Files
superbrain/web/docs/AUTHELIA.md
T
Andrew S Erwin f372936894
release gate / check (push) Failing after 7m28s
Add deployment tiers, self-service password reset, and Authelia SSO fixes
Product tiers (decided 2026-10-26): TIER=core|multi is the deployment knob.
core (federated install, paying customers) derives AUTH_MODE=oidc with
signup/bootstrap off - Authelia is the only way in and accounts are
provisioned upstream (Superpanel -> LDAP -> Authelia). multi (hosted
self-service) derives AUTH_MODE=password: signup, password login and
SMTP-backed self-reset, with the OIDC bridge refused even when variables
are set. Explicit AUTH_MODE/SIGNUP_ENABLED/ALLOW_BOOTSTRAP_SIGNUP always
override the tier; invalid values fail startup instead of falling back.
Go enforces every gate at the API; the web UI mirrors it (conditional
credentials provider, SSO-only login page, signup/reset redirects).

Authelia-only bootstrap: ProvisionExternal grants ADMIN to ADMIN_EMAILS
addresses at first SSO login, and --seed accepts SEED_SUBJECT to link a
pre-existing password account offline - the only path when 409 'account
link required' meets a deployment where nobody can password-login to call
oidc-link.

Self-service password reset (multi tier): POST /api/password/forgot and
/api/password/reset with hashed single-use 30-minute tokens
(PasswordResetToken, migration 011 + schema.sql), enumeration-safe
identical 200s, per-IP rate limits, tokenVersion bump on success (all
prior sessions revoked), OIDC-only accounts excluded by design. New
internal/mailer sends via netguard+outbound budget; NETGUARD_TRUSTED_HOSTS
pins operator-chosen relays that resolve privately (split-horizon DNS)
without the blanket INTEGRATIONS_ALLOW_PRIVATE switch. Web gains
/forgot-password and /reset-password pages and a login-page link.

Federated install fixes: the Authelia client now registers a
claims_policy putting email in the ID token (production AccessDenied -
Auth.js builds OIDC profiles exclusively from ID-token claims), config is
validated before restarting the shared Authelia, uninstall removes the
claims block marker-safely, and generated .env switches to TIER=core with
a password-less admin seed.

Tests: tier derivation/override unit tests, mode and tier integration
tests (403 gates, bridge refusal, ADMIN_EMAILS promotion, offline link),
reset-flow integration tests against a loopback SMTP fake, netguard
trusted-host tests. Docs: RUNNING.md, web/docs/AUTHELIA.md section 7,
.env.example, STRATEGY.md.
2026-10-26 12:28:43 -05:00

13 KiB

Connecting superbrain to Authelia (OIDC)

superbrain uses Authelia as its primary OpenID Connect provider. The trusted Next.js server runs the authorization-code flow, validates the ID token, and then exchanges the verified identity for a local Go user. Email/password login remains available as a fallback in the default AUTH_MODE=both; see §7 for the Authelia-only (AUTH_MODE=oidc) and password-only (AUTH_MODE=password) deployment shapes.

This guide covers the Authelia client configuration and how the identity bridge maps a verified subject to the PostgreSQL users that Go authorizes.


1. Current implementation

Paths in this table are relative to the repository root.

Piece File Current behavior
Config detection web/lib/oidc-config.ts enabled means all three OIDC variables contain non-placeholder values; it does not verify connectivity or a working login
Auth provider web/auth.ts Registers provider authelia when configured and exchanges verified identities for local Go users
Login page web/app/login/client.tsx Shows the Authelia button whenever the three variables are configured
Settings → OIDC web/app/(app)/settings/client.tsx Shows configuration status, issuer, and callback URL
Go OIDC handlers internal/oidc/provider.go Status reports configuration; login and callback remain 501 stubs
Go identity bridge internal/auth/oidc_provision.go POST /api/auth/oidc/identity resolves/creates the local user from a service token

A value counts as "not set" if it is empty or looks like a placeholder. These are matched case-insensitively: REPLACE_ME, changeme, placeholder, anything containing example.com/.org/.net, <...>, values starting with your_/your-, or todo.

All three variables must hold real values before the NextAuth provider is registered. The readiness gate and identity mapping are separate requirements.

The root .env.example supplies:

OIDC_ISSUER=REPLACE_ME
OIDC_CLIENT_ID=REPLACE_ME
OIDC_CLIENT_SECRET=REPLACE_ME

Setting these values prepares the configuration. Complete section 3 before expecting users to sign in through Authelia.


2. What to configure in Authelia

