Tenant Management DOMAIN

Overview

The tenant management surface in Dwilar/lita-api exposes the administrative entry points for creating and retrieving tenant records under the versioned /v1 API namespace. The implementation is intentionally small and explicit: tenant creation is guarded by an admin:tenants scope check, validated with zod, persisted through @lita/core, and written to the audit trail immediately after the record is created.

This fits the repository’s multi-tenant API model by keeping tenant administration separate from tenant-scoped business data. The routes are registered in apps/api/src/routes/v1/index.ts, and the create flow is designed to carry actor context into the audit pipeline while the lookup flow resolves a tenant by UUID and returns a 404 payload when the record is missing.

Architecture Overview

flowchart LR
    AdminClient[Admin Client] --> RegisterV1[registerV1Routes]
    RegisterV1 --> TenantsRoutes[tenantsRoutes]

    TenantsRoutes --> CreateTenantRoute[POST v1 tenants]
    TenantsRoutes --> GetTenantRoute[GET v1 tenants id]

    CreateTenantRoute --> ScopeCheck[requireScope admin tenants]
    ScopeCheck --> CoreCreate[createTenant]
    CreateTenantRoute --> AuditCall[request logAuditEvent]
    AuditCall --> AuditPlugin[auditPlugin]
    AuditPlugin --> RecordAudit[recordAuditEvent]

    GetTenantRoute --> CoreGet[getTenant]

    subgraph RequestContext [Request Context]
        TenantPlugin[tenantPlugin]
        TenantPlugin --> RequestTenantId[request tenantId]
        AuditPlugin --> RequestAuth[request auth]
    end

Route Registration

registerV1Routes

[!NOTE] The tenant lookup handler returns {"error":"not_found"} with a 404 status, but the declared response schema in the route only documents a 200 response. Clients generated strictly from the schema will not see the 404 body shape.

apps/api/src/routes/v1/index.ts

registerV1Routes wires the tenant administration routes into the versioned API prefix and registers the rest of the v1 surface in the same place.

