admin

package
v0.28.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 31, 2026 License: AGPL-3.0 Imports: 65 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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

func AuditMiddleware(db *sqlx.DB) func(http.Handler) http.Handler

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

func IsMaskedTokenValue(token string) bool

IsMaskedTokenValue checks if a token value contains masking characters.

func RegisterAboutRoutes added in v0.16.5

func RegisterAboutRoutes(r chi.Router)

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

func RegisterAccountTokensRoutes(r chi.Router, db *sqlx.DB)

RegisterAccountTokensRoutes registers all /api/account-tokens routes.

func RegisterAccountTokensRoutesWithConfig

func RegisterAccountTokensRoutesWithConfig(r chi.Router, db *sqlx.DB, cfg *config.Config)

RegisterAccountTokensRoutesWithConfig is like RegisterAccountTokensRoutes but accepts optional runtime config for proxy-aware upstream calls.

func RegisterAccountsRoutes

func RegisterAccountsRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)

RegisterAccountsRoutes registers all /api/accounts routes.

func RegisterAnnouncementsRoutes

func RegisterAnnouncementsRoutes(r chi.Router, db *sqlx.DB)

RegisterAnnouncementsRoutes mounts the announcement endpoints.

func RegisterAuditLogsRoutes

func RegisterAuditLogsRoutes(r chi.Router, db *sqlx.DB)

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

func RegisterAuthSettingsRoutes(r chi.Router, db *sqlx.DB, sessions *auth.SessionManager)

RegisterAuthSettingsRoutes registers all /api/settings/auth routes. sessions may be nil (tests): rotation then skips session revocation.

func RegisterBackupRoutes

func RegisterBackupRoutes(r chi.Router, db *sqlx.DB)

RegisterBackupRoutes registers all /api/settings/backup routes.

func RegisterCatalogSourceRoutes added in v0.16.9

func RegisterCatalogSourceRoutes(r chi.Router, db *sqlx.DB)

RegisterCatalogSourceRoutes mounts the catalog registry + sync endpoints.

func RegisterChannelTestRoutes

func RegisterChannelTestRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)

RegisterChannelTestRoutes registers admin-only forced-channel probe endpoints.

POST /api/admin/test-channel
POST /api/debug/channel-probe (alias)

func RegisterCheckinRoutes

func RegisterCheckinRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)

RegisterCheckinRoutes registers all /api/checkin routes.

func RegisterDatabaseRoutes

func RegisterDatabaseRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)

RegisterDatabaseRoutes registers all /api/settings/database routes.

func RegisterDownstreamKeysRoutes

func RegisterDownstreamKeysRoutes(r chi.Router, db *sqlx.DB)

RegisterDownstreamKeysRoutes registers all /api/downstream-keys routes.

func RegisterDownstreamPricingRoutes

func RegisterDownstreamPricingRoutes(r chi.Router, db *sqlx.DB)

