2023-01-25 23:05:29 +00:00
|
|
|
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"
|
|
|
|
|
2023-02-27 22:37:41 +00:00
|
|
|
"go.salty.im/saltyim/internal/authreq"
|
2023-01-25 23:05:29 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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)
|
|
|
|
}
|