Function Responsibility
registerV1Routes Registers authRoutes, tenantsRoutes, creditProfilesRoutes, decisionsRoutes, webhooksRoutes, and eventsRoutes under their /v1/* prefixes.

Route Namespace Mapping

Registered plugin Prefix
authRoutes /v1/auth
tenantsRoutes /v1/tenants
creditProfilesRoutes /v1/credit-profiles
decisionsRoutes /v1/decisions
webhooksRoutes /v1/webhooks
eventsRoutes /v1/events

The tenant management domain is therefore part of the same API-first versioned contract as the other tenant-scoped resources, but it remains isolated under its own prefix.

Tenant Administration Routes

tenantsRoutes

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

tenantsRoutes is a FastifyPluginAsync that exposes two endpoints:

Endpoint Purpose
POST /v1/tenants Creates a tenant and writes an audit event.
GET /v1/tenants/:id Fetches a tenant by UUID and returns 404 when missing.

The create handler is the only tenant route in this file that explicitly checks authorization scope and emits an audit event. The read handler validates the path parameter and returns the stored tenant or a not_found payload.

Request and Response Models

Create Tenant Request
Property Type Description
name string Tenant display name. Must be at least 2 characters long.
Create Tenant Response
Property Type Description
id string Tenant identifier returned by createTenant.
name string Tenant name returned by createTenant.
status string Tenant status returned by createTenant.
Get Tenant Path Parameters
Property Type Description
id string Tenant UUID.
Get Tenant Response
Property Type Description
id string Tenant identifier returned by getTenant.
name string Tenant name.
status string Tenant status.
Not Found Payload
Property Type Description
error string Literal value not_found.

Create Tenant

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

{
    "title": "Create Tenant",
    "description": "Creates a tenant after validating the request body and checking the admin:tenants scope. The created tenant is written to the audit trail with tenant metadata.",
    "method": "POST",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/v1/tenants",
    "headers": [
        {
            "key": "Authorization",
            "value": "Bearer <token>",
            "required": true
        },
        {
            "key": "Content-Type",
            "value": "application/json",
            "required": true
        }
    ],
    "queryParams": [],
    "pathParams": [],
    "bodyType": "json",
    "requestBody": "{\n    \"name\": \"Acme Financial Services\"\n}",
    "formData": [],
    "rawBody": "",
    "responses": {
        "201": {
            "description": "Tenant created successfully",
            "body": "{\n    \"id\": \"7f31d7b8-3a6d-4df2-b2a5-8b0df4c9f7c1\",\n    \"name\": \"Acme Financial Services\",\n    \"status\": \"ACTIVE\"\n}"
        }
    }
}

Behavior traced from the handler:

  • z.object({ name: z.string().min(2) }) rejects empty and single-character names.
  • requireScope(request, "admin:tenants") is executed before persistence.
  • createTenant(body.name) is awaited and its return value is sent back.
  • request.logAuditEvent(...) is called with:
    • action: "tenant.create"
    • targetType: "Tenant"
    • targetId: tenant.id
    • metadata: { name: tenant.name }
  • reply.code(201) is set before the tenant object is returned.

Get Tenant

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

{
    "title": "Get Tenant",
    "description": "Fetches a tenant by UUID and returns a 404 payload when the tenant does not exist.",
    "method": "GET",
    "baseUrl": "<ApiBaseUrl>",
    "endpoint": "/v1/tenants/:id",
    "headers": [],
    "queryParams": [],
    "pathParams": [
        {
            "key": "id",
            "value": "7f31d7b8-3a6d-4df2-b2a5-8b0df4c9f7c1",
            "required": true
        }
    ],
    "bodyType": "none",
    "requestBody": "",
    "formData": [],
    "rawBody": "",
    "responses": {
        "200": {
            "description": "Tenant found",
            "body": "{\n    \"id\": \"7f31d7b8-3a6d-4df2-b2a5-8b0df4c9f7c1\",\n    \"name\": \"Acme Financial Services\",\n    \"status\": \"ACTIVE\"\n}"
        },
        "404": {
            "description": "Tenant not found",
            "body": "{\n    \"error\": \"not_found\"\n}"
        }
    }
}

Behavior traced from the handler:

  • z.object({ id: z.string().uuid() }) validates the path parameter before the handler logic.
  • getTenant(params.id) is awaited.
  • When no tenant is returned, the handler sets reply.code(404) and returns { error: "not_found" }.
  • When a tenant exists, the tenant object is returned directly.

Request Context and Audit Infrastructure

Tenant Context Plugin

[!NOTE] GET /v1/tenants/:id does not call requireScope("admin:tenants") in the code shown. The only enforcement visible in this handler is UUID validation plus not-found handling.

apps/api/src/plugins/tenant.ts

tenantPlugin augments the Fastify request with tenant context derived from authenticated requests.

Decorated field Type Description
request.tenantId `string \ undefined`

Behavior traced from the hook:

  • If request.auth is missing, the hook returns immediately.
  • request.tenantId is assigned from request.auth.tenantId.
  • When request.auth exists but request.tenantId is missing, the hook sends a 400 response with { error: "missing tenant" }.

This is the request-side tenant boundary used by other tenant-scoped routes in the repository, and it is the same field that the audit plugin expects before it writes a record.

Audit Logging Plugin

apps/api/src/plugins/audit.ts

auditPlugin decorates each request with logAuditEvent, which forwards structured audit data into recordAuditEvent.

Decorated method Responsibility
logAuditEvent Persists tenant-scoped audit records when tenant and auth context are present.

Audit data flow:

  1. The route calls request.logAuditEvent(...).
  2. auditPlugin checks this.tenantId and this.auth.
  3. If either is missing, the call returns without persisting anything.
  4. When both are present, recordAuditEvent(...) receives:
    • tenantId
    • actorType
    • actorId
    • action
    • targetType
    • targetId
    • ip
    • userAgent
    • metadata

Audit Event Emission Flow

sequenceDiagram
    participant Admin as Admin Caller
    participant Route as tenantsRoutes
    participant Core as lita core
    participant Audit as request logAuditEvent
    participant Store as recordAuditEvent

    Admin->>Route: POST /v1/tenants
    Route->>Route: requireScope admin tenants
    Route->>Core: createTenant
    Core-->>Route: tenant record
    Route->>Audit: logAuditEvent tenant.create
    Audit->>Audit: check tenantId and auth
    Audit->>Store: recordAuditEvent
    Store-->>Audit: persisted
    Route-->>Admin: 201 tenant

Feature Flows

Create Tenant and Record Audit Trail

sequenceDiagram
    participant A as Admin
    participant R as POST v1 tenants
    participant S as requireScope
    participant C as createTenant
    participant L as request logAuditEvent
    participant B as Audit Store

    A->>R: Send tenant name
    R->>R: Validate name with zod
    R->>S: Check admin tenants scope
    S-->>R: Allowed
    R->>C: createTenant name
    C-->>R: tenant
    R->>L: tenant.create event
    L->>B: recordAuditEvent
    B-->>L: saved
    R-->>A: 201 tenant response

[!NOTE] request.logAuditEvent is invoked unconditionally by the create handler, but the plugin only persists when both request.tenantId and request.auth are present. Audit emission therefore depends on upstream request decoration, not on the route handler alone.

Flow summary:

  • The request body must contain a name with a minimum length of 2.
  • The handler enforces admin:tenants before any tenant record is created.
  • The created tenant is immediately returned and separately audited.

Retrieve Tenant by ID

sequenceDiagram
    participant A as Admin
    participant R as GET v1 tenants id
    participant V as zod params validation
    participant C as getTenant

    A->>R: Send tenant UUID
    R->>V: Validate id
    V-->>R: Valid
    R->>C: getTenant id
    C-->>R: tenant or null
    alt tenant exists
        R-->>A: 200 tenant
    else tenant missing
        R-->>A: 404 not_found
    end

Flow summary:

  • The route accepts only UUID-shaped identifiers.
  • A missing tenant becomes a 404 response with { error: "not_found" }.
  • No audit event is emitted for the read path in the code shown.

Error Handling

Validation Failures

Route Validation Rule Result
POST /v1/tenants name must be a string with length at least 2 Request fails validation before createTenant runs.
GET /v1/tenants/:id id must be a UUID string Request fails validation before getTenant runs.

Runtime Error Paths

Route Condition Response
POST /v1/tenants Missing admin:tenants scope requireScope blocks the handler before persistence.
GET /v1/tenants/:id Tenant not found 404 with { "error": "not_found" }

Error Response Shape

Property Type Description
error string Error identifier returned by the route handler.

The tenant routes keep error handling explicit and local to the handler, which matches the repository’s API-first style: validation happens in the route schema, authorization is checked in the handler, and the not-found case is returned as a simple JSON payload.

Dependencies

Route-Level Dependencies

Dependency Type Purpose
FastifyPluginAsync Fastify Declares the route module.
z zod Validates request bodies, params, and response schemas.
createTenant @lita/core Persists a new tenant record.
getTenant @lita/core Retrieves a tenant record by ID.
requireScope ../../services/authz.js Enforces admin:tenants on the create route.
request.logAuditEvent request decoration Emits the tenant creation audit event.

Request Context Dependencies

Dependency File Role
request.auth apps/api/src/plugins/tenant.ts and audit plugin Supplies tenant context for request decoration and auditing.
request.tenantId apps/api/src/plugins/tenant.ts Used by the audit plugin as the tenant boundary.

Testing Considerations

Scenario Expected Result
Create tenant with a 1-character name Validation failure before handler execution.
Create tenant without admin:tenants scope Scope enforcement blocks the request.
Create tenant with valid payload Tenant is created, audited, and returned with status 201.
Get tenant with non-UUID id Validation failure before lookup.
Get tenant with unknown UUID 404 and { "error": "not_found" }.
Verify audit emission on create tenant.create event is forwarded when request tenant context is available.

Key Classes Reference

Class Responsibility
tenants.ts Implements tenant creation and lookup routes for /v1/tenants.
index.ts Registers the v1 route modules and mounts tenant routes under /v1/tenants.
audit.ts Decorates requests with logAuditEvent and persists audit entries.
tenant.ts Populates request.tenantId from authenticated request context.