diff --git a/docs/authentication/oidc.mdx b/docs/authentication/oidc.mdx new file mode 100644 index 0000000..7653a8d --- /dev/null +++ b/docs/authentication/oidc.mdx @@ -0,0 +1,107 @@ +--- +title: OIDC +--- + +Allow users to sign in with any OpenID Connect provider, such as Authentik, Auth0, Authelia, Zitadel, or VoidAuth. + +Use this when your identity provider does not have a dedicated page. For Google, Okta, and Keycloak, use their dedicated provider types instead. + +## Prerequisites + +- An OpenID Connect provider that supports [discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) (publishes `/.well-known/openid-configuration`) +- Admin access to create a client (application) +- [external_url](/configuration/config#general) + +## Setup + +### 1. Create a Client in Your Provider + +The exact steps vary by provider. Create a confidential OAuth 2.0 / OpenID Connect client with these settings: + +- **Grant type**: Authorization Code +- **Client authentication**: enabled (client secret) +- **Redirect URI**: + ``` + <>/api/auth/oidc/callback + ``` +- **Scopes**: `openid`, `email`, `profile` + +pgconsole requires an `email` claim. Make sure the client is allowed to release the user's email. + +### 2. Get Client Credentials + +Copy the **Client ID** and **Client Secret** from the client you created. + +### 3. Get Issuer URL + +The issuer URL is the base URL your provider publishes its discovery document under. pgconsole fetches `<>/.well-known/openid-configuration` to find the authorization, token, and userinfo endpoints. + +| Provider | Issuer URL pattern | +|----------|--------------------| +| Authentik | `https://auth.example.com/application/o/pgconsole/` | +| Auth0 | `https://your-tenant.us.auth0.com` | +| Authelia | `https://auth.example.com` | +| Zitadel | `https://your-org.zitadel.cloud` | + +To verify, open the issuer URL with `/.well-known/openid-configuration` appended in a browser. It should return a JSON document whose `issuer` field matches the URL you configured. + +### 4. Configure pgconsole + +Add the OIDC provider to your `pgconsole.toml`: + +```toml pgconsole.toml +[general] +external_url = "https://pgconsole.example.com" + +[auth] +# openssl rand -hex 32 +jwt_secret = "your-secret-key-at-least-32-characters-long" +signin_expiry = "7d" + +[[auth.providers]] +type = "oidc" +name = "Authentik" # optional, shown on the sign-in button +client_id = "pgconsole" +client_secret = "your-client-secret" +issuer_url = "https://auth.example.com/application/o/pgconsole/" + +# Allow each user to sign in. Emails must match those returned by your provider. +[[users]] +email = "alice@example.com" + +[[users]] +email = "bob@example.com" + +[[users]] +email = "carol@example.com" + +# Groups and IAM rules grant access; they do not create users. +[[groups]] +id = "dev-team" +name = "Development Team" +members = ["alice@example.com", "bob@example.com"] + +[[iam]] +connection = "production" +permissions = ["read"] +members = ["user:carol@example.com", "group:dev-team"] +``` + +See [OAuth Providers](/configuration/config#oauth-providers) in the configuration reference for all provider fields. + +pgconsole authenticates to the token endpoint with HTTP Basic (`client_secret_basic`) when your provider advertises it, and falls back to form-body credentials (`client_secret_post`) otherwise. If your client is registered for a specific method, set `token_auth_method` explicitly: + +```toml pgconsole.toml +[[auth.providers]] +type = "oidc" +client_id = "pgconsole" +client_secret = "your-client-secret" +issuer_url = "https://auth.example.com" +token_auth_method = "client_secret_post" +``` + +Only one `oidc` provider can be configured. To offer several identity providers side by side, combine `oidc` with the dedicated `google`, `okta`, or `keycloak` types. + +### 5. Restart pgconsole + +Restart the application for changes to take effect. A "Continue with Authentik" button (or "Continue with SSO" if `name` is omitted) will appear on the login page. diff --git a/docs/authentication/overview.mdx b/docs/authentication/overview.mdx index 4bc5a9c..106818d 100644 --- a/docs/authentication/overview.mdx +++ b/docs/authentication/overview.mdx @@ -9,7 +9,7 @@ pgconsole supports multiple authentication methods to secure access to your data | Method | Description | Best For | |--------|-------------|----------| | Email/Password | Built-in local authentication | Simple setups, small teams | -| SSO ([Google](/authentication/google), [Okta](/authentication/okta), [Keycloak](/authentication/keycloak)) | OAuth providers | Organizations with existing identity providers | +| SSO ([Google](/authentication/google), [Okta](/authentication/okta), [Keycloak](/authentication/keycloak), [OIDC](/authentication/oidc)) | OAuth providers | Organizations with existing identity providers | ## Configuration diff --git a/docs/configuration/config.mdx b/docs/configuration/config.mdx index e4b8a5d..d5b62eb 100644 --- a/docs/configuration/config.mdx +++ b/docs/configuration/config.mdx @@ -97,6 +97,13 @@ client_id = "0oaXXXXXXXXXXXXXX" client_secret = "your-okta-client-secret" issuer_url = "https://your-org.okta.com/oauth2/default" +[[auth.providers]] +type = "oidc" +name = "Authentik" +client_id = "pgconsole" +client_secret = "your-client-secret" +issuer_url = "https://auth.example.com/application/o/pgconsole/" + [[users]] email = "admin@example.com" password = "your-password" @@ -281,14 +288,18 @@ signin_expiry = "7d" ### OAuth Providers -OAuth providers are configured as an array of `[[auth.providers]]` entries. Each entry requires a `type` field. Repeat for multiple providers. +OAuth providers are configured as an array of `[[auth.providers]]` entries. Each entry requires a `type` field. Repeat for multiple providers, at most one per type. + +Use `type = "oidc"` for any provider that supports OpenID Connect discovery (Authentik, Auth0, Authelia, Zitadel, and most self-hosted identity providers). pgconsole resolves the authorization, token, and userinfo endpoints from `/.well-known/openid-configuration`. | Field | Description | Required | |-------|-------------|----------| -| `type` | Provider type: `google`, `keycloak`, or `okta` | Yes | +| `type` | Provider type: `google`, `keycloak`, `okta`, or `oidc` | Yes | | `client_id` | OAuth client ID | Yes | | `client_secret` | OAuth client secret | Yes | -| `issuer_url` | Issuer URL (required for `keycloak` and `okta`) | | +| `issuer_url` | Issuer URL (required for `keycloak`, `okta`, and `oidc`) | | +| `name` | Display name on the sign-in button (`oidc` only, defaults to "SSO") | | +| `token_auth_method` | How the client secret is sent to the token endpoint: `client_secret_basic` or `client_secret_post` (`oidc` only, inferred from discovery when omitted) | | ```toml pgconsole.toml # Google @@ -310,6 +321,14 @@ type = "okta" client_id = "0oaXXXXXXXXXXXXXX" client_secret = "your-okta-client-secret" issuer_url = "https://your-org.okta.com/oauth2/default" + +# Generic OIDC (Authentik, Auth0, Authelia, Zitadel, ...) +[[auth.providers]] +type = "oidc" +name = "Authentik" +client_id = "pgconsole" +client_secret = "your-client-secret" +issuer_url = "https://auth.example.com/application/o/pgconsole/" ``` ## Users diff --git a/docs/docs.json b/docs/docs.json index 5a2235c..e151c44 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -42,7 +42,8 @@ "pages": [ "authentication/google", "authentication/okta", - "authentication/keycloak" + "authentication/keycloak", + "authentication/oidc" ] } ] diff --git a/docs/features/audit-log.mdx b/docs/features/audit-log.mdx index dbc4f39..b637c44 100644 --- a/docs/features/audit-log.mdx +++ b/docs/features/audit-log.mdx @@ -68,7 +68,7 @@ All audit events are JSON objects with a common structure: | Field | Description | |-------|-------------| -| `provider` | Auth provider (`basic`, `google`, `keycloak`) | +| `provider` | Auth provider (`basic`, `google`, `okta`, `keycloak`, `oidc`) | | `ip` | Client IP address | | `success` | Whether login succeeded | | `error` | Error message (if failed) | diff --git a/server/auth-routes.ts b/server/auth-routes.ts index b364120..867f626 100644 --- a/server/auth-routes.ts +++ b/server/auth-routes.ts @@ -6,6 +6,7 @@ import { auditLogin, auditLogout } from './lib/audit' import { registerGoogleOAuth } from './lib/oauth/google' import { registerKeycloakOAuth } from './lib/oauth/keycloak' import { registerOktaOAuth } from './lib/oauth/okta' +import { registerOidcOAuth } from './lib/oauth/oidc' const router = Router() @@ -118,6 +119,7 @@ const oauthOpts = { registerGoogleOAuth(router, oauthOpts) registerKeycloakOAuth(router, oauthOpts) registerOktaOAuth(router, oauthOpts) +registerOidcOAuth(router, oauthOpts) // GET /api/auth/providers router.get('/providers', (_req: Request, res: Response) => { @@ -126,10 +128,10 @@ router.get('/providers', (_req: Request, res: Response) => { } const config = getAuthConfig() - const providers: Array<{ name: string }> = [] + const providers: Array<{ name: string; label?: string }> = [] if (getUsers().some(u => u.password)) providers.push({ name: 'basic' }) for (const provider of config?.providers ?? []) { - providers.push({ name: provider.type }) + providers.push(provider.name ? { name: provider.type, label: provider.name } : { name: provider.type }) } return res.json({ providers }) diff --git a/server/lib/auth.ts b/server/lib/auth.ts index 9c8b072..0a863ac 100644 --- a/server/lib/auth.ts +++ b/server/lib/auth.ts @@ -5,14 +5,14 @@ import { getAuthConfig, getUserByEmail } from './config' export interface TokenPayload extends JWTPayload { sub: string // email name?: string // display name (only if different from sub) - idp?: 'google' | 'keycloak' | 'okta' // identity provider (omitted for basic auth) + idp?: 'google' | 'keycloak' | 'okta' | 'oidc' // identity provider (omitted for basic auth) avatar?: string // avatar URL (Google profile picture) } export interface User { email: string name: string - idp?: 'google' | 'keycloak' | 'okta' // omitted for basic auth + idp?: 'google' | 'keycloak' | 'okta' | 'oidc' // omitted for basic auth avatar?: string // avatar URL (Google profile picture) } diff --git a/server/lib/config.ts b/server/lib/config.ts index e491869..45b72b3 100644 --- a/server/lib/config.ts +++ b/server/lib/config.ts @@ -34,10 +34,12 @@ export interface UserConfig { } export interface AuthProviderConfig { - type: 'google' | 'keycloak' | 'okta' + type: 'google' | 'keycloak' | 'okta' | 'oidc' client_id: string client_secret: string - issuer_url?: string // required for keycloak and okta + issuer_url?: string // required for keycloak, okta and oidc + name?: string // display name on the sign-in button (oidc only) + token_auth_method?: 'client_secret_basic' | 'client_secret_post' // oidc only; inferred from discovery when omitted } export interface AuthConfig { @@ -511,7 +513,7 @@ export async function loadConfigFromString(content: string): Promise { // Parse [[auth.providers]] array const providers: AuthProviderConfig[] = [] const rawProviders = a.providers as unknown[] | undefined - const validProviderTypes = ['google', 'keycloak', 'okta'] + const validProviderTypes = ['google', 'keycloak', 'okta', 'oidc'] if (rawProviders && Array.isArray(rawProviders)) { for (const entry of rawProviders) { const raw = entry as Record @@ -529,16 +531,22 @@ export async function loadConfigFromString(content: string): Promise { throw new Error(`${raw.type} provider missing required field: client_secret`) } - // issuer_url required for keycloak and okta - if ((raw.type === 'keycloak' || raw.type === 'okta') && (!raw.issuer_url || typeof raw.issuer_url !== 'string')) { + // issuer_url required for keycloak, okta and oidc + if ((raw.type === 'keycloak' || raw.type === 'okta' || raw.type === 'oidc') && (!raw.issuer_url || typeof raw.issuer_url !== 'string')) { throw new Error(`${raw.type} provider missing required field: issuer_url`) } + if (raw.token_auth_method !== undefined && raw.token_auth_method !== 'client_secret_basic' && raw.token_auth_method !== 'client_secret_post') { + throw new Error(`${raw.type} provider has invalid token_auth_method: ${raw.token_auth_method}. Must be one of: client_secret_basic, client_secret_post`) + } + providers.push({ type: raw.type as AuthProviderConfig['type'], client_id: raw.client_id, client_secret: raw.client_secret, issuer_url: typeof raw.issuer_url === 'string' ? raw.issuer_url.replace(/\/+$/, '') : undefined, + name: typeof raw.name === 'string' ? raw.name : undefined, + token_auth_method: raw.token_auth_method as AuthProviderConfig['token_auth_method'], }) } } diff --git a/server/lib/oauth/oidc.ts b/server/lib/oauth/oidc.ts new file mode 100644 index 0000000..ef5c1f1 --- /dev/null +++ b/server/lib/oauth/oidc.ts @@ -0,0 +1,170 @@ +import type { Router, Request, Response } from 'express' +import { createToken, type User } from '../auth' +import { getAuthProvider, getExternalUrl, getUserByEmail } from '../config' +import { auditLogin } from '../audit' +import type { OAuthOpts } from './types' + +interface OidcEndpoints { + authorization_endpoint: string + token_endpoint: string + userinfo_endpoint: string + // Send client credentials via HTTP Basic (RFC 6749 default) instead of the form body + token_auth_basic: boolean +} + +let cachedEndpoints: OidcEndpoints | undefined + +// Resolve endpoints from the OIDC discovery document, cached after first success +async function getEndpoints(issuerUrl: string): Promise { + if (cachedEndpoints) return cachedEndpoints + + const res = await fetch(`${issuerUrl}/.well-known/openid-configuration`) + if (!res.ok) { + throw new Error(`OIDC discovery failed: ${res.status}`) + } + const doc = await res.json() + if (!doc.authorization_endpoint || !doc.token_endpoint || !doc.userinfo_endpoint) { + throw new Error('OIDC discovery document missing required endpoints') + } + // client_secret_basic is the spec default when the provider doesn't advertise its methods + const authMethods: unknown = doc.token_endpoint_auth_methods_supported + cachedEndpoints = { + authorization_endpoint: doc.authorization_endpoint, + token_endpoint: doc.token_endpoint, + userinfo_endpoint: doc.userinfo_endpoint, + token_auth_basic: !Array.isArray(authMethods) || authMethods.includes('client_secret_basic'), + } + return cachedEndpoints +} + +export function registerOidcOAuth(router: Router, opts: OAuthOpts): void { + // GET /api/auth/oidc + router.get('/oidc', async (_req: Request, res: Response) => { + const oidc = getAuthProvider('oidc') + if (!oidc) { + return res.status(400).json({ error: 'OIDC not configured' }) + } + + let endpoints: OidcEndpoints + try { + endpoints = await getEndpoints(oidc.issuer_url!) + } catch (err) { + console.error('[oidc]', err) + return res.status(502).json({ error: 'OIDC discovery failed' }) + } + + const state = opts.generateState() + res.cookie(opts.stateCookie, state, opts.stateCookieOptions) + + const externalUrl = getExternalUrl()! + // Merge into any query string the discovered endpoint already carries + const authUrl = new URL(endpoints.authorization_endpoint) + authUrl.searchParams.set('client_id', oidc.client_id) + authUrl.searchParams.set('redirect_uri', `${externalUrl}/api/auth/oidc/callback`) + authUrl.searchParams.set('response_type', 'code') + authUrl.searchParams.set('scope', 'openid email profile') + authUrl.searchParams.set('state', state) + return res.redirect(authUrl.toString()) + }) + + // GET /api/auth/oidc/callback + router.get('/oidc/callback', async (req: Request, res: Response) => { + const oidc = getAuthProvider('oidc') + const externalUrl = getExternalUrl()! + + if (!oidc) { + return res.redirect(`${externalUrl}/signin?error=not_configured`) + } + + // Check for OAuth error response + const { error, code, state } = req.query + if (error) { + res.clearCookie(opts.stateCookie, { path: '/' }) + return res.redirect(`${externalUrl}/signin?error=${encodeURIComponent(String(error))}`) + } + + // Validate state parameter (CSRF protection) + const savedState = req.cookies?.[opts.stateCookie] + res.clearCookie(opts.stateCookie, { path: '/' }) + if (!state || !savedState || state !== savedState) { + return res.redirect(`${externalUrl}/signin?error=invalid_state`) + } + + if (!code || typeof code !== 'string') { + return res.redirect(`${externalUrl}/signin?error=no_code`) + } + + try { + const endpoints = await getEndpoints(oidc.issuer_url!) + + const tokenBody = new URLSearchParams({ + code, + redirect_uri: `${externalUrl}/api/auth/oidc/callback`, + grant_type: 'authorization_code', + }) + const tokenHeaders: Record = { 'Content-Type': 'application/x-www-form-urlencoded' } + // Explicit config wins over the method inferred from discovery + const useBasic = oidc.token_auth_method + ? oidc.token_auth_method === 'client_secret_basic' + : endpoints.token_auth_basic + if (useBasic) { + const credentials = `${encodeURIComponent(oidc.client_id)}:${encodeURIComponent(oidc.client_secret)}` + tokenHeaders.Authorization = `Basic ${Buffer.from(credentials).toString('base64')}` + } else { + tokenBody.set('client_id', oidc.client_id) + tokenBody.set('client_secret', oidc.client_secret) + } + const tokenRes = await fetch(endpoints.token_endpoint, { + method: 'POST', + headers: tokenHeaders, + body: tokenBody, + }) + if (!tokenRes.ok) { + return res.redirect(`${externalUrl}/signin?error=token_failed`) + } + + const tokens = await tokenRes.json() + const userRes = await fetch(endpoints.userinfo_endpoint, { + headers: { Authorization: `Bearer ${tokens.access_token}` }, + }) + if (!userRes.ok) { + return res.redirect(`${externalUrl}/signin?error=userinfo_failed`) + } + + const userInfo = await userRes.json() + + // Require email as the identity + if (!userInfo.email) { + return res.redirect(`${externalUrl}/signin?error=no_email`) + } + if (userInfo.email_verified === false) { + return res.redirect(`${externalUrl}/signin?error=email_not_verified`) + } + + // Check user is in [[users]] list + if (!getUserByEmail(userInfo.email)) { + return res.redirect(`${externalUrl}/signin?error=user_not_allowed`) + } + + // Build display name from first/last name, falling back to full name or email + const displayName = + userInfo.given_name && userInfo.family_name + ? `${userInfo.given_name} ${userInfo.family_name}` + : userInfo.name || userInfo.email + + const user: User = { + email: userInfo.email, + name: displayName, + idp: 'oidc', + } + + const token = await createToken(user) + res.cookie(opts.cookieName, token, opts.cookieOptions) + auditLogin(user.email, 'oidc', opts.getClientIp(req), true) + return res.redirect(externalUrl) + } catch { + auditLogin('unknown', 'oidc', opts.getClientIp(req), false, 'OIDC OAuth error') + return res.redirect(`${externalUrl}/signin?error=oauth_error`) + } + }) +} diff --git a/src/components/AuthForm.tsx b/src/components/AuthForm.tsx index ee2f09c..7e1e7e7 100644 --- a/src/components/AuthForm.tsx +++ b/src/components/AuthForm.tsx @@ -11,6 +11,7 @@ const oauthProviders: Record, label: 'Continue with Google', path: '/api/auth/google' }, keycloak: { icon: , label: 'Continue with Keycloak', path: '/api/auth/keycloak' }, okta: { icon: , label: 'Continue with Okta', path: '/api/auth/okta' }, + oidc: { icon: , label: 'Continue with SSO', path: '/api/auth/oidc' }, }; interface AuthFormProps { @@ -46,7 +47,11 @@ export default function AuthForm({ onSuccess }: AuthFormProps) { const hasBasic = providers.some((p) => p.name === 'basic'); const oauthEntries = providers .filter((p) => p.name !== 'basic' && p.name in oauthProviders) - .map((p) => ({ key: p.name, ...oauthProviders[p.name] })); + .map((p) => ({ + key: p.name, + ...oauthProviders[p.name], + ...(p.label ? { label: `Continue with ${p.label}` } : {}), + })); const hasOAuth = oauthEntries.length > 0; if (providers.length === 0) { diff --git a/src/lib/auth-client.ts b/src/lib/auth-client.ts index e59903b..05e3487 100644 --- a/src/lib/auth-client.ts +++ b/src/lib/auth-client.ts @@ -80,6 +80,7 @@ export async function signOut() { export interface AuthProvider { name: string + label?: string // display name for the sign-in button (oidc only) } export async function getProviders(): Promise {