Files
Warp/server/internal/roomserver/send.go
T
tajniak81andClaude Opus 5 c96f88e994
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 3: rooms, local only
Implements PLAN.md Phase 3: the roomserver, the room half of storage, the
Client-Server room endpoints and the admin room endpoints. A client can now
create a room, invite, join, leave, kick, ban, send messages and state,
redact, name a room with an alias and find one in the public directory.
Nothing talks to another server; every operation that would need to is
refused with a message that says so rather than a bare M_FORBIDDEN.

roomserver: one input pipeline every event goes through, whatever sent it —
validate, authorise, resolve, persist, emit. The rules are not
reimplemented here; internal/matrix is pure library code and this is what
connects it to a database and to a room's history. The Client-Server
handlers do no authorisation of their own, deliberately: whether Alice may
kick Bob is a question about the room's power levels, and the one place
that is answered correctly is the authorisation rules inside the pipeline.

A mutex per room serialises writers. Two events racing into one room would
each read the same forward extremities, both become one, and fork the room
for no reason — which would then need state resolution to put back
together. State resolution is wired in anyway for the multi-extremity
case. It is unreachable from outside in this phase, and the alternative is
a pipeline that authorises against one arbitrary branch of a fork without
saying so.

Room versions 3 to 12 all work and are each tested end to end. Version 12
earns that coverage: its room ID is the create event's own ID, its create
event carries no room_id, and the create event is excluded from every other
event's auth_events — so the state auth.Check is given is the event's
auth_events plus the create event, which that version identifies by room ID
rather than citing.

createRoom sends the spec's events in the spec's order, each authorised
against what the ones before it produced. A failure part-way leaves an
incomplete room, which is the lesser evil: the alternative is holding every
event of a new room in memory and writing them in one transaction, making
the pipeline that authorises them a special case. The one failure a second
client can cause at any time, an alias clash, takes the room row back out.

Redactions stay two decisions, as the spec keeps them. The rules let almost
any redaction into the room; whether it applies to its target is a separate
test, run inside the same transaction as the redaction itself so that a
client holding an event ID can always read the stripped event.

storage: events keyed by event ID rather than by a surrogate, since an
event ID appears in prev_events, auth_events, state snapshots and client
requests alike. Stream ordering comes from a counter row bumped inside the
write transaction, because a PostgreSQL sequence is explicitly not
transactional and a rolled-back write would leave a hole in the stream that
/sync would have to be taught to skip. State snapshots are stored per event
and deduplicated by content hash, so the table grows with state changes
rather than with traffic — and that is what makes "the state after a
forward extremity" answerable at all. The room's listing columns are
denormalised onto its row because the public directory orders every
published room by member count and pages the result, which cannot be done
by reading each room's state in turn.

Federation-disabled behaviour from PLAN.md section 3 is enforced here.
Restricted joins are the exception that works: the rule needs a signature
from the authorising user's server verified, and while federation is off
that server is always this one.

adminapi: room list and detail, purge, force-leave, and room and event
counters on the dashboard. clientapi gains its own rate-limit buckets for
createRoom and for joining, both of which write events rather than read
them.

Tested against the real event core and a real database rather than fakes:
what is under test is whether an event this server signs is one the
authorisation rules accept, and a fake of either would only prove that the
pipeline calls what the fake expects. The storage tests run against both
SQL drivers. docs/rooms.md describes the pipeline, the storage decisions
and the known gaps — chief among them that history visibility is
room-level rather than per-event, and that /sync still reports no rooms,
both of which belong with the event stream in Phase 4.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-16 10:34:57 +02:00

232 lines
7.8 KiB
Go