The example uses Authelia 4.39 syntax. Authelia must have its OIDC provider configured, be served over valid HTTPS, and be reachable from both the user's browser and the Next.js container. See the upstream OIDC provider and client configuration documentation for your installed version.

2.1 Generate a client secret

docker run --rm authelia/authelia:4.39 authelia crypto hash generate pbkdf2 \
  --variant sha512 --random --random.length 72 --random.charset rfc3986

This prints:

  • Random Password: the plain secret. It goes into superbrain as OIDC_CLIENT_SECRET.
  • Digest: the hashed secret. It goes into Authelia's client_secret.

2.2 Register the superbrain client (configuration.yml)

Merge this example into the existing OIDC provider configuration. Replace the client secret digest and public app hostname; keep your existing provider signing keys, HMAC secret, and other clients.

identity_providers:
  oidc:
    # jwks / hmac_secret must already be configured for OIDC to work
    claims_policies:
      superbrain:
        # Include these identity claims in the ID token.
        id_token: ['email', 'email_verified', 'name', 'preferred_username']
    clients:
      - client_id: 'superbrain'
        client_name: 'superbrain'
        client_secret: '$pbkdf2-sha512$310000$...'   # Digest from 2.1
        public: false
        authorization_policy: 'two_factor'          # or 'one_factor'
        consent_mode: 'explicit'
        claims_policy: 'superbrain'
        redirect_uris:
          - 'https://<superbrain_HOST>/api/auth/callback/authelia'
        scopes: ['openid', 'profile', 'email']
        grant_types: ['authorization_code']
        response_types: ['code']
        token_endpoint_auth_method: 'client_secret_basic'

Validate the configuration and restart your Authelia deployment after editing.

Redirect URI rule: it must exactly match <NEXTAUTH_URL>/api/auth/callback/authelia, including scheme, hostname, port if present, and path. For an HTTPS deployment, use https://<superbrain_HOST>/api/auth/callback/authelia.

The callback is handled by NextAuth on the web app, not the Go API. Forward /api/auth/* to Next.js in your reverse proxy. The identically named direct-Go callback on port 8080 remains a deliberate 501 stub.

2.3 Users

Provide email and profile claims for Authelia users. The bridge creates a password-less local user on first login. If the verified email matches an existing local password account, Go returns 409 Account link required; an administrator can link that account explicitly:

POST /api/admin/oidc-link
{ "userId": "<local user id>", "subject": "<authelia sub>" }

Matching an email string alone is not proof of ownership. The admin screen does not yet expose this link action; use the API while signed in as an administrator.


3. What to configure in superbrain

Set these environment variables in the root .env or hosting environment. Compose passes the OIDC variables to the API and web containers. Replace the sample hostnames with your actual hosts.

Variable Example Notes
NEXTAUTH_URL https://superbrain.company.tld Public web app URL; determines the callback
COOKIE_SECURE 1 For an HTTPS deployment
OIDC_ISSUER https://auth.company.tld Exact issuer advertised in Authelia's discovery document
OIDC_CLIENT_ID superbrain Must match client_id in Authelia
OIDC_CLIENT_SECRET (plain secret from 2.1) The plain value, not the digest

Keep the existing AUTH_SECRET: changing it makes stored IMAP passwords unreadable. The client secret is a separate value and stays server-side.

The default Compose ports bind to localhost. Configure an HTTPS reverse proxy for the public web URL before using these HTTPS settings; see RUNNING.md.

Apply environment changes from the repository root:

docker compose up -d --build

Open Settings → OIDC to confirm the three variables are set. With real values the login page enables Sign in with Authelia.


4. How the identity bridge works

NextAuth handles OIDC discovery, authorization, token exchange, and token validation. After validation, web/auth.ts signs a short-lived service token (typ=oidc-provision) with AUTH_SECRET and calls the Go endpoint:

POST /api/auth/oidc/identity

The request carries the configured issuer, the Authelia sub, email, email_verified, name, and picture. Go validates the service token, checks the issuer against OIDC_ISSUER, and resolves the identity against the Account table (provider='authelia', providerAccountId=sub).

Resolution policy:

  1. An existing provider link is authoritative.
  2. A matching local account with no password may be linked only when Authelia asserts a verified email.
  3. A matching local password account returns 409 Account link required.
  4. Otherwise Go creates a password-less local user. The first external user on a fresh installation follows the same bootstrap-admin rules as signup.

The NextAuth JWT stores the resolved local User.id and tokenVersion. web/lib/api.ts signs API assertions for that local ID, and Go reloads roles and ownership from PostgreSQL on every request. The OIDC sub is never used as a local user ID.


5. Verify the integration

  1. Open <OIDC_ISSUER>/.well-known/openid-configuration. It should return JSON with the expected issuer and endpoints. The Next container must also be able to reach those HTTPS endpoints.
  2. Check Settings → OIDC for the configured issuer and exact callback URL.
  3. Sign out, click Sign in with Authelia, and authenticate with Authelia.
  4. Confirm the browser returns through the NextAuth callback to /pages.
  5. Check /api/me through the web app and save a bookmark to confirm the session resolves to the intended local user and Go accepts its identity.
  6. Sign out and back in to verify the same user and data are retained.
  7. Test a new Authelia user, an explicitly linked existing account, and two different users to verify provisioning, account linking, and data isolation.

6. Troubleshooting

Symptom Likely cause
Config says Not connected One of the variables is empty or a placeholder, or containers were not recreated after editing .env
NextAuth returns AccessDenied The Go identity bridge rejected the exchange. The web container logs oidc provision: Go answered <status>: 409 = local password account needs explicit linking; 400 = missing subject/email (client lacks a claims_policy, so Authelia kept email out of the ID token) or an issuer mismatch between the web and app containers
Go callback returns 501 Expected stub; the browser callback must reach Next.js, not Go
Authelia shows "invalid redirect_uri" Callback URL not listed exactly in redirect_uris
Authelia logs "The state is missing or does not have enough characters" Auth.js omits state for OIDC providers by default (PKCE-only); the provider must set checks: ['pkce', 'state'] (it does — don't remove it)
Error page ?error=Configuration after login Wrong client secret (digest used instead of plain), or the issuer is unreachable or has an invalid TLS certificate
Required identity claims are missing Check Authelia's claims policy and user profile
Browser has a session, but Go returns 401 Check that the session ID is the resolved local User.id, not the OIDC subject

7. Deployment tiers and auth modes

Deployments have a product tier: TIER=core (federated install for paying customers — Authelia exclusively) or TIER=multi (hosted self-service — signup, password login, self-reset). The tier derives the mechanism-level variables; an explicitly set variable always wins. AUTH_MODE selects the authentication personality directly. Go enforces everything at the API; the web UI follows (hiding a form is never the only barrier):

Mode Password login Signup Password reset Authelia OIDC
both (default, no tier) ✅ ✅ (SIGNUP_ENABLED) ✅ (needs SMTP_*) ✅ when the three OIDC_* vars are real
password (TIER=multi) ✅ ✅ (SIGNUP_ENABLED) ✅ (needs SMTP_*) ⛔ disabled even with OIDC_* set
oidc (TIER=core) ⛔ 403 ⛔ 403 ⛔ 403 ✅ required

TIER=core additionally defaults SIGNUP_ENABLED and ALLOW_BOOTSTRAP_SIGNUP to off (accounts are provisioned upstream, e.g. Superpanel → LDAP → Authelia). TIER=multi keeps the historical defaults. The multi tier is intended to grow organization-level tenancy (memberships, per-tenant admin/billing) — decided 2026-10-26, not built yet.

In oidc mode:

  • The credentials provider is not registered in NextAuth, /signup, /forgot-password and /reset-password redirect to /login, and Go refuses POST /api/auth/login, POST /api/signup and the password-reset endpoints. The OIDC identity bridge is the only way in.
  • Accounts are provisioned upstream (on the federated core: Superpanel → LDAP → Authelia) and materialize locally on first SSO login.
  • Admin bootstrap: an address listed in ADMIN_EMAILS becomes ADMIN at its first SSO login; everyone else is USER.
  • The operator account can be seeded password-less (SEED_EMAIL=... /superbrain --seed). Do NOT seed a password in this mode: it is unusable (login is disabled) and it blocks the SSO bridge's verified-email auto-link with 409 Account link required.
  • Pre-existing password accounts (e.g. from before a mode switch) must be linked deliberately — email match alone is not proof. With login disabled nobody can obtain the admin session POST /api/admin/oidc-link requires, so use the offline path: docker exec -e SEED_EMAIL=<email> -e SEED_SUBJECT=<authelia sub> superbrain-app /superbrain --seed (idempotent; refuses subjects already linked to a different user).

In password mode the bridge (POST /api/auth/oidc/identity) is refused even with a valid service token, and the status endpoint reports OIDC disabled so the UI hides Authelia.

Unknown AUTH_MODE values fail startup (Validate) instead of silently falling back to both — a typo must never re-enable password login on an SSO-only deployment.