-
Notifications
You must be signed in to change notification settings - Fork 505
/
v1_keys_createKey.ts
629 lines (595 loc) · 21.2 KB
/
v1_keys_createKey.ts
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
import { type UnkeyAuditLog, insertUnkeyAuditLog } from "@/pkg/audit";
import { rootKeyAuth } from "@/pkg/auth/root_key";
import type { Database, Identity } from "@/pkg/db";
import { UnkeyApiError, openApiErrorResponses } from "@/pkg/errors";
import type { App } from "@/pkg/hono/app";
import { retry } from "@/pkg/util/retry";
import { createRoute, z } from "@hono/zod-openapi";
import { schema } from "@unkey/db";
import { sha256 } from "@unkey/hash";
import { newId } from "@unkey/id";
import { KeyV1 } from "@unkey/keys";
import { buildUnkeyQuery } from "@unkey/rbac";
const route = createRoute({
tags: ["keys"],
operationId: "createKey",
method: "post" as const,
path: "/v1/keys.createKey",
security: [{ bearerAuth: [] }],
request: {
body: {
required: true,
content: {
"application/json": {
schema: z.object({
apiId: z.string().openapi({
description: "Choose an `API` where this key should be created.",
example: "api_123",
}),
prefix: z
.string()
.max(16)
.optional()
.openapi({
description: `To make it easier for your users to understand which product an api key belongs to, you can add prefix them.
For example Stripe famously prefixes their customer ids with cus_ or their api keys with sk_live_.
The underscore is automatically added if you are defining a prefix, for example: "prefix": "abc" will result in a key like abc_xxxxxxxxx
`,
}),
name: z.string().optional().openapi({
description: "The name for your Key. This is not customer facing.",
example: "my key",
}),
byteLength: z.number().int().min(16).max(255).default(16).optional().openapi({
description:
"The byte length used to generate your key determines its entropy as well as its length. Higher is better, but keys become longer and more annoying to handle. The default is 16 bytes, or 2^^128 possible combinations.",
default: 16,
}),
ownerId: z.string().optional().openapi({
deprecated: true,
description: "Deprecated, use `externalId`",
example: "team_123",
}),
externalId: z
.string()
.optional()
.openapi({
description: `Your user's Id. This will provide a link between Unkey and your customer record.
When validating a key, we will return this back to you, so you can clearly identify your user from their api key.`,
example: "team_123",
}),
meta: z
.record(z.unknown())
.optional()
.openapi({
description:
"This is a place for dynamic meta data, anything that feels useful for you should go here",
example: {
billingTier: "PRO",
trialEnds: "2023-06-16T17:16:37.161Z",
},
}),
roles: z
.array(z.string().min(1).max(512))
.optional()
.openapi({
description:
"A list of roles that this key should have. If the role does not exist, an error is thrown",
example: ["admin", "finance"],
}),
permissions: z
.array(z.string().min(1).max(512))
.optional()
.openapi({
description:
"A list of permissions that this key should have. If the permission does not exist, an error is thrown",
example: ["domains.create_record", "say_hello"],
}),
expires: z.number().int().optional().openapi({
description:
"You can auto expire keys by providing a unix timestamp in milliseconds. Once Keys expire they will automatically be disabled and are no longer valid unless you enable them again.",
example: 1623869797161,
}),
remaining: z
.number()
.int()
.optional()
.openapi({
description:
"You can limit the number of requests a key can make. Once a key reaches 0 remaining requests, it will automatically be disabled and is no longer valid unless you update it.",
example: 1000,
externalDocs: {
description: "Learn more",
url: "https://unkey.dev/docs/features/remaining",
},
}),
refill: z
.object({
interval: z.enum(["daily", "monthly"]).openapi({
description: "Unkey will automatically refill verifications at the set interval.",
}),
amount: z.number().int().min(1).positive().openapi({
description:
"The number of verifications to refill for each occurrence is determined individually for each key.",
}),
refillDay: z
.number()
.min(1)
.max(31)
.optional()
.openapi({
description: `The day of the month, when we will refill the remaining verifications. To refill on the 15th of each month, set 'refillDay': 15.
If the day does not exist, for example you specified the 30th and it's february, we will refill them on the last day of the month instead.`,
}),
})
.optional()
.openapi({
description:
"Unkey enables you to refill verifications for each key at regular intervals.",
example: {
interval: "monthly",
amount: 100,
refillDay: 15,
},
}),
ratelimit: z
.object({
async: z
.boolean()
.default(true)
.optional()
.openapi({
description:
"Async will return a response immediately, lowering latency at the cost of accuracy. Will be required soon.",
externalDocs: {
description: "Learn more",
url: "https://unkey.dev/docs/features/ratelimiting",
},
}),
type: z
.enum(["fast", "consistent"])
.default("fast")
.optional()
.openapi({
description:
"Deprecated, use `async`. Fast ratelimiting doesn't add latency, while consistent ratelimiting is more accurate.",
externalDocs: {
description: "Learn more",
url: "https://unkey.dev/docs/features/ratelimiting",
},
deprecated: true,
}),
limit: z.number().int().min(1).openapi({
description: "The total amount of requests in a given interval.",
}),
duration: z.number().int().min(1000).optional().openapi({
description: "The window duration in milliseconds. Will be required soon.",
example: 60_000,
}),
refillRate: z.number().int().min(1).optional().openapi({
description: "How many tokens to refill during each refillInterval.",
deprecated: true,
}),
refillInterval: z.number().int().min(1).optional().openapi({
description: "The refill timeframe, in milliseconds.",
deprecated: true,
}),
})
.optional()
.openapi({
description: "Unkey comes with per-key fixed-window ratelimiting out of the box.",
example: {
type: "fast",
limit: 10,
duration: 60_000,
},
}),
enabled: z.boolean().default(true).optional().openapi({
description: "Sets if key is enabled or disabled. Disabled keys are not valid.",
example: false,
}),
recoverable: z
.boolean()
.default(false)
.optional()
.openapi({
description: `You may want to show keys again later. While we do not recommend this, we leave this option open for you.
In addition to storing the key's hash, recoverable keys are stored in an encrypted vault, allowing you to retrieve and display the plaintext later.
[https://www.unkey.com/docs/security/recovering-keys](https://www.unkey.com/docs/security/recovering-keys) for more information.`,
}),
environment: z
.string()
.max(256)
.optional()
.openapi({
description: `Environments allow you to divide your keyspace.
Some applications like Stripe, Clerk, WorkOS and others have a concept of "live" and "test" keys to
give the developer a way to develop their own application without the risk of modifying real world
resources.
When you set an environment, we will return it back to you when validating the key, so you can
handle it correctly.
`,
}),
}),
},
},
},
},
responses: {
200: {
description: "The configuration for an api",
content: {
"application/json": {
schema: z.object({
keyId: z.string().openapi({
description:
"The id of the key. This is not a secret and can be stored as a reference if you wish. You need the keyId to update or delete a key later.",
example: "key_123",
}),
key: z.string().openapi({
description:
"The newly created api key, do not store this on your own system but pass it along to your user.",
example: "prefix_xxxxxxxxx",
}),
}),
},
},
},
...openApiErrorResponses,
},
});
export type Route = typeof route;
export type V1KeysCreateKeyRequest = z.infer<
(typeof route.request.body.content)["application/json"]["schema"]
>;
export type V1KeysCreateKeyResponse = z.infer<
(typeof route.responses)[200]["content"]["application/json"]["schema"]
>;
export const registerV1KeysCreateKey = (app: App) =>
app.openapi(route, async (c) => {
const req = c.req.valid("json");
const { cache, db, logger, vault, rbac } = c.get("services");
const auth = await rootKeyAuth(
c,
buildUnkeyQuery(({ or }) => or("*", "api.*.create_key", `api.${req.apiId}.create_key`)),
);
const { val: api, err } = await cache.apiById.swr(req.apiId, async () => {
return (
(await db.readonly.query.apis.findFirst({
where: (table, { eq, and, isNull }) =>
and(eq(table.id, req.apiId), isNull(table.deletedAt)),
with: {
keyAuth: true,
},
})) ?? null
);
});
if (err) {
throw new UnkeyApiError({
code: "INTERNAL_SERVER_ERROR",
message: `unable to load api: ${err.message}`,
});
}
if (!api || api.workspaceId !== auth.authorizedWorkspaceId) {
throw new UnkeyApiError({
code: "NOT_FOUND",
message: `api ${req.apiId} not found`,
});
}
if (!api.keyAuth) {
throw new UnkeyApiError({
code: "PRECONDITION_FAILED",
message: `api ${req.apiId} is not setup to handle keys`,
});
}
if (req.recoverable && !api.keyAuth.storeEncryptedKeys) {
throw new UnkeyApiError({
code: "PRECONDITION_FAILED",
message: `api ${req.apiId} does not support recoverable keys`,
});
}
if (req.remaining === 0) {
throw new UnkeyApiError({
code: "BAD_REQUEST",
message: "remaining must be greater than 0.",
});
}
if ((req.remaining === null || req.remaining === undefined) && req.refill?.interval) {
throw new UnkeyApiError({
code: "BAD_REQUEST",
message: "remaining must be set if you are using refill.",
});
}
if (req.refill?.refillDay && req.refill.interval === "daily") {
throw new UnkeyApiError({
code: "BAD_REQUEST",
message: "when interval is set to 'daily', 'refillDay' must be null.",
});
}
/**
* Set up an api for production
*/
const authorizedWorkspaceId = auth.authorizedWorkspaceId;
const rootKeyId = auth.key.id;
const externalId = req.externalId ?? req.ownerId;
const [permissionIds, roleIds, identity] = await Promise.all([
getPermissionIds(db.readonly, authorizedWorkspaceId, req.permissions ?? []),
getRoleIds(db.readonly, authorizedWorkspaceId, req.roles ?? []),
externalId
? upsertIdentity(db.primary, authorizedWorkspaceId, externalId)
: Promise.resolve(null),
]);
const newKey = await retry(5, async (attempt) => {
if (attempt > 1) {
logger.warn("retrying key creation", {
attempt,
workspaceId: authorizedWorkspaceId,
apiId: api.id,
});
}
const secret = new KeyV1({
byteLength: req.byteLength ?? 16,
prefix: req.prefix,
}).toString();
const start = secret.slice(0, (req.prefix?.length ?? 0) + 5);
const kId = newId("key");
const hash = await sha256(secret.toString());
await db.primary.insert(schema.keys).values({
id: kId,
keyAuthId: api.keyAuthId!,
name: req.name,
hash,
start,
ownerId: externalId,
meta: req.meta ? JSON.stringify(req.meta) : null,
workspaceId: authorizedWorkspaceId,
forWorkspaceId: null,
expires: req.expires ? new Date(req.expires) : null,
createdAt: new Date(),
ratelimitAsync: req.ratelimit?.async ?? req.ratelimit?.type === "fast",
ratelimitLimit: req.ratelimit?.limit ?? req.ratelimit?.refillRate,
ratelimitDuration: req.ratelimit?.duration ?? req.ratelimit?.refillInterval,
remaining: req.remaining,
refillInterval: req.refill?.interval,
refillDay: req.refill?.interval === "daily" ? null : req?.refill?.refillDay ?? 1,
refillAmount: req.refill?.amount,
lastRefillAt: req.refill?.interval ? new Date() : null,
deletedAt: null,
enabled: req.enabled,
environment: req.environment ?? null,
identityId: identity?.id,
});
if (req.recoverable && api.keyAuth?.storeEncryptedKeys) {
const perm = rbac.evaluatePermissions(
buildUnkeyQuery(({ or }) => or("*", "api.*.encrypt_key", `api.${api.id}.encrypt_key`)),
auth.permissions,
);
if (perm.err) {
throw new UnkeyApiError({
code: "INTERNAL_SERVER_ERROR",
message: `unable to evaluate permissions: ${perm.err.message}`,
});
}
if (!perm.val.valid) {
throw new UnkeyApiError({
code: "INSUFFICIENT_PERMISSIONS",
message: `insufficient permissions to encrypt keys: ${perm.val.message}`,
});
}
const vaultRes = await retry(
3,
async () => {
return await vault.encrypt(c, {
keyring: authorizedWorkspaceId,
data: secret,
});
},
(attempt, err) =>
logger.warn("vault.encrypt failed", {
attempt,
err: err.message,
}),
);
await db.primary.insert(schema.encryptedKeys).values({
workspaceId: authorizedWorkspaceId,
keyId: kId,
encrypted: vaultRes.encrypted,
encryptionKeyId: vaultRes.keyId,
});
}
return {
id: kId,
secret,
};
});
await Promise.all([
roleIds.length > 0
? db.primary.insert(schema.keysRoles).values(
roleIds.map((roleId) => ({
keyId: newKey.id,
roleId,
workspaceId: authorizedWorkspaceId,
})),
)
: Promise.resolve(),
permissionIds.length > 0
? db.primary.insert(schema.keysPermissions).values(
permissionIds.map((permissionId) => ({
keyId: newKey.id,
permissionId,
workspaceId: authorizedWorkspaceId,
})),
)
: Promise.resolve(),
]);
const auditLogs: UnkeyAuditLog[] = [
{
workspaceId: authorizedWorkspaceId,
event: "key.create",
actor: {
type: "key",
id: rootKeyId,
},
description: `Created ${newKey.id} in ${api.keyAuthId}`,
resources: [
{
type: "key",
id: newKey.id,
},
{
type: "keyAuth",
id: api.keyAuthId!,
},
],
context: {
location: c.get("location"),
userAgent: c.get("userAgent"),
},
},
...roleIds.map(
(roleId) =>
({
workspaceId: authorizedWorkspaceId,
actor: { type: "key", id: rootKeyId },
event: "authorization.connect_role_and_key",
description: `Connected ${roleId} and ${newKey.id}`,
resources: [
{
type: "key",
id: newKey.id,
},
{
type: "role",
id: roleId,
},
],
context: {
location: c.get("location"),
userAgent: c.get("userAgent"),
},
}) satisfies UnkeyAuditLog,
),
...permissionIds.map(
(permissionId) =>
({
workspaceId: authorizedWorkspaceId,
actor: { type: "key", id: rootKeyId },
event: "authorization.connect_permission_and_key",
description: `Connected ${permissionId} and ${newKey.id}`,
resources: [
{
type: "key",
id: newKey.id,
},
{
type: "permission",
id: permissionId,
},
],
context: {
location: c.get("location"),
userAgent: c.get("userAgent"),
},
}) satisfies UnkeyAuditLog,
),
];
await insertUnkeyAuditLog(c, undefined, auditLogs);
return c.json({
keyId: newKey.id,
key: newKey.secret,
});
});
async function getPermissionIds(
db: Database,
workspaceId: string,
permissionNames: Array<string>,
): Promise<Array<string>> {
if (permissionNames.length === 0) {
return [];
}
const permissions = await db.query.permissions.findMany({
where: (table, { inArray, and, eq }) =>
and(eq(table.workspaceId, workspaceId), inArray(table.name, permissionNames)),
columns: {
id: true,
name: true,
},
});
if (permissions.length < permissionNames.length) {
const missingPermissions = permissionNames.filter(
(name) => !permissions.some((permission) => permission.name === name),
);
throw new UnkeyApiError({
code: "PRECONDITION_FAILED",
message: `Permissions ${JSON.stringify(
missingPermissions,
)} are missing, please create them first`,
});
}
return permissions.map((r) => r.id);
}
async function getRoleIds(
db: Database,
workspaceId: string,
roleNames: Array<string>,
): Promise<Array<string>> {
if (roleNames.length === 0) {
return [];
}
const roles = await db.query.roles.findMany({
where: (table, { inArray, and, eq }) =>
and(eq(table.workspaceId, workspaceId), inArray(table.name, roleNames)),
columns: {
id: true,
name: true,
},
});
if (roles.length < roleNames.length) {
const missingRoles = roleNames.filter((name) => !roles.some((role) => role.name === name));
throw new UnkeyApiError({
code: "PRECONDITION_FAILED",
message: `Roles ${JSON.stringify(missingRoles)} are missing, please create them first`,
});
}
return roles.map((r) => r.id);
}
export async function upsertIdentity(
db: Database,
workspaceId: string,
externalId: string,
): Promise<Identity> {
let identity = await db.query.identities.findFirst({
where: (table, { and, eq }) =>
and(eq(table.workspaceId, workspaceId), eq(table.externalId, externalId)),
});
if (identity) {
return identity;
}
await db
.insert(schema.identities)
.values({
id: newId("identity"),
createdAt: Date.now(),
environment: "default",
meta: {},
externalId,
updatedAt: null,
workspaceId,
})
.onDuplicateKeyUpdate({
set: {
updatedAt: Date.now(),
},
});
identity = await db.query.identities.findFirst({
where: (table, { and, eq }) =>
and(eq(table.workspaceId, workspaceId), eq(table.externalId, externalId)),
});
if (!identity) {
throw new UnkeyApiError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to read identity after upsert",
});
}
return identity;
}