Add deployment tiers, self-service password reset, and Authelia SSO fixes
release gate / check (push) Failing after 7m28s

Product tiers (decided 2026-10-26): TIER=core|multi is the deployment knob.
core (federated install, paying customers) derives AUTH_MODE=oidc with
signup/bootstrap off - Authelia is the only way in and accounts are
provisioned upstream (Superpanel -> LDAP -> Authelia). multi (hosted
self-service) derives AUTH_MODE=password: signup, password login and
SMTP-backed self-reset, with the OIDC bridge refused even when variables
are set. Explicit AUTH_MODE/SIGNUP_ENABLED/ALLOW_BOOTSTRAP_SIGNUP always
override the tier; invalid values fail startup instead of falling back.
Go enforces every gate at the API; the web UI mirrors it (conditional
credentials provider, SSO-only login page, signup/reset redirects).

Authelia-only bootstrap: ProvisionExternal grants ADMIN to ADMIN_EMAILS
addresses at first SSO login, and --seed accepts SEED_SUBJECT to link a
pre-existing password account offline - the only path when 409 'account
link required' meets a deployment where nobody can password-login to call
oidc-link.

Self-service password reset (multi tier): POST /api/password/forgot and
/api/password/reset with hashed single-use 30-minute tokens
(PasswordResetToken, migration 011 + schema.sql), enumeration-safe
identical 200s, per-IP rate limits, tokenVersion bump on success (all
prior sessions revoked), OIDC-only accounts excluded by design. New
internal/mailer sends via netguard+outbound budget; NETGUARD_TRUSTED_HOSTS
pins operator-chosen relays that resolve privately (split-horizon DNS)
without the blanket INTEGRATIONS_ALLOW_PRIVATE switch. Web gains
/forgot-password and /reset-password pages and a login-page link.

Federated install fixes: the Authelia client now registers a
claims_policy putting email in the ID token (production AccessDenied -
Auth.js builds OIDC profiles exclusively from ID-token claims), config is
validated before restarting the shared Authelia, uninstall removes the
claims block marker-safely, and generated .env switches to TIER=core with
a password-less admin seed.

