Add Authelia identity bridge for NextAuth sessions
release gate / check (push) Failing after 6m40s

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.
This commit is contained in:
Andrew S Erwin
2026-10-22 12:39:39 -05:00
parent d870eece1e
commit c432ff57e9
16 changed files with 796 additions and 150 deletions
+1 -1
View File
@@ -180,7 +180,7 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba
{oidc.enabled ? <Check className="h-4 w-4 mt-0.5 shrink-0" /> : <AlertTriangle className="h-4 w-4 mt-0.5 shrink-0" />}
<span>
{oidc.enabled
? <>Configured for <span className="font-mono break-all">{oidc.issuer}</span>. Client integration is still pending.</>
? <>Configured for <span className="font-mono break-all">{oidc.issuer}</span>. Authelia sign-in is enabled.</>
: <>Not connected. Authelia sign-in is disabled until all three variables below hold real values. Users can sign in with email and password meanwhile. Setup guide: <span className="font-mono">docs/AUTHELIA.md</span></>}
</span>
</div>
+3 -6
View File
@@ -10,9 +10,6 @@ import { toast } from 'sonner'
import { useRouter } from 'next/navigation'
export function LoginClient({ oidcEnabled }: { oidcEnabled: boolean }) {
// Client-owned integration point. Keep disabled until verified Authelia
// identities are mapped to Go users in auth.ts's sign-in callback.
const oidcReady = false
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)
@@ -59,14 +56,14 @@ export function LoginClient({ oidcEnabled }: { oidcEnabled: boolean }) {
className="w-full gap-2"
size="lg"
variant="default"
disabled={!oidcEnabled || !oidcReady}
disabled={!oidcEnabled}
>
<Shield className="h-5 w-5" />
Sign in with Authelia
</Button>
{(!oidcEnabled || !oidcReady) && (
{!oidcEnabled && (
<p className="text-center text-xs text-muted-foreground -mt-2">
Authelia single sign-on awaits client integration. Use email below.
Authelia single sign-on is not configured. Use email below.
</p>
)}
+77 -7
View File
@@ -18,7 +18,60 @@ const signClientIP = (secret: string, ip: string): { ts: string; sig: string } =
return { ts, sig: createHmac('sha256', secret).update(`${ip}|${ts}`).digest('hex') }
}
// NextAuth owns the browser session and the eventual client-managed OIDC flow.
// Exchange a verified Authelia identity for a local Go user. The Next server
// is the only holder of AUTH_SECRET; Go accepts the resulting oidc-provision
// token only on this endpoint. The OIDC subject is an account-link key, never
// a local User.id.
const provisionAuthelia = async (account: any, profile: any): Promise<{ id: string; role?: string; tokenVersion: number } | null> => {
const secret = process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET
const issuer = process.env.OIDC_ISSUER?.trim()
const subject = typeof account?.providerAccountId === 'string' ? account.providerAccountId : ''
if (!secret || !issuer || !subject) return null
const serviceToken = jwt.sign(
{ typ: 'oidc-provision', aud: 'superbrain-api' },
secret,
{ algorithm: 'HS256', issuer: 'superbrain', expiresIn: '60s' },
)
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), 5000)
try {
const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/auth/oidc/identity`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${serviceToken}` },
cache: 'no-store',
signal: controller.signal,
body: JSON.stringify({
issuer,
subject,
email: profile?.email ?? null,
emailVerified: profile?.email_verified === true,
name: profile?.name ?? profile?.preferred_username ?? null,
image: profile?.picture ?? null,
}),
})
if (!response.ok) {
// 409 means the local account needs explicit linking; never bypass it.
console.error(`oidc provision: Go answered ${response.status}`)
return null
}
const data = await response.json()
const id = data?.user?.id
const tokenVersion = data?.tokenVersion
if (typeof id !== 'string' || typeof tokenVersion !== 'number') {
console.error('oidc provision: malformed Go response')
return null
}
return { id, role: typeof data.user.role === 'string' ? data.user.role : undefined, tokenVersion }
} catch (error) {
const kind = error instanceof Error ? error.name : 'Error'
console.error(`oidc provision: Go unreachable (${kind})`)
return null
} finally {
clearTimeout(timer)
}
}
// NextAuth owns the browser session and the client-managed OIDC flow.
// Password verification and data ownership live in Go, not Prisma.
export const { handlers, auth, signIn, signOut } = NextAuth({
trustHost: true,
@@ -88,14 +141,31 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
],
callbacks: {
async signIn({ account }) {
// Client integration point: exchange a verified Authelia identity for a
// local Go User/Account before enabling OIDC. No subject is trusted as a
// database user ID; the backend exchange stays an explicit 501 stub.
return account?.provider !== 'authelia'
// Authelia identities are exchanged for local Go users in the jwt callback.
return account?.provider === 'authelia' || account?.provider === 'credentials'
},
async jwt({ token, user, account, profile, trigger }) {
if (trigger === 'signIn' && account?.provider === 'authelia') {
const local = await provisionAuthelia(account, profile)
if (!local) throw new Error('Authelia identity mapping failed')
token.id = local.id
token.ver = local.tokenVersion
token.role = local.role
return token
}
if (user) {
token.id = user.id
token.ver = user.tokenVersion
token.role = user.role
}
return token
},
async jwt({ token, user }) { if (user) { token.id = user.id; token.ver = user.tokenVersion } return token },
async session({ session, token }) {
if (session.user) { session.user.id = token.id as string; session.user.ver = token.ver }
if (session.user) {
session.user.id = token.id as string
session.user.ver = token.ver
session.user.role = token.role
}
return session
},
},
+61 -63
View File
@@ -1,14 +1,12 @@
# Connecting superbrain to Authelia (OIDC)
superbrain includes an **Authelia OpenID Connect provider scaffold**, but
end-to-end sign-in is intentionally **stubbed**. Real credentials register
the NextAuth provider; the login button and sign-in callback still block it
until a developer implements mapping to local Go users.
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 configuration you can prepare now and the developer work
needed to finish the connection. Email/password login remains available.
The client-managed OIDC flow runs on the trusted Next.js server; Go owns
local users, accounts, and data authorization.
This guide covers the Authelia client configuration and how the identity bridge
maps a verified subject to the PostgreSQL users that Go authorizes.
---
@@ -19,10 +17,11 @@ 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, but `callbacks.signIn` rejects every Authelia sign-in |
| Login page | `web/app/login/client.tsx` | `oidcReady = false` keeps the button disabled even with real credentials |
| Settings → OIDC | `web/app/(app)/settings/client.tsx` | Shows configuration status, issuer, and callback URL; explicitly says integration is pending |
| Go OIDC handlers | `internal/oidc/provider.go` | Status reports configuration; login and callback return **501** |
| 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`,
@@ -40,7 +39,7 @@ OIDC_CLIENT_ID=REPLACE_ME
OIDC_CLIENT_SECRET=REPLACE_ME
```
Setting these values prepares the configuration. Complete section 4 before
Setting these values prepares the configuration. Complete section 3 before
expecting users to sign in through Authelia.
---
@@ -104,14 +103,22 @@ if present, and path. For an HTTPS deployment, use
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 is a deliberate 501 stub.
direct-Go callback on port 8080 remains a deliberate 501 stub.
### 2.3 Users
Provide email and profile claims for Authelia users. Automatic local account
creation and linking are not implemented yet. The developer integration must
define account provisioning and verify ownership before linking an existing
email/password account; matching an email string alone is not enough.
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:
```text
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.
---
@@ -139,73 +146,65 @@ for the public web URL before using these HTTPS settings; see
Apply environment changes from the repository root:
```sh
docker compose up -d
docker compose up -d --build
```
Open **Settings → OIDC** to confirm the three variables are set. With real
values it shows **Configured … Client integration is still pending**.
This is configuration confirmation, not a successful connection test.
values the login page enables **Sign in with Authelia**.
---
## 4. Developer handoff: complete local identity mapping
## 4. How the identity bridge works
NextAuth handles OIDC discovery, authorization, token exchange, and token
validation. The remaining integration must connect that verified identity to
the PostgreSQL users that Go authorizes.
validation. After validation, `web/auth.ts` signs a short-lived service token
(`typ=oidc-provision`) with `AUTH_SECRET` and calls the Go endpoint:
1. **Add trusted Go-backed identity lookup/provisioning.** No provisioning
endpoint is supplied yet. Any new endpoint must authenticate calls from
the trusted Next server, and accept only identities obtained after OIDC
verification. Define first-login account creation and an explicit policy
for linking existing accounts.
2. **Persist the external identity link.** Use the `User` and `Account` tables
in `db/schema.sql` to associate provider `authelia` and its verified subject
with a local `User.id`. Validate the configured issuer as part of the flow.
Returning users must resolve to the same local user.
3. **Update `web/auth.ts`.** Replace the unconditional Authelia rejection in
`callbacks.signIn` with the completed lookup/provisioning flow. Ensure the
JWT/session callbacks store the resolved local `User.id`, rather than the
OIDC profile's `sub`. `web/lib/api.ts` signs API assertions for the session
ID, and Go expects that ID to identify a real local user.
4. **Enable the login readiness gate.** Update `oidcReady` in
`web/app/login/client.tsx` only after identity mapping works. Retain the
configuration check for the three OIDC variables.
5. **Rebuild and verify.** Run `docker compose up -d --build`, then perform
the checks in section 5.
```text
POST /api/auth/oidc/identity
```
Keep the authorization-code callback on Next.js. Completing this integration
does not require turning Go's placeholder login/callback routes into another
OIDC client. Simply enabling the button or accepting `sub` as the local user
ID will not make authenticated Go data access work.
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`).
## 5. Verify the completed integration
Resolution policy:
Before implementing the handoff, you can verify configuration and discovery:
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. Confirm email/password login remains usable while integration is pending.
After the developer integration is complete:
1. Sign out, click **Sign in with Authelia**, and authenticate with Authelia.
2. Confirm the browser returns through the NextAuth callback to `/pages`.
3. Check `/api/me` through the web app and save a bookmark to confirm the
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.
4. Sign out and back in to verify the same user and data are retained.
5. Test a new Authelia user, an explicitly linked existing account, and two
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 |
|---|---|
| Variables are set, but button is disabled | Expected in the current build: `oidcReady` remains false until section 4 is implemented |
| Config still says Not connected | One of the variables is empty or a placeholder, or containers were not recreated after editing `.env` |
| NextAuth returns AccessDenied | The current `callbacks.signIn` deliberately rejects Authelia; after integration, investigate identity mapping |
| 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 |
@@ -214,8 +213,7 @@ After the developer integration is complete:
## 7. Optional: Authelia-only login
Once the completed integration has been verified, decide whether to keep
email/password login as a fallback. An Authelia-only deployment requires
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
+3 -3
View File
@@ -1,12 +1,12 @@
/**
* Authelia OIDC configuration (STUB-AWARE).
* Authelia OIDC configuration.
*
* Authelia sign-in is only enabled when all three env vars hold real values:
* Authelia sign-in is enabled when all three env vars hold real values:
* OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET
*
* Empty values or obvious placeholders (REPLACE_ME, example.com, changeme, ...)
* are treated as "not connected": the Authelia provider is not registered,
* the login button is shown disabled, and email/password login keeps working.
* the login button is disabled, and email/password login keeps working.
*
* See docs/AUTHELIA.md for the full connection guide.
*/