Files
superbrain/web/docs/AUTHELIA.md
T
Andrew S Erwin c432ff57e9
release gate / check (push) Failing after 6m40s
Add Authelia identity bridge for NextAuth sessions
Keep NextAuth as the OIDC/session layer and add a trusted Go provisioning endpoint that maps verified Authelia subjects to local users. Existing password accounts require explicit admin linking; new users are provisioned without a password. Enable the Authelia login path and update docs. Also fix test schema search_path so pg_trgm opclasses resolve.
2026-10-22 12:39:39 -05:00

9.6 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.

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; check the Go logs for oidc provision or a 409 Account link required
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
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. Optional: Authelia-only login

Email/password remains as a fallback. An Authelia-only deployment requires disabling the credentials provider, local login/signup screens, and local signup/login endpoints in both Next.js and Go, while preserving the trusted OIDC identity-provisioning path. Hiding the email form alone does not disable the backend password login routes.