mirror of
https://git.mills.io/saltyim/saltyim.git
synced 2024-06-30 02:31:08 +00:00
103 lines
2.1 KiB
Go
103 lines
2.1 KiB
Go
package authreq_test
|
|
|
|
import (
|
|
"crypto/ed25519"
|
|
"encoding/base64"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/julienschmidt/httprouter"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"go.salty.im/saltyim/internal/authreq"
|
|
)
|
|
|
|
var authorizationHeader = "Authorization"
|
|
|
|
func TestGETRequest(t *testing.T) {
|
|
assert := assert.New(t)
|
|
require := require.New(t)
|
|
|
|
pub, priv, err := ed25519.GenerateKey(nil)
|
|
require.NoError(err)
|
|
|
|
req, err := http.NewRequest(http.MethodGet, "http://example.com/"+enc(pub)+"/test?q=test", nil)
|
|
require.NoError(err)
|
|
|
|
req, err = authreq.Sign(req, priv)
|
|
require.NoError(err)
|
|
|
|
var hdlr httprouter.Handle = func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
|
c := authreq.ClaimsFromRequest(r)
|
|
if c == nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if !strings.Contains(req.URL.Path, c.Issuer) {
|
|
w.WriteHeader(http.StatusForbidden)
|
|
return
|
|
}
|
|
}
|
|
|
|
hdlr = authreq.VerifyMiddleware(hdlr)
|
|
|
|
rw := httptest.NewRecorder()
|
|
|
|
hdlr(rw, req, nil)
|
|
|
|
assert.Equal(rw.Code, http.StatusOK)
|
|
}
|
|
|
|
func TestPOSTRequest(t *testing.T) {
|
|
assert := assert.New(t)
|
|
require := require.New(t)
|
|
|
|
content := "this is post!"
|
|
|
|
pub, priv, err := ed25519.GenerateKey(nil)
|
|
require.NoError(err)
|
|
|
|
req, err := http.NewRequest(http.MethodPost, "http://example.com/"+enc(pub)+"/test?q=test", strings.NewReader(content))
|
|
require.NoError(err)
|
|
|
|
req, err = authreq.Sign(req, priv)
|
|
require.NoError(err)
|
|
|
|
var hdlr httprouter.Handle = func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
|
c := authreq.ClaimsFromRequest(r)
|
|
if c == nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
r.Body.Close()
|
|
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if !strings.Contains(req.URL.Path, c.Issuer) {
|
|
w.WriteHeader(http.StatusForbidden)
|
|
return
|
|
}
|
|
}
|
|
|
|
hdlr = authreq.VerifyMiddleware(hdlr)
|
|
|
|
rw := httptest.NewRecorder()
|
|
|
|
hdlr(rw, req, nil)
|
|
|
|
assert.Equal(rw.Code, http.StatusOK)
|
|
|
|
}
|
|
|
|
func enc(b []byte) string {
|
|
return base64.RawURLEncoding.EncodeToString(b)
|
|
}
|