feat(auth): add WorkOS and Keycloak SSO providers (rebased) (#220)
Some checks failed
ci/woodpecker/push/ci Pipeline failed

Co-authored-by: Jason Woltje <jason@diversecanvas.com>
Co-committed-by: Jason Woltje <jason@diversecanvas.com>
This commit was merged in pull request #220.
This commit is contained in:
2026-03-21 12:57:07 +00:00
committed by jason.woltje
parent f3e90df2a0
commit dd108b9ab4
16 changed files with 724 additions and 176 deletions

View File

@@ -1,17 +1,27 @@
'use client';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { signIn } from '@/lib/auth-client';
import { getEnabledSsoProviders } from '@/lib/sso-providers';
import Link from 'next/link';
import { api } from '@/lib/api';
import { authClient, signIn } from '@/lib/auth-client';
import type { SsoProviderDiscovery } from '@/lib/sso';
import { SsoProviderButtons } from '@/components/auth/sso-provider-buttons';
export default function LoginPage(): React.ReactElement {
const router = useRouter();
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const ssoProviders = getEnabledSsoProviders();
const hasSsoProviders = ssoProviders.length > 0;
const [ssoProviders, setSsoProviders] = useState<SsoProviderDiscovery[]>([]);
const [ssoLoadingProviderId, setSsoLoadingProviderId] = useState<
SsoProviderDiscovery['id'] | null
>(null);
useEffect(() => {
api<SsoProviderDiscovery[]>('/api/sso/providers')
.catch(() => [] as SsoProviderDiscovery[])
.then((providers) => setSsoProviders(providers.filter((provider) => provider.configured)));
}, []);
async function handleSubmit(e: React.FormEvent<HTMLFormElement>): Promise<void> {
e.preventDefault();
@@ -33,6 +43,27 @@ export default function LoginPage(): React.ReactElement {
router.push('/chat');
}
async function handleSsoSignIn(providerId: SsoProviderDiscovery['id']): Promise<void> {
setError(null);
setSsoLoadingProviderId(providerId);
try {
const result = await authClient.signIn.oauth2({
providerId,
callbackURL: '/chat',
newUserCallbackURL: '/chat',
});
if (result.error) {
setError(result.error.message ?? `Sign in with ${providerId} failed`);
setSsoLoadingProviderId(null);
}
} catch (err: unknown) {
setError(err instanceof Error ? err.message : `Sign in with ${providerId} failed`);
setSsoLoadingProviderId(null);
}
}
return (
<div>
<h1 className="text-2xl font-semibold">Sign in</h1>
@@ -47,26 +78,7 @@ export default function LoginPage(): React.ReactElement {
</div>
)}
{hasSsoProviders && (
<div className="mt-6 space-y-3">
{ssoProviders.map((provider) => (
<Link
key={provider.id}
href={provider.href}
className="flex w-full items-center justify-center gap-2 rounded-lg border border-surface-border bg-surface-elevated px-4 py-2.5 text-sm font-medium text-text-primary transition-colors hover:bg-surface-hover focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-surface-card"
>
{provider.buttonLabel}
</Link>
))}
<div className="relative flex items-center">
<div className="flex-1 border-t border-surface-border" />
<span className="mx-3 text-xs text-text-muted">or</span>
<div className="flex-1 border-t border-surface-border" />
</div>
</div>
)}
<form className={hasSsoProviders ? 'space-y-4' : 'mt-6 space-y-4'} onSubmit={handleSubmit}>
<form className="mt-6 space-y-4" onSubmit={handleSubmit}>
<div>
<label htmlFor="email" className="block text-sm font-medium text-text-secondary">
Email
@@ -108,6 +120,14 @@ export default function LoginPage(): React.ReactElement {
</button>
</form>
<SsoProviderButtons
providers={ssoProviders}
loadingProviderId={ssoLoadingProviderId}
onOidcSignIn={(providerId) => {
void handleSsoSignIn(providerId);
}}
/>
<p className="mt-4 text-center text-sm text-text-muted">
Don&apos;t have an account?{' '}
<Link href="/register" className="text-blue-400 hover:text-blue-300">

View File

@@ -3,6 +3,8 @@
import { useCallback, useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { authClient, useSession } from '@/lib/auth-client';
import type { SsoProviderDiscovery } from '@/lib/sso';
import { SsoProviderSection } from '@/components/settings/sso-provider-section';
// ─── Types ────────────────────────────────────────────────────────────────────
@@ -424,7 +426,9 @@ function NotificationsTab(): React.ReactElement {
function ProvidersTab(): React.ReactElement {
const [providers, setProviders] = useState<ProviderInfo[]>([]);
const [ssoProviders, setSsoProviders] = useState<SsoProviderDiscovery[]>([]);
const [loading, setLoading] = useState(true);
const [ssoLoading, setSsoLoading] = useState(true);
const [testStatuses, setTestStatuses] = useState<Record<string, ProviderTestStatus>>({});
useEffect(() => {
@@ -434,6 +438,13 @@ function ProvidersTab(): React.ReactElement {
.finally(() => setLoading(false));
}, []);
useEffect(() => {
api<SsoProviderDiscovery[]>('/api/sso/providers')
.catch(() => [] as SsoProviderDiscovery[])
.then((providers) => setSsoProviders(providers))
.finally(() => setSsoLoading(false));
}, []);
const testConnection = useCallback(async (providerId: string): Promise<void> => {
setTestStatuses((prev) => ({
...prev,
@@ -464,35 +475,44 @@ function ProvidersTab(): React.ReactElement {
.find((m) => providers.find((p) => p.id === m.provider)?.available);
return (
<section className="space-y-4">
<h2 className="text-lg font-medium text-text-secondary">LLM Providers</h2>
{loading ? (
<p className="text-sm text-text-muted">Loading providers...</p>
) : providers.length === 0 ? (
<div className="rounded-lg border border-surface-border bg-surface-card p-4">
<p className="text-sm text-text-muted">
No providers configured. Set{' '}
<code className="rounded bg-surface-elevated px-1 py-0.5 text-xs">OLLAMA_BASE_URL</code>{' '}
or{' '}
<code className="rounded bg-surface-elevated px-1 py-0.5 text-xs">
MOSAIC_CUSTOM_PROVIDERS
</code>{' '}
to add providers.
</p>
</div>
) : (
<div className="space-y-4">
{providers.map((provider) => (
<ProviderCard
key={provider.id}
provider={provider}
defaultModel={defaultModel}
testStatus={testStatuses[provider.id] ?? { state: 'idle' }}
onTest={() => void testConnection(provider.id)}
/>
))}
</div>
)}
<section className="space-y-6">
<div className="space-y-4">
<h2 className="text-lg font-medium text-text-secondary">SSO Providers</h2>
<SsoProviderSection providers={ssoProviders} loading={ssoLoading} />
</div>
<div className="space-y-4">
<h2 className="text-lg font-medium text-text-secondary">LLM Providers</h2>
{loading ? (
<p className="text-sm text-text-muted">Loading providers...</p>
) : providers.length === 0 ? (
<div className="rounded-lg border border-surface-border bg-surface-card p-4">
<p className="text-sm text-text-muted">
No providers configured. Set{' '}
<code className="rounded bg-surface-elevated px-1 py-0.5 text-xs">
OLLAMA_BASE_URL
</code>{' '}
or{' '}
<code className="rounded bg-surface-elevated px-1 py-0.5 text-xs">
MOSAIC_CUSTOM_PROVIDERS
</code>{' '}
to add providers.
</p>
</div>
) : (
<div className="space-y-4">
{providers.map((provider) => (
<ProviderCard
key={provider.id}
provider={provider}
defaultModel={defaultModel}
testStatus={testStatuses[provider.id] ?? { state: 'idle' }}
onTest={() => void testConnection(provider.id)}
/>
))}
</div>
)}
</div>
</section>
);
}

View File

@@ -0,0 +1,45 @@
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { SsoProviderButtons } from './sso-provider-buttons.js';
describe('SsoProviderButtons', () => {
it('renders OIDC sign-in buttons and SAML fallback links', () => {
const html = renderToStaticMarkup(
<SsoProviderButtons
providers={[
{
id: 'workos',
name: 'WorkOS',
protocols: ['oidc'],
configured: true,
loginMode: 'oidc',
callbackPath: '/api/auth/oauth2/callback/workos',
teamSync: { enabled: true, claim: 'organization_id' },
samlFallback: { configured: false, loginUrl: null },
warnings: [],
},
{
id: 'keycloak',
name: 'Keycloak',
protocols: ['oidc', 'saml'],
configured: true,
loginMode: 'saml',
callbackPath: null,
teamSync: { enabled: true, claim: 'groups' },
samlFallback: {
configured: true,
loginUrl: 'https://sso.example.com/realms/mosaic/protocol/saml',
},
warnings: [],
},
]}
onOidcSignIn={vi.fn()}
/>,
);
expect(html).toContain('Continue with WorkOS');
expect(html).toContain('Continue with Keycloak (SAML)');
expect(html).toContain('https://sso.example.com/realms/mosaic/protocol/saml');
});
});

View File

@@ -0,0 +1,55 @@
import React from 'react';
import type { SsoProviderDiscovery } from '@/lib/sso';
interface SsoProviderButtonsProps {
providers: SsoProviderDiscovery[];
loadingProviderId?: string | null;
onOidcSignIn: (providerId: SsoProviderDiscovery['id']) => void;
}
export function SsoProviderButtons({
providers,
loadingProviderId = null,
onOidcSignIn,
}: SsoProviderButtonsProps): React.ReactElement | null {
const visibleProviders = providers.filter((provider) => provider.configured);
if (visibleProviders.length === 0) {
return null;
}
return (
<div className="mt-6 space-y-3 border-t border-surface-border pt-6">
<p className="text-sm font-medium text-text-secondary">Single sign-on</p>
<div className="space-y-3">
{visibleProviders.map((provider) => {
if (provider.loginMode === 'saml' && provider.samlFallback.loginUrl) {
return (
<a
key={provider.id}
href={provider.samlFallback.loginUrl}
className="flex w-full items-center justify-center rounded-lg border border-surface-border bg-surface-elevated px-4 py-2.5 text-sm font-medium text-text-primary transition-colors hover:border-accent/50 hover:text-accent"
>
Continue with {provider.name} (SAML)
</a>
);
}
return (
<button
key={provider.id}
type="button"
disabled={loadingProviderId === provider.id}
onClick={() => onOidcSignIn(provider.id)}
className="flex w-full items-center justify-center rounded-lg border border-surface-border bg-surface-elevated px-4 py-2.5 text-sm font-medium text-text-primary transition-colors hover:border-accent/50 hover:text-accent disabled:opacity-50"
>
{loadingProviderId === provider.id
? `Redirecting to ${provider.name}...`
: `Continue with ${provider.name}`}
</button>
);
})}
</div>
</div>
);
}

View File

@@ -0,0 +1,46 @@
import React from 'react';
import { describe, expect, it } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { SsoProviderSection } from './sso-provider-section.js';
describe('SsoProviderSection', () => {
it('renders configured providers with callback, sync, and fallback details', () => {
const html = renderToStaticMarkup(
<SsoProviderSection
loading={false}
providers={[
{
id: 'workos',
name: 'WorkOS',
protocols: ['oidc'],
configured: true,
loginMode: 'oidc',
callbackPath: '/api/auth/oauth2/callback/workos',
teamSync: { enabled: true, claim: 'organization_id' },
samlFallback: { configured: false, loginUrl: null },
warnings: [],
},
{
id: 'keycloak',
name: 'Keycloak',
protocols: ['oidc', 'saml'],
configured: true,
loginMode: 'saml',
callbackPath: null,
teamSync: { enabled: true, claim: 'groups' },
samlFallback: {
configured: true,
loginUrl: 'https://sso.example.com/realms/mosaic/protocol/saml',
},
warnings: [],
},
]}
/>,
);
expect(html).toContain('WorkOS');
expect(html).toContain('/api/auth/oauth2/callback/workos');
expect(html).toContain('Team sync claim: organization_id');
expect(html).toContain('SAML fallback: https://sso.example.com/realms/mosaic/protocol/saml');
});
});

View File

@@ -0,0 +1,67 @@
import React from 'react';
import type { SsoProviderDiscovery } from '@/lib/sso';
interface SsoProviderSectionProps {
providers: SsoProviderDiscovery[];
loading: boolean;
}
export function SsoProviderSection({
providers,
loading,
}: SsoProviderSectionProps): React.ReactElement {
if (loading) {
return <p className="text-sm text-text-muted">Loading SSO providers...</p>;
}
const configuredProviders = providers.filter((provider) => provider.configured);
if (providers.length === 0 || configuredProviders.length === 0) {
return (
<div className="rounded-lg border border-surface-border bg-surface-card p-4">
<p className="text-sm text-text-muted">
No SSO providers configured. Set WorkOS or Keycloak environment variables to enable SSO.
</p>
</div>
);
}
return (
<div className="space-y-4">
{configuredProviders.map((provider) => (
<div
key={provider.id}
className="rounded-lg border border-surface-border bg-surface-card p-4"
>
<div className="flex items-center justify-between gap-4">
<div>
<h3 className="text-sm font-medium text-text-primary">{provider.name}</h3>
<p className="text-xs text-text-muted">
{provider.protocols.join(' + ').toUpperCase()}
{provider.loginMode ? ` • primary ${provider.loginMode.toUpperCase()}` : ''}
</p>
</div>
<span className="rounded-full border border-accent/30 bg-accent/10 px-2 py-1 text-xs font-medium text-accent">
Enabled
</span>
</div>
<div className="mt-3 space-y-2 text-xs text-text-muted">
{provider.callbackPath && <p>Callback: {provider.callbackPath}</p>}
{provider.teamSync.enabled && provider.teamSync.claim && (
<p>Team sync claim: {provider.teamSync.claim}</p>
)}
{provider.samlFallback.configured && provider.samlFallback.loginUrl && (
<p>SAML fallback: {provider.samlFallback.loginUrl}</p>
)}
{provider.warnings.map((warning) => (
<p key={warning} className="text-warning">
{warning}
</p>
))}
</div>
</div>
))}
</div>
);
}

20
apps/web/src/lib/sso.ts Normal file
View File

@@ -0,0 +1,20 @@
export type SsoProtocol = 'oidc' | 'saml';
export type SsoLoginMode = 'oidc' | 'saml' | null;
export interface SsoProviderDiscovery {
id: 'authentik' | 'workos' | 'keycloak';
name: string;
protocols: SsoProtocol[];
configured: boolean;
loginMode: SsoLoginMode;
callbackPath: string | null;
teamSync: {
enabled: boolean;
claim: string | null;
};
samlFallback: {
configured: boolean;
loginUrl: string | null;
};
warnings: string[];
}