Backend Phase B (1/2): password auth + sessions

Argon2id password hashing (PHC format, self-encoded/decoded without an
external lib) with constant-time verification, UserStore (create/get by
email and id) and SessionStore (opaque crypto/rand tokens, SHA-256 hashed
in DB, create/lookup/revoke, last_seen_at bump on lookup).

HTTP layer: Register/Login/Logout handlers + RequireAuth middleware.
Login uses a dummy-hash path so unknown-email and wrong-password yield the
same timing/shape, narrowing user enumeration. Tokens accepted via Bearer
header (native clients) or session cookie (HttpOnly, SameSite=Lax).

Routes wired in api.go: POST /auth/register, /auth/login, /auth/logout.
Verified with go test, go vet and an end-to-end smoke test against a real
PostgreSQL container (register/login/logout/duplicate/short-pw/wrong-pw).

OIDC (Phase B part 2) follows next; the issueSession helper is reused.
This commit is contained in:
Tronax 2026-08-05 19:05:07 +02:00
parent 2899eb205b
commit 7b1c18590e
Signed by: Tronax
SSH key fingerprint: SHA256:2pKKXDZucWvaF/GzXNz0FY53EAO1YDLN80bqS+TTz/o
10 changed files with 756 additions and 29 deletions

View file

@ -0,0 +1,137 @@
// Package auth implements password hashing, session management and (later) OIDC
// verification for the mitbringsl backend.
package auth
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strconv"
"strings"
"golang.org/x/crypto/argon2"
)
// Argon2Params holds the cost parameters for the Argon2id key derivation.
// Defaults follow the RFC-9106 "first recommended" option for memory-hard
// single-instance hashing (m=64MiB, t=3, p=4). They are deliberately not
// configurable via env to avoid accidental downgrades; change via code instead.
type Argon2Params struct {
Memory uint32 // in KiB
Iterations uint32
Parallelism uint8
SaltLength uint32 // bytes
KeyLength uint32 // bytes
}
// DefaultArgon2Params are tuned for a backend with ~256MiB headroom per login.
// Memory = 64 * 1024 KiB = 64 MiB.
var DefaultArgon2Params = Argon2Params{
Memory: 64 * 1024,
Iterations: 3,
Parallelism: 4,
SaltLength: 16,
KeyLength: 32,
}
// ErrInvalidHash is returned when a stored password hash is not a valid PHC string.
var ErrInvalidHash = errors.New("invalid password hash")
// HashPassword derives an Argon2id hash from the password and encodes it in the
// PHC string format: $argon2id$v=19$m=<m>,t=<t>,p=<p>$<salt_b64>$<hash_b64>.
// The returned string is safe to store verbatim in the users.password_hash column.
func HashPassword(password string, p Argon2Params) (string, error) {
salt := make([]byte, p.SaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate salt: %w", err)
}
key := argon2.IDKey([]byte(password), salt, p.Iterations, p.Memory, p.Parallelism, p.KeyLength)
return encodePHC(p, salt, key), nil
}
// VerifyPassword compares a password against a stored PHC-format hash in constant
// time. It returns a non-nil error if the hash is malformed or the password does
// not match.
func VerifyPassword(password, encoded string) error {
p, salt, hash, err := decodePHC(encoded)
if err != nil {
return err
}
otherKey := argon2.IDKey([]byte(password), salt, p.Iterations, p.Memory, p.Parallelism, uint32(len(hash)))
if subtle.ConstantTimeCompare(hash, otherKey) != 1 {
return errors.New("password does not match")
}
return nil
}
// --- PHC encoding helpers ----------------------------------------------------
const phcAlg = "argon2id"
func encodePHC(p Argon2Params, salt, key []byte) string {
b64 := base64.RawStdEncoding.EncodeToString
return fmt.Sprintf("$%s$v=%d$m=%d,t=%d,p=%d$%s$%s",
phcAlg, argon2.Version, p.Memory, p.Iterations, p.Parallelism,
b64(salt), b64(key))
}
func decodePHC(encoded string) (Argon2Params, []byte, []byte, error) {
parts := strings.Split(encoded, "$")
// Expected: ["", "argon2id", "v=19", "m=..,t=..,p=..", "<salt>", "<hash>"]
if len(parts) != 6 || parts[1] != phcAlg {
return Argon2Params{}, nil, nil, fmt.Errorf("%w: wrong format", ErrInvalidHash)
}
var version int
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
return Argon2Params{}, nil, nil, fmt.Errorf("%w: parse version: %v", ErrInvalidHash, err)
}
if version != argon2.Version {
return Argon2Params{}, nil, nil, fmt.Errorf("%w: unsupported version %d", ErrInvalidHash, version)
}
p, err := parseParams(parts[3])
if err != nil {
return Argon2Params{}, nil, nil, err
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return Argon2Params{}, nil, nil, fmt.Errorf("%w: decode salt: %v", ErrInvalidHash, err)
}
key, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return Argon2Params{}, nil, nil, fmt.Errorf("%w: decode key: %v", ErrInvalidHash, err)
}
p.KeyLength = uint32(len(key))
p.SaltLength = uint32(len(salt))
return p, salt, key, nil
}
func parseParams(s string) (Argon2Params, error) {
var p Argon2Params
for _, kv := range strings.Split(s, ",") {
k, v, ok := strings.Cut(kv, "=")
if !ok {
return Argon2Params{}, fmt.Errorf("%w: malformed param %q", ErrInvalidHash, kv)
}
n, err := strconv.ParseUint(v, 10, 32)
if err != nil {
return Argon2Params{}, fmt.Errorf("%w: parse %s: %v", ErrInvalidHash, k, err)
}
switch k {
case "m":
p.Memory = uint32(n)
case "t":
p.Iterations = uint32(n)
case "p":
p.Parallelism = uint8(n)
}
}
if p.Memory == 0 || p.Iterations == 0 || p.Parallelism == 0 {
return Argon2Params{}, fmt.Errorf("%w: missing cost parameter", ErrInvalidHash)
}
return p, nil
}