Repository navigation
Expand file tree
/
Copy pathapi-keys.controller.ts
More file actions
361 lines (345 loc) · 10.7 KB
/
Copy pathapi-keys.controller.ts
File metadata and controls
361 lines (345 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Query,
UseGuards,
ForbiddenException,
BadRequestException,
} from "@nestjs/common";
import {
ApiBearerAuth,
ApiTags,
ApiOperation,
ApiResponse,
} from "@nestjs/swagger";
import { ApiKeyScope } from "@prisma/client";
import { AuthGuard } from "../common/guards/auth.guard";
import { CurrentUser } from "../common/decorators/current-user.decorator";
import { AuthenticatedUser } from "../auth/auth.types";
import { ApiKeyService } from "./api-key.service";
import { PrismaService } from "../database/prisma.service";
import {
CreateApiKeyDto,
OrganizationApiKeysQueryDto,
} from "./dto/api-key-request.dto";
/**
* API Keys Controller - Machine-to-machine integration credential management.
*
* Access control:
* - All endpoints require wallet authentication (AuthGuard) + organization admin role
* - Organization isolation enforced at query level (cannot manage other orgs' keys)
* - Role check must be implemented per organization membership/admin status
* (this codebase doesn't yet have explicit org-role modeling, so we check
* organization membership implicitly via user context when available)
*
* Response behavior:
* - Creation: returns raw secret EXACTLY ONCE (never retrievable again)
* - Listing: returns metadata only (id, prefix, name, status, scopes, dates)
* - Rotation: returns new raw secret EXACTLY ONCE, invalidates old secret immediately
* - Revocation: marks key REVOKED, takes effect immediately (no cache window)
*
* One-time secret display:
* - Clients must save the returned secret immediately
* - No code path allows retrieving or reconstructing the secret later
* - If secret is lost, client must rotate the key to get a new one
*/
@ApiBearerAuth()
@ApiTags("api-keys")
@UseGuards(AuthGuard)
@Controller("api-keys")
export class ApiKeysController {
constructor(
private readonly apiKeyService: ApiKeyService,
private readonly prisma: PrismaService,
) {}
/**
* Create a new API key for an organization.
*
* Authorization: Organization admin only
* Returns: Raw secret (display ONCE), key metadata
* Note: Secret is never stored again; must be saved by client
*/
@Post()
@ApiOperation({
summary: "Create a new API key",
description:
"Generate a new API key for machine-to-machine integrations. The raw secret is returned exactly once and cannot be retrieved later.",
})
@ApiResponse({
status: 201,
description: "API key created successfully",
schema: {
example: {
secret: "dGVzdGtleTAx_[...base64url encrypted key...]",
apiKey: {
id: "key_abc123",
prefix: "dGVzdGtl",
name: "GitHub CI",
status: "ACTIVE",
scopes: ["PROOF_VERIFY", "PAYMENT_READ"],
createdAt: "2026-08-24T12:00:00Z",
expiresAt: null,
},
},
},
})
async createKey(
@CurrentUser() user: AuthenticatedUser,
@Body()
body: CreateApiKeyDto,
) {
// Authorization: User must be organization admin
const organizationId = await this.getAuthorizedOrganizationId(
user,
body.organizationId,
);
if (!organizationId) {
throw new ForbiddenException(
"Only organization admins can create API keys. You must be the organization creator or an admin member.",
);
}
const expiresAt = body.expiresAt ? new Date(body.expiresAt) : undefined;
if (expiresAt && expiresAt <= new Date()) {
throw new BadRequestException("expiresAt must be in the future");
}
// Validate scopes if provided
if (body.scopes) {
const validScopes = Object.values(ApiKeyScope);
for (const scope of body.scopes) {
if (!validScopes.includes(scope)) {
throw new BadRequestException(`Invalid scope: ${scope}`);
}
}
}
const result = await this.apiKeyService.createKey({
organizationId,
createdBy: user.id,
name: body.name,
scopes: body.scopes,
expiresAt,
});
// Important: return includes the raw secret exactly once
return {
secret: result.secret,
apiKey: result.apiKey,
};
}
/**
* List API keys for user's organization.
*
* Authorization: Organization admin only
* Returns: Metadata only (never includes secrets or hashes)
*/
@Get()
@ApiOperation({
summary: "List API keys for your organization",
description: "List all API keys for your organization (metadata only, no secrets).",
})
@ApiResponse({
status: 200,
description: "List of API keys",
schema: {
example: [
{
id: "key_abc123",
prefix: "dGVzdGtl",
name: "GitHub CI",
status: "ACTIVE",
scopes: ["PROOF_VERIFY", "PAYMENT_READ"],
createdAt: "2026-08-24T12:00:00Z",
rotatedAt: null,
revokedAt: null,
expiresAt: null,
lastUsedAt: "2026-08-24T13:30:00Z",
},
],
},
})
async listKeys(
@CurrentUser() user: AuthenticatedUser,
@Query() query: OrganizationApiKeysQueryDto = {},
) {
// Authorization: User must be organization admin
const organizationId = await this.getAuthorizedOrganizationId(
user,
query.organizationId,
);
if (!organizationId) {
throw new ForbiddenException(
"Only organization admins can list API keys. You must be the organization creator or an admin member.",
);
}
const keys = await this.apiKeyService.listKeysForOrganization(
organizationId,
);
return keys.map((key) => ({
id: key.id,
prefix: key.prefix,
name: key.name,
status: key.status,
scopes: key.scopeAssignments.map((sa) => sa.scope),
createdAt: key.createdAt,
rotatedAt: key.rotatedAt,
revokedAt: key.revokedAt,
expiresAt: key.expiresAt,
lastUsedAt: key.lastUsedAt,
}));
}
/**
* Rotate an API key: generate new secret, invalidate old immediately.
*
* Authorization: Organization admin only
* Returns: New raw secret (display ONCE), updated key metadata
* Effect: Old secret stops working immediately
*/
@Post(":id/rotate")
@ApiOperation({
summary: "Rotate an API key",
description:
"Generate a new secret for an existing API key. The old secret is invalidated immediately and can never be used again.",
})
@ApiResponse({
status: 200,
description: "API key rotated successfully",
schema: {
example: {
secret: "bmV3c2VjcmV0MDEy_[...base64url encrypted key...]",
apiKey: {
id: "key_abc123",
prefix: "bmV3c2Vj",
name: "GitHub CI",
status: "ACTIVE",
scopes: ["PROOF_VERIFY", "PAYMENT_READ"],
rotatedAt: "2026-08-24T14:00:00Z",
},
},
},
})
async rotateKey(
@CurrentUser() user: AuthenticatedUser,
@Param("id") keyId: string,
@Query() query: OrganizationApiKeysQueryDto = {},
) {
// Authorization: User must be organization admin
const organizationId = await this.getAuthorizedOrganizationId(
user,
query.organizationId,
);
if (!organizationId) {
throw new ForbiddenException(
"Only organization admins can rotate API keys. You must be the organization creator or an admin member.",
);
}
// Verify the key belongs to this organization (enforced by service)
try {
const result = await this.apiKeyService.rotateKey(
keyId,
organizationId,
user.id, // Pass actor for audit logging
);
// Important: return includes the new raw secret exactly once
return {
secret: result.secret,
apiKey: result.apiKey,
};
} catch (error) {
if (
error instanceof Error &&
error.message.includes("does not belong to this organization")
) {
throw new ForbiddenException(
"API key does not belong to your organization",
);
}
throw error;
}
}
/**
* Revoke an API key: mark as revoked, take effect immediately.
*
* Authorization: Organization admin only
* Returns: Updated key metadata
* Effect: Revoked key is rejected by auth guard immediately
*/
@Delete(":id/revoke")
@ApiOperation({
summary: "Revoke an API key",
description:
"Revoke an API key. The key is immediately rejected by the authentication system.",
})
@ApiResponse({
status: 200,
description: "API key revoked successfully",
})
async revokeKey(
@CurrentUser() user: AuthenticatedUser,
@Param("id") keyId: string,
@Query() query: OrganizationApiKeysQueryDto = {},
) {
// Authorization: User must be organization admin
const organizationId = await this.getAuthorizedOrganizationId(
user,
query.organizationId,
);
if (!organizationId) {
throw new ForbiddenException(
"Only organization admins can revoke API keys. You must be the organization creator or an admin member.",
);
}
// Verify the key belongs to this organization (enforced by service)
try {
await this.apiKeyService.revokeKey(
keyId,
organizationId,
user.id, // Pass actor for audit logging
);
return { message: "API key revoked successfully" };
} catch (error) {
if (error instanceof Error && error.message.includes("Key not found")) {
throw new ForbiddenException("API key not found");
}
if (
error instanceof Error &&
error.message.includes("does not belong to this organization")
) {
throw new ForbiddenException(
"API key does not belong to your organization",
);
}
throw error;
}
}
/**
* Helper: Get user's primary organization ID and verify admin access.
*
* Returns the organization ID if the user is an admin of at least one organization.
* In this codebase, organization admin is determined by:
* - User created the organization (createdById == userId), OR
* - User has ADMIN role (global admin has access to all orgs)
*
* TODO: This implementation assumes user can only manage orgs they created.
* For multi-admin orgs, implement explicit OrganizationMember join table
* with role field (admin, member, etc.)
*
* @returns organizationId if authorized as admin, null otherwise
*/
private async getAuthorizedOrganizationId(
user: AuthenticatedUser,
requestedOrganizationId?: string,
): Promise<string | null> {
const org = await this.prisma.organization.findFirst({
where: {
...(requestedOrganizationId ? { id: requestedOrganizationId } : {}),
...(user.role === "ADMIN" ? {} : { createdById: user.id }),
},
select: {
id: true,
},
});
return org?.id || null;
}
}