Skip to content
quarry Artifact [ee91eb0485]
Login

Artifact [ee91eb0485]

Artifact ee91eb04857c91ad72bfd2cf1094690504c6d0ae44be399d7d994675db9771f6:


package main

import (
	"context"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
	"time"

	"craftdesign.group/quarry/internal/api"
	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
	"craftdesign.group/quarry/internal/web"
)

// doorRig is the forge's credential doors over a real store: one
// private repository, one account holding o and i on it.
type doorRig struct {
	rg    *registrar
	doors *tokenDoors
	api   http.Handler
}

const doorPassword = "pw-jan-12345"

func newDoorRig(t *testing.T) doorRig {
	t.Helper()
	rg := newTestRegistrar(t, 25)
	db := rg.odb
	if err := db.AddAccount("jan", doorPassword, false); err != nil {
		t.Fatal(err)
	}
	for _, repo := range []string{"vault", "other"} {
		if err := db.AddRepo(repo, t.TempDir(), "", oltp.Private); err != nil {
			t.Fatal(err)
		}
		if err := db.SetCaps("jan", repo, "oi"); err != nil {
			t.Fatal(err)
		}
	}
	rg.refreshPrivate()
	doors := &tokenDoors{db: db, limit: web.NewLoginLimiter()}
	rg.doors = doors
	byPassword := func(repo, user, pass string, need ops.Auth) api.Decision {
		if _, ok := db.Authenticate(user, pass); !ok {
			return api.Denied
		}
		return api.Allowed
	}
	// One op that needs the check-in letter on the repository it names.
	r := ops.NewRegistry()
	if err := ops.Register(r, ops.Op[struct{}, struct{}]{
		Name: "door.test", Caps: "i", Scope: ops.ScopeRepo, Kind: ops.Command, Auth: ops.Token,
		Route: "POST /api/v1/r/{repo}/door-test", Doc: "test double: needs i",
		Run: func(context.Context, struct{}) (struct{}, error) { return struct{}{}, nil },
	}); err != nil {
		t.Fatal(err)
	}
	// A forge-scope op, and the identity op a repository-limited token
	// may still reach.
	for _, op := range []struct {
		name, route string
		kind        ops.Kind
	}{
		{"door.fleet", "POST /api/v1/door-fleet", ops.Command},
		{"me.account", "GET /api/v1/me", ops.Query},
		{"repo.add", "POST /api/v1/repos", ops.Command},
	} {
		if err := ops.Register(r, ops.Op[stubIn, struct{}]{
			Name: op.name, Kind: op.kind, Auth: ops.Token,
			Route: op.route, Doc: "test double: forge scope",
			Run: func(context.Context, stubIn) (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, byPassword))
	if err != nil {
		t.Fatal(err)
	}
	return doorRig{rg: rg, doors: doors, api: doors.wrap(h)}
}

func (g doorRig) mint(t *testing.T, spec oltp.TokenSpec) (string, oltp.Token) {
	t.Helper()
	if spec.Name == "" {
		spec.Name = "t"
	}
	v, tok, err := g.rg.odb.MintToken("jan", spec)
	if err != nil {
		t.Fatal(err)
	}
	return v, tok
}

func (g doorRig) callAPI(repo, user, pass string) int {
	req := httptest.NewRequest(http.MethodPost, "/api/v1/r/"+repo+"/door-test", nil)
	req.SetBasicAuth(user, pass)
	w := httptest.NewRecorder()
	g.api.ServeHTTP(w, req)
	return w.Code
}

func basicReq(user, pass string) *http.Request {
	req := httptest.NewRequest(http.MethodPost, "/r/vault/xfer", nil)
	req.SetBasicAuth(user, pass)
	return req
}

func scopes(s ...string) []string { return s }

// A token works only at the doors its scope allows, and only on the
// repositories it names; a refusal is the same status a wrong password
// gets.
func TestATokenOpensOnlyItsScopesDoors(t *testing.T) {
	g := newDoorRig(t)
	apiTok, _ := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeAPI)})
	webTok, _ := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeWeb)})
	syncTok, _ := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeSync)})
	narrow, _ := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeAPI, oltp.ScopeSync), Repos: []string{"other"}})
	wrong := g.callAPI("vault", "jan", "not-the-password")

	webVerify := g.doors.verify(oltp.ScopeWeb, func(string, string, string, ops.Auth) api.Decision { return api.Denied })
	for _, tc := range []struct {
		name      string
		value     string
		api, web  bool
		syncBasic bool
	}{
		{"api", apiTok, true, false, false},
		{"web", webTok, false, true, false},
		{"sync", syncTok, false, false, true},
		{"api+sync naming another repository", narrow, false, false, false},
	} {
		code := g.callAPI("vault", "jan", tc.value)
		if got := code == http.StatusOK; got != tc.api {
			t.Errorf("FAIL: %s token at the API door: %d", tc.name, code)
		} else if !tc.api && code != wrong {
			t.Errorf("FAIL: %s token refused %d at the API door, a wrong password %d", tc.name, code, wrong)
		} else {
			t.Logf("ok: %s token at the API door: %d", tc.name, code)
		}
		if got := webVerify("vault", "jan", tc.value, ops.Token) == api.Allowed; got != tc.web {
			t.Errorf("FAIL: %s token at the web door: allowed=%v", tc.name, got)
		}
		if got := g.rg.SyncReadGate(basicReq("jan", tc.value), "vault", ""); got != tc.syncBasic {
			t.Errorf("FAIL: %s token at the sync lane's Basic round: read=%v", tc.name, got)
		}
	}
	// The narrow token does reach the repository it names.
	if code := g.callAPI("other", "jan", narrow); code != http.StatusOK {
		t.Errorf("FAIL: a token naming other refused there: %d", code)
	}
	if !g.rg.SyncReadGate(basicReq("jan", narrow), "other", "") {
		t.Errorf("FAIL: a sync token naming other cannot read it")
	}
	// Passwords keep their doors.
	if code := g.callAPI("vault", "jan", doorPassword); code != http.StatusOK {
		t.Errorf("FAIL: the password at the API door: %d", code)
	}
}

