diff --git a/backend/src/__tests__/sso.test.ts b/backend/src/__tests__/sso.test.ts index b45e42f5..94a8eb92 100644 --- a/backend/src/__tests__/sso.test.ts +++ b/backend/src/__tests__/sso.test.ts @@ -50,13 +50,13 @@ describe('SSO Config Endpoints (Protected)', () => { expect(res.status).toBe(401); }); - it('GET /api/sso/config returns 403 without Admiral', async () => { + it('GET /api/sso/config returns 200 with admin token (no Admiral required)', async () => { const res = await supertest(app) .get('/api/sso/config') .set('Authorization', `Bearer ${adminToken}`); - // Without an Admiral license, this should be 403 - expect(res.status).toBe(403); - expect(res.body.code).toBe('PAID_REQUIRED'); + // SSO config is now available to all tiers, only admin role required + expect(res.status).toBe(200); + expect(Array.isArray(res.body)).toBe(true); }); it('PUT /api/sso/config/:provider returns 401 without auth', async () => { @@ -85,6 +85,12 @@ describe('SSO OIDC Authorize', () => { expect(res.status).toBe(302); expect(res.headers.location).toContain('sso_error'); }); + + it('GET /api/auth/sso/oidc/oidc_custom/authorize redirects to error when not configured', async () => { + const res = await supertest(app).get('/api/auth/sso/oidc/oidc_custom/authorize'); + expect(res.status).toBe(302); + expect(res.headers.location).toContain('sso_error'); + }); }); describe('SSO OIDC Callback', () => { @@ -192,6 +198,22 @@ describe('SSO User Provisioning', () => { expect(user.auth_provider).toBe('ldap'); }); + it('provisionUser works with oidc_custom provider', async () => { + const { SSOService } = await import('../services/SSOService'); + const sso = SSOService.getInstance(); + const user = sso.provisionUser({ + authProvider: 'oidc_custom', + providerId: 'custom-sub-789', + preferredUsername: 'customuser', + email: 'custom@example.com', + role: 'viewer', + }); + expect(user.auth_provider).toBe('oidc_custom'); + expect(user.provider_id).toBe('custom-sub-789'); + expect(user.email).toBe('custom@example.com'); + expect(user.username).toBe('customuser'); + }); + it('SSO users cannot log in via local password endpoint', async () => { // The SSO user from the first test has a $sso$ password hash // Trying to log in with any password should fail @@ -387,25 +409,12 @@ describe('LDAP Filter Escaping', () => { }); describe('SSO Config Validation on PUT', () => { - // We need an Admiral-licensed admin token for these tests. - // Mock getTier/getVariant so requireAdmiral passes. - let admiralToken: string; - - beforeAll(async () => { - const { LicenseService } = await import('../services/LicenseService'); - vi.spyOn(LicenseService.getInstance(), 'getTier').mockReturnValue('paid'); - vi.spyOn(LicenseService.getInstance(), 'getVariant').mockReturnValue('admiral'); - admiralToken = jwt.sign({ username: 'testadmin', role: 'admin' }, TEST_JWT_SECRET, { expiresIn: '1h' }); - }); - - afterAll(() => { - vi.restoreAllMocks(); - }); + // SSO config routes require admin role but no longer require Admiral tier it('rejects enabled LDAP config without Server URL', async () => { const res = await supertest(app) .put('/api/sso/config/ldap') - .set('Authorization', `Bearer ${admiralToken}`) + .set('Authorization', `Bearer ${adminToken}`) .send({ enabled: true, ldapSearchBase: 'ou=users,dc=example' }); expect(res.status).toBe(400); expect(res.body.error).toContain('Server URL'); @@ -414,7 +423,7 @@ describe('SSO Config Validation on PUT', () => { it('rejects enabled LDAP config without Search Base', async () => { const res = await supertest(app) .put('/api/sso/config/ldap') - .set('Authorization', `Bearer ${admiralToken}`) + .set('Authorization', `Bearer ${adminToken}`) .send({ enabled: true, ldapUrl: 'ldap://localhost:389' }); expect(res.status).toBe(400); expect(res.body.error).toContain('Search Base'); @@ -423,7 +432,7 @@ describe('SSO Config Validation on PUT', () => { it('rejects enabled OIDC config without Client ID', async () => { const res = await supertest(app) .put('/api/sso/config/oidc_google') - .set('Authorization', `Bearer ${admiralToken}`) + .set('Authorization', `Bearer ${adminToken}`) .send({ enabled: true }); expect(res.status).toBe(400); expect(res.body.error).toContain('Client ID'); @@ -432,16 +441,34 @@ describe('SSO Config Validation on PUT', () => { it('rejects enabled Okta config without Issuer URL', async () => { const res = await supertest(app) .put('/api/sso/config/oidc_okta') - .set('Authorization', `Bearer ${admiralToken}`) + .set('Authorization', `Bearer ${adminToken}`) .send({ enabled: true, oidcClientId: 'test-client-id' }); expect(res.status).toBe(400); expect(res.body.error).toContain('Issuer URL'); }); + it('rejects enabled Custom OIDC config without Issuer URL', async () => { + const res = await supertest(app) + .put('/api/sso/config/oidc_custom') + .set('Authorization', `Bearer ${adminToken}`) + .send({ enabled: true, oidcClientId: 'test-client-id' }); + expect(res.status).toBe(400); + expect(res.body.error).toContain('Issuer URL'); + }); + + it('accepts oidc_custom as a valid provider', async () => { + const res = await supertest(app) + .put('/api/sso/config/oidc_custom') + .set('Authorization', `Bearer ${adminToken}`) + .send({ enabled: false }); + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + }); + it('allows saving disabled config without required fields', async () => { const res = await supertest(app) .put('/api/sso/config/ldap') - .set('Authorization', `Bearer ${admiralToken}`) + .set('Authorization', `Bearer ${adminToken}`) .send({ enabled: false }); expect(res.status).toBe(200); expect(res.body.success).toBe(true); @@ -450,9 +477,32 @@ describe('SSO Config Validation on PUT', () => { it('rejects invalid provider name', async () => { const res = await supertest(app) .put('/api/sso/config/invalid_provider') - .set('Authorization', `Bearer ${admiralToken}`) + .set('Authorization', `Bearer ${adminToken}`) .send({ enabled: true }); expect(res.status).toBe(400); expect(res.body.error).toContain('Invalid SSO provider'); }); }); + +describe('SSO Claim Mapping', () => { + it('resolveRoleFromOidc respects custom admin claim name', async () => { + const { SSOService } = await import('../services/SSOService'); + const sso = SSOService.getInstance(); + // Access private method for testing + const resolve = (sso as unknown as { + resolveRoleFromOidc: (userInfo: Record, config: { oidcAdminClaim?: string; oidcAdminClaimValue?: string; oidcDefaultRole?: string }) => string; + }).resolveRoleFromOidc.bind(sso); + + // Standard claim name + expect(resolve({ groups: ['sencho-admins'] }, { oidcAdminClaim: 'groups', oidcAdminClaimValue: 'sencho-admins' })).toBe('admin'); + + // Custom claim name + expect(resolve({ roles: 'admin-role' }, { oidcAdminClaim: 'roles', oidcAdminClaimValue: 'admin-role' })).toBe('admin'); + + // Claim missing, falls back to default + expect(resolve({}, { oidcAdminClaim: 'roles', oidcAdminClaimValue: 'admin-role', oidcDefaultRole: 'viewer' })).toBe('viewer'); + + // Claim present but no match + expect(resolve({ roles: 'user-role' }, { oidcAdminClaim: 'roles', oidcAdminClaimValue: 'admin-role', oidcDefaultRole: 'viewer' })).toBe('viewer'); + }); +}); diff --git a/backend/src/index.ts b/backend/src/index.ts index c254eef3..baa3eb47 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -923,7 +923,7 @@ app.post('/api/auth/sso/ldap', authRateLimiter, async (req: Request, res: Respon app.get('/api/auth/sso/oidc/:provider/authorize', ssoRateLimiter, async (req: Request, res: Response): Promise => { try { const provider = String(req.params.provider); - const validProviders = ['oidc_google', 'oidc_github', 'oidc_okta']; + const validProviders = ['oidc_google', 'oidc_github', 'oidc_okta', 'oidc_custom']; if (!validProviders.includes(provider)) { res.status(400).json({ error: 'Invalid SSO provider' }); return; @@ -5654,7 +5654,7 @@ app.post('/api/system/console-token', authMiddleware, (req: Request, res: Respon } }); -// --- SSO Config Routes (admin + Admiral, local-only) --- +// --- SSO Config Routes (admin, local-only) --- app.get('/api/sso/config', (req: Request, res: Response): void => { if (req.apiTokenScope) { @@ -5662,7 +5662,6 @@ app.get('/api/sso/config', (req: Request, res: Response): void => { return; } if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; try { const configs = DatabaseService.getInstance().getSSOConfigs(); const result = configs.map(c => { @@ -5685,7 +5684,6 @@ app.get('/api/sso/config/:provider', (req: Request, res: Response): void => { return; } if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; try { const config = SSOService.getInstance().getProviderConfig(String(req.params.provider)); if (!config) { @@ -5709,10 +5707,9 @@ app.put('/api/sso/config/:provider', (req: Request, res: Response): void => { return; } if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; try { const provider = String(req.params.provider); - const validProviders = ['ldap', 'oidc_google', 'oidc_github', 'oidc_okta']; + const validProviders = ['ldap', 'oidc_google', 'oidc_github', 'oidc_okta', 'oidc_custom']; if (!validProviders.includes(provider)) { res.status(400).json({ error: 'Invalid SSO provider' }); return; @@ -5727,7 +5724,7 @@ app.put('/api/sso/config/:provider', (req: Request, res: Response): void => { if (!config.ldapSearchBase?.trim()) missing.push('Search Base'); } else { if (!config.oidcClientId?.trim()) missing.push('Client ID'); - if (provider === 'oidc_okta' && !config.oidcIssuerUrl?.trim()) missing.push('Issuer URL'); + if ((provider === 'oidc_okta' || provider === 'oidc_custom') && !config.oidcIssuerUrl?.trim()) missing.push('Issuer URL'); } if (missing.length > 0) { res.status(400).json({ error: `Missing required fields: ${missing.join(', ')}` }); @@ -5750,7 +5747,6 @@ app.delete('/api/sso/config/:provider', (req: Request, res: Response): void => { return; } if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; try { const deletedProvider = String(req.params.provider); SSOService.getInstance().deleteProviderConfig(deletedProvider); @@ -5768,7 +5764,6 @@ app.post('/api/sso/config/:provider/test', async (req: Request, res: Response): return; } if (!requireAdmin(req, res)) return; - if (!requireAdmiral(req, res)) return; try { const provider = String(req.params.provider); if (provider === 'ldap') { diff --git a/backend/src/services/DatabaseService.ts b/backend/src/services/DatabaseService.ts index d1b016c4..5b7e9770 100644 --- a/backend/src/services/DatabaseService.ts +++ b/backend/src/services/DatabaseService.ts @@ -94,7 +94,7 @@ export interface WebhookExecution { executed_at: number; } -export type AuthProvider = 'local' | 'ldap' | 'oidc_google' | 'oidc_github' | 'oidc_okta'; +export type AuthProvider = 'local' | 'ldap' | 'oidc_google' | 'oidc_github' | 'oidc_okta' | 'oidc_custom'; export type UserRole = 'admin' | 'viewer' | 'deployer' | 'node-admin' | 'auditor'; export type ResourceType = 'stack' | 'node'; diff --git a/backend/src/services/SSOService.ts b/backend/src/services/SSOService.ts index 62f53ac3..451301d2 100644 --- a/backend/src/services/SSOService.ts +++ b/backend/src/services/SSOService.ts @@ -43,6 +43,10 @@ export interface SSOProviderConfig { oidcAdminClaim?: string; oidcAdminClaimValue?: string; oidcDefaultRole?: 'admin' | 'viewer'; + // Custom OIDC claim mapping + oidcIdClaim?: string; + oidcUsernameClaim?: string; + oidcEmailClaim?: string; } export interface SSOAuthResult { @@ -61,6 +65,7 @@ const PROVIDER_DISPLAY_NAMES: Record = { oidc_google: 'Google', oidc_github: 'GitHub', oidc_okta: 'Okta', + oidc_custom: 'Custom OIDC', }; const WELL_KNOWN_ISSUERS: Record = { @@ -85,6 +90,7 @@ export class SSOService { this.seedOidcFromEnv('oidc_google', 'SSO_OIDC_GOOGLE'); this.seedOidcFromEnv('oidc_github', 'SSO_OIDC_GITHUB'); this.seedOidcFromEnv('oidc_okta', 'SSO_OIDC_OKTA'); + this.seedOidcFromEnv('oidc_custom', 'SSO_OIDC_CUSTOM'); } private seedLdapFromEnv(): void { @@ -123,7 +129,7 @@ export class SSOService { const config: SSOProviderConfig = { provider, enabled: true, - displayName: PROVIDER_DISPLAY_NAMES[provider] || provider, + displayName: process.env[`${envPrefix}_DISPLAY_NAME`] || PROVIDER_DISPLAY_NAMES[provider] || provider, oidcIssuerUrl: process.env[`${envPrefix}_ISSUER_URL`] || WELL_KNOWN_ISSUERS[provider] || '', oidcClientId: process.env[`${envPrefix}_CLIENT_ID`] || '', oidcClientSecret: process.env[`${envPrefix}_CLIENT_SECRET`] || '', @@ -131,6 +137,9 @@ export class SSOService { oidcAdminClaim: process.env.SSO_OIDC_ADMIN_CLAIM || 'groups', oidcAdminClaimValue: process.env.SSO_OIDC_ADMIN_CLAIM_VALUE || 'sencho-admins', oidcDefaultRole: (process.env.SSO_DEFAULT_ROLE as 'admin' | 'viewer') || 'viewer', + oidcIdClaim: process.env[`${envPrefix}_ID_CLAIM`] || undefined, + oidcUsernameClaim: process.env[`${envPrefix}_USERNAME_CLAIM`] || undefined, + oidcEmailClaim: process.env[`${envPrefix}_EMAIL_CLAIM`] || undefined, }; const configForStorage = { ...config }; @@ -416,13 +425,20 @@ export class SSOService { } } - const sub = String(userInfo.sub || userInfo.id || ''); + // Use configurable claim names for custom providers, with standard OIDC fallbacks + const idClaimName = config.oidcIdClaim || 'sub'; + const usernameClaimName = config.oidcUsernameClaim || 'preferred_username'; + const emailClaimName = config.oidcEmailClaim || 'email'; + + const sub = String(userInfo[idClaimName] ?? userInfo.sub ?? userInfo.id ?? ''); if (!sub) { return { success: false, error: 'Could not determine user identity from provider' }; } - const email = String(userInfo.email || ''); - const name = String(userInfo.name || userInfo.preferred_username || userInfo.login || email.split('@')[0] || `sso_${sub.substring(0, 8)}`); + const email = String(userInfo[emailClaimName] ?? userInfo.email ?? ''); + const name = String( + userInfo[usernameClaimName] ?? userInfo.name ?? userInfo.preferred_username ?? userInfo.login ?? email.split('@')[0] ?? `sso_${sub.substring(0, 8)}` + ); const role = this.resolveRoleFromOidc(userInfo, config); if (isDebugEnabled()) console.debug('[SSO:debug] OIDC userInfo resolved', { provider, sub, email: email || '(none)', name, role }); diff --git a/docs/features/sso.mdx b/docs/features/sso.mdx index 9b516052..bd34505a 100644 --- a/docs/features/sso.mdx +++ b/docs/features/sso.mdx @@ -1,13 +1,9 @@ --- title: SSO & LDAP Authentication -description: Authenticate with your existing identity provider - LDAP, Google, GitHub, or Okta. +description: Authenticate with your existing identity provider, including LDAP, Google, GitHub, Okta, and any spec-compliant OIDC provider. --- - - SSO requires a Sencho **Admiral** license. Skipper and Community Edition do not include this feature. - - -Sencho Admiral lets your team sign in using existing identity providers instead of managing separate credentials. SSO works **alongside** password authentication - it does not replace it. +Sencho lets your team sign in using existing identity providers instead of managing separate credentials. SSO works **alongside** password authentication; it does not replace it. SSO is available in all Sencho editions, including Community. ## Supported providers @@ -17,6 +13,7 @@ Sencho Admiral lets your team sign in using existing identity providers instead | **Google** | OpenID Connect | Google Workspace or personal Google accounts | | **GitHub** | OAuth 2.0 | GitHub personal accounts and GitHub orgs | | **Okta** | OpenID Connect | Any Okta org or Okta-compatible IdP | +| **Custom OIDC** | OpenID Connect | Any spec-compliant OIDC provider: Keycloak, Authentik, Authelia, Zitadel, KanIDM, Pocket ID, and more | ## How it works @@ -25,9 +22,9 @@ Sencho Admiral lets your team sign in using existing identity providers instead 1. User enters their directory username and password on the Sencho login page 2. Sencho binds to LDAP with a service account, searches for the user, then verifies their password 3. If this is their first login, a Sencho account is automatically created -4. Sencho issues a JWT and the user is logged in - identical to a password login +4. Sencho issues a JWT and the user is logged in, identical to a password login -### OIDC / OAuth flow (Google, GitHub, Okta) +### OIDC / OAuth flow (Google, GitHub, Okta, Custom OIDC) 1. User clicks the provider button on the login page (e.g., "Sign in with Google") 2. Browser redirects to the identity provider for authentication @@ -43,8 +40,8 @@ All OIDC flows use **PKCE** (Proof Key for Code Exchange) and a **state paramete When a user logs in via SSO for the first time, Sencho automatically creates a local account: - **Username** is derived from their identity provider profile (display name, email prefix, or login handle) -- **Role** is assigned based on [role mapping](#role-mapping) - defaults to Viewer if no mapping matches -- **Password** is set to an unusable placeholder - SSO users cannot log in with a password +- **Role** is assigned based on [role mapping](#role-mapping); defaults to Viewer if no mapping matches +- **Password** is set to an unusable placeholder. SSO users cannot log in with a password - **Seat limits** from your license apply. If admin seats are full, the user is downgraded to Viewer. If all seats are full, login is denied with a clear error message. On subsequent logins, the existing account is reused. The user's **email** and **role** are synced from the identity provider on every login. If a user is added to your admin group, they will be promoted to Admin on their next login. If removed, they will be demoted to their default role. Seat limits are respected: if admin seats are full, the promotion is deferred until a seat opens up. @@ -76,12 +73,12 @@ If the user's ID token contains a `groups` claim with the value `sencho-admins`, SSO can be configured two ways: -1. **Settings UI** - Go to **Settings → SSO** in the Sencho dashboard. Enable providers, enter credentials, and test connections from the UI. Changes take effect immediately without restarting. +1. **Settings UI** - Go to **Settings > SSO** in the Sencho dashboard. Enable providers, enter credentials, and test connections from the UI. Changes take effect immediately without restarting. 2. **Environment variables** - Set `SSO_*` variables in your Docker Compose file. These seed the database on first boot. After that, the database configuration is authoritative. ### Via Settings UI -Admins can manage SSO providers in **Settings → SSO**. Each provider is displayed as a collapsible card with: +Admins can manage SSO providers in **Settings > SSO**. Each provider is displayed as a collapsible card with: - An **enable/disable** toggle and an **Active** badge when enabled - Provider-specific configuration fields (expand the card to configure) @@ -90,7 +87,7 @@ Admins can manage SSO providers in **Settings → SSO**. Each provider is displa - A **Remove** button to delete an existing provider configuration - SSO settings panel showing all four identity providers + SSO settings panel showing all five identity providers Expand a provider card to configure it. The LDAP configuration form includes: @@ -114,7 +111,7 @@ OIDC providers (Google, GitHub, Okta) share a common configuration form: | Field | Description | |-------|-------------| -| **Issuer URL** | (Okta only) Your Okta issuer URL | +| **Issuer URL** | (Okta and Custom OIDC) Your provider's OIDC issuer URL | | **Client ID** | OAuth client ID from your identity provider | | **Client Secret** | OAuth client secret | | **Admin Claim** | JWT claim name inspected for role mapping (e.g., `groups`) | @@ -126,6 +123,24 @@ OIDC providers (Google, GitHub, Okta) share a common configuration form: Google OIDC configuration form with client ID, client secret, and role claim mapping +### Custom OIDC configuration + +The **Custom OIDC** provider has additional fields beyond the standard OIDC configuration: + +| Field | Description | +|-------|-------------| +| **Display Name** | Label shown on the login button (e.g., "Corporate SSO") | +| **Issuer URL** | Base URL of the OIDC discovery endpoint (without `/.well-known/openid-configuration`) | +| **User ID Claim** | Claim name for the unique user identifier (default: `sub`) | +| **Username Claim** | Claim name for the display name (default: `preferred_username`) | +| **Email Claim** | Claim name for the email address (default: `email`) | + +The claim mapping fields let you tell Sencho which token claims correspond to user identity fields. Most spec-compliant providers use the standard claim names, so you can leave these blank unless your provider uses non-standard names. + + + Custom OIDC configuration form with discovery URL, claim mapping, and role settings + + ### Via environment variables Environment variables are useful for initial deployment or infrastructure-as-code workflows. They seed the SSO configuration on first startup. After that, changes made in the Settings UI take precedence. @@ -172,6 +187,20 @@ Environment variables are useful for initial deployment or infrastructure-as-cod | `SSO_OIDC_OKTA_CLIENT_ID` | - | Okta application client ID | | `SSO_OIDC_OKTA_CLIENT_SECRET` | - | Okta client secret (encrypted at rest) | +### Custom OIDC + +| Variable | Default | Description | +|----------|---------|-------------| +| `SSO_OIDC_CUSTOM_ENABLED` | `false` | Enable the custom OIDC provider | +| `SSO_OIDC_CUSTOM_DISPLAY_NAME` | `oidc_custom` | Label shown on the login button | +| `SSO_OIDC_CUSTOM_ISSUER_URL` | - | OIDC issuer URL (the base of the discovery endpoint) | +| `SSO_OIDC_CUSTOM_CLIENT_ID` | - | OAuth client ID from your identity provider | +| `SSO_OIDC_CUSTOM_CLIENT_SECRET` | - | OAuth client secret (encrypted at rest) | +| `SSO_OIDC_CUSTOM_SCOPES` | `openid email profile` | Space-separated OAuth scopes | +| `SSO_OIDC_CUSTOM_ID_CLAIM` | `sub` | Token claim for the unique user identifier | +| `SSO_OIDC_CUSTOM_USERNAME_CLAIM` | `preferred_username` | Token claim for the display name | +| `SSO_OIDC_CUSTOM_EMAIL_CLAIM` | `email` | Token claim for the email address | + ### General | Variable | Default | Description | @@ -187,19 +216,108 @@ Environment variables are useful for initial deployment or infrastructure-as-cod If Sencho is behind a reverse proxy (nginx, Traefik, Caddy), you **must** set `SSO_CALLBACK_URL` to your external URL. Otherwise, OAuth callbacks will fail. -Set `SSO_CALLBACK_URL` to the URL users access Sencho from - for example, `https://sencho.example.com`. Sencho uses this to construct the OAuth redirect URI that your identity provider calls back to. +Set `SSO_CALLBACK_URL` to the URL users access Sencho from, for example, `https://sencho.example.com`. Sencho uses this to construct the OAuth redirect URI that your identity provider calls back to. If not set, Sencho auto-detects the URL from the request's `Host` header and protocol, which works for direct access but fails behind proxies that rewrite the host. +## Provider-specific setup examples + +### Keycloak + +1. Create a new client in your Keycloak realm (Client type: **OpenID Connect**) +2. Set **Valid redirect URIs** to `https://sencho.example.com/api/auth/sso/oidc/oidc_custom/callback` +3. Enable **Client authentication** (confidential access type) and copy the client secret from the Credentials tab +4. The Issuer URL is your realm URL: `https://keycloak.example.com/realms/myrealm` +5. Keycloak uses standard claim names by default, so you can leave claim mapping blank + +### Authentik + +1. Create a new OAuth2/OpenID Provider in Authentik +2. Set the redirect URI to `https://sencho.example.com/api/auth/sso/oidc/oidc_custom/callback` +3. Copy the Client ID and Client Secret +4. The Issuer URL is `https://authentik.example.com/application/o//` +5. Default claims work. For group-based admin mapping, configure a `groups` scope in Authentik + +### Authelia + +1. Add an OpenID Connect client to your Authelia configuration +2. Set `redirect_uris` to include `https://sencho.example.com/api/auth/sso/oidc/oidc_custom/callback` +3. The Issuer URL is your Authelia domain: `https://auth.example.com` +4. Authelia uses standard OIDC claims + +### Zitadel + +1. Create a new Web application in your Zitadel project +2. Add `https://sencho.example.com/api/auth/sso/oidc/oidc_custom/callback` as a redirect URI +3. The Issuer URL is your Zitadel instance URL: `https://zitadel.example.com` +4. Copy the Client ID and Client Secret from the application settings + +### KanIDM + +1. Create a new OAuth2 client in KanIDM +2. Set the redirect URI and copy the client credentials +3. The Issuer URL is your KanIDM domain: `https://kanidm.example.com/oauth2/openid/` +4. KanIDM may use `name` instead of `preferred_username` for the username claim. Set **Username Claim** to `name` if usernames are not being mapped correctly. + +### Pocket ID + +1. Create a new OIDC client in Pocket ID +2. Set the callback URL to `https://sencho.example.com/api/auth/sso/oidc/oidc_custom/callback` +3. The Issuer URL is your Pocket ID instance URL +4. Copy the Client ID and Secret from the client configuration + ## Security - **PKCE** - All OIDC flows use `code_challenge_method=S256` to prevent authorization code interception - **State parameter** - A cryptographic random value protects against CSRF attacks on the OAuth callback - **Encrypted secrets** - LDAP bind passwords and OIDC client secrets are encrypted at rest - **No local password** - SSO users are created with an unusable password hash. They cannot bypass SSO by using the password login form -- **Admin-only configuration** - Only Admiral administrators can enable or configure SSO providers +- **Admin-only configuration** - Only administrators can enable or configure SSO providers -For common SSO issues (LDAP connection errors, OAuth callback mismatches, SSO buttons not appearing), see the [Troubleshooting](/operations/troubleshooting#ldap-connection-refused) page. +## Troubleshooting + +### Discovery URL errors + +If the **Test Connection** button returns an error like "Discovery failed" or a network timeout: + +- Verify the Issuer URL is reachable from the Sencho container (not just your browser) +- Confirm the URL does not include `/.well-known/openid-configuration`, just the base issuer URL +- For providers behind a corporate firewall, ensure the Sencho container's DNS can resolve the hostname +- Check that HTTPS certificates are valid. Self-signed certificates may require additional container configuration + +### Issuer mismatch + +If login fails with an issuer validation error, the `issuer` value in the provider's discovery document does not match what Sencho expects. This commonly happens when: + +- The Issuer URL has a trailing slash mismatch (e.g., `https://auth.example.com` vs `https://auth.example.com/`) +- The provider is accessed via a different hostname than it advertises in its discovery document + +Fix: set the Issuer URL to exactly match the `issuer` field returned by your provider's `/.well-known/openid-configuration` endpoint. + +### Claim mapping not working + +If users are created with incorrect usernames or missing emails: + +- Enable debug mode (`DEBUG=true` environment variable) to see the raw claims Sencho receives from the provider +- Check your provider's documentation for which claims it includes in the ID token and userinfo response +- Verify that the scopes you configured include the necessary permissions (some providers require explicit `profile` or `email` scopes) +- Set the appropriate claim names in the Custom OIDC claim mapping fields + +### Redirect URI mismatch + +If the provider returns an "invalid redirect URI" error during login: + +- The callback URL configured in your identity provider must exactly match: `https://sencho.example.com/api/auth/sso/oidc/oidc_custom/callback` +- If Sencho is behind a reverse proxy, set `SSO_CALLBACK_URL` to your external URL +- Some providers are strict about trailing slashes and HTTP vs HTTPS + +### SSO buttons not appearing on login page + +- Verify the provider is **enabled** (toggle on) in Settings > SSO +- Check that the provider configuration was saved successfully +- The login page fetches enabled providers on load. Hard refresh the page if changes were just made. + +For common SSO issues (LDAP connection errors, OAuth callback mismatches), see the [Troubleshooting](/operations/troubleshooting#ldap-connection-refused) page. ## Combining SSO with two-factor authentication diff --git a/docs/getting-started/sso-quickstart.mdx b/docs/getting-started/sso-quickstart.mdx index 3cd790ee..4bfe4f82 100644 --- a/docs/getting-started/sso-quickstart.mdx +++ b/docs/getting-started/sso-quickstart.mdx @@ -3,9 +3,7 @@ title: SSO Setup Guide description: Step-by-step instructions for connecting Sencho to your identity provider. --- - - SSO requires a Sencho **Admiral** license. You can configure SSO via environment variables (shown below) or from the Settings UI after first boot. - +SSO can be configured via environment variables (shown below) or from the Settings UI after first boot. ## Google OIDC @@ -35,7 +33,7 @@ Restart Sencho. A "Google" button will appear on the login page. ## GitHub OAuth -1. Go to **GitHub → Settings → Developer Settings → [OAuth Apps](https://github.com/settings/developers)** +1. Go to **GitHub > Settings > Developer Settings > [OAuth Apps](https://github.com/settings/developers)** 2. Click **New OAuth App** 3. Set: - **Application name**: Sencho @@ -54,7 +52,7 @@ Restart Sencho. A "Google" button will appear on the login page. ## Okta OIDC -1. In the [Okta Admin Console](https://admin.okta.com), go to **Applications → Create App Integration** +1. In the [Okta Admin Console](https://admin.okta.com), go to **Applications > Create App Integration** 2. Select **OIDC - OpenID Connect** and **Web Application** 3. Set the **Sign-in redirect URI** to: `https://sencho.example.com/api/auth/sso/oidc/oidc_okta/callback` 4. Note your **Okta domain** (e.g., `https://dev-123456.okta.com`) @@ -70,6 +68,39 @@ Restart Sencho. A "Google" button will appear on the login page. - SSO_CALLBACK_URL=https://sencho.example.com ``` +## Custom OIDC (Keycloak, Authentik, Authelia, and others) + +The Custom OIDC provider connects Sencho to any identity provider that supports OpenID Connect discovery. This includes Keycloak, Authentik, Authelia, Zitadel, KanIDM, Pocket ID, and any other spec-compliant provider. + +1. In your identity provider, create a new **OIDC / OAuth2 client application** +2. Set the **Redirect URI** to: `https://sencho.example.com/api/auth/sso/oidc/oidc_custom/callback` +3. Note the **Issuer URL** (the base of the `/.well-known/openid-configuration` endpoint, without the well-known path) +4. Copy the **Client ID** and **Client Secret** +5. Add to your `docker-compose.yml`: + +```yaml + environment: + - SSO_OIDC_CUSTOM_ENABLED=true + - SSO_OIDC_CUSTOM_DISPLAY_NAME=Corporate SSO + - SSO_OIDC_CUSTOM_ISSUER_URL=https://auth.example.com/realms/myrealm + - SSO_OIDC_CUSTOM_CLIENT_ID=your-client-id + - SSO_OIDC_CUSTOM_CLIENT_SECRET=your-client-secret + - SSO_CALLBACK_URL=https://sencho.example.com +``` + +If your provider uses non-standard claim names, add claim mapping: + +```yaml + environment: + - SSO_OIDC_CUSTOM_ID_CLAIM=sub + - SSO_OIDC_CUSTOM_USERNAME_CLAIM=preferred_username + - SSO_OIDC_CUSTOM_EMAIL_CLAIM=email +``` + + + Most spec-compliant providers use the standard OIDC claim names (`sub`, `preferred_username`, `email`). You only need to configure claim mapping if your provider uses different names. See the [SSO feature page](/features/sso#provider-specific-setup-examples) for provider-specific notes. + + ## LDAP / Active Directory 1. Identify your LDAP server's URL and port (default: `389` for LDAP, `636` for LDAPS) @@ -116,7 +147,7 @@ By default, all SSO users are assigned the **Viewer** role. To grant Admin to sp This tells Sencho to check the `groups` claim in the OIDC ID token. If it contains `sencho-admins`, the user gets Admin. Roles are synced on every login, so removing a user from the admin group will demote them on their next sign-in. - Some providers (e.g., Azure AD, Okta) require custom scopes to include group claims in the ID token. You can configure additional scopes in the **Scopes** field in Settings > SSO, or via environment variable. The default is `openid email profile`. + Some providers (e.g., Okta, Zitadel) require custom scopes to include group claims in the ID token. You can configure additional scopes in the **Scopes** field in Settings > SSO, or via environment variable. The default is `openid email profile`. ## Full docker-compose.yml example with SSO @@ -139,6 +170,12 @@ services: - SSO_OIDC_GOOGLE_ENABLED=true - SSO_OIDC_GOOGLE_CLIENT_ID=your-google-client-id - SSO_OIDC_GOOGLE_CLIENT_SECRET=your-google-secret + # Custom OIDC (e.g., Keycloak) + - SSO_OIDC_CUSTOM_ENABLED=true + - SSO_OIDC_CUSTOM_DISPLAY_NAME=Keycloak + - SSO_OIDC_CUSTOM_ISSUER_URL=https://keycloak.example.com/realms/myrealm + - SSO_OIDC_CUSTOM_CLIENT_ID=your-keycloak-client-id + - SSO_OIDC_CUSTOM_CLIENT_SECRET=your-keycloak-secret # LDAP - SSO_LDAP_ENABLED=true - SSO_LDAP_URL=ldap://ldap.example.com:389 @@ -154,4 +191,4 @@ services: - SSO_CALLBACK_URL=https://sencho.example.com ``` -For the complete list of environment variables and their defaults, see [SSO & LDAP Authentication →](/features/sso#sso-environment-variables-reference). +For the complete list of environment variables and their defaults, see [SSO & LDAP Authentication >](/features/sso#sso-environment-variables-reference). diff --git a/docs/images/sso/sso-settings-custom-oidc.png b/docs/images/sso/sso-settings-custom-oidc.png new file mode 100644 index 00000000..b53e9b55 Binary files /dev/null and b/docs/images/sso/sso-settings-custom-oidc.png differ diff --git a/docs/images/sso/sso-settings.png b/docs/images/sso/sso-settings.png index 43ea2f4d..f649d422 100644 Binary files a/docs/images/sso/sso-settings.png and b/docs/images/sso/sso-settings.png differ diff --git a/frontend/src/components/Login.tsx b/frontend/src/components/Login.tsx index 03b54dac..03cadd35 100644 --- a/frontend/src/components/Login.tsx +++ b/frontend/src/components/Login.tsx @@ -4,6 +4,7 @@ import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; +import { KeyRound } from 'lucide-react'; interface SSOProvider { provider: string; @@ -34,6 +35,8 @@ function getProviderIcon(provider: string) { ); + case 'oidc_custom': + return ; default: return null; } diff --git a/frontend/src/components/SSOSection.tsx b/frontend/src/components/SSOSection.tsx index 97c41622..91004a01 100644 --- a/frontend/src/components/SSOSection.tsx +++ b/frontend/src/components/SSOSection.tsx @@ -7,9 +7,7 @@ import { Combobox } from '@/components/ui/combobox'; import { Badge } from '@/components/ui/badge'; import { toast } from '@/components/ui/toast-store'; import { apiFetch } from '@/lib/api'; -import { AdmiralGate } from './AdmiralGate'; import { CapabilityGate } from './CapabilityGate'; -import { TierBadge } from './TierBadge'; import { Shield, Loader2, CheckCircle, XCircle } from 'lucide-react'; const ROLE_OPTIONS = [ @@ -38,6 +36,10 @@ interface SSOProviderConfig { oidcAdminClaim?: string; oidcAdminClaimValue?: string; oidcDefaultRole?: string; + // Custom OIDC claim mapping + oidcIdClaim?: string; + oidcUsernameClaim?: string; + oidcEmailClaim?: string; } const PROVIDERS = [ @@ -45,6 +47,7 @@ const PROVIDERS = [ { id: 'oidc_google', label: 'Google', type: 'oidc' as const }, { id: 'oidc_github', label: 'GitHub', type: 'oidc' as const }, { id: 'oidc_okta', label: 'Okta', type: 'oidc' as const }, + { id: 'oidc_custom', label: 'Custom OIDC', type: 'oidc' as const }, ]; function ProviderCard({ providerId, type, label, initialConfig, onSave }: { @@ -227,14 +230,32 @@ function ProviderCard({ providerId, type, label, initialConfig, onSave }: { ) : ( <> - {providerId === 'oidc_okta' && ( + {providerId === 'oidc_custom' && ( +
+ + update('displayName', e.target.value)} + /> +

+ Name shown on the login button (e.g., "Corporate SSO"). +

+
+ )} + {(providerId === 'oidc_okta' || providerId === 'oidc_custom') && (
update('oidcIssuerUrl', e.target.value)} /> + {providerId === 'oidc_custom' && ( +

+ Base URL of the OIDC discovery endpoint (without /.well-known/openid-configuration). +

+ )}
)}
@@ -274,7 +295,7 @@ function ProviderCard({ providerId, type, label, initialConfig, onSave }: { />
-
+
+ {providerId === 'oidc_custom' && ( + <> +
+
+ + update('oidcIdClaim', e.target.value)} + /> +
+
+ + update('oidcUsernameClaim', e.target.value)} + /> +
+
+ + update('oidcEmailClaim', e.target.value)} + /> +
+
+

+ Map claims from your provider's token to Sencho user fields. Leave blank for standard OIDC defaults. +

+ + )} )} @@ -341,13 +395,12 @@ export function SSOSection() { const getConfig = (provider: string) => configs.find(c => c.provider === provider) || null; return ( -

- SSO Authentication + SSO Authentication

Connect your identity provider so team members can sign in with their existing credentials. @@ -374,6 +427,5 @@ export function SSOSection() {

-
); } diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index cc3daf1d..1987a555 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -1,6 +1,7 @@ import { useState, useEffect, useLayoutEffect, useRef } from 'react'; import { Dialog, + DialogClose, DialogContent, DialogTitle, DialogDescription, @@ -14,7 +15,7 @@ import { apiFetch } from '@/lib/api'; import { SENCHO_SETTINGS_CHANGED } from '@/lib/events'; import type { SenchoSettingsChangedDetail } from '@/lib/events'; import { - Shield, Activity, Bell, Code, Server, Package, + Shield, Activity, Bell, Code, Server, Package, X, Info, Crown, Webhook, Users, Zap, Database, LifeBuoy, Lock, Tag, Route, } from 'lucide-react'; import { NodeManager } from './NodeManager'; @@ -337,7 +338,7 @@ export function SettingsModal({ isOpen, onClose, initialSection }: SettingsModal return ( !open && onClose()}> - + Settings Hub Configure Sencho settings @@ -366,7 +367,7 @@ export function SettingsModal({ isOpen, onClose, initialSection }: SettingsModal } label="Users" locked={!isPaid} /> )} {!isRemote && isAdmin && ( - } label="SSO" locked={!isAdmiral} /> + } label="SSO" /> )} {!isRemote && isAdmin && ( } label="API Tokens" locked={!isAdmiral} /> @@ -421,11 +422,19 @@ export function SettingsModal({ isOpen, onClose, initialSection }: SettingsModal
{/* Main Content Area */} - -
- {renderSection()} +
+
+ + + Close +
- + +
+ {renderSection()} +
+
+
); diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsx index 260acf11..8e1ea2ca 100644 --- a/frontend/src/components/ui/combobox.tsx +++ b/frontend/src/components/ui/combobox.tsx @@ -99,7 +99,7 @@ export function Combobox({ disabled={disabled} onClick={() => { if (!disabled) setOpen(true) }} className={cn( - "flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50", + "flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-glass-border bg-input px-3 py-2 text-sm shadow-sm transition-colors focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50", !value && "text-muted-foreground" )} > @@ -112,7 +112,7 @@ export function Combobox({ {/* Options list — absolutely positioned overlay */} {open && ( -
+
{filtered.length === 0 ? (
diff --git a/frontend/src/components/ui/dialog.tsx b/frontend/src/components/ui/dialog.tsx index 64fe4e4f..996cf0ae 100644 --- a/frontend/src/components/ui/dialog.tsx +++ b/frontend/src/components/ui/dialog.tsx @@ -20,8 +20,8 @@ import { // while delegating animation to animate-ui's spring-based dialog const DialogContent = React.forwardRef< HTMLDivElement, - React.ComponentProps ->(({ className, children, ...props }, ref) => ( + React.ComponentProps & { showClose?: boolean } +>(({ className, children, showClose = true, ...props }, ref) => ( {children} - - - Close - + {showClose && ( + + + Close + + )} )); diff --git a/frontend/src/components/ui/multi-select-combobox.tsx b/frontend/src/components/ui/multi-select-combobox.tsx index 9b281cac..17b623d2 100644 --- a/frontend/src/components/ui/multi-select-combobox.tsx +++ b/frontend/src/components/ui/multi-select-combobox.tsx @@ -87,7 +87,7 @@ export function MultiSelectCombobox({ disabled={disabled} onClick={() => { if (!disabled) setOpen(!open) }} className={cn( - "flex h-7 items-center gap-1.5 whitespace-nowrap rounded-md border border-input bg-transparent px-2.5 text-xs shadow-sm ring-offset-background focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 transition-colors", + "flex h-7 items-center gap-1.5 whitespace-nowrap rounded-md border border-glass-border bg-input px-2.5 text-xs shadow-sm transition-colors focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50", selected.size > 0 ? "text-foreground" : "text-muted-foreground", open && "ring-1 ring-ring border-ring" )} @@ -97,7 +97,7 @@ export function MultiSelectCombobox({ {open && ( -
+
{options.length > 5 && (