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
19 changes: 14 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,8 @@ v2026.9.5

## API and MCP naming

Use the same naming conventions as Monk, Goal, Cipher, and ResponseKeeper
where the operations have the same meaning. Product-specific resources and
protocol-defined contracts keep their own semantics.
These are LabStack's shared API and MCP conventions. Product-specific
resources and protocol-defined contracts keep their own semantics.

- Application HTTP routes use `/api`, lowercase words, meaningful slash-separated
domains/resources/actions, and plural collections. Do not use hyphens in
Expand All @@ -115,18 +114,28 @@ protocol-defined contracts keep their own semantics.
Each segment should have a domain, resource, or action meaning; do not
mechanically split compound words. Colon actions are conventions in other
API ecosystems.
- User profile PATCH uses `/api/users/{id}` with `email` and `display_name`;
role and status PATCH use `/api/users/{id}/role` and `/api/users/{id}/status`.
- Equivalent authentication flows use `/api/auth/me`, `/api/auth/code/send`,
`/api/auth/code/verify`, and `POST /api/auth/logout`. Flow selection, passkeys,
account linking, and sign-in link verification are distinct operations.
OIDC sign-in uses `/api/auth/oidc/start` and `/api/auth/oidc/callback` without
a provider segment because Fanout supports exactly one configured provider.
- Operational routes use `/healthz` for liveness, `/readyz` for readiness,
and `/metrics` for Prometheus exposition. Preserve authorization requirements.
- MCP tool names use verb-first snake_case and describe their behavior:
`get`, `list`, `search`, `inspect`, `create`, `replace`, and domain actions.
Full replacement uses `replace`, not `update`. Do not add product prefixes
solely to avoid collisions in clients that aggregate servers.
- New product-owned JSON fields and query parameters use snake_case. Preserve
protocol-defined names, including MCP, OAuth, OTLP, and AG-UI fields. Existing
- MCP tool annotations must reflect actual read-only, destructive, and
idempotent behavior.
- Product-owned JSON fields and query parameters use snake_case; an entity's
own identifier is `id`. Preserve protocol-defined names, including MCP,
OAuth, OTLP, and AG-UI fields. Existing
client-contract exceptions require a deliberate contract change.
- Cursor-paginated collections return `items` and `next_cursor` (null at the
end) and accept `page_size` and `cursor`. Unpaginated lists keep a named
array such as `dashboards` or `versions`.
- Product CalVer, client-contract versions, and protocol versions are separate.
Do not put the product release or maturity suffix in API paths or tool names.
- Breaking naming changes update registrations, authorization classification,
Expand Down
2 changes: 1 addition & 1 deletion cmd/fanout-docgen/routes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func TestCollectRoutesResolvesGroupPrefixes(t *testing.T) {
relative := map[string]bool{
"/overview": true, "/topology": true, "/logs": true,
"/trace": true, "/performance": true,
"/runs": true, "/threads": true, "/threads/:threadID": true,
"/runs": true, "/threads": true, "/threads/:id": true,
}
for _, r := range routes {
if relative[r.Path] {
Expand Down
4 changes: 2 additions & 2 deletions cmd/fanout/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -554,8 +554,8 @@ func createLoginLink(cfg config.Config, rawEmail string, output io.Writer) error
if err != nil {
return err
}
if !user.Active {
return fmt.Errorf("user %s is inactive", email)
if user.Status != auth.UserStatusActive {
return fmt.Errorf("user %s is suspended", email)
}
token, err := auth.NewCodeStore(sqlite.DB, cfg.AuthCodeSecret).CreateLoginLink(email)
if err != nil {
Expand Down
32 changes: 27 additions & 5 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ 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 completes setup.
Inactive accounts are not recreated or reactivated. Public installations
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.

Expand All @@ -82,7 +82,7 @@ docker exec <container> fanout --config /etc/fanout/fanout.yaml \
login-link admin@example.com
```

The command refuses missing or inactive users and a missing control database.
The command refuses missing or suspended users and a missing control database.
It writes a hashed credential and a `login_link.issued` audit event, then prints
one URL to stderr. The URL expires after 15 minutes, works once, and writes a
distinct `login_link.redeemed` audit event when used. Running it while Fanout is
Expand All @@ -92,6 +92,28 @@ Fix SMTP after regaining access if email-code login is expected. OIDC-mode
recovery remains at the identity provider or OIDC configuration layer; local
login links are deliberately unavailable in that mode.

### User account API

All user-management routes require an administrator. User projections, including
`GET /api/auth/me` and `GET /api/users`, expose `display_name` and `status`.
Status is either `active` or `suspended`; roles remain `viewer`, `operator`,
and `admin`.

- `POST /api/users` provisions an account with `email`, `display_name`, and
`role`. New accounts have status `active`.
- `PATCH /api/users/{id}` changes only `email` and `display_name`; omitted
profile fields retain their values.
- `PATCH /api/users/{id}/role` accepts only `{"role":"viewer"}` (or
`operator` or `admin`).
- `PATCH /api/users/{id}/status` accepts only `{"status":"suspended"}` or
`{"status":"active"}`.

Unknown fields return `400`. Email, role, and status changes revoke browser
sessions. Suspension also blocks sign-in and OAuth token use. 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`.

### Adding local users without SMTP

User creation remains available when SMTP is not configured. The API returns
Expand All @@ -101,15 +123,15 @@ same command shown above and deliver it through a trusted channel. When SMTP is
configured, Fanout sends the invitation synchronously and reports relay
failure rather than claiming it was delivered.

If the local account is inactive or its address is no longer usable, the
If the local account is suspended or its address is no longer usable, the
command refuses to mint a credential. Stop Fanout, copy the control database,
and repair that account without deleting it or its owned data:

```sql
SELECT id, email, role, active FROM users;
SELECT id, email, display_name, role, status FROM users;

UPDATE users
SET email = 'you@example.com', active = 1, role = 'admin'
SET email = 'you@example.com', status = 'active', role = 'admin'
WHERE id = '<the administrator id>';
```

Expand Down
4 changes: 0 additions & 4 deletions docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,6 @@ original host.
- `/metrics` exposes Prometheus metrics. Keep it private or configure
`FANOUT_METRICS_TOKEN`; do not make it public merely to simplify scraping.

When upgrading from a version that exposed `/-/metrics`, change Prometheus
`metrics_path` and any proxy rules to `/metrics`. The retired path returns 404
even with a valid metrics token; it does not redirect.

Alert on repeated restarts, readiness failures, ingest authentication failures,
telemetry drops, sustained query latency, and available disk space. Retention
is controlled by `FANOUT_RETENTION_DAYS`; maintenance removes expired data on
Expand Down
23 changes: 12 additions & 11 deletions internal/agent/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ func NewRuntime(provider Provider, tools toolExecutor, store *Store) *Runtime {
func (r *Runtime) Register(group *echo.Group) {
group.POST("/runs", r.Run)
group.GET("/threads", r.ListThreads)
group.GET("/threads/:threadID", r.GetThread)
group.PATCH("/threads/:threadID", r.RenameThread)
group.DELETE("/threads/:threadID", r.DeleteThread)
group.GET("/threads/:id", r.GetThread)
group.PATCH("/threads/:id", r.RenameThread)
group.DELETE("/threads/:id", r.DeleteThread)
}

type threadCursor struct {
Expand All @@ -79,10 +79,10 @@ func (r *Runtime) ListThreads(c *echo.Context) error {
return ownerErr
}
limit := 30
if raw := strings.TrimSpace(c.QueryParam("limit")); raw != "" {
if raw := strings.TrimSpace(c.QueryParam("page_size")); raw != "" {
parsed, err := strconv.Atoi(raw)
if err != nil || parsed < 1 || parsed > 100 {
return echo.NewHTTPError(http.StatusBadRequest, "limit must be between 1 and 100")
return echo.NewHTTPError(http.StatusBadRequest, "page_size must be between 1 and 100")
}
limit = parsed
}
Expand All @@ -106,25 +106,26 @@ func (r *Runtime) ListThreads(c *echo.Context) error {
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to list threads").Wrap(err)
}
nextCursor := ""
var nextCursor *string
if len(items) > limit {
items = items[:limit]
last := items[len(items)-1]
encoded, err := json.Marshal(threadCursor{UpdatedAt: last.Updated, ThreadID: last.ThreadID})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to paginate threads").Wrap(err)
}
nextCursor = base64.RawURLEncoding.EncodeToString(encoded)
value := base64.RawURLEncoding.EncodeToString(encoded)
nextCursor = &value
}
return c.JSON(http.StatusOK, map[string]any{"threads": items, "nextCursor": nextCursor})
return c.JSON(http.StatusOK, map[string]any{"items": items, "next_cursor": nextCursor})
}

func (r *Runtime) GetThread(c *echo.Context) error {
ownerID, ownerErr := api.RequestOwner(c)
if ownerErr != nil {
return ownerErr
}
thread, err := r.store.Thread(c.Request().Context(), ownerID, c.Param("threadID"))
thread, err := r.store.Thread(c.Request().Context(), ownerID, c.Param("id"))
if errors.Is(err, ErrThreadNotFound) {
return echo.NewHTTPError(http.StatusNotFound, "thread not found")
}
Expand All @@ -149,7 +150,7 @@ func (r *Runtime) RenameThread(c *echo.Context) error {
if title == "" || len([]rune(title)) > 120 {
return echo.NewHTTPError(http.StatusBadRequest, "thread title must be between 1 and 120 characters")
}
if err := r.store.RenameThread(c.Request().Context(), ownerID, c.Param("threadID"), title); errors.Is(err, ErrThreadNotFound) {
if err := r.store.RenameThread(c.Request().Context(), ownerID, c.Param("id"), title); errors.Is(err, ErrThreadNotFound) {
return echo.NewHTTPError(http.StatusNotFound, "thread not found")
} else if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to rename thread").Wrap(err)
Expand All @@ -162,7 +163,7 @@ func (r *Runtime) DeleteThread(c *echo.Context) error {
if ownerErr != nil {
return ownerErr
}
if err := r.store.DeleteThread(c.Request().Context(), ownerID, c.Param("threadID")); errors.Is(err, ErrThreadNotFound) {
if err := r.store.DeleteThread(c.Request().Context(), ownerID, c.Param("id")); errors.Is(err, ErrThreadNotFound) {
return echo.NewHTTPError(http.StatusNotFound, "thread not found")
} else if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to delete thread").Wrap(err)
Expand Down
8 changes: 4 additions & 4 deletions internal/agent/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,16 @@ var ErrThreadNotFound = errors.New("agent thread not found")

// Thread is a persisted agent conversation owned by one user.
type Thread struct {
ThreadID string `json:"threadId"`
ThreadID string `json:"id"`
Messages []agtypes.Message `json:"messages"`
Updated string `json:"updatedAt"`
Updated string `json:"updated_at"`
}

// ThreadSummary is the compact representation returned by conversation history.
type ThreadSummary struct {
ThreadID string `json:"threadId"`
ThreadID string `json:"id"`
Title string `json:"title"`
Updated string `json:"updatedAt"`
Updated string `json:"updated_at"`
}

// ThreadListOptions controls owner-scoped conversation history queries.
Expand Down
77 changes: 73 additions & 4 deletions internal/agent/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -463,23 +463,92 @@ func TestThreadRouteHidesOtherOwnersThread(t *testing.T) {
t.Fatalf("cross-owner thread read = %d, want 404", recorder.Code)
}

request = httptest.NewRequest(http.MethodGet, "/api/agent/threads?q=owner&limit=1", nil)
request = httptest.NewRequest(http.MethodGet, "/api/agent/threads?q=owner&page_size=1", nil)
request.AddCookie(cookie)
recorder = httptest.NewRecorder()
e.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Fatalf("thread list = %d, want 200: %s", recorder.Code, recorder.Body.String())
}
var page struct {
Threads []ThreadSummary `json:"threads"`
NextCursor string `json:"nextCursor"`
Items []ThreadSummary `json:"items"`
NextCursor *string `json:"next_cursor"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &page); err != nil {
t.Fatal(err)
}
if len(page.Threads) != 1 || page.Threads[0].ThreadID != "own-thread" || page.NextCursor != "" {
if len(page.Items) != 1 || page.Items[0].ThreadID != "own-thread" || page.NextCursor != nil {
t.Fatalf("owner-scoped thread page = %#v", page)
}
var wire map[string]json.RawMessage
if err := json.Unmarshal(recorder.Body.Bytes(), &wire); err != nil {
t.Fatal(err)
}
if len(wire) != 2 || string(wire["next_cursor"]) != "null" || wire["items"] == nil {
t.Fatalf("thread page JSON = %s", recorder.Body.String())
}
var summaries []map[string]json.RawMessage
if err := json.Unmarshal(wire["items"], &summaries); err != nil {
t.Fatal(err)
}
if len(summaries[0]) != 3 || string(summaries[0]["id"]) != `"own-thread"` || summaries[0]["title"] == nil || summaries[0]["updated_at"] == nil {
t.Fatalf("thread summary JSON = %s", wire["items"])
}
read := func(path string) *httptest.ResponseRecorder {
request := httptest.NewRequest(http.MethodGet, path, nil)
request.AddCookie(cookie)
recorder := httptest.NewRecorder()
e.ServeHTTP(recorder, request)
return recorder
}
threadResponse := read("/api/agent/threads/own-thread")
if threadResponse.Code != http.StatusOK {
t.Fatalf("own thread = %d: %s", threadResponse.Code, threadResponse.Body.String())
}
wire = nil
if err := json.Unmarshal(threadResponse.Body.Bytes(), &wire); err != nil {
t.Fatal(err)
}
if len(wire) != 3 || string(wire["id"]) != `"own-thread"` || wire["messages"] == nil || wire["updated_at"] == nil {
t.Fatalf("thread JSON = %s", threadResponse.Body.String())
}
for _, value := range []string{"0", "101", "invalid"} {
if response := read("/api/agent/threads?page_size=" + value); response.Code != http.StatusBadRequest {
t.Fatalf("page_size %q = %d, want 400", value, response.Code)
}
}
if _, err := store.StartRun(context.Background(), ownerB.ID, agtypes.RunAgentInput{
ThreadID: "older-thread", RunID: "run-3",
Messages: []agtypes.Message{{ID: "message-2", Role: agtypes.RoleUser, Content: "Investigate another issue"}},
}); err != nil {
t.Fatal(err)
}
if _, err := database.DB.Exec(`UPDATE agui_threads SET updated_at = '2026-10-01 00:00:00' WHERE owner_id = ?`, ownerB.ID); err != nil {
t.Fatal(err)
}
firstPage := read("/api/agent/threads?page_size=1")
if firstPage.Code != http.StatusOK {
t.Fatalf("first page = %d: %s", firstPage.Code, firstPage.Body.String())
}
if err := json.Unmarshal(firstPage.Body.Bytes(), &page); err != nil {
t.Fatal(err)
}
if len(page.Items) != 1 || page.Items[0].ThreadID != "own-thread" || page.NextCursor == nil || *page.NextCursor == "" {
t.Fatalf("first thread page = %#v", page)
}
lastPage := read("/api/agent/threads?page_size=1&cursor=" + *page.NextCursor)
if lastPage.Code != http.StatusOK {
t.Fatalf("last page = %d: %s", lastPage.Code, lastPage.Body.String())
}
if err := json.Unmarshal(lastPage.Body.Bytes(), &page); err != nil {
t.Fatal(err)
}
if len(page.Items) != 1 || page.Items[0].ThreadID != "older-thread" || page.NextCursor != nil {
t.Fatalf("last thread page = %#v", page)
}
if response := read("/api/agent/threads?cursor=invalid"); response.Code != http.StatusBadRequest {
t.Fatalf("invalid cursor = %d, want 400", response.Code)
}

mutation := func(method, path, body string) *httptest.ResponseRecorder {
request := httptest.NewRequest(method, path, strings.NewReader(body))
Expand Down
22 changes: 11 additions & 11 deletions internal/api/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,9 @@ func (h *AuthHandler) Setup(c *echo.Context) error {
return rateLimited(c, 15*time.Minute)
}
var req struct {
Email string `json:"email"`
Name string `json:"name"`
SetupToken string `json:"setup_token"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
SetupToken string `json:"setup_token"`
}
if err := c.Bind(&req); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "email is required")
Expand All @@ -119,7 +119,7 @@ func (h *AuthHandler) Setup(c *echo.Context) error {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
createEvent := auth.AuditEvent{EventType: "setup.completed", Outcome: "success", RemoteIP: c.RealIP(), UserAgent: c.Request().UserAgent()}
user, err := h.users.CreateFirstAdminWithAudit(email, req.Name, createEvent)
user, err := h.users.CreateFirstAdminWithAudit(email, req.DisplayName, createEvent)
if errors.Is(err, auth.ErrSetupComplete) {
// The setup credential creates exactly one administrator. Establishing
// a session for an existing admin here would let one token mint
Expand Down Expand Up @@ -219,7 +219,7 @@ func (h *AuthHandler) Start(c *echo.Context) error {
slog.Error("auth: login user lookup failed", "err", userErr)
return echo.NewHTTPError(http.StatusInternalServerError, "failed to start login")
}
if !errors.Is(userErr, auth.ErrUserNotFound) && !user.Active {
if !errors.Is(userErr, auth.ErrUserNotFound) && user.Status != auth.UserStatusActive {
jitter()
return c.JSON(200, map[string]bool{"code_sent": true})
}
Expand Down Expand Up @@ -308,10 +308,10 @@ func (h *AuthHandler) Verify(c *echo.Context) error {
slog.Error("auth: complete verified self-signup", "err", err)
return echo.NewHTTPError(http.StatusInternalServerError, "failed to complete login")
}
if errors.Is(err, auth.ErrUserNotFound) || !user.Active {
h.recordAudit(c, auth.AuditEvent{EventType: "login.failed", Outcome: "denied", TargetType: "email", Metadata: map[string]any{"reason": "inactive_or_missing"}})
if errors.Is(err, auth.ErrUserNotFound) || user.Status != auth.UserStatusActive {
h.recordAudit(c, auth.AuditEvent{EventType: "login.failed", Outcome: "denied", TargetType: "email", Metadata: map[string]any{"reason": "suspended_or_missing"}})
jitter()
return echo.NewHTTPError(http.StatusUnauthorized, "user not found or inactive")
return echo.NewHTTPError(http.StatusUnauthorized, "user not found or suspended")
}

if err := h.establishSession(c, user); err != nil {
Expand Down Expand Up @@ -353,10 +353,10 @@ func (h *AuthHandler) LoginLink(c *echo.Context) error {
slog.Error("auth: login link user lookup failed", "err", err)
return echo.NewHTTPError(http.StatusInternalServerError, "failed to complete login")
}
if errors.Is(err, auth.ErrUserNotFound) || !user.Active {
h.recordAudit(c, auth.AuditEvent{EventType: "login.failed", Outcome: "denied", TargetType: "email", Metadata: map[string]any{"reason": "inactive_or_missing_login_link_user"}})
if errors.Is(err, auth.ErrUserNotFound) || user.Status != auth.UserStatusActive {
h.recordAudit(c, auth.AuditEvent{EventType: "login.failed", Outcome: "denied", TargetType: "email", Metadata: map[string]any{"reason": "suspended_or_missing_login_link_user"}})
jitter()
return echo.NewHTTPError(http.StatusUnauthorized, "user not found or inactive")
return echo.NewHTTPError(http.StatusUnauthorized, "user not found or suspended")
}
if err := h.establishSession(c, user); err != nil {
slog.Error("auth: login link session establishment failed", "user_id", user.ID, "err", err)
Expand Down
Loading
Loading