Tests: tier derivation/override unit tests, mode and tier integration
tests (403 gates, bridge refusal, ADMIN_EMAILS promotion, offline link),
reset-flow integration tests against a loopback SMTP fake, netguard
trusted-host tests. Docs: RUNNING.md, web/docs/AUTHELIA.md section 7,
.env.example, STRATEGY.md.
This commit is contained in:
Andrew S Erwin
2026-10-26 12:28:43 -05:00
parent d7a2abc683
commit f372936894
33 changed files with 1879 additions and 64 deletions
+36
View File
@@ -19,6 +19,25 @@ ADMIN_EMAILS=
# Master switch for self-service registration (default enabled). Set to 0 on
# private instances where accounts are provisioned only by an operator.
#SIGNUP_ENABLED=0
# Product tier — the single deployment knob. Derives defaults for the
# mechanism-level variables below; an explicitly set variable always wins.
# core Authelia-only install for paying customers (federated suite):
# implies AUTH_MODE=oidc, SIGNUP_ENABLED off, bootstrap off;
# accounts are provisioned upstream (Superpanel -> LDAP -> Authelia).
# multi hosted self-service install: implies AUTH_MODE=password (signup +
# password login + self-service reset; configure SMTP_* below).
# Invalid values fail startup instead of falling back.
#TIER=core
# Authentication personality (overrides the TIER default when set):
# both (default) email/password login + signup AND Authelia OIDC
# password multi-tenant shape: email signup + password login only; OIDC is
# disabled even when the OIDC_* variables are set
# oidc core/federated shape: Authelia exclusively — password login,
# signup and password reset are refused; accounts are provisioned
# upstream (e.g. Superpanel -> LDAP -> Authelia -> SSO) and reach
# ADMIN via ADMIN_EMAILS on first SSO login. Invalid values fail
# startup instead of falling back.
#AUTH_MODE=both
# Trust the X-Real-IP header for rate-limit identity. Set to 1 ONLY when a
# proxy in front of the web container overwrites X-Real-IP with the real peer
# address (the bundled nginx template does; scripts/server-deploy.sh writes
@@ -41,6 +60,23 @@ POSTGRES_VOLUME_EXTERNAL=false
OIDC_ISSUER=REPLACE_ME
OIDC_CLIENT_ID=REPLACE_ME
OIDC_CLIENT_SECRET=REPLACE_ME
# SMTP relay for transactional mail (password-reset links). Unset SMTP_HOST
# or SMTP_FROM disables self-service reset: /api/password/forgot then answers
# 503 and the login page link leads to an explanatory dead end. Port 465
# uses implicit TLS; other ports use STARTTLS when advertised. A relay on a
# private network additionally needs INTEGRATIONS_ALLOW_PRIVATE=1 (netguard).
#SMTP_HOST=smtp.example.internal
#SMTP_PORT=587
#SMTP_USERNAME=
#SMTP_PASSWORD=
#SMTP_FROM=superbrain@example.tld
# Operator-pinned hostnames (comma-separated) whose DNS answers may be
# private addresses — for relays behind split-horizon DNS, e.g.
# NETGUARD_TRUSTED_HOSTS=mail.example.tld when the LAN resolver answers
# 192.168.x.x for it. Only the SMTP host is looked up against this list;
# previews, CardDAV and IMAP stay fully guarded. Never list a name a user
# can influence.
#NETGUARD_TRUSTED_HOSTS=
# --- Optional, not needed for the Compose stack ---
# Go API listen port (default 8080).
+19
View File
@@ -256,6 +256,25 @@ The core app works without any external services.
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.
- **Password-reset email (SMTP):** self-service "Forgot password" needs an
SMTP relay (applies to `AUTH_MODE=both`/`password`; in `oidc` mode the
reset endpoints are refused and Authelia owns recovery — see
[web/docs/AUTHELIA.md](web/docs/AUTHELIA.md) §7): set `SMTP_HOST`,
`SMTP_FROM` (and `SMTP_USERNAME`/`SMTP_PASSWORD`
when the relay requires AUTH) in `.env`. Port 465 uses implicit TLS; other
ports upgrade via STARTTLS when advertised. When the relay's hostname
resolves to a private address from the server (common with split-horizon
DNS for in-house relays), pin it with
`NETGUARD_TRUSTED_HOSTS=relay.example.tld` — the pin is only consulted for
the operator-set SMTP host, so user-driven dials (previews, CardDAV, IMAP)
stay fully guarded. The blanket `INTEGRATIONS_ALLOW_PRIVATE=1` also works
but relaxes every outbound dial; reserve it for deliberate LAN
deployments.
Without SMTP config the reset endpoints answer 503 and
password login still works normally. Reset links are single-use, valid for
30 minutes, and completing a reset signs out every existing session for
that account. OIDC-only (password-less) accounts never receive reset mail
by design — use Authelia's own recovery for those.
## Troubleshooting
+20
View File
@@ -0,0 +1,20 @@
-- 011_password_reset.sql — self-service password reset (token table).
--
-- Additive and idempotent: schema.sql already carries the identical table,
-- so this is a structural no-op on a fresh database and the only path that
-- creates it on an installed one (db-converge proves both land the same).
--
-- Tokens are random 256-bit values; only the SHA-256 hash is persisted, so
-- a database leak yields no working reset links. Rows are single-use
-- ("usedAt"), short-lived ("expiresAt"), and issuing a fresh token deletes
-- the user's previous ones (see internal/db/password_reset.go).
CREATE TABLE IF NOT EXISTS "PasswordResetToken" (
id text PRIMARY KEY,
"userId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"tokenHash" text NOT NULL UNIQUE,
"expiresAt" timestamptz NOT NULL,
"usedAt" timestamptz,
"createdAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS "PasswordResetToken_userId_idx" ON "PasswordResetToken"("userId");
+14
View File
@@ -59,6 +59,20 @@ CREATE TABLE "VerificationToken" (
UNIQUE(identifier, token)
);
-- 2.3b PasswordResetToken: single-use, hashed, short-lived password-reset
-- tokens (self-service "forgot password"). Only the SHA-256 hash of the
-- emailed token is stored; issuing a new token deletes the user's previous
-- ones and consuming one marks it used inside a row-locked transaction.
CREATE TABLE "PasswordResetToken" (
id text PRIMARY KEY,
"userId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"tokenHash" text NOT NULL UNIQUE,
"expiresAt" timestamptz NOT NULL,
"usedAt" timestamptz,
"createdAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "PasswordResetToken_userId_idx" ON "PasswordResetToken"("userId");
-- 2.4 Bookmark
CREATE TABLE "Bookmark" (
id text PRIMARY KEY,
+53 -15
View File
@@ -132,12 +132,30 @@ Written by `config_superbrain` into `/federated/apps/superbrain/.env`
AUTH_SECRET must not invalidate them**.
- `POSTGRES_PASSWORD` for the `superbrain` DB user.
- `ADMIN_EMAILS=admin@$DOMAIN`, `ALLOW_BOOTSTRAP_SIGNUP=0`,
`SIGNUP_ENABLED=0` (private instance; accounts provisioned by operator),
`COOKIE_SECURE=1`.
- Decision 2026-10-26 (supersedes the 2026-10-25 open-signup experiment):
deployments have a product **tier** — `TIER=core|multi` — which derives
the mechanism defaults (`AUTH_MODE`, `SIGNUP_ENABLED`,
`ALLOW_BOOTSTRAP_SIGNUP`); explicit variables override. The core install
is `TIER=core`: Authelia-only (`AUTH_MODE=oidc` derived), signup and
bootstrap off. Go refuses password login, signup and password reset at
the API (hiding the web UI is not the barrier); the identity bridge is
the only way in. Account creation happens upstream in Superpanel → LDAP
→ Authelia and materializes locally on first SSO login. The hosted
product is `TIER=multi`: `AUTH_MODE=password` derived (signup/login/
self-reset; OIDC bridge refused even with variables set) — SMTP-backed
password reset belongs to that tier (see RUNNING.md); core needs no SMTP
config. Longer term the multi tier is meant to grow ORGANIZATION-level
tenancy (tenant_id, memberships, per-tenant admin/billing) — decided
2026-10-26, not built yet; today it is multi-user.
- Admin bootstrap on the core tier: an `ADMIN_EMAILS` address becomes ADMIN
at first SSO login (`ProvisionExternal`); a fresh SSO user is USER.
- Operator account: `docker exec -e SEED_EMAIL=admin@$DOMAIN
-e SEED_PASSWORD="$ADMINPASS" superbrain-app /superbrain --seed` — verified
idempotent (no-op if the email exists) and grants ADMIN when the email is in
`ADMIN_EMAILS`.
superbrain-app /superbrain --seed` — password-less on purpose: a password
is unusable with login disabled and would block the SSO verified-email
auto-link (409). Idempotent; grants ADMIN via ADMIN_EMAILS. Pre-existing
password accounts (e.g. from before the mode switch) must be linked
offline: same command plus `-e SEED_SUBJECT=<authelia sub>`.
**Rate-limiting caveat (open item):** with `TRUSTED_PROXY=1` the web container
reads the client IP from `X-Real-IP` **only** — it deliberately ignores
@@ -153,12 +171,24 @@ Decide before cutover; (a) is safe to start with.
Follows the bookstack pattern in `lib/bookstack.sh`:
1. Append a client to `/federated/apps/authelia/data/config/idproviders.yml`:
`client_id: superbrain`, `consent_mode: implicit`,
`authorization_policy: one_factor`, scopes `openid profile email`,
`client_id: superbrain`, `claims_policy: superbrain`,
`consent_mode: implicit`, `authorization_policy: one_factor`, scopes
`openid profile email`,
`redirect_uris: [https://superbrain.$DOMAIN/api/auth/callback/authelia]`
(the NextAuth provider id is `authelia`), save a copy to
(the NextAuth provider id is `authelia`), plus a `claims_policies` entry
`superbrain: {id_token: [email, email_verified, name, preferred_username]}`
— without it Authelia keeps `email` out of the ID token (hit in production
2026-10-25: Auth.js builds the OIDC profile exclusively from ID-token
claims, the Go bridge answered 400 "Subject and email are required", and
every login ended in AccessDenied). Save a copy of the client block to
`/federated/apps/superbrain/.superbrain.oidc-client.yml` (chmod 600),
`restart_service authelia`.
validate with `docker exec authelia authelia validate-config --config
/config/configuration.yml --config /config/idproviders.yml
--config.experimental.filters template`, then `restart_service authelia`.
The uninstall path removes the claims block by its `### Superbrain claims`
marker (marker + exactly 2 lines), drops a then-empty `claims_policies:`
key, and must run BEFORE the client-block range deletion — that range
starts at the first `### Superbrain` match.
2. Append `OIDC_ISSUER=https://authelia.$DOMAIN`, `OIDC_CLIENT_ID=superbrain`,
`OIDC_CLIENT_SECRET=<create_password>` to the app `.env`, then
`docker compose up -d --force-recreate web` — **not** `restart_service`:
@@ -166,16 +196,24 @@ Follows the bookstack pattern in `lib/bookstack.sh`:
(hit in production 2026-10-25: web came up with zero OIDC vars and
NextAuth returned `error=Configuration`).
Verified end-to-end: in-container issuer discovery works through the
`extra_hosts` pin, and `/api/auth/signin/authelia` 302s to
Verified: in-container issuer discovery works through the `extra_hosts` pin,
`/api/auth/signin/authelia` 302s to
`https://authelia.$DOMAIN/api/oidc/authorization` with the exact registered
redirect URI, `openid profile email` and PKCE S256.
redirect URI, `openid profile email` and PKCE S256, and (after the claims
policy fix of 2026-10-25) the identity bridge receives `email` in the ID
token. Other house apps (gitea, bookstack, immich) never needed a claims
policy because they call the userinfo endpoint themselves; superbrain's
Auth.js flow does not.
Operator note (product invariant): SSO sign-in auto-provisions **new** users,
but existing password accounts require explicit linking via
`POST /api/admin/oidc-link` — email match alone is intentionally not proof.
Seed the admin with password first, then link, or let SSO provision and
promote via `ADMIN_EMAILS`.
but existing password accounts require explicit linking — email match alone
is intentionally not proof. In `AUTH_MODE=oidc` the admin API link
(`POST /api/admin/oidc-link`) needs a session nobody can obtain, so the
offline path is the seed CLI: `docker exec -e SEED_EMAIL=... -e SEED_SUBJECT=...
superbrain-app /superbrain --seed`. Standard flow on core: seed the admin
password-less (ADMIN via `ADMIN_EMAILS`), first SSO login links by verified
email; everyone else is provisioned by Superpanel → LDAP → Authelia and
auto-provisions on first login.
### mcpserver link: drop for now
+73 -9
View File
@@ -167,10 +167,23 @@ NEXTAUTH_URL=https://superbrain.$DOMAIN
AUTH_TRUST_HOST=true
API_BASE_URL=http://superbrain-app:8080
# --- Access policy (private instance: operator-provisioned accounts) ---
# --- Access policy ---
# Decision 2026-10-26: the core/federated install is the CORE TIER —
# TIER=core derives AUTH_MODE=oidc (Authelia only: Go refuses password
# login, signup and password reset at the API), signup off and bootstrap
# off; no explicit overrides are set here on purpose, so the tier defaults
# are the single source of truth. Accounts are provisioned upstream
# (Superpanel -> LDAP -> Authelia) and materialize locally on first SSO
# login. ADMIN_EMAILS makes a listed address ADMIN at first SSO login —
# the only bootstrap path in this tier. The operator account is seeded
# password-less; a pre-existing password account can be linked offline:
# docker exec -e SEED_EMAIL=... -e SEED_SUBJECT=... superbrain-app
# /superbrain --seed (needed because the SSO bridge refuses to auto-link
# password accounts by email alone). The hosted self-service product is
# the other tier: TIER=multi (AUTH_MODE=password, signup + SMTP-backed
# self-reset; see RUNNING.md).
ADMIN_EMAILS=admin@$DOMAIN
ALLOW_BOOTSTRAP_SIGNUP=0
SIGNUP_ENABLED=0
TIER=core
COOKIE_SECURE=1
# TRUSTED_PROXY deliberately unset — traefik does not send X-Real-IP.
EOF
@@ -208,8 +221,13 @@ start_superbrain() {
# Provision the operator account. Verified idempotent (no-op when the email
# already exists); grants ADMIN because admin@$DOMAIN is in ADMIN_EMAILS.
# Password-less on purpose (AUTH_MODE=oidc): a password would be unusable
# with login disabled AND would block the SSO bridge's verified-email
# auto-link (409). First Authelia login links the account; if Authelia ever
# stops asserting email_verified, link offline instead with
# -e SEED_SUBJECT=<authelia sub> on the same command.
for i in $(seq 1 10); do
docker exec -e SEED_EMAIL="admin@$DOMAIN" -e SEED_PASSWORD="$ADMINPASS" -e SEED_NAME="Admin" \
docker exec -e SEED_EMAIL="admin@$DOMAIN" -e SEED_NAME="Admin" \
superbrain-app /superbrain --seed &>/dev/null && break
sleep 3
done
@@ -230,10 +248,29 @@ uninstall_superbrain() {
docker exec pdns pdnsutil delete-rrset $DOMAIN superbrain.$DOMAIN A &>/dev/null
# Remove Authelia SSO config if present (immich pattern)
if grep -q "### Superbrain" /federated/apps/authelia/data/config/idproviders.yml 2>/dev/null; then
sed -i '/### Superbrain/,/### /{/### [A-Z]/!{/### /!d}}' /federated/apps/authelia/data/config/idproviders.yml
sed -i '/### Superbrain/d' /federated/apps/authelia/data/config/idproviders.yml
# Remove Authelia SSO config if present (immich pattern). Two blocks exist:
# the claims policy ("### Superbrain claims", possibly with the
# claims_policies: key we created) and the client ("### Superbrain").
# Remove the claims block FIRST and by exact line count - the client-block
# range deletion below starts at the first "### Superbrain" match, and a
# leftover claims marker would make it eat the claims_policies:/clients: keys.
AUTH_YML=/federated/apps/authelia/data/config/idproviders.yml
if grep -q "### Superbrain" "$AUTH_YML" 2>/dev/null; then
sed -i '/### Superbrain claims/{N;N;d}' "$AUTH_YML"
# Drop claims_policies: again when our policy was its only entry.
awk '
/^ claims_policies:$/ {
if ((getline nxt) > 0) {
if (nxt ~ /^ /) { print; print nxt } else { print nxt }
}
next
}
{ print }
' "$AUTH_YML" > "$AUTH_YML.tmp" && mv "$AUTH_YML.tmp" "$AUTH_YML"
sed -i '/### Superbrain/,/### /{/### [A-Z]/!{/### /!d}}' "$AUTH_YML"
sed -i '/### Superbrain/d' "$AUTH_YML"
docker exec authelia authelia validate-config --config /config/configuration.yml --config /config/idproviders.yml --config.experimental.filters template \
|| echo "WARNING: Authelia config does not validate after superbrain removal - inspect $AUTH_YML before relying on SSO"
restart_service authelia
fi
@@ -250,10 +287,29 @@ configsso_superbrain() {
SUPERBRAIN_CLIENT_SECRET=$(create_password)
SUPERBRAIN_CLIENT_SECRET_HASH=$(docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 --password $SUPERBRAIN_CLIENT_SECRET | awk '{ print $2 }')
# Authelia only includes claims listed in a claims policy's id_token set in
# the ID token, and Auth.js builds the OIDC profile EXCLUSIVELY from ID-token
# claims (it only calls userinfo when a provider sets idToken:false, which
# superbrain must not). Without email in the id_token the Go bridge answers
# 400 "Subject and email are required" and every SSO login ends in
# AccessDenied (hit in production 2026-10-25). Register the policy next to
# the client; the uninstall path removes both.
AUTH_YML=/federated/apps/authelia/data/config/idproviders.yml
SUPERBRAIN_CLAIMS="['email', 'email_verified', 'name', 'preferred_username']"
cp -a "$AUTH_YML" "$AUTH_YML.bak-superbrain"
if grep -q '^ superbrain:$' "$AUTH_YML"; then
echo " claims policy 'superbrain' already present, keeping it"
elif grep -q '^ claims_policies:' "$AUTH_YML"; then
sed -i "/^ claims_policies:/a\\ ### Superbrain claims\n superbrain:\n id_token: $SUPERBRAIN_CLAIMS" "$AUTH_YML"
else
sed -i "/^ clients:/i\\ claims_policies:\n ### Superbrain claims\n superbrain:\n id_token: $SUPERBRAIN_CLAIMS" "$AUTH_YML"
fi
SUPERBRAIN_OIDC_CLIENT_YAML=$(cat <<EOF
### Superbrain
- client_id: 'superbrain'
client_name: 'Superbrain'
claims_policy: 'superbrain'
client_secret: $SUPERBRAIN_CLIENT_SECRET_HASH
consent_mode: 'implicit'
public: false
@@ -267,10 +323,18 @@ configsso_superbrain() {
userinfo_signed_response_alg: 'none'
EOF
)
printf '%s\n' "$SUPERBRAIN_OIDC_CLIENT_YAML" >> /federated/apps/authelia/data/config/idproviders.yml
printf '%s\n' "$SUPERBRAIN_OIDC_CLIENT_YAML" >> "$AUTH_YML"
printf '%s\n' "$SUPERBRAIN_OIDC_CLIENT_YAML" > /federated/apps/superbrain/.superbrain.oidc-client.yml
chmod 600 /federated/apps/superbrain/.superbrain.oidc-client.yml
# idproviders.yml is shared by every SSO app: validate the merged config
# before restarting, and restore the backup when it does not parse.
if ! docker exec authelia authelia validate-config --config /config/configuration.yml --config /config/idproviders.yml --config.experimental.filters template; then
cp -a "$AUTH_YML.bak-superbrain" "$AUTH_YML"
failcheck "Authelia config invalid after adding superbrain - restored $AUTH_YML.bak-superbrain"
fi
rm -f "$AUTH_YML.bak-superbrain"
restart_service authelia
# env_file pattern: appending here is enough — web picks the values up on
+21
View File
@@ -51,10 +51,27 @@ services:
# value keeps local defaults (bootstrap enabled, signup open).
ALLOW_BOOTSTRAP_SIGNUP: ${ALLOW_BOOTSTRAP_SIGNUP:-}
SIGNUP_ENABLED: ${SIGNUP_ENABLED:-}
# Auth personality: both (default) | password (multi-tenant: signup
# only, no Authelia) | oidc (core: Authelia only, no password login).
AUTH_MODE: ${AUTH_MODE:-}
# Product tier: core | multi. Derives AUTH_MODE/SIGNUP_ENABLED/
# ALLOW_BOOTSTRAP_SIGNUP defaults; explicit variables override.
TIER: ${TIER:-}
COOKIE_SECURE: ${COOKIE_SECURE:-}
OIDC_ISSUER: ${OIDC_ISSUER:-}
OIDC_CLIENT_ID: ${OIDC_CLIENT_ID:-}
OIDC_CLIENT_SECRET: ${OIDC_CLIENT_SECRET:-}
# Transactional mail (password reset). Like the H-3 vars above these
# must reach the Go container explicitly; a private-network relay also
# needs INTEGRATIONS_ALLOW_PRIVATE=1 (netguard) to be dialable.
SMTP_HOST: ${SMTP_HOST:-}
SMTP_PORT: ${SMTP_PORT:-}
SMTP_USERNAME: ${SMTP_USERNAME:-}
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
SMTP_FROM: ${SMTP_FROM:-}
# Operator-pinned hostnames allowed to resolve to private addresses
# (split-horizon DNS relays). Never put user-supplied names here.
NETGUARD_TRUSTED_HOSTS: ${NETGUARD_TRUSTED_HOSTS:-}
ports: ["127.0.0.1:${APP_HOST_PORT:-8080}:8080"]
healthcheck:
test: [CMD, /superbrain, --healthcheck]
@@ -77,6 +94,10 @@ services:
NEXTAUTH_SECRET: ${AUTH_SECRET}
NEXTAUTH_URL: ${NEXTAUTH_URL:-http://localhost:3000}
AUTH_TRUST_HOST: "true"
# Must match the app container: gates the credentials provider and the
# signup/reset pages (Go enforces the same rules server-side).
AUTH_MODE: ${AUTH_MODE:-}
TIER: ${TIER:-}
# Review H-1: opt in only when a proxy in front of web pins X-Real-IP
# (the shipped nginx template does; scripts/server-deploy.sh sets it).
# Leave unset when port 3000 is browser-reachable directly, otherwise
+14 -2
View File
@@ -10,7 +10,6 @@ import (
"net/http"
"net/mail"
"net/url"
"os"
"strings"
"time"
)
@@ -56,7 +55,13 @@ func HandleSignup(w http.ResponseWriter, r *http.Request) {
if !checkAuthRequest(w, r) {
return
}
if os.Getenv("SIGNUP_ENABLED") == "0" {
if config.AuthMode() == "oidc" {
failure(w, 403, "Registration is disabled")
return
}
// SIGNUP_ENABLED explicitly, or derived from TIER (core: off — accounts
// are provisioned upstream). See config.SignupEnabled.
if !config.SignupEnabled() {
failure(w, 403, "Registration is disabled")
return
}
@@ -180,6 +185,13 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
if !checkAuthRequest(w, r) {
return
}
// AUTH_MODE=oidc deployments (core/federated shape) are Authelia-only:
// the password endpoint is refused outright, not merely hidden — the
// login form's absence in the web UI must not be the only barrier.
if config.AuthMode() == "oidc" {
failure(w, 403, "Password login is disabled on this server")
return
}
var req SigninRequest
if !decode(w, r, &req) {
return
+7
View File
@@ -86,6 +86,13 @@ func HandleOIDCIdentity(w http.ResponseWriter, r *http.Request) {
failure(w, http.StatusMethodNotAllowed, "Use POST")
return
}
// AUTH_MODE=password deployments (multi-tenant shape) have no Authelia:
// the bridge is refused even with valid OIDC_* variables and a valid
// service token, so a stray config can never provision identities.
if config.AuthMode() == "password" {
failure(w, http.StatusForbidden, "OIDC provisioning is disabled on this server")
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")
+228
View File
@@ -0,0 +1,228 @@
// Self-service password reset: "forgot password" emails a single-use link,
// "reset" consumes it. Both endpoints are unauthenticated, so they follow
// the same rules as login/signup:
//
// - No account enumeration (review SEC-4 pattern): /forgot answers the
// identical 200 {"ok":true} whether or not the address exists, has a
// password, or the email actually went out. Delivery problems are logged
// for the operator, never surfaced per-address.
// - Tokens are 256-bit random values; only the SHA-256 hash is stored.
// A reset bumps tokenVersion, invalidating every session minted with
// the old password (review SEC-02 revocation semantics).
// - OIDC-only (password-less) accounts are deliberately excluded: handing
// them a password would open a credential path around Authelia that the
// provisioning bridge refuses to create by email match alone.
//
// Sending requires SMTP_HOST/SMTP_FROM (see internal/mailer); without them
// /forgot answers 503 — a global deployment property, not a per-account
// signal.
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"log"
"net/http"
"net/mail"
"strings"
"time"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/mailer"
)
const (
resetTokenTTL = 30 * time.Minute
resetTokenBytes = 32
forgotIPLimit = 5 // forgot-password requests per IP per window
forgotIPWindow = time.Hour
resetIPLimit = 10 // reset submissions per IP per window
resetIPWindow = time.Hour
maxResetTokenLen = 128
minResetPassword = 8 // mirrors signup
maxResetPasswordB = 72 // bcrypt input cap, mirrors signup
)
var (
forgotIPs = newLimiterStore()
resetIPs = newLimiterStore()
)
// RateLimitForgot and RateLimitReset cap the two unauthenticated reset
// endpoints per effective client IP. Like signup (and unlike login) they
// keep the loopback exemption for same-host consumers of the 127.0.0.1
// binding; a forwarded identity never earns it (review SEC-2).
func RateLimitForgot(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !isLoopback(r) {
if ok, retry := forgotIPs.allow(EffectiveClientIP(r), forgotIPLimit, forgotIPWindow, time.Now()); !ok {
tooManyRequests(w, retry)
return
}
}
next(w, r)
}
}
func RateLimitReset(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !isLoopback(r) {
if ok, retry := resetIPs.allow(EffectiveClientIP(r), resetIPLimit, resetIPWindow, time.Now()); !ok {
tooManyRequests(w, retry)
return
}
}
next(w, r)
}
}
// HandleForgotPassword accepts {"email": ...} and always answers 200
// {"ok":true} once the request is well-formed — the response must not
// distinguish registered, unregistered, or OIDC-only addresses.
//
// POST /api/password/forgot
func HandleForgotPassword(w http.ResponseWriter, r *http.Request) {
if !checkAuthRequest(w, r) {
return
}
// SSO-only deployments have no local passwords to reset; Authelia owns
// recovery there. Refuse before the SMTP check so the response does not
// vary with mail configuration.
if config.AuthMode() == "oidc" {
failure(w, 403, "Password reset is disabled on this server")
return
}
cfg := config.Load()
if !mailer.LoadConfig().Configured() {
// Global misconfiguration; identical for every address.
failure(w, 503, "Password reset is not available on this server")
return
}
base := strings.TrimRight(strings.TrimSpace(cfg.NextAuthURL), "/")
if base == "" {
log.Printf("password reset: NEXTAUTH_URL is unset; cannot build reset links")
failure(w, 503, "Password reset is not available on this server")
return
}
var req struct {
Email string `json:"email"`
}
if !decode(w, r, &req) {
return
}
email := strings.ToLower(strings.TrimSpace(req.Email))
// Every early exit below answers the same 200; only the operator log
// knows whether a mail went out.
okResponse := func() { writeJSON(w, 200, SignupResponse{true}) }
if email == "" {
okResponse()
return
}
if a, e := mail.ParseAddress(email); e != nil || a.Address != email || len(email) > maxSignupEmailLen {
okResponse()
return
}
u, e := db.NewUserRepo(db.FromContext(r.Context())).FindByEmail(r.Context(), email)
if e != nil {
if !errors.Is(e, db.ErrNotFound) {
log.Printf("password reset: user lookup failed: %v", e)
}
okResponse()
return
}
// Password-less (OIDC-provisioned) accounts are out of scope by design.
if u.Password == nil || *u.Password == "" {
log.Printf("password reset: ignored request for password-less account %s", email)
okResponse()
return
}
raw := make([]byte, resetTokenBytes)
if _, e := rand.Read(raw); e != nil {
log.Printf("password reset: token generation failed: %v", e)
okResponse()
return
}
token := base64.RawURLEncoding.EncodeToString(raw)
sum := sha256.Sum256([]byte(token))
repo := db.NewPasswordResetRepo(db.FromContext(r.Context()))
if e := repo.Create(r.Context(), u.ID, hex.EncodeToString(sum[:]), time.Now().Add(resetTokenTTL)); e != nil {
log.Printf("password reset: token store failed: %v", e)
okResponse()
return
}
link := base + "/reset-password?token=" + token
body := "We received a request to reset your Superbrain password.\n\n" +
"Open this link within " + resetTokenTTL.String() + " to choose a new password:\n\n" +
link + "\n\n" +
"If you did not request a reset, you can ignore this email; the link is\n" +
"single-use and your password stays unchanged.\n"
if e := mailer.Send(r.Context(), email, "Reset your Superbrain password", body); e != nil {
log.Printf("password reset: delivery to %s failed: %v", email, e)
}
okResponse()
}
// HandleResetPassword accepts {"token": ..., "password": ...}, consumes the
// token and sets the new bcrypt hash while invalidating existing sessions.
//
// POST /api/password/reset
func HandleResetPassword(w http.ResponseWriter, r *http.Request) {
if !checkAuthRequest(w, r) {
return
}
if config.AuthMode() == "oidc" {
failure(w, 403, "Password reset is disabled on this server")
return
}
var req struct {
Token string `json:"token"`
Password string `json:"password"`
}
if !decode(w, r, &req) {
return
}
token := strings.TrimSpace(req.Token)
if token == "" || len(token) > maxResetTokenLen {
failure(w, 400, "Invalid or expired token")
return
}
if len(req.Password) < minResetPassword {
failure(w, 400, "Password must be at least 8 characters")
return
}
if len(req.Password) > maxResetPasswordB {
failure(w, 400, "Password must be at most 72 bytes")
return
}
sum := sha256.Sum256([]byte(token))
userID, e := db.NewPasswordResetRepo(db.FromContext(r.Context())).Consume(r.Context(), hex.EncodeToString(sum[:]))
if e != nil {
if errors.Is(e, db.ErrNotFound) {
failure(w, 400, "Invalid or expired token")
return
}
failure(w, 500, "Database unavailable")
return
}
hash, e := bcryptHashImpl(req.Password)
if e != nil {
failure(w, 500, "Unable to hash password")
return
}
if e := db.NewUserRepo(db.FromContext(r.Context())).SetPassword(r.Context(), userID, hash); e != nil {
if errors.Is(e, db.ErrNotFound) {
failure(w, 400, "Invalid or expired token")
return
}
failure(w, 500, "Unable to reset password")
return
}
// Audited like role changes (review SEC-11): ids only, no secrets.
log.Printf("audit: password reset completed for user %s", userID)
writeJSON(w, 200, SignupResponse{true})
}
+1 -1
View File
@@ -162,7 +162,7 @@ var (
// sequential tests do not inherit each other's buckets (the login endpoint
// has no loopback exemption since review SEC-1).
func ResetRateLimits() {
for _, s := range []*limiterStore{loginIPs, signupIPs, loginFailures} {
for _, s := range []*limiterStore{loginIPs, signupIPs, loginFailures, forgotIPs, resetIPs} {
s.mu.Lock()
s.m = map[string]*counter{}
s.mu.Unlock()
+87 -2
View File
@@ -122,9 +122,84 @@ func IsAdminEmail(email string) bool {
// so the documented "sign up, then sign in" onboarding keeps working;
// exposed deployments set ALLOW_BOOTSTRAP_SIGNUP=0 and provision operators
// via ADMIN_EMAILS/seed instead, so an attacker scanning for new
// installations cannot claim the instance.
// installations cannot claim the instance. The core tier defaults to OFF
// (operator-provisioned); an explicit value always wins.
func AllowBootstrapSignup() bool {
return os.Getenv("ALLOW_BOOTSTRAP_SIGNUP") != "0"
if v := strings.TrimSpace(os.Getenv("ALLOW_BOOTSTRAP_SIGNUP")); v != "" {
return v != "0"
}
return Tier() != "core"
}
// Tier is the product tier of the deployment (TIER):
//
// core federated/private install for paying customers: Authelia SSO only,
// accounts provisioned upstream (Superpanel -> LDAP -> Authelia),
// no self-service signup or bootstrap.
// multi hosted multi-user install: self-service signup + password login
// + self-service reset. (The multi-tenant/orgs data model is future
// work; the tier name is reserved for it.)
//
// TIER derives defaults for the mechanism-level knobs (AUTH_MODE,
// SIGNUP_ENABLED, ALLOW_BOOTSTRAP_SIGNUP); an explicitly set variable always
// wins over its tier default. Invalid values fail startup (Validate).
func Tier() string {
switch strings.ToLower(strings.TrimSpace(os.Getenv("TIER"))) {
case "core":
return "core"
case "multi":
return "multi"
default:
return ""
}
}
// AuthMode is the deployment's authentication personality:
//
// both (default) password login/signup and Authelia OIDC coexist;
// OIDC is active only when the three OIDC_* variables hold real
// values (the historical behavior).
// password multi-tenant shape: email signup + password login only. OIDC is
// DISABLED even when OIDC_* variables are set — provisioning
// identities over the bridge is refused.
// oidc core/federated shape: Authelia exclusively. Password login,
// signup and password reset are all refused; accounts arrive
// through the trusted OIDC identity bridge (operator-provisioned
// upstream, e.g. via LDAP/Superpanel).
//
// AUTH_MODE set explicitly wins; otherwise TIER derives it (core -> oidc,
// multi -> password). Unknown AUTH_MODE values are rejected at startup
// (Validate) rather than silently falling back: a typo in a security posture
// must fail loudly, not quietly re-enable password login on an SSO-only
// deployment.
func AuthMode() string {
switch strings.ToLower(strings.TrimSpace(os.Getenv("AUTH_MODE"))) {
case "password":
return "password"
case "oidc":
return "oidc"
case "both":
return "both"
}
switch Tier() {
case "core":
return "oidc"
case "multi":
return "password"
default:
return "both"
}
}
// SignupEnabled reports whether self-service registration is accepted.
// SIGNUP_ENABLED set explicitly wins ("0" disables); otherwise the core tier
// disables signup (accounts are provisioned upstream) and every other
// deployment keeps the historical default of enabled.
func SignupEnabled() bool {
if v := strings.TrimSpace(os.Getenv("SIGNUP_ENABLED")); v != "" {
return v != "0"
}
return Tier() != "core"
}
// Validate fails fast on configuration the app cannot use, instead of
@@ -139,5 +214,15 @@ func (c *Config) Validate() error {
return fmt.Errorf("NEXTAUTH_URL must be an absolute http(s) URL, got %q", c.NextAuthURL)
}
}
switch strings.ToLower(strings.TrimSpace(os.Getenv("AUTH_MODE"))) {
case "", "both", "password", "oidc":
default:
return fmt.Errorf("AUTH_MODE must be one of both, password, oidc; got %q", os.Getenv("AUTH_MODE"))
}
switch strings.ToLower(strings.TrimSpace(os.Getenv("TIER"))) {
case "", "core", "multi":
default:
return fmt.Errorf("TIER must be one of core, multi; got %q", os.Getenv("TIER"))
}
return nil
}
+73
View File
@@ -79,3 +79,76 @@ func TestEncryptionSecretPrecedence(t *testing.T) {
t.Fatal("ENCRYPTION_KEY must win over the auth secret")
}
}
// TIER derives the mechanism defaults; explicit variables always win.
// Unknown values must fail Validate instead of silently falling back —
// a typo must never re-enable password login on an SSO-only deployment.
func TestTierDerivation(t *testing.T) {
clean := func() {
for _, k := range []string{"TIER", "AUTH_MODE", "SIGNUP_ENABLED", "ALLOW_BOOTSTRAP_SIGNUP"} {
t.Setenv(k, "")
}
}
clean()
if Tier() != "" || AuthMode() != "both" || !SignupEnabled() || !AllowBootstrapSignup() {
t.Fatal("unset tier must keep historical defaults (both/signup/bootstrap on)")
}
t.Setenv("TIER", "core")
if AuthMode() != "oidc" {
t.Fatalf("core tier: AuthMode = %s, want oidc", AuthMode())
}
if SignupEnabled() {
t.Fatal("core tier must default signup off")
}
if AllowBootstrapSignup() {
t.Fatal("core tier must default bootstrap off")
}
t.Setenv("TIER", "multi")
if AuthMode() != "password" {
t.Fatalf("multi tier: AuthMode = %s, want password", AuthMode())
}
if !SignupEnabled() || !AllowBootstrapSignup() {
t.Fatal("multi tier keeps signup/bootstrap defaults on")
}
// Explicit variables override tier defaults in both directions.
t.Setenv("TIER", "core")
t.Setenv("AUTH_MODE", "both")
t.Setenv("SIGNUP_ENABLED", "1")
t.Setenv("ALLOW_BOOTSTRAP_SIGNUP", "1")
if AuthMode() != "both" || !SignupEnabled() || !AllowBootstrapSignup() {
t.Fatal("explicit vars must win over core tier defaults")
}
t.Setenv("TIER", "multi")
t.Setenv("AUTH_MODE", "oidc")
t.Setenv("SIGNUP_ENABLED", "0")
if AuthMode() != "oidc" || SignupEnabled() {
t.Fatal("explicit vars must win over multi tier defaults")
}
clean()
// Case/whitespace normalization.
t.Setenv("TIER", " CORE ")
if Tier() != "core" || AuthMode() != "oidc" {
t.Fatal("TIER must be normalized case-insensitively")
}
clean()
// Startup validation rejects unknown values.
t.Setenv("TIER", "enterprise")
if err := (&Config{AuthSecret: "s"}).Validate(); err == nil {
t.Fatal("invalid TIER passed validation")
}
t.Setenv("TIER", "multi")
t.Setenv("AUTH_MODE", "sso")
if err := (&Config{AuthSecret: "s"}).Validate(); err == nil {
t.Fatal("invalid AUTH_MODE passed validation")
}
t.Setenv("AUTH_MODE", "oidc")
if err := (&Config{AuthSecret: "s"}).Validate(); err != nil {
t.Fatalf("valid tier+mode rejected: %v", err)
}
clean()
}
+57
View File
@@ -0,0 +1,57 @@
package db
import (
"context"
"database/sql"
"errors"
"time"
)
// PasswordResetRepo stores single-use password-reset tokens.
//
// Only the SHA-256 hash of the token is persisted — the plain value exists
// solely inside the emailed link — so a database leak does not hand out
// working reset URLs. Issuing a token deletes the user's previous ones (the
// newest link wins), and consumption is one transaction guarded by row lock
// so two concurrent resets with the same token cannot both succeed.
type PasswordResetRepo struct{ db *DB }
func NewPasswordResetRepo(d *DB) *PasswordResetRepo { return &PasswordResetRepo{db: d} }
// Create stores a fresh token hash for the user, replacing any outstanding
// tokens, and sweeps that user's expired/used rows to keep the table small.
func (r *PasswordResetRepo) Create(ctx context.Context, userID, tokenHash string, expiresAt time.Time) error {
return Transaction(ctx, r.db, func(tx *sql.Tx) error {
if _, err := tx.ExecContext(ctx, `DELETE FROM "PasswordResetToken" WHERE "userId"=$1`, userID); err != nil {
return err
}
_, err := tx.ExecContext(ctx,
`INSERT INTO "PasswordResetToken"(id,"userId","tokenHash","expiresAt") VALUES($1,$2,$3,$4)`,
NewID(), userID, tokenHash, expiresAt)
return err
})
}
// Consume marks a valid (unexpired, unused) token as used and returns the
// owning user id. Anything else — unknown hash, expired, already used —
// reports ErrNotFound without revealing which case applied.
func (r *PasswordResetRepo) Consume(ctx context.Context, tokenHash string) (string, error) {
var userID string
err := Transaction(ctx, r.db, func(tx *sql.Tx) error {
err := tx.QueryRowContext(ctx,
`SELECT "userId" FROM "PasswordResetToken" WHERE "tokenHash"=$1 AND "usedAt" IS NULL AND "expiresAt">now() FOR UPDATE`,
tokenHash).Scan(&userID)
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
if err != nil {
return err
}
_, err = tx.ExecContext(ctx, `UPDATE "PasswordResetToken" SET "usedAt"=now() WHERE "tokenHash"=$1`, tokenHash)
return err
})
if err != nil {
return "", err
}
return userID, nil
}
+26 -1
View File
@@ -77,6 +77,23 @@ func (r *UserRepo) BumpTokenVersion(ctx context.Context, id string) error {
return err
}
// SetPassword replaces the bcrypt hash AND bumps tokenVersion in one
// transaction: a password change (reset) must invalidate every session
// minted under the old credentials, the same revocation path as an explicit
// "sign out everywhere". Missing user reports ErrNotFound.
func (r *UserRepo) SetPassword(ctx context.Context, id, bcryptHash string) error {
return Transaction(ctx, r.db, func(tx *sql.Tx) error {
res, err := tx.ExecContext(ctx, `UPDATE "User" SET password=$1,"tokenVersion"="tokenVersion"+1,"updatedAt"=now() WHERE id=$2`, bcryptHash, id)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return nil
})
}
type NewUserInput struct {
ID, Name, Email, Password, Role string
EmailVerified *string
@@ -285,6 +302,14 @@ func (r *UserRepo) ProvisionExternal(ctx context.Context, in ExternalUserInput)
}
// 3. New external user. Name falls back to the email local part.
// Operator-listed addresses (ADMIN_EMAILS) become ADMIN at first SSO
// login: on AUTH_MODE=oidc deployments this is the only bootstrap
// path — password login, signup and the seeded-password flow are all
// unavailable there. Same trust semantics as --seed.
role := "USER"
if config.IsAdminEmail(in.Email) {
role = "ADMIN"
}
id := NewID()
name := strings.TrimSpace(in.Name)
if name == "" {
@@ -304,7 +329,7 @@ func (r *UserRepo) ProvisionExternal(ctx context.Context, in ExternalUserInput)
ID: id,
Name: name,
Email: in.Email,
Role: "USER",
Role: role,
EmailVerified: verified,
Image: image,
External: true,
+221
View File
@@ -0,0 +1,221 @@
package http
import (
"context"
"net/http"
"net/http/cookiejar"
"testing"
"time"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/scripts"
)
// AUTH_MODE=oidc (core/federated shape): Authelia exclusively. Password
// login, signup and password reset are refused at the API — hiding the web
// UI alone must never be the barrier — while the trusted identity bridge
// keeps working and provisions operators listed in ADMIN_EMAILS as ADMIN.
func TestAuthModeOIDC(t *testing.T) {
srv, d := testServerDB(t)
t.Setenv("AUTH_MODE", "oidc")
t.Setenv("OIDC_ISSUER", "https://auth.test")
t.Setenv("OIDC_CLIENT_ID", "superbrain")
t.Setenv("OIDC_CLIENT_SECRET", "test-secret")
t.Setenv("SMTP_HOST", "mail.test")
t.Setenv("SMTP_FROM", "superbrain@test")
t.Setenv("ADMIN_EMAILS", "operator@superbrain.test")
jar, _ := cookiejar.New(nil)
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
c.request("POST", "/api/auth/login", map[string]any{"email": "a@superbrain.test", "password": "a-long-test-password"}, 403)
c.request("POST", "/api/signup", map[string]any{"email": "a@superbrain.test", "password": "a-long-test-password"}, 403)
c.request("POST", "/api/password/forgot", map[string]any{"email": "a@superbrain.test"}, 403)
c.request("POST", "/api/password/reset", map[string]any{"token": "x", "password": "brand-new-password"}, 403)
// The identity bridge still provisions. A fresh SSO user is USER...
body := map[string]any{"issuer": "https://auth.test", "subject": "sub-user", "email": "someone@superbrain.test", "emailVerified": true}
status, out := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body)
if status != 200 {
t.Fatalf("identity provision: wanted 200, got %d: %v", status, out)
}
if role := out["user"].(map[string]any)["role"]; role != "USER" {
t.Fatalf("fresh SSO user role = %v, wanted USER", role)
}
// ...and an operator-listed email becomes ADMIN on first SSO login —
// the only bootstrap path when password login is disabled.
body = map[string]any{"issuer": "https://auth.test", "subject": "sub-operator", "email": "operator@superbrain.test", "emailVerified": true}
status, out = postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body)
if status != 200 {
t.Fatalf("operator provision: wanted 200, got %d: %v", status, out)
}
if role := out["user"].(map[string]any)["role"]; role != "ADMIN" {
t.Fatalf("ADMIN_EMAILS SSO user role = %v, wanted ADMIN", role)
}
// Seed CLI with SEED_SUBJECT links an offline-provisioned operator
// without any session (the chicken-and-egg escape hatch for this mode).
t.Setenv("SEED_EMAIL", "seeded@superbrain.test")
t.Setenv("SEED_SUBJECT", "sub-seeded")
t.Setenv("SEED_PASSWORD", "")
if err := scripts.Seed(context.Background(), d); err != nil {
t.Fatalf("seed with subject: %v", err)
}
body = map[string]any{"issuer": "https://auth.test", "subject": "sub-seeded", "email": "seeded@superbrain.test", "emailVerified": true}
if status, _ := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body); status != 200 {
t.Fatalf("seeded subject login: wanted 200, got %d", status)
}
// Re-running the same seed is idempotent.
if err := scripts.Seed(context.Background(), d); err != nil {
t.Fatalf("seed must be idempotent: %v", err)
}
}
// A pre-existing PASSWORD account still refuses auto-link by email in oidc
// mode (409); the operator links it offline via SEED_SUBJECT, after which
// SSO resolves to the SAME local user — exactly the core-upgrade path.
func TestAuthModeOIDCLinksExistingPasswordAccount(t *testing.T) {
srv, d := testServerDB(t)
// Create the password account while passwords still work.
jar, _ := cookiejar.New(nil)
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
c.request("POST", "/api/signup", map[string]any{"email": "admin@superbrain.test", "password": "a-long-test-password"}, 201)
c.request("POST", "/api/auth/login", map[string]any{"email": "admin@superbrain.test", "password": "a-long-test-password"}, 200)
adminID := meID(c)
t.Setenv("AUTH_MODE", "oidc")
t.Setenv("OIDC_ISSUER", "https://auth.test")
t.Setenv("ADMIN_EMAILS", "")
body := map[string]any{"issuer": "https://auth.test", "subject": "sub-admin", "email": "admin@superbrain.test", "emailVerified": true}
if status, _ := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body); status != 409 {
t.Fatalf("password account must refuse email auto-link: wanted 409, got %d", status)
}
t.Setenv("SEED_EMAIL", "admin@superbrain.test")
t.Setenv("SEED_SUBJECT", "sub-admin")
t.Setenv("SEED_PASSWORD", "")
if err := scripts.Seed(context.Background(), d); err != nil {
t.Fatalf("offline link: %v", err)
}
status, out := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body)
if status != 200 {
t.Fatalf("linked login: wanted 200, got %d: %v", status, out)
}
if got := out["user"].(map[string]any)["id"]; got != adminID {
t.Fatalf("SSO resolved to %v, wanted the pre-existing local user %s", got, adminID)
}
// The subject can never be re-pointed at another user by re-seeding.
t.Setenv("SEED_EMAIL", "other@superbrain.test")
if err := scripts.Seed(context.Background(), d); err == nil {
t.Fatal("linking an already-linked subject to a different user must fail")
}
}
// AUTH_MODE=password (multi-tenant shape): signup/password login only. The
// OIDC bridge is refused even with valid variables AND a valid service token,
// and the status endpoint reports OIDC disabled so the UI hides Authelia.
func TestAuthModePassword(t *testing.T) {
srv, _ := testServerDB(t)
t.Setenv("AUTH_MODE", "password")
t.Setenv("OIDC_ISSUER", "https://auth.test")
t.Setenv("OIDC_CLIENT_ID", "superbrain")
t.Setenv("OIDC_CLIENT_SECRET", "test-secret")
jar, _ := cookiejar.New(nil)
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
c.request("POST", "/api/signup", map[string]any{"email": "tenant@superbrain.test", "password": "a-long-test-password"}, 201)
c.request("POST", "/api/auth/login", map[string]any{"email": "tenant@superbrain.test", "password": "a-long-test-password"}, 200)
body := map[string]any{"issuer": "https://auth.test", "subject": "sub-x", "email": "x@superbrain.test", "emailVerified": true}
if status, _ := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body); status != 403 {
t.Fatalf("identity bridge in password mode: wanted 403, got %d", status)
}
status := c.request("GET", "/api/auth/oidc/status", nil, 200)
if status["enabled"] != false {
t.Fatalf("oidc status must report disabled in password mode: %v", status)
}
}
// LinkExternal (the mechanism behind SEED_SUBJECT and POST
// /api/admin/oidc-link) refuses to move a subject between users.
func TestLinkExternalConflict(t *testing.T) {
_, d := testServerDB(t)
repo := db.NewUserRepo(d)
ctx := context.Background()
a, _ := repo.Create(ctx, &db.NewUserInput{ID: db.NewID(), Name: "A", Email: "a@superbrain.test", Password: "x", Role: "USER"})
b, _ := repo.Create(ctx, &db.NewUserInput{ID: db.NewID(), Name: "B", Email: "b@superbrain.test", Password: "x", Role: "USER"})
if err := repo.LinkExternal(ctx, a, "authelia", "sub-1"); err != nil {
t.Fatal(err)
}
if err := repo.LinkExternal(ctx, a, "authelia", "sub-1"); err != nil {
t.Fatalf("relinking the same user must be idempotent: %v", err)
}
if err := repo.LinkExternal(ctx, b, "authelia", "sub-1"); err != db.ErrAccountLinked {
t.Fatalf("subject move: wanted ErrAccountLinked, got %v", err)
}
}
// TIER=core alone (no AUTH_MODE set) must behave exactly like the oidc
// shape: the tier derives the mode end to end.
func TestTierCoreDerivesOIDCOnly(t *testing.T) {
srv, _ := testServerDB(t)
t.Setenv("TIER", "core")
t.Setenv("OIDC_ISSUER", "https://auth.test")
t.Setenv("OIDC_CLIENT_ID", "superbrain")
t.Setenv("OIDC_CLIENT_SECRET", "test-secret")
jar, _ := cookiejar.New(nil)
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
c.request("POST", "/api/auth/login", map[string]any{"email": "a@superbrain.test", "password": "a-long-test-password"}, 403)
c.request("POST", "/api/signup", map[string]any{"email": "a@superbrain.test", "password": "a-long-test-password"}, 403)
c.request("POST", "/api/password/forgot", map[string]any{"email": "a@superbrain.test"}, 403)
body := map[string]any{"issuer": "https://auth.test", "subject": "sub-tier", "email": "tier@superbrain.test", "emailVerified": true}
if status, out := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body); status != 200 {
t.Fatalf("identity provision on core tier: wanted 200, got %d: %v", status, out)
}
}
// TIER=multi alone must refuse the OIDC bridge even with real variables and
// a valid service token, while signup and password login keep working.
func TestTierMultiDerivesPasswordOnly(t *testing.T) {
srv, _ := testServerDB(t)
t.Setenv("TIER", "multi")
t.Setenv("OIDC_ISSUER", "https://auth.test")
t.Setenv("OIDC_CLIENT_ID", "superbrain")
t.Setenv("OIDC_CLIENT_SECRET", "test-secret")
jar, _ := cookiejar.New(nil)
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
c.request("POST", "/api/signup", map[string]any{"email": "tenant@superbrain.test", "password": "a-long-test-password"}, 201)
c.request("POST", "/api/auth/login", map[string]any{"email": "tenant@superbrain.test", "password": "a-long-test-password"}, 200)
body := map[string]any{"issuer": "https://auth.test", "subject": "sub-m", "email": "m@superbrain.test", "emailVerified": true}
if status, _ := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body); status != 403 {
t.Fatalf("identity bridge on multi tier: wanted 403, got %d", status)
}
if status := c.request("GET", "/api/auth/oidc/status", nil, 200); status["enabled"] != false {
t.Fatalf("oidc status must report disabled on multi tier: %v", status)
}
}
// Explicit variables override tier defaults (the documented escape hatch):
// TIER=core + AUTH_MODE=both re-enables password login, while signup stays
// off until SIGNUP_ENABLED says otherwise.
func TestTierExplicitOverride(t *testing.T) {
srv, _ := testServerDB(t)
t.Setenv("TIER", "core")
t.Setenv("AUTH_MODE", "both")
jar, _ := cookiejar.New(nil)
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
// Signup stays off via the core-tier default...
c.request("POST", "/api/signup", map[string]any{"email": "o@superbrain.test", "password": "a-long-test-password"}, 403)
// ...until explicitly re-enabled.
t.Setenv("SIGNUP_ENABLED", "1")
c.request("POST", "/api/signup", map[string]any{"email": "o@superbrain.test", "password": "a-long-test-password"}, 201)
c.request("POST", "/api/auth/login", map[string]any{"email": "o@superbrain.test", "password": "a-long-test-password"}, 200)
}
+233
View File
@@ -0,0 +1,233 @@
package http
import (
"bufio"
"context"
"net"
"net/http"
"net/http/cookiejar"
"regexp"
"strings"
"sync"
"testing"
"time"
"github.com/andrew/superbrain/internal/db"
)
// fakeSMTP is a minimal loopback SMTP relay: it speaks just enough of the
// protocol for internal/mailer (greeting, EHLO without extensions so no
// STARTTLS/AUTH is attempted, MAIL/RCPT/DATA/QUIT) and records every
// delivered message. Same fixture pattern as the CardDAV/IMAP fakes; the
// harness sets INTEGRATIONS_ALLOW_PRIVATE=1 so netguard permits loopback.
type fakeSMTP struct {
t *testing.T
ln net.Listener
mu sync.Mutex
msgs [][2]string // {envelope recipient, DATA payload}
done chan struct{}
close sync.Once
}
func newFakeSMTP(t *testing.T) *fakeSMTP {
t.Helper()
ln, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal(e)
}
f := &fakeSMTP{t: t, ln: ln, done: make(chan struct{})}
go f.serve()
t.Cleanup(func() { f.close.Do(func() { close(f.done); ln.Close() }) })
return f
}
func (f *fakeSMTP) serve() {
for {
conn, e := f.ln.Accept()
if e != nil {
return
}
go f.handle(conn)
}
}
func (f *fakeSMTP) handle(conn net.Conn) {
defer conn.Close()
r := bufio.NewReader(conn)
say := func(s string) { conn.SetWriteDeadline(time.Now().Add(5 * time.Second)); conn.Write([]byte(s + "\r\n")) }
say("220 fake ESMTP")
var rcpt string
inData := false
var data strings.Builder
for {
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
line, e := r.ReadString('\n')
if e != nil {
return
}
line = strings.TrimRight(line, "\r\n")
if inData {
if line == "." {
inData = false
f.mu.Lock()
f.msgs = append(f.msgs, [2]string{rcpt, data.String()})
f.mu.Unlock()
data.Reset()
say("250 OK queued")
continue
}
data.WriteString(line + "\n")
continue
}
up := strings.ToUpper(line)
switch {
case strings.HasPrefix(up, "EHLO"), strings.HasPrefix(up, "HELO"):
say("250 fake") // single-line: no extensions advertised
case strings.HasPrefix(up, "MAIL FROM"):
say("250 OK")
case strings.HasPrefix(up, "RCPT TO"):
rcpt = strings.TrimSuffix(strings.TrimPrefix(line[strings.Index(line, ":")+1:], "<"), ">")
say("250 OK")
case up == "DATA":
inData = true
say("354 End data with <CR><LF>.<CR><LF>")
case up == "QUIT":
say("221 Bye")
return
case up == "RSET", up == "NOOP":
say("250 OK")
default:
say("250 OK")
}
}
}
func (f *fakeSMTP) messages() [][2]string {
f.mu.Lock()
defer f.mu.Unlock()
return append([][2]string(nil), f.msgs...)
}
// waitForMessage blocks until the fake has n messages (SMTP delivery is
// synchronous from the handler's perspective, but the fake serves in its own
// goroutines).
func (f *fakeSMTP) waitForMessage(t *testing.T, n int) [2]string {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
msgs := f.messages()
if len(msgs) >= n {
return msgs[n-1]
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("fake SMTP received %d messages, wanted %d", len(f.messages()), n)
return [2]string{}
}
var resetLinkRx = regexp.MustCompile(`/reset-password\?token=([A-Za-z0-9_-]+)`)
func TestPasswordResetFlow(t *testing.T) {
srv, d := testServerDB(t)
smtp := newFakeSMTP(t)
host, port, _ := net.SplitHostPort(smtp.ln.Addr().String())
t.Setenv("SMTP_HOST", host)
t.Setenv("SMTP_PORT", port)
t.Setenv("SMTP_FROM", "superbrain@superbrain.test")
t.Setenv("NEXTAUTH_URL", "https://superbrain.test")
jar, _ := cookiejar.New(nil)
alice := apiClient{t, &http.Client{Jar: jar}, srv.URL}
alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201)
login := func(c apiClient, email, password string, status int) map[string]any {
return c.request("POST", "/api/auth/login", map[string]any{"email": email, "password": password}, status)
}
first := login(alice, "alice@superbrain.test", "a-long-test-password", 200)
firstVersion := int(first["tokenVersion"].(float64))
// Unknown address: the SAME 200 {"ok":true} body and no mail (review
// SEC-4: no unauthenticated existence oracle).
unknown := alice.request("POST", "/api/password/forgot", map[string]any{"email": "nobody@superbrain.test"}, 200)
if len(unknown) != 1 || unknown["ok"] != true {
t.Fatalf("forgot body for unknown address is distinguishable: %v", unknown)
}
// An OIDC-only (password-less) account must never receive a reset link:
// setting a password would open a credential path around Authelia.
oidcID := db.NewID()
if _, e := db.NewUserRepo(d).Create(context.Background(), &db.NewUserInput{
ID: oidcID, Name: "OIDC Only", Email: "oidc-only@superbrain.test", Role: "USER", External: true,
}); e != nil {
t.Fatal(e)
}
alice.request("POST", "/api/password/forgot", map[string]any{"email": "oidc-only@superbrain.test"}, 200)
if msgs := smtp.messages(); len(msgs) != 0 {
t.Fatalf("mail sent for unknown/OIDC-only addresses: %v", msgs)
}
// Real request: one mail, link carries the token.
alice.request("POST", "/api/password/forgot", map[string]any{"email": "alice@superbrain.test"}, 200)
msg := smtp.waitForMessage(t, 1)
if msg[0] != "alice@superbrain.test" {
t.Fatalf("envelope recipient = %q", msg[0])
}
m := resetLinkRx.FindStringSubmatch(msg[1])
if m == nil {
t.Fatalf("no reset link in mail body:\n%s", msg[1])
}
token := m[1]
if !strings.Contains(msg[1], "https://superbrain.test/reset-password") {
t.Fatalf("reset link does not use NEXTAUTH_URL:\n%s", msg[1])
}
// Password policy mirrors signup.
alice.request("POST", "/api/password/reset", map[string]any{"token": token, "password": "short"}, 400)
// The token survives a rejected attempt (it was never consumed).
alice.request("POST", "/api/password/reset", map[string]any{"token": token, "password": strings.Repeat("x", 73)}, 400)
alice.request("POST", "/api/password/reset", map[string]any{"token": "not-a-real-token", "password": "brand-new-password"}, 400)
// Successful reset: old password dies, new one works, and tokenVersion
// bumps so every session minted before the reset is revoked (SEC-02).
alice.request("POST", "/api/password/reset", map[string]any{"token": token, "password": "brand-new-password"}, 200)
login(alice, "alice@superbrain.test", "a-long-test-password", 401)
after := login(alice, "alice@superbrain.test", "brand-new-password", 200)
if int(after["tokenVersion"].(float64)) != firstVersion+1 {
t.Fatalf("tokenVersion = %v, wanted %d (reset must revoke prior sessions)", after["tokenVersion"], firstVersion+1)
}
// Single-use: replaying the consumed token fails.
alice.request("POST", "/api/password/reset", map[string]any{"token": token, "password": "another-password-1"}, 400)
login(alice, "alice@superbrain.test", "brand-new-password", 200)
// A fresh request supersedes outstanding tokens (newest link wins).
alice.request("POST", "/api/password/forgot", map[string]any{"email": "alice@superbrain.test"}, 200)
token2 := resetLinkRx.FindStringSubmatch(smtp.waitForMessage(t, 2)[1])[1]
alice.request("POST", "/api/password/forgot", map[string]any{"email": "alice@superbrain.test"}, 200)
token3 := resetLinkRx.FindStringSubmatch(smtp.waitForMessage(t, 3)[1])[1]
alice.request("POST", "/api/password/reset", map[string]any{"token": token2, "password": "superseded-pass-1"}, 400)
alice.request("POST", "/api/password/reset", map[string]any{"token": token3, "password": "final-password-1"}, 200)
login(alice, "alice@superbrain.test", "final-password-1", 200)
// Expired tokens are rejected: age the stored row directly.
alice.request("POST", "/api/password/forgot", map[string]any{"email": "alice@superbrain.test"}, 200)
token4 := resetLinkRx.FindStringSubmatch(smtp.waitForMessage(t, 4)[1])[1]
if _, e := d.Exec(`UPDATE "PasswordResetToken" SET "expiresAt"=now()-interval '1 minute'`); e != nil {
t.Fatal(e)
}
alice.request("POST", "/api/password/reset", map[string]any{"token": token4, "password": "too-late-pass-1"}, 400)
}
func TestPasswordResetWithoutSMTP(t *testing.T) {
srv := testServer(t)
// No SMTP_HOST/SMTP_FROM configured: forgot reports a global 503 (a
// deployment property, identical for every address — not an oracle).
t.Setenv("SMTP_HOST", "")
t.Setenv("SMTP_FROM", "")
t.Setenv("NEXTAUTH_URL", "https://superbrain.test")
jar, _ := cookiejar.New(nil)
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
c.request("POST", "/api/signup", map[string]any{"email": "carol@superbrain.test", "password": "a-long-test-password"}, 201)
c.request("POST", "/api/password/forgot", map[string]any{"email": "carol@superbrain.test"}, 503)
c.request("POST", "/api/password/forgot", map[string]any{"email": "unknown@superbrain.test"}, 503)
// Reset still validates tokens structurally even without SMTP config.
c.request("POST", "/api/password/reset", map[string]any{"token": "x", "password": "brand-new-password"}, 400)
}
+4
View File
@@ -41,6 +41,10 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server {
// 4.1 Auth and account (rate limited for non-loopback peers)
mux.HandleFunc("POST /api/signup", auth.RateLimitSignup(auth.HandleSignup))
mux.HandleFunc("POST /api/auth/login", auth.RateLimitLogin(auth.HandleLogin))
// Self-service password reset (unauthenticated; enumeration-safe and
// rate limited per effective client IP like signup).
mux.HandleFunc("POST /api/password/forgot", auth.RateLimitForgot(auth.HandleForgotPassword))
mux.HandleFunc("POST /api/password/reset", auth.RateLimitReset(auth.HandleResetPassword))
mux.HandleFunc("GET /api/auth/", auth.HandleAuth) // csrf, callbacks, session, signout
mux.HandleFunc("POST /api/auth/", auth.HandleAuth)
mux.HandleFunc("GET /api/me", authed(auth.HandleMe))
+178
View File
@@ -0,0 +1,178 @@
// Package mailer sends transactional email (password-reset links) through a
// configured SMTP relay.
//
// Like every server-initiated dial, sending is bounded by internal/outbound
// and guarded by internal/netguard: private/link-local relay hosts (the
// normal in-cluster case, e.g. a docker-mailserver on the compose network)
// require INTEGRATIONS_ALLOW_PRIVATE=1, exactly like IMAP and CardDAV.
//
// Configuration (env):
//
// SMTP_HOST relay host (required; empty disables sending entirely)
// SMTP_PORT default 587; 465 selects implicit TLS, otherwise STARTTLS
// is used when the server advertises it
// SMTP_USERNAME optional; enables AUTH PLAIN when non-empty
// SMTP_PASSWORD optional
// SMTP_FROM envelope+header sender (required, e.g. superbrain@host)
package mailer
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"net/smtp"
"os"
"strconv"
"strings"
"time"
"github.com/andrew/superbrain/internal/netguard"
"github.com/andrew/superbrain/internal/outbound"
)
// ErrNotConfigured means SMTP_HOST/SMTP_FROM are unset; callers surface a
// 503 rather than pretending the message was queued.
var ErrNotConfigured = errors.New("mailer: SMTP is not configured")
// sendTimeout bounds one full SMTP conversation (dial + TLS + transfer).
const sendTimeout = 30 * time.Second
// Config is the SMTP_* environment snapshot.
type Config struct {
Host string
Port int
Username string
Password string
From string
}
// LoadConfig reads the SMTP_* variables. An unset or unparsable SMTP_PORT
// falls back to 587 (submission).
func LoadConfig() Config {
port := 587
if v := strings.TrimSpace(os.Getenv("SMTP_PORT")); v != "" {
if p, err := strconv.Atoi(v); err == nil && p > 0 && p < 65536 {
port = p
}
}
return Config{
Host: strings.TrimSpace(os.Getenv("SMTP_HOST")),
Port: port,
Username: strings.TrimSpace(os.Getenv("SMTP_USERNAME")),
Password: os.Getenv("SMTP_PASSWORD"),
From: strings.TrimSpace(os.Getenv("SMTP_FROM")),
}
}
// Configured reports whether Send can possibly work. This is a global
// deployment property, so surfacing it to unauthenticated callers leaks
// nothing per-account.
func (c Config) Configured() bool { return c.Host != "" && c.From != "" }
// Send delivers one plain-text message. It is synchronous: the caller owns
// the request context and any retry policy.
func Send(ctx context.Context, to, subject, body string) error {
cfg := LoadConfig()
if !cfg.Configured() {
return ErrNotConfigured
}
if to == "" {
return errors.New("mailer: missing recipient")
}
// Global send budget: password resets are rare and an unreachable or
// blackholed relay must not pile up goroutines (same shape as the IMAP
// and CardDAV callers).
release, _, ok := outbound.Reserve("smtp", 5, time.Minute)
if !ok {
return errors.New("mailer: send budget exhausted")
}
defer release()
ctx, cancel := context.WithTimeout(ctx, sendTimeout)
defer cancel()
conn, err := dial(ctx, cfg.Host, cfg.Port)
if err != nil {
return fmt.Errorf("mailer: dial: %w", err)
}
if cfg.Port == 465 {
// Implicit TLS: handshake before the SMTP greeting is read.
tlsConn := tls.Client(conn, &tls.Config{ServerName: cfg.Host})
if err := tlsConn.HandshakeContext(ctx); err != nil {
conn.Close()
return fmt.Errorf("mailer: tls: %w", err)
}
conn = tlsConn
}
client, err := smtp.NewClient(conn, cfg.Host)
if err != nil {
conn.Close()
return fmt.Errorf("mailer: smtp handshake: %w", err)
}
defer client.Close()
if cfg.Port != 465 {
if ok, _ := client.Extension("STARTTLS"); ok {
if err := client.StartTLS(&tls.Config{ServerName: cfg.Host}); err != nil {
return fmt.Errorf("mailer: starttls: %w", err)
}
}
}
if cfg.Username != "" {
if ok, _ := client.Extension("AUTH"); !ok {
return errors.New("mailer: relay requires credentials but does not advertise AUTH")
}
if err := client.Auth(smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)); err != nil {
return fmt.Errorf("mailer: auth: %w", err)
}
}
if err := client.Mail(cfg.From); err != nil {
return fmt.Errorf("mailer: MAIL FROM: %w", err)
}
if err := client.Rcpt(to); err != nil {
return fmt.Errorf("mailer: RCPT TO: %w", err)
}
data, err := client.Data()
if err != nil {
return fmt.Errorf("mailer: DATA: %w", err)
}
msg := strings.Join([]string{
"From: " + cfg.From,
"To: " + to,
"Subject: " + sanitizeHeader(subject),
"Date: " + time.Now().UTC().Format(time.RFC1123Z),
"MIME-Version: 1.0",
"Content-Type: text/plain; charset=UTF-8",
"Content-Transfer-Encoding: 8BIT",
"",
body,
"",
}, "\r\n")
if _, err := data.Write([]byte(msg)); err != nil {
return fmt.Errorf("mailer: write: %w", err)
}
if err := data.Close(); err != nil {
return fmt.Errorf("mailer: data close: %w", err)
}
// Best effort; Close() above already released the connection on error.
_ = client.Quit()
return nil
}
// sanitizeHeader strips CR/LF so a caller-controlled subject can never
// inject additional headers (or a second message).
func sanitizeHeader(s string) string {
return strings.NewReplacer("\r", " ", "\n", " ").Replace(strings.TrimSpace(s))
}
// dial resolves and connects through netguard: range checks apply unless
// INTEGRATIONS_ALLOW_PRIVATE=1 (house relays live on private networks), and
// only the standard SMTP ports are reachable from public ranges.
func dial(ctx context.Context, host string, port int) (net.Conn, error) {
address := net.JoinHostPort(host, strconv.Itoa(port))
if netguard.AllowPrivate() {
return netguard.DialContext(ctx, "tcp", address)
}
return netguard.DialContextPorts(ctx, "tcp", address, 25, 465, 587)
}
+31 -1
View File
@@ -10,6 +10,7 @@ import (
"net"
"os"
"strconv"
"strings"
"time"
)
@@ -19,6 +20,35 @@ import (
// mail on private addresses). It is off in the production Compose stack.
func AllowPrivate() bool { return os.Getenv("INTEGRATIONS_ALLOW_PRIVATE") == "1" }
// TrustedHost reports whether host is pinned in NETGUARD_TRUSTED_HOSTS
// (comma-separated, case-insensitive), which exempts its resolved addresses
// from the public-range check in DialContext.
//
// It exists for house infrastructure that LAN DNS resolves to a private
// address — e.g. an SMTP relay behind split-horizon DNS, where the public
// hostname answers 192.168.x.x inside the network. Only operator-configured,
// deployment-fixed hostnames belong in that variable. Callers must NEVER
// consult this exemption for user-supplied hostnames (previews, CardDAV,
// IMAP): a user who could pin their own "trusted" host would walk straight
// through the SSRF hole this package exists to close. Today the only
// consumer is internal/mailer, whose host comes exclusively from SMTP_HOST.
func TrustedHost(host string) bool {
v := os.Getenv("NETGUARD_TRUSTED_HOSTS")
if v == "" {
return false
}
host = strings.ToLower(strings.TrimSpace(host))
if host == "" {
return false
}
for _, h := range strings.Split(v, ",") {
if h = strings.ToLower(strings.TrimSpace(h)); h != "" && h == host {
return true
}
}
return false
}
// extraBlocked covers ranges net.IP's helpers miss. IPv4: "this network"
// (0.0.0.0/8), RFC 6598 CGNAT (100.64.0.0/10 — used by Tailscale, GKE
// internal LBs, some Docker setups), IETF protocol assignments
@@ -189,7 +219,7 @@ func DialContext(ctx context.Context, network, address string) (net.Conn, error)
if len(ips) == 0 {
return nil, errors.New("netguard: unresolved address")
}
if !AllowPrivate() {
if !AllowPrivate() && !TrustedHost(host) {
for _, a := range ips {
if !IsPublic(a.IP) {
return nil, errBlocked
+57
View File
@@ -111,3 +111,60 @@ func TestDialContextFallsBackAmongValidatedAddresses(t *testing.T) {
}
conn.Close()
}
// NETGUARD_TRUSTED_HOSTS pins operator-configured hostnames whose resolved
// addresses may be private (split-horizon house relays). The exemption is
// exact-match and case-insensitive, and never extends to other hosts.
func TestTrustedHost(t *testing.T) {
t.Setenv("NETGUARD_TRUSTED_HOSTS", "")
if TrustedHost("mail.example.tld") {
t.Fatal("empty variable must trust nothing")
}
t.Setenv("NETGUARD_TRUSTED_HOSTS", " Mail.Example.TLD , other.example.tld ")
if !TrustedHost("mail.example.tld") {
t.Fatal("pinned host was not trusted")
}
if !TrustedHost("OTHER.example.tld") {
t.Fatal("match must be case-insensitive")
}
if TrustedHost("evil.example.tld") || TrustedHost("") {
t.Fatal("unpinned/empty hosts must not be trusted")
}
if TrustedHost("mail.example.tld.evil.tld") {
t.Fatal("suffix tricks must not match")
}
}
// A pinned host reaches a private address without the global
// INTEGRATIONS_ALLOW_PRIVATE switch, while unpinned hosts stay blocked.
func TestDialContextTrustedHostBypass(t *testing.T) {
t.Setenv("INTEGRATIONS_ALLOW_PRIVATE", "")
ln, e := net.Listen("tcp4", "127.0.0.1:0")
if e != nil {
t.Skipf("no IPv4 loopback listener possible: %v", e)
}
defer ln.Close()
go func() {
for {
c, e := ln.Accept()
if e != nil {
return
}
c.Close()
}
}()
port := ln.Addr().(*net.TCPAddr).Port
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
t.Setenv("NETGUARD_TRUSTED_HOSTS", "localhost")
conn, e := DialContext(ctx, "tcp", fmt.Sprintf("localhost:%d", port))
if e != nil {
t.Fatalf("trusted host dial failed: %v", e)
}
conn.Close()
if _, e := DialContext(ctx, "tcp", fmt.Sprintf("127.0.0.1:%d", port)); e == nil {
t.Fatal("raw loopback IP must stay blocked while only 'localhost' is pinned")
}
}
+6 -2
View File
@@ -15,6 +15,8 @@ import (
"os"
"regexp"
"strings"
"github.com/andrew/superbrain/internal/config"
)
var placeholderPatterns = []*regexp.Regexp{
@@ -50,7 +52,9 @@ type OidcStatus struct {
Issuer *string
}
// Status returns the current OIDC configuration state.
// Status returns the current OIDC configuration state. AUTH_MODE=password
// disables OIDC regardless of the variables (multi-tenant shape: signup
// only, no Authelia); the identity bridge refuses provisioning to match.
func Status() OidcStatus {
issuerSet := isRealValue(os.Getenv("OIDC_ISSUER"))
clientIdSet := isRealValue(os.Getenv("OIDC_CLIENT_ID"))
@@ -61,7 +65,7 @@ func Status() OidcStatus {
issuer = &v
}
return OidcStatus{
Enabled: issuerSet && clientIdSet && clientSecretSet,
Enabled: config.AuthMode() != "password" && issuerSet && clientIdSet && clientSecretSet,
IssuerSet: issuerSet,
ClientIDSet: clientIdSet,
ClientSecretSet: clientSecretSet,
+94 -15
View File
@@ -2,6 +2,7 @@ package scripts
import (
"context"
"errors"
"fmt"
"github.com/andrew/superbrain/internal/db"
"golang.org/x/crypto/bcrypt"
@@ -9,28 +10,106 @@ import (
"strings"
)
// Seed only creates the requested account; it never clears existing records.
// Seed creates or links the requested operator account; it never clears
// existing records.
//
// SEED_EMAIL required
// SEED_PASSWORD password for a local login account
// SEED_SUBJECT optional Authelia subject to link (provider "authelia")
// SEED_NAME optional display name
//
// SEED_SUBJECT is the offline escape hatch for AUTH_MODE=oidc deployments
// (core/federated shape): password login is disabled there, so an operator
// cannot sign in to call POST /api/admin/oidc-link — and a pre-existing
// password account (e.g. one created by an earlier seed) makes the SSO
// bridge answer 409 "Account link required" instead of auto-linking by
// email. Linking from the CLI is deliberate operator action, which is the
// proof-of-ownership the email match alone can never provide.
//
// Combinations:
// - password only: classic local account (existing email: no-op).
// - subject only, or neither: password-less SSO account. In AUTH_MODE=oidc
// this is the correct operator seed — a password would be unusable
// (login is disabled) AND would block the SSO bridge's verified-email
// auto-link with a 409. With SEED_SUBJECT the link is explicit; without
// it, the first SSO login links by verified email match.
// - password + subject: local account that also accepts SSO.
//
// Role: ADMIN when SEED_EMAIL is listed in ADMIN_EMAILS, else USER. Idempotent
// for both the user row and the account link; a subject already linked to a
// DIFFERENT user is refused.
func Seed(ctx context.Context, d *db.DB) error {
email, password := strings.ToLower(strings.TrimSpace(os.Getenv("SEED_EMAIL"))), os.Getenv("SEED_PASSWORD")
if email == "" || password == "" {
return fmt.Errorf("SEED_EMAIL and SEED_PASSWORD are required")
subject := strings.TrimSpace(os.Getenv("SEED_SUBJECT"))
if email == "" {
return fmt.Errorf("SEED_EMAIL is required")
}
if len(subject) > 255 {
return fmt.Errorf("SEED_SUBJECT is too long")
}
repo := db.NewUserRepo(d)
if _, e := repo.FindByEmail(ctx, email); e == nil {
return nil
}
hash, e := bcrypt.GenerateFromPassword([]byte(password), 12)
if e != nil {
return e
}
name := os.Getenv("SEED_NAME")
if name == "" {
name = "Admin"
// Pre-flight: a subject already linked to a DIFFERENT account is refused
// before anything is created, so a bad SEED_SUBJECT never leaves an
// orphan user behind.
if subject != "" {
if u, e := repo.FindByAccount(ctx, "authelia", subject); e == nil {
if u.Email == nil || *u.Email != email {
return fmt.Errorf("subject is already linked to a different user")
}
fmt.Printf("subject already linked to %s; nothing to do\n", email)
return nil
} else if !errors.Is(e, db.ErrNotFound) {
return e
}
}
role := "USER"
if db.IsAdminEmail(email) {
role = "ADMIN"
}
_, e = repo.Create(ctx, &db.NewUserInput{ID: db.NewID(), Name: name, Email: email, Password: string(hash), Role: role})
return e
u, e := repo.FindByEmail(ctx, email)
if e != nil && !errors.Is(e, db.ErrNotFound) {
return e
}
if e == nil {
// Existing account: link the subject when asked, otherwise no-op.
if subject == "" {
return nil
}
if e := repo.LinkExternal(ctx, u.ID, "authelia", subject); e != nil {
if errors.Is(e, db.ErrAccountLinked) {
return fmt.Errorf("subject is already linked to a different user")
}
return e
}
fmt.Printf("linked authelia subject to existing account %s\n", email)
return nil
}
name := os.Getenv("SEED_NAME")
if name == "" {
name = "Admin"
}
in := &db.NewUserInput{ID: db.NewID(), Name: name, Email: email, Role: role}
if password == "" {
in.External = true // password-less: SSO only
} else {
hash, e := bcrypt.GenerateFromPassword([]byte(password), 12)
if e != nil {
return e
}
in.Password = string(hash)
}
if _, e := repo.Create(ctx, in); e != nil {
return e
}
if subject != "" {
if e := repo.LinkExternal(ctx, in.ID, "authelia", subject); e != nil {
if errors.Is(e, db.ErrAccountLinked) {
return fmt.Errorf("subject is already linked to a different user")
}
return e
}
}
return nil
}
+72
View File
@@ -0,0 +1,72 @@
'use client'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Link2, Mail } from 'lucide-react'
import Link from 'next/link'
import { toast } from 'sonner'
export function ForgotPasswordClient() {
const [email, setEmail] = useState('')
const [loading, setLoading] = useState(false)
const [sent, setSent] = useState(false)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setLoading(true)
try {
const res = await fetch('/api/password/forgot', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }),
})
const data = await res.json()
if (res.ok) {
// The server answer is deliberately identical for every address
// (no account enumeration), so the UI must not claim more than
// "if the account exists, a link is on its way".
setSent(true)
} else {
toast.error(data?.error ?? 'Could not send the reset link')
}
} catch {
toast.error('Could not send the reset link')
}
setLoading(false)
}
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<div className="w-full max-w-sm space-y-8">
<div className="text-center">
<div className="flex justify-center mb-4">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
<Link2 className="h-7 w-7" />
</div>
</div>
<h1 className="font-display text-3xl font-bold tracking-tight">Reset Password</h1>
<p className="text-sm text-muted-foreground mt-2">
{sent
? 'If that email has an account, a reset link is on its way. Check your inbox.'
: 'Enter your account email and we will send you a reset link.'}
</p>
</div>
{!sent && (
<form onSubmit={handleSubmit} className="space-y-3">
<div className="relative">
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input type="email" placeholder="Email" value={email} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)} className="pl-10" required />
</div>
<Button type="submit" className="w-full" loading={loading}>Send Reset Link</Button>
</form>
)}
<p className="text-center text-xs text-muted-foreground">
Remembered it? <Link href="/login" className="text-primary hover:underline">Back to sign in</Link>
</p>
</div>
</div>
)
}
+14
View File
@@ -0,0 +1,14 @@
import { ForgotPasswordClient } from './client'
import { auth } from '@/auth'
import { redirect } from 'next/navigation'
import { passwordAuthEnabled } from '@/lib/oidc-config'
export const dynamic = 'force-dynamic'
export default async function ForgotPasswordPage() {
// SSO-only deployments have no local passwords; Authelia owns recovery.
if (!passwordAuthEnabled()) redirect('/login')
const session = await auth()
if (session?.user) redirect('/pages')
return <ForgotPasswordClient />
}
+16 -2
View File
@@ -9,7 +9,7 @@ import Link from 'next/link'
import { toast } from 'sonner'
import { useRouter } from 'next/navigation'
export function LoginClient({ oidcEnabled }: { oidcEnabled: boolean }) {
export function LoginClient({ oidcEnabled, passwordEnabled }: { oidcEnabled: boolean; passwordEnabled: boolean }) {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)
@@ -61,12 +61,21 @@ export function LoginClient({ oidcEnabled }: { oidcEnabled: boolean }) {
<Shield className="h-5 w-5" />
Sign in with Authelia
</Button>
{!oidcEnabled && (
{!oidcEnabled && passwordEnabled && (
<p className="text-center text-xs text-muted-foreground -mt-2">
Authelia single sign-on is not configured. Use email below.
</p>
)}
{!oidcEnabled && !passwordEnabled && (
<p className="text-center text-xs text-muted-foreground -mt-2">
This server is configured for Authelia single sign-on only, but
the OIDC variables are missing or placeholders. Ask the operator
to check AUTH_MODE / OIDC_* configuration.
</p>
)}
{passwordEnabled && (
<>
<div className="relative">
<div className="absolute inset-0 flex items-center"><div className="w-full border-t" /></div>
<div className="relative flex justify-center text-xs"><span className="bg-background px-2 text-muted-foreground">or continue with email</span></div>
@@ -95,6 +104,9 @@ export function LoginClient({ oidcEnabled }: { oidcEnabled: boolean }) {
required
/>
</div>
<div className="text-right">
<Link href="/forgot-password" className="text-xs text-muted-foreground hover:text-primary hover:underline">Forgot password?</Link>
</div>
<Button type="submit" variant="outline" className="w-full" loading={loading}>
Sign in with Email
</Button>
@@ -103,6 +115,8 @@ export function LoginClient({ oidcEnabled }: { oidcEnabled: boolean }) {
<p className="text-center text-xs text-muted-foreground">
Don't have an account? <Link href="/signup" className="text-primary hover:underline">Sign up</Link>
</p>
</>
)}
</div>
</div>
</div>
+2 -2
View File
@@ -1,12 +1,12 @@
import { LoginClient } from './client'
import { auth } from '@/auth'
import { redirect } from 'next/navigation'
import { getOidcStatus } from '@/lib/oidc-config'
import { getOidcStatus, passwordAuthEnabled } from '@/lib/oidc-config'
export const dynamic = 'force-dynamic'
export default async function LoginPage() {
const session = await auth()
if (session?.user) redirect('/pages')
return <LoginClient oidcEnabled={getOidcStatus().enabled} />
return <LoginClient oidcEnabled={getOidcStatus().enabled} passwordEnabled={passwordAuthEnabled()} />
}
+100
View File
@@ -0,0 +1,100 @@
'use client'
import { useState } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Link2, Lock } from 'lucide-react'
import Link from 'next/link'
import { toast } from 'sonner'
export function ResetPasswordClient() {
const params = useSearchParams()
const token = params.get('token') ?? ''
const router = useRouter()
const [password, setPassword] = useState('')
const [confirm, setConfirm] = useState('')
const [loading, setLoading] = useState(false)
const [done, setDone] = useState(false)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
// Mirror the server's signup-identical policy (min 8 chars).
if (password.length < 8) { toast.error('Password must be at least 8 characters'); return }
if (password !== confirm) { toast.error('Passwords do not match'); return }
setLoading(true)
try {
const res = await fetch('/api/password/reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, password }),
})
const data = await res.json()
if (res.ok) {
setDone(true)
toast.success('Password updated. Sign in with your new password.')
router.push('/login')
} else {
toast.error(data?.error ?? 'Could not reset the password')
}
} catch {
toast.error('Could not reset the password')
}
setLoading(false)
}
if (!token || done) {
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<div className="w-full max-w-sm space-y-8 text-center">
<div className="flex justify-center mb-4">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
<Link2 className="h-7 w-7" />
</div>
</div>
<h1 className="font-display text-3xl font-bold tracking-tight">Reset Password</h1>
<p className="text-sm text-muted-foreground mt-2">
This reset link is invalid or has already been used. Request a fresh one to continue.
</p>
<p className="text-center text-xs text-muted-foreground">
<Link href="/forgot-password" className="text-primary hover:underline">Request a new link</Link>
{' · '}
<Link href="/login" className="text-primary hover:underline">Back to sign in</Link>
</p>
</div>
</div>
)
}
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<div className="w-full max-w-sm space-y-8">
<div className="text-center">
<div className="flex justify-center mb-4">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
<Link2 className="h-7 w-7" />
</div>
</div>
<h1 className="font-display text-3xl font-bold tracking-tight">Choose a New Password</h1>
<p className="text-sm text-muted-foreground mt-2">Resetting signs out every other device.</p>
</div>
<form onSubmit={handleSubmit} className="space-y-3">
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input type="password" placeholder="New password (min 8 chars)" value={password} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)} className="pl-10" minLength={8} required autoFocus />
</div>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input type="password" placeholder="Confirm new password" value={confirm} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setConfirm(e.target.value)} className="pl-10" minLength={8} required />
</div>
<Button type="submit" className="w-full" loading={loading}>Update Password</Button>
</form>
<p className="text-center text-xs text-muted-foreground">
<Link href="/login" className="text-primary hover:underline">Back to sign in</Link>
</p>
</div>
</div>
)
}
+20
View File
@@ -0,0 +1,20 @@
import { ResetPasswordClient } from './client'
import { auth } from '@/auth'
import { redirect } from 'next/navigation'
import { passwordAuthEnabled } from '@/lib/oidc-config'
import { Suspense } from 'react'
export const dynamic = 'force-dynamic'
export default async function ResetPasswordPage() {
// SSO-only deployments have no local passwords; Authelia owns recovery.
if (!passwordAuthEnabled()) redirect('/login')
const session = await auth()
if (session?.user) redirect('/pages')
// useSearchParams in the client needs a Suspense boundary for prerender.
return (
<Suspense>
<ResetPasswordClient />
</Suspense>
)
}
+4
View File
@@ -1,8 +1,12 @@
import { SignupClient } from './client'
import { auth } from '@/auth'
import { redirect } from 'next/navigation'
import { passwordAuthEnabled } from '@/lib/oidc-config'
export default async function SignupPage() {
// AUTH_MODE=oidc: accounts are provisioned upstream (e.g. Superpanel ->
// LDAP -> Authelia -> SSO), never by self-service signup.
if (!passwordAuthEnabled()) redirect('/login')
const session = await auth()
if (session?.user) redirect('/pages')
return <SignupClient />
+6 -3
View File
@@ -2,7 +2,7 @@ import NextAuth, { CredentialsSignin } from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import jwt from 'jsonwebtoken'
import { createHmac } from 'node:crypto'
import { getOidcStatus } from '@/lib/oidc-config'
import { getOidcStatus, passwordAuthEnabled } from '@/lib/oidc-config'
// Review SEC-2: browser IP attestation for Go's rate limiting (see lib/api.ts
// for the identical semantics used by the data proxy). Duplicated here to keep
@@ -96,7 +96,10 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
email: profile.email, image: profile.picture ?? null }
},
} as any] : []),
CredentialsProvider({
// AUTH_MODE=oidc (core/federated shape): the credentials provider is not
// registered at all — Go refuses /api/auth/login there too, so this is
// defense in depth, not the only barrier.
...(passwordAuthEnabled() ? [CredentialsProvider({
credentials: { email: { label: 'Email', type: 'email' }, password: { label: 'Password', type: 'password' } },
async authorize(credentials, request) {
if (!credentials?.email || !credentials?.password) return null
@@ -141,7 +144,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
// everywhere") — review SEC-02.
return { ...data.user, tokenVersion: data.tokenVersion }
},
}),
})] : []),
],
callbacks: {
async signIn({ account }) {
+52 -8
View File
@@ -3,7 +3,9 @@
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.
remains available as a fallback in the default `AUTH_MODE=both`; see §7 for
the Authelia-only (`AUTH_MODE=oidc`) and password-only (`AUTH_MODE=password`)
deployment shapes.
This guide covers the Authelia client configuration and how the identity bridge
maps a verified subject to the PostgreSQL users that Go authorizes.
@@ -204,7 +206,7 @@ a local user ID.
| Symptom | Likely cause |
|---|---|
| Config says Not connected | One of the variables is empty or a placeholder, or containers were not recreated after editing `.env` |
| NextAuth returns AccessDenied | The Go identity bridge rejected the exchange; check the Go logs for `oidc provision` or a `409 Account link required` |
| NextAuth returns AccessDenied | The Go identity bridge rejected the exchange. The **web** container logs `oidc provision: Go answered <status>`: `409` = local password account needs explicit linking; `400` = missing subject/email (client lacks a `claims_policy`, so Authelia kept `email` out of the ID token) or an issuer mismatch between the web and app containers |
| 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` |
| Authelia logs "The state is missing or does not have enough characters" | Auth.js omits `state` for OIDC providers by default (PKCE-only); the provider must set `checks: ['pkce', 'state']` (it does — don't remove it) |
@@ -212,10 +214,52 @@ a local user ID.
| Required identity claims are missing | Check Authelia's claims policy and user profile |
| Browser has a session, but Go returns 401 | Check that the session ID is the resolved local `User.id`, not the OIDC subject |
## 7. Optional: Authelia-only login
## 7. Deployment tiers and auth modes
Email/password remains as a fallback. An Authelia-only deployment requires
disabling the credentials provider, local login/signup screens, and local
signup/login endpoints in both Next.js and Go, while preserving the trusted
OIDC identity-provisioning path. Hiding the email form alone does not disable
the backend password login routes.
Deployments have a product tier: `TIER=core` (federated install for paying
customers — Authelia exclusively) or `TIER=multi` (hosted self-service —
signup, password login, self-reset). The tier derives the mechanism-level
variables; an explicitly set variable always wins. `AUTH_MODE` selects the
authentication personality directly. Go enforces everything at the API; the
web UI follows (hiding a form is never the only barrier):
| Mode | Password login | Signup | Password reset | Authelia OIDC |
|---|---|---|---|---|
| `both` (default, no tier) | ✅ | ✅ (`SIGNUP_ENABLED`) | ✅ (needs `SMTP_*`) | ✅ when the three `OIDC_*` vars are real |
| `password` (`TIER=multi`) | ✅ | ✅ (`SIGNUP_ENABLED`) | ✅ (needs `SMTP_*`) | ⛔ disabled even with `OIDC_*` set |
| `oidc` (`TIER=core`) | ⛔ 403 | ⛔ 403 | ⛔ 403 | ✅ required |
`TIER=core` additionally defaults `SIGNUP_ENABLED` and
`ALLOW_BOOTSTRAP_SIGNUP` to off (accounts are provisioned upstream, e.g.
Superpanel → LDAP → Authelia). `TIER=multi` keeps the historical defaults.
The multi tier is intended to grow organization-level tenancy (memberships,
per-tenant admin/billing) — decided 2026-10-26, not built yet.
In `oidc` mode:
- The credentials provider is not registered in NextAuth, `/signup`,
`/forgot-password` and `/reset-password` redirect to `/login`, and Go
refuses `POST /api/auth/login`, `POST /api/signup` and the password-reset
endpoints. The OIDC identity bridge is the only way in.
- Accounts are provisioned upstream (on the federated core: Superpanel →
LDAP → Authelia) and materialize locally on first SSO login.
- Admin bootstrap: an address listed in `ADMIN_EMAILS` becomes ADMIN at its
first SSO login; everyone else is USER.
- The operator account can be seeded password-less
(`SEED_EMAIL=... /superbrain --seed`). Do NOT seed a password in this
mode: it is unusable (login is disabled) and it blocks the SSO bridge's
verified-email auto-link with `409 Account link required`.
- Pre-existing password accounts (e.g. from before a mode switch) must be
linked deliberately — email match alone is not proof. With login disabled
nobody can obtain the admin session `POST /api/admin/oidc-link` requires,
so use the offline path:
`docker exec -e SEED_EMAIL=<email> -e SEED_SUBJECT=<authelia sub> superbrain-app /superbrain --seed`
(idempotent; refuses subjects already linked to a different user).
In `password` mode the bridge (`POST /api/auth/oidc/identity`) is refused
even with a valid service token, and the status endpoint reports OIDC
disabled so the UI hides Authelia.
Unknown `AUTH_MODE` values fail startup (`Validate`) instead of silently
falling back to `both` — a typo must never re-enable password login on an
SSO-only deployment.
+40 -1
View File
@@ -28,12 +28,51 @@ export interface OidcStatus {
issuer: string | null
}
/**
* TIER is the product tier (mirrors Go's config.Tier):
* core Authelia-only install for paying customers (derives AUTH_MODE=oidc)
* multi hosted self-service install (derives AUTH_MODE=password)
* An explicit AUTH_MODE always wins over the tier default, exactly like Go.
*/
export type Tier = 'core' | 'multi' | ''
export function getTier(): Tier {
const t = (process.env.TIER ?? '').trim().toLowerCase()
return t === 'core' || t === 'multi' ? t : ''
}
/**
* AUTH_MODE is the deployment's authentication personality (mirrors Go's
* config.AuthMode; Go enforces the same rules server-side):
* both (default) password login/signup + Authelia coexist
* password multi-tenant shape: signup/password login only, OIDC disabled
* even when the OIDC_* variables hold real values
* oidc core/federated shape: Authelia only; the credentials provider
* is not registered and signup/reset pages redirect to /login
*/
export type AuthMode = 'both' | 'password' | 'oidc'
export function getAuthMode(): AuthMode {
const m = (process.env.AUTH_MODE ?? '').trim().toLowerCase()
if (m === 'password' || m === 'oidc' || m === 'both') return m
switch (getTier()) {
case 'core': return 'oidc'
case 'multi': return 'password'
default: return 'both'
}
}
/** Whether email/password authentication (login, signup, reset) is offered. */
export function passwordAuthEnabled(): boolean {
return getAuthMode() !== 'oidc'
}
export function getOidcStatus(): OidcStatus {
const issuerSet = isRealValue(process.env.OIDC_ISSUER)
const clientIdSet = isRealValue(process.env.OIDC_CLIENT_ID)
const clientSecretSet = isRealValue(process.env.OIDC_CLIENT_SECRET)
return {
enabled: issuerSet && clientIdSet && clientSecretSet,
enabled: getAuthMode() !== 'password' && issuerSet && clientIdSet && clientSecretSet,
issuerSet,
clientIdSet,
clientSecretSet,