Tenant Management Domain - Tenant Context Propagation and Isolation in the Request Pipeline

Overview

This domain documents how Dwilar/lita-api carries tenant identity from authentication into request-scoped state, and how that tenant identity is reused to isolate writes, replay idempotent requests, and persist audit events. The pipeline is built so that tenantId is not guessed from the URL or request body; it is derived from the authenticated request context and then propagated through downstream hooks and handlers.

For tenant management operations, the request pipeline enforces three distinct boundaries: authentication first, tenant binding second, and tenant-scoped persistence last. The tenant boundary is reused as a mandatory partition key in idempotency storage and audit records, which keeps replay behavior and audit history aligned with the same tenant context that authorized the request.

Architecture Overview

flowchart TD
    Client[API Client]

    subgraph RequestAuth [Request Authentication]
        AuthPlugin[authPlugin onRequest]
        ResolveKey[resolveApiKey]
        VerifyJwt[verifyJwt]
        VerifyUs[verifyUsAccessToken]
        VerifyJp[verifyJpAccessToken]
    end

    subgraph TenantBinding [Tenant Context Binding]
        TenantPlugin[tenantPlugin preHandler]
        RequestTenant[request tenantId]
    end

    subgraph RequestControl [Request Control]
        IdempotencyPlugin[idempotencyPlugin preHandler]
        RouteHandler[Tenant route handler]
        RequireScope[requireScope]
        AuditDecorator[request logAuditEvent]
    end

    subgraph Persistence [Persistence]
        PrismaIdem[prisma idempotencyKey]
        RecordAudit[recordAuditEvent]
        TenantStore[createTenant getTenant]
    end

    Client --> AuthPlugin
    AuthPlugin --> ResolveKey
    AuthPlugin --> VerifyJwt
    AuthPlugin --> VerifyUs
    AuthPlugin --> VerifyJp
    AuthPlugin --> TenantPlugin
    TenantPlugin --> RequestTenant
    RequestTenant --> IdempotencyPlugin
    RequestTenant --> RouteHandler
    RouteHandler --> RequireScope
    RouteHandler --> AuditDecorator
    IdempotencyPlugin --> PrismaIdem
    AuditDecorator --> RecordAudit
    RouteHandler --> TenantStore

Request Context Extensions

The tenant pipeline works by decorating FastifyRequest with request-scoped properties that are later consumed by route handlers and persistence hooks.

Fastify Request augmentation

Property Type Source Description
auth AuthContext apps/api/src/plugins/auth.ts Populated by authPlugin after Bearer token verification. The tenant pipeline uses its tenantId, actorType, actorId, and scopes fields.
tenantId `string \ undefined` apps/api/src/plugins/tenant.ts
usAccess `UsAccessContext \ undefined` apps/api/src/plugins/auth.ts
jpAccess `JpAccessContext \ undefined` apps/api/src/plugins/auth.ts
idempotencyKey `string \ undefined` apps/api/src/plugins/idempotency.ts
idempotencyRequestHash `string \ undefined` apps/api/src/plugins/idempotency.ts

Tenant-aware token contexts

UsAccessContext

File: apps/api/src/services/us-api.ts

Property Type Description
consentId string Consent identifier extracted from the access token.
tenantId string Tenant identifier extracted from the access token.
purpose ConsentPurpose Token purpose claim used in downstream authorization.
dataCategories DataCategory[] Category scopes derived from the access token.

JpAccessContext

File: apps/api/src/services/jp-api.ts

Property Type Description
consentId string Consent identifier extracted from the access token.
tenantId string Tenant identifier extracted from the access token.
purpose JpConsentPurpose Token purpose claim used in downstream authorization.
dataCategories JpDataCategory[] Category scopes derived from the access token.

Component Structure

1. Request Authentication and Tenant Binding

auth.ts

File: apps/api/src/plugins/auth.ts

authPlugin is the first enforcement point for non-public requests. It validates request metadata, resolves the caller’s auth context, and populates tenant-aware request fields before handlers run.

Hook Description
onRequest Skips /healthz, /readyz, /openapi.json, and any path starting with /docs. For all other paths, requires X-Request-Id and a Bearer authorization header, then resolves the request into request.auth, request.usAccess, or request.jpAccess.

Auth resolution order

  • resolveApiKey(token)
  • verifyJwt(token)
  • verifyUsAccessToken(token)
  • verifyJpAccessToken(token)

Tenant propagation behavior

  • For US and JP access tokens, tenantId comes from the token payload and is copied into request.auth.tenantId.
  • The derived auth context also sets actorType to client, actorId to the consent identifier, and scopes to the token’s data categories.

