Skip to content

Role-based access control ​

CritterWatch ships with an auth-agnostic, ClaimsPrincipal-based RBAC layer. It governs who can view what and — more importantly — who can take state-changing actions (DLQ replay, projection rebuild, tenant ops, chaos toggles, listener pause / restart, etc.) across every monitored service.

Off-mode is the default. Single-tenant deployments and existing hosts that haven't configured RBAC keep working exactly as they did before — every authenticated caller (including anonymous in dev) can do everything the license permits. Enforced mode is a single DI call away.

How CritterWatch decides ​

CritterWatch never owns identity. The host's authentication layer (OIDC, reverse-proxy header trust, JWT bearer, Windows auth, whatever) builds a ClaimsPrincipal; CritterWatch reads it. A small interface decides what that principal is allowed to do:

csharp
public interface ICritterWatchAuthorizer
{
    Task<bool> IsAllowedAsync(
        ClaimsPrincipal principal,
        string capability,
        string? resource = null,
        CancellationToken ct = default);
}
  • capability — one of the Capabilities string constants. Identifies the thing the caller is trying to do.
  • resource — optional scope: the target service name, projection shard, tenant id, alert stream id, etc. Lets you write rules like "this on-call rotation can clear alerts on TripService but not RepairShop."

You implement this interface against whatever rule store fits your environment — LDAP groups, OIDC role claims, a static config file, a database, a custom rule engine. CritterWatch never assumes a schema.

Turning enforcement on ​

Register your authorizer alongside the rest of the CritterWatch services. The DI extension replaces the off-mode DefaultAllowAuthorizer:

csharp
builder.Services.AddCritterWatchAuthorization<MyAuthorizer>();

That single line lights up enforcement everywhere CritterWatch ships gates today — HTTP endpoints, MCP action tools, all paths annotated with [RequiresPermission]. No further wiring is needed; the off-mode shim is removed and your authorizer drives every decision.

For incremental rollout (e.g. you want to ship enforced mode but double-check denies against logs first), wrap your authorizer to log-and-allow during a soak window before flipping to log-and-deny.

Off-mode is preserved when no custom authorizer is registered.AddCritterWatchServices(...) auto-wires AddCritterWatchAuthorization() with TryAdd so the BFF's static codegen always resolves an authorizer; the resulting DefaultAllowAuthorizer returns true for every decision, which is the off-mode behaviour. Your explicit AddCritterWatchAuthorization<TAuthorizer>() replaces it.

Fail-closed on missing principal ​

If enforced mode is on and a request arrives without an authenticated principal (principal?.Identity?.IsAuthenticated != true), CritterWatch rejects the request before calling your authorizer. That short-circuit exists so a misconfigured authentication scheme can't accidentally let unauthenticated callers through against a permissive authorizer.

Off-mode (no custom authorizer registered) keeps allowing anonymous principals — that's the off-mode behaviour for single-tenant dev hosts.

What's gated, and how ​

HTTP endpoints ​

State-changing operator HTTP endpoints are annotated with the [RequiresPermission] attribute. Wolverine's HTTP codegen weaves the RBAC check into the chain ahead of the endpoint body:

csharp
public static class AlertEndpoint
{
    [RequiresPermission(Capabilities.AlertClear)]
    [WolverinePost("/api/critterwatch/alerts/{alertStreamId}/clear")]
    public static async Task<AlertClearedMessage?> ClearAlert(...)
    {
        // body runs only if the authorizer said yes
    }
}

On deny the request short-circuits with a 403 Forbidden ProblemDetails response. The denied capability is exposed in the capability extension field so clients can map the response back to a specific missing grant:

json
{
  "status": 403,
  "title": "Forbidden",
  "detail": "Caller is not authorized for capability \"alert.clear\".",
  "capability": "alert.clear"
}

No UseExceptionHandler ceremony is required on the host — the frame writes the response directly.

SignalR-routed commands ​

