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>
128 lines
3.9 KiB
Go
128 lines
3.9 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"database/sql"
|
|
"errors"
|
|
"time"
|
|
)
|
|
|
|
// SessionTTL is how long a sign-in lasts.
|
|
const SessionTTL = 14 * 24 * time.Hour
|
|
|
|
// ErrNoSession says a session cookie names nothing usable.
|
|
var ErrNoSession = errors.New("not signed in")
|
|
|
|
// Session is an open sign-in.
|
|
type Session struct {
|
|
UserID string
|
|
CSRFHash []byte
|
|
ExpiresAt time.Time
|
|
}
|
|
|
|
// NewSessionToken mints a session or CSRF token.
|
|
func NewSessionToken() (string, error) {
|
|
raw := make([]byte, 32)
|
|
if _, err := rand.Read(raw); err != nil {
|
|
return "", err
|
|
}
|
|
return encodeBase62(raw), nil
|
|
}
|
|
|
|
// CreateSession opens a session and returns nothing: the caller already holds
|
|
// the tokens, and neither is stored in the clear.
|
|
func (s *SQLite) CreateSession(ctx context.Context, userID, token, csrf string, ttl time.Duration) error {
|
|
if ttl <= 0 {
|
|
ttl = SessionTTL
|
|
}
|
|
now := time.Now()
|
|
_, err := s.db.ExecContext(ctx,
|
|
`INSERT INTO sessions (token_hash, user_id, csrf_hash, created_at, expires_at, last_seen)
|
|
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
HashKey(token), userID, HashKey(csrf), millis(now), millis(now.Add(ttl)), millis(now))
|
|
return err
|
|
}
|
|
|
|
// SessionByToken resolves a cookie to its session and the person it belongs to.
|
|
//
|
|
// One query rather than two: a session whose user has been suspended must stop
|
|
// working immediately, and checking that in a second round trip is a check
|
|
// somebody eventually forgets.
|
|
func (s *SQLite) SessionByToken(ctx context.Context, token string) (Session, User, error) {
|
|
row := s.db.QueryRowContext(ctx,
|
|
`SELECT s.user_id, s.csrf_hash, s.expires_at,
|
|
u.id, u.email, u.name, u.password_hash, u.state, COALESCE(u.project_id, ''),
|
|
u.created_at, u.approved_at, u.approved_by, u.last_login_at
|
|
FROM sessions s JOIN users u ON u.id = s.user_id
|
|
WHERE s.token_hash = ?`, HashKey(token))
|
|
|
|
var sess Session
|
|
var expires int64
|
|
var u User
|
|
var state string
|
|
var created int64
|
|
var approved, lastLogin sql.NullInt64
|
|
var approvedBy sql.NullString
|
|
|
|
if err := row.Scan(&sess.UserID, &sess.CSRFHash, &expires,
|
|
&u.ID, &u.Email, &u.Name, &u.PasswordHash, &state, &u.ProjectID,
|
|
&created, &approved, &approvedBy, &lastLogin); err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return Session{}, User{}, ErrNoSession
|
|
}
|
|
return Session{}, User{}, err
|
|
}
|
|
|
|
sess.ExpiresAt = fromMillis(expires)
|
|
if time.Now().After(sess.ExpiresAt) {
|
|
return Session{}, User{}, ErrNoSession
|
|
}
|
|
|
|
u.State = UserState(state)
|
|
u.CreatedAt = fromMillis(created)
|
|
u.ApprovedAt = fromNullMillis(approved)
|
|
u.ApprovedBy = approvedBy.String
|
|
u.LastLoginAt = fromNullMillis(lastLogin)
|
|
|
|
if !u.CanSignIn() {
|
|
// Suspended between sign-in and now. The session exists; it just stops
|
|
// meaning anything.
|
|
return Session{}, User{}, ErrNoSession
|
|
}
|
|
return sess, u, nil
|
|
}
|
|
|
|
// TouchSession records activity, at most once a minute.
|
|
func (s *SQLite) TouchSession(ctx context.Context, token string, at time.Time) error {
|
|
_, err := s.db.ExecContext(ctx,
|
|
`UPDATE sessions SET last_seen = ? WHERE token_hash = ? AND last_seen < ?`,
|
|
millis(at), HashKey(token), millis(at.Add(-time.Minute)))
|
|
return err
|
|
}
|
|
|
|
// DeleteSession signs one browser out.
|
|
func (s *SQLite) DeleteSession(ctx context.Context, token string) error {
|
|
_, err := s.db.ExecContext(ctx, `DELETE FROM sessions WHERE token_hash = ?`, HashKey(token))
|
|
return err
|
|
}
|
|
|
|
// DeleteUserSessions signs a person out everywhere.
|
|
//
|
|
// What suspension and a password change both need: leaving old sessions open
|
|
// would make either of them advisory.
|
|
func (s *SQLite) DeleteUserSessions(ctx context.Context, userID string) error {
|
|
_, err := s.db.ExecContext(ctx, `DELETE FROM sessions WHERE user_id = ?`, userID)
|
|
return err
|
|
}
|
|
|
|
// PurgeSessions removes expired rows.
|
|
func (s *SQLite) PurgeSessions(ctx context.Context, before time.Time) (int64, error) {
|
|
res, err := s.db.ExecContext(ctx, `DELETE FROM sessions WHERE expires_at < ?`, millis(before))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
n, _ := res.RowsAffected()
|
|
return n, nil
|
|
}
|