Note: The authPlugin requires X-Request-Id before any Bearer token validation. Requests that omit that header are rejected with a 400 response even if the token itself would otherwise be valid.


tenant.ts

File: apps/api/src/plugins/tenant.ts

tenantPlugin turns authenticated tenant claims into direct request state.

Hook Description
preHandler Copies request.auth.tenantId into request.tenantId. If request.auth exists but does not contain a tenant identifier, the hook responds with 400 { error: "missing tenant" }.

Isolation rule

  • request.tenantId is the request-local tenant partition key.
  • Downstream code does not derive tenant context from route params or request payloads.

2. Tenant-Scoped Idempotency

idempotency.ts

File: apps/api/src/plugins/idempotency.ts

idempotencyPlugin scopes replay protection to authenticated tenant requests and stores completed responses for replay.

Hook Description
preHandler For POST requests with request.tenantId and an Idempotency-Key header, it hashes the JSON body, checks prisma.idempotencyKey for an existing row keyed by tenantId and key, and either short-circuits with the stored response or attaches idempotencyKey and idempotencyRequestHash to the request.
onSend Persists the outgoing payload as a completed idempotency record when request.idempotencyKey and request.tenantId are present.

Persistence shape

  • Lookup key: tenantId_key
  • Stored fields: tenantId, key, requestHash, responseJson, status, expiresAt
  • Expiration: 24 hours from write time

Note: The lookup path keys only on tenantId and key. If the same tenant reuses an Idempotency-Key, the stored responseJson is replayed even when the request body changes, because requestHash is recorded but not compared during lookup.


3. Tenant-Aware Audit Recording

audit.ts

File: apps/api/src/plugins/audit.ts

auditPlugin decorates the request with a tenant-bound audit helper. The helper only writes an audit record when both authentication and tenant context are present.

Decoration Description
logAuditEvent Persists an audit event through recordAuditEvent using the request’s tenant, actor, IP address, user agent, and caller-provided metadata.

Audit payload passed to recordAuditEvent

  • tenantId: this.tenantId
  • actorType: this.auth.actorType
  • actorId: this.auth.actorId
  • action: input.action
  • targetType: input.targetType
  • targetId: input.targetId
  • ip: this.ip
  • userAgent: this.headers["user-agent"] ?? "unknown"
  • metadata: input.metadata ?? {}

This makes tenantId the partition key for audit history, so audit rows stay aligned with the same tenant boundary that authorized the request.


4. Scope Enforcement Helper

authz.ts

File: apps/api/src/services/authz.ts

requireScope is the route-level authorization guard used by tenant administration writes.

Method Description
requireScope Reads request.auth?.scopes, throws an error with statusCode = 403 when the requested scope is missing, and otherwise returns normally.

Behavior

  • Required scope is passed by the route handler.
  • The helper does not derive tenant context; it only checks the scope list already attached to request.auth.

5. Tenant Management Routes

tenants.ts

File: apps/api/src/routes/v1/tenants.ts

This route set is the tenant management surface in the API. It depends on global authentication middleware and uses the tenant pipeline to keep create operations tenant-bound and auditable.

Route Handler Description
POST / Requires the admin:tenants scope, creates a tenant, writes an audit event, and returns the created tenant.
GET /:id Fetches a tenant by UUID and returns 404 when not found.

Route-level enforcement

  • Global authPlugin runs before the route handler and requires X-Request-Id plus Bearer auth.
  • POST / calls requireScope(request, "admin:tenants") before tenant creation.
  • POST / calls request.logAuditEvent(...) after the tenant is created.
  • GET /:id does not call requireScope.

Note: POST / performs explicit scope enforcement with requireScope(request, "admin:tenants"), but GET /:id does not. The read handler therefore relies on the global auth middleware only, while the write handler adds an extra authorization gate.


auth.ts

File: apps/api/src/routes/v1/auth.ts

This route exposes an auth inspection endpoint that returns the current request auth context.

Route Handler Description
POST /token/introspect Returns whether the request body contains a token string and echoes the current request auth tenant and scopes.

API Integration

Authentication and request headers

Note: The handler does not verify the submitted body.token. It sets active from Boolean(body.token) and returns request.auth?.tenantId and request.auth?.scopes, which come from the current authenticated request rather than from the posted token value.

All tenant-management endpoints shown here are behind the global request auth hook.

  • Authorization: Bearer <token>
  • X-Request-Id: <request-id>

Tenant-scoped POST requests can also carry:

  • Idempotency-Key: <key> [badge:optional]

Endpoint details

