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

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
22 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
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);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens in vault creation fails here? You aren't handling the negative path:

For example encryption fails but the user receives no error or success message, The key gets upserted into the database but without encryption, on the frontend to inform them that it failed.

[
    {
        "error": {
            "json": {
                "message": "Unable to encrypt, fetch error: error code: 1016",
                "code": -32603,
                "data": {
                    "code": "INTERNAL_SERVER_ERROR",
                    "httpStatus": 500,
                    "stack": "Error: Unable to encrypt, fetch error: error code: 1016\n    at (vc/edge/function:298:40314)\n    at (vc/edge/function:298:43255)\n    at (vc/edge/function:295:126266)\n    at (vc/edge/function:295:125662)\n    at (vc/edge/function:295:125662)\n    at (vc/edge/function:295:125662)\n    at (vc/edge/function:295:125985)\n    at (vc/edge/function:337:12967)\n    at (vc/edge/function:337:14421)",
                    "path": "key.create"
                }
            }
        }
    }
]

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image
New changes will display the toast like this if the encryption fails

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",
"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();
}
}
Loading