Documentation
¶
Overview ¶
Package admin implements the REST API handlers for the admin dashboard.
metapi-go/handler/admin — session lifecycle endpoints (#1034 session model).
POST /api/auth/login master token -> HttpOnly session cookie (public) GET /api/auth/session bootstrap probe: is this browser authenticated? (public) POST /api/auth/logout revoke the session row + clear the cookie (public) POST /api/auth/ws-ticket mint a one-time 60s ticket for the ops WebSocket (authed)
login/logout/session are registered in AdminAuth's public allowlist: login must be reachable without a session (it is the place the master token is presented, protected by the strict /api/auth/* rate bucket), and logout/session stay idempotent/read-only so an expired browser can always recover the sign-in state without a 401 redirect loop.
Index ¶
- Constants
- func AppendBackgroundTaskLog(taskID, message string)
- func AuditMiddleware(db *sqlx.DB) func(http.Handler) http.Handler
- func IsMaskedTokenValue(token string) bool
- func RegisterAboutRoutes(r chi.Router)
- func RegisterAccountTokensRoutes(r chi.Router, db *sqlx.DB)
- func RegisterAccountTokensRoutesWithConfig(r chi.Router, db *sqlx.DB, cfg *config.Config)
- func RegisterAccountsRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)
- func RegisterAnnouncementsRoutes(r chi.Router, db *sqlx.DB)
- func RegisterAuditLogsRoutes(r chi.Router, db *sqlx.DB)
- func RegisterAuthSettingsRoutes(r chi.Router, db *sqlx.DB, sessions *auth.SessionManager)
- func RegisterBackupRoutes(r chi.Router, db *sqlx.DB)
- func RegisterCatalogSourceRoutes(r chi.Router, db *sqlx.DB)
- func RegisterChannelTestRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)
- func RegisterCheckinRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)
- func RegisterDatabaseRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)
- func RegisterDownstreamKeysRoutes(r chi.Router, db *sqlx.DB)
- func RegisterDownstreamPricingRoutes(r chi.Router, db *sqlx.DB)
- func RegisterEventsRoutes(r chi.Router, db *sqlx.DB)
- func RegisterMaintenanceRoutes(r chi.Router, db *sqlx.DB)
- func RegisterModelRatesRoutes(r chi.Router, db *sqlx.DB)
- func RegisterModelRedirectRoutes(r chi.Router, db *sqlx.DB)
- func RegisterMonitorHealthRoute(r chi.Router, db *sqlx.DB)
- func RegisterMonitorProxyRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)
- func RegisterMonitorRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)
- func RegisterNotifyRoutes(r chi.Router)
- func RegisterOauthRoutes(r chi.Router, db *sqlx.DB)
- func RegisterOpsWSRoutes(r chi.Router, cfg *config.Config, sessions *auth.SessionManager)
- func RegisterResinRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)
- func RegisterSchedulerStatusRoutes(r chi.Router, db *sqlx.DB)
- func RegisterSearchRoutes(r chi.Router, db *sqlx.DB)
- func RegisterSessionRoutes(r chi.Router, cfg *config.Config, sessions *auth.SessionManager)
- func RegisterSettingsRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)
- func RegisterSiteAnnouncementsRoutes(r chi.Router, db *sqlx.DB)
- func RegisterSitesRoutes(r chi.Router, db *sqlx.DB)
- func RegisterStatsRoutes(r chi.Router, db *sqlx.DB)
- func RegisterTagsRoutes(r chi.Router, db *sqlx.DB)
- func RegisterTasksRoutes(r chi.Router, db *sqlx.DB)
- func RegisterTestRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)
- func RegisterTokenRoutesWithDeps(r chi.Router, db *sqlx.DB, deps TokenRoutesDeps)
- func RegisterUpdateCenterRoutes(r chi.Router)
- func SetBackgroundTaskDB(db *sqlx.DB)
- type BackgroundTask
- type BackgroundTaskLogEntry
- type BackgroundTaskStartOptions
- type BackgroundTaskStatus
- type RouteDecisionExplainer
- type RouteDecisionRefresher
- type SiteAnnouncementFailedSite
- type SiteAnnouncementSyncResult
- type TokenRoutesDeps
Constants ¶
const ( TokenValueStatusReady = "ready" TokenValueStatusMaskedPending = "masked_pending" )
TokenValueStatusReady and MaskedPending
const ( // ErrorCodeInvalidID rejects a URL path ID that is missing, non-numeric // or non-positive (pathID helper; every /api route with an {id} segment). ErrorCodeInvalidID = "invalidId" // ErrorCodeInvalidDatabaseType rejects a runtime-database dialect that is // neither sqlite nor postgres (/api/settings/database/* endpoints). ErrorCodeInvalidDatabaseType = "invalidDatabaseType" // ErrorCodeEmptyMigrationTarget rejects a migration request whose target // connection string is blank (POST /api/settings/database/migrate). ErrorCodeEmptyMigrationTarget = "emptyMigrationTarget" // ErrorCodeSameMigrationTarget rejects a migration whose target resolves // to the currently-running database (POST /api/settings/database/migrate). ErrorCodeSameMigrationTarget = "sameMigrationTarget" // ErrorCodeAccountNotFound rejects a request whose `{id}` path segment or // body references an account that does not exist (accounts / account // tokens / accounts-health route families). ErrorCodeAccountNotFound = "accountNotFound" // ErrorCodeOperationNotImplemented marks an honest 501 residual surface // (a known unimplemented feature — never a fake stub success). Emitted on // the residual 501 bodies via writeNotImplementedResidual. ErrorCodeOperationNotImplemented = "operationNotImplemented" // ErrorCodeTokenNotFound rejects an account-token operation whose // referenced token does not exist (account-tokens route family). ErrorCodeTokenNotFound = "tokenNotFound" // ErrorCodeRouteNotFound rejects a token-route operation whose // referenced route does not exist (routes family). ErrorCodeRouteNotFound = "routeNotFound" // ErrorCodeChannelNotFound rejects a route-channels operation whose // referenced channel does not exist (routes/{id}/channels family). ErrorCodeChannelNotFound = "channelNotFound" // ErrorCodeSiteNotFound rejects a request whose `{id}` path segment or // body references a site that does not exist (sites / accounts / site // announcements route families). ErrorCodeSiteNotFound = "siteNotFound" // ErrorCodeOperationNotSupported rejects an operation that the account // connection type does not support (e.g. API-key connections managing // account tokens). ErrorCodeOperationNotSupported = "operationNotSupported" // ErrorCodeResourceDisabled marks a failure caused by a capability being // currently unavailable — engine not configured, probe scheduler not // running, or the like. ErrorCodeResourceDisabled = "resourceDisabled" // ErrorCodeInvalidSettingsValue rejects a runtime-settings apply whose body // carries an invalid field value (the settings_apply validation funnel); // 5xx apply failures intentionally carry no code. ErrorCodeInvalidSettingsValue = "invalidSettingsValue" // ErrorCodeResourceLoadFailed marks a 5xx read-path failure where entity // data could not be loaded (accounts / announcements / events / channels / // site announcements / stats / token routes). One code for the whole // load-failure family; the per-entity English message stays the display // fallback. ErrorCodeResourceLoadFailed = "resourceLoadFailed" )
Machine-readable errorCode values carried on unified admin error bodies ({"error", "errorCode", ...}). Contract + registry table: docs/api.md.
Convention: errorCode values are stable camelCase identifiers. The field is OPTIONAL and additive — endpoints without a registered code omit it entirely, and the human-readable "error" message stays the source of truth for display. Clients must never substring-match on "error" when a code exists for their case.
New codes are added only for real call sites (no speculative taxonomy); register every new constant in the docs/api.md registry table.
Variables ¶
This section is empty.
Functions ¶
func AppendBackgroundTaskLog ¶ added in v0.13.0
func AppendBackgroundTaskLog(taskID, message string)
AppendBackgroundTaskLog appends a progress log entry to a pending/running background task's in-memory Logs slice (capped at backgroundTaskLogLimit) and updates its human-readable Message so /api/tasks/{id} polling surfaces meaningful progress while the runner is still executing. It is a no-op for unknown or already-terminal task IDs so callers can call it unconditionally from inside a runner without tracking liveness themselves.
Logs are memory-only (admin_background_tasks has no logs column); the durable row's message column is updated best-effort so a cross-process /api/tasks/{id} GET still shows the latest progress line.
func AuditMiddleware ¶
AuditMiddleware wraps admin handlers and records write operations. It must be mounted after AdminAuth so only authenticated requests pass. Panics inside the handler are recorded as status 500 before re-panicking, so chi's outer Recoverer still renders the standard error page.
func IsMaskedTokenValue ¶
IsMaskedTokenValue checks if a token value contains masking characters.
func RegisterAboutRoutes ¶ added in v0.16.5
RegisterAboutRoutes registers GET /api/about, the build-provenance surface the About page renders.
This is a dedicated endpoint rather than an extension of an existing one: /api/update-center/status is an explicit local-only stub whose contract is "no in-app version discovery" (its 0.0.0 placeholders are asserted by update_center_test.go), and /health + /ready are unauthenticated probes with a frozen payload that must not leak build provenance. Build metadata has no other owner, so it gets its own route.
Takes no *sqlx.DB: every field comes from the linker or the Go runtime, so the endpoint keeps answering when the database is unavailable.
func RegisterAccountTokensRoutes ¶
RegisterAccountTokensRoutes registers all /api/account-tokens routes.
func RegisterAccountTokensRoutesWithConfig ¶
RegisterAccountTokensRoutesWithConfig is like RegisterAccountTokensRoutes but accepts optional runtime config for proxy-aware upstream calls.
func RegisterAccountsRoutes ¶
RegisterAccountsRoutes registers all /api/accounts routes.
func RegisterAnnouncementsRoutes ¶
RegisterAnnouncementsRoutes mounts the announcement endpoints.
func RegisterAuditLogsRoutes ¶
GET /api/admin/audit-logs?limit=&offset=&method=&path= Lists recent admin write operations newest-first. method filters exact methods (POST/PUT/PATCH/DELETE); path filters by substring.
func RegisterAuthSettingsRoutes ¶
RegisterAuthSettingsRoutes registers all /api/settings/auth routes. sessions may be nil (tests): rotation then skips session revocation.
func RegisterBackupRoutes ¶
RegisterBackupRoutes registers all /api/settings/backup routes.
func RegisterCatalogSourceRoutes ¶ added in v0.16.9
RegisterCatalogSourceRoutes mounts the catalog registry + sync endpoints.
func RegisterChannelTestRoutes ¶
RegisterChannelTestRoutes registers admin-only forced-channel probe endpoints.
POST /api/admin/test-channel POST /api/debug/channel-probe (alias)
func RegisterCheckinRoutes ¶
RegisterCheckinRoutes registers all /api/checkin routes.
func RegisterDatabaseRoutes ¶
RegisterDatabaseRoutes registers all /api/settings/database routes.
func RegisterDownstreamKeysRoutes ¶
RegisterDownstreamKeysRoutes registers all /api/downstream-keys routes.
func RegisterDownstreamPricingRoutes ¶
Mounted under /v1/* so it inherits ProxyAuth + CORS from the /v1 route group.
func RegisterEventsRoutes ¶
RegisterEventsRoutes registers all /api/events routes.
func RegisterMaintenanceRoutes ¶
RegisterMaintenanceRoutes registers all /api/settings/maintenance routes.
func RegisterModelRatesRoutes ¶
RegisterModelRatesRoutes mounts the rate overview endpoint.
func RegisterModelRedirectRoutes ¶
RegisterModelRedirectRoutes mounts the redirect endpoints.
func RegisterMonitorHealthRoute ¶ added in v0.11.0
RegisterMonitorHealthRoute mounts the read-only observability health projection. It never hard-disables anything — the response only aggregates the in-memory runtime breaker state and the DB-backed channel cooldown / site+account health counters.
func RegisterMonitorProxyRoutes ¶ added in v0.16.7
RegisterMonitorProxyRoutes registers the /monitor-proxy/ldoh* iframe proxy surface. Authentication is the HttpOnly meta_monitor_auth cookie minted by createSession — iframe sub-resource requests cannot carry an Authorization header, so mounting these routes behind the Bearer AdminAuth middleware breaks the LDOH iframe (Wave 4 security handoff F1). The handler enforces the cookie itself via ensureMonitorAuth; keep this registrar outside any Bearer-gated group.
func RegisterMonitorRoutes ¶
RegisterMonitorRoutes registers the Bearer-protected /api/monitor configuration surface. The cookie-authenticated iframe proxy lives in RegisterMonitorProxyRoutes and must be wired OUTSIDE the admin auth group (see router/router.go).
func RegisterNotifyRoutes ¶
RegisterNotifyRoutes registers the /api/settings/notify/test route.
func RegisterOauthRoutes ¶
RegisterOauthRoutes registers all /api/oauth routes. Start/rebind issue cryptographically random server-stored state tokens (TTL 10m); session lookup and manual callback validate that state.
func RegisterOpsWSRoutes ¶
RegisterOpsWSRoutes mounts the live ops WebSocket endpoint. sessions may be nil (DB-less boot): the endpoint then fails closed.
func RegisterResinRoutes ¶ added in v0.13.0
RegisterResinRoutes mounts the Resin observability endpoints behind admin auth.
Currently exposes:
GET /api/admin/resin/status — global enable flag, resin URL (masked), active lease snapshot, and per-site override list.
All responses are read-only: this surface is observability-only and does not mutate Resin state or the lease tracker.
func RegisterSchedulerStatusRoutes ¶
Data sources are existing signals only — no scheduler code changes: - checkin: checkin_logs aggregate (status counts + latest timestamp) - balance-refresh: accounts.last_balance_refresh / last_checkin_at - oauth-refresh / sub2api-refresh: extra_config is JSON — we do not parse it here (cross-dialect); the events table carries token/balance alerts - model-probe: in-memory ProbeRunSummary (single-instance honest) - announcements: site_announcements.last_seen_at - daily-summary / log-cleanup / usage-aggregation: recent events rows
func RegisterSearchRoutes ¶
RegisterSearchRoutes registers all /api/search routes.
func RegisterSessionRoutes ¶ added in v0.16.19
RegisterSessionRoutes mounts the admin session lifecycle endpoints. sessions may be nil (DB-less boot): all endpoints then fail closed.
func RegisterSettingsRoutes ¶
RegisterSettingsRoutes registers all /api/settings routes (runtime, brand-list, system-proxy/test).
func RegisterSiteAnnouncementsRoutes ¶
RegisterSiteAnnouncementsRoutes registers all /api/site-announcements routes. Also wires the background SiteAnnouncementScheduler to real SyncSiteAnnouncements . Routes register before StartBackgroundServices, so the package-level default is installed for NewSiteAnnouncementScheduler to pick up.
func RegisterSitesRoutes ¶
RegisterSitesRoutes registers all /api/sites routes.
func RegisterStatsRoutes ¶
RegisterStatsRoutes registers all /api/stats and /api/models routes.
func RegisterTagsRoutes ¶
RegisterTagsRoutes mounts the tag endpoints behind admin auth.
func RegisterTasksRoutes ¶
RegisterTasksRoutes registers /api/tasks routes. list/get observe memory-visible tasks AND durable tasks from admin_background_tasks when the handler DB is set. Cold DB fallback enables cross-instance visibility.
func RegisterTestRoutes ¶
RegisterTestRoutes registers all /api/test routes.
Known limitation : - sync proxy/chat probes alias the forced-channel harness when a channel/site is forced - stream + async job create surfaces return honest 501 known limitations (no fake SSE/job success) - job status/cancel return 404 (no in-process /api/test job registry; never invent stub-job ids)
func RegisterTokenRoutesWithDeps ¶
func RegisterTokenRoutesWithDeps(r chi.Router, db *sqlx.DB, deps TokenRoutesDeps)
RegisterTokenRoutesWithDeps registers routes with optional decision engine deps.
func RegisterUpdateCenterRoutes ¶
RegisterUpdateCenterRoutes registers all /api/update-center routes.
Known limitation : - status/check are local stubs (never invent updateAvailable=true) - config is echo-only (no durable helper registry config product) - deploy/rollback/task stream are honest 501 known limitations (no stub task ids / fake SSE) See limitation-update-center.md.
func SetBackgroundTaskDB ¶
SetBackgroundTaskDB stores the DB handle used by free-function start/update. Called from server boot or test wiring.
Types ¶
type BackgroundTask ¶
type BackgroundTask struct {
ID string `json:"id"`
Type string `json:"type"`
Title string `json:"title"`
Status BackgroundTaskStatus `json:"status"`
Message string `json:"message"`
Error *string `json:"error"`
Result any `json:"result"`
DedupeKey *string `json:"dedupeKey"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
StartedAt *string `json:"startedAt"`
FinishedAt *string `json:"finishedAt"`
Logs []BackgroundTaskLogEntry `json:"logs"`
// contains filtered or unexported fields
}
StartBackgroundTask dual-writes to `admin_background_tasks` when a runtime DB is available so multi-instance deployments can list/get tasks across processes. Memory cache is the primary fast path; DB is the cold cross-process fallback. Cleanup removes expired rows from both memory and DB.
func StartBackgroundTask ¶
func StartBackgroundTask(opts BackgroundTaskStartOptions, runner func() (any, error)) (task *BackgroundTask, reused bool)
When dedupeKey matches a pending/running task across memory+DB, that task is reused.
type BackgroundTaskLogEntry ¶
type BackgroundTaskLogEntry struct {
Seq int `json:"seq"`
Message string `json:"message"`
CreatedAt string `json:"createdAt"`
}
BackgroundTaskLogEntry is a single task log line.
type BackgroundTaskStartOptions ¶
BackgroundTaskStartOptions configures StartBackgroundTask.
type BackgroundTaskStatus ¶
type BackgroundTaskStatus string
BackgroundTaskStatus mirrors the TS background task lifecycle.
const ( BackgroundTaskPending BackgroundTaskStatus = "pending" BackgroundTaskRunning BackgroundTaskStatus = "running" BackgroundTaskSucceeded BackgroundTaskStatus = "succeeded" BackgroundTaskFailed BackgroundTaskStatus = "failed" )
type RouteDecisionExplainer ¶
type RouteDecisionExplainer interface {
ExplainSelection(ctx context.Context, requestedModel string, excludeChannelIDs []int64, policy routing.DownstreamRoutingPolicy) (routing.RouteDecisionExplanation, error)
ExplainSelectionForRoute(ctx context.Context, routeID int64, requestedModel string, excludeChannelIDs []int64, policy routing.DownstreamRoutingPolicy) (routing.RouteDecisionExplanation, error)
ExplainSelectionRouteWide(ctx context.Context, routeID int64, policy routing.DownstreamRoutingPolicy) (routing.RouteDecisionExplanation, error)
}
RouteDecisionExplainer is the router surface used by decision admin APIs. Tests inject fakes; production wires routing.TokenRouter.
type RouteDecisionRefresher ¶
type RouteDecisionRefresher interface {
RefreshAllRouteDecisionSnapshots(ctx context.Context, refreshPricingCatalog bool) (exactModelCount int, wildcardRouteCount int, err error)
}
RouteDecisionRefresher refreshes persisted route decision snapshots.
type SiteAnnouncementFailedSite ¶
type SiteAnnouncementFailedSite struct {
SiteID int64 `json:"siteId"`
SiteName string `json:"siteName"`
Message string `json:"message"`
}
SiteAnnouncementFailedSite is one site that failed during announcement sync.
type SiteAnnouncementSyncResult ¶
type SiteAnnouncementSyncResult struct {
ScannedSites int `json:"scannedSites"`
Inserted int `json:"inserted"`
Updated int `json:"updated"`
Unsupported int `json:"unsupported"`
Notifications int `json:"notifications"`
Events int `json:"events"`
Failed int `json:"failed"`
FailedSites []SiteAnnouncementFailedSite `json:"failedSites"`
}
SiteAnnouncementSyncResult mirrors the TS syncSiteAnnouncements result shape. Used by the admin HTTP task path and by SiteAnnouncementScheduler via SyncSiteAnnouncements.
func SyncSiteAnnouncements ¶
func SyncSiteAnnouncements(db *sqlx.DB, siteID *int64) SiteAnnouncementSyncResult
SyncSiteAnnouncements fetches announcements for active sites (or one site) via platform adapters and upserts site_announcements. Exported so the background SiteAnnouncementScheduler can reuse this path without HTTP.
type TokenRoutesDeps ¶
type TokenRoutesDeps struct {
Router RouteDecisionExplainer
Decisions RouteDecisionRefresher
}
TokenRoutesDeps are optional dependencies for route decision endpoints.
Source Files
¶
- about.go
- account_tokens.go
- account_tokens_sync.go
- accounts.go
- accounts_health.go
- accounts_models.go
- announcements.go
- audit_logs.go
- auth_settings.go
- catalog_sources.go
- channel_test_harness.go
- channels.go
- checkin_routes.go
- checkin_schedule.go
- credential_export.go
- credential_masking.go
- doc.go
- downstream_keys.go
- downstream_keys_normalize.go
- error_codes.go
- events.go
- helpers.go
- json_decode.go
- key_admission_snapshot.go
- model_price_compare.go
- model_rates.go
- model_redirects.go
- model_refresh.go
- models_verify.go
- monitor.go
- monitor_health.go
- oauth_routes.go
- ops_ws.go
- probe_history.go
- resin.go
- response_errors.go
- scheduler_status.go
- search.go
- session_routes.go
- settings.go
- settings_apply.go
- settings_backup.go
- settings_backup_webdav.go
- settings_database.go
- settings_maintenance.go
- settings_migration.go
- settings_notify.go
- site_announcements.go
- sites.go
- stats.go
- stats_balance.go
- stats_heatmap.go
- stats_helpers.go
- stats_latency.go
- stats_marketplace.go
- tags.go
- tasks.go
- test.go
- token_routes.go
- token_routes_channels.go
- token_routes_decisions.go
- update_center.go