-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathapi-keys.controller.ts
More file actions
469 lines (447 loc) · 13.6 KB
/
Copy pathapi-keys.controller.ts
File metadata and controls
469 lines (447 loc) · 13.6 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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import {
Body,
Controller,
Delete,
Get,
HttpCode,
Param,
Post,
HttpStatus,
Query,
UseGuards,
ForbiddenException,
BadRequestException,
} from "@nestjs/common";
import {
ApiBearerAuth,
ApiExcludeEndpoint,
ApiParam,
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 { ApiErrorDto } from "../common/dto/api-error.dto";
import { SESSION_AUTH_SCHEME } from "../common/swagger/security-schemes";
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)
* - Organization admin currently means global ADMIN or organization creator.
* Multi-admin memberships require a future OrganizationMember model.
*
* 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(SESSION_AUTH_SCHEME)
@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,
},
},
},
})
@ApiResponse({
status: HttpStatus.UNAUTHORIZED,
description: "Session token is missing, malformed, invalid, or expired.",
type: ApiErrorDto,
})
@ApiResponse({
status: HttpStatus.FORBIDDEN,
description:
"The caller is not an administrator of the organization named in the request.",
type: ApiErrorDto,
})
@ApiResponse({
status: HttpStatus.BAD_REQUEST,
description:
"`expiresAt` is not in the future, or `scopes` names a scope that does not exist.",
type: ApiErrorDto,
})
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",
},
],
},
})
@ApiResponse({
status: HttpStatus.UNAUTHORIZED,
description: "Session token is missing, malformed, invalid, or expired.",
type: ApiErrorDto,
})
@ApiResponse({
status: HttpStatus.FORBIDDEN,
description:
"The caller is not an administrator of the organization named in the request.",
type: ApiErrorDto,
})
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",
},
},
},
})
@ApiParam({
name: "id",
description: "API key to rotate.",
example: "ckv8v6h2b0000qzrmn831i7rn",
})
@ApiResponse({
status: HttpStatus.UNAUTHORIZED,
description: "Session token is missing, malformed, invalid, or expired.",
type: ApiErrorDto,
})
@ApiResponse({
status: HttpStatus.FORBIDDEN,
description:
"The caller is not an administrator of the organization, or the key belongs " +
"to another organization. The two answer alike so the response cannot be " +
"used to discover which key identifiers exist.",
type: ApiErrorDto,
})
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: 204 No Content
* Effect: Revoked key is rejected by auth guard immediately
*/
@Delete(":id")
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({
summary: "Revoke an API key",
description:
"Revoke an API key. The key is immediately rejected by the authentication system.",
})
@ApiResponse({
status: HttpStatus.NO_CONTENT,
description: "API key revoked successfully",
})
@ApiParam({
name: "id",
description: "API key to revoke.",
example: "ckv8v6h2b0000qzrmn831i7rn",
})
@ApiResponse({
status: HttpStatus.UNAUTHORIZED,
description: "Session token is missing, malformed, invalid, or expired.",
type: ApiErrorDto,
})
@ApiResponse({
status: HttpStatus.FORBIDDEN,
description:
"The caller is not an administrator of the organization, the key belongs to " +
"another organization, or no such key exists.",
type: ApiErrorDto,
})
async revokeKey(
@CurrentUser() user: AuthenticatedUser,
@Param("id") keyId: string,
@Query() query: OrganizationApiKeysQueryDto = {},
) {
await this.revokeAuthorizedKey(user, keyId, query);
}
@Delete(":id/revoke")
@HttpCode(HttpStatus.NO_CONTENT)
@ApiExcludeEndpoint()
async revokeKeyLegacy(
@CurrentUser() user: AuthenticatedUser,
@Param("id") keyId: string,
@Query() query: OrganizationApiKeysQueryDto = {},
) {
await this.revokeAuthorizedKey(user, keyId, query);
}
private async revokeAuthorizedKey(
user: AuthenticatedUser,
keyId: string,
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
);
} 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 the requested
* organization. If no organization was requested, it only infers one when
* exactly one manageable organization exists.
* 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)
*
* @returns organizationId if authorized as admin, null otherwise
*/
private async getAuthorizedOrganizationId(
user: AuthenticatedUser,
requestedOrganizationId?: string,
): Promise<string | null> {
const accessWhere =
user.role === "ADMIN" ? {} : { createdById: user.id };
if (requestedOrganizationId) {
const org = await this.prisma.organization.findFirst({
where: {
id: requestedOrganizationId,
...accessWhere,
},
select: {
id: true,
},
});
return org?.id || null;
}
const organizations = await this.prisma.organization.findMany({
where: accessWhere,
select: {
id: true,
},
orderBy: {
createdAt: "asc",
},
take: 2,
});
if (organizations.length === 0) return null;
if (organizations.length === 1) return organizations[0]?.id ?? null;
throw new BadRequestException(
"organizationId is required when you can manage more than one organization",
);
}
}