From c432ff57e91f44d11433bed6c455320d8705da73 Mon Sep 17 00:00:00 2001 From: Andrew S Erwin Date: Thu, 22 Oct 2026 12:39:39 -0500 Subject: [PATCH] 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. --- .env.example | 3 +- API.md | 6 +- README.md | 61 +++--- RUNNING.md | 11 +- internal/auth/oidc_provision.go | 140 +++++++++++++ internal/authguard/handlers.go | 39 ++++ internal/db/users.go | 296 ++++++++++++++++++++++++--- internal/http/integration_test.go | 6 +- internal/http/oidc_provision_test.go | 144 +++++++++++++ internal/http/server.go | 5 + internal/oidc/provider.go | 10 +- web/app/(app)/settings/client.tsx | 2 +- web/app/login/client.tsx | 9 +- web/auth.ts | 84 +++++++- web/docs/AUTHELIA.md | 124 ++++++----- web/lib/oidc-config.ts | 6 +- 16 files changed, 796 insertions(+), 150 deletions(-) create mode 100644 internal/auth/oidc_provision.go create mode 100644 internal/http/oidc_provision_test.go diff --git a/.env.example b/.env.example index 62144b3..2b4197b 100644 --- a/.env.example +++ b/.env.example @@ -36,7 +36,8 @@ POSTGRES_VOLUME_EXTERNAL=false # every mutating request fail with 403 "Invalid request origin". #APP_HOST_PORT=8080 #WEB_HOST_PORT=3000 -# Client-owned Authelia integration remains stubbed until connected. +# Authelia OIDC sign-in is enabled when all three values hold real values. +# The Next server owns the OIDC flow; Go provisions the local user. OIDC_ISSUER=REPLACE_ME OIDC_CLIENT_ID=REPLACE_ME OIDC_CLIENT_SECRET=REPLACE_ME diff --git a/API.md b/API.md index b24f7cc..cf42551 100644 --- a/API.md +++ b/API.md @@ -24,6 +24,7 @@ capped (100 per bookmark/tag/collection share, 200 per shared date). | POST | `/api/auth/signout` | `{ok:true}` and expired cookie; same-origin `Origin` required when present | | GET | `/api/me` | `{user,effectiveUser,isAdmin,viewingAs}`; real and effective identities | | GET | `/api/auth/oidc/status` | `{enabled,issuerSet,clientIdSet,clientSecretSet}`; never includes secrets or the issuer URL | +| POST | `/api/auth/oidc/identity` | Server-to-server only: requires `typ=oidc-provision` bearer token; body `{issuer,subject,email,emailVerified,name,image}`; returns the local `{user,tokenVersion}` or **409** when an existing password account needs explicit linking | | GET | `/api/auth/oidc/login` | **501**, client-owned Authelia integration stub | | GET, POST | `/api/auth/callback/authelia` | **501**, client-owned callback stub | @@ -256,7 +257,10 @@ Always uses the real user, even while viewing another account. |---|---|---| | GET | `/api/admin/users` | Safe user projections with bookmark/page/tag counts; excludes `@example.com` test users | | PATCH | `/api/admin/users` | `{ok:true}` for `{userId,role:"USER"\|"ADMIN"}`; refuses self-demotion | +| POST | `/api/admin/oidc-link` | `{ok:true}` for `{userId,subject}`; explicitly links an existing local account to an Authelia subject; `409` when that subject is already linked elsewhere | | POST | `/api/admin/view-as` | `{ok:true}`; `{userId}` sets an eight-hour HttpOnly cookie, `{userId:null}` clears it | Route registration: `internal/http/server.go`. Only the client-owned OIDC -login/callback remain stubs; application data routes use PostgreSQL. +login/callback remain stubs; application data routes use PostgreSQL. The +trusted Next server exchanges verified Authelia identities at +`POST /api/auth/oidc/identity`; that route is not a browser session endpoint. diff --git a/README.md b/README.md index e30c712..650a4e5 100644 --- a/README.md +++ b/README.md @@ -151,11 +151,12 @@ install it); the index-backed page search depends on it. ### Connecting Authelia (OIDC) -**Authelia sign-in is currently stubbed. Connecting it requires both server -configuration and developer integration; setting environment variables alone -does not enable it.** Email/password sign-in works while that integration is -pending. The full [Authelia connection guide](web/docs/AUTHELIA.md) includes -the client registration example and the implementation handoff. +Authelia is the primary sign-in path when configured. The trusted Next.js +server handles the OIDC authorization-code flow, validates the ID token, and +then exchanges the verified identity for a local Go user. Email/password +sign-in remains available as a fallback. The full +[Authelia connection guide](web/docs/AUTHELIA.md) includes the client +registration example and the identity-mapping details. #### 1. Register the app in Authelia @@ -187,30 +188,35 @@ OIDC_CLIENT_SECRET= Serve the web app through an HTTPS reverse proxy; the default Docker ports bind to localhost. Keep your existing `AUTH_SECRET` unchanged. Apply the -environment changes with `docker compose up -d`, then check **Settings → OIDC**. -It will report that the variables are configured but integration is pending. -The login button remains disabled at this stage. +environment changes with `docker compose up -d --build`, then check +**Settings → OIDC**. When all three variables hold real values, the Authelia +button is enabled. -#### 3. Complete the developer integration +#### 3. How identity mapping works -The trusted Next.js server owns OIDC verification and the callback. The -remaining work is to: +The Next server owns OIDC verification and the callback. After Authelia returns +a verified identity, NextAuth's `jwt` callback calls the Go API's +`POST /api/auth/oidc/identity` endpoint with a short-lived service token +(`typ=oidc-provision`). Go resolves the OIDC subject to a local `User` through +the `Account` table: -1. Implement Go-backed lookup/provisioning of a local `User` and `Account` - for the verified Authelia identity. A provisioning endpoint is not yet - supplied; any new endpoint must authenticate the trusted Next server. -2. Update `web/auth.ts` to resolve the verified identity to the local - `User.id` and permit sign-in only after that succeeds. The session and - API assertion must use this local ID, not Authelia's `sub` claim. Existing - accounts need an explicit, verified account-linking policy. -3. Enable the readiness gate in `web/app/login/client.tsx` after mapping works, - rebuild with `docker compose up -d --build`, and verify sign-in, first-login - provisioning, returning users, and Go-backed data access. +- An existing provider link is authoritative. +- A matching local account with no password may be linked when Authelia asserts + a verified email. +- A matching local **password** account returns `409 Account link required`. + Email alone is not proof of identity; an administrator links it explicitly + with `POST /api/admin/oidc-link` (`{userId,subject}`). +- 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 Go OIDC login/callback handlers in `internal/oidc/provider.go` deliberately -return **501**. They are not the NextAuth callback implementation. Config status -(including an `enabled` flag) indicates that values are present, not that an -end-to-end login has been implemented. +The NextAuth session and every API assertion use the **local** `User.id`, never +Authelia's `sub` claim. A Go `tokenVersion` bump on sign-out revokes both the +NextAuth-backed assertions and Go cookie sessions. + +The Go OIDC login/callback handlers in `internal/oidc/provider.go` remain 501 +stubs. They are not the NextAuth callback implementation; the Next server drives +the flow. Config status (including an `enabled` flag) indicates that values are +present, not that Go itself runs an OIDC client. ## Developer commands @@ -307,8 +313,9 @@ separate accounts. Current integration boundaries: -- Authelia still requires the developer identity-mapping work described above; - use email/password for this test build. +- Authelia is the primary sign-in path when configured; email/password remains + a fallback. Existing password accounts require explicit linking to an + Authelia identity. - IMAP and Nextcloud require the client's own service credentials. - Alerts are browser-only and checked every five minutes while the app is open. - Page autosave needs an API connection. Check the save indicator; use **Save diff --git a/RUNNING.md b/RUNNING.md index 1430a15..8fda45c 100644 --- a/RUNNING.md +++ b/RUNNING.md @@ -74,7 +74,9 @@ POSTGRES_VOLUME_EXTERNAL=false The supplied `POSTGRES_PASSWORD=superbrain` works with the bundled database. If you choose a different password, set it before the first startup; use a random hexadecimal value to avoid special characters in the connection URL. -Keep the `OIDC_*` placeholders as supplied: use email/password login for now. +Keep the `OIDC_*` placeholders as supplied for email/password login. To use +Authelia instead, fill in the real OIDC values and follow +[web/docs/AUTHELIA.md](web/docs/AUTHELIA.md). Keep `.env` for future starts and upgrades. It is ignored by Git. **Keep `AUTH_SECRET` unchanged:** changing it invalidates sessions, and — unless a @@ -250,9 +252,10 @@ The core app works without any external services. synced contact with a bookmark. - **Browser alerts:** Allow notifications when prompted. Alert checks run while the app is open in your browser. -- **Authelia:** This integration is intentionally unfinished. Setting OIDC - environment variables alone does not enable sign-in. See - [web/docs/AUTHELIA.md](web/docs/AUTHELIA.md) for integration details. +- **Authelia:** OIDC sign-in is enabled when all three `OIDC_*` variables hold + real values. The Next server validates the identity and Go provisions the + local user. See [web/docs/AUTHELIA.md](web/docs/AUTHELIA.md) for client + registration and account-linking details. ## Troubleshooting diff --git a/internal/auth/oidc_provision.go b/internal/auth/oidc_provision.go new file mode 100644 index 0000000..229d4b1 --- /dev/null +++ b/internal/auth/oidc_provision.go @@ -0,0 +1,140 @@ +package auth + +import ( + "encoding/json" + "errors" + "net/http" + "strings" + "time" + + "github.com/andrew/superbrain/internal/config" + "github.com/andrew/superbrain/internal/db" + "github.com/golang-jwt/jwt/v5" +) + +// TokenTypeOIDCProvision identifies the short-lived service credential the +// Next server presents when exchanging a verified Authelia identity for a +// local user. It is deliberately distinct from "assertion": ReadSession only +// accepts "assertion" on the Bearer channel and "session" on the cookie +// channel, so a provisioning token can never be replayed as a user session. +const ( + TokenTypeOIDCProvision = "oidc-provision" + oidcProvisionAudience = "superbrain-api" + maxOIDCProvisionLifetime = 120 * time.Second + maxOIDCProvisionSubject = 255 + maxOIDCProvisionImageLen = 2048 + maxOIDCProvisionBodyBytes = 16 << 10 +) + +// ServiceClaims is the payload of the Next-to-Go OIDC provisioning token. +type ServiceClaims struct { + Type string `json:"typ,omitempty"` + jwt.RegisteredClaims +} + +// VerifyServiceToken validates the provisioning token's signature, issuer, +// audience, expiry and type. The Next server signs with AUTH_SECRET (the same +// secret Go uses for sessions) and a 60-second lifetime; this caps it at two +// minutes to bound replay if a token leaks. +func VerifyServiceToken(token, secret string) error { + if secret == "" { + return errors.New("auth: empty service secret") + } + claims := &ServiceClaims{} + tok, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (interface{}, error) { + return []byte(secret), nil + }, + jwt.WithValidMethods([]string{"HS256"}), + jwt.WithIssuer("superbrain"), + jwt.WithAudience(oidcProvisionAudience), + jwt.WithExpirationRequired(), + jwt.WithLeeway(5*time.Second), + ) + if err != nil { + return err + } + if !tok.Valid || claims.Type != TokenTypeOIDCProvision { + return errors.New("auth: invalid service token") + } + if claims.IssuedAt == nil || claims.ExpiresAt == nil { + return errors.New("auth: service token missing timestamps") + } + if claims.ExpiresAt.Sub(claims.IssuedAt.Time) > maxOIDCProvisionLifetime { + return errors.New("auth: service token lifetime too long") + } + return nil +} + +type oidcIdentityRequest struct { + Issuer string `json:"issuer"` + Subject string `json:"subject"` + Email string `json:"email"` + EmailVerified bool `json:"emailVerified"` + Name string `json:"name"` + Image string `json:"image"` +} + +// HandleOIDCIdentity resolves a verified Authelia identity to a local Go user. +// It is server-to-server only: the caller must present the short-lived +// oidc-provision service token. The response contains the LOCAL user id and +// tokenVersion; the OIDC subject is never used as a User.id. +// +// POST /api/auth/oidc/identity +func HandleOIDCIdentity(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + if r.Method != http.MethodPost { + failure(w, http.StatusMethodNotAllowed, "Use POST") + return + } + header := r.Header.Get("Authorization") + if !strings.HasPrefix(header, "Bearer ") || VerifyServiceToken(strings.TrimPrefix(header, "Bearer "), config.Load().Secret()) != nil { + failure(w, http.StatusUnauthorized, "Unauthorized") + return + } + r.Body = http.MaxBytesReader(w, r.Body, maxOIDCProvisionBodyBytes) + var req oidcIdentityRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + failure(w, http.StatusRequestEntityTooLarge, "Request body too large") + return + } + failure(w, http.StatusBadRequest, "Invalid JSON") + return + } + req.Issuer = strings.TrimSpace(req.Issuer) + req.Subject = strings.TrimSpace(req.Subject) + req.Email = strings.ToLower(strings.TrimSpace(req.Email)) + req.Name = strings.TrimSpace(req.Name) + req.Image = strings.TrimSpace(req.Image) + if req.Subject == "" || req.Email == "" { + failure(w, http.StatusBadRequest, "Subject and email are required") + return + } + if len(req.Subject) > maxOIDCProvisionSubject || len(req.Email) > maxSignupEmailLen || len([]rune(req.Name)) > maxSignupNameLen || len(req.Image) > maxOIDCProvisionImageLen { + failure(w, http.StatusBadRequest, "Invalid identity") + return + } + configured := strings.TrimRight(strings.TrimSpace(config.Load().OIDCIssuer), "/") + if configured == "" || strings.TrimRight(req.Issuer, "/") != configured { + failure(w, http.StatusBadRequest, "Unknown issuer") + return + } + u, err := db.NewUserRepo(db.FromContext(r.Context())).ProvisionExternal(r.Context(), db.ExternalUserInput{ + Provider: "authelia", + ProviderAccountID: req.Subject, + Email: req.Email, + EmailVerified: req.EmailVerified, + Name: req.Name, + Image: req.Image, + }) + if errors.Is(err, db.ErrLinkRequired) { + failure(w, http.StatusConflict, "Account link required") + return + } + if err != nil { + failure(w, http.StatusInternalServerError, "Unable to resolve identity") + return + } + writeJSON(w, http.StatusOK, map[string]any{"user": identity(u), "tokenVersion": u.TokenVersion}) +} diff --git a/internal/authguard/handlers.go b/internal/authguard/handlers.go index 5ed5d9f..87bfe5f 100644 --- a/internal/authguard/handlers.go +++ b/internal/authguard/handlers.go @@ -10,6 +10,7 @@ import ( "github.com/andrew/superbrain/internal/handlers" "log" "net/http" + "strings" "time" ) @@ -97,6 +98,44 @@ func HandleAdminPatchUser(w http.ResponseWriter, r *http.Request) { log.Printf("audit: admin %s changed role of %s: %s -> %s", s.RealID, b.UserID, target.Role, b.Role) handlers.WriteJSON(w, 200, handlers.OK{OK: true}) } + +// HandleAdminLinkOIDC explicitly links an existing local account to an +// Authelia subject. This is the operator escape hatch for an account that +// already has a password: the provisioning bridge deliberately refuses to +// auto-link those by email alone. +func HandleAdminLinkOIDC(w http.ResponseWriter, r *http.Request) { + var b struct { + UserID string `json:"userId"` + Subject string `json:"subject"` + } + if json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&b) != nil { + handlers.WriteJSON(w, 400, handlers.Error{Error: "Invalid JSON"}) + return + } + b.UserID = strings.TrimSpace(b.UserID) + b.Subject = strings.TrimSpace(b.Subject) + if b.UserID == "" || b.Subject == "" || len(b.Subject) > 255 { + handlers.WriteJSON(w, 400, handlers.Error{Error: "Invalid link"}) + return + } + s, _ := auth.SessionFromContext(r.Context()) + e := db.NewUserRepo(db.FromContext(r.Context())).LinkExternal(r.Context(), b.UserID, "authelia", b.Subject) + if errors.Is(e, db.ErrNotFound) { + handlers.WriteJSON(w, 404, handlers.Error{Error: "Not found"}) + return + } + if errors.Is(e, db.ErrAccountLinked) { + handlers.WriteJSON(w, 409, handlers.Error{Error: "Subject already linked"}) + return + } + if e != nil { + handlers.WriteJSON(w, 500, handlers.Error{Error: "Unable to link account"}) + return + } + log.Printf("audit: admin %s linked authelia subject to user %s", s.RealID, b.UserID) + handlers.WriteJSON(w, 200, handlers.OK{OK: true}) +} + func HandleAdminViewAs(w http.ResponseWriter, r *http.Request) { var b struct { UserID *string `json:"userId"` diff --git a/internal/db/users.go b/internal/db/users.go index dc55042..c15d972 100644 --- a/internal/db/users.go +++ b/internal/db/users.go @@ -4,19 +4,28 @@ import ( "context" "database/sql" "encoding/json" + "errors" + "strings" + "time" + "github.com/andrew/superbrain/internal/config" "github.com/andrew/superbrain/internal/models" ) type UserRepo struct{ db *DB } +// ErrLinkRequired means an external identity matches an existing local +// password account but has not been explicitly linked. Callers must return a +// conflict instead of silently taking over the account. +var ErrLinkRequired = errors.New("account link required") + func NewUserRepo(d *DB) *UserRepo { return &UserRepo{d} } -func (r *UserRepo) find(ctx context.Context, field, value string) (*models.User, error) { - o, err := One(ctx, r.db, `SELECT to_jsonb(u) FROM "User" u WHERE `+Quote(field)+`=$1`, value) + +func userFromObject(o Object) (*models.User, error) { + raw, err := json.Marshal(o) if err != nil { return nil, err } - raw, _ := json.Marshal(o) var row struct { ID string `json:"id"` Name *string `json:"name"` @@ -32,12 +41,31 @@ func (r *UserRepo) find(ctx context.Context, field, value string) (*models.User, } return &models.User{ID: row.ID, Name: row.Name, Email: row.Email, EmailVerified: row.EmailVerified, Image: row.Image, Password: row.Password, Role: row.Role, TokenVersion: row.TokenVersion}, nil } + +func findUser(ctx context.Context, q Queryer, field, value string) (*models.User, error) { + o, err := One(ctx, q, `SELECT to_jsonb(u) FROM "User" u WHERE `+Quote(field)+`=$1`, value) + if err != nil { + return nil, err + } + return userFromObject(o) +} + +func (r *UserRepo) find(ctx context.Context, field, value string) (*models.User, error) { + return findUser(ctx, r.db, field, value) +} func (r *UserRepo) FindByEmail(ctx context.Context, e string) (*models.User, error) { return r.find(ctx, "email", e) } func (r *UserRepo) FindByID(ctx context.Context, id string) (*models.User, error) { return r.find(ctx, "id", id) } +func (r *UserRepo) FindByAccount(ctx context.Context, provider, providerAccountID string) (*models.User, error) { + o, err := One(ctx, r.db, `SELECT to_jsonb(u) FROM "Account" a JOIN "User" u ON u.id=a."userId" WHERE a.provider=$1 AND a."providerAccountId"=$2`, provider, providerAccountID) + if err != nil { + return nil, err + } + return userFromObject(o) +} func (r *UserRepo) SetRole(ctx context.Context, id, role string) error { _, err := r.db.ExecContext(ctx, `UPDATE "User" SET role=$1,"updatedAt"=now() WHERE id=$2`, role, id) return err @@ -49,7 +77,71 @@ func (r *UserRepo) BumpTokenVersion(ctx context.Context, id string) error { return err } -type NewUserInput struct{ ID, Name, Email, Password, Role string } +type NewUserInput struct { + ID, Name, Email, Password, Role string + EmailVerified *string + Image *string + // External users have no local password. The bootstrap logic still applies + // to the first external user on a fresh installation. + External bool +} + +// createUserTx performs the shared bootstrap decision and inserts the row. +// The caller owns the transaction and the advisory lock; keeping this separate +// lets signup and external provisioning use exactly the same first-admin rules. +func createUserTx(ctx context.Context, tx *sql.Tx, u *NewUserInput) (string, error) { + if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(927438)`); err != nil { + return "", err + } + var bootstrapDone bool + if err := tx.QueryRowContext(ctx, `SELECT COALESCE((SELECT value->>'completed' FROM "AppSetting" WHERE key='adminBootstrap'),'false')::boolean`).Scan(&bootstrapDone); err != nil { + return "", err + } + var admins int + if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM "User" WHERE role='ADMIN' AND COALESCE(email,'') NOT LIKE '%@example.com'`).Scan(&admins); err != nil { + return "", err + } + role := u.Role + if role == "" { + role = "USER" + } + promote := config.AllowBootstrapSignup() && !bootstrapDone && admins == 0 && len(config.AdminEmails()) == 0 && !isTestEmail(u.Email) && role == "USER" + if promote { + role = "ADMIN" + } + // Record bootstrap completion as soon as the installation has (or was + // just given) a real administrator. A test-address signup with no + // admins present never claims the bootstrap. + if !bootstrapDone && (role == "ADMIN" || admins > 0) { + if _, err := tx.ExecContext(ctx, `INSERT INTO "AppSetting"(key,value) VALUES('adminBootstrap',jsonb_build_object('completed',true)) ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value,"updatedAt"=now()`); err != nil { + return "", err + } + } + var password any + if u.External { + password = nil + } else { + password = u.Password + } + var emailVerified any + if u.EmailVerified != nil { + emailVerified = *u.EmailVerified + } + var image any + if u.Image != nil { + image = *u.Image + } + _, err := Insert(ctx, tx, "User", Object{ + "id": u.ID, + "name": u.Name, + "email": u.Email, + "password": password, + "role": role, + "emailVerified": emailVerified, + "image": image, + }) + return u.ID, err +} // A transaction-scoped lock serializes first-admin selection with signup. // @@ -61,37 +153,175 @@ type NewUserInput struct{ ID, Name, Email, Password, Role string } // (ADMIN_EMAILS + make seed, or promotion by an existing admin). func (r *UserRepo) Create(ctx context.Context, u *NewUserInput) (string, error) { err := Transaction(ctx, r.db, func(tx *sql.Tx) error { - if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(927438)`); err != nil { - return err - } - var bootstrapDone bool - if err := tx.QueryRowContext(ctx, `SELECT COALESCE((SELECT value->>'completed' FROM "AppSetting" WHERE key='adminBootstrap'),'false')::boolean`).Scan(&bootstrapDone); err != nil { - return err - } - var admins int - if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM "User" WHERE role='ADMIN' AND COALESCE(email,'') NOT LIKE '%@example.com'`).Scan(&admins); err != nil { - return err - } - role := u.Role - if role == "" { - role = "USER" - } - promote := config.AllowBootstrapSignup() && !bootstrapDone && admins == 0 && len(config.AdminEmails()) == 0 && !isTestEmail(u.Email) && role == "USER" - if promote { - role = "ADMIN" - } - // Record bootstrap completion as soon as the installation has (or was - // just given) a real administrator. A test-address signup with no - // admins present never claims the bootstrap. - if !bootstrapDone && (role == "ADMIN" || admins > 0) { - if _, err := tx.ExecContext(ctx, `INSERT INTO "AppSetting"(key,value) VALUES('adminBootstrap',jsonb_build_object('completed',true)) ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value,"updatedAt"=now()`); err != nil { - return err - } - } - _, err := Insert(ctx, tx, "User", Object{"id": u.ID, "name": u.Name, "email": u.Email, "password": u.Password, "role": role}) - return err + _, e := createUserTx(ctx, tx, u) + return e }) return u.ID, err } + +// ExternalUserInput is the verified profile returned by the OIDC bridge. +// ProviderAccountID is the OIDC subject; it is only ever used to find the +// local account link, never as the local User.id. +type ExternalUserInput struct { + Provider string + ProviderAccountID string + Email string + EmailVerified bool + Name string + Image string +} + +func insertAccountTx(ctx context.Context, tx *sql.Tx, userID string, in ExternalUserInput) error { + _, err := Insert(ctx, tx, "Account", Object{ + "id": NewID(), + "userId": userID, + "type": "oidc", + "provider": in.Provider, + "providerAccountId": in.ProviderAccountID, + }) + return err +} + +// ErrAccountLinked means the external subject is already linked to a +// different local user; an operator must unlink it deliberately first. +var ErrAccountLinked = errors.New("account already linked") + +func (r *UserRepo) LinkExternal(ctx context.Context, userID, provider, subject string) error { + return Transaction(ctx, r.db, func(tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, provider+":"+subject); err != nil { + return err + } + if _, err := findUser(ctx, tx, "id", userID); err != nil { + return err + } + var existing string + err := tx.QueryRowContext(ctx, `SELECT "userId" FROM "Account" WHERE provider=$1 AND "providerAccountId"=$2`, provider, subject).Scan(&existing) + if err == nil { + if existing == userID { + return nil + } + return ErrAccountLinked + } + if !errors.Is(err, sql.ErrNoRows) { + return err + } + _, err = Insert(ctx, tx, "Account", Object{ + "id": NewID(), + "userId": userID, + "type": "oidc", + "provider": provider, + "providerAccountId": subject, + }) + return err + }) +} + +// ProvisionExternal resolves an OIDC identity to a local user. The advisory +// lock is keyed by provider+subject so concurrent first logins cannot create +// duplicate accounts. Linking policy is deliberately conservative: +// +// - an existing Account link is authoritative; +// - a matching local account with no password may be linked only when the +// IdP asserts a verified email; +// - a matching local password account returns ErrLinkRequired (409) and must +// be linked explicitly by an operator; email alone is not proof of identity. +func (r *UserRepo) ProvisionExternal(ctx context.Context, in ExternalUserInput) (*models.User, error) { + var out *models.User + err := Transaction(ctx, r.db, func(tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, in.Provider+":"+in.ProviderAccountID); err != nil { + return err + } + // 1. Existing provider link is authoritative. + o, err := One(ctx, tx, `SELECT to_jsonb(u) FROM "Account" a JOIN "User" u ON u.id=a."userId" WHERE a.provider=$1 AND a."providerAccountId"=$2`, in.Provider, in.ProviderAccountID) + if err == nil { + u, err := userFromObject(o) + if err != nil { + return err + } + if in.EmailVerified && u.EmailVerified == nil { + if _, err := tx.ExecContext(ctx, `UPDATE "User" SET "emailVerified"=now(),"updatedAt"=now() WHERE id=$1`, u.ID); err != nil { + return err + } + now := time.Now().UTC().Format(time.RFC3339) + u.EmailVerified = &now + } + out = u + return nil + } + if !errors.Is(err, ErrNotFound) { + return err + } + + // 2. Existing local account with the same email. + if in.Email != "" { + o, err := One(ctx, tx, `SELECT to_jsonb(u) FROM "User" u WHERE email=$1`, in.Email) + if err == nil { + u, err := userFromObject(o) + if err != nil { + return err + } + if u.Password != nil && *u.Password != "" { + return ErrLinkRequired + } + if !in.EmailVerified { + return ErrLinkRequired + } + if err := insertAccountTx(ctx, tx, u.ID, in); err != nil { + return err + } + if u.EmailVerified == nil { + if _, err := tx.ExecContext(ctx, `UPDATE "User" SET "emailVerified"=now(),"updatedAt"=now() WHERE id=$1`, u.ID); err != nil { + return err + } + now := time.Now().UTC().Format(time.RFC3339) + u.EmailVerified = &now + } + out = u + return nil + } + if !errors.Is(err, ErrNotFound) { + return err + } + } + + // 3. New external user. Name falls back to the email local part. + id := NewID() + name := strings.TrimSpace(in.Name) + if name == "" { + name = strings.SplitN(in.Email, "@", 2)[0] + } + var verified *string + if in.EmailVerified { + now := time.Now().UTC().Format(time.RFC3339) + verified = &now + } + var image *string + if in.Image != "" { + img := in.Image + image = &img + } + if _, err := createUserTx(ctx, tx, &NewUserInput{ + ID: id, + Name: name, + Email: in.Email, + Role: "USER", + EmailVerified: verified, + Image: image, + External: true, + }); err != nil { + return err + } + if err := insertAccountTx(ctx, tx, id, in); err != nil { + return err + } + u, err := findUser(ctx, tx, "id", id) + if err != nil { + return err + } + out = u + return nil + }) + return out, err +} func isTestEmail(e string) bool { return len(e) >= 12 && e[len(e)-12:] == "@example.com" } func IsAdminEmail(email string) bool { return config.IsAdminEmail(email) } diff --git a/internal/http/integration_test.go b/internal/http/integration_test.go index 4e2be45..1cda8e1 100644 --- a/internal/http/integration_test.go +++ b/internal/http/integration_test.go @@ -55,7 +55,11 @@ func testServerDB(t *testing.T) (*httptest.Server, *db.DB) { t.Fatal(e) } q := u.Query() - q.Set("search_path", schema) + // The pg_trgm extension is installed in public by the database init + // script. The test schema owns the app tables, but PostgreSQL must also + // see public to resolve gin_trgm_ops when schema.sql builds the trigram + // indexes. Test schemas still take precedence for every app table. + q.Set("search_path", schema+",public") u.RawQuery = q.Encode() d, e := db.New(&config.Config{DatabaseURL: u.String()}) if e != nil { diff --git a/internal/http/oidc_provision_test.go b/internal/http/oidc_provision_test.go new file mode 100644 index 0000000..74a1525 --- /dev/null +++ b/internal/http/oidc_provision_test.go @@ -0,0 +1,144 @@ +package http + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "os" + "testing" + "time" + + "github.com/andrew/superbrain/internal/db" + "github.com/golang-jwt/jwt/v5" +) + +func oidcServiceToken(t *testing.T, typ string, expires time.Time) string { + t.Helper() + claims := jwt.MapClaims{ + "typ": typ, + "iss": "superbrain", + "aud": "superbrain-api", + "iat": time.Now().Add(-time.Minute).Unix(), + "exp": expires.Unix(), + } + tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + signed, err := tok.SignedString([]byte(os.Getenv("NEXTAUTH_SECRET"))) + if err != nil { + t.Fatal(err) + } + return signed +} + +func postOIDCIdentity(t *testing.T, url, token string, body map[string]any) (int, map[string]any) { + t.Helper() + raw, _ := json.Marshal(body) + req, err := http.NewRequest(http.MethodPost, url+"/api/auth/oidc/identity", bytes.NewReader(raw)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + out, _ := io.ReadAll(res.Body) + var decoded map[string]any + _ = json.Unmarshal(out, &decoded) + return res.StatusCode, decoded +} + +func TestOIDCIdentityProvisioning(t *testing.T) { + t.Setenv("OIDC_ISSUER", "https://auth.test") + t.Setenv("ALLOW_BOOTSTRAP_SIGNUP", "1") + srv, database := testServerDB(t) + + // A browser/session token must never authenticate this endpoint. + if status, _ := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "assertion", time.Now().Add(time.Minute)), map[string]any{ + "issuer": "https://auth.test", "subject": "sub-a", "email": "a@example.test", "emailVerified": true, + }); status != http.StatusUnauthorized { + t.Fatalf("assertion token: wanted 401, got %d", status) + } + // An expired provisioning token is rejected. + if status, _ := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(-time.Minute)), map[string]any{ + "issuer": "https://auth.test", "subject": "sub-a", "email": "a@example.test", "emailVerified": true, + }); status != http.StatusUnauthorized { + t.Fatalf("expired token: wanted 401, got %d", status) + } + + token := oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)) + // Issuer must match the configured value. + if status, _ := postOIDCIdentity(t, srv.URL, token, map[string]any{ + "issuer": "https://other.test", "subject": "sub-a", "email": "a@example.test", "emailVerified": true, + }); status != http.StatusBadRequest { + t.Fatalf("unknown issuer: wanted 400, got %d", status) + } + + body := map[string]any{ + "issuer": "https://auth.test", "subject": "sub-a", "email": "a@example.test", + "emailVerified": true, "name": "Alice", "image": "https://img.test/a.png", + } + status, created := postOIDCIdentity(t, srv.URL, token, body) + if status != http.StatusOK { + t.Fatalf("new identity: wanted 200, got %d: %v", status, created) + } + user := created["user"].(map[string]any) + id := user["id"].(string) + if id == "" { + t.Fatal("new identity returned no local id") + } + if user["role"] != "ADMIN" { + t.Fatalf("first external user should bootstrap as ADMIN, got %v", user["role"]) + } + if created["tokenVersion"].(float64) < 1 { + t.Fatalf("missing tokenVersion: %v", created) + } + repo := db.NewUserRepo(database) + linked, err := repo.FindByAccount(context.Background(), "authelia", "sub-a") + if err != nil { + t.Fatal(err) + } + if linked.ID != id || linked.Password != nil || linked.EmailVerified == nil { + t.Fatalf("unexpected provisioned user: %+v", linked) + } + + // Returning identity resolves to the same local user, never a duplicate. + status, again := postOIDCIdentity(t, srv.URL, token, body) + if status != http.StatusOK { + t.Fatalf("returning identity: wanted 200, got %d: %v", status, again) + } + if again["user"].(map[string]any)["id"] != id { + t.Fatal("returning identity created a different local user") + } + + // A matching local password account is not auto-linked by email. + localID, err := repo.Create(context.Background(), &db.NewUserInput{ + ID: db.NewID(), Name: "Local", Email: "password@example.test", Password: "hash", Role: "USER", + }) + if err != nil { + t.Fatal(err) + } + status, _ = postOIDCIdentity(t, srv.URL, token, map[string]any{ + "issuer": "https://auth.test", "subject": "sub-password", "email": "password@example.test", "emailVerified": true, + }) + if status != http.StatusConflict { + t.Fatalf("password account: wanted 409, got %d", status) + } + + // An operator can link that account explicitly; the same subject then + // resolves to it without creating a duplicate. + if err := repo.LinkExternal(context.Background(), localID, "authelia", "sub-password"); err != nil { + t.Fatal(err) + } + status, linkedAgain := postOIDCIdentity(t, srv.URL, token, map[string]any{ + "issuer": "https://auth.test", "subject": "sub-password", "email": "password@example.test", "emailVerified": true, + }) + if status != http.StatusOK || linkedAgain["user"].(map[string]any)["id"] != localID { + t.Fatalf("explicit link: wanted local user %s, got %d %v", localID, status, linkedAgain) + } +} diff --git a/internal/http/server.go b/internal/http/server.go index 82af08a..58b6ec3 100644 --- a/internal/http/server.go +++ b/internal/http/server.go @@ -48,12 +48,17 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server { // Authelia OIDC (stub-aware; the client drives the flow via NextAuth) mux.HandleFunc("GET /api/auth/oidc/status", oidc.HandleStatus) mux.HandleFunc("GET /api/auth/oidc/login", oidc.HandleLogin) + // The Next server exchanges a verified Authelia identity for a local user + // here. This is server-to-server only and requires the oidc-provision + // service token; the OIDC subject is never used as a local User.id. + mux.HandleFunc("POST /api/auth/oidc/identity", auth.HandleOIDCIdentity) mux.HandleFunc("GET /api/auth/callback/authelia", oidc.HandleCallback) mux.HandleFunc("POST /api/auth/callback/authelia", oidc.HandleCallback) // 4.2 Admin (use real user; 403 unless ADMIN) mux.HandleFunc("GET /api/admin/users", admin(authguard.HandleAdminListUsers)) mux.HandleFunc("PATCH /api/admin/users", admin(authguard.HandleAdminPatchUser)) + mux.HandleFunc("POST /api/admin/oidc-link", admin(authguard.HandleAdminLinkOIDC)) mux.HandleFunc("POST /api/admin/view-as", admin(authguard.HandleAdminViewAs)) // 4.3 Bookmarks diff --git a/internal/oidc/provider.go b/internal/oidc/provider.go index 9d54657..f8bfd93 100644 --- a/internal/oidc/provider.go +++ b/internal/oidc/provider.go @@ -1,11 +1,15 @@ package oidc -// Provider is the Authelia OIDC sign-in provider. +// Provider is the Authelia OIDC status/scaffold package. // -// Porting guide 3.1: the Authelia provider is registered only when +// Porting guide 3.1: the Authelia provider is registered in NextAuth only when // getOidcStatus().enabled. Scope "openid profile email". Profile mapping: // id=sub, name = name ?? preferred_username ?? sub, email, image = picture. -// It links to an existing account with the same email. +// +// The browser OIDC code flow (authorization code exchange, token endpoint, +// userinfo) runs in the trusted Next.js server. These Go routes remain 501 +// stubs for compatibility; the actual local identity exchange lives in +// internal/auth/oidc_provision.go. Do not implement a second OIDC client here. // // STUB: the full OIDC code flow (authorization code exchange, token endpoint, // userinfo) is NOT implemented in Go — it will be driven by the client, which diff --git a/web/app/(app)/settings/client.tsx b/web/app/(app)/settings/client.tsx index 8638a88..e1ae8c9 100644 --- a/web/app/(app)/settings/client.tsx +++ b/web/app/(app)/settings/client.tsx @@ -180,7 +180,7 @@ export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callba {oidc.enabled ? : } {oidc.enabled - ? <>Configured for {oidc.issuer}. Client integration is still pending. + ? <>Configured for {oidc.issuer}. 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: docs/AUTHELIA.md} diff --git a/web/app/login/client.tsx b/web/app/login/client.tsx index 8d4b4a9..154cf59 100644 --- a/web/app/login/client.tsx +++ b/web/app/login/client.tsx @@ -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} > Sign in with Authelia - {(!oidcEnabled || !oidcReady) && ( + {!oidcEnabled && (

- Authelia single sign-on awaits client integration. Use email below. + Authelia single sign-on is not configured. Use email below.

)} diff --git a/web/auth.ts b/web/auth.ts index be0f52a..73b4284 100644 --- a/web/auth.ts +++ b/web/auth.ts @@ -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 }, }, diff --git a/web/docs/AUTHELIA.md b/web/docs/AUTHELIA.md index a5de64d..d04261f 100644 --- a/web/docs/AUTHELIA.md +++ b/web/docs/AUTHELIA.md @@ -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": "", "subject": "" } +``` + +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 `/.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 diff --git a/web/lib/oidc-config.ts b/web/lib/oidc-config.ts index 0f5aa29..8fe9153 100644 --- a/web/lib/oidc-config.ts +++ b/web/lib/oidc-config.ts @@ -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. */