Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Recoverable keys feature for the dashboard #2110

Closed
wants to merge 51 commits into from
Closed
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
75db25a
Recoverable keys feature for the dashboard
harshsbhat Sep 17, 2024
365117e
Merge branch 'main' into harshbhat/recoverable-keys
harshsbhat Sep 17, 2024
ab6ad58
Checking for the Store_encrypted_keys from teh dashboard too
harshsbhat Sep 18, 2024
197fe6e
Merge branch 'main' into harshbhat/recoverable-keys
harshsbhat Sep 18, 2024
b795941
Show keyId after creating a new key
harshsbhat Sep 17, 2024
e1a92c2
lint
harshsbhat Sep 17, 2024
3379c0e
Requested changes
harshsbhat Sep 18, 2024
7cd8dc6
Removed unused component
harshsbhat Sep 18, 2024
6f903de
Add the actual link in the description
harshsbhat Sep 18, 2024
43aa747
Remove wrong rebase
harshsbhat Sep 18, 2024
e89dfa3
merge conflicts
harshsbhat Sep 18, 2024
c8d08d0
Fixing pnpm lock file
harshsbhat Sep 18, 2024
babbde4
Merge remote-tracking branch 'origin/main' into harshbhat/recoverable…
harshsbhat Sep 18, 2024
4b74619
Error handling for encrypt fail as well as disabled store encrypt keys
harshsbhat Sep 19, 2024
596b315
Merge branch 'main' into harshbhat/recoverable-keys
harshsbhat Sep 19, 2024
7ffdbc4
fix: cf cache ratelimits (#2112)
chronark Sep 19, 2024
7028fc4
Merge remote-tracking branch 'origin/main' into harshbhat/recoverable…
harshsbhat Sep 19, 2024
2d6d304
Disabling the card if store encrypted is disabled
harshsbhat Sep 19, 2024
68c6599
[autofix.ci] apply automated fixes
autofix-ci[bot] Sep 19, 2024
ee40896
Merge branch 'main' into harshbhat/recoverable-keys
harshsbhat Sep 20, 2024
ca22641
Added transaction
harshsbhat Sep 20, 2024
2bcfb89
Merge branch 'main' into harshbhat/recoverable-keys
harshsbhat Sep 21, 2024
9302c62
Merge branch 'main' into harshbhat/recoverable-keys
harshsbhat Sep 21, 2024
9699b48
Merge branch 'main' into harshbhat/recoverable-keys
harshsbhat Sep 24, 2024
c46e0a0
Merge branch 'main' into harshbhat/recoverable-keys
harshsbhat Sep 24, 2024
77b5e03
Merge branch 'main' into harshbhat/recoverable-keys
harshsbhat Sep 24, 2024
ee5e94a
Change the display after creating the new key with recoverable
harshsbhat Sep 24, 2024
fce16ae
Merge branch 'main' into harshbhat/recoverable-keys
harshsbhat Sep 25, 2024
f9877c7
Update apps/dashboard/lib/trpc/routers/key/create.ts
harshsbhat Sep 27, 2024
314ac7a
Merge remote-tracking branch 'origin/main' into harshbhat/recoverable…
harshsbhat Sep 28, 2024
bf876bc
Fix link and remove licence from vault
harshsbhat Sep 28, 2024
441a038
Merge branch 'main' into harshbhat/recoverable-keys
harshsbhat Oct 1, 2024
8125c72
[autofix.ci] apply automated fixes
autofix-ci[bot] Oct 1, 2024
050145c
feat: Added support to sidebar (#2119)
harshsbhat Oct 2, 2024
0535b2b
chore(email): update styling, copy, urls (#2141)
mcstepp Oct 2, 2024
4944c5f
chore: Delay email and upgrade Resend (#2152)
perkinsjr Oct 2, 2024
3a5bf01
fix: make keys UI responsive to mobile devices (#2145)
geraldmaboshe Oct 2, 2024
1545e7b
chore: Update to dot com (#2155)
perkinsjr Oct 2, 2024
b15c192
Update email to be "James from Unkey <[email protected]>"
perkinsjr Oct 2, 2024
bf1dcf7
chore: update legacy_keys_verifyKey.ts (#2158)
eltociear Oct 3, 2024
e7f6bf1
feat: added README.md in /packages/api (#2153)
Abhi-Bohora Oct 3, 2024
a78085a
chore: create changeset
chronark Oct 3, 2024
e8f0f5d
chore(release): version packages (#2160)
github-actions[bot] Oct 3, 2024
7da6d0d
Recoverable keys feature for the dashboard
harshsbhat Sep 17, 2024
72f9983
Checking for the Store_encrypted_keys from teh dashboard too
harshsbhat Sep 18, 2024
69942ca
Show keyId after creating a new key
harshsbhat Sep 17, 2024
ebea66b
Requested changes
harshsbhat Sep 18, 2024
6a35257
merge conflicts
harshsbhat Sep 18, 2024
c739b68
Fixing pnpm lock file
harshsbhat Sep 18, 2024
c25761f
Error handling for encrypt fail as well as disabled store encrypt keys
harshsbhat Sep 19, 2024
5db2d9a
fix: cf cache ratelimits (#2112)
chronark Sep 19, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ const formSchema = z.object({
},
)
.optional(),
recoverEnabled: z.boolean().default(false),
limitEnabled: z.boolean().default(false),
limit: z
.object({
Expand Down Expand Up @@ -163,6 +164,7 @@ export const CreateKey: React.FC<Props> = ({ apiId, keyAuthId }) => {
expireEnabled: false,
limitEnabled: false,
metaEnabled: false,
recoverEnabled: false,
ratelimitEnabled: false,
},
});
Expand Down Expand Up @@ -203,6 +205,7 @@ export const CreateKey: React.FC<Props> = ({ apiId, keyAuthId }) => {
expires: values.expires?.getTime() ?? undefined,
ownerId: values.ownerId ?? undefined,
remaining: values.limit?.remaining ?? undefined,
recoverEnabled: values.recoverEnabled,
enabled: true,
});

Expand Down Expand Up @@ -257,7 +260,6 @@ export const CreateKey: React.FC<Props> = ({ apiId, keyAuthId }) => {
Please pass it on to your user or store it somewhere safe.
</AlertDescription>
</Alert>

<Code className="flex items-center justify-between w-full gap-4 my-8 ph-no-capture max-sm:text-xs sm:overflow-hidden">
<pre>{showKey ? key.data.key : maskedKey}</pre>
<div className="flex items-start justify-between gap-4 max-sm:absolute max-sm:right-11">
Expand Down Expand Up @@ -292,6 +294,7 @@ export const CreateKey: React.FC<Props> = ({ apiId, keyAuthId }) => {
form.setValue("expireEnabled", false);
form.setValue("ratelimitEnabled", false);
form.setValue("metaEnabled", false);
form.setValue("recoverEnabled", false);
form.setValue("limitEnabled", false);
router.refresh();
}}
Expand Down Expand Up @@ -806,6 +809,54 @@ export const CreateKey: React.FC<Props> = ({ apiId, keyAuthId }) => {
) : null}
</CardContent>
</Card>
<Card>
<CardContent className="justify-between w-full p-4 item-center">
<div className="flex items-center justify-between w-full">
<span>Recoverable</span>

<FormField
control={form.control}
name="recoverEnabled"
render={({ field }) => (
<FormItem>
<FormLabel className="sr-only">Recoverable</FormLabel>
<FormControl>
<Switch
onCheckedChange={(e) => {
field.onChange(e);
if (field.value === false) {
resetLimited();
}
}}
/>
</FormControl>
</FormItem>
)}
/>
</div>

{form.watch("recoverEnabled") ? (
<>
{form.formState.errors.ratelimit && (
<p className="text-xs text-center text-content-alert">
{form.formState.errors.ratelimit.message}
</p>
)}
perkinsjr marked this conversation as resolved.
Show resolved Hide resolved
harshsbhat marked this conversation as resolved.
Show resolved Hide resolved
</>
) : null}
<p className="text-xs text-content-subtle">
You can choose to recover and display plaintext keys later, though it's
not recommended. Recoverable keys are securely stored in an encrypted
vault. For more, visit{" "}
<Link
className="font-semibold"
href={"unkey.com/docs/security/recovering-keys"}
>
unkey.com/docs/security/recovering-keys.
</Link>
</p>
</CardContent>
</Card>
perkinsjr marked this conversation as resolved.
Show resolved Hide resolved

<div className="w-full">
<Button
Expand Down
22 changes: 20 additions & 2 deletions apps/dashboard/lib/trpc/routers/key/create.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Api } from "@/app/(app)/settings/root-keys/[keyId]/permissions/api";
import { db, schema } from "@/lib/db";
import { env } from "@/lib/env";
import { ingestAuditLogs } from "@/lib/tinybird";
import { TRPCError } from "@trpc/server";
import { newId } from "@unkey/id";
import { newKey } from "@unkey/keys";
import { type EncryptRequest, type RequestContext, Vault } from "@unkey/vault";
import { z } from "zod";
import { auth, t } from "../../trpc";

Expand All @@ -15,6 +18,7 @@ export const createKey = t.procedure
keyAuthId: z.string(),
ownerId: z.string().nullish(),
meta: z.record(z.unknown()).optional(),
recoverEnabled: z.boolean().optional(),
remaining: z.number().int().positive().optional(),
refill: z
.object({
Expand Down Expand Up @@ -67,7 +71,6 @@ export const createKey = t.procedure
prefix: input.prefix,
byteLength: input.bytes,
});

await db
.insert(schema.keys)
.values({
Expand Down Expand Up @@ -100,7 +103,22 @@ export const createKey = t.procedure
"We are unable to create the key. Please contact support using support.unkey.dev",
});
});

if (input.recoverEnabled && keyAuth?.storeEncryptedKeys) {
perkinsjr marked this conversation as resolved.
Show resolved Hide resolved
const vault = new Vault(env().AGENT_URL, env().AGENT_TOKEN);
const encryptReq: EncryptRequest = {
keyring: workspace.id,
data: key,
};
const requestId = crypto.randomUUID();
const context: RequestContext = { requestId };
const vaultRes = await vault.encrypt(context, encryptReq);
harshsbhat marked this conversation as resolved.
Show resolved Hide resolved
await db.insert(schema.encryptedKeys).values({
keyId: keyId,
workspaceId: workspace.id,
encrypted: vaultRes.encrypted,
encryptionKeyId: vaultRes.keyId,
});
}
await ingestAuditLogs({
workspaceId: workspace.id,
actor: { type: "user", id: ctx.user.id },
Expand Down
1 change: 1 addition & 0 deletions apps/dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"@unkey/rbac": "workspace:^",
"@unkey/resend": "workspace:^",
"@unkey/schema": "workspace:^",
"@unkey/vault": "workspace:^",
"@unkey/vercel": "workspace:^",
"@upstash/ratelimit": "^2.0.1",
"@upstash/redis": "^1.31.3",
Expand Down
15 changes: 15 additions & 0 deletions internal/vault/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "@unkey/vault",
"version": "1.0.0",
"description": "",
"main": "src/index.ts",
"types": "src/index.ts",
"keywords": [],
"author": "",
"license": "ISC",
harshsbhat marked this conversation as resolved.
Show resolved Hide resolved
"devDependencies": {
"@types/node": "^20.14.9",
"@unkey/tsconfig": "workspace:*",
"typescript": "^5.5.3"
}
}
101 changes: 101 additions & 0 deletions internal/vault/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
export type EncryptRequest = {
keyring: string;
data: string;
};

export type EncryptResponse = {
encrypted: string;
keyId: string;
};

export type EncryptBulkRequest = {
keyring: string;
data: string[];
};

export type EncryptBulkResponse = {
encrypted: EncryptResponse[];
};

export type DecryptRequest = {
keyring: string;
encrypted: string;
};

export type DecryptResponse = {
plaintext: string;
};

export type RequestContext = {
requestId: string;
};

export class Vault {
private readonly baseUrl: string;
private readonly token: string;

constructor(baseUrl: string, token: string) {
this.baseUrl = baseUrl;
this.token = token;
}

public async encrypt(c: RequestContext, req: EncryptRequest): Promise<EncryptResponse> {
const url = `${this.baseUrl}/vault.v1.VaultService/Encrypt`;
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.token}`,
"Unkey-Request-Id": c.requestId,
},
body: JSON.stringify(req),
});

if (!res.ok) {
throw new Error(`Unable to encrypt, fetch error: ${await res.text()}`);
}

return res.json();
}

public async encryptBulk(
c: RequestContext,
req: EncryptBulkRequest,
): Promise<EncryptBulkResponse> {
const url = `${this.baseUrl}/vault.v1.VaultService/EncryptBulk`;
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.token}`,
"Unkey-Request-Id": c.requestId,
},
body: JSON.stringify(req),
});

if (!res.ok) {
throw new Error(`Unable to encryptBulk, fetch error: ${await res.text()}`);
}

return res.json();
}

public async decrypt(c: RequestContext, req: DecryptRequest): Promise<DecryptResponse> {
const url = `${this.baseUrl}/vault.v1.VaultService/Decrypt`;
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.token}`,
"Unkey-Request-Id": c.requestId,
},
body: JSON.stringify(req),
});

if (!res.ok) {
throw new Error(`Unable to decrypt, fetch error: ${await res.text()}`);
}

return res.json();
}
}