Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions docs/tenants-api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# /api/tenants

Tenant write endpoints are authenticated and validate request input with Zod
before handlers run. Validation failures return the standard error envelope.

## POST /api/tenants

Creates a tenant record for the authenticated actor.

Required header:

```http
x-user-id: dev-1
```

Request body:

```json
{
"name": "GrantFox Ops",
"slug": "grantfox-ops",
"contactEmail": "ops@grantfox.test",
"plan": "growth",
"metadata": {
"campaign": "fwc26"
}
}
```

Fields:

| Field | Required | Notes |
|---|---:|---|
| `name` | yes | Trimmed string, 1-120 chars |
| `slug` | no | 3-63 lowercase letters, numbers, or hyphens; normalized to lowercase |
| `contactEmail` | no | Valid email address, max 254 chars |
| `plan` | no | `starter`, `growth`, or `enterprise`; defaults to `starter` |
| `metadata` | no | Up to 20 keys; primitive string/number/boolean values only |

Success response: `201` with `{ success: true, data, requestId, timestamp }`.

## PATCH /api/tenants/:tenantId

Updates a tenant. `tenantId` must be 3-64 chars using letters, numbers,
underscores, or hyphens.

Request body accepts at least one of:

```json
{
"name": "GrantFox Stadium Ops",
"contactEmail": "stadium-ops@grantfox.test",
"plan": "enterprise",
"metadata": {
"campaign": "fwc26"
}
}
```

Success response: `200` with `{ success: true, data, requestId, timestamp }`.

## Validation Errors

Invalid requests return `400` before route logic runs:

```json
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": [
{
"field": "body.name",
"message": "name is required",
"code": "INVALID_TYPE"
}
]
},
"requestId": "req-tenant-create",
"timestamp": "2026-07-28T00:00:00.000Z"
}
```

Unknown JSON fields are rejected.
3 changes: 1 addition & 2 deletions src/middleware/errorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import type { ValidationErrorDetail } from './validate.js';
import { ValidationError } from './validate.js';
import { buildErrorEnvelope } from './envelope.js';
import type { ErrorEnvelope } from '../types/ResponseEnvelope.js';
import { buildErrorEnvelope } from './envelope.js';

const isProduction = process.env.NODE_ENV === "production";

Expand Down Expand Up @@ -100,7 +99,7 @@ export function errorHandler(
}

const details = extractValidationDetails(err);
const body = errorEnvelope(code, finalMessage, requestId, details);
const body = buildErrorEnvelope(code, finalMessage, requestId, details);

