Files
Warp/server/internal/federation/gate.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

154 lines
4.7 KiB
Go

// Package federation is the Server-Server protocol, with no knowledge of
// rooms: the gate and the allow/deny policy, X-Matrix request signing,
// server discovery, the signed HTTP client and the key ring.
//
// Every federation route is registered through Gate.Protect, so flipping
// federation.enabled through the admin API takes effect on the next request
// without re-registering routes or restarting the process. What the switch
// also has to start and stop — the outbound queue — is the federationapi
// package's Module; see docs/federation.md.
package federation
import (
"maps"
"net/http"
"slices"
"strings"
"sync"
"github.com/dariuszjaniak/warp/server/internal/httputil"
)
// Gate reports whether federation is currently live. The callback reads the
// settings service, so the answer tracks the runtime switch.
type Gate struct {
enabled func() bool
policy *Policy
}
// NewGate builds a gate. A nil callback means permanently disabled, which
// is the safe default for a half-wired server.
func NewGate(enabled func() bool, policy *Policy) *Gate {
if enabled == nil {
enabled = func() bool { return false }
}
if policy == nil {
policy = NewPolicy(nil, nil)
}
return &Gate{enabled: enabled, policy: policy}
}
// Enabled reports the live state of the switch.
func (g *Gate) Enabled() bool { return g.enabled() }
// Policy returns the allow/deny list filter.
func (g *Gate) Policy() *Policy { return g.policy }
// Protect wraps a federation handler so that it answers M_UNRECOGNIZED
// while federation is off. The spec's answer for an endpoint a server does
// not implement is a 404, and from the outside a federation-disabled Warp
// is exactly that: a server without a federation API.
func (g *Gate) Protect(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !g.enabled() {
httputil.WriteError(w, r, httputil.Unrecognized())
return
}
h.ServeHTTP(w, r)
})
}
// ProtectFunc is Protect for an error-returning handler.
func (g *Gate) ProtectFunc(h httputil.Handler) http.Handler {
return g.Protect(httputil.Wrap(h))
}
// RejectClientRequest is the error a Client-Server endpoint returns when it
// would need federation to answer: joining a remote room, inviting a remote
// user, querying a remote directory. The message is deliberately explicit —
// "M_FORBIDDEN" alone sends operators hunting through power levels.
func RejectClientRequest(action string) error {
return httputil.Forbidden("Federation is disabled on this server; %s is not possible", action)
}
// Policy filters remote servers by name. An empty allowlist means "any
// server not on the denylist"; a non-empty one means "only these".
type Policy struct {
mu sync.RWMutex
allowlist map[string]struct{}
denylist map[string]struct{}
}
// NewPolicy builds a policy from config lists.
func NewPolicy(allowlist, denylist []string) *Policy {
p := &Policy{}
p.Replace(allowlist, denylist)
return p
}
// Replace swaps both lists atomically; the admin API edits them at runtime.
func (p *Policy) Replace(allowlist, denylist []string) {
allow := toSet(allowlist)
deny := toSet(denylist)
p.mu.Lock()
defer p.mu.Unlock()
p.allowlist, p.denylist = allow, deny
}
// Allowed reports whether traffic to or from serverName may flow. The
// denylist always wins.
func (p *Policy) Allowed(serverName string) bool {
name := normalise(serverName)
if name == "" {
return false
}
p.mu.RLock()
defer p.mu.RUnlock()
if _, denied := p.denylist[name]; denied {
return false
}
if len(p.allowlist) == 0 {
return true
}
_, allowed := p.allowlist[name]
return allowed
}
// Lists returns copies of the current allow and deny lists, for the admin
// API and the dashboard.
func (p *Policy) Lists() (allowlist, denylist []string) {
p.mu.RLock()
defer p.mu.RUnlock()
return setToSlice(p.allowlist), setToSlice(p.denylist)
}
func toSet(names []string) map[string]struct{} {
out := make(map[string]struct{}, len(names))
for _, n := range names {
if n = normalise(n); n != "" {
out[n] = struct{}{}
}
}
return out
}
// setToSlice lists a set in order, so that the admin panel shows the
// same list the same way every time.
func setToSlice(set map[string]struct{}) []string {
// Never nil: an empty list is [] in the admin API, not null.
out := slices.AppendSeq(make([]string, 0, len(set)), maps.Keys(set))
slices.Sort(out)
return out
}
// normalise lower-cases a server name. Matrix server names are
// case-sensitive in theory, but every real deployment uses a DNS name,
// and treating "Example.com" as a different server from "example.com"
// would turn a typo in the allowlist into an open door.
func normalise(serverName string) string {
return strings.ToLower(strings.TrimSpace(serverName))
}