package roomserver
import (
"context"
"encoding/json"
"fmt"
"github.com/dariuszjaniak/warp/server/internal/matrix/auth"
"github.com/dariuszjaniak/warp/server/internal/matrix/event"
"github.com/dariuszjaniak/warp/server/internal/matrix/roomversion"
"github.com/dariuszjaniak/warp/server/internal/storage"
)
// SendEventRequest sends one event into a room on a user's behalf.
type SendEventRequest struct {
RoomID string
// Sender is the full user ID sending the event.
Sender string
Type string
// StateKey makes this a state event when it is non-nil.
StateKey *string
Content json.RawMessage
// Transaction, when set, makes the send idempotent: a retry with the
// same transaction ID returns the event the first attempt created.
// State events have no transaction ID in the Client-Server API, which
// is why this is optional.
Transaction *storage.TransactionRef
}
// SendEvent sends a message or state event into a room.
//
// It does no authorisation of its own, deliberately: whether a user may
// send a given type into a given room is a question about the room's power
// levels and membership, and the one place that is answered correctly is
// the authorisation rules inside the pipeline. A handler-level check here
// would be a second, worse copy of them.
//
// The one thing it does refuse up front is m.room.create. The rules would
// refuse it too — a second create event in a room is rejected — but the
// error a client gets for "you cannot re-create a room" is more use than
// the one for "rule 2 said no".
func (r *API) SendEvent(ctx context.Context, req SendEventRequest) (string, error) {
if req.Type == event.TypeCreate {
return "", fmt.Errorf("%w: a room's m.room.create event is sent by createRoom and cannot be replaced",
ErrForbidden)
}
if req.Type == event.TypeMember {
// A membership change through the state endpoint is legitimate and
// the rules handle it, but the membership value still has to be one
// the rules know: content that is not a membership at all would
// otherwise become an event nobody can interpret.
if err := checkMembershipContent(req.Content); err != nil {
return "", err
}
}
sent, err := r.send(ctx, sendRequest{
RoomID: req.RoomID,
Type: req.Type,
StateKey: req.StateKey,
Sender: req.Sender,
Content: req.Content,
Transaction: req.Transaction,
})
if err != nil {
return "", err
}
return sent.EventID(), nil
}
// checkMembershipContent rejects an m.room.member content whose membership
// is missing or not one of the five the spec defines.
func checkMembershipContent(content json.RawMessage) error {
var body struct {
Membership string `json:"membership"`
}
if err := json.Unmarshal(content, &body); err != nil {
return fmt.Errorf("%w: an m.room.member content needs a membership", ErrInvalidContent)
}
switch body.Membership {
case event.MembershipJoin, event.MembershipLeave, event.MembershipInvite,
event.MembershipBan, event.MembershipKnock:
return nil
case "":
return fmt.Errorf("%w: an m.room.member content needs a membership", ErrInvalidContent)
default:
return fmt.Errorf("%w: %q is not a membership", ErrInvalidContent, body.Membership)
}
}
// RedactRequest asks to redact an event.
type RedactRequest struct {
RoomID string
// Sender is the full user ID sending the redaction.
Sender string
// EventID is the event to redact.
EventID string
Reason string
Transaction *storage.TransactionRef
}
// Redact redacts an event.
//
// This is two decisions, not one, and the spec keeps them apart. The first
// is whether the m.room.redaction event may be in the room at all, which
// the authorisation rules answer and which is permissive: almost any member
// may send one, because a server receiving a redaction for an event it has
// never seen still has to be able to store it. The second is whether the
// redaction takes effect on its target, which needs both events in hand and
// is auth.ShouldApplyRedaction's job — either the sender has the redact
// level, or the redaction comes from the same server as the event, because
// a server may always take back its own users' events.
//
// Phase 3 only ever has both events, since every event in a room is local.
// A redaction whose target has not arrived is a federation case.
func (r *API) Redact(ctx context.Context, req RedactRequest) (string, error) {
// The room is read first so that a room this server does not have is a
// 404 before anything is built, and so that a room whose version is no
// longer supported says so.
room, err := r.store.Room(ctx, req.RoomID)
if err != nil {
return "", err
}
if _, err := r.rules(room); err != nil {
return "", err
}
// The target is read before the redaction is built so that redacting
// an event that does not exist is a 404 rather than an event in the
// room that refers to nothing.
if _, err := r.store.Event(ctx, req.RoomID, req.EventID); err != nil {
return "", err
}
content := map[string]any{}
if req.Reason != "" {
content["reason"] = req.Reason
}
redaction, err := r.send(ctx, sendRequest{
RoomID: req.RoomID,
Type: event.TypeRedaction,
Sender: req.Sender,
Content: mustMarshal(content),
Redacts: req.EventID,
Transaction: req.Transaction,
})
if err != nil {
return "", err
}
return redaction.EventID(), nil
}
// prepareRedaction decides whether a redaction takes effect and, if it
// does, puts the target's redacted form into the write.
//
// It runs inside persist, within the same transaction as the redaction
// event itself, so that a client which gets an event ID back can always
// read the stripped event.
func (r *API) prepareRedaction(ctx context.Context, write *storage.RoomWrite, req persistRequest) error {
storedTarget, err := r.store.Event(ctx, req.Room.ID, req.RedactsEventID)
if isNotFound(err) {
// Over federation a redaction can arrive before its target, and the
// right answer is to keep it and apply it later. Locally the target
// was read before the redaction was built, so this means it was
// purged in between.
r.log.Info("redaction target is not here",
"room_id", req.Room.ID, "redacts", req.RedactsEventID)
return nil
} else if err != nil {
return err
}
if storedTarget.RedactedBy != "" {
// Already redacted. The event stays as it is: a second redaction
// has nothing left to remove.
return nil
}
target, err := parseEvent(storedTarget, req.Rules)
if err != nil {
return err
}
applies, err := r.redactionApplies(ctx, req.Room, req.Rules, req.Event, target)
if err != nil {
return err
}
if !applies {
// The event is in the room and has no effect, which is what the
// spec asks for. It is worth a log line: from the client's side a
// redaction that returns an event ID and changes nothing looks
// exactly like one that worked.
r.log.Info("accepted a redaction that does not apply",
"room_id", req.Room.ID, "event_id", req.Event.EventID(),
"redacts", req.RedactsEventID, "sender", req.Event.Sender())
return nil
}
redacted, err := target.Redact()
if err != nil {
return fmt.Errorf("redacting %s: %w", req.RedactsEventID, err)
}
write.Redacts = req.RedactsEventID
write.RedactedJSON = redacted.JSON()
return nil
}
// redactionApplies runs the spec's "should this redaction be applied" test.
func (r *API) redactionApplies(ctx context.Context, room storage.Room, rules roomversion.Rules, redaction, target *event.Event) (bool, error) {
st, err := r.currentState(ctx, room, rules)
if err != nil {
return false, err
}
create := st.Create()
if create == nil {
return false, fmt.Errorf("%w: %s has no create event in its state", ErrRejected, room.ID)
}
powerLevels, err := auth.ResolvePowerLevels(st.PowerLevels(), create, rules)
if err != nil {
return false, fmt.Errorf("%w: %v", ErrRejected, err)
}
return auth.ShouldApplyRedaction(redaction, target, powerLevels), nil
}