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>
267 lines
7.7 KiB
Go
267 lines
7.7 KiB
Go
package account
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/subtle"
|
|
"encoding/base32"
|
|
"errors"
|
|
"log/slog"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
|
|
)
|
|
|
|
// What a sign-in or sign-up can fail with.
|
|
var (
|
|
ErrBadCredentials = errors.New("that email and password do not match an account")
|
|
ErrNotApproved = errors.New("this account is waiting for approval")
|
|
ErrSuspended = errors.New("this account has been suspended")
|
|
ErrTooManyTries = errors.New("too many attempts; try again shortly")
|
|
ErrInvalidEmail = errors.New("that does not look like an email address")
|
|
)
|
|
|
|
// Store is what the service needs from persistence.
|
|
type Store interface {
|
|
CreateUser(ctx context.Context, u store.User) error
|
|
UserByEmail(ctx context.Context, email string) (store.User, error)
|
|
UserByID(ctx context.Context, id string) (store.User, error)
|
|
TouchLogin(ctx context.Context, id string, at time.Time) error
|
|
|
|
CreateSession(ctx context.Context, userID, token, csrf string, ttl time.Duration) error
|
|
SessionByToken(ctx context.Context, token string) (store.Session, store.User, error)
|
|
DeleteSession(ctx context.Context, token string) error
|
|
TouchSession(ctx context.Context, token string, at time.Time) error
|
|
}
|
|
|
|
// Config tunes the service.
|
|
type Config struct {
|
|
// SignupOpen decides whether anyone may create an account. Off, the form is
|
|
// not served at all; accounts are made with `llmgw users create`.
|
|
SignupOpen bool
|
|
// SessionTTL is how long a sign-in lasts.
|
|
SessionTTL time.Duration
|
|
// MaxAttempts and AttemptWindow bound password guessing per address.
|
|
MaxAttempts int
|
|
AttemptWindow time.Duration
|
|
}
|
|
|
|
// DefaultConfig returns sensible values.
|
|
func DefaultConfig() Config {
|
|
return Config{
|
|
SignupOpen: true,
|
|
SessionTTL: store.SessionTTL,
|
|
MaxAttempts: 10,
|
|
AttemptWindow: 15 * time.Minute,
|
|
}
|
|
}
|
|
|
|
func (c *Config) normalize() {
|
|
d := DefaultConfig()
|
|
if c.SessionTTL <= 0 {
|
|
c.SessionTTL = d.SessionTTL
|
|
}
|
|
if c.MaxAttempts <= 0 {
|
|
c.MaxAttempts = d.MaxAttempts
|
|
}
|
|
if c.AttemptWindow <= 0 {
|
|
c.AttemptWindow = d.AttemptWindow
|
|
}
|
|
}
|
|
|
|
// Service is signup, sign-in and sessions.
|
|
type Service struct {
|
|
store Store
|
|
cfg Config
|
|
log *slog.Logger
|
|
now func() time.Time
|
|
|
|
mu sync.Mutex
|
|
attempts map[string]*attemptWindow
|
|
}
|
|
|
|
type attemptWindow struct {
|
|
count int
|
|
since time.Time
|
|
}
|
|
|
|
// New builds the service.
|
|
func New(s Store, cfg Config, log *slog.Logger) *Service {
|
|
cfg.normalize()
|
|
if log == nil {
|
|
log = slog.Default()
|
|
}
|
|
return &Service{store: s, cfg: cfg, log: log, now: time.Now, attempts: map[string]*attemptWindow{}}
|
|
}
|
|
|
|
// SignupOpen reports whether the form should be served.
|
|
func (s *Service) SignupOpen() bool { return s.cfg.SignupOpen }
|
|
|
|
// SignUp creates a pending account.
|
|
//
|
|
// It returns nil whether or not the address was already taken. A signup form
|
|
// that says "this address already has an account" is an account enumerator that
|
|
// anyone can run, and the person signing up learns nothing they need: either
|
|
// way, what happens next is that they wait for approval.
|
|
func (s *Service) SignUp(ctx context.Context, email, name, password string) error {
|
|
email = store.NormalizeEmail(email)
|
|
if !validEmail(email) {
|
|
return ErrInvalidEmail
|
|
}
|
|
hash, err := HashPassword(password)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if name = strings.TrimSpace(name); name == "" {
|
|
name = email
|
|
}
|
|
|
|
err = s.store.CreateUser(ctx, store.User{
|
|
ID: randomID("usr"), Email: email, Name: name,
|
|
PasswordHash: hash, State: store.UserPending, CreatedAt: s.now(),
|
|
})
|
|
if errors.Is(err, store.ErrEmailTaken) {
|
|
// Logged so an operator can see it; not told to the caller.
|
|
s.log.Info("signup for an address that already has an account")
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.log.Info("a new account is waiting for approval", "email", email)
|
|
return nil
|
|
}
|
|
|
|
// SignIn checks a password and opens a session, returning the session token and
|
|
// the CSRF token that must accompany the forms in it.
|
|
func (s *Service) SignIn(ctx context.Context, email, password string) (token, csrf string, err error) {
|
|
email = store.NormalizeEmail(email)
|
|
if !s.allowAttempt(email) {
|
|
return "", "", ErrTooManyTries
|
|
}
|
|
|
|
u, err := s.store.UserByEmail(ctx, email)
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
// Verify anyway, against a hash that cannot match. Returning early here
|
|
// would let a stopwatch enumerate every account on the system.
|
|
_, _ = VerifyPassword(password, dummyHash)
|
|
return "", "", ErrBadCredentials
|
|
}
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
|
|
ok, err := VerifyPassword(password, u.PasswordHash)
|
|
if err != nil || !ok {
|
|
return "", "", ErrBadCredentials
|
|
}
|
|
// The password was right, so this was not an attack.
|
|
s.clearAttempts(email)
|
|
|
|
// State is checked after the password, on purpose. Checking first would
|
|
// tell anyone who guesses an address whether it has a pending account.
|
|
switch u.State {
|
|
case store.UserPending:
|
|
return "", "", ErrNotApproved
|
|
case store.UserSuspended:
|
|
return "", "", ErrSuspended
|
|
}
|
|
|
|
if token, err = store.NewSessionToken(); err != nil {
|
|
return "", "", err
|
|
}
|
|
if csrf, err = store.NewSessionToken(); err != nil {
|
|
return "", "", err
|
|
}
|
|
if err := s.store.CreateSession(ctx, u.ID, token, csrf, s.cfg.SessionTTL); err != nil {
|
|
return "", "", err
|
|
}
|
|
if err := s.store.TouchLogin(ctx, u.ID, s.now()); err != nil {
|
|
s.log.Warn("could not record a sign-in", "err", err)
|
|
}
|
|
return token, csrf, nil
|
|
}
|
|
|
|
// Resolve turns a session cookie into the person holding it.
|
|
func (s *Service) Resolve(ctx context.Context, token string) (store.Session, store.User, error) {
|
|
if token == "" {
|
|
return store.Session{}, store.User{}, store.ErrNoSession
|
|
}
|
|
sess, u, err := s.store.SessionByToken(ctx, token)
|
|
if err != nil {
|
|
return store.Session{}, store.User{}, err
|
|
}
|
|
if err := s.store.TouchSession(ctx, token, s.now()); err != nil {
|
|
s.log.Debug("could not touch a session", "err", err)
|
|
}
|
|
return sess, u, nil
|
|
}
|
|
|
|
// SignOut closes one session.
|
|
func (s *Service) SignOut(ctx context.Context, token string) error {
|
|
if token == "" {
|
|
return nil
|
|
}
|
|
return s.store.DeleteSession(ctx, token)
|
|
}
|
|
|
|
// CheckCSRF compares a submitted token against the session's.
|
|
//
|
|
// A cookie authenticates the browser, not the page that asked. Without this, any
|
|
// site the person visits can post a form to ours and have the browser attach the
|
|
// session automatically.
|
|
func (s *Service) CheckCSRF(sess store.Session, submitted string) bool {
|
|
if submitted == "" || len(sess.CSRFHash) == 0 {
|
|
return false
|
|
}
|
|
return subtle.ConstantTimeCompare(store.HashKey(submitted), sess.CSRFHash) == 1
|
|
}
|
|
|
|
// allowAttempt bounds password guessing per address.
|
|
//
|
|
// Per address rather than per IP: an attacker has many addresses to come from
|
|
// and only one to guess against, and limiting by IP would lock out everyone
|
|
// behind one office NAT the moment somebody fat-fingers their password.
|
|
func (s *Service) allowAttempt(email string) bool {
|
|
now := s.now()
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
w, ok := s.attempts[email]
|
|
if !ok || now.Sub(w.since) > s.cfg.AttemptWindow {
|
|
s.attempts[email] = &attemptWindow{count: 1, since: now}
|
|
return true
|
|
}
|
|
w.count++
|
|
return w.count <= s.cfg.MaxAttempts
|
|
}
|
|
|
|
func (s *Service) clearAttempts(email string) {
|
|
s.mu.Lock()
|
|
delete(s.attempts, email)
|
|
s.mu.Unlock()
|
|
}
|
|
|
|
// validEmail is deliberately crude. A real check is delivery, which this does
|
|
// not do; this only rejects what is obviously not an address so the database
|
|
// does not fill with them.
|
|
func validEmail(s string) bool {
|
|
at := strings.IndexByte(s, '@')
|
|
if at <= 0 || at != strings.LastIndexByte(s, '@') || at == len(s)-1 {
|
|
return false
|
|
}
|
|
if strings.ContainsAny(s, " \t\r\n<>\"") {
|
|
return false
|
|
}
|
|
return strings.Contains(s[at+1:], ".")
|
|
}
|
|
|
|
func randomID(prefix string) string {
|
|
var buf [10]byte
|
|
_, _ = rand.Read(buf[:])
|
|
return prefix + "-" + strings.ToLower(
|
|
base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(buf[:]))
|
|
}
|