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 all 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 @@ -77,6 +77,7 @@ const formSchema = z.object({
},
)
.optional(),
recoverEnabled: z.boolean().default(false),
limitEnabled: z.boolean().default(false),
limit: z
.object({
Expand Down Expand Up @@ -145,9 +146,10 @@ const formSchema = z.object({
type Props = {
apiId: string;
keyAuthId: string;
checkStoreEncryptedKeys: boolean;
};

export const CreateKey: React.FC<Props> = ({ apiId, keyAuthId }) => {
export const CreateKey: React.FC<Props> = ({ apiId, keyAuthId, checkStoreEncryptedKeys }) => {
const router = useRouter();

const form = useForm<z.infer<typeof formSchema>>({
Expand All @@ -162,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 @@ -201,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 @@ -295,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 @@ -809,6 +814,56 @@ export const CreateKey: React.FC<Props> = ({ apiId, keyAuthId }) => {
) : null}
</CardContent>
</Card>
{checkStoreEncryptedKeys && (
<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>
)}
</>
) : 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>
)}

<div className="w-full">
<Button
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export default async function CreateKeypage(props: {
params: {
apiId: string;
keyAuthId: string;
checkStoreEncryptedKeys: boolean;
};
}) {
const tenantId = getTenantId();
Expand All @@ -22,6 +23,13 @@ export default async function CreateKeypage(props: {
if (!keyAuth || keyAuth.workspace.tenantId !== tenantId) {
return notFound();
}
const checkStoreEncryptedKeys = keyAuth?.storeEncryptedKeys === true;

return <CreateKey keyAuthId={keyAuth.id} apiId={props.params.apiId} />;
return (
<CreateKey
keyAuthId={keyAuth.id}
apiId={props.params.apiId}
checkStoreEncryptedKeys={checkStoreEncryptedKeys}
/>
);
}
98 changes: 67 additions & 31 deletions apps/dashboard/lib/trpc/routers/key/create.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
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 { rateLimitedProcedure, ratelimit } from "@/lib/trpc/ratelimitProcedure";
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";

export const createKey = rateLimitedProcedure(ratelimit.create)
Expand All @@ -14,6 +17,7 @@ export const createKey = rateLimitedProcedure(ratelimit.create)
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 @@ -82,39 +86,71 @@ export const createKey = rateLimitedProcedure(ratelimit.create)
prefix: input.prefix,
byteLength: input.bytes,
});
await db.transaction(async (tx) => {
await tx
.insert(schema.keys)
.values({
id: keyId,
keyAuthId: keyAuth.id,
name: input.name,
hash,
start,
ownerId: input.ownerId,
meta: JSON.stringify(input.meta ?? {}),
workspaceId: workspace.id,
forWorkspaceId: null,
expires: input.expires ? new Date(input.expires) : null,
createdAt: new Date(),
ratelimitAsync: input.ratelimit?.async,
ratelimitLimit: input.ratelimit?.limit,
ratelimitDuration: input.ratelimit?.duration,
remaining: input.remaining,
refillInterval: input.refill?.interval ?? null,
refillAmount: input.refill?.amount ?? null,
lastRefillAt: input.refill?.interval ? new Date() : null,
deletedAt: null,
enabled: input.enabled,
environment: input.environment,
})
.catch((_err) => {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message:
"We are unable to create the key. Please contact support using support.unkey.dev",
});
});

await db
.insert(schema.keys)
.values({
id: keyId,
keyAuthId: keyAuth.id,
name: input.name,
hash,
start,
ownerId: input.ownerId,
meta: JSON.stringify(input.meta ?? {}),
workspaceId: workspace.id,
forWorkspaceId: null,
expires: input.expires ? new Date(input.expires) : null,
createdAt: new Date(),
ratelimitAsync: input.ratelimit?.async,
ratelimitLimit: input.ratelimit?.limit,
ratelimitDuration: input.ratelimit?.duration,
remaining: input.remaining,
refillInterval: input.refill?.interval ?? null,
refillAmount: input.refill?.amount ?? null,
lastRefillAt: input.refill?.interval ? new Date() : null,
deletedAt: null,
enabled: input.enabled,
environment: input.environment,
})
.catch((_err) => {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message:
"We are unable to create the key. Please contact support using support.unkey.dev",
if (input.recoverEnabled && keyAuth?.storeEncryptedKeys) {
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 tx
.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]",
});
});
}
});

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