Operator commands invoked through the SignalR hub (the SPA's normal path for buttons like Rebuild projection, Clear alert, Add tenant) go through the same [RequiresPermission] enforcement as the matching HTTP endpoint. The handler reads the operator's ClaimsPrincipal off the SignalR connection — Wolverine 6.2+ surfaces it as SignalREnvelope.Principal (a ClaimsPrincipal? captured from HubCallerContext.User), and the RBAC middleware on the inbound relay path consumes it directly:

  • The same authorizer fires. ICritterWatchAuthorizer.IsAllowedAsync(...) receives the SignalR caller's principal, the same capability string that the matching HTTP endpoint guards, and the same resource scope. The resource is the most specific thing the command names: the service for most commands, the tenant id for the five tenant commands, and for a projection command the projection's agent URI with @{tenantId} appended when it targets one tenant (for example event-subscription://tripservice/TripSummary:All@acme-corp). The MCP tools ask about the same resources, so one grant covers both surfaces — see MCP › Per-tenant scoping.
  • A command can need more than one capability. Edit & Replay needs dlq.edit as well as dlq.replay; the authorizer is asked about both, and a refusal names the one that was missing.
  • On deny the SignalR message is dropped with an envelope mirroring the HTTP 403 ProblemDetails shape — the SPA's notification surface renders it as a toast, and the audit log records the denial.
  • No connection-bridge plumbing is needed. The captured principal rides the envelope, so the off-mode DefaultAllowAuthorizer path and the production-mode ICritterWatchAuthorizer path use the same call shape; integrators don't need their own claim-forwarding shim.
  • An embedded console enforces the same checks. Every command from the browser passes through the console before your application's handler runs it. In 1.1.0-rc.1 an embedded console skipped them (RBAC, the audit row, the acknowledgement and the license-cap refusal); upgrade to 1.1.0-rc.2 or later.

If you're wiring a custom SignalR client (a third-party admin tool, an audit bot), pass the bearer token / cookie on the SignalR connection the same way you would for the HTTP API. The hub's authentication scheme governs principal acquisition; everything downstream is identical.

MCP action tools ​

The cross-application MCP server (CritterWatch.Mcp) exposes 47 RBAC-gated state-changing tools across fourteen families:

FamilyToolsCapabilities
DLQReplay / Discard / Replay, Archive, Restore or Discard a failure group / Write a failure group's notedlq.replay, dlq.discard, dlq.archive (archive and restore), dlq.note
ProjectionPause / Restart / Rebuild / Eject / Eject a retired versionprojection.pause, projection.restart, projection.rebuild, projection.eject (both ejects)
High water detectionRestart one node's loop for one databaseprojection.restart-high-water (scoped to the service)
High water markAdvance one database's mark past a gap (skips those sequences for good)projection.advance-high-water (scoped to the service)
Scheduled messagesSchedule a projection rebuild / Cancel / Rescheduleprojection.rebuild, scheduled-message.cancel, scheduled-message.reschedule
TenantAdd / Enable / Disable / Remove / HardDeletetenant.add, tenant.enable, tenant.disable, tenant.remove, tenant.hard-delete (scoped to the tenant id)
DocumentUpdate / Delete / Undeletedocuments.write (update), documents.delete (delete and undelete)
AlertAcknowledge / Snooze / Clearalert.acknowledge, alert.snooze, alert.clear
ChaosMonkeyEnable / Disable / SetFailureRate / SetSlowHandler / SetProjectionFailureRate / SetProjectionPoison / ClearProjectionPoison / SeedDeadLetterschaos-monkey.toggle (enable/disable), chaos-monkey.configure (rate / delay / poison / seeding knobs)
ListenerPause / Restart / Drainlistener.pause, listener.restart, listener.drain
MetricsDeleteSamplesmetrics.delete
ServiceEvictservice.evict
Recurring schedulePause / Resume / Trigger nowrecurring-schedule.pause, recurring-schedule.resume, recurring-schedule.trigger
Stream compactionRun / Pause / Resume a policycompaction-policy.run (run), recurring-schedule.pause / recurring-schedule.resume (pause / resume)

There is no MCP edit-and-replay tool, so dlq.edit has no MCP side.

Sixteen read tools run the same enforcement pipeline, because each returns business data or sits beside an action: the three dead-letter reads (summarize_dead_letters / summarize_dead_letter_groups / query_dead_letters) against mcp.dlq.read, the two conversation reads (list_conversations / get_conversation) against mcp.conversations.read, the three saga reads (list_sagas / list_saga_instances / get_saga_instance) against mcp.sagas.read, the three projection tools (diagnose_projection / run_projection_stepper / get_projection_apply_source) against mcp.projection.step, query_events against mcp.events.query, query_sql against mcp.sql.query, query_documents / get_document against mcp.documents.read, and preview_high_water_advance against projection.advance-high-water, the grant of the advance it previews. Every other read tool is license-gated only (see the catalog below).

Two more MCP behaviours sit beside this gate:

  • Confirmation tokens. Thirteen irreversible tools answer their first call with a preview and a single-use confirmationToken, and act only when the same call comes back with it. The licence and the capability are checked on both calls. See confirmation tokens.
  • Read-only mode. AddCritterWatchMcp(o => o.ReadOnly = true) or CritterWatch:Mcp:ReadOnly = true registers only the read tools, and any CritterWatch action reached another way is refused with the deny code McpReadOnly, whatever the authorizer would say. See read-only.

Every tool calls the same enforcement helper before publishing the underlying command — the deny envelope is stable JSON the MCP client returns verbatim:

json
{
  "error": "Forbidden",
  "message": "Caller is not authorized for capability 'dlq.replay' on resource 'TripService'.",
  "capability": "dlq.replay",
  "resource": "TripService"
}

The MCP transport is configured stateless so IHttpContextAccessor reflects the current tool invocation's principal — see the MCP integration page for details.

Attribution in the audit log. An action an agent takes through MCP is recorded with the caller's name, channel MCP, and the client its request named. The relay ticket the MCP gate attaches to the command is what carries both, so a row cannot be attributed to MCP by anything a monitored service could write. With RBAC off the caller has no name and the row reads anonymous, still on channel MCP, and that ticket grants nothing: the relay authorizes exactly as it would with no ticket. See Audit Log › Channels.

The capability catalog ​

Strings, not enums — keep the wire format stable across audit-log replay. Add new capabilities at the bottom of Capabilities; never renumber or repurpose existing ones.

Read surfaces (17) ​

dashboard.view, services.view, projections.view, event-store-explorer.view, event-modeling.view, projection-stepper.view, alerts.view, metrics.view, health.view, audit-log.view, scheduled-messages.view, dead-letters.view, tenants.view, listeners.view, timeline.view, topology.view, durability.view.

Declared, and with one exception enforced nowhere yet. The exception is projection-stepper.view (1.2): the Event Store Explorer's Step Through tab needs it to step a projection through events or to rehydrate an aggregate, scoped to the store or else the service, because both show application data. For the same reason each run leaves an audit row (RequestProjectionRun or RequestRehydrateAggregate), as a saga read does. Its MCP twin, run_projection_stepper, needs mcp.projection.step as well, as the saga tools need both of their grants. diagnose_projection sends nothing to the service, so it needs only mcp.projection.step.

MCP read gate (7) ​

MCP read tools are license-gated but RBAC-free, with seven deliberate exceptions. Each is a read that returns business data rather than operational metadata, so "may look at it" is granted separately from "may act on it":

mcp.dlq.read — the three dead-letter reads (summarize_dead_letters / summarize_dead_letter_groups / query_dead_letters). Dead letters carry message bodies and exception detail, so this is granted separately from the dlq.replay / dlq.discard actions.

mcp.projection.step — the three projection tools (diagnose_projection / run_projection_stepper / get_projection_apply_source). Stepping a projection replays the service's production code over its real events and returns the projected state itself, before and after every event: a strictly larger exposure than a single dead letter. One capability covers all three because they are the two ends of one runbook — find the failing shard, replay it, read the Apply that ran — and splitting them would let an operator hold the drill-down without the diagnosis it exists to serve.

mcp.events.query — the query_events tool. Event payloads are business data, and the tool reads them across a service's whole store rather than one stream. The monitored service must also have opted in via EnableEventStoreExplorer; the capability is the console-side half of that gate.

mcp.sql.query — the query_sql tool. A SELECT reaches every projection table in the store, so this is the widest read CritterWatch offers. It is separate from the SPA's sql.query because the two surfaces are granted to different populations, and every run on either writes an audit entry.

mcp.conversations.read — the list_conversations and get_conversation tools. A hop carries no message body, but a failed hop's status description is the handler's exception message, and exception text often carries the data that failed. list_conversations checks the grant on the service it names, or fleet-wide; get_conversation checks it on every service the conversation touches, so an operator scoped to one service cannot read another's exception text through a conversation they share.

mcp.sagas.read — the list_sagas, list_saga_instances and get_saga_instance tools (1.2). A saga's persisted state is application data the way an event or a document is. Checked on the named service, or fleet-wide for list_sagas without one.

mcp.documents.read — the query_documents and get_document tools. They return whole stored documents, the same business data a SELECT * would, so they carry a grant of their own and every call writes an audit entry. list_document_types stays license-only: a type list is schema, not data. The monitored service must also have opted in via EnableDocumentExplorer, which follows EnableEventStoreExplorer when unset. An embedded console sets these switches through ConfigureMonitoring.

An MCP read needs the console's read grant too

query_documents, get_document and query_sql reach the service through the console relay, the same path the SPA's reads take, and the relay checks documents.read / sql.query against the MCP caller. So on an RBAC host an agent needs both grants: mcp.documents.read and documents.read, or mcp.sql.query and sql.query. The relay also writes the audit entry, once, in the caller's name.

Before CritterWatch 1.1 these three tools published without the relay ticket that carries the caller (an earlier fix covered the action tools, not these), so on an RBAC host the relay refused every agent read without asking the authorizer, and the tool reported a timeout. On a host without RBAC each call was audited twice, once as "anonymous".

Operator actions (52) ​

GroupCapabilities
DLQdlq.replay, dlq.discard, dlq.edit, dlq.archive, dlq.note, dlq.triage
Listenerslistener.pause, listener.restart, listener.drain, endpoint.update
Projectionsprojection.pause, projection.restart, projection.rebuild, projection.eject, projection.restart-high-water, projection.advance-high-water, subscription.rewind
Scheduled messagesscheduled-message.cancel, scheduled-message.reschedule, scheduled-message.edit
Tenantstenant.add, tenant.enable, tenant.disable, tenant.remove, tenant.hard-delete
Recurring schedulesrecurring-schedule.pause, recurring-schedule.resume, recurring-schedule.trigger
Stream compactioncompaction-policy.run, event-store.compact
Ad-hoc SQLsql.query
Document readsdocuments.read
Saga state readssagas.read
Document edits / deletesdocuments.write, documents.delete
Document filter watchesdocuments.watch
Cluster / agentsnode.eject, agent.pin, agent.unpin, election.trigger, agent.thresholds.push, node.history.clear
Servicesservice.evict, service.license-slot
Alertsalert.acknowledge, alert.snooze, alert.clear, alert.config.edit
ChaosMonkeychaos-monkey.toggle, chaos-monkey.configure
Configurationconfig.edit
Metricsmetrics.delete

dlq.edit gates rewriting a dead letter: Edit & Replay needs it as well as dlq.replay, because it changes the message body before replaying it. Before 1.1 it was declared and checked nowhere, so anyone who could replay could also rewrite. Every dead-letter replay, discard and edit-and-replay is also written to the audit log, one row per service, from the console and MCP alike.

dlq.archive gates archiving and restoring dead letters (1.1): they leave the queue and come back, and nothing is lost, so the grant is neither replay's nor discard's. Cancelling a running dead-letter operation needs the capability that starting it needed, on each service it is cancelled on. dlq.note gates writing the note on a failure group, which changes no dead letter but is what the next operator reads. Archive, restore, cancel and notes are all audited (ArchiveDlq, RestoreDlq, CancelDlq, NoteDlqGroup).

The console's own commands check what their MCP twins check (1.2). Acknowledging, snoozing and clearing an alert need alert.acknowledge, alert.snooze and alert.clear on the alert; evicting a service needs service.evict; deleting metrics samples needs a license and metrics.delete on the service, or on * for every service. Before 1.2 these were checked over MCP and not from the console. service.license-slot (1.2) gates pinning a service to a licensed slot and releasing the pin: when the fleet is larger than the license, the pins decide which services are monitored. A refused command is answered with the reason, never dropped in silence.

dlq.triage (1.2) gates asking the console's AI to explain a failure group. It changes nothing, but each request is a paid model call and sends data from the group's dead letters to the model provider, so it is a grant of its own rather than a read. It is checked on each of the group's services, and a request is refused when the caller lacks it on any of them; an accepted request is audited (DeadLetterGroup.Explain).

documents.read is a read that carries a capability, for the reason sql.query does: a page of documents, or one by id, returns business data. It is scoped to the store the request names, or else the service, and every request writes an audit entry. The Document Explorer's type list and mapping DDL are schema and stay ungated. sagas.read (1.2) is the same kind of grant for a saga's persisted state: the Saga Explorer's instance list and instance page need it, scoped to the service, and every read is audited (RequestSagaInstances, RequestSagaInstance). The saga catalog stays ungated. It is the console's grant; mcp.sagas.read is the agents', and the MCP saga tools need both on an RBAC host. documents.write (replace a document from its JSON) and documents.delete (delete one, and restore a soft-deleted one, its inverse) gate the explorer's write half, and the MCP update_document / delete_document / undelete_document tools ask for the same two on the same resource. Scoped the same way and audited. Each write is also license-gated, and the monitored service refuses it unless EnableDocumentEditing resolves on (Development only by default).

Design notes ​

  • Toggle vs configure split. ChaosMonkey on/off is a separate gate from the rate / delay knobs so an operator trusted to stop chaos isn't automatically trusted to crank the dial higher first. Same pattern is applied across HTTP + MCP surfaces.
  • HardDelete vs Remove. tenant.hard-delete is split from tenant.remove because hard-delete issues PostgreSQL DROP DATABASE … WITH (FORCE) on the tenant's database, while soft remove leaves the database intact for backup / forensic recovery.

Custom authorizer skeleton ​

A starting point that grants roles via OIDC claim mapping:

cs
public sealed class RoleClaimAuthorizer : ICritterWatchAuthorizer
{
    private readonly IReadOnlyDictionary<string, IReadOnlySet<string>> _capabilityRoles = new Dictionary<string, IReadOnlySet<string>>
    {
        [Capabilities.DlqReplay] = new HashSet<string> { "sre", "platform" },
        [Capabilities.DlqDiscard] = new HashSet<string> { "platform" },
        [Capabilities.ProjectionRebuild] = new HashSet<string> { "platform" },
        [Capabilities.TenantHardDelete] = new HashSet<string> { "platform-admin" },
        // … one row per capability you want to gate
    };

    public Task<bool> IsAllowedAsync(
        ClaimsPrincipal principal,
        string capability,
        string? resource = null,
        CancellationToken ct = default)
    {
        if (!_capabilityRoles.TryGetValue(capability, out var requiredRoles))
        {
            // Anything not explicitly listed is denied — fail-closed default.
            return Task.FromResult(false);
        }

        var has = principal.Claims
            .Where(c => c.Type == ClaimTypes.Role || c.Type == "role" || c.Type == "roles")
            .Any(c => requiredRoles.Contains(c.Value));

        return Task.FromResult(has);
    }
}

Hook it up:

cs
builder.Services.AddCritterWatchAuthorization<RoleClaimAuthorizer>();

For resource-scoped rules (e.g. only allow alert.clear on services matching a per-rotation prefix), read the resource parameter:

csharp
public Task<bool> IsAllowedAsync(
    ClaimsPrincipal principal,
    string capability,
    string? resource,
    CancellationToken ct)
{
    if (capability == Capabilities.AlertClear && resource is not null)
    {
        var serviceName = resource.Split(':').Skip(1).FirstOrDefault();
        if (serviceName is not null && OnCallRotation.OwnsService(principal, serviceName))
            return Task.FromResult(true);
    }

    return _baseline.IsAllowedAsync(principal, capability, resource, ct);
}

Testing your authorizer ​

RbacFoundationTests and RbacEnforcementHttpTests in the CritterWatch repo are the reference patterns. For your own host:

csharp
[Fact]
public async Task sre_role_can_replay_dlq()
{
    var authorizer = new RoleClaimAuthorizer(/* … */);
    var principal = new ClaimsPrincipal(
        new ClaimsIdentity(
            [new Claim(ClaimTypes.Role, "sre")],
            authenticationType: "Test"));

    var allowed = await authorizer.IsAllowedAsync(
        principal, Capabilities.DlqReplay, resource: "TripService");

    allowed.ShouldBeTrue();
}

For HTTP-level end-to-end coverage, Alba scenarios against a real Wolverine.Http pipeline exercise the full codegen path — see src/Tests/Services/RbacEnforcementHttpTests.cs for the shape.

  • Cross-application MCP server — RBAC enforcement on the MCP tool surface
  • Clustering — RBAC works the same in single-node and clustered deployments
  • Licensing — license gating is a separate, complementary layer (RBAC governs which authenticated principals can do something; license gating governs whether the operation is enabled at all)