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