feat: SSO & LDAP authentication for Team Pro (#209)

* feat: SSO & LDAP authentication for Team Pro

Add SSO integration allowing Team Pro users to authenticate via LDAP/Active Directory, Google, GitHub, and Okta identity providers. SSO works alongside password authentication with auto-provisioning and role mapping.

- LDAP bind+search authentication with group-based role mapping
- OIDC/OAuth2 flows with PKCE and CSRF protection for Google, GitHub, Okta
- Auto-provisioning: first SSO login creates a Sencho account automatically
- Role mapping via LDAP group membership or OIDC JWT claims
- SSO settings UI in Settings → SSO with per-provider config and test connection
- SSO login buttons on login page with LDAP toggle
- Environment variable seeding for infrastructure-as-code workflows
- Secrets encrypted at rest via CryptoService (AES-256-GCM)
- Seat limit enforcement during auto-provisioning
- Full documentation: feature docs, quickstart guides, env var reference

* fix: resolve ESLint errors in SSO feature

- Remove unnecessary escape characters in regex character classes
- Remove unused `issuer` variable from OIDC callback handler
- Fix setState-in-effect lint error in Login.tsx by using useState initializer
- Suppress set-state-in-effect for SSOSection fetch pattern (matches existing codebase convention)
This commit is contained in:
Anso
2026-03-28 03:30:01 -04:00
committed by GitHub
parent b429097fa2
commit bd4008f509
20 changed files with 2247 additions and 14 deletions
+103 -5
View File
@@ -1,26 +1,82 @@
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { useAuth } from '@/context/AuthContext';
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
interface SSOProvider {
provider: string;
displayName: string;
type: 'ldap' | 'oidc';
}
function getProviderIcon(provider: string) {
switch (provider) {
case 'oidc_google':
return (
<svg className="w-4 h-4 mr-2" viewBox="0 0 24 24" fill="currentColor">
<path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" />
<path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
<path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
<path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
</svg>
);
case 'oidc_github':
return (
<svg className="w-4 h-4 mr-2" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z" />
</svg>
);
case 'oidc_okta':
return (
<svg className="w-4 h-4 mr-2" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 0C5.389 0 0 5.389 0 12s5.389 12 12 12 12-5.389 12-12S18.611 0 12 0zm0 18c-3.314 0-6-2.686-6-6s2.686-6 6-6 6 2.686 6 6-2.686 6-6 6z" />
</svg>
);
default:
return null;
}
}
export function Login({
className,
...props
}: React.ComponentPropsWithoutRef<"div">) {
const { login } = useAuth();
const { login, ssoLdapLogin } = useAuth();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [error, setError] = useState(() => {
const params = new URLSearchParams(window.location.search);
const ssoError = params.get('sso_error');
if (ssoError) {
window.history.replaceState({}, '', window.location.pathname);
return ssoError;
}
return '';
});
const [isLoading, setIsLoading] = useState(false);
const [loginMode, setLoginMode] = useState<'local' | 'ldap'>('local');
const [ssoProviders, setSsoProviders] = useState<SSOProvider[]>([]);
useEffect(() => {
fetch('/api/auth/sso/providers', { credentials: 'include' })
.then(r => r.ok ? r.json() : [])
.then((providers: SSOProvider[]) => setSsoProviders(providers))
.catch(() => {});
}, []);
const hasLdap = ssoProviders.some(p => p.type === 'ldap');
const oidcProviders = ssoProviders.filter(p => p.type === 'oidc');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setIsLoading(true);
const result = await login(username, password);
const result = loginMode === 'ldap' && ssoLdapLogin
? await ssoLdapLogin(username, password)
: await login(username, password);
if (!result.success) {
setError(result.error || 'Login failed');
@@ -106,10 +162,52 @@ export function Login({
</div>
)}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? 'Logging in...' : 'Login'}
{isLoading
? 'Logging in...'
: loginMode === 'ldap'
? 'Sign in with LDAP'
: 'Login'
}
</Button>
{hasLdap && (
<button
type="button"
className="text-sm text-muted-foreground hover:text-foreground text-center transition-colors"
onClick={() => setLoginMode(loginMode === 'local' ? 'ldap' : 'local')}
>
{loginMode === 'local' ? 'Sign in with LDAP instead' : 'Sign in with password instead'}
</button>
)}
</div>
</form>
{oidcProviders.length > 0 && (
<>
<div className="relative my-6">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">Or continue with</span>
</div>
</div>
<div className="flex flex-col gap-2">
{oidcProviders.map(p => (
<Button
key={p.provider}
variant="outline"
className="w-full"
onClick={() => {
window.location.href = `/api/auth/sso/oidc/${p.provider}/authorize`;
}}
>
{getProviderIcon(p.provider)}
{p.displayName}
</Button>
))}
</div>
</>
)}
</div>
</div>
</div>
+365
View File
@@ -0,0 +1,365 @@
import { useState, useEffect } from 'react';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner';
import { apiFetch } from '@/lib/api';
import { ProGate } from './ProGate';
import { Shield, Loader2, CheckCircle, XCircle } from 'lucide-react';
interface SSOProviderConfig {
provider: string;
enabled: boolean;
displayName: string;
// LDAP
ldapUrl?: string;
ldapBindDn?: string;
ldapBindPassword?: string;
ldapSearchBase?: string;
ldapSearchFilter?: string;
ldapAdminGroupDn?: string;
ldapDefaultRole?: string;
ldapTlsRejectUnauthorized?: boolean;
// OIDC
oidcIssuerUrl?: string;
oidcClientId?: string;
oidcClientSecret?: string;
oidcScopes?: string;
oidcAdminClaim?: string;
oidcAdminClaimValue?: string;
oidcDefaultRole?: string;
}
const PROVIDERS = [
{ id: 'ldap', label: 'LDAP / Active Directory', type: 'ldap' as const },
{ id: 'oidc_google', label: 'Google', type: 'oidc' as const },
{ id: 'oidc_github', label: 'GitHub', type: 'oidc' as const },
{ id: 'oidc_okta', label: 'Okta', type: 'oidc' as const },
];
function ProviderCard({ providerId, type, label, initialConfig, onSave }: {
providerId: string;
type: 'ldap' | 'oidc';
label: string;
initialConfig: SSOProviderConfig | null;
onSave: () => void;
}) {
const [config, setConfig] = useState<Partial<SSOProviderConfig>>(initialConfig || { enabled: false });
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [testResult, setTestResult] = useState<{ success: boolean; error?: string } | null>(null);
const [expanded, setExpanded] = useState(!!initialConfig?.enabled);
const update = (field: string, value: string | boolean) => {
setConfig(prev => ({ ...prev, [field]: value }));
};
const handleSave = async () => {
setSaving(true);
try {
const body = {
...config,
provider: providerId,
displayName: config.displayName || label,
};
const res = await apiFetch(`/sso/config/${providerId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (res.ok) {
toast.success('SSO configuration saved');
onSave();
} else {
const data = await res.json();
toast.error(data?.error || data?.message || 'Failed to save');
}
} catch (error: unknown) {
toast.error((error as Error)?.message || 'Failed to save SSO configuration');
} finally {
setSaving(false);
}
};
const handleTest = async () => {
setTesting(true);
setTestResult(null);
try {
const res = await apiFetch(`/sso/config/${providerId}/test`, { method: 'POST' });
const data = await res.json();
setTestResult(data);
if (data.success) {
toast.success('Connection successful');
} else {
toast.error(data.error || 'Connection failed');
}
} catch {
setTestResult({ success: false, error: 'Connection test failed' });
} finally {
setTesting(false);
}
};
const handleDelete = async () => {
try {
const res = await apiFetch(`/sso/config/${providerId}`, { method: 'DELETE' });
if (res.ok) {
toast.success('SSO provider removed');
setConfig({ enabled: false });
setExpanded(false);
onSave();
}
} catch {
toast.error('Failed to remove provider');
}
};
return (
<div className="border border-border rounded-lg">
<div
className="flex items-center justify-between p-4 cursor-pointer hover:bg-muted/30 transition-colors"
onClick={() => setExpanded(!expanded)}
>
<div className="flex items-center gap-3">
<span className="font-medium text-sm">{label}</span>
{initialConfig?.enabled && (
<Badge variant="secondary" className="text-xs bg-green-500/10 text-green-500 border-green-500/20">
Active
</Badge>
)}
</div>
<div className="flex items-center gap-2">
<Switch
checked={!!config.enabled}
onCheckedChange={(checked) => update('enabled', checked)}
onClick={(e) => e.stopPropagation()}
/>
</div>
</div>
{expanded && (
<div className="border-t border-border p-4 space-y-4">
{type === 'ldap' ? (
<>
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Server URL</Label>
<Input
placeholder="ldap://ldap.example.com:389"
value={config.ldapUrl || ''}
onChange={e => update('ldapUrl', e.target.value)}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Bind DN</Label>
<Input
placeholder="cn=readonly,dc=example,dc=com"
value={config.ldapBindDn || ''}
onChange={e => update('ldapBindDn', e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Bind Password</Label>
<Input
type="password"
placeholder="Enter to update"
value={config.ldapBindPassword || ''}
onChange={e => update('ldapBindPassword', e.target.value)}
/>
</div>
</div>
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Search Base</Label>
<Input
placeholder="ou=users,dc=example,dc=com"
value={config.ldapSearchBase || ''}
onChange={e => update('ldapSearchBase', e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Search Filter</Label>
<Input
placeholder="(uid={{username}})"
value={config.ldapSearchFilter || ''}
onChange={e => update('ldapSearchFilter', e.target.value)}
/>
<p className="text-xs text-muted-foreground">
Use <code className="bg-muted px-1 rounded">{'{{username}}'}</code> as placeholder.
For Active Directory: <code className="bg-muted px-1 rounded">{'(sAMAccountName={{username}})'}</code>
</p>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Admin Group DN</Label>
<Input
placeholder="cn=sencho-admins,ou=groups,dc=..."
value={config.ldapAdminGroupDn || ''}
onChange={e => update('ldapAdminGroupDn', e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Default Role</Label>
<Select
value={config.ldapDefaultRole || 'viewer'}
onValueChange={v => update('ldapDefaultRole', v)}
>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="viewer">Viewer</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="flex items-center gap-2">
<Switch
checked={config.ldapTlsRejectUnauthorized !== false}
onCheckedChange={checked => update('ldapTlsRejectUnauthorized', checked)}
/>
<Label className="text-xs text-muted-foreground">Verify TLS certificate</Label>
</div>
</>
) : (
<>
{providerId === 'oidc_okta' && (
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Issuer URL</Label>
<Input
placeholder="https://dev-123456.okta.com"
value={config.oidcIssuerUrl || ''}
onChange={e => update('oidcIssuerUrl', e.target.value)}
/>
</div>
)}
<div className="grid grid-cols-2 gap-3">
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Client ID</Label>
<Input
placeholder="Client ID"
value={config.oidcClientId || ''}
onChange={e => update('oidcClientId', e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Client Secret</Label>
<Input
type="password"
placeholder="Enter to update"
value={config.oidcClientSecret || ''}
onChange={e => update('oidcClientSecret', e.target.value)}
/>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Admin Claim</Label>
<Input
placeholder="groups"
value={config.oidcAdminClaim || ''}
onChange={e => update('oidcAdminClaim', e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Admin Claim Value</Label>
<Input
placeholder="sencho-admins"
value={config.oidcAdminClaimValue || ''}
onChange={e => update('oidcAdminClaimValue', e.target.value)}
/>
</div>
</div>
<div className="grid gap-2">
<Label className="text-xs text-muted-foreground">Default Role</Label>
<Select
value={config.oidcDefaultRole || 'viewer'}
onValueChange={v => update('oidcDefaultRole', v)}
>
<SelectTrigger className="w-[140px]"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="viewer">Viewer</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
</SelectContent>
</Select>
</div>
</>
)}
<div className="flex items-center justify-between pt-2">
<div className="flex items-center gap-2">
<Button size="sm" onClick={handleSave} disabled={saving}>
{saving ? <><Loader2 className="w-3 h-3 mr-1 animate-spin" /> Saving...</> : 'Save'}
</Button>
<Button size="sm" variant="outline" onClick={handleTest} disabled={testing}>
{testing ? <><Loader2 className="w-3 h-3 mr-1 animate-spin" /> Testing...</> : 'Test Connection'}
</Button>
{testResult && (
testResult.success
? <CheckCircle className="w-4 h-4 text-green-500" />
: <XCircle className="w-4 h-4 text-red-500" />
)}
</div>
{initialConfig && (
<Button size="sm" variant="ghost" className="text-red-500 hover:text-red-400" onClick={handleDelete}>
Remove
</Button>
)}
</div>
</div>
)}
</div>
);
}
export function SSOSection() {
const [configs, setConfigs] = useState<SSOProviderConfig[]>([]);
const fetchConfigs = async () => {
try {
const res = await apiFetch('/sso/config');
if (res.ok) setConfigs(await res.json());
} catch { /* ignore - ProGate will handle non-pro */ }
};
// eslint-disable-next-line react-hooks/set-state-in-effect
useEffect(() => { fetchConfigs(); }, []);
const getConfig = (provider: string) => configs.find(c => c.provider === provider) || null;
return (
<ProGate featureName="SSO Authentication">
<div className="space-y-6">
<div>
<h3 className="text-lg font-semibold tracking-tight flex items-center gap-2">
<Shield className="w-5 h-5" />
SSO Authentication
</h3>
<p className="text-sm text-muted-foreground mt-1">
Connect your identity provider so team members can sign in with their existing credentials.
SSO works alongside password authentication it does not replace it.
</p>
</div>
<div className="space-y-3">
{PROVIDERS.map(p => (
<ProviderCard
key={p.id}
providerId={p.id}
type={p.type}
label={p.label}
initialConfig={getConfig(p.id)}
onSave={fetchConfigs}
/>
))}
</div>
<div className="text-xs text-muted-foreground space-y-1">
<p>SSO users are automatically provisioned on first login and assigned a role based on your identity provider's group membership.</p>
<p>For OIDC providers, set the OAuth callback URL to: <code className="bg-muted px-1 rounded">{'https://<your-sencho-url>/api/auth/sso/oidc/<provider>/callback'}</code></p>
</div>
</div>
</ProGate>
);
}
+10 -2
View File
@@ -27,6 +27,7 @@ import { useAuth } from '@/context/AuthContext';
import { useLicense } from '@/context/LicenseContext';
import { TierBadge } from './TierBadge';
import { ProGate } from './ProGate';
import { SSOSection } from './SSOSection';
interface Agent {
type: 'discord' | 'slack' | 'webhook';
@@ -48,7 +49,7 @@ interface PatchableSettings {
log_retention_days?: string;
}
type SectionId = 'account' | 'license' | 'users' | 'system' | 'notifications' | 'webhooks' | 'developer' | 'nodes' | 'appstore' | 'support' | 'about';
type SectionId = 'account' | 'license' | 'users' | 'sso' | 'system' | 'notifications' | 'webhooks' | 'developer' | 'nodes' | 'appstore' | 'support' | 'about';
interface WebhookItem {
id: number;
@@ -656,7 +657,7 @@ export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
// When switching to a remote node, reset to a node-scoped section if on a global-only one
useEffect(() => {
if (isRemote && (activeSection === 'account' || activeSection === 'license' || activeSection === 'users' || activeSection === 'notifications' || activeSection === 'webhooks' || activeSection === 'nodes' || activeSection === 'appstore')) {
if (isRemote && (activeSection === 'account' || activeSection === 'license' || activeSection === 'users' || activeSection === 'sso' || activeSection === 'notifications' || activeSection === 'webhooks' || activeSection === 'nodes' || activeSection === 'appstore')) {
setActiveSection('system');
}
}, [isRemote]); // eslint-disable-line react-hooks/exhaustive-deps
@@ -997,6 +998,9 @@ export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
{!isRemote && isAdmin && (
<NavButton section="users" icon={<Users className="w-4 h-4 mr-2" />} label="Users" />
)}
{!isRemote && isAdmin && (
<NavButton section="sso" icon={<Shield className="w-4 h-4 mr-2" />} label="SSO" />
)}
<NavButton
section="system"
icon={<Activity className="w-4 h-4 mr-2" />}
@@ -1452,6 +1456,10 @@ export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
<UsersSection />
)}
{activeSection === 'sso' && (
<SSOSection />
)}
{activeSection === 'developer' && (
<div className="space-y-6">
<div className="flex items-start justify-between pr-8">