Files
Warp/server/internal/clientapi/register.go
T
tajniak81andClaude Opus 5.5 a94794b866
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 9: application services and admin completion
Implements PLAN.md Phase 9. internal/appservice reads registration files
(appservice.config_files), matches namespaces the way Synapse does
(anchored at the start), and delivers events to each service as
transactions read from the roomserver's event stream at a cursor kept in
appservice_state. A transaction in flight is recorded, so after a restart
it is resent under the same ID; failures back off from 2s to 5m, and a
successful ping cuts the backoff short.

In the Client-Server API an as_token acts as the service's sender or, with
?user_id=, as any existing user in its namespace. Services register and
log in their users with m.login.application_service; exclusive user and
alias namespaces are refused to everybody else with M_EXCLUSIVE. Unknown
aliases and users in a namespace are asked of the service first. The
ping endpoint reports M_URL_NOT_SET, M_BAD_STATUS, M_CONNECTION_FAILED
and M_CONNECTION_TIMEOUT. Services' own requests, and their users' when
rate_limited is false, skip the rate limiter.

Users can change their password (POST /account/password) and deactivate
their account (POST /account/deactivate), both behind the password.
Deactivation revokes tokens, deletes devices, optionally erases the
profile and leaves every room through a new userapi.AccountObserver.

The admin API is complete: user detail, the admin flag, deactivation and
reactivation, password resets, devices, media quotas
(media.max_user_storage_bytes plus per-user overrides), registration
tokens with use limits and expiry (registration.require_token), server
notices (internal/servernotices, server_notices.*), an editor for the
federation allow/deny lists persisted in server_settings, a delivery view
of the application services, and an audit log of every change.

Migration 0011 adds the registration token, server notice room, media
quota, audit log and appservice cursor tables. Policy lists are now
returned sorted. The Complement entrypoint loads the registrations
Complement mounts in /complement/appservice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 12:58:28 +02:00

370 lines
12 KiB
Go

