diff --git a/.env.example b/.env.example index e45538562..0c173671e 100644 --- a/.env.example +++ b/.env.example @@ -85,11 +85,6 @@ # Default: 0 # FANOUT_DUCKDB_THREADS= -# FANOUT_FIRST_ADMIN_EMAIL; string -# Creates this address as the first active administrator when the control database has no users, instead of printing the one-time setup URL; ignored once users exist. -# Default: (empty) -# FANOUT_FIRST_ADMIN_EMAIL= - # FANOUT_HEALTHCHECK_CERT_FILE; string # Selects the client certificate fanout healthcheck presents; requires FANOUT_HEALTHCHECK_KEY_FILE and FANOUT_TLS_CLIENT_CA_FILE. # Default: (empty) diff --git a/README.md b/README.md index 62c2b08dd..17d33d14e 100644 --- a/README.md +++ b/README.md @@ -39,9 +39,7 @@ docker run --name fanout --restart unless-stopped -p 7520:7520 \ ``` Open the one-time setup URL printed by the container and create the first administrator. Fanout -displays the ingest token exactly once; save it with your collector secrets. To skip the setup URL, -set `FANOUT_FIRST_ADMIN_EMAIL` and issue the first ingest token after signing in; see -[first boot](https://fanout.run/docs/get-started/first-boot). For later sign-in +displays the ingest token exactly once; save it with your collector secrets. For later sign-in without SMTP, mint a 15-minute, single-use link against the running container's control database: ```sh diff --git a/cmd/fanout/main.go b/cmd/fanout/main.go index ecabd0569..6e8c83453 100644 --- a/cmd/fanout/main.go +++ b/cmd/fanout/main.go @@ -205,12 +205,12 @@ func main() { auditStore := auth.NewAuditStore(sqlite.DB) setup := auth.NewSetup() - setupRequired, err := prepareFirstAdministrator(cfg.FirstAdminEmail, userStore) + userCount, err := userStore.CountUsers() if err != nil { slog.Error("auth status init failed", "err", err) os.Exit(1) } - if setupRequired { + if userCount == 0 { token, _, err := setup.Rotate() if err != nil { slog.Error("setup token init failed", "err", err) @@ -724,34 +724,6 @@ func browserLoginURL(cfg config.Config) *url.URL { return loginURL } -// prepareFirstAdministrator applies FANOUT_FIRST_ADMIN_EMAIL and reports whether the -// control database still has no users, in which case the caller opens the -// one-time setup URL. The administrator is created only in an empty database; once -// any user exists the setting never creates, promotes or reactivates anyone. -func prepareFirstAdministrator(firstAdminEmail string, users *auth.UserStore) (bool, error) { - if firstAdminEmail != "" { - firstAdmin, outcome, err := users.DesignateFirstAdmin(firstAdminEmail) - if err != nil { - return false, fmt.Errorf("designate first administrator from FANOUT_FIRST_ADMIN_EMAIL: %w", err) - } - switch outcome { - case auth.FirstAdminCreated: - slog.Info("auth: first administrator created from FANOUT_FIRST_ADMIN_EMAIL; no setup URL is issued", "email", firstAdmin.Email) - case auth.FirstAdminPresent: - if firstAdmin.Role != auth.RoleAdmin || firstAdmin.Status != auth.UserStatusActive { - slog.Warn("auth: FANOUT_FIRST_ADMIN_EMAIL names an existing account that is not an active administrator; it was left unchanged", "email", firstAdmin.Email, "role", firstAdmin.Role, "status", firstAdmin.Status) - } - case auth.FirstAdminRefused: - slog.Warn("auth: FANOUT_FIRST_ADMIN_EMAIL ignored; the control database already has users and none has this email, so no account was created. Unset it, or have an administrator add the account", "email", firstAdmin.Email) - } - } - count, err := users.CountUsers() - if err != nil { - return false, err - } - return count == 0, nil -} - func printSetupBanner(httpAddr, token string) { lines := []string{ "============================================================", diff --git a/cmd/fanout/main_test.go b/cmd/fanout/main_test.go index 04e28dcaf..a91915d73 100644 --- a/cmd/fanout/main_test.go +++ b/cmd/fanout/main_test.go @@ -13,7 +13,6 @@ import ( "errors" "flag" "io" - "log/slog" "math/big" "net" "net/http" @@ -220,92 +219,6 @@ func TestCreateLoginLink(t *testing.T) { } } -func TestPrepareFirstAdministratorWithoutFirstAdminEmailKeepsSetup(t *testing.T) { - sqlite, err := store.NewSQLite(":memory:") - if err != nil { - t.Fatalf("NewSQLite: %v", err) - } - defer sqlite.Close() - users := auth.NewUserStore(sqlite.DB) - setupRequired, err := prepareFirstAdministrator("", users) - if err != nil || !setupRequired { - t.Fatalf("prepareFirstAdministrator = (%v, %v), want (true, nil)", setupRequired, err) - } - if count, _ := users.CountUsers(); count != 0 { - t.Fatalf("users = %d, want 0", count) - } -} - -func TestPrepareFirstAdministratorCreatesAdministratorWhoCanUseLoginLink(t *testing.T) { - cfg := config.Config{ - AuthMode: "local", - AuthCodeSecret: "0123456789abcdef0123456789abcdef", - DataDir: t.TempDir(), - Addr: ":7520", - FirstAdminEmail: "First@Example.com", - } - if err := os.MkdirAll(cfg.ControlDir(), 0o755); err != nil { - t.Fatalf("MkdirAll: %v", err) - } - sqlite, err := store.NewSQLite(cfg.ControlSQLitePath()) - if err != nil { - t.Fatalf("NewSQLite: %v", err) - } - users := auth.NewUserStore(sqlite.DB) - setupRequired, err := prepareFirstAdministrator(cfg.FirstAdminEmail, users) - if err != nil || setupRequired { - t.Fatalf("prepareFirstAdministrator = (%v, %v), want (false, nil)", setupRequired, err) - } - firstAdmin, err := users.GetByEmail("first@example.com") - if err != nil || firstAdmin.Role != auth.RoleAdmin || firstAdmin.Status != auth.UserStatusActive { - t.Fatalf("firstAdmin = %+v err = %v, want active admin", firstAdmin, err) - } - // A restart with the same setting is a no-op, and still issues no setup URL. - setupRequired, err = prepareFirstAdministrator(cfg.FirstAdminEmail, users) - if err != nil || setupRequired { - t.Fatalf("restart prepareFirstAdministrator = (%v, %v), want (false, nil)", setupRequired, err) - } - if count, _ := users.CountUsers(); count != 1 { - t.Fatalf("users = %d, want 1", count) - } - if err := sqlite.Close(); err != nil { - t.Fatalf("Close: %v", err) - } - var output bytes.Buffer - if err := createLoginLink(cfg, "first@example.com", &output); err != nil { - t.Fatalf("createLoginLink for first administrator: %v", err) - } - if !strings.Contains(output.String(), "login_token=") { - t.Fatalf("login link output = %q", output.String()) - } -} - -func TestPrepareFirstAdministratorRefusesDifferentAddress(t *testing.T) { - sqlite, err := store.NewSQLite(":memory:") - if err != nil { - t.Fatalf("NewSQLite: %v", err) - } - defer sqlite.Close() - users := auth.NewUserStore(sqlite.DB) - if _, err := users.CreateFirstAdminWithAudit("admin@example.com", "", auth.AuditEvent{EventType: "setup.completed", Outcome: "success"}); err != nil { - t.Fatalf("CreateFirstAdmin: %v", err) - } - var logs bytes.Buffer - previous := slog.Default() - slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) - setupRequired, err := prepareFirstAdministrator(" First@Example.com", users) - slog.SetDefault(previous) - if err != nil || setupRequired { - t.Fatalf("prepareFirstAdministrator = (%v, %v), want (false, nil)", setupRequired, err) - } - if _, err := users.GetByEmail("first@example.com"); !errors.Is(err, auth.ErrUserNotFound) { - t.Fatalf("different address lookup err = %v, want ErrUserNotFound", err) - } - if out := logs.String(); !strings.Contains(out, "level=WARN") || !strings.Contains(out, "FANOUT_FIRST_ADMIN_EMAIL ignored") || !strings.Contains(out, "email=first@example.com") { - t.Fatalf("refusal log = %q, want a warning naming first@example.com", out) - } -} - func TestHealthcheckURL(t *testing.T) { for _, tc := range []struct{ addr, cert, want string }{ {"", "", "http://127.0.0.1:7520/healthz"}, diff --git a/docs/authentication.md b/docs/authentication.md index c145f8b8b..81e58cce3 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -40,33 +40,6 @@ Setup credential behavior: > screen — can hold it until the credential is consumed or expires. Treat a > leaked banner as a compromised installation and rebuild the database. -### First administrator email instead of a setup URL - -Set `FANOUT_FIRST_ADMIN_EMAIL` to create the first administrator without a setup URL. -When the user count is zero at startup, Fanout creates that address as an -active `admin`, records a `setup.completed` audit event with -`source: first_admin_email`, and prints no banner. The address is validated -when configuration loads. The setting takes effect only on first start with an -empty database. The account is a regular, permanent administrator; changing or -removing the setting later has no effect. - -- It creates an account only in an empty control database, under the same - transactional check as interactive setup. -- With users present it creates nothing. A matching account is left as it is; - if that account is not an active administrator, Fanout logs a warning. A - different address is refused with a warning, and no account is created. -- No ingest token is issued at startup. The administrator issues the first one from - **Connect telemetry → Ingest token** or `POST /api/settings/ingest/token/rotate`. - Ingest stays closed until then. - -> [!WARNING] -> Until the first administrator signs in, whoever first proves control of that address -> claims the administrator account: anyone who can read its mailbox in local -> mode, or any identity provider account that asserts that email in OIDC mode. -> Use an address you control, sign in promptly after first boot, and in OIDC -> mode confirm that the account's `identity.linked` audit event (in the control -> database's `auth_audit_events` table) came from your own sign-in. - ### Before you complete setup Local mode requires only a 32-character `FANOUT_AUTH_CODE_SECRET`. SMTP is @@ -89,11 +62,7 @@ successfully verified. The role is fixed: self-signup can never create an operator or administrator. The setting requires complete SMTP configuration and local auth mode. -Self-signup remains unavailable until the first administrator exists. An -administrator created from `FANOUT_FIRST_ADMIN_EMAIL` counts, so with that -setting self-signup opens at first boot, before that administrator has signed -in. It still creates only viewers and cannot claim the administrator's address, -which already belongs to an account. +Self-signup remains unavailable until the first administrator completes setup. Suspended accounts are not recreated or reactivated. Public installations should enforce traffic and AI-budget limits at the deployment edge; Fanout also retains its per-IP, per-address, expiry, and attempt limits described below. diff --git a/internal/api/oidc_test.go b/internal/api/oidc_test.go index 13d429c1a..a0ffecee2 100644 --- a/internal/api/oidc_test.go +++ b/internal/api/oidc_test.go @@ -131,32 +131,20 @@ func TestSafeReturnTo(t *testing.T) { } } -// testOIDCProvider is a minimal OpenID provider for driving the real start and -// callback handlers. It issues one RS256 ID token per token exchange for the -// configured email and groups, bound to the nonce from the last start. -type testOIDCProvider struct { - issuer string - email string - groups []string - nonce string - challenge string - pkceVerified bool -} - -func newTestOIDCProvider(t *testing.T, email string) *testOIDCProvider { - t.Helper() +func TestOIDCFlowValidatesPKCENonceAndCreatesSession(t *testing.T) { key, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { t.Fatalf("generate signing key: %v", err) } - p := &testOIDCProvider{email: email} + var issuer, issuedNonce, expectedChallenge string + var pkceVerified bool idp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.URL.Path { case "/.well-known/openid-configuration": _ = json.NewEncoder(w).Encode(map[string]any{ - "issuer": p.issuer, "authorization_endpoint": p.issuer + "/authorize", "token_endpoint": p.issuer + "/token", - "jwks_uri": p.issuer + "/keys", "response_types_supported": []string{"code"}, + "issuer": issuer, "authorization_endpoint": issuer + "/authorize", "token_endpoint": issuer + "/token", + "jwks_uri": issuer + "/keys", "response_types_supported": []string{"code"}, "subject_types_supported": []string{"public"}, "id_token_signing_alg_values_supported": []string{"RS256"}, "token_endpoint_auth_methods_supported": []string{"client_secret_basic"}, }) @@ -174,14 +162,11 @@ func newTestOIDCProvider(t *testing.T, email string) *testOIDCProvider { } verifier := r.Form.Get("code_verifier") digest := sha256.Sum256([]byte(verifier)) - p.pkceVerified = verifier != "" && base64.RawURLEncoding.EncodeToString(digest[:]) == p.challenge + pkceVerified = verifier != "" && base64.RawURLEncoding.EncodeToString(digest[:]) == expectedChallenge claims := jwt.MapClaims{ - "iss": p.issuer, "sub": "subject-1", "aud": "fanout-client", + "iss": issuer, "sub": "subject-1", "aud": "fanout-client", "exp": time.Now().Add(time.Minute).Unix(), "iat": time.Now().Add(-time.Second).Unix(), - "nonce": p.nonce, "email": p.email, "email_verified": true, - } - if p.groups != nil { - claims["groups"] = p.groups + "nonce": issuedNonce, "email": "admin@example.com", "email_verified": true, } idToken := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) idToken.Header["kid"] = "test-key" @@ -198,17 +183,33 @@ func newTestOIDCProvider(t *testing.T, email string) *testOIDCProvider { http.NotFound(w, r) } })) - t.Cleanup(idp.Close) - p.issuer = idp.URL - return p -} + defer idp.Close() + issuer = idp.URL + + db, err := appstore.NewSQLite(":memory:") + if err != nil { + t.Fatalf("NewSQLite: %v", err) + } + defer db.Close() + users := appauth.NewUserStore(db.DB) + user, err := users.CreateWithAudit("admin@example.com", "", "admin", appauth.AuditEvent{EventType: "user.created", Outcome: "success"}) + if err != nil { + t.Fatalf("create user: %v", err) + } + identities := appauth.NewIdentityStore(db.DB) + sessions := appauth.NewBrowserSessions(db.DB, 12*time.Hour, 7*24*time.Hour, false) + e := echo.New() + e.Use(echo.WrapMiddleware(sessions.Middleware)) + cfg := config.Config{ + AuthMode: "oidc", OIDCIssuerURL: issuer, OIDCClientID: "fanout-client", OIDCClientSecret: "client-secret", + PublicURL: "https://fanout.example.com", OIDCEmailVerification: "required", OIDCDefaultRole: "viewer", + } + if err := RegisterOIDCRoutes(context.Background(), e, cfg, users, identities, sessions, appauth.NewAuditStore(db.DB)); err != nil { + t.Fatalf("RegisterOIDCRoutes: %v", err) + } -// login runs /api/auth/oidc/start and then the callback with the issued state -// and pre-auth cookie, returning the callback response. -func (p *testOIDCProvider) login(t *testing.T, e *echo.Echo, returnTo string) *httptest.ResponseRecorder { - t.Helper() startRecorder := httptest.NewRecorder() - e.ServeHTTP(startRecorder, httptest.NewRequest(http.MethodGet, "/api/auth/oidc/start?return_to="+url.QueryEscape(returnTo), nil)) + e.ServeHTTP(startRecorder, httptest.NewRequest(http.MethodGet, "/api/auth/oidc/start?return_to=/dashboards", nil)) if startRecorder.Code != http.StatusFound { t.Fatalf("OIDC start status = %d, want 302: %s", startRecorder.Code, startRecorder.Body.String()) } @@ -217,60 +218,27 @@ func (p *testOIDCProvider) login(t *testing.T, e *echo.Echo, returnTo string) *h t.Fatalf("parse authorization redirect: %v", err) } state := authorizeURL.Query().Get("state") - p.nonce = authorizeURL.Query().Get("nonce") - p.challenge = authorizeURL.Query().Get("code_challenge") - if state == "" || p.nonce == "" || p.challenge == "" || authorizeURL.Query().Get("code_challenge_method") != "S256" { + issuedNonce = authorizeURL.Query().Get("nonce") + expectedChallenge = authorizeURL.Query().Get("code_challenge") + if state == "" || issuedNonce == "" || expectedChallenge == "" || authorizeURL.Query().Get("code_challenge_method") != "S256" { t.Fatalf("incomplete authorization redirect: %s", authorizeURL.String()) } cookies := startRecorder.Result().Cookies() if len(cookies) != 1 { t.Fatalf("pre-auth cookies = %d, want 1", len(cookies)) } + callback := httptest.NewRequest(http.MethodGet, "/api/auth/oidc/callback?code=authorization-code&state="+url.QueryEscape(state), nil) callback.AddCookie(cookies[0]) callbackRecorder := httptest.NewRecorder() e.ServeHTTP(callbackRecorder, callback) - return callbackRecorder -} - -func newOIDCCallbackServer(t *testing.T, cfg config.Config, db *appstore.SQLite) (*echo.Echo, *appauth.IdentityStore) { - t.Helper() - identities := appauth.NewIdentityStore(db.DB) - sessions := appauth.NewBrowserSessions(db.DB, 12*time.Hour, 7*24*time.Hour, false) - e := echo.New() - e.Use(echo.WrapMiddleware(sessions.Middleware)) - if err := RegisterOIDCRoutes(context.Background(), e, cfg, appauth.NewUserStore(db.DB), identities, sessions, appauth.NewAuditStore(db.DB)); err != nil { - t.Fatalf("RegisterOIDCRoutes: %v", err) - } - return e, identities -} - -func TestOIDCFlowValidatesPKCENonceAndCreatesSession(t *testing.T) { - idp := newTestOIDCProvider(t, "admin@example.com") - db, err := appstore.NewSQLite(":memory:") - if err != nil { - t.Fatalf("NewSQLite: %v", err) - } - defer db.Close() - users := appauth.NewUserStore(db.DB) - user, err := users.CreateWithAudit("admin@example.com", "", "admin", appauth.AuditEvent{EventType: "user.created", Outcome: "success"}) - if err != nil { - t.Fatalf("create user: %v", err) - } - cfg := config.Config{ - AuthMode: "oidc", OIDCIssuerURL: idp.issuer, OIDCClientID: "fanout-client", OIDCClientSecret: "client-secret", - PublicURL: "https://fanout.example.com", OIDCEmailVerification: "required", OIDCDefaultRole: "viewer", - } - e, identities := newOIDCCallbackServer(t, cfg, db) - - callbackRecorder := idp.login(t, e, "/dashboards") if callbackRecorder.Code != http.StatusFound || callbackRecorder.Header().Get("Location") != "/dashboards" { t.Fatalf("OIDC callback = %d location %q: %s", callbackRecorder.Code, callbackRecorder.Header().Get("Location"), callbackRecorder.Body.String()) } - if !idp.pkceVerified { + if !pkceVerified { t.Fatal("token exchange did not present the PKCE verifier from the pre-auth session") } - identity, err := identities.Find(t.Context(), idp.issuer, "subject-1") + identity, err := identities.Find(t.Context(), issuer, "subject-1") if err != nil || identity.UserID != user.ID { t.Fatalf("linked identity = %+v, err %v", identity, err) } @@ -283,54 +251,6 @@ func TestOIDCFlowValidatesPKCENonceAndCreatesSession(t *testing.T) { } } -// An administrator designated by FANOUT_FIRST_ADMIN_EMAIL has no linked identity until the -// first OIDC sign-in. That sign-in must link by verified email, audit the -// link, and keep the account an administrator even when the group mapping would -// demote it, because it is the only active administrator. -func TestOIDCCallbackLinksDesignatedFirstAdministrator(t *testing.T) { - idp := newTestOIDCProvider(t, "First@Example.com") - idp.groups = []string{"staff"} - db, err := appstore.NewSQLite(":memory:") - if err != nil { - t.Fatalf("NewSQLite: %v", err) - } - defer db.Close() - users := appauth.NewUserStore(db.DB) - firstAdmin, outcome, err := users.DesignateFirstAdmin("first@example.com") - if err != nil || outcome != appauth.FirstAdminCreated { - t.Fatalf("DesignateFirstAdmin = (%v, %v)", outcome, err) - } - cfg := config.Config{ - AuthMode: "oidc", OIDCIssuerURL: idp.issuer, OIDCClientID: "fanout-client", OIDCClientSecret: "client-secret", - PublicURL: "https://fanout.example.com", OIDCEmailVerification: "required", OIDCDefaultRole: "viewer", - OIDCAdminGroups: "fanout-admins", OIDCOperatorGroups: "fanout-operators", - } - e, identities := newOIDCCallbackServer(t, cfg, db) - - callbackRecorder := idp.login(t, e, "/") - if callbackRecorder.Code != http.StatusFound || callbackRecorder.Header().Get("Location") != "/" { - t.Fatalf("OIDC callback = %d location %q: %s", callbackRecorder.Code, callbackRecorder.Header().Get("Location"), callbackRecorder.Body.String()) - } - identity, err := identities.Find(t.Context(), idp.issuer, "subject-1") - if err != nil || identity.UserID != firstAdmin.ID { - t.Fatalf("linked identity = %+v, err %v; want first administrator %s", identity, err, firstAdmin.ID) - } - after, err := users.GetByID(firstAdmin.ID) - if err != nil || after.Role != appauth.RoleAdmin || after.Status != appauth.UserStatusActive { - t.Fatalf("first administrator after OIDC login = %+v err %v, want active admin", after, err) - } - var linked, roleChanges int - if err := db.DB.QueryRow(`SELECT COUNT(*) FROM auth_audit_events WHERE event_type = 'identity.linked' AND actor_user_id = ?`, firstAdmin.ID).Scan(&linked); err != nil { - t.Fatalf("count identity.linked: %v", err) - } - if err := db.DB.QueryRow(`SELECT COUNT(*) FROM auth_audit_events WHERE event_type = 'role.changed'`).Scan(&roleChanges); err != nil { - t.Fatalf("count role.changed: %v", err) - } - if linked != 1 || roleChanges != 0 { - t.Fatalf("identity.linked = %d role.changed = %d, want 1 and 0", linked, roleChanges) - } -} - func TestOIDCCallbackRejectsInvalidIdentityTokensAndProvisioning(t *testing.T) { cases := []struct { name string diff --git a/internal/api/settings_test.go b/internal/api/settings_test.go index 36b6f27ba..3751d2a20 100644 --- a/internal/api/settings_test.go +++ b/internal/api/settings_test.go @@ -61,57 +61,6 @@ func TestRotateIngestToken_PersistsHashReturnsPlaintext(t *testing.T) { } } -// An administrator created from FANOUT_FIRST_ADMIN_EMAIL never runs interactive setup, so -// the first ingest token comes from the rotate action on an empty setting. -func TestRotateIngestToken_IssuesFirstTokenForDesignatedAdministrator(t *testing.T) { - s, store := newConfigServer(t, config.Config{Addr: ":7520"}) - firstAdmin, _, err := s.users.DesignateFirstAdmin("first@example.com") - if err != nil { - t.Fatalf("DesignateFirstAdmin: %v", err) - } - cookie := s.login(t, firstAdmin) - read := func() ingestResponse { - t.Helper() - rec := httptest.NewRecorder() - s.e.ServeHTTP(rec, sessionRequest(http.MethodGet, "/api/settings/ingest", nil, cookie)) - if rec.Code != http.StatusOK { - t.Fatalf("GET status = %d %s", rec.Code, rec.Body.String()) - } - var resp ingestResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - return resp - } - if read().TokenRequired { - t.Fatal("designated administrator database already has an ingest token") - } - rec := httptest.NewRecorder() - req := sessionRequest(http.MethodPost, "/api/settings/ingest/token/rotate", nil, cookie) - s.e.ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf("rotate status = %d %s", rec.Code, rec.Body.String()) - } - var resp ingestResponse - if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - current, err := store.GetIngest(req.Context()) - if err != nil || !resp.TokenRequired || !settings.CheckIngestToken(resp.IngestToken, current.TokenHash) { - t.Fatalf("response=%+v current=%+v err=%v", resp, current, err) - } - if !read().TokenRequired { - t.Fatal("token_required is false after the first token was issued") - } - var events int - if err := s.db.DB.QueryRow(`SELECT COUNT(*) FROM auth_audit_events WHERE event_type = 'ingest_key.rotated' AND actor_user_id = ?`, firstAdmin.ID).Scan(&events); err != nil { - t.Fatalf("query audit: %v", err) - } - if events != 1 { - t.Fatalf("ingest audit events = %d, want 1", events) - } -} - func TestIngestSettingsCapabilities(t *testing.T) { s, _ := newConfigServer(t, config.Config{Addr: ":7520"}) viewer, _ := s.users.CreateWithAudit("viewer@example.com", "", "viewer", auth.AuditEvent{EventType: "user.created", Outcome: "success"}) diff --git a/internal/auth/first_admin.go b/internal/auth/first_admin.go deleted file mode 100644 index bbc318505..000000000 --- a/internal/auth/first_admin.go +++ /dev/null @@ -1,58 +0,0 @@ -package auth - -import ( - "errors" -) - -// FirstAdminOutcome reports what DesignateFirstAdmin did with a configured -// first administrator email. -type FirstAdminOutcome int - -const ( - // FirstAdminUnknown is the zero value, returned with every error: nothing - // is known about the account and no outcome should be acted on. - FirstAdminUnknown FirstAdminOutcome = iota - // FirstAdminCreated means the control database had no users and the - // address was created as an active administrator. - FirstAdminCreated - // FirstAdminPresent means users already existed and one of them has the - // configured email. The account is returned unchanged, whatever its role or status. - FirstAdminPresent - // FirstAdminRefused means users already existed and none has the - // configured email. - // Nothing was created: the setting designates only the first administrator. - FirstAdminRefused -) - -// DesignateFirstAdmin creates the first administrator from a configured -// email. It creates an account only when the control database holds no users, -// using the same transactional check as interactive setup, so it can never -// add a second administrator alongside an existing installation's accounts. -// When users already exist it reports whether the address is among them and -// changes nothing. FirstAdminRefused returns the normalized email in -// User.Email so callers can report it; no such account exists. -func (s *UserStore) DesignateFirstAdmin(rawEmail string) (User, FirstAdminOutcome, error) { - email, err := NormalizeEmail(rawEmail) - if err != nil { - return User{}, FirstAdminUnknown, err - } - user, err := s.CreateFirstAdminWithAudit(email, "", AuditEvent{ - EventType: "setup.completed", - Outcome: "success", - Metadata: map[string]any{"source": "first_admin_email"}, - }) - if err == nil { - return user, FirstAdminCreated, nil - } - if !errors.Is(err, ErrSetupComplete) { - return User{}, FirstAdminUnknown, err - } - existing, err := s.GetByEmail(email) - if errors.Is(err, ErrUserNotFound) { - return User{Email: email}, FirstAdminRefused, nil - } - if err != nil { - return User{}, FirstAdminUnknown, err - } - return existing, FirstAdminPresent, nil -} diff --git a/internal/auth/first_admin_test.go b/internal/auth/first_admin_test.go deleted file mode 100644 index 9ab6ec294..000000000 --- a/internal/auth/first_admin_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package auth - -import ( - "context" - "testing" -) - -func TestDesignateFirstAdminCreatesActiveAdministratorInEmptyDatabase(t *testing.T) { - sqlite := newTestSQLite(t) - users := NewUserStore(sqlite.DB) - - user, outcome, err := users.DesignateFirstAdmin(" First@Example.com ") - if err != nil { - t.Fatalf("DesignateFirstAdmin: %v", err) - } - if outcome != FirstAdminCreated { - t.Fatalf("outcome = %v, want FirstAdminCreated", outcome) - } - if user.Email != "first@example.com" || user.Role != RoleAdmin || user.Status != UserStatusActive { - t.Fatalf("firstAdmin = %+v, want active admin first@example.com", user) - } - var source string - if err := sqlite.DB.QueryRowContext(context.Background(), - `SELECT json_extract(metadata_json, '$.source') FROM auth_audit_events WHERE event_type = 'setup.completed' AND target_id = ?`, user.ID, - ).Scan(&source); err != nil { - t.Fatalf("setup audit event: %v", err) - } - if source != "first_admin_email" { - t.Fatalf("audit source = %q, want first_admin_email", source) - } -} - -func TestDesignateFirstAdminIsIdempotentForTheSameAddress(t *testing.T) { - users := NewUserStore(newTestSQLite(t).DB) - created, _, err := users.DesignateFirstAdmin("first@example.com") - if err != nil { - t.Fatalf("first DesignateFirstAdmin: %v", err) - } - again, outcome, err := users.DesignateFirstAdmin("FIRST@example.com") - if err != nil { - t.Fatalf("second DesignateFirstAdmin: %v", err) - } - if outcome != FirstAdminPresent || again.ID != created.ID { - t.Fatalf("outcome = %v user = %+v, want FirstAdminPresent for %s", outcome, again, created.ID) - } - if count, _ := users.CountUsers(); count != 1 { - t.Fatalf("users = %d, want 1", count) - } -} - -func TestDesignateFirstAdminRefusesADifferentAddress(t *testing.T) { - users := NewUserStore(newTestSQLite(t).DB) - if _, err := users.CreateFirstAdminWithAudit("admin@example.com", "", AuditEvent{EventType: "setup.completed", Outcome: "success"}); err != nil { - t.Fatalf("CreateFirstAdmin: %v", err) - } - refused, outcome, err := users.DesignateFirstAdmin(" First@Example.com ") - if err != nil { - t.Fatalf("DesignateFirstAdmin: %v", err) - } - if outcome != FirstAdminRefused || refused.ID != "" || refused.Email != "first@example.com" { - t.Fatalf("outcome = %v user = %+v, want FirstAdminRefused reporting first@example.com", outcome, refused) - } - if _, err := users.GetByEmail("first@example.com"); err != ErrUserNotFound { - t.Fatalf("GetByEmail(firstAdmin) err = %v, want ErrUserNotFound", err) - } - if count, _ := users.CountUsers(); count != 1 { - t.Fatalf("users = %d, want 1", count) - } -} - -func TestDesignateFirstAdminLeavesAnExistingAccountUnchanged(t *testing.T) { - users := NewUserStore(newTestSQLite(t).DB) - if _, err := users.CreateFirstAdminWithAudit("admin@example.com", "", AuditEvent{EventType: "setup.completed", Outcome: "success"}); err != nil { - t.Fatalf("CreateFirstAdmin: %v", err) - } - viewer, err := users.CreateWithAudit("first@example.com", "", RoleViewer, AuditEvent{EventType: "user.created", Outcome: "success"}) - if err != nil { - t.Fatalf("Create viewer: %v", err) - } - user, outcome, err := users.DesignateFirstAdmin("first@example.com") - if err != nil { - t.Fatalf("DesignateFirstAdmin: %v", err) - } - if outcome != FirstAdminPresent || user.ID != viewer.ID || user.Role != RoleViewer { - t.Fatalf("outcome = %v user = %+v, want unchanged viewer", outcome, user) - } -} - -func TestDesignateFirstAdminRejectsInvalidEmail(t *testing.T) { - users := NewUserStore(newTestSQLite(t).DB) - if _, outcome, err := users.DesignateFirstAdmin("not-an-email"); err == nil || outcome != FirstAdminUnknown { - t.Fatalf("DesignateFirstAdmin = (%v, %v), want FirstAdminUnknown with an error", outcome, err) - } - if count, _ := users.CountUsers(); count != 0 { - t.Fatalf("users = %d, want 0", count) - } -} diff --git a/internal/config/config.go b/internal/config/config.go index b016f203b..74f2f5e42 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -167,9 +167,6 @@ type Config struct { AuthCodeSecret string `group:"auth" env:"FANOUT_AUTH_CODE_SECRET" secret:"true"` // SelfSignup allows verified email addresses to create viewer accounts; requires local auth and SMTP. SelfSignup bool `group:"auth" env:"FANOUT_SELF_SIGNUP" default:"false"` - // FirstAdminEmail creates this address as the first active administrator when the control - // database has no users, instead of printing the one-time setup URL; ignored once users exist. - FirstAdminEmail string `group:"auth" env:"FANOUT_FIRST_ADMIN_EMAIL"` // SessionIdleTTL expires inactive sessions; use a Go duration of at least 5m. SessionIdleTTL time.Duration `group:"auth" env:"FANOUT_SESSION_IDLE_TTL" default:"12h"` // SessionAbsoluteTTL limits total session lifetime; it must be at least FANOUT_SESSION_IDLE_TTL. @@ -335,11 +332,6 @@ func (c Config) Validate() error { return fmt.Errorf("FANOUT_AUTH_CODE_SECRET must be at least 32 characters") } } - if c.FirstAdminEmail != "" { - if _, err := appauth.NormalizeEmail(c.FirstAdminEmail); err != nil { - return fmt.Errorf("FANOUT_FIRST_ADMIN_EMAIL must be a valid email address") - } - } if anySet(c.SMTPHost, c.SMTPUser, c.SMTPPass, c.SMTPFrom) { if !c.SMTPConfigured() { return fmt.Errorf("FANOUT_SMTP_HOST, FANOUT_SMTP_USERNAME, FANOUT_SMTP_PASSWORD, and FANOUT_SMTP_FROM must all be set when SMTP is configured") diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 81c3488f4..ab31b48fb 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -58,20 +58,6 @@ func TestLoadTreatsEmptyEnvironmentValuesAsAbsent(t *testing.T) { } } -func TestLoadFirstAdminEmail(t *testing.T) { - cfg, err := Load(LoadOptions{Environ: append(validEnvironment(), "FANOUT_FIRST_ADMIN_EMAIL=First@Example.com")}) - if err != nil { - t.Fatal(err) - } - if cfg.FirstAdminEmail != "First@Example.com" { - t.Fatalf("FirstAdminEmail = %q", cfg.FirstAdminEmail) - } - _, err = Load(LoadOptions{Environ: append(validEnvironment(), "FANOUT_FIRST_ADMIN_EMAIL=first.example.com")}) - if err == nil || !strings.Contains(err.Error(), "FANOUT_FIRST_ADMIN_EMAIL must be a valid email address") { - t.Fatalf("invalid first administrator email error = %v", err) - } -} - func TestConfigurationSchemaUsesUnitBearingDurations(t *testing.T) { specs, err := configFieldSpecs() if err != nil { @@ -287,9 +273,6 @@ func TestValidate(t *testing.T) { {"AI provider invalid", func(c *Config) { c.AIProvider = "unknown" }}, {"auth code secret empty", func(c *Config) { c.AuthCodeSecret = "" }}, {"auth code secret short", func(c *Config) { c.AuthCodeSecret = "short" }}, - {"first admin email invalid", func(c *Config) { c.FirstAdminEmail = "first" }}, - {"first admin email blank", func(c *Config) { c.FirstAdminEmail = " " }}, - {"first admin email with display name", func(c *Config) { c.FirstAdminEmail = "First " }}, {"self-signup without SMTP", func(c *Config) { c.SelfSignup = true; c.SMTPHost = "" }}, {"local self-signup in OIDC mode", func(c *Config) { c.SelfSignup = true diff --git a/internal/ingest/auth.go b/internal/ingest/auth.go index 8c0ec18e6..e279840d3 100644 --- a/internal/ingest/auth.go +++ b/internal/ingest/auth.go @@ -82,10 +82,9 @@ func (a *ingestAuthorizer) authorizeToken(ctx context.Context, token string) err return fmt.Errorf("%w: %v", errIngestAuthUnavailable, err) } if ingestCfg.TokenHash == "" { - // No token has been issued yet: interactive setup issues the first one, - // and an administrator created from FANOUT_FIRST_ADMIN_EMAIL issues it from Settings. - // Reject all requests until then; collectors must wait. - slog.Warn("ingest: rejecting request — no ingest token configured; an administrator must issue one") + // Pre-setup (no admin yet) — no token exists to check against. Reject + // all requests until setup completes; collectors must wait. + slog.Warn("ingest: rejecting request — no ingest token configured (setup not complete)") return errIngestNotInitialized } if token == "" || !settings.CheckIngestToken(token, ingestCfg.TokenHash) { diff --git a/internal/settings/ingest.go b/internal/settings/ingest.go index 13a839969..ab5a9b53e 100644 --- a/internal/settings/ingest.go +++ b/internal/settings/ingest.go @@ -14,9 +14,8 @@ import ( const ingestKey = "ingest" // Ingest holds the ingest-auth configuration. TokenHash is set during -// interactive first-admin setup, or issued and rotated from the Settings page -// (the only path for an administrator created from FANOUT_FIRST_ADMIN_EMAIL); while unset, -// the authorizer rejects all OTLP requests. Collectors +// first-admin setup and rotatable from the Settings page; when unset +// (pre-setup), the authorizer rejects all OTLP requests. Collectors // present the token via `Authorization: Bearer`. type Ingest struct { TokenHash string `json:"token_hash"` diff --git a/site/src/content/docs/docs/concepts/authentication.mdx b/site/src/content/docs/docs/concepts/authentication.mdx index 010ea403f..0d9517660 100644 --- a/site/src/content/docs/docs/concepts/authentication.mdx +++ b/site/src/content/docs/docs/concepts/authentication.mdx @@ -24,8 +24,7 @@ and recovery. `FANOUT_SELF_SIGNUP` allows verified email addresses to create viewer accounts. It defaults to `false` and requires complete SMTP configuration. Self-signup is -available only once the first administrator exists; an administrator created -from `FANOUT_FIRST_ADMIN_EMAIL` counts, even before signing in. Viewers can read +available only after the first administrator completes setup. Viewers can read all telemetry, manage their own dashboards and run the built-in agent. The built-in agent sends requests to your configured model provider and can incur charges. Enabling self-signup grants that access to anyone who can verify diff --git a/site/src/content/docs/docs/get-started/first-boot.mdx b/site/src/content/docs/docs/get-started/first-boot.mdx index b9c1295b4..9a0c21b4b 100644 --- a/site/src/content/docs/docs/get-started/first-boot.mdx +++ b/site/src/content/docs/docs/get-started/first-boot.mdx @@ -1,7 +1,7 @@ --- title: First boot description: What Fanout checks before it opens a listener, and how to claim the first administrator account. -summary: Configuration validation, the one-time setup URL or a configured first administrator, and the ingest token you are shown once. +summary: Configuration validation, the one-time setup URL, and the ingest token you are shown once. read_when: - The process refuses to start and you want to know what it validated. - You have a running instance and need to create the first administrator. @@ -57,52 +57,6 @@ The setup URL is an administrator credential. Restrict access to process logs until it is consumed or expires. Treat a leaked setup URL as a compromised installation and rebuild with a fresh data directory before repeating setup. -## Naming the first administrator instead - -Set `FANOUT_FIRST_ADMIN_EMAIL` to skip the setup URL. When the control database -holds no users at startup, Fanout creates that address as an active -administrator and prints no setup banner, so no administrator credential reaches -the logs: - -```sh -docker run --name fanout --restart unless-stopped -p 7520:7520 \ - -v fanout-data:/var/lib/fanout/data \ - -e FANOUT_AUTH_CODE_SECRET=$(openssl rand -hex 32) \ - -e FANOUT_FIRST_ADMIN_EMAIL=admin@example.com \ - labstack/fanout:latest -``` - -Fanout validates the address when it loads configuration and stops with an -error if it is malformed. The setting takes effect only on first start with an -empty database. The account it creates is a regular, permanent administrator, -and changing or removing the setting later has no effect on it: - -- Once any user exists, it creates nothing. Restarting with the same address is - a no-op. A different address is refused with a warning naming it, and no - account is created; an administrator adds further accounts with `POST /api/users`. -- It never promotes, reactivates or edits an existing account. If the address - belongs to an account that is not an active administrator, Fanout warns and - leaves the account unchanged. - -The first administrator signs in like any other user: with an email code when -SMTP is configured, or with `fanout login-link` as shown below. In OIDC mode -they sign in through the provider, and Fanout links the first sign-in to the account -by its email address, subject to the usual allowed group and domain checks. - -:::caution[Claim the administrator account promptly] -Until the first administrator signs in, whoever first proves control of that address -claims the administrator account: anyone who can read its mailbox in local mode, -or any identity provider account that asserts that email in OIDC mode. Use an -address you control, sign in promptly after first boot, and in OIDC mode confirm -that the account's `identity.linked` audit event came from your own sign-in. -::: - -No setup request runs, so no ingest token is issued at first boot and ingest -rejects every exporter until the first administrator issues one. After signing in, open -**Connect telemetry → Ingest token** in the account menu and choose -**Issue token**, or call `POST /api/settings/ingest/token/rotate`. Save the token -when it is shown. - ## Signing in afterwards Local mode has no passwords. Once SMTP is configured, active users receive diff --git a/site/src/content/docs/docs/guides/troubleshooting.mdx b/site/src/content/docs/docs/guides/troubleshooting.mdx index e0630951f..b55a9224f 100644 --- a/site/src/content/docs/docs/guides/troubleshooting.mdx +++ b/site/src/content/docs/docs/guides/troubleshooting.mdx @@ -102,11 +102,9 @@ permission error. Work down this list in order: -1. **Has a token been issued?** Before the first ingest token exists there is - nothing to check against, and ingest rejects everything. Interactive setup - issues the first token; an administrator created from - `FANOUT_FIRST_ADMIN_EMAIL` issues it from **Connect telemetry → Ingest - token**. A collector started earlier fails until then. +1. **Has setup finished?** Before the first administrator exists there is no + ingest token to check against, and ingest rejects everything. A collector + started ahead of setup fails until you complete it. 2. **Is it the right credential, in the right header?** The ingest token is `foi_`-prefixed and goes in `Authorization: Bearer`. Browser sessions and MCP tokens are not ingest credentials. diff --git a/site/src/content/docs/docs/reference/configuration/auth.mdx b/site/src/content/docs/docs/reference/configuration/auth.mdx index 92d90b0f3..a069e50ef 100644 --- a/site/src/content/docs/docs/reference/configuration/auth.mdx +++ b/site/src/content/docs/docs/reference/configuration/auth.mdx @@ -20,7 +20,6 @@ Vendor credentials and endpoints keep the vendor's documented names. |---|---|---| | `FANOUT_AUTH_CODE_SECRET` or `FANOUT_AUTH_CODE_SECRET_FILE` | string · secret | — | | `FANOUT_AUTH_MODE` | string | `local` | -| `FANOUT_FIRST_ADMIN_EMAIL` | string | — | | `FANOUT_OIDC_ADMIN_GROUPS` | string | — | | `FANOUT_OIDC_ALLOWED_DOMAINS` | string | — | | `FANOUT_OIDC_ALLOWED_GROUPS` | string | — | @@ -46,10 +45,6 @@ Signs local sign-in codes; required in local mode with at least 32 characters. Selects local sign-in or oidc; each mode validates its prerequisites. -### `FANOUT_FIRST_ADMIN_EMAIL` - -Creates this address as the first active administrator when the control database has no users, instead of printing the one-time setup URL; ignored once users exist. - ### `FANOUT_OIDC_ADMIN_GROUPS` Lists identity-provider groups mapped to admin, separated by commas.