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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ Where to look first:
- Logs and events are read newest first through their indexes; time marks (`marks.go`) turn date ranges into sequence ranges. Text search of logs compares each line (`textutil.ContainsFold`), first on the stored bytes when the text has no character JSON escapes (`rawSearchable`), so most lines are never decoded; a count that the index walks answer exactly counts keys (`countByKeys`); log counts (the pager) stop at `store.LogCountLimit` (10000; `CountLogs` returns `more`, the pager shows "of 10000+"). A walk over the logs (`scanLogs`; not a count by keys) stops at `config.LogSearchTime` (20 s, every request alike, by the store's clock, `searchBudget`) and reports a `store.LogScan`: `Rest` (logs below it not searched; `merged` steps every walk key by key, so one bound holds for all) and `SearchedTo` (every log received since was searched, from the time marks); a count gives `FromID`, the oldest match or where it stopped, which bounds its list (`LogFilter.FromID`).
- API lists fetch `limit+1` rows; `store.Page` trims them and says whether a next page exists (cursor pagination). The web app's lists use pages (`Offset`/`Limit` of `IssueFilter`/`LogFilter`, the API's offset cursor); issues and logs by walking indexes newest first.
- `store` never imports `sentry`: callers map to `NewEvent`/`NewLog`.
- `internal/server`: `net/http` ServeMux with method patterns (`"GET /health"`), wrapped in a request-logging middleware (its `statusRecorder` unwraps, so `http.ResponseController`, the read deadline of ingest bodies, reaches the connection) and `recoverPanics` inside it: a handler's panic is logged with method, path, route and stack and answered as a JSON 500 "internal error" (the connection is dropped if the answer had begun). Built from `server.Options`; depends on small interfaces (`Pinger`, `http.Handler` for ingest, `Routes` for the API and the web app), so tests use fakes. Mounts ingest (open), `/health` (open; 503 when `Store.Ping`, a read of the store, fails), the links that stop emails (`Unsubscribe`, open, signed), the API wrapped in `protectAPI` (IP allowlist first, then API token); MCP, OAuth, the web app (`Web`, every address no other route takes) and its API (`UIAPI`, a `UIRoutes`: routes plus the handler of every other address under `UIAPIPrefix`) use the IP allowlist plus their own authentication. `RESTPrefix` (`/api/v1/`) and `UIAPIPrefix` (`/api/ui/`) are defined here; the one `"/api/"` fallback (`unknownAPI`) sends `/api/ui/...` to the web app's API (a login, then a JSON 404) and anything else to a JSON 404 behind the token. `headers.go`: `ContentSecurityPolicy` (the one builder: script sources such as the page's inline hashes), `SecurityHeaders` (policy, nosniff, `Referrer-Policy: same-origin` (no-referrer would make browsers send `Origin: null` on same-origin POSTs), `X-Frame-Options`), `SameOrigin` (Origin's host is the request's, and https when the request is (`IsHTTPS` with the trusted proxies); oauth compares with PUBLIC_URL on purpose), used by `web` and `api/ui.go`.
- `internal/server`: `net/http` ServeMux with method patterns (`"GET /health"`), wrapped in a request-logging middleware (its `statusRecorder` unwraps, so `http.ResponseController`, the read deadline of ingest bodies, reaches the connection) and `recoverPanics` inside it: a handler's panic is logged with method, path, route and stack and answered as a JSON 500 "internal error" (the connection is dropped if the answer had begun). Built from `server.Options`; depends on small interfaces (`Pinger`, `http.Handler` for ingest, `Routes` for the API and the web app), so tests use fakes. Mounts ingest (open), `/health` (open; 503 when `Store.Ping` fails: a read of the store, or its last write failed, `kv.DB.WriteError`, as on a full disk), the links that stop emails (`Unsubscribe`, open, signed), the API wrapped in `protectAPI` (IP allowlist first, then API token); MCP, OAuth, the web app (`Web`, every address no other route takes) and its API (`UIAPI`, a `UIRoutes`: routes plus the handler of every other address under `UIAPIPrefix`) use the IP allowlist plus their own authentication. `RESTPrefix` (`/api/v1/`) and `UIAPIPrefix` (`/api/ui/`) are defined here; the one `"/api/"` fallback (`unknownAPI`) sends `/api/ui/...` to the web app's API (a login, then a JSON 404) and anything else to a JSON 404 behind the token. `headers.go`: `ContentSecurityPolicy` (the one builder: script sources such as the page's inline hashes), `SecurityHeaders` (policy, nosniff, `Referrer-Policy: same-origin` (no-referrer would make browsers send `Origin: null` on same-origin POSTs), `X-Frame-Options`), `SameOrigin` (Origin's host is the request's, and https when the request is (`IsHTTPS` with the trusted proxies); oauth compares with PUBLIC_URL on purpose), used by `web` and `api/ui.go`.
- `internal/server` (`access.go`): `ClientIP` (uses `X-Forwarded-For` only when the direct peer is in `TRUSTED_PROXIES`, read right to left; entries may carry a port; addresses are compared unmapped and without an IPv6 zone, `comparable`, and IPv4-mapped networks in the settings are stored as IPv4), `FromTrustedProxy`, `RequireAllowedIP` (403, a debug log line with the address seen), `RequireToken` (constant-time; empty `API_TOKEN` closes the REST API).
- `internal/server` (`json.go`): `WriteJSON`/`JSONError` for JSON responses (`{"error": ...}`). Ingest keeps its own `writeError` because Sentry SDKs expect `{"detail": ...}` plus `X-Sentry-Error`.
- `internal/api` (the catalog): the one catalog of requests, served as the REST API, as MCP tools and to the web app. `Endpoints(projects, services.All)` lists them in order; handlers reach data only through `services.All` (no store), so tools and pages apply the same rules (with nil arguments it only serves to read the definitions); each is `Define(Endpoint{Name, Description, ReadOnly, Idempotent, Destructive, Confirm, Admin, Transports, OpenWithTemporaryPassword}, handler)` with `handler(ctx, Call, In) (Out, error)`: the input schema comes from `In` (`json` + `jsonschema` tags, `jsonschema.For`) with the enums of `Choices` and the bounds of every `limit` (`DefaultLimit`, `MaxLimit`), `Run` validates the input map against it and decodes it. A new tool or API route = one entry + its handler; nothing else to register. `Call.Access()` is the projects the call sees (all for the REST token, the viewer's otherwise; handlers find projects by name or id through `services.Projects.Find` (`params.go`: `projectIDs` for filters, a missing one 404, a hidden one 403; `projectsField` for a form's field: unknown 400, hidden 403 at the field) and pass the access to services). `Call` has the `Transport` (`TransportREST`, `TransportMCP`, `TransportUI`; a `Call` without one runs nothing), the `Viewer` (the user of the agent or the web app; empty for the REST token), the `Actor` (recorded in the history) and the server `Address` (DSNs); `ForAgent()` is true unless the transport is REST or the web app (fail closed), and then `call.Text` redacts free text with `agentprompt.Redact`. Output is JSON, or `api.Text` written as is (the agent prompt of `get_issue`/`get_event`). Errors are sorted in one place (`OutcomeOf`: the HTTP status, the kind an MCP tool error starts with (`Outcome.ToolText`: `invalid: …`, `forbidden: …`, `not found: …`, `conflict: …`, `unavailable: …`, `internal error`) and the body), which `fail` (REST, the web app, the plain requests) and MCP's `failed` use: `InputError` with its status (`Invalid` 400, `notFound` 404, `conflict` 409, 413, 429 with `Retry-After`, 502 for a destination that refused a test message); `services.Reason` of `services.ErrForbidden` (the role or a rule of who may change whom; `services.Forbidden(reason)`), `services.ErrHidden` (a record of a project outside the viewer's; `services.Hidden(what, ids...)`, which names only what the caller gave, never the record's data) both 403, `store.ErrNotFound` (`services.Missing`) 404, `services.ErrConflict` 409; `services.Refusal` (a form refused as 403 or 409 with its fields, `formError` renames them; a taken project name 409, "This name cannot be used." for a hidden one); `ErrNotFound` 404; anything else logged and reported as "internal error". MCP adds the viewer's project names to a hidden record's refusal (`forbidden: issue k3x9q2mf is not in your projects (frontend, test2)`), which `list_projects` shows them anyway, so an agent tells a deleted issue from a hidden one; a 403 confirms only that an id or name exists. A refused form is `problemsError` (the problem of each field, renamed to the input's names) or `duplicateError` (409, the connection that already sends there, unnamed when hidden): over HTTP the body is `ErrorBody` `{error, fields?, duplicate?}` whatever the status, so a page shows each problem at its field, MCP gets the joined message (`TestInputErrorBody`, `errors_test.go`). Lists: `Page{items, next_cursor}`, 20 rows by default, at most 100, plain-number cursors (offset for issues/projects/deliveries, at most `store.MaxOffset` (`parseOffset`; `ListIssues` clamps too, since offset+limit must not overflow), last id for events/logs; `list_users` and `list_connections` return every row in one page). Every endpoint names its `Transports` (`Define` panics without; `AllTransports`, `ActsAsUser` = MCP and the web app, or one): `Run` refuses what `Refused(call)` names (`AllowedFor` is it being nil): an endpoint its transport does not serve (`ErrNotFound`), for a user without `CanAdminister` an `Admin` one (`services.ErrForbidden`, "your role may not do this"), and in the web app, while the user has a temporary password, anything without `OpenWithTemporaryPassword` (403 "change your password first"); the token runs every REST endpoint. REST only: `get_event_payload` (raw payload), `list_trace` (log attributes), their output must not reach a model provider (the web app reads the payload, indented, inside `get_issue_details`). `ActsAsUser` (`manage.go`, `notifications.go`): account, agents, projects, users, notification connections and email confirmation, acting as the user (`Users` and `Agents` refuse by role with `services.Forbidden` (403: "your role may not change this user" for a user changing an admin, `services.TakeOverProblem` for a user with projects the admin lacks; nobody changes themselves there: "change your own account on /account"); `Projects`, `Connections`, `Verification` and `Deliveries` check no role, only the access (`Projects.Save` keeps the disk share an admin's; `delete_project` is `Admin`)); form rules are shared because tools pass the form's fields as `url.Values` to `services.Projects.Save`/`Connections.Save`, starting from `FormValues` of the stored record so fields not given keep their values. `get_storage` (`session.go`, the web app only): the data the database holds against `MAX_DATABASE_SIZE` (`services.Projects.Storage`, `store.ProjectUsage.Live`, the cleanup's own measure) with the parts of the projects the viewer sees (`ProjectUsage.OnDisk`), other (live minus those projects), the files apart (`files`, `ProjectUsage.Files`), the start and stop percents, `last_received`, `dropped` (per project, `ingest.DropCounter` through `services.Dependencies.Dropped`), for the Projects page. `get_session` (`session.go`, the web app only, `OpenWithTemporaryPassword`): the viewer (`user`, with `display_name`), `can_administer`, `app_name` (`services.All.AppName`), the unresolved count, `project_colors` (the shown color of every project the viewer sees, by name, `services.Projects.ColorsByName`; badges set it with the `style:` directive), `all_projects` (the viewer sees every project, future ones included), `assignable_roles` (`store.User.AssignableRoles`, empty for a user) and `theme` (the user's, `store.User.Theme`, empty until the app records one). `set_theme` (the web app only, `OpenWithTemporaryPassword`, `store.Themes` as `Choices`; `services.Users.SetTheme`, `Store.UpdateUserTheme`) saves the user's theme. The web app's own endpoints (never MCP, mostly because their output is unredacted): `count_issues`, `list_issue_levels`, `list_issue_projects` (the count, level choices and project choices of the issue list (the projects some issue is in, from the tallies, `IssueProjects`: no issue read), from the filters `list_issues` takes, `issueFiltersInput`; `issueOutput.mcp_reference`, `agentprompt.MCPReference`, is filled only for the web app); `list_log_levels` (the level choices of the logs list: the levels some stored log in the viewer's projects has, highest first; no filters); `list_issue_projects` and `list_log_projects` (the project choices: from the issue tallies, `Store.IssueProjects`; one seek per visible project in the logs' project index, `Store.LogProjects`); `get_issue_details` (`issue_details.go`: an issue with its history, its 20 newest events (`next_cursor` for `list_issue_events`, whose items carry `received_at`) and one event (`?event=`, the latest by default) read by `services.Issues.Details`: `event_state` shown, unreadable, missing (not stored, or another issue's) or none (`services.EventState`, generated as a union through `outputSchemas`), the facts, exceptions outermost first with frames newest first, maps as name-sorted pairs, JSON indented by Go, related logs, the stored payload and the agent prompt); `apply_issue_action` (resolve, ignore, reopen or delete 1 to `services.MaxActionIssues` issues, `services.IssueActions` as choices; `ignore_for`/`ignore_until_events` (`ignoreBoundInput`, also on `update_issue_status`) only with ignore, else 400 (`services.ErrBoundWithoutIgnore`); invalid ids 400; deleted ones skipped; delete needs `CanAdminister`, checked by `services.Issues.ApplyAction`, else 403; missing and hidden issues skipped); `delete_logs` (`Admin`, `Destructive`, not for agents, whose logs are for reading: `log_ids`, 1 to `services.MaxActionLogs`, missing ones skipped; `{deleted}`; `list_logs` rows carry their `id`; `count_logs` and `list_logs` say `stopped` and `searched_to` when the search ran out of time, `count_logs` gives `from_id` for `list_logs`, and a stopped `list_logs` has a `next_cursor` that goes on below where it stopped); `list_cleanups` (`services.Projects.Cleanups` → `ShownRun`: `VisibleRun`, the projects outside access as one Other row, sizes from `ShownRun.Left`), `get_project_setup` (every role; `connected`/`connected_at` from the first contact (`services.Projects.Contact`, `store.ProjectUsage.FirstContact`), `received` once something is stored), `get_project_defaults`; `get_user` (`{user, can_manage, can_take_over, access_editable}` with reasons); `get_mcp_setup` (`agents.go`: how to connect an agent); `get_connection` (saved tokens masked by `textutil.MaskSecret`, never whole), `get_connection_defaults`, `test_chat`, `count_deliveries`. `set_connection_active` (also MCP) changes only `active`: a whole-form save would refuse a connection whose tokens cannot be read. `list_users` rows are `get_user`'s; `userOutput` has `display_name` and `created_at`; `list_agents` returns `user_id`, `owners` (whose agents the caller may list, only when more than one) and `connected` per agent; `get_project` gives `shown_color`, and an unknown project is `services.Missing` (404, naming it and pointing to `list_projects`). `create_user`/`update_user` take the roles of `store.AssignableRoles` as `Choices`. `list_projects` gives every role the recorded log levels as an explicit list, highest first (`config.Recording.RecordedLogLevels`, also behind `services.Projects.FormValues`). `typescript_test.go` (`TestTypeScriptCatalog`) generates `web/src/lib/api/catalog.gen.ts` from the endpoints the web app may call: inputs from `InputSchema`, outputs from the handler's output type (`Define` keeps it; `time.Time` → `IsoTime`, `json.RawMessage` → `unknown`), the method and admin/destructive/confirm flags (an endpoint of the web app that answers `Text` fails it: the app reads JSON only), the plain requests (`PlainRequests`, `plainRequests`), `ErrorBody`, `choices`, `levels` (highest first), `shownLevel` (the aliases of `config.EventLevelAliases` too), `apiPrefix`, `maxLimit`, and the values of the server's rules: `limits` (`config.Limits`), `issueStatuses` (with `store.StatusMeanings`), `maxActionIssues` (`services.MaxActionIssues`), `projectPalette` (`config.ProjectPalette`), `personalTokenKind` (`store.GrantToken`), `cleanupSteps` and `cleanupRules` (the cleanup by size), `diskShare` (`store.MinDiskShare`, `MaxDiskShare`, `DiskShareStep`), `roleSummaries`, `help` (`docs.Fields`, and of `docs.Settings` only `shownSettings`: a field or variable the app names that is not generated fails its type check); an unsupported schema keyword fails it, a stale file fails `make test`, `make api-types` rewrites it (excluded from Prettier). Never requests of the catalog, in any transport: logins, changing your own password (the account page asks for the current one, through `session.Auth` and its login limit) and generating personal tokens (`TestCatalogNeverChangesCredentials`, which allows them only in `plain*.go`): they are the plain requests of the web app (`plain.go`, `PlainRequests`: `login_state`, `login`, `setup_admin`, `logout`, `change_password`, `personal_token`, `authorization_request`, `authorization_decision`, each with its method and the Go types of its JSON input and output, `NoContent` for a 204), whose handlers (`LoginRequests` in `plain.go`, `AgentRequests` in `plain_agents.go`, joined in `app.New`) `NewUI` takes by name and mounts on their method inside the same guard; no endpoint takes their names (`TestEndpointNames`). The mount checks no session: each handler reads it itself (`sessionViewer`, the one session check of the catalog's calls and the plain requests) and applies the temporary-password rule where it matters, since `login` and `login_state` must work without one: `login_state` `{app_name, redirect?}` (redirect = `server.SafeNext(next)` only with a valid session); `login` 429 `session.TooManyAttempts` with `Retry-After` (the login window), 401 "Wrong email or password." for a wrong password and an unknown user alike, 200 `{next}`, or `{next, setup: true}` for the env credentials while there is no admin (no session; see Users and roles); `logout` 204 even without a session; `change_password` open with a temporary password, problems as 400 `{error, fields}`, the login limit 429 at `current_password` (`session.ErrTooManyAttempts`); `personal_token` and the consent requests 403 with a temporary password; a body over 64 KiB 413. The description (`ToolDescription`) of a `Destructive` tool, or a `Confirm` one (it changes who may access the server, where errors are sent or what it records), tells the agent to get an explicit confirmation in chat.
Expand Down
2 changes: 1 addition & 1 deletion docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Image tags: `latest` (newest release), `X.Y` (newest patch of a minor version),

The container runs as an unprivileged user (uid 65534). A bind-mounted data folder must be writable by it: `sudo chown 65534:65534 ./data`. A named volume, as in the example, needs nothing.

`GET /health` answers 200 while the server works; Docker uses it too (`docker ps` shows `healthy`).
`GET /health` answers 200 while the server works, and 503 once the database cannot be read or its writes fail (a full disk); Docker uses it too (`docker ps` shows `healthy`).

## HTTPS and a reverse proxy

Expand Down
7 changes: 6 additions & 1 deletion internal/storage/database/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,8 +252,13 @@ func (database *Store) syncToDisk() error {
})
}

// Ping reads the format key, so a closed store or a failing disk answers with an error.
// Ping reads the format key, so a closed store or a failing disk answers
// with an error, as does a store whose last write failed.
func (database *Store) Ping(context.Context) error {
if err := database.db.WriteError(); err != nil {
return fmt.Errorf("writes fail: %w", err)
}

_, err := database.db.Get(database.formatKey)

return err
Expand Down
Loading
Loading