// Expiry and revocation take effect on the next request at every door.
func TestExpiryAndRevokeEndATokenAtEveryDoor(t *testing.T) {
	g := newDoorRig(t)
	value, tok := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeAPI, oltp.ScopeSync)})
	if code := g.callAPI("vault", "jan", value); code != http.StatusOK {
		t.Fatalf("FAIL: a fresh token refused: %d", code)
	}
	if err := g.rg.odb.RevokeToken("jan", tok.ID); err != nil {
		t.Fatal(err)
	}
	if code := g.callAPI("vault", "jan", value); code != http.StatusUnauthorized {
		t.Errorf("FAIL: a revoked token at the API door: %d", code)
	}
	if g.rg.SyncReadGate(basicReq("jan", value), "vault", "") {
		t.Errorf("FAIL: a revoked token still reads over sync")
	}
	short, _ := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeAPI, oltp.ScopeSync), Expires: time.Now().Add(2 * time.Second)})
	if code := g.callAPI("vault", "jan", short); code != http.StatusOK {
		t.Fatalf("FAIL: a live short token refused: %d", code)
	}
	time.Sleep(2100 * time.Millisecond)
	if code := g.callAPI("vault", "jan", short); code != http.StatusUnauthorized {
		t.Errorf("FAIL: an expired token at the API door: %d", code)
	}
	if g.rg.SyncReadGate(basicReq("jan", short), "vault", "") {
		t.Errorf("FAIL: an expired token still reads over sync")
	}
}

// The ceiling caps the letters the router and the read gate see: a token
// ceilinged to o reads but cannot do what needs i, and one ceilinged to
// i on a private repository holds no read letter beyond what i implies.
func TestTheCeilingCapsLettersAtTheDoors(t *testing.T) {
	g := newDoorRig(t)
	readOnly, _ := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeAPI, oltp.ScopeSync), Ceiling: "o"})
	if code := g.callAPI("vault", "jan", readOnly); code != http.StatusForbidden {
		t.Errorf("FAIL: a token ceilinged to o reached an op needing i: %d", code)
	}
	if !g.rg.SyncReadGate(basicReq("jan", readOnly), "vault", "") {
		t.Errorf("FAIL: a token ceilinged to o cannot read")
	}
	upload, _ := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeSync), Ceiling: "y"})
	if g.rg.SyncReadGate(basicReq("jan", upload), "vault", "") {
		t.Errorf("FAIL: a token ceilinged to y reads a private repository the public cannot")
	}
}

