Skip to content
quarry Artifact [ac8aede786]
Login

Artifact [ac8aede786]

Artifact ac8aede7862d9ff1c5d513e8425989805962cc20124b818732544998840f140c:


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 < 50; i++ {
		w := g.bearerAPI(syncTok)
		var body map[string]any
		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"])
		}
		next, _ := body["next"].(map[string]any)
		if next["say"] == nil || next["say"] == "" || next["help"] == nil || next["help"] == "" || next["call"] == nil || body["error"] == "" {
			t.Fatalf("FAIL: try %d: body lacks error or a full next: %v", i, body)
		}
		if _, has := next["cmd"]; has {
			t.Fatalf("FAIL: try %d: next carries cmd before the client exists: %v", i, next)
		}
	}
	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 fifty 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]any
		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"])
		}
	}
	w := g.bearerAPI(bad)
	if w.Code != http.StatusTooManyRequests {
		t.Errorf("FAIL: after six garbage tries got %d, want 429", w.Code)
	}
	var held map[string]any
	json.Unmarshal(w.Body.Bytes(), &held)
	next, _ := held["next"].(map[string]any)
	if held["error"] == nil || next["say"] == nil || next["say"] == "" || next["help"] == nil || w.Header().Get("Retry-After") == "" {
		t.Errorf("FAIL: the 429 hold lacks error, next or Retry-After: %v", held)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}