Docs / Core Concepts

Security, RBAC & Rate Limits

RFC 9700 refresh token rotation with reuse detection, API Key vs. JWT workspace guards, OWNER/ADMIN/VIEWER RBAC, sliding-window rate limits, PII masking, and audit retention.

Updated 2026-11-28~5 min readSecurity & Governance

KestrelMQ is architected for multi-tenant isolation from day one, combining domain-separated JWTs, SHA-256 API keys, Redis sliding-window quotas, recursive PII scrubbing, and automated delivery_attempts retention cleanup.

Authentication Modes & Headers

Endpoints in KestrelMQ use one of three guard strategies:

GuardAccepted HeadersWorkspace ResolutionEndpoints
ApiKeyGuardAuthorization: Bearer kmq_live_... or X-API-Key: kmq_live_...Derived automatically from api_keys.key_hash (SHA-256, cached 300s in Redis).POST /v1/events, POST /v1/events/bulk, POST /mcp
JwtAuthGuard + RolesGuardAuthorization: Bearer <accessToken> + X-Workspace-Id: <uuid> (or :id param / workspaceId body field)Verified against workspace_members (workspace_id, user_id)./v1/workspaces/*, /v1/integrations/*, /v1/templates/*, /v1/rules/*, /v1/schemas/*, /v1/inbound-sources/*
JwtOrApiKeyGuardEither kmq_live_... API key or <accessToken> + X-Workspace-IdAPI key tenant scope or verified RBAC membership.GET /v1/deliveries, GET /v1/deliveries/:id, POST /v1/deliveries/:id/replay, POST /v1/deliveries/:id/cancel, GET /v1/analytics/summary

Operator Sessions & RFC 9700 Refresh Token Rotation

User passwords are hashed with Argon2id (argon2 package). On POST /v1/auth/login, unknown emails execute a dummy argon2Verify against a startup-generated hash to prevent timing-based account enumeration.

  • Domain separation: Access tokens (JWT_ACCESS_SECRET, default 900s / 15m) carry type: "access"; refresh tokens (JWT_REFRESH_SECRET, default 604800s / 7d) carry type: "refresh", sid (session family UUID), and jti (single-use token UUID).
  • Atomic Lua rotation & reuse detection (POST /v1/auth/refresh): AuthService executes an atomic Redis Lua script against auth:rt:family:{sid}:
    • If the presented jti matches the active token, Redis atomically replaces it with a new jti and returns a fresh { accessToken, refreshToken, expiresIn, user } pair.
    • If an already-rotated jti is replayed (REUSED), Redis immediately deletes the entire session family (DEL auth:rt:family:{sid}) and returns 401 Unauthorized ("Refresh token reuse detected; session revoked").
  • Logout (POST /v1/auth/logout): Deletes auth:rt:family:{sid} and returns 204 No Content.

Workspace RBAC (OWNER, ADMIN, VIEWER)

RolesGuard enforces a strict role hierarchy (OWNER = 3 > ADMIN = 2 > VIEWER = 1). Add existing users by email or userId via POST /v1/workspaces/:id/members:

add-workspace-member.sh
curl -s -X POST http://localhost:3000/v1/workspaces/${WORKSPACE_ID}/members \
  -H "Authorization: Bearer ${ACCESS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "sre@acme.io",
    "role": "ADMIN"
  }'
  • OWNER: Full control, including assigning other OWNER members.
  • ADMIN: Create/update/delete integrations, templates, routing rules, schemas, inbound sources, mint kmq_live_ API keys, rotate webhook_signing_secret, replay/cancel deliveries, and add ADMIN or VIEWER members.
  • VIEWER: Read-only access to GET endpoints (integrations, templates, rules, schemas, inbound-sources, deliveries, analytics/summary) and non-mutating POST /v1/schemas/infer.

Sliding-Window Rate Limiting (RateLimitGuard)

High-throughput ingestion and MCP endpoints (/v1/events, /v1/events/bulk, /mcp) enforce per-workspace quotas in Redis (ratelimit:workspace:{workspaceId}) over RATE_LIMIT_WINDOW_MS (default 60,000ms):

  • FREE: 60 requests / 60s (RATE_LIMIT_FREE_MAX), 10k deliveries / month
  • PRO: 3,000 requests / 60s (RATE_LIMIT_PRO_MAX), 500k deliveries / month

With BILLING_MODE=cloud, plan changes are managed through Cloud Billing and self-serve switching in the dashboard is disabled.

Every response includes standard rate-limit headers:

HTTP Response Headers
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 58
X-RateLimit-Reset: 1764363660

When the quota is exhausted, KestrelMQ responds with 429 Too Many Requests (application/problem+json, type: "https://errors.kestrelmq.dev/too-many-requests") and a Retry-After header (in seconds).

Secret & PII Redaction and Audit Retention

Recursive Masking (maskSensitiveData)

  • Credential keys (always masked): Any object property or header matching password, apiKey, credentials, token, secret, privateKey, or Authorization (case-insensitive, ignoring _ and -) is replaced with "[REDACTED]" before writing to delivery_attempts or returning from GET /v1/deliveries/:id and MCP inspect_delivery.
  • PII keys (maskPii: true): JSON response bodies stored in delivery_attempts.response_body (truncated at 16,384 chars) and unhandled exception logs also redact email, emails, phone, and phones keys to "[REDACTED]".

Automated Log Retention (RetentionProcessor)

RetentionProcessor schedules a daily BullMQ cron job (0 3 * * *) on the maintenance queue (cleanup-delivery-attempts) that purges expired delivery_attempts in 1,000-row batches based on workspaces.plan:

Workspace Plandelivery_attempts Retention Window
FREE7 days
PRO30 days