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 14 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 All @@ -176,8 +178,7 @@ export const CreateKey: React.FC<Props> = ({ apiId, keyAuthId }) => {
},
onError(err) {
console.error(err);
const message = parseTrpcError(err);
toast.error(message);
toast.error(err.message);
},
});

Expand All @@ -203,6 +204,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 @@ -297,6 +299,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 @@ -811,6 +814,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
43 changes: 42 additions & 1 deletion 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,6 +103,44 @@ export const createKey = t.procedure
"We are unable to create the key. Please contact support using support.unkey.dev",
});
});
if (input.recoverEnabled && !keyAuth?.storeEncryptedKeys) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message:
"Storing encrypted keys for your workspace is disabled. Please contact support using [email protected]",
});
}

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).catch((_err) => {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Encryption Failed. Please contact support using [email protected]",
});
});
await db
.insert(schema.encryptedKeys)
.values({
keyId: keyId,
workspaceId: workspace?.id,
encrypted: vaultRes.encrypted,
encryptionKeyId: vaultRes.keyId,
})
.catch((_err) => {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message:
"We are unable to store encrypt the key. Please contact support using [email protected]",
});
});
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

This doesn't resolve the issue of key inserts even if the encryption fails.

You need to handle rollback of the key creation if the encryption fails. You either need to wrap the transaction in the create transaction, or you need to handle the rollback manually. Otherwise an end user will have extra keys for no reasons.

It should be something like:

Happy path:

  1. Create Key
  2. Encrypt key
  3. Return success

Unsuccessful:

  1. Create Key
  2. Encyption or insert fails
  3. Make sure key is removed from the DB
  4. Return error.

Some reading.

https://orm.drizzle.team/docs/transactions#transactions


await ingestAuditLogs({
workspaceId: workspace.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