CI / Test (ubuntu-latest) (push) Canceled after 0s
CI / Test (windows-latest) (push) Canceled after 0s
CI / Storage tests on PostgreSQL (push) Canceled after 0s
CI / Complement (federation off) (push) Canceled after 0s
CI / golangci-lint (push) Canceled after 0s
CI / Smoke test the binary (push) Canceled after 0s
Implements PLAN.md Phase 1. A client can now register, log in, manage its devices and set its profile; an operator can create accounts and flip the runtime switches. There are still no rooms and no real /sync. userapi: accounts, argon2id passwords in PHC format, devices, access and refresh tokens stored as SHA-256 hashes, account data and the admin flag. Its storage interface is storage.UserStore, implemented once in sqlstore with `?` placeholders; the postgres driver supplies a rebind function and unique-violation recognition rather than keeping a second copy of thirty statements. Timestamps in these tables are int64 milliseconds, the unit the Client-Server API uses on the wire. Client-Server API: register (user-interactive auth with m.login.dummy and optional registration tokens), register/available, token validity, login with m.login.password, logout, logout/all, refresh, account/whoami, capabilities, devices/* with password-gated deletion, profile/*, global and per-room account data. GET /sync is a deliberate placeholder: it answers a valid token with an empty but well-formed response and refuses a revoked one. Phase 1 has no rooms, so that is the whole truth, and it is what makes session revocation observable. Phase 4 replaces it with the syncapi. Auth middleware resolves a bearer token (header or the legacy query parameter) to a device and user, answering an expired token with the soft logout the spec asks for. Rate limiting is a token bucket per endpoint class keyed on the client address, returning M_LIMIT_EXCEEDED with retry_after_ms. adminapi v1 under /_warp/admin/v1: admin-only auth via a normal Matrix token, GET/PUT /federation and /registration driving internal/settings and reporting a config-pinned switch as a 409, GET/POST /users, GET /stats. warp create-account [--admin] creates the first account straight in the database, so a new install with registration off has a way in. Complement is wired up for the federation=off profile: an image meeting its contract, an entrypoint that configures Warp entirely from WARP_* variables, and a runner that builds, clones and executes the target set (TestRegistration, TestLogin, TestDeviceManagement). It has not been run yet -- there is no container runtime on the development machine -- so the three tests' assertions were read from the Complement sources and pinned as httptest tests instead, and CI gained a job that runs the real thing. Also fixes a .gitignore bug from Phase 0: the unanchored `warp` pattern, meant for the built binary, also matched the directory server/cmd/warp and silently excluded the entire command package from the repository. The binary patterns are now anchored to the repository root, and cmd/warp is committed for the first time. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
138 lines
4.8 KiB
Go
138 lines
4.8 KiB
Go
package userapi
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"golang.org/x/crypto/argon2"
|
|
)
|
|
|
|
// Argon2id parameters. These are OWASP's recommended settings for argon2id
|
|
// (19 MiB, two passes, one lane): strong enough to make a stolen hash
|
|
// expensive to attack, cheap enough that a login does not become a denial of
|
|
// service against the server itself.
|
|
//
|
|
// The values are recorded in every hash, so raising them later is a matter
|
|
// of changing these constants; old hashes keep verifying with the parameters
|
|
// they were made with, and are rewritten the next time the password changes.
|
|
const (
|
|
argonMemoryKiB = 19 * 1024
|
|
argonTime = 2
|
|
argonLanes = 1
|
|
argonSaltLen = 16
|
|
argonKeyLen = 32
|
|
)
|
|
|
|
// MaxPasswordLength caps a password at 512 bytes. Argon2id does not care how
|
|
// long its input is, but accepting unbounded input means accepting unbounded
|
|
// work in the hash function.
|
|
const MaxPasswordLength = 512
|
|
|
|
// ErrPasswordTooLong is returned when a password exceeds MaxPasswordLength.
|
|
var ErrPasswordTooLong = fmt.Errorf("password must be at most %d bytes", MaxPasswordLength)
|
|
|
|
// ErrInvalidPasswordHash is returned when a stored hash cannot be parsed. It
|
|
// means the row is corrupt, not that the password was wrong.
|
|
var ErrInvalidPasswordHash = errors.New("stored password hash is malformed")
|
|
|
|
// HashPassword returns an encoded argon2id hash in the PHC string format:
|
|
//
|
|
// $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>
|
|
//
|
|
// The format is the de facto standard for password hashes, so the parameters
|
|
// travel with the hash and an operator can tell at a glance what a row was
|
|
// written with.
|
|
func HashPassword(password string) (string, error) {
|
|
if len(password) > MaxPasswordLength {
|
|
return "", ErrPasswordTooLong
|
|
}
|
|
salt := make([]byte, argonSaltLen)
|
|
if _, err := rand.Read(salt); err != nil {
|
|
return "", fmt.Errorf("generate password salt: %w", err)
|
|
}
|
|
key := argon2.IDKey([]byte(password), salt, argonTime, argonMemoryKiB, argonLanes, argonKeyLen)
|
|
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
|
argon2.Version, argonMemoryKiB, argonTime, argonLanes,
|
|
b64.EncodeToString(salt), b64.EncodeToString(key)), nil
|
|
}
|
|
|
|
// VerifyPassword reports whether password matches encoded. An unparseable
|
|
// hash is an error rather than a mismatch, so a corrupt row shows up in the
|
|
// logs instead of looking like a wrong password forever.
|
|
func VerifyPassword(encoded, password string) (bool, error) {
|
|
if len(password) > MaxPasswordLength {
|
|
return false, ErrPasswordTooLong
|
|
}
|
|
params, salt, want, err := decodeHash(encoded)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
got := argon2.IDKey([]byte(password), salt, params.time, params.memory, params.lanes, uint32(len(want)))
|
|
return subtle.ConstantTimeCompare(got, want) == 1, nil
|
|
}
|
|
|
|
// b64 is the unpadded base64 the PHC format uses.
|
|
var b64 = base64.RawStdEncoding
|
|
|
|
type argonParams struct {
|
|
memory uint32
|
|
time uint32
|
|
lanes uint8
|
|
}
|
|
|
|
// decodeHash parses a PHC argon2id string.
|
|
func decodeHash(encoded string) (argonParams, []byte, []byte, error) {
|
|
// "", "argon2id", "v=19", "m=...,t=...,p=...", salt, hash
|
|
parts := strings.Split(encoded, "$")
|
|
if len(parts) != 6 || parts[0] != "" {
|
|
return argonParams{}, nil, nil, ErrInvalidPasswordHash
|
|
}
|
|
if parts[1] != "argon2id" {
|
|
return argonParams{}, nil, nil, fmt.Errorf("%w: unsupported algorithm %q", ErrInvalidPasswordHash, parts[1])
|
|
}
|
|
|
|
var version int
|
|
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
|
return argonParams{}, nil, nil, ErrInvalidPasswordHash
|
|
}
|
|
if version != argon2.Version {
|
|
return argonParams{}, nil, nil, fmt.Errorf("%w: unsupported argon2 version %d", ErrInvalidPasswordHash, version)
|
|
}
|
|
|
|
var p argonParams
|
|
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.time, &p.lanes); err != nil {
|
|
return argonParams{}, nil, nil, ErrInvalidPasswordHash
|
|
}
|
|
if p.memory == 0 || p.time == 0 || p.lanes == 0 {
|
|
return argonParams{}, nil, nil, ErrInvalidPasswordHash
|
|
}
|
|
|
|
salt, err := b64.DecodeString(parts[4])
|
|
if err != nil || len(salt) == 0 {
|
|
return argonParams{}, nil, nil, ErrInvalidPasswordHash
|
|
}
|
|
key, err := b64.DecodeString(parts[5])
|
|
if err != nil || len(key) == 0 {
|
|
return argonParams{}, nil, nil, ErrInvalidPasswordHash
|
|
}
|
|
return p, salt, key, nil
|
|
}
|
|
|
|
// dummyPasswordHash is verified against when the named account does not
|
|
// exist or has no password, so that a login attempt costs the same either
|
|
// way. Without it, the time a rejection takes would tell an attacker which
|
|
// user names are real.
|
|
var dummyPasswordHash = func() string {
|
|
hash, err := HashPassword("warp: this password hashes nothing")
|
|
if err != nil {
|
|
// HashPassword only fails on a short read from crypto/rand, which
|
|
// at init time means the process cannot work at all.
|
|
panic("userapi: cannot build the dummy password hash: " + err.Error())
|
|
}
|
|
return hash
|
|
}()
|