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.

Limit the creation of machine users to `owner` role

Kiran Kf7e3595bf504
diff --git a/apps/web/app/api/tokens/[id]/route.ts b/apps/web/app/api/tokens/[id]/route.ts
index 97ccfe3413..49bd13d970 100644
--- a/apps/web/app/api/tokens/[id]/route.ts
+++ b/apps/web/app/api/tokens/[id]/route.ts
@@ -1,4 +1,5 @@
import { DubApiError } from "@/lib/api/errors";
+import { getScopesByRole } from "@/lib/api/tokens/scopes";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
@@ -48,11 +49,32 @@ export const GET = withWorkspace(
// PATCH /api/tokens/:id - update a specific token
export const PATCH = withWorkspace(
- async ({ workspace, params, req }) => {
+ async ({ workspace, params, req, session }) => {
const { name, scopes } = updateTokenSchema.parse(
await parseRequestBody(req),
);
+ const { role } = await prisma.projectUsers.findUniqueOrThrow({
+ where: {
+ userId_projectId: {
+ userId: session.user.id,
+ projectId: workspace.id,
+ },
+ },
+ select: {
+ role: true,
+ },
+ });
+
+ // Check given scopes are valid based on user's role
+ const userScopes = getScopesByRole(role);
+ if (scopes && scopes.every((scope) => !userScopes.includes(scope))) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "Some of the given scopes are not available for your role.",
+ });
+ }
+
const token = await prisma.restrictedToken.update({
where: {
id: params.id,
diff --git a/apps/web/app/api/tokens/route.ts b/apps/web/app/api/tokens/route.ts
index 09035ea2cf..ca176b88db 100644
--- a/apps/web/app/api/tokens/route.ts
+++ b/apps/web/app/api/tokens/route.ts
@@ -1,4 +1,5 @@
-import { scopesToName } from "@/lib/api/tokens/scopes";
+import { DubApiError } from "@/lib/api/errors";
+import { getScopesByRole, scopesToName } from "@/lib/api/tokens/scopes";
import { parseRequestBody } from "@/lib/api/utils";
import { hashToken, withWorkspace } from "@/lib/auth";
import { generateRandomName } from "@/lib/names";
@@ -20,6 +21,35 @@ export const POST = withWorkspace(
let machineUser: User | null = null;
+ const { role } = await prisma.projectUsers.findUniqueOrThrow({
+ where: {
+ userId_projectId: {
+ userId: session.user.id,
+ projectId: workspace.id,
+ },
+ },
+ select: {
+ role: true,
+ },
+ });
+
+ // Only workspace owners can create machine users
+ if (isMachine && role !== "owner") {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Only workspace owners can create machine users.",
+ });
+ }
+
+ // Check given scopes are valid based on user's role
+ const userScopes = getScopesByRole(role);
+ if (scopes && scopes.every((scope) => !userScopes.includes(scope))) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "Some of the given scopes are not available for your role.",
+ });
+ }
+
// Create machine user if needed
if (isMachine) {
const randomName = generateRandomName();
diff --git a/apps/web/lib/api/tokens/scopes.ts b/apps/web/lib/api/tokens/scopes.ts
index 2b740e435e..54c7af9a6a 100644
--- a/apps/web/lib/api/tokens/scopes.ts
+++ b/apps/web/lib/api/tokens/scopes.ts
@@ -148,27 +148,64 @@ export const resourcePermissions = [
},
],
},
-] as const;
+];
+
+// Get scopes by role
+export const getScopesByRole = (role: Role) => {
+ const scopes: string[] = ["apis.read", "apis.all"];
+
+ resourcePermissions.forEach((resource) => {
+ resource.permissions.forEach((permission) => {
+ if (permission.roles.includes(role)) {
+ scopes.push(permission.scope);
+ }
+ });
+ });
+
+ return scopes as Scope[];
+};
+
+// Get resource permissions by role
+export const getResourcePermissionsByRole = (role: Role) => {
+ return resourcePermissions
+ .map((resource) => {
+ const filteredPermissions = resource.permissions.filter((permission) =>
+ permission.roles.includes(role),
+ );
+
+ return {
+ ...resource,
+ permissions: filteredPermissions,
+ };
+ })
+ .filter((resource) => resource.permissions.length > 0);
+};
+
+// Expand the scopes to include all the required scopes
+export const normalizeScopes = (scopes: string[]): Scope[] => {
+ return (scopes || [])
+ .map((scope: Scope) => scopeMapping[scope] || scope)
+ .flat();
+};
-// Map roles to scopes
-// { owner: ["workspace.write"], member: ["workspace.read"] }
-export const roleScopesMapping = resourcePermissions.reduce<
- Record<Role, Scope[]>
+// Role permissions for each resource
+export const rolePermissionsMapping = resourcePermissions.reduce<
+ Record<Role, Record<string, boolean>>
>(
(acc, { permissions }) => {
- permissions.forEach(({ scope, roles }) => {
+ permissions.forEach(({ permission, roles }) => {
roles.forEach((role) => {
if (!acc[role]) {
- acc[role] = [];
+ acc[role] = {};
}
- acc[role].push(scope);
+ acc[role][permission] = true;
});
});
return acc;
},
- {} as Record<Role, Scope[]>,
+ {} as Record<Role, Record<string, boolean>>,
);
export const scopeMapping = {
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index 9bb76fd438..609b0fd8bb 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -102,12 +102,14 @@ model RestrictedToken {
updatedAt DateTime @updatedAt
userId String
projectId String
+ createdBy String? // user who created the token
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
@@index([userId])
@@index([projectId])
+ @@index([createdBy])
}
model Project {
diff --git a/apps/web/ui/modals/add-edit-token-modal.tsx b/apps/web/ui/modals/add-edit-token-modal.tsx
index 028c357d65..59c94bbb86 100644
--- a/apps/web/ui/modals/add-edit-token-modal.tsx
+++ b/apps/web/ui/modals/add-edit-token-modal.tsx
@@ -1,6 +1,6 @@
import {
Scope,
- resourcePermissions,
+ getResourcePermissionsByRole,
scopePresets,
} from "@/lib/api/tokens/scopes";
import useWorkspace from "@/lib/swr/use-workspace";
@@ -18,6 +18,7 @@ import {
} from "@dub/ui";
import { ToggleGroup } from "@dub/ui/src/toggle-group";
import { SimpleTooltipContent } from "@dub/ui/src/tooltip";
+import { cn } from "@dub/utils";
import {
Dispatch,
FormEvent,
@@ -57,7 +58,7 @@ function AddEditTokenModal({
onTokenCreated?: (token: string) => void;
}) {
const [saving, setSaving] = useState(false);
- const { id: workspaceId, logo, slug, betaTester } = useWorkspace();
+ const { id: workspaceId, logo, slug, betaTester, isOwner } = useWorkspace();
const [data, setData] = useState<APIKeyProps>(token || newToken);
const [preset, setPreset] = useState<ScopePreset>("all_access");
@@ -123,6 +124,9 @@ function AddEditTokenModal({
const { name, scopes } = data;
const buttonDisabled =
(!name || token?.name === name) && token?.scopes === scopes;
+ const resourcePermissions = getResourcePermissionsByRole(
+ isOwner ? "owner" : "member",
+ );
return (
<>
@@ -181,11 +185,19 @@ function AddEditTokenModal({
/>
</Label>
</div>
- <div className="flex w-1/2 items-center space-x-2 rounded-md border border-gray-300 bg-white transition-all hover:bg-gray-50 active:bg-gray-100">
+ <div
+ className={cn(
+ "flex w-1/2 items-center space-x-2 rounded-md border border-gray-300 bg-white transition-all hover:bg-gray-50 active:bg-gray-100",
+ {
+ "opacity-50": !isOwner,
+ },
+ )}
+ >
<RadioGroupItem
value="machine"
id="machine"
className="ml-3"
+ disabled={!isOwner}
/>
<Label
htmlFor="machine"
@@ -195,7 +207,11 @@ function AddEditTokenModal({
<InfoTooltip
content={
<SimpleTooltipContent
- title="A new bot member will be added to your workspace, and the key will be associated with it. Since the key is not tied to your account, it will not be deleted even if you leave the workspace."
+ title={
+ isOwner
+ ? "A new bot member will be added to your workspace, and the key will be associated with it. Since the key is not tied to your account, it will not be deleted even if you leave the workspace."
+ : "Only the workspace owner can create machine users."
+ }
cta="Learn more"
href="https://dub.co/docs/api-reference/tokens#machine-users"
/>