From 790cdd43c8a7fd46c1ebedc02039d91a46b822d8 Mon Sep 17 00:00:00 2001 From: atlas Date: Mon, 30 Nov 2026 15:25:53 +0100 Subject: [PATCH] gateway: answer 503 for a store outage and 429 for the rate limit, and retry both in swarm-logs and swarm-metrics --- docs/4-implementation/swarm/telemetry.md | 26 +- docs/5-project/process/conventions.md | 5 +- nix/host-modules/swarm-victorialogs.nix | 42 ++- nix/host-modules/swarm-victoriametrics.nix | 37 ++- nix/module-eval/core-toggle.nix | 44 ++- nix/module-eval/swarm-otel-identity.nix | 2 +- swarm-agent-verify/src/lib.rs | 76 ++++- swarm-agent-verify/src/retry.rs | 323 +++++++++++++++++++++ swarm-logs-auth/src/main.rs | 142 ++++++--- swarm-logs/Cargo.toml | 2 +- swarm-logs/README.md | 8 +- swarm-logs/src/query.rs | 21 +- swarm-metrics-auth/src/main.rs | 75 +++-- swarm-metrics/Cargo.toml | 2 +- swarm-metrics/README.md | 8 +- swarm-metrics/src/query.rs | 21 +- 16 files changed, 709 insertions(+), 125 deletions(-) create mode 100644 swarm-agent-verify/src/retry.rs diff --git a/docs/4-implementation/swarm/telemetry.md b/docs/4-implementation/swarm/telemetry.md index 09a04f53d..75f990e19 100644 --- a/docs/4-implementation/swarm/telemetry.md +++ b/docs/4-implementation/swarm/telemetry.md @@ -37,8 +37,8 @@ See `retentionPeriod` below before leaving it at its default. | `swarm.grafana.oidc.role` | Default `Admin` for everyone who logs in. Lower to `Viewer`/`Editor` if the swarm grows operators who shouldn't be able to reconfigure Grafana. | | `deploy.grafana.datasourceUrl` | Only if you front VictoriaMetrics with something else. It defaults to the store's swarm name (`https://`), so Grafana and the store can run on different hosts. | | `deploy.grafana.logsDatasourceUrl` | Only if you front VictoriaLogs with something else. It defaults to the log store's swarm name (`https://`), so Grafana and the store can run on different hosts. | -| `deploy.victoriametrics.agentAuthRate` | Default `50r/s` per client address, for agent reads checked by `swarm-metrics-agent-auth`; over it and `agentAuthBurst`, the gateway answers 403. | -| `deploy.victoriametrics.agentAuthBurst` | Default `500` requests above `agentAuthRate` before the 403s start. | +| `deploy.victoriametrics.agentAuthRate` | Default `50r/s` per client address, for agent reads checked by `swarm-metrics-agent-auth`; over it and `agentAuthBurst`, the gateway answers 429. | +| `deploy.victoriametrics.agentAuthBurst` | Default `500` requests above `agentAuthRate` before the 429s start. | | `deploy.victoriametrics.agentAuthVerdictTtl` | Default `60` seconds that `swarm-metrics-agent-auth` keeps granting an agent secret it verified. A replaced or deleted secret keeps working at the metrics store for up to that long. A revoked `metrics` permission does too. | | `deploy.victoriametrics.agentAuthPackage` | The `swarm-logs-auth` build that runs as `swarm-metrics-agent-auth`. Set on its own: `deploy.victorialogs.authPackage` doesn't reach it. | @@ -124,6 +124,18 @@ vhost does it: any other session or client there, operators included. - **Every other path**, the store's write and admin API included: 403. +The read API's answer says why a request failed. A bearer that doesn't match is +a 401, a missing `metrics` permission a 403, and a request over +`agentAuthRate` a 429. A secret store that can't answer within five seconds +makes the responder answer 503, which grants nothing. `auth_request` turns +every subrequest status but 2xx, 401 and 403 into a 500, so each read location +sends a failed `auth_request` to `@swarm_metrics_auth_failed`, which answers 503 +when the responder did and 500 otherwise. The rate limit sits on the read +locations, not on the responder's subrequest, so a 429 reaches the caller, and +it counts only requests with a `swarm-agent.` bearer. `swarm-metrics` waits and +retries a 503 or a 429, three tries in all, and the error after the last one +says the store is unavailable or rate limited. A 403 isn't retried. + The gateway remembers authelia's answer for the collector's push route. It keys the answer on the request's `Authorization` header and the route, keeps only a 200, and keeps it for 60 seconds. A burst of pushes from one token costs authelia one subrequest, and a push that finds its verdict in the cache doesn't wait on authelia, however slow it is. A 401 or 403 always goes to authelia again. A request without an `Authorization` header skips the cache, and the subrequest drops the `Cookie` header. A revoked or expired token keeps pushing for up to 60 seconds. The `/metrics` scrape and the other routes ask authelia every time. `swarm-metrics-auth` and `swarm-metrics-agent-auth` read the store with one @@ -137,9 +149,9 @@ store doesn't answer within five seconds, it checks requests against the last value it read instead of denying, and still refuses a wrong bearer; it tries the store again after three seconds. A revoked or rotated bearer stays accepted while the store is down, for an hour after the last read at -most; after that the responder denies again. The store's next answer +most; after that the responder answers 503, which grants nothing. The store's next answer replaces the value, and a process that holds none (it started while the -store was down) denies. `swarm-logs-grafana-auth` +store was down) answers 503 too. `swarm-logs-grafana-auth` is the same binary and does the same. `swarm-metrics-agent-auth` is the log store's `swarm-logs-auth` binary, with @@ -183,8 +195,8 @@ swarm. | Option | When you'd touch it | | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `deploy.victorialogs.retentionPeriod` | Default `30d`, far shorter than the metrics store's — logs are bulkier per unit of value and are typically read within days of ingestion. Raise it if you need to answer questions about last quarter. | -| `deploy.victorialogs.authRate` | Default `50r/s` per client address, for agent queries checked by `swarm-logs-auth`; over it and `authBurst`, the gateway answers 403. Agents on one host share the address; the default covers about a hundred cold-starting together. | -| `deploy.victorialogs.authBurst` | Default `500` requests above `authRate` before the 403s start. | +| `deploy.victorialogs.authRate` | Default `50r/s` per client address, for agent queries checked by `swarm-logs-auth`; over it and `authBurst`, the gateway answers 429. Agents on one host share the address; the default covers about a hundred cold-starting together. | +| `deploy.victorialogs.authBurst` | Default `500` requests above `authRate` before the 429s start. | | `deploy.victorialogs.authVerdictTtl` | Default `60` seconds that `swarm-logs-auth` keeps granting an agent secret it verified, without asking the secret store. A replaced or deleted secret keeps working at the log store for up to that long. A revoked `logs` permission does too. | | `deploy.victorialogs.grafanaAuthPackage` | The `swarm-metrics-auth` build that runs as `swarm-logs-grafana-auth`. Set on its own: `deploy.victoriametrics.authPackage` doesn't reach it. | | `swarm.victorialogs.domain` | Only to rename it. | @@ -198,7 +210,7 @@ intended writer. **Who may query.** `/select/logsql/` takes one of three credentials. An agent presents its `swarm-agent..` bearer, checked by `swarm-logs-auth`. The agent must also hold the `logs` permission, -which is off by default; without it the answer is a 403 (`docs/5-project/process/conventions.md`, Permissions). Grafana's datasource presents the same bearer as its +which is off by default; without it the answer is a 403 (`docs/5-project/process/conventions.md`, Permissions). A secret store that can't answer makes `swarm-logs-auth` answer 503, and `/select/logsql/` hands that 503 on through `@swarm_logs_auth_failed`; a request over `authRate` gets a 429. `swarm-logs` retries both, three tries in all, and names the cause when they run out. Grafana's datasource presents the same bearer as its metrics datasource, which `swarm-bao-grafana-metrics-bearer` creates, and a second `swarm-metrics-auth` instance (`swarm-logs-grafana-auth`) on the log store's host checks it against the same store path; the gateway tells it from diff --git a/docs/5-project/process/conventions.md b/docs/5-project/process/conventions.md index 21c82ef98..25b4599fa 100644 --- a/docs/5-project/process/conventions.md +++ b/docs/5-project/process/conventions.md @@ -294,7 +294,10 @@ because logs are the more sensitive. Grant one with `swarmctl agent permissions set ` (listing it with the others) or the create-agent screen; the setup assistant creates ruth with both, through the `ruth` archetype. An agent without it gets a 403 from the store's gateway when `swarm-logs` or -`swarm-metrics` queries; a bad secret is still a 401. +`swarm-metrics` queries; a bad secret is still a 401. A 503 means the store +behind the gateway couldn't answer, and a 429 means the agent's host is over +its rate. `swarm-logs` and `swarm-metrics` retry both, and neither is a missing +permission. An agent decodes its own record, in its harness (`hive-agent/src/swarm_permissions.rs`, through `swarm_queue_client::agent_permissions::read`), diff --git a/nix/host-modules/swarm-victorialogs.nix b/nix/host-modules/swarm-victorialogs.nix index ed6521a02..c582848e9 100644 --- a/nix/host-modules/swarm-victorialogs.nix +++ b/nix/host-modules/swarm-victorialogs.nix @@ -257,7 +257,7 @@ in so every agent on one host shares one budget. The default covers about a hundred agents on a host cold-starting at once, each costing one store login and read for its first query. Requests over the rate and its burst - are answered 403. + are answered 429. ''; }; @@ -267,7 +267,7 @@ in description = '' Requests a client address may make above {option}`services.hyperhive.deploy.victorialogs.authRate` before nginx - answers 403, served without delay. + answers 429, served without delay. ''; }; @@ -331,7 +331,11 @@ in "~^Bearer [0-9a-f]{64}$" /__swarm_logs_grafana_auth; default /__hive_authelia; } - limit_req_zone $binary_remote_addr zone=swarm_logs_agent_auth:1m rate=${deployCfg.victorialogs.authRate}; + map $http_authorization $swarm_logs_agent_limit_key { + "~^Bearer swarm-agent\." $binary_remote_addr; + default ""; + } + limit_req_zone $swarm_logs_agent_limit_key zone=swarm_logs_agent_auth:1m rate=${deployCfg.victorialogs.authRate}; map $http_authorization $swarm_logs_ingest_nocache { "" 1; default 0; @@ -420,12 +424,36 @@ in # Three checks: an agent's own `swarm-agent.` bearer goes to # `swarm-logs-auth`, Grafana's 64-hex bearer to `swarm-metrics-auth`, # anything else to authelia (`appendHttpConfig` above picks). + # + # The agents' rate limit and the 503 hand-on are set on this location; + # see `@swarm_logs_auth_failed` below. "^~ /select/logsql/" = { # No URI part, so the request path and its query string reach # the store as the caller sent them. proxyPass = upstream; extraConfig = '' + limit_req zone=swarm_logs_agent_auth burst=${toString deployCfg.victorialogs.authBurst} nodelay; + limit_req_status 429; auth_request /__swarm_logs_auth; + auth_request_set $swarm_logs_auth_status $upstream_status; + error_page 500 = @swarm_logs_auth_failed; + ''; + }; + + # Where a failed `auth_request` lands: the 503 the responder answered + # when its store could not, and a 500 for any other status. + # `auth_request` turns every subrequest status but 2xx, 401 and 403 + # into a 500, so this is how a 503 reaches the caller. For the same + # reason the rate limit is on the query location and not in the agent + # subrequest: there a 429 would become a 500. `limit_req` runs before + # `auth_request` and skips a request whose key is empty, which + # `swarm_logs_agent_limit_key` makes of every non-agent request. + "@swarm_logs_auth_failed" = { + extraConfig = '' + if ($swarm_logs_auth_status = 503) { + return 503; + } + return 500; ''; }; @@ -458,16 +486,12 @@ in # The `Authorization` header rides the subrequest unchanged. # # Any well-formed agent bearer the responder has not recently granted - # costs a secret store login and read, so the rate per client address - # is capped here, ahead of the responder. 403 when over: the only - # statuses `auth_request` passes through are 401 and 403, and - # `swarm-logs` retries a 401. + # costs a secret store login and read; the rate per client address is + # capped on the query location, ahead of this subrequest. "= /__swarm_logs_agent_auth" = { proxyPass = "http://unix:${logsAuthSocket}:/"; extraConfig = '' internal; - limit_req zone=swarm_logs_agent_auth burst=${toString deployCfg.victorialogs.authBurst} nodelay; - limit_req_status 403; proxy_pass_request_body off; proxy_set_header Content-Length ""; ''; diff --git a/nix/host-modules/swarm-victoriametrics.nix b/nix/host-modules/swarm-victoriametrics.nix index 0ace7ea2d..829f8f74b 100644 --- a/nix/host-modules/swarm-victoriametrics.nix +++ b/nix/host-modules/swarm-victoriametrics.nix @@ -96,8 +96,20 @@ let # `error_page 401 =302` follows it and reads authelia's login page as a 200 # holding no series. `/__metrics_read_auth` picks the check from the # caller's `Authorization` (`appendHttpConfig` below). + # + # The agents' rate limit is here and not in the agent subrequest: + # `auth_request` turns any subrequest status but 2xx, 401 and 403 into a 500, + # so a limit hit there could not reach the caller as a 429. `limit_req` runs + # before `auth_request` and does not count a request whose key is empty, + # which `swarm_metrics_agent_limit_key` makes of every request that is not + # an agent's. A responder answering 503 (its store cannot answer) is the one + # other subrequest status handed on, by `@swarm_metrics_auth_failed`. readAuth = '' + limit_req zone=swarm_metrics_agent_auth burst=${toString deployCfg.victoriametrics.agentAuthBurst} nodelay; + limit_req_status 429; auth_request /__metrics_read_auth; + auth_request_set $swarm_metrics_auth_status $upstream_status; + error_page 500 = @swarm_metrics_auth_failed; ''; readLocations = let @@ -336,7 +348,7 @@ in costs a secret store login and read, whether the bearer is right or not. Keyed by client address, so every agent on one host shares one budget. - Requests over the rate and its burst are answered 403. + Requests over the rate and its burst are answered 429. ''; }; @@ -346,7 +358,7 @@ in description = '' Requests a client address may make above {option}`services.hyperhive.deploy.victoriametrics.agentAuthRate` before - nginx answers 403, served without delay. + nginx answers 429, served without delay. ''; }; @@ -418,7 +430,11 @@ in "~^Bearer " /__metrics_grafana_auth; default /__metrics_authelia; } - limit_req_zone $binary_remote_addr zone=swarm_metrics_agent_auth:1m rate=${deployCfg.victoriametrics.agentAuthRate}; + map $http_authorization $swarm_metrics_agent_limit_key { + "~^Bearer swarm-agent\." $binary_remote_addr; + default ""; + } + limit_req_zone $swarm_metrics_agent_limit_key zone=swarm_metrics_agent_auth:1m rate=${deployCfg.victoriametrics.agentAuthRate}; map $http_authorization $swarm_metrics_ingest_nocache { "" 1; default 0; @@ -449,6 +465,16 @@ in # its queries, and authenticates none of them. "/".return = "403"; + # Where a failed read-location `auth_request` lands: the 503 the + # responder answered when its store could not, and a 500 for any + # other status. + "@swarm_metrics_auth_failed".extraConfig = '' + if ($swarm_metrics_auth_status = 503) { + return 503; + } + return 500; + ''; + # The swarm UI's quick link opens the bare domain. The store's own # index page links mostly to paths refused above, so send it to vmui. "= /".return = "302 /vmui/"; @@ -508,14 +534,11 @@ in # An agent's bearer, checked by `swarm-metrics-agent-auth`. Any # well-formed agent bearer the responder has not recently granted # costs a store login and read, so the rate per client address is - # capped here. 403 when over: `auth_request` passes only 401 and 403 - # through, and `swarm-metrics` retries a 401. + # capped on the read locations (`readAuth`), ahead of this subrequest. "= /__metrics_agent_auth" = { proxyPass = "http://unix:${agentAuthSocket}:/"; extraConfig = '' internal; - limit_req zone=swarm_metrics_agent_auth burst=${toString deployCfg.victoriametrics.agentAuthBurst} nodelay; - limit_req_status 403; proxy_pass_request_body off; proxy_set_header Content-Length ""; ''; diff --git a/nix/module-eval/core-toggle.nix b/nix/module-eval/core-toggle.nix index 667d923cc..3f6bd79d4 100644 --- a/nix/module-eval/core-toggle.nix +++ b/nix/module-eval/core-toggle.nix @@ -1276,7 +1276,11 @@ let && lib.all ( r: lib.hasInfix "auth_request /__metrics_read_auth;" r.extraConfig - && !(lib.hasInfix "error_page" r.extraConfig) + && !(lib.hasInfix "error_page 401" r.extraConfig) + && lib.hasInfix "limit_req zone=swarm_metrics_agent_auth burst=${toString v.agentAuthBurst} nodelay;" r.extraConfig + && lib.hasInfix "limit_req_status 429;" r.extraConfig + && lib.hasInfix "auth_request_set $swarm_metrics_auth_status $upstream_status;" r.extraConfig + && lib.hasInfix "error_page 500 = @swarm_metrics_auth_failed;" r.extraConfig ) (lib.attrValues reads) && lib.hasInfix "map \$http_authorization \$swarm_metrics_read_auth_target" http && lib.hasInfix agentArm http @@ -1299,10 +1303,12 @@ let && lib.hasInfix "--surface metrics" agentUnit.serviceConfig.ExecStart && lib.hasInfix "--verdict-ttl ${toString v.agentAuthVerdictTtl}" agentUnit.serviceConfig.ExecStart && agentUnit.serviceConfig.LoadCredential == unit.serviceConfig.LoadCredential - && lib.hasInfix "limit_req_zone $binary_remote_addr zone=swarm_metrics_agent_auth:1m rate=${v.agentAuthRate};" http - && - lib.hasInfix "limit_req zone=swarm_metrics_agent_auth burst=${toString v.agentAuthBurst} nodelay;" - l."= /__metrics_agent_auth".extraConfig + && lib.hasInfix "limit_req_zone $swarm_metrics_agent_limit_key zone=swarm_metrics_agent_auth:1m rate=${v.agentAuthRate};" http + && lib.hasInfix "\"~^Bearer swarm-agent\\.\" $binary_remote_addr;" http + && !(lib.hasInfix "limit_req" l."= /__metrics_agent_auth".extraConfig) + && lib.hasInfix "if ($swarm_metrics_auth_status = 503) {" l."@swarm_metrics_auth_failed".extraConfig + && lib.hasInfix "return 503;" l."@swarm_metrics_auth_failed".extraConfig + && lib.hasInfix "return 500;" l."@swarm_metrics_auth_failed".extraConfig && !(lib.hasInfix "limit_req" l."= /__metrics_grafana_auth".extraConfig) && lib.hasInfix "auth_request /__metrics_authelia;" l."^~ /vmui/".extraConfig && lib.hasInfix "error_page 401 =302" l."^~ /vmui/".extraConfig @@ -1416,9 +1422,9 @@ let q = v."logs.t.local".locations."^~ /select/logsql/".extraConfig; browser = v."logs.t.local".locations."/".extraConfig; in - !(lib.hasInfix "error_page" q) + !(lib.hasInfix "error_page 401" q) && !(lib.hasInfix "auth.t.local" q) - && lib.hasInfix "error_page" browser + && lib.hasInfix "error_page 401" browser && lib.hasInfix "auth.t.local" browser; } { @@ -1526,9 +1532,11 @@ let } { # Every agent bearer the responder has not recently granted costs a - # store login and read, so its location carries the per-address limit. - # The responder gets the grant TTL from the option. The query and - # authelia locations carry no limit of their own. + # store login and read, so the query location limits per address, as a + # 429 the caller sees, and only for an agent's bearer. A responder 503 + # is handed on by the named location. The responder gets the grant TTL + # from the option. The agent subrequest and the authelia location carry + # no limit of their own. name = "agent bearer checks are rate-limited per address and granted for a TTL"; ok = let @@ -1537,12 +1545,20 @@ let unit = allLocal.systemd.services.swarm-logs-auth; v = allLocal.services.hyperhive.deploy.victorialogs; in - lib.hasInfix "limit_req_zone $binary_remote_addr zone=swarm_logs_agent_auth:1m rate=${v.authRate};" http + lib.hasInfix "limit_req_zone $swarm_logs_agent_limit_key zone=swarm_logs_agent_auth:1m rate=${v.authRate};" http + && lib.hasInfix "\"~^Bearer swarm-agent\\.\" $binary_remote_addr;" http && lib.hasInfix "limit_req zone=swarm_logs_agent_auth burst=${toString v.authBurst} nodelay;" - l."= /__swarm_logs_agent_auth".extraConfig - && lib.hasInfix "limit_req_status 403;" l."= /__swarm_logs_agent_auth".extraConfig - && !(lib.hasInfix "limit_req" l."^~ /select/logsql/".extraConfig) + l."^~ /select/logsql/".extraConfig + && lib.hasInfix "limit_req_status 429;" l."^~ /select/logsql/".extraConfig + && !(lib.hasInfix "limit_req" l."= /__swarm_logs_agent_auth".extraConfig) + && + lib.hasInfix "auth_request_set $swarm_logs_auth_status $upstream_status;" + l."^~ /select/logsql/".extraConfig + && lib.hasInfix "error_page 500 = @swarm_logs_auth_failed;" l."^~ /select/logsql/".extraConfig + && lib.hasInfix "if ($swarm_logs_auth_status = 503) {" l."@swarm_logs_auth_failed".extraConfig + && lib.hasInfix "return 503;" l."@swarm_logs_auth_failed".extraConfig + && lib.hasInfix "return 500;" l."@swarm_logs_auth_failed".extraConfig && !(lib.hasInfix "limit_req" l."= /__hive_authelia".extraConfig) && lib.hasInfix "--verdict-ttl 60" unit.serviceConfig.ExecStart; } diff --git a/nix/module-eval/swarm-otel-identity.nix b/nix/module-eval/swarm-otel-identity.nix index ef5c84c50..ede4bac15 100644 --- a/nix/module-eval/swarm-otel-identity.nix +++ b/nix/module-eval/swarm-otel-identity.nix @@ -507,7 +507,7 @@ let let h = allLocal.services.hyperhive; locs = allLocal.services.nginx.virtualHosts.${h.swarm.victorialogs.domain}.locations; - checksOf = l: lib.filter (lib.hasPrefix "auth_request") (lib.splitString "\n" l.extraConfig); + checksOf = l: lib.filter (lib.hasPrefix "auth_request /") (lib.splitString "\n" l.extraConfig); in h.deploy.victorialogs.enable && locs ? "= /metrics" diff --git a/swarm-agent-verify/src/lib.rs b/swarm-agent-verify/src/lib.rs index 0aa74001d..a90d397b6 100644 --- a/swarm-agent-verify/src/lib.rs +++ b/swarm-agent-verify/src/lib.rs @@ -10,11 +10,14 @@ //! [`agent_token`] also holds the spelling the agents, `swarm-logs` and //! `swarm-metrics` format their token in. //! +//! [`retry`] is how those two CLIs ride out a gateway answering 503 or 429. +//! //! Two verifiers use this: the queue's auth callout (`swarm-nats-auth`) and //! the log store's `auth_request` responder (`swarm-logs-auth`). Each reads //! the store under its own certificate. pub mod agent_token; +pub mod retry; use std::future::Future; use std::time::Duration; @@ -150,14 +153,38 @@ impl CredentialSource for Connection { } } +/// What checking an agent's token against the store came to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Verdict { + /// The secret is the one stored for the agent it names. + Verified, + /// The store answered, and the secret is not the agent's: nothing stored, + /// another agent's object, or a different value. + Denied, + /// The store did not answer, by error or by timeout. Nothing is granted; + /// a later try may find an answer. + Unavailable, +} + /// Whether `token`'s secret is the one stored for the agent it names. /// -/// The lookup is bounded by `timeout`, after which this denies. +/// The lookup is bounded by `timeout`, after which this denies. A caller that +/// must tell an outage from a refusal uses [`check`]. pub async fn verify( source: &impl CredentialSource, token: &AgentToken<'_>, timeout: Duration, ) -> bool { + check(source, token, timeout).await == Verdict::Verified +} + +/// [`verify`], keeping a store that did not answer apart from a secret that +/// does not match. +pub async fn check( + source: &impl CredentialSource, + token: &AgentToken<'_>, + timeout: Duration, +) -> Verdict { let agent = token.agent; let stored = match tokio::time::timeout(timeout, source.lookup(agent)).await { Ok(Ok(Some(stored))) => stored, @@ -166,7 +193,7 @@ pub async fn verify( agent, "no queue credential is stored for this agent; denying" ); - return false; + return Verdict::Denied; } Ok(Err(e)) => { tracing::warn!( @@ -174,11 +201,11 @@ pub async fn verify( error = format!("{e:#}"), "credential lookup failed; denying" ); - return false; + return Verdict::Unavailable; } Err(_) => { tracing::warn!(agent, "credential lookup timed out; denying"); - return false; + return Verdict::Unavailable; } }; if stored.agent != agent { @@ -187,16 +214,16 @@ pub async fn verify( stored_agent = %stored.agent, "the stored credential names a different agent than its path; denying" ); - return false; + return Verdict::Denied; } // Constant time, so the time to refuse says nothing about how much of the // secret was right. A length mismatch returns early; the length is not // secret, every minted secret has the same one. - stored - .value - .as_bytes() - .ct_eq(token.secret.as_bytes()) - .into() + if bool::from(stored.value.as_bytes().ct_eq(token.secret.as_bytes())) { + Verdict::Verified + } else { + Verdict::Denied + } } #[cfg(test)] @@ -298,4 +325,33 @@ mod tests { async fn a_stored_object_naming_another_agent_is_denied() { assert!(!verified(&stored("argus", "atlas"), "swarm-agent.argus.Ab9_-zSECRET").await); } + + async fn verdict(source: &Fake, token: &str) -> Verdict { + let token = parse_agent_token(token) + .expect("an agent token") + .expect("well-formed"); + check(source, &token, BOUND).await + } + + /// A store that did not answer is `Unavailable`; every answer that is not + /// the agent's secret is `Denied`. + #[tokio::test] + async fn an_outage_is_unavailable_and_a_refusal_is_denied() { + const TOKEN: &str = "swarm-agent.atlas.Ab9_-zSECRET"; + assert_eq!(verdict(&atlas(), TOKEN).await, Verdict::Verified); + assert_eq!( + verdict(&atlas(), "swarm-agent.atlas.Ab9_-zSECREX").await, + Verdict::Denied + ); + assert_eq!( + verdict(&stored("argus", "argus"), TOKEN).await, + Verdict::Denied + ); + assert_eq!( + verdict(&stored("atlas", "argus"), TOKEN).await, + Verdict::Denied + ); + assert_eq!(verdict(&Fake::Fails, TOKEN).await, Verdict::Unavailable); + assert_eq!(verdict(&Fake::Hangs, TOKEN).await, Verdict::Unavailable); + } } diff --git a/swarm-agent-verify/src/retry.rs b/swarm-agent-verify/src/retry.rs new file mode 100644 index 000000000..298c73412 --- /dev/null +++ b/swarm-agent-verify/src/retry.rs @@ -0,0 +1,323 @@ +//! The retry policy of an agent's CLI against a store gateway. +//! +//! The gateway answers 503 when the secret store behind it cannot answer and +//! 429 when the agent's host is over its rate; both pass. [`send`] sends a +//! request up to [`MAX_TRIES`] times, waiting between tries, and returns the +//! first reply that is neither. When the tries run out the error names the +//! cause, so the caller reports an outage or a rate limit and not a missing +//! permission. Any other status, a 401 and a 403 included, is returned at once +//! for the caller to read. +//! +//! No wait is longer than [`MAX_WAIT`], so the waits of all the tries sum to under +//! ten seconds. A `Retry-After` past that ends the retrying instead of being +//! cut short. + +use std::time::Duration; + +use anyhow::bail; + +/// Tries at one request, the first included. +pub const MAX_TRIES: u32 = 3; + +/// The wait after the first failed try. Each later wait doubles it. +const BASE_WAIT: Duration = Duration::from_millis(500); + +/// The longest single wait, a `Retry-After` included. +pub const MAX_WAIT: Duration = Duration::from_secs(4); + +/// What the gateway's answer to one try was, apart from the reply itself. +#[derive(Debug)] +pub struct Attempt { + /// The HTTP status. + pub status: u16, + /// The wait the `Retry-After` header asked for, from [`parse_retry_after`]. + pub retry_after: Option, + /// The reply, handed back when the status is not retried. + pub response: R, +} + +/// The seconds a `Retry-After` header holds. The HTTP-date form is not read: +/// the gateway sets neither form, and a date is `None` here, which leaves the +/// backoff in charge. +#[must_use] +pub fn parse_retry_after(value: &str) -> Option { + value.trim().parse::().ok().map(Duration::from_secs) +} + +/// What a retrying client waits on: time and a jitter. +pub trait Pause { + /// Blocks for `wait`. + fn sleep(&mut self, wait: Duration); + /// A value in `[0, 1)` that spreads the waits of agents that failed + /// together. + fn jitter(&mut self) -> f64; +} + +/// The wall clock, and the sub-second part of it as the jitter. +pub struct Clock; + +impl Pause for Clock { + fn sleep(&mut self, wait: Duration) { + std::thread::sleep(wait); + } + + fn jitter(&mut self) -> f64 { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |since| since.subsec_nanos()); + f64::from(nanos) / 1e9 + } +} + +/// Why a try is repeated. +#[derive(Clone, Copy)] +enum Cause { + Unavailable, + RateLimited, +} + +impl Cause { + fn of(status: u16) -> Option { + match status { + 503 => Some(Self::Unavailable), + 429 => Some(Self::RateLimited), + _ => None, + } + } + + fn describe(self) -> &'static str { + match self { + Self::Unavailable => "unavailable", + Self::RateLimited => "rate limited", + } + } +} + +/// The wait before try number `next` (2 or later): the `Retry-After` when the +/// reply carried one, else the doubling backoff scaled by the jitter into +/// `[0.5, 1)` of itself. `None` when a `Retry-After` is past [`MAX_WAIT`]. +fn wait_before(next: u32, retry_after: Option, jitter: f64) -> Option { + if let Some(asked) = retry_after { + return (asked <= MAX_WAIT).then_some(asked); + } + let doubling = BASE_WAIT * 2u32.pow(next.saturating_sub(2)); + Some( + doubling + .min(MAX_WAIT) + .mul_f64(0.5 + 0.5 * jitter.clamp(0.0, 1.0)), + ) +} + +/// Calls `try_once` until its status is not one that is retried, at most +/// [`MAX_TRIES`] times, and returns that reply. `what` names the store in the +/// error. +/// +/// # Errors +/// +/// What `try_once` returns, at once; or, when the last try was still a 503 or +/// a 429, or a `Retry-After` asked for more than [`MAX_WAIT`], an error naming +/// the store as unavailable or rate limited. +pub fn send( + what: &str, + pause: &mut impl Pause, + mut try_once: impl FnMut() -> anyhow::Result>, +) -> anyhow::Result { + let mut tries = 0; + loop { + tries += 1; + let attempt = try_once()?; + let Some(cause) = Cause::of(attempt.status) else { + return Ok(attempt.response); + }; + let wait = (tries < MAX_TRIES) + .then(|| wait_before(tries + 1, attempt.retry_after, pause.jitter())) + .flatten(); + let Some(wait) = wait else { + bail!( + "the {what} is {} ({}) after {tries} {}", + cause.describe(), + attempt.status, + if tries == 1 { "try" } else { "tries" }, + ); + }; + tracing::debug!(status = attempt.status, ?wait, "retrying"); + pause.sleep(wait); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Records the waits instead of sleeping, and jitters by a fixed value. + struct Recorded { + waits: Vec, + jitter: f64, + } + + impl Pause for Recorded { + fn sleep(&mut self, wait: Duration) { + self.waits.push(wait); + } + + fn jitter(&mut self) -> f64 { + self.jitter + } + } + + fn pause() -> Recorded { + Recorded { + waits: Vec::new(), + jitter: 0.0, + } + } + + /// Answers with each status in turn, counting the tries. + fn replies( + statuses: &[u16], + retry_after: Option, + ) -> impl FnMut() -> anyhow::Result> { + let mut statuses = statuses.iter().copied(); + move || { + let status = statuses.next().expect("no more tries than replies"); + Ok(Attempt { + status, + retry_after, + response: status, + }) + } + } + + #[test] + fn two_503s_then_a_200_succeed() { + let mut p = pause(); + let got = send("store", &mut p, replies(&[503, 503, 200], None)).expect("succeeds"); + assert_eq!(got, 200); + assert_eq!(p.waits.len(), 2); + } + + #[test] + fn a_429_is_retried_like_a_503() { + let mut p = pause(); + assert_eq!( + send("store", &mut p, replies(&[429, 200], None)).expect("succeeds"), + 200 + ); + assert_eq!(p.waits.len(), 1); + } + + #[test] + fn three_429s_end_in_an_error_naming_the_rate_limit() { + let mut p = pause(); + let err = send("store", &mut p, replies(&[429, 429, 429], None)).expect_err("gives up"); + let text = err.to_string(); + assert!(text.contains("rate limited"), "{text}"); + assert!(text.contains("429"), "{text}"); + assert!(!text.contains("permission"), "{text}"); + assert_eq!(p.waits.len(), 2, "no wait after the last try"); + } + + #[test] + fn three_503s_end_in_an_error_naming_the_outage() { + let mut p = pause(); + let err = send("store", &mut p, replies(&[503, 503, 503], None)).expect_err("gives up"); + let text = err.to_string(); + assert!(text.contains("unavailable"), "{text}"); + assert!(text.contains("3 tries"), "{text}"); + } + + /// Anything else is the caller's to read, at the first try. + #[test] + fn other_statuses_are_returned_without_a_retry() { + for status in [200, 401, 403, 404, 500, 502] { + let mut p = pause(); + let got = send("store", &mut p, replies(&[status], None)).expect("returned"); + assert_eq!(got, status); + assert!(p.waits.is_empty(), "{status}"); + } + } + + #[test] + fn a_failed_send_is_returned_without_a_retry() { + let mut p = pause(); + let err = + send::<()>("store", &mut p, || anyhow::bail!("connection refused")).expect_err("fails"); + assert_eq!(err.to_string(), "connection refused"); + assert!(p.waits.is_empty()); + } + + /// The waits double, and the jitter scales each into `[0.5, 1)` of it. + #[test] + fn the_waits_double_and_are_jittered() { + let mut full = Recorded { + waits: Vec::new(), + jitter: 0.999_999, + }; + send("store", &mut full, replies(&[503, 503, 200], None)).expect("succeeds"); + assert_eq!(full.waits.len(), 2); + assert!(full.waits[0] < BASE_WAIT && full.waits[0] > BASE_WAIT.mul_f64(0.99)); + assert!(full.waits[1] < BASE_WAIT * 2 && full.waits[1] > (BASE_WAIT * 2).mul_f64(0.99)); + + let mut none = pause(); + send("store", &mut none, replies(&[503, 503, 200], None)).expect("succeeds"); + assert_eq!(none.waits, [BASE_WAIT.mul_f64(0.5), BASE_WAIT]); + } + + #[test] + fn a_retry_after_is_waited_as_given() { + let mut p = pause(); + send( + "store", + &mut p, + replies(&[429, 429, 200], Some(Duration::from_secs(2))), + ) + .expect("succeeds"); + assert_eq!(p.waits, [Duration::from_secs(2), Duration::from_secs(2)]); + } + + /// A `Retry-After` past the bound ends the retrying at once rather than + /// being cut short. + #[test] + fn a_retry_after_past_the_bound_gives_up_at_once() { + let mut p = pause(); + let err = send( + "store", + &mut p, + replies(&[503], Some(MAX_WAIT + Duration::from_secs(1))), + ) + .expect_err("gives up"); + assert!(err.to_string().contains("unavailable"), "{err}"); + assert!(p.waits.is_empty()); + } + + #[test] + fn the_waits_stay_under_ten_seconds() { + for jitter in [0.0, 0.5, 0.999_999] { + for retry_after in [None, Some(MAX_WAIT)] { + let mut p = Recorded { + waits: Vec::new(), + jitter, + }; + send("store", &mut p, replies(&[503, 503, 503], retry_after)) + .expect_err("gives up"); + assert!(p.waits.iter().sum::() < Duration::from_secs(10)); + } + } + } + + #[test] + fn a_retry_after_is_read_in_seconds_only() { + assert_eq!(parse_retry_after("3"), Some(Duration::from_secs(3))); + assert_eq!(parse_retry_after(" 0 "), Some(Duration::ZERO)); + assert_eq!(parse_retry_after("Wed, 21 Oct 2026 07:28:00 GMT"), None); + assert_eq!(parse_retry_after("-1"), None); + assert_eq!(parse_retry_after(""), None); + } + + /// `Clock`'s jitter stays in `[0, 1)`. + #[test] + fn the_clock_jitters_within_the_unit_interval() { + let jitter = Clock.jitter(); + assert!((0.0..1.0).contains(&jitter), "{jitter}"); + } +} diff --git a/swarm-logs-auth/src/main.rs b/swarm-logs-auth/src/main.rs index f83224848..f54540f93 100644 --- a/swarm-logs-auth/src/main.rs +++ b/swarm-logs-auth/src/main.rs @@ -9,8 +9,10 @@ //! instance guards. It answers 200 when the secret is the one stored at //! `swarm/agents//queue` and the agent holds the permission for that //! surface (`logs` or `metrics`), 401 when the secret does not verify, and 403 -//! when it does but the permission is not held. A grant it cannot read is not -//! held. Any other status becomes a 500 for the caller in `auth_request`. +//! when it does but the grant is absent or lacks the permission. A store that +//! cannot answer, for the secret or the grant, is 503 and grants nothing. The +//! gateway hands the 503 on to the caller; `auth_request` itself turns any +//! status but 2xx, 401 and 403 into a 500. //! //! The permission is read from the leaf swarm-controller mirrors //! (`swarm_secret_client::observability`), because this responder has no queue @@ -37,13 +39,13 @@ use anyhow::Context as _; use axum::extract::State; use axum::http::{HeaderMap, StatusCode, header}; use clap::{Parser, ValueEnum}; -use swarm_agent_verify::CredentialSource; use swarm_agent_verify::agent_token::parse_agent_token; +use swarm_agent_verify::{CredentialSource, Verdict}; use swarm_secret_client::observability::{Grant, grant_path}; use verdicts::Verdicts; /// How long one store lookup may take before the request is denied. Well -/// under nginx's 60s `proxy_read_timeout`, so a slow store reads as a 401 +/// under nginx's 60s `proxy_read_timeout`, so a slow store answers 503 /// rather than a gateway timeout. const LOOKUP_TIMEOUT: Duration = Duration::from_secs(5); @@ -154,7 +156,8 @@ async fn decide( tracing::debug!(agent = token.agent, "verified recently"); return StatusCode::OK; } - // One login for both reads: the credential and the grant. + // One login for both reads: the credential and the grant. A login that + // fails or is too slow is the store not answering, not a refusal. let conn = match tokio::time::timeout(responder.lookup_timeout, responder.source.connect()).await { Ok(Ok(conn)) => conn, @@ -164,31 +167,45 @@ async fn decide( error = format!("{e:#}"), "store login failed; denying" ); - return StatusCode::UNAUTHORIZED; + return StatusCode::SERVICE_UNAVAILABLE; } Err(_) => { tracing::warn!(agent = token.agent, "store login timed out; denying"); - return StatusCode::UNAUTHORIZED; + return StatusCode::SERVICE_UNAVAILABLE; } }; - if !swarm_agent_verify::verify(&conn, &token, responder.lookup_timeout).await { - return StatusCode::UNAUTHORIZED; + match swarm_agent_verify::check(&conn, &token, responder.lookup_timeout).await { + Verdict::Verified => {} + Verdict::Denied => return StatusCode::UNAUTHORIZED, + Verdict::Unavailable => return StatusCode::SERVICE_UNAVAILABLE, } - if !holds_permission(responder, &conn, token.agent).await { - return StatusCode::FORBIDDEN; + match holds_permission(responder, &conn, token.agent).await { + Held::Yes => {} + Held::No => return StatusCode::FORBIDDEN, + Held::Unavailable => return StatusCode::SERVICE_UNAVAILABLE, } tracing::info!(agent = token.agent, surface = ?responder.surface, "verified"); lock(&responder.verdicts).grant(bearer, now); StatusCode::OK } -/// Whether `agent` holds the permission for the surface. A grant that is -/// absent, unreadable or slow is not held. +/// Whether an agent holds the permission for the surface. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Held { + Yes, + /// The store answered: the grant is absent, or lacks the permission. + No, + /// The grant could not be read or the read was too slow. Not held, but not + /// known to be missing either. + Unavailable, +} + +/// Whether `agent` holds the permission for the surface. async fn holds_permission( responder: &Responder, conn: &impl GrantSource, agent: &str, -) -> bool { +) -> Held { let grant = match tokio::time::timeout(responder.lookup_timeout, conn.grant(agent)).await { Ok(Ok(Some(grant))) => grant, Ok(Ok(None)) => { @@ -196,7 +213,7 @@ async fn holds_permission( agent, "no permission grant is mirrored for this agent; denying" ); - return false; + return Held::No; } Ok(Err(e)) => { tracing::warn!( @@ -204,18 +221,19 @@ async fn holds_permission( error = format!("{e:#}"), "grant lookup failed; denying" ); - return false; + return Held::Unavailable; } Err(_) => { tracing::warn!(agent, "grant lookup timed out; denying"); - return false; + return Held::Unavailable; } }; - let held = responder.surface.allowed_by(grant); - if !held { + if responder.surface.allowed_by(grant) { + Held::Yes + } else { tracing::info!(agent, surface = ?responder.surface, "agent lacks the permission; denying"); + Held::No } - held } /// The cache holds no invariant a panicking holder could break mid-way, so a @@ -279,7 +297,7 @@ async fn main() -> anyhow::Result<()> { std::fs::set_permissions(&args.socket, std::fs::Permissions::from_mode(0o666)) .with_context(|| format!("chmod {}", args.socket.display()))?; tracing::info!(socket = %args.socket.display(), "swarm-logs-auth listening"); - // Ready means the store answers: with it down every request is a 401. + // Ready means the store answers: with it down every request is a 503. let probe = Arc::clone(&responder); health.ready_while_checked(move || { let probe = Arc::clone(&probe); @@ -323,11 +341,21 @@ mod tests { Hangs, } + /// What the credential read answers, while atlas's credential is stored. + #[derive(Clone, Copy)] + enum Queue { + Answers, + Unreadable, + /// Accepts the read and never answers. + Hangs, + } + /// A store holding atlas's credential until `revoke` and her grant leaf, /// counting lookups of each. struct Atlas { lookups: AtomicUsize, revoked: AtomicBool, + queue: Mutex, leaf: Mutex, grant_lookups: AtomicUsize, /// Store logins, one per `connect`. @@ -341,6 +369,7 @@ mod tests { Self { lookups: AtomicUsize::new(0), revoked: AtomicBool::new(false), + queue: Mutex::new(Queue::Answers), leaf: Mutex::new(leaf), grant_lookups: AtomicUsize::new(0), logins: AtomicUsize::new(0), @@ -348,6 +377,13 @@ mod tests { } } + /// Atlas holds `logs` and `metrics`, and the credential read is `queue`. + fn with_queue(queue: Queue) -> Self { + let store = Self::both(); + *store.queue.lock().unwrap() = queue; + store + } + /// Atlas holds `logs` and `metrics`. fn both() -> Self { Self::with(Leaf::Holds(Grant { @@ -372,6 +408,12 @@ mod tests { impl CredentialSource for &Atlas { async fn lookup(&self, agent: &str) -> anyhow::Result> { self.lookups.fetch_add(1, Ordering::SeqCst); + let queue = *self.queue.lock().unwrap(); + match queue { + Queue::Answers => {} + Queue::Unreadable => anyhow::bail!("store unreachable"), + Queue::Hangs => std::future::pending().await, + } Ok( (agent == "atlas" && !self.revoked.load(Ordering::SeqCst)).then(|| { AgentCredential { @@ -461,15 +503,10 @@ mod tests { ); } - /// No grant, an empty grant and a grant that cannot be read all deny. + /// No grant and an empty grant are a definite refusal. #[tokio::test] - async fn without_a_readable_grant_the_answer_is_403() { - for leaf in [ - Leaf::Absent, - Leaf::Unreadable, - Leaf::Hangs, - Leaf::Holds(Grant::default()), - ] { + async fn without_a_grant_the_answer_is_403() { + for leaf in [Leaf::Absent, Leaf::Holds(Grant::default())] { let store = Atlas::with(leaf); assert_eq!( decide( @@ -483,6 +520,45 @@ mod tests { } } + /// A grant the store fails or is too slow to read is not a refusal: 503, + /// and nothing is granted or remembered. + #[tokio::test] + async fn a_grant_that_cannot_be_read_is_503() { + for leaf in [Leaf::Unreadable, Leaf::Hangs] { + let store = Atlas::with(leaf); + let r = responder(&store, Surface::Logs); + assert_eq!( + decide(&r, Some(GOOD), Instant::now()).await, + StatusCode::SERVICE_UNAVAILABLE + ); + store.set_leaf(Leaf::Absent); + assert_eq!( + decide(&r, Some(GOOD), Instant::now()).await, + StatusCode::FORBIDDEN, + "the outage was remembered" + ); + } + } + + /// A credential read that fails or is too slow is 503, not the 401 of a + /// secret that does not match. + #[tokio::test] + async fn a_credential_that_cannot_be_read_is_503() { + for queue in [Queue::Unreadable, Queue::Hangs] { + let store = Atlas::with_queue(queue); + assert_eq!( + decide( + &responder(&store, Surface::Logs), + Some(GOOD), + Instant::now() + ) + .await, + StatusCode::SERVICE_UNAVAILABLE + ); + assert_eq!(store.grant_lookups.load(Ordering::SeqCst), 0); + } + } + #[tokio::test] async fn everything_else_is_401() { let store = Atlas::both(); @@ -523,16 +599,16 @@ mod tests { assert_eq!(store.logins.load(Ordering::SeqCst), 1, "remembered"); } - /// A store that refuses the login answers nothing, so the request is - /// denied and neither read is tried. + /// A store that refuses the login answers nothing: the request is 503, and + /// neither read is tried. #[tokio::test] - async fn a_refused_login_is_a_denial_and_reads_nothing() { + async fn a_refused_login_is_503_and_reads_nothing() { let store = Atlas::both(); store.login_fails.store(true, Ordering::SeqCst); let r = responder(&store, Surface::Logs); assert_eq!( decide(&r, Some(GOOD), Instant::now()).await, - StatusCode::UNAUTHORIZED + StatusCode::SERVICE_UNAVAILABLE ); assert_eq!(store.logins.load(Ordering::SeqCst), 1); assert_eq!(store.lookups(), 0); diff --git a/swarm-logs/Cargo.toml b/swarm-logs/Cargo.toml index 90ec1b51b..c6b7cd6eb 100644 --- a/swarm-logs/Cargo.toml +++ b/swarm-logs/Cargo.toml @@ -18,7 +18,7 @@ swarm-agent-verify.workspace = true swarm-secret-client.workspace = true # Only to drive that one async read; the query itself is blocking. tokio.workspace = true -# Blocking, not async: this binary makes one request (two on a 401) and +# Blocking, not async: this binary makes one request (repeated on a 401, 503 or 429) and # exits, so a reactor would exist only to be torn down. reqwest = { workspace = true, features = ["blocking"] } serde_json.workspace = true diff --git a/swarm-logs/README.md b/swarm-logs/README.md index 71cdf219c..841e54ce6 100644 --- a/swarm-logs/README.md +++ b/swarm-logs/README.md @@ -33,8 +33,12 @@ auth callout also uses). A 401 makes `swarm-logs` read the secret again and retry once, which covers a secret re-minted between the read and the check. `swarm-logs-auth` grants a secret it has verified for 60 s by default without asking the store again, so a replaced secret also keeps working for up to that long. -A 403 is the gateway's per-address rate limit on these checks; it is not -retried. +A 403 means the agent lacks the `logs` permission and is not retried. A 503 +means the secret store behind the check could not answer, and a 429 means the +agent's host is over the gateway's per-address rate; `swarm-logs` waits and +retries either, three tries in all (`swarm_agent_verify::retry`), honouring a +`Retry-After` of up to four seconds. When the tries run out the error says the +store is unavailable or rate limited. 🩸 The secret is never logged or rendered into an error. diff --git a/swarm-logs/src/query.rs b/swarm-logs/src/query.rs index 4ca0eb102..3b0029067 100644 --- a/swarm-logs/src/query.rs +++ b/swarm-logs/src/query.rs @@ -13,6 +13,7 @@ use std::io::{BufRead as _, BufReader, Write}; use anyhow::{Context as _, Result, bail}; +use swarm_agent_verify::retry; use crate::auth::Config; @@ -52,16 +53,30 @@ pub fn run( if let Some(limit) = limit { form.push(("limit", limit.to_string())); } - let send = || -> Result { + let mut send_once = || -> Result> { let bearer = cfg .bearer() .context("reading this agent's credential for the swarm log store")?; - http.post(&cfg.query_url) + let response = http + .post(&cfg.query_url) .bearer_auth(bearer) .form(&form) .send() - .with_context(|| format!("querying the swarm log store at {}", cfg.query_url)) + .with_context(|| format!("querying the swarm log store at {}", cfg.query_url))?; + let retry_after = response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|v| v.to_str().ok()) + .and_then(retry::parse_retry_after); + Ok(retry::Attempt { + status: response.status().as_u16(), + retry_after, + response, + }) }; + // A 503 (the store behind the gateway is down) and a 429 (this host is + // over its rate) are waited out; see `swarm_agent_verify::retry`. + let mut send = || retry::send("swarm log store", &mut retry::Clock, &mut send_once); let mut response = send()?; // A 401 can be a secret re-minted between the store read and the check, diff --git a/swarm-metrics-auth/src/main.rs b/swarm-metrics-auth/src/main.rs index 9c8b3c96c..a931edfb4 100644 --- a/swarm-metrics-auth/src/main.rs +++ b/swarm-metrics-auth/src/main.rs @@ -5,9 +5,9 @@ //! (`swarm-victoriametrics.nix`) any other bearer, on the log store //! (`swarm-victorialogs.nix`, which runs this binary too) a 64-hex one. It //! answers 200 when the bearer is the value stored at `--store-path`, which -//! Grafana's host creates and its datasource presents, and 401 otherwise: -//! `auth_request` turns any other status into a 500 for the caller. A store -//! that does not answer is a 401 only until a value has been read; see below. +//! Grafana's host creates and its datasource presents, and 401 otherwise. A +//! store that does not answer is a 503 until a value has been read (see +//! below), which the gateway hands on. //! //! It reads the store under its own certificate, whose policy reaches that one //! path, and serves a unix socket whose directory only nginx may enter. @@ -22,12 +22,12 @@ //! costs one lookup, success or failure. //! //! When the store does not answer, requests are checked against the last -//! value it did return, up to `MAX_KEPT_AGE` after that read, and a wrong -//! bearer is still refused. The first such request of each failure streak logs -//! it. A revoked or rotated bearer therefore stays accepted while the store -//! cannot be reached, for at most `MAX_KEPT_AGE`; the first answer replaces the -//! value, or drops it when the store holds none. Past that age the value is -//! dropped, and a process that has not yet read the store has none: both deny. +//! value it did return, up to `MAX_KEPT_AGE` after that read; a wrong bearer +//! is still refused. The first such request of each failure streak logs it. A +//! revoked or rotated bearer therefore stays accepted while the store cannot +//! be reached, for at most `MAX_KEPT_AGE`; the first answer replaces the value, +//! or drops it when the store holds none. Past that age the value is dropped, +//! and a process that has not yet read the store has none: both answer 503. use std::future::Future; use std::os::unix::fs::PermissionsExt as _; @@ -44,8 +44,8 @@ use subtle::ConstantTimeEq as _; use swarm_secret_client::client::{DEFAULT_CERT_MOUNT, Settings}; /// How long one store lookup may take before the store counts as not -/// answering. Well under nginx's 60s `proxy_read_timeout`, so a slow store -/// reads as a 401 or a fallback answer rather than a gateway timeout. +/// answering. Well under nginx's 60s `proxy_read_timeout`, so a slow store is +/// answered with a 503 or a fallback, not a gateway timeout. const LOOKUP_TIMEOUT: Duration = Duration::from_secs(5); /// How long requests skip the lookup after one failed or timed out. Each @@ -280,7 +280,7 @@ async fn decide( } if cache.stored.is_none() { tracing::warn!("the store did not answer and no bearer is held; denying"); - return StatusCode::UNAUTHORIZED; + return StatusCode::SERVICE_UNAVAILABLE; } if let Some(line) = cache.fallback_notice() { tracing::warn!("{line}"); @@ -473,21 +473,26 @@ mod tests { } } - /// Nothing stored, an empty value, and a store that cannot answer are - /// all denials, whatever the bearer, when no value was ever read, and - /// the store is asked once for all of those requests: each answer is - /// remembered (the failure for its window, the others for the TTL), so - /// bearers sent at the responder cannot make it log in over and over. + /// Nothing stored and an empty value are 401, whatever the bearer, and a + /// store that cannot answer is 503, when no value was ever read. The store + /// is asked once for all of those requests: each answer is remembered (the + /// failure for its window, the others for the TTL), so bearers sent at the + /// responder cannot make it log in over and over. #[tokio::test] - async fn no_usable_stored_value_is_401_and_is_asked_once() { - for answer in [holds_nothing, || holds(""), fails] { + async fn no_usable_stored_value_is_401_an_outage_is_503_and_it_is_asked_once() { + let answers: [(Answer, StatusCode); 3] = [ + (holds_nothing, StatusCode::UNAUTHORIZED), + (|| holds(""), StatusCode::UNAUTHORIZED), + (fails, StatusCode::SERVICE_UNAVAILABLE), + ]; + for (answer, expected) in answers { let mut source = MockBearerSource::new(); source.expect_lookup().times(1).returning(answer); let r = responder(source); for authorization in [GOOD, "Bearer ", GOOD, "Bearer other", GOOD] { assert_eq!( decide(&r, Some(authorization), Instant::now()).await, - StatusCode::UNAUTHORIZED + expected ); } } @@ -542,8 +547,14 @@ mod tests { async fn a_failed_lookup_is_retried_after_the_failure_window() { let r = responder(store(&[fails, secret])); let t0 = Instant::now(); - assert_eq!(decide(&r, Some(GOOD), t0).await, StatusCode::UNAUTHORIZED); - assert_eq!(decide(&r, Some(GOOD), t0).await, StatusCode::UNAUTHORIZED); + assert_eq!( + decide(&r, Some(GOOD), t0).await, + StatusCode::SERVICE_UNAVAILABLE + ); + assert_eq!( + decide(&r, Some(GOOD), t0).await, + StatusCode::SERVICE_UNAVAILABLE + ); let after = t0 + LOOKUP_FAILURE_WINDOW + Duration::from_secs(1); assert_eq!(decide(&r, Some(GOOD), after).await, StatusCode::OK); } @@ -577,14 +588,15 @@ mod tests { } /// With no value ever read, a store that sleeps past `LOOKUP_TIMEOUT` - /// denies the bearer the last test accepts. + /// denies the bearer the last test accepts, with the 503 of an outage and not + /// the 401 of a wrong bearer. #[tokio::test(start_paused = true)] - async fn a_timeout_without_a_last_good_bearer_is_401() { + async fn a_timeout_without_a_last_good_bearer_is_503() { let r = responder(store(&[hangs])); for _ in 0..3 { assert_eq!( decide(&r, Some(GOOD), Instant::now()).await, - StatusCode::UNAUTHORIZED + StatusCode::SERVICE_UNAVAILABLE ); } } @@ -616,7 +628,7 @@ mod tests { ); assert_eq!( decide(&r, Some(GOOD), Instant::now() + TTL).await, - StatusCode::UNAUTHORIZED + StatusCode::SERVICE_UNAVAILABLE ); } @@ -628,9 +640,10 @@ mod tests { async fn a_burst_against_an_unanswering_store_costs_one_lookup() { const BURST: usize = 20; for (name, outage) in [("erroring", fails as Answer), ("hanging", hangs)] { - for (value_read, expected) in - [(false, StatusCode::UNAUTHORIZED), (true, StatusCode::OK)] - { + for (value_read, expected) in [ + (false, StatusCode::SERVICE_UNAVAILABLE), + (true, StatusCode::OK), + ] { let answers: Vec = if value_read { vec![secret, outage] } else { @@ -726,11 +739,11 @@ mod tests { let expired = t0 + Duration::from_hours(1); assert_eq!( decide(&r, Some(GOOD), expired).await, - StatusCode::UNAUTHORIZED + StatusCode::SERVICE_UNAVAILABLE ); assert_eq!( decide(&r, Some(GOOD), expired + Duration::from_secs(1)).await, - StatusCode::UNAUTHORIZED + StatusCode::SERVICE_UNAVAILABLE ); } diff --git a/swarm-metrics/Cargo.toml b/swarm-metrics/Cargo.toml index fcb2153d6..005822d70 100644 --- a/swarm-metrics/Cargo.toml +++ b/swarm-metrics/Cargo.toml @@ -18,7 +18,7 @@ swarm-agent-verify.workspace = true swarm-secret-client.workspace = true # Only to drive that one async read; the query itself is blocking. tokio.workspace = true -# Blocking, not async: this binary makes one request (two on a 401) and +# Blocking, not async: this binary makes one request (repeated on a 401, 503 or 429) and # exits, so a reactor would exist only to be torn down. reqwest = { workspace = true, features = ["blocking"] } diff --git a/swarm-metrics/README.md b/swarm-metrics/README.md index 39ebb7ab5..9e916a6a4 100644 --- a/swarm-metrics/README.md +++ b/swarm-metrics/README.md @@ -33,8 +33,12 @@ On the metrics store's host, nginx hands a bearer of that shape to `swarm-metrics-agent-auth`, a `swarm-logs-auth` instance logged in to the store under that host's `swarm-metrics-auth` leaf. It grants a secret it has verified for 60 s by default (`deploy.victoriametrics.agentAuthVerdictTtl`). -A 403 is the gateway's per-address rate limit on these checks, and -`swarm-metrics` doesn't retry it. +A 403 means the agent lacks the `metrics` permission and is not retried. A 503 +means the secret store behind the check could not answer, and a 429 means the +agent's host is over the gateway's per-address rate; `swarm-metrics` waits and +retries either, three tries in all (`swarm_agent_verify::retry`), honouring a +`Retry-After` of up to four seconds. When the tries run out the error says the +store is unavailable or rate limited. 🩸 The secret is never logged or rendered into an error. diff --git a/swarm-metrics/src/query.rs b/swarm-metrics/src/query.rs index 96b3ba797..f55a8a4d2 100644 --- a/swarm-metrics/src/query.rs +++ b/swarm-metrics/src/query.rs @@ -10,6 +10,7 @@ use std::io::Write; use anyhow::{Context as _, Result, bail}; use reqwest::Url; +use swarm_agent_verify::retry; use crate::auth::Config; @@ -101,15 +102,29 @@ pub fn url(base: &str, request: &Request) -> Result { pub fn run(cfg: &Config, request: &Request, out: &mut impl Write) -> Result<()> { let url = url(&cfg.base_url, request)?; let http = build_http_client()?; - let send = || -> Result { + let mut send_once = || -> Result> { let bearer = cfg .bearer() .context("reading this agent's credential for the swarm metrics store")?; - http.get(url.clone()) + let response = http + .get(url.clone()) .bearer_auth(bearer) .send() - .with_context(|| format!("querying the swarm metrics store at {}", url.path())) + .with_context(|| format!("querying the swarm metrics store at {}", url.path()))?; + let retry_after = response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|v| v.to_str().ok()) + .and_then(retry::parse_retry_after); + Ok(retry::Attempt { + status: response.status().as_u16(), + retry_after, + response, + }) }; + // A 503 (the store behind the gateway is down) and a 429 (this host is + // over its rate) are waited out; see `swarm_agent_verify::retry`. + let mut send = || retry::send("swarm metrics store", &mut retry::Clock, &mut send_once); let mut response = send()?; // A 401 can be a secret re-minted between the store read and the check,