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
+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