Mounted under /v1/* so it inherits ProxyAuth + CORS from the /v1 route group.

func RegisterEventsRoutes

func RegisterEventsRoutes(r chi.Router, db *sqlx.DB)

RegisterEventsRoutes registers all /api/events routes.

func RegisterGatewayUserRoutes added in v0.27.0

func RegisterGatewayUserRoutes(r chi.Router, db *store.DB)

RegisterGatewayUserRoutes configures the single system's ordinary users and groups. Only the deployment administrator may use this surface. It does not issue a user credential, session or downstream Key.

func RegisterImportedUpstreamRoutes added in v0.23.0

func RegisterImportedUpstreamRoutes(r chi.Router, db *sqlx.DB)

Imported upstreams are distinct from native account-backed route channels. These projections deliberately never select credentials or custom headers.

func RegisterMaintenanceRoutes

func RegisterMaintenanceRoutes(r chi.Router, db *sqlx.DB)

RegisterMaintenanceRoutes registers all /api/settings/maintenance routes.

func RegisterModelRatesRoutes

func RegisterModelRatesRoutes(r chi.Router, db *sqlx.DB)

RegisterModelRatesRoutes mounts the rate overview endpoint.

func RegisterModelRedirectRoutes

func RegisterModelRedirectRoutes(r chi.Router, db *sqlx.DB)

RegisterModelRedirectRoutes mounts the redirect endpoints.

func RegisterMonitorHealthRoute added in v0.11.0

func RegisterMonitorHealthRoute(r chi.Router, db *sqlx.DB)

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

func RegisterMonitorProxyRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)

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. The handler enforces the cookie itself via ensureMonitorAuth; keep this registrar outside any Bearer-gated group.

func RegisterMonitorRoutes

func RegisterMonitorRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)

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

func RegisterNotifyRoutes(r chi.Router)

RegisterNotifyRoutes registers the /api/settings/notify/test route.

func RegisterOauthRoutes

func RegisterOauthRoutes(r chi.Router, db *sqlx.DB)

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

func RegisterOpsWSRoutes(r chi.Router, cfg *config.Config, sessions *auth.SessionManager)

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

func RegisterResinRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)

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

func RegisterSchedulerStatusRoutes(r chi.Router, db *sqlx.DB)

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

func RegisterSearchRoutes(r chi.Router, db *sqlx.DB)

RegisterSearchRoutes registers all /api/search routes.

func RegisterSessionRoutes added in v0.16.19

func RegisterSessionRoutes(r chi.Router, cfg *config.Config, sessions *auth.SessionManager)

RegisterSessionRoutes mounts the admin session lifecycle endpoints. sessions may be nil (DB-less boot): all endpoints then fail closed.

func RegisterSettingsRoutes

func RegisterSettingsRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)

RegisterSettingsRoutes registers all /api/settings routes (runtime, brand-list, system-proxy/test).

func RegisterSiteAnnouncementsRoutes

func RegisterSiteAnnouncementsRoutes(r chi.Router, db *sqlx.DB)

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

func RegisterSitesRoutes(r chi.Router, db *sqlx.DB)

RegisterSitesRoutes registers all /api/sites routes.

func RegisterStatsRoutes

func RegisterStatsRoutes(r chi.Router, db *sqlx.DB)

RegisterStatsRoutes registers all /api/stats and /api/models routes.

func RegisterTagsRoutes

func RegisterTagsRoutes(r chi.Router, db *sqlx.DB)

RegisterTagsRoutes mounts the tag endpoints behind admin auth.

func RegisterTasksRoutes

func RegisterTasksRoutes(r chi.Router, db *sqlx.DB)

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

func RegisterTestRoutes(r chi.Router, db *sqlx.DB, cfg *config.Config)

RegisterTestRoutes registers all /api/test routes.

Known limitation: - sync chat probes alias the forced-channel harness when a channel/site is forced - full path/multipart routing matrix without a forced channel returns an honest 501 residual

func RegisterTokenRoutesWithDeps

func RegisterTokenRoutesWithDeps(r chi.Router, db *sqlx.DB, deps TokenRoutesDeps)

RegisterTokenRoutesWithDeps registers routes with optional decision engine deps.

func RegisterUpdateCenterRoutes

func RegisterUpdateCenterRoutes(r chi.Router)

RegisterUpdateCenterRoutes registers the /api/update-center routes.

Known limitation: - status is a local stub (never invent updateAvailable=true) - deploy/rollback/task-stream surfaces are removed; product updates stay external.

func RegisterUpstreamCatalogRoutes added in v0.24.0

func RegisterUpstreamCatalogRoutes(r chi.Router, db *sqlx.DB)

RegisterUpstreamCatalogRoutes adds explicit native catalog creation without taking over the imported connection/member maintenance endpoints.

func RegisterUpstreamLifecycleRoutes added in v0.24.0

func RegisterUpstreamLifecycleRoutes(r chi.Router, db *sqlx.DB)

func RegisterUpstreamPresetRoutes added in v0.24.0

func RegisterUpstreamPresetRoutes(r chi.Router)

RegisterUpstreamPresetRoutes exposes only local configuration projections. Resolving a preset makes no outbound request and reads no credentials.

func RegisterUserActivationRoutes added in v0.27.0

func RegisterUserActivationRoutes(r chi.Router, db *store.DB, sessions *auth.UserSessionManager)

RegisterUserActivationRoutes is admin-only, reconfirmed and audited by the existing admin group. Reset codes appear only in this no-store POST result.

func RegisterUserBudgetRoutes added in v0.27.0

func RegisterUserBudgetRoutes(r chi.Router, db *store.DB)

RegisterUserBudgetRoutes inherits the admin audit middleware. The local guard also protects standalone mounts and requires reauthentication on writes.

func SetBackgroundTaskDB

func SetBackgroundTaskDB(db *sqlx.DB)

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

type BackgroundTaskStartOptions struct {
	Type      string
	Title     string
	DedupeKey string
	KeepMs    int64
}

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL