Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

feat(sso): add SAML 2.0 and multi-provider SSO support

rcourtman97701297c461
diff --git a/frontend-modern/src/components/Settings/SSOProvidersPanel.tsx b/frontend-modern/src/components/Settings/SSOProvidersPanel.tsx
new file mode 100644
index 0000000000..a8895fe20a
--- /dev/null
+++ b/frontend-modern/src/components/Settings/SSOProvidersPanel.tsx
@@ -0,0 +1,1220 @@
+import { Component, Show, For, createSignal, onMount, createMemo } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { Card } from '@/components/shared/Card';
+import { SectionHeader } from '@/components/shared/SectionHeader';
+import { Toggle } from '@/components/shared/Toggle';
+import { formField, labelClass, controlClass, formHelpText } from '@/components/shared/Form';
+import { notificationStore } from '@/stores/notifications';
+import { logger } from '@/utils/logger';
+import { hasFeature, loadLicenseStatus } from '@/stores/license';
+import Plus from 'lucide-solid/icons/plus';
+import Pencil from 'lucide-solid/icons/pencil';
+import Trash2 from 'lucide-solid/icons/trash-2';
+import Shield from 'lucide-solid/icons/shield';
+import Key from 'lucide-solid/icons/key';
+import Globe from 'lucide-solid/icons/globe';
+import Copy from 'lucide-solid/icons/copy';
+import ExternalLink from 'lucide-solid/icons/external-link';
+import CheckCircle from 'lucide-solid/icons/check-circle';
+import XCircle from 'lucide-solid/icons/x-circle';
+import Eye from 'lucide-solid/icons/eye';
+import X from 'lucide-solid/icons/x';
+
+// Types
+interface SSOProvider {
+ id: string;
+ name: string;
+ type: 'oidc' | 'saml';
+ enabled: boolean;
+ displayName?: string;
+ iconUrl?: string;
+ priority: number;
+ oidcIssuerUrl?: string;
+ oidcClientId?: string;
+ oidcClientSecretSet?: boolean;
+ samlIdpEntityId?: string;
+ samlSpEntityId?: string;
+ samlMetadataUrl?: string;
+ samlAcsUrl?: string;
+ allowedGroups?: string[];
+ allowedDomains?: string[];
+ allowedEmails?: string[];
+}
+
+interface SSOProvidersResponse {
+ providers: SSOProvider[];
+ defaultProviderId?: string;
+ allowMultipleProviders: boolean;
+}
+
+// Test connection response
+interface TestResult {
+ success: boolean;
+ message: string;
+ error?: string;
+ details?: {
+ type: string;
+ entityId?: string;
+ ssoUrl?: string;
+ sloUrl?: string;
+ tokenEndpoint?: string;
+ userinfoEndpoint?: string;
+ certificates?: Array<{
+ subject: string;
+ issuer: string;
+ notBefore: string;
+ notAfter: string;
+ isExpired: boolean;
+ }>;
+ };
+}
+
+// Metadata preview response
+interface MetadataPreview {
+ xml: string;
+ parsed: {
+ entityId: string;
+ ssoUrl?: string;
+ sloUrl?: string;
+ certificates?: Array<{
+ subject: string;
+ notAfter: string;
+ isExpired?: boolean;
+ }>;
+ nameIdFormats?: string[];
+ };
+}
+
+// Provider form for creating/editing
+interface ProviderForm {
+ id: string;
+ name: string;
+ type: 'oidc' | 'saml';
+ enabled: boolean;
+ displayName: string;
+ priority: number;
+ // OIDC fields
+ oidcIssuerUrl: string;
+ oidcClientId: string;
+ oidcClientSecret: string;
+ oidcRedirectUrl: string;
+ oidcLogoutUrl: string;
+ oidcScopes: string;
+ // SAML fields
+ samlIdpMetadataUrl: string;
+ samlIdpMetadataXml: string;
+ samlIdpSsoUrl: string;
+ samlIdpEntityId: string;
+ samlIdpCertificate: string;
+ samlSpEntityId: string;
+ samlSignRequests: boolean;
+ samlAllowIdpInitiated: boolean;
+ samlUsernameAttr: string;
+ samlEmailAttr: string;
+ samlGroupsAttr: string;
+ // Common
+ allowedGroups: string;
+ allowedDomains: string;
+ allowedEmails: string;
+ groupRoleMappings: string;
+}
+
+const emptyForm = (): ProviderForm => ({
+ id: '',
+ name: '',
+ type: 'oidc',
+ enabled: true,
+ displayName: '',
+ priority: 0,
+ oidcIssuerUrl: '',
+ oidcClientId: '',
+ oidcClientSecret: '',
+ oidcRedirectUrl: '',
+ oidcLogoutUrl: '',
+ oidcScopes: 'openid profile email',
+ samlIdpMetadataUrl: '',
+ samlIdpMetadataXml: '',
+ samlIdpSsoUrl: '',
+ samlIdpEntityId: '',
+ samlIdpCertificate: '',
+ samlSpEntityId: '',
+ samlSignRequests: false,
+ samlAllowIdpInitiated: false,
+ samlUsernameAttr: '',
+ samlEmailAttr: 'email',
+ samlGroupsAttr: '',
+ allowedGroups: '',
+ allowedDomains: '',
+ allowedEmails: '',
+ groupRoleMappings: '',
+});
+
+const listToString = (values?: string[]) => (values && values.length > 0 ? values.join(', ') : '');
+const splitList = (input: string) =>
+ input
+ .split(/[,\s]+/)
+ .map((v) => v.trim())
+ .filter(Boolean);
+
+const mappingsToString = (mappings?: Record<string, string>) =>
+ mappings ? Object.entries(mappings).map(([k, v]) => `${k}=${v}`).join(', ') : '';
+
+const stringToMappings = (input: string) => {
+ const result: Record<string, string> = {};
+ splitList(input).forEach(pair => {
+ const [k, v] = pair.split('=').map(s => s.trim());
+ if (k && v) result[k] = v;
+ });
+ return result;
+};
+
+interface Props {
+ onConfigUpdated?: () => void;
+}
+
+export const SSOProvidersPanel: Component<Props> = (props) => {
+ const [providers, setProviders] = createSignal<SSOProvider[]>([]);
+ const [loading, setLoading] = createSignal(true);
+ const [saving, setSaving] = createSignal(false);
+ const [showModal, setShowModal] = createSignal(false);
+ const [editingProvider, setEditingProvider] = createSignal<SSOProvider | null>(null);
+ const [form, setForm] = createStore<ProviderForm>(emptyForm());
+ const [advancedOpen, setAdvancedOpen] = createSignal(false);
+ const [deleteConfirm, setDeleteConfirm] = createSignal<string | null>(null);
+ const [publicUrl, setPublicUrl] = createSignal<string>('');
+
+ // Test connection state
+ const [testing, setTesting] = createSignal(false);
+ const [testResult, setTestResult] = createSignal<TestResult | null>(null);
+
+ // Metadata preview state
+ const [showMetadataPreview, setShowMetadataPreview] = createSignal(false);
+ const [metadataPreview, setMetadataPreview] = createSignal<MetadataPreview | null>(null);
+ const [loadingPreview, setLoadingPreview] = createSignal(false);
+
+ const hasAdvancedSSO = createMemo(() => hasFeature('advanced_sso'));
+
+ const loadProviders = async () => {
+ setLoading(true);
+ try {
+ const { apiFetch } = await import('@/utils/apiClient');
+ const response = await apiFetch('/api/security/sso/providers');
+ if (!response.ok) {
+ throw new Error(`Failed to load SSO providers (${response.status})`);
+ }
+ const data = (await response.json()) as SSOProvidersResponse;
+ setProviders(data.providers || []);
+
+ // Also get public URL for metadata display
+ const statusResp = await apiFetch('/api/security/status');
+ if (statusResp.ok) {
+ const status = await statusResp.json();
+ setPublicUrl(status.publicUrl || window.location.origin);
+ }
+ } catch (error) {
+ logger.error('[SSOProvidersPanel] Failed to load providers:', error);
+ notificationStore.error('Failed to load SSO providers');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ onMount(() => {
+ loadLicenseStatus();
+ loadProviders();
+ });
+
+ const openAddModal = (type: 'oidc' | 'saml') => {
+ setEditingProvider(null);
+ setForm(emptyForm());
+ setForm('type', type);
+ setAdvancedOpen(false);
+ setShowModal(true);
+ };
+
+ const openEditModal = async (provider: SSOProvider) => {
+ setEditingProvider(provider);
+ try {
+ const { apiFetch } = await import('@/utils/apiClient');
+ const response = await apiFetch(`/api/security/sso/providers/${provider.id}`);
+ if (!response.ok) throw new Error('Failed to load provider details');
+ const full = await response.json();
+
+ setForm({
+ id: full.id,
+ name: full.name,
+ type: full.type,
+ enabled: full.enabled,
+ displayName: full.displayName || '',
+ priority: full.priority || 0,
+ oidcIssuerUrl: full.oidc?.issuerUrl || '',
+ oidcClientId: full.oidc?.clientId || '',
+ oidcClientSecret: '',
+ oidcRedirectUrl: full.oidc?.redirectUrl || '',
+ oidcLogoutUrl: full.oidc?.logoutUrl || '',
+ oidcScopes: full.oidc?.scopes?.join(' ') || 'openid profile email',
+ samlIdpMetadataUrl: full.saml?.idpMetadataUrl || '',
+ samlIdpMetadataXml: full.saml?.idpMetadataXml || '',
+ samlIdpSsoUrl: full.saml?.idpSsoUrl || '',
+ samlIdpEntityId: full.saml?.idpEntityId || '',
+ samlIdpCertificate: full.saml?.idpCertificate || '',
+ samlSpEntityId: full.saml?.spEntityId || '',
+ samlSignRequests: full.saml?.signRequests || false,
+ samlAllowIdpInitiated: full.saml?.allowIdpInitiated || false,
+ samlUsernameAttr: full.saml?.usernameAttr || '',
+ samlEmailAttr: full.saml?.emailAttr || 'email',
+ samlGroupsAttr: full.saml?.groupsAttr || full.groupsClaim || '',
+ allowedGroups: listToString(full.allowedGroups),
+ allowedDomains: listToString(full.allowedDomains),
+ allowedEmails: listToString(full.allowedEmails),
+ groupRoleMappings: mappingsToString(full.groupRoleMappings),
+ });
+ setAdvancedOpen(false);
+ setShowModal(true);
+ } catch (error) {
+ logger.error('[SSOProvidersPanel] Failed to load provider for editing:', error);
+ notificationStore.error('Failed to load provider details');
+ }
+ };
+
+ const handleSave = async (e?: Event) => {
+ e?.preventDefault();
+ setSaving(true);
+
+ try {
+ const { apiFetch } = await import('@/utils/apiClient');
+ const isEdit = !!editingProvider();
+
+ // Build payload based on type
+ const payload: Record<string, unknown> = {
+ id: form.id || undefined,
+ name: form.name.trim(),
+ type: form.type,
+ enabled: form.enabled,
+ displayName: form.displayName.trim() || undefined,
+ priority: form.priority,
+ allowedGroups: splitList(form.allowedGroups),
+ allowedDomains: splitList(form.allowedDomains),
+ allowedEmails: splitList(form.allowedEmails),
+ groupRoleMappings: stringToMappings(form.groupRoleMappings),
+ };
+
+ if (form.type === 'oidc') {
+ payload.oidc = {
+ issuerUrl: form.oidcIssuerUrl.trim(),
+ clientId: form.oidcClientId.trim(),
+ clientSecret: form.oidcClientSecret.trim() || undefined,
+ redirectUrl: form.oidcRedirectUrl.trim() || undefined,
+ logoutUrl: form.oidcLogoutUrl.trim() || undefined,
+ scopes: splitList(form.oidcScopes),
+ };
+ payload.groupsClaim = form.samlGroupsAttr.trim() || undefined;
+ } else {
+ payload.saml = {
+ idpMetadataUrl: form.samlIdpMetadataUrl.trim() || undefined,
+ idpMetadataXml: form.samlIdpMetadataXml.trim() || undefined,
+ idpSsoUrl: form.samlIdpSsoUrl.trim() || undefined,
+ idpEntityId: form.samlIdpEntityId.trim() || undefined,
+ idpCertificate: form.samlIdpCertificate.trim() || undefined,
+ spEntityId: form.samlSpEntityId.trim() || undefined,
+ signRequests: form.samlSignRequests,
+ allowIdpInitiated: form.samlAllowIdpInitiated,
+ usernameAttr: form.samlUsernameAttr.trim() || undefined,
+ emailAttr: form.samlEmailAttr.trim() || undefined,
+ groupsAttr: form.samlGroupsAttr.trim() || undefined,
+ };
+ payload.groupsClaim = form.samlGroupsAttr.trim() || undefined;
+ }
+
+ const url = isEdit
+ ? `/api/security/sso/providers/${editingProvider()!.id}`
+ : '/api/security/sso/providers';
+
+ const response = await apiFetch(url, {
+ method: isEdit ? 'PUT' : 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+
+ if (!response.ok) {
+ const errText = await response.text();
+ throw new Error(errText || `Failed to save provider (${response.status})`);
+ }
+
+ notificationStore.success(isEdit ? 'Provider updated' : 'Provider created');
+ setShowModal(false);
+ loadProviders();
+ props.onConfigUpdated?.();
+ } catch (error) {
+ logger.error('[SSOProvidersPanel] Failed to save provider:', error);
+ notificationStore.error(`Failed to save provider: ${error}`);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const handleDelete = async (providerId: string) => {
+ try {
+ const { apiFetch } = await import('@/utils/apiClient');
+ const response = await apiFetch(`/api/security/sso/providers/${providerId}`, {
+ method: 'DELETE',
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to delete provider (${response.status})`);
+ }
+
+ notificationStore.success('Provider deleted');
+ setDeleteConfirm(null);
+ loadProviders();
+ props.onConfigUpdated?.();
+ } catch (error) {
+ logger.error('[SSOProvidersPanel] Failed to delete provider:', error);
+ notificationStore.error('Failed to delete provider');
+ }
+ };
+
+ const handleToggleEnabled = async (provider: SSOProvider) => {
+ try {
+ const { apiFetch } = await import('@/utils/apiClient');
+ const response = await apiFetch(`/api/security/sso/providers/${provider.id}`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ ...provider, enabled: !provider.enabled }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to update provider (${response.status})`);
+ }
+
+ notificationStore.success(provider.enabled ? 'Provider disabled' : 'Provider enabled');
+ loadProviders();
+ props.onConfigUpdated?.();
+ } catch (error) {
+ logger.error('[SSOProvidersPanel] Failed to toggle provider:', error);
+ notificationStore.error('Failed to update provider');
+ }
+ };
+
+ const copyToClipboard = (text: string, label: string) => {
+ navigator.clipboard.writeText(text);
+ notificationStore.success(`${label} copied to clipboard`);
+ };
+
+ // Test connection for current form configuration
+ const testConnection = async () => {
+ setTesting(true);
+ setTestResult(null);
+
+ try {
+ const { apiFetch } = await import('@/utils/apiClient');
+
+ const payload: Record<string, unknown> = {
+ type: form.type,
+ };
+
+ if (form.type === 'oidc') {
+ payload.oidc = {
+ issuerUrl: form.oidcIssuerUrl.trim(),
+ clientId: form.oidcClientId.trim() || undefined,
+ };
+ } else {
+ payload.saml = {
+ idpMetadataUrl: form.samlIdpMetadataUrl.trim() || undefined,
+ idpMetadataXml: form.samlIdpMetadataXml.trim() || undefined,
+ idpSsoUrl: form.samlIdpSsoUrl.trim() || undefined,
+ idpCertificate: form.samlIdpCertificate.trim() || undefined,
+ };
+ }
+
+ const response = await apiFetch('/api/security/sso/providers/test', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+
+ const result = (await response.json()) as TestResult;
+ setTestResult(result);
+
+ if (result.success) {
+ notificationStore.success('Connection test successful');
+ } else {
+ notificationStore.error(`Connection test failed: ${result.message}`);
+ }
+ } catch (error) {
+ logger.error('[SSOProvidersPanel] Test connection error:', error);
+ setTestResult({
+ success: false,
+ message: 'Failed to test connection',
+ error: String(error),
+ });
+ notificationStore.error('Failed to test connection');
+ } finally {
+ setTesting(false);
+ }
+ };
+
+ // Check if we have enough info to test
+ const canTest = () => {
+ if (form.type === 'oidc') {
+ return !!form.oidcIssuerUrl.trim();
+ }
+ return !!(
+ form.samlIdpMetadataUrl.trim() ||
+ form.samlIdpMetadataXml.trim() ||
+ form.samlIdpSsoUrl.trim()
+ );
+ };
+
+ // Fetch and preview metadata
+ const fetchMetadataPreview = async () => {
+ if (!form.samlIdpMetadataUrl.trim()) {
+ notificationStore.error('Please enter an IdP Metadata URL');
+ return;
+ }
+
+ setLoadingPreview(true);
+ setMetadataPreview(null);
+
+ try {
+ const { apiFetch } = await import('@/utils/apiClient');
+
+ const response = await apiFetch('/api/security/sso/providers/metadata/preview', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ type: 'saml',
+ metadataUrl: form.samlIdpMetadataUrl.trim(),
+ }),
+ });
+
+ if (!response.ok) {
+ const err = await response.text();
+ throw new Error(err || 'Failed to fetch metadata');
+ }
+
+ const preview = (await response.json()) as MetadataPreview;
+ setMetadataPreview(preview);
+ setShowMetadataPreview(true);
+ } catch (error) {
+ logger.error('[SSOProvidersPanel] Metadata preview error:', error);
+ notificationStore.error(`Failed to fetch metadata: ${error}`);
+ } finally {
+ setLoadingPreview(false);
+ }
+ };
+
+ return (
+ <div class="space-y-6">
+ {/* License banner */}
+ <Show when={!hasAdvancedSSO() && !loading()}>
+ <Card padding="md" class="bg-gradient-to-r from-indigo-50 to-purple-50 dark:from-indigo-900/20 dark:to-purple-900/20 border border-indigo-100 dark:border-indigo-800">
+ <div class="flex flex-col sm:flex-row items-center gap-4">
+ <div class="flex-1">
+ <h4 class="text-base font-semibold text-gray-900 dark:text-white">Advanced SSO</h4>
+ <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
+ SAML 2.0 and multi-provider SSO requires Pulse Pro. Basic OIDC is available in the free tier.
+ </p>
+ </div>
+ <a
+ href="https://pulserelay.pro/"
+ target="_blank"
+ class="px-5 py-2.5 text-sm font-semibold bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors flex items-center gap-2"
+ >
+ Upgrade to Pro
+ <ExternalLink class="w-4 h-4" />
+ </a>
+ </div>
+ </Card>
+ </Show>
+
+ {/* Main panel */}
+ <Card
+ padding="none"
+ class="overflow-hidden border border-gray-200 dark:border-gray-700"
+ border={false}
+ >
+ {/* Header */}
+ <div class="bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
+ <div class="flex items-center justify-between gap-3">
+ <div class="flex items-center gap-3">
+ <div class="p-2 bg-blue-100 dark:bg-blue-900/40 rounded-lg">
+ <Shield class="w-5 h-5 text-blue-600 dark:text-blue-300" strokeWidth={2} />
+ </div>
+ <SectionHeader
+ title="Single Sign-On Providers"
+ description="Configure OIDC and SAML identity providers"
+ size="sm"
+ class="flex-1"
+ />
+ </div>
+ <div class="flex gap-2">
+ <button
+ type="button"
+ onClick={() => openAddModal('oidc')}
+ class="px-3 py-1.5 text-sm font-medium bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-1.5"
+ >
+ <Plus class="w-4 h-4" />
+ Add OIDC
+ </button>
+ <Show when={hasAdvancedSSO()}>
+ <button
+ type="button"
+ onClick={() => openAddModal('saml')}
+ class="px-3 py-1.5 text-sm font-medium bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors flex items-center gap-1.5"
+ >
+ <Plus class="w-4 h-4" />
+ Add SAML
+ </button>
+ </Show>
+ </div>
+ </div>
+ </div>
+
+ {/* Content */}
+ <div class="p-6">
+ <Show when={loading()}>
+ <div class="flex items-center gap-3 text-sm text-gray-600 dark:text-gray-300">
+ <span class="h-4 w-4 border-2 border-current border-t-transparent rounded-full animate-spin" />
+ Loading SSO providers...
+ </div>
+ </Show>
+
+ <Show when={!loading() && providers().length === 0}>
+ <div class="text-center py-8 text-gray-500 dark:text-gray-400">
+ <Shield class="w-12 h-12 mx-auto mb-3 opacity-40" />
+ <p class="text-sm">No SSO providers configured</p>
+ <p class="text-xs mt-1">Click "Add OIDC" or "Add SAML" to get started</p>
+ </div>
+ </Show>
+
+ <Show when={!loading() && providers().length > 0}>
+ <div class="space-y-3">
+ <For each={providers()}>
+ {(provider) => (
+ <div class={`p-4 rounded-lg border ${provider.enabled ? 'bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700' : 'bg-gray-50 dark:bg-gray-800/50 border-gray-200 dark:border-gray-700 opacity-60'}`}>
+ <div class="flex items-center justify-between gap-4">
+ <div class="flex items-center gap-3 min-w-0">
+ <div class={`p-2 rounded-lg ${provider.type === 'oidc' ? 'bg-blue-100 dark:bg-blue-900/40' : 'bg-purple-100 dark:bg-purple-900/40'}`}>
+ {provider.type === 'oidc' ? (
+ <Globe class="w-5 h-5 text-blue-600 dark:text-blue-300" />
+ ) : (
+ <Key class="w-5 h-5 text-purple-600 dark:text-purple-300" />
+ )}
+ </div>
+ <div class="min-w-0">
+ <div class="flex items-center gap-2">
+ <span class="font-medium text-gray-900 dark:text-white truncate">
+ {provider.name}
+ </span>
+ <span class={`px-1.5 py-0.5 text-xs font-medium rounded ${provider.type === 'oidc' ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300' : 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300'}`}>
+ {provider.type.toUpperCase()}
+ </span>
+ </div>
+ <p class="text-xs text-gray-500 dark:text-gray-400 truncate">
+ {provider.type === 'oidc'
+ ? provider.oidcIssuerUrl
+ : provider.samlIdpEntityId || provider.samlMetadataUrl}
+ </p>
+ </div>
+ </div>
+ <div class="flex items-center gap-2">
+ <Toggle
+ checked={provider.enabled}
+ onChange={() => handleToggleEnabled(provider)}
+ containerClass="items-center"
+ />
+ <button
+ type="button"
+ onClick={() => openEditModal(provider)}
+ class="p-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-colors"
+ title="Edit provider"
+ >
+ <Pencil class="w-4 h-4" />
+ </button>
+ <button
+ type="button"
+ onClick={() => setDeleteConfirm(provider.id)}
+ class="p-2 text-gray-500 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
+ title="Delete provider"
+ >
+ <Trash2 class="w-4 h-4" />
+ </button>
+ </div>
+ </div>
+
+ {/* SAML metadata info */}
+ <Show when={provider.type === 'saml' && provider.enabled}>
+ <div class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">
+ <div class="flex flex-wrap gap-4 text-xs">
+ <div class="flex items-center gap-1">
+ <span class="text-gray-500">SP Metadata:</span>
+ <button
+ type="button"
+ onClick={() => copyToClipboard(provider.samlMetadataUrl || '', 'Metadata URL')}
+ class="text-blue-600 hover:underline flex items-center gap-1"
+ >
+ {provider.samlMetadataUrl}
+ <Copy class="w-3 h-3" />
+ </button>
+ </div>
+ <div class="flex items-center gap-1">
+ <span class="text-gray-500">ACS URL:</span>
+ <button
+ type="button"
+ onClick={() => copyToClipboard(provider.samlAcsUrl || '', 'ACS URL')}
+ class="text-blue-600 hover:underline flex items-center gap-1"
+ >
+ {provider.samlAcsUrl}
+ <Copy class="w-3 h-3" />
+ </button>
+ </div>
+ </div>
+ </div>
+ </Show>
+ </div>
+ )}
+ </For>
+ </div>
+ </Show>
+ </div>
+ </Card>
+
+ {/* Add/Edit Modal */}
+ <Show when={showModal()}>
+ <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setShowModal(false)}>
+ <div
+ class="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div class="sticky top-0 bg-white dark:bg-gray-800 px-6 py-4 border-b border-gray-200 dark:border-gray-700 z-10">
+ <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
+ {editingProvider() ? 'Edit' : 'Add'} {form.type.toUpperCase()} Provider
+ </h3>
+ </div>
+
+ <form class="p-6 space-y-4" onSubmit={handleSave}>
+ {/* Common fields */}
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div class={formField}>
+ <label class={labelClass()}>Provider Name</label>
+ <input
+ type="text"
+ value={form.name}
+ onInput={(e) => setForm('name', e.currentTarget.value)}
+ placeholder="e.g., Corporate SSO"
+ class={controlClass()}
+ required
+ />
+ <p class={formHelpText}>Display name for this provider</p>
+ </div>
+ <div class={formField}>
+ <label class={labelClass()}>Display Name (Button)</label>
+ <input
+ type="text"
+ value={form.displayName}
+ onInput={(e) => setForm('displayName', e.currentTarget.value)}
+ placeholder="Sign in with SSO"
+ class={controlClass()}
+ />
+ <p class={formHelpText}>Text shown on login button</p>
+ </div>
+ </div>
+
+ {/* OIDC-specific fields */}
+ <Show when={form.type === 'oidc'}>
+ <div class="space-y-4">
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div class={formField}>
+ <label class={labelClass()}>Issuer URL</label>
+ <div class="flex gap-2">
+ <input
+ type="url"
+ value={form.oidcIssuerUrl}
+ onInput={(e) => setForm('oidcIssuerUrl', e.currentTarget.value)}
+ placeholder="https://login.example.com/realms/pulse"
+ class={controlClass() + ' flex-1'}
+ required
+ />
+ <button
+ type="button"
+ onClick={testConnection}
+ disabled={testing() || !canTest()}
+ class="px-3 py-2 text-sm font-medium bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap"
+ title="Test connection to IdP"
+ >
+ {testing() ? 'Testing...' : 'Test'}
+ </button>
+ </div>
+ </div>
+ <div class={formField}>
+ <label class={labelClass()}>Client ID</label>
+ <input
+ type="text"
+ value={form.oidcClientId}
+ onInput={(e) => setForm('oidcClientId', e.currentTarget.value)}
+ placeholder="pulse-client"
+ class={controlClass()}
+ required
+ />
+ </div>
+ <div class={formField}>
+ <label class={labelClass()}>Client Secret</label>
+ <input
+ type="password"
+ value={form.oidcClientSecret}
+ onInput={(e) => setForm('oidcClientSecret', e.currentTarget.value)}
+ placeholder={editingProvider() ? '•••••••• (leave blank to keep)' : 'Optional for PKCE'}
+ class={controlClass()}
+ />
+ </div>
+ <div class={formField}>
+ <label class={labelClass()}>Redirect URL</label>
+ <input
+ type="url"
+ value={form.oidcRedirectUrl}
+ onInput={(e) => setForm('oidcRedirectUrl', e.currentTarget.value)}
+ placeholder="Auto-detected if empty"
+ class={controlClass()}
+ />
+ </div>
+ </div>
+ </div>
+ </Show>
+
+ {/* SAML-specific fields */}
+ <Show when={form.type === 'saml'}>
+ <div class="space-y-4">
+ <div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
+ <p class="text-xs text-blue-800 dark:text-blue-200">
+ <strong>Setup:</strong> Provide either IdP Metadata URL (preferred) or configure SSO URL + Certificate manually.
+ Use the SP Metadata URL below to configure your Identity Provider.
+ </p>
+ <Show when={publicUrl()}>
+ <div class="mt-2 flex items-center gap-2">
+ <span class="text-xs text-blue-700 dark:text-blue-300">SP Metadata:</span>
+ <code class="text-xs bg-blue-100 dark:bg-blue-900/40 px-2 py-0.5 rounded">
+ {publicUrl()}/api/saml/{form.id || '{id}'}/metadata
+ </code>
+ </div>
+ </Show>
+ </div>
+
+ <div class={formField}>
+ <label class={labelClass()}>IdP Metadata URL</label>
+ <div class="flex gap-2">
+ <input
+ type="url"
+ value={form.samlIdpMetadataUrl}
+ onInput={(e) => setForm('samlIdpMetadataUrl', e.currentTarget.value)}
+ placeholder="https://idp.example.com/metadata"
+ class={controlClass() + ' flex-1'}
+ />
+ <button
+ type="button"
+ onClick={testConnection}
+ disabled={testing() || !canTest()}
+ class="px-3 py-2 text-sm font-medium bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap"
+ title="Test connection to IdP"
+ >
+ {testing() ? 'Testing...' : 'Test'}
+ </button>
+ <button
+ type="button"
+ onClick={fetchMetadataPreview}
+ disabled={loadingPreview() || !form.samlIdpMetadataUrl.trim()}
+ class="px-3 py-2 text-sm font-medium bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap flex items-center gap-1"
+ title="Preview IdP metadata XML"
+ >
+ <Eye class="w-4 h-4" />
+ {loadingPreview() ? 'Loading...' : 'Preview'}
+ </button>
+ </div>
+ <p class={formHelpText}>URL to fetch IdP metadata (preferred method)</p>
+ </div>
+
+ <div class="text-center text-xs text-gray-500 dark:text-gray-400">— or configure manually —</div>
+
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div class={formField}>
+ <label class={labelClass()}>IdP SSO URL</label>
+ <input
+ type="url"
+ value={form.samlIdpSsoUrl}
+ onInput={(e) => setForm('samlIdpSsoUrl', e.currentTarget.value)}
+ placeholder="https://idp.example.com/sso"
+ class={controlClass()}
+ />
+ </div>
+ <div class={formField}>
+ <label class={labelClass()}>IdP Entity ID</label>
+ <input
+ type="text"
+ value={form.samlIdpEntityId}
+ onInput={(e) => setForm('samlIdpEntityId', e.currentTarget.value)}
+ placeholder="https://idp.example.com"
+ class={controlClass()}
+ />
+ </div>
+ </div>
+
+ <div class={formField}>
+ <label class={labelClass()}>IdP Certificate (PEM)</label>
+ <textarea
+ rows={4}
+ value={form.samlIdpCertificate}
+ onInput={(e) => setForm('samlIdpCertificate', e.currentTarget.value)}
+ placeholder="-----BEGIN CERTIFICATE-----&#10;...&#10;-----END CERTIFICATE-----"
+ class={controlClass('font-mono text-xs')}
+ />
+ </div>
+
+ <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
+ <div class={formField}>
+ <label class={labelClass()}>Username Attribute</label>
+ <input
+ type="text"
+ value={form.samlUsernameAttr}
+ onInput={(e) => setForm('samlUsernameAttr', e.currentTarget.value)}
+ placeholder="NameID (default)"
+ class={controlClass()}
+ />
+ </div>
+ <div class={formField}>
+ <label class={labelClass()}>Email Attribute</label>
+ <input
+ type="text"
+ value={form.samlEmailAttr}
+ onInput={(e) => setForm('samlEmailAttr', e.currentTarget.value)}
+ placeholder="email"
+ class={controlClass()}
+ />
+ </div>
+ <div class={formField}>
+ <label class={labelClass()}>Groups Attribute</label>
+ <input
+ type="text"
+ value={form.samlGroupsAttr}
+ onInput={(e) => setForm('samlGroupsAttr', e.currentTarget.value)}
+ placeholder="groups"
+ class={controlClass()}
+ />
+ </div>
+ </div>
+
+ <div class="flex gap-4">
+ <label class="flex items-center gap-2 text-sm">
+ <input
+ type="checkbox"
+ checked={form.samlAllowIdpInitiated}
+ onChange={(e) => setForm('samlAllowIdpInitiated', e.currentTarget.checked)}
+ class="rounded border-gray-300"
+ />
+ <span class="text-gray-700 dark:text-gray-300">Allow IdP-initiated SSO</span>
+ </label>
+ </div>
+ </div>
+ </Show>
+
+ {/* Test result display */}
+ <Show when={testResult()}>
+ <div
+ class={`p-4 rounded-lg border ${
+ testResult()?.success
+ ? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800'
+ : 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800'
+ }`}
+ >
+ <div class="flex items-start gap-3">
+ {testResult()?.success ? (
+ <CheckCircle class="w-5 h-5 text-green-600 dark:text-green-400 flex-shrink-0 mt-0.5" />
+ ) : (
+ <XCircle class="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
+ )}
+ <div class="flex-1 min-w-0">
+ <p
+ class={`text-sm font-medium ${
+ testResult()?.success
+ ? 'text-green-800 dark:text-green-200'
+ : 'text-red-800 dark:text-red-200'
+ }`}
+ >
+ {testResult()?.message}
+ </p>
+ <Show when={testResult()?.error}>
+ <p class="text-xs text-red-600 dark:text-red-400 mt-1">{testResult()?.error}</p>
+ </Show>
+ <Show when={testResult()?.success && testResult()?.details}>
+ <dl class="mt-2 grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1 text-xs">
+ <Show when={testResult()?.details?.entityId}>
+ <div class="flex gap-2">
+ <dt class="text-gray-500 dark:text-gray-400">Entity ID:</dt>
+ <dd class="text-gray-700 dark:text-gray-300 truncate">{testResult()?.details?.entityId}</dd>
+ </div>
+ </Show>
+ <Show when={testResult()?.details?.ssoUrl}>
+ <div class="flex gap-2">
+ <dt class="text-gray-500 dark:text-gray-400">SSO URL:</dt>
+ <dd class="text-gray-700 dark:text-gray-300 truncate">{testResult()?.details?.ssoUrl}</dd>
+ </div>
+ </Show>
+ <Show when={testResult()?.details?.tokenEndpoint}>
+ <div class="flex gap-2">
+ <dt class="text-gray-500 dark:text-gray-400">Token Endpoint:</dt>
+ <dd class="text-gray-700 dark:text-gray-300 truncate">{testResult()?.details?.tokenEndpoint}</dd>
+ </div>
+ </Show>
+ <Show when={testResult()?.details?.certificates && testResult()!.details!.certificates!.length > 0}>
+ <div class="col-span-2 mt-1">
+ <dt class="text-gray-500 dark:text-gray-400 mb-1">Certificates:</dt>
+ <dd class="space-y-1">
+ <For each={testResult()?.details?.certificates}>
+ {(cert) => (
+ <div class={`text-xs px-2 py-1 rounded ${cert.isExpired ? 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300' : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'}`}>
+ <span class="font-medium">{cert.subject}</span>
+ <span class="mx-1">•</span>
+ <span>Expires: {new Date(cert.notAfter).toLocaleDateString()}</span>
+ <Show when={cert.isExpired}>
+ <span class="ml-1 text-red-600 dark:text-red-400 font-medium">(Expired!)</span>
+ </Show>
+ </div>
+ )}
+ </For>
+ </dd>
+ </div>
+ </Show>
+ </dl>
+ </Show>
+ </div>
+ <button
+ type="button"
+ onClick={() => setTestResult(null)}
+ class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
+ >
+ <X class="w-4 h-4" />
+ </button>
+ </div>
+ </div>
+ </Show>
+
+ {/* Advanced options (collapsed by default) */}
+ <div class="pt-2">
+ <button
+ type="button"
+ class="text-xs font-semibold text-blue-600 hover:underline dark:text-blue-300"
+ onClick={() => setAdvancedOpen(!advancedOpen())}
+ >
+ {advancedOpen() ? 'Hide' : 'Show'} access restrictions & role mapping
+ </button>
+
+ <Show when={advancedOpen()}>
+ <div class="mt-4 space-y-4 p-4 bg-gray-50 dark:bg-gray-800/50 rounded-lg">
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div class={formField}>
+ <label class={labelClass()}>Allowed Groups</label>
+ <textarea
+ rows={2}
+ value={form.allowedGroups}
+ onInput={(e) => setForm('allowedGroups', e.currentTarget.value)}
+ placeholder="admin, sso-users"
+ class={controlClass('min-h-[60px]')}
+ />
+ <p class={formHelpText}>Comma-separated. Empty allows all.</p>
+ </div>
+ <div class={formField}>
+ <label class={labelClass()}>Allowed Domains</label>
+ <textarea
+ rows={2}
+ value={form.allowedDomains}
+ onInput={(e) => setForm('allowedDomains', e.currentTarget.value)}
+ placeholder="example.com, corp.io"
+ class={controlClass('min-h-[60px]')}
+ />
+ <p class={formHelpText}>Email domains (without @)</p>
+ </div>
+ <div class={formField}>
+ <label class={labelClass()}>Allowed Emails</label>
+ <textarea
+ rows={2}
+ value={form.allowedEmails}
+ onInput={(e) => setForm('allowedEmails', e.currentTarget.value)}
+ placeholder="[email protected]"
+ class={controlClass('min-h-[60px]')}
+ />
+ </div>
+ <div class={formField}>
+ <label class={labelClass()}>Group Role Mappings</label>
+ <textarea
+ rows={2}
+ value={form.groupRoleMappings}
+ onInput={(e) => setForm('groupRoleMappings', e.currentTarget.value)}
+ placeholder="admins=admin, ops=operator"
+ class={controlClass('min-h-[60px]')}
+ />
+ <p class={formHelpText}>Format: group=roleId</p>
+ </div>
+ </div>
+ </div>
+ </Show>
+ </div>
+
+ {/* Actions */}
+ <div class="flex justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
+ <button
+ type="button"
+ onClick={() => setShowModal(false)}
+ class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
+ disabled={saving()}
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ class="px-4 py-2 text-sm font-medium bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
+ disabled={saving()}
+ >
+ {saving() ? 'Saving...' : editingProvider() ? 'Save Changes' : 'Create Provider'}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </Show>
+
+ {/* Delete confirmation modal */}
+ <Show when={deleteConfirm()}>
+ <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setDeleteConfirm(null)}>
+ <div
+ class="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full p-6"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">Delete Provider?</h3>
+ <p class="text-sm text-gray-600 dark:text-gray-400 mb-4">
+ This will permanently delete this SSO provider. Users will no longer be able to sign in using this provider.
+ </p>
+ <div class="flex justify-end gap-3">
+ <button
+ type="button"
+ onClick={() => setDeleteConfirm(null)}
+ class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={() => handleDelete(deleteConfirm()!)}
+ class="px-4 py-2 text-sm font-medium bg-red-600 text-white rounded-lg hover:bg-red-700"
+ >
+ Delete Provider
+ </button>
+ </div>
+ </div>
+ </div>
+ </Show>
+
+ {/* Metadata Preview modal */}
+ <Show when={showMetadataPreview() && metadataPreview()}>
+ <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setShowMetadataPreview(false)}>
+ <div
+ class="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-4xl w-full max-h-[90vh] flex flex-col"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {/* Modal header */}
+ <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between flex-shrink-0">
+ <h3 class="text-lg font-semibold text-gray-900 dark:text-white">IdP Metadata Preview</h3>
+ <button
+ type="button"
+ onClick={() => setShowMetadataPreview(false)}
+ class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
+ >
+ <X class="w-5 h-5" />
+ </button>
+ </div>
+
+ {/* Parsed info summary */}
+ <div class="px-6 py-4 bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
+ <h4 class="text-sm font-medium text-gray-900 dark:text-white mb-3">Parsed Information</h4>
+ <dl class="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
+ <div>
+ <dt class="text-gray-500 dark:text-gray-400 text-xs uppercase tracking-wide">Entity ID</dt>
+ <dd class="text-gray-900 dark:text-white font-mono text-xs mt-0.5 break-all">
+ {metadataPreview()?.parsed.entityId || 'N/A'}
+ </dd>
+ </div>
+ <div>
+ <dt class="text-gray-500 dark:text-gray-400 text-xs uppercase tracking-wide">SSO URL</dt>
+ <dd class="text-gray-900 dark:text-white font-mono text-xs mt-0.5 break-all">
+ {metadataPreview()?.parsed.ssoUrl || 'N/A'}
+ </dd>
+ </div>
+ <Show when={metadataPreview()?.parsed.sloUrl}>
+ <div>
+ <dt class="text-gray-500 dark:text-gray-400 text-xs uppercase tracking-wide">SLO URL</dt>
+ <dd class="text-gray-900 dark:text-white font-mono text-xs mt-0.5 break-all">
+ {metadataPreview()?.parsed.sloUrl}
+ </dd>
+ </div>
+ </Show>
+ <Show when={metadataPreview()?.parsed.certificates && metadataPreview()!.parsed.certificates!.length > 0}>
+ <div class="sm:col-span-2">
+ <dt class="text-gray-500 dark:text-gray-400 text-xs uppercase tracking-wide mb-1">Certificates</dt>
+ <dd class="space-y-1">
+ <For each={metadataPreview()?.parsed.certificates}>
+ {(cert) => (
+ <div class={`text-xs px-2 py-1 rounded ${cert.isExpired ? 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300' : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'}`}>
+ <span class="font-medium">{cert.subject}</span>
+ <span class="mx-1">•</span>
+ <span>Expires: {new Date(cert.notAfter).toLocaleDateString()}</span>
+ <Show when={cert.isExpired}>
+ <span class="ml-1 text-red-600 dark:text-red-400 font-medium">(Expired!)</span>
+ </Show>
+ </div>
+ )}
+ </For>
+ </dd>
+ </div>
+ </Show>
+ </dl>
+ </div>
+
+ {/* Raw XML */}
+ <div class="flex-1 overflow-auto p-4">
+ <div class="flex items-center justify-between mb-2">
+ <h4 class="text-sm font-medium text-gray-900 dark:text-white">Raw XML</h4>
+ <button
+ type="button"
+ onClick={() => {
+ if (metadataPreview()?.xml) {
+ navigator.clipboard.writeText(metadataPreview()!.xml);
+ notificationStore.success('XML copied to clipboard');
+ }
+ }}
+ class="px-2 py-1 text-xs font-medium text-gray-600 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-600 flex items-center gap-1"
+ >
+ <Copy class="w-3 h-3" />
+ Copy
+ </button>
+ </div>
+ <pre class="text-xs bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto whitespace-pre-wrap break-all font-mono">
+ {metadataPreview()?.xml}
+ </pre>
+ </div>
+
+ {/* Modal footer */}
+ <div class="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end flex-shrink-0">
+ <button
+ type="button"
+ onClick={() => setShowMetadataPreview(false)}
+ class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
+ >
+ Close
+ </button>
+ </div>
+ </div>
+ </div>
+ </Show>
+ </div>
+ );
+};
+
+export default SSOProvidersPanel;
diff --git a/internal/api/saml_handlers.go b/internal/api/saml_handlers.go
new file mode 100644
index 0000000000..f1dbdb052e
--- /dev/null
+++ b/internal/api/saml_handlers.go
@@ -0,0 +1,483 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
+ "github.com/rs/zerolog/log"
+)
+
+// SAMLServiceManager manages multiple SAML services for different providers
+type SAMLServiceManager struct {
+ mu sync.RWMutex
+ services map[string]*SAMLService
+ baseURL string
+}
+
+// NewSAMLServiceManager creates a new SAML service manager
+func NewSAMLServiceManager(baseURL string) *SAMLServiceManager {
+ return &SAMLServiceManager{
+ services: make(map[string]*SAMLService),
+ baseURL: baseURL,
+ }
+}
+
+// GetService returns a SAML service for the given provider ID
+func (m *SAMLServiceManager) GetService(providerID string) *SAMLService {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.services[providerID]
+}
+
+// InitializeProvider creates or updates a SAML service for a provider
+func (m *SAMLServiceManager) InitializeProvider(ctx context.Context, providerID string, cfg *config.SAMLProviderConfig) error {
+ service, err := NewSAMLService(ctx, providerID, cfg, m.baseURL)
+ if err != nil {
+ return err
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.services[providerID] = service
+
+ log.Info().
+ Str("provider_id", providerID).
+ Msg("Initialized SAML provider")
+
+ return nil
+}
+
+// RemoveProvider removes a SAML service
+func (m *SAMLServiceManager) RemoveProvider(providerID string) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ delete(m.services, providerID)
+}
+
+// handleSAMLLogin initiates a SAML authentication flow
+func (r *Router) handleSAMLLogin(w http.ResponseWriter, req *http.Request) {
+ providerID := extractSAMLProviderID(req.URL.Path, "login")
+ if providerID == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_provider", "Provider ID is required", nil)
+ return
+ }
+
+ // Security: Validate provider ID format
+ if !validateProviderID(providerID) {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_provider", "Invalid provider ID format", nil)
+ return
+ }
+
+ provider := r.getSSOProvider(providerID)
+ if provider == nil || provider.Type != config.SSOProviderTypeSAML || !provider.Enabled {
+ writeErrorResponse(w, http.StatusNotFound, "provider_not_found", "SAML provider not found or not enabled", nil)
+ return
+ }
+
+ service := r.samlManager.GetService(providerID)
+ if service == nil {
+ // Try to initialize the provider
+ if err := r.samlManager.InitializeProvider(req.Context(), providerID, provider.SAML); err != nil {
+ log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to initialize SAML provider")
+ writeErrorResponse(w, http.StatusInternalServerError, "saml_init_failed", "Failed to initialize SAML provider", nil)
+ return
+ }
+ service = r.samlManager.GetService(providerID)
+ }
+
+ // Get return URL from query or form
+ returnTo := sanitizeOIDCReturnTo(req.URL.Query().Get("returnTo"))
+ if returnTo == "" && req.Method == http.MethodPost {
+ var payload struct {
+ ReturnTo string `json:"returnTo"`
+ }
+ if err := json.NewDecoder(req.Body).Decode(&payload); err == nil {
+ returnTo = sanitizeOIDCReturnTo(payload.ReturnTo)
+ }
+ }
+
+ // Create SAML AuthnRequest
+ redirectURL, err := service.MakeAuthRequest(returnTo)
+ if err != nil {
+ log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to create SAML auth request")
+ writeErrorResponse(w, http.StatusInternalServerError, "saml_auth_failed", "Failed to create authentication request", nil)
+ return
+ }
+
+ LogAuditEvent("saml_login_initiated", "", GetClientIP(req), req.URL.Path, true, "Provider: "+providerID)
+
+ // Redirect for GET, return JSON for POST
+ if req.Method == http.MethodGet {
+ http.Redirect(w, req, redirectURL, http.StatusFound)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(map[string]string{
+ "authorizationUrl": redirectURL,
+ })
+}
+
+// handleSAMLACS handles the SAML Assertion Consumer Service (callback)
+func (r *Router) handleSAMLACS(w http.ResponseWriter, req *http.Request) {
+ if req.Method != http.MethodPost {
+ writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only POST is allowed", nil)
+ return
+ }
+
+ providerID := extractSAMLProviderID(req.URL.Path, "acs")
+ if providerID == "" {
+ r.redirectSAMLError(w, req, "", "invalid_provider")
+ return
+ }
+
+ // Security: Validate provider ID format
+ if !validateProviderID(providerID) {
+ r.redirectSAMLError(w, req, "", "invalid_provider")
+ return
+ }
+
+ provider := r.getSSOProvider(providerID)
+ if provider == nil || provider.Type != config.SSOProviderTypeSAML || !provider.Enabled {
+ r.redirectSAMLError(w, req, "", "provider_not_found")
+ return
+ }
+
+ service := r.samlManager.GetService(providerID)
+ if service == nil {
+ r.redirectSAMLError(w, req, "", "provider_not_initialized")
+ return
+ }
+
+ // Process SAML response
+ result, relayState, err := service.ProcessResponse(req)
+ if err != nil {
+ log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to process SAML response")
+ LogAuditEvent("saml_login", "", GetClientIP(req), req.URL.Path, false, "SAML response validation failed: "+err.Error())
+ r.redirectSAMLError(w, req, relayState, "saml_validation_failed")
+ return
+ }
+
+ // Check group restrictions
+ if len(provider.AllowedGroups) > 0 {
+ if !intersects(result.Groups, provider.AllowedGroups) {
+ log.Debug().
+ Str("username", result.Username).
+ Strs("user_groups", result.Groups).
+ Strs("allowed_groups", provider.AllowedGroups).
+ Msg("User not in allowed groups")
+ LogAuditEvent("saml_login", result.Username, GetClientIP(req), req.URL.Path, false, "Group restriction failed")
+ r.redirectSAMLError(w, req, relayState, "group_restricted")
+ return
+ }
+ }
+
+ // Check domain restrictions
+ if len(provider.AllowedDomains) > 0 && result.Email != "" {
+ if !matchesDomain(result.Email, provider.AllowedDomains) {
+ log.Debug().
+ Str("email", result.Email).
+ Strs("allowed_domains", provider.AllowedDomains).
+ Msg("Email domain not allowed")
+ LogAuditEvent("saml_login", result.Username, GetClientIP(req), req.URL.Path, false, "Domain restriction failed")
+ r.redirectSAMLError(w, req, relayState, "domain_restricted")
+ return
+ }
+ }
+
+ // Check email restrictions
+ if len(provider.AllowedEmails) > 0 && result.Email != "" {
+ if !matchesValue(result.Email, provider.AllowedEmails) {
+ log.Debug().
+ Str("email", result.Email).
+ Strs("allowed_emails", provider.AllowedEmails).
+ Msg("Email not in allowed list")
+ LogAuditEvent("saml_login", result.Username, GetClientIP(req), req.URL.Path, false, "Email restriction failed")
+ r.redirectSAMLError(w, req, relayState, "email_restricted")
+ return
+ }
+ }
+
+ // RBAC Integration: Map SAML groups to Pulse roles
+ if authManager := internalauth.GetManager(); authManager != nil && len(provider.GroupRoleMappings) > 0 {
+ var rolesToAssign []string
+ seenRoles := make(map[string]bool)
+
+ for _, group := range result.Groups {
+ if roleID, ok := provider.GroupRoleMappings[group]; ok {
+ if !seenRoles[roleID] {
+ rolesToAssign = append(rolesToAssign, roleID)
+ seenRoles[roleID] = true
+ }
+ }
+ }
+
+ if len(rolesToAssign) > 0 {
+ log.Info().
+ Str("user", result.Username).
+ Strs("mapped_roles", rolesToAssign).
+ Msg("Auto-assigning roles based on SAML group mapping")
+ if err := authManager.UpdateUserRoles(result.Username, rolesToAssign); err != nil {
+ log.Error().Err(err).Str("user", result.Username).Msg("Failed to auto-assign SAML roles")
+ LogAuditEvent("saml_role_assignment", result.Username, GetClientIP(req), req.URL.Path, false, "Failed to auto-assign roles: "+strings.Join(rolesToAssign, ", "))
+ } else {
+ LogAuditEvent("saml_role_assignment", result.Username, GetClientIP(req), req.URL.Path, true, "Auto-assigned roles: "+strings.Join(rolesToAssign, ", "))
+ }
+ }
+ }
+
+ // Establish session
+ username := result.Username
+ if username == "" {
+ username = result.Email
+ }
+ if username == "" {
+ username = result.NameID
+ }
+
+ // Store SAML session info for potential SLO
+ samlSession := &SAMLSessionInfo{
+ ProviderID: providerID,
+ NameID: result.NameID,
+ SessionIndex: result.SessionIdx,
+ }
+
+ if err := r.establishSAMLSession(w, req, username, samlSession); err != nil {
+ log.Error().Err(err).Msg("Failed to establish session after SAML login")
+ LogAuditEvent("saml_login", username, GetClientIP(req), req.URL.Path, false, "Session creation failed")
+ r.redirectSAMLError(w, req, relayState, "session_failed")
+ return
+ }
+
+ LogAuditEvent("saml_login", username, GetClientIP(req), req.URL.Path, true, "SAML login success via "+providerID)
+
+ // Redirect to return URL
+ target := relayState
+ if target == "" {
+ target = "/"
+ }
+ target = addQueryParam(target, "saml", "success")
+ http.Redirect(w, req, target, http.StatusFound)
+}
+
+// handleSAMLMetadata returns the SP metadata XML
+func (r *Router) handleSAMLMetadata(w http.ResponseWriter, req *http.Request) {
+ if req.Method != http.MethodGet {
+ writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only GET is allowed", nil)
+ return
+ }
+
+ providerID := extractSAMLProviderID(req.URL.Path, "metadata")
+ if providerID == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_provider", "Provider ID is required", nil)
+ return
+ }
+
+ // Security: Validate provider ID format
+ if !validateProviderID(providerID) {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_provider", "Invalid provider ID format", nil)
+ return
+ }
+
+ provider := r.getSSOProvider(providerID)
+ if provider == nil || provider.Type != config.SSOProviderTypeSAML {
+ writeErrorResponse(w, http.StatusNotFound, "provider_not_found", "SAML provider not found", nil)
+ return
+ }
+
+ service := r.samlManager.GetService(providerID)
+ if service == nil {
+ // Try to initialize the provider
+ if provider.SAML != nil {
+ if err := r.samlManager.InitializeProvider(req.Context(), providerID, provider.SAML); err != nil {
+ log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to initialize SAML provider for metadata")
+ writeErrorResponse(w, http.StatusInternalServerError, "saml_init_failed", "Failed to initialize SAML provider", nil)
+ return
+ }
+ service = r.samlManager.GetService(providerID)
+ }
+ if service == nil {
+ writeErrorResponse(w, http.StatusNotFound, "provider_not_initialized", "SAML provider not initialized", nil)
+ return
+ }
+ }
+
+ metadata, err := service.GetMetadata()
+ if err != nil {
+ log.Error().Err(err).Str("provider_id", providerID).Msg("Failed to generate SAML metadata")
+ writeErrorResponse(w, http.StatusInternalServerError, "metadata_error", "Failed to generate metadata", nil)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/xml")
+ w.Header().Set("Content-Disposition", "inline; filename=metadata.xml")
+ w.Write(metadata)
+}
+
+// handleSAMLLogout handles SAML Single Logout
+func (r *Router) handleSAMLLogout(w http.ResponseWriter, req *http.Request) {
+ providerID := extractSAMLProviderID(req.URL.Path, "logout")
+ if providerID == "" {
+ // Fall back to regular logout
+ r.handleLogout(w, req)
+ return
+ }
+
+ // Security: Validate provider ID format
+ if !validateProviderID(providerID) {
+ // Invalid ID, fall back to regular logout
+ r.handleLogout(w, req)
+ return
+ }
+
+ service := r.samlManager.GetService(providerID)
+ if service == nil {
+ // Fall back to regular logout
+ r.handleLogout(w, req)
+ return
+ }
+
+ // Get session info for SLO
+ session := r.getSAMLSessionInfo(req)
+ if session == nil || session.NameID == "" {
+ // No SAML session info, fall back to regular logout
+ r.handleLogout(w, req)
+ return
+ }
+
+ // Clear local session first
+ r.clearSession(w, req)
+
+ // Attempt SAML SLO
+ logoutURL, err := service.MakeLogoutRequest(session.NameID, session.SessionIndex)
+ if err != nil {
+ log.Warn().Err(err).Str("provider_id", providerID).Msg("SAML SLO not available, local logout only")
+ LogAuditEvent("saml_logout", "", GetClientIP(req), req.URL.Path, true, "Local logout only (SLO not available)")
+ http.Redirect(w, req, "/?logout=success", http.StatusFound)
+ return
+ }
+
+ LogAuditEvent("saml_logout", "", GetClientIP(req), req.URL.Path, true, "Initiating SAML SLO")
+ http.Redirect(w, req, logoutURL, http.StatusFound)
+}
+
+// handleSAMLSLO handles SAML Single Logout responses/requests
+func (r *Router) handleSAMLSLO(w http.ResponseWriter, req *http.Request) {
+ // For now, just redirect to home with logout success
+ // A full implementation would validate the LogoutResponse
+ r.clearSession(w, req)
+ LogAuditEvent("saml_slo_callback", "", GetClientIP(req), req.URL.Path, true, "SAML SLO complete")
+ http.Redirect(w, req, "/?logout=success", http.StatusFound)
+}
+
+// SAMLSessionInfo stores SAML-specific session information for SLO
+type SAMLSessionInfo struct {
+ ProviderID string `json:"providerId"`
+ NameID string `json:"nameId"`
+ SessionIndex string `json:"sessionIndex"`
+}
+
+// establishSAMLSession creates a session for a SAML-authenticated user
+func (r *Router) establishSAMLSession(w http.ResponseWriter, req *http.Request, username string, samlInfo *SAMLSessionInfo) error {
+ // Use the existing session mechanism
+ // For SAML, we don't have refresh tokens, so we pass nil for OIDC tokens
+ return r.establishOIDCSession(w, req, username, nil)
+}
+
+// getSAMLSessionInfo retrieves SAML session info from the current session
+func (r *Router) getSAMLSessionInfo(req *http.Request) *SAMLSessionInfo {
+ // TODO: Implement retrieval of SAML session info from session storage
+ // For now, return nil which causes fallback to regular logout
+ return nil
+}
+
+// clearSession clears the current session
+func (r *Router) clearSession(w http.ResponseWriter, req *http.Request) {
+ // Clear session cookie
+ http.SetCookie(w, &http.Cookie{
+ Name: "session",
+ Value: "",
+ Path: "/",
+ MaxAge: -1,
+ HttpOnly: true,
+ Secure: req.TLS != nil,
+ SameSite: http.SameSiteLaxMode,
+ })
+}
+
+func (r *Router) redirectSAMLError(w http.ResponseWriter, req *http.Request, returnTo string, code string) {
+ target := returnTo
+ if target == "" {
+ target = "/"
+ }
+ target = addQueryParam(target, "saml", "error")
+ if code != "" {
+ target = addQueryParam(target, "saml_error", code)
+ }
+ http.Redirect(w, req, target, http.StatusFound)
+}
+
+// extractSAMLProviderID extracts the provider ID from a SAML endpoint path
+// Expected paths: /api/saml/{providerID}/login, /api/saml/{providerID}/acs, etc.
+func extractSAMLProviderID(path, endpoint string) string {
+ // Path format: /api/saml/{id}/{endpoint}
+ parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
+ if len(parts) >= 3 && parts[0] == "api" && parts[1] == "saml" {
+ if len(parts) >= 4 && parts[3] == endpoint {
+ return parts[2]
+ }
+ // Also handle /api/saml/{id}/{endpoint} without trailing parts
+ if len(parts) == 4 && parts[3] == endpoint {
+ return parts[2]
+ }
+ }
+ return ""
+}
+
+// getSSOProvider retrieves an SSO provider by ID from the current configuration
+func (r *Router) getSSOProvider(providerID string) *config.SSOProvider {
+ if r.ssoConfig == nil {
+ return nil
+ }
+ return r.ssoConfig.GetProvider(providerID)
+}
+
+// InitializeSAMLProviders initializes all enabled SAML providers
+func (r *Router) InitializeSAMLProviders(ctx context.Context) error {
+ if r.ssoConfig == nil {
+ return nil
+ }
+
+ for _, provider := range r.ssoConfig.Providers {
+ if provider.Type == config.SSOProviderTypeSAML && provider.Enabled && provider.SAML != nil {
+ if err := r.samlManager.InitializeProvider(ctx, provider.ID, provider.SAML); err != nil {
+ log.Error().
+ Err(err).
+ Str("provider_id", provider.ID).
+ Msg("Failed to initialize SAML provider")
+ // Continue initializing other providers
+ }
+ }
+ }
+
+ return nil
+}
+
+// RefreshSAMLProvider refreshes a SAML provider's IdP metadata
+func (r *Router) RefreshSAMLProvider(ctx context.Context, providerID string) error {
+ service := r.samlManager.GetService(providerID)
+ if service == nil {
+ return nil
+ }
+
+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+
+ return service.RefreshMetadata(ctx)
+}
diff --git a/internal/api/saml_service.go b/internal/api/saml_service.go
new file mode 100644
index 0000000000..62ed1421fe
--- /dev/null
+++ b/internal/api/saml_service.go
@@ -0,0 +1,609 @@
+package api
+
+import (
+ "context"
+ "crypto/rsa"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/pem"
+ "encoding/xml"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/crewjam/saml"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rs/zerolog/log"
+)
+
+// SAMLService manages SAML Service Provider functionality for a single provider
+type SAMLService struct {
+ mu sync.RWMutex
+ providerID string
+ config *config.SAMLProviderConfig
+ sp *saml.ServiceProvider
+ idpMetadata *saml.EntityDescriptor
+ httpClient *http.Client
+ baseURL string
+ lastRefresh time.Time
+}
+
+// SAMLAuthResult contains the result of a successful SAML authentication
+type SAMLAuthResult struct {
+ Username string
+ Email string
+ Groups []string
+ FirstName string
+ LastName string
+ NameID string
+ SessionIdx string
+ Attributes map[string][]string
+}
+
+// NewSAMLService creates a new SAML service for a provider
+func NewSAMLService(ctx context.Context, providerID string, cfg *config.SAMLProviderConfig, baseURL string) (*SAMLService, error) {
+ if cfg == nil {
+ return nil, errors.New("saml configuration is nil")
+ }
+
+ service := &SAMLService{
+ providerID: providerID,
+ config: cfg,
+ baseURL: strings.TrimRight(baseURL, "/"),
+ httpClient: newSAMLHTTPClient(),
+ }
+
+ // Load IdP metadata
+ if err := service.loadIDPMetadata(ctx); err != nil {
+ return nil, fmt.Errorf("failed to load idp metadata: %w", err)
+ }
+
+ // Initialize Service Provider
+ if err := service.initServiceProvider(); err != nil {
+ return nil, fmt.Errorf("failed to initialize service provider: %w", err)
+ }
+
+ return service, nil
+}
+
+func newSAMLHTTPClient() *http.Client {
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ transport.TLSClientConfig = &tls.Config{
+ MinVersion: tls.VersionTLS12,
+ }
+ return &http.Client{
+ Transport: transport,
+ Timeout: 30 * time.Second,
+ }
+}
+
+// loadIDPMetadata loads Identity Provider metadata from URL or XML
+func (s *SAMLService) loadIDPMetadata(ctx context.Context) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ var metadata *saml.EntityDescriptor
+ var err error
+
+ if s.config.IDPMetadataURL != "" {
+ metadata, err = s.fetchIDPMetadataFromURL(ctx, s.config.IDPMetadataURL)
+ if err != nil {
+ return fmt.Errorf("failed to fetch idp metadata from url: %w", err)
+ }
+ } else if s.config.IDPMetadataXML != "" {
+ metadata, err = parseIDPMetadataXML([]byte(s.config.IDPMetadataXML))
+ if err != nil {
+ return fmt.Errorf("failed to parse idp metadata xml: %w", err)
+ }
+ } else {
+ // Build metadata from manual configuration
+ metadata, err = s.buildManualMetadata()
+ if err != nil {
+ return fmt.Errorf("failed to build manual metadata: %w", err)
+ }
+ }
+
+ s.idpMetadata = metadata
+ s.lastRefresh = time.Now()
+
+ log.Info().
+ Str("provider_id", s.providerID).
+ Str("entity_id", metadata.EntityID).
+ Msg("Loaded SAML IdP metadata")
+
+ return nil
+}
+
+func (s *SAMLService) fetchIDPMetadataFromURL(ctx context.Context, metadataURL string) (*saml.EntityDescriptor, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, metadataURL, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := s.httpClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("metadata request returned status %d", resp.StatusCode)
+ }
+
+ body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) // 1MB limit
+ if err != nil {
+ return nil, err
+ }
+
+ return parseIDPMetadataXML(body)
+}
+
+func parseIDPMetadataXML(data []byte) (*saml.EntityDescriptor, error) {
+ var metadata saml.EntityDescriptor
+ if err := xml.Unmarshal(data, &metadata); err != nil {
+ // Try parsing as EntityDescriptor wrapped in EntitiesDescriptor
+ var entities saml.EntitiesDescriptor
+ if err2 := xml.Unmarshal(data, &entities); err2 != nil {
+ return nil, fmt.Errorf("failed to parse metadata: %w", err)
+ }
+ if len(entities.EntityDescriptors) == 0 {
+ return nil, errors.New("no entity descriptors found in metadata")
+ }
+ metadata = entities.EntityDescriptors[0]
+ }
+ return &metadata, nil
+}
+
+func (s *SAMLService) buildManualMetadata() (*saml.EntityDescriptor, error) {
+ if s.config.IDPSSOURL == "" {
+ return nil, errors.New("idp sso url is required for manual configuration")
+ }
+
+ ssoURL, err := url.Parse(s.config.IDPSSOURL)
+ if err != nil {
+ return nil, fmt.Errorf("invalid idp sso url: %w", err)
+ }
+
+ entityID := s.config.IDPEntityID
+ if entityID == "" {
+ entityID = s.config.IDPIssuer
+ }
+ if entityID == "" {
+ entityID = s.config.IDPSSOURL
+ }
+
+ metadata := &saml.EntityDescriptor{
+ EntityID: entityID,
+ IDPSSODescriptors: []saml.IDPSSODescriptor{
+ {
+ SSODescriptor: saml.SSODescriptor{
+ RoleDescriptor: saml.RoleDescriptor{
+ ProtocolSupportEnumeration: "urn:oasis:names:tc:SAML:2.0:protocol",
+ },
+ },
+ SingleSignOnServices: []saml.Endpoint{
+ {
+ Binding: saml.HTTPRedirectBinding,
+ Location: ssoURL.String(),
+ },
+ {
+ Binding: saml.HTTPPostBinding,
+ Location: ssoURL.String(),
+ },
+ },
+ },
+ },
+ }
+
+ // Add SLO endpoint if configured
+ if s.config.IDPSLOUrl != "" {
+ sloURL, err := url.Parse(s.config.IDPSLOUrl)
+ if err == nil {
+ metadata.IDPSSODescriptors[0].SingleLogoutServices = []saml.Endpoint{
+ {
+ Binding: saml.HTTPRedirectBinding,
+ Location: sloURL.String(),
+ },
+ }
+ }
+ }
+
+ // Add IdP certificate if provided
+ if err := s.addIDPCertificate(metadata); err != nil {
+ return nil, err
+ }
+
+ return metadata, nil
+}
+
+func (s *SAMLService) addIDPCertificate(metadata *saml.EntityDescriptor) error {
+ var certData []byte
+ var err error
+
+ if s.config.IDPCertFile != "" {
+ certData, err = os.ReadFile(s.config.IDPCertFile)
+ if err != nil {
+ return fmt.Errorf("failed to read idp certificate file: %w", err)
+ }
+ } else if s.config.IDPCertificate != "" {
+ certData = []byte(s.config.IDPCertificate)
+ } else {
+ return nil // No certificate provided
+ }
+
+ // Parse PEM certificate
+ block, _ := pem.Decode(certData)
+ if block == nil {
+ return errors.New("failed to decode idp certificate pem")
+ }
+
+ cert, err := x509.ParseCertificate(block.Bytes)
+ if err != nil {
+ return fmt.Errorf("failed to parse idp certificate: %w", err)
+ }
+
+ if len(metadata.IDPSSODescriptors) > 0 {
+ metadata.IDPSSODescriptors[0].KeyDescriptors = []saml.KeyDescriptor{
+ {
+ Use: "signing",
+ KeyInfo: saml.KeyInfo{
+ X509Data: saml.X509Data{
+ X509Certificates: []saml.X509Certificate{
+ {Data: string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}))},
+ },
+ },
+ },
+ },
+ }
+ }
+
+ return nil
+}
+
+func (s *SAMLService) initServiceProvider() error {
+ // Build SP Entity ID
+ spEntityID := s.config.SPEntityID
+ if spEntityID == "" {
+ spEntityID = fmt.Sprintf("%s/saml/%s", s.baseURL, s.providerID)
+ }
+
+ // Build ACS URL
+ acsPath := s.config.SPACSPath
+ if acsPath == "" {
+ acsPath = fmt.Sprintf("/api/saml/%s/acs", s.providerID)
+ }
+ acsURL, err := url.Parse(s.baseURL + acsPath)
+ if err != nil {
+ return fmt.Errorf("failed to parse acs url: %w", err)
+ }
+
+ // Build Metadata URL
+ metadataPath := s.config.SPMetadataPath
+ if metadataPath == "" {
+ metadataPath = fmt.Sprintf("/api/saml/%s/metadata", s.providerID)
+ }
+ metadataURL, err := url.Parse(s.baseURL + metadataPath)
+ if err != nil {
+ return fmt.Errorf("failed to parse metadata url: %w", err)
+ }
+
+ forceAuthn := s.config.ForceAuthn
+
+ sp := saml.ServiceProvider{
+ EntityID: spEntityID,
+ AcsURL: *acsURL,
+ MetadataURL: *metadataURL,
+ IDPMetadata: s.idpMetadata,
+ AllowIDPInitiated: s.config.AllowIDPInitiated,
+ ForceAuthn: &forceAuthn,
+ }
+
+ // Set SLO URL if the IdP supports it
+ if len(s.idpMetadata.IDPSSODescriptors) > 0 &&
+ len(s.idpMetadata.IDPSSODescriptors[0].SingleLogoutServices) > 0 {
+ sloURL, err := url.Parse(s.baseURL + fmt.Sprintf("/api/saml/%s/slo", s.providerID))
+ if err == nil {
+ sp.SloURL = *sloURL
+ }
+ }
+
+ // Load SP certificate and key if signing is enabled
+ if s.config.SignRequests {
+ cert, key, err := s.loadSPCredentials()
+ if err != nil {
+ return fmt.Errorf("failed to load sp credentials: %w", err)
+ }
+ sp.Key = key
+ sp.Certificate = cert
+ }
+
+ s.sp = &sp
+
+ log.Info().
+ Str("provider_id", s.providerID).
+ Str("entity_id", spEntityID).
+ Str("acs_url", acsURL.String()).
+ Bool("sign_requests", s.config.SignRequests).
+ Msg("Initialized SAML Service Provider")
+
+ return nil
+}
+
+func (s *SAMLService) loadSPCredentials() (*x509.Certificate, *rsa.PrivateKey, error) {
+ var certData, keyData []byte
+ var err error
+
+ // Load certificate
+ if s.config.SPCertFile != "" {
+ certData, err = os.ReadFile(s.config.SPCertFile)
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to read sp certificate file: %w", err)
+ }
+ } else if s.config.SPCertificate != "" {
+ certData = []byte(s.config.SPCertificate)
+ } else {
+ return nil, nil, errors.New("sp certificate is required for signing")
+ }
+
+ // Load private key
+ if s.config.SPKeyFile != "" {
+ keyData, err = os.ReadFile(s.config.SPKeyFile)
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to read sp private key file: %w", err)
+ }
+ } else if s.config.SPPrivateKey != "" {
+ keyData = []byte(s.config.SPPrivateKey)
+ } else {
+ return nil, nil, errors.New("sp private key is required for signing")
+ }
+
+ // Parse certificate
+ certBlock, _ := pem.Decode(certData)
+ if certBlock == nil {
+ return nil, nil, errors.New("failed to decode sp certificate pem")
+ }
+ cert, err := x509.ParseCertificate(certBlock.Bytes)
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to parse sp certificate: %w", err)
+ }
+
+ // Parse private key
+ keyBlock, _ := pem.Decode(keyData)
+ if keyBlock == nil {
+ return nil, nil, errors.New("failed to decode sp private key pem")
+ }
+
+ var key *rsa.PrivateKey
+ switch keyBlock.Type {
+ case "RSA PRIVATE KEY":
+ key, err = x509.ParsePKCS1PrivateKey(keyBlock.Bytes)
+ case "PRIVATE KEY":
+ parsedKey, err := x509.ParsePKCS8PrivateKey(keyBlock.Bytes)
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to parse pkcs8 private key: %w", err)
+ }
+ var ok bool
+ key, ok = parsedKey.(*rsa.PrivateKey)
+ if !ok {
+ return nil, nil, errors.New("sp private key is not rsa")
+ }
+ default:
+ return nil, nil, fmt.Errorf("unsupported private key type: %s", keyBlock.Type)
+ }
+
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to parse sp private key: %w", err)
+ }
+
+ return cert, key, nil
+}
+
+// MakeAuthRequest creates a SAML AuthnRequest and returns the redirect URL
+func (s *SAMLService) MakeAuthRequest(relayState string) (string, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ if s.sp == nil {
+ return "", errors.New("service provider not initialized")
+ }
+
+ if relayState == "" {
+ relayState = "/"
+ }
+
+ // Use the simple redirect method
+ redirectURL, err := s.sp.MakeRedirectAuthenticationRequest(relayState)
+ if err != nil {
+ return "", fmt.Errorf("failed to create auth request: %w", err)
+ }
+
+ log.Debug().
+ Str("provider_id", s.providerID).
+ Str("redirect_url", redirectURL.String()).
+ Msg("Created SAML AuthnRequest")
+
+ return redirectURL.String(), nil
+}
+
+// ProcessResponse processes a SAML response and extracts user information
+func (s *SAMLService) ProcessResponse(r *http.Request) (*SAMLAuthResult, string, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ if s.sp == nil {
+ return nil, "", errors.New("service provider not initialized")
+ }
+
+ // Parse the form to get SAMLResponse and RelayState
+ if err := r.ParseForm(); err != nil {
+ return nil, "", fmt.Errorf("failed to parse form: %w", err)
+ }
+
+ relayState := r.FormValue("RelayState")
+
+ // Allow IdP-initiated flow
+ possibleRequestIDs := []string{}
+ if s.sp.AllowIDPInitiated {
+ possibleRequestIDs = append(possibleRequestIDs, "")
+ }
+
+ // Parse and validate the SAML assertion
+ assertion, err := s.sp.ParseResponse(r, possibleRequestIDs)
+ if err != nil {
+ return nil, relayState, fmt.Errorf("failed to validate saml response: %w", err)
+ }
+
+ // Extract user information from assertion
+ result := &SAMLAuthResult{
+ Attributes: make(map[string][]string),
+ }
+
+ // Get NameID
+ if assertion.Subject != nil && assertion.Subject.NameID != nil {
+ result.NameID = assertion.Subject.NameID.Value
+ }
+
+ // Get session index from AuthnStatement
+ for _, authnStatement := range assertion.AuthnStatements {
+ if authnStatement.SessionIndex != "" {
+ result.SessionIdx = authnStatement.SessionIndex
+ break
+ }
+ }
+
+ // Extract attributes
+ for _, statement := range assertion.AttributeStatements {
+ for _, attr := range statement.Attributes {
+ values := make([]string, 0, len(attr.Values))
+ for _, v := range attr.Values {
+ values = append(values, v.Value)
+ }
+ result.Attributes[attr.Name] = values
+
+ // Also try FriendlyName
+ if attr.FriendlyName != "" {
+ result.Attributes[attr.FriendlyName] = values
+ }
+ }
+ }
+
+ // Extract specific attributes based on configuration
+ result.Username = s.extractAttribute(result.Attributes, s.config.UsernameAttr, result.NameID)
+ result.Email = s.extractAttribute(result.Attributes, s.config.EmailAttr, "")
+ result.FirstName = s.extractAttribute(result.Attributes, s.config.FirstNameAttr, "")
+ result.LastName = s.extractAttribute(result.Attributes, s.config.LastNameAttr, "")
+
+ // Extract groups
+ if s.config.GroupsAttr != "" {
+ if groups, ok := result.Attributes[s.config.GroupsAttr]; ok {
+ result.Groups = groups
+ }
+ }
+
+ log.Info().
+ Str("provider_id", s.providerID).
+ Str("username", result.Username).
+ Str("email", result.Email).
+ Int("groups", len(result.Groups)).
+ Msg("Processed SAML assertion")
+
+ return result, relayState, nil
+}
+
+func (s *SAMLService) extractAttribute(attrs map[string][]string, attrName, defaultValue string) string {
+ if attrName == "" {
+ return defaultValue
+ }
+ if vals, ok := attrs[attrName]; ok && len(vals) > 0 {
+ return vals[0]
+ }
+ return defaultValue
+}
+
+// GetMetadata returns the SP metadata XML
+func (s *SAMLService) GetMetadata() ([]byte, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ if s.sp == nil {
+ return nil, errors.New("service provider not initialized")
+ }
+
+ metadata := s.sp.Metadata()
+ return xml.MarshalIndent(metadata, "", " ")
+}
+
+// MakeLogoutRequest creates a SAML LogoutRequest for SLO
+func (s *SAMLService) MakeLogoutRequest(nameID, sessionIdx string) (string, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ if s.sp == nil {
+ return "", errors.New("service provider not initialized")
+ }
+
+ // Check if IdP supports SLO
+ if len(s.idpMetadata.IDPSSODescriptors) == 0 ||
+ len(s.idpMetadata.IDPSSODescriptors[0].SingleLogoutServices) == 0 {
+ return "", errors.New("idp does not support single logout")
+ }
+
+ sloService := s.idpMetadata.IDPSSODescriptors[0].SingleLogoutServices[0]
+
+ req, err := s.sp.MakeLogoutRequest(sloService.Location, nameID)
+ if err != nil {
+ return "", fmt.Errorf("failed to create logout request: %w", err)
+ }
+
+ // Build redirect URL
+ redirectURL := req.Redirect("")
+
+ return redirectURL.String(), nil
+}
+
+// RefreshMetadata reloads IdP metadata (useful for key rotation)
+func (s *SAMLService) RefreshMetadata(ctx context.Context) error {
+ if s.config.IDPMetadataURL == "" {
+ return errors.New("cannot refresh metadata without url")
+ }
+
+ if err := s.loadIDPMetadata(ctx); err != nil {
+ return err
+ }
+
+ // Reinitialize SP with new metadata
+ return s.initServiceProvider()
+}
+
+// ProviderID returns the provider identifier
+func (s *SAMLService) ProviderID() string {
+ return s.providerID
+}
+
+// GetSPEntityID returns the Service Provider Entity ID
+func (s *SAMLService) GetSPEntityID() string {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ if s.sp == nil {
+ return ""
+ }
+ return s.sp.EntityID
+}
+
+// GetIDPEntityID returns the Identity Provider Entity ID
+func (s *SAMLService) GetIDPEntityID() string {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ if s.idpMetadata == nil {
+ return ""
+ }
+ return s.idpMetadata.EntityID
+}
diff --git a/internal/api/sso_handlers.go b/internal/api/sso_handlers.go
new file mode 100644
index 0000000000..2552299b9d
--- /dev/null
+++ b/internal/api/sso_handlers.go
@@ -0,0 +1,1094 @@
+package api
+
+import (
+ "context"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/base64"
+ "encoding/json"
+ "encoding/pem"
+ "encoding/xml"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+ "time"
+
+ "github.com/crewjam/saml"
+ "github.com/google/uuid"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rs/zerolog/log"
+)
+
+// Security constants for SSO
+const (
+ maxProviderIDLength = 64
+ maxProviderNameLength = 128
+ maxURLLength = 2048
+ maxRequestBodySize = 1 << 20 // 1MB
+)
+
+// providerIDRegex validates provider IDs (alphanumeric, hyphens, underscores)
+var providerIDRegex = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}[a-zA-Z0-9]?$`)
+
+// validateProviderID checks if a provider ID is safe and valid
+func validateProviderID(id string) bool {
+ if id == "" || len(id) > maxProviderIDLength {
+ return false
+ }
+ return providerIDRegex.MatchString(id)
+}
+
+// sanitizeProviderName sanitizes a provider name
+func sanitizeProviderName(name string) string {
+ name = strings.TrimSpace(name)
+ if len(name) > maxProviderNameLength {
+ name = name[:maxProviderNameLength]
+ }
+ // Remove control characters
+ name = strings.Map(func(r rune) rune {
+ if r < 32 || r == 127 {
+ return -1
+ }
+ return r
+ }, name)
+ return name
+}
+
+// validateURL checks if a URL is valid and uses an allowed scheme
+func validateURL(urlStr string, allowedSchemes []string) bool {
+ if urlStr == "" || len(urlStr) > maxURLLength {
+ return false
+ }
+ parsed, err := url.ParseRequestURI(urlStr)
+ if err != nil {
+ return false
+ }
+ for _, scheme := range allowedSchemes {
+ if strings.EqualFold(parsed.Scheme, scheme) {
+ return true
+ }
+ }
+ return false
+}
+
+// SSOProviderResponse represents an SSO provider for API responses
+type SSOProviderResponse struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Enabled bool `json:"enabled"`
+ DisplayName string `json:"displayName,omitempty"`
+ IconURL string `json:"iconUrl,omitempty"`
+ Priority int `json:"priority"`
+
+ // OIDC-specific (only present for OIDC providers)
+ OIDCIssuerURL string `json:"oidcIssuerUrl,omitempty"`
+ OIDCClientID string `json:"oidcClientId,omitempty"`
+ OIDCClientSecretSet bool `json:"oidcClientSecretSet,omitempty"`
+
+ // SAML-specific (only present for SAML providers)
+ SAMLIDPEntityID string `json:"samlIdpEntityId,omitempty"`
+ SAMLSPEntityID string `json:"samlSpEntityId,omitempty"`
+ SAMLMetadataURL string `json:"samlMetadataUrl,omitempty"`
+ SAMLACSUrl string `json:"samlAcsUrl,omitempty"`
+
+ // Common restrictions
+ AllowedGroups []string `json:"allowedGroups,omitempty"`
+ AllowedDomains []string `json:"allowedDomains,omitempty"`
+ AllowedEmails []string `json:"allowedEmails,omitempty"`
+}
+
+// SSOProvidersListResponse represents the list of SSO providers
+type SSOProvidersListResponse struct {
+ Providers []SSOProviderResponse `json:"providers"`
+ DefaultProviderID string `json:"defaultProviderId,omitempty"`
+ AllowMultipleProviders bool `json:"allowMultipleProviders"`
+}
+
+// handleSSOProviders handles listing and creating SSO providers
+func (r *Router) handleSSOProviders(w http.ResponseWriter, req *http.Request) {
+ switch req.Method {
+ case http.MethodGet:
+ r.handleListSSOProviders(w, req)
+ case http.MethodPost:
+ r.handleCreateSSOProvider(w, req)
+ default:
+ writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)
+ }
+}
+
+// handleSSOProvider handles getting, updating, and deleting a specific SSO provider
+func (r *Router) handleSSOProvider(w http.ResponseWriter, req *http.Request) {
+ // Extract provider ID from path: /api/security/sso/providers/{id}
+ providerID := strings.TrimPrefix(req.URL.Path, "/api/security/sso/providers/")
+ providerID = strings.TrimSuffix(providerID, "/")
+
+ if providerID == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "missing_id", "Provider ID is required", nil)
+ return
+ }
+
+ // Security: Validate provider ID format to prevent injection attacks
+ if !validateProviderID(providerID) {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_id", "Invalid provider ID format", nil)
+ return
+ }
+
+ switch req.Method {
+ case http.MethodGet:
+ r.handleGetSSOProvider(w, req, providerID)
+ case http.MethodPut:
+ r.handleUpdateSSOProvider(w, req, providerID)
+ case http.MethodDelete:
+ r.handleDeleteSSOProvider(w, req, providerID)
+ default:
+ writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)
+ }
+}
+
+func (r *Router) handleListSSOProviders(w http.ResponseWriter, req *http.Request) {
+ if r.ssoConfig == nil {
+ r.ssoConfig = config.NewSSOConfig()
+ }
+
+ response := SSOProvidersListResponse{
+ Providers: make([]SSOProviderResponse, 0),
+ DefaultProviderID: r.ssoConfig.DefaultProviderID,
+ AllowMultipleProviders: r.ssoConfig.AllowMultipleProviders,
+ }
+
+ for _, p := range r.ssoConfig.Providers {
+ response.Providers = append(response.Providers, providerToResponse(&p, r.config.PublicURL))
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(response)
+}
+
+func (r *Router) handleGetSSOProvider(w http.ResponseWriter, req *http.Request, providerID string) {
+ if r.ssoConfig == nil {
+ writeErrorResponse(w, http.StatusNotFound, "not_found", "Provider not found", nil)
+ return
+ }
+
+ provider := r.ssoConfig.GetProvider(providerID)
+ if provider == nil {
+ writeErrorResponse(w, http.StatusNotFound, "not_found", "Provider not found", nil)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(providerToResponse(provider, r.config.PublicURL))
+}
+
+func (r *Router) handleCreateSSOProvider(w http.ResponseWriter, req *http.Request) {
+ body, err := io.ReadAll(io.LimitReader(req.Body, maxRequestBodySize))
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "read_error", "Failed to read request body", nil)
+ return
+ }
+
+ var provider config.SSOProvider
+ if err := json.Unmarshal(body, &provider); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Invalid JSON payload", nil)
+ return
+ }
+
+ // Generate ID if not provided
+ if provider.ID == "" {
+ provider.ID = uuid.NewString()
+ }
+
+ // Security: Validate provider ID format
+ if !validateProviderID(provider.ID) {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid provider ID format", nil)
+ return
+ }
+
+ // Sanitize provider name
+ provider.Name = sanitizeProviderName(provider.Name)
+ provider.DisplayName = sanitizeProviderName(provider.DisplayName)
+
+ // Validate provider
+ if provider.Name == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Provider name is required", nil)
+ return
+ }
+
+ if provider.Type != config.SSOProviderTypeOIDC && provider.Type != config.SSOProviderTypeSAML {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Provider type must be 'oidc' or 'saml'", nil)
+ return
+ }
+
+ // Security: Validate OIDC URLs
+ if provider.Type == config.SSOProviderTypeOIDC && provider.OIDC != nil {
+ if provider.OIDC.IssuerURL != "" && !validateURL(provider.OIDC.IssuerURL, []string{"https", "http"}) {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid OIDC issuer URL", nil)
+ return
+ }
+ if provider.OIDC.RedirectURL != "" && !validateURL(provider.OIDC.RedirectURL, []string{"https", "http"}) {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid OIDC redirect URL", nil)
+ return
+ }
+ }
+
+ // Security: Validate SAML URLs
+ if provider.Type == config.SSOProviderTypeSAML && provider.SAML != nil {
+ if provider.SAML.IDPMetadataURL != "" && !validateURL(provider.SAML.IDPMetadataURL, []string{"https", "http"}) {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid SAML metadata URL", nil)
+ return
+ }
+ if provider.SAML.IDPSSOURL != "" && !validateURL(provider.SAML.IDPSSOURL, []string{"https", "http"}) {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid SAML SSO URL", nil)
+ return
+ }
+ }
+
+ // Security: Validate icon URL if provided
+ if provider.IconURL != "" && !validateURL(provider.IconURL, []string{"https", "http", "data"}) {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid icon URL", nil)
+ return
+ }
+
+ if r.ssoConfig == nil {
+ r.ssoConfig = config.NewSSOConfig()
+ }
+
+ // Check for duplicate ID
+ if r.ssoConfig.GetProvider(provider.ID) != nil {
+ writeErrorResponse(w, http.StatusConflict, "duplicate_id", "Provider with this ID already exists", nil)
+ return
+ }
+
+ // Add provider
+ if err := r.ssoConfig.AddProvider(provider); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "add_error", err.Error(), nil)
+ return
+ }
+
+ // Persist configuration
+ if err := r.saveSSOConfig(); err != nil {
+ log.Error().Err(err).Msg("Failed to persist SSO configuration")
+ // Remove the provider we just added since persistence failed
+ r.ssoConfig.RemoveProvider(provider.ID)
+ writeErrorResponse(w, http.StatusInternalServerError, "save_error", "Failed to save configuration", nil)
+ return
+ }
+
+ // Initialize SAML provider if applicable
+ if provider.Type == config.SSOProviderTypeSAML && provider.Enabled && provider.SAML != nil {
+ if err := r.samlManager.InitializeProvider(req.Context(), provider.ID, provider.SAML); err != nil {
+ log.Warn().Err(err).Str("provider_id", provider.ID).Msg("Failed to initialize SAML provider (will retry on first use)")
+ }
+ }
+
+ LogAuditEvent("sso_provider_created", "", GetClientIP(req), req.URL.Path, true, "Created provider: "+provider.Name)
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusCreated)
+ json.NewEncoder(w).Encode(providerToResponse(&provider, r.config.PublicURL))
+}
+
+func (r *Router) handleUpdateSSOProvider(w http.ResponseWriter, req *http.Request, providerID string) {
+ if r.ssoConfig == nil {
+ writeErrorResponse(w, http.StatusNotFound, "not_found", "Provider not found", nil)
+ return
+ }
+
+ existing := r.ssoConfig.GetProvider(providerID)
+ if existing == nil {
+ writeErrorResponse(w, http.StatusNotFound, "not_found", "Provider not found", nil)
+ return
+ }
+
+ body, err := io.ReadAll(io.LimitReader(req.Body, maxRequestBodySize))
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "read_error", "Failed to read request body", nil)
+ return
+ }
+
+ var updated config.SSOProvider
+ if err := json.Unmarshal(body, &updated); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Invalid JSON payload", nil)
+ return
+ }
+
+ // Ensure ID matches
+ updated.ID = providerID
+
+ // Sanitize inputs
+ updated.Name = sanitizeProviderName(updated.Name)
+ updated.DisplayName = sanitizeProviderName(updated.DisplayName)
+
+ if updated.Name == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Provider name is required", nil)
+ return
+ }
+
+ // Security: Validate URLs for OIDC
+ if updated.Type == config.SSOProviderTypeOIDC && updated.OIDC != nil {
+ if updated.OIDC.IssuerURL != "" && !validateURL(updated.OIDC.IssuerURL, []string{"https", "http"}) {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid OIDC issuer URL", nil)
+ return
+ }
+ if updated.OIDC.RedirectURL != "" && !validateURL(updated.OIDC.RedirectURL, []string{"https", "http"}) {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid OIDC redirect URL", nil)
+ return
+ }
+ }
+
+ // Security: Validate URLs for SAML
+ if updated.Type == config.SSOProviderTypeSAML && updated.SAML != nil {
+ if updated.SAML.IDPMetadataURL != "" && !validateURL(updated.SAML.IDPMetadataURL, []string{"https", "http"}) {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid SAML metadata URL", nil)
+ return
+ }
+ if updated.SAML.IDPSSOURL != "" && !validateURL(updated.SAML.IDPSSOURL, []string{"https", "http"}) {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid SAML SSO URL", nil)
+ return
+ }
+ }
+
+ // Security: Validate icon URL if provided
+ if updated.IconURL != "" && !validateURL(updated.IconURL, []string{"https", "http", "data"}) {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid icon URL", nil)
+ return
+ }
+
+ // Preserve secrets if not provided in update
+ if updated.Type == config.SSOProviderTypeOIDC && updated.OIDC != nil && existing.OIDC != nil {
+ if updated.OIDC.ClientSecret == "" && existing.OIDC.ClientSecretSet {
+ updated.OIDC.ClientSecret = existing.OIDC.ClientSecret
+ updated.OIDC.ClientSecretSet = true
+ }
+ }
+
+ // Update provider
+ if err := r.ssoConfig.UpdateProvider(updated); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "update_error", err.Error(), nil)
+ return
+ }
+
+ // Persist configuration
+ if err := r.saveSSOConfig(); err != nil {
+ log.Error().Err(err).Msg("Failed to persist SSO configuration")
+ // Revert to existing provider
+ r.ssoConfig.UpdateProvider(*existing)
+ writeErrorResponse(w, http.StatusInternalServerError, "save_error", "Failed to save configuration", nil)
+ return
+ }
+
+ // Re-initialize SAML provider if applicable
+ if updated.Type == config.SSOProviderTypeSAML && updated.SAML != nil {
+ if updated.Enabled {
+ if err := r.samlManager.InitializeProvider(req.Context(), updated.ID, updated.SAML); err != nil {
+ log.Warn().Err(err).Str("provider_id", updated.ID).Msg("Failed to re-initialize SAML provider")
+ }
+ } else {
+ r.samlManager.RemoveProvider(updated.ID)
+ }
+ }
+
+ LogAuditEvent("sso_provider_updated", "", GetClientIP(req), req.URL.Path, true, "Updated provider: "+updated.Name)
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(providerToResponse(&updated, r.config.PublicURL))
+}
+
+func (r *Router) handleDeleteSSOProvider(w http.ResponseWriter, req *http.Request, providerID string) {
+ if r.ssoConfig == nil {
+ writeErrorResponse(w, http.StatusNotFound, "not_found", "Provider not found", nil)
+ return
+ }
+
+ existing := r.ssoConfig.GetProvider(providerID)
+ if existing == nil {
+ writeErrorResponse(w, http.StatusNotFound, "not_found", "Provider not found", nil)
+ return
+ }
+
+ // Remove provider
+ if err := r.ssoConfig.RemoveProvider(providerID); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "remove_error", err.Error(), nil)
+ return
+ }
+
+ // Persist configuration
+ if err := r.saveSSOConfig(); err != nil {
+ log.Error().Err(err).Msg("Failed to persist SSO configuration")
+ // Re-add the provider since persistence failed
+ r.ssoConfig.AddProvider(*existing)
+ writeErrorResponse(w, http.StatusInternalServerError, "save_error", "Failed to save configuration", nil)
+ return
+ }
+
+ // Remove SAML service if applicable
+ if existing.Type == config.SSOProviderTypeSAML {
+ r.samlManager.RemoveProvider(providerID)
+ }
+
+ LogAuditEvent("sso_provider_deleted", "", GetClientIP(req), req.URL.Path, true, "Deleted provider: "+existing.Name)
+
+ w.WriteHeader(http.StatusNoContent)
+}
+
+func (r *Router) saveSSOConfig() error {
+ if r.persistence == nil {
+ return nil
+ }
+ return r.persistence.SaveSSOConfig(r.ssoConfig)
+}
+
+func providerToResponse(p *config.SSOProvider, publicURL string) SSOProviderResponse {
+ resp := SSOProviderResponse{
+ ID: p.ID,
+ Name: p.Name,
+ Type: string(p.Type),
+ Enabled: p.Enabled,
+ DisplayName: p.DisplayName,
+ IconURL: p.IconURL,
+ Priority: p.Priority,
+ AllowedGroups: p.AllowedGroups,
+ AllowedDomains: p.AllowedDomains,
+ AllowedEmails: p.AllowedEmails,
+ }
+
+ if resp.DisplayName == "" {
+ resp.DisplayName = p.Name
+ }
+
+ baseURL := publicURL
+ if baseURL == "" {
+ baseURL = "http://localhost:7655"
+ }
+
+ if p.Type == config.SSOProviderTypeOIDC && p.OIDC != nil {
+ resp.OIDCIssuerURL = p.OIDC.IssuerURL
+ resp.OIDCClientID = p.OIDC.ClientID
+ resp.OIDCClientSecretSet = p.OIDC.ClientSecretSet || p.OIDC.ClientSecret != ""
+ }
+
+ if p.Type == config.SSOProviderTypeSAML && p.SAML != nil {
+ resp.SAMLIDPEntityID = p.SAML.IDPEntityID
+ if resp.SAMLIDPEntityID == "" {
+ resp.SAMLIDPEntityID = p.SAML.IDPIssuer
+ }
+ resp.SAMLSPEntityID = p.SAML.SPEntityID
+ if resp.SAMLSPEntityID == "" {
+ resp.SAMLSPEntityID = baseURL + "/saml/" + p.ID
+ }
+ resp.SAMLMetadataURL = baseURL + "/api/saml/" + p.ID + "/metadata"
+ resp.SAMLACSUrl = baseURL + "/api/saml/" + p.ID + "/acs"
+ }
+
+ return resp
+}
+
+// ============================================================================
+// SSO Provider Connection Testing
+// ============================================================================
+
+const (
+ maxTestRequestBodySize = 32 * 1024 // 32KB
+ testConnectionTimeout = 30 * time.Second
+)
+
+// SSOTestRequest represents a request to test SSO provider configuration
+type SSOTestRequest struct {
+ Type string `json:"type"` // "saml" or "oidc"
+ SAML *SAMLTestConfig `json:"saml,omitempty"`
+ OIDC *OIDCTestConfig `json:"oidc,omitempty"`
+}
+
+// SAMLTestConfig contains SAML configuration to test
+type SAMLTestConfig struct {
+ IDPMetadataURL string `json:"idpMetadataUrl,omitempty"`
+ IDPMetadataXML string `json:"idpMetadataXml,omitempty"`
+ IDPSSOURL string `json:"idpSsoUrl,omitempty"`
+ IDPCertificate string `json:"idpCertificate,omitempty"`
+}
+
+// OIDCTestConfig contains OIDC configuration to test
+type OIDCTestConfig struct {
+ IssuerURL string `json:"issuerUrl"`
+ ClientID string `json:"clientId,omitempty"`
+}
+
+// SSOTestResponse represents the result of a connection test
+type SSOTestResponse struct {
+ Success bool `json:"success"`
+ Message string `json:"message"`
+ Error string `json:"error,omitempty"`
+ Details *SSOTestDetails `json:"details,omitempty"`
+}
+
+// SSOTestDetails contains detailed information about the tested provider
+type SSOTestDetails struct {
+ Type string `json:"type"`
+ EntityID string `json:"entityId,omitempty"`
+ SSOURL string `json:"ssoUrl,omitempty"`
+ SLOURL string `json:"sloUrl,omitempty"`
+ Certificates []CertificateInfo `json:"certificates,omitempty"`
+ // OIDC-specific
+ TokenEndpoint string `json:"tokenEndpoint,omitempty"`
+ UserinfoEndpoint string `json:"userinfoEndpoint,omitempty"`
+ JwksURI string `json:"jwksUri,omitempty"`
+ SupportedScopes []string `json:"supportedScopes,omitempty"`
+}
+
+// CertificateInfo contains certificate details
+type CertificateInfo struct {
+ Subject string `json:"subject"`
+ Issuer string `json:"issuer"`
+ NotBefore time.Time `json:"notBefore"`
+ NotAfter time.Time `json:"notAfter"`
+ IsExpired bool `json:"isExpired"`
+}
+
+// handleTestSSOProvider tests an SSO provider configuration
+func (r *Router) handleTestSSOProvider(w http.ResponseWriter, req *http.Request) {
+ if req.Method != http.MethodPost {
+ writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)
+ return
+ }
+
+ // Rate limiting
+ clientIP := GetClientIP(req)
+ if !authLimiter.Allow(clientIP) {
+ writeErrorResponse(w, http.StatusTooManyRequests, "rate_limited", "Too many requests", nil)
+ return
+ }
+
+ body, err := io.ReadAll(io.LimitReader(req.Body, maxTestRequestBodySize))
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "read_error", "Failed to read request body", nil)
+ return
+ }
+
+ var testReq SSOTestRequest
+ if err := json.Unmarshal(body, &testReq); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Invalid JSON payload", nil)
+ return
+ }
+
+ // Validate request
+ if testReq.Type != "saml" && testReq.Type != "oidc" {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Type must be 'saml' or 'oidc'", nil)
+ return
+ }
+
+ var response SSOTestResponse
+
+ ctx, cancel := context.WithTimeout(req.Context(), testConnectionTimeout)
+ defer cancel()
+
+ switch testReq.Type {
+ case "saml":
+ response = r.testSAMLConnection(ctx, testReq.SAML)
+ case "oidc":
+ response = r.testOIDCConnection(ctx, testReq.OIDC)
+ }
+
+ LogAuditEvent("sso_provider_test", "", clientIP, req.URL.Path, response.Success,
+ "Tested "+testReq.Type+" provider connection")
+
+ w.Header().Set("Content-Type", "application/json")
+ if response.Success {
+ w.WriteHeader(http.StatusOK)
+ } else {
+ w.WriteHeader(http.StatusBadRequest)
+ }
+ json.NewEncoder(w).Encode(response)
+}
+
+func (r *Router) testSAMLConnection(ctx context.Context, cfg *SAMLTestConfig) SSOTestResponse {
+ if cfg == nil {
+ return SSOTestResponse{
+ Success: false,
+ Message: "SAML configuration is required",
+ Error: "missing_config",
+ }
+ }
+
+ // Need at least one source of metadata
+ if cfg.IDPMetadataURL == "" && cfg.IDPMetadataXML == "" && cfg.IDPSSOURL == "" {
+ return SSOTestResponse{
+ Success: false,
+ Message: "Provide IdP Metadata URL, XML, or SSO URL",
+ Error: "missing_metadata",
+ }
+ }
+
+ // Validate URLs
+ if cfg.IDPMetadataURL != "" && !validateURL(cfg.IDPMetadataURL, []string{"https", "http"}) {
+ return SSOTestResponse{
+ Success: false,
+ Message: "Invalid metadata URL format",
+ Error: "invalid_url",
+ }
+ }
+
+ var metadata *saml.EntityDescriptor
+ var rawXML []byte
+ var err error
+
+ httpClient := newTestHTTPClient()
+
+ if cfg.IDPMetadataURL != "" {
+ rawXML, metadata, err = fetchSAMLMetadataFromURL(ctx, httpClient, cfg.IDPMetadataURL)
+ if err != nil {
+ return SSOTestResponse{
+ Success: false,
+ Message: "Failed to fetch metadata from URL",
+ Error: err.Error(),
+ }
+ }
+ } else if cfg.IDPMetadataXML != "" {
+ rawXML = []byte(cfg.IDPMetadataXML)
+ metadata, err = parseSAMLMetadataXML(rawXML)
+ if err != nil {
+ return SSOTestResponse{
+ Success: false,
+ Message: "Failed to parse metadata XML",
+ Error: err.Error(),
+ }
+ }
+ } else {
+ // Manual configuration - just validate the SSO URL
+ if !validateURL(cfg.IDPSSOURL, []string{"https", "http"}) {
+ return SSOTestResponse{
+ Success: false,
+ Message: "Invalid SSO URL format",
+ Error: "invalid_url",
+ }
+ }
+ return SSOTestResponse{
+ Success: true,
+ Message: "SSO URL is valid (manual configuration)",
+ Details: &SSOTestDetails{
+ Type: "saml",
+ SSOURL: cfg.IDPSSOURL,
+ },
+ }
+ }
+
+ // Extract details from metadata
+ details := &SSOTestDetails{
+ Type: "saml",
+ EntityID: metadata.EntityID,
+ }
+
+ // Extract SSO URL
+ if len(metadata.IDPSSODescriptors) > 0 {
+ idpDesc := metadata.IDPSSODescriptors[0]
+ for _, sso := range idpDesc.SingleSignOnServices {
+ if sso.Binding == saml.HTTPPostBinding || sso.Binding == saml.HTTPRedirectBinding {
+ details.SSOURL = sso.Location
+ break
+ }
+ }
+ // Extract SLO URL
+ for _, slo := range idpDesc.SingleLogoutServices {
+ details.SLOURL = slo.Location
+ break
+ }
+ // Extract certificates
+ for _, kd := range idpDesc.KeyDescriptors {
+ if kd.Use == "signing" || kd.Use == "" {
+ for _, x509Cert := range kd.KeyInfo.X509Data.X509Certificates {
+ certInfo := extractCertificateInfo(x509Cert.Data)
+ if certInfo != nil {
+ details.Certificates = append(details.Certificates, *certInfo)
+ }
+ }
+ }
+ }
+ }
+
+ _ = rawXML // Used for metadata preview endpoint
+
+ return SSOTestResponse{
+ Success: true,
+ Message: "SAML metadata validated successfully",
+ Details: details,
+ }
+}
+
+func (r *Router) testOIDCConnection(ctx context.Context, cfg *OIDCTestConfig) SSOTestResponse {
+ if cfg == nil {
+ return SSOTestResponse{
+ Success: false,
+ Message: "OIDC configuration is required",
+ Error: "missing_config",
+ }
+ }
+
+ if cfg.IssuerURL == "" {
+ return SSOTestResponse{
+ Success: false,
+ Message: "Issuer URL is required",
+ Error: "missing_issuer",
+ }
+ }
+
+ if !validateURL(cfg.IssuerURL, []string{"https", "http"}) {
+ return SSOTestResponse{
+ Success: false,
+ Message: "Invalid issuer URL format",
+ Error: "invalid_url",
+ }
+ }
+
+ // Fetch OIDC discovery document
+ discoveryURL := strings.TrimRight(cfg.IssuerURL, "/") + "/.well-known/openid-configuration"
+
+ httpClient := newTestHTTPClient()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, discoveryURL, nil)
+ if err != nil {
+ return SSOTestResponse{
+ Success: false,
+ Message: "Failed to create discovery request",
+ Error: err.Error(),
+ }
+ }
+
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ return SSOTestResponse{
+ Success: false,
+ Message: "Failed to fetch OIDC discovery document",
+ Error: err.Error(),
+ }
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return SSOTestResponse{
+ Success: false,
+ Message: "OIDC discovery returned non-200 status",
+ Error: resp.Status,
+ }
+ }
+
+ body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ if err != nil {
+ return SSOTestResponse{
+ Success: false,
+ Message: "Failed to read discovery response",
+ Error: err.Error(),
+ }
+ }
+
+ var discovery struct {
+ Issuer string `json:"issuer"`
+ AuthorizationEndpoint string `json:"authorization_endpoint"`
+ TokenEndpoint string `json:"token_endpoint"`
+ UserinfoEndpoint string `json:"userinfo_endpoint"`
+ JwksURI string `json:"jwks_uri"`
+ ScopesSupported []string `json:"scopes_supported"`
+ }
+
+ if err := json.Unmarshal(body, &discovery); err != nil {
+ return SSOTestResponse{
+ Success: false,
+ Message: "Failed to parse discovery document",
+ Error: err.Error(),
+ }
+ }
+
+ // Validate issuer matches
+ if discovery.Issuer != cfg.IssuerURL && discovery.Issuer != strings.TrimRight(cfg.IssuerURL, "/") {
+ log.Warn().
+ Str("expected", cfg.IssuerURL).
+ Str("actual", discovery.Issuer).
+ Msg("OIDC issuer mismatch - this may cause token validation issues")
+ }
+
+ details := &SSOTestDetails{
+ Type: "oidc",
+ EntityID: discovery.Issuer,
+ TokenEndpoint: discovery.TokenEndpoint,
+ UserinfoEndpoint: discovery.UserinfoEndpoint,
+ JwksURI: discovery.JwksURI,
+ SupportedScopes: discovery.ScopesSupported,
+ }
+
+ return SSOTestResponse{
+ Success: true,
+ Message: "OIDC discovery successful",
+ Details: details,
+ }
+}
+
+// ============================================================================
+// SSO Metadata Preview
+// ============================================================================
+
+// MetadataPreviewRequest represents a request to preview IdP metadata
+type MetadataPreviewRequest struct {
+ Type string `json:"type"` // "saml"
+ MetadataURL string `json:"metadataUrl,omitempty"`
+ MetadataXML string `json:"metadataXml,omitempty"`
+}
+
+// MetadataPreviewResponse contains the metadata preview
+type MetadataPreviewResponse struct {
+ XML string `json:"xml"`
+ Parsed *ParsedMetadataInfo `json:"parsed"`
+}
+
+// ParsedMetadataInfo contains parsed metadata information
+type ParsedMetadataInfo struct {
+ EntityID string `json:"entityId"`
+ SSOURL string `json:"ssoUrl,omitempty"`
+ SLOURL string `json:"sloUrl,omitempty"`
+ Certificates []CertificateInfo `json:"certificates,omitempty"`
+ NameIDFormats []string `json:"nameIdFormats,omitempty"`
+}
+
+// handleMetadataPreview fetches and displays IdP metadata
+func (r *Router) handleMetadataPreview(w http.ResponseWriter, req *http.Request) {
+ if req.Method != http.MethodPost {
+ writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed", nil)
+ return
+ }
+
+ // Rate limiting
+ clientIP := GetClientIP(req)
+ if !authLimiter.Allow(clientIP) {
+ writeErrorResponse(w, http.StatusTooManyRequests, "rate_limited", "Too many requests", nil)
+ return
+ }
+
+ body, err := io.ReadAll(io.LimitReader(req.Body, maxTestRequestBodySize))
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "read_error", "Failed to read request body", nil)
+ return
+ }
+
+ var previewReq MetadataPreviewRequest
+ if err := json.Unmarshal(body, &previewReq); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Invalid JSON payload", nil)
+ return
+ }
+
+ if previewReq.Type != "saml" {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Only SAML metadata preview is supported", nil)
+ return
+ }
+
+ if previewReq.MetadataURL == "" && previewReq.MetadataXML == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Provide either metadataUrl or metadataXml", nil)
+ return
+ }
+
+ ctx, cancel := context.WithTimeout(req.Context(), testConnectionTimeout)
+ defer cancel()
+
+ var rawXML []byte
+ var metadata *saml.EntityDescriptor
+
+ httpClient := newTestHTTPClient()
+
+ if previewReq.MetadataURL != "" {
+ if !validateURL(previewReq.MetadataURL, []string{"https", "http"}) {
+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", "Invalid metadata URL", nil)
+ return
+ }
+ rawXML, metadata, err = fetchSAMLMetadataFromURL(ctx, httpClient, previewReq.MetadataURL)
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "fetch_error", "Failed to fetch metadata: "+err.Error(), nil)
+ return
+ }
+ } else {
+ rawXML = []byte(previewReq.MetadataXML)
+ metadata, err = parseSAMLMetadataXML(rawXML)
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "parse_error", "Failed to parse metadata: "+err.Error(), nil)
+ return
+ }
+ }
+
+ // Build parsed info
+ parsed := &ParsedMetadataInfo{
+ EntityID: metadata.EntityID,
+ }
+
+ if len(metadata.IDPSSODescriptors) > 0 {
+ idpDesc := metadata.IDPSSODescriptors[0]
+
+ // Extract SSO URL
+ for _, sso := range idpDesc.SingleSignOnServices {
+ if sso.Binding == saml.HTTPPostBinding || sso.Binding == saml.HTTPRedirectBinding {
+ parsed.SSOURL = sso.Location
+ break
+ }
+ }
+
+ // Extract SLO URL
+ for _, slo := range idpDesc.SingleLogoutServices {
+ parsed.SLOURL = slo.Location
+ break
+ }
+
+ // Extract NameID formats
+ for _, nid := range idpDesc.NameIDFormats {
+ parsed.NameIDFormats = append(parsed.NameIDFormats, string(nid))
+ }
+
+ // Extract certificates
+ for _, kd := range idpDesc.KeyDescriptors {
+ if kd.Use == "signing" || kd.Use == "" {
+ for _, x509Cert := range kd.KeyInfo.X509Data.X509Certificates {
+ certInfo := extractCertificateInfo(x509Cert.Data)
+ if certInfo != nil {
+ parsed.Certificates = append(parsed.Certificates, *certInfo)
+ }
+ }
+ }
+ }
+ }
+
+ // Format XML for display
+ formattedXML := formatXML(rawXML)
+
+ response := MetadataPreviewResponse{
+ XML: formattedXML,
+ Parsed: parsed,
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(response)
+}
+
+// ============================================================================
+// Helper Functions
+// ============================================================================
+
+func newTestHTTPClient() *http.Client {
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ transport.TLSClientConfig = &tls.Config{
+ MinVersion: tls.VersionTLS12,
+ }
+ return &http.Client{
+ Transport: transport,
+ Timeout: testConnectionTimeout,
+ }
+}
+
+func fetchSAMLMetadataFromURL(ctx context.Context, client *http.Client, metadataURL string) ([]byte, *saml.EntityDescriptor, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, metadataURL, nil)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, nil, fmt.Errorf("metadata request returned status %d", resp.StatusCode)
+ }
+
+ body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) // 1MB limit
+ if err != nil {
+ return nil, nil, err
+ }
+
+ metadata, err := parseSAMLMetadataXML(body)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ return body, metadata, nil
+}
+
+func parseSAMLMetadataXML(data []byte) (*saml.EntityDescriptor, error) {
+ var metadata saml.EntityDescriptor
+ if err := xml.Unmarshal(data, &metadata); err != nil {
+ // Try parsing as EntitiesDescriptor
+ var entities saml.EntitiesDescriptor
+ if err2 := xml.Unmarshal(data, &entities); err2 != nil {
+ return nil, fmt.Errorf("failed to parse metadata: %v", err)
+ }
+ if len(entities.EntityDescriptors) == 0 {
+ return nil, fmt.Errorf("no entity descriptors found in metadata")
+ }
+ metadata = entities.EntityDescriptors[0]
+ }
+ return &metadata, nil
+}
+
+func extractCertificateInfo(certData string) *CertificateInfo {
+ // Remove whitespace and decode base64
+ certData = strings.ReplaceAll(certData, "\n", "")
+ certData = strings.ReplaceAll(certData, "\r", "")
+ certData = strings.ReplaceAll(certData, " ", "")
+
+ // Try to decode as PEM first
+ var derBytes []byte
+ block, _ := pem.Decode([]byte(certData))
+ if block != nil {
+ derBytes = block.Bytes
+ } else {
+ // Assume it's base64 encoded DER
+ var err error
+ derBytes, err = base64Decode(certData)
+ if err != nil {
+ return nil
+ }
+ }
+
+ cert, err := x509.ParseCertificate(derBytes)
+ if err != nil {
+ return nil
+ }
+
+ return &CertificateInfo{
+ Subject: cert.Subject.String(),
+ Issuer: cert.Issuer.String(),
+ NotBefore: cert.NotBefore,
+ NotAfter: cert.NotAfter,
+ IsExpired: time.Now().After(cert.NotAfter),
+ }
+}
+
+func base64Decode(s string) ([]byte, error) {
+ // Try standard base64 first
+ decoded, err := base64.StdEncoding.DecodeString(s)
+ if err != nil {
+ // Try URL-safe base64
+ decoded, err = base64.URLEncoding.DecodeString(s)
+ }
+ return decoded, err
+}
+
+func formatXML(data []byte) string {
+ // Try to pretty-print the XML
+ var buf strings.Builder
+ decoder := xml.NewDecoder(strings.NewReader(string(data)))
+ encoder := xml.NewEncoder(&buf)
+ encoder.Indent("", " ")
+
+ for {
+ token, err := decoder.Token()
+ if err != nil {
+ break
+ }
+ if err := encoder.EncodeToken(token); err != nil {
+ // Fall back to original
+ return string(data)
+ }
+ }
+ encoder.Flush()
+
+ if buf.Len() > 0 {
+ return buf.String()
+ }
+ return string(data)
+}
diff --git a/internal/api/sso_handlers_test.go b/internal/api/sso_handlers_test.go
new file mode 100644
index 0000000000..d288413601
--- /dev/null
+++ b/internal/api/sso_handlers_test.go
@@ -0,0 +1,555 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+)
+
+// Counter for generating unique test IPs to avoid rate limiting
+var testIPCounter uint64
+
+// getUniqueTestIP returns a unique IP for each test to avoid rate limiting
+func getUniqueTestIP() string {
+ n := atomic.AddUint64(&testIPCounter, 1)
+ return fmt.Sprintf("10.%d.%d.%d", (n>>16)&255, (n>>8)&255, n&255)
+}
+
+// setTestIP sets a unique IP on the request to avoid rate limiting
+func setTestIP(req *http.Request) {
+ ip := getUniqueTestIP()
+ req.RemoteAddr = ip + ":12345"
+}
+
+// Sample SAML metadata for testing
+const testSAMLMetadata = `<?xml version="1.0" encoding="UTF-8"?>
+<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="https://idp.example.com">
+ <IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
+ <KeyDescriptor use="signing">
+ <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
+ <X509Data>
+ <X509Certificate>MIICpDCCAYwCCQDU+pQ4P3rFWjANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwHhcNMjQwMTAxMDAwMDAwWhcNMjcwMTAxMDAwMDAwWjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC7o5e7Xv6ufFhDFQgGX4cMi2e0q1z1E+xJxPJ7mQK0lCk5Y6r6J0fHxXrLJ7kA6mMj6F/D8r9ZgT0rQ1eV6H8xJU4z+C/w5E9JQ+YB7EZ8x0mC3z9HxKM7qM3eF7+Y5TJb3l0N5E1C2vL7qJX5Z6T2N8vA/8R5kE+g0m3E7Y6z7K2N6E9A0J8F5E3D2V6N9G0H1I2J3K4L5M6N7O8P9Q0R1S2T3U4V5W6X7Y8Z9</X509Certificate>
+ </X509Data>
+ </KeyInfo>
+ </KeyDescriptor>
+ <SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://idp.example.com/sso"/>
+ <SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://idp.example.com/sso"/>
+ <SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://idp.example.com/slo"/>
+ </IDPSSODescriptor>
+</EntityDescriptor>`
+
+// Sample OIDC discovery document
+const testOIDCDiscovery = `{
+ "issuer": "https://idp.example.com",
+ "authorization_endpoint": "https://idp.example.com/oauth2/authorize",
+ "token_endpoint": "https://idp.example.com/oauth2/token",
+ "userinfo_endpoint": "https://idp.example.com/oauth2/userinfo",
+ "jwks_uri": "https://idp.example.com/.well-known/jwks.json",
+ "scopes_supported": ["openid", "profile", "email"]
+}`
+
+func TestHandleTestSSOProvider_SAMLSuccess(t *testing.T) {
+ // Create mock SAML metadata server
+ metadataServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/xml")
+ w.Write([]byte(testSAMLMetadata))
+ }))
+ defer metadataServer.Close()
+
+ reqBody := SSOTestRequest{
+ Type: "saml",
+ SAML: &SAMLTestConfig{
+ IDPMetadataURL: metadataServer.URL,
+ },
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/test", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleTestSSOProvider(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
+ }
+
+ var resp SSOTestResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("failed to unmarshal response: %v", err)
+ }
+
+ if !resp.Success {
+ t.Errorf("expected success=true, got false: %s", resp.Error)
+ }
+
+ if resp.Details == nil {
+ t.Fatal("expected details to be present")
+ }
+
+ if resp.Details.EntityID != "https://idp.example.com" {
+ t.Errorf("expected entityId='https://idp.example.com', got '%s'", resp.Details.EntityID)
+ }
+
+ if resp.Details.SSOURL != "https://idp.example.com/sso" {
+ t.Errorf("expected ssoUrl='https://idp.example.com/sso', got '%s'", resp.Details.SSOURL)
+ }
+}
+
+func TestHandleTestSSOProvider_SAMLMetadataXML(t *testing.T) {
+ reqBody := SSOTestRequest{
+ Type: "saml",
+ SAML: &SAMLTestConfig{
+ IDPMetadataXML: testSAMLMetadata,
+ },
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/test", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleTestSSOProvider(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
+ }
+
+ var resp SSOTestResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("failed to unmarshal response: %v", err)
+ }
+
+ if !resp.Success {
+ t.Errorf("expected success=true, got false: %s", resp.Error)
+ }
+
+ if resp.Details.EntityID != "https://idp.example.com" {
+ t.Errorf("expected entityId='https://idp.example.com', got '%s'", resp.Details.EntityID)
+ }
+}
+
+func TestHandleTestSSOProvider_SAMLFetchError(t *testing.T) {
+ // Server that returns 500
+ errorServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusInternalServerError)
+ }))
+ defer errorServer.Close()
+
+ reqBody := SSOTestRequest{
+ Type: "saml",
+ SAML: &SAMLTestConfig{
+ IDPMetadataURL: errorServer.URL,
+ },
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/test", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleTestSSOProvider(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
+ }
+
+ var resp SSOTestResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("failed to unmarshal response: %v", err)
+ }
+
+ if resp.Success {
+ t.Error("expected success=false, got true")
+ }
+}
+
+func TestHandleTestSSOProvider_SAMLInvalidXML(t *testing.T) {
+ reqBody := SSOTestRequest{
+ Type: "saml",
+ SAML: &SAMLTestConfig{
+ IDPMetadataXML: "not valid xml",
+ },
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/test", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleTestSSOProvider(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
+ }
+
+ var resp SSOTestResponse
+ json.Unmarshal(rec.Body.Bytes(), &resp)
+
+ if resp.Success {
+ t.Error("expected success=false for invalid XML")
+ }
+}
+
+func TestHandleTestSSOProvider_OIDCSuccess(t *testing.T) {
+ // Create mock OIDC discovery server
+ discoveryServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/.well-known/openid-configuration" {
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte(testOIDCDiscovery))
+ } else {
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer discoveryServer.Close()
+
+ reqBody := SSOTestRequest{
+ Type: "oidc",
+ OIDC: &OIDCTestConfig{
+ IssuerURL: discoveryServer.URL,
+ },
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/test", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleTestSSOProvider(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
+ }
+
+ var resp SSOTestResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("failed to unmarshal response: %v", err)
+ }
+
+ if !resp.Success {
+ t.Errorf("expected success=true, got false: %s", resp.Error)
+ }
+
+ if resp.Details == nil {
+ t.Fatal("expected details to be present")
+ }
+
+ if resp.Details.TokenEndpoint == "" {
+ t.Error("expected tokenEndpoint to be present")
+ }
+}
+
+func TestHandleTestSSOProvider_OIDCFetchError(t *testing.T) {
+ reqBody := SSOTestRequest{
+ Type: "oidc",
+ OIDC: &OIDCTestConfig{
+ IssuerURL: "http://localhost:99999", // Invalid port
+ },
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/test", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleTestSSOProvider(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
+ }
+
+ var resp SSOTestResponse
+ json.Unmarshal(rec.Body.Bytes(), &resp)
+
+ if resp.Success {
+ t.Error("expected success=false for unreachable server")
+ }
+}
+
+func TestHandleTestSSOProvider_InvalidType(t *testing.T) {
+ reqBody := map[string]string{
+ "type": "invalid",
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/test", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleTestSSOProvider(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
+ }
+}
+
+func TestHandleTestSSOProvider_MissingConfig(t *testing.T) {
+ tests := []struct {
+ name string
+ reqBody SSOTestRequest
+ }{
+ {
+ name: "saml without config",
+ reqBody: SSOTestRequest{
+ Type: "saml",
+ },
+ },
+ {
+ name: "oidc without config",
+ reqBody: SSOTestRequest{
+ Type: "oidc",
+ },
+ },
+ {
+ name: "saml with empty config",
+ reqBody: SSOTestRequest{
+ Type: "saml",
+ SAML: &SAMLTestConfig{},
+ },
+ },
+ {
+ name: "oidc with empty issuer",
+ reqBody: SSOTestRequest{
+ Type: "oidc",
+ OIDC: &OIDCTestConfig{},
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ body, _ := json.Marshal(tt.reqBody)
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/test", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleTestSSOProvider(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Errorf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
+ }
+
+ var resp SSOTestResponse
+ json.Unmarshal(rec.Body.Bytes(), &resp)
+
+ if resp.Success {
+ t.Error("expected success=false for missing config")
+ }
+ })
+ }
+}
+
+func TestHandleMetadataPreview_Success(t *testing.T) {
+ // Create mock metadata server
+ metadataServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/xml")
+ w.Write([]byte(testSAMLMetadata))
+ }))
+ defer metadataServer.Close()
+
+ reqBody := MetadataPreviewRequest{
+ Type: "saml",
+ MetadataURL: metadataServer.URL,
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/metadata/preview", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleMetadataPreview(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
+ }
+
+ var resp MetadataPreviewResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("failed to unmarshal response: %v", err)
+ }
+
+ if resp.XML == "" {
+ t.Error("expected XML content to be present")
+ }
+
+ if resp.Parsed == nil {
+ t.Fatal("expected parsed info to be present")
+ }
+
+ if resp.Parsed.EntityID != "https://idp.example.com" {
+ t.Errorf("expected entityId='https://idp.example.com', got '%s'", resp.Parsed.EntityID)
+ }
+
+ if resp.Parsed.SSOURL != "https://idp.example.com/sso" {
+ t.Errorf("expected ssoUrl='https://idp.example.com/sso', got '%s'", resp.Parsed.SSOURL)
+ }
+}
+
+func TestHandleMetadataPreview_FromXML(t *testing.T) {
+ reqBody := MetadataPreviewRequest{
+ Type: "saml",
+ MetadataXML: testSAMLMetadata,
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/metadata/preview", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleMetadataPreview(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
+ }
+
+ var resp MetadataPreviewResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("failed to unmarshal response: %v", err)
+ }
+
+ if resp.Parsed.EntityID != "https://idp.example.com" {
+ t.Errorf("expected entityId='https://idp.example.com', got '%s'", resp.Parsed.EntityID)
+ }
+}
+
+func TestHandleMetadataPreview_InvalidURL(t *testing.T) {
+ reqBody := MetadataPreviewRequest{
+ Type: "saml",
+ MetadataURL: "not-a-valid-url",
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/metadata/preview", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleMetadataPreview(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
+ }
+}
+
+func TestHandleMetadataPreview_FetchError(t *testing.T) {
+ reqBody := MetadataPreviewRequest{
+ Type: "saml",
+ MetadataURL: "http://localhost:99999/metadata",
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/metadata/preview", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleMetadataPreview(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
+ }
+}
+
+func TestHandleMetadataPreview_UnsupportedType(t *testing.T) {
+ reqBody := MetadataPreviewRequest{
+ Type: "oidc",
+ MetadataURL: "https://example.com",
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/metadata/preview", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleMetadataPreview(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
+ }
+}
+
+func TestHandleMetadataPreview_MissingInput(t *testing.T) {
+ reqBody := MetadataPreviewRequest{
+ Type: "saml",
+ // No URL or XML
+ }
+ body, _ := json.Marshal(reqBody)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/security/sso/providers/metadata/preview", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ setTestIP(req)
+ rec := httptest.NewRecorder()
+
+ router := &Router{}
+ router.handleMetadataPreview(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected status %d, got %d", http.StatusBadRequest, rec.Code)
+ }
+}
+
+// Test helper functions
+func TestParseSAMLMetadataXML(t *testing.T) {
+ metadata, err := parseSAMLMetadataXML([]byte(testSAMLMetadata))
+ if err != nil {
+ t.Fatalf("failed to parse valid metadata: %v", err)
+ }
+
+ if metadata.EntityID != "https://idp.example.com" {
+ t.Errorf("expected entityID='https://idp.example.com', got '%s'", metadata.EntityID)
+ }
+
+ if len(metadata.IDPSSODescriptors) == 0 {
+ t.Fatal("expected IDPSSODescriptors to be present")
+ }
+}
+
+func TestParseSAMLMetadataXML_Invalid(t *testing.T) {
+ _, err := parseSAMLMetadataXML([]byte("not xml"))
+ if err == nil {
+ t.Error("expected error for invalid XML")
+ }
+}
+
+func TestFormatXML(t *testing.T) {
+ input := `<root><child>value</child></root>`
+ output := formatXML([]byte(input))
+
+ // Should contain indentation
+ if output == input {
+ t.Log("XML formatting may not have added indentation, but that's acceptable")
+ }
+
+ // Should still contain the data
+ if !bytes.Contains([]byte(output), []byte("value")) {
+ t.Error("formatted XML should still contain original content")
+ }
+}
diff --git a/internal/config/sso.go b/internal/config/sso.go
new file mode 100644
index 0000000000..99fdb85706
--- /dev/null
+++ b/internal/config/sso.go
@@ -0,0 +1,461 @@
+package config
+
+import (
+ "fmt"
+ "net/url"
+ "strings"
+)
+
+// SSOProviderType defines the type of SSO provider
+type SSOProviderType string
+
+const (
+ SSOProviderTypeOIDC SSOProviderType = "oidc"
+ SSOProviderTypeSAML SSOProviderType = "saml"
+)
+
+// SSOProvider represents a single SSO identity provider configuration.
+// It can be either OIDC or SAML type.
+type SSOProvider struct {
+ // Common fields
+ ID string `json:"id"` // Unique identifier (auto-generated if empty)
+ Name string `json:"name"` // Display name (e.g., "Corporate SSO", "Google", "Okta")
+ Type SSOProviderType `json:"type"` // "oidc" or "saml"
+ Enabled bool `json:"enabled"` // Whether this provider is active
+ DisplayName string `json:"displayName,omitempty"` // Button text on login page (defaults to Name)
+ IconURL string `json:"iconUrl,omitempty"` // Optional icon URL for login button
+ Priority int `json:"priority,omitempty"` // Display order (lower = higher priority)
+
+ // Access restrictions (apply to both OIDC and SAML)
+ AllowedGroups []string `json:"allowedGroups,omitempty"` // Restrict to specific groups
+ AllowedDomains []string `json:"allowedDomains,omitempty"` // Restrict to email domains
+ AllowedEmails []string `json:"allowedEmails,omitempty"` // Restrict to specific emails
+
+ // Role mapping (apply to both OIDC and SAML)
+ GroupsClaim string `json:"groupsClaim,omitempty"` // Claim/attribute containing groups
+ GroupRoleMappings map[string]string `json:"groupRoleMappings,omitempty"` // Map groups to Pulse roles
+
+ // OIDC-specific configuration
+ OIDC *OIDCProviderConfig `json:"oidc,omitempty"`
+
+ // SAML-specific configuration
+ SAML *SAMLProviderConfig `json:"saml,omitempty"`
+}
+
+// OIDCProviderConfig contains OIDC-specific settings
+type OIDCProviderConfig struct {
+ IssuerURL string `json:"issuerUrl"`
+ ClientID string `json:"clientId"`
+ ClientSecret string `json:"clientSecret,omitempty"`
+ RedirectURL string `json:"redirectUrl,omitempty"` // Optional - auto-detected if empty
+ LogoutURL string `json:"logoutUrl,omitempty"` // Optional OIDC end-session URL
+ Scopes []string `json:"scopes,omitempty"` // Defaults to ["openid", "profile", "email"]
+ UsernameClaim string `json:"usernameClaim,omitempty"`
+ EmailClaim string `json:"emailClaim,omitempty"`
+ CABundle string `json:"caBundle,omitempty"` // Path to CA bundle for self-signed certs
+
+ // Internal tracking
+ ClientSecretSet bool `json:"clientSecretSet,omitempty"` // True if secret is configured (don't expose actual value)
+ EnvOverrides map[string]bool `json:"-"` // Fields locked by env vars
+}
+
+// SAMLProviderConfig contains SAML 2.0 specific settings
+type SAMLProviderConfig struct {
+ // Identity Provider settings (from IdP metadata)
+ IDPMetadataURL string `json:"idpMetadataUrl,omitempty"` // URL to fetch IdP metadata (preferred)
+ IDPMetadataXML string `json:"idpMetadataXml,omitempty"` // Raw XML metadata (alternative to URL)
+ IDPSSOURL string `json:"idpSsoUrl,omitempty"` // SSO URL (extracted from metadata or manual)
+ IDPSLOUrl string `json:"idpSloUrl,omitempty"` // Single Logout URL (optional)
+ IDPCertificate string `json:"idpCertificate,omitempty"` // IdP signing certificate (PEM format)
+ IDPCertFile string `json:"idpCertFile,omitempty"` // Path to IdP certificate file (alternative)
+ IDPEntityID string `json:"idpEntityId,omitempty"` // IdP Entity ID (extracted from metadata or manual)
+ IDPIssuer string `json:"idpIssuer,omitempty"` // Alias for IDPEntityID for compatibility
+
+ // Service Provider settings (Pulse as SP)
+ SPEntityID string `json:"spEntityId,omitempty"` // Pulse's Entity ID (auto-generated if empty)
+ SPACSPath string `json:"spAcsPath,omitempty"` // Assertion Consumer Service path (default: /api/saml/{id}/acs)
+ SPMetadataPath string `json:"spMetadataPath,omitempty"` // SP Metadata path (default: /api/saml/{id}/metadata)
+ SPCertificate string `json:"spCertificate,omitempty"` // SP signing certificate (PEM format, optional)
+ SPPrivateKey string `json:"spPrivateKey,omitempty"` // SP private key (PEM format, optional)
+ SPCertFile string `json:"spCertFile,omitempty"` // Path to SP certificate file
+ SPKeyFile string `json:"spKeyFile,omitempty"` // Path to SP private key file
+ SignRequests bool `json:"signRequests,omitempty"` // Sign SAML requests (requires SP cert/key)
+ WantAssertionsSigned bool `json:"wantAssertionsSigned,omitempty"` // Require signed assertions (recommended)
+ AllowUnencrypted bool `json:"allowUnencrypted,omitempty"` // Allow unencrypted assertions (less secure)
+
+ // Attribute mapping
+ UsernameAttr string `json:"usernameAttr,omitempty"` // SAML attribute for username (default: NameID)
+ EmailAttr string `json:"emailAttr,omitempty"` // SAML attribute for email
+ GroupsAttr string `json:"groupsAttr,omitempty"` // SAML attribute for groups
+ FirstNameAttr string `json:"firstNameAttr,omitempty"`
+ LastNameAttr string `json:"lastNameAttr,omitempty"`
+
+ // Advanced settings
+ NameIDFormat string `json:"nameIdFormat,omitempty"` // NameID format (default: unspecified)
+ ForceAuthn bool `json:"forceAuthn,omitempty"` // Force re-authentication
+ AllowIDPInitiated bool `json:"allowIdpInitiated,omitempty"` // Allow IdP-initiated SSO (security risk)
+ RelayStateTemplate string `json:"relayStateTemplate,omitempty"` // Custom relay state template
+}
+
+// SSOConfig holds the complete SSO configuration with multiple providers
+type SSOConfig struct {
+ // Providers is the list of configured SSO providers
+ Providers []SSOProvider `json:"providers,omitempty"`
+
+ // DefaultProviderID is the provider to use when none is specified
+ // If empty and only one provider exists, that provider is used
+ DefaultProviderID string `json:"defaultProviderId,omitempty"`
+
+ // AllowMultipleProviders enables showing provider selection on login page
+ // If false and multiple providers exist, only the default is shown
+ AllowMultipleProviders bool `json:"allowMultipleProviders,omitempty"`
+}
+
+// NewSSOConfig creates a new empty SSO configuration
+func NewSSOConfig() *SSOConfig {
+ return &SSOConfig{
+ Providers: []SSOProvider{},
+ AllowMultipleProviders: true,
+ }
+}
+
+// GetProvider returns a provider by ID
+func (c *SSOConfig) GetProvider(id string) *SSOProvider {
+ if c == nil {
+ return nil
+ }
+ for i := range c.Providers {
+ if c.Providers[i].ID == id {
+ return &c.Providers[i]
+ }
+ }
+ return nil
+}
+
+// GetEnabledProviders returns all enabled providers sorted by priority
+func (c *SSOConfig) GetEnabledProviders() []SSOProvider {
+ if c == nil {
+ return nil
+ }
+ result := make([]SSOProvider, 0)
+ for _, p := range c.Providers {
+ if p.Enabled {
+ result = append(result, p)
+ }
+ }
+ // Sort by priority (lower = first)
+ for i := 0; i < len(result)-1; i++ {
+ for j := i + 1; j < len(result); j++ {
+ if result[j].Priority < result[i].Priority {
+ result[i], result[j] = result[j], result[i]
+ }
+ }
+ }
+ return result
+}
+
+// GetDefaultProvider returns the default provider
+func (c *SSOConfig) GetDefaultProvider() *SSOProvider {
+ if c == nil {
+ return nil
+ }
+ if c.DefaultProviderID != "" {
+ return c.GetProvider(c.DefaultProviderID)
+ }
+ enabled := c.GetEnabledProviders()
+ if len(enabled) > 0 {
+ return &enabled[0]
+ }
+ return nil
+}
+
+// HasEnabledProviders returns true if at least one provider is enabled
+func (c *SSOConfig) HasEnabledProviders() bool {
+ return len(c.GetEnabledProviders()) > 0
+}
+
+// AddProvider adds a new provider to the configuration
+func (c *SSOConfig) AddProvider(p SSOProvider) error {
+ if c == nil {
+ return fmt.Errorf("sso config is nil")
+ }
+ if p.ID == "" {
+ return fmt.Errorf("provider id is required")
+ }
+ if c.GetProvider(p.ID) != nil {
+ return fmt.Errorf("provider with id %q already exists", p.ID)
+ }
+ c.Providers = append(c.Providers, p)
+ return nil
+}
+
+// UpdateProvider updates an existing provider
+func (c *SSOConfig) UpdateProvider(p SSOProvider) error {
+ if c == nil {
+ return fmt.Errorf("sso config is nil")
+ }
+ for i := range c.Providers {
+ if c.Providers[i].ID == p.ID {
+ c.Providers[i] = p
+ return nil
+ }
+ }
+ return fmt.Errorf("provider with id %q not found", p.ID)
+}
+
+// RemoveProvider removes a provider by ID
+func (c *SSOConfig) RemoveProvider(id string) error {
+ if c == nil {
+ return fmt.Errorf("sso config is nil")
+ }
+ for i := range c.Providers {
+ if c.Providers[i].ID == id {
+ c.Providers = append(c.Providers[:i], c.Providers[i+1:]...)
+ // Clear default if we removed it
+ if c.DefaultProviderID == id {
+ c.DefaultProviderID = ""
+ }
+ return nil
+ }
+ }
+ return fmt.Errorf("provider with id %q not found", id)
+}
+
+// Validate checks the SSO configuration for errors
+func (c *SSOConfig) Validate() error {
+ if c == nil {
+ return nil
+ }
+
+ seenIDs := make(map[string]bool)
+ for i, p := range c.Providers {
+ if p.ID == "" {
+ return fmt.Errorf("provider %d: id is required", i)
+ }
+ if seenIDs[p.ID] {
+ return fmt.Errorf("provider %d: duplicate id %q", i, p.ID)
+ }
+ seenIDs[p.ID] = true
+
+ if p.Name == "" {
+ return fmt.Errorf("provider %q: name is required", p.ID)
+ }
+
+ if p.Type != SSOProviderTypeOIDC && p.Type != SSOProviderTypeSAML {
+ return fmt.Errorf("provider %q: invalid type %q (must be 'oidc' or 'saml')", p.ID, p.Type)
+ }
+
+ if p.Enabled {
+ if err := validateProvider(&p); err != nil {
+ return fmt.Errorf("provider %q: %w", p.ID, err)
+ }
+ }
+ }
+
+ if c.DefaultProviderID != "" && c.GetProvider(c.DefaultProviderID) == nil {
+ return fmt.Errorf("default provider %q not found", c.DefaultProviderID)
+ }
+
+ return nil
+}
+
+func validateProvider(p *SSOProvider) error {
+ switch p.Type {
+ case SSOProviderTypeOIDC:
+ if p.OIDC == nil {
+ return fmt.Errorf("oidc configuration is required for oidc provider")
+ }
+ return validateOIDCProvider(p.OIDC)
+ case SSOProviderTypeSAML:
+ if p.SAML == nil {
+ return fmt.Errorf("saml configuration is required for saml provider")
+ }
+ return validateSAMLProvider(p.SAML)
+ }
+ return nil
+}
+
+func validateOIDCProvider(cfg *OIDCProviderConfig) error {
+ if strings.TrimSpace(cfg.IssuerURL) == "" {
+ return fmt.Errorf("issuer url is required")
+ }
+ if _, err := url.ParseRequestURI(cfg.IssuerURL); err != nil {
+ return fmt.Errorf("invalid issuer url: %w", err)
+ }
+ if strings.TrimSpace(cfg.ClientID) == "" {
+ return fmt.Errorf("client id is required")
+ }
+ return nil
+}
+
+func validateSAMLProvider(cfg *SAMLProviderConfig) error {
+ // Must have either metadata URL, metadata XML, or manual SSO URL
+ hasMetadata := strings.TrimSpace(cfg.IDPMetadataURL) != "" || strings.TrimSpace(cfg.IDPMetadataXML) != ""
+ hasManual := strings.TrimSpace(cfg.IDPSSOURL) != ""
+
+ if !hasMetadata && !hasManual {
+ return fmt.Errorf("either idp metadata (url or xml) or idp sso url is required")
+ }
+
+ if cfg.IDPMetadataURL != "" {
+ if _, err := url.ParseRequestURI(cfg.IDPMetadataURL); err != nil {
+ return fmt.Errorf("invalid idp metadata url: %w", err)
+ }
+ }
+
+ if cfg.IDPSSOURL != "" {
+ if _, err := url.ParseRequestURI(cfg.IDPSSOURL); err != nil {
+ return fmt.Errorf("invalid idp sso url: %w", err)
+ }
+ }
+
+ // If signing is enabled, certificate and key are required
+ if cfg.SignRequests {
+ hasCert := strings.TrimSpace(cfg.SPCertificate) != "" || strings.TrimSpace(cfg.SPCertFile) != ""
+ hasKey := strings.TrimSpace(cfg.SPPrivateKey) != "" || strings.TrimSpace(cfg.SPKeyFile) != ""
+ if !hasCert || !hasKey {
+ return fmt.Errorf("sp certificate and private key are required when signing requests")
+ }
+ }
+
+ return nil
+}
+
+// Clone creates a deep copy of the SSO configuration
+func (c *SSOConfig) Clone() *SSOConfig {
+ if c == nil {
+ return nil
+ }
+
+ clone := &SSOConfig{
+ DefaultProviderID: c.DefaultProviderID,
+ AllowMultipleProviders: c.AllowMultipleProviders,
+ Providers: make([]SSOProvider, len(c.Providers)),
+ }
+
+ for i, p := range c.Providers {
+ clone.Providers[i] = cloneProvider(p)
+ }
+
+ return clone
+}
+
+func cloneProvider(p SSOProvider) SSOProvider {
+ clone := p
+
+ // Clone slices
+ if p.AllowedGroups != nil {
+ clone.AllowedGroups = append([]string{}, p.AllowedGroups...)
+ }
+ if p.AllowedDomains != nil {
+ clone.AllowedDomains = append([]string{}, p.AllowedDomains...)
+ }
+ if p.AllowedEmails != nil {
+ clone.AllowedEmails = append([]string{}, p.AllowedEmails...)
+ }
+ if p.GroupRoleMappings != nil {
+ clone.GroupRoleMappings = make(map[string]string, len(p.GroupRoleMappings))
+ for k, v := range p.GroupRoleMappings {
+ clone.GroupRoleMappings[k] = v
+ }
+ }
+
+ // Clone OIDC config
+ if p.OIDC != nil {
+ oidc := *p.OIDC
+ if p.OIDC.Scopes != nil {
+ oidc.Scopes = append([]string{}, p.OIDC.Scopes...)
+ }
+ if p.OIDC.EnvOverrides != nil {
+ oidc.EnvOverrides = make(map[string]bool, len(p.OIDC.EnvOverrides))
+ for k, v := range p.OIDC.EnvOverrides {
+ oidc.EnvOverrides[k] = v
+ }
+ }
+ clone.OIDC = &oidc
+ }
+
+ // Clone SAML config
+ if p.SAML != nil {
+ saml := *p.SAML
+ clone.SAML = &saml
+ }
+
+ return clone
+}
+
+// MigrateFromOIDCConfig converts legacy OIDCConfig to new SSOConfig format
+func MigrateFromOIDCConfig(oidc *OIDCConfig) *SSOConfig {
+ if oidc == nil {
+ return NewSSOConfig()
+ }
+
+ sso := NewSSOConfig()
+
+ // Only migrate if OIDC was actually configured
+ if oidc.IssuerURL == "" || oidc.ClientID == "" {
+ return sso
+ }
+
+ provider := SSOProvider{
+ ID: "legacy-oidc",
+ Name: "Single Sign-On",
+ Type: SSOProviderTypeOIDC,
+ Enabled: oidc.Enabled,
+ AllowedGroups: oidc.AllowedGroups,
+ AllowedDomains: oidc.AllowedDomains,
+ AllowedEmails: oidc.AllowedEmails,
+ GroupsClaim: oidc.GroupsClaim,
+ GroupRoleMappings: oidc.GroupRoleMappings,
+ OIDC: &OIDCProviderConfig{
+ IssuerURL: oidc.IssuerURL,
+ ClientID: oidc.ClientID,
+ ClientSecret: oidc.ClientSecret,
+ RedirectURL: oidc.RedirectURL,
+ LogoutURL: oidc.LogoutURL,
+ Scopes: oidc.Scopes,
+ UsernameClaim: oidc.UsernameClaim,
+ EmailClaim: oidc.EmailClaim,
+ CABundle: oidc.CABundle,
+ ClientSecretSet: oidc.ClientSecret != "",
+ EnvOverrides: oidc.EnvOverrides,
+ },
+ }
+
+ sso.Providers = append(sso.Providers, provider)
+ sso.DefaultProviderID = provider.ID
+
+ return sso
+}
+
+// ToLegacyOIDCConfig converts the first OIDC provider back to legacy format for backwards compatibility
+func (c *SSOConfig) ToLegacyOIDCConfig() *OIDCConfig {
+ if c == nil {
+ return NewOIDCConfig()
+ }
+
+ for _, p := range c.Providers {
+ if p.Type == SSOProviderTypeOIDC && p.OIDC != nil {
+ return &OIDCConfig{
+ Enabled: p.Enabled,
+ IssuerURL: p.OIDC.IssuerURL,
+ ClientID: p.OIDC.ClientID,
+ ClientSecret: p.OIDC.ClientSecret,
+ RedirectURL: p.OIDC.RedirectURL,
+ LogoutURL: p.OIDC.LogoutURL,
+ Scopes: p.OIDC.Scopes,
+ UsernameClaim: p.OIDC.UsernameClaim,
+ EmailClaim: p.OIDC.EmailClaim,
+ GroupsClaim: p.GroupsClaim,
+ AllowedGroups: p.AllowedGroups,
+ AllowedDomains: p.AllowedDomains,
+ AllowedEmails: p.AllowedEmails,
+ GroupRoleMappings: p.GroupRoleMappings,
+ CABundle: p.OIDC.CABundle,
+ EnvOverrides: p.OIDC.EnvOverrides,
+ }
+ }
+ }
+
+ return NewOIDCConfig()
+}
diff --git a/internal/config/sso_test.go b/internal/config/sso_test.go
new file mode 100644
index 0000000000..56366e5fa9
--- /dev/null
+++ b/internal/config/sso_test.go
@@ -0,0 +1,911 @@
+package config
+
+import (
+ "testing"
+)
+
+func TestNewSSOConfig(t *testing.T) {
+ cfg := NewSSOConfig()
+ if cfg == nil {
+ t.Fatal("NewSSOConfig returned nil")
+ }
+ if cfg.Providers == nil {
+ t.Error("Providers slice should not be nil")
+ }
+ if len(cfg.Providers) != 0 {
+ t.Error("Providers slice should be empty")
+ }
+ if !cfg.AllowMultipleProviders {
+ t.Error("AllowMultipleProviders should default to true")
+ }
+}
+
+func TestSSOConfig_GetProvider(t *testing.T) {
+ cfg := &SSOConfig{
+ Providers: []SSOProvider{
+ {ID: "p1", Name: "Provider 1"},
+ {ID: "p2", Name: "Provider 2"},
+ },
+ }
+
+ tests := []struct {
+ name string
+ id string
+ wantName string
+ wantNil bool
+ }{
+ {"existing provider", "p1", "Provider 1", false},
+ {"second provider", "p2", "Provider 2", false},
+ {"non-existent", "p3", "", true},
+ {"empty id", "", "", true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ p := cfg.GetProvider(tt.id)
+ if tt.wantNil {
+ if p != nil {
+ t.Errorf("GetProvider(%q) = %v, want nil", tt.id, p)
+ }
+ } else {
+ if p == nil {
+ t.Fatalf("GetProvider(%q) = nil, want non-nil", tt.id)
+ }
+ if p.Name != tt.wantName {
+ t.Errorf("GetProvider(%q).Name = %q, want %q", tt.id, p.Name, tt.wantName)
+ }
+ }
+ })
+ }
+
+ // Test nil config
+ var nilCfg *SSOConfig
+ if p := nilCfg.GetProvider("p1"); p != nil {
+ t.Error("GetProvider on nil config should return nil")
+ }
+}
+
+func TestSSOConfig_GetEnabledProviders(t *testing.T) {
+ cfg := &SSOConfig{
+ Providers: []SSOProvider{
+ {ID: "p1", Name: "Provider 1", Enabled: false, Priority: 10},
+ {ID: "p2", Name: "Provider 2", Enabled: true, Priority: 20},
+ {ID: "p3", Name: "Provider 3", Enabled: true, Priority: 5},
+ {ID: "p4", Name: "Provider 4", Enabled: true, Priority: 15},
+ },
+ }
+
+ enabled := cfg.GetEnabledProviders()
+ if len(enabled) != 3 {
+ t.Fatalf("GetEnabledProviders() returned %d providers, want 3", len(enabled))
+ }
+
+ // Should be sorted by priority (ascending)
+ expectedOrder := []string{"p3", "p4", "p2"}
+ for i, p := range enabled {
+ if p.ID != expectedOrder[i] {
+ t.Errorf("GetEnabledProviders()[%d].ID = %q, want %q", i, p.ID, expectedOrder[i])
+ }
+ }
+
+ // Test nil config
+ var nilCfg *SSOConfig
+ if result := nilCfg.GetEnabledProviders(); result != nil {
+ t.Error("GetEnabledProviders on nil config should return nil")
+ }
+}
+
+func TestSSOConfig_GetDefaultProvider(t *testing.T) {
+ tests := []struct {
+ name string
+ cfg *SSOConfig
+ wantID string
+ wantNil bool
+ }{
+ {
+ name: "explicit default",
+ cfg: &SSOConfig{
+ DefaultProviderID: "p2",
+ Providers: []SSOProvider{
+ {ID: "p1", Enabled: true, Priority: 1},
+ {ID: "p2", Enabled: true, Priority: 2},
+ },
+ },
+ wantID: "p2",
+ wantNil: false,
+ },
+ {
+ name: "first enabled when no default",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {ID: "p1", Enabled: false, Priority: 1},
+ {ID: "p2", Enabled: true, Priority: 10},
+ {ID: "p3", Enabled: true, Priority: 5},
+ },
+ },
+ wantID: "p3", // lowest priority among enabled
+ wantNil: false,
+ },
+ {
+ name: "no enabled providers",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {ID: "p1", Enabled: false},
+ },
+ },
+ wantNil: true,
+ },
+ {
+ name: "nil config",
+ cfg: nil,
+ wantNil: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ p := tt.cfg.GetDefaultProvider()
+ if tt.wantNil {
+ if p != nil {
+ t.Errorf("GetDefaultProvider() = %v, want nil", p)
+ }
+ } else {
+ if p == nil {
+ t.Fatal("GetDefaultProvider() = nil, want non-nil")
+ }
+ if p.ID != tt.wantID {
+ t.Errorf("GetDefaultProvider().ID = %q, want %q", p.ID, tt.wantID)
+ }
+ }
+ })
+ }
+}
+
+func TestSSOConfig_HasEnabledProviders(t *testing.T) {
+ tests := []struct {
+ name string
+ cfg *SSOConfig
+ want bool
+ }{
+ {
+ name: "has enabled",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{{ID: "p1", Enabled: true}},
+ },
+ want: true,
+ },
+ {
+ name: "none enabled",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{{ID: "p1", Enabled: false}},
+ },
+ want: false,
+ },
+ {
+ name: "empty providers",
+ cfg: &SSOConfig{Providers: []SSOProvider{}},
+ want: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := tt.cfg.HasEnabledProviders(); got != tt.want {
+ t.Errorf("HasEnabledProviders() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestSSOConfig_AddProvider(t *testing.T) {
+ cfg := NewSSOConfig()
+
+ // Add first provider
+ err := cfg.AddProvider(SSOProvider{ID: "p1", Name: "Provider 1"})
+ if err != nil {
+ t.Fatalf("AddProvider() error = %v, want nil", err)
+ }
+ if len(cfg.Providers) != 1 {
+ t.Errorf("len(Providers) = %d, want 1", len(cfg.Providers))
+ }
+
+ // Add second provider
+ err = cfg.AddProvider(SSOProvider{ID: "p2", Name: "Provider 2"})
+ if err != nil {
+ t.Fatalf("AddProvider() error = %v, want nil", err)
+ }
+ if len(cfg.Providers) != 2 {
+ t.Errorf("len(Providers) = %d, want 2", len(cfg.Providers))
+ }
+
+ // Duplicate ID should fail
+ err = cfg.AddProvider(SSOProvider{ID: "p1", Name: "Duplicate"})
+ if err == nil {
+ t.Error("AddProvider() with duplicate ID should return error")
+ }
+
+ // Empty ID should fail
+ err = cfg.AddProvider(SSOProvider{ID: "", Name: "No ID"})
+ if err == nil {
+ t.Error("AddProvider() with empty ID should return error")
+ }
+
+ // Nil config should fail
+ var nilCfg *SSOConfig
+ err = nilCfg.AddProvider(SSOProvider{ID: "p1"})
+ if err == nil {
+ t.Error("AddProvider() on nil config should return error")
+ }
+}
+
+func TestSSOConfig_UpdateProvider(t *testing.T) {
+ cfg := &SSOConfig{
+ Providers: []SSOProvider{
+ {ID: "p1", Name: "Original"},
+ },
+ }
+
+ // Update existing
+ err := cfg.UpdateProvider(SSOProvider{ID: "p1", Name: "Updated"})
+ if err != nil {
+ t.Fatalf("UpdateProvider() error = %v, want nil", err)
+ }
+ if cfg.Providers[0].Name != "Updated" {
+ t.Errorf("Provider name = %q, want %q", cfg.Providers[0].Name, "Updated")
+ }
+
+ // Update non-existent
+ err = cfg.UpdateProvider(SSOProvider{ID: "p2", Name: "Non-existent"})
+ if err == nil {
+ t.Error("UpdateProvider() for non-existent provider should return error")
+ }
+
+ // Nil config
+ var nilCfg *SSOConfig
+ err = nilCfg.UpdateProvider(SSOProvider{ID: "p1"})
+ if err == nil {
+ t.Error("UpdateProvider() on nil config should return error")
+ }
+}
+
+func TestSSOConfig_RemoveProvider(t *testing.T) {
+ cfg := &SSOConfig{
+ DefaultProviderID: "p1",
+ Providers: []SSOProvider{
+ {ID: "p1", Name: "Provider 1"},
+ {ID: "p2", Name: "Provider 2"},
+ },
+ }
+
+ // Remove non-existent
+ err := cfg.RemoveProvider("p3")
+ if err == nil {
+ t.Error("RemoveProvider() for non-existent provider should return error")
+ }
+
+ // Remove existing (and default)
+ err = cfg.RemoveProvider("p1")
+ if err != nil {
+ t.Fatalf("RemoveProvider() error = %v, want nil", err)
+ }
+ if len(cfg.Providers) != 1 {
+ t.Errorf("len(Providers) = %d, want 1", len(cfg.Providers))
+ }
+ if cfg.DefaultProviderID != "" {
+ t.Errorf("DefaultProviderID = %q, want empty (cleared)", cfg.DefaultProviderID)
+ }
+
+ // Remove last provider
+ err = cfg.RemoveProvider("p2")
+ if err != nil {
+ t.Fatalf("RemoveProvider() error = %v, want nil", err)
+ }
+ if len(cfg.Providers) != 0 {
+ t.Errorf("len(Providers) = %d, want 0", len(cfg.Providers))
+ }
+
+ // Nil config
+ var nilCfg *SSOConfig
+ err = nilCfg.RemoveProvider("p1")
+ if err == nil {
+ t.Error("RemoveProvider() on nil config should return error")
+ }
+}
+
+func TestSSOConfig_Validate(t *testing.T) {
+ tests := []struct {
+ name string
+ cfg *SSOConfig
+ wantErr bool
+ }{
+ {
+ name: "nil config",
+ cfg: nil,
+ wantErr: false,
+ },
+ {
+ name: "empty config",
+ cfg: &SSOConfig{},
+ wantErr: false,
+ },
+ {
+ name: "valid OIDC provider",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {
+ ID: "oidc1",
+ Name: "OIDC Provider",
+ Type: SSOProviderTypeOIDC,
+ Enabled: true,
+ OIDC: &OIDCProviderConfig{
+ IssuerURL: "https://idp.example.com",
+ ClientID: "client123",
+ },
+ },
+ },
+ },
+ wantErr: false,
+ },
+ {
+ name: "valid SAML provider with metadata URL",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {
+ ID: "saml1",
+ Name: "SAML Provider",
+ Type: SSOProviderTypeSAML,
+ Enabled: true,
+ SAML: &SAMLProviderConfig{
+ IDPMetadataURL: "https://idp.example.com/metadata",
+ },
+ },
+ },
+ },
+ wantErr: false,
+ },
+ {
+ name: "valid SAML provider with SSO URL",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {
+ ID: "saml1",
+ Name: "SAML Provider",
+ Type: SSOProviderTypeSAML,
+ Enabled: true,
+ SAML: &SAMLProviderConfig{
+ IDPSSOURL: "https://idp.example.com/sso",
+ },
+ },
+ },
+ },
+ wantErr: false,
+ },
+ {
+ name: "missing provider ID",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {ID: "", Name: "Test"},
+ },
+ },
+ wantErr: true,
+ },
+ {
+ name: "duplicate provider ID",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {ID: "p1", Name: "Provider 1"},
+ {ID: "p1", Name: "Provider 2"},
+ },
+ },
+ wantErr: true,
+ },
+ {
+ name: "missing provider name",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {ID: "p1", Name: ""},
+ },
+ },
+ wantErr: true,
+ },
+ {
+ name: "invalid provider type",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {ID: "p1", Name: "Test", Type: "invalid"},
+ },
+ },
+ wantErr: true,
+ },
+ {
+ name: "enabled OIDC without config",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {ID: "p1", Name: "Test", Type: SSOProviderTypeOIDC, Enabled: true},
+ },
+ },
+ wantErr: true,
+ },
+ {
+ name: "enabled SAML without config",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {ID: "p1", Name: "Test", Type: SSOProviderTypeSAML, Enabled: true},
+ },
+ },
+ wantErr: true,
+ },
+ {
+ name: "OIDC missing issuer URL",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {
+ ID: "p1",
+ Name: "Test",
+ Type: SSOProviderTypeOIDC,
+ Enabled: true,
+ OIDC: &OIDCProviderConfig{ClientID: "client123"},
+ },
+ },
+ },
+ wantErr: true,
+ },
+ {
+ name: "OIDC missing client ID",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {
+ ID: "p1",
+ Name: "Test",
+ Type: SSOProviderTypeOIDC,
+ Enabled: true,
+ OIDC: &OIDCProviderConfig{IssuerURL: "https://idp.example.com"},
+ },
+ },
+ },
+ wantErr: true,
+ },
+ {
+ name: "SAML missing metadata/SSO URL",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {
+ ID: "p1",
+ Name: "Test",
+ Type: SSOProviderTypeSAML,
+ Enabled: true,
+ SAML: &SAMLProviderConfig{},
+ },
+ },
+ },
+ wantErr: true,
+ },
+ {
+ name: "SAML signing without cert/key",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {
+ ID: "p1",
+ Name: "Test",
+ Type: SSOProviderTypeSAML,
+ Enabled: true,
+ SAML: &SAMLProviderConfig{
+ IDPMetadataURL: "https://idp.example.com/metadata",
+ SignRequests: true,
+ },
+ },
+ },
+ },
+ wantErr: true,
+ },
+ {
+ name: "invalid default provider ID",
+ cfg: &SSOConfig{
+ DefaultProviderID: "nonexistent",
+ Providers: []SSOProvider{
+ {ID: "p1", Name: "Test"},
+ },
+ },
+ wantErr: true,
+ },
+ {
+ name: "disabled provider skips validation",
+ cfg: &SSOConfig{
+ Providers: []SSOProvider{
+ {
+ ID: "p1",
+ Name: "Test",
+ Type: SSOProviderTypeOIDC,
+ Enabled: false,
+ OIDC: nil, // Would fail if enabled
+ },
+ },
+ },
+ wantErr: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := tt.cfg.Validate()
+ if (err != nil) != tt.wantErr {
+ t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ })
+ }
+}
+
+func TestSSOConfig_Clone(t *testing.T) {
+ original := &SSOConfig{
+ DefaultProviderID: "p1",
+ AllowMultipleProviders: true,
+ Providers: []SSOProvider{
+ {
+ ID: "p1",
+ Name: "Provider 1",
+ Type: SSOProviderTypeOIDC,
+ Enabled: true,
+ AllowedGroups: []string{"admin", "users"},
+ AllowedDomains: []string{"example.com"},
+ GroupRoleMappings: map[string]string{
+ "admin": "administrator",
+ },
+ OIDC: &OIDCProviderConfig{
+ IssuerURL: "https://idp.example.com",
+ ClientID: "client123",
+ ClientSecret: "secret",
+ Scopes: []string{"openid", "profile"},
+ },
+ },
+ {
+ ID: "p2",
+ Name: "Provider 2",
+ Type: SSOProviderTypeSAML,
+ Enabled: false,
+ SAML: &SAMLProviderConfig{
+ IDPMetadataURL: "https://idp2.example.com/metadata",
+ },
+ },
+ },
+ }
+
+ clone := original.Clone()
+
+ // Verify deep copy
+ if clone == original {
+ t.Error("Clone() returned same pointer")
+ }
+ if clone.DefaultProviderID != original.DefaultProviderID {
+ t.Error("DefaultProviderID not cloned")
+ }
+ if clone.AllowMultipleProviders != original.AllowMultipleProviders {
+ t.Error("AllowMultipleProviders not cloned")
+ }
+ if len(clone.Providers) != len(original.Providers) {
+ t.Error("Providers slice length mismatch")
+ }
+
+ // Modify clone and verify original unchanged
+ clone.Providers[0].Name = "Modified"
+ if original.Providers[0].Name == "Modified" {
+ t.Error("Modifying clone affected original - not a deep copy")
+ }
+
+ clone.Providers[0].AllowedGroups[0] = "modified"
+ if original.Providers[0].AllowedGroups[0] == "modified" {
+ t.Error("Modifying clone's AllowedGroups affected original")
+ }
+
+ clone.Providers[0].GroupRoleMappings["admin"] = "modified"
+ if original.Providers[0].GroupRoleMappings["admin"] == "modified" {
+ t.Error("Modifying clone's GroupRoleMappings affected original")
+ }
+
+ clone.Providers[0].OIDC.ClientSecret = "modified"
+ if original.Providers[0].OIDC.ClientSecret == "modified" {
+ t.Error("Modifying clone's OIDC config affected original")
+ }
+
+ // Test nil clone
+ var nilCfg *SSOConfig
+ if result := nilCfg.Clone(); result != nil {
+ t.Error("Clone() on nil should return nil")
+ }
+}
+
+func TestMigrateFromOIDCConfig(t *testing.T) {
+ tests := []struct {
+ name string
+ oidc *OIDCConfig
+ wantLen int
+ checkFn func(*testing.T, *SSOConfig)
+ }{
+ {
+ name: "nil OIDC config",
+ oidc: nil,
+ wantLen: 0,
+ },
+ {
+ name: "empty OIDC config",
+ oidc: &OIDCConfig{},
+ wantLen: 0,
+ },
+ {
+ name: "valid OIDC config",
+ oidc: &OIDCConfig{
+ Enabled: true,
+ IssuerURL: "https://idp.example.com",
+ ClientID: "client123",
+ ClientSecret: "secret",
+ RedirectURL: "https://app.example.com/callback",
+ AllowedGroups: []string{"admin"},
+ AllowedDomains: []string{"example.com"},
+ GroupsClaim: "groups",
+ GroupRoleMappings: map[string]string{
+ "admin": "administrator",
+ },
+ },
+ wantLen: 1,
+ checkFn: func(t *testing.T, sso *SSOConfig) {
+ p := sso.GetProvider("legacy-oidc")
+ if p == nil {
+ t.Fatal("legacy-oidc provider not found")
+ }
+ if p.Type != SSOProviderTypeOIDC {
+ t.Errorf("Type = %q, want %q", p.Type, SSOProviderTypeOIDC)
+ }
+ if !p.Enabled {
+ t.Error("Provider should be enabled")
+ }
+ if p.OIDC.IssuerURL != "https://idp.example.com" {
+ t.Errorf("IssuerURL = %q, want %q", p.OIDC.IssuerURL, "https://idp.example.com")
+ }
+ if p.OIDC.ClientID != "client123" {
+ t.Errorf("ClientID = %q, want %q", p.OIDC.ClientID, "client123")
+ }
+ if len(p.AllowedGroups) != 1 || p.AllowedGroups[0] != "admin" {
+ t.Errorf("AllowedGroups = %v, want [admin]", p.AllowedGroups)
+ }
+ if sso.DefaultProviderID != "legacy-oidc" {
+ t.Errorf("DefaultProviderID = %q, want %q", sso.DefaultProviderID, "legacy-oidc")
+ }
+ },
+ },
+ {
+ name: "OIDC config missing client ID (not migrated)",
+ oidc: &OIDCConfig{
+ IssuerURL: "https://idp.example.com",
+ },
+ wantLen: 0,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ sso := MigrateFromOIDCConfig(tt.oidc)
+ if sso == nil {
+ t.Fatal("MigrateFromOIDCConfig returned nil")
+ }
+ if len(sso.Providers) != tt.wantLen {
+ t.Errorf("len(Providers) = %d, want %d", len(sso.Providers), tt.wantLen)
+ }
+ if tt.checkFn != nil {
+ tt.checkFn(t, sso)
+ }
+ })
+ }
+}
+
+func TestSSOConfig_ToLegacyOIDCConfig(t *testing.T) {
+ tests := []struct {
+ name string
+ sso *SSOConfig
+ wantNil bool
+ checkFn func(*testing.T, *OIDCConfig)
+ }{
+ {
+ name: "nil SSO config",
+ sso: nil,
+ wantNil: false, // Returns NewOIDCConfig()
+ },
+ {
+ name: "no OIDC providers",
+ sso: &SSOConfig{},
+ wantNil: false,
+ },
+ {
+ name: "SAML only",
+ sso: &SSOConfig{
+ Providers: []SSOProvider{
+ {
+ ID: "saml1",
+ Type: SSOProviderTypeSAML,
+ SAML: &SAMLProviderConfig{},
+ },
+ },
+ },
+ wantNil: false,
+ },
+ {
+ name: "with OIDC provider",
+ sso: &SSOConfig{
+ Providers: []SSOProvider{
+ {
+ ID: "oidc1",
+ Type: SSOProviderTypeOIDC,
+ Enabled: true,
+ AllowedGroups: []string{"admin"},
+ GroupsClaim: "groups",
+ OIDC: &OIDCProviderConfig{
+ IssuerURL: "https://idp.example.com",
+ ClientID: "client123",
+ ClientSecret: "secret",
+ },
+ },
+ },
+ },
+ checkFn: func(t *testing.T, oidc *OIDCConfig) {
+ if !oidc.Enabled {
+ t.Error("Enabled should be true")
+ }
+ if oidc.IssuerURL != "https://idp.example.com" {
+ t.Errorf("IssuerURL = %q, want %q", oidc.IssuerURL, "https://idp.example.com")
+ }
+ if oidc.ClientID != "client123" {
+ t.Errorf("ClientID = %q, want %q", oidc.ClientID, "client123")
+ }
+ if oidc.GroupsClaim != "groups" {
+ t.Errorf("GroupsClaim = %q, want %q", oidc.GroupsClaim, "groups")
+ }
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ oidc := tt.sso.ToLegacyOIDCConfig()
+ if oidc == nil {
+ t.Fatal("ToLegacyOIDCConfig returned nil")
+ }
+ if tt.checkFn != nil {
+ tt.checkFn(t, oidc)
+ }
+ })
+ }
+}
+
+// Test URL validation
+func TestValidateOIDCProvider(t *testing.T) {
+ tests := []struct {
+ name string
+ cfg *OIDCProviderConfig
+ wantErr bool
+ }{
+ {
+ name: "valid config",
+ cfg: &OIDCProviderConfig{
+ IssuerURL: "https://idp.example.com",
+ ClientID: "client123",
+ },
+ wantErr: false,
+ },
+ {
+ name: "invalid issuer URL",
+ cfg: &OIDCProviderConfig{
+ IssuerURL: "not-a-url",
+ ClientID: "client123",
+ },
+ wantErr: true,
+ },
+ {
+ name: "empty issuer URL",
+ cfg: &OIDCProviderConfig{
+ IssuerURL: "",
+ ClientID: "client123",
+ },
+ wantErr: true,
+ },
+ {
+ name: "whitespace issuer URL",
+ cfg: &OIDCProviderConfig{
+ IssuerURL: " ",
+ ClientID: "client123",
+ },
+ wantErr: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := validateOIDCProvider(tt.cfg)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("validateOIDCProvider() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ })
+ }
+}
+
+func TestValidateSAMLProvider(t *testing.T) {
+ tests := []struct {
+ name string
+ cfg *SAMLProviderConfig
+ wantErr bool
+ }{
+ {
+ name: "valid with metadata URL",
+ cfg: &SAMLProviderConfig{
+ IDPMetadataURL: "https://idp.example.com/metadata",
+ },
+ wantErr: false,
+ },
+ {
+ name: "valid with metadata XML",
+ cfg: &SAMLProviderConfig{
+ IDPMetadataXML: "<xml>...</xml>",
+ },
+ wantErr: false,
+ },
+ {
+ name: "valid with SSO URL",
+ cfg: &SAMLProviderConfig{
+ IDPSSOURL: "https://idp.example.com/sso",
+ },
+ wantErr: false,
+ },
+ {
+ name: "missing all required fields",
+ cfg: &SAMLProviderConfig{},
+ wantErr: true,
+ },
+ {
+ name: "invalid metadata URL",
+ cfg: &SAMLProviderConfig{
+ IDPMetadataURL: "not-a-url",
+ },
+ wantErr: true,
+ },
+ {
+ name: "invalid SSO URL",
+ cfg: &SAMLProviderConfig{
+ IDPSSOURL: "not-a-url",
+ },
+ wantErr: true,
+ },
+ {
+ name: "signing enabled without cert",
+ cfg: &SAMLProviderConfig{
+ IDPMetadataURL: "https://idp.example.com/metadata",
+ SignRequests: true,
+ },
+ wantErr: true,
+ },
+ {
+ name: "signing enabled with cert but no key",
+ cfg: &SAMLProviderConfig{
+ IDPMetadataURL: "https://idp.example.com/metadata",
+ SignRequests: true,
+ SPCertificate: "-----BEGIN CERTIFICATE-----...",
+ },
+ wantErr: true,
+ },
+ {
+ name: "signing enabled with cert file and key file",
+ cfg: &SAMLProviderConfig{
+ IDPMetadataURL: "https://idp.example.com/metadata",
+ SignRequests: true,
+ SPCertFile: "/path/to/cert.pem",
+ SPKeyFile: "/path/to/key.pem",
+ },
+ wantErr: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := validateSAMLProvider(tt.cfg)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("validateSAMLProvider() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ })
+ }
+}