package main
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"craftdesign.group/quarry/internal/api"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
"craftdesign.group/quarry/internal/web"
)
// A login token is refused the browser-only acts at the real token door:
// the door builds the context the gate reads, so the marker travels from the
// stored token and not from a test's hand.
func TestALoginTokenIsHeldToTheHardStopsAtTheTokenDoor(t *testing.T) {
rg := newTestRegistrar(t, 25)
db := rg.odb
if err := db.AddAccount("jan", doorPassword, false); err != nil {
t.Fatal(err)
}
if err := db.AddRepo("vault", t.TempDir(), "", oltp.Private); err != nil {
t.Fatal(err)
}
if err := db.SetCaps("jan", "vault", "oia"); err != nil {
t.Fatal(err)
}
rg.refreshPrivate()
doors := &tokenDoors{db: db, limit: web.NewLoginLimiter()}
r := ops.NewRegistry()
r.SetCommandGate(api.Deps{}.HardStops())
if err := ops.Register(r, ops.Op[struct{}, struct{}]{
Name: "branch.protection.set", Caps: "a", Scope: ops.ScopeRepo, Kind: ops.Command, Auth: ops.Token,
Route: "POST /api/v1/r/{repo}/branch-protection", Doc: "test double: protection",
Run: func(context.Context, struct{}) (struct{}, error) { return struct{}{}, nil },
}); err != nil {
t.Fatal(err)
}
h, err := api.RouterWithCaps(r, "test", func(account, repo string) api.CapSet { return db.EffectiveCaps(account, repo) },
nil, doors.verify(oltp.ScopeAPI, func(string, string, string, ops.Auth) api.Decision { return api.Denied }))
if err != nil {
t.Fatal(err)
}
api := doors.wrap(h)
call := func(value string) (int, string) {
req := httptest.NewRequest(http.MethodPost, "/api/v1/r/vault/branch-protection", nil)
req.SetBasicAuth("jan", value)
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
return w.Code, w.Body.String()
}
login, _, err := db.MintToken("jan", oltp.TokenSpec{Name: "mac-mini", Scopes: []string{oltp.ScopeAPI, oltp.ScopeSync, oltp.ScopeLogin}})
if err != nil {
t.Fatal(err)
}
plain, _, err := db.MintToken("jan", oltp.TokenSpec{Name: "plain", Scopes: []string{oltp.ScopeAPI}})
if err != nil {
t.Fatal(err)
}
if code, body := call(login); code != http.StatusForbidden || !strings.Contains(body, `"code":"browser_only"`) || !strings.Contains(body, `"next":{"say"`) {
t.Errorf("FAIL: a login token changing protection answered %d %s", code, body)
}
if code, body := call(plain); code != http.StatusOK {
t.Errorf("FAIL: a token that is not a login was held to the stops: %d %s", code, body)
}
if !t.Failed() {
t.Log("ok")
}
}