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.

Add SAML SSO enforcement for enterprise workspaces

Kiran Kf18b9de74192
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
index 63395ad0f5..212f355648 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
@@ -32,6 +32,7 @@ const updateWorkspaceSchema = createWorkspaceSchema
z.null(),
])
.optional(),
+ enforceSAML: z.boolean().optional(),
})
.partial();
@@ -75,7 +76,7 @@ export const GET = withWorkspace(
// PATCH /api/workspaces/[idOrSlug] – update a specific workspace by id or slug
export const PATCH = withWorkspace(
- async ({ req, workspace }) => {
+ async ({ req, workspace, session }) => {
const {
name,
slug,
@@ -83,6 +84,7 @@ export const PATCH = withWorkspace(
conversionEnabled,
allowedHostnames,
publishableKey,
+ enforceSAML,
} = await updateWorkspaceSchema.parseAsync(await parseRequestBody(req));
if (["free", "pro"].includes(workspace.plan) && conversionEnabled) {
@@ -92,6 +94,13 @@ export const PATCH = withWorkspace(
});
}
+ if (enforceSAML && workspace.plan !== "enterprise") {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "SAML SSO is only available on enterprise plans.",
+ });
+ }
+
const validHostnames = allowedHostnames
? validateAllowedHostnames(allowedHostnames)
: undefined;
@@ -103,6 +112,26 @@ export const PATCH = withWorkspace(
)
: null;
+ // Handle SAML SSO enforcement
+ let ssoEmailDomain: string | null | undefined = undefined;
+ let ssoEnforcedAt: Date | null | undefined = undefined;
+
+ if (enforceSAML !== undefined) {
+ if (enforceSAML) {
+ ssoEmailDomain = session.user.email.split("@")[1];
+ ssoEnforcedAt = new Date();
+ } else {
+ ssoEnforcedAt = null;
+ ssoEmailDomain = null;
+ }
+
+ // Don't overwrite the SSO enforcement if it's already set
+ if (enforceSAML && workspace.ssoEnforcedAt) {
+ ssoEnforcedAt = undefined;
+ ssoEmailDomain = undefined;
+ }
+ }
+
try {
const response = await prisma.project.update({
where: {
@@ -117,6 +146,8 @@ export const PATCH = withWorkspace(
allowedHostnames: validHostnames,
}),
...(publishableKey !== undefined && { publishableKey }),
+ ...(enforceSAML !== undefined && { ssoEnforcedAt }),
+ ...(ssoEmailDomain !== undefined && { ssoEmailDomain }),
},
include: {
domains: {
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts
index 6a533c9a34..f5a5c9d62c 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/saml/route.ts
@@ -1,6 +1,7 @@
import { withWorkspace } from "@/lib/auth";
import { jackson, samlAudience } from "@/lib/jackson";
import z from "@/lib/zod";
+import { prisma } from "@dub/prisma";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { NextResponse } from "next/server";
@@ -76,7 +77,7 @@ export const POST = withWorkspace(
// DELETE /api/workspaces/[idOrSlug]/saml – delete all SAML connections
export const DELETE = withWorkspace(
- async ({ searchParams }) => {
+ async ({ searchParams, workspace }) => {
const { clientID, clientSecret } =
deleteSAMLConnectionSchema.parse(searchParams);
@@ -87,6 +88,16 @@ export const DELETE = withWorkspace(
clientSecret,
});
+ await prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ ssoEnforcedAt: null,
+ ssoEmailDomain: null,
+ },
+ });
+
return NextResponse.json({ response: "removed SAML connection" });
},
{
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/security/saml.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/security/saml.tsx
index e6a94b50c6..a80ccd6070 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/security/saml.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/security/saml.tsx
@@ -5,16 +5,19 @@ import useWorkspace from "@/lib/swr/use-workspace";
import { useRemoveSAMLModal } from "@/ui/modals/remove-saml-modal";
import { useSAMLModal } from "@/ui/modals/saml-modal";
import { ThreeDots } from "@/ui/shared/icons";
-import { Button, IconMenu, Popover, TooltipContent } from "@dub/ui";
+import { Button, IconMenu, Popover, Switch, TooltipContent } from "@dub/ui";
import { SAML_PROVIDERS } from "@dub/utils";
import { Lock, ShieldOff } from "lucide-react";
-import { useMemo, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
+import { toast } from "sonner";
export function SAML() {
- const { plan } = useWorkspace();
+ const { plan, id, name, ssoEnforcedAt, mutate } = useWorkspace();
const { SAMLModal, setShowSAMLModal } = useSAMLModal();
const { RemoveSAMLModal, setShowRemoveSAMLModal } = useRemoveSAMLModal();
const { provider, configured, loading } = useSAML();
+ const [openPopover, setOpenPopover] = useState(false);
+ const [isUpdating, setIsUpdating] = useState(false);
const currentProvider = useMemo(
() => provider && SAML_PROVIDERS.find((p) => p.name.startsWith(provider)),
@@ -54,7 +57,58 @@ export function SAML() {
}
}, [provider, configured, loading]);
- const [openPopover, setOpenPopover] = useState(false);
+ const updateWorkspace = useCallback(
+ async (data: any) => {
+ setIsUpdating(true);
+
+ try {
+ const response = await fetch(`/api/workspaces/${id}`, {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ });
+
+ if (response.ok) {
+ await mutate();
+ } else {
+ const { error } = await response.json();
+ throw new Error(error.message || "Failed to update workspace.");
+ }
+ } catch (error) {
+ throw error;
+ } finally {
+ setIsUpdating(false);
+ }
+ },
+ [id, mutate],
+ );
+
+ const handleSSOEnforcementChange = async (checked: boolean) => {
+ if (!configured) {
+ toast.error("Please configure SAML SSO first before enforcing it.");
+ return;
+ }
+
+ try {
+ await updateWorkspace({
+ enforceSAML: checked,
+ });
+
+ toast.success(
+ checked
+ ? "SAML SSO enforcement enabled."
+ : "SAML SSO enforcement disabled.",
+ );
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to update the setting.",
+ );
+ }
+ };
return (
<>
@@ -145,14 +199,30 @@ export function SAML() {
</div>
</div>
- <div className="flex items-center justify-between rounded-b-lg border-t border-neutral-200 bg-neutral-50 px-3 py-5 sm:px-10">
- <a
- href="https://dub.co/help/category/saml-sso"
- target="_blank"
- className="text-sm text-neutral-400 underline underline-offset-4 transition-colors hover:text-neutral-700"
- >
- Learn more about SAML SSO.
- </a>
+ <div className="rounded-b-lg border-t border-neutral-200 bg-neutral-50 px-3 py-5 sm:px-10">
+ {configured ? (
+ <div className="flex items-center justify-between">
+ <label className="text-sm font-medium text-neutral-700">
+ Require SAML SSO authentication for all members of the
+ workspace.
+ </label>
+ <Switch
+ checked={!!ssoEnforcedAt}
+ disabled={isUpdating || plan !== "enterprise"}
+ fn={handleSSOEnforcementChange}
+ />
+ </div>
+ ) : (
+ <div className="flex items-center justify-between">
+ <a
+ href="https://dub.co/help/category/saml-sso"
+ target="_blank"
+ className="text-sm text-neutral-400 underline underline-offset-4 transition-colors hover:text-neutral-700"
+ >
+ Learn more about SAML SSO.
+ </a>
+ </div>
+ )}
</div>
</div>
</>
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 35df3dfedf..2e6b8aeaae 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -211,6 +211,7 @@ export interface ExtendedWorkspaceProps extends WorkspaceProps {
workspacePreferences?: z.infer<typeof workspacePreferencesSchema>;
})[];
publishableKey: string | null;
+ ssoEnforcedAt: Date | null;
}
export type WorkspaceWithUsers = Omit<WorkspaceProps, "domains">;
diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.ts
index c7baaccf4c..9b966679e0 100644
--- a/apps/web/lib/zod/schemas/workspaces.ts
+++ b/apps/web/lib/zod/schemas/workspaces.ts
@@ -167,6 +167,7 @@ export const WorkspaceSchemaExtended = WorkspaceSchema.extend({
}),
),
publishableKey: z.string().nullable(),
+ ssoEnforcedAt: z.date().nullable(),
});
export const OnboardingUsageSchema = z.object({