Files
Warp/server/internal/clientapi/profile_test.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

171 lines
6.2 KiB
Go

package clientapi_test
import (
"context"
"net/http"
"strings"
"testing"
"github.com/dariuszjaniak/warp/server/internal/clientapi"
"github.com/dariuszjaniak/warp/server/internal/federation"
)
const profilePath = "/_matrix/client/v3/profile"
func TestProfileRoundTrip(t *testing.T) {
ts := newTestServer(t, nil)
acc := ts.register("alice", "superuser")
// A fresh account has neither field, and the spec distinguishes that
// from an empty one: clients fall back to the localpart.
rec := ts.get(profilePath+"/"+acc.UserID, "")
expectStatus(t, rec, http.StatusOK)
body := jsonBody(t, rec)
if _, present := body["displayname"]; present {
t.Errorf("an unset display name must be omitted, got %s", rec.Body.String())
}
rec = ts.do(request{method: http.MethodPut, path: profilePath + "/" + acc.UserID + "/displayname",
token: acc.AccessToken, body: map[string]any{"displayname": "Alice"}})
expectStatus(t, rec, http.StatusOK)
rec = ts.do(request{method: http.MethodPut, path: profilePath + "/" + acc.UserID + "/avatar_url",
token: acc.AccessToken, body: map[string]any{"avatar_url": "mxc://warp.example/abc"}})
expectStatus(t, rec, http.StatusOK)
rec = ts.get(profilePath+"/"+acc.UserID, "")
expectStatus(t, rec, http.StatusOK)
body = jsonBody(t, rec)
if body["displayname"] != "Alice" || body["avatar_url"] != "mxc://warp.example/abc" {
t.Errorf("profile = %s", rec.Body.String())
}
// The per-field endpoints return only their own field.
rec = ts.get(profilePath+"/"+acc.UserID+"/displayname", "")
expectStatus(t, rec, http.StatusOK)
body = jsonBody(t, rec)
if body["displayname"] != "Alice" {
t.Errorf("displayname = %v", body["displayname"])
}
if _, present := body["avatar_url"]; present {
t.Error("/displayname must not include the avatar")
}
rec = ts.get(profilePath+"/"+acc.UserID+"/avatar_url", "")
expectStatus(t, rec, http.StatusOK)
if jsonBody(t, rec)["avatar_url"] != "mxc://warp.example/abc" {
t.Errorf("avatar_url = %s", rec.Body.String())
}
}
// TestProfileReadsArePublic covers the rule a member list depends on: a
// client showing somebody's name has no token for them.
func TestProfileReadsArePublic(t *testing.T) {
ts := newTestServer(t, nil)
acc := ts.register("alice", "superuser")
rec := ts.do(request{method: http.MethodPut, path: profilePath + "/" + acc.UserID + "/displayname",
token: acc.AccessToken, body: map[string]any{"displayname": "my_display_name"}})
expectStatus(t, rec, http.StatusOK)
for _, path := range []string{
profilePath + "/" + acc.UserID,
profilePath + "/" + acc.UserID + "/displayname",
} {
rec := ts.get(path, "")
expectStatus(t, rec, http.StatusOK)
if name := jsonBody(t, rec)["displayname"]; name != "my_display_name" {
t.Errorf("GET %s without a token returned %v", path, name)
}
}
}
func TestProfileWritesAreOwnOnly(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "superuser")
bob := ts.register("bob", "bobspassword")
rec := ts.do(request{method: http.MethodPut, path: profilePath + "/" + alice.UserID + "/displayname",
token: bob.AccessToken, body: map[string]any{"displayname": "not bob"}})
expectError(t, rec, http.StatusForbidden, "M_FORBIDDEN")
// An admin may, which is what lets the panel clean up a profile.
ts.makeAdmin(bob)
rec = ts.do(request{method: http.MethodPut, path: profilePath + "/" + alice.UserID + "/displayname",
token: bob.AccessToken, body: map[string]any{"displayname": "set by an admin"}})
expectStatus(t, rec, http.StatusOK)
}
func TestProfileWritesRequireAToken(t *testing.T) {
ts := newTestServer(t, nil)
acc := ts.register("alice", "superuser")
rec := ts.do(request{method: http.MethodPut, path: profilePath + "/" + acc.UserID + "/displayname",
body: map[string]any{"displayname": "Alice"}})
expectError(t, rec, http.StatusUnauthorized, "M_MISSING_TOKEN")
}
func TestProfileOfUnknownUserIs404(t *testing.T) {
ts := newTestServer(t, nil)
expectError(t, ts.get(profilePath+"/@nobody:warp.example", ""),
http.StatusNotFound, "M_NOT_FOUND")
}
func TestProfileRejectsMalformedUserID(t *testing.T) {
ts := newTestServer(t, nil)
expectError(t, ts.get(profilePath+"/@no-server-name", ""),
http.StatusBadRequest, "M_INVALID_PARAM")
}
// TestProfileOfRemoteUserHonoursTheFederationSwitch is where PLAN.md
// section 3 shows up in the Client-Server API: with federation off there is
// no way to answer, and the spec's M_FORBIDDEN with a clear message is the
// honest reply.
func TestProfileOfRemoteUserHonoursTheFederationSwitch(t *testing.T) {
remote := fakeRemoteProfiles{"@bob:other.example": {"displayname": "Bob Remote"}}
ts := newTestServer(t, func(o *clientapi.Options) { o.RemoteProfiles = remote })
rec := ts.get(profilePath+"/@bob:other.example", "")
expectError(t, rec, http.StatusForbidden, "M_FORBIDDEN")
if msg, _ := jsonBody(t, rec)["error"].(string); !strings.Contains(msg, "Federation is disabled") {
t.Errorf("the message should say why, got %q", msg)
}
// With the switch on the user's own server is asked.
if err := ts.settings.SetFederationEnabled(t.Context(), true); err != nil {
t.Fatalf("SetFederationEnabled: %v", err)
}
rec = ts.get(profilePath+"/@bob:other.example", "")
if rec.Code != http.StatusOK {
t.Fatalf("remote profile status = %d (body %s)", rec.Code, rec.Body.String())
}
if name, _ := jsonBody(t, rec)["displayname"].(string); name != "Bob Remote" {
t.Errorf("remote display name = %q", name)
}
expectError(t, ts.get(profilePath+"/@nobody:other.example", ""),
http.StatusNotFound, "M_NOT_FOUND")
}
// fakeRemoteProfiles answers profile queries from a table, as the remote
// server would.
type fakeRemoteProfiles map[string]map[string]any
func (f fakeRemoteProfiles) QueryProfile(_ context.Context, _, userID, _ string) (map[string]any, error) {
profile, ok := f[userID]
if !ok {
return nil, &federation.HTTPError{Status: http.StatusNotFound, Code: "M_NOT_FOUND"}
}
return profile, nil
}
func TestProfileRejectsOverlongDisplayName(t *testing.T) {
ts := newTestServer(t, nil)
acc := ts.register("alice", "superuser")
rec := ts.do(request{method: http.MethodPut, path: profilePath + "/" + acc.UserID + "/displayname",
token: acc.AccessToken, body: map[string]any{"displayname": strings.Repeat("x", 1000)}})
expectError(t, rec, http.StatusBadRequest, "M_TOO_LARGE")
}