Phase 1: accounts and sessions
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>
This commit is contained in:
tajniak81andClaude Opus 5 committed 2026-10-15 18:18:37 +02:00
1 parent b4fb60a8ab
commit 6004bb01de
68 files changed
+9729 -66

No files matched your search

+249
View File
@@ -0,0 +1,249 @@
package clientapi
import (
"errors"
"net/http"
"github.com/dariuszjaniak/warp/server/internal/httputil"
"github.com/dariuszjaniak/warp/server/internal/userapi"
)
// Login identifier types. Third-party identifiers (email, phone) need an
// identity server, which is a non-goal for now.
const (
identifierUser = "m.id.user"
)
// loginIdentifier is the `identifier` object of a login or a password stage.
type loginIdentifier struct {
Type string `json:"type"`
User string `json:"user"`
}
// loginRequest is the body of POST /login.
type loginRequest struct {
Type string `json:"type"`
Identifier loginIdentifier `json:"identifier"`
// User is the deprecated identifier form, still sent by older clients
// and by some test harnesses.
User string `json:"user"`
Password string `json:"password"`
DeviceID string `json:"device_id"`
InitialDeviceDisplayName string `json:"initial_device_display_name"`
RefreshToken bool `json:"refresh_token"`
}
// loginFlow is one entry of GET /login.
//
// The spec defines a flow as having `stages`, but for login every flow has
// exactly one, and clients have always read a flat `type`. Both are sent:
// `type` for the clients, `stages` for a strict reading of the spec.
type loginFlow struct {
Type string `json:"type"`
Stages []string `json:"stages,omitempty"`
}
type loginFlowsResponse struct {
Flows []loginFlow `json:"flows"`
}
// loginResponse is the body of a successful login.
type loginResponse struct {
UserID string `json:"user_id"`
AccessToken string `json:"access_token"`
DeviceID string `json:"device_id"`
RefreshToken string `json:"refresh_token,omitempty"`
ExpiresInMS int64 `json:"expires_in_ms,omitempty"`
// HomeServer is deprecated but still read by older clients.
HomeServer string `json:"home_server,omitempty"`
WellKnown *wellKnownDiscovery `json:"well_known,omitempty"`
}
// wellKnownDiscovery mirrors /.well-known/matrix/client, which the spec
// allows a login response to carry so a client does not have to fetch it.
type wellKnownDiscovery struct {
Homeserver wellKnownBaseURL `json:"m.homeserver"`
}
type wellKnownBaseURL struct {
BaseURL string `json:"base_url"`
}
// handleLoginFlows implements GET /_matrix/client/v3/login.
func (c *ClientAPI) handleLoginFlows(w http.ResponseWriter, _ *http.Request) error {
httputil.WriteJSON(w, http.StatusOK, loginFlowsResponse{
Flows: []loginFlow{{Type: stagePassword, Stages: []string{stagePassword}}},
})
return nil
}
// handleLogin implements POST /_matrix/client/v3/login.
//
// Every rejection is the same M_FORBIDDEN, whether the account does not
// exist, has no password or the password is wrong, and userapi spends the
// same work on each. A login endpoint that distinguishes them is a user
// directory for anyone who asks.
func (c *ClientAPI) handleLogin(w http.ResponseWriter, r *http.Request) error {
var req loginRequest
if err := httputil.DecodeJSON(w, r, &req); err != nil {
return err
}
if req.Type != stagePassword {
return httputil.Unknown(http.StatusBadRequest, "Login type %q is not supported", req.Type)
}
identifier := req.Identifier.User
switch {
case identifier != "" && req.Identifier.Type != identifierUser:
return httputil.InvalidParam("Login identifier type %q is not supported", req.Identifier.Type)
case identifier == "":
identifier = req.User
}
if identifier == "" {
return httputil.MissingParam("A user identifier is required")
}
localpart, err := c.users.ParseLocalUserID(identifier)
switch {
case errors.Is(err, userapi.ErrForeignServer):
// Not a federation matter: an account on another server has its
// password there, and no amount of federation changes that.
return httputil.Forbidden("Cannot log in as a user of another server")
case err != nil:
return httputil.Forbidden("Invalid username or password")
}
switch err := c.users.CheckPassword(r.Context(), localpart, req.Password); {
case err == nil:
case errors.Is(err, userapi.ErrWrongPassword), errors.Is(err, userapi.ErrNoPassword):
return httputil.Forbidden("Invalid username or password")
default:
return err
}
account, err := c.users.Account(r.Context(), localpart)
if err != nil {
return err
}
if account.Deactivated {
return httputil.UserDeactivated()
}
if req.DeviceID != "" {
if err := userapi.ValidateDeviceID(req.DeviceID); err != nil {
return httputil.InvalidParam("%s", err.Error())
}
}
session, err := c.users.CreateSession(r.Context(), userapi.SessionRequest{
Localpart: localpart,
DeviceID: req.DeviceID,
DisplayName: req.InitialDeviceDisplayName,
WithRefreshToken: req.RefreshToken,
IP: c.clientIP(r),
UserAgent: r.UserAgent(),
})
if err != nil {
return err
}
resp := loginResponse{
UserID: session.UserID,
AccessToken: session.AccessToken,
DeviceID: session.DeviceID,
RefreshToken: session.RefreshToken,
ExpiresInMS: session.ExpiresInMS,
HomeServer: c.serverName,
}
if c.clientBaseURL != "" {
resp.WellKnown = &wellKnownDiscovery{
Homeserver: wellKnownBaseURL{BaseURL: c.clientBaseURL},
}
}
httputil.WriteJSON(w, http.StatusOK, resp)
return nil
}
// refreshRequest is the body of POST /refresh.
type refreshRequest struct {
RefreshToken string `json:"refresh_token"`
}
// refreshResponse is its answer.
type refreshResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresInMS int64 `json:"expires_in_ms,omitempty"`
}
// handleRefresh implements POST /_matrix/client/v3/refresh.
//
// It is unauthenticated on purpose: the refresh token *is* the credential,
// and the access token it replaces has usually already expired.
func (c *ClientAPI) handleRefresh(w http.ResponseWriter, r *http.Request) error {
var req refreshRequest
if err := httputil.DecodeJSON(w, r, &req); err != nil {
return err
}
if req.RefreshToken == "" {
return httputil.MissingParam("refresh_token is required")
}
session, err := c.users.RefreshSession(r.Context(), req.RefreshToken)
switch {
case err == nil:
case errors.Is(err, userapi.ErrNoSuchToken):
// A soft logout: the device is probably still legitimate, it just
// cannot prove it any more.
return httputil.UnknownToken(true)
case errors.Is(err, userapi.ErrAccountDeactivated):
return httputil.UserDeactivated()
default:
return err
}
httputil.WriteJSON(w, http.StatusOK, refreshResponse{
AccessToken: session.AccessToken,
RefreshToken: session.RefreshToken,
ExpiresInMS: session.ExpiresInMS,
})
return nil
}
// handleLogout implements POST /_matrix/client/v3/logout. Logging out
// deletes the device, not only the token: that is what the spec says, and it
// is what keeps a user's device list from filling up with dead entries.
func (c *ClientAPI) handleLogout(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
if err := c.users.DeleteDevices(r.Context(), auth.Localpart, []string{auth.DeviceID}); err != nil {
return err
}
httputil.WriteJSON(w, http.StatusOK, struct{}{})
return nil
}
// handleLogoutAll implements POST /_matrix/client/v3/logout/all.
func (c *ClientAPI) handleLogoutAll(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
if err := c.users.DeleteAllDevices(r.Context(), auth.Localpart); err != nil {
return err
}
httputil.WriteJSON(w, http.StatusOK, struct{}{})
return nil
}
// handleWhoami implements GET /_matrix/client/v3/account/whoami.
func (c *ClientAPI) handleWhoami(w http.ResponseWriter, _ *http.Request, auth userapi.Authenticated) error {
httputil.WriteJSON(w, http.StatusOK, map[string]any{
"user_id": auth.UserID,
"device_id": auth.DeviceID,
// Guest accounts are not implemented, so this is always false
// rather than omitted: clients branch on it.
"is_guest": false,
})
return nil
}