if (!res.headersSent) {
res.status(statusCode).json(body);
Expand Down
2 changes: 2 additions & 0 deletions src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type { SubscriptionRepository } from "../repositories/subscriptionReposit
import type { DeveloperRepository } from "../repositories/developerRepository.js";
import type { ApiRepository } from "../repositories/apiRepository.js";
import { createForecastRouter } from "./forecast.js";
import { createTenantsRouter } from "./tenants.js";
import { config } from "../config/index.js";
import { createBillingRateLimitMiddleware } from "../middleware/rateLimit.js";

Expand Down Expand Up @@ -88,6 +89,7 @@ export function createApiRouter(deps: ApiRouterDeps = {}): Router {
);

router.use("/forecast", createForecastRouter());
router.use("/tenants", createTenantsRouter());

if (deps.scheduledExportsService) {
router.use(
Expand Down
267 changes: 267 additions & 0 deletions src/routes/tenants.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
import express from 'express';
import request from 'supertest';
import { errorHandler } from '../middleware/errorHandler.js';
import { requestIdMiddleware } from '../middleware/requestId.js';
import { logger } from '../logger.js';
import {
createTenantsRouter,
type TenantRecord,
type TenantRepository,
} from './tenants.js';
import type { CreateTenantInput, UpdateTenantInput } from '../validators/tenants.js';

class MockTenantRepository implements TenantRepository {
create = jest.fn(async (input: CreateTenantInput, actorId: string): Promise<TenantRecord> => ({
id: 'ten_test_123',
name: input.name,
slug: input.slug ?? 'grantfox-ops',
contactEmail: input.contactEmail,
plan: input.plan,
metadata: input.metadata,
createdBy: actorId,
createdAt: '2026-07-28T00:00:00.000Z',
updatedAt: '2026-07-28T00:00:00.000Z',
}));

update = jest.fn(async (tenantId: string, input: UpdateTenantInput, actorId: string): Promise<TenantRecord> => ({
id: tenantId,
name: input.name ?? 'GrantFox Ops',
slug: 'grantfox-ops',
contactEmail: input.contactEmail,
plan: input.plan ?? 'starter',
metadata: input.metadata,
createdBy: actorId,
createdAt: '2026-07-28T00:00:00.000Z',
updatedAt: '2026-07-28T01:00:00.000Z',
}));
}

function buildApp(repository = new MockTenantRepository()) {
const app = express();
app.use(express.json());
app.use(requestIdMiddleware);
app.use('/api/tenants', createTenantsRouter({ tenantRepository: repository }));
app.use(errorHandler);
return { app, repository };
}

function buildDefaultRepositoryApp() {
const app = express();
app.use(express.json());
app.use(requestIdMiddleware);
app.use('/api/tenants', createTenantsRouter());
app.use(errorHandler);
return app;
}

describe('createTenantsRouter', () => {
let infoSpy: jest.SpyInstance;

beforeEach(() => {
infoSpy = jest.spyOn(logger, 'info').mockImplementation(() => undefined);
});

afterEach(() => {
infoSpy.mockRestore();
});

it('returns 401 before validation when unauthenticated', async () => {
const { app, repository } = buildApp();

const res = await request(app).post('/api/tenants').send({});

expect(res.status).toBe(401);
expect(res.body.error.code).toBe('UNAUTHORIZED');
expect(repository.create).not.toHaveBeenCalled();
});

it('creates a tenant with parsed input and structured success envelope', async () => {
const { app, repository } = buildApp();

const res = await request(app)
.post('/api/tenants')
.set('x-user-id', 'dev-1')
.set('x-request-id', 'req-tenant-create')
.set('x-correlation-id', 'corr-tenant-create')
.send({
name: ' GrantFox Ops ',
slug: 'GrantFox-Ops',
contactEmail: 'ops@grantfox.test',
plan: 'growth',
metadata: { campaign: 'fwc26' },
});

expect(res.status).toBe(201);
expect(res.body).toMatchObject({
success: true,
data: {
id: 'ten_test_123',
name: 'GrantFox Ops',
slug: 'grantfox-ops',
plan: 'growth',
},
requestId: 'req-tenant-create',
});
expect(repository.create).toHaveBeenCalledWith(
expect.objectContaining({ name: 'GrantFox Ops', slug: 'grantfox-ops' }),
'dev-1',
);
expect(infoSpy).toHaveBeenCalledWith(
'[tenants] tenant created',
expect.objectContaining({
requestId: 'req-tenant-create',
correlationId: 'corr-tenant-create',
tenantId: 'ten_test_123',
actorId: 'dev-1',
}),
);
});

it('returns structured 400 for invalid create body', async () => {
const { app, repository } = buildApp();

const res = await request(app)
.post('/api/tenants')
.set('x-user-id', 'dev-1')
.set('x-request-id', 'req-invalid-create')
.send({ contactEmail: 'bad-email' });

expect(res.status).toBe(400);
expect(res.body).toMatchObject({
success: false,
error: {
code: 'VALIDATION_ERROR',
message: 'Request validation failed',
},
requestId: 'req-invalid-create',
});
expect(res.body.error.details).toEqual(
expect.arrayContaining([
expect.objectContaining({ field: 'body.name' }),
expect.objectContaining({ field: 'body.contactEmail' }),
]),
);
expect(repository.create).not.toHaveBeenCalled();
});

it('returns structured 400 for unknown create fields', async () => {
const { app } = buildApp();

const res = await request(app)
.post('/api/tenants')
.set('x-user-id', 'dev-1')
.send({ name: 'GrantFox Ops', unsafeRole: 'admin' });

expect(res.status).toBe(400);
expect(res.body.error.details).toEqual(
expect.arrayContaining([
expect.objectContaining({ field: 'body', code: 'UNRECOGNIZED_KEYS' }),
]),
);
});

it('updates a tenant with validated params and body', async () => {
const { app, repository } = buildApp();

const res = await request(app)
.patch('/api/tenants/tenant_123')
.set('x-user-id', 'dev-1')
.set('x-request-id', 'req-tenant-update')
.send({ name: 'GrantFox Stadium Ops', plan: 'enterprise' });

expect(res.status).toBe(200);
expect(res.body.data).toMatchObject({
id: 'tenant_123',
name: 'GrantFox Stadium Ops',
plan: 'enterprise',
});
expect(repository.update).toHaveBeenCalledWith(
'tenant_123',
expect.objectContaining({ name: 'GrantFox Stadium Ops', plan: 'enterprise' }),
'dev-1',
);
});

it('returns structured 400 for invalid patch params and empty body', async () => {
const { app, repository } = buildApp();

const res = await request(app)
.patch('/api/tenants/no')
.set('x-user-id', 'dev-1')
.set('x-request-id', 'req-invalid-update')
.send({});

expect(res.status).toBe(400);
expect(res.body.requestId).toBe('req-invalid-update');
expect(res.body.error.details).toEqual(
expect.arrayContaining([
expect.objectContaining({ field: 'body' }),
expect.objectContaining({ field: 'params.tenantId' }),
]),
);
expect(repository.update).not.toHaveBeenCalled();
});

it('uses the default repository to create and update tenants', async () => {
const app = buildDefaultRepositoryApp();

const created = await request(app)
.post('/api/tenants')
.set('x-user-id', 'dev-1')
.send({ name: 'AI' });

expect(created.status).toBe(201);
expect(created.body.data).toEqual(
expect.objectContaining({
id: expect.stringMatching(/^ten_/),
name: 'AI',
slug: 'tenant-ai',
plan: 'starter',
createdBy: 'dev-1',
}),
);

const updated = await request(app)
.patch(`/api/tenants/${created.body.data.id}`)
.set('x-user-id', 'dev-1')
.send({ contactEmail: 'ai-ops@grantfox.test' });

expect(updated.status).toBe(200);
expect(updated.body.data).toEqual(
expect.objectContaining({
id: created.body.data.id,
name: 'AI',
slug: 'tenant-ai',
contactEmail: 'ai-ops@grantfox.test',
}),
);
});

it('routes repository errors through the error handler', async () => {
const repository = new MockTenantRepository();
repository.create.mockRejectedValueOnce(new Error('tenant store unavailable'));
const { app } = buildApp(repository);

const res = await request(app)
.post('/api/tenants')
.set('x-user-id', 'dev-1')
.send({ name: 'GrantFox Ops' });

expect(res.status).toBe(500);
expect(res.body.error.code).toBe('INTERNAL_SERVER_ERROR');
});

it('routes update repository errors through the error handler', async () => {
const repository = new MockTenantRepository();
repository.update.mockRejectedValueOnce(new Error('tenant store unavailable'));
const { app } = buildApp(repository);

const res = await request(app)
.patch('/api/tenants/tenant_123')
.set('x-user-id', 'dev-1')
.send({ name: 'GrantFox Ops' });

expect(res.status).toBe(500);
expect(res.body.error.code).toBe('INTERNAL_SERVER_ERROR');
});
});
Loading
Loading