package main
import (
"bytes"
"compress/zlib"
"crypto/sha1"
"encoding/binary"
"encoding/hex"
"io"
"net/http"
"net/http/httptest"
"testing"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/web"
"craftdesign.group/quarry/internal/xfer"
)
// signInFront is the sync front as main wires it, over a private
// repository "vault" jan may read, with the forge's own limiter.
type signInFront struct {
f *xfer.Fronter
doors *tokenDoors
token string
}
func newSignInFront(t *testing.T) signInFront {
t.Helper()
rg := newTestRegistrar(t, 25)
db := rg.odb
db.SyncProjectCode = func(string) (string, bool) { return "6f3c2a1b9d8e7f0a5c4b3d2e1f009988aabbccdd", true }
if err := db.AddAccount("jan", "pw-jan-12345", 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", "oiy"); err != nil {
t.Fatal(err)
}
rg.refreshPrivate()
doors := &tokenDoors{db: db, limit: web.NewLoginLimiter()}
rg.doors = doors
tok, err := db.MintSyncToken("jan")
if err != nil {
t.Fatal(err)
}
f := xfer.New()
t.Cleanup(f.Close)
f.SetAuth(db)
f.SetLoginLimit(doors)
f.SetBasicSignIn(doors.syncSignIn)
f.SetBasicLogin(doors.basicSyncLogin)
f.SetReadGate(rg.SyncReadGate)
f.SetHoldGate(rg.SyncHoldGate)
f.SetProjectCode(func(name string) (string, bool) { return db.SyncProjectCode(name) })
f.SetDecoyKey(bytes.Repeat([]byte{3}, 32))
return signInFront{f: f, doors: doors, token: tok}
}
func fossilContainer(cards string) []byte {
var buf bytes.Buffer
var n [4]byte
binary.BigEndian.PutUint32(n[:], uint32(len(cards)))
buf.Write(n[:])
zw := zlib.NewWriter(&buf)
zw.Write([]byte(cards))
zw.Close()
return buf.Bytes()
}
// serve sends one clone round to repo with Basic user:secret and cards.
func (s signInFront) serve(repo, user, secret, cards string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/r/"+repo, io.NopCloser(bytes.NewReader(fossilContainer(cards))))
req.SetPathValue("repo", repo)
req.Header.Set("Content-Type", "application/x-fossil")
req.Header.Set("User-Agent", "Fossil/2.28")
if user != "" {
req.SetBasicAuth(user, secret)
}
w := httptest.NewRecorder()
s.f.ServeHTTP(w, req)
return w
}
func (s signInFront) allowed(user string) bool {
ok, _ := s.doors.limit.Allowed(user, "192.0.2.1")
return ok
}
const cloneCards = "pragma client-version 22800 20260311 113146\nclone 3 1\n"
// Every Basic credential on the sync lane, password or token, is one
// counted sign-in per request: wrong ones hold the account; a held one
// is answered alike right or wrong, on a private repository and an
// address that names nothing; the right password is refused while held.
func TestSyncBasicIsARateLimitedSignIn(t *testing.T) {
s := newSignInFront(t)
for i := 0; i < 5; i++ {
if w := s.serve("vault", "jan", "qat_wrong_wrongwrongwrong", cloneCards); w.Code != http.StatusUnauthorized {
t.Errorf("FAIL: wrong token %d answered %d, want 401", i, w.Code)
}
}
// Five misses do not hold (the sixth does), so each request counted
// once: the read gate and the hold gate read Basic too, uncounted.
if !s.allowed("jan") {
t.Fatalf("FAIL: five wrong tokens counted more than five misses")
}
if w := s.serve("vault", "jan", "wrong-password", cloneCards); w.Code != http.StatusUnauthorized {
t.Errorf("FAIL: a wrong password answered %d, want 401", w.Code)
}
if s.allowed("jan") {
t.Fatalf("FAIL: six wrong credentials did not hold the account")
}
var first *httptest.ResponseRecorder
for _, repo := range []string{"vault", "pat/nothere"} {
for _, secret := range []string{"pw-jan-12345", "wrong-password", s.token, "qat_wrong_wrongwrongwrong"} {
w := s.serve(repo, "jan", secret, cloneCards)
if first == nil {
first = w
continue
}
// The seconds left tick with the clock, not the credential.
if w.Code != first.Code || !bytes.Equal(digitless(cardsOf(t, w)), digitless(cardsOf(t, first))) ||
w.Header().Get("Content-Type") != first.Header().Get("Content-Type") || len(w.Header()) != len(first.Header()) {
t.Errorf("FAIL: held: %s with a %d-byte secret answered differently (%d)", repo, len(secret), w.Code)
}
}
}
card := cardsOf(t, first)
if first.Code != http.StatusOK || !bytes.HasPrefix(card, []byte(`error Sign-ins\sfor\sthis\saccount\sare\son\shold`)) {
t.Errorf("FAIL: held answer %d %q, want the hold card", first.Code, card)
}
if !t.Failed() {
t.Log("ok")
}
}
func cardsOf(t *testing.T, w *httptest.ResponseRecorder) []byte {
t.Helper()
zr, err := zlib.NewReader(bytes.NewReader(w.Body.Bytes()[4:]))
if err != nil {
t.Fatalf("FAIL: not a fossil container: %q", w.Body.Bytes())
}
out, _ := io.ReadAll(zr)
return out
}
func digitless(b []byte) []byte {
return bytes.Map(func(r rune) rune {
if r >= '0' && r <= '9' {
return '#'
}
return r
}, b)
}
// A request with a good Basic credential and a login card of the same
// account that does not verify counts one success and no miss.
func TestGoodBasicBesideABadCardCountsOneSuccess(t *testing.T) {
s := newSignInFront(t)
for i := 0; i < 3; i++ {
s.doors.limit.Failed("jan", "192.0.2.1")
}
covered := cloneCards + "# r\n"
sum := sha1.Sum([]byte(covered))
nonce := hex.EncodeToString(sum[:])
sig := sha1.Sum([]byte(nonce + "not-the-secret"))
s.serve("vault", "jan", s.token, "login jan "+nonce+" "+hex.EncodeToString(sig[:])+"\n"+covered)
// Cleared by the success and nothing counted after it: five more
// misses still do not hold.
for i := 0; i < 5; i++ {
s.doors.limit.Failed("jan", "192.0.2.1")
}
if !s.allowed("jan") {
t.Errorf("FAIL: the request counted a miss, or no success")
}
if !t.Failed() {
t.Log("ok")
}
}
// Through the front as main wires it: a held account is answered byte
// for byte alike (status, the headers a client acts on, the decompressed
// cards) for a right and a wrong password and a right and a wrong
// token, on a real private repository and on an address that names
// nothing. The hold's seconds tick with the clock, so a round that
// straddles a second is taken again; one that differs otherwise fails.
func TestAHeldAccountAnswersByteIdenticallyThroughTheFront(t *testing.T) {
s := newSignInFront(t)
for i := 0; i < 6; i++ {
s.doors.limit.Failed("jan", "192.0.2.1")
}
if s.allowed("jan") {
t.Fatal("FAIL: six misses did not hold the account")
}
headers := []string{"Content-Type", "WWW-Authenticate", "Retry-After", "Link", "Cache-Control"}
shape := func(w *httptest.ResponseRecorder) string {
out := []byte{byte(w.Code >> 8), byte(w.Code)}
for _, h := range headers {
out = append(out, h+"="+w.Header().Get(h)+"\n"...)
}
return string(append(out, cardsOf(t, w)...))
}
for round := 0; ; round++ {
var want, wantDigitless string
same, onlyClock := true, true
for _, repo := range []string{"vault", "pat/nothere"} {
for _, secret := range []string{"pw-jan-12345", "wrong-password", s.token, "qat_wrong_wrongwrongwrong"} {
got := shape(s.serve(repo, "jan", secret, cloneCards))
if want == "" {
want, wantDigitless = got, string(digitless([]byte(got)))
continue
}
if got != want {
same = false
onlyClock = onlyClock && string(digitless([]byte(got))) == wantDigitless
}
}
}
if same {
if !bytes.Contains([]byte(want), []byte(`error Sign-ins\sfor\sthis\saccount\sare\son\shold`)) {
t.Errorf("FAIL: the held answer is not the hold card: %q", want)
}
break
}
if !onlyClock || round == 2 {
t.Fatalf("FAIL: a held account was answered differently by credential or repository")
}
}
if !t.Failed() {
t.Log("ok")
}
}