// A refused token is a miss on the sign-in limiter: five buy the same
// hold five wrong passwords at the sign-in form buy, at the API door and
// the sync lane alike, and a held account's good token is held too.
func TestTokenMissesFeedTheLoginLimiter(t *testing.T) {
	g := newDoorRig(t)
	good, tok := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeAPI, oltp.ScopeSync)})
	bad := "qat_" + tok.ID + "_WRONGWRONGWRONGWRONGWRONGWRONGWR"
	for i := 0; i < 3; i++ {
		g.callAPI("vault", "jan", bad)
	}
	// The sync lane counts in its one sign-in (syncSignIn); the read
	// gate behind it is uncounted and never sees a refused or held Basic.
	for i := 0; i < 3; i++ {
		g.doors.syncSignIn(basicReq("jan", bad))
	}
	if code := g.callAPI("vault", "jan", good); code != http.StatusTooManyRequests {
		t.Errorf("FAIL: after six token misses the API door answered %d, want 429", code)
	} else {
		t.Log("ok: six token misses across two doors hold the account")
	}
	if acct, held, _ := g.doors.syncSignIn(basicReq("jan", good)); !held || acct != "" {
		t.Errorf("FAIL: a held account's good token still signs in over sync")
	}
	// A success clears it: here, the limiter's own clear, as the sign-in
	// form's success would.
	g.doors.limit.Succeeded("jan", "192.0.2.1")
	if code := g.callAPI("vault", "jan", good); code != http.StatusOK {
		t.Errorf("FAIL: after the slate cleared the good token answered %d", code)
	}
}

// A token with a list of repositories does nothing at forge scope but
// read its own identity; a token without a list is unaffected.
func TestARepoLimitedTokenIsRefusedAtForgeScope(t *testing.T) {
	g := newDoorRig(t)
	limited, _ := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeAPI, oltp.ScopeWeb), Repos: []string{"vault"}})
	open, _ := g.mint(t, oltp.TokenSpec{Scopes: scopes(oltp.ScopeAPI)})
	call := func(method, path, pass string) int {
		req := httptest.NewRequest(method, path, nil)
		req.SetBasicAuth("jan", pass)
		w := httptest.NewRecorder()
		g.api.ServeHTTP(w, req)
		return w.Code
	}
	if code := call("POST", "/api/v1/door-fleet", limited); code != http.StatusForbidden {
		t.Errorf("FAIL: a repo-limited token at a forge-scope op: %d, want 403", code)
	} else {
		t.Log("ok: a repo-limited token is refused at forge scope")
	}
	// A body naming the token's own repository does not make a
	// forge-scope op about it: repo.add name=vault is a new repository.
	req := httptest.NewRequest("POST", "/api/v1/repos", strings.NewReader(`{"name":"vault"}`))
	req.Header.Set("Content-Type", "application/json")
	req.SetBasicAuth("jan", limited)
	w := httptest.NewRecorder()
	g.api.ServeHTTP(w, req)
	if w.Code != http.StatusForbidden {
		t.Errorf("FAIL: repo.add name=vault by a [vault]-limited token: %d, want 403", w.Code)
	} else {
		t.Log("ok: a body naming the token's repository does not open forge scope")
	}
	form := httptest.NewRequest("POST", "/api/v1/repos", strings.NewReader("name=vault"))
	form.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	form.SetBasicAuth("jan", limited)
	w = httptest.NewRecorder()
	g.api.ServeHTTP(w, form)
	if w.Code != http.StatusForbidden {
		t.Errorf("FAIL: repo.add form name=vault by a [vault]-limited token: %d, want 403", w.Code)
	}
	if code := call("GET", "/api/v1/me", limited); code != http.StatusOK {
		t.Errorf("FAIL: a repo-limited token reading its own identity: %d", code)
	}
	if code := call("POST", "/api/v1/r/vault/door-test", limited); code != http.StatusOK {
		t.Errorf("FAIL: a repo-limited token on its own repository: %d", code)
	}
	if code := call("POST", "/api/v1/door-fleet", open); code != http.StatusOK {
		t.Errorf("FAIL: an unlimited token at a forge-scope op: %d", code)
	}
	webVerify := g.doors.verify(oltp.ScopeWeb, func(string, string, string, ops.Auth) api.Decision { return api.Denied })
	if webVerify("", "jan", limited, ops.Token) == api.Allowed {
		t.Errorf("FAIL: a repo-limited web token passed a forge-scope page")
	}
}

// stubIn is the forge-scope doubles' input: a name, as repo.add's has.
type stubIn struct {
	Name string `json:"name" validate:"max=64"`
}

