Skip to content
quarry Artifact [d1161df837]
Login

Artifact [d1161df837]

Artifact d1161df8378e17377ee3c0477f2d5e9d3450042519c19031c2a6d50a8521e128:


package xfer

import (
	"net/http"
	"testing"
	"time"
)

// countingLimit is a LoginLimit that holds a user after max misses.
type countingLimit struct {
	max    int
	misses map[string]int
}

func (l *countingLimit) Allowed(_ *http.Request, user string) (bool, time.Duration) {
	return l.misses[user] < l.max, 90 * time.Second
}
func (l *countingLimit) Failed(_ *http.Request, user string)    { l.misses[user]++ }
func (l *countingLimit) Succeeded(_ *http.Request, user string) { delete(l.misses, user) }

// A login card that does not verify against any of the account's
// credentials is a miss against that account (RFC 0021, Rate limits);
// once the limiter holds the account, even a good card proves nothing;
// a verified card clears the count.
func TestLoginCardMissesFeedTheLimiter(t *testing.T) {
	f := New()
	f.SetAuth(secrets{"jan": "right"})
	lim := &countingLimit{max: 2, misses: map[string]int{}}
	f.SetLoginLimit(lim)
	try := func(secret string) loginState {
		body := signedLogin("jan", secret)
		return f.verifiedLogin("alpha", probe(zitUA), body, scanRequest(body))
	}
	if st := try("right"); st.user != "jan" {
		t.Fatalf("FAIL: a good card did not verify")
	}
	try("wrong")
	if lim.misses["jan"] != 1 {
		t.Errorf("FAIL: a bad card counted %d misses, want 1", lim.misses["jan"])
	}
	try("wrong")
	if st := try("right"); st.user != "" {
		t.Errorf("FAIL: a held account still verified")
	} else {
		t.Log("ok: a held account's good card proves nothing")
	}
	delete(lim.misses, "jan")
	try("wrong")
	if st := try("right"); st.user != "jan" || lim.misses["jan"] != 0 {
		t.Errorf("FAIL: a verified card did not clear the count: %+v, misses %d", st, lim.misses["jan"])
	}
	// A card for a name with no credential here is a miss too, and holds
	// that name exactly as it holds one with a credential: a held caller
	// is told it is held, so the hold must not depend on whether the
	// name can push to this repository, or it would say which names can.
	body := signedLogin("kim", "anything")
	for i := 0; i < lim.max; i++ {
		f.verifiedLogin("alpha", probe(zitUA), body, scanRequest(body))
	}
	if lim.misses["kim"] != lim.max {
		t.Errorf("FAIL: a name with no credential counted %d misses, want %d", lim.misses["kim"], lim.max)
	}
	withCred := signedLogin("jan", "wrong")
	delete(lim.misses, "jan")
	for i := 0; i < lim.max; i++ {
		f.verifiedLogin("alpha", probe(zitUA), withCred, scanRequest(withCred))
	}
	a := f.verifiedLogin("alpha", probe(zitUA), body, scanRequest(body))
	b := f.verifiedLogin("alpha", probe(zitUA), withCred, scanRequest(withCred))
	c := f.verifiedLogin("nowhere", probe(zitUA), withCred, scanRequest(withCred))
	if !a.held || !b.held || !c.held {
		t.Errorf("FAIL: held differs: no credential %v, credential %v, unknown repository %v", a.held, b.held, c.held)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}