package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"craftdesign.group/quarry/internal/oltp"
)
// A token may arrive as a bearer header, which names no account and is
// never written into a URL the way a Basic user:password is. It meets
// the same door as Basic: the same answer for a good token, and the
// same refusal for a wrong secret or an unknown token.
func TestATokenMayArriveAsABearer(t *testing.T) {
g := newSiteRig(t)
v, _ := g.mint(t, oltp.ScopeAPI)
bearer := func(path, value string) int {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Header.Set("Authorization", "Bearer "+value)
w := httptest.NewRecorder()
g.h.ServeHTTP(w, req)
return w.Code
}
basic, _ := g.do(http.MethodGet, "/api/v1/r/granted/info", v, "", nil)
if got := bearer("/api/v1/r/granted/info", v); got != http.StatusOK || got != basic {
t.Errorf("FAIL: the token as a bearer answered %d, as Basic %d", got, basic)
}
if got := bearer("/api/v1/me", v); got != http.StatusOK {
t.Errorf("FAIL: a bearer token is nobody to /api/v1/me: %d", got)
}
id, _, _ := strings.Cut(strings.TrimPrefix(v, "qat_"), "_")
for name, value := range map[string]string{
"a wrong secret": "qat_" + id + "_wrongwrongwrong",
"an unknown token": "qat_nosuchid_secretsecret",
} {
if got := bearer("/api/v1/me", value); got != http.StatusUnauthorized {
t.Errorf("FAIL: %s as a bearer answered %d", name, got)
}
}
}