Artifact 54d7c0e434613c4a8027e81ff83141d6dd2fb42c4cde22d3351b2a764a1b4a48:
- File
internal/auth/verify_test.go
— part of check-in
[d810a8118f]
at
2026-10-18 20:01:53
on branch main
— fix: handle time exactly as fossil does (#442)
* fix(manifest): round a caller's check-in and tag time as fossil does
Fossil reads a --date-override through SQLite's strftime, which rounds the seconds to the millisecond (holding a fraction past .999 in its second) rather than truncating them. A caller time finer than a millisecond now gets the D card fossil would write for it; the default clock time is still truncated, as fossil reads its clock.
fsltype.CardTime and CardTimeNow are the one place both rules live, and the checkout commit path and branch creation take their default time through them.
* fix(repo): stamp config and user rows in seconds since 1970
Fossil writes config.mtime and user.mtime with its now() SQL function, time(0). SetConfig, SetHashPolicy and CreateUser wrote julianday('now') instead, so fossil read those rows as dating from 1970 when comparing times in a configuration merge, and SetCaps and SetPassword left the user's mtime alone where fossil's user command restamps it.
* fix(auth): read and write user.cexpire as a Julian day
Fossil keeps user.cexpire as a Julian day (src/login.c). A sync login parsed it as RFC 3339 or 'YYYY-MM-DD HH:MM:SS' text, so any value fossil had written failed to parse and the login was refused as expired. The expiry is now read through julianday(), which takes both forms, and repo invite --ttl writes a Julian day; its write error is now checked.
* fix(checkout): set file times as fossil's --setmtime does
Fossil's --setmtime gives each unedited file the time of the newest check-in, among the version and its primary ancestors, that recorded the file's content, truncated to whole seconds (mtime_of_manifest_file), and it does so for every unedited file of the version once the checkout is up to date (vfile_check_signature with CKSIG_SETMTIME). SetMTime gave every written file the target check-in's time to the millisecond, and an update left the files it did not write alone.
* fix(stash): keep and show stash and bisect times as fossil does
Fossil stores stash.ctime as julianday('now') and lists it with datetime(ctime); go-libfossil stored CURRENT_TIMESTAMP text, which the two drivers returned in different forms, and showed a fossil-written time as a bare number. bisect's list now shows datetime(event.mtime), as fossil's bisect ls does, instead of the Julian day.
* test(verify): fossil rebuild keeps the times go-libfossil stores
A repository go-libfossil wrote, with check-ins at caller and clock times, a tag and a branch, is rebuilt by the fossil binary, and every check-in event, plink and tagxref time must come back unchanged.
* test(sync): a fossil clone and push agree on every synced time
The fossil binary clones a go-libfossil server, unversioned files included, commits at a time finer than a millisecond and pushes back. Each side derives check-in event, plink and tagxref times from the artifacts itself, and the unversioned time travels on the wire; both repositories must then hold the same values.
* fix(resolve): bound NAME:TIMESTAMP with julianday() as fossil does
Fossil resolves BRANCH:TIMESTAMP with event.mtime<=julianday(BOUND). The bound was computed in the text form event rows hold, so on a millisecond where that form is larger than julianday()'s, a check-in at the bound itself resolved here and not in fossil.
* fix(manifest): round a caller's card time with integer arithmetic
CardTime followed SQLite's printing of the seconds as a double, which is not a well-defined rounding: at exact half-millisecond ties fossil 2.28's SQLite gives .124 for .1245 but .020 for .0195, and other SQLite versions differ again. A caller time is now rounded to the nearest millisecond on its nanoseconds, ties up, held at .999 as fossil holds it. The fossil binary test compares every non-tie value, across second, minute, day and year ends; ties are asserted on their own.
* fix(auth): ignore user.cexpire at sync login, as fossil does
user.cexpire is the expiry of fossil's web-login cookie: fossil sets it at web login, writes 0 at logout, and its sync login (check_login) never reads it. Refusing a sync login on it locked out anyone who had logged into or out of fossil's web UI, or whose cookie had lapsed.
The invite TTL that relied on it now lives in a config row of its own, invite-expire:LOGIN, as a UTC instant checked at sync login; repo invite no longer writes cexpire, and the expiry is no longer written in local time and read as UTC. Deleting a user drops its invite expiry.
Tracked in #441.
* fix(repo): convert Julian config and user mtimes on open
Repositories go-libfossil wrote before config and user rows were stamped in seconds since 1970 still hold Julian days there, which fossil reads as January 1970. Open converts those rows to the seconds they stand for. It checks first and writes only when a row needs it, so it converts once and takes no write lock on an up-to-date repository.
* fix(checkout): set a file no check-in recorded to 1970, as fossil does
With no mlink row for a file's artifact in the version's ancestry, fossil's max(event.mtime) is NULL, which mtime_of_manifest_file reads as 0, so --setmtime sets the file to 1970. SetMTime skipped the file.
* fix(stash): list stashes by creation time, as fossil's stash ls does
fossil stash ls orders by ctime, oldest first. List ordered by stash id, newest first; it now orders by ctime with the id breaking a tie.
* fix(auth): clear a login's invite expiry with the user, atomically
DeleteUser removed the user and its invite expiry in two statements; a failure between them left the user's expiry behind or the user without it. Both now go in one transaction. A user fossil deleted leaves its invite-expire row behind, so CreateUser clears it in the same transaction as the insert; repo invite sets its own expiry afterwards.
The on-open conversion of Julian config and user mtimes is now best-effort: while another connection holds the write lock, Open skips it and a later open converts the rows, instead of failing. (user: [email protected], size: 12092) [annotate] [blame] [check-ins using] [more...]
package auth import ( "bytes" "crypto/sha1" "encoding/hex" "testing" "time" "github.com/danmestas/go-libfossil/db" "github.com/danmestas/go-libfossil/internal/xfer" ) // buildLoginCard returns the login card a client would send ahead of payload, // as the server sees it: decoded from the wire, so it carries the body tail // its nonce is checked against. payload is the body after the login line. func buildLoginCard(user, password, projectCode string, payload []byte) *xfer.LoginCard { nonce := sha1Hex(payload) sharedSecret := sha1Hex([]byte(projectCode + "/" + user + "/" + password)) signature := sha1Hex([]byte(nonce + sharedSecret)) return onWire(&xfer.LoginCard{User: user, Nonce: nonce, Signature: signature}, payload) } // onWire decodes card followed by body, as a server receives them. func onWire(card *xfer.LoginCard, body []byte) *xfer.LoginCard { var buf bytes.Buffer if err := xfer.EncodeCard(&buf, card); err != nil { panic(err) } buf.Write(body) msg, err := xfer.DecodeUncompressed(buf.Bytes()) if err != nil { panic(err) } return msg.Cards[0].(*xfer.LoginCard) } func sha1Hex(data []byte) string { h := sha1.Sum(data) return hex.EncodeToString(h[:]) } func TestVerifyLoginSuccess(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) // Create user with known password err := CreateUser(d, code, "alice", "secret123", "ios") if err != nil { t.Fatalf("CreateUser: %v", err) } // Build valid login card payload := []byte("push sc pc\nigot abc123\n") card := buildLoginCard("alice", "secret123", code, payload) // Verify should succeed user, err := VerifyLogin(d, code, card) if err != nil { t.Fatalf("VerifyLogin: expected success, got %v", err) } if user.Login != "alice" { t.Errorf("user.Login = %q, want alice", user.Login) } if user.Cap != "ios" { t.Errorf("user.Cap = %q, want ios", user.Cap) } } func TestVerifyLoginWrongPassword(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) // Create user with known password err := CreateUser(d, code, "alice", "secret123", "o") if err != nil { t.Fatalf("CreateUser: %v", err) } // Build login card with wrong password payload := []byte("push sc pc\nigot abc123\n") card := buildLoginCard("alice", "wrongpassword", code, payload) // Verify should fail _, err = VerifyLogin(d, code, card) if err != ErrAuthFailed { t.Errorf("VerifyLogin wrong password: got %v, want ErrAuthFailed", err) } } func TestVerifyLoginUnknownUser(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) // Build login card for nonexistent user payload := []byte("push sc pc\nigot abc123\n") card := buildLoginCard("doesnotexist", "anypassword", code, payload) // Verify should fail _, err := VerifyLogin(d, code, card) if err != ErrAuthFailed { t.Errorf("VerifyLogin unknown user: got %v, want ErrAuthFailed", err) } } func TestVerifyLoginNilDB(t *testing.T) { defer func() { if r := recover(); r == nil { t.Error("VerifyLogin with nil DB should panic") } }() card := &xfer.LoginCard{User: "alice", Nonce: "abc", Signature: "def"} VerifyLogin(nil, "test-code", card) } func TestVerifyLoginNilCard(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) defer func() { if r := recover(); r == nil { t.Error("VerifyLogin with nil card should panic") } }() VerifyLogin(d, code, nil) } // A login card's signature covers only its nonce, so a card captured from one // request must fail once it heads any other body (draft ยง6.2). func TestVerifyLoginReplayedOntoOtherBody(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) if err := CreateUser(d, code, "alice", "secret123", "ios"); err != nil { t.Fatalf("CreateUser: %v", err) } signed := buildLoginCard("alice", "secret123", code, []byte("pull sc pc\n")) replay := onWire(&xfer.LoginCard{ User: signed.User, Nonce: signed.Nonce, Signature: signed.Signature, }, []byte("push sc pc\n")) if _, err := VerifyLogin(d, code, replay); err != ErrAuthFailed { t.Fatalf("VerifyLogin replayed card: got %v, want ErrAuthFailed", err) } } // A card that never came off the wire has no body for its nonce to cover. func TestVerifyLoginUndecodedCard(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) if err := CreateUser(d, code, "alice", "secret123", "ios"); err != nil { t.Fatalf("CreateUser: %v", err) } payload := []byte("pull sc pc\n") nonce := sha1Hex(payload) secret := sha1Hex([]byte(code + "/alice/secret123")) card := &xfer.LoginCard{User: "alice", Nonce: nonce, Signature: sha1Hex([]byte(nonce + secret))} if _, err := VerifyLogin(d, code, card); err != ErrAuthFailed { t.Fatalf("VerifyLogin undecoded card: got %v, want ErrAuthFailed", err) } } // nobody and anonymous need no password and gain no capabilities (src/xfer.c // check_login), but their nonce must still cover the body. func TestVerifyLoginNobodyAndAnonymous(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) for _, login := range []string{"nobody", "anonymous"} { card := buildLoginCard(login, "whatever", code, []byte("pull sc pc\n")) u, err := VerifyLogin(d, code, card) if err != nil { t.Fatalf("VerifyLogin %s: %v", login, err) } if u.Login != login || u.Cap != "" { t.Fatalf("VerifyLogin %s = %+v, want login %q with no capabilities", login, u, login) } replay := onWire(&xfer.LoginCard{User: login, Nonce: card.Nonce, Signature: card.Signature}, []byte("push sc pc\n")) if _, err := VerifyLogin(d, code, replay); err != ErrAuthFailed { t.Fatalf("VerifyLogin replayed %s: got %v, want ErrAuthFailed", login, err) } } } // An account with no stored password cannot be logged into: its signature // would be SHA1(nonce), which anyone can compute (src/xfer.c check_login // requires length(pw)>0). func TestVerifyLoginRefusesPasswordless(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) if _, err := d.Exec("INSERT INTO user(login, pw, cap) VALUES('carol', '', 'oi')"); err != nil { t.Fatalf("insert carol: %v", err) } payload := []byte("pull sc pc\n") nonce := sha1Hex(payload) card := onWire(&xfer.LoginCard{User: "carol", Nonce: nonce, Signature: sha1Hex([]byte(nonce))}, payload) if _, err := VerifyLogin(d, code, card); err != ErrAuthFailed { t.Fatalf("VerifyLogin with empty password: got %v, want ErrAuthFailed", err) } } // developer and reader are capability templates other users inherit, not // accounts, even when a row for them carries a password. func TestVerifyLoginRefusesReservedLogins(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) for _, login := range []string{"developer", "reader"} { secret := sha1Hex([]byte(code + "/" + login + "/pw")) if _, err := d.Exec( // New repositories already hold these rows, as fossil's do; give // each a password so only the reserved-name rule can refuse it. "INSERT INTO user(login, pw, cap) VALUES(?, ?, 'oi')"+ " ON CONFLICT(login) DO UPDATE SET pw=excluded.pw, cap=excluded.cap", login, secret); err != nil { t.Fatalf("insert %s: %v", login, err) } card := buildLoginCard(login, "pw", code, []byte("pull sc pc\n")) if _, err := VerifyLogin(d, code, card); err != ErrAuthFailed { t.Fatalf("VerifyLogin %s: got %v, want ErrAuthFailed", login, err) } } } // aliceCard creates alice with a password and returns a valid login card. func aliceCard(t *testing.T, d *db.DB, code string) *xfer.LoginCard { t.Helper() if err := CreateUser(d, code, "alice", "secret123", "o"); err != nil { t.Fatalf("CreateUser: %v", err) } return buildLoginCard("alice", "secret123", code, []byte("push sc pc\nigot abc123\n")) } // TestVerifyLoginIgnoresCookieExpiry: user.cexpire is the expiry of fossil's // web-login cookie, which fossil's sync login never reads (#441). A Julian // expiry fossil wrote, the 0 its logout writes, and an expiry long past all // still log in. func TestVerifyLoginIgnoresCookieExpiry(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) card := aliceCard(t, d, code) for _, cexpire := range []string{"julianday('now')+365", "0", "julianday('now')-1", "'2020-01-01 00:00:00'"} { if _, err := d.Exec("UPDATE user SET cexpire=" + cexpire + " WHERE login='alice'"); err != nil { t.Fatalf("set cexpire: %v", err) } if _, err := VerifyLogin(d, code, card); err != nil { t.Errorf("cexpire=%s: VerifyLogin = %v, want success", cexpire, err) } } } // TestVerifyLoginChecksInviteExpiry: an invite's expiry, kept apart from // cexpire, refuses the login once past and admits it before, whatever // cexpire holds. The expiry is an instant, so the zone it was computed in // does not move it. func TestVerifyLoginChecksInviteExpiry(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) card := aliceCard(t, d, code) east := time.FixedZone("UTC+10", 10*3600) west := time.FixedZone("UTC-6", -6*3600) cases := []struct { expiry time.Time cexpire string want error }{ {time.Now().Add(time.Hour).In(east), "0", nil}, {time.Now().Add(time.Hour).In(west), "julianday('now')-1", nil}, {time.Now().Add(-time.Hour).In(east), "julianday('now')+365", ErrAuthFailed}, {time.Now().Add(-time.Hour).In(west), "NULL", ErrAuthFailed}, } for _, c := range cases { if err := SetInviteExpiry(d, "alice", c.expiry); err != nil { t.Fatalf("SetInviteExpiry: %v", err) } if _, err := d.Exec("UPDATE user SET cexpire=" + c.cexpire + " WHERE login='alice'"); err != nil { t.Fatalf("set cexpire: %v", err) } if _, err := VerifyLogin(d, code, card); err != c.want { t.Errorf("invite expiry %v, cexpire=%s: VerifyLogin = %v, want %v", c.expiry, c.cexpire, err, c.want) } } } // An invite expiry that does not read as a time refuses the login. func TestVerifyLoginRefusesUnreadableInviteExpiry(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) card := aliceCard(t, d, code) if _, err := d.Exec("INSERT INTO config(name, value) VALUES(?, 'soon')", InviteExpiryKey("alice")); err != nil { t.Fatal(err) } if _, err := VerifyLogin(d, code, card); err != ErrAuthFailed { t.Errorf("VerifyLogin = %v, want ErrAuthFailed", err) } } // Deleting a user drops its invite expiry, so a later user of that login // does not inherit it. func TestDeleteUserDropsInviteExpiry(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) aliceCard(t, d, code) if err := SetInviteExpiry(d, "alice", time.Now().Add(-time.Hour)); err != nil { t.Fatal(err) } if err := DeleteUser(d, "alice"); err != nil { t.Fatal(err) } card := aliceCard(t, d, code) if _, err := VerifyLogin(d, code, card); err != nil { t.Errorf("VerifyLogin after re-creating alice = %v, want success", err) } } // A user fossil deleted leaves its invite expiry behind; creating a user of // that login clears it, so the new user does not inherit it. func TestCreateUserClearsStaleInviteExpiry(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) if err := SetInviteExpiry(d, "alice", time.Now().Add(-time.Hour)); err != nil { t.Fatal(err) } card := aliceCard(t, d, code) if _, err := VerifyLogin(d, code, card); err != nil { t.Errorf("VerifyLogin for a newly created alice = %v, want success", err) } } // DeleteUser removes the user and its invite expiry together: when the // second delete fails, the user is still there. func TestDeleteUserIsAtomic(t *testing.T) { d := setupTestDB(t) code := projectCode(t, d) aliceCard(t, d, code) if err := SetInviteExpiry(d, "alice", time.Now().Add(time.Hour)); err != nil { t.Fatal(err) } if _, err := d.Exec(`CREATE TEMP TRIGGER keep_invites BEFORE DELETE ON config WHEN old.name GLOB 'invite-expire:*' BEGIN SELECT RAISE(ABORT, 'kept'); END`); err != nil { t.Fatal(err) } if err := DeleteUser(d, "alice"); err == nil { t.Fatal("DeleteUser succeeded although the invite expiry could not be removed") } var n int if err := d.QueryRow("SELECT count(*) FROM user WHERE login='alice'").Scan(&n); err != nil { t.Fatal(err) } if n != 1 { t.Fatalf("alice rows after a failed DeleteUser = %d, want 1", n) } }