Files
Warp/server/internal/userapi/tokens.go
T
tajniak81andClaude Opus 5 6004bb01de
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
Phase 1: accounts and sessions
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>
2026-10-15 18:18:37 +02:00

101 lines
3.7 KiB
Go

package userapi
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
)
// Token prefixes. Matrix tokens are opaque to clients, so the prefix is for
// our side: it makes a token recognisable in a log or a bug report, it lets
// secret scanners match on something, and it means a client that sends its
// refresh token where the access token belongs gets a clear rejection
// instead of a puzzling one.
const (
accessTokenPrefix = "warp_at_"
refreshTokenPrefix = "warp_rt_"
)
// tokenEntropyBytes is the random part of a token: 256 bits, the same order
// as the session cookies of anything else worth attacking.
const tokenEntropyBytes = 32
// deviceIDLength is how many characters a generated device ID has. Ten
// uppercase letters is the shape clients and users are used to seeing, and
// 26^10 is far more than a user will ever have devices.
const deviceIDLength = 10
// deviceIDAlphabet is uppercase ASCII only: device IDs are read aloud during
// device verification, so digits and letters that look alike are a nuisance.
const deviceIDAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
// GenerateAccessToken returns a new access token.
func GenerateAccessToken() (string, error) { return generateToken(accessTokenPrefix) }
// GenerateRefreshToken returns a new refresh token.
func GenerateRefreshToken() (string, error) { return generateToken(refreshTokenPrefix) }
func generateToken(prefix string) (string, error) {
raw := make([]byte, tokenEntropyBytes)
if _, err := rand.Read(raw); err != nil {
return "", fmt.Errorf("generate token: %w", err)
}
// URL-safe and unpadded: tokens travel in query strings as well as in
// the Authorization header.
return prefix + base64.RawURLEncoding.EncodeToString(raw), nil
}
// HashToken returns the stored form of a token: lowercase hex SHA-256.
//
// The database holds hashes rather than tokens so that a dump cannot be
// replayed as a set of live sessions. SHA-256 with no salt or stretching is
// the right choice here, unlike for passwords: the input is 256 bits of
// uniform randomness, so there is no dictionary to try, and the hash is on
// the path of every authenticated request.
func HashToken(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
// GenerateDeviceID returns a random device ID for a login that did not name
// one.
func GenerateDeviceID() (string, error) {
raw := make([]byte, deviceIDLength)
if _, err := rand.Read(raw); err != nil {
return "", fmt.Errorf("generate device ID: %w", err)
}
out := make([]byte, deviceIDLength)
for i, b := range raw {
// The alphabet has 26 letters and a byte has 256 values, so the
// modulo is very slightly biased towards the first four letters.
// For a name whose only job is to be unique among a user's handful
// of devices, that is not worth a rejection loop.
out[i] = deviceIDAlphabet[int(b)%len(deviceIDAlphabet)]
}
return string(out), nil
}
// MaxDeviceIDLength caps a client-supplied device ID. The spec sets no
// limit, but the column is a primary key and an unbounded one invites abuse.
const MaxDeviceIDLength = 255
// ValidateDeviceID checks a client-supplied device ID. Device IDs are opaque
// strings, so the only rules are that it is non-empty, short enough, and
// free of control characters that would mangle a log line.
func ValidateDeviceID(deviceID string) error {
if deviceID == "" {
return fmt.Errorf("%w: device_id must not be empty", ErrInvalidDeviceID)
}
if len(deviceID) > MaxDeviceIDLength {
return fmt.Errorf("%w: device_id must be at most %d bytes", ErrInvalidDeviceID, MaxDeviceIDLength)
}
for _, r := range deviceID {
if r < 0x20 || r == 0x7f {
return fmt.Errorf("%w: device_id must not contain control characters", ErrInvalidDeviceID)
}
}
return nil
}