Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,12 @@
# Default: false
# FANOUT_ROLLUP_SKIP_TO_LATEST=

# FANOUT_SCIM_TOKEN; string; secret
# Enables SCIM 2.0 user provisioning under /scim/v2 and turns off browser setup; requires OIDC mode and at least 32 characters.
# Default: (empty)
# FANOUT_SCIM_TOKEN=
# Alternatively set FANOUT_SCIM_TOKEN_FILE to a secret file path; do not set both.

# FANOUT_SELF_SIGNUP; boolean
# Allows verified email addresses to create viewer accounts; requires local auth and SMTP.
# Default: false
Expand Down
2 changes: 2 additions & 0 deletions cmd/fanout-docgen/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,8 @@ func requirement(doc api.RouteDoc) string {
return "any signed-in user"
case api.RoutePolicyProtocol:
return "protocol handshake"
case api.RoutePolicySCIM:
return "SCIM bearer token, when `FANOUT_SCIM_TOKEN` is set"
case api.RoutePolicyServiceCredential:
return fmt.Sprintf("`%s`, or a service credential", doc.Capability)
case api.RoutePolicyCapability:
Expand Down
39 changes: 10 additions & 29 deletions cmd/fanout/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
"net/url"
"os"
"os/signal"
"regexp"
"runtime"
"strings"
"syscall"
Expand Down Expand Up @@ -51,8 +50,6 @@ import (
"github.com/labstack/fanout/internal/ui"
)

var tokenRedactRe = regexp.MustCompile(`token=[^&]+`)

// version is set at build time via -ldflags "-X main.version=...".
var version = "dev"

Expand Down Expand Up @@ -221,7 +218,7 @@ func main() {
slog.Error("auth status init failed", "err", err)
os.Exit(1)
}
if userCount == 0 {
if setupBannerRequired(userCount, cfg) {
token, _, err := setup.Rotate()
if err != nil {
slog.Error("setup token init failed", "err", err)
Expand All @@ -245,31 +242,7 @@ func main() {
slog.Info("trusted proxy IP extraction enabled", "header", "X-Forwarded-For", "cidrs", cfg.TrustedProxyCIDRs)
}
e.Use(middleware.Recover())
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
LogURI: true,
LogStatus: true,
LogLatency: true,
LogMethod: true,
LogRemoteIP: true,
LogUserAgent: true,
HandleError: true,
LogValuesFunc: func(c *echo.Context, v middleware.RequestLoggerValues) error {
uri := v.URI
if strings.Contains(uri, "token=") {
uri = tokenRedactRe.ReplaceAllString(uri, "token=REDACTED")
}
attrs := []any{"method", v.Method, "uri", uri, "status", v.Status, "latency", v.Latency}
if v.Error != nil {
attrs = []any{"method", v.Method, "route", c.Path(), "status", v.Status, "latency", v.Latency, "err", v.Error}
}
if v.Status >= 500 {
slog.Error("request", attrs...)
} else {
slog.Info("request", attrs...)
}
return nil
},
}))
e.Use(api.RequestLogger())

api.RegisterAuthMiddleware(e, userStore, browserSessions, auditStore, cfg)

Expand Down Expand Up @@ -345,6 +318,7 @@ func main() {
api.RegisterHealthRoutes(e, q, cfg, oidcDiscovery)

api.RegisterUserRoutes(e, userStore, smtpCfg, cfg)
api.RegisterSCIMRoutes(e, cfg, userStore, identityStore)
api.RegisterSettingsRoutes(e, cfg, settingsStore, auditStore)
slog.Info("auth enabled")

Expand Down Expand Up @@ -790,6 +764,13 @@ func browserLoginURL(cfg config.Config) *url.URL {
return loginURL
}

// setupBannerRequired reports whether to mint the one-time setup credential.
// A SCIM token means accounts come from the provisioner, so the credential is
// never created and cannot reach the log.
func setupBannerRequired(userCount int64, cfg config.Config) bool {
return userCount == 0 && cfg.SCIMToken == ""
}

func printSetupBanner(httpAddr, token string) {
lines := []string{
"============================================================",
Expand Down
26 changes: 26 additions & 0 deletions cmd/fanout/setup_banner_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package main

import (
"testing"

"github.com/labstack/fanout/internal/config"
)

func TestSetupBannerRequired(t *testing.T) {
scim := config.Config{SCIMToken: "configured"}
for _, tc := range []struct {
name string
count int64
cfg config.Config
want bool
}{
{"empty without SCIM", 0, config.Config{}, true},
{"populated without SCIM", 1, config.Config{}, false},
{"empty with SCIM", 0, scim, false},
{"populated with SCIM", 1, scim, false},
} {
if got := setupBannerRequired(tc.count, tc.cfg); got != tc.want {
t.Errorf("%s = %v, want %v", tc.name, got, tc.want)
}
}
}
97 changes: 95 additions & 2 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,8 @@ when there are no users.
`{"status":"active"}`.

Unknown fields return `400`. Email, role, and status changes revoke browser
sessions. Suspension also blocks sign-in and OAuth token use. Demotion,
sessions. Suspension also blocks sign-in and revokes the user's OAuth tokens
and pending authorization codes; reactivation does not restore them. Demotion,
suspension, and deletion cannot remove the last active administrator.
The first-run `POST /api/auth/setup` request uses `display_name` alongside
`email` and `setup_token`.
Expand Down Expand Up @@ -303,16 +304,108 @@ require a browser session. Administrators can still revoke all of a user's
access, including browser sessions and OAuth tokens, through
`POST /api/users/{id}/access/revoke`.

## SCIM provisioning

Set `FANOUT_SCIM_TOKEN` (or `FANOUT_SCIM_TOKEN_FILE`) to let an identity provider
or automation create, update and deactivate accounts. The setting requires
`FANOUT_AUTH_MODE=oidc` and a value of at least 32 characters with no whitespace.
Without it the routes do not exist and nothing below applies.

With a token configured, Fanout prints no setup banner, `/api/auth/setup` returns
`410`, and `/api/auth/status` reports `setup_required: false`. The first
administrator comes from SCIM.

Fanout implements a small subset of SCIM 2.0 (RFC 7644) under `/scim/v2`.
Requests send `Authorization: Bearer <token>`, and bodies use
`application/scim+json` or `application/json`. Responses use
`application/scim+json`, and failures use the RFC 7644 error format.

| Route | Purpose |
|---|---|
| `POST /scim/v2/Users` | Create an account and link its identity |
| `GET /scim/v2/Users?filter=...` | Find an account |
| `GET /scim/v2/Users/{id}` | Read an account |
| `PATCH /scim/v2/Users/{id}` | Change `active`, the role, the email or `displayName` |

Other methods return `405` and other paths under `/scim/v2` return `404`. Delete
is not supported; deactivate with `active: false`. The `ServiceProviderConfig`,
`Schemas` and `ResourceTypes` discovery endpoints are not implemented.

### Creating accounts

`POST` requires the core User schema, `externalId`, `userName` and one value in
`roles`. `externalId` is the subject (`sub`) at the configured issuer, and is
treated as an exact opaque string. `userName` is the email address. If `emails`
is sent, its primary value must be the same address. The role is `admin`,
`operator` or `viewer`. `active` defaults to `true`.

The account and the identity `(FANOUT_OIDC_ISSUER_URL, externalId)` are written
in one transaction with their audit events. The user's first OIDC login finds
that identity, so no match by email takes place.

A `POST` for an identity that already exists returns `200` with the current
account and changes nothing, so a delayed retry cannot undo a later change. Send
a `PATCH` to change an existing account. A new account returns `201`. An email
held by a different account returns `409` with `scimType` `uniqueness`; Fanout
never links an existing account by email.

While there are no users, only an active administrator can be created, using the
same transactional check as setup. Any other request returns `409`, so it can be
retried once an administrator exists. Concurrent administrators are all created.

### Finding accounts

`filter` accepts exactly `externalId eq "value"` and `userName eq "value"`.
Attribute names and `eq` are case-insensitive, and the value is a JSON string,
so `"` and `\` must be escaped. `externalId` matches exactly; `userName` is
normalized like any email address. Anything else, including a missing filter,
returns `400` with `scimType` `invalidFilter`. `startIndex` and `count` are
accepted.

### Updating accounts

`PATCH` takes the `PatchOp` schema with `add` or `replace` operations on `active`,
`roles`, `userName`, `emails` and `displayName`, with or without a `path`. A path
filter such as `emails[type eq "work"].value` is not supported. `remove` returns
`400`. All operations in a request apply as one update, so the checks below see
the final state.

A request that changes nothing returns `200` and writes nothing: no session
revocation, no token revocation and no audit event. Resending the same state is
safe. Changing the email or reactivating an account keeps its identity link.

Deactivating or demoting the last active administrator returns `409`. The check
runs in the same write transaction as the update.

Deactivation suspends the account. In one transaction it revokes the user's
browser sessions, revokes their MCP OAuth access and refresh tokens, and deletes
their pending OAuth authorization codes. Reactivation restores none of these, so
the user signs in and connects MCP clients again. Deactivating an account that
is already suspended removes anything still live and writes a `session.revoked`
event; if nothing is live it writes nothing.

Requests to `/scim/v2` are logged without their query string, because a filter
holds an email address or subject.

Every change writes an audit event: `user.provisioned` and `identity.linked` on
creation, then `user.suspended`, `user.reactivated`, `role.changed` or
`user.updated`. Metadata records `mode: scim`, which fields changed and any role
or status transition. Addresses and the token are never recorded.

The token is compared in constant time and is never logged. Rotate it by
changing the setting and restarting Fanout.

## Credentials at a glance

| Credential | Purpose | Rotation |
|---|---|---|
| Setup URL | Creates the first administrator | One-time, expires in 1 hour |
| Setup URL | Creates the first administrator | One-time, expires in 1 hour; not issued when `FANOUT_SCIM_TOKEN` is set |
| Login URL | Authenticates one existing active local user | One-time, expires in 15 minutes; mint with `fanout login-link` |
| Break-glass URL | Authenticates one active administrator in OIDC mode | One-time, expires in 15 minutes; mint with `fanout login-link --break-glass` |
| Browser session | Interactive access | Idle and absolute TTL; revoked on role, email, or status change |
| Ingest token | OTLP ingest | Settings page; `FANOUT_INGEST_TOKEN` sets only the first token |
| Metrics token | `/metrics` scrape | `FANOUT_METRICS_TOKEN` |
| SCIM token | User provisioning at `/scim/v2` | `FANOUT_SCIM_TOKEN`; change the setting and restart |
| MCP OAuth tokens | MCP clients | 30-day access tokens, checked on every request; 90-day refresh tokens renewed on each use. Refresh rotation with replay-family revocation, admitting the same client's rotated token for one access-token lifetime so processes sharing a credential can refresh from stale copies. Users disconnect individual agents in Settings; admins can still revoke all of a user's access |

Local email codes allow three attempts per code and expire after five minutes.
Expand Down
1 change: 1 addition & 0 deletions docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Every secret accepts either its value or its file path:
| `FANOUT_SMTP_PASSWORD` | `FANOUT_SMTP_PASSWORD_FILE` |
| `FANOUT_INGEST_TOKEN` | `FANOUT_INGEST_TOKEN_FILE` |
| `FANOUT_METRICS_TOKEN` | `FANOUT_METRICS_TOKEN_FILE` |
| `FANOUT_SCIM_TOKEN` | `FANOUT_SCIM_TOKEN_FILE` |
| `ANTHROPIC_API_KEY` | `ANTHROPIC_API_KEY_FILE` |
| `OPENAI_API_KEY` | `OPENAI_API_KEY_FILE` |

Expand Down
5 changes: 4 additions & 1 deletion internal/api/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func (h *AuthHandler) Status(c *echo.Context) error {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to check auth status")
}
return c.JSON(200, map[string]any{
"setup_required": count == 0,
"setup_required": count == 0 && h.cfg.SCIMToken == "",
"auth_enabled": true,
"auth_mode": strings.ToLower(strings.TrimSpace(h.cfg.AuthMode)),
"agent_available": h.cfg.AgentConfigured(),
Expand All @@ -87,6 +87,9 @@ func (h *AuthHandler) Status(c *echo.Context) error {
}

func (h *AuthHandler) Setup(c *echo.Context) error {
if h.cfg.SCIMToken != "" {
return echo.NewHTTPError(http.StatusGone, "browser setup is disabled because accounts are provisioned by SCIM")
}
if !h.setupLimiter.Allow(c.RealIP()) {
return rateLimited(c, 15*time.Minute)
}
Expand Down
41 changes: 37 additions & 4 deletions internal/api/auth_middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ const (
routePolicyCapability
routePolicyServiceCredential
routePolicyProtocol
routePolicySCIM
)

type routePolicy struct {
Expand Down Expand Up @@ -87,12 +88,21 @@ func RegisterAuthMiddleware(e *echo.Echo, users *auth.UserStore, sessions *auth.
}

func AuthMiddleware(users *auth.UserStore, sessions *auth.BrowserSessions, cfg config.Config) echo.MiddlewareFunc {
// Without a token, SCIM paths are classified exactly as if SCIM did not
// exist: unknown to the API and left to the browser application.
classify := classifyNonSCIMRoute
if cfg.SCIMToken != "" {
classify = classifyRoute
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
path := c.Request().URL.Path
policy, classified := classifyRoute(c.Request().Method, path)
policy, classified := classify(c.Request().Method, path)
if cfg.SCIMToken != "" && isSCIMPath(path) {
return authorizeSCIM(c, cfg.SCIMToken, classified, next)
}
if !classified {
if routePathKnown(path) {
if routePathKnown(classify, path) {
return echo.NewHTTPError(http.StatusMethodNotAllowed, "method not allowed")
}
// Echo may match the trace parameter to an empty or multi-segment ID.
Expand Down Expand Up @@ -261,7 +271,30 @@ func constantTimeToken(presented, expected string) bool {
return subtle.ConstantTimeCompare([]byte(presented), []byte(expected)) == 1
}

// classifyRoute is the full route table, used when SCIM is enabled and to
// document the routes.
func classifyRoute(method, path string) (routePolicy, bool) {
if isSCIMPath(path) {
return classifySCIMRoute(method, path)
}
return classifyNonSCIMRoute(method, path)
}

func classifySCIMRoute(method, path string) (routePolicy, bool) {
policy := routePolicy{kind: routePolicySCIM}
rest, ok := strings.CutPrefix(path, scimUsersPath)
switch {
case !ok:
return policy, false
case rest == "":
return policy, method == http.MethodGet || method == http.MethodPost
case strings.HasPrefix(rest, "/") && len(rest) > 1 && !strings.Contains(rest[1:], "/"):
return policy, method == http.MethodGet || method == http.MethodPatch
}
return policy, false
}

func classifyNonSCIMRoute(method, path string) (routePolicy, bool) {
read := method == http.MethodGet || method == http.MethodHead
unsafe := method == http.MethodPost || method == http.MethodPut || method == http.MethodPatch || method == http.MethodDelete

Expand Down Expand Up @@ -346,9 +379,9 @@ func isProtectedPath(path string) bool {
return strings.HasPrefix(path, "/api/") || strings.HasPrefix(path, "/debug/") || path == "/metrics"
}

func routePathKnown(path string) bool {
func routePathKnown(classify func(method, path string) (routePolicy, bool), path string) bool {
for _, method := range []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete} {
if _, ok := classifyRoute(method, path); ok {
if _, ok := classify(method, path); ok {
return true
}
}
Expand Down
16 changes: 16 additions & 0 deletions internal/api/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,10 @@ func TestRoutePolicyClassification(t *testing.T) {
{http.MethodPost, "/mcp", routePolicyProtocol, ""},
{http.MethodPost, "/api/mcp", routePolicyCapability, ReadTelemetry},
{http.MethodGet, "/assets/app.js", routePolicyPublic, ""},
{http.MethodGet, "/scim/v2/Users", routePolicySCIM, ""},
{http.MethodPost, "/scim/v2/Users", routePolicySCIM, ""},
{http.MethodGet, "/scim/v2/Users/user-1", routePolicySCIM, ""},
{http.MethodPatch, "/scim/v2/Users/user-1", routePolicySCIM, ""},
}
for _, tc := range tests {
policy, ok := classifyRoute(tc.method, tc.path)
Expand All @@ -215,6 +219,18 @@ func TestRoutePolicyClassification(t *testing.T) {
t.Errorf("%s %s policy = {%v %q}, want {%v %q}", tc.method, tc.path, policy.kind, policy.capability, tc.kind, tc.capability)
}
}
for _, tc := range []struct{ method, path string }{
{http.MethodDelete, "/scim/v2/Users/user-1"},
{http.MethodPut, "/scim/v2/Users/user-1"},
{http.MethodPost, "/scim/v2/Users/user-1"},
{http.MethodGet, "/scim/v2/Users/"},
{http.MethodGet, scimUsersPath + "/user-1/extra"},
{http.MethodGet, "/scim/v2/Groups"},
} {
if _, ok := classifyRoute(tc.method, tc.path); ok {
t.Errorf("%s %s must be unclassified", tc.method, tc.path)
}
}
if _, ok := classifyRoute(http.MethodPost, "/api/new-unreviewed-route"); ok {
t.Fatal("unreviewed API route must be unclassified")
}
Expand Down
3 changes: 3 additions & 0 deletions internal/api/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const (
RoutePolicyCapability = "capability"
RoutePolicyServiceCredential = "service-credential"
RoutePolicyProtocol = "protocol"
RoutePolicySCIM = "scim"
)

// RouteDoc is what a reader needs to know before calling a route: whether it
Expand Down Expand Up @@ -58,6 +59,8 @@ func DescribeRoute(method, path string) (RouteDoc, bool) {
doc.Policy = RoutePolicyServiceCredential
case routePolicyProtocol:
doc.Policy = RoutePolicyProtocol
case routePolicySCIM:
doc.Policy = RoutePolicySCIM
default:
// A new kind added to the switch without a name here would otherwise be
// published as an empty cell, which reads as "no requirement".
Expand Down
Loading
Loading