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
+140
View File
@@ -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})
}
+39
View File
@@ -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"`
+263 -33
View File
@@ -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) }
+5 -1
View File
@@ -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 {
+144
View File
@@ -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)
}
}
+5
View File
@@ -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
+7 -3
View File
@@ -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