forked from veridatum-labs/earnproof-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-key.service.ts
More file actions
427 lines (398 loc) · 12.9 KB
/
Copy pathapi-key.service.ts
File metadata and controls
427 lines (398 loc) · 12.9 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
import {
ForbiddenException,
Injectable,
Logger,
NotFoundException,
} from "@nestjs/common";
import { ApiKeyScope, ResourceStatus } from "@prisma/client";
import { randomBytes, timingSafeEqual } from "crypto";
import { sha256 } from "../common/crypto/hash";
import { PrismaService } from "../database/prisma.service";
/**
* API Key Service - Secure credential management for machine-to-machine integrations.
*
* Design decisions:
*
* 1. Hashing algorithm: SHA-256 (fast cryptographic hash, not bcrypt)
* - API keys are high-entropy random secrets (32 bytes), not weak human passwords
* - SHA-256 is the standard for API key hashing in industry (e.g., GitHub, Stripe)
* - bcrypt's slow-hash design is for defending against brute-force on weak passwords
* - Against brute-force on high-entropy random secrets, SHA-256 + salt is sufficient
* - This codebase already uses SHA-256 for other credentials (proof hashes, wallet hashes)
* - Reasoning: consistent with existing patterns, appropriate for threat model
*
* 2. Key format: 32 bytes (256 bits) of randomness, base64url-encoded
* - Yields ~43 characters when encoded
* - Prefix: first 8 characters (32 bits of entropy for human recognition)
* - Sufficient entropy for cryptographic security
*
* 3. Secret display: returned ONCE on creation/rotation, never stored/retrievable
* - API key lifecycle: generate → hash → store hash+prefix → display secret once → never again
* - No code path can reconstruct or re-display the raw secret
*
* 4. Organization isolation: enforced at query level, not surface-level checks
* - Every lookup includes organizationId filter
* - Cannot list/rotate/revoke another org's keys even with valid token
*
* 5. Audit logging: records administrative actions (create, rotate, revoke, use)
* - Never logs raw secrets or hashes
* - Logs only non-sensitive identifiers: keyId, prefix, organizationId, actor
* - Timestamps and action types for complete audit trail
*/
@Injectable()
export class ApiKeyService {
private readonly logger = new Logger(ApiKeyService.name);
private readonly KEY_BYTES = 32;
constructor(private readonly prisma: PrismaService) {}
/**
* Generate a new cryptographically strong API key secret.
*
* @returns Object with raw secret (display once) and prefix (for storage/display in listings)
*/
generateSecret(): {
secret: string;
prefix: string;
} {
const randomBytes32 = randomBytes(this.KEY_BYTES);
const secret = randomBytes32.toString("base64url");
const prefix = secret.substring(0, 8);
return { secret, prefix };
}
/**
* Hash a raw API key secret for storage.
* Uses SHA-256: appropriate for high-entropy API keys.
*
* @param secret - The raw secret (display only, never logged)
* @returns SHA-256 hash as hex string
*/
hashSecret(secret: string): string {
return sha256(secret);
}
/**
* Verify a presented secret against a stored hash.
* Returns true if they match (constant-time comparison).
*
* @param secret - Presented secret from client
* @param storedHash - Stored hash from database
* @returns true if secret hashes to storedHash
*/
verifySecret(secret: string, storedHash: string): boolean {
const computedHash = this.hashSecret(secret);
// SECURITY: Use constant-time comparison to prevent timing attacks.
// Timing attacks exploit variable execution time to distinguish between:
// - Invalid format (fails regex, returns early)
// - Valid format but wrong value (runs full comparison)
// By always performing the full comparison regardless of format validity,
// we ensure attackers cannot leak information about the expected hash format
// via response timing. We use a dummy buffer of correct length (64 hex chars = 32 bytes)
// for malformed storedHash to maintain constant execution time.
const isValidFormat = /^[a-f0-9]{64}$/i.test(storedHash);
const hashBufferToCompare = isValidFormat
? Buffer.from(storedHash, "hex")
: Buffer.alloc(32); // Dummy: 32 bytes (same length as a valid SHA-256 hash)
try {
return timingSafeEqual(
Buffer.from(computedHash, "hex"),
hashBufferToCompare,
);
} catch {
// timingSafeEqual throws if buffers are different lengths
// This shouldn't happen given our allocation strategy, but guard anyway
return false;
}
}
/**
* Look up an API key by prefix to narrow the search space,
* then verify the full secret against the stored hash.
*
* This is more efficient than hashing the presented secret and
* scanning all stored hashes. Prefix is not secret (8 chars from a 43-char key).
*
* @param prefix - First 8 characters of the presented key (non-secret)
* @param secret - Full presented secret (secret)
* @param organizationId - Organization scope for isolation
* @returns ApiKey record if valid, null if not found/invalid/revoked/expired
*/
async lookupAndVerifyKey(
prefix: string,
secret: string,
organizationId: string,
) {
// Lookup by prefix + organization (narrow scope quickly)
const apiKey = await this.prisma.apiKey.findFirst({
where: {
prefix,
organizationId,
status: ResourceStatus.ACTIVE,
OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }],
},
include: {
scopeAssignments: {
select: {
scope: true,
},
},
organization: {
select: {
id: true,
slug: true,
},
},
},
});
if (!apiKey) {
return null; // Not found, revoked, expired, or wrong org
}
// Verify the full secret matches stored hash
const isValid = this.verifySecret(secret, apiKey.keyHash);
if (!isValid) {
return null; // Hash mismatch (wrong secret)
}
return apiKey;
}
/**
* Create a new API key for an organization.
*
* @param input - Creation parameters
* @returns Object with raw secret (display once) and stored key metadata
*/
async createKey(input: {
organizationId: string;
createdBy: string;
name: string;
scopes?: ApiKeyScope[];
expiresAt?: Date;
}) {
const { secret, prefix } = this.generateSecret();
const keyHash = this.hashSecret(secret);
const apiKey = await this.prisma.apiKey.create({
data: {
organizationId: input.organizationId,
createdById: input.createdBy,
name: input.name,
prefix,
keyHash,
expiresAt: input.expiresAt,
scopeAssignments: input.scopes
? {
createMany: {
data: input.scopes.map((scope) => ({ scope })),
},
}
: undefined,
},
include: {
scopeAssignments: {
select: {
scope: true,
},
},
},
});
// Audit log: API key created (never log secret or hash)
await this.prisma.auditLog.create({
data: {
actorType: "user",
actorId: input.createdBy,
action: "api_key.created",
resourceType: "api_key",
resourceId: apiKey.id,
metadata: {
prefix: apiKey.prefix,
name: apiKey.name,
organizationId: apiKey.organizationId,
scopes: apiKey.scopeAssignments.map((sa) => sa.scope),
expiresAt: apiKey.expiresAt?.toISOString(),
},
},
});
return {
secret, // Display ONCE - never stored, never retrievable
apiKey: {
id: apiKey.id,
prefix: apiKey.prefix,
name: apiKey.name,
status: apiKey.status,
scopes: apiKey.scopeAssignments.map((sa) => sa.scope),
createdAt: apiKey.createdAt,
expiresAt: apiKey.expiresAt,
},
};
}
/**
* Rotate an API key: generate new secret, invalidate old one immediately.
* Key ID remains stable so references in client code don't break.
*
* @param keyId - ID of key to rotate
* @param organizationId - Organization scope
* @returns New secret and updated key metadata
*/
async rotateKey(keyId: string, organizationId: string, actorId?: string) {
const { secret, prefix } = this.generateSecret();
const keyHash = this.hashSecret(secret);
const apiKey = await this.prisma.apiKey.update({
where: { id: keyId, organizationId },
data: {
prefix,
keyHash,
rotatedAt: new Date(),
},
include: {
scopeAssignments: {
select: {
scope: true,
},
},
},
});
// Verify organization ownership
if (apiKey.organizationId !== organizationId) {
throw new ForbiddenException("Key does not belong to this organization");
}
// Audit log: API key rotated (never log secrets or hashes)
await this.prisma.auditLog.create({
data: {
actorType: "user",
actorId: actorId ?? null,
action: "api_key.rotated",
resourceType: "api_key",
resourceId: apiKey.id,
metadata: {
prefix: apiKey.prefix,
name: apiKey.name,
organizationId: apiKey.organizationId,
rotatedAt: apiKey.rotatedAt?.toISOString(),
},
},
});
return {
secret, // Display ONCE - new secret invalidates old immediately
apiKey: {
id: apiKey.id,
prefix: apiKey.prefix,
name: apiKey.name,
status: apiKey.status,
scopes: apiKey.scopeAssignments.map((sa) => sa.scope),
rotatedAt: apiKey.rotatedAt,
},
};
}
/**
* Revoke an API key: mark as REVOKED, take effect immediately.
*
* @param keyId - ID of key to revoke
* @param organizationId - Organization scope
* @param actorId - User performing the revocation
*/
async revokeKey(keyId: string, organizationId: string, actorId?: string) {
const apiKey = await this.prisma.apiKey.findFirst({
where: { id: keyId, organizationId },
select: {
organizationId: true,
prefix: true,
name: true,
},
});
if (!apiKey) {
throw new NotFoundException("Key not found");
}
await this.prisma.apiKey.update({
where: { id: keyId, organizationId },
data: {
status: ResourceStatus.REVOKED,
revokedAt: new Date(),
},
});
// Audit log: API key revoked
await this.prisma.auditLog.create({
data: {
actorType: "user",
actorId: actorId ?? null,
action: "api_key.revoked",
resourceType: "api_key",
resourceId: keyId,
metadata: {
prefix: apiKey.prefix,
name: apiKey.name,
organizationId: apiKey.organizationId,
revokedAt: new Date().toISOString(),
},
},
});
}
/**
* List all API keys for an organization (metadata only, no secrets).
*
* @param organizationId - Organization to list keys for
* @returns List of key metadata (id, prefix, name, status, scopes, dates)
*/
async listKeysForOrganization(organizationId: string) {
return this.prisma.apiKey.findMany({
where: {
organizationId,
},
select: {
id: true,
prefix: true,
name: true,
status: true,
scopeAssignments: {
select: {
scope: true,
},
},
createdAt: true,
rotatedAt: true,
revokedAt: true,
expiresAt: true,
lastUsedAt: true,
},
orderBy: {
createdAt: "desc",
},
});
}
/**
* Record that an API key was used (for lastUsedAt tracking).
* Non-identifying timestamp only (no IP, no user-agent).
* Also logs successful key authentication to audit trail.
*
* @param keyId - Key that was used
* @param organizationId - Organization the key belongs to
*/
async recordKeyUsage(keyId: string, organizationId?: string) {
try {
const updated = await this.prisma.apiKey.update({
where: { id: keyId },
data: {
lastUsedAt: new Date(),
},
select: {
prefix: true,
name: true,
organizationId: true,
},
});
// Audit log: API key used (successful authentication)
if (organizationId && organizationId === updated.organizationId) {
await this.prisma.auditLog.create({
data: {
actorType: "api_key",
actorId: keyId, // The API key itself is the actor
action: "api_key.authenticated",
resourceType: "api_key",
resourceId: keyId,
metadata: {
prefix: updated.prefix,
organizationId: updated.organizationId,
timestamp: new Date().toISOString(),
},
},
});
}
} catch {
// Log but don't throw - usage tracking shouldn't block requests
this.logger.warn(`Failed to record API key usage for ${keyId}`);
}
}
}