Files
Warp/server/internal/roomserver/acl.go
T
tajniak81andClaude Opus 5.5 6aaf554336
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 5: federation
Implements PLAN.md Phase 5: the Server-Server API. Warp joins rooms on
other servers and lets their users join its rooms, invites across servers
with the invitee's server countersigning, rejects remote invites (locally
if the inviter is unreachable), and exchanges events, typing, receipts and
to-device messages with other homeservers — all behind the runtime switch,
which now starts and stops real outbound traffic.

The protocol lives in internal/federation with no knowledge of rooms:
X-Matrix signing (fuzzed parser), the spec's discovery algorithm keeping
the dial address and the TLS name apart, a signed client that refuses
every request while the switch is off or the policy denies the
destination, and a key ring that caches other servers' keys for at most a
week, with optional notaries.

The roomserver takes events from elsewhere through the spec's intake:
signatures and hashes (a hash mismatch keeps the redacted form), the rules
against the event's own auth events, against the state before it — with
/get_missing_events for small gaps and /state_ids for wide ones — and
against the current state, where a failure is a soft failure. Events held
without their state are outliers: a column on roomserver_events, because
the current state of a room joined over federation is almost all
outliers, and excluded from every timeline query. Forks are resolved at
the room's head. Membership across servers is make_join/send_join,
make_leave/send_leave and countersigned invites, in both directions;
m.room.server_acl is enforced on everything another server sends.
History before a remote join is backfilled when /messages pages past it,
stored at negative stream positions.

internal/federationapi is the running component: the inbound endpoints,
and an outbound queue that persists what it owes each destination, sends
it in transactions of 50 PDUs and 100 EDUs, backs off from ten seconds to
six hours, survives restarts, and drops events persisted while federation
is off rather than delivering a backlog in one burst. Its Module is what
the switch starts and stops.

Also: a TLS listener for port 8448, trusted key servers, key validity and
an outbound CA bundle in the config; per-destination health and backoff
reset in the admin API; remote profiles, aliases and directories in the
Client-Server API; a Complement federation profile. See
docs/federation.md, including its known gaps (no partial-state joins, no
key rotation).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 17:14:20 +02:00

139 lines
4.2 KiB
Go

package roomserver
import (
"context"
"encoding/json"
"fmt"
"net"
"regexp"
"strings"
"sync"
"github.com/dariuszjaniak/warp/server/internal/federation"
)
// TypeServerACL is the state event that says which servers may take part
// in a room.
const TypeServerACL = "m.room.server_acl"
// Server ACLs.
//
// A room can ban whole servers. The ACL is ordinary room state, and what
// it does is decided by every server in the room for itself: requests and
// events from a server the ACL denies are refused, as if that server were
// not there. It is the one defence a room has against a server that
// creates users faster than moderators can ban them.
//
// It applies to what a server *sends*: its transactions' PDUs, its EDUs,
// its joins and leaves, and its reads of the room's history. It does not
// rewrite the past — events already in the room stay — and it does not
// apply to the server enforcing it.
// aclContent is the content of an m.room.server_acl event.
type aclContent struct {
Allow []string `json:"allow"`
Deny []string `json:"deny"`
AllowIPLiterals *bool `json:"allow_ip_literals"`
}
// globCache keeps compiled ACL globs: the same handful of patterns are
// matched against every request a busy room sees.
var globCache sync.Map // pattern -> *regexp.Regexp
// globMatch matches a server name against an ACL glob, where '*' is any
// run of characters and '?' is any one. The match ignores case, as every
// implementation does: a DNS name is not case-sensitive, and an ACL that
// "example.com" got around by writing "EXAMPLE.com" would be no ACL.
func globMatch(pattern, name string) bool {
if cached, ok := globCache.Load(pattern); ok {
return cached.(*regexp.Regexp).MatchString(name)
}
var b strings.Builder
b.WriteString(`(?i)^`)
for _, r := range pattern {
switch r {
case '*':
b.WriteString(`.*`)
case '?':
b.WriteString(`.`)
default:
b.WriteString(regexp.QuoteMeta(string(r)))
}
}
b.WriteString(`$`)
re, err := regexp.Compile(b.String())
if err != nil {
return false
}
globCache.Store(pattern, re)
return re.MatchString(name)
}
// aclAllows applies one ACL to a server name. The port is not part of
// what an ACL matches.
func aclAllows(acl aclContent, serverName string) bool {
host := serverName
if parsed, err := federation.ParseServerName(serverName); err == nil {
host = parsed.Host
if parsed.IsIP && acl.AllowIPLiterals != nil && !*acl.AllowIPLiterals {
return false
}
} else if h, _, err := net.SplitHostPort(serverName); err == nil {
host = h
}
for _, deny := range acl.Deny {
if globMatch(deny, host) {
return false
}
}
for _, allow := range acl.Allow {
if globMatch(allow, host) {
return true
}
}
// An ACL with an empty allow list allows nobody. That is what the
// spec says, and the room's own server is protected from it only
// because a server never applies a room's ACL to itself.
return false
}
// ServerAllowed reports whether a room's ACL lets a server take part. A
// room with no ACL allows everybody, and this server is always allowed.
func (r *API) ServerAllowed(ctx context.Context, roomID, serverName string) (bool, error) {
if serverName == r.serverName {
return true, nil
}
stored, err := r.store.CurrentStateEvent(ctx, roomID, TypeServerACL, "")
if isNotFound(err) {
return true, nil
} else if err != nil {
return false, err
}
acl, ok := parseACL(contentOf(stored))
if !ok {
// An ACL nobody can read restricts nobody; refusing everyone over
// a malformed event would let one bad state event cut a room off.
r.log.Warn("ignoring an unreadable server ACL", "room_id", roomID, "event_id", stored.EventID)
return true, nil
}
return aclAllows(acl, serverName), nil
}
// parseACL decodes an ACL's content, reporting whether it could.
func parseACL(content json.RawMessage) (aclContent, bool) {
var acl aclContent
return acl, json.Unmarshal(content, &acl) == nil
}
// requireAllowed refuses a server the room's ACL denies.
func (r *API) requireAllowed(ctx context.Context, roomID, serverName string) error {
ok, err := r.ServerAllowed(ctx, roomID, serverName)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("%w: %s is denied by the server ACL of %s", ErrForbidden, serverName, roomID)
}
return nil
}