package clientapi
import (
"crypto/rand"
"errors"
"net/http"
"github.com/dariuszjaniak/warp/server/internal/httputil"
"github.com/dariuszjaniak/warp/server/internal/userapi"
)
// registerRequest is the body of POST /register.
type registerRequest struct {
// Type is m.login.application_service for an application service
// registering one of its users, and otherwise absent.
Type string `json:"type"`
Username string `json:"username"`
Password string `json:"password"`
DeviceID string `json:"device_id"`
InitialDeviceDisplayName string `json:"initial_device_display_name"`
// InhibitLogin asks for the account without a session, for a client
// registering on someone else's behalf.
InhibitLogin bool `json:"inhibit_login"`
RefreshToken bool `json:"refresh_token"`
Auth *uiaRequest `json:"auth"`
}
// registerResponse is the body of a successful POST /register.
type registerResponse struct {
UserID string `json:"user_id"`
// The session fields are absent when inhibit_login was set.
AccessToken string `json:"access_token,omitempty"`
DeviceID string `json:"device_id,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
ExpiresInMS int64 `json:"expires_in_ms,omitempty"`
// HomeServer is deprecated and still read by older clients, which
// treat its absence as a malformed response.
HomeServer string `json:"home_server,omitempty"`
}
// handleRegister implements POST /_matrix/client/v3/register.
//
// The order of the checks matters and is not the obvious one. The spec has
// the registration flow start with a 401 listing the flows, so an empty
// body must get the challenge rather than a complaint about the missing
// password — but a username that is unusable or already taken has to be
// rejected *before* the challenge, because a client that has to complete a
// flow only to be told the name was taken cannot retry without starting
// over. Complement checks both halves of that.
func (c *ClientAPI) handleRegister(w http.ResponseWriter, r *http.Request) error {
var req registerRequest
if err := httputil.DecodeJSON(w, r, &req); err != nil {
return err
}
// Guest registration needs the room-level restrictions that come with
// the roomserver, so it is refused rather than half-implemented.
if kind := r.URL.Query().Get("kind"); kind != "" && kind != "user" {
if kind == "guest" {
return httputil.Forbidden("Guest access is not supported by this server")
}
return httputil.InvalidParam("Unknown registration kind %q", kind)
}
// An application service registering one of its users is not a
// sign-up: it needs neither the registration switch nor the flow.
if req.Type == loginAppService || (req.Auth != nil && req.Auth.Type == loginAppService) {
return c.registerAppServiceUser(w, r, req)
}
if !c.settings.RegistrationEnabled() {
return httputil.Forbidden("Registration is disabled on this server")
}
localpart := userapi.NormaliseLocalpart(req.Username)
if localpart != "" {
if err := userapi.ValidateLocalpart(localpart, c.serverName); err != nil {
return httputil.InvalidUsername("%s", err.Error())
}
taken, err := c.users.AccountExists(r.Context(), localpart)
if err != nil {
return err
}
if taken {
return httputil.UserInUse()
}
if err := c.checkExclusiveUser(c.users.UserID(localpart), ""); err != nil {
return err
}
}
flows := c.registrationFlows()
sessionID, done, err := c.beginOrAdvanceUIA(w, flows, req.Auth,
func(stage string, auth *uiaRequest) (*httputil.MatrixError, error) {
return c.registrationStage(r, stage, auth)
})
if err != nil || !done {
return err
}
// Only now that the client has authenticated is the rest of the body
// worth validating.
if req.Password == "" {
return httputil.MissingParam("A password is required to register an account")
}
if len(req.Password) > userapi.MaxPasswordLength {
return httputil.NewError(http.StatusBadRequest, httputil.ErrCodeWeakPassword,
"Password must be at most %d bytes", userapi.MaxPasswordLength)
}
if req.DeviceID != "" {
if err := userapi.ValidateDeviceID(req.DeviceID); err != nil {
return httputil.InvalidParam("%s", err.Error())
}
}
if localpart == "" {
// The spec lets a client leave the name to the server.
if localpart, err = generateLocalpart(); err != nil {
return err
}
}
// The token is spent now that an account is about to exist, not when
// the stage was passed: a sign-up abandoned halfway costs no use. A
// token that ran out in between is refused here.
release := func() {}
if c.regTokens.Required() {
var token string
if session := c.uia.get(sessionID); session != nil {
token = session.registrationToken
}
release, err = c.regTokens.Spend(r.Context(), token)
switch {
case errors.Is(err, userapi.ErrNoSuchRegistrationToken):
c.uia.remove(sessionID)
return httputil.Forbidden("The registration token is no longer valid")
case err != nil:
return err
}
}
if _, err := c.users.CreateAccount(r.Context(), userapi.NewAccountRequest{
Localpart: localpart,
Password: req.Password,
}); err != nil {
release()
switch {
case errors.Is(err, userapi.ErrUserExists):
// Lost the race against another registration of the same name
// between the check above and the insert.
return httputil.UserInUse()
case errors.Is(err, userapi.ErrInvalidLocalpart):
return httputil.InvalidUsername("%s", err.Error())
default:
return err
}
}
// The flow has been acted on; a replay of the same request must not
// create a second account.
c.uia.remove(sessionID)
resp := registerResponse{
UserID: c.users.UserID(localpart),
HomeServer: c.serverName,
}
if req.InhibitLogin {
httputil.WriteJSON(w, http.StatusOK, resp)
return nil
}
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.AccessToken = session.AccessToken
resp.DeviceID = session.DeviceID
resp.RefreshToken = session.RefreshToken
resp.ExpiresInMS = session.ExpiresInMS
httputil.WriteJSON(w, http.StatusOK, resp)
return nil
}
// registrationFlows is what a client has to complete to register.
//
// m.login.dummy is a stage that is satisfied by being attempted. It exists
// so that the flow is never empty: the spec's registration is always
// interactive, and a server with no real requirements still has to offer
// something for the client to complete.
func (c *ClientAPI) registrationFlows() []uiaFlow {
if c.regTokens.Required() {
return []uiaFlow{{Stages: []string{stageRegistrationToken, stageDummy}}}
}
return []uiaFlow{{Stages: []string{stageDummy}}}
}
// registrationStage checks one stage of the registration flow.
func (c *ClientAPI) registrationStage(r *http.Request, stage string, auth *uiaRequest) (*httputil.MatrixError, error) {
switch stage {
case stageDummy:
return nil, nil
case stageRegistrationToken:
if auth.Token == "" {
return httputil.MissingParam("A registration token is required"), nil
}
valid, err := c.regTokens.Valid(r.Context(), auth.Token)
if err != nil {
return nil, err
}
if !valid {
return httputil.Forbidden("Invalid registration token"), nil
}
c.uia.setRegistrationToken(auth.Session, auth.Token)
return nil, nil
default:
// beginOrAdvanceUIA only calls this for stages it offered, so
// reaching here means the flow list and this switch disagree.
return nil, httputil.InternalError()
}
}
// handleRegisterAvailable implements GET /register/available, the live check
// a client runs while the user is typing a name.
func (c *ClientAPI) handleRegisterAvailable(w http.ResponseWriter, r *http.Request) error {
username := r.URL.Query().Get("username")
if username == "" {
return httputil.MissingParam("The username query parameter is required")
}
localpart := userapi.NormaliseLocalpart(username)
if err := userapi.ValidateLocalpart(localpart, c.serverName); err != nil {
return httputil.InvalidUsername("%s", err.Error())
}
taken, err := c.users.AccountExists(r.Context(), localpart)
if err != nil {
return err
}
if taken {
return httputil.UserInUse()
}
if err := c.checkExclusiveUser(c.users.UserID(localpart), ""); err != nil {
return err
}
httputil.WriteJSON(w, http.StatusOK, map[string]bool{"available": true})
return nil
}
// handleRegistrationTokenValidity implements
// GET /_matrix/client/v1/register/m.login.registration_token/validity, which
// lets a client tell the user their token is wrong before they fill in the
// rest of the form.
func (c *ClientAPI) handleRegistrationTokenValidity(w http.ResponseWriter, r *http.Request) error {
token := r.URL.Query().Get("token")
if token == "" {
return httputil.MissingParam("The token query parameter is required")
}
valid, err := c.regTokens.Valid(r.Context(), token)
if err != nil {
return err
}
httputil.WriteJSON(w, http.StatusOK, map[string]bool{"valid": valid})
return nil
}
// registerAppServiceUser registers a user for the application service
// whose token the request carries.
//
// The user has to be in the service's user namespace. There is no
// password: an application service's users are only ever used through
// the service, which needs none, or through an m.login.application_service
// login, which needs the service's token rather than a password.
func (c *ClientAPI) registerAppServiceUser(w http.ResponseWriter, r *http.Request, req registerRequest) error {
token := accessTokenFrom(r)
if token == "" {
return httputil.MissingToken()
}
svc := c.appservices.Registry().ByToken(token)
if svc == nil {
return httputil.UnknownToken(false)
}
if req.Username == "" {
return httputil.MissingParam("An application service has to name the user it registers")
}
localpart := userapi.NormaliseLocalpart(req.Username)
if err := userapi.ValidateLocalpart(localpart, c.serverName); err != nil {
return httputil.InvalidUsername("%s", err.Error())
}
userID := c.users.UserID(localpart)
if !svc.OwnsUser(userID) {
return httputil.Exclusive("%s is not in the namespace of application service %s", userID, svc.ID)
}
if req.DeviceID != "" {
if err := userapi.ValidateDeviceID(req.DeviceID); err != nil {
return httputil.InvalidParam("%s", err.Error())
}
}
_, err := c.users.CreateAccount(r.Context(), userapi.NewAccountRequest{Localpart: localpart})
switch {
case errors.Is(err, userapi.ErrUserExists):
return httputil.UserInUse()
case errors.Is(err, userapi.ErrInvalidLocalpart):
return httputil.InvalidUsername("%s", err.Error())
case err != nil:
return err
}
resp := registerResponse{UserID: userID, HomeServer: c.serverName}
if req.InhibitLogin {
httputil.WriteJSON(w, http.StatusOK, resp)
return nil
}
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.AccessToken = session.AccessToken
resp.DeviceID = session.DeviceID
resp.RefreshToken = session.RefreshToken
resp.ExpiresInMS = session.ExpiresInMS
httputil.WriteJSON(w, http.StatusOK, resp)
return nil
}
// generatedLocalpartAlphabet is the character set for a server-chosen user
// name: lowercase letters and digits, which are valid everywhere in a
// localpart and unambiguous when read out.
const generatedLocalpartAlphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
// generatedLocalpartLength gives roughly 62 bits of entropy, enough that a
// server-generated name will not collide with an existing one in practice.
const generatedLocalpartLength = 12
// generateLocalpart invents a user name for a registration that did not ask
// for one.
func generateLocalpart() (string, error) {
raw := make([]byte, generatedLocalpartLength)
if _, err := rand.Read(raw); err != nil {
return "", err
}
out := make([]byte, generatedLocalpartLength)
for i, b := range raw {
out[i] = generatedLocalpartAlphabet[int(b)%len(generatedLocalpartAlphabet)]
}
return string(out), nil
}