diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3e455759..97699582 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -214,7 +214,7 @@ jobs: -f deploy/helm/orbit/values-prod.example.yaml > /dev/null helm template orbit deploy/helm/orbit -n orbit -f deploy/helm/orbit/values.yaml \ --set auth.acknowledgeInsecureDev=true \ - --set networkPolicy.enabled=true \ + --set networkPolicy.enabled=true --set monitoring.port=9090 \ --set worker.enabled=true --set worker.token=render-check-only > /dev/null helm template orbit deploy/helm/orbit -n orbit -f deploy/helm/orbit/values.yaml \ --set auth.acknowledgeInsecureDev=true \ @@ -223,6 +223,21 @@ jobs: --set monitoring.port=9090 \ --set monitoring.token.existingSecret=render-check-only > /dev/null + # Worker pods (agent code) must not reach an unauthenticated /metrics (#398). + - name: helm template (metrics are not reachable from workers) + run: | + if helm template orbit deploy/helm/orbit -n orbit -f deploy/helm/orbit/values.yaml \ + --set auth.acknowledgeInsecureDev=true --set networkPolicy.enabled=true > /dev/null 2>&1; then + echo "::error::networkPolicy without monitoring.port or token must be refused"; exit 1 + fi + out="$(helm template orbit deploy/helm/orbit -n orbit -f deploy/helm/orbit/values-prod.example.yaml)" + grep -q 'value: "0.0.0.0:9090"' <<<"$out" + workers="$(awk '/^kind: NetworkPolicy/{p=0} /name: orbit-workers$/{p=1} p' <<<"$out")" + grep -q 'port: 8080' <<<"$workers" + if grep -q 'port: 9090' <<<"$workers"; then + echo "::error::worker NetworkPolicy allows the metrics port"; exit 1 + fi + # ---------------------------------------------------------------- migrations # AGENTS.md rule 7: migrations are append-only. A migration that already exists on the # base branch may have been applied somewhere, so a change may add files but never diff --git a/changelog.d/398.changed.md b/changelog.d/398.changed.md new file mode 100644 index 00000000..56ad7895 --- /dev/null +++ b/changelog.d/398.changed.md @@ -0,0 +1 @@ +- Helm: with `networkPolicy.enabled=true` the chart refuses to serve `/metrics` without a token on the API port, which worker pods can reach. Set `monitoring.port` (as `values-prod.example.yaml` now does) or `monitoring.token`, or set `monitoring.allowWorkersOnApiPort=true` to accept the exposure ([#398](https://github.com/opsifyhq/orbit/issues/398)). diff --git a/changelog.d/398.fixed.md b/changelog.d/398.fixed.md new file mode 100644 index 00000000..77a72c81 --- /dev/null +++ b/changelog.d/398.fixed.md @@ -0,0 +1 @@ +- Metrics: the HTTP request families no longer reach their series cap in normal use (it is now sized for every route template, method and status class), and the in-flight execution count uses a new partial index instead of reading every execution, so scrapes stay cheap as history grows ([#398](https://github.com/opsifyhq/orbit/issues/398)). diff --git a/crates/orbit-api/src/metrics.rs b/crates/orbit-api/src/metrics.rs index 1074eea0..f0ff689c 100644 --- a/crates/orbit-api/src/metrics.rs +++ b/crates/orbit-api/src/metrics.rs @@ -29,6 +29,11 @@ use orbit_store::ExecutionRecord; /// Upper bound on distinct label sets per metric family. const MAX_SERIES_PER_FAMILY: usize = 200; +/// Cap for the HTTP families, whose label sets grow with the route table: every route +/// template times every method label (8, including `other`) times every status class +/// (5) must fit, so normal traffic (405s and CORS preflights included) never drops a +/// series. `routes_fit_the_http_series_cap` keeps this in step with `routes.rs`. +const MAX_HTTP_SERIES: usize = 8192; /// How long a database snapshot is reused, so scraping cannot load the database. const SNAPSHOT_TTL: Duration = Duration::from_secs(10); @@ -320,7 +325,7 @@ impl Metrics { let labels = owned(labels); let mut registry = self.lock(); let series = registry.counters.entry(name).or_default(); - if !series.contains_key(&labels) && series.len() >= MAX_SERIES_PER_FAMILY { + if !series.contains_key(&labels) && series.len() >= series_cap(name) { self.dropped.fetch_add(1, Ordering::Relaxed); return; } @@ -340,7 +345,7 @@ impl Metrics { let labels = owned(labels); let mut registry = self.lock(); let series = registry.histograms.entry(name).or_default(); - if !series.contains_key(&labels) && series.len() >= MAX_SERIES_PER_FAMILY { + if !series.contains_key(&labels) && series.len() >= series_cap(name) { self.dropped.fetch_add(1, Ordering::Relaxed); return; } @@ -696,6 +701,14 @@ impl EventBus for MeteredBus { } } +/// Series cap for one family: the HTTP families are keyed by route template. +fn series_cap(name: &str) -> usize { + match name { + "orbit_http_requests_total" | "orbit_http_request_duration_seconds" => MAX_HTTP_SERIES, + _ => MAX_SERIES_PER_FAMILY, + } +} + fn family(name: &str) -> Option<&'static Family> { FAMILIES.iter().find(|family| family.name == name) } @@ -955,6 +968,61 @@ mod tests { .contains("orbit_provider_probes_total{kind=\"kind-0\",result=\"ok\"} 2\n")); } + /// Route templates registered in `routes.rs` (the first string after each `.route(`). + fn route_templates() -> Vec { + let source = include_str!("routes.rs"); + let mut templates: Vec = source + .split(".route(") + .skip(1) + .filter_map(|rest| { + let start = rest.find('"')? + 1; + let end = start + rest[start..].find('"')?; + Some(rest[start..end].to_string()) + }) + // routes.rs also mentions `.route(` in code; templates start with "/". + .filter(|template| template.starts_with('/')) + .collect(); + // Swagger UI and the 404 fallback add a few labels of their own. + templates + .extend(["/docs", "/docs/", "/docs/{*rest}", "/api/v1/openapi.json"].map(String::from)); + templates.push("unmatched".to_string()); + templates.sort(); + templates.dedup(); + templates + } + + #[test] + fn routes_fit_the_http_series_cap() { + let templates = route_templates(); + assert!(templates.len() > 100, "parsed {} routes", templates.len()); + let methods = [ + "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD", "TRACE", + ]; + let statuses = [101, 200, 304, 404, 503]; + assert!( + templates.len() * methods.len() * statuses.len() <= MAX_HTTP_SERIES, + "{} routes need a larger MAX_HTTP_SERIES", + templates.len() + ); + // Every route with every method and status class: nothing is dropped. + let metrics = Metrics::new(); + for template in &templates { + for method in methods { + for status in statuses { + metrics.http_started(); + metrics.http_finished(method, template, status, Duration::from_millis(3)); + } + } + } + let text = metrics.render(&[]); + assert!(text.contains("orbit_metrics_dropped_series_total 0\n")); + let series = text + .lines() + .filter(|line| line.starts_with("orbit_http_requests_total{")) + .count(); + assert_eq!(series, templates.len() * methods.len() * statuses.len()); + } + fn execution(status: &str) -> ExecutionRecord { let now = chrono::Utc::now(); ExecutionRecord { diff --git a/crates/orbit-store/migrations/0066_executions_in_flight_idx.sql b/crates/orbit-store/migrations/0066_executions_in_flight_idx.sql new file mode 100644 index 00000000..f26f0741 --- /dev/null +++ b/crates/orbit-store/migrations/0066_executions_in_flight_idx.sql @@ -0,0 +1,10 @@ +-- /metrics counts in-flight executions across all organizations on every snapshot +-- (metrics_snapshot). executions_status_idx is keyed (org_id, status) and covers +-- every row ever written, so that count read the whole index and grew with history. +-- This partial index holds only in-flight rows; the query names the same literal +-- statuses so the planner can match the predicate (a bound array cannot). +-- Plain CREATE INDEX (see 0051): on a very large install, create it by hand with +-- CONCURRENTLY before upgrading. +CREATE INDEX IF NOT EXISTS executions_in_flight_status_idx + ON executions (status) + WHERE status IN ('queued', 'dispatched', 'running', 'awaiting_approval'); diff --git a/crates/orbit-store/src/metrics.rs b/crates/orbit-store/src/metrics.rs index 81c58ada..155c3194 100644 --- a/crates/orbit-store/src/metrics.rs +++ b/crates/orbit-store/src/metrics.rs @@ -8,8 +8,16 @@ use chrono::{Duration, Utc}; use crate::{Store, StoreResult}; -/// Statuses in which an execution still occupies a queue slot or a worker. +/// Statuses in which an execution still occupies a queue slot or a worker. The +/// in-flight count ([`IN_FLIGHT_COUNT_SQL`]) and migration 0066 repeat them as literals; +/// `in_flight_query_matches_the_statuses` keeps the three in step. pub const IN_FLIGHT_STATUSES: [&str; 4] = ["queued", "dispatched", "running", "awaiting_approval"]; +/// The in-flight count. The statuses are literals, not a bound array, so the planner can +/// use the partial `executions_in_flight_status_idx` (migration 0066), whose predicate +/// lists the same statuses; its cost no longer grows with finished executions. +pub const IN_FLIGHT_COUNT_SQL: &str = "SELECT status, COUNT(*) FROM executions \ + WHERE status IN ('queued', 'dispatched', 'running', 'awaiting_approval') \ + GROUP BY status"; /// Statuses in which a launched worker is still (coming) up. pub const LIVE_LAUNCH_STATUSES: [&str; 3] = ["pending", "starting", "running"]; @@ -32,12 +40,9 @@ impl Store { &self, heartbeat_stale_seconds: i64, ) -> StoreResult { - let executions: Vec<(String, i64)> = sqlx::query_as( - "SELECT status, COUNT(*) FROM executions WHERE status = ANY($1) GROUP BY status", - ) - .bind(IN_FLIGHT_STATUSES.map(String::from).to_vec()) - .fetch_all(&self.pool) - .await?; + let executions: Vec<(String, i64)> = sqlx::query_as(IN_FLIGHT_COUNT_SQL) + .fetch_all(&self.pool) + .await?; let launches: Vec<(String, i64)> = sqlx::query_as( r#" SELECT status, COUNT(*) FROM worker_launches @@ -98,7 +103,26 @@ fn with_zeroes(known: &[&str], counted: Vec<(String, i64)>) -> Vec<(String, i64) #[cfg(test)] mod tests { - use super::with_zeroes; + use super::{with_zeroes, IN_FLIGHT_COUNT_SQL, IN_FLIGHT_STATUSES}; + + #[test] + fn in_flight_query_matches_the_statuses() { + let listed = IN_FLIGHT_STATUSES + .iter() + .map(|status| format!("'{status}'")) + .collect::>() + .join(", "); + let predicate = format!("status IN ({listed})"); + assert!( + IN_FLIGHT_COUNT_SQL.contains(&predicate), + "{IN_FLIGHT_COUNT_SQL}" + ); + let migration = include_str!("../migrations/0066_executions_in_flight_idx.sql"); + assert!( + migration.contains(&predicate), + "the index predicate must match" + ); + } #[test] fn missing_statuses_are_reported_as_zero() { diff --git a/crates/orbit-store/tests/store_integration.rs b/crates/orbit-store/tests/store_integration.rs index afbba8cf..0079e0ef 100644 --- a/crates/orbit-store/tests/store_integration.rs +++ b/crates/orbit-store/tests/store_integration.rs @@ -4425,6 +4425,43 @@ async fn installation_wide_execution_count_uses_created_at_index() { tx.rollback().await.unwrap(); } +#[tokio::test] +async fn in_flight_metrics_count_uses_the_partial_index() { + let Some(store) = test_store().await else { + return; + }; + let pool = store.pool(); + // Disable sequential scans for this plan only (a tiny test table favours them) to + // prove the partial index serves the exact query /metrics runs (#398). + let mut tx = pool.begin().await.unwrap(); + sqlx::query("SET LOCAL enable_seqscan = off") + .execute(&mut *tx) + .await + .unwrap(); + // A constant query text, so wrapping it is safe. + let lines: Vec = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "EXPLAIN {}", + orbit_store::metrics::IN_FLIGHT_COUNT_SQL + ))) + .fetch_all(&mut *tx) + .await + .unwrap(); + let plan = lines.join("\n"); + // Any index whose predicate is the in-flight statuses keeps the cost independent of + // finished executions; on a tiny table the planner sometimes picks the older + // executions_agent_active_idx (same predicate, migration 0051) over the new one. + assert!( + plan.contains("executions_in_flight_status_idx") + || plan.contains("executions_agent_active_idx"), + "expected a partial in-flight index, got: {plan}" + ); + assert!( + !plan.contains("executions_status_idx") && !plan.contains("Seq Scan"), + "the full (org_id, status) index or the table must not be scanned: {plan}" + ); + tx.rollback().await.unwrap(); +} + // --------------------------------------------------------------------------- // Per-execution liveness and worker boot identity (#342) // --------------------------------------------------------------------------- diff --git a/deploy/helm/orbit/README.md b/deploy/helm/orbit/README.md index b030096a..cc909997 100644 --- a/deploy/helm/orbit/README.md +++ b/deploy/helm/orbit/README.md @@ -285,6 +285,7 @@ catalogue and examples: `docs/development/observability.md`. | `monitoring.serviceMonitor.interval` / `.scrapeTimeout` | `30s` / `10s` | | | `monitoring.serviceMonitor.scheme` / `.tlsConfig` | `http` / `{}` | | | `monitoring.serviceMonitor.relabelings` / `.metricRelabelings` | `[]` / `[]` | | +| `monitoring.allowWorkersOnApiPort` | `false` | with `networkPolicy.enabled`, the chart refuses `/metrics` on `api.port` without a token, because worker pods can reach that port. Set `monitoring.port` or a token, or `true` to accept the exposure | | `monitoring.allowFrom` | `[]` | with `networkPolicy.enabled` and `monitoring.port`: peers allowed to reach the metrics port (empty = any) | ## Troubleshooting diff --git a/deploy/helm/orbit/templates/_helpers.tpl b/deploy/helm/orbit/templates/_helpers.tpl index 282341f8..538bc964 100644 --- a/deploy/helm/orbit/templates/_helpers.tpl +++ b/deploy/helm/orbit/templates/_helpers.tpl @@ -158,6 +158,9 @@ Production guardrails. Included from templates/validate.yaml so it runs on every {{- if and .Values.monitoring.serviceMonitor.enabled .Values.monitoring.token.existingSecret .Values.monitoring.serviceMonitor.namespace (ne (toString .Values.monitoring.serviceMonitor.namespace) .Release.Namespace) -}} {{- fail "monitoring.serviceMonitor.namespace must be the release namespace when monitoring.token.existingSecret is set: the ServiceMonitor reads the token Secret from its own namespace." -}} {{- end -}} +{{- if and .Values.networkPolicy.enabled (not .Values.monitoring.port) (not .Values.monitoring.token.existingSecret) (not .Values.monitoring.allowWorkersOnApiPort) -}} +{{- fail "networkPolicy.enabled=true lets worker pods reach orbit-api's port, and /metrics is served there without a token, so agent code could read installation-wide figures such as orbit_license_usage. Set monitoring.port (for example 9090; workers cannot reach it and monitoring.allowFrom limits who can), or monitoring.token.existingSecret, or set monitoring.allowWorkersOnApiPort=true to accept the exposure." -}} +{{- end -}} {{- if and .Values.ingress.enabled (eq (toString .Values.auth.mode) "dev") .Values.auth.dev.allowAnonymous (not .Values.auth.acknowledgeInsecureDev) -}} {{- fail "ingress.enabled=true with auth.mode=dev and auth.dev.allowAnonymous=true exposes an anonymous Owner UI. Use auth.mode=oidc (see values-prod.example.yaml), set auth.dev.allowAnonymous=false, disable the ingress, or set auth.acknowledgeInsecureDev=true for a throwaway local/test cluster." -}} {{- end -}} diff --git a/deploy/helm/orbit/values-prod.example.yaml b/deploy/helm/orbit/values-prod.example.yaml index 802ea98f..a4995664 100644 --- a/deploy/helm/orbit/values-prod.example.yaml +++ b/deploy/helm/orbit/values-prod.example.yaml @@ -185,6 +185,16 @@ launcher: networkPolicy: enabled: true +# Serve /metrics on its own port. Worker pods may reach only the API port, so agent code +# cannot read the metrics; the chart refuses networkPolicy without this (or a token). +# Limit who may scrape with monitoring.allowFrom, for example: +# allowFrom: +# - namespaceSelector: +# matchLabels: +# kubernetes.io/metadata.name: monitoring +monitoring: + port: 9090 + platform: environment: production seedDemo: false diff --git a/deploy/helm/orbit/values.yaml b/deploy/helm/orbit/values.yaml index 5cde47b7..40a21089 100644 --- a/deploy/helm/orbit/values.yaml +++ b/deploy/helm/orbit/values.yaml @@ -230,6 +230,10 @@ monitoring: # /healthz, and the API port then stops serving /metrics. Use it to keep scrapes out # of the anonymous rate limit and to isolate the port with a NetworkPolicy. port: 0 + # With networkPolicy.enabled, worker pods (agent code) can reach the API port, so the + # chart refuses an unauthenticated /metrics there: set `port` or `token`, or set this + # to true to accept that agents can read the installation-wide gauges. + allowWorkersOnApiPort: false # Require scrapers to send a bearer token. The Secret must be in the release # namespace; the ServiceMonitor below references the same Secret. token: diff --git a/docs/development/deployment.md b/docs/development/deployment.md index f917ec62..2422986a 100644 --- a/docs/development/deployment.md +++ b/docs/development/deployment.md @@ -162,7 +162,7 @@ Key values (all in `deploy/helm/orbit/values.yaml`): | `launcher.authSecrets` | `orbit-opencode-auth*,orbit-pi-auth*` | Secret names (exact or `prefix*`) a worker profile may mount as `authSecretName`. Empty allows none. Sets `ORBIT_WORKER_AUTH_SECRETS` on the API and the launcher | | `launcher.imagePullSecret` | empty | Pull secret added to every pod the launcher creates | | `launcher.admissionPolicy.enabled` | `true` | ValidatingAdmissionPolicies that limit what the launcher ServiceAccount may create (names, Secret types, mounted Secrets, host access). Kubernetes 1.30+; cluster-scoped, so disable it when the installer has only namespace rights. See [kubernetes-launcher.md](kubernetes-launcher.md) | -| `networkPolicy.enabled` | `false` | NetworkPolicies: PostgreSQL, NATS and the launcher accept only the API; worker pods accept nothing and reach only DNS, the API and addresses outside `networkPolicy.worker.egressExcept`. Needs a CNI that enforces NetworkPolicy. On in `values-prod.example.yaml` | +| `networkPolicy.enabled` | `false` | NetworkPolicies: PostgreSQL, NATS and the launcher accept only the API; worker pods accept nothing and reach only DNS, the API and addresses outside `networkPolicy.worker.egressExcept`. Needs a CNI that enforces NetworkPolicy. On in `values-prod.example.yaml`. Requires `monitoring.port` or `monitoring.token` (or `monitoring.allowWorkersOnApiPort=true`), since workers reach the API port | | `networkPolicy.worker.egressCidrs`, `.egressExcept`, `.extraEgress` | `0.0.0.0/0`, `::/0` minus private, CGNAT and link-local ranges; none | Worker egress. Add private Git hosts or model servers as `extraEgress` rules | | `api.autoMigrate` | `true` | Apply migrations on API start-up (`ORBIT_DB_AUTO_MIGRATE`); they take an advisory lock, so several replicas are safe | | `api.podDisruptionBudget.enabled`, `.minAvailable` | `false`, `1` | PodDisruptionBudget for the API; on in `values-prod.example.yaml` | diff --git a/docs/development/observability.md b/docs/development/observability.md index b65ba41a..ec2dd08d 100644 --- a/docs/development/observability.md +++ b/docs/development/observability.md @@ -76,6 +76,12 @@ networkPolicy: With a token, the ServiceMonitor must live in the release namespace, because Prometheus reads the token Secret from the ServiceMonitor's namespace. +Worker pods may reach the API port (they call the worker protocol there), so agent code +could read an unauthenticated `/metrics` served on it, including `orbit_license_usage`. +With `networkPolicy.enabled=true` the chart therefore refuses to render unless +`monitoring.port` or `monitoring.token` is set; worker egress never includes the +dedicated port. Set `monitoring.allowWorkersOnApiPort=true` to accept the exposure. + ### Without Kubernetes ```yaml @@ -170,7 +176,7 @@ scrape_configs: | Metric | Type | Meaning | |---|---|---| | `orbit_metrics_collect_errors_total` | counter | Scrapes for which the database gauges could not be read. | -| `orbit_metrics_dropped_series_total` | counter | Samples dropped because a family reached its series cap (200). Should stay 0. | +| `orbit_metrics_dropped_series_total` | counter | Samples dropped because a family reached its series cap (8192 for the two HTTP families, sized for every route template × method × status class; 200 for the others). Should stay 0. | ## Cardinality and privacy diff --git a/docs/security/threat-analysis.md b/docs/security/threat-analysis.md index 54014589..93efaa4a 100644 --- a/docs/security/threat-analysis.md +++ b/docs/security/threat-analysis.md @@ -223,7 +223,10 @@ Container images are **not** scanned for vulnerabilities in CI; see "Residual ri restrict it further, set `ORBIT_METRICS_TOKEN` (bearer token, compared as SHA-256 digests; 401 without it) and/or `ORBIT_METRICS_ADDR` (dedicated listener that serves only `/metrics` and `/healthz`; the API port then returns 404 for `/metrics`), and limit the - port with `networkPolicy.enabled` and `monitoring.allowFrom`. The API logs a warning at + port with `networkPolicy.enabled` and `monitoring.allowFrom`. Worker pods (agent code) + may reach the API port, so with `networkPolicy.enabled` the chart refuses an + unauthenticated `/metrics` on that port unless `monitoring.allowWorkersOnApiPort=true`; + the dedicated port is outside worker egress. The API logs a warning at start when it runs in production with neither set. The dedicated listener has no rate limit, so do not publish it. See [Observability](../development/observability.md).