Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Prevent empty-scope API tokens from inheriting full role permissions. (#4533)

Kiran K4e8ff9c48c41
diff --git a/apps/web/app/api/tokens/[id]/route.ts b/apps/web/app/api/tokens/[id]/route.ts
index 1aa891bc8b..750bd19426 100644
--- a/apps/web/app/api/tokens/[id]/route.ts
+++ b/apps/web/app/api/tokens/[id]/route.ts
@@ -21,6 +21,7 @@ export const GET = withWorkspace(
name: true,
partialKey: true,
scopes: true,
+ expires: true,
lastUsed: true,
createdAt: true,
updatedAt: true,
diff --git a/apps/web/app/api/tokens/route.ts b/apps/web/app/api/tokens/route.ts
index 302f3f9fe7..675c812122 100644
--- a/apps/web/app/api/tokens/route.ts
+++ b/apps/web/app/api/tokens/route.ts
@@ -39,6 +39,7 @@ export const GET = withWorkspace(
name: true,
partialKey: true,
scopes: true,
+ expires: true,
lastUsed: true,
createdAt: true,
updatedAt: true,
@@ -90,7 +91,7 @@ export const POST = withWorkspace(
});
}
- if (!validateScopesForRole(scopes || [], role)) {
+ if (!validateScopesForRole(scopes, role)) {
throw new DubApiError({
code: "unprocessable_entity",
message: "Some of the given scopes are not available for your role.",
@@ -150,10 +151,7 @@ export const POST = withWorkspace(
partialKey,
userId: isMachine ? machineUser?.id! : session.user.id,
projectId: workspace.id,
- scopes:
- scopes && scopes.length > 0
- ? [...new Set(scopes)].join(" ")
- : null,
+ scopes: [...new Set(scopes)].join(" "),
},
});
},
@@ -172,8 +170,8 @@ export const POST = withWorkspace(
email: session.user.email,
token: {
name,
- type: scopesToName(scopes || []).name,
- permissions: scopesToName(scopes || []).description,
+ type: scopesToName(scopes).name,
+ permissions: scopesToName(scopes).description,
},
workspace: {
name: workspace.name,
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tokens/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tokens/page.tsx
index 9895ec828a..3cdd8b5dce 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tokens/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tokens/page.tsx
@@ -20,6 +20,7 @@ import {
Key,
PenWriting,
Popover,
+ StatusBadge,
Table,
Tooltip,
usePagination,
@@ -140,7 +141,21 @@ export default function TokensPage() {
id: "partialKey",
header: "Key",
accessorKey: "partialKey",
- cell: ({ row }) => row.original.partialKey,
+ cell: ({ row }) => {
+ const isExpired =
+ row.original.expires && new Date(row.original.expires) < new Date();
+
+ return (
+ <span className="flex items-center gap-2">
+ {row.original.partialKey}
+ {isExpired && (
+ <StatusBadge variant="warning" size="sm" icon={null}>
+ Expired
+ </StatusBadge>
+ )}
+ </span>
+ );
+ },
},
{
id: "lastUsed",
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
index c97b9028d4..aac725c11e 100644
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@ -407,8 +407,11 @@ export const withWorkspace = (
permissions = getPermissionsByRole(workspace.users[0].role);
// Find the subset of permissions that the user has access to based on the token scopes
- if (isRestrictedToken && token?.scopes) {
- const tokenScopes = (token.scopes.split(" ") as Scope[]) || [];
+ // Empty/null scopes must fail closed (no permissions) — never inherit full role perms
+ if (isRestrictedToken) {
+ const tokenScopes = (token?.scopes?.split(" ").filter(Boolean) ??
+ []) as Scope[];
+
permissions = mapScopesToPermissions(tokenScopes).filter((p) =>
permissions.includes(p),
);
diff --git a/apps/web/lib/zod/schemas/token.ts b/apps/web/lib/zod/schemas/token.ts
index 7c6931229a..08964a93bf 100644
--- a/apps/web/lib/zod/schemas/token.ts
+++ b/apps/web/lib/zod/schemas/token.ts
@@ -11,7 +11,9 @@ export const createTokenSchema = z.object({
.min(1)
.max(50),
isMachine: z.boolean().optional().default(false),
- scopes: z.array(z.enum(SCOPES)).default([]).optional(),
+ scopes: z.array(z.enum(SCOPES)).min(1, {
+ error: "Please select at least one scope for this API key.",
+ }),
});
// Schema to validate the request body when updating a token
@@ -31,6 +33,7 @@ export const tokenSchema = z.object({
.string()
.nullable()
.transform((val) => val?.split(" ") ?? []),
+ expires: z.date().nullable(),
lastUsed: z.date().nullable(),
createdAt: z.date(),
updatedAt: z.date(),
diff --git a/apps/web/scripts/migrations/expire-empty-scope-tokens.ts b/apps/web/scripts/migrations/expire-empty-scope-tokens.ts
new file mode 100644
index 0000000000..900229e29d
--- /dev/null
+++ b/apps/web/scripts/migrations/expire-empty-scope-tokens.ts
@@ -0,0 +1,83 @@
+import "dotenv-flow/config";
+
+import { tokenCache } from "@/lib/auth/token-cache";
+import { prisma } from "@/lib/prisma";
+
+// Expire RestrictedTokens that have null or empty scopes.
+async function main() {
+ const now = new Date();
+
+ const tokens = await prisma.restrictedToken.findMany({
+ where: {
+ // Tokens with no scopes that have either never been used, or not used in the last 30 days
+ AND: [
+ { OR: [{ scopes: null }, { scopes: "" }] },
+ {
+ OR: [
+ { lastUsed: null },
+ {
+ lastUsed: {
+ lt: new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000),
+ },
+ },
+ ],
+ },
+ ],
+ },
+ orderBy: {
+ lastUsed: "asc",
+ },
+ include: {
+ project: {
+ select: {
+ name: true,
+ slug: true,
+ plan: true,
+ trialEndsAt: true,
+ },
+ },
+ },
+ });
+
+ console.table(
+ tokens.map(
+ ({ id, name, projectId, partialKey, lastUsed, scopes, project }) => ({
+ id,
+ name,
+ projectId,
+ workspace: project.name,
+ slug: project.slug,
+ plan: project.plan,
+ partialKey,
+ lastUsed,
+ scopes,
+ }),
+ ),
+ );
+
+ if (tokens.length === 0) {
+ console.log("No tokens to expire");
+ return;
+ }
+
+ const { count } = await prisma.restrictedToken.updateMany({
+ where: {
+ id: {
+ in: tokens.map((token) => token.id),
+ },
+ },
+ data: {
+ expires: now,
+ },
+ });
+
+ console.log(`Expired ${count} tokens`);
+
+ await tokenCache.expireMany({
+ hashedKeys: tokens.map((token) => token.hashedKey),
+ });
+
+ console.log(`Invalidated cache for ${tokens.length} tokens`);
+}
+
+main();
diff --git a/apps/web/ui/modals/add-edit-token-modal.tsx b/apps/web/ui/modals/add-edit-token-modal.tsx
index e08c2a38cb..547e3aeff2 100644
--- a/apps/web/ui/modals/add-edit-token-modal.tsx
+++ b/apps/web/ui/modals/add-edit-token-modal.tsx
@@ -130,8 +130,19 @@ function AddEditTokenModal({
};
const { name, scopes } = data;
- const buttonDisabled =
- (!name || token?.name === name) && token?.scopes === scopes;
+ const selectedScopes = Object.values(scopes).filter(Boolean);
+
+ let disabledReason: string | null = null;
+
+ if (selectedScopes.length === 0) {
+ disabledReason = "Select at least one permission.";
+ } else if (!name) {
+ disabledReason = "Enter a name.";
+ } else if (token?.name === name && token?.scopes === scopes) {
+ disabledReason = "No changes have been made.";
+ }
+
+ const buttonDisabled = disabledReason !== null;
const scopesByResources = transformScopesForUI(
getScopesByResourceForRole(role),
@@ -314,6 +325,7 @@ function AddEditTokenModal({
<Button
text={token ? "Save changes" : "Create API key"}
disabled={buttonDisabled}
+ disabledTooltip={disabledReason}
loading={saving}
/>
</form>