Skip to content
quarry Artifact [5922cb1719]
Login

Artifact [5922cb1719]

Artifact 5922cb1719043357e1803b2f1ef1b4aabe1fa9f616d029b3d76e112f03f8abdd:


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)
		}
	}
}