// An account's password at the API door is a sign-in like any other: the
// hold is asked before the password is looked at, every miss is counted
// whatever the name, and a held name answers the same for a right
// password, a wrong one, and a name that is no account.
func TestPasswordMissesFeedTheLoginLimiterAtTheAPIDoor(t *testing.T) {
	g := newDoorRig(t)
	call := func(addr, user, pass string) int {
		req := httptest.NewRequest(http.MethodPost, "/api/v1/r/vault/door-test", nil)
		req.RemoteAddr = addr
		req.SetBasicAuth(user, pass)
		w := httptest.NewRecorder()
		g.api.ServeHTTP(w, req)
		return w.Code
	}
	// One address per name, so the hold each one meets is the name's own
	// and not the address's.
	const janAddr, ghostAddr = "198.51.100.7:1000", "198.51.100.8:1000"
	for i := 0; i < 6; i++ {
		if code := call(janAddr, "jan", "wrong-"+doorPassword); code != http.StatusUnauthorized {
			t.Fatalf("FAIL: miss %d answered %d, want 401", i, code)
		}
		if code := call(ghostAddr, "nobody-here", "wrong-"+doorPassword); code != http.StatusUnauthorized {
			t.Fatalf("FAIL: an unknown name's miss %d answered %d, want 401", i, code)
		}
	}
	for _, c := range []struct{ name, addr, user, pass string }{
		{"right password", janAddr, "jan", doorPassword},
		{"wrong password", janAddr, "jan", "again-" + doorPassword},
		{"unknown account", ghostAddr, "nobody-here", "again-" + doorPassword},
	} {
		if code := call(c.addr, c.user, c.pass); code != http.StatusTooManyRequests {
			t.Errorf("FAIL: a held name with a %s answered %d, want 429", c.name, code)
		}
	}
	// A name and address nobody has touched are not held by another's
	// misses.
	if err := g.rg.odb.AddAccount("kim", doorPassword, false); err != nil {
		t.Fatal(err)
	}
	if err := g.rg.odb.SetCaps("kim", "vault", "oi"); err != nil {
		t.Fatal(err)
	}
	if code := call("198.51.100.9:1000", "kim", doorPassword); code != http.StatusOK {
		t.Errorf("FAIL: an unheld address answered %d for a right password, want 200", code)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// anonymRig is doors.wrap over a router with an op that needs no sign-in
// and holds no capability letter on the repository, so a stranger's call
// ends at the capability gate with 403, and one with no letters at all
// answers 200.
func anonymRig(t *testing.T) (http.Handler, *tokenDoors) {
	t.Helper()
	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.Public); err != nil {
		t.Fatal(err)
	}
	if err := db.SetCaps("jan", "vault", "oi"); err != nil {
		t.Fatal(err)
	}
	// Nobody anonymous holds j, or the gate the review found would never
	// answer 403 to a stranger.
	if err := db.SetCategoryCaps("vault", "nobody", "g"); err != nil {
		t.Fatal(err)
	}
	rg.refreshPrivate()
	doors := &tokenDoors{db: db, limit: web.NewLoginLimiter()}
	r := ops.NewRegistry()
	for _, spec := range []struct{ name, route, caps string }{
		{"anon.needsj", "POST /api/v1/r/{repo}/anon-needs-j", "j"},
		{"anon.open", "POST /api/v1/r/{repo}/anon-open", ""},
		{"signed.needsj", "POST /api/v1/r/{repo}/signed-needs-j", "j"},
	} {
		auth := ops.Anonymous
		if spec.name == "signed.needsj" {
			auth = ops.Token
		}
		if err := ops.Register(r, ops.Op[stubIn, struct{}]{
			Name: spec.name, Caps: spec.caps, Scope: ops.ScopeRepo, Kind: ops.Command, Auth: auth,
			Route: spec.route, Doc: "test double",
			Run: func(context.Context, stubIn) (struct{}, error) { return struct{}{}, nil },
		}); err != nil {
			t.Fatal(err)
		}
	}
	byPassword := func(repo, user, pass string, need ops.Auth) api.Decision {
		if _, ok := db.Authenticate(user, pass); !ok {
			return api.Denied
		}
		return api.Allowed
	}
	h, err := api.RouterWithCaps(r, "test", func(account, repo string) api.CapSet { return db.EffectiveCaps(account, repo) },
		nil, doors.verify(oltp.ScopeAPI, byPassword))
	if err != nil {
		t.Fatal(err)
	}
	return doors.wrap(h), doors
}

// A refusal that ends 403 or 200 is still a rejected credential: the
// hold is counted from what the credential check answered, never from
// the status the surface happened to end on, so five misses buy a hold
// however the op they were sent to answers.
func TestARejectedCredentialIsCountedWhateverTheAnswer(t *testing.T) {
	// Each surface gets its own gate, its own limiter and its own
	// address, so an earlier case's hold cannot hide a later one that
	// charges nothing.
	type surface struct {
		name string
		path string
		code int    // what a rejected credential answers here
		mix  string // the surface whose misses are interleaved, "" for none
	}
	for _, sc := range []surface{
		{"an op that answers 401", "/api/v1/r/vault/signed-needs-j", http.StatusUnauthorized, ""},
		{"an anonymous op whose capability gate answers 403", "/api/v1/r/vault/anon-needs-j", http.StatusForbidden, "/api/v1/r/vault/signed-needs-j"},
		{"an anonymous op that answers 200", "/api/v1/r/vault/anon-open", http.StatusOK, "/api/v1/r/vault/signed-needs-j"},
		{"a path that is no op at all, answering 404", "/api/v1/r/vault/no-such-op", http.StatusNotFound, "/api/v1/r/vault/signed-needs-j"},
	} {
		t.Run(sc.name, func(t *testing.T) {
			h, doors := anonymRig(t)
			const addr = "203.0.113.10:1234"
			call := func(path, user, pass string) int {
				req := httptest.NewRequest(http.MethodPost, path, nil)
				req.RemoteAddr = addr
				req.SetBasicAuth(user, pass)
				w := httptest.NewRecorder()
				h.ServeHTTP(w, req)
				return w.Code
			}
			// The pre-hold answer is the surface's own, not a 401 every
			// path would give: a 403 or a 200 says the gate ran and the
			// credential was rejected regardless of it.
			if code := call(sc.path, "jan", "wrong-"+doorPassword); code != sc.code {
				t.Fatalf("FAIL: a rejected credential at %s answered %d, want %d", sc.path, code, sc.code)
			}
			if ok, _ := doors.limit.Allowed("jan", "203.0.113.10"); !ok {
				t.Fatalf("FAIL: one miss held the name")
			}
			// Six misses at the surface itself buy the hold, without any
			// help from another one.
			for i := 0; i < 6; i++ {
				call(sc.path, "jan", "wrong-"+doorPassword)
			}
			if ok, wait := doors.limit.Allowed("jan", "203.0.113.10"); ok || wait <= 0 {
				t.Errorf("FAIL: six rejected credentials at %s left the name unheld", sc.path)
			}
			// And the hold answers the surface alike for a right
			// password, a wrong one, and a name that is no account.
			if code := call(sc.path, "jan", doorPassword); code != http.StatusTooManyRequests {
				t.Errorf("FAIL: a held name with the right password at %s answered %d, want 429", sc.path, code)
			}
			// A stale Basic beside a correct form is not the form's
			// sign-in and must not clear the hold either.
			if sc.mix != "" {
				const other = "203.0.113.11:1234"
				callOther := func(path, user, pass string) int {
					req := httptest.NewRequest(http.MethodPost, path, nil)
					req.RemoteAddr = other
					req.SetBasicAuth(user, pass)
					w := httptest.NewRecorder()
					h.ServeHTTP(w, req)
					return w.Code
				}
				// Mixed: five at the signing op, one at the surface. If
				// the surface's answer cleared the count, the next
				// round's five would still be free and repeat forever.
				for i := 0; i < 6; i++ {
					for j := 0; j < 5; j++ {
						callOther(sc.mix, "kim", "wrong-"+doorPassword)
					}
					callOther(sc.path, "kim", "wrong-"+doorPassword)
				}
				if ok, _ := doors.limit.Allowed("kim", "203.0.113.11"); ok {
					t.Errorf("FAIL: a refusal answered at %s cleared misses counted before it", sc.path)
				}
			}
		})
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A live session answers for the browser, never the Basic credential
// beside it: a stale one must not be counted, or a signed-in person is
// locked out by a password their browser replays.
func TestALiveSessionBesideAStaleCredentialCountsNothing(t *testing.T) {
	h, doors := anonymRig(t)
	if err := doors.db.AddAccount("kim", doorPassword, false); err != nil {
		t.Fatal(err)
	}
	cookie, _, ok := doors.db.NewSession("kim", doorPassword)
	if !ok {
		t.Fatal("FAIL: session")
	}
	for i := 0; i < 8; i++ {
		req := httptest.NewRequest(http.MethodGet, "/r/vault", nil)
		req.RemoteAddr = "203.0.113.20:1234"
		req.SetBasicAuth("kim", "stale-"+doorPassword)
		req.AddCookie(&http.Cookie{Name: web.SessionCookie, Value: cookie})
		w := httptest.NewRecorder()
		h.ServeHTTP(w, req)
		if w.Code == http.StatusTooManyRequests {
			t.Fatalf("FAIL: a signed-in request was held at round %d", i)
		}
	}
	if ok, _ := doors.limit.Allowed("kim", "203.0.113.20"); !ok {
		t.Errorf("FAIL: a live session's stale Basic credential was counted")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// signinPageRig serves the real web layer's sign-in form behind the
// doors' wrap, over the same store and the same limiter.
func signinPageRig(t *testing.T) (http.Handler, *tokenDoors) {
	t.Helper()
	rg := newTestRegistrar(t, 25)
	db := rg.odb
	if err := db.AddAccount("jan", doorPassword, false); err != nil {
		t.Fatal(err)
	}
	doors := &tokenDoors{db: db, limit: web.NewLoginLimiter()}
	r := ops.NewRegistry()
	if err := api.RegisterAll(r, api.Deps{Version: "v", Accounts: accountStore{db: db},
		Repos: api.NewRepos(map[string]*api.Repo{})}); err != nil {
		t.Fatal(err)
	}
	deny := func(string, string, string, ops.Auth) api.Decision { return api.Denied }
	h := web.HandlerWith(r, nil, nil, []web.Option{
		web.WithSessions(sessionPlane{db: db}),
		web.WithCaps(capsPlane{db: db}),
		web.WithLoginLimiter(doors.limit),
	}, web.Verify(deny))
	return doors.wrap(h), doors
}

// The sign-in form authenticates the FORM's password, and the form's
// handler is the one thing that charges it. A Basic credential a browser
// happens to replay alongside the form is not that source and must not
// be counted a second time, or a handful of mistyped passwords exhaust
// each attempt twice and lock a person out of their own account.
func TestTheSignInFormIsChargedOnceWhateverBasicRidesBesideIt(t *testing.T) {
	h, _ := signinPageRig(t)
	post := func(user, pass string, withBasic bool) int {
		form := url.Values{"user": {user}, "password": {pass}}
		req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(form.Encode()))
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		req.RemoteAddr = "203.0.113.40:1234"
		if withBasic {
			req.SetBasicAuth("jan", "stale-"+doorPassword)
		}
		w := httptest.NewRecorder()
		h.ServeHTTP(w, req)
		return w.Code
	}
	// Three misses: a form miss, a stale Basic beside it, is one miss.
	for i := 0; i < 3; i++ {
		if code := post("jan", "wrong-"+doorPassword, true); code != http.StatusUnauthorized {
			t.Fatalf("FAIL: form miss %d answered %d, want 401", i, code)
		}
	}
	// The right password now still signs in: six misses is the budget,
	// and three mistyped forms are three.
	if code := post("jan", doorPassword, true); code != http.StatusSeeOther {
		t.Fatalf("FAIL: the right password after three misses answered %d, want 303", code)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The form path still charges: six mistyped forms hold it, and a correct
// one is then refused alike. Without this the exemption above could have
// silently taken the form off the limiter altogether.
func TestTheSignInFormStillChargesItsOwnMisses(t *testing.T) {
	h, doors := signinPageRig(t)
	post := func(pass string) int {
		form := url.Values{"user": {"jan"}, "password": {pass}}
		req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(form.Encode()))
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		req.RemoteAddr = "203.0.113.41:1234"
		w := httptest.NewRecorder()
		h.ServeHTTP(w, req)
		return w.Code
	}
	for i := 0; i < 6; i++ {
		if code := post("wrong-" + doorPassword); code != http.StatusUnauthorized {
			t.Fatalf("FAIL: form miss %d answered %d, want 401", i, code)
		}
	}
	if code := post(doorPassword); code != http.StatusTooManyRequests {
		t.Errorf("FAIL: the right password after six misses answered %d, want 429", code)
	}
	if ok, _ := doors.limit.Allowed("jan", "203.0.113.41"); ok {
		t.Errorf("FAIL: six form misses left the name unheld")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}