package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"craftdesign.group/quarry/internal/oltp"
)
func (g doorRig) bearerAPI(tok string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/api/v1/r/vault/door-test", nil)
req.Header.Set("Authorization", "Bearer "+tok)
w := httptest.NewRecorder()
g.api.ServeHTTP(w, req)
return w
}
// A token that proved itself but lacks the api scope is told which
// scope it lacks, and is not a failed sign-in.
func TestAWrongScopeTokenAtTheAPIIsToldAndNotCounted(t *testing.T) {
g := newDoorRig(t)
syncTok, _ := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeSync)})
for i := 0; i < 10; i++ {
w := g.bearerAPI(syncTok)
var body map[string]string
json.Unmarshal(w.Body.Bytes(), &body)
if w.Code != http.StatusUnauthorized || body["code"] != "wrong_scope" {
t.Fatalf("FAIL: try %d: status %d code %q, want 401 wrong_scope", i, w.Code, body["code"])
}
if body["next"] == "" || body["help"] != "/llms.txt" || body["error"] == "" {
t.Fatalf("FAIL: try %d: body lacks error, next or help: %v", i, body)
}
}
apiTok, _ := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeAPI)})
if w := g.bearerAPI(apiTok); w.Code != http.StatusOK {
t.Errorf("FAIL: an api token after ten wrong-scope tries answered %d, want 200", w.Code)
}
if !t.Failed() {
t.Log("ok")
}
}
// A value that has not proved itself is still a miss and still counts.
func TestAGarbageTokenAtTheAPIStillCounts(t *testing.T) {
g := newDoorRig(t)
_, tok := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeSync)})
bad := "qat_" + tok.ID + "_WRONGWRONGWRONGWRONGWRONGWRONGWR"
for i := 0; i < 6; i++ {
w := g.bearerAPI(bad)
var body map[string]string
json.Unmarshal(w.Body.Bytes(), &body)
if w.Code != http.StatusUnauthorized || body["code"] == "wrong_scope" {
t.Errorf("FAIL: garbage try %d: status %d code %q", i, w.Code, body["code"])
}
}
if w := g.bearerAPI(bad); w.Code != http.StatusTooManyRequests {
t.Errorf("FAIL: after six garbage tries got %d, want 429", w.Code)
}
if !t.Failed() {
t.Log("ok")
}
}