Create Tenant

{
    "title": "Create Tenant",
    "description": "Creates a tenant record, requires the admin:tenants scope, and writes a tenant-scoped audit event after creation.",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/tenants",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        },
        {
            "key": "Idempotency-Key",
            "value": "<idempotency-key>",
            "required": false
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"name\": \"Acme Finance\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Tenant created",
            "body": "{\n    \"id\": \"tenant_01HZX8JQ4C8M3KQ9B7Y2\",\n    \"name\": \"Acme Finance\",\n    \"status\": \"ACTIVE\"\n}"
        },
        "400": {
            "description": "Tenant context missing from auth",
            "body": "{\n    \"error\": \"missing tenant\"\n}"
        },
        "401": {
            "description": "Missing or invalid request authentication",
            "body": "{\n    \"error\": {\n        \"code\": \"unauthorized\",\n        \"message\": \"Authorization: Bearer <PARTNER_API_KEY> is required\",\n        \"request_id\": \"req_01J0ABCDEF1234567890\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

Get Tenant

{
    "title": "Get Tenant",
    "description": "Fetches a tenant by UUID after the global auth middleware has validated the request.",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/tenants/{id}",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "550e8400-e29b-41d4-a716-446655440000"
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Tenant found",
            "body": "{\n    \"id\": \"550e8400-e29b-41d4-a716-446655440000\",\n    \"name\": \"Acme Finance\",\n    \"status\": \"ACTIVE\"\n}"
        },
        "404": {
            "description": "Tenant not found",
            "body": "{\n    \"error\": \"not_found\"\n}"
        },
        "401": {
            "description": "Missing or invalid request authentication",
            "body": "{\n    \"error\": {\n        \"code\": \"unauthorized\",\n        \"message\": \"Authorization: Bearer <PARTNER_API_KEY> is required\",\n        \"request_id\": \"req_01J0ABCDEF1234567890\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

Introspect Token

{
    "title": "Introspect Token",
    "description": "Returns the current request auth tenant and scopes together with a boolean derived from the posted token string.",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/api/v1/auth/token/introspect",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "X-Request-Id",
            "value": "<request-id>",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"token\": \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.example\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Introspection result",
            "body": "{\n    \"active\": true,\n    \"tenantId\": \"tenant_01HZX8JQ4C8M3KQ9B7Y2\",\n    \"scopes\": [\n        \"admin:tenants\"\n    ]\n}"
        },
        "400": {
            "description": "Missing X-Request-Id header",
            "body": "{\n    \"error\": {\n        \"code\": \"invalid_request\",\n        \"message\": \"X-Request-Id header is required\",\n        \"request_id\": \"req_01J0ABCDEF1234567890\",\n        \"retryable\": false\n    }\n}"
        },
        "401": {
            "description": "Missing or invalid request authentication",
            "body": "{\n    \"error\": {\n        \"code\": \"unauthorized\",\n        \"message\": \"Authorization: Bearer <PARTNER_API_KEY> is required\",\n        \"request_id\": \"req_01J0ABCDEF1234567890\",\n        \"retryable\": false\n    }\n}"
        }
    }
}

Feature Flows

1. Authenticated tenant context propagation

sequenceDiagram
    participant C as Client
    participant A as authPlugin onRequest
    participant T as tenantPlugin preHandler
    participant R as Request handler

    C->>A: Authorization and X Request Id
    A->>A: resolveApiKey or verifyJwt or verifyUsAccessToken or verifyJpAccessToken
    A-->>C: request.auth set
    T->>T: copy request.auth.tenantId to request.tenantId
    alt tenantId missing in auth
        T-->>C: 400 missing tenant
    else tenantId present
        T-->>R: request.tenantId available
    end

This is the core tenant isolation path. The tenant identifier is not derived from the URL or payload; it is copied from the authenticated request context into a request-local field before the handler executes.


2. Tenant creation with scope enforcement, audit, and optional idempotency

sequenceDiagram
    participant C as Client
    participant A as authPlugin onRequest
    participant T as tenantPlugin preHandler
    participant I as idempotencyPlugin preHandler
    participant H as tenantsRoutes handler
    participant S as requireScope
    participant AU as request logAuditEvent
    participant P as prisma
    participant O as onSend

    C->>A: POST /api/v1/tenants with headers
    A->>A: resolve auth and tenant aware context
    T->>T: set request.tenantId from request.auth.tenantId
    I->>P: findUnique by tenantId_key when Idempotency-Key is present
    alt replay hit
        I-->>C: 200 stored responseJson
    else fresh request
        H->>S: requireScope admin:tenants
        S-->>H: allowed
        H->>H: createTenant
        H->>AU: logAuditEvent
        AU->>P: recordAuditEvent with tenantId
        H-->>O: response payload
        O->>P: create idempotencyKey row with tenantId
        O-->>C: 201 tenant payload
    end

The route writes both audit history and idempotency state with the same tenant boundary that was established by the authentication pipeline.


3. Current request auth inspection

sequenceDiagram
    participant C as Client
    participant A as authPlugin onRequest
    participant R as token introspect handler

    C->>A: POST /api/v1/auth/token/introspect
    A->>A: validate X Request Id and Bearer auth
    A-->>R: request.auth available
    R->>R: active = Boolean body token
    R-->>C: active, request auth tenantId, scopes

This endpoint returns the current request auth context rather than the posted token’s validated claims.

State Management

Request-scoped tenant state

State Trigger Stored fields Effect
Authenticated authPlugin resolves a token successfully request.auth, request.usAccess, request.jpAccess Enables tenant-aware request processing.
TenantBound tenantPlugin copies request.auth.tenantId request.tenantId Provides a direct tenant partition key to downstream hooks and handlers.
IdempotencyChecked idempotencyPlugin sees POST plus Idempotency-Key plus request.tenantId request.idempotencyKey, request.idempotencyRequestHash Enables replay or persistence of tenant-scoped responses.
Auditable request.logAuditEvent is called tenant, actor, action, target, metadata Persists an audit row tied to the same tenant boundary.
stateDiagram-v2
    [*] --> RequestReceived
    RequestReceived --> Authenticated : authPlugin onRequest
    Authenticated --> TenantBound : tenantPlugin preHandler
    TenantBound --> IdempotencyChecked : POST with Idempotency Key
    TenantBound --> Handled : no idempotency key
    IdempotencyChecked --> Replayed : existing tenantId key row
    IdempotencyChecked --> Handled : new request
    Handled --> Audited : request logAuditEvent
    Audited --> Completed
    Replayed --> Completed

Error Handling

Authentication and tenant binding errors

Source Condition Outcome
authPlugin Missing X-Request-Id Sends 400 with invalid_request and the request id.
authPlugin No usable Bearer token Sends 401 with unauthorized.
tenantPlugin request.auth exists but has no tenantId Sends 400 { error: "missing tenant" }.
requireScope Scope is absent from request.auth.scopes Throws an error with statusCode = 403.

Idempotency and audit behavior on failure paths

Source Condition Outcome
idempotencyPlugin No POST, no tenantId, or no Idempotency-Key header Leaves the request untouched.
idempotencyPlugin Existing tenant-scoped idempotency row is found Sends the stored responseJson with 200 and skips the route handler.
auditPlugin Missing tenantId or auth Returns without persisting an audit event.

Integration Points

  • @lita/auth supplies token verification and API key resolution used by authPlugin.
  • @lita/core supplies createTenant and getTenant for tenant CRUD.
  • @lita/db supplies Prisma access for idempotencyKey persistence.
  • recordAuditEvent is invoked from auditPlugin with tenant, actor, and request metadata.
  • requireScope is the tenant-management authorization gate for admin:tenants.

Dependencies

Runtime dependencies

  • Fastify plugin lifecycle via fastify-plugin
  • @lita/auth
  • @lita/core
  • @lita/db
  • Node crypto for request body hashing in idempotency storage

Request headers

  • Authorization
  • X-Request-Id
  • Idempotency-Key [badge:optional]

Testing Considerations

  • Verify that non-public requests without X-Request-Id receive the invalid_request error from authPlugin.
  • Verify that authenticated requests missing a tenant identifier return 400 missing tenant before tenant-sensitive handlers run.
  • Verify that POST /api/v1/tenants requires admin:tenants.
  • Verify that tenant creation writes an audit event containing the tenant identifier from request.tenantId.
  • Verify that repeated POST requests with the same Idempotency-Key and tenant return the stored response.
  • Verify that changing the request body while reusing the same tenant-scoped idempotency key still replays the stored response.

Key Classes Reference

Class Responsibility
auth.ts Resolves authentication, derives tenant-aware request context, and enforces request header presence.
tenant.ts Copies tenantId from auth into request state and blocks tenant-less authenticated requests.
idempotency.ts Implements tenant-scoped POST replay and persistence.
audit.ts Writes tenant-partitioned audit records from request context.
authz.ts Enforces route scopes using request.auth.scopes.
tenants.ts Handles tenant creation and lookup routes.
auth.ts Exposes request-auth token introspection for the current authenticated request.