CI / test (push) Successful in 1m9s
Every key needed an operator with a shell. This adds the login system that made that necessary, which is the thing I argued against building until it was asked for — so it is built as if it will be attacked, because a public login form is. Signing up produces an account that can do nothing. Approval is what makes it work and stays on the CLI: having a shell on the control plane is what makes someone an administrator, and that is a smaller thing to get right than roles and an admin UI that mints credentials. The details that matter: Passwords are argon2id, where a slow hash is correct — the input is chosen by a human and has a dictionary, which is the opposite of an API key. Both kinds of authentication now live in this codebase and they are in separate packages so neither set of assumptions leaks into the other. Length is the only rule: composition rules push people towards Password1! and cost more entropy than they buy. Signup never says whether an address already has an account, and sign-in answers the same way for a wrong password and a missing account — verifying against a dummy hash when there is no user, so a stopwatch cannot enumerate accounts. Account state is checked after the password, not before, so guessing an address reveals nothing about it. Guessing is bounded per address rather than per IP: an attacker has many addresses to come from and one to guess against, and limiting by IP locks out an office behind one NAT. Sessions are server-side, so signing out and suspending take effect immediately rather than whenever a token expires; suspension is checked in the same query that resolves the session, because a second round trip is a check somebody eventually forgets. Every state-changing form carries a CSRF token verified against a hash in the session — a cookie authenticates the browser, not the page that asked. Key ownership is enforced in the UPDATE rather than by reading first, so a guessed key id from another account changes nothing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
313 lines
9.7 KiB
Go
313 lines
9.7 KiB
Go
package account
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
|
|
)
|
|
|
|
func newStore(t *testing.T) *store.SQLite {
|
|
t.Helper()
|
|
s, err := store.OpenSQLite(context.Background(), filepath.Join(t.TempDir(), "a.db"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = s.Close() })
|
|
|
|
ctx := context.Background()
|
|
for _, err := range []error{
|
|
s.PutOrg(ctx, store.Org{ID: "org", Name: "Org"}),
|
|
s.PutTeam(ctx, store.Team{ID: "team", OrgID: "org", Name: "Team"}),
|
|
s.PutProject(ctx, store.Project{ID: "proj", TeamID: "team", Name: "Proj"}),
|
|
} {
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
return s
|
|
}
|
|
|
|
func newService(t *testing.T) (*Service, *store.SQLite) {
|
|
t.Helper()
|
|
s := newStore(t)
|
|
return New(s, DefaultConfig(), slog.New(slog.DiscardHandler)), s
|
|
}
|
|
|
|
const goodPassword = "correct horse battery staple"
|
|
|
|
func TestSignupLeavesAnAccountWaiting(t *testing.T) {
|
|
// A public signup form that produced a working account would be a way in.
|
|
svc, st := newService(t)
|
|
ctx := context.Background()
|
|
|
|
if err := svc.SignUp(ctx, "Ayse@Example.COM", "Ayşe", goodPassword); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
u, err := st.UserByEmail(ctx, "ayse@example.com")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if u.State != store.UserPending {
|
|
t.Errorf("a new account is %q", u.State)
|
|
}
|
|
if u.Email != "ayse@example.com" {
|
|
t.Errorf("the address was not normalized: %q", u.Email)
|
|
}
|
|
|
|
if _, _, err := svc.SignIn(ctx, "ayse@example.com", goodPassword); !errors.Is(err, ErrNotApproved) {
|
|
t.Errorf("a pending account signed in: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestSignupDoesNotRevealExistingAccounts(t *testing.T) {
|
|
// A form that says "this address already has an account" is an account
|
|
// enumerator anyone can run, and the person signing up learns nothing they
|
|
// need: either way they wait for approval.
|
|
svc, _ := newService(t)
|
|
ctx := context.Background()
|
|
|
|
if err := svc.SignUp(ctx, "ayse@example.com", "A", goodPassword); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := svc.SignUp(ctx, "ayse@example.com", "Someone Else", goodPassword); err != nil {
|
|
t.Errorf("the second signup reported %v, which confirms the address is taken", err)
|
|
}
|
|
}
|
|
|
|
func TestApprovalIsWhatMakesAnAccountWork(t *testing.T) {
|
|
svc, st := newService(t)
|
|
ctx := context.Background()
|
|
must(t, svc.SignUp(ctx, "ayse@example.com", "A", goodPassword))
|
|
|
|
u, _ := st.UserByEmail(ctx, "ayse@example.com")
|
|
must(t, st.ApproveUser(ctx, u.ID, "proj", "ilker", time.Now()))
|
|
|
|
token, csrf, err := svc.SignIn(ctx, "ayse@example.com", goodPassword)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if token == "" || csrf == "" {
|
|
t.Fatal("sign-in produced no session")
|
|
}
|
|
_, got, err := svc.Resolve(ctx, token)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got.ProjectID != "proj" {
|
|
t.Errorf("the approved account landed in project %q", got.ProjectID)
|
|
}
|
|
}
|
|
|
|
func TestApprovalNeedsAProject(t *testing.T) {
|
|
// An approved account with nowhere to put its keys passes every check and
|
|
// then fails at the first key it tries to make.
|
|
_, st := newStoreAndUser(t)
|
|
if err := st.ApproveUser(context.Background(), "usr-1", "", "ilker", time.Now()); err == nil {
|
|
t.Error("an account was approved into no project")
|
|
}
|
|
}
|
|
|
|
func newStoreAndUser(t *testing.T) (*Service, *store.SQLite) {
|
|
t.Helper()
|
|
svc, st := newService(t)
|
|
hash, _ := HashPassword(goodPassword)
|
|
must(t, st.CreateUser(context.Background(), store.User{
|
|
ID: "usr-1", Email: "ayse@example.com", Name: "A",
|
|
PasswordHash: hash, State: store.UserPending, CreatedAt: time.Now(),
|
|
}))
|
|
return svc, st
|
|
}
|
|
|
|
func TestSuspensionTakesEffectOnOpenSessions(t *testing.T) {
|
|
// Leaving existing sessions open would make suspension advisory.
|
|
svc, st := newStoreAndUser(t)
|
|
ctx := context.Background()
|
|
must(t, st.ApproveUser(ctx, "usr-1", "proj", "ilker", time.Now()))
|
|
|
|
token, _, err := svc.SignIn(ctx, "ayse@example.com", goodPassword)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, _, err := svc.Resolve(ctx, token); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
must(t, st.SetUserState(ctx, "usr-1", store.UserSuspended))
|
|
if _, _, err := svc.Resolve(ctx, token); !errors.Is(err, store.ErrNoSession) {
|
|
t.Errorf("a suspended account kept its session: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestSignOutEndsTheSession(t *testing.T) {
|
|
svc, st := newStoreAndUser(t)
|
|
ctx := context.Background()
|
|
must(t, st.ApproveUser(ctx, "usr-1", "proj", "ilker", time.Now()))
|
|
|
|
token, _, _ := svc.SignIn(ctx, "ayse@example.com", goodPassword)
|
|
must(t, svc.SignOut(ctx, token))
|
|
if _, _, err := svc.Resolve(ctx, token); !errors.Is(err, store.ErrNoSession) {
|
|
t.Errorf("the session survived sign-out: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestAWrongPasswordAndAMissingAccountAreIndistinguishable(t *testing.T) {
|
|
svc, st := newStoreAndUser(t)
|
|
ctx := context.Background()
|
|
must(t, st.ApproveUser(ctx, "usr-1", "proj", "ilker", time.Now()))
|
|
|
|
_, _, wrong := svc.SignIn(ctx, "ayse@example.com", "wrong password here")
|
|
_, _, missing := svc.SignIn(ctx, "nobody@example.com", "wrong password here")
|
|
if !errors.Is(wrong, ErrBadCredentials) || !errors.Is(missing, ErrBadCredentials) {
|
|
t.Fatalf("wrong=%v missing=%v", wrong, missing)
|
|
}
|
|
}
|
|
|
|
func TestGuessingIsBounded(t *testing.T) {
|
|
// Without this a public login form is an open brute-force target.
|
|
svc, st := newStoreAndUser(t)
|
|
ctx := context.Background()
|
|
must(t, st.ApproveUser(ctx, "usr-1", "proj", "ilker", time.Now()))
|
|
|
|
cfg := DefaultConfig()
|
|
cfg.MaxAttempts = 3
|
|
svc = New(st, cfg, slog.New(slog.DiscardHandler))
|
|
|
|
for i := range 3 {
|
|
if _, _, err := svc.SignIn(ctx, "ayse@example.com", "nope"); !errors.Is(err, ErrBadCredentials) {
|
|
t.Fatalf("attempt %d: %v", i, err)
|
|
}
|
|
}
|
|
if _, _, err := svc.SignIn(ctx, "ayse@example.com", "nope"); !errors.Is(err, ErrTooManyTries) {
|
|
t.Errorf("guessing was not bounded: %v", err)
|
|
}
|
|
// And a correct password is refused too while the window is open, or the
|
|
// limit would be trivially bypassed by interleaving.
|
|
if _, _, err := svc.SignIn(ctx, "ayse@example.com", goodPassword); !errors.Is(err, ErrTooManyTries) {
|
|
t.Errorf("the window did not apply to a correct password: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestASuccessfulSignInClearsTheWindow(t *testing.T) {
|
|
// Otherwise a person who mistypes their password a few times is locked out
|
|
// for the rest of the window even after getting it right.
|
|
st := newStore(t)
|
|
hash, _ := HashPassword(goodPassword)
|
|
ctx := context.Background()
|
|
must(t, st.CreateUser(ctx, store.User{
|
|
ID: "usr-1", Email: "a@example.com", Name: "A",
|
|
PasswordHash: hash, State: store.UserPending, CreatedAt: time.Now(),
|
|
}))
|
|
must(t, st.ApproveUser(ctx, "usr-1", "proj", "ilker", time.Now()))
|
|
|
|
cfg := DefaultConfig()
|
|
cfg.MaxAttempts = 3
|
|
svc := New(st, cfg, slog.New(slog.DiscardHandler))
|
|
|
|
for range 2 {
|
|
_, _, _ = svc.SignIn(ctx, "a@example.com", "nope")
|
|
}
|
|
if _, _, err := svc.SignIn(ctx, "a@example.com", goodPassword); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for range 3 {
|
|
if _, _, err := svc.SignIn(ctx, "a@example.com", "nope"); errors.Is(err, ErrTooManyTries) {
|
|
t.Fatal("the window was not cleared by a successful sign-in")
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCSRFTokensAreCheckedAgainstTheSession(t *testing.T) {
|
|
svc, st := newStoreAndUser(t)
|
|
ctx := context.Background()
|
|
must(t, st.ApproveUser(ctx, "usr-1", "proj", "ilker", time.Now()))
|
|
|
|
token, csrf, _ := svc.SignIn(ctx, "ayse@example.com", goodPassword)
|
|
sess, _, _ := svc.Resolve(ctx, token)
|
|
|
|
if !svc.CheckCSRF(sess, csrf) {
|
|
t.Error("the session's own token was rejected")
|
|
}
|
|
for _, bad := range []string{"", "wrong", csrf + "x", csrf[:len(csrf)-1]} {
|
|
if svc.CheckCSRF(sess, bad) {
|
|
t.Errorf("%q was accepted as a csrf token", bad)
|
|
}
|
|
}
|
|
// A token from another session must not work in this one.
|
|
other, otherCSRF, _ := svc.SignIn(ctx, "ayse@example.com", goodPassword)
|
|
_ = other
|
|
if svc.CheckCSRF(sess, otherCSRF) {
|
|
t.Error("another session's token was accepted")
|
|
}
|
|
}
|
|
|
|
func TestPasswordsAreHashedNotStored(t *testing.T) {
|
|
svc, st := newService(t)
|
|
ctx := context.Background()
|
|
must(t, svc.SignUp(ctx, "ayse@example.com", "A", goodPassword))
|
|
|
|
u, _ := st.UserByEmail(ctx, "ayse@example.com")
|
|
if strings.Contains(u.PasswordHash, goodPassword) {
|
|
t.Fatal("the password is in the database")
|
|
}
|
|
if !strings.HasPrefix(u.PasswordHash, "$argon2id$") {
|
|
t.Errorf("hash format: %q", u.PasswordHash)
|
|
}
|
|
ok, err := VerifyPassword(goodPassword, u.PasswordHash)
|
|
if err != nil || !ok {
|
|
t.Errorf("the hash does not verify: %v %v", ok, err)
|
|
}
|
|
if ok, _ := VerifyPassword("something else entirely", u.PasswordHash); ok {
|
|
t.Error("a wrong password verified")
|
|
}
|
|
}
|
|
|
|
func TestTwoHashesOfOnePasswordDiffer(t *testing.T) {
|
|
// A salt that did not vary would make the table a rainbow-table lookup.
|
|
a, _ := HashPassword(goodPassword)
|
|
b, _ := HashPassword(goodPassword)
|
|
if a == b {
|
|
t.Fatal("hashing is not salted")
|
|
}
|
|
}
|
|
|
|
func TestShortPasswordsAreRefused(t *testing.T) {
|
|
if _, err := HashPassword("short"); !errors.Is(err, ErrWeakPassword) {
|
|
t.Errorf("a five-character password was accepted: %v", err)
|
|
}
|
|
svc, _ := newService(t)
|
|
if err := svc.SignUp(context.Background(), "a@example.com", "A", "short"); !errors.Is(err, ErrWeakPassword) {
|
|
t.Errorf("signup accepted it: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestMalformedHashesAreRejectedRatherThanMatched(t *testing.T) {
|
|
for _, bad := range []string{"", "plaintext", "$argon2id$", "$bcrypt$v=19$m=1,t=1,p=1$aa$bb"} {
|
|
if ok, err := VerifyPassword(goodPassword, bad); ok || err == nil {
|
|
t.Errorf("VerifyPassword(%q) = %v, %v", bad, ok, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestObviousNonAddressesAreRefused(t *testing.T) {
|
|
svc, _ := newService(t)
|
|
ctx := context.Background()
|
|
for _, bad := range []string{"", "ayse", "ayse@", "@example.com", "a b@example.com", "a@b", "a@@b.com"} {
|
|
if err := svc.SignUp(ctx, bad, "A", goodPassword); !errors.Is(err, ErrInvalidEmail) {
|
|
t.Errorf("SignUp(%q) = %v", bad, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func must(t *testing.T, err error) {
|
|
t.Helper()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|