Files
llmgw/internal/store/users.go
T
Ilker ManapandClaude Opus 5 216fc9bb03 Let people sign up, be approved, and issue their own keys
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>
2026-09-16 09:32:35 +02:00

200 lines
6.4 KiB
Go

package store
import (
"context"
"database/sql"
"errors"
"strings"
"time"
)
// UserState is where an account is in its life.
type UserState string
// The account states. A new account is pending until an operator approves it,
// which is what keeps a public signup form from being a way in.
const (
UserPending UserState = "pending"
UserActive UserState = "active"
UserSuspended UserState = "suspended"
)
// ErrEmailTaken says an address already has an account.
//
// It is returned to callers that need to know — the CLI — and deliberately not
// surfaced to a signup form, where it would confirm which addresses have
// accounts here.
var ErrEmailTaken = errors.New("that address already has an account")
// User is a person.
type User struct {
ID string
Email string
Name string
PasswordHash string
State UserState
// ProjectID is assigned at approval and decides which limits the person's
// keys inherit. Empty while pending.
ProjectID string
CreatedAt time.Time
ApprovedAt time.Time
ApprovedBy string
LastLoginAt time.Time
}
// CanSignIn reports whether this account may open a session.
func (u User) CanSignIn() bool { return u.State == UserActive }
// NormalizeEmail is applied at every boundary, so two accounts cannot differ
// only in case — which would be two accounts to the database and one to every
// human who looks at them.
func NormalizeEmail(email string) string {
return strings.ToLower(strings.TrimSpace(email))
}
const userColumns = `id, email, name, password_hash, state, COALESCE(project_id, ''),
created_at, approved_at, approved_by, last_login_at`
// CreateUser records a new, unapproved account.
func (s *SQLite) CreateUser(ctx context.Context, u User) error {
u.Email = NormalizeEmail(u.Email)
_, err := s.db.ExecContext(ctx,
`INSERT INTO users (id, email, name, password_hash, state, project_id, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
u.ID, u.Email, u.Name, u.PasswordHash, string(u.State),
nullString(u.ProjectID), millis(u.CreatedAt))
if err != nil && strings.Contains(err.Error(), "UNIQUE") {
return ErrEmailTaken
}
return err
}
// UserByEmail finds an account by its address.
func (s *SQLite) UserByEmail(ctx context.Context, email string) (User, error) {
return s.scanUser(s.db.QueryRowContext(ctx,
`SELECT `+userColumns+` FROM users WHERE email = ?`, NormalizeEmail(email)))
}
// UserByID finds an account.
func (s *SQLite) UserByID(ctx context.Context, id string) (User, error) {
return s.scanUser(s.db.QueryRowContext(ctx,
`SELECT `+userColumns+` FROM users WHERE id = ?`, id))
}
// Users lists accounts, optionally filtered by state.
func (s *SQLite) Users(ctx context.Context, state UserState) ([]User, error) {
query := `SELECT ` + userColumns + ` FROM users`
var args []any
if state != "" {
query += ` WHERE state = ?`
args = append(args, string(state))
}
query += ` ORDER BY created_at`
return queryAll(ctx, s.db, query, args, func(rows *sql.Rows) (User, error) {
return s.scanUser(rows)
})
}
// ApproveUser activates an account and places it in a project.
//
// The project is required: an approved account with nowhere to put its keys
// would pass every check and then fail at the first key it tried to make.
func (s *SQLite) ApproveUser(ctx context.Context, id, projectID, by string, at time.Time) error {
if projectID == "" {
return errors.New("approving an account needs a project for its keys")
}
res, err := s.db.ExecContext(ctx,
`UPDATE users SET state = ?, project_id = ?, approved_at = ?, approved_by = ?
WHERE id = ? AND state = ?`,
string(UserActive), projectID, millis(at), by, id, string(UserPending))
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return nil
}
// SetUserState suspends or reinstates an account.
func (s *SQLite) SetUserState(ctx context.Context, id string, state UserState) error {
res, err := s.db.ExecContext(ctx, `UPDATE users SET state = ? WHERE id = ?`, string(state), id)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return nil
}
// TouchLogin records a successful sign-in.
func (s *SQLite) TouchLogin(ctx context.Context, id string, at time.Time) error {
_, err := s.db.ExecContext(ctx, `UPDATE users SET last_login_at = ? WHERE id = ?`,
millis(at), id)
return err
}
// KeysForUser lists the keys a person made for themselves.
func (s *SQLite) KeysForUser(ctx context.Context, userID string) ([]Key, error) {
return queryAll(ctx, s.db,
`SELECT `+keyColumns+` FROM api_keys WHERE user_id = ? ORDER BY created_at DESC`,
[]any{userID}, func(rows *sql.Rows) (Key, error) { return scanKey(rows) })
}
// CreateUserKey issues a key owned by a person.
func (s *SQLite) CreateUserKey(ctx context.Context, userID string, k Key) error {
if len(k.Hash) == 0 {
return errors.New("store: a key needs a hash")
}
_, err := s.db.ExecContext(ctx,
`INSERT INTO api_keys (`+keyColumns+`, user_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
k.ID, k.Hash, k.Prefix, k.Name, k.ProjectID,
nullString(k.Band), nullString(k.RoutingProfile),
millis(k.CreatedAt), nullMillis(k.ExpiresAt), nullMillis(k.RevokedAt),
nullMillis(k.LastUsedAt), userID)
return err
}
// RevokeUserKey revokes a key only if it belongs to this person.
//
// The ownership check is in the statement rather than in a prior read: two
// queries would leave a window where a key changes hands between them, and more
// importantly it would be one forgotten check away from letting anyone revoke
// anyone's key by id.
func (s *SQLite) RevokeUserKey(ctx context.Context, userID, keyID string, at time.Time) error {
res, err := s.db.ExecContext(ctx,
`UPDATE api_keys SET revoked_at = ?
WHERE id = ? AND user_id = ? AND revoked_at IS NULL`,
millis(at), keyID, userID)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return nil
}
func (s *SQLite) scanUser(sc scanner) (User, error) {
var u User
var state string
var created int64
var approved, lastLogin sql.NullInt64
var approvedBy sql.NullString
if err := sc.Scan(&u.ID, &u.Email, &u.Name, &u.PasswordHash, &state, &u.ProjectID,
&created, &approved, &approvedBy, &lastLogin); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return User{}, ErrNotFound
}
return User{}, err
}
u.State = UserState(state)
u.CreatedAt = fromMillis(created)
u.ApprovedAt = fromNullMillis(approved)
u.ApprovedBy = approvedBy.String
u.LastLoginAt = fromNullMillis(lastLogin)
return u, nil
}