diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 45accd171..84671ed58 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -225,7 +225,16 @@ type Router struct { // the message it is, and the batch's single turn is the only dispatch. // NewRouter wires the package default, so a production router batches; // nil disables coalescing (test setups). - Batches *TextBatchAggregator + Batches *TextBatchAggregator + // SlashAccess gates slash commands by sender role. Nil leaves every + // command available, which is the pre-policy behaviour; a composition + // that configures an allowlist sets it so an admin-only command cannot + // run for a sender the policy does not name (see slash_access.go). + SlashAccess *SlashAccessPolicy + // SlashDenials records each refused slash command for audit. Optional: + // nil still refuses and still writes the refusal to Log, it only means + // the deployment keeps no durable record of it. + SlashDenials SlashDenialRecorder sessionTracker *sessionTracker gatewayName string // titlingMu guards titling, the set of sessions with a title proposal @@ -352,6 +361,13 @@ func (r *Router) route(ctx context.Context, in Inbound) (string, error) { text := strings.TrimSpace(in.Message.Text) cmd, _ := parseCmd(text, r.gatewayName) + // The command gate runs before any dispatch, so a refused command + // executes none of its handler -- not even the part that would read the + // argument or reach the model. + if reply, refused := r.checkSlashAccess(ctx, in, cmd); refused { + return reply, nil + } + if reply, handled, err := r.dispatchLocal(ctx, in.Message, r.sessionPlatform(in), text, cmd); handled { return reply, err } diff --git a/internal/gateway/slash_access.go b/internal/gateway/slash_access.go new file mode 100644 index 000000000..08da4369d --- /dev/null +++ b/internal/gateway/slash_access.go @@ -0,0 +1,165 @@ +package gateway + +import ( + "context" + "fmt" + "slices" + "strings" +) + +// SlashRole is a chat sender's standing for slash-command access. +type SlashRole string + +const ( + // SlashRoleAdmin may run every slash command. + SlashRoleAdmin SlashRole = "admin" + // SlashRoleUser is a known non-admin sender: it may run the ordinary + // commands and any admin command delegated to it. + SlashRoleUser SlashRole = "user" + // SlashRoleUnknown is a sender no list names. It may run nothing. + SlashRoleUnknown SlashRole = "unknown" +) + +// SlashDecision is the outcome of one slash-access check. +type SlashDecision struct { + Allowed bool + Role SlashRole + // Reason is empty when Allowed, else the refusal cause: "unknown + // sender" or "not permitted". + Reason string +} + +// SlashDenial is one refused slash command. +type SlashDenial struct { + Sender string + Command string + Role SlashRole + Reason string +} + +// SlashDenialRecorder receives one record per refused slash command, so a +// deployment can persist the refusal where an operator reviews it. +type SlashDenialRecorder interface { + RecordSlashDenial(ctx context.Context, denial SlashDenial) error +} + +// slashAdminOnly names the commands that reconfigure the installation or the +// model it runs, and therefore require an admin. Every other command in +// messaging.LocalCommands is an ordinary user command; task control +// (/approve, /cancel) is deliberately ordinary here because it is scoped by +// task ownership at its own layer. +var slashAdminOnly = map[string]bool{ + "/model": true, + "/personality": true, + "/settings": true, + "/update": true, + "/restart": true, +} + +// SlashAccessPolicy decides which slash commands a chat sender may run. It +// is deny-by-default: a sender named by neither list may run nothing, so the +// zero value refuses every command. +// +// AllowAdminFrom names the senders with full access. UserAllowedCommands +// names the non-admin senders and, for each, the admin commands delegated to +// it (the ordinary commands are always available to a named user). +// +// The Router consults the policy before dispatching any local command, so a +// refusal executes none of the handler and is visible to the sender and to +// the daemon log; a wired SlashDenials sink records it for audit. The policy +// is keyed on the channel-native sender, not on an org principal: a chat +// message carries no identity the access chain can evaluate (the +// sender-to-identity mapping is archie-core-c1qx, still open), so this is the +// layer that can decide at the point the command is typed. A composition with +// no policy leaves every command available, which is the pre-policy +// behaviour. The posture follows docs/prds/orgs-and-access.md: deny by +// default, an explicit grant per principal. +type SlashAccessPolicy struct { + AllowAdminFrom []string + UserAllowedCommands map[string][]string +} + +// Role reports the sender's standing: admin when AllowAdminFrom names it, +// user when UserAllowedCommands names it, unknown otherwise. An admin entry +// wins over a user entry for the same sender. +func (p *SlashAccessPolicy) Role(sender string) SlashRole { + if p == nil { + return SlashRoleUnknown + } + if slices.Contains(p.AllowAdminFrom, sender) { + return SlashRoleAdmin + } + if _, ok := p.UserAllowedCommands[sender]; ok { + return SlashRoleUser + } + return SlashRoleUnknown +} + +// Decide reports whether sender may run command. An admin may run anything; a +// user may run the ordinary commands and any admin command delegated to it; +// an unknown sender may run nothing. +func (p *SlashAccessPolicy) Decide(sender, command string) SlashDecision { + cmd := slashCommandName(command) + role := p.Role(sender) + switch role { + case SlashRoleAdmin: + return SlashDecision{Allowed: true, Role: role} + case SlashRoleUser: + if !slashAdminOnly[cmd] || slices.Contains(p.UserAllowedCommands[sender], cmd) { + return SlashDecision{Allowed: true, Role: role} + } + return SlashDecision{Role: role, Reason: "not permitted"} + default: + return SlashDecision{Role: SlashRoleUnknown, Reason: "unknown sender"} + } +} + +// slashCommandName reduces a command token to its bare name: leading and +// trailing space, an @gateway mention, and any argument are dropped, so +// "/model@archie gpt-5" decides as "/model". +func slashCommandName(command string) string { + fields := strings.Fields(command) + if len(fields) == 0 { + return "" + } + token := fields[0] + if i := strings.IndexByte(token, '@'); i >= 0 { + token = token[:i] + } + return token +} + +// slashSender identifies the party a decision is made for. SenderID is the +// channel-native stable id; Sender is the display form, used only when a +// channel offers no stable id. +func slashSender(in Inbound) string { + if in.Message.SenderID != "" { + return in.Message.SenderID + } + return in.Message.Sender +} + +// checkSlashAccess enforces the policy on a local command, returning +// (reply, true) when it is refused. A nil policy allows. Non-command text +// never reaches the gate. +func (r *Router) checkSlashAccess(ctx context.Context, in Inbound, cmd string) (string, bool) { + if r.SlashAccess == nil || !strings.HasPrefix(cmd, "/") { + return "", false + } + sender := slashSender(in) + decision := r.SlashAccess.Decide(sender, cmd) + if decision.Allowed { + return "", false + } + denial := SlashDenial{Sender: sender, Command: cmd, Role: decision.Role, Reason: decision.Reason} + if r.SlashDenials != nil { + if err := r.SlashDenials.RecordSlashDenial(ctx, denial); err != nil && r.Log != nil { + r.Log.Error("record slash denial", "err", err) + } + } + if r.Log != nil { + r.Log.Warn("slash command refused", + "sender", sender, "command", cmd, "role", string(decision.Role), "reason", decision.Reason) + } + return fmt.Sprintf("You are not permitted to run %s.", cmd), true +} diff --git a/internal/gateway/slash_access_test.go b/internal/gateway/slash_access_test.go new file mode 100644 index 000000000..2efe9da84 --- /dev/null +++ b/internal/gateway/slash_access_test.go @@ -0,0 +1,178 @@ +package gateway + +import ( + "context" + "strings" + "testing" +) + +// recordingSlashDenials is the audit sink a refused command is reported to. +type recordingSlashDenials struct { + denials []SlashDenial +} + +func (r *recordingSlashDenials) RecordSlashDenial(_ context.Context, d SlashDenial) error { + r.denials = append(r.denials, d) + return nil +} + +func TestSlashAccessPolicyAdminMayRunAdminCommand(t *testing.T) { + policy := &SlashAccessPolicy{AllowAdminFrom: []string{"42"}} + decision := policy.Decide("42", "/model") + if !decision.Allowed || decision.Role != SlashRoleAdmin { + t.Fatalf("Decide(admin, /model) = %+v, want allowed as admin", decision) + } +} + +func TestSlashAccessPolicyUserRefusedAdminCommand(t *testing.T) { + policy := &SlashAccessPolicy{UserAllowedCommands: map[string][]string{"7": {}}} + decision := policy.Decide("7", "/restart") + if decision.Allowed { + t.Fatalf("Decide(user, /restart) = %+v, want refused", decision) + } + if decision.Role != SlashRoleUser || decision.Reason == "" { + t.Fatalf("Decide(user, /restart) = %+v, want a user refusal with a reason", decision) + } +} + +func TestSlashAccessPolicyUserMayRunUserCommand(t *testing.T) { + policy := &SlashAccessPolicy{UserAllowedCommands: map[string][]string{"7": {}}} + decision := policy.Decide("7", "/status") + if !decision.Allowed || decision.Role != SlashRoleUser { + t.Fatalf("Decide(user, /status) = %+v, want allowed as a user command", decision) + } +} + +func TestSlashAccessPolicyDelegatedAdminCommandIsAllowed(t *testing.T) { + policy := &SlashAccessPolicy{UserAllowedCommands: map[string][]string{"7": {"/restart"}}} + decision := policy.Decide("7", "/restart") + if !decision.Allowed || decision.Role != SlashRoleUser { + t.Fatalf("Decide(user, delegated /restart) = %+v, want allowed", decision) + } +} + +func TestSlashAccessPolicyUnknownSenderRefused(t *testing.T) { + policy := &SlashAccessPolicy{AllowAdminFrom: []string{"42"}} + decision := policy.Decide("99", "/status") + if decision.Allowed { + t.Fatalf("Decide(unknown, /status) = %+v, want refused", decision) + } + if decision.Role != SlashRoleUnknown || decision.Reason == "" { + t.Fatalf("Decide(unknown, /status) = %+v, want an unknown-sender refusal", decision) + } +} + +func TestSlashAccessPolicyZeroValueDeniesEverything(t *testing.T) { + var policy SlashAccessPolicy + if decision := policy.Decide("anyone", "/status"); decision.Allowed { + t.Fatalf("zero policy Decide() = %+v, want denied", decision) + } +} + +func TestSlashAccessPolicyAdminWinsOverUserGrant(t *testing.T) { + policy := &SlashAccessPolicy{ + AllowAdminFrom: []string{"7"}, + UserAllowedCommands: map[string][]string{"7": {}}, + } + if role := policy.Role("7"); role != SlashRoleAdmin { + t.Fatalf("Role(7) = %q, want admin to win over the user entry", role) + } +} + +func TestSlashAccessPolicyNormalisesGatewayMention(t *testing.T) { + policy := &SlashAccessPolicy{AllowAdminFrom: []string{"42"}} + if decision := policy.Decide("42", "/model@archie"); !decision.Allowed { + t.Fatalf("Decide(admin, /model@archie) = %+v, want allowed", decision) + } +} + +func TestRouteRefusesAdminCommandForUnknownSender(t *testing.T) { + models := &fakeModelManager{models: []string{"openai/gpt"}, activeModel: "openai/gpt"} + router := NewRouter(nil, nil, "test") + router.Models = models + router.SlashAccess = &SlashAccessPolicy{AllowAdminFrom: []string{"admin-1"}} + + reply, err := router.Route(context.Background(), inbound("chan", "/model openai/gpt")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(reply, "/model") || !strings.Contains(reply, "not permitted") { + t.Fatalf("reply = %q, want a visible refusal naming the command", reply) + } + if models.activeModel != "openai/gpt" { + t.Fatalf("activeModel = %q, the refused command executed", models.activeModel) + } +} + +func TestRouteAllowsAdminCommand(t *testing.T) { + models := &fakeModelManager{models: []string{"openai/gpt"}, activeModel: "openai/gpt"} + router := NewRouter(nil, nil, "test") + router.Models = models + router.SlashAccess = &SlashAccessPolicy{AllowAdminFrom: []string{"admin-1"}} + + in := inbound("chan", "/model openai/gpt") + in.Message.SenderID = "admin-1" + reply, err := router.Route(context.Background(), in) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(reply, "Active model set") { + t.Fatalf("reply = %q, want the admin's command to run", reply) + } +} + +func TestRouteRefusesNonAdminAndRecordsDenial(t *testing.T) { + restarts := 0 + router := NewRouter(nil, nil, "test") + router.Restart = func(context.Context) error { restarts++; return nil } + router.SlashAccess = &SlashAccessPolicy{UserAllowedCommands: map[string][]string{"user-7": {}}} + denials := &recordingSlashDenials{} + router.SlashDenials = denials + + in := inbound("chan", "/restart") + in.Message.SenderID = "user-7" + reply, err := router.Route(context.Background(), in) + if err != nil { + t.Fatal(err) + } + if restarts != 0 { + t.Fatalf("restarts = %d, the refused command executed", restarts) + } + if !strings.Contains(reply, "not permitted") { + t.Fatalf("reply = %q, want a visible refusal", reply) + } + if len(denials.denials) != 1 { + t.Fatalf("denials = %+v, want exactly one audit record", denials.denials) + } + got := denials.denials[0] + if got.Sender != "user-7" || got.Command != "/restart" || got.Role != SlashRoleUser || got.Reason == "" { + t.Fatalf("denial = %+v, want the refused sender, command, role and reason", got) + } +} + +func TestRouteRefusesUnknownSenderForUserCommand(t *testing.T) { + router := NewRouter(&fakeStore{counts: map[string]int{}}, nil, "test") + router.SlashAccess = &SlashAccessPolicy{UserAllowedCommands: map[string][]string{"user-7": {}}} + + reply, err := router.Route(context.Background(), inbound("chan", "/status")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(reply, "Queue:") { + t.Fatalf("reply = %q, the unknown sender's command executed", reply) + } + if !strings.Contains(reply, "not permitted") { + t.Fatalf("reply = %q, want a visible refusal", reply) + } +} + +func TestRouteWithoutPolicyLeavesCommandsAvailable(t *testing.T) { + router := NewRouter(&fakeStore{counts: map[string]int{}}, nil, "test") + reply, err := router.Route(context.Background(), inbound("chan", "/status")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(reply, "Queue: idle") { + t.Fatalf("reply = %q, want the command to run with no policy configured", reply) + } +}