From 9b95d09ae0d4c370d6312a0cd594e6755be7a738 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 14:41:15 +0700 Subject: [PATCH 001/139] fix(proto): count the admission policy in the agent access hash release.json's agentAccess covered only the agent's roles, so a release that changed the admission policy didn't tell admins to run each cluster's connect command. Clusters that can't refresh their install (Pyo Cloud, self-update off, read only) only get a new policy that way. The hash now covers the policy's rules too, built with stand-in images so it stays the same whatever images an installation runs. --- RELEASING.md | 21 +++++--- crates/pyo-proto/src/bundles.rs | 19 ++++++- crates/pyo-proto/src/lib.rs | 8 +-- crates/pyo-proto/src/rbac.rs | 92 ++++++++++++++++++++++++++++----- scripts/release-manifest.ts | 6 +-- 5 files changed, 117 insertions(+), 29 deletions(-) diff --git a/RELEASING.md b/RELEASING.md index 86512c21..45301240 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -239,8 +239,8 @@ release carries it as an asset. Installations find it in **Settings › Updates* - `migrations`: the migration files, so an installation can say how many it hasn't run yet - the notices from `deploy/release-notices.json` -- `agentAccess`: a hash of the roles the release's agent is installed with - (see [Notices](#notices)) +- `agentAccess`: a hash of the roles and the admission policy the release's + agent is installed with (see [Notices](#notices)) - `k3s`: the k3s a fresh install gets, from `deploy/k3s.env` (see [Bump k3s](#bump-k3s)). - `sandbox`: the SHA-256 of each architecture's sandbox server files. @@ -291,13 +291,18 @@ release's (old notices never carry over): intermediate release has to run first (e.g. a migration in two steps). Older installations are told to update to `minFrom` first. -A change to the agent's roles needs no notice: `release.json` carries the -release agent's `agentAccess` (`pyo-agent access-hash`, which -`check-release` verifies), and an installation whose agent has other roles -adds "After updating, run the connect command shown in each cluster's -settings." to the update dialog by itself. An agent brings its admission +A change to the agent's roles or to its admission policy's rules needs no +notice: `release.json` carries the release agent's `agentAccess` +(`pyo-agent access-hash`, which `check-release` verifies), and an +installation whose agent has other ones adds "After updating, run the +connect command shown in each cluster's settings." to the update dialog by +itself. The images in the policy don't count. An agent brings its admission policy and image pins up to date on its own (with the self-update role), but -never its roles. +never its roles, and a cluster without that role (Pyo Cloud's, or with +`PYO_AGENT_SELF_UPDATE=false`) or read only gets a new policy only from its +connect command. Until then, the agent writes the gateway's client policies +in the shape the cluster's older policy accepts, and the cluster's settings +say to run the command. ### How an installation updates diff --git a/crates/pyo-proto/src/bundles.rs b/crates/pyo-proto/src/bundles.rs index a2268dd8..55130cce 100644 --- a/crates/pyo-proto/src/bundles.rs +++ b/crates/pyo-proto/src/bundles.rs @@ -443,10 +443,25 @@ pub fn bindings_in( /// its images, Pyo Static and the databases system with the installation's /// (`PYO_STATIC_IMAGE`, `PYO_DB_CONTROLLER_IMAGE`, `PYO_KV_IMAGE`). pub fn policy_bundles(waf_image: &str, geoip_image: &str) -> Vec { + policy_bundles_with( + waf_image, + geoip_image, + &crate::system::static_image_from_env(), + &crate::system::db_images_from_env(), + ) +} + +/// [`policy_bundles`] with these images for Pyo Static and the databases. +pub fn policy_bundles_with( + waf_image: &str, + geoip_image: &str, + static_image: &str, + db: &crate::system::DbImages, +) -> Vec { vec![ waf_bundle(waf_image, geoip_image), - static_bundle(&crate::system::static_image_from_env()), - databases_bundle(&crate::system::db_images_from_env()), + static_bundle(static_image), + databases_bundle(db), ] } diff --git a/crates/pyo-proto/src/lib.rs b/crates/pyo-proto/src/lib.rs index a37bd39c..c4fd2f5c 100644 --- a/crates/pyo-proto/src/lib.rs +++ b/crates/pyo-proto/src/lib.rs @@ -1334,10 +1334,10 @@ pub struct Release { /// What to know or do before updating (breaking changes, manual steps). #[serde(default)] pub before_you_update: Vec, - /// The release's [`rbac::access_hash`]: its agent's roles. When it isn't - /// the running Pyo's, every cluster needs its connect command after - /// the update (updates.rs says so first). The release's own agent - /// checks it (`pyo-agent check-release`). + /// The release's [`rbac::access_hash`]: its agent's roles and admission + /// policy. When it isn't the running Pyo's, every cluster needs its + /// connect command after the update (updates.rs says so first). The + /// release's own agent checks it (`pyo-agent check-release`). #[serde(default, skip_serializing_if = "Option::is_none")] pub agent_access: Option, } diff --git a/crates/pyo-proto/src/rbac.rs b/crates/pyo-proto/src/rbac.rs index 2e4b8e1c..29cc4e86 100644 --- a/crates/pyo-proto/src/rbac.rs +++ b/crates/pyo-proto/src/rbac.rs @@ -382,7 +382,23 @@ fn waf_pinned_for(block: bool) -> serde_json::Map { /// `waf_image` and `geoip_image`: the installation's images for the WAF's /// processor and the proxies' GeoIP database, the only ones they may use. pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { - let bundles = bundles::policy_bundles(waf_image, geoip_image); + admission_with( + waf_image, + geoip_image, + &system::static_image_from_env(), + &system::db_images_from_env(), + ) +} + +/// [`admission`] with these images for Pyo Static and the databases too, +/// rather than the installation's. +pub fn admission_with( + waf_image: &str, + geoip_image: &str, + static_image: &str, + db: &system::DbImages, +) -> Vec { + let bundles = bundles::policy_bundles_with(waf_image, geoip_image, static_image, db); // The pod spec of whatever the request makes pods from. let pod_spec = "object.kind == 'Pod' ? object.spec : object.kind == 'CronJob' ? object.spec.jobTemplate.spec.template.spec : object.spec.template.spec"; let validations = json!([ @@ -905,15 +921,36 @@ pub fn install_hash( /// A short hash (16 hex digits) of the roles and charts every install sets /// up, on any cluster and on the one Pyo runs on, with the optional -/// self-update role: what only a cluster's connect command can change (a -/// refresh never writes them). A release carries its own (release.json's -/// `agentAccess`), so an update that changes it says, before it starts, -/// that every cluster needs its connect command afterwards. +/// self-update role, and of the admission policy's rules: what only a +/// cluster's connect command can change (a refresh never writes the roles, +/// and a cluster without the self-update role, or read only, never gets a +/// refresh). A release carries its own (release.json's `agentAccess`), so +/// an update that changes it says, before it starts, that every cluster +/// needs its connect command afterwards. Images don't count: each release +/// has its own, and a refresh or the connect command brings them. pub fn access_hash() -> String { + access_hash_of(&access_admission()) +} + +/// The admission policy [`access_hash`] covers: its rules, with the same +/// stand-in images whatever the installation runs. +fn access_admission() -> Vec { + let db = system::DbImages { + controller: "db-controller".into(), + kv: "kv".into(), + postgres: system::POSTGRES_MAJORS.map(|m| format!("postgres:{m}")), + mysql_operator: "mysql-operator".into(), + mysql_backup: "mysql-backup".into(), + }; + admission_with("waf", "geoip", "static", &db) +} + +fn access_hash_of(admission: &[Value]) -> String { short_hash(&json!([ objects(false), objects(true), - self_update_objects() + self_update_objects(), + admission ])) } @@ -1541,10 +1578,12 @@ mod tests { } } - /// The roles' hash: stable for the same roles, 16 hex digits, and - /// not moved by what a refresh can change (pins, the policy). + /// The access hash: stable, 16 hex digits, not moved by the images (a + /// refresh or the connect command brings those), but moved by any change + /// to the roles or to the admission policy's rules, which a cluster + /// that can't refresh only gets from its connect command. #[test] - fn access_hash_covers_only_the_roles() { + fn access_hash_covers_the_roles_and_the_admission_policy() { let h = access_hash(); assert_eq!(h.len(), 16); assert!(h.chars().all(|c| c.is_ascii_hexdigit())); @@ -1553,16 +1592,45 @@ mod tests { let a = InstallParts::new(false, true, "w:1", "g:1", &db); let b = InstallParts::new(false, true, "w:2", "g:2", &db); assert_ne!(a.hash, b.hash, "pins change the install"); - assert_eq!(access_hash(), h, "but not the roles"); - // Its content: every role set an install can have. + assert_eq!(access_hash(), h, "but not the access"); + // Its content: every role set an install can have, and the policy + // with stand-in images. + let policy = access_admission(); assert_eq!( short_hash(&json!([ objects(false), objects(true), - self_update_objects() + self_update_objects(), + policy ])), h ); + assert_eq!(access_hash_of(&policy), h); + // Whatever images the installation runs (third-party images the + // code pins are part of the rules). + let text = json!(policy).to_string(); + assert!( + !text.contains("ghcr.io/upsetdev/") && !text.contains("127.0.0.1:5005"), + "{text}" + ); + // A change to the policy's rules: another hash. This one is what + // set apart a 0.5.4 install, whose client policies took no headers. + let mut older = policy.clone(); + let rules = older[0]["spec"]["variables"].to_string().replace( + "'clientIPDetection', 'connection', 'headers', 'tls'", + "'clientIPDetection', 'connection', 'tls'", + ); + assert_ne!(rules, older[0]["spec"]["variables"].to_string(), "the rule is there"); + older[0]["spec"]["variables"] = serde_json::from_str(&rules).unwrap(); + assert_ne!(access_hash_of(&older), h); + let mut message = policy.clone(); + message[0]["spec"]["validations"][0]["message"] = json!("another message"); + assert_ne!(access_hash_of(&message), h); + // And a change to the roles. + assert_ne!( + short_hash(&json!([objects(false), objects(true), json!([]), policy])), + h + ); } #[test] diff --git a/scripts/release-manifest.ts b/scripts/release-manifest.ts index 225c73c9..f60f8432 100644 --- a/scripts/release-manifest.ts +++ b/scripts/release-manifest.ts @@ -18,9 +18,9 @@ // the ones Pyo ships with, from crates/pyo-api/assets/sandbox-images/. Notices for this release come from // deploy/release-notices.json when its "version" is this one; the k3s a // fresh install gets, from deploy/k3s.env. `agentAccess` is the hash of the -// roles the release's agent is installed with (`pyo-agent access-hash`): -// installations on other roles tell their admin, before updating, to run -// each cluster's connect command afterwards. `sandbox` lists the SHA-256 of +// roles and admission policy the release's agent is installed with +// (`pyo-agent access-hash`): installations on others tell their admin, +// before updating, to run each cluster's connect command afterwards. `sandbox` lists the SHA-256 of // each architecture's sandbox server files (pyo-sandbox-linux-.tar.gz), // and `sandboxGvisor` those of runsc (pyo-sandbox-gvisor-linux-.tar.gz) // for servers without KVM: deploy/sandbox.sh checks them against it once From 8fae2421ab951983c4a20a798fcdf1450365c032 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 14:41:15 +0700 Subject: [PATCH 002/139] test(agent): add an in-memory kubernetes api for tests --- crates/pyo-agent/src/fakekube.rs | 344 +++++++++++++++++++++++++++++++ crates/pyo-agent/src/main.rs | 2 + 2 files changed, 346 insertions(+) create mode 100644 crates/pyo-agent/src/fakekube.rs diff --git a/crates/pyo-agent/src/fakekube.rs b/crates/pyo-agent/src/fakekube.rs new file mode 100644 index 00000000..b027c293 --- /dev/null +++ b/crates/pyo-agent/src/fakekube.rs @@ -0,0 +1,344 @@ +//! A Kubernetes API server in memory, for tests that run the agent's +//! writes end to end without a cluster: objects by path, server-side apply +//! as a replace, merge patches, deletes, lists with label selectors, and an +//! admission check each test sets (an older admission policy, say). + +use std::{ + collections::BTreeMap, + sync::{Arc, Mutex}, +}; + +use axum::{ + Router, + body::Bytes, + extract::State, + http::{HeaderMap, Method, StatusCode, Uri, header}, + response::{IntoResponse, Response}, +}; +use serde_json::{Value, json}; + +/// A write the server was asked for. +#[derive(Debug, Clone)] +pub struct Write { + /// "PATCH", "POST", "PUT" or "DELETE". + pub method: String, + /// The resource, as in its path ("clienttrafficpolicies"). + pub plural: String, + pub name: String, + pub body: Value, +} + +/// The admission check: None lets a write through, Some((code, message)) +/// refuses it with that status. +pub type Admit = Arc Option<(u16, String)> + Send + Sync>; + +/// (API prefix such as "apis/apps/v1", resource, namespace, name). +type Key = (String, String, String, String); + +struct Inner { + objects: BTreeMap, + refused: Vec, + admit: Admit, +} + +#[derive(Clone)] +pub struct FakeKube(Arc>); + +/// A path's (prefix, namespace, resource, name). +fn parse(path: &str) -> Option<(String, String, String, String)> { + let seg: Vec<&str> = path.trim_matches('/').split('/').collect(); + let (prefix, rest) = match *seg.first()? { + "api" if seg.len() >= 2 => (seg[..2].join("/"), &seg[2..]), + "apis" if seg.len() >= 3 => (seg[..3].join("/"), &seg[3..]), + _ => return None, + }; + let at = |i: usize| rest.get(i).map(|s| s.to_string()).unwrap_or_default(); + Some(match rest { + ["namespaces", _, _, ..] => (prefix, at(1), at(2), at(3)), + _ => (prefix, String::new(), at(0), at(1)), + }) +} + +fn decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = vec![]; + let mut i = 0; + while i < b.len() { + match b[i] { + b'%' if i + 2 < b.len() => { + let hex = std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or(""); + match u8::from_str_radix(hex, 16) { + Ok(v) => { + out.push(v); + i += 3; + continue; + } + Err(_) => out.push(b'%'), + } + } + b'+' => out.push(b' '), + c => out.push(c), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +fn query(uri: &Uri, key: &str) -> Option { + uri.query()?.split('&').find_map(|kv| { + let (k, v) = kv.split_once('=').unwrap_or((kv, "")); + (decode(k) == key).then(|| decode(v)) + }) +} + +/// Whether an object's labels match a label selector (`a=b`, `a!=b`, `a`, +/// `!a`, joined by commas). +fn selected(obj: &Value, selector: &str) -> bool { + let labels = &obj["metadata"]["labels"]; + selector.split(',').filter(|t| !t.is_empty()).all(|t| { + if let Some((k, v)) = t.split_once("!=") { + labels[k.trim()].as_str() != Some(v.trim()) + } else if let Some((k, v)) = t.split_once('=') { + labels[k.trim()].as_str() == Some(v.trim_start_matches('=').trim()) + } else if let Some(k) = t.strip_prefix('!') { + labels.get(k.trim()).is_none() + } else { + labels.get(t.trim()).is_some() + } + }) +} + +fn json_response(code: u16, body: Value) -> Response { + ( + StatusCode::from_u16(code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), + [(header::CONTENT_TYPE, "application/json")], + body.to_string(), + ) + .into_response() +} + +fn status(code: u16, reason: &str, message: &str) -> Response { + json_response( + code, + json!({ "kind": "Status", "apiVersion": "v1", "metadata": {}, "status": if code < 400 { "Success" } else { "Failure" }, "message": message, "reason": reason, "code": code }), + ) +} + +/// RFC 7386: `patch` merged into `into`. +fn merge(into: &mut Value, patch: &Value) { + match (into, patch) { + (Value::Object(a), Value::Object(b)) => { + for (k, v) in b { + if v.is_null() { + a.remove(k); + } else { + merge(a.entry(k.clone()).or_insert(Value::Null), v); + } + } + } + (into, patch) => *into = patch.clone(), + } +} + +async fn handle( + State(fake): State, + method: Method, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + if uri.path() == "/version" { + return json_response( + 200, + json!({ "major": "1", "minor": "33", "gitVersion": "v1.33.0" }), + ); + } + let Some((prefix, ns, plural, name)) = parse(uri.path()) else { + return status(404, "NotFound", "no such path"); + }; + let mut inner = fake.0.lock().unwrap(); + let key = (prefix.clone(), plural.clone(), ns.clone(), name.clone()); + if method == Method::GET { + if !name.is_empty() { + return match inner.objects.get(&key) { + Some(o) => json_response(200, o.clone()), + None => status(404, "NotFound", &format!("{plural} \"{name}\" not found")), + }; + } + let selector = query(&uri, "labelSelector").unwrap_or_default(); + let items: Vec = inner + .objects + .iter() + .filter(|((p, r, n, _), _)| *p == prefix && *r == plural && (ns.is_empty() || *n == ns)) + .map(|(_, o)| o.clone()) + .filter(|o| selected(o, &selector)) + .collect(); + return json_response( + 200, + json!({ "apiVersion": "v1", "kind": "List", "metadata": { "resourceVersion": "1" }, "items": items }), + ); + } + let mut obj: Value = serde_json::from_slice(&body).unwrap_or(Value::Null); + let name = if name.is_empty() { + obj["metadata"]["name"].as_str().unwrap_or("").to_owned() + } else { + name + }; + let key = (prefix, plural.clone(), ns.clone(), name.clone()); + let write = Write { + method: method.to_string(), + plural: plural.clone(), + name: name.clone(), + body: obj.clone(), + }; + if method == Method::DELETE { + return match inner.objects.remove(&key) { + Some(_) => status(200, "", "deleted"), + None => status(404, "NotFound", &format!("{plural} \"{name}\" not found")), + }; + } + let merge_patch = headers + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|t| t.contains("merge-patch")); + if merge_patch { + let Some(have) = inner.objects.get(&key) else { + return status(404, "NotFound", &format!("{plural} \"{name}\" not found")); + }; + let mut merged = have.clone(); + merge(&mut merged, &obj); + obj = merged; + } + let refusal = (inner.admit)(&Write { + body: obj.clone(), + ..write.clone() + }); + if let Some((code, message)) = refusal { + inner.refused.push(write); + return status( + code, + if code == 403 { "Forbidden" } else { "Invalid" }, + &message, + ); + } + obj["metadata"]["name"] = json!(name); + if !ns.is_empty() { + obj["metadata"]["namespace"] = json!(ns); + } + if obj["metadata"]["creationTimestamp"].is_null() { + obj["metadata"]["creationTimestamp"] = json!("2026-01-01T00:00:00Z"); + } + obj["metadata"]["resourceVersion"] = json!("1"); + inner.objects.insert(key, obj.clone()); + json_response(if method == Method::POST { 201 } else { 200 }, obj) +} + +impl FakeKube { + /// The server, and a client of it. Every write goes through until + /// [`FakeKube::admit`] says otherwise. + pub async fn start() -> (FakeKube, kube::Client) { + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let fake = FakeKube(Arc::new(Mutex::new(Inner { + objects: BTreeMap::new(), + refused: vec![], + admit: Arc::new(|_| None), + }))); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let app = Router::new().fallback(handle).with_state(fake.clone()); + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + let config = kube::Config::new(url.parse().unwrap()); + (fake, kube::Client::try_from(config).unwrap()) + } + + /// The admission check from now on. + pub fn admit(&self, f: impl Fn(&Write) -> Option<(u16, String)> + Send + Sync + 'static) { + self.0.lock().unwrap().admit = Arc::new(f); + } + + /// Put an object at its path ("apis/apps/v1/namespaces/shop/deployments/web"). + pub fn put(&self, path: &str, mut obj: Value) { + let (prefix, ns, plural, name) = parse(path).expect("a resource path"); + obj["metadata"]["name"] = json!(name); + if !ns.is_empty() { + obj["metadata"]["namespace"] = json!(ns); + } + self.0 + .lock() + .unwrap() + .objects + .insert((prefix, plural, ns, name), obj); + } + + /// The object at a path, as the server has it. + pub fn get(&self, path: &str) -> Option { + let (prefix, ns, plural, name) = parse(path)?; + self.0 + .lock() + .unwrap() + .objects + .get(&(prefix, plural, ns, name)) + .cloned() + } + + /// The writes the admission check refused, oldest first. + pub fn refused(&self) -> Vec { + self.0.lock().unwrap().refused.clone() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paths_and_selectors() { + assert_eq!( + parse( + "/apis/gateway.envoyproxy.io/v1alpha1/namespaces/pyo-gateway/clienttrafficpolicies/pyo-http" + ), + Some(( + "apis/gateway.envoyproxy.io/v1alpha1".into(), + "pyo-gateway".into(), + "clienttrafficpolicies".into(), + "pyo-http".into() + )) + ); + assert_eq!( + parse("/api/v1/namespaces/shop/services"), + Some(( + "api/v1".into(), + "shop".into(), + "services".into(), + String::new() + )) + ); + assert_eq!( + parse("/api/v1/namespaces/shop"), + Some(( + "api/v1".into(), + String::new(), + "namespaces".into(), + "shop".into() + )) + ); + assert_eq!( + parse("/apis/admissionregistration.k8s.io/v1/validatingadmissionpolicies/pyo-agent"), + Some(( + "apis/admissionregistration.k8s.io/v1".into(), + String::new(), + "validatingadmissionpolicies".into(), + "pyo-agent".into() + )) + ); + assert_eq!(decode("a%3Db%2Cc"), "a=b,c"); + let o = json!({ "metadata": { "labels": { "a": "1", "b": "2" } } }); + assert!(selected(&o, "a=1,b")); + assert!(selected(&o, "a==1,!c")); + assert!(!selected(&o, "a!=1")); + assert!(!selected(&o, "c")); + assert!(selected(&o, "")); + } +} diff --git a/crates/pyo-agent/src/main.rs b/crates/pyo-agent/src/main.rs index 1905f6d5..9b8843e5 100644 --- a/crates/pyo-agent/src/main.rs +++ b/crates/pyo-agent/src/main.rs @@ -18,6 +18,8 @@ mod dbimport; mod dbmetrics; mod dns; mod drain; +#[cfg(test)] +mod fakekube; mod firewall; mod forward; mod gateway; From d0d453820fc8c0cfab55165b7263c8c52218aff8 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 14:41:15 +0700 Subject: [PATCH 003/139] fix(agent): write client policies an older install accepts A cluster whose admission policy is older than the agent's refuses client traffic policies that remove visitor headers. The refused write stopped the rest of a service's routes: its WAF policies, stale route removal and the WAF settings. Deploys of services behind Cloudflare with an HTTPS domain failed, and so did settings that rewrite the shared policies. When such a write is refused, the agent writes the policy without its headers, as the older policy accepts, carries on, logs it once and reports it with each heartbeat until the cluster's install changes. --- crates/pyo-agent/src/gateway.rs | 278 ++++++++++++++++++++++++++------ crates/pyo-agent/src/scope.rs | 1 + crates/pyo-proto/src/rbac.rs | 5 + 3 files changed, 234 insertions(+), 50 deletions(-) diff --git a/crates/pyo-agent/src/gateway.rs b/crates/pyo-agent/src/gateway.rs index 3fd7f458..7e4416e3 100644 --- a/crates/pyo-agent/src/gateway.rs +++ b/crates/pyo-agent/src/gateway.rs @@ -25,7 +25,7 @@ use std::{ collections::BTreeMap, - sync::atomic::{AtomicU8, Ordering}, + sync::atomic::{AtomicBool, AtomicU8, Ordering}, }; use k8s_openapi::api::core::v1::Secret; @@ -765,8 +765,13 @@ pub async fn apply( let kind = o["kind"].as_str().unwrap_or("").to_owned(); let name = o["metadata"]["name"].as_str().unwrap_or("").to_owned(); let api = api_of(client, &kind); - match api.patch(&name, &pp(), &Patch::Apply(o)).await { - Ok(_) => {} + let written = if kind == "ClientTrafficPolicy" { + write_client_policy(&api, &name, o).await + } else { + api.patch(&name, &pp(), &Patch::Apply(o)).await.map(|_| ()) + }; + match written { + Ok(()) => {} Err(kube::Error::Api(e)) if e.code == 404 && kind == "Certificate" => { notes.push("cert-manager is still being installed on this cluster. HTTPS starts with a later deploy.".into()); } @@ -1906,26 +1911,19 @@ async fn web_settings(client: &Client) -> anyhow::Result { async fn write_web(client: &Client, w: system::WebSettings) -> anyhow::Result<()> { let policies = api_of(client, "ClientTrafficPolicy"); - policies - .patch( - "pyo-http", - &pp(), - &Patch::Apply(system::client_policy( - false, - system::WebSettings { - origin_pull: false, - ..w - }, - )), - ) - .await?; - policies - .patch( - "pyo-https", - &pp(), - &Patch::Apply(system::client_policy(true, w)), - ) - .await?; + write_client_policy( + &policies, + "pyo-http", + &system::client_policy( + false, + system::WebSettings { + origin_pull: false, + ..w + }, + ), + ) + .await?; + write_client_policy(&policies, "pyo-https", &system::client_policy(true, w)).await?; // Services behind a CDN: their HTTPS policies follow. let cdn = policies .list(&ListParams::default().labels(system::CDN_LABEL)) @@ -1938,7 +1936,56 @@ async fn write_web(client: &Client, w: system::WebSettings) -> anyhow::Result<() "spec": p.data["spec"].clone(), }); rewrite_cdn_policy(&mut o, w); - policies.patch(&name, &pp(), &Patch::Apply(&o)).await?; + write_client_policy(&policies, &name, &o).await?; + } + Ok(()) +} + +/// Said once in the agent's log when the cluster's install refuses the +/// client policies that remove client-sent visitor headers. +pub const HEADERS_KEPT: &str = "This cluster's install is older than Pyo's. Run the connect command in the cluster's settings so client-sent visitor headers are removed."; + +/// Whether the agent last wrote a client policy without its `headers` +/// because the install refused them. Sent with each heartbeat +/// (`AgentScope::headers_kept`). +static KEPT: AtomicBool = AtomicBool::new(false); + +pub fn headers_kept() -> bool { + KEPT.load(Ordering::Relaxed) +} + +/// A client policy without its `headers`: the shape an install whose +/// admission policy is older than this agent's accepts (it lists the +/// policies as they were before they removed visitor headers). +pub fn without_headers(o: &Value) -> Option { + o["spec"].get("headers")?; + let mut older = o.clone(); + older["spec"].as_object_mut()?.remove("headers"); + Some(older) +} + +/// Write a ClientTrafficPolicy. When the cluster's install refuses one +/// that removes visitor headers (its admission policy is older than this +/// agent's, and the cluster can't refresh it), it's written without them, +/// as that install accepts, so routes, certificates and the rest still go +/// on. That's said once ([`HEADERS_KEPT`]) and reported until such a +/// write goes through. +async fn write_client_policy(api: &Api, name: &str, o: &Value) -> kube::Result<()> { + let refused = match api.patch(name, &pp(), &Patch::Apply(o)).await { + Ok(_) => { + if o["spec"].get("headers").is_some() { + KEPT.store(false, Ordering::Relaxed); + } + return Ok(()); + } + Err(e) => e, + }; + let Some(older) = without_headers(o).filter(|_| crate::refused::is_refusal(&refused)) else { + return Err(refused); + }; + api.patch(name, &pp(), &Patch::Apply(&older)).await?; + if !KEPT.swap(true, Ordering::Relaxed) { + tracing::warn!(policy = name, error = %refused, "{HEADERS_KEPT}"); } Ok(()) } @@ -2004,19 +2051,18 @@ pub async fn set_origin_pull(client: &Client, ca_pem: &str) -> anyhow::Result anyhow::Result Option<(u16, String)> { + if w.plural != "clienttrafficpolicies" || w.method == "DELETE" { + return None; + } + let shared: Vec = [false, true] + .into_iter() + .flat_map(system::client_policy_variants) + .filter_map(|v| without_headers(&json!({ "spec": v })).map(|o| o["spec"].clone())) + .collect(); + let spec = &w.body["spec"]; + let ok = match w.name.as_str() { + "pyo-http" | "pyo-https" => shared.contains(spec), + system::TAILNET_GATEWAY => false, + _ => spec.get("headers").is_none(), + }; + (!ok).then(|| (403, format!("clienttrafficpolicies.gateway.envoyproxy.io \"{}\" is forbidden: ValidatingAdmissionPolicy 'pyo-agent' with binding 'pyo-agent' denied request: failed expression: gatewayAllowed", w.name))) + } + + /// A cluster that can't refresh its install (Pyo Cloud, self-update + /// off, read only) keeps 0.5.4's admission policy after the agent + /// moves on. Its client policies go in without the visitor headers' + /// removal, and the rest of a deploy's routes still does: the WAF's + /// policies after the CDN's client policy, the stale route's removal, + /// the gateway's settings. That's reported (the heartbeat's + /// `headersKept`) until the connect command brings the new policy. + #[tokio::test] + async fn an_older_admission_policy_gets_client_policies_without_headers() { + use pyo_proto::{Waf, WafSettings}; + let (kube, client) = crate::fakekube::FakeKube::start().await; + let at = |kind: &str, name: &str| { + let (group, plural) = match kind { + "HTTPRoute" => ("gateway.networking.k8s.io/v1", "httproutes"), + "EnvoyExtensionPolicy" => ("gateway.envoyproxy.io/v1alpha1", "envoyextensionpolicies"), + "SecurityPolicy" => ("gateway.envoyproxy.io/v1alpha1", "securitypolicies"), + _ => ("gateway.envoyproxy.io/v1alpha1", "clienttrafficpolicies"), + }; + format!("apis/{group}/namespaces/{GATEWAY_NS}/{plural}/{name}") + }; + kube.admit(admission_054); + // A route an earlier deploy made, that this one no longer has. + kube.put( + &at("HTTPRoute", "shop-web-old"), + json!({ "apiVersion": "gateway.networking.k8s.io/v1", "kind": "HTTPRoute", "metadata": { "labels": { SERVICE_LABEL: "svc_web" } }, "spec": {} }), + ); + // Behind Cloudflare, with its WAF on. + let mut b = spec(vec![domain("shop.example.com", "http", "letsencrypt", true)]); + b.firewall = Some(Firewall { + behind: Some("cloudflare".into()), + presets: [("cloudflare".to_owned(), vec!["173.245.48.0/20".to_owned()])].into(), + ..Default::default() + }); + b.waf = Some(Waf { + settings: WafSettings { + mode: "block".into(), + level: 1, + ..Default::default() + }, + rules: vec![], + }); + let pyo = PyoApi::new("http://127.0.0.1:9", "t").unwrap(); + let notes = apply(&client, &pyo, &b).await.expect("the deploy's routes"); + assert!(notes.is_empty(), "{notes:?}"); + // Refused with its headers, then written as 0.5.4 wrote it. + assert!( + kube.refused() + .iter() + .any(|w| w.name == "shop-web-cdn" && w.body["spec"]["headers"].is_object()) + ); + let cdn = kube.get(&at("ClientTrafficPolicy", "shop-web-cdn")).expect("the CDN's client policy"); + assert!(cdn["spec"].get("headers").is_none(), "{cdn}"); + assert_eq!( + cdn["spec"]["clientIPDetection"], + json!({ "xForwardedFor": { "trustedCIDRs": ["173.245.48.0/20"] } }) + ); + assert_eq!(cdn["metadata"]["labels"][system::CDN_LABEL], "cloudflare"); + // What comes after it. + for (kind, name) in [ + ("HTTPRoute", "shop-web-https-http"), + ("SecurityPolicy", "shop-web-https-http"), + ("EnvoyExtensionPolicy", "shop-web-https-http"), + ] { + assert!(kube.get(&at(kind, name)).is_some(), "{kind} {name}"); + } + assert!(kube.get(&at("HTTPRoute", "shop-web-old")).is_none(), "the stale route"); + assert!(headers_kept()); + + // The gateway's settings (origin pull, PROXY protocol): the shared + // policies as 0.5.4 lists them, and the CDN's follows. + write_web(&client, system::WebSettings { origin_pull: true, proxy_protocol: true }) + .await + .expect("the gateway's settings"); + for (https, name) in [(false, "pyo-http"), (true, "pyo-https")] { + let p = kube.get(&at("ClientTrafficPolicy", name)).expect(name); + assert!(p["spec"].get("headers").is_none(), "{p}"); + let w = system::WebSettings { origin_pull: https, proxy_protocol: true }; + assert_eq!(Some(p), without_headers(&system::client_policy(https, w)).map(|mut o| { + o["metadata"]["resourceVersion"] = json!("1"); + o["metadata"]["creationTimestamp"] = json!("2026-01-01T00:00:00Z"); + o + })); + } + let cdn = kube.get(&at("ClientTrafficPolicy", "shop-web-cdn")).unwrap(); + assert!(cdn["spec"]["proxyProtocol"].is_object() && cdn["spec"].get("headers").is_none()); + set_web_proxy_protocol(&client, false).await.expect("PROXY protocol off"); + set_origin_pull(&client, "").await.expect("origin pull off"); + assert!(kube.get(&at("ClientTrafficPolicy", "pyo-https")).unwrap()["spec"].get("tls").is_none()); + + // The connect command ran: the new policy takes them whole. + kube.admit(|_| None); + apply(&client, &pyo, &b).await.expect("the deploy's routes"); + let cdn = kube.get(&at("ClientTrafficPolicy", "shop-web-cdn")).unwrap(); + assert_eq!(cdn["spec"]["headers"], system::visitor_headers(system::cdn_own_headers("cloudflare"))); + write_web(&client, system::WebSettings::default()).await.unwrap(); + for name in ["pyo-http", "pyo-https"] { + let p = kube.get(&at("ClientTrafficPolicy", name)).unwrap(); + assert_eq!(p["spec"]["headers"], system::visitor_headers(&[]), "{name}"); + } + assert!(!headers_kept()); + + // Refused for anything else: an error, as before. + kube.admit(|w| { + (w.plural == "clienttrafficpolicies").then(|| (403, "ValidatingAdmissionPolicy 'pyo-agent' denied request".into())) + }); + assert!(write_web(&client, system::WebSettings::default()).await.is_err()); + kube.admit(|w| (w.plural == "clienttrafficpolicies").then(|| (500, "etcd timeout".into()))); + assert!(apply(&client, &pyo, &b).await.is_err()); + assert!(!headers_kept()); + } } diff --git a/crates/pyo-agent/src/scope.rs b/crates/pyo-agent/src/scope.rs index 50e4fb73..00b16c50 100644 --- a/crates/pyo-agent/src/scope.rs +++ b/crates/pyo-agent/src/scope.rs @@ -306,6 +306,7 @@ pub async fn detect(client: &Client, policy: Policy) -> AgentScope { policy, install, self_update, + headers_kept: crate::gateway::headers_kept(), } } diff --git a/crates/pyo-proto/src/rbac.rs b/crates/pyo-proto/src/rbac.rs index 29cc4e86..f8ed0f40 100644 --- a/crates/pyo-proto/src/rbac.rs +++ b/crates/pyo-proto/src/rbac.rs @@ -1033,6 +1033,11 @@ pub struct AgentScope { /// It may refresh its admission policy ([`SELF_UPDATE_ROLE`] is bound). #[serde(default)] pub self_update: bool, + /// The cluster's admission policy is older than the agent's and refused + /// the client policies that remove client-sent visitor headers, so the + /// agent wrote them without that (`gateway.rs` `write_client_policy`). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub headers_kept: bool, } /// What the gateway could get at if it were broken into. From 402f2c4a37b7e98f96b4de5d05f2371ea8d2f34c Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 14:41:15 +0700 Subject: [PATCH 004/139] fix(api): say when a cluster's older install keeps visitor headers --- crates/pyo-api/src/install.rs | 41 ++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/pyo-api/src/install.rs b/crates/pyo-api/src/install.rs index e305947c..859ecd13 100644 --- a/crates/pyo-api/src/install.rs +++ b/crates/pyo-api/src/install.rs @@ -422,6 +422,21 @@ fn token_stamp(token: &str) -> String { /// the command is): shown with its "Update needed", and by what waits for it. pub const OUTDATED: &str = "This cluster's agent needs an update. Run the command under Refresh this cluster in the cluster's settings."; +/// An outdated install that refused the client policies removing +/// client-sent visitor headers: its agent wrote them without that +/// (`AgentScope::headers_kept`). +pub const HEADERS_KEPT: &str = "This cluster's install is older than Pyo's. Run the command under Refresh this cluster in the cluster's settings so client-sent visitor headers are removed."; + +/// Why an outdated install needs its connect command, when nothing more +/// particular is known. +fn outdated_message(scope: &pyo_proto::rbac::AgentScope) -> &'static str { + if scope.headers_kept { + HEADERS_KEPT + } else { + OUTDATED + } +} + /// A deploy that needs what an outdated install can't do. pub fn outdated_deploy() -> String { format!("{OUTDATED} Then deploy again.") @@ -632,7 +647,7 @@ pub async fn sync( if !message.is_empty() { out["message"] = json!(message); } else if state == "outdated" { - out["message"] = json!(OUTDATED); + out["message"] = json!(outdated_message(scope)); } Ok((out, send)) } @@ -688,6 +703,30 @@ mod tests { assert_eq!(install_state(&loose, "h1", None).0, "current"); } + /// A cluster whose install refused the client policies that remove + /// visitor headers says so, and what to run. + #[test] + fn an_install_that_keeps_visitor_headers_says_so() { + let mut s = scope("old", false); + assert_eq!(install_state(&s, "h1", None).0, "outdated"); + assert_eq!(outdated_message(&s), OUTDATED); + s.headers_kept = true; + assert_eq!(outdated_message(&s), HEADERS_KEPT); + assert!(HEADERS_KEPT.contains("Refresh this cluster")); + assert!(!HEADERS_KEPT.contains(';')); + // As the agent sends it, and as older agents (without it) do. + let sent: AgentScope = serde_json::from_value(serde_json::json!({ + "access": "limited", "admission": "enforced", "headersKept": true, + })) + .unwrap(); + assert!(sent.headers_kept); + let older: AgentScope = + serde_json::from_value(serde_json::json!({ "access": "limited", "admission": "enforced" })) + .unwrap(); + assert!(!older.headers_kept); + assert!(serde_json::to_value(&older).unwrap().get("headersKept").is_none()); + } + #[test] fn a_missing_admission_policy_waits_for_the_connect_command() { let missing = AgentScope { From 0ecf370ea87c9aa0d0c9f0d270579ae24775aebd Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 14:41:15 +0700 Subject: [PATCH 005/139] fix(agent): keep applying the firewall past a failing service --- crates/pyo-agent/src/firewall.rs | 123 +++++++++++++++++++++++++------ 1 file changed, 100 insertions(+), 23 deletions(-) diff --git a/crates/pyo-agent/src/firewall.rs b/crates/pyo-agent/src/firewall.rs index 04ef04c1..81532331 100644 --- a/crates/pyo-agent/src/firewall.rs +++ b/crates/pyo-agent/src/firewall.rs @@ -141,29 +141,17 @@ pub async fn sync(agent: &crate::Agent, sync: FirewallSync) -> anyhow::Result = vec![]; for t in &sync.targets { - // Its workload gone (a delete that ran first: commands on a service - // take turns, main.rs `ordered_keys`): its routes stay gone. - let spec = gateway::target_spec(t, sync.waf)?; - let Some((notes, _)) = gateway::apply_routes(agent, &spec, true).await? else { - skipped += 1; - continue; - }; - for note in notes { - tracing::warn!(service = %t.service.name, "{note}"); - } - // Ports that bypass the gateway: their Service carries the ranges the - // network policy lets in (rollout.rs's set_isolation writes it). - let services: Api = Api::namespaced(client.clone(), &t.service.namespace); - let public = crate::rollout::public_service_name(&t.service.name); - if services.get_opt(&public).await?.is_some() { - let patch = json!({ "metadata": { "annotations": { FIREWALL_ANNOTATION: gateway::ip_blocks_json(&gateway::fw_layers(&spec, None)) } } }); - services - .patch(&public, &PatchParams::default(), &Patch::Merge(&patch)) - .await?; + match apply_target(agent, t, sync.waf).await { + Ok(true) => n += 1, + Ok(false) => skipped += 1, + Err(e) => { + tracing::warn!(service = %t.service.name, error = %format!("{e:#}"), "couldn't apply the firewall to a service"); + failed.push(format!("{}: {e:#}", t.service.name)); + } } - crate::rollout::set_isolation(client, &t.service.namespace, t.network_isolation).await?; - n += 1; } // No service wants it: the routes no longer point at it (above); the // API removes it. @@ -175,8 +163,97 @@ pub async fn sync(agent: &crate::Agent, sync: FirewallSync) -> anyhow::Result format!("Firewall applied to {n} service(s)"), _ => format!("Firewall applied to {n} service(s); {skipped} no longer here"), - }) + }; + if !failed.is_empty() { + anyhow::bail!("{done}. It couldn't be applied to {}", failed.join(". ")); + } + Ok(done) +} + +/// Apply the firewall to one running service: its routes, its public +/// Service's ranges and its network policies. False when its workload is +/// gone (a delete that ran first: commands on a service take turns, main.rs +/// `ordered_keys`), and its routes stay gone. +async fn apply_target( + agent: &crate::Agent, + t: &pyo_proto::FirewallTarget, + waf: bool, +) -> anyhow::Result { + let client = &agent.kube; + let spec = gateway::target_spec(t, waf)?; + let Some((notes, _)) = gateway::apply_routes(agent, &spec, true).await? else { + return Ok(false); + }; + for note in notes { + tracing::warn!(service = %t.service.name, "{note}"); + } + // Ports that bypass the gateway: their Service carries the ranges the + // network policy lets in (rollout.rs's set_isolation writes it). + let services: Api = Api::namespaced(client.clone(), &t.service.namespace); + let public = crate::rollout::public_service_name(&t.service.name); + if services.get_opt(&public).await?.is_some() { + let patch = json!({ "metadata": { "annotations": { FIREWALL_ANNOTATION: gateway::ip_blocks_json(&gateway::fw_layers(&spec, None)) } } }); + services + .patch(&public, &PatchParams::default(), &Patch::Merge(&patch)) + .await?; + } + crate::rollout::set_isolation(client, &t.service.namespace, t.network_isolation).await?; + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A firewall sync goes on past a service whose routes fail: the + /// services after it still get theirs, and the sync says which failed. + #[tokio::test] + async fn one_failing_service_doesnt_stop_the_others() { + let (kube, client) = crate::fakekube::FakeKube::start().await; + let target = |name: &str| -> pyo_proto::FirewallTarget { + serde_json::from_value(json!({ + "service": { "serviceId": format!("svc_{name}"), "name": name, "namespace": format!("ns-{name}"), "workloadKind": "Deployment" }, + "projectId": "prj_1", "routesRevision": 1, "firewall": {}, + "ports": [{ "name": "http", "containerPort": 8080, "protocol": "HTTP", "exposure": "http", "publicPort": null }], + "domains": [{ "hostname": format!("{name}.example.com"), "portName": "http" }], + })) + .unwrap() + }; + let mut targets = vec![]; + for name in ["a", "b", "c"] { + kube.put( + &format!("apis/apps/v1/namespaces/ns-{name}/deployments/{name}"), + json!({ "apiVersion": "apps/v1", "kind": "Deployment", "metadata": { "labels": { crate::observe::SERVICE_LABEL: format!("svc_{name}") } } }), + ); + targets.push(target(name)); + } + // The first service's routes can't be written. + kube.admit(|w| w.body.to_string().contains("svc_a").then(|| (500, "etcd timeout".into()))); + let agent = crate::Agent { + kube: client, + api: crate::api::PyoApi::new("http://127.0.0.1:9", "t").unwrap(), + cancels: Default::default(), + deploying: Default::default(), + routes: Default::default(), + policy: std::sync::Arc::new(std::sync::RwLock::new(Default::default())), + }; + let e = sync(&agent, FirewallSync { targets, waf: false }) + .await + .expect_err("the first service failed"); + let e = format!("{e:#}"); + assert!(e.starts_with("Firewall applied to 2 service(s)."), "{e}"); + assert!(e.contains("a: ") && e.contains("etcd timeout"), "{e}"); + assert!(!e.contains("b: ") && !e.contains("c: "), "{e}"); + let route = |name: &str| { + kube.get(&format!( + "apis/gateway.networking.k8s.io/v1/namespaces/{GATEWAY_NS}/httproutes/ns-{name}-{name}-http-http" + )) + }; + assert!(route("a").is_none()); + assert!(route("b").is_some(), "the service after it"); + assert!(route("c").is_some(), "and the last one"); + } } From 62188628054df5bc975e612bbdebdf51626fe223 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 14:41:15 +0700 Subject: [PATCH 006/139] fix(agent): keep publishing ports past a failing service --- crates/pyo-agent/src/rollout.rs | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/crates/pyo-agent/src/rollout.rs b/crates/pyo-agent/src/rollout.rs index 4764b327..27c43da2 100644 --- a/crates/pyo-agent/src/rollout.rs +++ b/crates/pyo-agent/src/rollout.rs @@ -694,6 +694,8 @@ pub async fn set_public_ports(client: &kube::Client, on: bool) -> anyhow::Result ))) .await?; let mut changed: Vec = vec![]; + // One Service that fails doesn't keep the others from theirs. + let mut failed: Vec = vec![]; for svc in &list.items { let (Some(ns), Some(name)) = (svc.metadata.namespace.clone(), svc.metadata.name.clone()) else { @@ -709,10 +711,14 @@ pub async fn set_public_ports(client: &kube::Client, on: bool) -> anyhow::Result }; if let Err(e) = api.patch(&name, &pp, &Patch::Merge(&patch)).await { // Its server ports were taken meanwhile: new ones. - let Some(retry) = public_patch(svc, on, false).filter(|_| on) else { - return Err(e.into()); + let retried = match public_patch(svc, on, false).filter(|_| on) { + Some(retry) => api.patch(&name, &pp, &Patch::Merge(&retry)).await.err(), + None => Some(e), }; - api.patch(&name, &pp, &Patch::Merge(&retry)).await?; + if let Some(e) = retried { + failed.push(format!("{ns}/{name}: {e}")); + continue; + } } tracing::info!(namespace = %ns, service = %name, on, "public ports"); if !changed.contains(&ns) { @@ -721,11 +727,22 @@ pub async fn set_public_ports(client: &kube::Client, on: bool) -> anyhow::Result } // The namespaces' policies follow their public Services. for ns in changed { - let isolated = Api::::namespaced(client.clone(), &ns) + let isolated = match Api::::namespaced(client.clone(), &ns) .get_opt(pyo_proto::ISOLATION_POLICY) - .await? - .is_some(); - set_isolation(client, &ns, isolated).await?; + .await + { + Ok(p) => p.is_some(), + Err(e) => { + failed.push(format!("{ns}: {e}")); + continue; + } + }; + if let Err(e) = set_isolation(client, &ns, isolated).await { + failed.push(format!("{ns}: {e:#}")); + } + } + if !failed.is_empty() { + anyhow::bail!("{}", failed.join(". ")); } Ok(()) } From 4727af8c7b7fea3b6fa1864bcd64abde8091f19a Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 14:41:55 +0700 Subject: [PATCH 007/139] fix(agent): write the gateway's client policies again once the install changes --- crates/pyo-agent/src/gateway.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/pyo-agent/src/gateway.rs b/crates/pyo-agent/src/gateway.rs index 7e4416e3..0bd33c3c 100644 --- a/crates/pyo-agent/src/gateway.rs +++ b/crates/pyo-agent/src/gateway.rs @@ -1484,11 +1484,17 @@ pub async fn remove(client: &Client, service_id: &str) { /// manifest that also allows it) reaches the proxies, which then roll. The /// tailnet Gateway follows the API's wanted list (tailnet.rs). /// One the cluster's install refuses (older than Pyo's, until the -/// cluster's connect command runs) waits for that install to change. +/// cluster's connect command runs) waits for that install to change. So do +/// client policies written as an older install accepts them +/// ([`headers_kept`]): they're written again once it changes. pub async fn ensure(client: Client) { let mut refusals = 0; loop { match ensure_once(&client).await { + Ok(()) if headers_kept() => { + refusals += 1; + crate::refused::wait_for_install(&client, refusals).await; + } Ok(()) => { tracing::info!("gateway ready"); return; From b145440139653511e94c79a20eb7b03cd6760344 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:03:13 +0700 Subject: [PATCH 008/139] docs: apply the tunnel decisions to the cloudflare tunnel spec Answers the spec's 13 open questions as accepted on 2026-11-22: the origin key on the control plane, 15 year origin certificates with no renewal loop, ports kept public in tunnel mode, an optional apex-only default domain, no record put back by default when a domain goes, and the cf-visitor redirect at the gateway. Adds what came up since: the migration moves to 0040, the connect.sh preflight already shipped in 0.5.5, a cluster on an older install is refused tunnel mode until its connect command runs, and tunnel routes carry no 403 gate so a domain answers both ways while it switches. Adds a build status section to pick the work up from. --- docs/cloudflare-tunnel.md | 284 +++++++++++++++++++++++++++----------- 1 file changed, 202 insertions(+), 82 deletions(-) diff --git a/docs/cloudflare-tunnel.md b/docs/cloudflare-tunnel.md index 1e3239a3..89dab759 100644 --- a/docs/cloudflare-tunnel.md +++ b/docs/cloudflare-tunnel.md @@ -30,8 +30,93 @@ that commit. Pyo Cloud references are to pyo-cloud at 94956c8. 16. Docs pages 17. Test plan 18. Build plan (phases, file:line) -19. Open questions +19. Open questions (answered) 20. Draft docs page +21. Build status + +--- + +## Decisions (2026-11-22) + +The user accepted these answers to the open questions (§19). The sections +below are updated to match. + +1. **Origin certificate key**: made by the control plane (rcgen) and kept + sealed with the team's certificates. +2. **Origin CA validity**: 15 years (5475 days, Cloudflare's longest). No + renewal loop. Pyo still revokes and issues a new one on demand: when a + new name isn't covered, on **Rotate** (new tunnel token and new + certificate), and on removal. +3. **TCP and UDP ports in tunnel mode**: published on the servers by + default, since the user asked for them per service. The Traffic panel + says they don't go through the tunnel. +4. **Default domain**: optional. Only a zone apex, as `*.example.com`. A + cluster can be in tunnel mode with only domains switched by hand (Pyo + Ops needs that). Without a default domain there are no free domains in + tunnel mode. +5. **Removing a domain** that replaced a record: the old record isn't put + back by default. The remove dialog offers "Put back the old record" + (off by default). +6. **One Cloudflare account per tunnel**: yes. +7. **Pyo's own dashboard through the tunnel**: not in 0.51.0. +8. **Pyo Ops**: cloud.pyo.dev and agent.pyo.dev move onto it right after + 0.51.0, with no default domain. Planned in §14, not done as part of + this work. +9. **HTTPS redirect**: at the Gateway, from `cf-visitor`. +10. **Who may switch a domain**: developers when nothing is in the way, + owners and admins when it replaces an existing record. +11. **CF-Connecting-IP fix**: shipped in 0.5.5 (§8.4). Done. +12. **Release number**: 0.51.0. +13. **Large uploads**: done in 0.5.x (database dumps upload in parts, + static site files up to 90 MiB). Done. + +Decisions made while building (not in the first draft): + +- **What moves when a cluster switches to tunnel mode.** Pyo asks for a + switch of every domain of the cluster in a tunnel-ready zone of the + tunnel's account. A domain with nothing in the way (no record, or only + Pyo's own) switches. A domain with someone else's record stops at + "confirm" and waits for **Replace and switch**. So records made by hand + or by Terraform (Pyo Ops) are never replaced without a yes. Pyo's own + direct record isn't kept in `previous`: Switch back makes a new one. +- **No 403 gate on tunnel names.** The first draft put the firewall's + "behind" gate (`source.port != 0`) on tunnel routes. It's left out: + Envoy reads the visitor from X-Forwarded-For only on connections from + the connectors, so any other connection is its own visitor and can't + pick an address. Without the gate a domain answers both ways while it + switches (the Gateway has the tunnel listener before the record moves, + and keeps it until the record is back), so there's no gap on a cluster + with public ports. A new connector pod whose address isn't trusted yet + is seen as its own address for those few seconds. +- **Tunnel domains keep their :80 route.** Nothing reaches it through the + tunnel (cloudflared speaks HTTPS), but a domain mid-switch still + answers plain HTTP directly. Less special casing in the route builder. +- **A behind-Cloudflare service with tunnel domains**: its CDN client + policy covers only its direct HTTPS listeners. The tunnel policy covers + the tunnel ones (Envoy Gateway allows one section policy per listener). + The behind gate stays on its direct routes only. +- **Clusters on an older install.** Tunnel mode changes the agent's + admission policy (the connector's Deployment, Secret and PDB in + pyo-system, the `pyo-tunnel-origin` and `pyo-public-ports` Services, the + `tunnel` client policy label). Since 1cebb7a the policy counts toward + `agentAccess`, so the 0.51.0 release shows the "run the connect command" + notice by itself. On top of that: + - `setClusterTraffic` to `tunnel` is refused while the cluster's install + is outdated (`install::install_state` says "outdated", or the agent + hasn't reported the `tunnel` capability): "Run the command under + Refresh this cluster in the cluster's settings first." So a cluster + never loses its public ports for a tunnel it can't run. + - When the install later turns out older than the agent (a refused + write of a tunnel object), the agent keeps what's running, writes + nothing else for the tunnel, reports `TunnelReport.refused`, and tries + again once the install changes (`refused::install_stamp`). The status + line says "Run the command under Refresh this cluster in the cluster's + settings." The Gateway itself is never broken by that refusal: the + tunnel client policy is written through `write_client_policy`, and a + refused one is skipped and reported, never stopping the service's + routes. +- **Rotate** gives the tunnel a new token and a new certificate in one + action. There's no separate certificate action. --- @@ -49,7 +134,7 @@ that commit. Pyo Cloud references are to pyo-cloud at 94956c8. - The control plane holds the token (sealed, as today), makes one tunnel per cluster through Cloudflare's API, keeps its routes (remotely managed ingress) and proxied DNS records in step with the cluster's domains, and - issues and renews an Origin CA certificate for Pyo Gateway. + issues a 15 year Origin CA certificate for Pyo Gateway. - The agent gets only the tunnel token. It runs cloudflared as a system part (2 replicas spread across servers, HTTP/2 to Cloudflare), pointed at Pyo Gateway inside the cluster over HTTPS, and reports its health. @@ -76,7 +161,7 @@ that commit. Pyo Cloud references are to pyo-cloud at 94956c8. - More than one Cloudflare account per cluster tunnel (see §11). - Managing zone settings (Always Use HTTPS, SSL mode, caching). Pyo never changes zone-wide settings. -- Pyo's own dashboard through the tunnel (open question Q7). +- Pyo's own dashboard through the tunnel (decision 7). - Uptime checks or status pages (never in Pyo). ## 2. How it fits together @@ -138,12 +223,13 @@ Radio group, same look as "Traffic routing" (`TrafficMode.tsx:24-53`): When Cloudflare Tunnel is picked, the panel shows its settings below the radio group: -- **Default domain** (select of tunnel-ready zones, required): hint - "Services get names like web.example.com." +- **Default domain** (select of tunnel-ready zones, optional, "None" + first): hint "Services get names like web.example.com." - **Cloudflare account** (select, only when the token's zones span more than one account). -- **Public TCP and UDP ports** (switch, shown only when the cluster has any): - "On every server except build-only servers." +- **Public TCP and UDP ports** (switch, on by default, shown only when the + cluster has any): "On every server except build-only servers. They don't + go through the tunnel." - Status line (see §10), with a **Remove tunnel** button under Danger zone when the cluster is not in tunnel mode and still has one. @@ -151,7 +237,7 @@ Confirm dialog before switching to Cloudflare Tunnel: - Title: "Switch eu to Cloudflare Tunnel?" - Body lines, only those that apply: - - "Websites on example.com zones move to the tunnel." + - "Websites on example.com zones move to the tunnel. Records Pyo didn't make wait for your OK." - "3 domains aren't in your Cloudflare account. They stop answering from the internet." - "The public dashboard closes. Open Pyo through Tailscale or your local network." (cluster Pyo runs on) - Buttons: "Cancel", "Switch". @@ -195,7 +281,7 @@ become one switch, on by default in tunnel mode: **E. Remove domain**: the existing remove dialog's `DeleteRecordSwitch` (`Cloudflare.tsx:410`) gets a second switch when a record was kept: -"Put back the old record" (on by default), description +"Put back the old record" (off by default, decision 5), description "A blog.example.com 203.0.113.7". ### 3.2 CLI (`crates/pyo-cli`) @@ -205,7 +291,7 @@ New subcommands under the existing `pyo cloudflare` and `pyo domain` ``` pyo cloudflare tunnel status [--cluster eu] -pyo cloudflare tunnel on --cluster eu --default-domain example.com [--account ] [--no-public-ports] +pyo cloudflare tunnel on --cluster eu [--default-domain example.com] [--account ] [--no-public-ports] pyo cloudflare tunnel off --cluster eu [--to public|tailscale] pyo cloudflare tunnel remove --cluster eu [--keep-records] pyo cloudflare tunnel rotate --cluster eu @@ -240,8 +326,8 @@ spec). Plus one read endpoint. Details in §5. ## 4. Data model and migration -New migration `crates/pyo-api/migrations/0039_cloudflare_tunnel.sql` (next -free number after `0038_database_log_follows.sql`). +New migration `crates/pyo-api/migrations/0040_cloudflare_tunnel.sql` (0039 +went to `0039_database_import_parts.sql` in 0.5.5). ```sql -- The cluster's traffic: 'public' (ports 80 and 443 on its servers), @@ -284,9 +370,12 @@ CREATE TABLE pyo.cluster_tunnels ( -- The Origin CA certificate the tunnel's domains use. certificate_id text REFERENCES pyo.certificates (id) ON DELETE SET NULL, -- Cloudflare's id for it, to revoke it, and the one it replaced - -- (revoked a day after the agent took the new one). + -- (revoked a day after the new one was issued). cf_certificate_id text, cf_certificate_old text, + cf_certificate_old_at timestamptz, + -- Asked for by Rotate: a new tunnel secret and a new certificate. + rotate boolean NOT NULL DEFAULT false, -- Last reads: Cloudflare's view ({status, connections: [{colo, clientVersion, -- openedAt, originIp}], at}) and the agent's ({tunnelId, pods: [...], at}). cf_status jsonb NOT NULL DEFAULT '{}', @@ -357,8 +446,10 @@ for the token, "Clusters" for traffic, "Domains" for the switch /// How a cluster takes web traffic: "public" (ports 80 and 443 on every server but build-only ones), /// "tailscale" (only from the tailnet, or only inside the cluster without Tailscale) or "tunnel" /// (through Cloudflare Tunnel, with no ports 80 and 443 open). For "tunnel", the team's Cloudflare -/// token needs Cloudflare Tunnel:Edit and SSL and Certificates:Edit, and `defaultDomain` names one of -/// its zones: services get names under it. Domains in the account move to the tunnel. Team owners and admins. +/// token needs Cloudflare Tunnel:Edit and SSL and Certificates:Edit. `defaultDomain` (optional) names one of +/// its zones: services get names under it. Domains in the account move to the tunnel, and those with a +/// record Pyo didn't make wait for `setDomainTunnel` with `replace`. Refused while the cluster's install is +/// older than Pyo's. Team owners and admins. SetClusterTraffic { cluster_id: String, mode: String, @@ -437,7 +528,7 @@ pinned, no redirects, outbound client with `Reach { private: false }`). | Rotate token | `PATCH /accounts/{acct}/cfd_tunnel/{tunnel}` `{ "tunnel_secret": "" }`, then drop connections | Cloudflare Tunnel:Edit | | Drop connections | `DELETE /accounts/{acct}/cfd_tunnel/{tunnel}/connections` | Cloudflare Tunnel:Edit | | Delete tunnel | `DELETE /accounts/{acct}/cfd_tunnel/{tunnel}` (needs no active connections) | Cloudflare Tunnel:Edit | -| Origin certificate | `POST /certificates` `{ "csr": "", "hostnames": [...], "request_type": "origin-ecc", "requested_validity": 365 }` | SSL and Certificates:Edit | +| Origin certificate | `POST /certificates` `{ "csr": "", "hostnames": [...], "request_type": "origin-ecc", "requested_validity": 5475 }` | SSL and Certificates:Edit | | Revoke it | `DELETE /certificates/{id}` | SSL and Certificates:Edit | Checked against Cloudflare's docs on 2026-11-22: "Create a tunnel (API)" @@ -509,8 +600,9 @@ tasks next to `deploy::dns_watcher` (`deploy.rs:2531`). Per cluster with a 3. **Wanted routes** = every domain with `tunnel: true` on a non-deleting service of the cluster (by `services.cluster_id`), plus `*.` when set. PUT when the hash differs. -4. **Certificate.** Needed names (§9). Missing a name or under 30 days - left: issue a new one, store it, point the domains at it (§9). +4. **Certificate.** Needed names (§9). Missing a name, or `rotate` set: + issue a new one, store it, point the domains at it (§9). No renewal by + age (15 years, decision 2). 5. **Records**, only after step 3 succeeded in this or an earlier pass: - Rows `status = 'switching'`: `cloudflare::ensure`-like with `kind = CNAME`, `content = .cfargotunnel.com`, @@ -530,8 +622,8 @@ tasks next to `deploy::dns_watcher` (`deploy.rs:2531`). Per cluster with a `cf_status`. Health is computed (§10). Down for 5 minutes: alert event `cluster.tunnel_down` (alerts.rs, like server offline), and `cluster.tunnel_up` when back. -8. **Old certificate.** `cf_certificate_old` and the agent confirmed the - new one a day ago (routes synced): revoke and clear. +8. **Old certificate.** `cf_certificate_old` and `cf_certificate_old_at` + passed (a day after the new one was issued): revoke and clear. 9. **Removing.** `state = 'removing'`: PUT ingress with only the catch-all, restore or delete records (only Pyo's, `ours()`), enqueue `TunnelRemove`, wait for its answer (or 10 minutes), drop connections, @@ -556,12 +648,15 @@ switching, `active` once the CNAME is in place and the route is live. ### 6.5 Free domains in tunnel mode `freedomain::Mode` (`freedomain.rs:69-89`) gains `Tunnel`. In tunnel mode -the cluster's free domain is `-.` +with a default domain, the cluster's free domain is +`-.` (covered by the wildcard record and route) instead of nip.io, and the dashboard's "free domain" button makes that. Existing nip.io domains on the cluster stop answering from the internet in tunnel mode (no public 80/443). The confirm dialog counts them with the other unreachable domains. On -Switch back to public, they answer again (nothing to move). +Switch back to public, they answer again (nothing to move). Without a +default domain, the cluster has no free domain in tunnel mode and the +dashboard's button says "Pick a default domain first." ## 7. Agent @@ -659,10 +754,11 @@ The agent watches pods with `app.kubernetes.io/name=pyo-tunnel` (all their `/128`). A change rewrites the client policies of services with tunnel domains (§8.3), the same way the websites' settings rewrite CDN policies today (`gateway.rs:1914`). A new pod's first requests can arrive before its -address is trusted. They're refused by the gate (403) for those few seconds, -never let through with the wrong visitor. The readiness probe keeps -Cloudflare from sending it traffic until cloudflared is connected, which -usually takes longer than the policy update. +address is trusted. For those few seconds they're seen as the pod's own +address (see Decisions). The readiness probe keeps Cloudflare from +sending it traffic until cloudflared is connected, which usually takes +longer than the policy update, and the agent watches pods as soon as +they have an address, ready or not. ### 7.4 Heartbeat @@ -685,6 +781,9 @@ pub struct TunnelReport { pub pods: Vec, /// The origin Service and the tunnel certificate Secret are in place. pub origin_ready: bool, + /// The cluster's install refused a tunnel object: its admission policy + /// is older than the agent's (see Decisions). + pub refused: bool, } ``` @@ -752,11 +851,10 @@ set by `routes::domain_specs` (`routes.rs:19-43`) from the domain's hostname (`gateway.rs:320-335`), `tls = "custom"`, the tunnel's certificate (fetched like any uploaded one, `gateway.rs:741-758`). - **Routes**: its own route per port, `{base}-tunnel-{port}`, parent the - service's Gateway and its listener sections, so the gate below applies to - tunnel names only. A service can mix tunnel and direct domains. -- **No :80 routes**: tunnel domains are left out of the shared HTTP - listener (`gateway.rs:347-380`). cloudflared always speaks HTTPS to the - Gateway. + service's Gateway, so the redirect below applies to tunnel names only. + A service can mix tunnel and direct domains. +- **:80 routes stay** as for any domain (see Decisions). cloudflared + always speaks HTTPS to the Gateway. - **HTTPS redirect**: with `redirect_https`, the tunnel route's first rule matches header `cf-visitor` exactly `{"scheme":"http"}` and redirects to https (301). Cloudflare sets that header on every proxied request and @@ -768,11 +866,9 @@ set by `routes::domain_specs` (`routes.rs:19-43`) from the domain's the visitor from X-Forwarded-For (the address Cloudflare appended, the same one it puts in CF-Connecting-IP) only on connections from cloudflared's pods. Everyone else is their own address. -- **Gate**: the firewall's "behind" gate (`firewall::behind_gate_rule`, - `BEHIND_GATE_CEL = "source.port != 0"`, `pyo-proto/src/firewall.rs:136-150`) - goes ahead of the service's own rules on the tunnel routes. A direct - connection with a tunnel hostname (another pod, or a visitor reaching - 443 on a public-ports cluster) gets 403. +- **No gate** (see Decisions): tunnel routes get the service's own + firewall rules (`web_authorization` without `behind`), never the CDN + gate. A direct connection with a tunnel hostname is its own visitor. - **Firewall, rate limits, WAF, countries**: unchanged. They read the visitor Envoy worked out, so they see the real one. GeoIP country follows the visitor address. The access log's `remote` field @@ -811,7 +907,7 @@ header is Cloudflare's own, so audit and rate limits see the real visitor. This also closes the Pyo Cloud item "checking real client IPs in the audit log". -Done in 0.5.5 (branch `fix/client-ip-headers`): +**Done** in 0.5.5 (branch `fix/client-ip-headers`, decision 11): - Every client policy sets `headers.earlyRequestHeaders.remove` (`system::visitor_headers`): CF-Connecting-IP, CF-Connecting-IPv6, @@ -840,8 +936,8 @@ mode. ## 9. Certificates -- **One Origin CA certificate per cluster tunnel**, ECDSA P-256, 365 days, - renewed 30 days before it ends. Names: for each tunnel hostname, the +- **One Origin CA certificate per cluster tunnel**, ECDSA P-256, 5475 + days (15 years), never renewed by age (decision 2). Names: for each tunnel hostname, the hostname itself if it's a zone apex, else `*.` (`blog.example.com` → `*.example.com`, `a.b.example.com` → `*.b.example.com`), plus `*.`. Deduped, at most 200. @@ -852,21 +948,21 @@ mode. (`pyo.certificates`, key sealed with `seal_credential`), named "Cloudflare Tunnel (eu)", issuer "Cloudflare Origin CA". This is the pattern preview wildcards already use (`previews/domain.rs:460-520`). - Open question Q1 covers keeping the key in the cluster instead. + Decision 1. - **Tunnel domains use it as an uploaded certificate**: `tlsMode = "custom"`, `certificateId = cluster_tunnels.certificate_id`. The agent already fetches custom certificates from the API and writes them as the listener's Secret (`gateway.rs:741-758`). Nothing new on the agent's side. -- **Renewal**: the new certificate replaces the row's chain and key in - place (same id), and the services using it get a routes sync - (`certs::used_by`, `certs.rs:208`, as `ReplaceCertificate` does). The - old Cloudflare certificate is revoked a day later (§6.3 step 8). +- **Reissue** (a name not covered, or Rotate): the new certificate + replaces the row's chain and key in place (same id), and the services + using it get a routes sync (`certs::used_by`, `certs.rs:208`, as + `ReplaceCertificate` does). The old Cloudflare certificate is revoked a + day later (§6.3 step 8). - **ACME skipped**: tunnel domains never get a cert-manager `Certificate`, so no HTTP-01 to fail. `cloudflare::proxy_ready` (`cloudflare.rs:1199-1245`) only handles `via = 'direct'` rows. -- **Expiry alerts**: the existing certificate warnings (`certs::warn_expiring`, - `certs.rs:223`) skip certificates the tunnel loop renews, unless renewal - failed for 7 days. +- **Expiry alerts**: none needed in practice (15 years). The existing + warnings (`certs::warn_expiring`) still apply if one ever gets close. - Visitors see Cloudflare's edge certificate (Universal SSL). The Origin CA certificate is only between cloudflared and the Gateway. @@ -886,7 +982,9 @@ Extra lines under the status, only when true: - "pyo-tunnel can't start on fal2: ImagePullBackOff" (from the agent's pod reason). - "Connect Cloudflare again to change the tunnel." (token gone or refused). -- "Certificate renewal failed: " (after 7 days of failures). +- "Certificate: " (the last issue failed). +- "Run the command under Refresh this cluster in the cluster's settings." + (the agent reports `refused`, see Decisions). Colours follow the existing Badge tones (success, warning, destructive). The cluster list shows a small "Tunnel" badge next to the cluster's status @@ -902,8 +1000,9 @@ when in tunnel mode, warning tone when degraded or down. another account. The tunnel lives in the account of the default domain's zone. Zones in other accounts show "Another Cloudflare account" and stay direct. -- **Default domain**: required in tunnel mode, since nip.io names can't be - proxied. It must be a zone the token covers (`example.com`, not +- **Default domain**: optional (decision 4). Without it, only domains + switched by hand use the tunnel, and there are no free domains (nip.io + names can't be proxied). It must be a zone the token covers (`example.com`, not `apps.example.com`): Universal SSL only covers one level below the zone, so `web.apps.example.com` would fail TLS at Cloudflare without Advanced Certificate Manager. One wildcard record `*.example.com` (proxied CNAME) @@ -958,8 +1057,9 @@ when in tunnel mode, warning tone when degraded or down. | QUIC/7844 blocked outbound | cloudflared can't connect | Pod not ready. Docs: allow outbound TCP 7844 | | Tunnel deleted in Cloudflare | 1033 until recreated | Loop recreates it, repoints Pyo's records, sends the new token | | Routes edited in Cloudflare | Pyo's config is PUT back on the next pass | Docs: don't edit Pyo's tunnel in Cloudflare | -| Origin certificate expired or revoked | 502 from cloudflared | Renewed 30 days early. Failures shown on the status line and alerted after 7 days | +| Origin certificate revoked by hand | 502 from cloudflared | Rotate issues a new one. Issue failures shown on the status line | | Agent too old (no `tunnel` capability) | Choice greyed out | "Not reported yet." | +| Cluster install older than the agent | Tunnel mode refused, or a running connector kept as it is | "Run the command under Refresh this cluster…" (see Decisions) | | New cloudflared pod not yet trusted | Its requests get 403 for a few seconds | Pod watch updates the policy | | Record conflict | Switch stops at "confirm" | User replaces or cancels | | Cloudflare 429 or 5xx | Pass retried later | Backoff per team | @@ -1046,10 +1146,9 @@ could move to this once 0.51.0 runs on Pyo Ops: 1. In Pyo Ops (team frans), replace the Cloudflare token with one that also has Cloudflare Tunnel:Edit and SSL and Certificates:Edit on pyo.dev. -2. Cluster `cl_eavb3paccm12` › Traffic › Cloudflare Tunnel, default domain - none or pyo.dev (open question Q8: a wildcard on pyo.dev would catch - unknown names, so likely no default domain on Pyo Ops). That needs the - default domain to be optional when every domain is switched by hand. +2. Cluster `cl_eavb3paccm12` › Traffic › Cloudflare Tunnel, no default + domain (decision 8: a wildcard on pyo.dev would catch unknown names). + The default domain is optional (decision 4). 3. Switch cloud.pyo.dev and agent.pyo.dev to the tunnel. Pyo shows the Terraform CNAMEs to the old tunnel and asks. After the switch, traffic goes through Pyo's tunnel. The old one stays up until removed, so this @@ -1078,17 +1177,15 @@ repo needs no change for them. ## 15. connect.sh -The existing-k3s branch (`crates/pyo-api/assets/connect.sh:1237-1243`) gets -a preflight in 0.5.5 that finds Traefik or another program on 80 or 443 -(separate fix, not part of this spec). In 0.51.0 that preflight: +Done in 0.5.5 (`8545c8f`, `378fa72`): connect.sh finds Traefik or another +program on 80 or 443, sends `&webPorts=busy` with the manifest request, +leaves the firewall as it is, and the API turns public traffic off before +the agent's first heartbeat (`install::web_ports_busy`). In 0.51.0: -- prints one line and goes on: - `Ports 80 and 443 are in use. In Pyo, choose Cloudflare Tunnel or Tailscale only for this cluster.` -- adds `&webPorts=busy` to the manifest request (`connect.sh:1011`). The - API sets the cluster's `traffic` to `tailscale` before the agent's first - heartbeat, so Envoy is installed with a ClusterIP Service and no - `svclb-envoy` pods sit pending against Traefik's. -- skips `ufw allow 443` (`connect.sh:1024`) and 80 when the ports are busy. +- `web_ports_busy` writes `traffic = 'tailscale'` (the generated + `public_traffic` can't be written). +- connect.sh's line (`web_ports_line`) becomes + `Ports 80 and 443 are in use by Traefik. Public traffic stays off, so your sites keep working. Cloudflare Tunnel can take your websites instead.` The dashboard then shows on the new cluster: "Ports 80 and 443 are taken on this server. Choose Cloudflare Tunnel or Tailscale only." with a link to @@ -1117,8 +1214,8 @@ Changed: "Public TCP and UDP ports" adds the tunnel-mode switch. - `firewall.mdx` "Behind Cloudflare" (`:58`): tunnel domains don't need it. Rules see the real visitor. -- `certificates.mdx`: the Cloudflare Tunnel certificate Pyo makes and - renews. +- `certificates.mdx`: the Cloudflare Tunnel certificate Pyo makes (15 + years, a new one on Rotate). - `system-reference.mdx` "What runs on your server" (`:143`): `pyo-tunnel` (cloudflared, 2 replicas), `pyo-tunnel-origin`, `pyo-public-ports`. "Connections" (`:41`): outbound TCP 7844 to Cloudflare in tunnel mode. @@ -1220,11 +1317,12 @@ through signed commands. ## 18. Build plan -One branch per phase, merged to `dev` in order. Rust builds one at a time -under the laptop guardrails. Each phase ends green and shippable behind the -capability flag. +Built on one branch, `feat/cloudflare-tunnel` (worktree `pyo-tunnel`), +merged to `dev` only when the feature is complete and tested. Rust builds +one at a time under the laptop guardrails. Each phase ends green and +shippable behind the capability flag. -**Phase 0 (0.5.5, separate fixes, referenced)** +**Phase 0 (0.5.5, separate fixes, done)** - connect.sh 80/443 preflight (`connect.sh:1237-1243`). - Remove client-sent `CF-Connecting-IP` at the Gateway (§8.4): @@ -1281,7 +1379,6 @@ capability flag. - `crates/pyo-api/src/snapshot.rs:140-170`: `traffic`, `tunnel`. `cloudflare::attach` (`cloudflare.rs:591-621`): `via`, `previous`. - `crates/pyo-api/src/deploy.rs:2547`: skip tunnel domains in DNS checks. -- `crates/pyo-api/src/certs.rs:223`: skip renewed tunnel certificates. - `crates/pyo-api/src/alerts.rs`: `cluster.tunnel_down`/`_up` events. **Phase 4: traffic choice, switching, default domain** @@ -1313,8 +1410,8 @@ capability flag. **Phase 5: ports, connect.sh, alerts** - `pyo-public-ports` Service (§8.5) in `gateway.rs` with its rbac pin. -- `crates/pyo-api/assets/connect.sh:1011`, `:1024`, preflight message. -- `crates/pyo-api/src/install.rs`: read `webPorts=busy`, set `traffic`. +- `crates/pyo-api/assets/connect.sh` `web_ports_line`: mention the tunnel. +- `crates/pyo-api/src/install.rs` `web_ports_busy`: set `traffic`. **Phase 6: docs, tests, Pyo Ops** @@ -1323,10 +1420,13 @@ capability flag. - Real-zone test with the user's approval (§17.4). - After 0.51.0 is on Pyo Ops: move cloud.pyo.dev and agent.pyo.dev (§14), then the pyo-cloud cleanup commit. -- Release notes (Features: Cloudflare Tunnel, Security Fixes: the - CF-Connecting-IP fix if it ships here). +- Release notes (Features: Cloudflare Tunnel). The CF-Connecting-IP fix + shipped in 0.5.5. + +## 19. Open questions (answered) -## 19. Open questions +All answered on 2026-11-22. See Decisions at the top. Kept for the +record. 1. **Origin certificate key**: made by the control plane and kept sealed with the team's certificates (like preview wildcards, less code), or @@ -1390,13 +1490,14 @@ It also lets Pyo run on a server where another program already uses ports 1. Open your cluster's **Settings** and find **Traffic**. 2. Pick **Cloudflare Tunnel**. -3. Pick a **default domain**. Services get names under it, like - `web.example.com`. +3. Pick a **default domain** if you want one. Services get names under + it, like `web.example.com`. 4. Select **Switch**. Pyo creates the tunnel and starts two connectors on different servers. -Domains in your Cloudflare account move to the tunnel. Domains in other -accounts stop answering from the internet. +Domains in your Cloudflare account move to the tunnel. If a name has a +record Pyo didn't make, Pyo asks first. Domains in other accounts stop +answering from the internet. ## Move one domain @@ -1423,7 +1524,8 @@ audit log all see the real visitor. ## TCP and UDP ports Cloudflare Tunnel carries websites only. Public TCP and UDP ports stay on -your servers' public addresses, or on Tailscale. +your servers' public addresses, or on Tailscale. They don't go through +the tunnel. ## Cloudflare's limits @@ -1437,3 +1539,21 @@ Pick **Public ports** or **Tailscale only**. Then select **Switch back** on each domain, and **Remove tunnel**. Pyo deletes the tunnel and only the records it made. ``` + +## 21. Build status + +Kept current as each phase lands, so the work can be picked up from here. +Branch `feat/cloudflare-tunnel`, worktree `/home/frx/workspace/upsetdev/pyo-tunnel`. +Not merged into `dev` until the feature is complete and tested. + +| Phase | State | +|---|---| +| Decisions applied to this spec | Done | +| 1. Token and zones | Next | +| 2. Agent and Gateway | Not started | +| 3. Control plane | Not started | +| 4. Traffic choice, switching, default domain | Not started | +| 5. Ports, connect.sh, alerts | Not started | +| 6. Docs, e2e, real-zone test, Pyo Ops | Not started (real zone and Pyo Ops need the user) | + +Known gaps: none yet. From e3d91dde8b97c524659d2cac8b9e9337fa364cd6 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:09:10 +0700 Subject: [PATCH 009/139] feat(cloudflare): check the token's tunnel permissions per zone Each zone now carries its Cloudflare account and whether it can use Cloudflare Tunnel: the token may edit DNS there, make tunnels in its account (a probe tunnel made and deleted once per account, leftovers cleaned up) and read its Origin CA certificates. Tunnel permissions are optional. A zone with neither stays DNS only, and only half of them is reported as a problem. Adds the tunnel API client (tunnels, routes, tokens, Origin CA certificates) behind its own trait, with a fake account for tests, and the pure parts the tunnel loop builds on: the routes, their hash and the certificate's names. Not compiled yet. --- crates/pyo-api/src/cloudflare.rs | 88 +++- crates/pyo-api/src/cloudflare/tests.rs | 454 ++++++++++++++++++- crates/pyo-api/src/cloudflare/tunnel.rs | 557 ++++++++++++++++++++++++ crates/pyo-api/src/ops.rs | 4 +- 4 files changed, 1073 insertions(+), 30 deletions(-) create mode 100644 crates/pyo-api/src/cloudflare/tunnel.rs diff --git a/crates/pyo-api/src/cloudflare.rs b/crates/pyo-api/src/cloudflare.rs index f845651a..f8eaaed8 100644 --- a/crates/pyo-api/src/cloudflare.rs +++ b/crates/pyo-api/src/cloudflare.rs @@ -19,6 +19,9 @@ //! first HTTP-01 check reaches the cluster directly. //! - A proxied record suggests the service's "Behind Cloudflare" firewall //! switch (the dashboard's DNS record line), until it's on. +//! - Cloudflare Tunnel (tunnel.rs): with Cloudflare Tunnel:Edit in the +//! account and SSL and Certificates:Edit in a zone, the zone is +//! tunnel-ready. Both are optional: DNS:Edit alone still connects. use crate::error::Json; use crate::error::Query; @@ -44,6 +47,9 @@ const TIMEOUT: Duration = Duration::from_secs(20); /// Zones looked at in one test, at most. const MAX_ZONES: usize = 200; +pub(crate) mod tunnel; +use tunnel::TunnelApi; + // ── Zones and records ────────────────────────────────────────────────────── /// A zone the token sees, as stored and shown. @@ -57,6 +63,32 @@ pub struct Zone { /// The permission it lacks, when it can't. #[serde(default, skip_serializing_if = "Option::is_none")] pub missing: Option, + /// The Cloudflare account it's in. A tunnel lives in one account and + /// only takes names from that account's zones. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub account_id: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub account_name: String, + /// Whether it can use Cloudflare Tunnel. + #[serde(default)] + pub tunnel: TunnelAccess, +} + +/// Whether a zone can use Cloudflare Tunnel: the token may edit DNS in it, +/// make tunnels in its account and issue its Origin CA certificates. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct TunnelAccess { + pub ready: bool, + /// The tunnel permissions the token lacks here. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub missing: Vec, +} + +impl Zone { + /// It can take domains through a tunnel. + pub fn tunnel_ready(&self) -> bool { + self.can_edit && self.tunnel.ready + } } /// A DNS record at Cloudflare. @@ -258,9 +290,13 @@ pub(crate) async fn missing_in( } } -/// The zones a token covers, and what it can do in each. -pub(crate) async fn inspect(cf: &C, marker: &str) -> Result, CfError> { - let mut zones = match cf.zones().await { +/// The zones a token covers, and what it can do in each: DNS per zone, +/// tunnels once per account, Origin CA certificates per zone. +pub(crate) async fn inspect( + cf: &C, + marker: &str, +) -> Result, CfError> { + let mut zones = match cf.zone_accounts().await { Ok(z) => z, Err(CfError::Denied(m)) => { return Err(CfError::Denied(if m.is_empty() { @@ -271,16 +307,38 @@ pub(crate) async fn inspect(cf: &C, marker: &str) -> Result return Err(e), }; - zones.sort_by(|a, b| a.1.cmp(&b.1)); + zones.sort_by(|a, b| a.name.cmp(&b.name)); zones.truncate(MAX_ZONES); + let mut tunnels: HashMap> = HashMap::new(); let mut out = vec![]; for z in &zones { - let missing = missing_in(cf, z, marker).await?; + let missing = missing_in(cf, &(z.id.clone(), z.name.clone()), marker).await?; + let mut lacks = vec![]; + if z.account_id.is_empty() { + lacks.push(tunnel::TUNNEL_EDIT.to_owned()); + } else { + if !tunnels.contains_key(&z.account_id) { + let m = tunnel::tunnel_missing(cf, &z.account_id).await?; + tunnels.insert(z.account_id.clone(), m); + } + if let Some(Some(m)) = tunnels.get(&z.account_id) { + lacks.push(m.clone()); + } + } + if let Some(m) = tunnel::certs_missing(cf, &z.id).await? { + lacks.push(m); + } out.push(Zone { - id: z.0.clone(), - name: z.1.to_ascii_lowercase(), + id: z.id.clone(), + name: z.name.to_ascii_lowercase(), can_edit: missing.is_none(), - missing, + missing: missing.clone(), + account_id: z.account_id.clone(), + account_name: z.account_name.clone(), + tunnel: TunnelAccess { + ready: missing.is_none() && lacks.is_empty(), + missing: lacks, + }, }); } Ok(out) @@ -293,14 +351,22 @@ pub fn problems(zones: &[Zone]) -> Vec { "The token can't see any zones. Give it Zone:Read on the zones Pyo may use.".into(), ]; } - zones + let mut out: Vec = zones .iter() .filter_map(|z| { z.missing .as_ref() .map(|m| format!("{}: give the token {m}.", z.name)) }) - .collect() + .collect(); + // Tunnel permissions are optional: a zone with neither is DNS only. + // One of the two means a tunnel was meant, so the other is a problem. + for z in zones.iter().filter(|z| z.can_edit) { + if z.tunnel.missing.len() == 1 { + out.push(format!("{}: give the token {}.", z.name, z.tunnel.missing[0])); + } + } + out } // ── Cloudflare over HTTP ─────────────────────────────────────────────────── @@ -791,7 +857,7 @@ pub struct CloudflareQuery { #[utoipa::path(get, path = "/cloudflare", operation_id = "getCloudflare", tag = "Integrations", params(CloudflareQuery), responses( - (status = 200, description = "`connected`, and when connected `zones` (each with `id`, `name`, `canEdit` and, when it can't, `missing`: the permission the token lacks), `createdAt`, `testedAt`, and for owners and admins `hint` and `createdBy`.", body = Object), + (status = 200, description = "`connected`, and when connected `zones` (each with `id`, `name`, `canEdit` and, when it can't, `missing`: the permission the token lacks, `accountId`, `accountName`, and `tunnel`: `ready` and the tunnel permissions it lacks as `missing`), `createdAt`, `testedAt`, and for owners and admins `hint` and `createdBy`.", body = Object), (status = 404, description = "No such team, or you aren't in it.", body = crate::error::ErrorBody), ), extensions(("x-pyo-access" = json!("read"))))] diff --git a/crates/pyo-api/src/cloudflare/tests.rs b/crates/pyo-api/src/cloudflare/tests.rs index 6fa01d07..bb3d02cd 100644 --- a/crates/pyo-api/src/cloudflare/tests.rs +++ b/crates/pyo-api/src/cloudflare/tests.rs @@ -2,22 +2,29 @@ //! only Pyo's own, who may do what, and the HTTP client's handling of //! Cloudflare's answers. Cloudflare itself is a fake account. -use std::sync::Mutex; +use std::{collections::HashMap, sync::Mutex}; +use super::tunnel::{CfZone, Connection, Kept, OriginCert, Tunnel}; use super::*; -const MARK: &str = "Made by Pyo (abc123)"; +pub(super) const MARK: &str = "Made by Pyo (abc123)"; -fn zone(id: &str, name: &str) -> Zone { +pub(super) fn zone(id: &str, name: &str) -> Zone { Zone { id: id.into(), name: name.into(), can_edit: true, missing: None, + account_id: "acct1".into(), + account_name: "Acme".into(), + tunnel: TunnelAccess { + ready: true, + missing: vec![], + }, } } -fn rec(id: &str, kind: &str, name: &str, content: &str, comment: Option<&str>) -> Record { +pub(super) fn rec(id: &str, kind: &str, name: &str, content: &str, comment: Option<&str>) -> Record { Record { id: id.into(), kind: kind.into(), @@ -29,24 +36,40 @@ fn rec(id: &str, kind: &str, name: &str, content: &str, comment: Option<&str>) - } #[derive(Clone, Copy, PartialEq)] -enum Dns { +pub(super) enum Dns { None, Read, Edit, } -/// A Cloudflare account: zones, the token's DNS permission in each, and -/// every call made. -struct Fake { - zones: Vec<(String, String, Dns)>, - zone_read: bool, - records: Mutex>, - calls: Mutex>, +/// A Cloudflare account: zones, the token's DNS permission in each, its +/// tunnels and Origin CA certificates, and every call made. +pub(super) struct Fake { + pub zones: Vec<(String, String, Dns)>, + pub zone_read: bool, + pub records: Mutex>, + /// Records' TTLs, by id (1, automatic, when not set). + pub ttls: Mutex>, + pub calls: Mutex>, next: Mutex, + /// Each zone's account (acct1 "Acme" when not set). + pub accounts: HashMap, + /// Accounts where the token can't make tunnels. + pub no_tunnels: Vec, + /// Zones whose Origin CA certificates the token can't read or issue. + pub no_certs: Vec, + /// (account, tunnel). + pub tunnels: Mutex>, + /// Each tunnel's routes: (version, config). + pub configs: Mutex>, + /// Each tunnel's secret. + pub secrets: Mutex>, + /// Issued Origin CA certificates: (id, names, revoked). + pub certs: Mutex, bool)>>, } impl Fake { - fn new(zones: &[(&str, &str, Dns)]) -> Self { + pub fn new(zones: &[(&str, &str, Dns)]) -> Self { Self { zones: zones .iter() @@ -54,16 +77,72 @@ impl Fake { .collect(), zone_read: true, records: Mutex::new(vec![]), + ttls: Mutex::new(HashMap::new()), calls: Mutex::new(vec![]), next: Mutex::new(0), + accounts: HashMap::new(), + no_tunnels: vec![], + no_certs: vec![], + tunnels: Mutex::new(vec![]), + configs: Mutex::new(HashMap::new()), + secrets: Mutex::new(HashMap::new()), + certs: Mutex::new(vec![]), } } - fn with(self, zone: &str, r: Record) -> Self { + pub fn with(self, zone: &str, r: Record) -> Self { self.records.lock().unwrap().push((zone.into(), r)); self } + pub fn account_of(&self, zone: &str) -> (String, String) { + self.accounts + .get(zone) + .cloned() + .unwrap_or_else(|| ("acct1".into(), "Acme".into())) + } + + fn id(&self, prefix: &str) -> String { + let mut n = self.next.lock().unwrap(); + *n += 1; + format!("{prefix}{n}") + } + + /// A tunnel id as Cloudflare makes them (a UUID). + fn uuid(&self) -> String { + let n = self.id(""); + format!("00000000-0000-4000-8000-{:0>12}", n) + } + + pub fn tunnel_list(&self) -> Vec { + self.tunnels + .lock() + .unwrap() + .iter() + .map(|(_, t)| t.clone()) + .collect() + } + + /// Set a tunnel's status and connections, as Cloudflare reports them. + pub fn connect(&self, id: &str, status: &str, colos: &[&str]) { + for (_, t) in self.tunnels.lock().unwrap().iter_mut() { + if t.id == id { + t.status = status.into(); + t.connections = colos + .iter() + .enumerate() + .map(|(i, c)| Connection { + client_id: format!("c{}", i / 2), + colo: (*c).into(), + client_version: "2026.10.7".into(), + opened_at: "2026-11-22T00:00:00Z".into(), + origin_ip: "203.0.113.7".into(), + }) + .collect(); + } + } + } + fn dns(&self, zone: &str) -> Dns { self.zones .iter() @@ -136,10 +215,8 @@ impl Cloudflare for Fake { if self.dns(zone_id) != Dns::Edit { return Err(Self::denied()); } - let mut n = self.next.lock().unwrap(); - *n += 1; let made = Record { - id: format!("r{n}"), + id: self.id("r"), kind: r.kind.clone(), name: r.name.clone(), content: r.content.clone(), @@ -656,3 +733,346 @@ fn reads_cloudflares_answers() { .unwrap(); assert!(!ours(&no_comment, MARK, "a.example.com")); } + +impl tunnel::TunnelApi for Fake { + async fn zone_accounts(&self) -> Result, CfError> { + Ok(self + .zones() + .await? + .into_iter() + .map(|(id, name)| { + let (account_id, account_name) = self.account_of(&id); + CfZone { + id, + name, + account_id, + account_name, + } + }) + .collect()) + } + + async fn records_kept(&self, zone_id: &str, name: &str) -> Result, CfError> { + let ttls = self.ttls.lock().unwrap().clone(); + Ok(self + .records(zone_id, name) + .await? + .into_iter() + .map(|r| Kept { + ttl: ttls.get(&r.id).copied().unwrap_or(1), + id: r.id, + kind: r.kind, + name: r.name, + content: r.content, + proxied: r.proxied, + comment: r.comment, + }) + .collect()) + } + + async fn create_kept(&self, zone_id: &str, r: &Kept) -> Result { + self.log(format!( + "create {zone_id} {} {} {}", + r.kind, r.name, r.content + )); + if self.dns(zone_id) != Dns::Edit { + return Err(Self::denied()); + } + let made = Record { + id: self.id("r"), + ..r.record() + }; + self.ttls.lock().unwrap().insert(made.id.clone(), r.ttl); + self.records + .lock() + .unwrap() + .push((zone_id.into(), made.clone())); + Ok(made) + } + + async fn tunnels_named(&self, account: &str, name: &str) -> Result, CfError> { + self.log(format!("tunnels {account} {name}")); + if self.no_tunnels.iter().any(|a| a == account) { + return Err(Self::denied()); + } + Ok(self + .tunnels + .lock() + .unwrap() + .iter() + .filter(|(a, t)| a == account && t.name.starts_with(name) && !t.deleted) + .map(|(_, t)| t.clone()) + .collect()) + } + + async fn create_tunnel(&self, account: &str, name: &str) -> Result { + self.log(format!("create tunnel {account} {name}")); + if self.no_tunnels.iter().any(|a| a == account) { + return Err(Self::denied()); + } + let t = Tunnel { + id: self.uuid(), + name: name.into(), + status: "inactive".into(), + ..Default::default() + }; + self.tunnels + .lock() + .unwrap() + .push((account.into(), t.clone())); + self.secrets + .lock() + .unwrap() + .insert(t.id.clone(), "first".into()); + Ok(t) + } + + async fn tunnel(&self, account: &str, id: &str) -> Result { + self.tunnels + .lock() + .unwrap() + .iter() + .find(|(a, t)| a == account && t.id == id) + .map(|(_, t)| t.clone()) + .ok_or(CfError::NotFound) + } + + async fn delete_tunnel(&self, account: &str, id: &str) -> Result<(), CfError> { + self.log(format!("delete tunnel {id}")); + let mut ts = self.tunnels.lock().unwrap(); + let Some((_, t)) = ts.iter_mut().find(|(a, t)| a == account && t.id == id) else { + return Err(CfError::NotFound); + }; + if !t.connections.is_empty() { + return Err(CfError::Refused( + "Cannot delete tunnel because it has active connections".into(), + )); + } + t.deleted = true; + Ok(()) + } + + async fn tunnel_token(&self, account: &str, id: &str) -> Result { + self.tunnel(account, id).await?; + let secret = self + .secrets + .lock() + .unwrap() + .get(id) + .cloned() + .unwrap_or_default(); + Ok(format!("token-{id}-{secret}")) + } + + async fn put_config(&self, account: &str, id: &str, config: &Value) -> Result { + self.log(format!("put config {id}")); + self.tunnel(account, id).await?; + let mut cs = self.configs.lock().unwrap(); + let v = cs.get(id).map_or(1, |(v, _)| v + 1); + cs.insert(id.into(), (v, config.clone())); + Ok(v) + } + + async fn config(&self, account: &str, id: &str) -> Result<(i64, Value), CfError> { + self.tunnel(account, id).await?; + Ok(self + .configs + .lock() + .unwrap() + .get(id) + .cloned() + .unwrap_or((0, Value::Null))) + } + + async fn rotate_secret(&self, account: &str, id: &str, secret: &str) -> Result<(), CfError> { + self.log(format!("rotate {id}")); + self.tunnel(account, id).await?; + self.secrets + .lock() + .unwrap() + .insert(id.into(), secret.into()); + Ok(()) + } + + async fn drop_connections(&self, account: &str, id: &str) -> Result<(), CfError> { + self.log(format!("drop connections {id}")); + self.tunnel(account, id).await?; + self.connect(id, "inactive", &[]); + Ok(()) + } + + async fn origin_certs(&self, zone_id: &str) -> Result, CfError> { + if self.no_certs.iter().any(|z| z == zone_id) { + return Err(Self::denied()); + } + Ok(vec![]) + } + + async fn issue_origin_cert( + &self, + csr_pem: &str, + hostnames: &[String], + ) -> Result { + self.log(format!("issue {}", hostnames.join(","))); + let zone_denied = self.zones.iter().any(|(id, name, _)| { + self.no_certs.contains(id) + && hostnames + .iter() + .any(|h| h.trim_start_matches("*.").ends_with(name.as_str())) + }); + if zone_denied { + return Err(Self::denied()); + } + assert!(csr_pem.contains("CERTIFICATE REQUEST"), "{csr_pem}"); + let id = format!("{}", 1000 + self.certs.lock().unwrap().len()); + self.certs + .lock() + .unwrap() + .push((id.clone(), hostnames.to_vec(), false)); + Ok(OriginCert { + id, + pem: String::new(), + }) + } + + async fn revoke_origin_cert(&self, id: &str) -> Result<(), CfError> { + self.log(format!("revoke {id}")); + for c in self.certs.lock().unwrap().iter_mut() { + if c.0 == id { + c.2 = true; + return Ok(()); + } + } + Err(CfError::NotFound) + } +} + +// ── Tunnel permissions ───────────────────────────────────────────────────── + +#[tokio::test] +async fn a_test_says_which_zones_can_use_a_tunnel() { + let mut cf = Fake::new(&[ + ("z1", "example.com", Dns::Edit), + ("z2", "other.org", Dns::Edit), + ("z3", "certless.dev", Dns::Edit), + ("z4", "readonly.io", Dns::Read), + ]); + cf.accounts + .insert("z2".into(), ("acct2".into(), "Other Co".into())); + cf.no_tunnels = vec!["acct2".into()]; + cf.no_certs = vec!["z2".into(), "z3".into()]; + let zones = inspect(&cf, MARK).await.unwrap(); + let got: Vec<(&str, &str, bool, Vec)> = zones + .iter() + .map(|z| { + ( + z.name.as_str(), + z.account_id.as_str(), + z.tunnel_ready(), + z.tunnel.missing.clone(), + ) + }) + .collect(); + assert_eq!( + got, + [ + ("certless.dev", "acct1", false, vec![tunnel::CERTS_EDIT.to_owned()]), + ("example.com", "acct1", true, vec![]), + ( + "other.org", + "acct2", + false, + vec![tunnel::TUNNEL_EDIT.to_owned(), tunnel::CERTS_EDIT.to_owned()] + ), + ("readonly.io", "acct1", false, vec![]), + ] + ); + assert_eq!(zones[1].account_name, "Acme"); + // A zone that can't edit DNS can't be tunnel-ready either. + assert!(!zones[3].tunnel.ready); + // DNS only (neither tunnel permission) is no problem. Half of them is. + assert_eq!( + problems(&zones), + [ + "readonly.io: give the token DNS:Edit.", + "certless.dev: give the token SSL and Certificates:Edit." + ] + ); + // The tunnel check is once per account, and leaves nothing behind. + let checks = cf + .calls() + .iter() + .filter(|c| c.starts_with("create tunnel acct1 pyo-check-")) + .count(); + assert_eq!(checks, 1); + assert!(cf.tunnel_list().iter().all(|t| t.deleted)); +} + +#[tokio::test] +async fn a_probe_tunnel_left_behind_is_deleted() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + cf.tunnels.lock().unwrap().push(( + "acct1".into(), + Tunnel { + id: "11111111-2222-4333-8444-555555555555".into(), + name: "pyo-check-a1b2c3".into(), + ..Default::default() + }, + )); + // Someone's own tunnel with another name: never touched. + cf.tunnels.lock().unwrap().push(( + "acct1".into(), + Tunnel { + id: "11111111-2222-4333-8444-666666666666".into(), + name: "home-lab".into(), + ..Default::default() + }, + )); + inspect(&cf, MARK).await.unwrap(); + let ts = cf.tunnel_list(); + assert!(ts.iter().filter(|t| t.name.starts_with("pyo-check-")).all(|t| t.deleted)); + assert!(ts.iter().any(|t| t.name == "home-lab" && !t.deleted)); +} + +#[test] +fn zones_stored_before_the_tunnel_read_as_dns_only() { + let z: Zone = + serde_json::from_value(json!({ "id": "z1", "name": "example.com", "canEdit": true })).unwrap(); + assert!(!z.tunnel_ready()); + assert_eq!(z.account_id, ""); + let v = serde_json::to_value(zone("z1", "example.com")).unwrap(); + assert_eq!(v["accountId"], "acct1"); + assert_eq!(v["tunnel"], json!({ "ready": true })); +} + +#[test] +fn tunnel_ids_are_uuids_before_they_go_into_paths() { + use tunnel::uuid_ok; + assert!(uuid_ok("c1744f8b-faa1-48a4-9e5c-02ac921467fa")); + assert!(!uuid_ok("c1744f8b-faa1-48a4-9e5c-02ac921467f")); + assert!(!uuid_ok("../../zones/x-faa1-48a4-9e5c-02ac921467fa")); + assert!(!uuid_ok("c1744f8bxfaa1-48a4-9e5c-02ac921467fa")); +} + +#[test] +fn reads_cloudflares_tunnels() { + let t = tunnel::tunnel_from(&json!({ + "id": "c1744f8b-faa1-48a4-9e5c-02ac921467fa", "name": "pyo-cl_1-abc123", + "status": "healthy", "deleted_at": null, "account_tag": "699d98642c564d2e855e9661899b7252", + "connections": [{ + "colo_name": "FRA", "uuid": "1bedc50d-42b3-473c-b108-ff3d10c0d925", "id": "1bedc50d-42b3-473c-b108-ff3d10c0d925", + "is_pending_reconnect": false, "origin_ip": "203.0.113.7", "opened_at": "2026-11-22T10:00:00Z", + "client_id": "1bedc50d-42b3-473c-b108-ff3d10c0d925", "client_version": "2026.10.7", + }], + })) + .unwrap(); + assert_eq!(t.status, "healthy"); + assert!(!t.deleted); + assert_eq!(t.connections[0].colo, "FRA"); + let gone = tunnel::tunnel_from(&json!({ + "id": "c1744f8b-faa1-48a4-9e5c-02ac921467fa", "name": "x", "deleted_at": "2026-11-22T10:00:00Z", + })) + .unwrap(); + assert!(gone.deleted); + assert!(tunnel::tunnel_from(&json!({ "id": "../x" })).is_err()); +} diff --git a/crates/pyo-api/src/cloudflare/tunnel.rs b/crates/pyo-api/src/cloudflare/tunnel.rs new file mode 100644 index 00000000..4e2edaf1 --- /dev/null +++ b/crates/pyo-api/src/cloudflare/tunnel.rs @@ -0,0 +1,557 @@ +//! Cloudflare Tunnel: what Pyo asks of Cloudflare for a cluster's tunnel +//! (docs/cloudflare-tunnel.md §6). The tunnel itself, its routes (remotely +//! managed ingress), its token for the cluster's connector, the Origin CA +//! certificate Pyo Gateway shows cloudflared, and the token checks that say +//! which zones can use a tunnel. +//! +//! Everything goes through [`Http`]'s pinned client to `api.cloudflare.com` +//! only, with the team's token. The token never leaves the control plane: +//! the cluster only ever gets the tunnel's own token. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; + +use super::{CfError, Http, Record, id_ok}; +use reqwest::Method; + +/// The permission a tunnel needs in the account. +pub const TUNNEL_EDIT: &str = "Cloudflare Tunnel:Edit"; +/// The permission an Origin CA certificate needs in the zone. +pub const CERTS_EDIT: &str = "SSL and Certificates:Edit"; + +/// What a probe tunnel is named: removed right after the check, and any +/// left behind by a check that stopped halfway is removed by the next. +pub const CHECK_PREFIX: &str = "pyo-check-"; + +/// How long the Origin CA certificate is valid: 15 years, Cloudflare's +/// longest (decision 2). Never renewed by age. +pub const CERT_DAYS: u32 = 5475; + +/// The most names one Origin CA certificate takes. +pub const MAX_CERT_NAMES: usize = 200; + +/// Where cloudflared sends requests: Pyo's own Service in front of the +/// Gateway's HTTPS listener (`system::TUNNEL_ORIGIN_SERVICE`). +pub const ORIGIN: &str = "https://pyo-tunnel-origin.pyo-gateway.svc.cluster.local:443"; + +/// A zone as Cloudflare lists it, with the account it's in. +#[derive(Debug, Clone, PartialEq)] +pub struct CfZone { + pub id: String, + pub name: String, + pub account_id: String, + pub account_name: String, +} + +/// A tunnel at Cloudflare. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Tunnel { + pub id: String, + pub name: String, + /// "inactive", "degraded", "healthy" or "down". + pub status: String, + /// Deleted at Cloudflare (it stays listed for a while). + pub deleted: bool, + pub connections: Vec, +} + +/// One of a tunnel's connections to Cloudflare's edge. +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Connection { + /// The connector it belongs to (one cloudflared runs four). + pub client_id: String, + pub colo: String, + pub client_version: String, + pub opened_at: String, + pub origin_ip: String, +} + +/// A record as it was, kept to be put back (`dns_records.previous`). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Kept { + #[serde(default, skip_serializing)] + pub id: String, + #[serde(rename = "type")] + pub kind: String, + pub name: String, + pub content: String, + #[serde(default)] + pub proxied: bool, + #[serde(default = "auto_ttl")] + pub ttl: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub comment: Option, +} + +fn auto_ttl() -> u32 { + 1 +} + +impl Kept { + pub fn record(&self) -> Record { + Record { + id: self.id.clone(), + kind: self.kind.clone(), + name: self.name.clone(), + content: self.content.clone(), + proxied: self.proxied, + comment: self.comment.clone(), + } + } +} + +/// An Origin CA certificate Cloudflare issued. +#[derive(Debug, Clone, PartialEq)] +pub struct OriginCert { + pub id: String, + pub pem: String, +} + +/// What Pyo asks of Cloudflare for tunnels and their certificates, on top +/// of DNS ([`super::Cloudflare`]). [`Http`] is the real one; the tests use +/// a fake account. +pub(crate) trait TunnelApi { + /// Every zone the token can read, with its account. + async fn zone_accounts(&self) -> Result, CfError>; + /// The records with exactly this name, with what's needed to put them + /// back as they were. + async fn records_kept(&self, zone_id: &str, name: &str) -> Result, CfError>; + /// Create a record as it was. + async fn create_kept(&self, zone_id: &str, r: &Kept) -> Result; + /// The account's tunnels named `name` that aren't deleted. + async fn tunnels_named(&self, account: &str, name: &str) -> Result, CfError>; + /// A remotely managed tunnel (its routes are set through the API). + async fn create_tunnel(&self, account: &str, name: &str) -> Result; + async fn tunnel(&self, account: &str, id: &str) -> Result; + async fn delete_tunnel(&self, account: &str, id: &str) -> Result<(), CfError>; + /// The token a connector runs the tunnel with. + async fn tunnel_token(&self, account: &str, id: &str) -> Result; + /// Replace the tunnel's routes. Cloudflare's version of them comes back. + async fn put_config(&self, account: &str, id: &str, config: &Value) -> Result; + /// Cloudflare's version of the tunnel's routes, and the routes. + async fn config(&self, account: &str, id: &str) -> Result<(i64, Value), CfError>; + /// Give the tunnel a new secret (so a new token). + async fn rotate_secret(&self, account: &str, id: &str, secret: &str) -> Result<(), CfError>; + /// Drop the tunnel's connections (they come back with a current token). + async fn drop_connections(&self, account: &str, id: &str) -> Result<(), CfError>; + /// The zone's Origin CA certificates (proves the token may read them). + async fn origin_certs(&self, zone_id: &str) -> Result, CfError>; + /// Issue an Origin CA certificate for a CSR. + async fn issue_origin_cert( + &self, + csr_pem: &str, + hostnames: &[String], + ) -> Result; + async fn revoke_origin_cert(&self, id: &str) -> Result<(), CfError>; +} + +/// Tunnel ids are UUIDs. +pub fn uuid_ok(id: &str) -> bool { + id.len() == 36 + && id.bytes().enumerate().all(|(i, b)| match i { + 8 | 13 | 18 | 23 => b == b'-', + _ => b.is_ascii_hexdigit(), + }) +} + +/// Origin CA certificate ids: digits (a long serial), nothing else. +fn cert_id_ok(id: &str) -> bool { + !id.is_empty() && id.len() <= 80 && id.bytes().all(|b| b.is_ascii_digit()) +} + +fn tunnel_path(account: &str, id: Option<&str>, rest: &str) -> Result { + if !id_ok(account) || id.is_some_and(|i| !uuid_ok(i)) { + return Err(CfError::NotFound); + } + Ok(match id { + Some(i) => format!("/accounts/{account}/cfd_tunnel/{i}{rest}"), + None => format!("/accounts/{account}/cfd_tunnel{rest}"), + }) +} + +fn unreadable() -> CfError { + CfError::Refused("an answer Pyo can't read".into()) +} + +/// A tunnel as Cloudflare answers with it. Its connections are listed per +/// connection (`connections`, each with its connector's `client_id`). +pub fn tunnel_from(v: &Value) -> Result { + let id = v["id"].as_str().filter(|i| uuid_ok(i)).ok_or_else(unreadable)?; + let s = |v: &Value, k: &str| v[k].as_str().unwrap_or("").to_owned(); + Ok(Tunnel { + id: id.to_owned(), + name: s(v, "name"), + status: s(v, "status"), + deleted: v["deleted_at"].as_str().is_some_and(|d| !d.is_empty()), + connections: v["connections"] + .as_array() + .into_iter() + .flatten() + .map(|c| Connection { + client_id: s(c, "client_id"), + colo: s(c, "colo_name"), + client_version: s(c, "client_version"), + opened_at: s(c, "opened_at"), + origin_ip: s(c, "origin_ip"), + }) + .collect(), + }) +} + +fn kept_from(v: &Value) -> Result { + serde_json::from_value::(v.clone()) + .map(|mut k| { + k.id = v["id"].as_str().unwrap_or("").to_owned(); + k + }) + .map_err(|_| unreadable()) +} + +impl TunnelApi for Http { + async fn zone_accounts(&self) -> Result, CfError> { + let mut out = vec![]; + for page in 1..=20 { + let mut url = Self::url("/zones"); + url.query_pairs_mut() + .append_pair("per_page", "50") + .append_pair("page", &page.to_string()); + let v = self.call(Method::GET, url, None).await?; + for z in v["result"].as_array().into_iter().flatten() { + if let (Some(id), Some(name)) = (z["id"].as_str(), z["name"].as_str()) + && id_ok(id) + { + let account = z["account"]["id"].as_str().filter(|a| id_ok(a)); + out.push(CfZone { + id: id.to_owned(), + name: name.to_owned(), + account_id: account.unwrap_or("").to_owned(), + account_name: z["account"]["name"] + .as_str() + .unwrap_or("") + .chars() + .take(100) + .collect(), + }); + } + } + if page >= v["result_info"]["total_pages"].as_i64().unwrap_or(1) { + break; + } + } + Ok(out) + } + + async fn records_kept(&self, zone_id: &str, name: &str) -> Result, CfError> { + let mut url = Self::url(&Self::record_path(zone_id, None)?); + url.query_pairs_mut() + .append_pair("name", name) + .append_pair("per_page", "100"); + let v = self.call(Method::GET, url, None).await?; + v["result"] + .as_array() + .into_iter() + .flatten() + .map(kept_from) + .collect() + } + + async fn create_kept(&self, zone_id: &str, r: &Kept) -> Result { + let url = Self::url(&Self::record_path(zone_id, None)?); + let mut body = json!({ + "type": r.kind, "name": r.name, "content": r.content, + "ttl": r.ttl, "proxied": r.proxied, + }); + if let Some(c) = &r.comment { + body["comment"] = json!(c); + } + super::record_from(&self.call(Method::POST, url, Some(body)).await?["result"]) + } + + async fn tunnels_named(&self, account: &str, name: &str) -> Result, CfError> { + let mut url = Self::url(&tunnel_path(account, None, "")?); + url.query_pairs_mut() + .append_pair("name", name) + .append_pair("is_deleted", "false") + .append_pair("per_page", "50"); + let v = self.call(Method::GET, url, None).await?; + v["result"] + .as_array() + .into_iter() + .flatten() + .map(tunnel_from) + .collect() + } + + async fn create_tunnel(&self, account: &str, name: &str) -> Result { + let url = Self::url(&tunnel_path(account, None, "")?); + let body = json!({ "name": name, "config_src": "cloudflare" }); + tunnel_from(&self.call(Method::POST, url, Some(body)).await?["result"]) + } + + async fn tunnel(&self, account: &str, id: &str) -> Result { + let url = Self::url(&tunnel_path(account, Some(id), "")?); + tunnel_from(&self.call(Method::GET, url, None).await?["result"]) + } + + async fn delete_tunnel(&self, account: &str, id: &str) -> Result<(), CfError> { + let url = Self::url(&tunnel_path(account, Some(id), "")?); + self.call(Method::DELETE, url, None).await.map(|_| ()) + } + + async fn tunnel_token(&self, account: &str, id: &str) -> Result { + let url = Self::url(&tunnel_path(account, Some(id), "/token")?); + let v = self.call(Method::GET, url, None).await?; + v["result"] + .as_str() + .filter(|t| !t.is_empty() && t.len() <= 4096 && t.bytes().all(|b| b.is_ascii_graphic())) + .map(str::to_owned) + .ok_or_else(unreadable) + } + + async fn put_config(&self, account: &str, id: &str, config: &Value) -> Result { + let url = Self::url(&tunnel_path(account, Some(id), "/configurations")?); + let v = self + .call(Method::PUT, url, Some(json!({ "config": config }))) + .await?; + Ok(v["result"]["version"].as_i64().unwrap_or(0)) + } + + async fn config(&self, account: &str, id: &str) -> Result<(i64, Value), CfError> { + let url = Self::url(&tunnel_path(account, Some(id), "/configurations")?); + let v = self.call(Method::GET, url, None).await?; + Ok(( + v["result"]["version"].as_i64().unwrap_or(0), + v["result"]["config"].clone(), + )) + } + + async fn rotate_secret(&self, account: &str, id: &str, secret: &str) -> Result<(), CfError> { + let url = Self::url(&tunnel_path(account, Some(id), "")?); + self.call(Method::PATCH, url, Some(json!({ "tunnel_secret": secret }))) + .await + .map(|_| ()) + } + + async fn drop_connections(&self, account: &str, id: &str) -> Result<(), CfError> { + let url = Self::url(&tunnel_path(account, Some(id), "/connections")?); + self.call(Method::DELETE, url, None).await.map(|_| ()) + } + + async fn origin_certs(&self, zone_id: &str) -> Result, CfError> { + if !id_ok(zone_id) { + return Err(CfError::NotFound); + } + let mut url = Self::url("/certificates"); + url.query_pairs_mut().append_pair("zone_id", zone_id); + let v = self.call(Method::GET, url, None).await?; + Ok(v["result"] + .as_array() + .into_iter() + .flatten() + .filter_map(|c| c["id"].as_str().map(str::to_owned)) + .collect()) + } + + async fn issue_origin_cert( + &self, + csr_pem: &str, + hostnames: &[String], + ) -> Result { + let url = Self::url("/certificates"); + let body = json!({ + "csr": csr_pem, "hostnames": hostnames, + "request_type": "origin-ecc", "requested_validity": CERT_DAYS, + }); + let v = self.call(Method::POST, url, Some(body)).await?; + let r = &v["result"]; + match (r["id"].as_str(), r["certificate"].as_str()) { + (Some(id), Some(pem)) if cert_id_ok(id) => Ok(OriginCert { + id: id.to_owned(), + pem: pem.to_owned(), + }), + _ => Err(unreadable()), + } + } + + async fn revoke_origin_cert(&self, id: &str) -> Result<(), CfError> { + if !cert_id_ok(id) { + return Err(CfError::NotFound); + } + let url = Self::url(&format!("/certificates/{id}")); + self.call(Method::DELETE, url, None).await.map(|_| ()) + } +} + +// ── Checking a token ─────────────────────────────────────────────────────── + +/// Whether the token may make tunnels in an account: it makes a probe +/// tunnel and deletes it again (a token without Cloudflare Tunnel:Edit is +/// refused the first step). Probes left behind are deleted first. The +/// permission it lacks, or None. +pub(crate) async fn tunnel_missing( + cf: &C, + account: &str, +) -> Result, CfError> { + let left = match cf.tunnels_named(account, CHECK_PREFIX).await { + Ok(t) => t, + Err(CfError::Denied(_)) => return Ok(Some(TUNNEL_EDIT.into())), + Err(e) => return Err(e), + }; + for t in left.iter().filter(|t| t.name.starts_with(CHECK_PREFIX)) { + let _ = cf.delete_tunnel(account, &t.id).await; + } + let mut b = [0u8; 3]; + rand::fill(&mut b); + match cf + .create_tunnel(account, &format!("{CHECK_PREFIX}{}", hex::encode(b))) + .await + { + Ok(t) => { + cf.delete_tunnel(account, &t.id).await?; + Ok(None) + } + Err(CfError::Denied(_)) => Ok(Some(TUNNEL_EDIT.into())), + Err(e) => Err(e), + } +} + +/// Whether the token may read a zone's Origin CA certificates. Edit can't +/// be proven without issuing one, so the first issue says plainly when it's +/// missing. The permission it lacks, or None. +pub(crate) async fn certs_missing( + cf: &C, + zone_id: &str, +) -> Result, CfError> { + match cf.origin_certs(zone_id).await { + Ok(_) => Ok(None), + Err(CfError::Denied(_)) => Ok(Some(CERTS_EDIT.into())), + Err(e) => Err(e), + } +} + +// ── The routes ───────────────────────────────────────────────────────────── + +/// One route rule for a hostname, to Pyo Gateway over HTTPS. The visitor's +/// host goes as SNI, so the Origin CA certificate is checked against it +/// (one shape for exact names and the wildcard). +fn rule(hostname: &str) -> Value { + json!({ + "hostname": hostname, + "service": ORIGIN, + "originRequest": { "matchSNItoHost": true, "connectTimeout": 10, "keepAliveTimeout": 90 }, + }) +} + +/// The tunnel's routes: each hostname, exact names first (longest first, +/// then by name), the default domain's wildcard last, then the catch-all. +/// cloudflared matches top down. +pub fn ingress(hostnames: &[String], default_domain: Option<&str>) -> Value { + let mut exact: Vec = hostnames + .iter() + .map(|h| h.trim().trim_end_matches('.').to_ascii_lowercase()) + .filter(|h| !h.is_empty()) + .collect(); + exact.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b))); + exact.dedup(); + let wildcard = default_domain.map(|d| format!("*.{}", d.to_ascii_lowercase())); + exact.retain(|h| Some(h) != wildcard.as_ref()); + let mut rules: Vec = exact.iter().map(|h| rule(h)).collect(); + if let Some(w) = &wildcard { + rules.push(rule(w)); + } + rules.push(json!({ "service": "http_status:404" })); + json!({ "ingress": rules }) +} + +/// Only the catch-all: what's left while a tunnel is removed. +pub fn empty_ingress() -> Value { + ingress(&[], None) +} + +/// The routes' hash, to PUT them only when they change. serde_json keeps +/// keys sorted, so the same routes always hash the same. +pub fn config_hash(config: &Value) -> String { + hex::encode(Sha256::digest(config.to_string().as_bytes())) +} + +// ── The certificate's names ──────────────────────────────────────────────── + +/// The name that covers a tunnel hostname on the certificate: the zone's +/// apex itself, else a wildcard one level up (`blog.example.com` → +/// `*.example.com`, `a.b.example.com` → `*.b.example.com`). +pub fn cert_name(host: &str, zone: &str) -> String { + let host = host.trim_end_matches('.').to_ascii_lowercase(); + let zone = zone.trim_end_matches('.').to_ascii_lowercase(); + if host == zone { + return host; + } + match host.split_once('.') { + Some((_, parent)) => format!("*.{parent}"), + None => host, + } +} + +/// Every name the tunnel's certificate needs: one per hostname (each with +/// its zone), the default domain's wildcard. Sorted, deduped. Too many for +/// one certificate: Err. +pub fn cert_names( + hosts: &[(String, String)], + default_domain: Option<&str>, +) -> Result, String> { + let mut names: Vec = hosts.iter().map(|(h, z)| cert_name(h, z)).collect(); + if let Some(d) = default_domain { + names.push(format!("*.{}", d.to_ascii_lowercase())); + } + names.sort(); + names.dedup(); + if names.len() > MAX_CERT_NAMES { + return Err("This tunnel has too many names for one certificate.".into()); + } + Ok(names) +} + +/// Whether a certificate with `have` names covers all of `want`. +pub fn covers_all(have: &[String], want: &[String]) -> bool { + want.iter().all(|w| have.contains(w)) +} + +/// A new key and its CSR for the tunnel's certificate: ECDSA P-256. The +/// key stays on the control plane, sealed with the team's certificates +/// (decision 1). (CSR PEM, key PEM). +pub fn key_and_csr(names: &[String]) -> anyhow::Result<(String, String)> { + use rcgen::{CertificateParams, DistinguishedName, DnType, KeyPair, PKCS_ECDSA_P256_SHA256}; + let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; + let mut p = CertificateParams::new(names.to_vec())?; + let mut dn = DistinguishedName::new(); + dn.push( + DnType::CommonName, + names.first().cloned().unwrap_or_default(), + ); + p.distinguished_name = dn; + let csr = p.serialize_request(&key)?; + Ok((csr.pem()?, key.serialize_pem())) +} + +/// A new tunnel secret, as Cloudflare takes it: 32 random bytes, base64. +pub fn new_secret() -> String { + use base64::Engine; + let mut b = [0u8; 32]; + rand::fill(&mut b); + base64::engine::general_purpose::STANDARD.encode(b) +} + +/// The tunnel's name at Cloudflare: the cluster and this installation, so +/// two installations sharing an account never take each other's. +pub fn tunnel_name(cluster_id: &str, install_id: &str, attempt: u32) -> String { + match attempt { + 0 | 1 => format!("pyo-{cluster_id}-{install_id}"), + n => format!("pyo-{cluster_id}-{install_id}-{n}"), + } +} + +/// Where a tunnel's CNAME points. +pub fn cname_target(tunnel_id: &str) -> String { + format!("{tunnel_id}.cfargotunnel.com") +} diff --git a/crates/pyo-api/src/ops.rs b/crates/pyo-api/src/ops.rs index 930493e4..53bbb4eb 100644 --- a/crates/pyo-api/src/ops.rs +++ b/crates/pyo-api/src/ops.rs @@ -2933,9 +2933,9 @@ pub(crate) enum Op { }, /// Revoke a Pyo registry token. Team owners and admins. RevokeRegistryToken { id: String }, - /// Connect the team's Cloudflare account, or replace its token. The token needs Zone:Read and DNS:Edit on the zones Pyo may use. Pyo lists its zones, checks it can edit DNS in each (it makes and deletes a TXT record `_pyo-check.`), then keeps it encrypted. It's never shown again. Team owners and admins. + /// Connect the team's Cloudflare account, or replace its token. The token needs Zone:Read and DNS:Edit on the zones Pyo may use, and for Cloudflare Tunnel also Cloudflare Tunnel:Edit and SSL and Certificates:Edit. Pyo lists its zones and their accounts, checks it can edit DNS in each (it makes and deletes a TXT record `_pyo-check.`), checks the tunnel permissions (it makes and deletes a tunnel `pyo-check-` once per account, and reads each zone's Origin CA certificates), then keeps it encrypted. It's never shown again. Each zone's `tunnel` says whether it can use Cloudflare Tunnel. Team owners and admins. ConnectCloudflare { team_id: String, token: String }, - /// Check the saved Cloudflare token again: the zones it covers now, and what it's missing (`problems`). Team owners and admins. + /// Check the saved Cloudflare token again: the zones it covers now, whether each can use Cloudflare Tunnel, and what it's missing (`problems`). Team owners and admins. TestCloudflare { team_id: String }, /// Forget the team's Cloudflare token. DNS records Pyo made stay in Cloudflare. Team owners and admins. RemoveCloudflare { team_id: String }, From adc8e62c248c7900e1180d06fcb2dfdd7349050f Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:09:10 +0700 Subject: [PATCH 010/139] feat(cli): show each zone's tunnel state in pyo cloudflare --- crates/pyo-cli/src/cloudflare.rs | 48 ++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/crates/pyo-cli/src/cloudflare.rs b/crates/pyo-cli/src/cloudflare.rs index 57cd139b..9003c75e 100644 --- a/crates/pyo-cli/src/cloudflare.rs +++ b/crates/pyo-cli/src/cloudflare.rs @@ -36,7 +36,7 @@ fn read_token(file: Option<&str>, env: Option) -> Result { let t = t.trim().to_owned(); if t.is_empty() { bail!( - "Give the token in a file (--token-file, - for stdin) or in CLOUDFLARE_API_TOKEN. It needs Zone:Read and DNS:Edit." + "Give the token in a file (--token-file, - for stdin) or in CLOUDFLARE_API_TOKEN. It needs Zone:Read and DNS:Edit, and for Cloudflare Tunnel also Cloudflare Tunnel:Edit and SSL and Certificates:Edit." ); } Ok(t) @@ -54,18 +54,41 @@ fn print_zones(zones: &Value) { .chain([4]) .max() .unwrap_or(4); - println!("{}", ui::dim(&format!("{: String { + let missing: Vec<&str> = t["missing"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + if t["ready"] == json!(true) { + ui::green("ready") + } else if missing.len() == 1 { + ui::yellow(&format!("needs {}", missing[0])) + } else { + ui::dim("DNS only") } } @@ -253,6 +276,21 @@ mod tests { assert_eq!(zone_for(&s, "t2", "a.example.com"), None); } + #[test] + fn the_tunnel_column_says_what_a_zone_can_do() { + let plain = |t: Value| { + tunnel_column(&t) + .chars() + .filter(|c| !c.is_control()) + .collect::() + }; + assert!(plain(json!({ "ready": true })).contains("ready")); + assert!(plain(json!({ "ready": false, "missing": ["SSL and Certificates:Edit"] })).contains("needs SSL and Certificates:Edit")); + assert!(plain(json!({ "ready": false, "missing": ["a", "b"] })).contains("DNS only")); + // Stored before the tunnel: DNS only. + assert!(plain(Value::Null).contains("DNS only")); + } + #[test] fn tokens_come_from_a_file_or_the_environment() { assert_eq!(read_token(None, Some(" abc \n".into())).unwrap(), "abc"); From 12cf81f9a0536cfed0eefcabb03f909d111531c6 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:09:10 +0700 Subject: [PATCH 011/139] feat(dash): show which cloudflare zones can use a tunnel --- dash/src/components/pyo/Cloudflare.tsx | 19 ++++++++++++++++--- dash/src/lib/pyo/types.ts | 5 +++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/dash/src/components/pyo/Cloudflare.tsx b/dash/src/components/pyo/Cloudflare.tsx index 73aeb6dc..8fb2e6d2 100644 --- a/dash/src/components/pyo/Cloudflare.tsx +++ b/dash/src/components/pyo/Cloudflare.tsx @@ -23,7 +23,7 @@ import { usePyo, } from "~/lib/pyo/store"; import { toast } from "~/lib/pyo/toast"; -import type { Application, Domain } from "~/lib/pyo/types"; +import type { Application, CloudflareZone, Domain } from "~/lib/pyo/types"; // The team's Cloudflare account: Pyo creates the DNS records of domains in // its zones. Only owners and admins see or change the token. @@ -75,8 +75,9 @@ export function CloudflareDialog({ onClose }: { onClose: () => void }) {
{editable.map((z) => ( - + {z.name} + {zoneNote(z)} ))} {lacking.map((z) => ( @@ -141,7 +142,7 @@ export function CloudflareDialog({ onClose }: { onClose: () => void }) {
{(p) => ( @@ -232,6 +233,18 @@ export function CloudflareDialog({ onClose }: { onClose: () => void }) { }); } +/** A zone's tunnel state on its badge: ready, DNS only, or the one permission it lacks. */ +function zoneTone(z: CloudflareZone): "success" | "warning" | undefined { + if (z.tunnel?.ready) return "success"; + return z.tunnel?.missing?.length === 1 ? "warning" : undefined; +} + +function zoneNote(z: CloudflareZone): string { + if (z.tunnel?.ready) return ""; + const missing = z.tunnel?.missing ?? []; + return missing.length === 1 ? ` · needs ${missing[0]}` : " · DNS only"; +} + /** What to do about a new domain's DNS record in Cloudflare. */ export type CloudflareChoice = { create: boolean; proxied: boolean }; diff --git a/dash/src/lib/pyo/types.ts b/dash/src/lib/pyo/types.ts index 5ad8668d..32bac56a 100644 --- a/dash/src/lib/pyo/types.ts +++ b/dash/src/lib/pyo/types.ts @@ -943,6 +943,11 @@ export type CloudflareZone = { canEdit: boolean; /** The permission the token lacks there. */ missing?: string; + /** The Cloudflare account it's in. */ + accountId?: string; + accountName?: string; + /** Whether it can use Cloudflare Tunnel, and the tunnel permissions the token lacks. */ + tunnel?: { ready: boolean; missing?: string[] }; }; /** A team's Cloudflare account: its zones, never the token. */ From e56d6f3ba5364a977c9443cb894bc58a4153609c Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:09:19 +0700 Subject: [PATCH 012/139] docs: update the tunnel build status after phase 1 --- docs/cloudflare-tunnel.md | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/docs/cloudflare-tunnel.md b/docs/cloudflare-tunnel.md index 89dab759..30bcc2e7 100644 --- a/docs/cloudflare-tunnel.md +++ b/docs/cloudflare-tunnel.md @@ -1548,12 +1548,31 @@ Not merged into `dev` until the feature is complete and tested. | Phase | State | |---|---| -| Decisions applied to this spec | Done | -| 1. Token and zones | Next | -| 2. Agent and Gateway | Not started | +| Decisions applied to this spec | Done (b145440) | +| 1. Token and zones | Written, not compiled (e3d91dd api, adc8e62 cli, 12cf81f dash, tsc passes) | +| 2. Agent and Gateway | Next | | 3. Control plane | Not started | | 4. Traffic choice, switching, default domain | Not started | | 5. Ports, connect.sh, alerts | Not started | | 6. Docs, e2e, real-zone test, Pyo Ops | Not started (real zone and Pyo Ops need the user) | -Known gaps: none yet. +Phase 1 notes: + +- `cloudflare/tunnel.rs` holds the tunnel API client (`TunnelApi`, a + trait of its own so the edgecert fakes that implement `Cloudflare` stay + as they are), the token checks, `ingress()`, `config_hash()`, + `cert_names()`, `key_and_csr()`. Phase 3 adds the loop next to it. +- The fake account in `cloudflare/tests.rs` implements both traits + (tunnels, routes, secrets, certificates) and is `pub(super)` so the + tunnel loop's tests can use it. +- `removeCloudflare` refusing while a tunnel exists moves to Phase 3 (it + needs the `cluster_tunnels` table). + +Known gaps: + +- Nothing on this branch has been compiled or tested yet: `cargo check` + was blocked by the permission classifier on 2026-11-22. Run + `cargo check -p pyo-api -p pyo-cli --tests` and + `cargo test -p pyo-api cloudflare::` first when picking this up. +- `dash/node_modules` in the worktree is a symlink to the main + checkout's, for `tsc` only (ignored by git). From 5284a7003b7e2910e4fc7708a5a34204081ed40c Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:21:06 +0700 Subject: [PATCH 013/139] docs: gate tunnel domains once their switch completes The user asked for both paths only while a domain switches. A domain's tunnel is now switching or on: while switching, direct visitors and the tunnel both work and the plain http route stays. Once the record points at the tunnel, direct connections get 403 and the http route goes. Switch back passes through switching again. --- docs/cloudflare-tunnel.md | 83 ++++++++++++++++++++++----------------- 1 file changed, 48 insertions(+), 35 deletions(-) diff --git a/docs/cloudflare-tunnel.md b/docs/cloudflare-tunnel.md index 30bcc2e7..316d9323 100644 --- a/docs/cloudflare-tunnel.md +++ b/docs/cloudflare-tunnel.md @@ -79,18 +79,21 @@ Decisions made while building (not in the first draft): "confirm" and waits for **Replace and switch**. So records made by hand or by Terraform (Pyo Ops) are never replaced without a yes. Pyo's own direct record isn't kept in `previous`: Switch back makes a new one. -- **No 403 gate on tunnel names.** The first draft put the firewall's - "behind" gate (`source.port != 0`) on tunnel routes. It's left out: - Envoy reads the visitor from X-Forwarded-For only on connections from - the connectors, so any other connection is its own visitor and can't - pick an address. Without the gate a domain answers both ways while it - switches (the Gateway has the tunnel listener before the record moves, - and keeps it until the record is back), so there's no gap on a cluster - with public ports. A new connector pod whose address isn't trusted yet - is seen as its own address for those few seconds. -- **Tunnel domains keep their :80 route.** Nothing reaches it through the - tunnel (cloudflared speaks HTTPS), but a domain mid-switch still - answers plain HTTP directly. Less special casing in the route builder. +- **Both paths only while a domain switches** (user, 2026-11-22). A + domain's `tunnel` is `"switching"` or `"on"`: + - `"switching"`: the Gateway has the tunnel listener and route, the + tunnel route has no 403 gate, and the domain keeps its plain-HTTP + :80 route. Direct visitors and the tunnel both work, so there's no + gap on a cluster with public ports while the record moves. + - `"on"` (the record points at the tunnel, switch complete): the + firewall's "behind" gate (`source.port != 0`) goes ahead of the + tunnel route's rules, so a direct, non-tunnel connection with that + hostname gets 403, and the :80 route is removed. + - Switch back goes through `"switching"` again before the record + moves back, so direct visitors are let in before DNS sends them. + - A new connector pod whose address isn't trusted yet is refused by + the gate (403) for those few seconds, never let through with the + wrong visitor. - **A behind-Cloudflare service with tunnel domains**: its CDN client policy covers only its direct HTTPS listeners. The tunnel policy covers the tunnel ones (Envoy Gateway allows one section policy per listener). @@ -401,9 +404,10 @@ ALTER TABLE pyo.dns_records ADD CONSTRAINT dns_records_status_check Plus row security for `cluster_tunnels` on `team_id`, like `0032_row_security_rest.sql`. -Domain spec (`services.spec.domains[]`, JSON) gains `"tunnel": true` for a -domain served through the tunnel. It's the agent's switch (routes.rs) and -changes routes, so it bumps `routes_revision` like any domain change. +Domain spec (`services.spec.domains[]`, JSON) gains `"tunnel"`: +`"switching"` (both paths, see Decisions) or `"on"` (only through the +tunnel). Absent: direct. It's the agent's switch (routes.rs) and changes +routes, so it bumps `routes_revision` like any domain change. `dns_records.via` mirrors it for the record's side. The domain's `tlsMode` becomes `"custom"` with `certificateId` = the tunnel's certificate while via Tunnel, and goes back to what it was (`"auto"` by default) on Switch back. @@ -430,7 +434,7 @@ Snapshot (`crates/pyo-api/src/snapshot.rs:140-170`) per cluster: ``` Per domain, `dnsRecord` (`cloudflare::attach`, `cloudflare.rs:591-621`) -gains `via` and `previous`, and the domain itself carries `tunnel: true`. +gains `via` and `previous`, and the domain itself carries `tunnel`. `dash/src/lib/pyo/types.ts` (`Cluster` at `:391`, `Domain.dnsRecord` at `:907`) follows. @@ -597,22 +601,27 @@ tasks next to `deploy::dns_watcher` (`deploy.rs:2531`). Per cluster with a 2. **Tunnel.** No `tunnel_id`: create it, store the id. `GET` returns 404 or `deleted_at`: create a new one (same name plus `-2`), mark every Pyo-made tunnel record to repoint, send the new token. -3. **Wanted routes** = every domain with `tunnel: true` on a non-deleting +3. **Wanted routes** = every domain with `tunnel` set on a non-deleting service of the cluster (by `services.cluster_id`), plus `*.` when set. PUT when the hash differs. 4. **Certificate.** Needed names (§9). Missing a name, or `rotate` set: issue a new one, store it, point the domains at it (§9). No renewal by age (15 years, decision 2). 5. **Records**, only after step 3 succeeded in this or an earlier pass: - - Rows `status = 'switching'`: `cloudflare::ensure`-like with + - Rows `status = 'switching'`, once the service's routes with the + domain's `tunnel: "switching"` reached the agent (its applied routes + revision is at least the switch's): `cloudflare::ensure`-like with `kind = CNAME`, `content = .cfargotunnel.com`, `proxied = true`, comment `marker(install_id)`. Replaced records go to - `previous` (only when the op said `replace`). Then `status = 'created'` - and the domain's `status = 'active'`. - - Rows `status = 'reverting'`: delete Pyo's CNAME (`delete_ours`, - `cloudflare.rs:1124`), create each `previous` record as it was (or an A - record to the public IP, per the op), then drop the route on the next - pass (records first, route after: no gap). + `previous` (only when the op said `replace`). Then `status = 'created'`, + the domain's `tunnel = "on"` (gate on, :80 route gone) and its + `status = 'active'`. + - Rows `status = 'reverting'`: the domain goes back to + `tunnel: "switching"` first. Once that reached the agent: delete + Pyo's CNAME (`delete_ours`, `cloudflare.rs:1124`), create each + `previous` record as it was (or an A record to the public IP, per the + op), then drop `tunnel` from the domain and the route on the next pass + (records first, route after: no gap). - The default domain's wildcard: `edgecert::ensure_wildcard` (`sandbox/edgecert.rs:775`) with a CNAME. 6. **Agent token.** The agent's last report has no tunnel or another @@ -641,7 +650,7 @@ token. ### 6.4 Domain DNS checks `deploy::check_pending_dns` (`deploy.rs:2547`) skips domains with -`tunnel: true` (their address is Cloudflare's, not the cluster's), like it +`tunnel` set (their address is Cloudflare's, not the cluster's), like it skips `.ts.net`. The tunnel loop sets their status: `pending_dns` while switching, `active` once the CNAME is in place and the route is live. @@ -754,8 +763,8 @@ The agent watches pods with `app.kubernetes.io/name=pyo-tunnel` (all their `/128`). A change rewrites the client policies of services with tunnel domains (§8.3), the same way the websites' settings rewrite CDN policies today (`gateway.rs:1914`). A new pod's first requests can arrive before its -address is trusted. For those few seconds they're seen as the pod's own -address (see Decisions). The readiness probe keeps Cloudflare from +address is trusted. For those few seconds the gate refuses them (403) on +switched domains (see Decisions). The readiness probe keeps Cloudflare from sending it traffic until cloudflared is connected, which usually takes longer than the policy update, and the agent watches pods as soon as they have an address, ready or not. @@ -843,9 +852,9 @@ CEL pins near `:649-660`) with exactly this spec. ### 8.3 Tunnel domains on the service's Gateway `DomainSpec` (`lib.rs:2250-2264`) gains -`#[serde(default, skip_serializing_if = "is_false")] pub tunnel: bool`, -set by `routes::domain_specs` (`routes.rs:19-43`) from the domain's -`tunnel`. For a domain with `tunnel`: +`#[serde(default, skip_serializing_if = "String::is_empty")] pub tunnel: String` +(`""`, `"switching"` or `"on"`), set by `routes::domain_specs` +(`routes.rs:19-43`) from the domain's `tunnel`. For a domain with `tunnel`: - **Listener**: as today, one HTTPS listener `h-` on 443 per hostname (`gateway.rs:320-335`), `tls = "custom"`, the tunnel's @@ -853,8 +862,8 @@ set by `routes::domain_specs` (`routes.rs:19-43`) from the domain's - **Routes**: its own route per port, `{base}-tunnel-{port}`, parent the service's Gateway, so the redirect below applies to tunnel names only. A service can mix tunnel and direct domains. -- **:80 routes stay** as for any domain (see Decisions). cloudflared - always speaks HTTPS to the Gateway. +- **:80 routes** stay while `"switching"` and go once `"on"` (see + Decisions). cloudflared always speaks HTTPS to the Gateway. - **HTTPS redirect**: with `redirect_https`, the tunnel route's first rule matches header `cf-visitor` exactly `{"scheme":"http"}` and redirects to https (301). Cloudflare sets that header on every proxied request and @@ -866,9 +875,13 @@ set by `routes::domain_specs` (`routes.rs:19-43`) from the domain's the visitor from X-Forwarded-For (the address Cloudflare appended, the same one it puts in CF-Connecting-IP) only on connections from cloudflared's pods. Everyone else is their own address. -- **No gate** (see Decisions): tunnel routes get the service's own - firewall rules (`web_authorization` without `behind`), never the CDN - gate. A direct connection with a tunnel hostname is its own visitor. +- **Gate** (see Decisions): with `"on"`, the firewall's "behind" gate + (`firewall::behind_gate_rule`, `BEHIND_GATE_CEL = "source.port != 0"`) + goes ahead of the service's own rules on the tunnel route. A direct + connection with a tunnel hostname (another pod, or a visitor reaching + 443 on a public-ports cluster) gets 403. With `"switching"`, no gate. + Tunnel routes with both kinds of domains are split: `{base}-tunnel-{port}` + for `"on"` names, `{base}-switching-{port}` for the others. - **Firewall, rate limits, WAF, countries**: unchanged. They read the visitor Envoy worked out, so they see the real one. GeoIP country follows the visitor address. The access log's `remote` field From 0ef4273cf6c2e2da6f415b773b4c2fc9af02cc39 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:23:47 +0700 Subject: [PATCH 014/139] feat(cli): drop pyo sandbox servers create Buying a sandbox server at Hetzner moves to the dashboard for now. Removing one still asks about its price first. --- crates/pyo-cli/src/sandbox.rs | 72 +------ crates/pyo-cli/src/server.rs | 389 ---------------------------------- 2 files changed, 1 insertion(+), 460 deletions(-) delete mode 100644 crates/pyo-cli/src/server.rs diff --git a/crates/pyo-cli/src/sandbox.rs b/crates/pyo-cli/src/sandbox.rs index 94a99866..384b4861 100644 --- a/crates/pyo-cli/src/sandbox.rs +++ b/crates/pyo-cli/src/sandbox.rs @@ -206,30 +206,6 @@ pub enum ServersCommand { #[arg(long, value_name = "DOMAIN")] edge_domain: Option, }, - /// Buy a sandbox server at Hetzner. Pyo sets it up over your tailnet, - /// and it runs sandboxes on gVisor. Owners and admins. - Create { - /// Its name, lowercase letters, digits and dashes. - name: String, - /// A location, e.g. fsn1 (see pyo server types). - #[arg(long)] - location: String, - /// A server type, e.g. cx22 (see pyo server types). - #[arg(long = "type")] - server_type: String, - /// Serve sandbox ports at -.DOMAIN. Point *.DOMAIN at the server. - #[arg(long, value_name = "DOMAIN")] - edge_domain: Option, - /// Your SSH public key file, to sign in over your tailnet. - #[arg(long, value_name = "FILE")] - ssh_key: Option, - /// Don't ask to confirm the price. - #[arg(long, short = 'y')] - yes: bool, - /// Start it and exit, without following it. - #[arg(long)] - detach: bool, - }, /// The sandbox servers the team can use. Ls { /// Print it as JSON. @@ -697,52 +673,6 @@ async fn servers(api: &Api, team: Option<&str>, cmd: ServersCommand) -> Result<( println!("{}", r["command"].as_str().unwrap_or("")); Ok(()) } - ServersCommand::Create { - name, - location, - server_type, - edge_domain, - ssh_key, - yes, - detach, - } => { - let ssh_key = match ssh_key { - Some(p) => Some( - std::fs::read_to_string(&p) - .with_context(|| format!("Can't read {}", p.display()))? - .trim() - .to_owned(), - ), - None => None, - }; - let mut body = json!({ - "teamId": team, "name": name, "location": location, - "serverType": server_type, "sshKey": ssh_key, - }); - if let Some(d) = edge_domain { - body["edgeDomain"] = json!(d); - } - let path = "/api/v1/sandbox-servers/cloud"; - let r = match api.post(path, &body).await { - Err(e) if e.downcast_ref::().is_some() => { - println!("{e}"); - if !yes && !crate::server::yes_to("Go ahead? [y/N] ")? { - bail!("Nothing was changed."); - } - body["confirm"] = json!(true); - api.post(path, &body).await? - } - r => r?, - }; - ui::ok(&format!( - "Creating {name} at Hetzner. It runs sandboxes on gVisor." - )); - if detach { - return Ok(()); - } - let id = r["cloudServer"]["id"].as_str().unwrap_or("").to_owned(); - crate::server::follow(api, &id).await - } ServersCommand::Ls { json } => { let r = api .get(&format!("/api/v1/sandbox-servers?team={team}")) @@ -808,7 +738,7 @@ async fn servers(api: &Api, team: Option<&str>, cmd: ServersCommand) -> Result<( match api.delete(&path).await { Err(e) if e.downcast_ref::().is_some() => { println!("{e}"); - if !yes && !crate::server::yes_to("Go ahead? [y/N] ")? { + if !yes && !matches!(ui::ask("Go ahead? [y/N] ")?.trim(), "y" | "Y" | "yes") { bail!("Nothing was changed."); } api.delete(&format!("{path}?confirm=true")).await?; diff --git a/crates/pyo-cli/src/server.rs b/crates/pyo-cli/src/server.rs deleted file mode 100644 index a8772c53..00000000 --- a/crates/pyo-cli/src/server.rs +++ /dev/null @@ -1,389 +0,0 @@ -//! `pyo hetzner` and `pyo server`: connect a team to Hetzner Cloud, then -//! make servers there that join a cluster over the tailnet, follow them to -//! ready and delete them. Every create and delete shows its monthly price -//! and asks first (or -y). - -use std::io::{IsTerminal, Read, Write}; -use std::time::Duration; - -use anyhow::{Context, Result, bail}; -use serde_json::{Value, json}; - -use crate::{ - api::{Api, NeedsConfirm, State, new_id}, - ui, -}; - -/// A team by slug or id, else the first. -fn team<'a>(state: &'a State, team: Option<&str>) -> Result<&'a Value> { - let teams = state.teams(); - match team { - Some(t) => teams - .iter() - .find(|x| x["slug"] == json!(t) || x["id"] == json!(t)) - .with_context(|| format!("No team {t} among yours")), - None => teams.first().context("You aren't in any team"), - } -} - -fn id_of(v: &Value) -> String { - v["id"].as_str().unwrap_or("").to_owned() -} - -fn list<'a>(state: &'a State, key: &str) -> &'a [Value] { - state.0[key].as_array().map(Vec::as_slice).unwrap_or(&[]) -} - -/// The token: PYO_HETZNER_TOKEN, piped in, or typed without echo. -fn read_token(given: Option) -> Result { - if let Some(t) = given.filter(|t| !t.trim().is_empty()) { - return Ok(t.trim().to_owned()); - } - let mut s = String::new(); - if !std::io::stdin().is_terminal() { - std::io::stdin().read_to_string(&mut s)?; - return Ok(s.trim().to_owned()); - } - print!("Hetzner API token (Read & Write): "); - std::io::stdout().flush()?; - crossterm::terminal::enable_raw_mode()?; - let mut byte = [0u8; 1]; - let read = loop { - match std::io::stdin().read(&mut byte) { - Ok(1) if byte[0] == b'\r' || byte[0] == b'\n' => break Ok(()), - Ok(1) if byte[0] == 3 => break Err(anyhow::anyhow!("Cancelled.")), - Ok(1) if byte[0] == 127 || byte[0] == 8 => { - s.pop(); - } - Ok(1) => s.push(byte[0] as char), - Ok(_) => break Ok(()), - Err(e) => break Err(e.into()), - } - }; - crossterm::terminal::disable_raw_mode()?; - println!(); - read?; - Ok(s.trim().to_owned()) -} - -pub async fn connect(api: &Api, team_ref: Option<&str>, token: Option) -> Result<()> { - let state = api.state().await?; - let t = team(&state, team_ref)?; - let token = read_token(token)?; - let r = api - .op("saveHetzner", json!({ "teamId": id_of(t), "token": token })) - .await?; - let n = r["locations"].as_array().map_or(0, Vec::len); - ui::ok(&format!( - "Connected Hetzner to {}. The token sees {n} locations.", - t["name"].as_str().unwrap_or("") - )); - Ok(()) -} - -pub async fn test(api: &Api, team_ref: Option<&str>) -> Result<()> { - let state = api.state().await?; - let t = team(&state, team_ref)?; - let r = api.op("testHetzner", json!({ "teamId": id_of(t) })).await?; - for l in r["locations"].as_array().into_iter().flatten() { - println!( - "{} {}", - ui::bold(l["name"].as_str().unwrap_or("")), - ui::dim(&format!( - "{}, {}", - l["city"].as_str().unwrap_or(""), - l["country"].as_str().unwrap_or("") - )) - ); - } - ui::ok("Hetzner answers."); - Ok(()) -} - -pub async fn disconnect(api: &Api, team_ref: Option<&str>, yes: bool) -> Result<()> { - let state = api.state().await?; - let t = team(&state, team_ref)?; - if !yes && !yes_to("Forget the Hetzner token? Servers Pyo made there keep running. [y/N] ")? { - bail!("Kept."); - } - api.op("removeHetzner", json!({ "teamId": id_of(t) })) - .await?; - ui::ok("Hetzner disconnected."); - Ok(()) -} - -pub(crate) fn yes_to(q: &str) -> Result { - Ok(matches!( - ui::ask(q)?.trim().to_lowercase().as_str(), - "y" | "yes" - )) -} - -fn money(currency: &str, n: f64) -> String { - match currency { - "EUR" => format!("€{n:.2}"), - "USD" => format!("${n:.2}"), - c => format!("{n:.2} {c}"), - } -} - -pub async fn types(api: &Api, team_ref: Option<&str>, location: Option<&str>) -> Result<()> { - let state = api.state().await?; - let t = team(&state, team_ref)?; - let o = api - .get(&format!("/api/v1/cloud/options?team={}", id_of(t))) - .await?; - let currency = o["currency"].as_str().unwrap_or("EUR"); - let locations: Vec<&Value> = o["locations"] - .as_array() - .into_iter() - .flatten() - .filter(|l| location.is_none_or(|w| l["name"] == json!(w))) - .collect(); - if locations.is_empty() { - bail!("Hetzner has no location {}.", location.unwrap_or("")); - } - for l in locations { - let loc = l["name"].as_str().unwrap_or(""); - println!( - "{} {}", - ui::bold(loc), - ui::dim(&format!( - "{}, {}", - l["city"].as_str().unwrap_or(""), - l["country"].as_str().unwrap_or("") - )) - ); - for st in o["serverTypes"].as_array().into_iter().flatten() { - let Some(p) = st["prices"][loc].as_f64() else { - continue; - }; - let available = st["available"] - .as_array() - .is_some_and(|a| a.contains(&json!(loc))); - let note = if st["supported"] != true { - " (Arm, not for Pyo)" - } else if !available { - " (unavailable)" - } else { - "" - }; - let line = format!( - " {:<8} {:>2} vCPU {:>4} GB {:>5} GB disk {:<4} {:>8}/mo{note}", - st["name"].as_str().unwrap_or(""), - st["cores"], - st["memoryGb"], - st["diskGb"], - st["architecture"].as_str().unwrap_or(""), - money(currency, p), - ); - println!( - "{}", - if note.is_empty() { - line - } else { - ui::dim(&line) - } - ); - } - } - println!("{}", ui::dim("Monthly, before VAT, with the IPv4 address.")); - Ok(()) -} - -pub struct New<'a> { - pub team: Option<&'a str>, - pub cluster: Option<&'a str>, - pub new_cluster: Option<&'a str>, - pub name: Option<&'a str>, - pub location: &'a str, - pub server_type: &'a str, - pub builder: bool, - pub ssh_key: Option<&'a std::path::Path>, - pub tags: Vec, - pub yes: bool, - pub detach: bool, -} - -/// Sends an operation, showing its price and asking first. -async fn priced(api: &Api, op: &str, args: Value, yes: bool) -> Result { - match api.op(op, args.clone()).await { - Err(e) if e.downcast_ref::().is_some() => { - println!("{e}"); - if !yes && !yes_to("Go ahead? [y/N] ")? { - bail!("Nothing was changed."); - } - let mut args = args; - args["confirm"] = json!(true); - api.op(op, args).await - } - r => r, - } -} - -pub async fn create(api: &Api, n: New<'_>) -> Result<()> { - let state = api.state().await?; - let ssh_key = match n.ssh_key { - Some(p) => Some( - std::fs::read_to_string(p) - .with_context(|| format!("Can't read {}", p.display()))? - .trim() - .to_owned(), - ), - None => None, - }; - let id = new_id("cs"); - let (op, args) = if let Some(cluster_name) = n.new_cluster { - let t = team(&state, n.team)?; - ( - "createCloudCluster", - json!({ "id": new_id("cl"), "teamId": id_of(t), "name": cluster_name, "serverId": id, - "location": n.location, "serverType": n.server_type, "sshKey": ssh_key, "tags": n.tags }), - ) - } else { - let (_, cluster_id) = crate::compose::team_and_cluster(api, n.team, n.cluster).await?; - let taken: Vec<&str> = list(&state, "servers") - .iter() - .filter(|s| s["clusterId"] == json!(cluster_id)) - .filter_map(|s| s["name"].as_str()) - .chain( - list(&state, "cloudServers") - .iter() - .filter(|s| s["clusterId"] == json!(cluster_id)) - .filter_map(|s| s["name"].as_str()), - ) - .collect(); - let cluster_name = state - .cluster(&cluster_id) - .and_then(|c| c["name"].as_str()) - .unwrap_or("server") - .to_owned(); - let name = match n.name { - Some(x) => x.to_owned(), - None => (1..) - .map(|i| format!("{cluster_name}-{i}")) - .find(|x| !taken.contains(&x.as_str())) - .unwrap_or_default(), - }; - ( - "createCloudServer", - json!({ "id": id, "clusterId": cluster_id, "name": name, "location": n.location, - "serverType": n.server_type, "builder": n.builder, "sshKey": ssh_key, "tags": n.tags }), - ) - }; - let r = priced(api, op, args, n.yes).await?; - let name = r["name"].as_str().unwrap_or("").to_owned(); - ui::ok(&format!("Creating {name} at Hetzner.")); - if n.detach { - return Ok(()); - } - follow(api, &id).await -} - -/// Follows a new server to ready, saying each step. -pub(crate) async fn follow(api: &Api, id: &str) -> Result<()> { - let mut last = String::new(); - let mut sign_shown = false; - loop { - let state = api.state().await?; - let Some(s) = list(&state, "cloudServers") - .iter() - .find(|s| s["id"] == json!(id)) - else { - bail!("The server is gone."); - }; - let st = s["state"].as_str().unwrap_or("").to_owned(); - if st != last { - let label = match st.as_str() { - "creating" => "Creating", - "booting" => "Booting", - "joining" => "Joining", - "ready" => "Ready", - "failed" => "Failed", - other => other, - }; - println!("{} {label}", ui::dim("·")); - last = st.clone(); - } - if let Some(cmd) = s["signCommand"].as_str() - && !sign_shown - { - println!("Your tailnet has Tailnet Lock on. On a signing device, run:\n {cmd}"); - sign_shown = true; - } - match st.as_str() { - "ready" => { - ui::ok(&format!("{} is ready.", s["name"].as_str().unwrap_or(""))); - return Ok(()); - } - "failed" => bail!( - "{} Delete it with: pyo server delete {}", - s["error"].as_str().unwrap_or("It didn't join."), - s["name"].as_str().unwrap_or("") - ), - _ => tokio::time::sleep(Duration::from_secs(5)).await, - } - } -} - -pub async fn list_servers(api: &Api) -> Result<()> { - let state = api.state().await?; - let all = list(&state, "cloudServers"); - if all.is_empty() { - println!("No servers made at Hetzner."); - return Ok(()); - } - for s in all { - let cluster = s["clusterId"] - .as_str() - .and_then(|c| state.cluster(c)) - .and_then(|c| c["name"].as_str()) - .unwrap_or("(removed)"); - println!( - "{} {} {} in {} {}/mo {}", - ui::bold(s["name"].as_str().unwrap_or("")), - cluster, - s["serverType"].as_str().unwrap_or(""), - s["location"].as_str().unwrap_or(""), - money( - s["currency"].as_str().unwrap_or("EUR"), - s["monthly"].as_f64().unwrap_or(0.0) - ), - s["state"].as_str().unwrap_or("") - ); - if let Some(e) = s["error"].as_str() { - println!(" {} {e}", ui::red("error:")); - } - if let Some(c) = s["signCommand"].as_str() { - println!(" {} {c}", ui::yellow("sign:")); - } - } - Ok(()) -} - -pub async fn delete(api: &Api, name: &str, cluster: Option<&str>, yes: bool) -> Result<()> { - let state = api.state().await?; - let hits: Vec<&Value> = list(&state, "cloudServers") - .iter() - .filter(|s| s["id"] == json!(name) || s["name"] == json!(name)) - .filter(|s| { - cluster.is_none_or(|c| { - s["clusterId"] == json!(c) - || s["clusterId"] - .as_str() - .and_then(|id| state.cluster(id)) - .is_some_and(|x| x["name"] == json!(c)) - }) - }) - .collect(); - let s = match hits.len() { - 0 => bail!("No server {name} made at Hetzner. See them: pyo server list"), - 1 => hits[0], - _ => bail!("More than one server is called {name}. Pass --cluster."), - }; - priced(api, "deleteCloudServer", json!({ "id": s["id"] }), yes).await?; - ui::ok(&format!( - "Deleting {name}. Its services move off it first, then it's deleted at Hetzner." - )); - Ok(()) -} From 6f1ab4091d8aa84edcd231f0179725e1c84be05a Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:23:47 +0700 Subject: [PATCH 015/139] feat(cli): drop the hetzner and server commands Connecting Hetzner and making servers there is done in the dashboard for now. The API and MCP tools keep these ops. --- crates/pyo-cli/src/main.rs | 148 ------------------------------------- 1 file changed, 148 deletions(-) diff --git a/crates/pyo-cli/src/main.rs b/crates/pyo-cli/src/main.rs index 06c0cd59..c2b1af2c 100644 --- a/crates/pyo-cli/src/main.rs +++ b/crates/pyo-cli/src/main.rs @@ -17,7 +17,6 @@ mod login; mod pack; mod registry; mod sandbox; -mod server; mod service; mod ui; mod upgrade; @@ -321,19 +320,6 @@ enum Command { #[command(flatten)] which: Which, }, - /// Hetzner Cloud: the team's API token, for making servers there. - Hetzner { - #[command(subcommand)] - command: HetznerCommand, - /// The team (slug or id). Defaults to your first team. - #[arg(long, global = true)] - team: Option, - }, - /// Servers Pyo makes at Hetzner and joins to a cluster over your tailnet. - Server { - #[command(subcommand)] - command: ServerCommand, - }, /// The CLI's version, like --version. #[command(disable_version_flag = true)] Version, @@ -349,86 +335,6 @@ enum Command { }, } -#[derive(Subcommand)] -enum HetznerCommand { - /// Save a project API token with Read & Write. Owners and admins. - Connect { - /// The token. Without it, it's read from PYO_HETZNER_TOKEN, a pipe, or asked for. - #[arg(long, env = "PYO_HETZNER_TOKEN", hide_env_values = true)] - hetzner_token: Option, - }, - /// List the locations the saved token sees. - Test, - /// Forget the token. Servers Pyo made there keep running. - Disconnect { - /// Don't ask to confirm. - #[arg(long, short = 'y')] - yes: bool, - }, -} - -#[derive(Subcommand)] -enum ServerCommand { - /// Server types and their monthly prices at Hetzner. - Types { - /// One location, e.g. fsn1. - #[arg(long)] - location: Option, - /// The team (slug or id). Defaults to your first team. - #[arg(long)] - team: Option, - }, - /// Make a server at Hetzner and join it to a cluster. Shows the price and asks first. - Create { - /// The cluster it joins (name or id). Defaults to the team's default cluster. - #[arg(long, conflicts_with = "new_cluster")] - cluster: Option, - /// Make a new cluster with this name instead. The server is its first. - #[arg(long)] - new_cluster: Option, - /// Its name. Defaults to -. - #[arg(long, conflicts_with = "new_cluster")] - name: Option, - /// A Hetzner location, e.g. fsn1 (see pyo server types). - #[arg(long)] - location: String, - /// A server type, e.g. cx22 (see pyo server types). - #[arg(long = "type")] - server_type: String, - /// A build-only server. - #[arg(long, conflicts_with = "new_cluster")] - builder: bool, - /// Your SSH public key file, to sign in over your tailnet. - #[arg(long, value_name = "FILE")] - ssh_key: Option, - /// A tag for placing services (repeatable). - #[arg(long = "tag")] - tags: Vec, - /// The team (slug or id). Defaults to your first team. - #[arg(long)] - team: Option, - /// Don't ask to confirm the price. - #[arg(long, short = 'y')] - yes: bool, - /// Start it and exit, without following it. - #[arg(long)] - detach: bool, - }, - /// The servers Pyo made at Hetzner, and how they're doing. - List, - /// Move a server's services off it, take it out of its cluster and your tailnet, and delete it at Hetzner. - Delete { - /// Its name or id. - name: String, - /// Its cluster, when names repeat. - #[arg(long)] - cluster: Option, - /// Don't ask to confirm. - #[arg(long, short = 'y')] - yes: bool, - }, -} - #[derive(Subcommand)] enum DomainCommand { /// The service's domains and their status. @@ -1170,60 +1076,6 @@ async fn run(mut cli: Cli) -> anyhow::Result<()> { Ok(()) } Command::Upgrade { version } => upgrade::run(version).await, - Command::Hetzner { command, team } => { - let api = config::client(url, token)?; - let team = team.as_deref(); - match command { - HetznerCommand::Connect { hetzner_token } => { - server::connect(&api, team, hetzner_token).await - } - HetznerCommand::Test => server::test(&api, team).await, - HetznerCommand::Disconnect { yes } => server::disconnect(&api, team, yes).await, - } - } - Command::Server { command } => { - let api = config::client(url, token)?; - match command { - ServerCommand::Types { location, team } => { - server::types(&api, team.as_deref(), location.as_deref()).await - } - ServerCommand::Create { - cluster, - new_cluster, - name, - location, - server_type, - builder, - ssh_key, - tags, - team, - yes, - detach, - } => { - server::create( - &api, - server::New { - team: team.as_deref(), - cluster: cluster.as_deref(), - new_cluster: new_cluster.as_deref(), - name: name.as_deref(), - location: &location, - server_type: &server_type, - builder, - ssh_key: ssh_key.as_deref(), - tags, - yes, - detach, - }, - ) - .await - } - ServerCommand::List => server::list_servers(&api).await, - ServerCommand::Delete { name, cluster, yes } => { - server::delete(&api, &name, cluster.as_deref(), yes).await - } - } - } Command::Backup { command: BackupCommand::Now { volume, db, wait }, which, From 70a584e599ede7d2741c88a42fc0a3b5648a0314 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:26:31 +0700 Subject: [PATCH 016/139] fix(dash): stop the new project form flashing a name error on create The new project lands in the store at once, so the form read it as taking its own name and slug and showed both errors in red until the project page opened. The form now leaves out the project it just made and takes no second submit. --- dash/src/components/pyo/ProjectDialog.tsx | 13 +++++++++++-- dash/src/routes/_app/$team/projects/new.tsx | 1 + 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/dash/src/components/pyo/ProjectDialog.tsx b/dash/src/components/pyo/ProjectDialog.tsx index 81175a60..a06d2640 100644 --- a/dash/src/components/pyo/ProjectDialog.tsx +++ b/dash/src/components/pyo/ProjectDialog.tsx @@ -25,8 +25,13 @@ export function useProjectForm(project?: Project) { const [nsEdited, setNsEdited] = useState(!!project); const [description, setDescription] = useState(project?.description ?? ""); const [touched, setTouched] = useState(false); + // The project this form just made. It's in the store at once, so it + // mustn't read as taking its own name while the page moves on. + const [made, setMade] = useState(); - const others = projectsIn(s).filter((p) => p.id !== project?.id); + const others = projectsIn(s).filter( + (p) => p.id !== project?.id && p.id !== made, + ); const ns = nsEdited ? namespace : slugify(name); const errors = { name: !name.trim() @@ -48,7 +53,7 @@ export function useProjectForm(project?: Project) { ? "Another project already uses this name." : "", }; - const valid = !errors.name && !errors.namespace; + const valid = !made && !errors.name && !errors.namespace; return { name, setName, @@ -61,6 +66,8 @@ export function useProjectForm(project?: Project) { setDescription, touched, setTouched, + created: setMade, + reset: () => setMade(undefined), errors, valid, }; @@ -134,6 +141,7 @@ export function ProjectDialog({ f.setName(project?.name ?? ""); f.setDescription(project?.description ?? ""); f.setTouched(false); + f.reset(); // Reset when reopened. // eslint-disable-next-line react-hooks/exhaustive-deps }, [open]); @@ -160,6 +168,7 @@ export function ProjectDialog({ description: f.description, namespace: f.namespace, }); + f.created(id); toast({ title: `Project ${f.name.trim()} created` }); onClose(); void navigate({ diff --git a/dash/src/routes/_app/$team/projects/new.tsx b/dash/src/routes/_app/$team/projects/new.tsx index bad157f1..b098f90f 100644 --- a/dash/src/routes/_app/$team/projects/new.tsx +++ b/dash/src/routes/_app/$team/projects/new.tsx @@ -33,6 +33,7 @@ function NewProjectPage() { description: f.description, namespace: f.namespace, }); + f.created(id); toast({ title: `Project ${f.name.trim()} created` }); void navigate({ to: "/$team/$projectId", From 8791e267b7b2a7614e2c46ecfec8d726b800e83d Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:26:31 +0700 Subject: [PATCH 017/139] fix(dash): stop new databases flashing a name error on create A snapshot that came in before the database page opened listed the new database and the name field read it as taken. The form now leaves out the database it made, and Create stays off while the page moves. --- dash/src/components/pyo/database/NewDatabase.tsx | 14 +++++++++++--- dash/src/routes/_app/$team/import.tsx | 1 + 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/dash/src/components/pyo/database/NewDatabase.tsx b/dash/src/components/pyo/database/NewDatabase.tsx index 66c4da77..831b4712 100644 --- a/dash/src/components/pyo/database/NewDatabase.tsx +++ b/dash/src/components/pyo/database/NewDatabase.tsx @@ -92,8 +92,11 @@ export function useDatabaseDraft(engine: Engine, init?: { name: string; clusterI const [replicas, setReplicas] = useState(2); const [pooler, setPooler] = useState(true); const [rest, setRest] = useState(false); + // The database this form just made. Once it's in the store it mustn't + // read as taking its own name while the page moves on. + const [made, setMade] = useState(); const cluster = clusterId || ready[0]?.id || ""; - const nameError = name ? databaseNameError(engine, name, s.databases.filter((d) => d.teamId === s.currentTeamId)) : "Enter a name."; + const nameError = name ? databaseNameError(engine, name, s.databases.filter((d) => d.teamId === s.currentTeamId && d.id !== made)) : "Enter a name."; const custom = size === "custom"; const spec = custom ? { cpu, mem, storage } : SIZE_SPECS[size]; const sizeError = custom ? customError(engine, cpu, mem) || (storage >= 1 && storage <= 1000 ? "" : "Storage is 1 to 1000 GiB.") : ""; @@ -121,6 +124,7 @@ export function useDatabaseDraft(engine: Engine, init?: { name: string; clusterI rest, setRest, nameError, + created: setMade, custom, spec, sizeError, @@ -231,8 +235,12 @@ function NewDatabase({ engine }: { engine: Engine }) { setSaving(true); setError(""); const r = await api.createDatabase(f.fields()); - setSaving(false); - if ("error" in r) return setError(r.error); + if ("error" in r) { + setSaving(false); + return setError(r.error); + } + // Create stays off while the page moves on. + f.created(r.data.id); toast({ title: `Creating ${f.name}`, description: "It's ready in a minute or two." }); void navigate({ href: teamPath(currentSlug(), databaseHref(engine, r.data.id)) }); }; diff --git a/dash/src/routes/_app/$team/import.tsx b/dash/src/routes/_app/$team/import.tsx index 2590eff6..bdddc6cd 100644 --- a/dash/src/routes/_app/$team/import.tsx +++ b/dash/src/routes/_app/$team/import.tsx @@ -107,6 +107,7 @@ function ImportForm() { "databaseId" in target ? await importInto({ id: target.databaseId, teamId: s.currentTeamId, engine }, src) : await importNew(s.currentTeamId, engine, target.newDatabase, src); + if ("newDatabase" in target) f.created(newDbId); const name = into === "existing" ? existing?.name : f.name; toast({ title: `Importing into ${name}`, From d8901d84d1d0f744bdf8fcc964ef997e79480506 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:26:31 +0700 Subject: [PATCH 018/139] fix(dash): stop a new builder flashing a name error on add --- dash/src/routes/_app/$team/builders/new.tsx | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/dash/src/routes/_app/$team/builders/new.tsx b/dash/src/routes/_app/$team/builders/new.tsx index 73a10637..b85df68b 100644 --- a/dash/src/routes/_app/$team/builders/new.tsx +++ b/dash/src/routes/_app/$team/builders/new.tsx @@ -89,9 +89,13 @@ function AddBuilder() { const [server, setServer] = useState(""); const [saving, setSaving] = useState(false); const [touched, setTouched] = useState(false); + // The builder Add just made: it doesn't take its own name. + const [made, setMade] = useState(); const nameError = !DNS_LABEL.test(name) ? "Lowercase letters, digits and dashes." - : buildersIn(s).some((b) => b.name === name && b.id !== draftId) + : buildersIn(s).some( + (b) => b.name === name && b.id !== draftId && b.id !== made, + ) ? "A builder with this name exists." : ""; const free = servers.filter((x) => !x.builder); @@ -159,8 +163,9 @@ function AddBuilder() { setSaving(true); const [clusterId, targetNode] = target.split("|"); const r = await api.createBuilder({ name, kind, clusterId, server: targetNode }); - setSaving(false); - if (!r) return; + if (!r) return setSaving(false); + // Add stays off while the page moves on. + setMade(r.id); toast({ title: `Adding ${name}` }); void navigate({ to: "/$team/builders/$builderId", From 02590faccee45d4e2ebb2f4a93abbaf5109da306 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:26:31 +0700 Subject: [PATCH 019/139] fix(dash): keep a new hetzner cluster's name from reading as taken Once the cluster was made, the name field above its progress showed "A cluster with this name exists" for the cluster itself. --- dash/src/routes/_app/$team/clusters/new.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/dash/src/routes/_app/$team/clusters/new.tsx b/dash/src/routes/_app/$team/clusters/new.tsx index b8108271..33530d53 100644 --- a/dash/src/routes/_app/$team/clusters/new.tsx +++ b/dash/src/routes/_app/$team/clusters/new.tsx @@ -267,7 +267,11 @@ function HetznerCluster({ name && !/^[a-z0-9]([a-z0-9-]{0,59}[a-z0-9])?$/.test(name) ? "Lowercase letters, digits and dashes." : s.clusters.some( - (c) => c.teamId === s.currentTeamId && c.name === name && c.id !== draftId, + (c) => + c.teamId === s.currentTeamId && + c.name === name && + c.id !== draftId && + c.id !== made?.clusterId, ) ? "A cluster with this name exists." : ""; From b7090b0bc2cffd21c70d252ddb98ba5c5ce1857e Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:35:05 +0700 Subject: [PATCH 020/139] fix(api): read hetzner server type availability per location Hetzner removed GET /datacenters on 2026-10-01 and now answers 410 "API functionality was removed". Pyo read it to learn where each server type can be made, so the server type and price list failed and no Hetzner server (cluster or sandbox) could be made. Read availability and deprecation from each server type's `locations` instead, as Hetzner's changelog says. A location where a type is being phased out is left out with its price, like a type phased out everywhere before. The fake Hetzner in tests now answers in the current shape and 410 on /datacenters. Examples name cx23, since cx22 is no longer sold. --- crates/pyo-api/src/cloud/hetzner.rs | 91 +++++++++++++++++------------ crates/pyo-api/src/cloud/mod.rs | 42 ++++++++----- crates/pyo-api/src/ops.rs | 2 +- crates/pyo-api/src/sandbox/mod.rs | 2 +- crates/pyo-cli/src/main.rs | 2 +- crates/pyo-cli/src/sandbox.rs | 2 +- 6 files changed, 88 insertions(+), 53 deletions(-) diff --git a/crates/pyo-api/src/cloud/hetzner.rs b/crates/pyo-api/src/cloud/hetzner.rs index 6c9f5b81..02efe835 100644 --- a/crates/pyo-api/src/cloud/hetzner.rs +++ b/crates/pyo-api/src/cloud/hetzner.rs @@ -207,23 +207,6 @@ impl Provider for Hetzner { async fn catalog(&self) -> Result { let locations = self.locations().await?; let types = self.all("/server_types", "server_types").await?; - // Which types each datacenter can make now. - let mut available: BTreeMap> = BTreeMap::new(); - for dc in self.all("/datacenters", "datacenters").await? { - let loc = s(&dc["location"]["name"]); - for id in dc["server_types"]["available"] - .as_array() - .into_iter() - .flatten() - { - if let Some(id) = id.as_u64() { - let l = available.entry(id).or_default(); - if !l.contains(&loc) { - l.push(loc.clone()); - } - } - } - } // The IPv4 address each server gets costs extra. let pricing = self.call(Method::GET, "/pricing", None).await?; let currency = pricing["pricing"]["currency"] @@ -247,11 +230,30 @@ impl Provider for Hetzner { } let mut server_types: Vec = types .iter() - .filter(|t| t["deprecated"] != true && t["deprecation"].is_null()) - .map(|t| { - let id = t["id"].as_u64().unwrap_or(0); + .filter_map(|t| { + // Each type lists the locations that sell it. A location + // where Hetzner is phasing the type out has a `deprecation` + // and is left out, the same as a type phased out everywhere. + // `available` false means sold out for now. + let sold: Vec<(String, bool)> = t["locations"] + .as_array() + .into_iter() + .flatten() + .filter(|l| l["deprecation"].is_null()) + .map(|l| (s(&l["name"]), l["available"] == true)) + .filter(|(name, _)| !name.is_empty()) + .collect(); + if sold.is_empty() { + return None; + } + let mut available: Vec = sold + .iter() + .filter(|(_, now)| *now) + .map(|(name, _)| name.clone()) + .collect(); + available.sort(); let architecture = s(&t["architecture"]); - ServerType { + Some(ServerType { name: s(&t["name"]), description: s(&t["description"]), cores: t["cores"].as_u64().unwrap_or(0) as u32, @@ -266,13 +268,16 @@ impl Provider for Hetzner { .flatten() .filter_map(|p| { let loc = s(&p["location"]); + if !sold.iter().any(|(name, _)| *name == loc) { + return None; + } let m = price(&p["price_monthly"]["net"])?; let ip = ipv4.get(&loc).copied().unwrap_or(0.0); Some((loc, ((m + ip) * 100.0).round() / 100.0)) }) .collect(), - available: available.get(&id).cloned().unwrap_or_default(), - } + available, + }) }) .collect(); server_types.sort_by(|a, b| { @@ -442,25 +447,39 @@ pub mod mock { { "id": 2, "name": "ash", "city": "Ashburn, VA", "country": "US", "network_zone": "us-east" }, ], "meta": page_one }), ), + // The shape since 2026-11-02: availability and deprecation + // per location, and no `deprecated` field. ("GET", "/server_types") => ( 200, json!({ "server_types": [ - { "id": 22, "name": "cx22", "description": "CX22", "cores": 2, "memory": 4.0, "disk": 40, "cpu_type": "shared", "architecture": "x86", "deprecated": false, "deprecation": null, + { "id": 104, "name": "cx23", "description": "CX23", "cores": 2, "memory": 4.0, "disk": 40, "cpu_type": "shared", "category": "Cost-Optimized", "architecture": "x86", "storage_type": "local", "deprecation": null, + "locations": [ + { "id": 1, "name": "fsn1", "deprecation": null, "recommended": true, "available": true }, + { "id": 2, "name": "ash", "deprecation": null, "recommended": false, "available": false } ], + "prices": [ + { "location": "fsn1", "price_hourly": { "net": "0.0061000000", "gross": "0.0072590000" }, "price_monthly": { "net": "3.7900000000", "gross": "4.5101000000" }, "included_traffic": 21990232555520i64, "price_per_tb_traffic": { "net": "1.0000000000", "gross": "1.1900000000" } }, + { "location": "ash", "price_hourly": { "net": "0.0080000000", "gross": "0.0080000000" }, "price_monthly": { "net": "4.9900000000", "gross": "4.9900000000" }, "included_traffic": 1099511627776i64, "price_per_tb_traffic": { "net": "1.0000000000", "gross": "1.0000000000" } } ] }, + { "id": 45, "name": "cax11", "description": "CAX11", "cores": 2, "memory": 4.0, "disk": 40, "cpu_type": "shared", "category": "Cost-Optimized", "architecture": "arm", "storage_type": "local", "deprecation": null, + "locations": [ { "id": 1, "name": "fsn1", "deprecation": null, "recommended": false, "available": true } ], + "prices": [ { "location": "fsn1", "price_hourly": { "net": "0.0053000000", "gross": "0.0063070000" }, "price_monthly": { "net": "3.2900000000", "gross": "3.9151000000" }, "included_traffic": 21990232555520i64, "price_per_tb_traffic": { "net": "1.0000000000", "gross": "1.1900000000" } } ] }, + { "id": 108, "name": "cpx22", "description": "CPX22", "cores": 2, "memory": 4.0, "disk": 80, "cpu_type": "shared", "category": "Regular Purpose", "architecture": "x86", "storage_type": "local", "deprecation": null, + "locations": [ + { "id": 1, "name": "fsn1", "deprecation": { "announced": "2025-10-16T00:00:00Z", "unavailable_after": "2027-01-01T00:00:00Z" }, "recommended": false, "available": true }, + { "id": 2, "name": "ash", "deprecation": null, "recommended": true, "available": true } ], "prices": [ - { "location": "fsn1", "price_monthly": { "net": "3.7900000000", "gross": "4.5101000000" } }, - { "location": "ash", "price_monthly": { "net": "4.9900000000", "gross": "4.9900000000" } } ] }, - { "id": 45, "name": "cax11", "description": "CAX11", "cores": 2, "memory": 4.0, "disk": 40, "cpu_type": "shared", "architecture": "arm", "deprecated": false, "deprecation": null, - "prices": [ { "location": "fsn1", "price_monthly": { "net": "3.2900000000", "gross": "3.9151000000" } } ] }, - { "id": 1, "name": "cx11", "description": "old", "cores": 1, "memory": 2.0, "disk": 20, "cpu_type": "shared", "architecture": "x86", "deprecated": true, - "prices": [ { "location": "fsn1", "price_monthly": { "net": "3.0000000000", "gross": "3.5700000000" } } ] }, + { "location": "fsn1", "price_hourly": { "net": "0.0100000000", "gross": "0.0119000000" }, "price_monthly": { "net": "6.4900000000", "gross": "7.7231000000" }, "included_traffic": 21990232555520i64, "price_per_tb_traffic": { "net": "1.0000000000", "gross": "1.1900000000" } }, + { "location": "ash", "price_hourly": { "net": "0.0120000000", "gross": "0.0120000000" }, "price_monthly": { "net": "7.4900000000", "gross": "7.4900000000" }, "included_traffic": 1099511627776i64, "price_per_tb_traffic": { "net": "1.0000000000", "gross": "1.0000000000" } } ] }, + { "id": 22, "name": "cx22", "description": "CX22", "cores": 2, "memory": 4.0, "disk": 40, "cpu_type": "shared", "category": "Cost-Optimized", "architecture": "x86", "storage_type": "local", + "deprecation": { "announced": "2025-10-16T00:00:00Z", "unavailable_after": "2026-12-31T00:00:00Z" }, + "locations": [ { "id": 1, "name": "fsn1", "deprecation": { "announced": "2025-10-16T00:00:00Z", "unavailable_after": "2026-12-31T00:00:00Z" }, "recommended": false, "available": true } ], + "prices": [ { "location": "fsn1", "price_hourly": { "net": "0.0050000000", "gross": "0.0059500000" }, "price_monthly": { "net": "3.0000000000", "gross": "3.5700000000" }, "included_traffic": 21990232555520i64, "price_per_tb_traffic": { "net": "1.0000000000", "gross": "1.1900000000" } } ] }, ], "meta": page_one }), ), - ("GET", "/datacenters") => ( - 200, - json!({ "datacenters": [ - { "name": "fsn1-dc14", "location": { "name": "fsn1" }, "server_types": { "supported": [22, 45, 1], "available": [22, 45] } }, - { "name": "ash-dc1", "location": { "name": "ash" }, "server_types": { "supported": [22], "available": [] } }, - ], "meta": page_one }), + // Removed on 2026-10-01: Hetzner answers 410 Gone. + ("GET", r) if r.starts_with("/datacenters") => ( + 410, + json!({ "error": { "code": "deprecated_api_endpoint", "message": "API functionality was removed", + "details": { "announcement": "https://docs.hetzner.cloud/changelog" } } }), ), ("GET", "/pricing") => ( 200, diff --git a/crates/pyo-api/src/cloud/mod.rs b/crates/pyo-api/src/cloud/mod.rs index d47300cf..40c3a60d 100644 --- a/crates/pyo-api/src/cloud/mod.rs +++ b/crates/pyo-api/src/cloud/mod.rs @@ -77,7 +77,7 @@ pub struct Location { #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct ServerType { - /// "cx22" + /// "cx23" pub name: String, pub description: String, pub cores: u32, @@ -989,29 +989,45 @@ mod tests { #[tokio::test] async fn catalog_reads_types_prices_and_availability() { - let h = Hetzner::mock(mock::TOKEN, mock::Mock::new()); + let m = mock::Mock::new(); + let h = Hetzner::mock(mock::TOKEN, m.clone()); let c = h.catalog().await.unwrap(); assert_eq!(c.currency, "EUR"); assert_eq!(c.locations.len(), 2); - // The deprecated type is left out; the cheapest comes first. + // The type phased out everywhere is left out. The cheapest comes first. let names: Vec<&str> = c.server_types.iter().map(|t| t.name.as_str()).collect(); - assert_eq!(names, ["cax11", "cx22"]); - let cx = c.server_types.iter().find(|t| t.name == "cx22").unwrap(); + assert_eq!(names, ["cax11", "cx23", "cpx22"]); + let cx = c.server_types.iter().find(|t| t.name == "cx23").unwrap(); // 3.79 for the server, 0.50 for its IPv4 address. assert_eq!(cx.prices.get("fsn1"), Some(&4.29)); + assert_eq!(cx.prices.get("ash"), Some(&4.99)); + assert_eq!(cx.available, ["fsn1"]); assert!(cx.supported && cx.architecture == "x86"); - assert_eq!(c.pick("fsn1", "cx22").unwrap(), 4.29); + assert_eq!(c.pick("fsn1", "cx23").unwrap(), 4.29); // Arm isn't for Pyo's servers. assert!(c.pick("fsn1", "cax11").unwrap_err().message.contains("Arm")); // Sold out in Ashburn. - let e = c.pick("ash", "cx22").unwrap_err(); + let e = c.pick("ash", "cx23").unwrap_err(); assert!( e.message.contains("isn't available in Ashburn"), "{}", e.message ); - assert!(c.pick("nbg1", "cx22").is_err()); + // Phased out in Falkenstein only: sold in Ashburn, no price in Falkenstein. + let cpx = c.server_types.iter().find(|t| t.name == "cpx22").unwrap(); + assert_eq!(cpx.available, ["ash"]); + assert_eq!(cpx.prices.keys().collect::>(), ["ash"]); + assert_eq!(c.pick("ash", "cpx22").unwrap(), 7.49); + assert!(c.pick("fsn1", "cpx22").is_err()); + assert!(c.pick("fsn1", "cx22").is_err()); + assert!(c.pick("nbg1", "cx23").is_err()); assert!(c.pick("fsn1", "cx99").is_err()); + // Only endpoints Hetzner still has: /datacenters answers 410 since 2026-10-01. + let calls = m.0.lock().unwrap().calls.clone(); + assert!( + !calls.iter().any(|c| c.contains("/datacenters")), + "{calls:?}" + ); } #[tokio::test] @@ -1039,7 +1055,7 @@ mod tests { .collect(); assert_eq!(open, ["tcp/80", "tcp/443", "udp/41641"]); } - let mut c = create("web-1", "cx22", "cl_one", "#cloud-config\n"); + let mut c = create("web-1", "cx23", "cl_one", "#cloud-config\n"); c.firewall = Some(&fw); let r = h.create(&c).await.unwrap(); assert_eq!(r.status, "initializing"); @@ -1130,9 +1146,9 @@ mod tests { let m = mock::Mock::new(); m.0.lock().unwrap().limit = 1; let h = Hetzner::mock(mock::TOKEN, m.clone()); - h.create(&create("a", "cx22", "cl_one", "")).await.unwrap(); + h.create(&create("a", "cx23", "cl_one", "")).await.unwrap(); let e = h - .create(&create("b", "cx22", "cl_one", "")) + .create(&create("b", "cx23", "cl_one", "")) .await .unwrap_err(); assert!(matches!(e, CloudError::Quota(_))); @@ -1141,9 +1157,9 @@ mod tests { assert!(api.message.contains("server limit") && api.message.contains("Limits page")); m.0.lock().unwrap().limit = 5; - m.0.lock().unwrap().sold_out = vec!["cx32".into()]; + m.0.lock().unwrap().sold_out = vec!["cx33".into()]; let e = h - .create(&create("c", "cx32", "cl_one", "")) + .create(&create("c", "cx33", "cl_one", "")) .await .unwrap_err(); assert!(matches!(e, CloudError::Unavailable(_))); diff --git a/crates/pyo-api/src/ops.rs b/crates/pyo-api/src/ops.rs index 930493e4..87c95193 100644 --- a/crates/pyo-api/src/ops.rs +++ b/crates/pyo-api/src/ops.rs @@ -2745,7 +2745,7 @@ pub(crate) enum Op { provider: Option, /// A location's `name` from getCloudOptions ("fsn1"). location: String, - /// A server type's `name` from getCloudOptions ("cx22"). + /// A server type's `name` from getCloudOptions ("cx23"). server_type: String, /// A build-only server: only Pyo's builder runs on it. #[serde(default)] diff --git a/crates/pyo-api/src/sandbox/mod.rs b/crates/pyo-api/src/sandbox/mod.rs index f03e1474..fb4e38e4 100644 --- a/crates/pyo-api/src/sandbox/mod.rs +++ b/crates/pyo-api/src/sandbox/mod.rs @@ -1558,7 +1558,7 @@ pub struct AddCloudServer { pub provider: Option, /// A location's `name` from getCloudOptions ("fsn1"). pub location: String, - /// A server type's `name` from getCloudOptions ("cx22"). + /// A server type's `name` from getCloudOptions ("cx23"). pub server_type: String, /// A domain whose wildcard points at the server, as for /// `addSandboxServer`. diff --git a/crates/pyo-cli/src/main.rs b/crates/pyo-cli/src/main.rs index 06c0cd59..0e2311f9 100644 --- a/crates/pyo-cli/src/main.rs +++ b/crates/pyo-cli/src/main.rs @@ -392,7 +392,7 @@ enum ServerCommand { /// A Hetzner location, e.g. fsn1 (see pyo server types). #[arg(long)] location: String, - /// A server type, e.g. cx22 (see pyo server types). + /// A server type, e.g. cx23 (see pyo server types). #[arg(long = "type")] server_type: String, /// A build-only server. diff --git a/crates/pyo-cli/src/sandbox.rs b/crates/pyo-cli/src/sandbox.rs index 94a99866..f6ff5424 100644 --- a/crates/pyo-cli/src/sandbox.rs +++ b/crates/pyo-cli/src/sandbox.rs @@ -214,7 +214,7 @@ pub enum ServersCommand { /// A location, e.g. fsn1 (see pyo server types). #[arg(long)] location: String, - /// A server type, e.g. cx22 (see pyo server types). + /// A server type, e.g. cx23 (see pyo server types). #[arg(long = "type")] server_type: String, /// Serve sandbox ports at -.DOMAIN. Point *.DOMAIN at the server. From 085bc599cc2c5b650899a0773af01999a23bf87f Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 15:35:05 +0700 Subject: [PATCH 021/139] fix(api): keep hetzner's own words in its errors An error Hetzner gave no code for read "Hetzner answered 410: API functionality was removed". A 410 now says Hetzner removed a part of its API that Pyo calls, and every other error says the status and quotes Hetzner's message. --- crates/pyo-api/src/cloud/hetzner.rs | 10 ++---- crates/pyo-api/src/cloud/mod.rs | 56 +++++++++++++++++++++++++++-- 2 files changed, 56 insertions(+), 10 deletions(-) diff --git a/crates/pyo-api/src/cloud/hetzner.rs b/crates/pyo-api/src/cloud/hetzner.rs index 02efe835..124a999e 100644 --- a/crates/pyo-api/src/cloud/hetzner.rs +++ b/crates/pyo-api/src/cloud/hetzner.rs @@ -129,14 +129,8 @@ pub fn error_of(status: u16, body: &Value) -> CloudError { (_, "uniqueness_error") => CloudError::NameTaken, (429, _) | (_, "rate_limit_exceeded") => CloudError::RateLimited, (404, _) | (_, "not_found") => CloudError::NotFound, - _ => CloudError::Other { - status, - message: if message.is_empty() { - format!("status {status}") - } else { - message - }, - }, + (410, _) | (_, "deprecated_api_endpoint") => CloudError::Removed(message), + _ => CloudError::Other { status, message }, } } diff --git a/crates/pyo-api/src/cloud/mod.rs b/crates/pyo-api/src/cloud/mod.rs index 40c3a60d..a1db2720 100644 --- a/crates/pyo-api/src/cloud/mod.rs +++ b/crates/pyo-api/src/cloud/mod.rs @@ -177,6 +177,8 @@ pub enum CloudError { /// A server without this installation's label: never deleted. NotOurs, Network(String), + /// A part of Hetzner's API Pyo calls is gone (410): its message. + Removed(String), Other { status: u16, message: String, @@ -195,11 +197,28 @@ impl std::fmt::Display for CloudError { Self::NotFound => f.write_str("Hetzner has no such server."), Self::NotOurs => f.write_str("This server doesn't carry this Pyo's label at Hetzner, so Pyo won't delete it."), Self::Network(e) => write!(f, "Couldn't reach Hetzner. {e}"), - Self::Other { status, message } => write!(f, "Hetzner answered {status}: {message}"), + Self::Removed(message) => { + f.write_str("Hetzner removed a part of its API that Pyo calls")?; + said(f, message) + } + Self::Other { status, message } => { + write!(f, "Hetzner answered with error {status}")?; + said(f, message) + } } } } +/// Hetzner's own words after ours, when it gave some. +fn said(f: &mut std::fmt::Formatter<'_>, message: &str) -> std::fmt::Result { + let message = message.trim().trim_end_matches('.'); + if message.is_empty() { + f.write_str(".") + } else { + write!(f, ". It said: \"{message}\".") + } +} + impl std::error::Error for CloudError {} impl From for ApiError { @@ -213,7 +232,9 @@ impl From for ApiError { | CloudError::NotOurs => StatusCode::CONFLICT, CloudError::RateLimited => StatusCode::TOO_MANY_REQUESTS, CloudError::NotFound => StatusCode::NOT_FOUND, - CloudError::Network(_) | CloudError::Other { .. } => StatusCode::BAD_GATEWAY, + CloudError::Network(_) | CloudError::Removed(_) | CloudError::Other { .. } => { + StatusCode::BAD_GATEWAY + } }; ApiError::new(status, e.to_string()) } @@ -1030,6 +1051,37 @@ mod tests { ); } + #[test] + fn hetzner_errors_keep_its_message() { + let gone = hetzner::error_of( + 410, + &json!({ "error": { "code": "deprecated_api_endpoint", "message": "API functionality was removed", + "details": { "announcement": "https://docs.hetzner.cloud/changelog" } } }), + ); + assert_eq!( + gone, + CloudError::Removed("API functionality was removed".into()) + ); + assert_eq!( + gone.to_string(), + "Hetzner removed a part of its API that Pyo calls. It said: \"API functionality was removed\"." + ); + let api: ApiError = gone.into(); + assert_eq!(api.status, axum::http::StatusCode::BAD_GATEWAY); + assert_eq!( + hetzner::error_of( + 503, + &json!({ "error": { "code": "maintenance", "message": "cannot perform operation due to maintenance." } }) + ) + .to_string(), + "Hetzner answered with error 503. It said: \"cannot perform operation due to maintenance\"." + ); + assert_eq!( + hetzner::error_of(500, &Value::Null).to_string(), + "Hetzner answered with error 500." + ); + } + #[tokio::test] async fn create_and_delete() { let m = mock::Mock::new(); From 8d0e33f79e85834360e4d43425b13a7f615ce80d Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:10:09 +0700 Subject: [PATCH 022/139] feat(dash): add cloudflare tunnel types and ops Clusters gain traffic, tunnel and the tunnel capability. Domains gain tunnel, and their records gain via, previous and the switching states. The store sends setClusterTraffic, setDomainTunnel, removeClusterTunnel and rotateTunnelToken. --- dash/src/components/pyo/TrafficMode.tsx | 2 +- dash/src/lib/pyo/store.ts | 102 ++++++++++++++++++++++-- dash/src/lib/pyo/types.ts | 60 +++++++++++++- 3 files changed, 153 insertions(+), 11 deletions(-) diff --git a/dash/src/components/pyo/TrafficMode.tsx b/dash/src/components/pyo/TrafficMode.tsx index c138a9ac..09d02ab7 100644 --- a/dash/src/components/pyo/TrafficMode.tsx +++ b/dash/src/components/pyo/TrafficMode.tsx @@ -83,7 +83,7 @@ export function ClusterPublicTraffic({ cluster: c }: { cluster: Cluster }) { { - const res = await api.setClusterPublicTraffic(c.id, v); + const res = await api.setClusterTraffic(c.id, v ? "public" : "tailscale"); if (res?.ok) toast({ title: v ? "Public traffic on" : "Public traffic off", diff --git a/dash/src/lib/pyo/store.ts b/dash/src/lib/pyo/store.ts index f28fa28b..f38c5136 100644 --- a/dash/src/lib/pyo/store.ts +++ b/dash/src/lib/pyo/store.ts @@ -35,6 +35,7 @@ import type { AlertEvent, AlertKind, Cluster, + ClusterTraffic, ClusterServer, ControlBackup, Updates, @@ -736,6 +737,19 @@ export function cloudflareZoneFor( .filter((z) => host === z.name || host.endsWith(`.${z.name}`)) .sort((a, b) => b.name.length - a.name.length)[0]; } +/** How a cluster takes web traffic, from `publicTraffic` when it isn't reported. */ +export const clusterTraffic = (c: Cluster): ClusterTraffic => + c.traffic ?? (c.publicTraffic === false ? "tailscale" : "public"); + +/** The zone that lets a hostname use the cluster's tunnel: ready, in the tunnel's account. */ +export function tunnelZoneFor(s: PyoState, hostname: string, c?: Cluster) { + const t = c?.tunnel; + if (!t || t.state === "removing") return undefined; + const zone = cloudflareZoneFor(s, hostname, c.teamId); + return zone?.tunnel?.ready && zone.accountId === t.accountId + ? zone + : undefined; +} /** Your role in a team. */ export const roleIn = (s: PyoState, wsId = s.currentTeamId) => s.members.find((m) => m.teamId === wsId && m.email === s.user.email)?.role; @@ -1497,13 +1511,46 @@ export const api = { }); return send("setClusterWebProxyProtocol", { clusterId, on }); }, - /** The gateway answers public traffic on the cluster's servers, or not. */ - setClusterPublicTraffic(clusterId: string, on: boolean) { + /** How the cluster takes web traffic. Tunnel mode takes its settings along. */ + setClusterTraffic( + clusterId: string, + mode: ClusterTraffic, + tunnel?: { + defaultDomain: string | null; + accountId?: string; + portsPublic?: boolean; + }, + ) { update((s) => { const c = s.clusters.find((x) => x.id === clusterId); - if (c) c.publicTraffic = on; + if (!c) return; + c.traffic = mode; + c.publicTraffic = mode === "public"; + if (c.tunnel && tunnel) { + c.tunnel.defaultDomain = tunnel.defaultDomain; + if (tunnel.portsPublic !== undefined) + c.tunnel.portsPublic = tunnel.portsPublic; + } }); - return send("setClusterPublicTraffic", { clusterId, on }); + return send<{ traffic: ClusterTraffic; moving: number }>( + "setClusterTraffic", + { clusterId, mode, ...tunnel }, + ); + }, + /** Remove the cluster's tunnel; `restoreRecords` puts back what it replaced. */ + removeClusterTunnel(clusterId: string, restoreRecords: boolean) { + update((s) => { + const c = s.clusters.find((x) => x.id === clusterId); + if (c?.tunnel) { + c.tunnel.state = "removing"; + c.tunnel.health = "removing"; + } + }); + return send("removeClusterTunnel", { clusterId, restoreRecords }); + }, + /** A new tunnel token and certificate. */ + rotateTunnelToken(clusterId: string) { + return send("rotateTunnelToken", { clusterId }); }, /** The cluster's preview domain; null removes it. */ setClusterPreviewDomain(id: string, domain: string | null) { @@ -1994,8 +2041,8 @@ export const api = { tlsMode?: TlsMode; certificateId?: string; }, - /** Create its DNS record in Cloudflare once it's saved. */ - cloudflare?: { proxied: boolean }, + /** Create its DNS record in Cloudflare once it's saved, or switch it to the tunnel. */ + cloudflare?: { proxied: boolean } | { tunnel: true }, ) { const domainId = newId("dom"); update((s) => { @@ -2012,7 +2059,9 @@ export const api = { }); const res = await saveService(id); if (res?.ok && cloudflare) - await api.createDnsRecord(id, domainId, { proxied: cloudflare.proxied }); + await ("tunnel" in cloudflare + ? api.setDomainTunnel(id, domainId, { on: true }) + : api.createDnsRecord(id, domainId, { proxied: cloudflare.proxied })); return res; }, /** HTTPS settings of a domain; applied live once the service is deployed. */ @@ -2038,8 +2087,18 @@ export const api = { async removeDomain( id: string, domainId: string, - opts?: { deleteDnsRecord?: boolean }, + opts?: { deleteDnsRecord?: boolean; restoreRecord?: boolean }, ) { + // Put back the record a tunnel domain replaced, before it goes. + if (opts?.restoreRecord) { + const res = await send("setDomainTunnel", { + serviceId: id, + domainId, + on: false, + restore: true, + }); + if (!res?.ok) return null; + } if (opts?.deleteDnsRecord) { const res = await send("deleteDnsRecord", { serviceId: id, domainId }); if (!res?.ok) return null; @@ -2628,6 +2687,33 @@ export const api = { }); return res; }, + /** + * Serve a domain through the cluster's tunnel, or switch it back. + * `replace` replaces records in the way, `restore` puts a kept one back. + */ + setDomainTunnel( + serviceId: string, + domainId: string, + opts: { on: boolean; replace?: boolean; restore?: boolean }, + ) { + update((s) => { + const d = s.services + .find((a) => a.id === serviceId) + ?.domains.find((x) => x.id === domainId); + if (!d) return; + if (opts.on) d.tunnel ??= "switching"; + if (d.dnsRecord && (opts.on || d.dnsRecord.via === "tunnel")) + d.dnsRecord = { + ...d.dnsRecord, + status: opts.on ? "switching" : "reverting", + error: null, + }; + }); + return send<{ status: "switching" | "active" | "reverting" | "direct" }>( + "setDomainTunnel", + { serviceId, domainId, ...opts }, + ); + }, saveTailscale(clientId: string, secret?: string, clusterId?: string) { return attempt<{ checks: TailscaleCheck[] }>("saveTailscale", { clusterId, diff --git a/dash/src/lib/pyo/types.ts b/dash/src/lib/pyo/types.ts index 32bac56a..899b7d59 100644 --- a/dash/src/lib/pyo/types.ts +++ b/dash/src/lib/pyo/types.ts @@ -408,6 +408,10 @@ export type Cluster = { webProxyProtocol?: boolean; /** The gateway answers public traffic on its servers (all but build-only ones); on by default. */ publicTraffic?: boolean; + /** How it takes web traffic: public ports, only the tailnet, or Cloudflare Tunnel. */ + traffic?: ClusterTraffic; + /** Its Cloudflare Tunnel; absent when it has none. */ + tunnel?: ClusterTunnel | null; /** Its public IPv4 address, for DNS records (never a private one); null without one. */ publicIp?: string | null; /** Its Tailscale IPv4 address that answers websites; null without one. */ @@ -473,6 +477,8 @@ export type Cluster = { trafficModes?: boolean; /** The agent can keep traffic on the same server ("local"). */ trafficLocal?: boolean; + /** The agent can run a Cloudflare Tunnel connector. */ + tunnel?: boolean; /** What the agent may do on the cluster; null until it reports it. */ agentScope?: AgentScope | null; /** The agent's update protocol (0: it can't update Pyo or itself). */ @@ -493,6 +499,35 @@ export type Cluster = { lastSeenAt: Timestamp; }; +/** How a cluster takes web traffic. */ +export type ClusterTraffic = "public" | "tailscale" | "tunnel"; + +export type TunnelHealth = + "connected" | "degraded" | "down" | "starting" | "unknown" | "removing"; + +/** A cluster's Cloudflare Tunnel, as the control plane and the agent see it. */ +export type ClusterTunnel = { + state: "creating" | "ready" | "failed" | "removing"; + error: string | null; + accountId: string; + accountName: string; + tunnelId: string | null; + tunnelName: string; + /** Its zone apex: services get names under it. */ + defaultDomain: string | null; + /** Public TCP and UDP ports stay open on the servers. */ + portsPublic: boolean; + connectors: { server: string; ready: boolean; reason?: string | null }[]; + /** Cloudflare's data centers it's connected to ("FRA"). */ + colos: string[]; + connections: number; + health: TunnelHealth; + /** The cluster's install refused a tunnel object: run the connect command again. */ + refused: boolean; + certificate: { id: ID; notAfter: Timestamp } | null; + checkedAt: Timestamp | null; +}; + /** A cluster's wildcard domain for preview URLs. */ export type ClusterPreviewDomain = { /** "preview.example.com" */ @@ -907,6 +942,8 @@ export type Domain = { createdAt: Timestamp; /** Its DNS record in the team's Cloudflare account, when Pyo was asked to make one. */ dnsRecord?: DnsRecordState; + /** Through the cluster's Cloudflare Tunnel: "switching" (both ways work) or "on". */ + tunnel?: "switching" | "on"; }; /** A domain's DNS record in Cloudflare, as Pyo left it. */ @@ -918,16 +955,35 @@ export type DnsRecordState = { proxied: boolean; /** Proxied was asked for: on once the certificate is issued. */ proxy: boolean; - /** "created": Pyo made it. "exists": it already pointed there. "conflict": other records have the name. */ - status: "created" | "exists" | "conflict" | "failed"; + /** + * "created": Pyo made it. "exists": it already pointed there. "conflict": + * other records have the name. "switching" and "reverting": moving to the + * tunnel and back. + */ + status: + "created" | "exists" | "conflict" | "failed" | "switching" | "reverting"; error?: string | null; /** The records in the way, on a conflict. */ existing: CloudflareRecord[]; /** Pyo made it, so Pyo may delete it. */ mine: boolean; + /** A CNAME to the cluster's tunnel, or straight to the cluster. */ + via?: "direct" | "tunnel"; + /** The records it replaced, kept for Switch back. */ + previous?: PreviousRecord[]; updatedAt: Timestamp; }; +/** A record a tunnel domain replaced. */ +export type PreviousRecord = { + type: string; + name: string; + content: string; + proxied: boolean; + ttl: number; + comment?: string | null; +}; + export type CloudflareRecord = { id: string; type: string; From 4ea735693927590fac8c5659fb6ebb2f3d4426e9 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:12:38 +0700 Subject: [PATCH 023/139] feat(dash): choose public ports, tailscale or cloudflare tunnel The Public traffic panel becomes Traffic, a radio group of three choices. Cloudflare Tunnel takes a default domain, an account when the zones span more than one, and the public TCP and UDP ports switch, and asks before it switches. The panel shows the tunnel's health and Rotate, and Danger zone removes a tunnel the cluster no longer uses. --- dash/src/components/pyo/TrafficMode.tsx | 152 +++++--- dash/src/components/pyo/Tunnel.tsx | 353 ++++++++++++++++++ .../$team/clusters/$clusterId/settings.tsx | 6 +- 3 files changed, 458 insertions(+), 53 deletions(-) create mode 100644 dash/src/components/pyo/Tunnel.tsx diff --git a/dash/src/components/pyo/TrafficMode.tsx b/dash/src/components/pyo/TrafficMode.tsx index 09d02ab7..3be60529 100644 --- a/dash/src/components/pyo/TrafficMode.tsx +++ b/dash/src/components/pyo/TrafficMode.tsx @@ -1,9 +1,11 @@ +import { useState, type ReactNode } from "react"; +import { TunnelSettings, tunnelUnavailable } from "~/components/pyo/Tunnel"; import { LearnMore } from "~/components/ui/LearnMore"; import { optionClass, Switch } from "~/components/ui/Field"; import { Panel } from "~/components/ui/Panel"; -import { api } from "~/lib/pyo/store"; +import { api, clusterTraffic, usePyo } from "~/lib/pyo/store"; import { toast } from "~/lib/pyo/toast"; -import type { Cluster, TrafficMode } from "~/lib/pyo/types"; +import type { Cluster, ClusterTraffic as Traffic, TrafficMode } from "~/lib/pyo/types"; // How a cluster routes requests. Replicas are placed the same way in every // mode (evenly across regions, then servers); this only changes where each @@ -15,6 +17,42 @@ const MODES: { value: TrafficMode; label: string; hint: string }[] = [ { value: "spread", label: "Global", hint: "Distribute traffic across all servers" }, ]; +/** One choice of a radio group panel: a label and a hint line. */ +function RadioOption({ + name, + checked, + disabled, + label, + hint, + onSelect, +}: { + name: string; + checked: boolean; + disabled: boolean; + label: string; + hint: ReactNode; + onSelect: () => void; +}) { + return ( + + ); +} + export function ClusterTrafficMode({ cluster: c }: { cluster: Cluster }) { const capable = !!c.capabilities.trafficModes; const current = c.trafficMode ?? "region"; @@ -28,28 +66,18 @@ export function ClusterTrafficMode({ cluster: c }: { cluster: Cluster }) { className="space-y-2 p-4" > {MODES.map((m) => ( - + name={`traffic-${c.id}`} + checked={current === m.value} + disabled={off(m.value)} + label={m.label} + hint={capable && off(m.value) ? "Not reported yet." : m.hint} + onSelect={async () => { + const res = await api.setClusterTrafficMode(c.id, m.value); + if (res?.ok) toast({ title: m.label, description: c.name }); + }} + /> ))}
@@ -73,36 +101,58 @@ export function ClusterTrafficMode({ cluster: c }: { cluster: Cluster }) { ); } -/** Whether the gateway answers public traffic on the cluster's servers. */ -export function ClusterPublicTraffic({ cluster: c }: { cluster: Cluster }) { - const on = c.publicTraffic !== false; - const mode = c.freeDomainAddress ?? "public"; +const TRAFFIC: { value: Traffic; label: string }[] = [ + { value: "public", label: "Public ports" }, + { value: "tailscale", label: "Tailscale only" }, + { value: "tunnel", label: "Cloudflare Tunnel" }, +]; + +/** How the cluster takes web traffic: public ports, only the tailnet, or Cloudflare Tunnel. */ +export function ClusterTraffic({ cluster: c }: { cluster: Cluster }) { + const s = usePyo(); + const current = clusterTraffic(c); + // Cloudflare Tunnel waits for its settings and a confirm before it applies. + const [picked, setPicked] = useState(null); + const shown = picked ?? current; + const unavailable = current === "tunnel" ? null : tunnelUnavailable(s, c); + const hint = (m: Traffic) => + m === "public" + ? "Ports 80 and 443 on every server except build-only servers." + : m === "tailscale" + ? c.tailnet || c.tailscale + ? "Only from your tailnet." + : "Only inside the cluster until you set up Tailscale." + : (unavailable ?? "No open ports. Websites come in through Cloudflare."); + const pick = async (m: Traffic) => { + if (m === "tunnel" && current !== "tunnel") return setPicked(m); + setPicked(null); + if (m === current) return; + const res = await api.setClusterTraffic(c.id, m); + if (res?.ok) + toast({ title: TRAFFIC.find((x) => x.value === m)!.label, description: c.name }); + }; return ( - -
- { - const res = await api.setClusterTraffic(c.id, v ? "public" : "tailscale"); - if (res?.ok) - toast({ - title: v ? "Public traffic on" : "Public traffic off", - description: c.name, - }); - }} - label="Accept public traffic" - description={ - <> - {on - ? "On every server except build-only servers." - : mode === "tailscale" - ? "Services are reachable only from your tailnet." - : "Services are reachable only inside the cluster."}{" "} - - - } - /> + }> +
+ {TRAFFIC.map((m) => ( + void pick(m.value)} + /> + ))}
+ {shown === "tunnel" || c.tunnel ? ( + setPicked(null)} + /> + ) : null}
); } diff --git a/dash/src/components/pyo/Tunnel.tsx b/dash/src/components/pyo/Tunnel.tsx new file mode 100644 index 00000000..506c4d68 --- /dev/null +++ b/dash/src/components/pyo/Tunnel.tsx @@ -0,0 +1,353 @@ +import { useState } from "react"; +import { Badge, Dot, type Tone } from "~/components/ui/Badge"; +import { Button } from "~/components/ui/Button"; +import { ConfirmDialog } from "~/components/ui/Dialog"; +import { Field, Select, Switch } from "~/components/ui/Field"; +import { plural } from "~/lib/pyo/format"; +import { isTailnetDomain } from "~/lib/pyo/freeDomain"; +import { + api, + cloudflareIn, + cloudflareZoneFor, + clusterTraffic, + listedServices, + usePyo, + type PyoState, +} from "~/lib/pyo/store"; +import { toast } from "~/lib/pyo/toast"; +import type { Cluster, ClusterTunnel } from "~/lib/pyo/types"; + +// A cluster's Cloudflare Tunnel: its settings in the Traffic panel, its +// health, its badge in the cluster list and its removal. + +/** Why the cluster can't use a tunnel yet, or null when it can. */ +export function tunnelUnavailable(s: PyoState, c: Cluster): string | null { + const account = cloudflareIn(s, c.teamId); + if (!account) return "Connect Cloudflare first."; + if (!account.zones.some((z) => z.tunnel?.ready)) + return "Give the token Cloudflare Tunnel:Edit."; + if (c.capabilities.tunnel !== true) return "Not reported yet."; + return null; +} + +/** "a", "a and b", "a, b and c". */ +const list = (xs: string[]) => + xs.length < 2 ? xs.join("") : `${xs.slice(0, -1).join(", ")} and ${xs.at(-1)}`; + +/** The tunnel's health as one line. */ +function healthLine(t: ClusterTunnel): { tone: Tone; text: string } { + const ready = t.connectors.filter((x) => x.ready).length; + if (t.state === "failed") + return { tone: "danger", text: `Cloudflare: ${t.error ?? "the tunnel wasn't made."}` }; + switch (t.health) { + case "connected": + return { + tone: "success", + text: ["Tunnel connected", plural(ready, "connector"), t.colos.join(", ")] + .filter(Boolean) + .join(" · "), + }; + case "degraded": + return { + tone: "warning", + text: `Tunnel degraded · ${ready} of ${plural(t.connectors.length, "connector")}`, + }; + case "down": + return { tone: "danger", text: "Tunnel down. Its websites don't answer." }; + case "starting": + return { tone: "progress", text: "Starting the tunnel…" }; + case "removing": + return { tone: "progress", text: "Removing the tunnel…" }; + default: + return { tone: "neutral", text: "Pyo can't reach Cloudflare. Websites keep working." }; + } +} + +/** The tunnel's status line, and the lines that say what's wrong. */ +export function TunnelStatus({ c }: { c: Cluster }) { + const s = usePyo(); + const t = c.tunnel; + if (!t) return null; + const line = healthLine(t); + const notes = [ + ...t.connectors + .filter((x) => !x.ready && x.reason) + .map((x) => `pyo-tunnel can't start on ${x.server}: ${x.reason}`), + t.state !== "failed" && t.error + ? t.error + : !cloudflareIn(s, c.teamId) + ? "Connect Cloudflare again to change the tunnel." + : null, + t.refused + ? "Run the command under Refresh this cluster in the cluster's settings." + : null, + ].filter((x): x is string => !!x); + return ( +
+

+ + {line.text} +

+ {notes.map((n) => ( +

+ {n} +

+ ))} +
+ ); +} + +/** "Tunnel" beside a cluster in tunnel mode, warning tone while it's degraded or down. */ +export function TunnelBadge({ c }: { c: Cluster }) { + if (clusterTraffic(c) !== "tunnel") return null; + const bad = c.tunnel?.health === "degraded" || c.tunnel?.health === "down"; + return Tunnel; +} + +/** + * The Traffic panel's tunnel part: its settings while Cloudflare Tunnel is + * picked, its status and Rotate while it has one. + */ +export function TunnelSettings({ + c, + editing, + onCancel, +}: { + c: Cluster; + /** Cloudflare Tunnel is picked. */ + editing: boolean; + onCancel: () => void; +}) { + const s = usePyo(); + const t = c.tunnel && c.tunnel.state !== "removing" ? c.tunnel : null; + const zones = (cloudflareIn(s, c.teamId)?.zones ?? []).filter( + (z) => z.tunnel?.ready && z.accountId, + ); + const accounts = [...new Map(zones.map((z) => [z.accountId!, z.accountName ?? z.accountId!]))]; + const [account, setAccount] = useState(t?.accountId ?? zones[0]?.accountId ?? ""); + const [domain, setDomain] = useState(t?.defaultDomain ?? ""); + const [ports, setPorts] = useState(t?.portsPublic ?? true); + const [confirm, setConfirm] = useState<"switch" | "rotate" | null>(null); + const inTunnel = clusterTraffic(c) === "tunnel"; + const install = c.capabilities.agentInstall; + const outdated = !!install && install.state !== "current"; + const services = listedServices(s).filter((a) => a.clusterId === c.id); + const hasPorts = services.some((a) => + a.ports.some( + (p) => p.protocol !== "HTTP" && (p.exposure === "loadbalancer" || p.exposure === "nodeport"), + ), + ); + const dirty = + !inTunnel || + domain !== (t?.defaultDomain ?? "") || + ports !== (t?.portsPublic ?? true) || + (!!account && account !== t?.accountId); + + // What the switch does, for its confirm dialog. + const domains = services + .flatMap((a) => a.domains) + .filter((d) => !isTailnetDomain(d.hostname)); + const zoneOf = (host: string) => { + const z = cloudflareZoneFor(s, host, c.teamId); + return z?.tunnel?.ready && z.accountId === account ? z.name : undefined; + }; + const moving = [...new Set(domains.map((d) => zoneOf(d.hostname)).filter((z): z is string => !!z))]; + const outside = domains.filter((d) => !zoneOf(d.hostname)).length; + const lines = [ + moving.length + ? `Websites on ${list(moving)} move to the tunnel. Records Pyo didn't make wait for your OK.` + : null, + outside === 1 + ? "1 domain isn't in your Cloudflare account. It stops answering from the internet." + : outside + ? `${outside} domains aren't in your Cloudflare account. They stop answering from the internet.` + : null, + c.sameCluster + ? "The public dashboard closes. Open Pyo through Tailscale or your local network." + : null, + ].filter((x): x is string => !!x); + + const save = async () => { + const res = await api.setClusterTraffic(c.id, "tunnel", { + defaultDomain: domain || null, + accountId: account || undefined, + portsPublic: ports, + }); + if (res?.ok) + toast({ + title: inTunnel ? "Tunnel saved" : "Cloudflare Tunnel", + description: res.moving ? `${plural(res.moving, "domain")} moving` : c.name, + }); + }; + + return ( + <> + {editing ? ( +
+ {accounts.length > 1 && !t ? ( + + {(p) => ( + + )} + + ) : null} + + {(p) => ( + + )} + + {hasPorts ? ( + + ) : null} + {outdated ? ( +

+ Run the command under Refresh this cluster in the cluster's settings first. +

+ ) : null} +
+ ) : null} + {c.tunnel ? ( +
+ +
+ ) : null} + {t || (editing && dirty) ? ( +
+ {t ? ( + + ) : null} + {editing && !inTunnel ? ( + + ) : null} + {editing && dirty ? ( + + ) : null} +
+ ) : null} + setConfirm(null)} + tone="primary" + title={`Switch ${c.name} to Cloudflare Tunnel?`} + description={ + lines.length ? ( +
+ {lines.map((l) => ( +

{l}

+ ))} +
+ ) : null + } + confirmLabel="Switch" + onConfirm={() => void save()} + /> + setConfirm(null)} + tone="primary" + title={`Rotate the tunnel token of ${c.name}?`} + description="The tunnel gets a new token and certificate, and reconnects." + confirmLabel="Rotate" + onConfirm={() => + void api.rotateTunnelToken(c.id).then((r) => { + if (r?.ok) toast({ title: "Tunnel token rotated", description: c.name }); + }) + } + /> + + ); +} + +/** Danger zone: remove the tunnel of a cluster that's no longer in tunnel mode. */ +export function RemoveTunnelRow({ c }: { c: Cluster }) { + const [open, setOpen] = useState(false); + const [restore, setRestore] = useState(true); + if (!c.tunnel || clusterTraffic(c) === "tunnel") return null; + const removing = c.tunnel.state === "removing"; + return ( +
  • +
    +

    Remove tunnel

    +

    + {removing ? "Removing…" : c.tunnel.tunnelName} +

    +
    + + setOpen(false)} + title={`Remove the tunnel of ${c.name}?`} + description="Pyo deletes the DNS records it made for it." + confirmLabel="Remove tunnel" + onConfirm={() => + void api.removeClusterTunnel(c.id, restore).then((r) => { + if (r?.ok) toast({ title: "Removing the tunnel", description: c.name }); + }) + } + > + + +
  • + ); +} diff --git a/dash/src/routes/_app/$team/clusters/$clusterId/settings.tsx b/dash/src/routes/_app/$team/clusters/$clusterId/settings.tsx index 3c32af31..09a71f66 100644 --- a/dash/src/routes/_app/$team/clusters/$clusterId/settings.tsx +++ b/dash/src/routes/_app/$team/clusters/$clusterId/settings.tsx @@ -9,7 +9,8 @@ import { useHosted, usePyoVersion, } from "~/components/pyo/Managed"; -import { ClusterPublicTraffic, ClusterTrafficMode } from "~/components/pyo/TrafficMode"; +import { ClusterTraffic, ClusterTrafficMode } from "~/components/pyo/TrafficMode"; +import { RemoveTunnelRow } from "~/components/pyo/Tunnel"; import { Badge, ClusterStatusBadge } from "~/components/ui/Badge"; import { Button } from "~/components/ui/Button"; import { ConfirmDialog } from "~/components/ui/Dialog"; @@ -117,7 +118,7 @@ function ClusterSettings({ c }: { c: Cluster }) {
    - + @@ -147,6 +148,7 @@ function ClusterSettings({ c }: { c: Cluster }) {
    ) : null} +
  • Remove from Pyo

    From eadce0573032abb4e9e117414be1a6d798d881eb Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:12:47 +0700 Subject: [PATCH 024/139] feat(proto): describe the cloudflare tunnel connector and its admission Adds the tunnel's commands (TunnelSet, TunnelRemove), the heartbeat's TunnelReport, the reply's TunnelWanted and publicPorts, the agent's tunnel capability and a domain's tunnel state (switching or on). system.rs gets cloudflared by digest, its Deployment, Secret and disruption budget, the origin Service in front of the gateway's HTTPS and the Service that keeps public TCP and UDP ports in tunnel mode. The admission policy pins both Services, lets the agent write them by name and takes client policies labelled tunnel with Cloudflare's own visitor headers kept. firewall.rs adds the gated authorization for switched tunnel routes. --- crates/pyo-proto/src/firewall.rs | 32 +++++++ crates/pyo-proto/src/lib.rs | 93 ++++++++++++++++++ crates/pyo-proto/src/rbac.rs | 134 +++++++++++++++++++++++++- crates/pyo-proto/src/system.rs | 157 ++++++++++++++++++++++++++++++- 4 files changed, 410 insertions(+), 6 deletions(-) diff --git a/crates/pyo-proto/src/firewall.rs b/crates/pyo-proto/src/firewall.rs index 4122883d..e95af907 100644 --- a/crates/pyo-proto/src/firewall.rs +++ b/crates/pyo-proto/src/firewall.rs @@ -591,6 +591,38 @@ pub fn web_authorization(fw: &Firewall, entry: Entry) -> Option { Some(json!({ "defaultAction": default, "rules": rules })) } +/// A website's authorization on its tunnel routes once its record points +/// at the tunnel (`DomainSpec::tunnel_only`): the behind gate first, so only +/// the tunnel's connectors (whose visitor was read from X-Forwarded-For) +/// get through and a direct connection gets 403, then the service's own +/// rules. The service's own "behind" CDN doesn't apply there. +pub fn tunnel_authorization(fw: &Firewall) -> Value { + let own = Firewall { + behind: None, + ..fw.clone() + }; + let (default, rules) = match authorization(&[&own], true) { + Some(a) => ( + a["defaultAction"].clone(), + a["rules"].as_array().cloned().unwrap_or_default(), + ), + None => (json!("Allow"), vec![]), + }; + let rules: Vec = [behind_gate_rule()].into_iter().chain(rules).collect(); + json!({ "defaultAction": default, "rules": rules }) +} + +/// What a tunnel client policy trusts: these addresses, or (with none +/// yet) one no connection ever comes from, never "anyone". +pub fn trusted_or_nothing(mut cidrs: Vec) -> Vec { + cidrs.sort(); + cidrs.dedup(); + if cidrs.is_empty() { + cidrs.push(NOTHING.into()); + } + cidrs +} + /// Whether a website's plain HTTP routes take its rate limits: not behind /// a CDN, where every request there comes from the CDN's few addresses. pub fn http_rate_limits(fw: &Firewall) -> bool { diff --git a/crates/pyo-proto/src/lib.rs b/crates/pyo-proto/src/lib.rs index c4fd2f5c..065eb520 100644 --- a/crates/pyo-proto/src/lib.rs +++ b/crates/pyo-proto/src/lib.rs @@ -146,6 +146,58 @@ pub struct Heartbeat { /// services get what a newer agent writes. Empty from older agents. #[serde(default, skip_serializing_if = "String::is_empty")] pub routes_version: String, + /// The Cloudflare Tunnel connector, when the cluster has one (or the + /// agent knows tunnels: then it says it has none). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tunnel: Option, +} + +/// The cluster's Cloudflare Tunnel connector, as the agent sees it. +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct TunnelReport { + /// The tunnel its token is for (the Secret's label). None: no token here. + #[serde(default)] + pub tunnel_id: Option, + #[serde(default)] + pub replicas: i32, + #[serde(default)] + pub ready_replicas: i32, + #[serde(default)] + pub pods: Vec, + /// The origin Service is in place. + #[serde(default)] + pub origin_ready: bool, + /// The cluster's install refused a tunnel object: its admission policy + /// is older than the agent's. What runs is kept as it is. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub refused: bool, +} + +/// One connector pod. +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct TunnelPod { + pub server: String, + pub ready: bool, + #[serde(default)] + pub restarts: i32, + /// Why it isn't ready ("ImagePullBackOff"), at most 200 characters. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + +/// The Cloudflare Tunnel connector Pyo wants ([`HeartbeatReply::tunnel`]). +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct TunnelWanted { + /// The tunnel to run (with the token the agent has for it). None: + /// remove the connector and its token. + #[serde(default)] + pub tunnel_id: Option, + /// In tunnel mode, TCP and UDP ports stay published on the servers. + #[serde(default)] + pub ports_public: bool, } /// A server's Tailscale, as tailscaled says (the agent's tailnet pod on it). @@ -531,6 +583,10 @@ pub struct Capabilities { /// firewall sync is on its way, is still starting. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub waf_active: Vec, + /// The agent runs a Cloudflare Tunnel connector (`TunnelSet`) and + /// writes tunnel domains' routes. + #[serde(default)] + pub tunnel: bool, } /// A server where the gateway can't get some of its ports. @@ -1307,6 +1363,12 @@ pub enum Command { /// The team's registry tokens (their hashes) for the door of the /// cluster's own registry: these, and no others, from now on. SyncRegistryTokens(Box), + /// Run the cluster's Cloudflare Tunnel connector with this token: kept + /// as the Secret pyo-system/pyo-tunnel, labelled with the tunnel's id, + /// and the connector (re)applied. `data` is a [`TunnelReport`]. + TunnelSet { tunnel_id: String, token: String }, + /// Stop the connector and delete its token. + TunnelRemove {}, } // ── Releases and updates ─────────────────────────────────────────────────── @@ -2295,8 +2357,30 @@ pub struct DomainSpec { /// Send plain HTTP requests to HTTPS (when `tls` is set). #[serde(default)] pub redirect_https: bool, + /// Through the cluster's Cloudflare Tunnel: "switching" (the tunnel and + /// direct visitors both get through, while its record moves) or "on" + /// (only the tunnel: direct connections get 403, no plain HTTP route). + /// "": direct only. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub tunnel: String, } +impl DomainSpec { + /// Served through the tunnel ("switching" or "on"). + pub fn via_tunnel(&self) -> bool { + matches!(self.tunnel.as_str(), TUNNEL_SWITCHING | TUNNEL_ON) + } + /// Only through the tunnel. + pub fn tunnel_only(&self) -> bool { + self.tunnel == TUNNEL_ON + } +} + +/// A domain's `tunnel` while its record moves: both paths answer. +pub const TUNNEL_SWITCHING: &str = "switching"; +/// A domain's `tunnel` once its record points at the tunnel. +pub const TUNNEL_ON: &str = "on"; + /// An uploaded certificate, as the agent gets it: the chain and its key, PEM. #[derive(Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -2680,6 +2764,15 @@ pub struct HeartbeatReply { /// without it): left as it is. #[serde(default, skip_serializing_if = "Option::is_none")] pub public_dashboard: Option, + /// The Cloudflare Tunnel connector. None (a reply without it): left as + /// it is. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tunnel: Option, + /// Public TCP and UDP ports are published on the servers: with public + /// traffic, or in tunnel mode when the cluster keeps them. None (a + /// reply without it): as `public_traffic` says. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub public_ports: Option, } /// Pyo's dashboard on the public IP ([`system::public_dashboard_objects`]). diff --git a/crates/pyo-proto/src/rbac.rs b/crates/pyo-proto/src/rbac.rs index f8ed0f40..c455cfaa 100644 --- a/crates/pyo-proto/src/rbac.rs +++ b/crates/pyo-proto/src/rbac.rs @@ -265,7 +265,7 @@ pub fn objects(upgrades: bool) -> Vec { { "apiGroups": ["networking.k8s.io"], "resources": ["networkpolicies"], "verbs": ["get", "patch", "delete"], "resourceNames": [system::FIREWALL_POLICY] }, // Websites on the servers' Tailscale addresses: its own Service. { "apiGroups": [""], "resources": ["services"], "verbs": ["create"] }, - { "apiGroups": [""], "resources": ["services"], "verbs": ["get", "patch", "delete"], "resourceNames": [system::TAILNET_WEB_SERVICE, system::TAILNET_VIP_SERVICE, system::PUBLIC_NAT_SERVICE] }, + { "apiGroups": [""], "resources": ["services"], "verbs": ["get", "patch", "delete"], "resourceNames": [system::TAILNET_WEB_SERVICE, system::TAILNET_VIP_SERVICE, system::PUBLIC_NAT_SERVICE, system::TUNNEL_ORIGIN_SERVICE, system::PUBLIC_PORTS_SERVICE] }, // The Tailscale Services' wanted list, for the servers' tailnet pods. { "apiGroups": [""], "resources": ["configmaps"], "verbs": ["get", "patch", "delete"], "resourceNames": [system::TAILNET_WANTED] }, // The proxy's failed pods, cleaned up (an eviction on a full @@ -561,7 +561,7 @@ pub fn admission_with( (!has(object.spec.connection) || (object.spec.connection.all(k, k in ['connectionLimit', 'maxAcceptPerSocketEvent']) && (!has(object.spec.connection.maxAcceptPerSocketEvent) || object.spec.connection.maxAcceptPerSocketEvent == 1) && (!has(object.spec.connection.connectionLimit) || (object.spec.connection.connectionLimit.all(k, k == 'value') && object.spec.connection.connectionLimit.value >= 1)))) && \ (!has(object.spec.proxyProtocol) || object.spec.proxyProtocol == {pp_optional})) || \ (object.metadata.labels[?'{cdn_label}'].orValue('') in {behind} && object.spec.all(k, k in ['targetRefs', 'clientIPDetection', 'connection', 'headers', 'tls', 'proxyProtocol', 'timeout']) && ({cdn_headers}) && \ - size(object.spec.targetRefs) >= 1 && object.spec.targetRefs.all(t, t.group == 'gateway.networking.k8s.io' && t.kind == 'Gateway' && t.name + '-cdn' == variables.objName && has(t.sectionName) && t.sectionName.startsWith('h-')) && \ + size(object.spec.targetRefs) >= 1 && object.spec.targetRefs.all(t, t.group == 'gateway.networking.k8s.io' && t.kind == 'Gateway' && t.name + (object.metadata.labels[?'{cdn_label}'].orValue('') == '{tunnel_cdn}' ? '-{tunnel_cdn}' : '-cdn') == variables.objName && has(t.sectionName) && t.sectionName.startsWith('h-')) && \ {ctp_https}.exists(v, ['connection', 'tls', 'proxyProtocol', 'timeout'].all(k, (k in v) == (k in object.spec) && (!(k in v) || v[k] == object.spec[k]))) && \ object.spec.clientIPDetection.all(k, k == 'xForwardedFor') && object.spec.clientIPDetection.xForwardedFor.all(k, k == 'trustedCIDRs') && \ size(object.spec.clientIPDetection.xForwardedFor.trustedCIDRs) >= 1 && size(object.spec.clientIPDetection.xForwardedFor.trustedCIDRs) <= {max_trusted} && \ @@ -602,6 +602,13 @@ pub fn admission_with( (request.resource.resource == 'services' && variables.objName == '{vip_svc}' && variables.sub == '' && (request.operation == 'DELETE' || (object.spec.all(k, k in {tw_keys}) && \ object.spec.type == 'ClusterIP' && object.spec.externalTrafficPolicy == 'Local' && object.spec.selector == {tw_selector} && object.spec.ports == {vip_ports} && \ size(object.spec.externalIPs) >= 1 && size(object.spec.externalIPs) <= 1024 && object.spec.externalIPs.all(ip, ip.matches({tw_v4}) || ip.matches({tw_v6}))))) || \ + (request.resource.resource == 'services' && variables.objName == '{origin_svc}' && variables.sub == '' && (request.operation == 'DELETE' || (object.spec.all(k, k in {origin_keys}) && \ + object.spec.type == 'ClusterIP' && object.spec.selector == {tw_selector} && object.spec.ports == {origin_ports}))) || \ + (request.resource.resource == 'services' && variables.objName == '{pp_svc}' && variables.sub == '' && (request.operation == 'DELETE' || (object.spec.all(k, k in {pp_keys}) && \ + object.spec.type == 'LoadBalancer' && object.spec.externalTrafficPolicy == 'Local' && object.spec.selector == {tw_selector} && size(object.spec.ports) >= 1 && size(object.spec.ports) <= 256 && \ + object.spec.ports.all(p, p.all(k, k in ['name', 'port', 'targetPort', 'protocol', 'nodePort']) && \ + ((p.protocol == 'UDP' && !(p.port in {udp_reserved})) || (p.protocol == 'TCP' && !(p.port in {tcp_reserved}) && !(p.port >= 19000 && p.port <= 19003))) && \ + p.targetPort == (p.port < 1024 ? p.port + 10000 : p.port))))) || \ (request.resource.resource == 'services' && variables.objName == '{nat_svc}' && variables.sub == '' && (request.operation == 'DELETE' || (object.spec.all(k, k in {tw_keys}) && \ object.spec.type == 'ClusterIP' && object.spec.externalTrafficPolicy == 'Local' && object.spec.selector == {tw_selector} && object.spec.ports == {tw_ports} && \ size(object.spec.externalIPs) >= 1 && size(object.spec.externalIPs) <= 64 && object.spec.externalIPs.all(ip, ip.matches({nat_v4}) && !ip.matches({nat_private}))))) || \ @@ -672,6 +679,16 @@ pub fn admission_with( // NAT (system.rs): this Service only, onto the proxies, the // websites' ports, and public IPv4 addresses alone. nat_svc = system::PUBLIC_NAT_SERVICE, + // Cloudflare Tunnel (system.rs): the connector's way in, onto the + // proxies' HTTPS only, and public TCP and UDP ports in tunnel + // mode, onto the proxies, never the websites' or the servers' + // own ports. + origin_svc = system::TUNNEL_ORIGIN_SERVICE, + origin_keys = cel_literal(&json!(["type", "selector", "ports"].iter().chain(system::TAILNET_WEB_DEFAULTED.iter()).collect::>())), + origin_ports = cel_literal(&system::tunnel_origin_ports()), + pp_svc = system::PUBLIC_PORTS_SERVICE, + pp_keys = cel_literal(&json!(["type", "externalTrafficPolicy", "selector", "ports"].iter().chain(system::TAILNET_WEB_DEFAULTED.iter()).chain(system::LOAD_BALANCER_DEFAULTED.iter()).collect::>())), + tunnel_cdn = system::TUNNEL_CDN, nat_v4 = cel_literal(&json!(system::IPV4_RE)), nat_private = cel_literal(&json!(system::NOT_PUBLIC_IPV4_RE)), label = system::GATEWAY_LABEL, @@ -693,7 +710,7 @@ pub fn admission_with( cdn_label = system::CDN_LABEL, // The headers it removes: all that name a visitor but the CDN's // own (system.rs `visitor_headers`), pinned per CDN. - cdn_headers = crate::firewall::BEHIND.iter().map(|cdn| format!( + cdn_headers = crate::firewall::BEHIND.iter().chain([&system::TUNNEL_CDN]).map(|cdn| format!( "(object.metadata.labels[?'{label}'].orValue('') == '{cdn}' && has(object.spec.headers) && object.spec.headers == {headers})", label = system::CDN_LABEL, headers = cel_literal(&system::visitor_headers(system::cdn_own_headers(cdn))))).collect::>().join(" || "), @@ -701,7 +718,8 @@ pub fn admission_with( // behind a CDN its connections only (firewall.rs). acme_rule = cel_literal(&crate::firewall::acme_rule()), gate_rule = cel_literal(&crate::firewall::behind_gate_rule()), - behind = cel_literal(&json!(crate::firewall::BEHIND)), + // The CDNs a website can be behind, and the tunnel's connectors. + behind = cel_literal(&json!(crate::firewall::BEHIND.iter().chain([&system::TUNNEL_CDN]).collect::>())), max_trusted = system::MAX_TRUSTED_CIDRS, trusted_v4 = cel_literal(&json!(system::TRUSTED_V4_RE)), trusted_v6 = cel_literal(&json!(system::TRUSTED_V6_RE)), @@ -1419,7 +1437,7 @@ mod tests { svc, [ &json!({ "apiGroups": [""], "resources": ["services"], "verbs": ["create"] }), - &json!({ "apiGroups": [""], "resources": ["services"], "verbs": ["get", "patch", "delete"], "resourceNames": [system::TAILNET_WEB_SERVICE, system::TAILNET_VIP_SERVICE, system::PUBLIC_NAT_SERVICE] }), + &json!({ "apiGroups": [""], "resources": ["services"], "verbs": ["get", "patch", "delete"], "resourceNames": [system::TAILNET_WEB_SERVICE, system::TAILNET_VIP_SERVICE, system::PUBLIC_NAT_SERVICE, system::TUNNEL_ORIGIN_SERVICE, system::PUBLIC_PORTS_SERVICE] }), ] ); let policy = admission("w", "g"); @@ -1479,6 +1497,112 @@ mod tests { /// The Service for the public IPs behind the cloud's NAT: pinned like /// the tailnet websites' one, on public IPv4 addresses only. + #[test] + fn the_tunnel_services_are_pinned() { + let policy = admission("w", "g"); + let all = policy[0]["spec"]["variables"] + .as_array() + .unwrap() + .iter() + .find(|v| v["name"] == "gatewayAllowed") + .unwrap()["expression"] + .as_str() + .unwrap(); + let clause = |name: &str| { + let start = all + .find(&format!("variables.objName == '{name}'")) + .unwrap_or_else(|| panic!("{name}'s clause")); + all[start..start + all[start..].find("))) || ").unwrap()].to_owned() + }; + let selector = format!( + "object.spec.selector == {}", + cel_literal(&system::proxy_pods()["matchLabels"]) + ); + let origin = clause(system::TUNNEL_ORIGIN_SERVICE); + for part in [ + "object.spec.type == 'ClusterIP'".to_owned(), + selector.clone(), + format!( + "object.spec.ports == {}", + cel_literal(&system::tunnel_origin_ports()) + ), + ] { + assert!(origin.contains(&part), "{part}\n{origin}"); + } + // No external addresses on the origin. + assert!(!origin.contains("externalIPs")); + let ports = clause(system::PUBLIC_PORTS_SERVICE); + for part in [ + "object.spec.type == 'LoadBalancer' && object.spec.externalTrafficPolicy == 'Local'" + .to_owned(), + selector, + "!(p.port in [80, 443, 10080, 10443, 22, 53, 2379, 2380, 6443, 10250".to_owned(), + "p.targetPort == (p.port < 1024 ? p.port + 10000 : p.port)".to_owned(), + ] { + assert!(ports.contains(&part), "{part}\n{ports}"); + } + assert!(!ports.contains("externalIPs")); + // What the agent writes is what's pinned. + assert_eq!(system::tunnel_origin_service()["spec"]["ports"], system::tunnel_origin_ports()); + let s = system::public_ports_service(&[("TCP".into(), 5432), ("UDP".into(), 53), ("TCP".into(), 25)]).unwrap(); + assert_eq!(s["spec"]["ports"][0], json!({ "name": "tcp-25", "port": 25, "targetPort": 10025, "protocol": "TCP" })); + assert_eq!(s["spec"]["ports"][1]["targetPort"], 5432); + assert!(system::public_ports_service(&[]).is_none()); + // The agent may write both, by name. + let roles = json!(objects(false)).to_string(); + assert!(roles.contains(system::TUNNEL_ORIGIN_SERVICE) && roles.contains(system::PUBLIC_PORTS_SERVICE)); + } + + #[test] + fn tunnel_client_policies_trust_only_their_listeners() { + let all = admission(system::WAF_IMAGE_DEFAULT, system::GEOIP_IMAGE_DEFAULT)[0].to_string(); + let start = all + .find("request.resource.resource == 'clienttrafficpolicies'") + .unwrap(); + let end = all[start..] + .find("request.resource.resource == 'securitypolicies'") + .unwrap(); + let ctp = &all[start..start + end]; + // The label, and Cloudflare's own headers kept (they come from it). + assert!(ctp.contains("dyn('cloudflare'), dyn('tunnel')"), "{ctp}"); + let kept = system::cel_literal(&system::visitor_headers(system::cdn_own_headers(system::TUNNEL_CDN))); + assert!(ctp.contains(&format!( + "(object.metadata.labels[?'{}'].orValue('') == 'tunnel' && has(object.spec.headers) && object.spec.headers == {kept})", + system::CDN_LABEL + ))); + // Named after its own Gateway. + assert!(ctp.contains("== 'tunnel' ? '-tunnel' : '-cdn') == variables.objName")); + // Not a CDN a user can pick. + assert!(!crate::firewall::BEHIND.contains(&system::TUNNEL_CDN)); + // Pod addresses as the policy holds them. + assert_eq!( + system::host_cidrs(&["10.42.1.7".into(), "fd00::5".into(), "10.42.1.7".into(), "bad".into()]), + ["10.42.1.7/32", "fd00::5/128"] + ); + let v4 = regex::Regex::new(system::TRUSTED_V4_RE).unwrap(); + let v6 = regex::Regex::new(system::TRUSTED_V6_RE).unwrap(); + assert!(v4.is_match("10.42.1.7/32") && v6.is_match("fd00::5/128")); + } + + #[test] + fn the_tunnel_connector_passes_the_pod_rules() { + let d = system::tunnel_deployment(system::CLOUDFLARED_IMAGE); + let pod = &d["spec"]["template"]["spec"]; + assert_eq!(pod["automountServiceAccountToken"], false); + assert!(pod.get("hostNetwork").is_none() && pod.get("volumes").is_none()); + let c = &pod["containers"][0]; + assert_eq!(c["securityContext"]["capabilities"]["drop"], json!(["ALL"])); + assert!(c.get("ports").is_none(), "nothing connects to it"); + assert!(c["args"].as_array().unwrap().contains(&json!("http2"))); + assert_eq!(d["metadata"]["namespace"], NS); + assert_eq!(system::tunnel_budget()["spec"]["minAvailable"], 1); + let s = system::tunnel_secret("c1744f8b-faa1-48a4-9e5c-02ac921467fa", "tok"); + assert_eq!(s["metadata"]["labels"][system::TUNNEL_ID_LABEL], "c1744f8b-faa1-48a4-9e5c-02ac921467fa"); + // The write role covers Deployments, Secrets and budgets in pyo-system. + let roles = json!(objects(false)).to_string(); + assert!(roles.contains("poddisruptionbudgets")); + } + #[test] fn the_public_nat_service_is_pinned() { let policy = admission("w", "g"); diff --git a/crates/pyo-proto/src/system.rs b/crates/pyo-proto/src/system.rs index f91de332..1b2041e6 100644 --- a/crates/pyo-proto/src/system.rs +++ b/crates/pyo-proto/src/system.rs @@ -1290,7 +1290,8 @@ pub const OTHER_VISITOR_HEADERS: [&str; 3] = ["x-real-ip", "x-client-ip", "forwa /// itself on every request it passes on. pub fn cdn_own_headers(cdn: &str) -> &'static [&'static str] { match cdn { - "cloudflare" => &["cf-connecting-ip", "cf-connecting-ipv6"], + // The tunnel's connectors pass on what Cloudflare set. + "cloudflare" | TUNNEL_CDN => &["cf-connecting-ip", "cf-connecting-ipv6"], _ => &[], } } @@ -2413,3 +2414,157 @@ mod tests { assert_eq!(cel_literal(&json!("a\nb\\c")), "'a\\nb\\\\c'"); } } + +// ── Cloudflare Tunnel ────────────────────────────────────────────────────── +// +// A cluster's websites through Cloudflare with no open ports +// (docs/cloudflare-tunnel.md). The agent runs the connector (cloudflared) +// in pyo-system with the tunnel's token, and points it at +// `TUNNEL_ORIGIN_SERVICE`, its own Service in front of the proxies' +// HTTPS listener. Tunnel domains' listeners trust X-Forwarded-For only from +// the connector's pods (a client policy labelled [`TUNNEL_CDN`]). + +/// cloudflared, by digest (2026.10.7), as Pyo Cloud runs it. Renovate keeps +/// it current. +pub const CLOUDFLARED_IMAGE: &str = "cloudflare/cloudflared@sha256:4955524aeaa379e154023d5a027c250f7b35041a2e7e950cf13f144bc9b9c5ba"; +/// The connector's Deployment, Secret and disruption budget in pyo-system. +pub const TUNNEL_NAME: &str = "pyo-tunnel"; +/// The label on its pods (and the selector). +pub const TUNNEL_APP: &str = "pyo-tunnel"; +/// The Secret's label with the tunnel id its token is for. +pub const TUNNEL_ID_LABEL: &str = "pyo.dev/tunnel-id"; +/// The Secret's key with the token. +pub const TUNNEL_TOKEN_KEY: &str = "token"; +/// Connectors: two, spread across servers where it can. +pub const TUNNEL_REPLICAS: i32 = 2; +/// Where cloudflared serves `/ready` (nothing reaches it: pyo-system +/// denies ingress). +pub const TUNNEL_METRICS_PORT: i32 = 2000; +/// The Service cloudflared sends requests to: the proxies' HTTPS. +pub const TUNNEL_ORIGIN_SERVICE: &str = "pyo-tunnel-origin"; +/// The label on a service's client policy for its tunnel listeners +/// ([`CDN_LABEL`]): not a CDN users pick (`firewall::BEHIND`). +pub const TUNNEL_CDN: &str = "tunnel"; +/// The Service that keeps public TCP and UDP ports on the servers in +/// tunnel mode, when the proxies' own Service isn't published. +pub const PUBLIC_PORTS_SERVICE: &str = "pyo-public-ports"; + +/// The connector's token, labelled with its tunnel. +pub fn tunnel_secret(tunnel_id: &str, token: &str) -> Value { + json!({ + "apiVersion": "v1", "kind": "Secret", + "metadata": { "name": TUNNEL_NAME, "namespace": crate::rbac::NS, "labels": { "app.kubernetes.io/managed-by": "pyo", TUNNEL_ID_LABEL: tunnel_id } }, + "type": "Opaque", + "stringData": { TUNNEL_TOKEN_KEY: token }, + }) +} + +/// The connector: cloudflared over HTTP/2 (QUIC is often blocked, and its +/// fallback is slow enough that the probe restarts it first), with no +/// service account token, non-root, read only, no capabilities. Never on +/// build-only servers, spread across servers where it can be. +pub fn tunnel_deployment(image: &str) -> Value { + let app = json!({ "app.kubernetes.io/name": TUNNEL_APP }); + let probe = json!({ "httpGet": { "path": "/ready", "port": TUNNEL_METRICS_PORT } }); + json!({ + "apiVersion": "apps/v1", "kind": "Deployment", + "metadata": { "name": TUNNEL_NAME, "namespace": crate::rbac::NS, "labels": { "app.kubernetes.io/name": TUNNEL_APP, "app.kubernetes.io/managed-by": "pyo" } }, + "spec": { + "replicas": TUNNEL_REPLICAS, + "selector": { "matchLabels": app }, + "strategy": { "type": "RollingUpdate", "rollingUpdate": { "maxSurge": 1, "maxUnavailable": 0 } }, + "template": { + "metadata": { "labels": app }, + "spec": { + "automountServiceAccountToken": false, + "affinity": gateway_affinity(), + "topologySpreadConstraints": [{ "maxSkew": 1, "topologyKey": "kubernetes.io/hostname", "whenUnsatisfiable": "ScheduleAnyway", "labelSelector": { "matchLabels": app } }], + "securityContext": { "runAsNonRoot": true, "runAsUser": 65532, "seccompProfile": { "type": "RuntimeDefault" } }, + "containers": [{ + "name": "cloudflared", + "image": image, + "args": ["tunnel", "--no-autoupdate", "--protocol", "http2", "--metrics", format!("0.0.0.0:{TUNNEL_METRICS_PORT}"), "--loglevel", "info", "run"], + "env": [{ "name": "TUNNEL_TOKEN", "valueFrom": { "secretKeyRef": { "name": TUNNEL_NAME, "key": TUNNEL_TOKEN_KEY } } }], + "readinessProbe": { "httpGet": probe["httpGet"], "periodSeconds": 10 }, + "livenessProbe": { "httpGet": probe["httpGet"], "initialDelaySeconds": 60, "periodSeconds": 30, "failureThreshold": 6 }, + "resources": { "requests": { "cpu": "10m", "memory": "32Mi" }, "limits": { "memory": "128Mi" } }, + "securityContext": { "allowPrivilegeEscalation": false, "readOnlyRootFilesystem": true, "capabilities": { "drop": ["ALL"] } }, + }], + }, + }, + }, + }) +} + +/// One connector stays up through a server's drain or a rollout. +pub fn tunnel_budget() -> Value { + json!({ + "apiVersion": "policy/v1", "kind": "PodDisruptionBudget", + "metadata": { "name": TUNNEL_NAME, "namespace": crate::rbac::NS, "labels": { "app.kubernetes.io/managed-by": "pyo" } }, + "spec": { "minAvailable": 1, "selector": { "matchLabels": { "app.kubernetes.io/name": TUNNEL_APP } } }, + }) +} + +/// The origin Service's one port: HTTPS onto the proxies' 443 listener. +pub fn tunnel_origin_ports() -> Value { + json!([{ "name": "https", "port": 443, "targetPort": 10443, "protocol": "TCP" }]) +} + +/// The Service cloudflared sends requests to, inside the cluster only. +pub fn tunnel_origin_service() -> Value { + json!({ + "apiVersion": "v1", "kind": "Service", + "metadata": { "name": TUNNEL_ORIGIN_SERVICE, "namespace": GATEWAY_NS, "labels": { "app.kubernetes.io/managed-by": "pyo" } }, + "spec": { "type": "ClusterIP", "selector": proxy_pods()["matchLabels"], "ports": tunnel_origin_ports() }, + }) +} + +/// Fields the API server fills in on a LoadBalancer Service with +/// externalTrafficPolicy Local, besides [`TAILNET_WEB_DEFAULTED`]. +pub const LOAD_BALANCER_DEFAULTED: [&str; 2] = ["allocateLoadBalancerNodePorts", "healthCheckNodePort"]; + +/// Public TCP and UDP ports in tunnel mode: a LoadBalancer Service onto +/// the proxies for these (protocol, public port), and nothing else. The +/// visitor's own address reaches the proxy (externalTrafficPolicy Local). +/// None without ports. +pub fn public_ports_service(ports: &[(String, i32)]) -> Option { + if ports.is_empty() { + return None; + } + let mut ports: Vec<(String, i32)> = ports.to_vec(); + ports.sort(); + ports.dedup(); + let list: Vec = ports + .iter() + .map(|(proto, port)| { + json!({ "name": format!("{}-{port}", proto.to_lowercase()), "port": port, "targetPort": crate::proxy_listen_port(*port), "protocol": proto }) + }) + .collect(); + Some(json!({ + "apiVersion": "v1", "kind": "Service", + "metadata": { "name": PUBLIC_PORTS_SERVICE, "namespace": GATEWAY_NS, "labels": { "app.kubernetes.io/managed-by": "pyo" } }, + "spec": { "type": "LoadBalancer", "externalTrafficPolicy": "Local", "selector": proxy_pods()["matchLabels"], "ports": list }, + })) +} + +/// A service's client policy for its tunnel listeners. +pub fn tunnel_policy_name(base: &str) -> String { + format!("{base}-{TUNNEL_CDN}") +} + +/// Addresses as a client policy trusts them: each one alone (/32, /128), +/// sorted, deduped. +pub fn host_cidrs(ips: &[String]) -> Vec { + let mut out: Vec = ips + .iter() + .filter_map(|ip| ip.parse::().ok()) + .map(|ip| match ip { + std::net::IpAddr::V4(v4) => format!("{v4}/32"), + std::net::IpAddr::V6(v6) => format!("{v6}/128"), + }) + .collect(); + out.sort(); + out.dedup(); + out.truncate(MAX_TRUSTED_CIDRS); + out +} From 4db8b6fce575f9b01c726b439a3517d243285895 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:12:47 +0700 Subject: [PATCH 025/139] feat(agent): run the cloudflare tunnel connector The agent keeps the tunnel token in pyo-system/pyo-tunnel, runs two cloudflared connectors with it, reports them with each heartbeat and removes them when the tunnel goes. The connectors' pod addresses are the only ones tunnel listeners trust for the visitor's address, and the policies follow when pods move. Tunnel domains get routes of their own: while switching both paths answer, and once switched direct connections get 403 and the plain HTTP route goes. A cf-visitor rule sends visitors Cloudflare took over plain HTTP to HTTPS. In tunnel mode public TCP and UDP ports go out through a Service of their own. An install older than the agent refuses these objects: what runs is kept, the deploy's other routes go on, and it's reported until the install changes. --- crates/pyo-agent/src/actions.rs | 4 +- crates/pyo-agent/src/gateway.rs | 459 ++++++++++++++++++++++++++++- crates/pyo-agent/src/main.rs | 18 +- crates/pyo-agent/src/observe.rs | 3 + crates/pyo-agent/src/tunnel.rs | 499 ++++++++++++++++++++++++++++++++ 5 files changed, 971 insertions(+), 12 deletions(-) create mode 100644 crates/pyo-agent/src/tunnel.rs diff --git a/crates/pyo-agent/src/actions.rs b/crates/pyo-agent/src/actions.rs index e6ebe393..d291e896 100644 --- a/crates/pyo-agent/src/actions.rs +++ b/crates/pyo-agent/src/actions.rs @@ -165,7 +165,9 @@ pub async fn run(agent: &Agent, command: Command) -> CommandResult { | Command::TailscaleCheckName { .. } | Command::TailscaleRemove { .. } | Command::SandboxCall(_) - | Command::SyncRegistryTokens(_) => { + | Command::SyncRegistryTokens(_) + | Command::TunnelSet { .. } + | Command::TunnelRemove {} => { unreachable!("handled by the command loop") } }; diff --git a/crates/pyo-agent/src/gateway.rs b/crates/pyo-agent/src/gateway.rs index 0bd33c3c..67efd64b 100644 --- a/crates/pyo-agent/src/gateway.rs +++ b/crates/pyo-agent/src/gateway.rs @@ -349,7 +349,7 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { for p in &ports { let hosts: Vec<&str> = secure .iter() - .filter(|d| d.port_name == *p) + .filter(|d| d.port_name == *p && !d.via_tunnel()) .map(|d| d.hostname.as_str()) .collect(); if !hosts.is_empty() { @@ -358,14 +358,44 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { "spec": { "parentRefs": [{ "name": base }], "hostnames": hosts, "rules": [web_rule(p)] }, })); } + // Through the Cloudflare Tunnel: routes of their own, so the + // gate (once switched) and the cf-visitor redirect apply to + // those names only. Grouped by switched or not, and by redirect. + for (only, redirect) in [(true, true), (true, false), (false, true), (false, false)] { + let hosts: Vec<&str> = secure + .iter() + .filter(|d| { + d.port_name == *p + && d.via_tunnel() + && d.tunnel_only() == only + && d.redirect_https == redirect + }) + .map(|d| d.hostname.as_str()) + .collect(); + if hosts.is_empty() { + continue; + } + let mut rules = vec![]; + if redirect { + rules.push(tunnel_redirect_rule()); + } + rules.push(web_rule(p)); + out.objects.push(json!({ + "apiVersion": "gateway.networking.k8s.io/v1", "kind": "HTTPRoute", + "metadata": meta(&tunnel_route_name(&base, only, redirect, p)), + "spec": { "parentRefs": [{ "name": base }], "hostnames": hosts, "rules": rules }, + })); + } } } // HTTP, on the shared :80 listener: redirects, then plain HTTP. let http_parent = json!([{ "name": HTTP_GATEWAY, "sectionName": "http" }]); + // A domain switched to the tunnel has no plain HTTP route: nothing + // reaches it directly any more (cloudflared speaks HTTPS). let redirect: Vec<&str> = secure .iter() - .filter(|d| d.redirect_https) + .filter(|d| d.redirect_https && !d.tunnel_only()) .map(|d| d.hostname.as_str()) .collect(); if !redirect.is_empty() { @@ -381,6 +411,7 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { .filter(reachable) .filter(public) .filter(|d| d.port_name == *p && !(!d.tls.is_empty() && d.redirect_https)) + .filter(|d| !d.tunnel_only()) .map(|d| d.hostname.as_str()) .collect(); if !hosts.is_empty() { @@ -428,11 +459,17 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { .filter(|n| !n.ends_with("-redirect")) .map(str::to_owned) .collect(); + // Switched to the tunnel: only its connectors get through. + let tunnel_auth = Some(pyo_proto::firewall::tunnel_authorization(&fw)); for name in names { - let https = name.starts_with(&format!("{base}-https-")); + let tunnel_on = name.starts_with(&format!("{base}-tunnel-")); + let https = name.starts_with(&format!("{base}-https-")) + || name.starts_with(&format!("{base}-switching-")); let on_tailnet = name.starts_with(system::TAILNET_ROUTE_PREFIX); let (authorization, rate) = if on_tailnet { (&None, rate.as_ref()) + } else if tunnel_on { + (&tunnel_auth, rate.as_ref()) } else if https { (&https_auth, rate.as_ref()) } else { @@ -468,10 +505,11 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { // settings (origin pull, PROXY protocol) are filled in as the cluster // has them when it's applied (`apply`). Without the CDN's ranges // nothing is trusted, so the CDN check above refuses everyone. + let direct: Vec<&&DomainSpec> = secure.iter().filter(|d| !d.via_tunnel()).collect(); if let Some((cdn, ranges)) = fw.behind_ranges().filter(|(_, r)| !r.is_empty()) - && !secure.is_empty() + && !direct.is_empty() { - let sections: Vec = secure + let sections: Vec = direct .iter() .map(|d| format!("h-{}", host_hash(&d.hostname))) .collect(); @@ -484,6 +522,32 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { })); } + // Through the tunnel: those listeners read the visitor from + // X-Forwarded-For only on connections from the tunnel's connectors + // (their pods' addresses, filled in when it's applied). While a domain + // switches, a service behind a CDN also still trusts the CDN, which + // reaches it directly until the record moves. + let tunneled: Vec<&&DomainSpec> = secure.iter().filter(|d| d.via_tunnel()).collect(); + if !tunneled.is_empty() { + let sections: Vec = tunneled + .iter() + .map(|d| format!("h-{}", host_hash(&d.hostname))) + .collect(); + let switching = tunneled.iter().any(|d| !d.tunnel_only()); + let extra: Vec = fw + .behind_ranges() + .filter(|_| switching) + .map(|(_, r)| r) + .unwrap_or_default(); + let name = system::tunnel_policy_name(&base); + let mut m = meta(&name); + m["labels"][system::CDN_LABEL] = json!(system::TUNNEL_CDN); + out.objects.push(json!({ + "apiVersion": "gateway.envoyproxy.io/v1alpha1", "kind": "ClientTrafficPolicy", "metadata": m, + "spec": system::cdn_client_policy_spec(system::TUNNEL_CDN, &base, §ions, system::WebSettings::default(), &pyo_proto::firewall::trusted_or_nothing(extra)), + })); + } + // The WAF: with the service's WAF on, its routes go through the // processor first (its custom rules, then the OWASP rules), failing // closed in block mode. The service's WAF rides on the policy, and the @@ -525,6 +589,30 @@ pub fn route_objects(spec: &DeploySpec) -> Routes { pub use system::WAF_ANNOTATION; +/// A service's route for its tunnel domains on a port: switched ("tunnel") +/// or switching, with or without the redirect to HTTPS ("-plain"). +pub fn tunnel_route_name(base: &str, only: bool, redirect: bool, port: &str) -> String { + format!( + "{base}-{}{}-{port}", + if only { "tunnel" } else { "switching" }, + if redirect { "" } else { "-plain" } + ) +} + +/// The value of `cf-visitor` Cloudflare sets on a request a visitor made +/// over plain HTTP. +pub const CF_VISITOR_HTTP: &str = r#"{"scheme":"http"}"#; + +/// A tunnel route's first rule with the redirect to HTTPS on: a request +/// Cloudflare took over plain HTTP (its `cf-visitor` says so) goes to +/// HTTPS, whatever the zone's own settings. +pub fn tunnel_redirect_rule() -> Value { + json!({ + "matches": [{ "headers": [{ "type": "Exact", "name": "cf-visitor", "value": CF_VISITOR_HTTP }] }], + "filters": [{ "type": "RequestRedirect", "requestRedirect": { "scheme": "https", "statusCode": 301 } }], + }) +} + /// Marks a UDP route with the address ranges its port lets in, for the /// network policy on the proxy's pods ("" when open), and with where the /// proxy listens for it. @@ -677,12 +765,21 @@ pub async fn apply( notes.push(p.clone()); } let mut r = route_objects(spec); - // Behind a CDN: its HTTPS client policy as the cluster's websites have - // theirs otherwise. - if let Some(o) = r.objects.iter_mut().find(|o| { + // Behind a CDN, or through the tunnel: its HTTPS client policy as the + // cluster's websites have theirs otherwise. The tunnel's trusts its + // connectors' pods as they are now. + let mut w = None; + for o in r.objects.iter_mut().filter(|o| { o["kind"] == "ClientTrafficPolicy" && o["metadata"]["labels"][system::CDN_LABEL].is_string() }) { - let w = web_settings(client).await?; + let w = match w { + Some(w) => w, + None => *w.insert(web_settings(client).await?), + }; + if o["metadata"]["labels"][system::CDN_LABEL] == system::TUNNEL_CDN { + let pods = crate::tunnel::trusted_now(); + set_trusted(o, |have| with_pods(have, &[], &pods)); + } rewrite_cdn_policy(o, w); } // New public TCP and UDP ports wait for the servers to free them (a port @@ -770,8 +867,17 @@ pub async fn apply( } else { api.patch(&name, &pp(), &Patch::Apply(o)).await.map(|_| ()) }; + let tunnel_policy = kind == "ClientTrafficPolicy" + && o["metadata"]["labels"][system::CDN_LABEL] == system::TUNNEL_CDN; match written { Ok(()) => {} + // An install older than this agent doesn't know the tunnel's + // policy: the rest of the routes still go on, and it's said. + Err(e) if tunnel_policy && crate::refused::is_refusal(&e) => { + crate::tunnel::refused_now(&e); + notes.push(crate::tunnel::REFUSED.into()); + continue; + } Err(kube::Error::Api(e)) if e.code == 404 && kind == "Certificate" => { notes.push("cert-manager is still being installed on this cluster. HTTPS starts with a later deploy.".into()); } @@ -1778,6 +1884,103 @@ pub fn public_nat_ips(nodes: &[k8s_openapi::api::core::v1::Node]) -> Vec static PUBLIC_NAT_REFUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// The gateway's public TCP and UDP ports (its `-ports` Gateways' +/// listeners) as (protocol, port). +pub fn l4_ports(gateways: &[DynamicObject]) -> Vec<(String, i32)> { + let mut out: Vec<(String, i32)> = gateways + .iter() + .filter(|g| g.labels().get(GATEWAY_LABEL).map(String::as_str) == Some(system::L4_GATEWAY)) + .flat_map(|g| { + g.data["spec"]["listeners"] + .as_array() + .cloned() + .unwrap_or_default() + }) + .filter_map(|l| { + Some(( + l["protocol"].as_str()?.to_owned(), + i32::try_from(l["port"].as_i64()?).ok()?, + )) + }) + .collect(); + out.sort(); + out.dedup(); + out +} + +static PUBLIC_PORTS_REFUSED: AtomicBool = AtomicBool::new(false); + +/// In tunnel mode with public TCP and UDP ports kept, the proxies' own +/// Service isn't published, so their ports go out through one of their +/// own (system.rs `PUBLIC_PORTS_SERVICE`). Off, or with no such port: none. +/// From each heartbeat's reply. +pub async fn set_public_ports_service(client: &Client, on: bool) { + let services: Api = + Api::namespaced(client.clone(), GATEWAY_NS); + let ports = if on { + match api_of(client, "Gateway").list(&ListParams::default()).await { + Ok(l) => l4_ports(&l.items), + Err(e) => { + tracing::warn!(error = %e, "couldn't list the gateway's ports"); + return; + } + } + } else { + vec![] + }; + let current = match services.get_opt(system::PUBLIC_PORTS_SERVICE).await { + Ok(s) => s, + Err(e) => { + tracing::warn!(error = %e, "couldn't read the public ports Service"); + return; + } + }; + match system::public_ports_service(&ports) { + None if current.is_none() => {} + None => match services + .delete(system::PUBLIC_PORTS_SERVICE, &DeleteParams::default()) + .await + { + Ok(_) => tracing::info!("no public TCP or UDP ports in tunnel mode"), + Err(e) => tracing::warn!(error = %e, "couldn't remove the public ports Service"), + }, + Some(want) => { + let have = current + .and_then(|s| s.spec) + .and_then(|s| s.ports) + .map(|p| serde_json::to_value(p).unwrap_or_default()); + let same = have.as_ref().is_some_and(|h| { + let strip = |v: &Value| -> Vec { + v.as_array() + .into_iter() + .flatten() + .map(|p| json!([p["name"], p["port"], p["targetPort"], p["protocol"]])) + .collect() + }; + strip(h) == strip(&want["spec"]["ports"]) + }); + if same { + return; + } + match services + .patch(system::PUBLIC_PORTS_SERVICE, &pp(), &Patch::Apply(&want)) + .await + { + Ok(_) => { + PUBLIC_PORTS_REFUSED.store(false, Ordering::Relaxed); + tracing::info!(?ports, "public TCP and UDP ports published in tunnel mode"); + } + Err(e) if crate::refused::is_refusal(&e) => { + if !PUBLIC_PORTS_REFUSED.swap(true, Ordering::Relaxed) { + tracing::warn!(error = %e, "couldn't publish the public ports in tunnel mode (run the cluster's connect command)"); + } + } + Err(e) => tracing::warn!(error = %e, "couldn't write the public ports Service"), + } + } + } +} + /// The cluster's own requests to the public IPs behind the cloud's NAT go /// to the proxies (system.rs `PUBLIC_NAT_SERVICE`), while it takes public /// traffic (from each heartbeat's reply): the Service written or removed @@ -1998,11 +2201,67 @@ async fn write_client_policy(api: &Api, name: &str, o: &Value) -> /// A service's CDN client policy with these websites' settings, its CDN, /// listeners and trusted ranges as they are. -fn rewrite_cdn_policy(o: &mut Value, w: system::WebSettings) { +/// A client policy's trusted ranges, changed by `f`. +fn set_trusted(o: &mut Value, f: impl FnOnce(Vec) -> Vec) { + let have: Vec = o["spec"]["clientIPDetection"]["xForwardedFor"]["trustedCIDRs"] + .as_array() + .into_iter() + .flatten() + .filter_map(|c| c.as_str().map(str::to_owned)) + .collect(); + o["spec"]["clientIPDetection"]["xForwardedFor"]["trustedCIDRs"] = json!(f(have)); +} + +/// A tunnel policy's trusted ranges with the connectors' pods now `pods` +/// instead of `old`: the rest (a CDN's ranges while a domain switches) +/// stays. Never empty. +pub fn with_pods(have: Vec, old: &[String], pods: &[String]) -> Vec { + let nothing = pyo_proto::firewall::trusted_or_nothing(vec![]); + let mut out: Vec = have + .into_iter() + .filter(|c| !old.contains(c) && !nothing.contains(c)) + .chain(pods.iter().cloned()) + .collect(); + out.truncate(system::MAX_TRUSTED_CIDRS); + pyo_proto::firewall::trusted_or_nothing(out) +} + +/// The connectors' pods moved (`old` → `pods`): every tunnel policy +/// trusts the new ones. Refused by an older install: said, and kept. +pub async fn set_tunnel_pods(client: &Client, old: &[String], pods: &[String]) -> anyhow::Result<()> { + let policies = api_of(client, "ClientTrafficPolicy"); + let found = policies + .list(&ListParams::default().labels(&format!("{}={}", system::CDN_LABEL, system::TUNNEL_CDN))) + .await?; + for p in found { + let name = p.name_any(); + let mut o = json!({ + "apiVersion": "gateway.envoyproxy.io/v1alpha1", "kind": "ClientTrafficPolicy", + "metadata": { "name": name, "namespace": GATEWAY_NS, "labels": p.labels() }, + "spec": p.data["spec"].clone(), + }); + set_trusted(&mut o, |have| with_pods(have, old, pods)); + if let Err(e) = write_client_policy(&policies, &name, &o).await { + if crate::refused::is_refusal(&e) { + crate::tunnel::refused_now(&e); + continue; + } + return Err(e.into()); + } + } + Ok(()) +} + +fn rewrite_cdn_policy(o: &mut Value, mut w: system::WebSettings) { let cdn = o["metadata"]["labels"][system::CDN_LABEL] .as_str() .unwrap_or("") .to_owned(); + // cloudflared has no origin pull certificate: the tunnel's listeners + // never ask for one (only its connectors reach them anyway). + if cdn == system::TUNNEL_CDN { + w.origin_pull = false; + } let spec = &o["spec"]; let gateway = spec["targetRefs"][0]["name"] .as_str() @@ -2404,6 +2663,7 @@ mod tests { String::new() }, redirect_https: redirect, + tunnel: String::new(), } } @@ -2868,6 +3128,185 @@ mod tests { ); } + #[test] + fn tunnel_domains_switch_then_close_the_direct_path() { + let tunnel = |host: &str, state: &str, redirect: bool| DomainSpec { + tunnel: state.into(), + ..domain(host, "http", "custom", redirect) + }; + let s = spec(vec![ + domain("direct.example.com", "http", "letsencrypt", true), + tunnel("moving.example.com", pyo_proto::TUNNEL_SWITCHING, true), + tunnel("done.example.com", pyo_proto::TUNNEL_ON, true), + tunnel("raw.example.com", pyo_proto::TUNNEL_ON, false), + ]); + let r = route_objects(&s); + let hosts = |name: &str| find(&r, "HTTPRoute", name)["spec"]["hostnames"].clone(); + // Each kind on a route of its own. + assert_eq!(hosts("shop-web-https-http"), json!(["direct.example.com"])); + assert_eq!(hosts("shop-web-switching-http"), json!(["moving.example.com"])); + assert_eq!(hosts("shop-web-tunnel-http"), json!(["done.example.com"])); + assert_eq!(hosts("shop-web-tunnel-plain-http"), json!(["raw.example.com"])); + // The redirect for visitors Cloudflare took over plain HTTP. + let done = find(&r, "HTTPRoute", "shop-web-tunnel-http"); + assert_eq!(done["spec"]["rules"][0], tunnel_redirect_rule()); + assert_eq!( + done["spec"]["rules"][0]["matches"][0]["headers"][0]["value"], + r#"{"scheme":"http"}"# + ); + assert!(done["spec"]["rules"][1]["backendRefs"].is_array()); + let raw = find(&r, "HTTPRoute", "shop-web-tunnel-plain-http"); + assert_eq!(raw["spec"]["rules"].as_array().unwrap().len(), 1); + // Plain HTTP: the switching domain still answers there, the switched ones don't. + let redirect = find(&r, "HTTPRoute", "shop-web-redirect")["spec"]["hostnames"].clone(); + assert_eq!(redirect, json!(["direct.example.com", "moving.example.com"])); + assert!(!r.objects.iter().any(|o| o["kind"] == "HTTPRoute" + && o["spec"]["hostnames"].as_array().is_some_and(|h| h.contains(&json!("done.example.com")) || h.contains(&json!("raw.example.com"))) + && o["spec"]["parentRefs"][0]["name"] == HTTP_GATEWAY)); + // Switched: the gate first, so a direct connection gets 403. + let gate = find(&r, "SecurityPolicy", "shop-web-tunnel-http"); + assert_eq!( + gate["spec"]["authorization"]["rules"][0], + pyo_proto::firewall::behind_gate_rule() + ); + assert!(r.objects.iter().any(|o| o["kind"] == "SecurityPolicy" + && o["metadata"]["name"] == "shop-web-tunnel-plain-http")); + // Switching: no gate, both paths answer. + assert!(!r.objects.iter().any(|o| o["kind"] == "SecurityPolicy" + && o["metadata"]["name"] == "shop-web-switching-http")); + // The tunnel's listeners trust its connectors only (filled in when + // applied), with Cloudflare's own headers kept. + let ctp = find(&r, "ClientTrafficPolicy", "shop-web-tunnel"); + assert_eq!(ctp["metadata"]["labels"][system::CDN_LABEL], system::TUNNEL_CDN); + let sections: Vec = ctp["spec"]["targetRefs"] + .as_array() + .unwrap() + .iter() + .map(|t| t["sectionName"].as_str().unwrap().to_owned()) + .collect(); + let mut want: Vec = ["moving.example.com", "done.example.com", "raw.example.com"] + .iter() + .map(|h| format!("h-{}", host_hash(h))) + .collect(); + want.sort(); + let mut got = sections.clone(); + got.sort(); + assert_eq!(got, want); + assert_eq!( + ctp["spec"]["clientIPDetection"]["xForwardedFor"]["trustedCIDRs"], + json!(["0.0.0.0/32"]) + ); + assert_eq!( + ctp["spec"]["headers"], + system::visitor_headers(&["cf-connecting-ip", "cf-connecting-ipv6"]) + ); + // No direct-domain CDN policy: the service isn't behind one. + assert!(!r.objects.iter().any(|o| o["metadata"]["name"] == "shop-web-cdn")); + } + + #[test] + fn behind_cloudflare_with_tunnel_domains_splits_the_listeners() { + let cf = vec!["173.245.48.0/20".to_owned()]; + let mut s = spec(vec![ + domain("shop.example.com", "http", "letsencrypt", false), + DomainSpec { + tunnel: pyo_proto::TUNNEL_SWITCHING.into(), + ..domain("blog.example.com", "http", "custom", false) + }, + ]); + s.firewall = Some(Firewall { + rules: vec![], + presets: [("cloudflare".to_owned(), cf.clone())].into(), + behind: Some("cloudflare".into()), + }); + let r = route_objects(&s); + let refs = |name: &str| find(&r, "ClientTrafficPolicy", name)["spec"]["targetRefs"].clone(); + assert_eq!( + refs("shop-web-cdn")[0]["sectionName"], + format!("h-{}", host_hash("shop.example.com")) + ); + assert_eq!(refs("shop-web-cdn").as_array().unwrap().len(), 1); + assert_eq!( + refs("shop-web-tunnel")[0]["sectionName"], + format!("h-{}", host_hash("blog.example.com")) + ); + // While it switches, Cloudflare still reaches it directly too. + assert_eq!( + find(&r, "ClientTrafficPolicy", "shop-web-tunnel")["spec"]["clientIPDetection"]["xForwardedFor"]["trustedCIDRs"], + json!(cf) + ); + // Switched: only the connectors. + s.domains[1].tunnel = pyo_proto::TUNNEL_ON.into(); + let r = route_objects(&s); + assert_eq!( + find(&r, "ClientTrafficPolicy", "shop-web-tunnel")["spec"]["clientIPDetection"]["xForwardedFor"]["trustedCIDRs"], + json!(["0.0.0.0/32"]) + ); + // The gate is the tunnel's, not doubled with the service's own. + let rules = find(&r, "SecurityPolicy", "shop-web-tunnel-plain-http")["spec"]["authorization"]["rules"].clone(); + let gates = rules + .as_array() + .unwrap() + .iter() + .filter(|r| **r == pyo_proto::firewall::behind_gate_rule()) + .count(); + assert_eq!(gates, 1); + } + + #[test] + fn tunnel_mode_publishes_the_gateways_own_ports() { + let gw = |name: &str, label: &str, listeners: Value| -> DynamicObject { + serde_json::from_value(json!({ + "apiVersion": "gateway.networking.k8s.io/v1", "kind": "Gateway", + "metadata": { "name": name, "namespace": GATEWAY_NS, "labels": { GATEWAY_LABEL: label } }, + "spec": { "listeners": listeners }, + })) + .unwrap() + }; + let all = [ + gw("shop-db-ports", system::L4_GATEWAY, json!([{ "name": "tcp-5432", "port": 5432, "protocol": "TCP" }, { "name": "udp-27015", "port": 27015, "protocol": "UDP" }])), + gw("shop-mq-ports", system::L4_GATEWAY, json!([{ "name": "tcp-5432", "port": 5432, "protocol": "TCP" }])), + gw("shop-web", "https", json!([{ "name": "h-1", "port": 443, "protocol": "HTTPS" }])), + ]; + assert_eq!( + l4_ports(&all), + [("TCP".to_owned(), 5432), ("UDP".to_owned(), 27015)] + ); + } + + #[test] + fn tunnel_policies_follow_the_connectors_pods() { + let old = vec!["10.42.0.5/32".to_owned()]; + let cf = "173.245.48.0/20".to_owned(); + assert_eq!( + with_pods(vec!["0.0.0.0/32".into()], &[], &["10.42.0.9/32".into()]), + ["10.42.0.9/32"] + ); + assert_eq!( + with_pods(vec![cf.clone(), old[0].clone()], &old, &["10.42.1.2/32".into()]), + ["10.42.1.2/32", cf.as_str()] + ); + // No pods: nobody, never anyone. + assert_eq!(with_pods(old.clone(), &old, &[]), ["0.0.0.0/32"]); + } + + /// An install older than the agent refuses the tunnel's client policy: + /// the rest of the deploy still goes on, and it's said. + #[tokio::test] + async fn a_refused_tunnel_policy_leaves_the_rest_of_the_routes() { + let (kube, client) = crate::fakekube::FakeKube::start().await; + kube.admit(|w| { + (w.plural == "clienttrafficpolicies" && w.name.ends_with("-tunnel")).then(|| (403, "clienttrafficpolicies.gateway.envoyproxy.io \"shop-web-tunnel\" is forbidden: ValidatingAdmissionPolicy 'pyo-agent' with binding 'pyo-agent' denied request".into())) + }); + let b = spec(vec![DomainSpec { + tunnel: pyo_proto::TUNNEL_ON.into(), + ..domain("shop.example.com", "http", "selfsigned", true) + }]); + let pyo = PyoApi::new("http://127.0.0.1:9", "t").unwrap(); + let notes = apply(&client, &pyo, &b).await.expect("the routes"); + assert!(notes.contains(&crate::tunnel::REFUSED.to_owned()), "{notes:?}"); + } + #[test] fn behind_cloudflare_routes() { let mut s = spec(vec![ diff --git a/crates/pyo-agent/src/main.rs b/crates/pyo-agent/src/main.rs index 9b8843e5..9034470f 100644 --- a/crates/pyo-agent/src/main.rs +++ b/crates/pyo-agent/src/main.rs @@ -45,6 +45,7 @@ mod tailnet; mod tailscale; mod terminal; mod tls; +mod tunnel; mod traffic; mod trust; mod upgrade; @@ -261,6 +262,7 @@ async fn heartbeat_loop(agent: Agent) { hb.host_proof = agent.api.host_proof(&agent.kube).await; hb.scope = Some(scope::detect(&agent.kube, policy.clone()).await); hb.tailnet = tailnet::statuses(&agent.kube).await; + hb.tunnel = Some(tunnel::report(&agent.kube).await); match agent.api.heartbeat(&hb).await { Ok(_) if policy.read_only => {} Ok(reply) => { @@ -270,9 +272,14 @@ async fn heartbeat_loop(agent: Agent) { if let Some(on) = reply.public_traffic { gateway::set_public_traffic(&agent.kube, on).await; gateway::set_public_nat(&agent.kube, on).await; - if let Err(e) = rollout::set_public_ports(&agent.kube, on).await { + // TCP and UDP ports: with public traffic, or kept + // in tunnel mode (then the gateway's go through a + // Service of their own). + let ports = reply.public_ports.unwrap_or(on); + if let Err(e) = rollout::set_public_ports(&agent.kube, ports).await { tracing::warn!(error = %format!("{e:#}"), "couldn't change public ports"); } + gateway::set_public_ports_service(&agent.kube, ports && !on).await; } if let Some(address) = &reply.free_domain_address { gateway::set_tailnet_web(&agent.kube, address == "tailscale").await; @@ -281,6 +288,9 @@ async fn heartbeat_loop(agent: Agent) { if let Some(t) = &reply.tailnet { tailnet::apply(&agent.kube, t, agent.api.same_cluster()).await; } + if let Some(w) = &reply.tunnel { + tunnel::follow(&agent.kube, w).await; + } if let Some(p) = &reply.public_dashboard && agent.api.same_cluster() { @@ -413,6 +423,8 @@ fn ordered_keys(c: &Command) -> Vec { | Command::TailscaleSync(_) | Command::TailscaleRemove { .. } => vec!["tailscale".to_owned()], Command::SyncRegistryTokens(_) => vec!["registry-tokens".to_owned()], + // The tunnel's token and connector: in the order sent. + Command::TunnelSet { .. } | Command::TunnelRemove {} => vec!["tunnel".to_owned()], _ => vec![], }; keys.sort(); @@ -604,6 +616,8 @@ async fn run_command(agent: Agent, envelope: CommandEnvelope) { tailscale::run_remove(&agent.kube, &names, &marks).await } Command::SandboxCall(c) => tailscale::sandbox::run(&c).await, + Command::TunnelSet { tunnel_id, token } => tunnel::set(&agent.kube, &tunnel_id, &token).await, + Command::TunnelRemove {} => tunnel::remove(&agent.kube).await, // Answered before switching: the switch stops this process. Command::UpdateAgent { image } => { let result = match upgrade::check_agent_image(&agent.kube, &image).await { @@ -725,6 +739,8 @@ fn command_kind(c: &Command) -> &'static str { Command::TailscaleRemove { .. } => "tailscale_remove", Command::SandboxCall(_) => "sandbox_call", Command::SyncRegistryTokens(_) => "sync_registry_tokens", + Command::TunnelSet { .. } => "tunnel_set", + Command::TunnelRemove {} => "tunnel_remove", Command::CheckDatabaseImport(_) => "check_database_import", Command::ListSnapshots(_) => "list_snapshots", Command::ForgetSnapshot(_) => "forget_snapshot", diff --git a/crates/pyo-agent/src/observe.rs b/crates/pyo-agent/src/observe.rs index e3a83aeb..43f7776d 100644 --- a/crates/pyo-agent/src/observe.rs +++ b/crates/pyo-agent/src/observe.rs @@ -880,6 +880,8 @@ pub async fn heartbeat(client: &Client) -> anyhow::Result { database_metrics: crate::dbmetrics::report(&pods, &m.pods, &k.volumes), tailnet: Vec::new(), routes_version: crate::gateway::routes_version().into(), + // Filled in by the heartbeat loop (tunnel.rs). + tunnel: None, }) } @@ -985,6 +987,7 @@ async fn capabilities( waf_rejected, waf_active, tailnet_web_ips: tailnet_web_ips(client).await, + tunnel: true, } } diff --git a/crates/pyo-agent/src/tunnel.rs b/crates/pyo-agent/src/tunnel.rs new file mode 100644 index 00000000..5495227b --- /dev/null +++ b/crates/pyo-agent/src/tunnel.rs @@ -0,0 +1,499 @@ +//! The cluster's Cloudflare Tunnel connector (docs/cloudflare-tunnel.md §7): +//! cloudflared in pyo-system with the tunnel's token, pointed at Pyo +//! Gateway's HTTPS through `system::TUNNEL_ORIGIN_SERVICE`. Pyo's control +//! plane holds the Cloudflare account. The agent only ever gets the +//! tunnel's own token (`TunnelSet`), keeps it in a Secret labelled with the +//! tunnel's id, and follows what each heartbeat reply wants. +//! +//! The connectors' pod addresses are the only ones the tunnel listeners +//! trust to say who the visitor is (gateway.rs, the `tunnel` client +//! policies). They're looked at with each heartbeat and the policies follow. +//! +//! A cluster whose install is older than this agent refuses these objects: +//! what runs is kept, nothing more is written until the install changes, +//! and the heartbeat says so (`TunnelReport::refused`). + +use std::sync::{ + Mutex, + atomic::{AtomicBool, Ordering}, +}; + +use k8s_openapi::api::{ + apps::v1::Deployment, + core::v1::{Pod, Secret, Service}, + policy::v1::PodDisruptionBudget, +}; +use kube::{ + Api, Client, ResourceExt, + api::{DeleteParams, ListParams, Patch, PatchParams}, +}; +use pyo_proto::{CommandResult, TunnelPod, TunnelReport, TunnelWanted, rbac, system}; +use serde_json::json; + +use crate::{MANAGER, failed}; + +/// Said when the cluster's install refuses the tunnel's objects. +pub const REFUSED: &str = "This cluster's install is older than Pyo's. Run the command under Refresh this cluster in the cluster's settings to use Cloudflare Tunnel."; + +/// What the agent keeps between heartbeats. +#[derive(Default)] +struct Kept { + /// The connectors' pod addresses the tunnel policies trust now. + pods: Vec, + /// The connector's objects as last applied (their JSON). + applied: String, + /// The install stamp a write was refused on. + refused_on: Option, +} + +static KEPT: Mutex = Mutex::new(Kept { + pods: vec![], + applied: String::new(), + refused_on: None, +}); +static REFUSED_NOW: AtomicBool = AtomicBool::new(false); + +fn kept() -> std::sync::MutexGuard<'static, Kept> { + KEPT.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The connectors' pod addresses, as the tunnel policies trust them. +pub fn trusted_now() -> Vec { + kept().pods.clone() +} + +/// The install refused a tunnel object: said once, and reported. +pub fn refused_now(e: &kube::Error) { + if !REFUSED_NOW.swap(true, Ordering::Relaxed) { + tracing::warn!(error = %e, "{REFUSED}"); + } +} + +fn pp() -> PatchParams { + PatchParams::apply(MANAGER).force() +} + +/// Tunnel ids are UUIDs (they go into a label). +pub fn id_ok(id: &str) -> bool { + id.len() == 36 + && id.bytes().enumerate().all(|(i, b)| match i { + 8 | 13 | 18 | 23 => b == b'-', + _ => b.is_ascii_hexdigit(), + }) +} + +fn secrets(client: &Client) -> Api { + Api::namespaced(client.clone(), rbac::NS) +} + +/// The tunnel the token here is for, from its Secret's label. +async fn token_for(client: &Client) -> kube::Result> { + Ok(secrets(client) + .get_opt(system::TUNNEL_NAME) + .await? + .and_then(|s| s.labels().get(system::TUNNEL_ID_LABEL).cloned())) +} + +/// The connector's objects, as written. +fn connector() -> [serde_json::Value; 3] { + [ + system::tunnel_deployment(system::CLOUDFLARED_IMAGE), + system::tunnel_budget(), + system::tunnel_origin_service(), + ] +} + +/// Write the connector's objects (only when they changed since the last +/// write here, or are missing). +async fn apply_connector(client: &Client, force: bool) -> kube::Result<()> { + let objects = connector(); + let text = serde_json::to_string(&objects).unwrap_or_default(); + let deployments: Api = Api::namespaced(client.clone(), rbac::NS); + let there = deployments.get_opt(system::TUNNEL_NAME).await?.is_some(); + if !force && there && kept().applied == text { + return Ok(()); + } + let [d, b, s] = &objects; + deployments + .patch(system::TUNNEL_NAME, &pp(), &Patch::Apply(d)) + .await?; + Api::::namespaced(client.clone(), rbac::NS) + .patch(system::TUNNEL_NAME, &pp(), &Patch::Apply(b)) + .await?; + Api::::namespaced(client.clone(), system::GATEWAY_NS) + .patch(system::TUNNEL_ORIGIN_SERVICE, &pp(), &Patch::Apply(s)) + .await?; + kept().applied = text; + Ok(()) +} + +/// A refused write: kept until the install changes. +async fn refused(client: &Client, e: &kube::Error) { + refused_now(e); + kept().refused_on = Some(crate::refused::install_stamp(client).await); +} + +/// `TunnelSet`: keep the token and run the connector with it. +pub async fn set(client: &Client, tunnel_id: &str, token: &str) -> CommandResult { + if !id_ok(tunnel_id) { + return failed("That isn't a tunnel id."); + } + if token.is_empty() || token.len() > 4096 || !token.bytes().all(|b| b.is_ascii_graphic()) { + return failed("That isn't a tunnel token."); + } + let written = async { + secrets(client) + .patch( + system::TUNNEL_NAME, + &pp(), + &Patch::Apply(system::tunnel_secret(tunnel_id, token)), + ) + .await?; + apply_connector(client, true).await + } + .await; + match written { + Ok(()) => { + REFUSED_NOW.store(false, Ordering::Relaxed); + kept().refused_on = None; + CommandResult { + data: serde_json::to_value(report(client).await).ok(), + ..crate::ok("The tunnel's connector is starting.") + } + } + Err(e) if crate::refused::is_refusal(&e) => { + refused(client, &e).await; + failed(REFUSED) + } + Err(e) => failed(format!("Couldn't start the tunnel's connector: {e}")), + } +} + +/// `TunnelRemove`: stop the connector, delete its token and its Service. +pub async fn remove(client: &Client) -> CommandResult { + match remove_all(client).await { + Ok(()) => crate::ok("The tunnel's connector is removed."), + Err(e) => failed(format!("Couldn't remove the tunnel's connector: {e}")), + } +} + +async fn remove_all(client: &Client) -> kube::Result<()> { + let gone = |r: kube::Result<()>| match r { + Err(kube::Error::Api(e)) if e.code == 404 => Ok(()), + other => other, + }; + let dp = DeleteParams::default(); + gone(Api::::namespaced(client.clone(), rbac::NS) + .delete(system::TUNNEL_NAME, &dp) + .await + .map(|_| ()))?; + gone(Api::::namespaced(client.clone(), rbac::NS) + .delete(system::TUNNEL_NAME, &dp) + .await + .map(|_| ()))?; + gone(secrets(client).delete(system::TUNNEL_NAME, &dp).await.map(|_| ()))?; + gone(Api::::namespaced(client.clone(), system::GATEWAY_NS) + .delete(system::TUNNEL_ORIGIN_SERVICE, &dp) + .await + .map(|_| ()))?; + kept().applied.clear(); + Ok(()) +} + +/// What a heartbeat reply wants: the connector for this tunnel (when the +/// token here is for it), or none. Then the tunnel policies follow the +/// connectors' pods. +pub async fn follow(client: &Client, wanted: &TunnelWanted) { + // Refused before: nothing until the install changes. + let waiting = kept().refused_on.clone(); + if let Some(on) = waiting { + if crate::refused::install_stamp(client).await == on { + return; + } + kept().refused_on = None; + REFUSED_NOW.store(false, Ordering::Relaxed); + } + let have = match token_for(client).await { + Ok(h) => h, + Err(e) => { + tracing::warn!(error = %e, "couldn't read the tunnel's token"); + return; + } + }; + let done = match (&wanted.tunnel_id, &have) { + (None, None) => Ok(()), + (None, Some(_)) => remove_all(client).await, + // The token for it is here: the connector runs with it. + (Some(w), Some(h)) if w == h => apply_connector(client, false).await, + // Waiting for `TunnelSet` (the report says which token is here). + (Some(_), _) => Ok(()), + }; + if let Err(e) = done { + if crate::refused::is_refusal(&e) { + refused(client, &e).await; + } else { + tracing::warn!(error = %e, "couldn't apply the tunnel's connector"); + } + return; + } + if let Err(e) = follow_pods(client).await { + tracing::warn!(error = %format!("{e:#}"), "couldn't update the tunnel's trusted addresses"); + } +} + +fn pods(client: &Client) -> Api { + Api::namespaced(client.clone(), rbac::NS) +} + +fn selector() -> ListParams { + ListParams::default().labels(&format!("app.kubernetes.io/name={}", system::TUNNEL_APP)) +} + +/// Every address of the connectors' pods, ready or not, as /32 and /128. +pub fn pod_cidrs(list: &[Pod]) -> Vec { + let ips: Vec = list + .iter() + .filter_map(|p| p.status.as_ref()) + .flat_map(|s| { + s.pod_ips + .iter() + .flatten() + .map(|ip| ip.ip.clone()) + .chain(s.pod_ip.clone()) + }) + .collect(); + system::host_cidrs(&ips) +} + +/// The tunnel policies trust the connectors' pods as they are now. +async fn follow_pods(client: &Client) -> anyhow::Result<()> { + let now = pod_cidrs(&pods(client).list(&selector()).await?.items); + let old = kept().pods.clone(); + if now == old { + return Ok(()); + } + crate::gateway::set_tunnel_pods(client, &old, &now).await?; + tracing::info!(pods = now.len(), "the tunnel's trusted addresses changed"); + kept().pods = now; + Ok(()) +} + +/// Why a pod isn't ready, at most 200 characters: a container's waiting +/// or last terminated reason. +fn not_ready_reason(p: &Pod) -> Option { + let statuses = p.status.as_ref()?.container_statuses.as_ref()?; + statuses.iter().find_map(|c| { + let st = c.state.as_ref()?; + let r = st + .waiting + .as_ref() + .and_then(|w| w.reason.clone()) + .or_else(|| st.terminated.as_ref().and_then(|t| t.reason.clone())) + .or_else(|| { + c.last_state + .as_ref() + .and_then(|l| l.terminated.as_ref()) + .and_then(|t| t.reason.clone()) + })?; + Some(r.chars().take(200).collect()) + }) +} + +/// Each connector pod as reported. +pub fn pod_reports(list: &[Pod]) -> Vec { + let mut out: Vec = list + .iter() + .map(|p| { + let ready = p + .status + .as_ref() + .and_then(|s| s.conditions.as_ref()) + .is_some_and(|cs| cs.iter().any(|c| c.type_ == "Ready" && c.status == "True")); + TunnelPod { + server: p + .spec + .as_ref() + .and_then(|s| s.node_name.clone()) + .unwrap_or_default(), + ready, + restarts: p + .status + .as_ref() + .and_then(|s| s.container_statuses.as_ref()) + .map(|cs| cs.iter().map(|c| c.restart_count).sum()) + .unwrap_or(0), + reason: if ready { None } else { not_ready_reason(p) }, + } + }) + .collect(); + out.sort_by(|a, b| a.server.cmp(&b.server)); + out +} + +/// The connector as it is, for the heartbeat. +pub async fn report(client: &Client) -> TunnelReport { + let tunnel_id = token_for(client).await.ok().flatten(); + let deployment = Api::::namespaced(client.clone(), rbac::NS) + .get_opt(system::TUNNEL_NAME) + .await + .ok() + .flatten(); + let (replicas, ready_replicas) = deployment + .as_ref() + .and_then(|d| d.status.as_ref()) + .map(|s| (s.replicas.unwrap_or(0), s.ready_replicas.unwrap_or(0))) + .unwrap_or((0, 0)); + let list = if deployment.is_some() { + pods(client) + .list(&selector()) + .await + .map(|l| l.items) + .unwrap_or_default() + } else { + vec![] + }; + let origin_ready = Api::::namespaced(client.clone(), system::GATEWAY_NS) + .get_opt(system::TUNNEL_ORIGIN_SERVICE) + .await + .ok() + .flatten() + .is_some(); + TunnelReport { + tunnel_id, + replicas, + ready_replicas, + pods: pod_reports(&list), + origin_ready, + refused: REFUSED_NOW.load(Ordering::Relaxed), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fakekube::FakeKube; + + const ID: &str = "c1744f8b-faa1-48a4-9e5c-02ac921467fa"; + const SECRET: &str = "api/v1/namespaces/pyo-system/secrets/pyo-tunnel"; + const DEPLOYMENT: &str = "apis/apps/v1/namespaces/pyo-system/deployments/pyo-tunnel"; + const BUDGET: &str = "apis/policy/v1/namespaces/pyo-system/poddisruptionbudgets/pyo-tunnel"; + const ORIGIN: &str = "api/v1/namespaces/pyo-gateway/services/pyo-tunnel-origin"; + + /// The tests share the agent's kept state: one at a time. + static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + + fn reset() { + let mut k = kept(); + *k = Kept::default(); + REFUSED_NOW.store(false, Ordering::Relaxed); + } + + /// The token goes into the Secret with its tunnel, the connector + /// starts, the report says so, and removing takes all of it away. + #[tokio::test] + async fn the_connector_runs_with_its_token_and_goes_with_it() { + let _one = SERIAL.lock().await; + let (kube, client) = FakeKube::start().await; + reset(); + assert!(!set(&client, "../x", "tok").await.ok); + assert!(!set(&client, ID, "").await.ok); + let r = set(&client, ID, "eyJhIjoiYiJ9").await; + assert!(r.ok, "{:?}", r.message); + let s = kube.get(SECRET).expect("the token's Secret"); + assert_eq!(s["metadata"]["labels"][system::TUNNEL_ID_LABEL], ID); + assert_eq!(s["stringData"]["token"], "eyJhIjoiYiJ9"); + let d = kube.get(DEPLOYMENT).expect("the connector"); + assert_eq!(d["spec"]["replicas"], 2); + assert!(kube.get(BUDGET).is_some()); + assert!(kube.get(ORIGIN).is_some()); + let rep = report(&client).await; + assert_eq!(rep.tunnel_id.as_deref(), Some(ID)); + assert!(rep.origin_ready && !rep.refused); + // The token never shows in what's reported. + assert!(!serde_json::to_string(&r.data).unwrap().contains("eyJhIjoiYiJ9")); + + // Wanted for another tunnel: left alone, waiting for its token. + follow( + &client, + &TunnelWanted { + tunnel_id: Some("00000000-0000-4000-8000-000000000001".into()), + ports_public: true, + }, + ) + .await; + assert!(kube.get(DEPLOYMENT).is_some()); + // Not wanted any more: gone, token and all. + follow(&client, &TunnelWanted::default()).await; + for path in [SECRET, DEPLOYMENT, BUDGET, ORIGIN] { + assert!(kube.get(path).is_none(), "{path}"); + } + assert_eq!(report(&client).await.tunnel_id, None); + // Removing again is fine. + assert!(remove(&client).await.ok); + } + + /// The connector is put back when it's missing, with the token here. + #[tokio::test] + async fn a_missing_connector_is_put_back() { + let _one = SERIAL.lock().await; + let (kube, client) = FakeKube::start().await; + reset(); + kube.put(SECRET, system::tunnel_secret(ID, "tok")); + let wanted = TunnelWanted { + tunnel_id: Some(ID.into()), + ports_public: true, + }; + follow(&client, &wanted).await; + assert!(kube.get(DEPLOYMENT).is_some()); + } + + /// An install older than this agent refuses the connector: the command + /// says what to run, the report says so, and nothing is tried again + /// until the install changes. + #[tokio::test] + async fn an_older_install_is_reported_and_waited_for() { + let _one = SERIAL.lock().await; + let (kube, client) = FakeKube::start().await; + reset(); + kube.admit(|w| { + (w.plural == "deployments").then(|| (403, "deployments.apps \"pyo-tunnel\" is forbidden: ValidatingAdmissionPolicy 'pyo-agent' with binding 'pyo-agent' denied request".into())) + }); + let r = set(&client, ID, "tok").await; + assert!(!r.ok); + assert_eq!(r.message.as_deref(), Some(REFUSED)); + assert!(report(&client).await.refused); + let before = kube.refused().len(); + follow( + &client, + &TunnelWanted { + tunnel_id: Some(ID.into()), + ports_public: true, + }, + ) + .await; + assert_eq!(kube.refused().len(), before, "not tried again"); + assert!(!REFUSED.contains(';')); + } + + #[test] + fn pods_report_their_server_and_why_they_wait() { + let pod: Pod = serde_json::from_value(json!({ + "metadata": { "name": "pyo-tunnel-1" }, + "spec": { "nodeName": "fal2", "containers": [] }, + "status": { + "podIP": "10.42.1.7", "podIPs": [{ "ip": "10.42.1.7" }, { "ip": "fd00::7" }], + "conditions": [{ "type": "Ready", "status": "False" }], + "containerStatuses": [{ "name": "cloudflared", "ready": false, "restartCount": 3, "image": "x", "imageID": "", + "state": { "waiting": { "reason": "ImagePullBackOff" } } }], + }, + })) + .unwrap(); + let r = pod_reports(std::slice::from_ref(&pod)); + assert_eq!(r[0].server, "fal2"); + assert!(!r[0].ready); + assert_eq!(r[0].restarts, 3); + assert_eq!(r[0].reason.as_deref(), Some("ImagePullBackOff")); + assert_eq!(pod_cidrs(&[pod]), ["10.42.1.7/32", "fd00::7/128"]); + assert!(id_ok(ID) && !id_ok("x")); + } +} From 3b9ae43ba41810edc7910d0ab5bafcadcf61dfa2 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:12:53 +0700 Subject: [PATCH 026/139] feat(api): run cloudflare tunnels from the control plane Migration 0040 adds the cluster's traffic choice (public, tailscale or tunnel, with public_traffic generated from it), cluster_tunnels with row security, and the tunnel side of dns_records. The tunnel loop runs every 30 seconds on the leader: it makes the tunnel (or makes it again when it's gone), keeps its routes and Origin CA certificate in step with the cluster's tunnel domains, moves records to the tunnel only once the agent has the routes, puts kept records back on switch back, sends the agent its token, reads Cloudflare's view every 2 minutes, alerts after 5 minutes down and takes a tunnel apart in order. New ops setClusterTraffic, setDomainTunnel, removeClusterTunnel and rotateTunnelToken, and GET /clusters/{id}/tunnel. Tunnel mode is refused until the cluster's install can run it. removeCloudflare is refused while a tunnel exists. The tunnel token is sealed while queued and wiped once answered. MCP's add_domain takes tunnel. --- .../migrations/0040_cloudflare_tunnel.sql | 89 ++ crates/pyo-api/src/agent.rs | 45 +- crates/pyo-api/src/alerts.rs | 36 +- crates/pyo-api/src/bg.rs | 3 + crates/pyo-api/src/cloudflare.rs | 37 +- crates/pyo-api/src/cloudflare/tests.rs | 8 +- crates/pyo-api/src/cloudflare/tunnel.rs | 134 ++ crates/pyo-api/src/cloudflare/tunnel_loop.rs | 1378 +++++++++++++++++ .../src/cloudflare/tunnel_loop_tests.rs | 279 ++++ crates/pyo-api/src/cloudflare/tunnel_ops.rs | 678 ++++++++ crates/pyo-api/src/deploy.rs | 3 + crates/pyo-api/src/gate.rs | 2 + crates/pyo-api/src/install.rs | 4 +- crates/pyo-api/src/lib.rs | 1 + crates/pyo-api/src/mcp.rs | 28 +- crates/pyo-api/src/openapi.rs | 1 + crates/pyo-api/src/ops.rs | 98 +- crates/pyo-api/src/routes.rs | 23 + crates/pyo-api/src/snapshot.rs | 6 + crates/pyo-api/src/teambackup.rs | 35 +- 20 files changed, 2867 insertions(+), 21 deletions(-) create mode 100644 crates/pyo-api/migrations/0040_cloudflare_tunnel.sql create mode 100644 crates/pyo-api/src/cloudflare/tunnel_loop.rs create mode 100644 crates/pyo-api/src/cloudflare/tunnel_loop_tests.rs create mode 100644 crates/pyo-api/src/cloudflare/tunnel_ops.rs diff --git a/crates/pyo-api/migrations/0040_cloudflare_tunnel.sql b/crates/pyo-api/migrations/0040_cloudflare_tunnel.sql new file mode 100644 index 00000000..c4d6dfdd --- /dev/null +++ b/crates/pyo-api/migrations/0040_cloudflare_tunnel.sql @@ -0,0 +1,89 @@ +-- Cloudflare Tunnel (cloudflare/tunnel.rs, docs/cloudflare-tunnel.md). + +-- The cluster's traffic: 'public' (ports 80 and 443 on its servers), +-- 'tailscale' (only the tailnet, or inside the cluster without one) or +-- 'tunnel' (websites through Cloudflare Tunnel, no ports 80 and 443). +ALTER TABLE pyo.clusters ADD COLUMN traffic text NOT NULL DEFAULT 'public' + CHECK (traffic IN ('public', 'tailscale', 'tunnel')); +UPDATE pyo.clusters SET traffic = CASE WHEN public_traffic THEN 'public' ELSE 'tailscale' END; +-- Every reader of public_traffic keeps working: it follows the choice. +ALTER TABLE pyo.clusters DROP COLUMN public_traffic; +ALTER TABLE pyo.clusters ADD COLUMN public_traffic boolean + GENERATED ALWAYS AS (traffic = 'public') STORED; + +-- A cluster's Cloudflare Tunnel. Nothing secret: the tunnel token is read +-- from Cloudflare when the agent needs it, and the Origin CA key sits +-- sealed with the team's certificates. +CREATE TABLE pyo.cluster_tunnels ( + cluster_id text PRIMARY KEY REFERENCES pyo.clusters (id) ON DELETE CASCADE, + team_id text NOT NULL REFERENCES pyo.teams (id) ON DELETE CASCADE, + account_id text NOT NULL, + account_name text NOT NULL DEFAULT '', + -- Cloudflare's id, once made, and its name there. + tunnel_id text, + tunnel_name text NOT NULL, + state text NOT NULL DEFAULT 'creating' + CHECK (state IN ('creating', 'ready', 'failed', 'removing')), + error text, + -- Its zone apex: '*.' gets a wildcard record and route. + default_domain text, + default_zone_id text, + -- Pyo's wildcard record, when it made it. + default_record_id text, + -- Public TCP and UDP ports while the cluster is in tunnel mode. + ports_public boolean NOT NULL DEFAULT true, + -- The routes Pyo last PUT (a hash), and Cloudflare's version of them. + config_hash text NOT NULL DEFAULT '', + config_version integer, + -- The Origin CA certificate the tunnel's domains use. + certificate_id text REFERENCES pyo.certificates (id) ON DELETE SET NULL, + -- Cloudflare's id for it, and the one it replaced, revoked once + -- cf_certificate_old_at has passed. + cf_certificate_id text, + cf_certificate_old text, + cf_certificate_old_at timestamptz, + -- Rotate was asked for: a new tunnel secret and a new certificate. + rotate boolean NOT NULL DEFAULT false, + -- Restore the records the tunnel's domains replaced while it's removed. + restore_records boolean NOT NULL DEFAULT true, + -- Last reads: Cloudflare's view and the agent's. + cf_status jsonb NOT NULL DEFAULT '{}', + agent_status jsonb NOT NULL DEFAULT '{}', + -- Since when Cloudflare says it's down (for the alert after 5 minutes), + -- and whether that alert went out. + down_since timestamptz, + down_alerted boolean NOT NULL DEFAULT false, + -- When the token last went to the agent (not more than every 5 minutes). + token_sent_at timestamptz, + -- When Cloudflare's view was last read. + checked_at timestamptz, + -- Cloudflare asked to wait (429) until then. + backoff_until timestamptz, + created_by text NOT NULL DEFAULT '', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX cluster_tunnels_team_idx ON pyo.cluster_tunnels (team_id); +ALTER TABLE pyo.cluster_tunnels ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.cluster_tunnels TO pyo_team + USING (team_id = ANY (pyo.team_scope())) + WITH CHECK (team_id = ANY (pyo.team_scope())); + +-- A domain through the tunnel: its record is a proxied CNAME to the +-- tunnel. `previous` keeps the records it replaced, for Switch back. +-- 'switching' and 'reverting' are the tunnel loop's to finish. +ALTER TABLE pyo.dns_records + ADD COLUMN via text NOT NULL DEFAULT 'direct' CHECK (via IN ('direct', 'tunnel')), + ADD COLUMN previous jsonb NOT NULL DEFAULT '[]', + -- The switch may replace records in the way (an owner or admin said so). + ADD COLUMN replace boolean NOT NULL DEFAULT false, + -- Switching back: put the kept records back (else an A record to the + -- cluster's public IP on a cluster with public ports, else nothing). + ADD COLUMN restore boolean NOT NULL DEFAULT true, + -- The routes sync the switch waits for on the agent (pyo.commands). + ADD COLUMN routes_command text; +ALTER TABLE pyo.dns_records DROP CONSTRAINT dns_records_status_check; +ALTER TABLE pyo.dns_records ADD CONSTRAINT dns_records_status_check + CHECK (status IN ('created', 'exists', 'conflict', 'failed', 'switching', 'reverting')); +CREATE INDEX dns_records_tunnel_idx ON pyo.dns_records (service_id) + WHERE status IN ('switching', 'reverting'); diff --git a/crates/pyo-api/src/agent.rs b/crates/pyo-api/src/agent.rs index a1b93a94..977690b4 100644 --- a/crates/pyo-api/src/agent.rs +++ b/crates/pyo-api/src/agent.rs @@ -349,6 +349,8 @@ async fn heartbeat( "wafRejected": caps.waf_rejected, // And those whose WAF policy it accepted (bundles.rs `waf_shown`). "wafActive": caps.waf_active, + // It runs a Cloudflare Tunnel connector (cloudflare/tunnel_loop.rs). + "tunnel": caps.tunnel, // Whether this agent can update Pyo and itself (updates.rs). "updates": hb.updates, // Its builders and pyo-static sign their requests (agent_auth.rs). @@ -388,6 +390,14 @@ async fn heartbeat( .execute(&mut *tx) .await?; name_from_host(&mut tx, &cluster.id, &cluster.team_id, &hb.servers).await?; + // Its Cloudflare Tunnel connector, as the agent sees it. + if let Some(t) = &hb.tunnel { + sqlx::query("UPDATE pyo.cluster_tunnels SET agent_status = $2 || jsonb_build_object('at', pyo.ms(now())) WHERE cluster_id = $1") + .bind(&cluster.id) + .bind(json!(t)) + .execute(&mut *tx) + .await?; + } // The server Pyo runs on, connecting for the first time: the team's // first builder goes there. Where every cluster keeps its own images // (Pyo Cloud), a team's first cluster to connect gets it. @@ -732,10 +742,43 @@ async fn heartbeat( let tailnet = crate::tailscale::wanted_for(&s.db, &cluster.id, same_cluster).await?; // Pyo's dashboard on the public IP, while it's open. let public_dashboard = crate::publicdash::wanted_for(&s.db, same_cluster).await?; - let reply = json!({ "ok": true, "clusterId": cluster.id, "serverLocations": server_locations, "serverTags": server_tags, "gpuPolicies": gpu_policies, "publicTraffic": public_traffic, "freeDomainAddress": free_domain_address, "projectTeams": project_teams, "observability": observability, "tailnet": tailnet, "publicDashboard": public_dashboard }); + // The Cloudflare Tunnel connector it runs, if any. + let tunnel = tunnel_wanted(&s.db, &cluster.id).await?; + // TCP and UDP ports on the servers: with public traffic, or in tunnel + // mode while the cluster keeps them. + let public_ports: bool = sqlx::query_scalar( + "SELECT c.traffic = 'public' OR (c.traffic = 'tunnel' AND coalesce(t.ports_public, true)) + FROM pyo.clusters c LEFT JOIN pyo.cluster_tunnels t ON t.cluster_id = c.id WHERE c.id = $1", + ) + .bind(&cluster.id) + .fetch_one(&s.db) + .await?; + let reply = json!({ "ok": true, "clusterId": cluster.id, "serverLocations": server_locations, "serverTags": server_tags, "gpuPolicies": gpu_policies, "publicTraffic": public_traffic, "freeDomainAddress": free_domain_address, "projectTeams": project_teams, "observability": observability, "tailnet": tailnet, "publicDashboard": public_dashboard, "tunnel": tunnel, "publicPorts": public_ports }); Ok(Json(signed_reply(&cluster.id, &headers, reply).await)) } +/// The Cloudflare Tunnel connector a cluster runs: its tunnel once +/// Cloudflare made it, none while it's removed or there's none (the agent +/// then removes what it has). Left out while the tunnel is still being +/// made. +async fn tunnel_wanted(db: &sqlx::PgPool, cluster_id: &str) -> ApiResult> { + let row: Option<(Option, String, bool)> = sqlx::query_as( + "SELECT tunnel_id, state, ports_public FROM pyo.cluster_tunnels WHERE cluster_id = $1", + ) + .bind(cluster_id) + .fetch_optional(db) + .await?; + Ok(match row { + None => Some(pyo_proto::TunnelWanted::default()), + Some((_, state, _)) if state == "removing" => Some(pyo_proto::TunnelWanted::default()), + Some((None, _, _)) => None, + Some((Some(id), _, ports_public)) => Some(pyo_proto::TunnelWanted { + tunnel_id: Some(id), + ports_public, + }), + }) +} + /// Which GPU servers are kept for GPU work. A server's own setting wins; /// by default one is, unless it's a control-plane server or the cluster has /// no other ready server for everything else (that would leave regular diff --git a/crates/pyo-api/src/alerts.rs b/crates/pyo-api/src/alerts.rs index 777160a9..5d0224fa 100644 --- a/crates/pyo-api/src/alerts.rs +++ b/crates/pyo-api/src/alerts.rs @@ -74,6 +74,9 @@ pub enum Event { BackupFailed, CertificateExpiring, CertificateFailed, + /// A cluster's Cloudflare Tunnel down for 5 minutes, and back. + TunnelDown, + TunnelUp, /// The Send test button. Test, } @@ -93,6 +96,8 @@ impl Event { match self { Event::DeployFailed => "deploy_failed", Event::ServerOffline | Event::ServerOnline => "server_offline", + // Websites unreachable, as a cluster is: the same setting. + Event::TunnelDown | Event::TunnelUp => "server_offline", Event::ServerPressure | Event::ServerPressureEnded => "server_pressure", Event::BackupFailed => "backup_failed", Event::CertificateExpiring | Event::CertificateFailed => "certificate", @@ -111,6 +116,8 @@ impl Event { Event::BackupFailed => "backup_failed", Event::CertificateExpiring => "certificate_expiring", Event::CertificateFailed => "certificate_failed", + Event::TunnelDown => "tunnel_down", + Event::TunnelUp => "tunnel_up", Event::Test => "test", } } @@ -120,6 +127,7 @@ impl Event { match self { Event::ServerOnline => Some(Event::ServerOffline), Event::ServerPressureEnded => Some(Event::ServerPressure), + Event::TunnelUp => Some(Event::TunnelDown), _ => None, } } @@ -128,7 +136,10 @@ impl Event { /// within the window after it ended is held, and sent if it still holds /// once the window is over. fn lasts(self) -> bool { - matches!(self, Event::ServerOffline | Event::ServerPressure) + matches!( + self, + Event::ServerOffline | Event::ServerPressure | Event::TunnelDown + ) } } @@ -147,6 +158,8 @@ pub fn classify(kind: &str, target: &Value) -> Option { Event::CertificateExpiring } "domain.certificate_failed" => Event::CertificateFailed, + "cluster.tunnel_down" => Event::TunnelDown, + "cluster.tunnel_up" => Event::TunnelUp, _ => return None, }) } @@ -928,6 +941,27 @@ async fn build( format!("/clusters/{name}"), ) } + Event::TunnelDown | Event::TunnelUp => { + let Some(name): Option = + sqlx::query_scalar("SELECT name FROM pyo.clusters WHERE id = $1") + .bind(&target_id) + .fetch_optional(&mut **tx) + .await? + else { + return Ok(None); + }; + let title = if event == Event::TunnelDown { + format!("Cloudflare Tunnel of {name} is down") + } else { + format!("Cloudflare Tunnel of {name} is back") + }; + alert( + format!("tunnel:{target_id}"), + title, + vec![], + format!("/clusters/{name}/settings"), + ) + } Event::ServerOffline | Event::ServerOnline => { let cluster_id = s(&context["clusterId"]); let Some(cluster): Option = diff --git a/crates/pyo-api/src/bg.rs b/crates/pyo-api/src/bg.rs index 9aa466af..96df85dd 100644 --- a/crates/pyo-api/src/bg.rs +++ b/crates/pyo-api/src/bg.rs @@ -77,6 +77,8 @@ pub const LOCK_UPDATES: i64 = 7_007; /// A hosted Pyo's agent updates (updates.rs `hosted_agents`). pub const LOCK_AGENT_UPDATES: i64 = 7_011; pub const LOCK_TAILSCALE: i64 = 7_009; +/// The Cloudflare Tunnel loop (cloudflare/tunnel_loop.rs). +pub const LOCK_TUNNEL: i64 = 7_012; /// Not a loop's: the backup store's layout, set up by one process at a time. pub const LOCK_BACKUP_STORE: i64 = 7_008; pub const LOCK_DATABASE_IMPORTS: i64 = 7_031; @@ -266,6 +268,7 @@ mod tests { LOCK_UPDATES, LOCK_AGENT_UPDATES, LOCK_TAILSCALE, + LOCK_TUNNEL, LOCK_BACKUP_STORE, LOCK_DATABASE_IMPORTS, crate::geoip::LOCK_GEOIP, diff --git a/crates/pyo-api/src/cloudflare.rs b/crates/pyo-api/src/cloudflare.rs index f8eaaed8..ed413492 100644 --- a/crates/pyo-api/src/cloudflare.rs +++ b/crates/pyo-api/src/cloudflare.rs @@ -48,6 +48,8 @@ const TIMEOUT: Duration = Duration::from_secs(20); const MAX_ZONES: usize = 200; pub(crate) mod tunnel; +pub(crate) mod tunnel_loop; +pub(crate) mod tunnel_ops; use tunnel::TunnelApi; // ── Zones and records ────────────────────────────────────────────────────── @@ -663,6 +665,7 @@ pub async fn attach( "SELECT service_id, domain_id, jsonb_build_object( 'zone', zone_name, 'type', type, 'content', content, 'proxied', proxied, 'proxy', proxy, 'status', status, 'error', error, 'existing', existing, 'mine', record_id IS NOT NULL, + 'via', via, 'previous', previous, 'updatedAt', pyo.ms(updated_at)) FROM pyo.dns_records WHERE team_id = ANY($1)", ) @@ -687,7 +690,10 @@ pub async fn attach( } /// A service was saved: records of domains it no longer has (or whose -/// hostname changed) are forgotten. What's at Cloudflare stays. +/// hostname changed) are forgotten. What's at Cloudflare stays, except a +/// record through the Cloudflare Tunnel: the tunnel loop deletes Pyo's +/// CNAME. The record it replaced isn't put back (decision 5), unless a +/// switch back that puts it back was already asked for. pub async fn forget_removed( tx: &mut Transaction<'_, Postgres>, service_id: &str, @@ -705,7 +711,19 @@ pub async fn forget_removed( }) .unzip(); sqlx::query( - "DELETE FROM pyo.dns_records r WHERE r.service_id = $1 + "UPDATE pyo.dns_records r SET status = 'reverting', restore = r.status = 'reverting' AND r.restore, + routes_command = NULL, updated_at = now() + WHERE r.service_id = $1 AND r.via = 'tunnel' + AND NOT EXISTS (SELECT 1 FROM unnest($2::text[], $3::text[]) AS d(id, host) + WHERE d.id = r.domain_id AND d.host = lower(r.hostname))", + ) + .bind(service_id) + .bind(&ids) + .bind(&hosts) + .execute(&mut **tx) + .await?; + sqlx::query( + "DELETE FROM pyo.dns_records r WHERE r.service_id = $1 AND r.via <> 'tunnel' AND NOT EXISTS (SELECT 1 FROM unnest($2::text[], $3::text[]) AS d(id, host) WHERE d.id = r.domain_id AND d.host = lower(r.hostname))", ) @@ -813,13 +831,26 @@ pub async fn test( Ok(json!({ "ok": problems.is_empty(), "zones": zones, "problems": problems })) } -/// Forget the token. Records Pyo made stay at Cloudflare. +/// Forget the token. Records Pyo made stay at Cloudflare. Refused while a +/// cluster of the team has a tunnel. pub async fn remove( tx: &mut Transaction<'_, Postgres>, user: &User, team_id: &str, ) -> ApiResult { require_role(tx, user, team_id, role_for(Action::ManageToken)).await?; + // Without the token, Pyo could no longer change or remove a tunnel. + let tunneled: Option = sqlx::query_scalar( + "SELECT c.name FROM pyo.cluster_tunnels t JOIN pyo.clusters c ON c.id = t.cluster_id WHERE t.team_id = $1 ORDER BY c.name LIMIT 1", + ) + .bind(team_id) + .fetch_optional(&mut **tx) + .await?; + if let Some(name) = tunneled { + return Err(ApiError::conflict(format!( + "Remove the Cloudflare Tunnel of {name} first. Its websites keep working until then." + ))); + } let gone = sqlx::query("DELETE FROM pyo.cloudflare_accounts WHERE team_id = $1") .bind(team_id) .execute(&mut **tx) diff --git a/crates/pyo-api/src/cloudflare/tests.rs b/crates/pyo-api/src/cloudflare/tests.rs index bb3d02cd..26147af8 100644 --- a/crates/pyo-api/src/cloudflare/tests.rs +++ b/crates/pyo-api/src/cloudflare/tests.rs @@ -143,7 +143,7 @@ impl Fake { } } - fn dns(&self, zone: &str) -> Dns { + pub fn dns(&self, zone: &str) -> Dns { self.zones .iter() .find(|z| z.0 == zone) @@ -151,15 +151,15 @@ impl Fake { .unwrap_or(Dns::None) } - fn log(&self, c: String) { + pub fn log(&self, c: String) { self.calls.lock().unwrap().push(c); } - fn calls(&self) -> Vec { + pub fn calls(&self) -> Vec { self.calls.lock().unwrap().clone() } - fn at(&self, zone: &str) -> Vec { + pub fn at(&self, zone: &str) -> Vec { self.records .lock() .unwrap() diff --git a/crates/pyo-api/src/cloudflare/tunnel.rs b/crates/pyo-api/src/cloudflare/tunnel.rs index 4e2edaf1..2f3ddd1d 100644 --- a/crates/pyo-api/src/cloudflare/tunnel.rs +++ b/crates/pyo-api/src/cloudflare/tunnel.rs @@ -555,3 +555,137 @@ pub fn tunnel_name(cluster_id: &str, install_id: &str, attempt: u32) -> String { pub fn cname_target(tunnel_id: &str) -> String { format!("{tunnel_id}.cfargotunnel.com") } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn routes_go_exact_names_first_then_the_wildcard_then_404() { + let hosts = vec![ + "blog.example.com".to_owned(), + "a.b.example.com".to_owned(), + "API.example.com.".to_owned(), + "blog.example.com".to_owned(), + "*.example.com".to_owned(), + ]; + let c = ingress(&hosts, Some("example.com")); + let names: Vec = c["ingress"] + .as_array() + .unwrap() + .iter() + .map(|r| r["hostname"].clone()) + .collect(); + assert_eq!( + names, + [ + json!("blog.example.com"), + json!("a.b.example.com"), + json!("api.example.com"), + json!("*.example.com"), + Value::Null + ] + ); + let first = &c["ingress"][0]; + assert_eq!(first["service"], ORIGIN); + assert_eq!(first["originRequest"]["matchSNItoHost"], true); + assert_eq!(c["ingress"][4], json!({ "service": "http_status:404" })); + // The same routes always hash the same, whatever order they came in. + let mut again = hosts.clone(); + again.reverse(); + assert_eq!( + config_hash(&ingress(&again, Some("example.com"))), + config_hash(&c) + ); + assert_ne!( + config_hash(&ingress(&hosts[..1], Some("example.com"))), + config_hash(&c) + ); + assert_eq!( + empty_ingress(), + json!({ "ingress": [{ "service": "http_status:404" }] }) + ); + } + + #[test] + fn certificate_names_cover_each_host_one_level_up() { + assert_eq!(cert_name("example.com", "example.com"), "example.com"); + assert_eq!(cert_name("blog.example.com", "example.com"), "*.example.com"); + assert_eq!(cert_name("a.b.example.com", "example.com"), "*.b.example.com"); + assert_eq!(cert_name("Shop.Example.com.", "example.com"), "*.example.com"); + let hosts = vec![ + ("blog.example.com".to_owned(), "example.com".to_owned()), + ("shop.example.com".to_owned(), "example.com".to_owned()), + ("other.org".to_owned(), "other.org".to_owned()), + ("x.y.other.org".to_owned(), "other.org".to_owned()), + ]; + assert_eq!( + cert_names(&hosts, Some("example.com")).unwrap(), + ["*.example.com", "*.y.other.org", "other.org"] + ); + let many: Vec<(String, String)> = (0..=MAX_CERT_NAMES) + .map(|i| (format!("a.s{i}.example.com"), "example.com".to_owned())) + .collect(); + assert_eq!( + cert_names(&many, None).unwrap_err(), + "This tunnel has too many names for one certificate." + ); + let have = vec!["*.example.com".to_owned(), "other.org".to_owned()]; + assert!(covers_all(&have, &["*.example.com".to_owned()])); + assert!(!covers_all(&have, &["*.b.example.com".to_owned()])); + } + + #[test] + fn a_csr_names_every_host_and_the_key_stays_here() { + let names = vec!["*.example.com".to_owned(), "example.com".to_owned()]; + let (csr, key) = key_and_csr(&names).unwrap(); + assert!(csr.starts_with("-----BEGIN CERTIFICATE REQUEST-----")); + assert!(key.contains("PRIVATE KEY")); + assert!(!csr.contains("PRIVATE KEY")); + } + + #[test] + fn names_secrets_and_targets() { + assert_eq!(tunnel_name("cl_1", "abc123", 0), "pyo-cl_1-abc123"); + assert_eq!(tunnel_name("cl_1", "abc123", 2), "pyo-cl_1-abc123-2"); + assert_eq!( + cname_target("c1744f8b-faa1-48a4-9e5c-02ac921467fa"), + "c1744f8b-faa1-48a4-9e5c-02ac921467fa.cfargotunnel.com" + ); + use base64::Engine; + let s = new_secret(); + assert_eq!( + base64::engine::general_purpose::STANDARD + .decode(&s) + .unwrap() + .len(), + 32 + ); + assert_ne!(new_secret(), s); + assert!(cert_id_ok("123456789012345678901234567890")); + assert!(!cert_id_ok("12/34")); + assert!(!cert_id_ok("")); + } + + #[test] + fn kept_records_round_trip_without_their_id() { + let k = kept_from(&json!({ + "id": "372e67954025e0ba6aaa6d586b9e0b59", "type": "A", "name": "blog.example.com", + "content": "203.0.113.7", "proxied": true, "ttl": 300, "comment": "by hand", + })) + .unwrap(); + assert_eq!(k.id, "372e67954025e0ba6aaa6d586b9e0b59"); + assert_eq!(k.ttl, 300); + let stored = serde_json::to_value(&k).unwrap(); + assert!(stored.get("id").is_none()); + assert_eq!(stored["type"], "A"); + let back: Kept = serde_json::from_value(stored).unwrap(); + assert_eq!(back.ttl, 300); + assert_eq!(back.comment.as_deref(), Some("by hand")); + let auto: Kept = serde_json::from_value( + json!({ "type": "CNAME", "name": "a.example.com", "content": "x.example.net" }), + ) + .unwrap(); + assert_eq!((auto.ttl, auto.proxied), (1, false)); + } +} diff --git a/crates/pyo-api/src/cloudflare/tunnel_loop.rs b/crates/pyo-api/src/cloudflare/tunnel_loop.rs new file mode 100644 index 00000000..8279bcc7 --- /dev/null +++ b/crates/pyo-api/src/cloudflare/tunnel_loop.rs @@ -0,0 +1,1378 @@ +//! The tunnel loop (docs/cloudflare-tunnel.md §6.3): every 30 seconds on +//! the leader, each cluster tunnel is brought to what Pyo wants. The +//! tunnel exists at Cloudflare, its routes are the cluster's tunnel +//! domains, its certificate covers them, their records point at it (or +//! back), the agent has its token, and Cloudflare's view of it is read +//! every 2 minutes. A tunnel being removed is taken apart in order. +//! +//! Every step touches Cloudflare only when something differs. Errors are +//! kept on the tunnel (`error`) or the record (`dns_records.error`) in +//! Cloudflare's words, never with the token. +//! +//! The parts that talk to Cloudflare are generic over [`Cloudflare`] and +//! [`TunnelApi`], so the tests run them against the fake account. + +use std::time::Duration; + +use serde_json::{Value, json}; +use sqlx::{Postgres, Transaction}; + +use super::{ + CfError, Cloudflare, Http, NewRecord, Record, delete_ours, install_id, marker, ours, + same_name, + tunnel::{self, Kept, OriginCert, Tunnel, TunnelApi}, + zone_for, +}; +use crate::{AppState, error::ApiResult, ops::log_activity}; + +/// How often the loop runs. +const EVERY: Duration = Duration::from_secs(30); +/// Down this long before the alert goes out. +const DOWN_ALERT_SECS: i64 = 300; +/// How long removal waits for the agent to stop the connector. +const REMOVE_WAIT_SECS: i64 = 600; + +/// The loop, on the leader. +pub async fn run(state: AppState) { + let mut tick = tokio::time::interval(EVERY); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + tick.tick().await; + if let Some(Err(e)) = + crate::bg::as_leader(&state.db, crate::bg::LOCK_TUNNEL, || pass(&state)).await + { + tracing::warn!(error = ?e.message, "tunnel loop failed"); + } + } +} + +/// One pass over every tunnel, one at a time. +pub async fn pass(s: &AppState) -> ApiResult<()> { + let ids: Vec = sqlx::query_scalar( + "SELECT cluster_id FROM pyo.cluster_tunnels + WHERE backoff_until IS NULL OR backoff_until < now() ORDER BY cluster_id", + ) + .fetch_all(&s.db) + .await?; + for id in ids { + if let Err(e) = one(s, &id).await { + tracing::warn!(cluster = %id, error = ?e.message, "tunnel pass failed"); + } + } + Ok(()) +} + +/// A cluster's tunnel as stored, with what's due. +#[derive(sqlx::FromRow, Debug, Clone, Default)] +pub(crate) struct Row { + pub cluster_id: String, + pub team_id: String, + pub account_id: String, + pub tunnel_id: Option, + pub tunnel_name: String, + pub state: String, + pub default_domain: Option, + pub default_zone_id: Option, + pub default_record_id: Option, + pub config_hash: String, + pub config_version: Option, + pub certificate_id: Option, + pub cf_certificate_id: Option, + pub cf_certificate_old: Option, + pub rotate: bool, + pub restore_records: bool, + pub agent_status: Value, + pub down_alerted: bool, + /// Computed: the old certificate may be revoked. + pub old_due: bool, + /// Computed: the token may go to the agent again. + pub token_due: bool, + /// Computed: Cloudflare's view is due. + pub check_due: bool, + /// Computed: seconds Cloudflare has said it's down. + pub down_secs: Option, + /// Computed: seconds since removal was asked for. + pub removing_secs: i64, + /// Computed: made in the last 5 minutes. + pub young: bool, +} + +const ROW: &str = "SELECT cluster_id, team_id, account_id, tunnel_id, tunnel_name, state, default_domain, default_zone_id, + default_record_id, config_hash, config_version, certificate_id, cf_certificate_id, cf_certificate_old, rotate, + restore_records, agent_status, down_alerted, + coalesce(cf_certificate_old_at < now(), false) AS old_due, + (token_sent_at IS NULL OR token_sent_at < now() - interval '5 minutes') AS token_due, + (checked_at IS NULL OR checked_at < now() - interval '2 minutes') AS check_due, + extract(epoch FROM now() - down_since)::bigint AS down_secs, + extract(epoch FROM now() - updated_at)::bigint AS removing_secs, + (created_at > now() - interval '5 minutes') AS young + FROM pyo.cluster_tunnels WHERE cluster_id = $1"; + +pub(crate) async fn load( + db: impl sqlx::PgExecutor<'_>, + cluster_id: &str, +) -> ApiResult> { + Ok(sqlx::query_as::<_, Row>(ROW) + .bind(cluster_id) + .fetch_optional(db) + .await?) +} + +/// Keep an error on the tunnel (or clear it with None). +async fn set_error(s: &AppState, cluster_id: &str, error: Option) -> ApiResult<()> { + sqlx::query("UPDATE pyo.cluster_tunnels SET error = $2 WHERE cluster_id = $1 AND error IS DISTINCT FROM $2") + .bind(cluster_id) + .bind(error) + .execute(&s.db) + .await?; + Ok(()) +} + +/// Cloudflare asked to slow down: this team's tunnels wait a minute. +async fn back_off(s: &AppState, team_id: &str) -> ApiResult<()> { + sqlx::query("UPDATE pyo.cluster_tunnels SET backoff_until = now() + interval '60 seconds' WHERE team_id = $1") + .bind(team_id) + .execute(&s.db) + .await?; + Ok(()) +} + +/// Cloudflare's 429. +fn slow_down(e: &CfError) -> bool { + matches!(e, CfError::Refused(m) if m.contains("429") || m.to_lowercase().contains("rate limit")) +} + +/// Said when the team's token is gone or refused. +pub const TOKEN_GONE: &str = "Connect Cloudflare again to change the tunnel. Its websites keep working."; + +/// One tunnel, one pass. +async fn one(s: &AppState, cluster_id: &str) -> ApiResult<()> { + let Some(row) = load(&s.db, cluster_id).await? else { + return Ok(()); + }; + let mut tx = s.db.begin().await?; + let account = super::account(s, &mut tx, &row.team_id).await.ok().flatten(); + let mark = marker(&install_id(&mut tx).await?); + tx.commit().await?; + let Some(account) = account else { + return set_error(s, cluster_id, Some(TOKEN_GONE.into())).await; + }; + let cf = Http::new(&account.token)?; + let r = if row.state == "removing" { + remove(s, &cf, &row, &account.zones, &mark).await + } else { + keep(s, &cf, &row, &account.zones, &mark).await + }; + match r { + Ok(()) => Ok(()), + Err(Step::Cf(e)) if slow_down(&e) => back_off(s, &row.team_id).await, + Err(Step::Cf(e @ CfError::Denied(_))) => { + set_error(s, cluster_id, Some(format!("{e} {TOKEN_GONE}"))).await + } + Err(Step::Cf(e)) => set_error(s, cluster_id, Some(e.to_string())).await, + Err(Step::Api(e)) => Err(e), + } +} + +/// Why a step stopped: Cloudflare said no, or Pyo's own trouble. +#[derive(Debug)] +pub(crate) enum Step { + Cf(CfError), + Api(crate::error::ApiError), +} + +impl From for Step { + fn from(e: CfError) -> Self { + Step::Cf(e) + } +} + +impl From for Step { + fn from(e: crate::error::ApiError) -> Self { + Step::Api(e) + } +} + +impl From for Step { + fn from(e: anyhow::Error) -> Self { + Step::Api(e.into()) + } +} + +impl From for Step { + fn from(e: sqlx::Error) -> Self { + Step::Api(e.into()) + } +} + +/// A tunnel domain of the cluster, as its service has it. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct TunnelDomain { + pub service_id: String, + pub domain_id: String, + pub host: String, + /// "switching" or "on". + pub tunnel: String, + pub zone_id: String, + pub zone_name: String, +} + +/// The cluster's domains that go through its tunnel, with their zones (a +/// domain no connected zone covers is left out: it can't be routed). +async fn tunnel_domains( + db: impl sqlx::PgExecutor<'_>, + cluster_id: &str, + zones: &[super::Zone], +) -> ApiResult> { + let rows: Vec<(String, String, String, String)> = sqlx::query_as( + "SELECT a.id, d->>'id', lower(d->>'hostname'), d->>'tunnel' + FROM pyo.services a, jsonb_array_elements(a.spec->'domains') d + WHERE a.cluster_id = $1 AND NOT a.deleting AND d->>'tunnel' IN ('switching', 'on') + ORDER BY 3", + ) + .bind(cluster_id) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .filter_map(|(service_id, domain_id, host, tunnel)| { + let z = zone_for(&host, zones)?; + Some(TunnelDomain { + service_id, + domain_id, + host, + tunnel, + zone_id: z.id.clone(), + zone_name: z.name.clone(), + }) + }) + .collect()) +} + +// ── Keeping a tunnel ─────────────────────────────────────────────────────── + +async fn keep( + s: &AppState, + cf: &C, + row: &Row, + zones: &[super::Zone], + mark: &str, +) -> Result<(), Step> { + let install = mark + .trim_start_matches("Made by Pyo (") + .trim_end_matches(')') + .to_owned(); + // 1. The tunnel itself. + let (t, recreated) = ensure_tunnel(cf, row, &install).await?; + if row.tunnel_id.as_deref() != Some(t.id.as_str()) { + sqlx::query( + "UPDATE pyo.cluster_tunnels SET tunnel_id = $2, tunnel_name = $3, state = 'ready', config_hash = '', token_sent_at = NULL, + default_record_id = NULL, updated_at = now() WHERE cluster_id = $1", + ) + .bind(&row.cluster_id) + .bind(&t.id) + .bind(&t.name) + .execute(&s.db) + .await?; + if recreated { + // Its records point at the old one: they move to the new one. + sqlx::query( + "UPDATE pyo.dns_records SET status = 'switching', updated_at = now() + WHERE via = 'tunnel' AND status = 'created' + AND service_id IN (SELECT id FROM pyo.services WHERE cluster_id = $1)", + ) + .bind(&row.cluster_id) + .execute(&s.db) + .await?; + let mut tx = s.db.begin().await?; + log_activity( + &mut tx, + &row.team_id, + "Pyo", + "cluster.tunnel_recreated", + "warning", + "The Cloudflare Tunnel was gone, so Pyo made a new one", + json!({ "kind": "cluster", "id": row.cluster_id, "label": t.name }), + json!({}), + ) + .await?; + tx.commit().await?; + } + } + let target = tunnel::cname_target(&t.id); + let domains = tunnel_domains(&s.db, &row.cluster_id, zones).await?; + + // 2. Its routes: every tunnel domain, plus the default domain's wildcard. + let hosts: Vec = domains.iter().map(|d| d.host.clone()).collect(); + let config = tunnel::ingress(&hosts, row.default_domain.as_deref()); + let hash = tunnel::config_hash(&config); + if hash != row.config_hash || recreated { + let version = cf.put_config(&row.account_id, &t.id, &config).await?; + sqlx::query("UPDATE pyo.cluster_tunnels SET config_hash = $2, config_version = $3 WHERE cluster_id = $1") + .bind(&row.cluster_id) + .bind(&hash) + .bind(version as i32) + .execute(&s.db) + .await?; + } + + // 3. Its certificate: every name covered. + let pairs: Vec<(String, String)> = domains + .iter() + .map(|d| (d.host.clone(), d.zone_name.clone())) + .collect(); + let certificate_id = match tunnel::cert_names(&pairs, row.default_domain.as_deref()) { + Ok(names) => ensure_certificate(s, cf, row, &names).await?, + Err(e) => { + set_error(s, &row.cluster_id, Some(e)).await?; + row.certificate_id.clone() + } + }; + + // 4. Its domains' certificates, and their records. + if let Some(cert) = &certificate_id { + tls_follow(s, &row.cluster_id, cert).await?; + } + records(s, cf, row, &target, zones, mark).await?; + default_record(s, cf, row, &target, mark).await?; + + // 5. The agent's token. + let agent_has = row.agent_status["tunnelId"].as_str(); + if agent_has != Some(t.id.as_str()) && row.token_due && agent_knows_tunnels(s, &row.cluster_id).await? { + let token = cf.tunnel_token(&row.account_id, &t.id).await?; + let mut tx = s.db.begin().await?; + crate::deploy::enqueue( + &mut tx, + &row.cluster_id, + pyo_proto::Command::TunnelSet { + tunnel_id: t.id.clone(), + token, + }, + ) + .await?; + sqlx::query("UPDATE pyo.cluster_tunnels SET token_sent_at = now() WHERE cluster_id = $1") + .bind(&row.cluster_id) + .execute(&mut *tx) + .await?; + tx.commit().await?; + s.wake(&row.cluster_id).await; + } + + // 6. Rotate: a new secret, old connections dropped, then the token again. + if row.rotate { + cf.rotate_secret(&row.account_id, &t.id, &tunnel::new_secret()) + .await?; + cf.drop_connections(&row.account_id, &t.id).await?; + sqlx::query( + "UPDATE pyo.cluster_tunnels SET rotate = false, token_sent_at = NULL, + agent_status = agent_status - 'tunnelId' WHERE cluster_id = $1", + ) + .bind(&row.cluster_id) + .execute(&s.db) + .await?; + } + + // 7. Cloudflare's view, every 2 minutes. + if row.check_due { + let now = cf.tunnel(&row.account_id, &t.id).await?; + status(s, row, &now).await?; + // Its routes changed outside Pyo: Pyo's go back. + if let Ok((version, _)) = cf.config(&row.account_id, &t.id).await + && row.config_version.is_some_and(|v| i64::from(v) != version) + { + sqlx::query("UPDATE pyo.cluster_tunnels SET config_hash = '' WHERE cluster_id = $1") + .bind(&row.cluster_id) + .execute(&s.db) + .await?; + } + } + + // 8. The certificate it replaced, a day later. + if row.old_due + && let Some(old) = &row.cf_certificate_old + { + match cf.revoke_origin_cert(old).await { + Ok(()) | Err(CfError::NotFound) => {} + Err(e) => return Err(e.into()), + } + sqlx::query("UPDATE pyo.cluster_tunnels SET cf_certificate_old = NULL, cf_certificate_old_at = NULL WHERE cluster_id = $1") + .bind(&row.cluster_id) + .execute(&s.db) + .await?; + } + set_error(s, &row.cluster_id, None).await?; + Ok(()) +} + +/// Whether the cluster's agent runs tunnels (an older one would never +/// answer `TunnelSet`). +async fn agent_knows_tunnels(s: &AppState, cluster_id: &str) -> ApiResult { + Ok(sqlx::query_scalar( + "SELECT coalesce((capabilities->>'tunnel')::boolean, false) FROM pyo.clusters WHERE id = $1", + ) + .bind(cluster_id) + .fetch_optional(&s.db) + .await? + .unwrap_or(false)) +} + +/// The tunnel at Cloudflare: the one stored, or (none yet, or deleted at +/// Cloudflare) one made now. A tunnel this installation made earlier under +/// the same name (a pass that stopped halfway) is taken, never someone +/// else's. (tunnel, made again after it was gone). +pub(crate) async fn ensure_tunnel( + cf: &C, + row: &Row, + install: &str, +) -> Result<(Tunnel, bool), CfError> { + if let Some(id) = &row.tunnel_id { + match cf.tunnel(&row.account_id, id).await { + Ok(t) if !t.deleted => return Ok((t, false)), + Ok(_) | Err(CfError::NotFound) => {} + Err(e) => return Err(e), + } + } + let base = tunnel::tunnel_name(&row.cluster_id, install, 0); + let taken = cf.tunnels_named(&row.account_id, &base).await?; + if row.tunnel_id.is_none() + && let Some(t) = taken.iter().find(|t| t.name == base && !t.deleted) + { + return Ok((t.clone(), false)); + } + let recreated = row.tunnel_id.is_some(); + for attempt in 1..=20 { + let name = tunnel::tunnel_name(&row.cluster_id, install, attempt); + if taken.iter().any(|t| t.name == name) { + continue; + } + return Ok((cf.create_tunnel(&row.account_id, &name).await?, recreated)); + } + Err(CfError::Refused( + "Too many tunnels with this cluster's name. Delete the old ones in Cloudflare.".into(), + )) +} + +// ── Records ──────────────────────────────────────────────────────────────── + +/// What became of a switch's record. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Switched { + /// The name points at the tunnel: Pyo's record, and the ones it + /// replaced (kept to put back). + Done { record: Record, previous: Vec }, + /// Records Pyo didn't make answer for the name: these. Nothing changed. + Confirm(Vec), +} + +/// Point `host` at the tunnel with a proxied CNAME. Pyo's own records on +/// the name go without asking. Anyone else's stop it, unless `replace`: +/// then they go and come back as `previous`. Never touches records of +/// other names, or types other than A, AAAA and CNAME. +pub(crate) async fn switch_record( + cf: &C, + zone_id: &str, + host: &str, + target: &str, + replace: bool, + mark: &str, +) -> Result { + let found = cf.records_kept(zone_id, host).await?; + let at: Vec<&Kept> = found + .iter() + .filter(|k| matches!(k.kind.as_str(), "A" | "AAAA" | "CNAME") && same_name(&k.name, host)) + .collect(); + let have = at + .iter() + .find(|k| k.kind == "CNAME" && k.content.eq_ignore_ascii_case(target) && ours(&k.record(), mark, host)) + .map(|k| k.record()); + let others: Vec<&Kept> = at + .iter() + .copied() + .filter(|k| have.as_ref().is_none_or(|h| h.id != k.id)) + .collect(); + let theirs: Vec<&Kept> = others + .iter() + .copied() + .filter(|k| !ours(&k.record(), mark, host)) + .collect(); + if !theirs.is_empty() && !replace { + return Ok(Switched::Confirm(theirs.iter().map(|k| k.record()).collect())); + } + for k in &others { + match cf.delete(zone_id, &k.id).await { + Ok(()) | Err(CfError::NotFound) => {} + Err(e) => return Err(e), + } + } + let previous: Vec = theirs.into_iter().cloned().collect(); + let record = match have { + Some(r) if r.proxied => r, + Some(r) => { + cf.set_proxied(zone_id, &r.id, true).await?; + Record { proxied: true, ..r } + } + None => { + cf.create( + zone_id, + &NewRecord { + kind: "CNAME".into(), + name: host.to_owned(), + content: target.to_owned(), + proxied: true, + comment: mark.to_owned(), + }, + ) + .await? + } + }; + Ok(Switched::Done { record, previous }) +} + +/// Point `host` back: Pyo's CNAME goes (only if it's still Pyo's), then +/// the kept records come back as they were. With none kept, `fallback` +/// (an A record to the cluster's public IP) is made instead, when given. +/// The record Pyo made, if any. +pub(crate) async fn revert_record( + cf: &C, + zone_id: &str, + host: &str, + record_id: Option<&str>, + previous: &[Kept], + fallback: Option<&str>, + mark: &str, +) -> Result, CfError> { + if let Some(id) = record_id { + delete_ours(cf, zone_id, id, host, mark).await?; + } + for k in previous { + cf.create_kept(zone_id, k).await?; + } + if !previous.is_empty() { + return Ok(None); + } + let Some(ip) = fallback else { + return Ok(None); + }; + Ok(Some( + cf.create( + zone_id, + &NewRecord { + kind: "A".into(), + name: host.to_owned(), + content: ip.to_owned(), + proxied: false, + comment: mark.to_owned(), + }, + ) + .await?, + )) +} + +/// A record row waiting for the loop. +#[derive(sqlx::FromRow, Debug)] +struct Waiting { + service_id: String, + domain_id: String, + hostname: String, + zone_id: String, + record_id: Option, + status: String, + previous: Value, + replace: bool, + restore: bool, + /// The routes sync it waits for: done, failed or still on its way. + routes: Option, + routes_error: Option, +} + +/// Rows switching to the tunnel or back, once the agent has the service's +/// routes for it (both paths answer then). +async fn records( + s: &AppState, + cf: &C, + row: &Row, + target: &str, + zones: &[super::Zone], + mark: &str, +) -> Result<(), Step> { + let waiting: Vec = sqlx::query_as( + "SELECT r.service_id, r.domain_id, r.hostname, r.zone_id, r.record_id, r.status, r.previous, r.replace, r.restore, + c.status AS routes, c.result->>'message' AS routes_error + FROM pyo.dns_records r JOIN pyo.services a ON a.id = r.service_id + LEFT JOIN pyo.commands c ON c.id = r.routes_command + WHERE a.cluster_id = $1 AND NOT a.deleting AND r.status IN ('switching', 'reverting') + ORDER BY r.hostname LIMIT 50", + ) + .bind(&row.cluster_id) + .fetch_all(&s.db) + .await?; + for w in waiting { + // The agent's routes first: no record moves before both paths answer. + match w.routes.as_deref() { + None | Some("done") => {} + Some("failed") => { + record_failed( + s, + &w, + &format!( + "The Gateway didn't take the change: {}", + w.routes_error.as_deref().unwrap_or("no reason given") + ), + ) + .await?; + continue; + } + Some(_) => continue, + } + let r = if w.status == "switching" { + switch_one(s, cf, row, &w, target, mark).await + } else { + revert_one(s, cf, row, &w, zones, mark).await + }; + match r { + Ok(()) => {} + Err(Step::Cf(e)) if slow_down(&e) => return Err(Step::Cf(e)), + Err(Step::Cf(e)) => record_failed(s, &w, &e.to_string()).await?, + Err(e) => return Err(e), + } + } + Ok(()) +} + +async fn record_failed(s: &AppState, w: &Waiting, error: &str) -> ApiResult<()> { + sqlx::query("UPDATE pyo.dns_records SET error = $3, updated_at = now() WHERE service_id = $1 AND domain_id = $2") + .bind(&w.service_id) + .bind(&w.domain_id) + .bind(error) + .execute(&s.db) + .await?; + Ok(()) +} + +async fn switch_one( + s: &AppState, + cf: &C, + row: &Row, + w: &Waiting, + target: &str, + mark: &str, +) -> Result<(), Step> { + let out = switch_record(cf, &w.zone_id, &w.hostname, target, w.replace, mark).await?; + let mut tx = s.db.begin().await?; + match out { + Switched::Confirm(existing) => { + sqlx::query( + "UPDATE pyo.dns_records SET status = 'conflict', existing = $3, error = NULL, updated_at = now() + WHERE service_id = $1 AND domain_id = $2", + ) + .bind(&w.service_id) + .bind(&w.domain_id) + .bind(json!(existing)) + .execute(&mut *tx) + .await?; + } + Switched::Done { record, previous } => { + // What it replaced before (a repoint after the tunnel came back) + // stays kept. + let mut kept: Vec = serde_json::from_value(w.previous.clone()).unwrap_or_default(); + kept.extend(previous.iter().cloned()); + sqlx::query( + "UPDATE pyo.dns_records SET status = 'created', via = 'tunnel', record_id = $3, type = 'CNAME', content = $4, + proxied = true, proxy = true, previous = $5, existing = '[]', error = NULL, replace = false, updated_at = now() + WHERE service_id = $1 AND domain_id = $2", + ) + .bind(&w.service_id) + .bind(&w.domain_id) + .bind(&record.id) + .bind(target) + .bind(json!(kept)) + .execute(&mut *tx) + .await?; + // Only through the tunnel now: the gate goes on, plain HTTP goes. + set_domain(&mut tx, &w.service_id, &w.domain_id, |d| { + d["tunnel"] = json!(pyo_proto::TUNNEL_ON); + d["status"] = json!("active"); + }) + .await?; + let wake = crate::routes::changed(&mut tx, &w.service_id, true).await?; + let replaced: Vec = previous + .iter() + .map(|k| format!("{} {}", k.kind, k.content)) + .collect(); + log_activity( + &mut tx, + &row.team_id, + "Pyo", + "domain.tunnel", + "success", + &if replaced.is_empty() { + format!("{} goes through the Cloudflare Tunnel", w.hostname) + } else { + format!( + "{} goes through the Cloudflare Tunnel (replaced {})", + w.hostname, + replaced.join(", ") + ) + }, + json!({ "kind": "service", "id": w.service_id, "label": w.hostname }), + json!({ "serviceId": w.service_id, "replaced": previous }), + ) + .await?; + tx.commit().await?; + if let Some(c) = wake { + s.wake(&c).await; + } + return Ok(()); + } + } + tx.commit().await?; + Ok(()) +} + +async fn revert_one( + s: &AppState, + cf: &C, + row: &Row, + w: &Waiting, + _zones: &[super::Zone], + mark: &str, +) -> Result<(), Step> { + let previous: Vec = if w.restore { + serde_json::from_value(w.previous.clone()).unwrap_or_default() + } else { + vec![] + }; + // Without a kept record, on a cluster with public ports: its own A record. + let mut tx = s.db.begin().await?; + let ip = crate::freedomain::load(&mut tx, &row.cluster_id) + .await? + .and_then(|(_, c)| c.public_ip()) + .map(|ip| ip.to_string()); + tx.commit().await?; + let fallback = ip.as_deref().filter(|_| w.restore); + let made = revert_record( + cf, + &w.zone_id, + &w.hostname, + w.record_id.as_deref(), + &previous, + fallback, + mark, + ) + .await?; + let mut tx = s.db.begin().await?; + match &made { + Some(r) => { + sqlx::query( + "UPDATE pyo.dns_records SET status = 'created', via = 'direct', record_id = $3, type = 'A', content = $4, + proxied = false, proxy = false, previous = '[]', existing = '[]', error = NULL, updated_at = now() + WHERE service_id = $1 AND domain_id = $2", + ) + .bind(&w.service_id) + .bind(&w.domain_id) + .bind(&r.id) + .bind(&r.content) + .execute(&mut *tx) + .await?; + } + None => { + sqlx::query("DELETE FROM pyo.dns_records WHERE service_id = $1 AND domain_id = $2") + .bind(&w.service_id) + .bind(&w.domain_id) + .execute(&mut *tx) + .await?; + } + } + // Direct again: its route at the tunnel goes with the next pass, and + // its certificate is what it was. + set_domain(&mut tx, &w.service_id, &w.domain_id, |d| { + leave_tunnel(d); + }) + .await?; + let wake = crate::routes::changed(&mut tx, &w.service_id, true).await?; + log_activity( + &mut tx, + &row.team_id, + "Pyo", + "domain.tunnel", + "info", + &format!("{} no longer goes through the Cloudflare Tunnel", w.hostname), + json!({ "kind": "service", "id": w.service_id, "label": w.hostname }), + json!({ "serviceId": w.service_id, "restored": previous }), + ) + .await?; + tx.commit().await?; + if let Some(c) = wake { + s.wake(&c).await; + } + Ok(()) +} + +/// A domain leaves the tunnel: no `tunnel`, and the certificate it had. +pub(crate) fn leave_tunnel(d: &mut Value) { + if let Some(o) = d.as_object_mut() { + o.remove("tunnel"); + if let Some(before) = o.remove("tlsModeBefore") { + o.insert("tlsMode".into(), before); + match o.remove("certificateIdBefore") { + Some(c) => { + o.insert("certificateId".into(), c); + } + None => { + o.remove("certificateId"); + } + } + } + } +} + +/// A tunnel domain takes the tunnel's certificate (the one it had is +/// kept to go back to). While it switches, a certificate already issued +/// for it stays (cloudflared trusts public CAs too, and direct visitors +/// still see a valid one). Whether it changed. +pub(crate) fn take_certificate(d: &mut Value, certificate_id: &str) -> bool { + let switching = d["tunnel"] == json!(pyo_proto::TUNNEL_SWITCHING); + let mode = d["tlsMode"].as_str().unwrap_or("auto").to_owned(); + let host = d["hostname"].as_str().unwrap_or("").to_owned(); + let issuer = crate::deploy::tls_issuer(&mode, &host); + let has_tunnel_cert = + issuer == "custom" && d["certificateId"] == json!(certificate_id); + if has_tunnel_cert { + return false; + } + let valid_now = (issuer == "letsencrypt" && d["tls"] == json!("issued")) || issuer == "custom"; + if switching && valid_now && d.get("tlsModeBefore").is_none() { + return false; + } + if d.get("tlsModeBefore").is_none() { + d["tlsModeBefore"] = json!(mode); + if let Some(c) = d.get("certificateId").cloned() { + d["certificateIdBefore"] = c; + } + } + d["tlsMode"] = json!("custom"); + d["certificateId"] = json!(certificate_id); + true +} + +/// Change one domain of a service's spec. +async fn set_domain( + tx: &mut Transaction<'_, Postgres>, + service_id: &str, + domain_id: &str, + f: impl FnOnce(&mut Value), +) -> ApiResult<()> { + let domains: Option = sqlx::query_scalar( + "SELECT coalesce(spec->'domains', '[]') FROM pyo.services WHERE id = $1 FOR UPDATE", + ) + .bind(service_id) + .fetch_optional(&mut **tx) + .await?; + let Some(mut domains) = domains else { + return Ok(()); + }; + if let Some(d) = domains + .as_array_mut() + .and_then(|ds| ds.iter_mut().find(|d| d["id"] == json!(domain_id))) + { + f(d); + } + sqlx::query("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1") + .bind(service_id) + .bind(&domains) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// Tunnel domains use the tunnel's certificate (see [`take_certificate`]). +/// Services whose domains changed get their routes again, and rows +/// switching for them wait for that sync. +async fn tls_follow(s: &AppState, cluster_id: &str, certificate_id: &str) -> ApiResult<()> { + let services: Vec<(String, Value)> = sqlx::query_as( + "SELECT a.id, coalesce(a.spec->'domains', '[]') FROM pyo.services a + WHERE a.cluster_id = $1 AND NOT a.deleting + AND EXISTS (SELECT 1 FROM jsonb_array_elements(a.spec->'domains') d WHERE d->>'tunnel' IN ('switching', 'on'))", + ) + .bind(cluster_id) + .fetch_all(&s.db) + .await?; + for (service_id, mut domains) in services { + let mut changed = false; + for d in domains.as_array_mut().into_iter().flatten() { + if matches!(d["tunnel"].as_str(), Some(pyo_proto::TUNNEL_SWITCHING | pyo_proto::TUNNEL_ON)) { + changed |= take_certificate(d, certificate_id); + } + } + if !changed { + continue; + } + let mut tx = s.db.begin().await?; + sqlx::query("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1") + .bind(&service_id) + .bind(&domains) + .execute(&mut *tx) + .await?; + if let Some((cluster, command)) = crate::routes::changed_waiting(&mut tx, &service_id).await? { + sqlx::query( + "UPDATE pyo.dns_records SET routes_command = $2 WHERE service_id = $1 AND status IN ('switching', 'reverting')", + ) + .bind(&service_id) + .bind(&command) + .execute(&mut *tx) + .await?; + tx.commit().await?; + s.wake(&cluster).await; + } else { + tx.commit().await?; + } + } + Ok(()) +} + +/// The default domain's wildcard record: `*.` to the tunnel, made +/// once. Someone else's record there stops it, and it's said. +async fn default_record( + s: &AppState, + cf: &C, + row: &Row, + target: &str, + mark: &str, +) -> Result<(), Step> { + let (Some(domain), Some(zone)) = (&row.default_domain, &row.default_zone_id) else { + return Ok(()); + }; + if row.default_record_id.is_some() { + return Ok(()); + } + let name = format!("*.{domain}"); + match switch_record(cf, zone, &name, target, false, mark).await? { + Switched::Done { record, .. } => { + sqlx::query("UPDATE pyo.cluster_tunnels SET default_record_id = $2 WHERE cluster_id = $1") + .bind(&row.cluster_id) + .bind(&record.id) + .execute(&s.db) + .await?; + } + Switched::Confirm(existing) => { + let what: Vec = existing + .iter() + .map(|r| format!("{} {}", r.kind, r.content)) + .collect(); + return Err(Step::Cf(CfError::Refused(format!( + "Cloudflare has a record for {name} ({}). Remove it, or pick another default domain.", + what.join(", ") + )))); + } + } + Ok(()) +} + +// ── The certificate ──────────────────────────────────────────────────────── + +/// Issue an Origin CA certificate for `names`, with a key made here. +pub(crate) async fn issue( + cf: &C, + names: &[String], +) -> Result<(OriginCert, String), CfError> { + let (csr, key) = tunnel::key_and_csr(names) + .map_err(|e| CfError::Refused(format!("Pyo couldn't make the certificate's key: {e}")))?; + let cert = match cf.issue_origin_cert(&csr, names).await { + Err(CfError::Denied(_)) => { + return Err(CfError::Denied(format!( + "give the token {} on the tunnel's zones.", + tunnel::CERTS_EDIT + ))); + } + other => other?, + }; + Ok((cert, key)) +} + +/// The tunnel's certificate covers `names` (issued again when it doesn't, +/// or when Rotate asked). Its id in the team's certificates. +async fn ensure_certificate( + s: &AppState, + cf: &C, + row: &Row, + names: &[String], +) -> Result, Step> { + let have: Option> = match &row.certificate_id { + Some(id) => sqlx::query_scalar("SELECT hostnames FROM pyo.certificates WHERE id = $1") + .bind(id) + .fetch_optional(&s.db) + .await?, + None => None, + }; + let covered = have.as_ref().is_some_and(|h| tunnel::covers_all(h, names)); + if covered && !row.rotate { + return Ok(row.certificate_id.clone()); + } + if names.is_empty() { + return Ok(row.certificate_id.clone()); + } + let (cert, key) = issue(cf, names).await?; + let now = pyo_proto::now_ms() / 1000; + let parsed = crate::certs::parse(&cert.pem, &key, now) + .map_err(|e| Step::Cf(CfError::Refused(format!("Cloudflare's certificate: {}", e.message))))?; + let sealed = crate::vault::get() + .seal_credential(&row.team_id, &parsed.key_pem) + .await?; + let id = row + .certificate_id + .clone() + .unwrap_or_else(|| crate::ids::new_id("crt")); + let cluster_name: String = sqlx::query_scalar("SELECT name FROM pyo.clusters WHERE id = $1") + .bind(&row.cluster_id) + .fetch_one(&s.db) + .await?; + let mut tx = s.db.begin().await?; + sqlx::query( + "INSERT INTO pyo.certificates (id, team_id, name, hostnames, issuer, not_before, not_after, fingerprint, chain_pem, key_sealed) + VALUES ($1, $2, $3, $4, $5, to_timestamp($6), to_timestamp($7), $8, $9, $10) + ON CONFLICT (id) DO UPDATE SET hostnames = $4, issuer = $5, not_before = to_timestamp($6), not_after = to_timestamp($7), + fingerprint = $8, chain_pem = $9, key_sealed = $10, warned_days = NULL, updated_at = now()", + ) + .bind(&id) + .bind(&row.team_id) + .bind(format!("Cloudflare Tunnel ({cluster_name})")) + .bind(&parsed.hostnames) + .bind("Cloudflare Origin CA") + .bind(parsed.not_before as f64) + .bind(parsed.not_after as f64) + .bind(&parsed.fingerprint) + .bind(&parsed.chain_pem) + .bind(&sealed) + .execute(&mut *tx) + .await?; + sqlx::query( + "UPDATE pyo.cluster_tunnels SET certificate_id = $2, cf_certificate_id = $3, rotate = rotate AND $5, + cf_certificate_old = coalesce($4, cf_certificate_old), + cf_certificate_old_at = CASE WHEN $4 IS NULL THEN cf_certificate_old_at ELSE now() + interval '1 day' END + WHERE cluster_id = $1", + ) + .bind(&row.cluster_id) + .bind(&id) + .bind(&cert.id) + .bind(&row.cf_certificate_id) + // Rotate also needs the new secret (step 6): only that clears it. + .bind(true) + .execute(&mut *tx) + .await?; + // Services using it get it again (the same id, a new chain and key). + let mut wake = vec![]; + for (service_id, _) in crate::certs::used_by(&mut tx, &id).await? { + if let Some(c) = crate::routes::changed(&mut tx, &service_id, true).await? { + wake.push(c); + } + } + log_activity( + &mut tx, + &row.team_id, + "Pyo", + "domain.certificate_replaced", + "success", + &format!("Got the Cloudflare Tunnel certificate of {cluster_name}"), + json!({ "kind": "certificate", "id": id, "label": format!("Cloudflare Tunnel ({cluster_name})") }), + json!({}), + ) + .await?; + tx.commit().await?; + wake.sort(); + wake.dedup(); + for c in wake { + s.wake(&c).await; + } + Ok(Some(id)) +} + +// ── Health ───────────────────────────────────────────────────────────────── + +/// The tunnel's health from Cloudflare's view and the agent's: +/// "connected", "degraded", "down", "starting" or "unknown". +pub fn health(cf: &Value, agent: &Value, young: bool) -> &'static str { + let status = cf["status"].as_str().unwrap_or(""); + let wanted = agent["replicas"].as_i64().unwrap_or(0); + let ready = agent["readyReplicas"].as_i64().unwrap_or(0); + match status { + "" => "unknown", + "healthy" if wanted > 0 && ready < wanted => "degraded", + "healthy" => "connected", + "degraded" => "degraded", + _ if young => "starting", + _ => "down", + } +} + +/// Keep Cloudflare's view of the tunnel, and say when it's been down for +/// 5 minutes (an alert), and when it's back. +async fn status(s: &AppState, row: &Row, t: &Tunnel) -> ApiResult<()> { + let cf_status = json!({ + "status": t.status, + "connections": t.connections, + "at": pyo_proto::now_ms(), + }); + let down = matches!(t.status.as_str(), "down" | "inactive") && !row.young; + sqlx::query( + "UPDATE pyo.cluster_tunnels SET cf_status = $2, checked_at = now(), + down_since = CASE WHEN $3 THEN coalesce(down_since, now()) ELSE NULL END + WHERE cluster_id = $1", + ) + .bind(&row.cluster_id) + .bind(&cf_status) + .bind(down) + .execute(&s.db) + .await?; + let alert = if down && !row.down_alerted && row.down_secs.unwrap_or(0) >= DOWN_ALERT_SECS { + Some(true) + } else if !down && row.down_alerted { + Some(false) + } else { + None + }; + if let Some(down) = alert { + let mut tx = s.db.begin().await?; + let name: String = sqlx::query_scalar("SELECT name FROM pyo.clusters WHERE id = $1") + .bind(&row.cluster_id) + .fetch_one(&mut *tx) + .await?; + sqlx::query("UPDATE pyo.cluster_tunnels SET down_alerted = $2 WHERE cluster_id = $1") + .bind(&row.cluster_id) + .bind(down) + .execute(&mut *tx) + .await?; + log_activity( + &mut tx, + &row.team_id, + "Pyo", + if down { "cluster.tunnel_down" } else { "cluster.tunnel_up" }, + if down { "failure" } else { "success" }, + &if down { + format!("The Cloudflare Tunnel of {name} is down") + } else { + format!("The Cloudflare Tunnel of {name} is back") + }, + json!({ "kind": "cluster", "id": row.cluster_id, "label": name }), + json!({}), + ) + .await?; + tx.commit().await?; + } + Ok(()) +} + +// ── As shown ─────────────────────────────────────────────────────────────── + +/// A tunnel as the dashboard, CLI and API show it: never a token. +pub fn shown(row: &Value) -> Value { + let cf = &row["cfStatus"]; + let agent = &row["agentStatus"]; + let connections = cf["connections"].as_array().cloned().unwrap_or_default(); + let mut colos: Vec = connections + .iter() + .filter_map(|c| c["colo"].as_str().map(str::to_owned)) + .collect(); + colos.sort(); + colos.dedup(); + let pods = agent["pods"].as_array().cloned().unwrap_or_default(); + let connectors: Vec = pods + .iter() + .map(|p| json!({ "server": p["server"], "ready": p["ready"], "reason": p["reason"] })) + .collect(); + json!({ + "state": row["state"], "error": row["error"], + "accountId": row["accountId"], "accountName": row["accountName"], + "tunnelId": row["tunnelId"], "tunnelName": row["tunnelName"], + "defaultDomain": row["defaultDomain"], "portsPublic": row["portsPublic"], + "connectors": connectors, + "colos": colos, + "connections": connections.len(), + "health": if row["state"] == "removing" { "removing" } else { health(cf, agent, row["young"] == json!(true)) }, + // The cluster's install refused the connector: its connect command + // brings the newer one. + "refused": agent["refused"] == json!(true), + "certificate": row["certificate"], + "checkedAt": cf["at"], + }) +} + +/// Each cluster's tunnel, as `tunnel` on the snapshot's clusters. +pub async fn attach( + db: &mut sqlx::PgConnection, + team_ids: &[String], + clusters: &mut [Value], +) -> ApiResult<()> { + let rows: Vec<(String, Value)> = sqlx::query_as(SHOWN).bind(team_ids).fetch_all(&mut *db).await?; + for c in clusters.iter_mut() { + if let Some((_, r)) = rows.iter().find(|(id, _)| c["id"] == json!(id)) { + c["tunnel"] = shown(r); + } + } + Ok(()) +} + +/// One cluster's tunnel, shown. None without one. +pub async fn one_shown(db: impl sqlx::PgExecutor<'_>, cluster_id: &str) -> ApiResult> { + let row: Option<(String, Value)> = sqlx::query_as(SHOWN_ONE) + .bind(cluster_id) + .fetch_optional(db) + .await?; + Ok(row.map(|(_, r)| shown(&r))) +} + +const SHOWN: &str = concat!( + "SELECT t.cluster_id, jsonb_build_object( + 'state', t.state, 'error', t.error, 'accountId', t.account_id, 'accountName', t.account_name, + 'tunnelId', t.tunnel_id, 'tunnelName', t.tunnel_name, 'defaultDomain', t.default_domain, 'portsPublic', t.ports_public, + 'cfStatus', t.cf_status, 'agentStatus', t.agent_status, 'young', t.created_at > now() - interval '5 minutes', + 'certificate', (SELECT jsonb_build_object('id', c.id, 'notAfter', pyo.ms(c.not_after)) FROM pyo.certificates c WHERE c.id = t.certificate_id)) + FROM pyo.cluster_tunnels t", + " WHERE t.team_id = ANY($1)" +); +const SHOWN_ONE: &str = concat!( + "SELECT t.cluster_id, jsonb_build_object( + 'state', t.state, 'error', t.error, 'accountId', t.account_id, 'accountName', t.account_name, + 'tunnelId', t.tunnel_id, 'tunnelName', t.tunnel_name, 'defaultDomain', t.default_domain, 'portsPublic', t.ports_public, + 'cfStatus', t.cf_status, 'agentStatus', t.agent_status, 'young', t.created_at > now() - interval '5 minutes', + 'certificate', (SELECT jsonb_build_object('id', c.id, 'notAfter', pyo.ms(c.not_after)) FROM pyo.certificates c WHERE c.id = t.certificate_id)) + FROM pyo.cluster_tunnels t", + " WHERE t.cluster_id = $1" +); + +// ── Removing a tunnel ────────────────────────────────────────────────────── + +/// Take a tunnel apart, in order: no routes but the catch-all, records +/// back (or only Pyo's deleted), the connector stopped, connections +/// dropped, the tunnel deleted, its certificate revoked. Then the row. +async fn remove( + s: &AppState, + cf: &C, + row: &Row, + zones: &[super::Zone], + mark: &str, +) -> Result<(), Step> { + if let Some(id) = &row.tunnel_id { + match cf + .put_config(&row.account_id, id, &tunnel::empty_ingress()) + .await + { + Ok(_) | Err(CfError::NotFound) => {} + Err(e) => return Err(e.into()), + } + } + // Every record through the tunnel, back. + let rows: Vec = sqlx::query_as( + "SELECT r.service_id, r.domain_id, r.hostname, r.zone_id, r.record_id, r.status, r.previous, r.replace, r.restore, + NULL::text AS routes, NULL::text AS routes_error + FROM pyo.dns_records r JOIN pyo.services a ON a.id = r.service_id + WHERE a.cluster_id = $1 AND (r.via = 'tunnel' OR r.status IN ('switching', 'reverting'))", + ) + .bind(&row.cluster_id) + .fetch_all(&s.db) + .await?; + for mut w in rows { + w.restore = row.restore_records; + revert_one(s, cf, row, &w, zones, mark).await?; + } + // Domains that never had a record: no longer through the tunnel. + let services: Vec = sqlx::query_scalar( + "SELECT a.id FROM pyo.services a WHERE a.cluster_id = $1 + AND EXISTS (SELECT 1 FROM jsonb_array_elements(a.spec->'domains') d WHERE d ? 'tunnel')", + ) + .bind(&row.cluster_id) + .fetch_all(&s.db) + .await?; + for service_id in services { + let mut tx = s.db.begin().await?; + let domains: Value = sqlx::query_scalar("SELECT coalesce(spec->'domains', '[]') FROM pyo.services WHERE id = $1 FOR UPDATE") + .bind(&service_id) + .fetch_one(&mut *tx) + .await?; + let mut domains = domains; + for d in domains.as_array_mut().into_iter().flatten() { + leave_tunnel(d); + } + sqlx::query("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1") + .bind(&service_id) + .bind(&domains) + .execute(&mut *tx) + .await?; + let wake = crate::routes::changed(&mut tx, &service_id, true).await?; + tx.commit().await?; + if let Some(c) = wake { + s.wake(&c).await; + } + } + // The default domain's wildcard, only if it's still Pyo's. + if let (Some(zone), Some(id), Some(domain)) = + (&row.default_zone_id, &row.default_record_id, &row.default_domain) + { + delete_ours(cf, zone, id, &format!("*.{domain}"), mark).await?; + } + // The connector: asked once, then waited for (or 10 minutes). + let agent_has = row.agent_status["tunnelId"].as_str().is_some(); + if agent_has && row.removing_secs < REMOVE_WAIT_SECS { + if row.token_due { + let mut tx = s.db.begin().await?; + crate::deploy::enqueue( + &mut tx, + &row.cluster_id, + pyo_proto::Command::TunnelRemove {}, + ) + .await?; + sqlx::query("UPDATE pyo.cluster_tunnels SET token_sent_at = now() WHERE cluster_id = $1") + .bind(&row.cluster_id) + .execute(&mut *tx) + .await?; + tx.commit().await?; + s.wake(&row.cluster_id).await; + } + return Ok(()); + } + if let Some(id) = &row.tunnel_id { + match cf.drop_connections(&row.account_id, id).await { + Ok(()) | Err(CfError::NotFound) => {} + Err(e) => return Err(e.into()), + } + match cf.delete_tunnel(&row.account_id, id).await { + Ok(()) | Err(CfError::NotFound) => {} + Err(e) => return Err(e.into()), + } + } + for c in [&row.cf_certificate_id, &row.cf_certificate_old].into_iter().flatten() { + match cf.revoke_origin_cert(c).await { + Ok(()) | Err(CfError::NotFound) => {} + Err(e) => return Err(e.into()), + } + } + let mut tx = s.db.begin().await?; + sqlx::query("DELETE FROM pyo.cluster_tunnels WHERE cluster_id = $1") + .bind(&row.cluster_id) + .execute(&mut *tx) + .await?; + if let Some(cert) = &row.certificate_id + && crate::certs::used_by(&mut tx, cert).await?.is_empty() + { + sqlx::query("DELETE FROM pyo.certificates WHERE id = $1") + .bind(cert) + .execute(&mut *tx) + .await?; + } + log_activity( + &mut tx, + &row.team_id, + "Pyo", + "cluster.tunnel_removed", + "info", + "Removed the Cloudflare Tunnel", + json!({ "kind": "cluster", "id": row.cluster_id, "label": row.tunnel_name }), + json!({}), + ) + .await?; + tx.commit().await?; + Ok(()) +} + +#[cfg(test)] +#[path = "tunnel_loop_tests.rs"] +mod tests; diff --git a/crates/pyo-api/src/cloudflare/tunnel_loop_tests.rs b/crates/pyo-api/src/cloudflare/tunnel_loop_tests.rs new file mode 100644 index 00000000..6aed3893 --- /dev/null +++ b/crates/pyo-api/src/cloudflare/tunnel_loop_tests.rs @@ -0,0 +1,279 @@ +//! The tunnel loop's steps against the fake Cloudflare account: the tunnel +//! made, taken back or made again, records switched and put back exactly, +//! only Pyo's own records deleted, the certificate issued, and the health +//! it shows. + +use serde_json::json; + +use super::*; +use crate::cloudflare::tests::{Dns, Fake, MARK, rec}; + +const TARGET: &str = "00000000-0000-4000-8000-000000000001.cfargotunnel.com"; + +fn row() -> Row { + Row { + cluster_id: "cl_1".into(), + team_id: "team_1".into(), + account_id: "acct1".into(), + tunnel_name: "pyo-cl_1-abc123".into(), + state: "creating".into(), + ..Default::default() + } +} + +#[tokio::test] +async fn a_tunnel_is_made_taken_back_or_made_again() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let mut r = row(); + let (t, again) = ensure_tunnel(&cf, &r, "abc123").await.unwrap(); + assert_eq!(t.name, "pyo-cl_1-abc123"); + assert!(!again); + // A pass that stopped before keeping its id: the same tunnel, not a second. + let (same, _) = ensure_tunnel(&cf, &r, "abc123").await.unwrap(); + assert_eq!(same.id, t.id); + assert_eq!(cf.tunnel_list().len(), 1); + // Kept: read, not made. + r.tunnel_id = Some(t.id.clone()); + let (kept, again) = ensure_tunnel(&cf, &r, "abc123").await.unwrap(); + assert_eq!((kept.id.as_str(), again), (t.id.as_str(), false)); + // Deleted by hand in Cloudflare: a new one, with a name of its own. + cf.tunnels.lock().unwrap()[0].1.deleted = true; + let (new, again) = ensure_tunnel(&cf, &r, "abc123").await.unwrap(); + assert!(again); + assert_ne!(new.id, t.id); + // Its name is free again once the old one is deleted. + assert_eq!(new.name, "pyo-cl_1-abc123"); + // Taken by a live one (a pass that stopped halfway): the next name. + r.tunnel_id = Some("00000000-0000-4000-8000-00000000ffff".into()); + let (third, again) = ensure_tunnel(&cf, &r, "abc123").await.unwrap(); + assert!(again); + assert_eq!(third.name, "pyo-cl_1-abc123-2"); +} + +#[tokio::test] +async fn someone_elses_tunnel_is_never_taken() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + cf.tunnels.lock().unwrap().push(( + "acct1".into(), + tunnel::Tunnel { + id: "11111111-2222-4333-8444-555555555555".into(), + name: "pyo-cl_1-zzz999".into(), + ..Default::default() + }, + )); + let (t, _) = ensure_tunnel(&cf, &row(), "abc123").await.unwrap(); + assert_eq!(t.name, "pyo-cl_1-abc123"); + assert_ne!(t.id, "11111111-2222-4333-8444-555555555555"); +} + +#[tokio::test] +async fn a_free_name_switches_without_asking() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let out = switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap(); + let Switched::Done { record, previous } = out else { + panic!("{out:?}") + }; + assert_eq!( + (record.kind.as_str(), record.content.as_str(), record.proxied), + ("CNAME", TARGET, true) + ); + assert_eq!(record.comment.as_deref(), Some(MARK)); + assert!(previous.is_empty()); + // Again: nothing more to do. + let again = switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap(); + assert!(matches!(again, Switched::Done { ref previous, .. } if previous.is_empty())); + assert_eq!(cf.at("z1").len(), 1); +} + +#[tokio::test] +async fn pyos_own_direct_record_goes_without_asking_and_isnt_kept() { + let mine = rec("m1", "A", "blog.example.com", "203.0.113.7", Some(MARK)); + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]).with("z1", mine); + let out = switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap(); + assert!(matches!(out, Switched::Done { ref previous, .. } if previous.is_empty())); + let now = cf.at("z1"); + assert_eq!(now.len(), 1); + assert_eq!(now[0].kind, "CNAME"); +} + +#[tokio::test] +async fn someone_elses_record_asks_first_then_is_kept_and_put_back_exactly() { + let mut theirs = rec("t1", "A", "blog.example.com", "198.51.100.9", Some("by hand")); + theirs.proxied = true; + let mx = rec("x1", "MX", "blog.example.com", "mail.example.com", None); + let other = rec("o1", "A", "shop.example.com", "198.51.100.9", None); + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]) + .with("z1", theirs.clone()) + .with("z1", mx.clone()) + .with("z1", other.clone()); + cf.ttls.lock().unwrap().insert("t1".into(), 300); + // Asked first: nothing changes. + let out = switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap(); + assert_eq!(out, Switched::Confirm(vec![theirs.clone()])); + assert_eq!(cf.at("z1").len(), 3); + // Replaced: kept as it was, every field. + let Switched::Done { record, previous } = + switch_record(&cf, "z1", "blog.example.com", TARGET, true, MARK) + .await + .unwrap() + else { + panic!("not switched") + }; + assert_eq!(previous.len(), 1); + let k = &previous[0]; + assert_eq!( + (k.kind.as_str(), k.content.as_str(), k.proxied, k.ttl, k.comment.as_deref()), + ("A", "198.51.100.9", true, 300, Some("by hand")) + ); + // Other types and names stay. + let names: Vec = cf.at("z1").iter().map(|r| r.id.clone()).collect(); + assert!(names.contains(&"x1".to_owned()) && names.contains(&"o1".to_owned())); + // Switch back: Pyo's CNAME goes, the kept record comes back as it was. + let made = revert_record(&cf, "z1", "blog.example.com", Some(&record.id), &previous, Some("203.0.113.7"), MARK) + .await + .unwrap(); + assert_eq!(made, None, "a kept record wins over the public IP"); + let back: Vec = cf + .at("z1") + .into_iter() + .filter(|r| r.name == "blog.example.com" && r.kind != "MX") + .collect(); + assert_eq!(back.len(), 1); + assert_eq!( + (back[0].kind.as_str(), back[0].content.as_str(), back[0].proxied, back[0].comment.as_deref()), + ("A", "198.51.100.9", true, Some("by hand")) + ); + assert_eq!(cf.ttls.lock().unwrap().get(&back[0].id), Some(&300)); +} + +#[tokio::test] +async fn switching_back_without_a_kept_record() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let Switched::Done { record, .. } = + switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap() + else { + panic!("not switched") + }; + // Public ports: Pyo's own A record to the cluster. + let made = revert_record(&cf, "z1", "blog.example.com", Some(&record.id), &[], Some("203.0.113.7"), MARK) + .await + .unwrap() + .expect("an A record"); + assert_eq!((made.kind.as_str(), made.content.as_str()), ("A", "203.0.113.7")); + assert_eq!(made.comment.as_deref(), Some(MARK)); + assert_eq!(cf.at("z1").len(), 1); + // Neither: the name is left empty. + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let Switched::Done { record, .. } = + switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap() + else { + panic!("not switched") + }; + assert_eq!( + revert_record(&cf, "z1", "blog.example.com", Some(&record.id), &[], None, MARK) + .await + .unwrap(), + None + ); + assert!(cf.at("z1").is_empty()); +} + +#[tokio::test] +async fn a_cname_changed_by_hand_is_left_when_switching_back() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let Switched::Done { record, .. } = + switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap() + else { + panic!("not switched") + }; + // Someone took the comment off: no longer Pyo's. + for (_, r) in cf.records.lock().unwrap().iter_mut() { + r.comment = Some("mine now".into()); + } + revert_record(&cf, "z1", "blog.example.com", Some(&record.id), &[], None, MARK) + .await + .unwrap(); + assert_eq!(cf.at("z1").len(), 1, "not Pyo's to delete"); +} + +#[tokio::test] +async fn a_cname_to_an_old_tunnel_is_repointed() { + let old = rec("c1", "CNAME", "blog.example.com", "old.cfargotunnel.com", Some(MARK)); + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]).with("z1", old); + let out = switch_record(&cf, "z1", "blog.example.com", TARGET, false, MARK) + .await + .unwrap(); + assert!(matches!(out, Switched::Done { .. })); + let now = cf.at("z1"); + assert_eq!(now.len(), 1); + assert_eq!(now[0].content, TARGET); +} + +#[tokio::test] +async fn the_certificate_is_issued_for_the_names_with_a_key_kept_here() { + let cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + let names = vec!["*.example.com".to_owned(), "example.com".to_owned()]; + let (cert, key) = issue(&cf, &names).await.unwrap(); + assert!(key.contains("PRIVATE KEY")); + let issued = cf.certs.lock().unwrap().clone(); + assert_eq!(issued, vec![(cert.id.clone(), names.clone(), false)]); + // Without SSL and Certificates:Edit: said plainly. + let mut cf = Fake::new(&[("z1", "example.com", Dns::Edit)]); + cf.no_certs = vec!["z1".into()]; + let e = issue(&cf, &names).await.unwrap_err(); + assert_eq!( + e.to_string(), + "Cloudflare refused the token: give the token SSL and Certificates:Edit on the tunnel's zones." + ); +} + +#[test] +fn health_from_both_views() { + let agent = |w: i64, r: i64| json!({ "replicas": w, "readyReplicas": r }); + assert_eq!(health(&json!({}), &agent(2, 2), false), "unknown"); + assert_eq!(health(&json!({ "status": "healthy" }), &agent(2, 2), false), "connected"); + assert_eq!(health(&json!({ "status": "healthy" }), &agent(2, 1), false), "degraded"); + assert_eq!(health(&json!({ "status": "degraded" }), &agent(2, 2), false), "degraded"); + assert_eq!(health(&json!({ "status": "inactive" }), &agent(2, 0), true), "starting"); + assert_eq!(health(&json!({ "status": "down" }), &agent(2, 0), false), "down"); + assert_eq!(health(&json!({ "status": "inactive" }), &json!({}), false), "down"); +} + +#[test] +fn domains_take_the_tunnel_certificate_and_give_it_back() { + // Switching with a certificate already issued: kept, both paths answer. + let mut d = json!({ "id": "dom_1", "hostname": "blog.example.com", "tlsMode": "auto", "tls": "issued", "tunnel": "switching" }); + assert!(!take_certificate(&mut d, "crt_t")); + assert_eq!(d["tlsMode"], "auto"); + // Switched: the tunnel's, the old one kept. + d["tunnel"] = json!("on"); + assert!(take_certificate(&mut d, "crt_t")); + assert_eq!((d["tlsMode"].as_str(), d["certificateId"].as_str()), (Some("custom"), Some("crt_t"))); + assert_eq!(d["tlsModeBefore"], "auto"); + assert!(!take_certificate(&mut d, "crt_t"), "already"); + leave_tunnel(&mut d); + assert_eq!(d["tlsMode"], "auto"); + assert!(d.get("certificateId").is_none() && d.get("tunnel").is_none() && d.get("tlsModeBefore").is_none()); + // Not issued yet (a new domain): the tunnel's at once, even while switching. + let mut d = json!({ "id": "dom_2", "hostname": "new.example.com", "tlsMode": "auto", "tls": "pending", "tunnel": "switching" }); + assert!(take_certificate(&mut d, "crt_t")); + // An uploaded one comes back with its own id. + let mut d = json!({ "id": "dom_3", "hostname": "up.example.com", "tlsMode": "custom", "certificateId": "crt_mine", "tunnel": "on" }); + assert!(take_certificate(&mut d, "crt_t")); + leave_tunnel(&mut d); + assert_eq!((d["tlsMode"].as_str(), d["certificateId"].as_str()), (Some("custom"), Some("crt_mine"))); +} diff --git a/crates/pyo-api/src/cloudflare/tunnel_ops.rs b/crates/pyo-api/src/cloudflare/tunnel_ops.rs new file mode 100644 index 00000000..f427cabd --- /dev/null +++ b/crates/pyo-api/src/cloudflare/tunnel_ops.rs @@ -0,0 +1,678 @@ +//! What people ask of a cluster's Cloudflare Tunnel (docs/cloudflare-tunnel.md +//! §5): the cluster's traffic, a domain through the tunnel or back, Rotate +//! and Remove. These only say what's wanted and return at once. The tunnel +//! loop (tunnel_loop.rs) does the Cloudflare work, so a slow Cloudflare +//! never holds a request. + +use serde_json::{Value, json}; +use sqlx::{Postgres, Transaction}; + +use super::{Action, Zone, account, role_for, tunnel, zone_for}; +use crate::{ + AppState, + auth::User, + error::{ApiError, ApiResult}, + ops::{Role, log_activity, require_role, team_of}, +}; + +/// The traffic choices. +pub const MODES: [&str; 3] = ["public", "tailscale", "tunnel"]; + +/// Said when the cluster's install can't run a tunnel yet. +pub const INSTALL_FIRST: &str = "Run the command under Refresh this cluster in the cluster's settings first."; + +fn bad(m: impl Into) -> ApiError { + ApiError::bad_request(m.into()) +} + +/// The zones a tunnel in `account_id` may take: tunnel-ready, in that +/// account. +pub fn tunnel_zones<'a>(zones: &'a [Zone], account_id: &str) -> Vec<&'a Zone> { + zones + .iter() + .filter(|z| z.tunnel_ready() && z.account_id == account_id) + .collect() +} + +/// The account a tunnel goes in: the one asked for, else the default +/// domain's, else the only one with tunnel-ready zones. +pub fn pick_account( + zones: &[Zone], + asked: Option<&str>, + default_domain: Option<&str>, +) -> Result { + let mut accounts: Vec<&str> = zones + .iter() + .filter(|z| z.tunnel_ready() && !z.account_id.is_empty()) + .map(|z| z.account_id.as_str()) + .collect(); + accounts.sort(); + accounts.dedup(); + if accounts.is_empty() { + return Err("Give the Cloudflare token Cloudflare Tunnel:Edit and SSL and Certificates:Edit, then test it under Integrations.".into()); + } + if let Some(a) = asked { + return if accounts.contains(&a) { + Ok(a.to_owned()) + } else { + Err("The token can't make tunnels in that Cloudflare account.".into()) + }; + } + if let Some(d) = default_domain + && let Some(z) = zones.iter().find(|z| z.name == d) + { + return Ok(z.account_id.clone()); + } + match accounts.as_slice() { + [one] => Ok((*one).to_owned()), + _ => Err("Pick the Cloudflare account for the tunnel.".into()), + } +} + +/// The default domain as given: a tunnel-ready zone's own name (its apex), +/// since Cloudflare's free certificate covers only one level below it. +pub fn default_domain<'a>(zones: &'a [&'a Zone], given: &str) -> Result<&'a Zone, String> { + let d = given.trim().trim_end_matches('.').trim_start_matches("*.").to_ascii_lowercase(); + zones + .iter() + .copied() + .find(|z| z.name == d) + .ok_or_else(|| { + if zones.iter().any(|z| d.ends_with(&format!(".{}", z.name))) { + format!("Pick a zone itself, like {}, not a name under it.", zones[0].name) + } else { + "Pick one of your Cloudflare zones that can use the tunnel.".into() + } + }) +} + +/// Whether a cluster's install can run a tunnel: its agent says it can, +/// and its install is this Pyo's (the admission policy lets the connector +/// in). Why not, when it can't. +pub fn install_ready(capabilities: &Value) -> Result<(), &'static str> { + if capabilities["tunnel"] != json!(true) { + return Err("This cluster's agent doesn't run Cloudflare Tunnel yet. Update the agent first."); + } + match capabilities["agentInstall"]["state"].as_str() { + Some("current") | None => Ok(()), + _ => Err(INSTALL_FIRST), + } +} + +/// A domain that can go through the tunnel: a hostname a tunnel-ready zone +/// of the tunnel's account covers. Not a free or tailnet domain. +fn can_tunnel(host: &str, zones: &[Zone], account_id: &str) -> Option { + if crate::freedomain::ip_in(host).is_some() || pyo_proto::system::is_tailnet_host(host) { + return None; + } + zone_for(host, zones) + .filter(|z| z.tunnel_ready() && z.account_id == account_id) + .cloned() +} + +/// Ask for a domain's switch to the tunnel: its domain takes +/// `tunnel: "switching"` (both paths answer), its record row waits for the +/// loop, which moves the record once the agent has the routes. +async fn begin_switch( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + service_id: &str, + domain_id: &str, + host: &str, + zone: &Zone, + replace: bool, +) -> ApiResult<()> { + sqlx::query( + "INSERT INTO pyo.dns_records (service_id, domain_id, team_id, hostname, zone_id, zone_name, type, status, replace, routes_command) + VALUES ($1, $2, $3, $4, $5, $6, 'CNAME', 'switching', $7, NULL) + ON CONFLICT (service_id, domain_id) DO UPDATE SET hostname = $4, zone_id = $5, zone_name = $6, status = 'switching', + replace = $7, error = NULL, existing = '[]', updated_at = now()", + ) + .bind(service_id) + .bind(domain_id) + .bind(team_id) + .bind(host) + .bind(&zone.id) + .bind(&zone.name) + .bind(replace) + .execute(&mut **tx) + .await?; + set_tunnel(tx, service_id, domain_id, Some(pyo_proto::TUNNEL_SWITCHING)).await +} + +async fn set_tunnel( + tx: &mut Transaction<'_, Postgres>, + service_id: &str, + domain_id: &str, + state: Option<&str>, +) -> ApiResult<()> { + let domains: Value = sqlx::query_scalar( + "SELECT coalesce(spec->'domains', '[]') FROM pyo.services WHERE id = $1 FOR UPDATE", + ) + .bind(service_id) + .fetch_one(&mut **tx) + .await?; + let mut domains = domains; + if let Some(d) = domains + .as_array_mut() + .and_then(|ds| ds.iter_mut().find(|d| d["id"] == json!(domain_id))) + { + match state { + Some(s) => { + d["tunnel"] = json!(s); + // Cloudflare's address, not the cluster's: the loop says + // when it's ready. + d["status"] = json!("pending_dns"); + } + None => super::tunnel_loop::leave_tunnel(d), + } + } + sqlx::query("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1") + .bind(service_id) + .bind(&domains) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// The service's routes follow, and its waiting rows wait for that sync. +async fn sync( + tx: &mut Transaction<'_, Postgres>, + service_id: &str, + wake: &mut Vec, +) -> ApiResult<()> { + if let Some((cluster, command)) = crate::routes::changed_waiting(tx, service_id).await? { + sqlx::query( + "UPDATE pyo.dns_records SET routes_command = $2 WHERE service_id = $1 AND status IN ('switching', 'reverting')", + ) + .bind(service_id) + .bind(&command) + .execute(&mut **tx) + .await?; + wake.push(cluster); + } + Ok(()) +} + +/// `setClusterTraffic`. +#[allow(clippy::too_many_arguments)] +pub async fn set_traffic( + s: &AppState, + tx: &mut Transaction<'_, Postgres>, + user: &User, + cluster_id: &str, + mode: &str, + default_domain_given: Option<&str>, + account_asked: Option<&str>, + ports_public: Option, + wake: &mut Vec, +) -> ApiResult { + let team_id = team_of(tx, "clusters", cluster_id).await?; + require_role(tx, user, &team_id, Role::Admin).await?; + if !MODES.contains(&mode) { + return Err(bad("Pick public, tailscale or tunnel.")); + } + let (name, caps): (String, Value) = + sqlx::query_as("SELECT name, coalesce(capabilities, '{}') FROM pyo.clusters WHERE id = $1") + .bind(cluster_id) + .fetch_one(&mut **tx) + .await?; + if mode != "tunnel" { + sqlx::query("UPDATE pyo.clusters SET traffic = $2 WHERE id = $1") + .bind(cluster_id) + .bind(mode) + .execute(&mut **tx) + .await?; + log_activity( + tx, + &team_id, + &user.name, + "cluster.updated", + "info", + &format!( + "{name} takes traffic {}", + if mode == "public" { "on public ports" } else { "from Tailscale only" } + ), + json!({ "kind": "cluster", "id": cluster_id, "label": name }), + json!({ "clusterId": cluster_id }), + ) + .await?; + wake.push(cluster_id.to_owned()); + return Ok(json!({ "ok": true, "traffic": mode })); + } + install_ready(&caps).map_err(bad)?; + let a = account(s, tx, &team_id) + .await? + .ok_or_else(|| bad("Connect Cloudflare under Integrations first."))?; + let given = default_domain_given.map(str::trim).filter(|d| !d.is_empty()); + let account_id = pick_account(&a.zones, account_asked, given).map_err(bad)?; + let usable = tunnel_zones(&a.zones, &account_id); + let default = match given { + Some(d) => Some(default_domain(&usable, d).map_err(bad)?.clone()), + None => None, + }; + let account_name = usable + .first() + .map(|z| z.account_name.clone()) + .unwrap_or_default(); + let existing: Option<(String, String, Option, Option, Option)> = sqlx::query_as( + "SELECT state, account_id, default_domain, default_zone_id, default_record_id FROM pyo.cluster_tunnels WHERE cluster_id = $1 FOR UPDATE", + ) + .bind(cluster_id) + .fetch_optional(&mut **tx) + .await?; + match existing { + Some((state, _, _, _, _)) if state == "removing" => { + return Err(ApiError::conflict( + "The tunnel is still being removed. Try again in a minute.", + )); + } + Some((_, had_account, _, _, _)) if had_account != account_id => { + return Err(ApiError::conflict( + "This cluster's tunnel is in another Cloudflare account. Remove the tunnel first.", + )); + } + Some((_, _, old_domain, old_zone, old_record)) => { + // Another default domain: Pyo's old wildcard record goes. + if old_domain.as_deref() != default.as_ref().map(|z| z.name.as_str()) + && let (Some(zone), Some(id), Some(d)) = (&old_zone, &old_record, &old_domain) + { + let mark = super::marker(&super::install_id(tx).await?); + super::delete_ours(&super::Http::new(&a.token)?, zone, id, &format!("*.{d}"), &mark) + .await + .map_err(super::api_error)?; + } + sqlx::query( + "UPDATE pyo.cluster_tunnels SET default_domain = $2, default_zone_id = $3, + default_record_id = CASE WHEN default_domain IS DISTINCT FROM $2 THEN NULL ELSE default_record_id END, + ports_public = coalesce($4, ports_public), updated_at = now() + WHERE cluster_id = $1", + ) + .bind(cluster_id) + .bind(default.as_ref().map(|z| &z.name)) + .bind(default.as_ref().map(|z| &z.id)) + .bind(ports_public) + .execute(&mut **tx) + .await?; + } + None => { + let install = super::install_id(tx).await?; + sqlx::query( + "INSERT INTO pyo.cluster_tunnels (cluster_id, team_id, account_id, account_name, tunnel_name, default_domain, default_zone_id, ports_public, created_by) + VALUES ($1, $2, $3, $4, $5, $6, $7, coalesce($8, true), $9)", + ) + .bind(cluster_id) + .bind(&team_id) + .bind(&account_id) + .bind(&account_name) + .bind(tunnel::tunnel_name(cluster_id, &install, 0)) + .bind(default.as_ref().map(|z| &z.name)) + .bind(default.as_ref().map(|z| &z.id)) + .bind(ports_public) + .bind(&user.name) + .execute(&mut **tx) + .await?; + log_activity( + tx, + &team_id, + &user.name, + "cluster.tunnel_created", + "info", + &format!("Asked Cloudflare for a tunnel for {name}"), + json!({ "kind": "cluster", "id": cluster_id, "label": name }), + json!({ "clusterId": cluster_id, "accountId": account_id }), + ) + .await?; + } + } + sqlx::query("UPDATE pyo.clusters SET traffic = 'tunnel' WHERE id = $1") + .bind(cluster_id) + .execute(&mut **tx) + .await?; + // Its domains in the account move to the tunnel. Those with someone + // else's record wait at "confirm" for an owner or admin. + let services: Vec<(String, Value)> = sqlx::query_as( + "SELECT id, coalesce(spec->'domains', '[]') FROM pyo.services WHERE cluster_id = $1 AND NOT deleting ORDER BY id", + ) + .bind(cluster_id) + .fetch_all(&mut **tx) + .await?; + let mut moving = 0; + for (service_id, domains) in services { + let mut any = false; + for d in domains.as_array().into_iter().flatten() { + let host = d["hostname"].as_str().unwrap_or("").to_lowercase(); + if d["tunnel"].is_string() { + continue; + } + let Some(zone) = can_tunnel(&host, &a.zones, &account_id) else { + continue; + }; + let domain_id = d["id"].as_str().unwrap_or(""); + begin_switch(tx, &team_id, &service_id, domain_id, &host, &zone, false).await?; + any = true; + moving += 1; + } + if any { + sync(tx, &service_id, wake).await?; + } + } + log_activity( + tx, + &team_id, + &user.name, + "cluster.updated", + "info", + &format!("{name} takes websites through Cloudflare Tunnel"), + json!({ "kind": "cluster", "id": cluster_id, "label": name }), + json!({ "clusterId": cluster_id, "moving": moving }), + ) + .await?; + wake.push(cluster_id.to_owned()); + Ok(json!({ "ok": true, "traffic": "tunnel", "moving": moving })) +} + +/// `setDomainTunnel`. +#[allow(clippy::too_many_arguments)] +pub async fn set_domain( + s: &AppState, + tx: &mut Transaction<'_, Postgres>, + user: &User, + service_id: &str, + domain_id: &str, + on: bool, + replace: bool, + restore: bool, + wake: &mut Vec, +) -> ApiResult { + let team_id = team_of(tx, "services", service_id).await?; + let (cluster_id, domains): (String, Value) = sqlx::query_as( + "SELECT cluster_id, coalesce(spec->'domains', '[]') FROM pyo.services WHERE id = $1 AND NOT deleting", + ) + .bind(service_id) + .fetch_optional(&mut **tx) + .await? + .ok_or_else(|| ApiError::not_found("Service"))?; + let d = domains + .as_array() + .and_then(|ds| ds.iter().find(|d| d["id"] == json!(domain_id))) + .cloned() + .ok_or_else(|| ApiError::not_found("Domain"))?; + let host = d["hostname"].as_str().unwrap_or("").to_lowercase(); + let row: Option<(String, String, Option, Value)> = sqlx::query_as( + "SELECT r.status, r.via, NULL::text, r.previous FROM pyo.dns_records r WHERE r.service_id = $1 AND r.domain_id = $2", + ) + .bind(service_id) + .bind(domain_id) + .fetch_optional(&mut **tx) + .await?; + let kept = row + .as_ref() + .is_some_and(|r| r.3.as_array().is_some_and(|a| !a.is_empty())); + // Replacing someone's record, or putting one back: owners and admins. + let action = if replace || (!on && restore && kept) { + Action::ReplaceRecord + } else { + Action::CreateRecord + }; + require_role(tx, user, &team_id, role_for(action)).await?; + let tunnel_row: Option<(String, String)> = sqlx::query_as( + "SELECT state, account_id FROM pyo.cluster_tunnels WHERE cluster_id = $1", + ) + .bind(&cluster_id) + .fetch_optional(&mut **tx) + .await?; + let Some((state, account_id)) = tunnel_row.filter(|(st, _)| st != "removing") else { + return Err(bad("This cluster has no Cloudflare Tunnel. Pick Cloudflare Tunnel under the cluster's Traffic first.")); + }; + let _ = state; + let status = row.as_ref().map(|r| r.0.as_str()).unwrap_or(""); + let via = row.as_ref().map(|r| r.1.as_str()).unwrap_or("direct"); + if on { + let a = account(s, tx, &team_id) + .await? + .ok_or_else(|| bad("Connect Cloudflare under Integrations first."))?; + let Some(zone) = can_tunnel(&host, &a.zones, &account_id) else { + return Err(bad(format!( + "No zone of the tunnel's Cloudflare account can take {host} through the tunnel." + ))); + }; + if via == "tunnel" && status == "created" { + return Ok(json!({ "ok": true, "status": "active" })); + } + begin_switch(tx, &team_id, service_id, domain_id, &host, &zone, replace).await?; + sync(tx, service_id, wake).await?; + log_activity( + tx, + &team_id, + &user.name, + "domain.tunnel", + "info", + &format!("Asked to move {host} to the Cloudflare Tunnel"), + json!({ "kind": "service", "id": service_id, "label": host }), + json!({ "serviceId": service_id, "replace": replace }), + ) + .await?; + return Ok(json!({ "ok": true, "status": "switching" })); + } + // Back. A switch that never moved the record (still switching, or + // waiting for a yes) just stops. + if via != "tunnel" { + if d["tunnel"].is_string() { + set_tunnel(tx, service_id, domain_id, None).await?; + sqlx::query( + "DELETE FROM pyo.dns_records WHERE service_id = $1 AND domain_id = $2 AND status IN ('switching', 'conflict') AND via = 'direct'", + ) + .bind(service_id) + .bind(domain_id) + .execute(&mut **tx) + .await?; + sync(tx, service_id, wake).await?; + } + return Ok(json!({ "ok": true, "status": "direct" })); + } + sqlx::query( + "UPDATE pyo.dns_records SET status = 'reverting', restore = $3, error = NULL, updated_at = now() + WHERE service_id = $1 AND domain_id = $2", + ) + .bind(service_id) + .bind(domain_id) + .bind(restore) + .execute(&mut **tx) + .await?; + // Both paths again before the record moves back. + set_tunnel(tx, service_id, domain_id, Some(pyo_proto::TUNNEL_SWITCHING)).await?; + sync(tx, service_id, wake).await?; + log_activity( + tx, + &team_id, + &user.name, + "domain.tunnel", + "info", + &format!("Asked to move {host} back from the Cloudflare Tunnel"), + json!({ "kind": "service", "id": service_id, "label": host }), + json!({ "serviceId": service_id, "restore": restore }), + ) + .await?; + Ok(json!({ "ok": true, "status": "reverting" })) +} + +/// `removeClusterTunnel`. +pub async fn remove( + tx: &mut Transaction<'_, Postgres>, + user: &User, + cluster_id: &str, + restore_records: bool, + wake: &mut Vec, +) -> ApiResult { + let team_id = team_of(tx, "clusters", cluster_id).await?; + require_role(tx, user, &team_id, Role::Admin).await?; + let (name, traffic): (String, String) = + sqlx::query_as("SELECT name, traffic FROM pyo.clusters WHERE id = $1") + .bind(cluster_id) + .fetch_one(&mut **tx) + .await?; + if traffic == "tunnel" { + return Err(bad( + "Pick Public ports or Tailscale only for the cluster first.", + )); + } + let n = sqlx::query( + "UPDATE pyo.cluster_tunnels SET state = 'removing', restore_records = $2, token_sent_at = NULL, updated_at = now() + WHERE cluster_id = $1 AND state <> 'removing'", + ) + .bind(cluster_id) + .bind(restore_records) + .execute(&mut **tx) + .await? + .rows_affected(); + if n > 0 { + log_activity( + tx, + &team_id, + &user.name, + "cluster.tunnel_removing", + "warning", + &format!("Removing the Cloudflare Tunnel of {name}"), + json!({ "kind": "cluster", "id": cluster_id, "label": name }), + json!({ "clusterId": cluster_id, "restoreRecords": restore_records }), + ) + .await?; + } + wake.push(cluster_id.to_owned()); + Ok(json!({ "ok": true })) +} + +/// `rotateTunnelToken`. +pub async fn rotate( + tx: &mut Transaction<'_, Postgres>, + user: &User, + cluster_id: &str, +) -> ApiResult { + let team_id = team_of(tx, "clusters", cluster_id).await?; + require_role(tx, user, &team_id, Role::Admin).await?; + let n = sqlx::query( + "UPDATE pyo.cluster_tunnels SET rotate = true WHERE cluster_id = $1 AND state <> 'removing'", + ) + .bind(cluster_id) + .execute(&mut **tx) + .await? + .rows_affected(); + if n == 0 { + return Err(ApiError::not_found("Cloudflare Tunnel")); + } + let name: String = sqlx::query_scalar("SELECT name FROM pyo.clusters WHERE id = $1") + .bind(cluster_id) + .fetch_one(&mut **tx) + .await?; + log_activity( + tx, + &team_id, + &user.name, + "cluster.tunnel_rotated", + "info", + &format!("Asked for a new Cloudflare Tunnel token and certificate for {name}"), + json!({ "kind": "cluster", "id": cluster_id, "label": name }), + json!({ "clusterId": cluster_id }), + ) + .await?; + Ok(json!({ "ok": true })) +} + +/// A cluster's Cloudflare Tunnel +/// +/// The cluster's tunnel as Pyo last saw it: its state, Cloudflare's view +/// (`health`, `connections`, `colos`), the connectors in the cluster +/// (`connectors`: each one's server, whether it's ready, and why not), its +/// default domain, its certificate, and `refused` when the cluster's install +/// is older than Pyo's. Never a token. Cloudflare is read every 2 minutes. +#[utoipa::path(get, path = "/clusters/{id}/tunnel", operation_id = "getClusterTunnel", tag = "Clusters", + params(("id" = String, Path, description = "The cluster's id (`cl_…`).")), + responses( + (status = 200, description = "`tunnel`: the cluster's tunnel, or null without one. `traffic`: \"public\", \"tailscale\" or \"tunnel\".", body = Object), + (status = 404, description = "No such cluster, or it isn't yours to see.", body = crate::error::ErrorBody), + ), + extensions(("x-pyo-access" = json!("read"))))] +pub async fn get( + axum::extract::State(s): axum::extract::State, + crate::auth::SessionUser(user): crate::auth::SessionUser, + axum::extract::Path(id): axum::extract::Path, +) -> ApiResult> { + let mut tx = crate::rls::begin(&s.db, &user).await?; + let team_id = team_of(&mut tx, "clusters", &id).await?; + require_role(&mut tx, &user, &team_id, Role::Viewer).await?; + let traffic: String = sqlx::query_scalar("SELECT traffic FROM pyo.clusters WHERE id = $1") + .bind(&id) + .fetch_one(&mut *tx) + .await?; + let tunnel = super::tunnel_loop::one_shown(&mut *tx, &id).await?; + tx.commit().await?; + Ok(crate::error::Json(json!({ "traffic": traffic, "tunnel": tunnel }))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cloudflare::tests::zone; + + fn in_account(id: &str, name: &str, account: &str) -> Zone { + Zone { + account_id: account.into(), + ..zone(id, name) + } + } + + #[test] + fn the_account_is_asked_for_only_when_it_isnt_clear() { + let one = [zone("z1", "example.com"), zone("z2", "other.org")]; + assert_eq!(pick_account(&one, None, None).unwrap(), "acct1"); + let two = [in_account("z1", "example.com", "a1"), in_account("z2", "other.org", "a2")]; + assert_eq!(pick_account(&two, None, None).unwrap_err(), "Pick the Cloudflare account for the tunnel."); + assert_eq!(pick_account(&two, None, Some("other.org")).unwrap(), "a2"); + assert_eq!(pick_account(&two, Some("a1"), None).unwrap(), "a1"); + assert!(pick_account(&two, Some("a9"), None).is_err()); + let mut dns_only = zone("z1", "example.com"); + dns_only.tunnel.ready = false; + assert!(pick_account(&[dns_only], None, None).unwrap_err().starts_with("Give the Cloudflare token")); + } + + #[test] + fn the_default_domain_is_a_zone_itself() { + let zones = [zone("z1", "example.com")]; + let usable: Vec<&Zone> = zones.iter().collect(); + assert_eq!(default_domain(&usable, "example.com").unwrap().id, "z1"); + assert_eq!(default_domain(&usable, "*.Example.com.").unwrap().id, "z1"); + assert_eq!( + default_domain(&usable, "apps.example.com").unwrap_err(), + "Pick a zone itself, like example.com, not a name under it." + ); + assert!(default_domain(&usable, "other.org").is_err()); + } + + #[test] + fn tunnel_mode_waits_for_an_install_that_can_run_it() { + assert_eq!(install_ready(&json!({})).unwrap_err(), "This cluster's agent doesn't run Cloudflare Tunnel yet. Update the agent first."); + assert_eq!( + install_ready(&json!({ "tunnel": true, "agentInstall": { "state": "outdated" } })).unwrap_err(), + INSTALL_FIRST + ); + assert_eq!( + install_ready(&json!({ "tunnel": true, "agentInstall": { "state": "updating" } })).unwrap_err(), + INSTALL_FIRST + ); + assert!(install_ready(&json!({ "tunnel": true, "agentInstall": { "state": "current" } })).is_ok()); + for m in [INSTALL_FIRST] { + assert!(!m.contains(';')); + } + } + + #[test] + fn free_and_tailnet_domains_stay_direct() { + let zones = [zone("z1", "example.com"), in_account("z2", "other.org", "a2")]; + assert!(can_tunnel("blog.example.com", &zones, "acct1").is_some()); + assert!(can_tunnel("blog.other.org", &zones, "acct1").is_none(), "another account"); + assert!(can_tunnel("web.203.0.113.7.nip.io", &zones, "acct1").is_none()); + assert!(can_tunnel("web.tail1234.ts.net", &zones, "acct1").is_none()); + assert!(can_tunnel("blog.nowhere.dev", &zones, "acct1").is_none()); + } +} diff --git a/crates/pyo-api/src/deploy.rs b/crates/pyo-api/src/deploy.rs index 47143f15..ee1d7c6b 100644 --- a/crates/pyo-api/src/deploy.rs +++ b/crates/pyo-api/src/deploy.rs @@ -2551,6 +2551,9 @@ pub(crate) async fn check_pending_dns(state: &AppState) -> ApiResult<()> { FROM pyo.services a, jsonb_array_elements(a.spec->'domains') d WHERE NOT a.deleting AND d->>'status' IN ('pending_dns', 'verifying') AND lower(d->>'hostname') NOT LIKE '%.ts.net' + -- Through the Cloudflare Tunnel: its address is Cloudflare's, + -- and the tunnel loop says when it's ready. + AND coalesce(d->>'tunnel', '') = '' AND pyo.ms(now()) - coalesce((d->>'dnsCheckedAt')::bigint, 0) >= CASE WHEN pyo.ms(now()) - coalesce((d->>'createdAt')::bigint, 0) < 3600000 THEN 30000 WHEN pyo.ms(now()) - coalesce((d->>'createdAt')::bigint, 0) < 86400000 THEN 300000 diff --git a/crates/pyo-api/src/gate.rs b/crates/pyo-api/src/gate.rs index 927125ed..aae7e1e2 100644 --- a/crates/pyo-api/src/gate.rs +++ b/crates/pyo-api/src/gate.rs @@ -42,6 +42,8 @@ const REMOVALS: &[&str] = &[ "remove_server", "forget_snapshot", "tailscale_remove", + // A team can always take its Cloudflare Tunnel (and its records) back. + "tunnel_remove", ]; /// Commands that follow a change made elsewhere, a removal's too (the diff --git a/crates/pyo-api/src/install.rs b/crates/pyo-api/src/install.rs index 859ecd13..5de9565b 100644 --- a/crates/pyo-api/src/install.rs +++ b/crates/pyo-api/src/install.rs @@ -129,8 +129,8 @@ async fn token_for_manifest(db: &sqlx::PgPool, token: &str) -> ApiResult<(String /// gateway is set up). A cluster that's running keeps its setting. async fn web_ports_busy(db: &sqlx::PgPool, cluster: &str) -> ApiResult<()> { let off = sqlx::query( - "UPDATE pyo.clusters SET public_traffic = false - WHERE id = $1 AND last_seen_at IS NULL AND public_traffic", + "UPDATE pyo.clusters SET traffic = 'tailscale' + WHERE id = $1 AND last_seen_at IS NULL AND traffic = 'public'", ) .bind(cluster) .execute(db) diff --git a/crates/pyo-api/src/lib.rs b/crates/pyo-api/src/lib.rs index d66cb511..2474c85a 100644 --- a/crates/pyo-api/src/lib.rs +++ b/crates/pyo-api/src/lib.rs @@ -551,6 +551,7 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { // Each loop runs on one worker at a time (leader lock); jobs on any. tokio::spawn(deploy::sweeper(state.clone())); tokio::spawn(deploy::dns_watcher(state.clone())); + tokio::spawn(cloudflare::tunnel_loop::run(state.clone())); tokio::spawn(builders::watcher(state.clone())); tokio::spawn(github::poller(state.clone())); tokio::spawn(git::poller(state.clone())); diff --git a/crates/pyo-api/src/mcp.rs b/crates/pyo-api/src/mcp.rs index b2163bda..f3c904fd 100644 --- a/crates/pyo-api/src/mcp.rs +++ b/crates/pyo-api/src/mcp.rs @@ -155,7 +155,7 @@ fn curated() -> Vec { "server_tags": { "type": "array", "items": { "type": "string" }, "description": "Older form of placement.tags" }, }), &["name", "image"]), "annotations": write }), json!({ "name": "set_service_placement", "title": "Set service placement", "description": "Choose where a service runs: any server of its cluster (servers and tags both empty), or only the servers named and every server with one of the tags, including servers tagged later (see list_servers). A service with a volume has to keep its volume's server, and one with a GPU needs a GPU server. It changes in place, without a redeploy: its replicas move over with the same image. Refused with the reason when no server picked can run it.", "inputSchema": schema(json!({ "service_id": service, "servers": { "type": "array", "items": { "type": "string" }, "description": "Server names" }, "tags": { "type": "array", "items": { "type": "string" }, "description": "Server tags" } }), &["service_id"]), "annotations": { "readOnlyHint": false, "destructiveHint": false, "idempotentHint": true } }), - json!({ "name": "add_domain", "title": "Add domain", "description": "Serve a service on a hostname, or on a free nip.io domain. It goes live in place, without a redeploy (a service never deployed gets it with its first deploy).", "inputSchema": schema(json!({ "service_id": service, "hostname": { "type": "string" }, "free_domain": { "type": "boolean" }, "cloudflare_dns": { "type": "boolean", "description": "Create its DNS record in the team's Cloudflare account when a connected zone covers the hostname (default true). Never overwrites a record." }, "proxied": { "type": "boolean", "description": "Proxied by Cloudflare, once its certificate is issued (default false)" } }), &["service_id"]), "annotations": write }), + json!({ "name": "add_domain", "title": "Add domain", "description": "Serve a service on a hostname, or on a free nip.io domain. It goes live in place, without a redeploy (a service never deployed gets it with its first deploy).", "inputSchema": schema(json!({ "service_id": service, "hostname": { "type": "string" }, "free_domain": { "type": "boolean" }, "cloudflare_dns": { "type": "boolean", "description": "Create its DNS record in the team's Cloudflare account when a connected zone covers the hostname (default true). Never overwrites a record." }, "proxied": { "type": "boolean", "description": "Proxied by Cloudflare, once its certificate is issued (default false)" }, "tunnel": { "type": "boolean", "description": "Through the cluster's Cloudflare Tunnel when a tunnel-ready zone covers the hostname (default: on in tunnel mode)." } }), &["service_id"]), "annotations": write }), json!({ "name": "set_static_serving", "title": "Set static serving", "description": "For a service whose build is a static site: serve its build as static files from the cluster's shared static server (\"static\", the default), or run it as a service of its own (\"service\"). Takes effect with the next deploy.", "inputSchema": schema(json!({ "service_id": service, "serve_as": { "type": "string", "enum": ["static", "service"] } }), &["service_id", "serve_as"]), "annotations": { "readOnlyHint": false, "destructiveHint": false, "idempotentHint": true } }), json!({ "name": "set_request_timeout", "title": "Set request timeout", "description": "How long the gateway waits for the service to answer a request on its domains before it returns 504, in seconds: 1 to 3600, or 0 for no limit. Without one it's 300. WebSockets aren't cut by it. It changes in place, without a redeploy.", "inputSchema": schema(json!({ "service_id": service, "seconds": { "type": ["integer", "null"], "minimum": 0, "maximum": 3600, "description": "null goes back to the default" } }), &["service_id", "seconds"]), "annotations": { "readOnlyHint": false, "destructiveHint": false, "idempotentHint": true } }), json!({ "name": "stop_service", "title": "Stop service", "description": "Stop the service (scale to zero). Settings and data are kept.", "inputSchema": schema(json!({ "service_id": service }), &["service_id"]), "annotations": { "readOnlyHint": false, "destructiveHint": true, "idempotentHint": true } }), @@ -1304,7 +1304,31 @@ pub(crate) async fn run_tool( && !n.is_empty() && (host == n || host.ends_with(&format!(".{n}"))) }); - let dns_record = if covered && args["cloudflare_dns"].as_bool().unwrap_or(true) { + // Through the cluster's Cloudflare Tunnel, by default in tunnel mode. + let cluster = list("clusters") + .into_iter() + .find(|c| c["id"] == a["clusterId"]) + .unwrap_or_default(); + let tunnel_mode = cluster["traffic"] == json!("tunnel"); + let tunnel_ready = covered + && cluster["tunnel"].is_object() + && list("cloudflare") + .iter() + .filter(|c| c["teamId"] == team) + .flat_map(|c| c["zones"].as_array().cloned().unwrap_or_default()) + .any(|z| { + let n = z["name"].as_str().unwrap_or(""); + z["tunnel"]["ready"] == json!(true) + && z["accountId"] == cluster["tunnel"]["accountId"] + && !n.is_empty() + && (host == n || host.ends_with(&format!(".{n}"))) + }); + let tunnel = tunnel_ready && args["tunnel"].as_bool().unwrap_or(tunnel_mode); + let dns_record = if tunnel { + op(json!({ "op": "setDomainTunnel", "serviceId": id, "domainId": d["id"], "on": true })) + .await + .unwrap_or_else(|e| json!({ "status": "failed", "error": e })) + } else if covered && args["cloudflare_dns"].as_bool().unwrap_or(true) { op(json!({ "op": "createDnsRecord", "serviceId": id, "domainId": d["id"], "proxied": args["proxied"].as_bool().unwrap_or(false), diff --git a/crates/pyo-api/src/openapi.rs b/crates/pyo-api/src/openapi.rs index 33852abb..0344fcb5 100644 --- a/crates/pyo-api/src/openapi.rs +++ b/crates/pyo-api/src/openapi.rs @@ -51,6 +51,7 @@ use crate::{auth::KeyAccess, error::ErrorBody, ops::Op}; crate::images::list, crate::images::registry, crate::cloudflare::get, + crate::cloudflare::tunnel_ops::get, crate::databases::list, crate::databases::get, crate::databases::extensions, diff --git a/crates/pyo-api/src/ops.rs b/crates/pyo-api/src/ops.rs index 53bbb4eb..86f0ab4a 100644 --- a/crates/pyo-api/src/ops.rs +++ b/crates/pyo-api/src/ops.rs @@ -94,6 +94,10 @@ pub fn routes() -> Router { .route("/images", get(crate::images::list)) .route("/registry", get(crate::images::registry)) .route("/cloudflare", get(crate::cloudflare::get)) + .route( + "/clusters/{id}/tunnel", + get(crate::cloudflare::tunnel_ops::get), + ) .route("/databases", get(crate::databases::list)) .route("/databases/{id}", get(crate::databases::get)) .route("/database-extensions", get(crate::databases::extensions)) @@ -2955,6 +2959,40 @@ pub(crate) enum Op { service_id: String, domain_id: String, }, + /// How a cluster takes web traffic: "public" (ports 80 and 443 on every server but build-only ones), "tailscale" (only from the tailnet, or only inside the cluster without Tailscale) or "tunnel" (through Cloudflare Tunnel, with no ports 80 and 443 open). For "tunnel", the team's Cloudflare token needs Cloudflare Tunnel:Edit and SSL and Certificates:Edit, and the cluster's install must be Pyo's (run its connect command first when it's older). Domains in zones of the tunnel's account move to the tunnel. Those with a DNS record Pyo didn't make wait for `setDomainTunnel` with `replace`. Pyo does the Cloudflare work in the background: the cluster's `tunnel` shows how it's going. Team owners and admins. + SetClusterTraffic { + cluster_id: String, + mode: String, + /// A zone of the token (its apex, like "example.com"): services get names under it, and `*.example.com` goes through the tunnel. Optional. + #[serde(default)] + default_domain: Option, + /// The Cloudflare account for the tunnel, when the token's zones are in more than one. + #[serde(default)] + account_id: Option, + /// Public TCP and UDP ports stay on the servers in tunnel mode (they don't go through the tunnel). On by default. + #[serde(default)] + ports_public: Option, + }, + /// Serve a domain through the cluster's Cloudflare Tunnel (`on`), or move it back. Pyo adds the tunnel's route first, then points the name at the tunnel with a proxied CNAME, so both paths answer while it moves. When records Pyo didn't make have the name, the domain's `dnsRecord.status` turns "conflict" and `existing` lists them. Send it again with `replace` to replace them (team owners and admins): Pyo keeps a copy. Moving back with `restore` puts that copy back (team owners and admins), or without one, points the name at the cluster's public IP. + SetDomainTunnel { + service_id: String, + domain_id: String, + on: bool, + /// Replace the records in the way. + #[serde(default)] + replace: bool, + /// Moving back: put back the records the tunnel replaced. On by default. + #[serde(default = "yes")] + restore: bool, + }, + /// Remove a cluster's Cloudflare Tunnel: its routes, the DNS records Pyo made (with `restoreRecords`, the ones they replaced come back), the connector in the cluster, its certificate and the tunnel itself. Pick Public ports or Tailscale only for the cluster first. Team owners and admins. + RemoveClusterTunnel { + cluster_id: String, + #[serde(default = "yes")] + restore_records: bool, + }, + /// Give the cluster's Cloudflare Tunnel a new token and a new certificate, and drop its old connections. Team owners and admins. + RotateTunnelToken { cluster_id: String }, /// Create a project and its services from a Docker Compose plan (from `POST /compose/preview`, edited if you like), and deploy them in order. ImportCompose { team_id: String, @@ -3393,9 +3431,10 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { Op::SaveCronJob { .. } | Op::RemoveCronJob { .. } | Op::RunCronJob { .. } => { ("Cron jobs", "crn") } - Op::VerifyDomain { .. } | Op::CreateDnsRecord { .. } | Op::DeleteDnsRecord { .. } => { - ("Domains", "dom") - } + Op::VerifyDomain { .. } + | Op::CreateDnsRecord { .. } + | Op::DeleteDnsRecord { .. } + | Op::SetDomainTunnel { .. } => ("Domains", "dom"), Op::UploadCertificate { .. } | Op::ReplaceCertificate { .. } | Op::RemoveCertificate { .. } => ("Domains", "crt"), @@ -3435,6 +3474,9 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { | Op::SetClusterTrafficMode { .. } | Op::SetClusterWebProxyProtocol { .. } | Op::SetClusterPublicTraffic { .. } + | Op::SetClusterTraffic { .. } + | Op::RemoveClusterTunnel { .. } + | Op::RotateTunnelToken { .. } | Op::SetClusterFreeDomainAddress { .. } => ("Clusters", "cl"), Op::AddFirewallRule { .. } | Op::UpdateFirewallRule { .. } @@ -4735,8 +4777,9 @@ async fn apply( Op::SetClusterPublicTraffic { cluster_id, on } => { let team_id = team_of(tx, "clusters", &cluster_id).await?; require_role(tx, user, &team_id, Role::Admin).await?; + // `public_traffic` follows `traffic` (a generated column). let name: String = sqlx::query_scalar( - "UPDATE pyo.clusters SET public_traffic = $2 WHERE id = $1 RETURNING name", + "UPDATE pyo.clusters SET traffic = CASE WHEN $2 THEN 'public' ELSE 'tailscale' END WHERE id = $1 RETURNING name", ) .bind(&cluster_id) .bind(on) @@ -8222,6 +8265,53 @@ async fn apply( service_id, domain_id, } => crate::cloudflare::delete_record(s, tx, user, &service_id, &domain_id).await, + Op::SetClusterTraffic { + cluster_id, + mode, + default_domain, + account_id, + ports_public, + } => { + crate::cloudflare::tunnel_ops::set_traffic( + s, + tx, + user, + &cluster_id, + &mode, + default_domain.as_deref(), + account_id.as_deref(), + ports_public, + wake, + ) + .await + } + Op::SetDomainTunnel { + service_id, + domain_id, + on, + replace, + restore, + } => { + crate::cloudflare::tunnel_ops::set_domain( + s, + tx, + user, + &service_id, + &domain_id, + on, + replace, + restore, + wake, + ) + .await + } + Op::RemoveClusterTunnel { + cluster_id, + restore_records, + } => crate::cloudflare::tunnel_ops::remove(tx, user, &cluster_id, restore_records, wake).await, + Op::RotateTunnelToken { cluster_id } => { + crate::cloudflare::tunnel_ops::rotate(tx, user, &cluster_id).await + } Op::UpdateProfile { name, timezone } => { let name = require_text(&name, "Name", 80)?; let tz = require_text(&timezone, "Time zone", 64)?; diff --git a/crates/pyo-api/src/routes.rs b/crates/pyo-api/src/routes.rs index a29e4654..75a07f3e 100644 --- a/crates/pyo-api/src/routes.rs +++ b/crates/pyo-api/src/routes.rs @@ -36,6 +36,11 @@ pub fn domain_specs(domains: &Value) -> Vec { redirect_https: d["redirectHttps"].as_bool().unwrap_or(true), port_name: s(d, "portName"), hostname, + // Through the cluster's Cloudflare Tunnel (cloudflare/tunnel.rs). + tunnel: match d["tunnel"].as_str() { + Some(t @ (pyo_proto::TUNNEL_SWITCHING | pyo_proto::TUNNEL_ON)) => t.to_owned(), + _ => String::new(), + }, } }) .collect() @@ -114,6 +119,24 @@ pub async fn changed( Ok(Some(cluster_id)) } +/// [`changed`], with the routes sync's command (to wait for the agent to +/// have it): (cluster, command id). None when nothing was queued (the +/// service never ran, or is being deleted). +pub async fn changed_waiting( + tx: &mut Transaction<'_, Postgres>, + service_id: &str, +) -> ApiResult> { + sqlx::query("UPDATE pyo.services SET routes_revision = routes_revision + 1 WHERE id = $1") + .bind(service_id) + .execute(&mut **tx) + .await?; + let Some((cluster_id, target)) = target(tx, service_id).await? else { + return Ok(None); + }; + let id = crate::deploy::enqueue(tx, &cluster_id, Command::SyncRoutes(Box::new(target))).await?; + Ok(Some((cluster_id, id))) +} + /// What a routes sync applies: the live deployment's service and ports (or, /// before its first rollout is done, that rollout's), its domains, firewall /// and WAF as they are now. None for a service never deployed (its first diff --git a/crates/pyo-api/src/snapshot.rs b/crates/pyo-api/src/snapshot.rs index 4325215d..568f4b06 100644 --- a/crates/pyo-api/src/snapshot.rs +++ b/crates/pyo-api/src/snapshot.rs @@ -152,6 +152,8 @@ pub async fn build(db: &PgPool, user: &User, agent_api_url: &str) -> ApiResult ApiResult Value { // Whether its install is this Pyo's (install.rs): the cluster // settings' "Updating" and "Update needed". "agentInstall": or("agentInstall", Value::Null), + // Its agent runs Cloudflare Tunnel connectors. + "tunnel": or("tunnel", json!(false)), }) } diff --git a/crates/pyo-api/src/teambackup.rs b/crates/pyo-api/src/teambackup.rs index ed76ecbc..eb4b30e5 100644 --- a/crates/pyo-api/src/teambackup.rs +++ b/crates/pyo-api/src/teambackup.rs @@ -479,7 +479,8 @@ fn secret_fields(cmd: &mut Value) -> Vec<&mut Value> { } ("tailscale_setup", "token") | ("tailscale_client", "secret") - | ("sandbox_call", "token") => out.push(v), + | ("sandbox_call", "token") + | ("tunnel_set", "token") => out.push(v), ("backup", "connection") | ("db_setup", "admin") => { if let Some(p) = v.get_mut("password") { out.push(p); @@ -505,11 +506,14 @@ pub async fn seal_command(team_id: &str, cmd: &mut Value) -> anyhow::Result<()> } /// A command whose secret fields are of no more use once it's answered -/// (Tailscale's token and client secret): blanked, so Pyo's database keeps -/// no Tailscale credential, not even sealed. +/// (Tailscale's token and client secret, a Cloudflare Tunnel's token): +/// blanked, so Pyo's database keeps no such credential, not even sealed. pub fn wipe_command(cmd: &mut Value) -> bool { let kind = cmd["kind"].as_str().unwrap_or("").to_owned(); - if !matches!(kind.as_str(), "tailscale_setup" | "tailscale_client" | "sandbox_call") { + if !matches!( + kind.as_str(), + "tailscale_setup" | "tailscale_client" | "sandbox_call" | "tunnel_set" + ) { return false; } for v in secret_fields(cmd) { @@ -1097,6 +1101,29 @@ mod tests { } } + /// The tunnel's token: sealed while queued, wiped once answered, as the + /// command reaches the database. + #[test] + fn the_tunnel_token_is_sealed_then_wiped() { + let c = Command::TunnelSet { + tunnel_id: "c1744f8b-faa1-48a4-9e5c-02ac921467fa".into(), + token: "eyJhIjoiYiJ9".into(), + }; + let mut v = serde_json::to_value(&c).unwrap(); + assert_eq!(v["kind"], "tunnel_set"); + let found: Vec = secret_fields(&mut v) + .into_iter() + .map(|v| v.as_str().unwrap().to_owned()) + .collect(); + assert_eq!(found, ["eyJhIjoiYiJ9"]); + assert!(wipe_command(&mut v)); + assert_eq!(v["token"], ""); + assert_eq!(v["tunnel_id"], "c1744f8b-faa1-48a4-9e5c-02ac921467fa"); + let mut remove = serde_json::to_value(Command::TunnelRemove {}).unwrap(); + assert!(secret_fields(&mut remove).is_empty()); + assert!(!wipe_command(&mut remove)); + } + #[test] fn repository_paths() { let cfg = backup::Settings { From a47f92e5a81d82c831d27c05580205aa4a277890 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:12:53 +0700 Subject: [PATCH 027/139] feat(cli): add pyo cloudflare tunnel and pyo domain tunnel --- crates/pyo-cli/src/cloudflare.rs | 216 +++++++++++++++++++++++++++++++ crates/pyo-cli/src/main.rs | 108 ++++++++++++++++ 2 files changed, 324 insertions(+) diff --git a/crates/pyo-cli/src/cloudflare.rs b/crates/pyo-cli/src/cloudflare.rs index 9003c75e..271c88a7 100644 --- a/crates/pyo-cli/src/cloudflare.rs +++ b/crates/pyo-cli/src/cloudflare.rs @@ -258,6 +258,212 @@ pub async fn domain_dns( .await } +// ── Cloudflare Tunnel ────────────────────────────────────────────────────── + +/// The cluster (name or id, else the team's default) a tunnel command is about. +async fn cluster_of(api: &Api, team: Option<&str>, cluster: Option<&str>) -> Result<(String, String)> { + let (_, id) = crate::compose::team_and_cluster(api, team, cluster).await?; + let state = api.state().await?; + let name = state + .cluster(&id) + .and_then(|c| c["name"].as_str()) + .unwrap_or(&id) + .to_owned(); + Ok((id, name)) +} + +/// A tunnel's state in one line, as the dashboard says it. +pub fn tunnel_line(t: &Value) -> String { + let n = t["connectors"].as_array().map_or(0, Vec::len); + let ready = t["connectors"] + .as_array() + .into_iter() + .flatten() + .filter(|c| c["ready"] == json!(true)) + .count(); + let colos: Vec<&str> = t["colos"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + match t["health"].as_str().unwrap_or("unknown") { + "connected" if colos.is_empty() => format!("Tunnel connected · {ready} connectors"), + "connected" => format!("Tunnel connected · {ready} connectors · {}", colos.join(", ")), + "degraded" => format!("Tunnel degraded · {ready} of {n} connectors"), + "down" => "Tunnel down. Its websites don't answer.".into(), + "starting" => "Starting the tunnel…".into(), + "removing" => "Removing the tunnel…".into(), + _ => "Pyo can't reach Cloudflare. Websites keep working.".into(), + } +} + +pub async fn tunnel_status(api: &Api, team: Option<&str>, cluster: Option<&str>) -> Result<()> { + let (id, name) = cluster_of(api, team, cluster).await?; + let v = api.get(&format!("/clusters/{id}/tunnel")).await?; + println!("{name}: traffic {}", v["traffic"].as_str().unwrap_or("public")); + let t = &v["tunnel"]; + if t.is_null() { + println!("No Cloudflare Tunnel. Turn it on: pyo cloudflare tunnel on --cluster {name}"); + return Ok(()); + } + println!("{}", tunnel_line(t)); + if let Some(e) = t["error"].as_str() { + println!("{}", ui::yellow(e)); + } + if t["refused"] == json!(true) { + println!( + "{}", + ui::yellow("Run the command under Refresh this cluster in the cluster's settings.") + ); + } + for c in t["connectors"].as_array().into_iter().flatten() { + let server = c["server"].as_str().unwrap_or("?"); + match c["reason"].as_str() { + Some(r) if c["ready"] != json!(true) => println!(" {server} {}", ui::red(r)), + _ if c["ready"] == json!(true) => println!(" {server} {}", ui::green("ready")), + _ => println!(" {server} {}", ui::dim("starting")), + } + } + if let Some(d) = t["defaultDomain"].as_str() { + println!("Default domain: *.{d}"); + } + // Each domain through it, from the snapshot. + let state = api.state().await?; + for s in state.services().iter().filter(|s| s["clusterId"] == json!(id)) { + for d in s["domains"].as_array().into_iter().flatten() { + let Some(state) = d["tunnel"].as_str() else { + continue; + }; + let host = d["hostname"].as_str().unwrap_or(""); + let rec = &d["dnsRecord"]; + let what = match (state, rec["status"].as_str()) { + (_, Some("conflict")) => ui::yellow("waiting for --replace"), + (_, Some("reverting")) => ui::dim("switching back"), + ("on", _) => ui::green("via Tunnel"), + _ => ui::dim("switching"), + }; + println!(" {host} {what}"); + } + } + Ok(()) +} + +pub async fn tunnel_on( + api: &Api, + team: Option<&str>, + cluster: Option<&str>, + default_domain: Option<&str>, + account: Option<&str>, + ports_public: bool, +) -> Result<()> { + let (id, name) = cluster_of(api, team, cluster).await?; + let v = api + .op( + "setClusterTraffic", + json!({ "clusterId": id, "mode": "tunnel", "defaultDomain": default_domain, "accountId": account, "portsPublic": ports_public }), + ) + .await?; + ui::ok(&format!("{name} takes websites through Cloudflare Tunnel")); + let moving = v["moving"].as_u64().unwrap_or(0); + if moving > 0 { + println!("{moving} domains are moving. See them: pyo cloudflare tunnel status --cluster {name}"); + } + Ok(()) +} + +pub async fn tunnel_off(api: &Api, team: Option<&str>, cluster: Option<&str>, to: &str) -> Result<()> { + if !matches!(to, "public" | "tailscale") { + bail!("--to is public or tailscale."); + } + let (id, name) = cluster_of(api, team, cluster).await?; + api.op("setClusterTraffic", json!({ "clusterId": id, "mode": to })) + .await?; + ui::ok(&format!( + "{name} takes traffic {}", + if to == "public" { "on public ports" } else { "from Tailscale only" } + )); + println!("Domains keep using the tunnel until you move them back: pyo domain tunnel --back"); + Ok(()) +} + +pub async fn tunnel_remove( + api: &Api, + team: Option<&str>, + cluster: Option<&str>, + restore: bool, + yes: bool, +) -> Result<()> { + let (id, name) = cluster_of(api, team, cluster).await?; + if !yes { + let a = ui::ask(&format!("Remove the Cloudflare Tunnel of {name}? [y/N] "))?; + if !a.eq_ignore_ascii_case("y") { + bail!("Not removed."); + } + } + api.op( + "removeClusterTunnel", + json!({ "clusterId": id, "restoreRecords": restore }), + ) + .await?; + ui::ok("Removing the tunnel. Pyo deletes only the records it made."); + Ok(()) +} + +pub async fn tunnel_rotate(api: &Api, team: Option<&str>, cluster: Option<&str>) -> Result<()> { + let (id, name) = cluster_of(api, team, cluster).await?; + api.op("rotateTunnelToken", json!({ "clusterId": id })) + .await?; + ui::ok(&format!("{name}'s tunnel gets a new token and certificate")); + Ok(()) +} + +/// `pyo domain tunnel`: a domain through the tunnel, or back. +pub async fn domain_tunnel( + api: &Api, + service: Option<&str>, + hostname: &str, + on: bool, + replace: bool, + restore: bool, +) -> Result<()> { + let t = crate::service::target(api, service).await?; + let host = hostname.trim().trim_end_matches('.').to_lowercase(); + let d = t.service()["domains"] + .as_array() + .into_iter() + .flatten() + .find(|d| d["hostname"] == json!(host)) + .with_context(|| format!("{host} isn't one of {}'s domains.", t.state.path_of(t.service())))?; + // A record already in the way, from an earlier try. + let rec = &d["dnsRecord"]; + if on && !replace && rec["status"] == json!("conflict") { + println!("{}", ui::yellow(&format!("Cloudflare has a record for {host}:"))); + for r in rec["existing"].as_array().into_iter().flatten() { + println!( + " {} {} {}", + r["type"].as_str().unwrap_or(""), + r["name"].as_str().unwrap_or(""), + r["content"].as_str().unwrap_or("") + ); + } + bail!("Run again with --replace to replace it. Pyo keeps a copy."); + } + let v = api + .op( + "setDomainTunnel", + json!({ "serviceId": t.id, "domainId": d["id"], "on": on, "replace": replace, "restore": restore }), + ) + .await?; + match v["status"].as_str().unwrap_or("") { + "active" => ui::ok(&format!("{host} already goes through the tunnel")), + "switching" => ui::ok(&format!("Switching {host} to the tunnel. If Cloudflare has a record Pyo didn't make, pyo cloudflare tunnel status shows it.")), + "reverting" => ui::ok(&format!("Switching {host} back")), + _ => ui::ok(&format!("{host} doesn't go through the tunnel")), + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -291,6 +497,16 @@ mod tests { assert!(plain(Value::Null).contains("DNS only")); } + #[test] + fn tunnel_lines() { + let t = json!({ "health": "connected", "colos": ["AMS", "FRA"], "connectors": [{ "ready": true }, { "ready": true }] }); + assert_eq!(tunnel_line(&t), "Tunnel connected · 2 connectors · AMS, FRA"); + let t = json!({ "health": "degraded", "connectors": [{ "ready": true }, { "ready": false }] }); + assert_eq!(tunnel_line(&t), "Tunnel degraded · 1 of 2 connectors"); + assert_eq!(tunnel_line(&json!({ "health": "down" })), "Tunnel down. Its websites don't answer."); + assert_eq!(tunnel_line(&json!({})), "Pyo can't reach Cloudflare. Websites keep working."); + } + #[test] fn tokens_come_from_a_file_or_the_environment() { assert_eq!(read_token(None, Some(" abc \n".into())).unwrap(), "abc"); diff --git a/crates/pyo-cli/src/main.rs b/crates/pyo-cli/src/main.rs index 06c0cd59..4dffdc96 100644 --- a/crates/pyo-cli/src/main.rs +++ b/crates/pyo-cli/src/main.rs @@ -465,6 +465,20 @@ enum DomainCommand { #[arg(long)] keep_dns_record: bool, }, + /// Serve a domain through the cluster's Cloudflare Tunnel, or move it back. + Tunnel { + /// e.g. app.example.com. + hostname: String, + /// Replace the records in the way. Owners and admins. + #[arg(long)] + replace: bool, + /// Move it back from the tunnel. + #[arg(long, conflicts_with = "replace")] + back: bool, + /// Moving back: don't put back the records the tunnel replaced. + #[arg(long, requires = "back")] + no_restore: bool, + }, /// Create a domain's DNS record in Cloudflare, or try again. Never overwrites a record. Dns { /// e.g. app.example.com. @@ -504,6 +518,59 @@ enum CloudflareCommand { #[arg(long, short = 'y')] yes: bool, }, + /// A cluster's Cloudflare Tunnel: websites through Cloudflare, no open ports. + Tunnel { + #[command(subcommand)] + command: TunnelCommand, + }, +} + +#[derive(Subcommand)] +enum TunnelCommand { + /// The tunnel, its connectors and its domains. + Status { + /// The cluster, by name or id (default: the team's). + #[arg(long)] + cluster: Option, + }, + /// Take the cluster's websites through Cloudflare Tunnel. Owners and admins. + On { + #[arg(long)] + cluster: Option, + /// A zone (like example.com): services get names under it. + #[arg(long)] + default_domain: Option, + /// The Cloudflare account, when the token's zones are in more than one. + #[arg(long)] + account: Option, + /// Don't keep public TCP and UDP ports on the servers. + #[arg(long)] + no_public_ports: bool, + }, + /// Take websites on public ports or Tailscale only again. The tunnel stays until removed. + Off { + #[arg(long)] + cluster: Option, + /// "public" or "tailscale". + #[arg(long, default_value = "public")] + to: String, + }, + /// Remove the tunnel, its records and its connector. Owners and admins. + Remove { + #[arg(long)] + cluster: Option, + /// Leave the records the tunnel replaced out (they're put back by default). + #[arg(long)] + keep_records: bool, + /// Don't ask to confirm. + #[arg(long, short = 'y')] + yes: bool, + }, + /// A new token and certificate for the tunnel. Owners and admins. + Rotate { + #[arg(long)] + cluster: Option, + }, } #[derive(Subcommand)] @@ -1147,6 +1214,12 @@ async fn run(mut cli: Cli) -> anyhow::Result<()> { proxied, replace, } => cloudflare::domain_dns(&api, s, &hostname, proxied, replace).await, + DomainCommand::Tunnel { + hostname, + replace, + back, + no_restore, + } => cloudflare::domain_tunnel(&api, s, &hostname, !back, replace, !no_restore).await, } } Command::Cloudflare { command, team } => { @@ -1160,6 +1233,41 @@ async fn run(mut cli: Cli) -> anyhow::Result<()> { CloudflareCommand::Test => cloudflare::test(&api, team).await, CloudflareCommand::Zones => cloudflare::zones(&api, team).await, CloudflareCommand::Remove { yes } => cloudflare::remove(&api, team, yes).await, + CloudflareCommand::Tunnel { command } => match command { + TunnelCommand::Status { cluster } => { + cloudflare::tunnel_status(&api, team, cluster.as_deref()).await + } + TunnelCommand::On { + cluster, + default_domain, + account, + no_public_ports, + } => { + cloudflare::tunnel_on( + &api, + team, + cluster.as_deref(), + default_domain.as_deref(), + account.as_deref(), + !no_public_ports, + ) + .await + } + TunnelCommand::Off { cluster, to } => { + cloudflare::tunnel_off(&api, team, cluster.as_deref(), &to).await + } + TunnelCommand::Remove { + cluster, + keep_records, + yes, + } => { + cloudflare::tunnel_remove(&api, team, cluster.as_deref(), !keep_records, yes) + .await + } + TunnelCommand::Rotate { cluster } => { + cloudflare::tunnel_rotate(&api, team, cluster.as_deref()).await + } + }, } } Command::Sandbox { command, team } => { From bf1cc7802dd888e62904cc931b92e9396546ac33 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:12:53 +0700 Subject: [PATCH 028/139] docs: note the tunnel decisions made while building --- docs/cloudflare-tunnel.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/cloudflare-tunnel.md b/docs/cloudflare-tunnel.md index 316d9323..558db98c 100644 --- a/docs/cloudflare-tunnel.md +++ b/docs/cloudflare-tunnel.md @@ -120,6 +120,22 @@ Decisions made while building (not in the first draft): routes. - **Rotate** gives the tunnel a new token and a new certificate in one action. There's no separate certificate action. +- **Certificates while switching**: a domain keeps a certificate already + issued for it while it's `"switching"` (cloudflared trusts public CAs + too, and direct visitors still see a valid one). It takes the tunnel's + Origin CA certificate once `"on"`, or at once when it has no issued one + (a new domain). Its old TLS mode is kept as `tlsModeBefore` (and + `certificateIdBefore`) and comes back with Switch back. +- **Public TCP and UDP ports** get their own heartbeat reply field, + `publicPorts` (public traffic, or tunnel mode with `ports_public`), so + they don't depend on the tunnel id being known yet. +- **connect.sh keeps its line** ("Public traffic stays off, so your sites + keep working."). The seamless-scripts rule keeps hints out of scripts. + The dashboard says Cloudflare Tunnel can take the websites. +- **Tunnel removal while a domain is removed**: the dashboard's "Put back + the old record" sends `setDomainTunnel` with `restore` before the domain + goes. A removed tunnel domain's record is otherwise reverted without + putting back what it replaced. --- From 6ab03c9f9dbe407f012bc13c9d3e6a2637b76bba Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:13:04 +0700 Subject: [PATCH 029/139] feat(dash): show a tunnel badge beside clusters in tunnel mode --- dash/src/components/pyo/Tunnel.tsx | 8 ++++++-- dash/src/routes/_app/$team/clusters/$clusterId.tsx | 2 ++ dash/src/routes/_app/$team/clusters/index.tsx | 3 +++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/dash/src/components/pyo/Tunnel.tsx b/dash/src/components/pyo/Tunnel.tsx index 506c4d68..22d4d082 100644 --- a/dash/src/components/pyo/Tunnel.tsx +++ b/dash/src/components/pyo/Tunnel.tsx @@ -98,10 +98,14 @@ export function TunnelStatus({ c }: { c: Cluster }) { } /** "Tunnel" beside a cluster in tunnel mode, warning tone while it's degraded or down. */ -export function TunnelBadge({ c }: { c: Cluster }) { +export function TunnelBadge({ c, className }: { c: Cluster; className?: string }) { if (clusterTraffic(c) !== "tunnel") return null; const bad = c.tunnel?.health === "degraded" || c.tunnel?.health === "down"; - return Tunnel; + return ( + + Tunnel + + ); } /** diff --git a/dash/src/routes/_app/$team/clusters/$clusterId.tsx b/dash/src/routes/_app/$team/clusters/$clusterId.tsx index 21d71479..ed988ff2 100644 --- a/dash/src/routes/_app/$team/clusters/$clusterId.tsx +++ b/dash/src/routes/_app/$team/clusters/$clusterId.tsx @@ -5,6 +5,7 @@ import { createFileRoute, Outlet } from "@tanstack/react-router"; import { placesOf } from "~/lib/pyo/location"; import { PlaceFlags } from "~/components/ui/Flag"; import { ClusterStatusBadge } from "~/components/ui/Badge"; +import { TunnelBadge } from "~/components/pyo/Tunnel"; import { ButtonLink } from "~/components/ui/Button"; import { EmptyState, Page, PageHeader } from "~/components/ui/Panel"; import { api, clusterByRef, clusterSummary, usePyo } from "~/lib/pyo/store"; @@ -44,6 +45,7 @@ function ClusterLayout() { {c.name} + ) : null} +

    {placesOf(c, s.servers).length > 1 @@ -480,6 +482,7 @@ function ClusterCard({ {clusterLabel[c.status]} ) : null} +

    From 57bc331fb4a6e3e92eab7420f1c940e3d0f5ca48 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:16:10 +0700 Subject: [PATCH 030/139] docs: update the tunnel build status --- docs/cloudflare-tunnel.md | 68 ++++++++++++++++++++++++++------------- 1 file changed, 46 insertions(+), 22 deletions(-) diff --git a/docs/cloudflare-tunnel.md b/docs/cloudflare-tunnel.md index 558db98c..fa2d1789 100644 --- a/docs/cloudflare-tunnel.md +++ b/docs/cloudflare-tunnel.md @@ -1577,31 +1577,55 @@ Not merged into `dev` until the feature is complete and tested. | Phase | State | |---|---| -| Decisions applied to this spec | Done (b145440) | -| 1. Token and zones | Written, not compiled (e3d91dd api, adc8e62 cli, 12cf81f dash, tsc passes) | -| 2. Agent and Gateway | Next | -| 3. Control plane | Not started | -| 4. Traffic choice, switching, default domain | Not started | -| 5. Ports, connect.sh, alerts | Not started | +| Decisions applied to this spec | Done (b145440, 5284a70, bf1cc78) | +| 1. Token and zones | Done, tested (e3d91dd api, adc8e62 cli, 12cf81f dash) | +| 2. Agent and Gateway | Written and compiled (eadce05 proto, 4db8b6f agent). Agent tunnel tests pass (9). pyo-proto rbac tests not run yet | +| 3. Control plane | Written and compiled (3b9ae43): migration 0040, tunnel_loop.rs, heartbeat and snapshot. Unit tests 24 of 26 passed, the 2 failures were test mistakes, fixed in 3b9ae43, not rerun yet | +| 4. Traffic choice, switching | API, MCP and CLI written (3b9ae43, a47f92e). Dashboard in progress on `feat/cloudflare-tunnel-dash` (worktree `pyo-tunnel-dash`) | +| 5. Ports, connect.sh, alerts | Public ports Service and tunnel alerts written. connect.sh keeps its line (see Decisions) | | 6. Docs, e2e, real-zone test, Pyo Ops | Not started (real zone and Pyo Ops need the user) | -Phase 1 notes: - -- `cloudflare/tunnel.rs` holds the tunnel API client (`TunnelApi`, a - trait of its own so the edgecert fakes that implement `Cloudflare` stay - as they are), the token checks, `ingress()`, `config_hash()`, - `cert_names()`, `key_and_csr()`. Phase 3 adds the loop next to it. -- The fake account in `cloudflare/tests.rs` implements both traits - (tunnels, routes, secrets, certificates) and is `pub(super)` so the - tunnel loop's tests can use it. -- `removeCloudflare` refusing while a tunnel exists moves to Phase 3 (it - needs the `cluster_tunnels` table). +Where things are: + +- `crates/pyo-api/src/cloudflare/tunnel.rs`: the Cloudflare tunnel client + (`TunnelApi`), token checks, routes, certificate names. +- `cloudflare/tunnel_loop.rs` (+ `tunnel_loop_tests.rs`): the loop, + switching and reverting records, certificates, health, removal, the + snapshot's `tunnel`. +- `cloudflare/tunnel_ops.rs`: the ops and `GET /clusters/{id}/tunnel`. +- `crates/pyo-agent/src/tunnel.rs`: the connector, its report, trusted + pod addresses. `gateway.rs`: tunnel routes, policies, public ports + Service. +- `crates/pyo-proto/src/system.rs` (Cloudflare Tunnel section), `rbac.rs` + (origin and public ports Services, `tunnel` client policies). + +Next: + +1. Rerun `cargo test -p pyo-proto -p pyo-agent -p pyo-api -p pyo-cli tunnel` + and `… cloudflare`, plus the full `-p pyo-api -p pyo-agent -p pyo-proto` + suites (the access hash and admission tests), and clippy. +2. Merge `feat/cloudflare-tunnel-dash` once its `tsc` passes. +3. A DATABASE_URL test (ignored by default, like install.rs's) for the + migration and the ops: traffic switch, switch and revert rows, + removeCloudflare refused. +4. Phase 6: pyo-docs pages, `scripts/tunnel-gate-e2e.sh`, + `scripts/fake-cloudflare/` with `PYO_DEV_CLOUDFLARE_API`. Known gaps: -- Nothing on this branch has been compiled or tested yet: `cargo check` - was blocked by the permission classifier on 2026-11-22. Run - `cargo check -p pyo-api -p pyo-cli --tests` and - `cargo test -p pyo-api cloudflare::` first when picking this up. -- `dash/node_modules` in the worktree is a symlink to the main +- Free domains in tunnel mode (`freedomain::Mode::Tunnel`, + `-.`) aren't built. The default + domain's wildcard record and route are. +- `GET /clusters/{id}/tunnel` returns the stored view (Cloudflare is read + every 2 minutes), not a fresh read. +- A service deleted while its domain goes through the tunnel leaves its + CNAME (its dns_records row cascades away before the loop sees it). +- Pyo Cloud's domain proof TXT (`_pyo-verify`) isn't written by Switch to + Tunnel. Domains were verified when added. +- A domain moved between clusters isn't removed from the other tunnel + first. +- The cluster-delete op doesn't wait for tunnel removal (§11). +- Nothing tested against a real Cloudflare account (needs the user's + approval and a throwaway zone). +- `dash/node_modules` in the worktrees is a symlink to the main checkout's, for `tsc` only (ignored by git). From 50f1a49e1a2dfa56799b21087a3327015f45e840 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:16:18 +0700 Subject: [PATCH 031/139] feat(dash): switch domains to the cloudflare tunnel and back A domain's record line shows Via Tunnel with Switch back, Switch to Tunnel in a tunnel-ready zone, the records in the way with Replace and switch, the switching states and failures. In tunnel mode a domain no tunnel zone covers says it doesn't answer from the internet. Add domain offers Through Cloudflare Tunnel, on by default in tunnel mode. Remove domain can put back the record a tunnel domain replaced. --- dash/src/components/pyo/AddDomainDialog.tsx | 20 +- dash/src/components/pyo/Cloudflare.tsx | 118 +++++++++- dash/src/components/pyo/TunnelRecord.tsx | 203 ++++++++++++++++++ .../$team/$projectId_/$serviceId/domains.tsx | 29 ++- 4 files changed, 353 insertions(+), 17 deletions(-) create mode 100644 dash/src/components/pyo/TunnelRecord.tsx diff --git a/dash/src/components/pyo/AddDomainDialog.tsx b/dash/src/components/pyo/AddDomainDialog.tsx index 0ee9ecf2..54d0dd80 100644 --- a/dash/src/components/pyo/AddDomainDialog.tsx +++ b/dash/src/components/pyo/AddDomainDialog.tsx @@ -9,6 +9,7 @@ import { import { CloudflareFields, useCloudflareFor, + useTunnelChoice, type CloudflareChoice, } from "~/components/pyo/Cloudflare"; import { SetUpTailscaleLink } from "~/components/pyo/Tailscale"; @@ -118,6 +119,12 @@ export function AddDomainDialog({ k === "own" ? hostname : "", app?.clusterId, ); + // Through the cluster's Cloudflare Tunnel instead of a direct record. + const viaTunnel = useTunnelChoice( + k === "own" && HOSTNAME.test(hostname) ? hostname : "", + app?.clusterId, + cf, + ).on; const matching = s.certificates.filter( (c) => c.teamId === (app?.teamId ?? s.currentTeamId) && @@ -170,9 +177,13 @@ export function AddDomainDialog({ ? { certificateId: cert.id } : {}), }, - k === "own" && inCloudflare && cf.create - ? { proxied: cf.proxied } - : undefined, + k !== "own" + ? undefined + : viaTunnel + ? { tunnel: true } + : inCloudflare && cf.create + ? { proxied: cf.proxied } + : undefined, ); toast({ title: fixed @@ -180,7 +191,7 @@ export function AddDomainDialog({ : `Added ${hostname} to ${app.name}`, description: !app.currentDeploymentId ? "Live after the first deploy." - : k !== "own" || (inCloudflare && cf.create) + : k !== "own" || viaTunnel || (inCloudflare && cf.create) ? undefined : "Create the DNS record, then check DNS.", }); @@ -334,6 +345,7 @@ export function AddDomainDialog({ clusterId={app?.clusterId} value={cf} onChange={setCf} + tunnel /> ) : null} {httpPorts.length > 1 ? ( diff --git a/dash/src/components/pyo/Cloudflare.tsx b/dash/src/components/pyo/Cloudflare.tsx index 8fb2e6d2..519ddf15 100644 --- a/dash/src/components/pyo/Cloudflare.tsx +++ b/dash/src/components/pyo/Cloudflare.tsx @@ -13,16 +13,24 @@ import { } from "~/components/pyo/IntegrationDialog"; import { Field, SecretInput, Switch } from "~/components/ui/Field"; import { timeAgo } from "~/lib/pyo/format"; -import { isFreeDomain } from "~/lib/pyo/freeDomain"; +import { isFreeDomain, isTailnetDomain } from "~/lib/pyo/freeDomain"; import { api, cloudflareIn, cloudflareZoneFor, + clusterTraffic, roleIn, servicePath, + tunnelZoneFor, usePyo, } from "~/lib/pyo/store"; import { toast } from "~/lib/pyo/toast"; +import { + onTunnel, + OutsideTunnel, + SwitchToTunnel, + TunnelRecordLine, +} from "~/components/pyo/TunnelRecord"; import type { Application, CloudflareZone, Domain } from "~/lib/pyo/types"; // The team's Cloudflare account: Pyo creates the DNS records of domains in @@ -245,31 +253,86 @@ function zoneNote(z: CloudflareZone): string { return missing.length === 1 ? ` · needs ${missing[0]}` : " · DNS only"; } -/** What to do about a new domain's DNS record in Cloudflare. */ -export type CloudflareChoice = { create: boolean; proxied: boolean }; +/** + * What to do about a new domain's DNS record in Cloudflare. `tunnel`: + * through the cluster's tunnel (unset: on in tunnel mode). + */ +export type CloudflareChoice = { create: boolean; proxied: boolean; tunnel?: boolean }; + +/** The tunnel-ready zone a new domain can use, and whether it goes through the tunnel. */ +export function useTunnelChoice( + hostname: string, + clusterId: string | undefined, + value: CloudflareChoice, +) { + const s = usePyo(); + const cluster = s.clusters.find((c) => c.id === clusterId); + const zone = + hostname && !isFreeDomain(hostname) + ? tunnelZoneFor(s, hostname, cluster) + : undefined; + const on = + !!zone && + (value.tunnel ?? (!!cluster && clusterTraffic(cluster) === "tunnel")); + return { zone, on }; +} /** * "Create the DNS record in Cloudflare" and "Proxied by Cloudflare", when a - * connected zone covers the hostname. Nothing otherwise. + * connected zone covers the hostname. Nothing otherwise. With `tunnel`, a + * tunnel-ready zone offers "Through Cloudflare Tunnel" first. */ export function CloudflareFields({ hostname, clusterId, value, onChange, + tunnel, }: { hostname: string; clusterId?: string; value: CloudflareChoice; onChange: (v: CloudflareChoice) => void; + /** Offer the cluster's tunnel (the caller switches the domain to it). */ + tunnel?: boolean; }) { const s = usePyo(); const zone = cloudflareZoneFor(s, hostname); + const choice = useTunnelChoice(tunnel ? hostname : "", clusterId, value); if (!zone || !hostname || isFreeDomain(hostname)) return null; const ip = s.clusters.find((c) => c.id === clusterId)?.publicIp; - const usable = zone.canEdit && !!ip; return (

    + {choice.zone ? ( + onChange({ ...value, tunnel: on })} + label="Through Cloudflare Tunnel" + description={`CNAME to the tunnel in ${choice.zone.name}`} + /> + ) : null} + {choice.on ? null : ( + + )} +
    + ); +} + +/** A direct A record: create it, and proxied or not. */ +function DirectRecordFields({ + zone, + ip, + value, + onChange, +}: { + zone: CloudflareZone; + ip?: string | null; + value: CloudflareChoice; + onChange: (v: CloudflareChoice) => void; +}) { + const usable = zone.canEdit && !!ip; + return ( + <> ) : null} -
    + ); } @@ -307,8 +370,42 @@ export function useCloudflareFor(hostname: string, clusterId?: string) { return !!zone?.canEdit && !!ip && !isFreeDomain(hostname); } -/** A domain's record in Cloudflare on the service's Domains: how it stands, and what to do. */ +/** + * A domain's record in Cloudflare on the service's Domains: how it stands, + * and what to do. Through the cluster's tunnel or not. + */ export function DnsRecordLine({ app, d }: { app: Application; d: Domain }) { + const s = usePyo(); + const cluster = s.clusters.find((c) => c.id === app.clusterId); + if (onTunnel(d)) return ; + const tunnelMode = !!cluster && clusterTraffic(cluster) === "tunnel"; + const zone = isFreeDomain(d.hostname) + ? undefined + : tunnelZoneFor(s, d.hostname, cluster); + if (tunnelMode && !zone && !isTailnetDomain(d.hostname)) + return ; + const r = d.dnsRecord; + const direct = ; + if (!zone || (r && !["created", "exists"].includes(r.status))) return direct; + return ( +
    + {direct} + +
    + ); +} + +/** A direct record: created, already there, in the way, or failed. */ +function DirectRecordLine({ + app, + d, + noCreate, +}: { + app: Application; + d: Domain; + /** No "Create in Cloudflare": the cluster takes no direct web traffic. */ + noCreate: boolean; +}) { const s = usePyo(); const r = d.dnsRecord; const admin = isAdmin(roleIn(s)); @@ -324,7 +421,12 @@ export function DnsRecordLine({ app, d }: { app: Application; d: Domain }) { }; if (!r) { // None yet: offer it while the domain waits for DNS. - if (!zone?.canEdit || d.status === "active" || isFreeDomain(d.hostname)) + if ( + noCreate || + !zone?.canEdit || + d.status === "active" || + isFreeDomain(d.hostname) + ) return null; return ( + ) : ( + An owner or admin can replace it. + )} + +
  • + + ); + + if (r?.status === "failed" || (r?.error && (r.status === "switching" || back))) + return ( +

    + Cloudflare: {r.error ?? "the record wasn't changed."} + +

    + ); + + if (!r || r.status === "switching" || back) + return ( +

    + + {back ? "Switching back…" : "Switching to the tunnel…"} +

    + ); + + const kept = r.previous ?? []; + const ip = cluster && clusterTraffic(cluster) === "public" ? cluster.publicIp : null; + return ( + <> +

    + + Via Tunnel · + + {r.type} {shortTarget(r.content)} + + {r.error ? · {r.error} : null} + {kept.length && !admin ? ( + · An owner or admin can switch it back. + ) : ( + + )} +

    + setConfirming(false)} + tone="primary" + title={ + kept.length + ? `Put back ${kept[0].type} ${kept[0].content} for ${d.hostname}?` + : ip + ? `Point ${d.hostname} at ${ip}?` + : `Remove Pyo's record for ${d.hostname}?` + } + description={null} + confirmLabel="Switch back" + onConfirm={() => void run({ on: false, restore: kept.length > 0 })} + /> + + ); +} + +/** "Switch to Tunnel" for a direct domain in a tunnel-ready zone. */ +export function SwitchToTunnel({ app, d }: { app: Application; d: Domain }) { + const s = usePyo(); + const [busy, setBusy] = useState(false); + if (roleIn(s) === "viewer") return null; + return ( + + ); +} + +/** In tunnel mode, a domain no tunnel zone covers doesn't answer from the internet. */ +export function OutsideTunnel({ c, d }: { c: Cluster; d: Domain }) { + const s = usePyo(); + const zone = cloudflareZoneFor(s, d.hostname, c.teamId); + return ( +

    + {zone && c.tunnel && zone.accountId !== c.tunnel.accountId + ? "Another Cloudflare account. It doesn't answer from the internet." + : "Not in your Cloudflare account. It doesn't answer from the internet."} +

    + ); +} + +/** The remove dialog's choice to put back the record a tunnel domain replaced. */ +export function RestoreRecordSwitch({ + d, + checked, + onChange, +}: { + d: Domain | null; + checked: boolean; + onChange: (v: boolean) => void; +}) { + const kept = d?.dnsRecord?.previous ?? []; + if (!kept.length) return null; + return ( + + ); +} diff --git a/dash/src/routes/_app/$team/$projectId_/$serviceId/domains.tsx b/dash/src/routes/_app/$team/$projectId_/$serviceId/domains.tsx index 2716a1bf..6e71630e 100644 --- a/dash/src/routes/_app/$team/$projectId_/$serviceId/domains.tsx +++ b/dash/src/routes/_app/$team/$projectId_/$serviceId/domains.tsx @@ -29,12 +29,13 @@ import { DeleteRecordSwitch, DnsRecordLine, } from "~/components/pyo/Cloudflare"; +import { onTunnel, RestoreRecordSwitch } from "~/components/pyo/TunnelRecord"; import { useState } from "react"; import { Button } from "~/components/ui/Button"; import { ConfirmDialog } from "~/components/ui/Dialog"; import { Callout, EmptyState, Panel } from "~/components/ui/Panel"; import { CopyButton } from "~/components/ui/Table"; -import { api, usePyo, serviceIdOf } from "~/lib/pyo/store"; +import { api, clusterTraffic, usePyo, serviceIdOf } from "~/lib/pyo/store"; import { toast } from "~/lib/pyo/toast"; import type { Application, Certificate, Domain } from "~/lib/pyo/types"; @@ -53,6 +54,7 @@ function Domains({ app }: { app: Application }) { const [adding, setAdding] = useState(false); const [removing, setRemoving] = useState(null); const [deleteRecord, setDeleteRecord] = useState(true); + const [restoreRecord, setRestoreRecord] = useState(false); const [picking, setPicking] = useState(null); const [replacing, setReplacing] = useState(null); const certOf = (d: Domain) => @@ -61,6 +63,8 @@ function Domains({ app }: { app: Application }) { : undefined; const cluster = s.clusters.find((c) => c.id === app.clusterId); const target = cluster?.publicIp ?? undefined; + // In tunnel mode no direct record helps: the tunnel line says what to do. + const tunnelMode = !!cluster && clusterTraffic(cluster) === "tunnel"; const httpPorts = app.ports.filter((p) => p.protocol === "HTTP"); return ( @@ -213,6 +217,7 @@ function Domains({ app }: { app: Application }) { danger: true, onSelect: () => { setDeleteRecord(true); + setRestoreRecord(false); setRemoving(d); }, }, @@ -263,6 +268,8 @@ function Domains({ app }: { app: Application }) { {d.status !== "active" && !isFreeDomain(d.hostname) && + !tunnelMode && + !onTunnel(d) && !( d.dnsRecord && ["created", "exists"].includes(d.dnsRecord.status) @@ -336,17 +343,29 @@ function Domains({ app }: { app: Application }) { confirmLabel="Remove domain" onConfirm={async () => { if (!removing) return; + // Putting back the old record replaces Pyo's own as well. + const restore = + !!removing.dnsRecord?.previous?.length && restoreRecord; const res = await api.removeDomain(app.id, removing.id, { - deleteDnsRecord: !!removing.dnsRecord?.mine && deleteRecord, + deleteDnsRecord: + !restore && !!removing.dnsRecord?.mine && deleteRecord, + restoreRecord: restore, }); if (res) toast({ title: `Removed ${removing.hostname}` }); }} > - + {restoreRecord && removing?.dnsRecord?.previous?.length ? null : ( + + )}
    ); From 3f41dd615f145ddcd52d1b8abaac6f12f5a28263 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:16:42 +0700 Subject: [PATCH 032/139] fix(dash): keep the tunnel's account when zones load late --- dash/src/components/pyo/Tunnel.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dash/src/components/pyo/Tunnel.tsx b/dash/src/components/pyo/Tunnel.tsx index 22d4d082..0e8a1397 100644 --- a/dash/src/components/pyo/Tunnel.tsx +++ b/dash/src/components/pyo/Tunnel.tsx @@ -128,7 +128,9 @@ export function TunnelSettings({ (z) => z.tunnel?.ready && z.accountId, ); const accounts = [...new Map(zones.map((z) => [z.accountId!, z.accountName ?? z.accountId!]))]; - const [account, setAccount] = useState(t?.accountId ?? zones[0]?.accountId ?? ""); + const [picked, setAccount] = useState(""); + // The tunnel's own account, as picked, or the first one. + const account = t?.accountId ?? (picked || zones[0]?.accountId || ""); const [domain, setDomain] = useState(t?.defaultDomain ?? ""); const [ports, setPorts] = useState(t?.portsPublic ?? true); const [confirm, setConfirm] = useState<"switch" | "rotate" | null>(null); From f0c769754d7fb86fddbfafbd6a17a36a5bc1c5df Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:22:57 +0700 Subject: [PATCH 033/139] docs: note the merged tunnel dashboard in the build status --- docs/cloudflare-tunnel.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/cloudflare-tunnel.md b/docs/cloudflare-tunnel.md index fa2d1789..71e075ef 100644 --- a/docs/cloudflare-tunnel.md +++ b/docs/cloudflare-tunnel.md @@ -1581,7 +1581,7 @@ Not merged into `dev` until the feature is complete and tested. | 1. Token and zones | Done, tested (e3d91dd api, adc8e62 cli, 12cf81f dash) | | 2. Agent and Gateway | Written and compiled (eadce05 proto, 4db8b6f agent). Agent tunnel tests pass (9). pyo-proto rbac tests not run yet | | 3. Control plane | Written and compiled (3b9ae43): migration 0040, tunnel_loop.rs, heartbeat and snapshot. Unit tests 24 of 26 passed, the 2 failures were test mistakes, fixed in 3b9ae43, not rerun yet | -| 4. Traffic choice, switching | API, MCP and CLI written (3b9ae43, a47f92e). Dashboard in progress on `feat/cloudflare-tunnel-dash` (worktree `pyo-tunnel-dash`) | +| 4. Traffic choice, switching | API, MCP and CLI written (3b9ae43, a47f92e). Dashboard merged (06dfbba, `tsc` passes): Traffic panel, tunnel badge, record line, add and remove domain | | 5. Ports, connect.sh, alerts | Public ports Service and tunnel alerts written. connect.sh keeps its line (see Decisions) | | 6. Docs, e2e, real-zone test, Pyo Ops | Not started (real zone and Pyo Ops need the user) | @@ -1604,7 +1604,9 @@ Next: 1. Rerun `cargo test -p pyo-proto -p pyo-agent -p pyo-api -p pyo-cli tunnel` and `… cloudflare`, plus the full `-p pyo-api -p pyo-agent -p pyo-proto` suites (the access hash and admission tests), and clippy. -2. Merge `feat/cloudflare-tunnel-dash` once its `tsc` passes. +2. Dashboard gaps: the new-service wizard has no tunnel switch, no + warning for deeper names (a.b.example.com), and "Certificate: + " shows only through `tunnel.error`. 3. A DATABASE_URL test (ignored by default, like install.rs's) for the migration and the ops: traffic switch, switch and revert rows, removeCloudflare refused. From 928ac34a56b1f195a3fb9cf0127f6b1b3a5355ae Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:35:46 +0700 Subject: [PATCH 034/139] fix(api): give the cluster tunnel endpoint its mcp tool and tidy clippy getClusterTunnel had no case in MCP's run_endpoint, so its tool couldn't run. Clippy's notes: the Cloudflare trait's zones() went unused once zones are read with their accounts, the tunnel section of system.rs sat after its tests, and a type and a test loop were simplified. --- crates/pyo-api/src/cloudflare.rs | 24 -- crates/pyo-api/src/cloudflare/tests.rs | 9 +- crates/pyo-api/src/cloudflare/tunnel_ops.rs | 10 +- crates/pyo-api/src/mcp.rs | 1 + crates/pyo-api/src/sandbox/edgecert/tests.rs | 9 - crates/pyo-proto/src/system.rs | 308 +++++++++---------- 6 files changed, 166 insertions(+), 195 deletions(-) diff --git a/crates/pyo-api/src/cloudflare.rs b/crates/pyo-api/src/cloudflare.rs index ed413492..cea3445e 100644 --- a/crates/pyo-api/src/cloudflare.rs +++ b/crates/pyo-api/src/cloudflare.rs @@ -151,8 +151,6 @@ fn api_error(e: CfError) -> ApiError { /// What Pyo asks of Cloudflare. [`Http`] is the real one; the tests use a /// fake account. pub(crate) trait Cloudflare { - /// Every zone the token can read, as (id, name). - async fn zones(&self) -> Result, CfError>; /// The records with exactly this name. async fn records(&self, zone_id: &str, name: &str) -> Result, CfError>; async fn record(&self, zone_id: &str, id: &str) -> Result; @@ -469,28 +467,6 @@ fn record_from(v: &Value) -> Result { } impl Cloudflare for Http { - async fn zones(&self) -> Result, CfError> { - let mut out = vec![]; - for page in 1..=20 { - let mut url = Self::url("/zones"); - url.query_pairs_mut() - .append_pair("per_page", "50") - .append_pair("page", &page.to_string()); - let v = self.call(Method::GET, url, None).await?; - for z in v["result"].as_array().into_iter().flatten() { - if let (Some(id), Some(name)) = (z["id"].as_str(), z["name"].as_str()) - && id_ok(id) - { - out.push((id.to_owned(), name.to_owned())); - } - } - if page >= v["result_info"]["total_pages"].as_i64().unwrap_or(1) { - break; - } - } - Ok(out) - } - async fn records(&self, zone_id: &str, name: &str) -> Result, CfError> { let mut url = Self::url(&Self::record_path(zone_id, None)?); url.query_pairs_mut() diff --git a/crates/pyo-api/src/cloudflare/tests.rs b/crates/pyo-api/src/cloudflare/tests.rs index 26147af8..7be4ef28 100644 --- a/crates/pyo-api/src/cloudflare/tests.rs +++ b/crates/pyo-api/src/cloudflare/tests.rs @@ -174,8 +174,8 @@ impl Fake { } } -impl Cloudflare for Fake { - async fn zones(&self) -> Result, CfError> { +impl Fake { + fn zone_list(&self) -> Result, CfError> { self.log("zones".into()); if !self.zone_read { return Err(Self::denied()); @@ -186,7 +186,9 @@ impl Cloudflare for Fake { .map(|z| (z.0.clone(), z.1.clone())) .collect()) } +} +impl Cloudflare for Fake { async fn records(&self, zone_id: &str, name: &str) -> Result, CfError> { self.log(format!("list {zone_id} {name}")); if self.dns(zone_id) == Dns::None { @@ -737,8 +739,7 @@ fn reads_cloudflares_answers() { impl tunnel::TunnelApi for Fake { async fn zone_accounts(&self) -> Result, CfError> { Ok(self - .zones() - .await? + .zone_list()? .into_iter() .map(|(id, name)| { let (account_id, account_name) = self.account_of(&id); diff --git a/crates/pyo-api/src/cloudflare/tunnel_ops.rs b/crates/pyo-api/src/cloudflare/tunnel_ops.rs index f427cabd..6bf8f2ac 100644 --- a/crates/pyo-api/src/cloudflare/tunnel_ops.rs +++ b/crates/pyo-api/src/cloudflare/tunnel_ops.rs @@ -194,6 +194,10 @@ async fn sync( Ok(()) } +/// A cluster's tunnel as `setClusterTraffic` finds it: (state, account, +/// default domain, its zone, Pyo's wildcard record). +type Existing = (String, String, Option, Option, Option); + /// `setClusterTraffic`. #[allow(clippy::too_many_arguments)] pub async fn set_traffic( @@ -255,7 +259,7 @@ pub async fn set_traffic( .first() .map(|z| z.account_name.clone()) .unwrap_or_default(); - let existing: Option<(String, String, Option, Option, Option)> = sqlx::query_as( + let existing: Option = sqlx::query_as( "SELECT state, account_id, default_domain, default_zone_id, default_record_id FROM pyo.cluster_tunnels WHERE cluster_id = $1 FOR UPDATE", ) .bind(cluster_id) @@ -661,9 +665,7 @@ mod tests { INSTALL_FIRST ); assert!(install_ready(&json!({ "tunnel": true, "agentInstall": { "state": "current" } })).is_ok()); - for m in [INSTALL_FIRST] { - assert!(!m.contains(';')); - } + assert!(!INSTALL_FIRST.contains(';')); } #[test] diff --git a/crates/pyo-api/src/mcp.rs b/crates/pyo-api/src/mcp.rs index f3c904fd..add281a0 100644 --- a/crates/pyo-api/src/mcp.rs +++ b/crates/pyo-api/src/mcp.rs @@ -650,6 +650,7 @@ async fn run_endpoint(s: &AppState, user: &User, id: &str, args: &Value) -> Resu "listImages" => json_of(crate::images::list(st(), me(), Query(args_as(args)?)).await), "getRegistry" => json_of(crate::images::registry(st(), me(), Query(args_as(args)?)).await), "getCloudflare" => json_of(crate::cloudflare::get(st(), me(), Query(args_as(args)?)).await), + "getClusterTunnel" => json_of(crate::cloudflare::tunnel_ops::get(st(), me(), path_id()?).await), "listDatabases" => json_of(crate::databases::list(st(), me(), Query(args_as(args)?)).await), "getDatabase" => { json_of(crate::databases::get(st(), me(), Path(arg(args, "id")?.to_owned())).await) diff --git a/crates/pyo-api/src/sandbox/edgecert/tests.rs b/crates/pyo-api/src/sandbox/edgecert/tests.rs index c1900924..1c135370 100644 --- a/crates/pyo-api/src/sandbox/edgecert/tests.rs +++ b/crates/pyo-api/src/sandbox/edgecert/tests.rs @@ -67,9 +67,6 @@ impl Cf { } impl Cloudflare for Arc { - async fn zones(&self) -> Result, CfError> { - Ok(vec![(ZONE.into(), "example.com".into())]) - } async fn records(&self, zone_id: &str, name: &str) -> Result, CfError> { assert_eq!(zone_id, ZONE); Ok(self.named(name)) @@ -434,9 +431,6 @@ async fn a_wildcard_certificate_through_dns01() { struct Dropping(Arc); impl Cloudflare for Dropping { - async fn zones(&self) -> Result, CfError> { - self.0.zones().await - } async fn records(&self, z: &str, n: &str) -> Result, CfError> { self.0.records(z, n).await } @@ -481,9 +475,6 @@ async fn a_failed_challenge_still_cleans_up() { struct Refusing; impl Cloudflare for Refusing { - async fn zones(&self) -> Result, CfError> { - Ok(vec![]) - } async fn records(&self, _: &str, _: &str) -> Result, CfError> { Ok(vec![]) } diff --git a/crates/pyo-proto/src/system.rs b/crates/pyo-proto/src/system.rs index 1b2041e6..be3a5b8c 100644 --- a/crates/pyo-proto/src/system.rs +++ b/crates/pyo-proto/src/system.rs @@ -1545,6 +1545,160 @@ pub fn cel_literal(v: &Value) -> String { } } +// ── Cloudflare Tunnel ────────────────────────────────────────────────────── +// +// A cluster's websites through Cloudflare with no open ports +// (docs/cloudflare-tunnel.md). The agent runs the connector (cloudflared) +// in pyo-system with the tunnel's token, and points it at +// `TUNNEL_ORIGIN_SERVICE`, its own Service in front of the proxies' +// HTTPS listener. Tunnel domains' listeners trust X-Forwarded-For only from +// the connector's pods (a client policy labelled [`TUNNEL_CDN`]). + +/// cloudflared, by digest (2026.10.7), as Pyo Cloud runs it. Renovate keeps +/// it current. +pub const CLOUDFLARED_IMAGE: &str = "cloudflare/cloudflared@sha256:4955524aeaa379e154023d5a027c250f7b35041a2e7e950cf13f144bc9b9c5ba"; +/// The connector's Deployment, Secret and disruption budget in pyo-system. +pub const TUNNEL_NAME: &str = "pyo-tunnel"; +/// The label on its pods (and the selector). +pub const TUNNEL_APP: &str = "pyo-tunnel"; +/// The Secret's label with the tunnel id its token is for. +pub const TUNNEL_ID_LABEL: &str = "pyo.dev/tunnel-id"; +/// The Secret's key with the token. +pub const TUNNEL_TOKEN_KEY: &str = "token"; +/// Connectors: two, spread across servers where it can. +pub const TUNNEL_REPLICAS: i32 = 2; +/// Where cloudflared serves `/ready` (nothing reaches it: pyo-system +/// denies ingress). +pub const TUNNEL_METRICS_PORT: i32 = 2000; +/// The Service cloudflared sends requests to: the proxies' HTTPS. +pub const TUNNEL_ORIGIN_SERVICE: &str = "pyo-tunnel-origin"; +/// The label on a service's client policy for its tunnel listeners +/// ([`CDN_LABEL`]): not a CDN users pick (`firewall::BEHIND`). +pub const TUNNEL_CDN: &str = "tunnel"; +/// The Service that keeps public TCP and UDP ports on the servers in +/// tunnel mode, when the proxies' own Service isn't published. +pub const PUBLIC_PORTS_SERVICE: &str = "pyo-public-ports"; + +/// The connector's token, labelled with its tunnel. +pub fn tunnel_secret(tunnel_id: &str, token: &str) -> Value { + json!({ + "apiVersion": "v1", "kind": "Secret", + "metadata": { "name": TUNNEL_NAME, "namespace": crate::rbac::NS, "labels": { "app.kubernetes.io/managed-by": "pyo", TUNNEL_ID_LABEL: tunnel_id } }, + "type": "Opaque", + "stringData": { TUNNEL_TOKEN_KEY: token }, + }) +} + +/// The connector: cloudflared over HTTP/2 (QUIC is often blocked, and its +/// fallback is slow enough that the probe restarts it first), with no +/// service account token, non-root, read only, no capabilities. Never on +/// build-only servers, spread across servers where it can be. +pub fn tunnel_deployment(image: &str) -> Value { + let app = json!({ "app.kubernetes.io/name": TUNNEL_APP }); + let probe = json!({ "httpGet": { "path": "/ready", "port": TUNNEL_METRICS_PORT } }); + json!({ + "apiVersion": "apps/v1", "kind": "Deployment", + "metadata": { "name": TUNNEL_NAME, "namespace": crate::rbac::NS, "labels": { "app.kubernetes.io/name": TUNNEL_APP, "app.kubernetes.io/managed-by": "pyo" } }, + "spec": { + "replicas": TUNNEL_REPLICAS, + "selector": { "matchLabels": app }, + "strategy": { "type": "RollingUpdate", "rollingUpdate": { "maxSurge": 1, "maxUnavailable": 0 } }, + "template": { + "metadata": { "labels": app }, + "spec": { + "automountServiceAccountToken": false, + "affinity": gateway_affinity(), + "topologySpreadConstraints": [{ "maxSkew": 1, "topologyKey": "kubernetes.io/hostname", "whenUnsatisfiable": "ScheduleAnyway", "labelSelector": { "matchLabels": app } }], + "securityContext": { "runAsNonRoot": true, "runAsUser": 65532, "seccompProfile": { "type": "RuntimeDefault" } }, + "containers": [{ + "name": "cloudflared", + "image": image, + "args": ["tunnel", "--no-autoupdate", "--protocol", "http2", "--metrics", format!("0.0.0.0:{TUNNEL_METRICS_PORT}"), "--loglevel", "info", "run"], + "env": [{ "name": "TUNNEL_TOKEN", "valueFrom": { "secretKeyRef": { "name": TUNNEL_NAME, "key": TUNNEL_TOKEN_KEY } } }], + "readinessProbe": { "httpGet": probe["httpGet"], "periodSeconds": 10 }, + "livenessProbe": { "httpGet": probe["httpGet"], "initialDelaySeconds": 60, "periodSeconds": 30, "failureThreshold": 6 }, + "resources": { "requests": { "cpu": "10m", "memory": "32Mi" }, "limits": { "memory": "128Mi" } }, + "securityContext": { "allowPrivilegeEscalation": false, "readOnlyRootFilesystem": true, "capabilities": { "drop": ["ALL"] } }, + }], + }, + }, + }, + }) +} + +/// One connector stays up through a server's drain or a rollout. +pub fn tunnel_budget() -> Value { + json!({ + "apiVersion": "policy/v1", "kind": "PodDisruptionBudget", + "metadata": { "name": TUNNEL_NAME, "namespace": crate::rbac::NS, "labels": { "app.kubernetes.io/managed-by": "pyo" } }, + "spec": { "minAvailable": 1, "selector": { "matchLabels": { "app.kubernetes.io/name": TUNNEL_APP } } }, + }) +} + +/// The origin Service's one port: HTTPS onto the proxies' 443 listener. +pub fn tunnel_origin_ports() -> Value { + json!([{ "name": "https", "port": 443, "targetPort": 10443, "protocol": "TCP" }]) +} + +/// The Service cloudflared sends requests to, inside the cluster only. +pub fn tunnel_origin_service() -> Value { + json!({ + "apiVersion": "v1", "kind": "Service", + "metadata": { "name": TUNNEL_ORIGIN_SERVICE, "namespace": GATEWAY_NS, "labels": { "app.kubernetes.io/managed-by": "pyo" } }, + "spec": { "type": "ClusterIP", "selector": proxy_pods()["matchLabels"], "ports": tunnel_origin_ports() }, + }) +} + +/// Fields the API server fills in on a LoadBalancer Service with +/// externalTrafficPolicy Local, besides [`TAILNET_WEB_DEFAULTED`]. +pub const LOAD_BALANCER_DEFAULTED: [&str; 2] = ["allocateLoadBalancerNodePorts", "healthCheckNodePort"]; + +/// Public TCP and UDP ports in tunnel mode: a LoadBalancer Service onto +/// the proxies for these (protocol, public port), and nothing else. The +/// visitor's own address reaches the proxy (externalTrafficPolicy Local). +/// None without ports. +pub fn public_ports_service(ports: &[(String, i32)]) -> Option { + if ports.is_empty() { + return None; + } + let mut ports: Vec<(String, i32)> = ports.to_vec(); + ports.sort(); + ports.dedup(); + let list: Vec = ports + .iter() + .map(|(proto, port)| { + json!({ "name": format!("{}-{port}", proto.to_lowercase()), "port": port, "targetPort": crate::proxy_listen_port(*port), "protocol": proto }) + }) + .collect(); + Some(json!({ + "apiVersion": "v1", "kind": "Service", + "metadata": { "name": PUBLIC_PORTS_SERVICE, "namespace": GATEWAY_NS, "labels": { "app.kubernetes.io/managed-by": "pyo" } }, + "spec": { "type": "LoadBalancer", "externalTrafficPolicy": "Local", "selector": proxy_pods()["matchLabels"], "ports": list }, + })) +} + +/// A service's client policy for its tunnel listeners. +pub fn tunnel_policy_name(base: &str) -> String { + format!("{base}-{TUNNEL_CDN}") +} + +/// Addresses as a client policy trusts them: each one alone (/32, /128), +/// sorted, deduped. +pub fn host_cidrs(ips: &[String]) -> Vec { + let mut out: Vec = ips + .iter() + .filter_map(|ip| ip.parse::().ok()) + .map(|ip| match ip { + std::net::IpAddr::V4(v4) => format!("{v4}/32"), + std::net::IpAddr::V6(v6) => format!("{v6}/128"), + }) + .collect(); + out.sort(); + out.dedup(); + out.truncate(MAX_TRUSTED_CIDRS); + out +} + #[cfg(test)] mod tests { #[test] @@ -2414,157 +2568,3 @@ mod tests { assert_eq!(cel_literal(&json!("a\nb\\c")), "'a\\nb\\\\c'"); } } - -// ── Cloudflare Tunnel ────────────────────────────────────────────────────── -// -// A cluster's websites through Cloudflare with no open ports -// (docs/cloudflare-tunnel.md). The agent runs the connector (cloudflared) -// in pyo-system with the tunnel's token, and points it at -// `TUNNEL_ORIGIN_SERVICE`, its own Service in front of the proxies' -// HTTPS listener. Tunnel domains' listeners trust X-Forwarded-For only from -// the connector's pods (a client policy labelled [`TUNNEL_CDN`]). - -/// cloudflared, by digest (2026.10.7), as Pyo Cloud runs it. Renovate keeps -/// it current. -pub const CLOUDFLARED_IMAGE: &str = "cloudflare/cloudflared@sha256:4955524aeaa379e154023d5a027c250f7b35041a2e7e950cf13f144bc9b9c5ba"; -/// The connector's Deployment, Secret and disruption budget in pyo-system. -pub const TUNNEL_NAME: &str = "pyo-tunnel"; -/// The label on its pods (and the selector). -pub const TUNNEL_APP: &str = "pyo-tunnel"; -/// The Secret's label with the tunnel id its token is for. -pub const TUNNEL_ID_LABEL: &str = "pyo.dev/tunnel-id"; -/// The Secret's key with the token. -pub const TUNNEL_TOKEN_KEY: &str = "token"; -/// Connectors: two, spread across servers where it can. -pub const TUNNEL_REPLICAS: i32 = 2; -/// Where cloudflared serves `/ready` (nothing reaches it: pyo-system -/// denies ingress). -pub const TUNNEL_METRICS_PORT: i32 = 2000; -/// The Service cloudflared sends requests to: the proxies' HTTPS. -pub const TUNNEL_ORIGIN_SERVICE: &str = "pyo-tunnel-origin"; -/// The label on a service's client policy for its tunnel listeners -/// ([`CDN_LABEL`]): not a CDN users pick (`firewall::BEHIND`). -pub const TUNNEL_CDN: &str = "tunnel"; -/// The Service that keeps public TCP and UDP ports on the servers in -/// tunnel mode, when the proxies' own Service isn't published. -pub const PUBLIC_PORTS_SERVICE: &str = "pyo-public-ports"; - -/// The connector's token, labelled with its tunnel. -pub fn tunnel_secret(tunnel_id: &str, token: &str) -> Value { - json!({ - "apiVersion": "v1", "kind": "Secret", - "metadata": { "name": TUNNEL_NAME, "namespace": crate::rbac::NS, "labels": { "app.kubernetes.io/managed-by": "pyo", TUNNEL_ID_LABEL: tunnel_id } }, - "type": "Opaque", - "stringData": { TUNNEL_TOKEN_KEY: token }, - }) -} - -/// The connector: cloudflared over HTTP/2 (QUIC is often blocked, and its -/// fallback is slow enough that the probe restarts it first), with no -/// service account token, non-root, read only, no capabilities. Never on -/// build-only servers, spread across servers where it can be. -pub fn tunnel_deployment(image: &str) -> Value { - let app = json!({ "app.kubernetes.io/name": TUNNEL_APP }); - let probe = json!({ "httpGet": { "path": "/ready", "port": TUNNEL_METRICS_PORT } }); - json!({ - "apiVersion": "apps/v1", "kind": "Deployment", - "metadata": { "name": TUNNEL_NAME, "namespace": crate::rbac::NS, "labels": { "app.kubernetes.io/name": TUNNEL_APP, "app.kubernetes.io/managed-by": "pyo" } }, - "spec": { - "replicas": TUNNEL_REPLICAS, - "selector": { "matchLabels": app }, - "strategy": { "type": "RollingUpdate", "rollingUpdate": { "maxSurge": 1, "maxUnavailable": 0 } }, - "template": { - "metadata": { "labels": app }, - "spec": { - "automountServiceAccountToken": false, - "affinity": gateway_affinity(), - "topologySpreadConstraints": [{ "maxSkew": 1, "topologyKey": "kubernetes.io/hostname", "whenUnsatisfiable": "ScheduleAnyway", "labelSelector": { "matchLabels": app } }], - "securityContext": { "runAsNonRoot": true, "runAsUser": 65532, "seccompProfile": { "type": "RuntimeDefault" } }, - "containers": [{ - "name": "cloudflared", - "image": image, - "args": ["tunnel", "--no-autoupdate", "--protocol", "http2", "--metrics", format!("0.0.0.0:{TUNNEL_METRICS_PORT}"), "--loglevel", "info", "run"], - "env": [{ "name": "TUNNEL_TOKEN", "valueFrom": { "secretKeyRef": { "name": TUNNEL_NAME, "key": TUNNEL_TOKEN_KEY } } }], - "readinessProbe": { "httpGet": probe["httpGet"], "periodSeconds": 10 }, - "livenessProbe": { "httpGet": probe["httpGet"], "initialDelaySeconds": 60, "periodSeconds": 30, "failureThreshold": 6 }, - "resources": { "requests": { "cpu": "10m", "memory": "32Mi" }, "limits": { "memory": "128Mi" } }, - "securityContext": { "allowPrivilegeEscalation": false, "readOnlyRootFilesystem": true, "capabilities": { "drop": ["ALL"] } }, - }], - }, - }, - }, - }) -} - -/// One connector stays up through a server's drain or a rollout. -pub fn tunnel_budget() -> Value { - json!({ - "apiVersion": "policy/v1", "kind": "PodDisruptionBudget", - "metadata": { "name": TUNNEL_NAME, "namespace": crate::rbac::NS, "labels": { "app.kubernetes.io/managed-by": "pyo" } }, - "spec": { "minAvailable": 1, "selector": { "matchLabels": { "app.kubernetes.io/name": TUNNEL_APP } } }, - }) -} - -/// The origin Service's one port: HTTPS onto the proxies' 443 listener. -pub fn tunnel_origin_ports() -> Value { - json!([{ "name": "https", "port": 443, "targetPort": 10443, "protocol": "TCP" }]) -} - -/// The Service cloudflared sends requests to, inside the cluster only. -pub fn tunnel_origin_service() -> Value { - json!({ - "apiVersion": "v1", "kind": "Service", - "metadata": { "name": TUNNEL_ORIGIN_SERVICE, "namespace": GATEWAY_NS, "labels": { "app.kubernetes.io/managed-by": "pyo" } }, - "spec": { "type": "ClusterIP", "selector": proxy_pods()["matchLabels"], "ports": tunnel_origin_ports() }, - }) -} - -/// Fields the API server fills in on a LoadBalancer Service with -/// externalTrafficPolicy Local, besides [`TAILNET_WEB_DEFAULTED`]. -pub const LOAD_BALANCER_DEFAULTED: [&str; 2] = ["allocateLoadBalancerNodePorts", "healthCheckNodePort"]; - -/// Public TCP and UDP ports in tunnel mode: a LoadBalancer Service onto -/// the proxies for these (protocol, public port), and nothing else. The -/// visitor's own address reaches the proxy (externalTrafficPolicy Local). -/// None without ports. -pub fn public_ports_service(ports: &[(String, i32)]) -> Option { - if ports.is_empty() { - return None; - } - let mut ports: Vec<(String, i32)> = ports.to_vec(); - ports.sort(); - ports.dedup(); - let list: Vec = ports - .iter() - .map(|(proto, port)| { - json!({ "name": format!("{}-{port}", proto.to_lowercase()), "port": port, "targetPort": crate::proxy_listen_port(*port), "protocol": proto }) - }) - .collect(); - Some(json!({ - "apiVersion": "v1", "kind": "Service", - "metadata": { "name": PUBLIC_PORTS_SERVICE, "namespace": GATEWAY_NS, "labels": { "app.kubernetes.io/managed-by": "pyo" } }, - "spec": { "type": "LoadBalancer", "externalTrafficPolicy": "Local", "selector": proxy_pods()["matchLabels"], "ports": list }, - })) -} - -/// A service's client policy for its tunnel listeners. -pub fn tunnel_policy_name(base: &str) -> String { - format!("{base}-{TUNNEL_CDN}") -} - -/// Addresses as a client policy trusts them: each one alone (/32, /128), -/// sorted, deduped. -pub fn host_cidrs(ips: &[String]) -> Vec { - let mut out: Vec = ips - .iter() - .filter_map(|ip| ip.parse::().ok()) - .map(|ip| match ip { - std::net::IpAddr::V4(v4) => format!("{v4}/32"), - std::net::IpAddr::V6(v6) => format!("{v6}/128"), - }) - .collect(); - out.sort(); - out.dedup(); - out.truncate(MAX_TRUSTED_CIDRS); - out -} From 20609d2985ea66b6006400b148a9bc5fce28edd3 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:35:47 +0700 Subject: [PATCH 035/139] docs: record the tunnel test results in the build status --- docs/cloudflare-tunnel.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/cloudflare-tunnel.md b/docs/cloudflare-tunnel.md index 71e075ef..72e72afc 100644 --- a/docs/cloudflare-tunnel.md +++ b/docs/cloudflare-tunnel.md @@ -1579,8 +1579,8 @@ Not merged into `dev` until the feature is complete and tested. |---|---| | Decisions applied to this spec | Done (b145440, 5284a70, bf1cc78) | | 1. Token and zones | Done, tested (e3d91dd api, adc8e62 cli, 12cf81f dash) | -| 2. Agent and Gateway | Written and compiled (eadce05 proto, 4db8b6f agent). Agent tunnel tests pass (9). pyo-proto rbac tests not run yet | -| 3. Control plane | Written and compiled (3b9ae43): migration 0040, tunnel_loop.rs, heartbeat and snapshot. Unit tests 24 of 26 passed, the 2 failures were test mistakes, fixed in 3b9ae43, not rerun yet | +| 2. Agent and Gateway | Done, tested (eadce05 proto, 4db8b6f agent) | +| 3. Control plane | Done, unit tested (3b9ae43): migration 0040, tunnel_loop.rs, heartbeat and snapshot. No database test yet | | 4. Traffic choice, switching | API, MCP and CLI written (3b9ae43, a47f92e). Dashboard merged (06dfbba, `tsc` passes): Traffic panel, tunnel badge, record line, add and remove domain | | 5. Ports, connect.sh, alerts | Public ports Service and tunnel alerts written. connect.sh keeps its line (see Decisions) | | 6. Docs, e2e, real-zone test, Pyo Ops | Not started (real zone and Pyo Ops need the user) | @@ -1599,11 +1599,15 @@ Where things are: - `crates/pyo-proto/src/system.rs` (Cloudflare Tunnel section), `rbac.rs` (origin and public ports Services, `tunnel` client policies). +Tests (2026-11-22): the full pyo-proto (167), pyo-agent (216), pyo-api +(611) and pyo-cli (80) suites pass, except `openapi::docs_copy_is_current`, +which compares with pyo-docs' `openapi/pyo.json` (regenerate it with the +docs in Phase 6). Clippy's 4 notes are fixed in the last commit, which +wasn't compiled again (the disk was at its 60 GB floor). + Next: -1. Rerun `cargo test -p pyo-proto -p pyo-agent -p pyo-api -p pyo-cli tunnel` - and `… cloudflare`, plus the full `-p pyo-api -p pyo-agent -p pyo-proto` - suites (the access hash and admission tests), and clippy. +1. Compile and clippy the last commit. 2. Dashboard gaps: the new-service wizard has no tunnel switch, no warning for deeper names (a.b.example.com), and "Certificate: " shows only through `tunnel.error`. From 9a42d36ce173930052c62e7b8acabbc1934d45b3 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:43:59 +0700 Subject: [PATCH 036/139] docs: record the clean tunnel clippy run --- docs/cloudflare-tunnel.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/cloudflare-tunnel.md b/docs/cloudflare-tunnel.md index 72e72afc..86d3e56d 100644 --- a/docs/cloudflare-tunnel.md +++ b/docs/cloudflare-tunnel.md @@ -1602,12 +1602,13 @@ Where things are: Tests (2026-11-22): the full pyo-proto (167), pyo-agent (216), pyo-api (611) and pyo-cli (80) suites pass, except `openapi::docs_copy_is_current`, which compares with pyo-docs' `openapi/pyo.json` (regenerate it with the -docs in Phase 6). Clippy's 4 notes are fixed in the last commit, which -wasn't compiled again (the disk was at its 60 GB floor). +docs in Phase 6). `cargo clippy -p pyo-proto -p pyo-agent -p pyo-api +-p pyo-cli --tests -- -D warnings` is clean on 928ac34, and the API and +CLI tunnel tests pass on it. Next: -1. Compile and clippy the last commit. +1. Regenerate pyo-docs' `openapi/pyo.json` with the Phase 6 docs. 2. Dashboard gaps: the new-service wizard has no tunnel switch, no warning for deeper names (a.b.example.com), and "Certificate: " shows only through `tunnel.error`. From 5f8d296b4e8899517e27014e1e7f452a34e7ba32 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:49:38 +0700 Subject: [PATCH 037/139] fix(proto): make the gateway, waf and tailnet pods critical A server short of disk evicted the Gateway's pod, and its DaemonSet replaced it over and over: the kubelet refused each new pod while the server had DiskPressure, about 11,000 times in two hours, until the cluster's datastore stalled. The proxies, the WAF and the tailnet pods now run with system-node-critical, so the kubelet neither evicts nor refuses them. --- crates/pyo-proto/src/system.rs | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/crates/pyo-proto/src/system.rs b/crates/pyo-proto/src/system.rs index f91de332..48618f56 100644 --- a/crates/pyo-proto/src/system.rs +++ b/crates/pyo-proto/src/system.rs @@ -414,6 +414,14 @@ pub fn waf_labels() -> Value { json!({ "app.kubernetes.io/name": WAF_NAME, "app.kubernetes.io/managed-by": "pyo" }) } +/// The priority of Pyo's pods that run on every server (the proxies, the +/// WAF, the tailnet pods, Vector): Kubernetes' own for such pods. A server +/// short of disk or memory never evicts them, and starts them all the same. +/// Without it, a DaemonSet's pod evicted there is replaced at once, the +/// replacement is refused, and so on: thousands of Failed pods an hour, +/// which can stall the cluster's datastore. +pub const SERVER_CRITICAL: &str = "system-node-critical"; + /// Which servers run a proxy: every one but build-only servers (labelled /// [`crate::BUILDER_NODE_LABEL`]; GPU servers too). The WAF's processor /// runs on exactly the same ones. @@ -445,6 +453,7 @@ pub fn waf_daemonset(image: &str, geoip_image: &str) -> Value { "serviceAccountName": WAF_NAME, "automountServiceAccountToken": true, "securityContext": { "runAsNonRoot": true, "runAsUser": 65532, "runAsGroup": 65532, "seccompProfile": { "type": "RuntimeDefault" } }, + "priorityClassName": SERVER_CRITICAL, "affinity": gateway_affinity(), "tolerations": [{ "key": crate::GPU_RESOURCE, "operator": "Exists", "effect": "NoSchedule" }], "containers": [{ @@ -664,6 +673,7 @@ pub fn envoy_proxy(geoip_image: &str, public: bool) -> Value { // host ports, so two fit on one server. "strategy": { "type": "RollingUpdate", "rollingUpdate": { "maxSurge": 1, "maxUnavailable": 0 } }, "pod": { + "priorityClassName": SERVER_CRITICAL, "affinity": gateway_affinity(), "tolerations": [{ "key": crate::GPU_RESOURCE, "operator": "Exists", "effect": "NoSchedule" }], "volumes": [{ "name": "geoip", "image": { "reference": geoip_image, "pullPolicy": "IfNotPresent" } }], @@ -1093,6 +1103,7 @@ pub fn tailnet_daemonset(image: &str) -> Value { "metadata": { "labels": labels }, "spec": { "serviceAccountName": TAILNET_DAEMONSET, + "priorityClassName": SERVER_CRITICAL, "affinity": gateway_affinity(), "tolerations": [{ "key": crate::GPU_RESOURCE, "operator": "Exists", "effect": "NoSchedule" }], "containers": [{ @@ -1638,6 +1649,31 @@ mod tests { } } + /// A server short of disk keeps its proxy, WAF and tailnet pod: the + /// kubelet neither evicts nor refuses them, so their DaemonSets never + /// replace them over and over. + #[test] + fn per_server_pods_are_critical() { + for public in [true, false] { + let p = envoy_proxy("g", public); + assert_eq!( + p["spec"]["provider"]["kubernetes"]["envoyDaemonSet"]["pod"]["priorityClassName"], + SERVER_CRITICAL + ); + } + for ds in [waf_daemonset("w", "g"), tailnet_daemonset("a")] { + assert_eq!(ds["kind"], "DaemonSet"); + assert_eq!( + ds["spec"]["template"]["spec"]["priorityClassName"], + SERVER_CRITICAL, + "{}", + ds["metadata"]["name"] + ); + } + // Kubernetes' built-in class for pods every server needs. + assert_eq!(SERVER_CRITICAL, "system-node-critical"); + } + /// An update never leaves a server without a proxy: the new one starts /// first, and the old one drains within the shutdown manager's 10 s. #[test] From 9d8167bf96c68a0f233d79ecfd0eaa209220a433 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:51:24 +0700 Subject: [PATCH 038/139] fix(agent): make vector's pods critical Vector runs on every server as a DaemonSet, so an eviction on a server short of disk could start the same replace and refuse loop as the Gateway's. It reports that server's disk too. Its pods now run with system-node-critical like the other per-server pods. --- crates/pyo-agent/src/observability.rs | 143 ++++++++++++++++---------- 1 file changed, 86 insertions(+), 57 deletions(-) diff --git a/crates/pyo-agent/src/observability.rs b/crates/pyo-agent/src/observability.rs index 26239f94..37905a04 100644 --- a/crates/pyo-agent/src/observability.rs +++ b/crates/pyo-agent/src/observability.rs @@ -226,67 +226,74 @@ async fn vector(client: &Client) -> anyhow::Result<()> { ) .await?; Api::::namespaced(client.clone(), NS) - .patch( - VECTOR, - &pp(), - &Patch::Apply(json!({ - "apiVersion": "apps/v1", "kind": "DaemonSet", - "metadata": { "name": VECTOR, "labels": labels }, - "spec": { - "selector": { "matchLabels": { "app.kubernetes.io/name": VECTOR } }, - // Every server's copy moves at once: one on a server that's - // down (it can't be replaced there) would otherwise hold - // the others on their old config for good. A copy is only - // gone for seconds, and picks up where it stopped. - "updateStrategy": { "type": "RollingUpdate", "rollingUpdate": { "maxUnavailable": "100%" } }, - "template": { - "metadata": { - "labels": labels, - // Restart Vector when its config changes. - "annotations": { "pyo/config-hash": format!("{:x}", fxhash(&config)) }, - }, - "spec": { - "serviceAccountName": VECTOR, - "tolerations": [{ "operator": "Exists" }], - "containers": [{ - "name": "vector", - "image": VECTOR_IMAGE, - // Also re-read the config when its Secret changes, in - // case a restart is held up. - "args": ["--config", "/etc/vector/vector.yaml", "--watch-config"], - "env": [ - { "name": "VECTOR_LOG", "value": "warn" }, - { "name": "PYO_NODE_NAME", "valueFrom": { "fieldRef": { "fieldPath": "spec.nodeName" } } }, - // host_metrics reads the server's, not the container's. - { "name": "PROCFS_ROOT", "value": "/host/proc" }, - { "name": "SYSFS_ROOT", "value": "/host/sys" }, - ], - // ~35 MiB at rest (measured). - "resources": { "requests": { "cpu": "10m", "memory": "48Mi" }, "limits": { "memory": "256Mi" } }, - "volumeMounts": [ - { "name": "config", "mountPath": "/etc/vector", "readOnly": true }, - { "name": "data", "mountPath": "/vector-data-dir" }, - { "name": "var-log", "mountPath": "/var/log", "readOnly": true }, - { "name": "host-proc", "mountPath": "/host/proc", "readOnly": true }, - { "name": "host-sys", "mountPath": "/host/sys", "readOnly": true }, - ], - }], - "volumes": [ - { "name": "config", "secret": { "secretName": VECTOR } }, - { "name": "data", "hostPath": { "path": "/var/lib/pyo-vector", "type": "DirectoryOrCreate" } }, - { "name": "var-log", "hostPath": { "path": "/var/log" } }, - { "name": "host-proc", "hostPath": { "path": "/proc" } }, - { "name": "host-sys", "hostPath": { "path": "/sys" } }, - ], - }, - }, - }, - })), - ) + .patch(VECTOR, &pp(), &Patch::Apply(vector_daemonset(&config))) .await?; Ok(()) } +/// Vector's DaemonSet: on every server, restarted when its config changes. +fn vector_daemonset(config: &str) -> serde_json::Value { + let labels = + json!({ "app.kubernetes.io/name": VECTOR, "app.kubernetes.io/managed-by": MANAGER }); + json!({ + "apiVersion": "apps/v1", "kind": "DaemonSet", + "metadata": { "name": VECTOR, "labels": labels }, + "spec": { + "selector": { "matchLabels": { "app.kubernetes.io/name": VECTOR } }, + // Every server's copy moves at once: one on a server that's + // down (it can't be replaced there) would otherwise hold + // the others on their old config for good. A copy is only + // gone for seconds, and picks up where it stopped. + "updateStrategy": { "type": "RollingUpdate", "rollingUpdate": { "maxUnavailable": "100%" } }, + "template": { + "metadata": { + "labels": labels, + // Restart Vector when its config changes. + "annotations": { "pyo/config-hash": format!("{:x}", fxhash(config)) }, + }, + "spec": { + "serviceAccountName": VECTOR, + // Kept on a server short of disk: it reports that + // server's disk, and its DaemonSet mustn't replace it + // over and over there. + "priorityClassName": pyo_proto::system::SERVER_CRITICAL, + "tolerations": [{ "operator": "Exists" }], + "containers": [{ + "name": "vector", + "image": VECTOR_IMAGE, + // Also re-read the config when its Secret changes, in + // case a restart is held up. + "args": ["--config", "/etc/vector/vector.yaml", "--watch-config"], + "env": [ + { "name": "VECTOR_LOG", "value": "warn" }, + { "name": "PYO_NODE_NAME", "valueFrom": { "fieldRef": { "fieldPath": "spec.nodeName" } } }, + // host_metrics reads the server's, not the container's. + { "name": "PROCFS_ROOT", "value": "/host/proc" }, + { "name": "SYSFS_ROOT", "value": "/host/sys" }, + ], + // ~35 MiB at rest (measured). + "resources": { "requests": { "cpu": "10m", "memory": "48Mi" }, "limits": { "memory": "256Mi" } }, + "volumeMounts": [ + { "name": "config", "mountPath": "/etc/vector", "readOnly": true }, + { "name": "data", "mountPath": "/vector-data-dir" }, + { "name": "var-log", "mountPath": "/var/log", "readOnly": true }, + { "name": "host-proc", "mountPath": "/host/proc", "readOnly": true }, + { "name": "host-sys", "mountPath": "/host/sys", "readOnly": true }, + ], + }], + "volumes": [ + { "name": "config", "secret": { "secretName": VECTOR } }, + { "name": "data", "hostPath": { "path": "/var/lib/pyo-vector", "type": "DirectoryOrCreate" } }, + { "name": "var-log", "hostPath": { "path": "/var/log" } }, + { "name": "host-proc", "hostPath": { "path": "/proc" } }, + { "name": "host-sys", "hostPath": { "path": "/sys" } }, + ], + }, + }, + }, + }) +} + /// The traffic store's volume: the kept requests. Asked for once, never /// resized (the store keeps to the team's limit itself) and kept when /// observability is off. @@ -409,3 +416,25 @@ fn fxhash(s: &str) -> u64 { (h ^ b as u64).wrapping_mul(0x100000001b3) }) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vector_stays_on_a_server_short_of_disk() { + let ds: DaemonSet = serde_json::from_value(vector_daemonset("a: 1")).unwrap(); + let spec = ds.spec.unwrap().template.spec.unwrap(); + assert_eq!( + spec.priority_class_name.as_deref(), + Some(pyo_proto::system::SERVER_CRITICAL) + ); + assert_eq!(spec.service_account_name.as_deref(), Some(VECTOR)); + // A new config restarts it. + let hash = |c: &str| { + vector_daemonset(c)["spec"]["template"]["metadata"]["annotations"]["pyo/config-hash"] + .clone() + }; + assert_ne!(hash("a: 1"), hash("a: 2")); + } +} From d4db517579867270a4c31c0b6110230696b385bc Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:51:24 +0700 Subject: [PATCH 039/139] fix(agent): clean up a pod loop at once and run again soon An owner with more than 50 Failed pods is in a loop, a DaemonSet's pod refused by its server a few times a second. Its pods past the newest three now go without the ten minute grace period, and the next run comes after 30 seconds instead of five minutes until no owner is over. Still only in Pyo's namespaces, by uid, 25 at a time with a pause. A run is tested against a fake Kubernetes API. --- crates/pyo-agent/src/cleanup.rs | 337 +++++++++++++++++++++++++++++--- 1 file changed, 312 insertions(+), 25 deletions(-) diff --git a/crates/pyo-agent/src/cleanup.rs b/crates/pyo-agent/src/cleanup.rs index 21f68e88..082d62f8 100644 --- a/crates/pyo-agent/src/cleanup.rs +++ b/crates/pyo-agent/src/cleanup.rs @@ -12,6 +12,13 @@ //! those, and a cron run's outcome is read from them), and a few at a time //! ([`BATCH`], [`PAUSE`], [`MAX_PER_RUN`]) so neither the API server nor the //! kubelets are flooded. +//! +//! An owner with more than [`STORM`] Failed pods is caught in a loop (a +//! DaemonSet's pod refused by its server over and over, a few a second): +//! its pods past the newest [`KEEP`] go without waiting out the grace +//! period, and the next run comes after [`SOON`] instead of minutes, until +//! no owner is over. Pyo's own DaemonSets are critical (pyo-proto's +//! `system::SERVER_CRITICAL`) so they don't loop: this is for what else may. use std::{collections::BTreeMap, time::Duration}; @@ -33,7 +40,11 @@ pub const BATCH: usize = 25; pub const PAUSE: Duration = Duration::from_secs(5); /// Deletions per run at most: the rest wait for the next run. pub const MAX_PER_RUN: usize = 500; +/// More Failed pods than this for one owner: a loop. +pub const STORM: usize = 50; const EVERY: Duration = Duration::from_secs(5 * 60); +/// The next run, while some owner is over [`STORM`]. +pub const SOON: Duration = Duration::from_secs(30); /// After a start: soon, but after the first heartbeat. const FIRST: Duration = Duration::from_secs(60); @@ -110,9 +121,19 @@ pub fn dead(p: &Pod) -> Option { }) } -/// The pods to delete, oldest first: past the grace period and not among -/// the newest [`KEEP`] of their owner (in their namespace). At most `max`. -pub fn choose(dead: Vec, now: i64, max: usize) -> Vec { +/// What a run deletes, and whether some owner is in a loop. +#[derive(Debug, Default, PartialEq)] +pub struct Choice { + /// Oldest first. + pub pods: Vec, + /// An owner has more than [`STORM`] Failed pods. + pub storm: bool, +} + +/// The pods to delete, oldest first: not among the newest [`KEEP`] of their +/// owner (in their namespace), and past the grace period unless their owner +/// is over [`STORM`]. At most `max`. Pods with no owner are never a loop. +pub fn choose(dead: Vec, now: i64, max: usize) -> Choice { let mut by_owner: BTreeMap<(String, String), Vec> = BTreeMap::new(); for d in dead { by_owner @@ -120,21 +141,25 @@ pub fn choose(dead: Vec, now: i64, max: usize) -> Vec { .or_default() .push(d); } - let mut out: Vec = by_owner - .into_values() - .flat_map(|mut pods| { - pods.sort_by_key(|d| std::cmp::Reverse(d.ended_at)); + let mut storm = false; + let mut out: Vec = vec![]; + for ((_, owner), mut pods) in by_owner { + let looping = !owner.is_empty() && pods.len() > STORM; + storm |= looping; + pods.sort_by_key(|d| std::cmp::Reverse(d.ended_at)); + out.extend( pods.into_iter() .skip(KEEP) - .filter(|d| now - d.ended_at >= GRACE_MS) - }) - .collect(); + .filter(|d| looping || now - d.ended_at >= GRACE_MS), + ); + } out.sort_by_key(|d| d.ended_at); out.truncate(max); - out + Choice { pods: out, storm } } -/// Every few minutes, for good. Not while the cluster's policy is read only. +/// Every few minutes, for good, or [`SOON`] again while pods loop. Not while +/// the cluster's policy is read only. pub async fn run(agent: Agent) { tokio::time::sleep(FIRST).await; loop { @@ -143,19 +168,36 @@ pub async fn run(agent: Agent) { .read() .unwrap_or_else(|e| e.into_inner()) .read_only; + let mut storm = false; if !read_only { - match once(&agent.kube).await { - Ok(0) => {} - Ok(n) => tracing::info!(deleted = n, "cleaned up failed pods"), + match once(&agent.kube, PAUSE).await { + Ok(r) => { + storm = r.storm; + if r.storm { + tracing::warn!( + deleted = r.deleted, + "pods are failing over and over, cleaning up again soon" + ); + } else if r.deleted > 0 { + tracing::info!(deleted = r.deleted, "cleaned up failed pods"); + } + } Err(e) => tracing::warn!(error = %e, "couldn't clean up failed pods"), } } - tokio::time::sleep(EVERY).await; + tokio::time::sleep(if storm { SOON } else { EVERY }).await; } } -/// One run: how many pods it deleted. -async fn once(client: &kube::Client) -> kube::Result { +/// What a run did. +#[derive(Debug, Default, PartialEq)] +struct Run { + deleted: usize, + storm: bool, +} + +/// One run, with `pause` between batches. +async fn once(client: &kube::Client, pause: Duration) -> kube::Result { let namespaces: Vec = Api::::all(client.clone()) .list(&ListParams::default()) .await? @@ -173,7 +215,10 @@ async fn once(client: &kube::Client) -> kube::Result { dead.extend(d); } } - let chosen = choose(dead, pyo_proto::now_ms(), MAX_PER_RUN); + let Choice { + pods: chosen, + storm, + } = choose(dead, pyo_proto::now_ms(), MAX_PER_RUN); let mut deleted = 0; // Namespaces where the agent's roles don't allow deleting. let mut refused: Vec = vec![]; @@ -182,7 +227,7 @@ async fn once(client: &kube::Client) -> kube::Result { continue; } if i > 0 && i % BATCH == 0 { - tokio::time::sleep(PAUSE).await; + tokio::time::sleep(pause).await; } // Only that very pod: a StatefulSet's next one has the same name. let dp = DeleteParams { @@ -207,7 +252,7 @@ async fn once(client: &kube::Client) -> kube::Result { } } } - Ok(deleted) + Ok(Run { deleted, storm }) } /// [`dead`], for a pod listed in `ns` (only ever that namespace's). @@ -244,7 +289,7 @@ mod tests { .map(|i| d("pyo-gateway", rs, &format!("p{i}"), 20 + i)) .collect(); // p0..p2 are the newest; p3..p5 go, oldest first. - assert_eq!(names(&choose(pods, NOW, 100)), ["p5", "p4", "p3"]); + assert_eq!(names(&choose(pods, NOW, 100).pods), ["p5", "p4", "p3"]); } #[test] @@ -257,7 +302,7 @@ mod tests { d("shop", rs, "young", 9), d("shop", rs, "old", 11), ]; - assert_eq!(names(&choose(pods, NOW, 100)), ["old"]); + assert_eq!(names(&choose(pods, NOW, 100).pods), ["old"]); } #[test] @@ -275,7 +320,7 @@ mod tests { d("shop", "", "bare4", 43), ]; // Three or fewer each, except the bare pods (one owner: none). - assert_eq!(names(&choose(pods, NOW, 100)), ["bare4"]); + assert_eq!(names(&choose(pods, NOW, 100).pods), ["bare4"]); } #[test] @@ -284,7 +329,7 @@ mod tests { let pods = (0..4700) .map(|i| d("pyo-gateway", rs, &format!("p{i}"), 20 + i)) .collect(); - let chosen = choose(pods, NOW, MAX_PER_RUN); + let chosen = choose(pods, NOW, MAX_PER_RUN).pods; assert_eq!(chosen.len(), MAX_PER_RUN); assert_eq!(chosen[0].name, "p4699"); assert!( @@ -294,10 +339,252 @@ mod tests { ); } + /// A DaemonSet's pod refused over and over: its young pods go too + /// (all but the newest three), and the next run comes soon. + #[test] + fn a_loop_skips_the_grace_period() { + let ds = "DaemonSet/envoy-pyo-1"; + let pods: Vec = (0..=STORM as i64) + .map(|i| d("pyo-gateway", ds, &format!("p{i}"), i % 5)) + .collect(); + let c = choose(pods.clone(), NOW, MAX_PER_RUN); + assert!(c.storm); + assert_eq!(c.pods.len(), STORM + 1 - KEEP); + // At its limit, not yet a loop: the grace period holds. + let c = choose(pods[..STORM].to_vec(), NOW, MAX_PER_RUN); + assert!(!c.storm); + assert!(c.pods.is_empty(), "{:?}", names(&c.pods)); + } + + /// Only the looping owner skips the grace period, and many pods with no + /// owner aren't a loop. + #[test] + fn a_loop_is_one_owners() { + let mut pods: Vec = (0..60) + .map(|i| d("pyo-system", "DaemonSet/pyo-vector", &format!("v{i}"), 1)) + .collect(); + pods.extend((0..5).map(|i| d("pyo-system", "ReplicaSet/pyo-agent-1", &format!("a{i}"), 1))); + pods.extend((0..5).map(|i| d("shop", "DaemonSet/pyo-vector", &format!("s{i}"), 1))); + let c = choose(pods, NOW, MAX_PER_RUN); + assert!(c.storm); + assert_eq!(c.pods.len(), 57); + assert!( + c.pods.iter().all(|p| p.name.starts_with('v')), + "{:?}", + names(&c.pods) + ); + + let bare: Vec = (0..80) + .map(|i| d("shop", "", &format!("b{i}"), 1)) + .collect(); + let c = choose(bare, NOW, MAX_PER_RUN); + assert!(!c.storm); + assert!(c.pods.is_empty()); + } + fn pod(v: serde_json::Value) -> Pod { serde_json::from_value(v).unwrap() } + /// A fake Kubernetes API: namespaces (name, labels), Failed pods per + /// namespace, and the deletes it got (namespace, name, uid precondition). + mod fake { + use std::sync::{Arc, Mutex}; + + use axum::{ + Json, Router, + body::Bytes, + extract::State, + http::{Method, StatusCode, Uri}, + response::{IntoResponse, Response}, + }; + use serde_json::{Value, json}; + + #[derive(Default)] + pub struct Cluster { + pub namespaces: Vec, + pub pods: Vec, + pub deleted: Vec<(String, String, String)>, + pub lists: Vec, + } + + pub type Shared = Arc>; + + async fn handle( + State(st): State, + method: Method, + uri: Uri, + body: Bytes, + ) -> Response { + let mut c = st.lock().unwrap(); + let path = uri.path().to_owned(); + let parts: Vec<&str> = path.trim_start_matches("/api/v1/").split('/').collect(); + match (method.as_str(), parts.as_slice()) { + ("GET", ["namespaces"]) => Json(json!({ + "apiVersion": "v1", "kind": "NamespaceList", "metadata": {}, "items": c.namespaces, + })) + .into_response(), + ("GET", ["namespaces", ns, "pods"]) => { + c.lists.push(format!("{ns}?{}", uri.query().unwrap_or_default())); + let items: Vec = c + .pods + .iter() + .filter(|p| p["metadata"]["namespace"] == *ns) + .cloned() + .collect(); + Json(json!({ "apiVersion": "v1", "kind": "PodList", "metadata": {}, "items": items })) + .into_response() + } + ("DELETE", ["namespaces", ns, "pods", name]) => { + let opts: Value = serde_json::from_slice(&body).unwrap_or_default(); + let uid = opts["preconditions"]["uid"].as_str().unwrap_or_default().to_owned(); + c.deleted.push(((*ns).to_owned(), (*name).to_owned(), uid)); + let at = c.pods.iter().position(|p| { + p["metadata"]["namespace"] == *ns && p["metadata"]["name"] == *name + }); + match at { + Some(i) => Json(c.pods.remove(i)).into_response(), + None => (StatusCode::NOT_FOUND, Json(json!({ "kind": "Status", "apiVersion": "v1", "status": "Failure", "reason": "NotFound", "code": 404, "message": "not found" }))).into_response(), + } + } + _ => (StatusCode::NOT_FOUND, Json(json!({ "kind": "Status", "apiVersion": "v1", "status": "Failure", "code": 404, "message": "no such path" }))).into_response(), + } + } + + pub async fn serve(cluster: Cluster) -> (kube::Client, Shared) { + let st: Shared = Arc::new(Mutex::new(cluster)); + let app = Router::new().fallback(handle).with_state(st.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let config = kube::Config::new(format!("http://{addr}").parse().unwrap()); + (kube::Client::try_from(config).unwrap(), st) + } + } + + fn failed_pod( + ns: &str, + name: &str, + owner: Option<(&str, &str)>, + ended: &str, + ) -> serde_json::Value { + let owners: Vec = owner + .map(|(kind, n)| json!({ "apiVersion": "apps/v1", "kind": kind, "name": n, "uid": "o", "controller": true })) + .into_iter() + .collect(); + json!({ + "apiVersion": "v1", "kind": "Pod", + "metadata": { "name": name, "namespace": ns, "uid": format!("uid-{name}"), "ownerReferences": owners }, + "status": { "phase": "Failed", "reason": "Evicted", "message": "The node had condition: [DiskPressure]. ", + "conditions": [{ "type": "Ready", "status": "False", "lastTransitionTime": ended }] }, + }) + } + + /// A run against a cluster where the proxy's DaemonSet loops on a + /// server short of disk: its pods go at once, each by its uid, but + /// only in Pyo's namespaces, never another's, and nothing young that + /// isn't looping. + #[tokio::test] + async fn a_run_cleans_up_a_loop_in_pyos_namespaces_only() { + use k8s_openapi::jiff::Timestamp; + let now = Timestamp::from_second(Timestamp::now().as_second()) + .unwrap() + .to_string(); + let ns = |name: &str, labels: serde_json::Value| json!({ "metadata": { "name": name, "labels": labels } }); + let mut cluster = fake::Cluster { + namespaces: vec![ + ns("pyo-gateway", json!({})), + ns("pyo-system", json!({})), + ns("theirs", json!({})), + ns( + "pyo-waf", + json!({ "pyo.dev/bundle": "waf", "pyo.dev/managed": "true" }), + ), + ], + ..Default::default() + }; + let ds = Some(("DaemonSet", "envoy-pyo-1")); + for i in 0..60 { + cluster + .pods + .push(failed_pod("pyo-gateway", &format!("envoy-{i}"), ds, &now)); + cluster.pods.push(failed_pod( + "theirs", + &format!("theirs-{i}"), + Some(("DaemonSet", "theirs")), + &now, + )); + cluster.pods.push(failed_pod( + "pyo-waf", + &format!("waf-{i}"), + Some(("DaemonSet", "pyo-waf")), + &now, + )); + } + // Just evicted, not looping: kept for now. + for i in 0..5 { + cluster.pods.push(failed_pod( + "pyo-system", + &format!("vector-{i}"), + Some(("DaemonSet", "pyo-vector")), + &now, + )); + } + let (client, st) = fake::serve(cluster).await; + + let run = once(&client, Duration::ZERO).await.unwrap(); + assert_eq!( + run, + Run { + deleted: 57, + storm: true + } + ); + let c = st.lock().unwrap(); + assert_eq!(c.deleted.len(), 57); + assert!( + c.deleted.iter().all(|(ns, name, uid)| ns == "pyo-gateway" + && name.starts_with("envoy-") + && *uid == format!("uid-{name}")), + "{:?}", + c.deleted + ); + // The newest three of the loop stay, and everything elsewhere. + assert_eq!( + c.pods + .iter() + .filter(|p| p["metadata"]["namespace"] == "pyo-gateway") + .count(), + KEEP + ); + assert_eq!(c.pods.len(), KEEP + 60 + 60 + 5); + // Only Pyo's namespaces are listed, Failed pods only, a page at a time. + let listed: Vec<&str> = c + .lists + .iter() + .map(|l| l.split('?').next().unwrap()) + .collect(); + assert_eq!(listed, ["pyo-gateway", "pyo-system"]); + assert!( + c.lists + .iter() + .all(|l| l.contains("fieldSelector=status.phase%3DFailed") && l.contains("limit=")), + "{:?}", + c.lists + ); + drop(c); + + // Nothing looping any more: the next run is in minutes. + let run = once(&client, Duration::ZERO).await.unwrap(); + assert_eq!( + run, + Run { + deleted: 0, + storm: false + } + ); + } + #[test] fn only_failed_pods_not_jobs_and_not_being_deleted() { let evicted = pod(json!({ From b9e534b5a6e6a1210e8eaba5d2682b04374aba53 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:55:50 +0700 Subject: [PATCH 040/139] fix(install): keep the agent running on a server short of disk The agent was evicted twice while the laptop had DiskPressure, so it stopped reporting the server and cleaning up the failed pods. It now runs with system-cluster-critical and tolerates the disk and memory pressure taints, so it also starts there after an update. A cluster gets this the next time its connect command runs. --- crates/pyo-api/src/install.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/pyo-api/src/install.rs b/crates/pyo-api/src/install.rs index e305947c..9ccc5fbe 100644 --- a/crates/pyo-api/src/install.rs +++ b/crates/pyo-api/src/install.rs @@ -378,9 +378,15 @@ spec: pyo.dev/token: "{token_stamp}" spec: serviceAccountName: pyo-agent + # It keeps running on a server short of disk or memory, and starts + # there after an update: it reports that state, and cleans up what + # the evictions leave. + priorityClassName: system-cluster-critical # It may run on a GPU server kept for GPU work. tolerations: - {{ key: nvidia.com/gpu, operator: Exists, effect: NoSchedule }} + - {{ key: node.kubernetes.io/disk-pressure, operator: Exists, effect: NoSchedule }} + - {{ key: node.kubernetes.io/memory-pressure, operator: Exists, effect: NoSchedule }} containers: - name: agent image: {image} @@ -874,6 +880,33 @@ mod tests { assert!(!a.contains(&sha256_hex("abc")), "not the lookup hash"); } + /// A server short of disk neither evicts the agent nor keeps a new one + /// from starting, so it goes on reporting and cleaning up there. + #[test] + fn the_agent_stays_on_a_server_short_of_disk() { + let pod = render("https://pyo.example.com", "img@sha256:00", "abc") + .split("\n---") + .filter_map(|d| serde_norway::from_str::(d).ok()) + .find(|d| d["kind"] == "Deployment" && d["metadata"]["name"] == "pyo-agent") + .expect("the agent's Deployment")["spec"]["template"]["spec"] + .clone(); + assert_eq!(pod["priorityClassName"], "system-cluster-critical"); + let tolerated: Vec<&str> = pod["tolerations"] + .as_array() + .unwrap() + .iter() + .filter(|t| t["operator"] == "Exists" && t["effect"] == "NoSchedule") + .filter_map(|t| t["key"].as_str()) + .collect(); + for taint in [ + "node.kubernetes.io/disk-pressure", + "node.kubernetes.io/memory-pressure", + "nvidia.com/gpu", + ] { + assert!(tolerated.contains(&taint), "{taint}: {tolerated:?}"); + } + } + #[test] fn the_manifest_is_stamped_with_its_install() { let yaml = render("https://pyo.example.com", "img@sha256:00", "abc"); From f6348e60695bee720c622736f73587e3107612ca Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:55:50 +0700 Subject: [PATCH 041/139] fix(install): let a server stop counting as short of disk sooner k3s evicts under 5% free disk, then keeps the server under DiskPressure until 10% more is free. On a disk filled by something other than pods, kubelet evicted nearly every pod for space they didn't hold and kept DiskPressure on for two hours. The kubelet drop-in now sets the disk settings itself: eviction under 5% free as before, a minimum reclaim of 1 GiB instead of 10%, and image cleanup from 85% used down to 75%. eviction-hard replaces k3s's list, which has only these two signals, so memory and inodes stay as they were. Written at every start like the memory reservations, so a server gets them when its script runs again. --- crates/pyo-api/assets/connect.sh | 41 ++++++++++++------ crates/pyo-api/assets/join.sh | 41 ++++++++++++------ crates/pyo-api/src/join.rs | 74 +++++++++++++++++++++++++++++++- deploy/install.sh | 41 ++++++++++++------ scripts/join-node.sh | 41 ++++++++++++------ scripts/setup-host.sh | 41 ++++++++++++------ 6 files changed, 217 insertions(+), 62 deletions(-) diff --git a/crates/pyo-api/assets/connect.sh b/crates/pyo-api/assets/connect.sh index 47ce8535..112b9416 100644 --- a/crates/pyo-api/assets/connect.sh +++ b/crates/pyo-api/assets/connect.sh @@ -677,7 +677,8 @@ k3s_install() { # sets aside memory for k3s and the system (kube-reserved and # system-reserved, in a k3s config drop-in), so the scheduler only hands # containers what's left: 256 MiB under 1.5 GB, 512 MiB under 3.5 GB, -# 768 MiB under 8 GB, 1 GiB from there. +# 768 MiB under 8 GB, 1 GiB from there. The same drop-in holds when +# kubelet frees disk space (disk_settings in the helper). # K3S_UNIT: k3s's systemd unit, k3s (a server) unless the script sets # k3s-agent first (a server joined to a cluster). K3S_UNIT=${K3S_UNIT:-k3s} @@ -690,7 +691,7 @@ small_machine() { mkdir -p "/etc/systemd/system/$K3S_UNIT.service.d" cat > /usr/local/lib/pyo-memory.sh <<'MEMORY' #!/bin/sh -# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's reservations and compressed +# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's settings and compressed # swap (zram), from this machine's memory at every boot. mem=$(awk '/^MemTotal:/ { print int($2 / 1024) }' "${PYO_MEMINFO:-/proc/meminfo}") # k3s's soft memory limit in MiB: 40% of the memory, at least 768 MiB @@ -715,6 +716,19 @@ reserved() { echo "768 256" fi } +# When kubelet frees disk space, at any size. Under 5% free it deletes +# unused images, then evicts pods, and the server counts as short of disk +# (DiskPressure) until it has 1 GiB more than that. k3s's own 10% more +# kept a server whose disk was filled by something else short of disk +# for hours, evicting nearly every pod for space they didn't hold. +# Unused images go from 85% used down to 75%, well before any of that. +# eviction-hard replaces k3s's whole list, which has these two only: no +# memory or inode limits (the reservations above leave the memory room). +disk_settings() { + printf ' - "%s"\n' 'eviction-hard=imagefs.available<5%,nodefs.available<5%' \ + 'eviction-minimum-reclaim=imagefs.available=1Gi,nodefs.available=1Gi' \ + 'image-gc-high-threshold=85' 'image-gc-low-threshold=75' +} case "$1" in k3s-env) # For k3s's EnvironmentFile: GOMEMLIMIT under 3.5 GB, else nothing. @@ -723,17 +737,20 @@ case "$1" in fi ;; k3s-config) - # k3s's config drop-in ($2): kubelet's reservations; none (no file) - # when the memory can't be read. + # k3s's config drop-in ($2): kubelet's reservations (none when the + # memory can't be read) and its disk settings. [ -n "$2" ] || exit 2 - if [ "${mem:-0}" -gt 0 ]; then - set -- "$2" $(reserved) - mkdir -p "$(dirname "$1")" - printf '%s\n' "# Managed by Pyo: what kubelet sets aside, from this machine's memory at each start." \ - 'kubelet-arg+:' " - \"kube-reserved=memory=$2Mi\"" " - \"system-reserved=memory=$3Mi\"" > "$1.new" && mv -f "$1.new" "$1" - else - rm -f "$2" - fi + out=$2 + mkdir -p "$(dirname "$out")" + { + echo "# Managed by Pyo: kubelet's settings, from this machine's memory at each start." + echo 'kubelet-arg+:' + if [ "${mem:-0}" -gt 0 ]; then + set -- $(reserved) + printf ' - "%s"\n' "kube-reserved=memory=$1Mi" "system-reserved=memory=$2Mi" + fi + disk_settings + } > "$out.new" && mv -f "$out.new" "$out" ;; zram-start) [ "${mem:-0}" -gt 0 ] && [ "$mem" -lt 2816 ] || exit 0 diff --git a/crates/pyo-api/assets/join.sh b/crates/pyo-api/assets/join.sh index a4bbce7a..bf91307e 100644 --- a/crates/pyo-api/assets/join.sh +++ b/crates/pyo-api/assets/join.sh @@ -330,7 +330,8 @@ K3S_UNIT=k3s-agent # sets aside memory for k3s and the system (kube-reserved and # system-reserved, in a k3s config drop-in), so the scheduler only hands # containers what's left: 256 MiB under 1.5 GB, 512 MiB under 3.5 GB, -# 768 MiB under 8 GB, 1 GiB from there. +# 768 MiB under 8 GB, 1 GiB from there. The same drop-in holds when +# kubelet frees disk space (disk_settings in the helper). # K3S_UNIT: k3s's systemd unit, k3s (a server) unless the script sets # k3s-agent first (a server joined to a cluster). K3S_UNIT=${K3S_UNIT:-k3s} @@ -343,7 +344,7 @@ small_machine() { mkdir -p "/etc/systemd/system/$K3S_UNIT.service.d" cat > /usr/local/lib/pyo-memory.sh <<'MEMORY' #!/bin/sh -# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's reservations and compressed +# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's settings and compressed # swap (zram), from this machine's memory at every boot. mem=$(awk '/^MemTotal:/ { print int($2 / 1024) }' "${PYO_MEMINFO:-/proc/meminfo}") # k3s's soft memory limit in MiB: 40% of the memory, at least 768 MiB @@ -368,6 +369,19 @@ reserved() { echo "768 256" fi } +# When kubelet frees disk space, at any size. Under 5% free it deletes +# unused images, then evicts pods, and the server counts as short of disk +# (DiskPressure) until it has 1 GiB more than that. k3s's own 10% more +# kept a server whose disk was filled by something else short of disk +# for hours, evicting nearly every pod for space they didn't hold. +# Unused images go from 85% used down to 75%, well before any of that. +# eviction-hard replaces k3s's whole list, which has these two only: no +# memory or inode limits (the reservations above leave the memory room). +disk_settings() { + printf ' - "%s"\n' 'eviction-hard=imagefs.available<5%,nodefs.available<5%' \ + 'eviction-minimum-reclaim=imagefs.available=1Gi,nodefs.available=1Gi' \ + 'image-gc-high-threshold=85' 'image-gc-low-threshold=75' +} case "$1" in k3s-env) # For k3s's EnvironmentFile: GOMEMLIMIT under 3.5 GB, else nothing. @@ -376,17 +390,20 @@ case "$1" in fi ;; k3s-config) - # k3s's config drop-in ($2): kubelet's reservations; none (no file) - # when the memory can't be read. + # k3s's config drop-in ($2): kubelet's reservations (none when the + # memory can't be read) and its disk settings. [ -n "$2" ] || exit 2 - if [ "${mem:-0}" -gt 0 ]; then - set -- "$2" $(reserved) - mkdir -p "$(dirname "$1")" - printf '%s\n' "# Managed by Pyo: what kubelet sets aside, from this machine's memory at each start." \ - 'kubelet-arg+:' " - \"kube-reserved=memory=$2Mi\"" " - \"system-reserved=memory=$3Mi\"" > "$1.new" && mv -f "$1.new" "$1" - else - rm -f "$2" - fi + out=$2 + mkdir -p "$(dirname "$out")" + { + echo "# Managed by Pyo: kubelet's settings, from this machine's memory at each start." + echo 'kubelet-arg+:' + if [ "${mem:-0}" -gt 0 ]; then + set -- $(reserved) + printf ' - "%s"\n' "kube-reserved=memory=$1Mi" "system-reserved=memory=$2Mi" + fi + disk_settings + } > "$out.new" && mv -f "$out.new" "$out" ;; zram-start) [ "${mem:-0}" -gt 0 ] && [ "$mem" -lt 2816 ] || exit 0 diff --git a/crates/pyo-api/src/join.rs b/crates/pyo-api/src/join.rs index 7de781b0..70aae119 100644 --- a/crates/pyo-api/src/join.rs +++ b/crates/pyo-api/src/join.rs @@ -600,8 +600,10 @@ mod tests { "{mem}: {text}" ); } - // Memory it can't read: no drop-in (the one before is removed). - assert_eq!(config("nothing\n"), None); + // Memory it can't read: no reservations, the disk settings still. + let text = config("nothing\n").expect("a drop-in"); + assert!(!text.contains("reserved="), "{text}"); + assert!(text.contains("\nkubelet-arg+:\n - \"eviction-hard="), "{text}"); // The unit runs it at every start, at the path small_machine writes. let block = script_block("small-machine", CONNECT_SCRIPT); assert!( @@ -613,6 +615,74 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// The same drop-in: kubelet frees disk space only under 5% free (unused + /// images well before), and the server stops counting as short of disk + /// once 1 GiB more is free, not k3s's 10% more. Whatever the memory. + #[test] + fn kubelet_frees_disk_space_late_and_lets_go_soon() { + let helper = CONNECT_SCRIPT + .split("<<'MEMORY'\n") + .nth(1) + .and_then(|r| r.split("\nMEMORY\n").next()) + .expect("connect.sh has the memory helper"); + let dir = std::env::temp_dir().join(format!("pyo-disk-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let want = " - \"eviction-hard=imagefs.available<5%,nodefs.available<5%\"\n\ + \x20 - \"eviction-minimum-reclaim=imagefs.available=1Gi,nodefs.available=1Gi\"\n\ + \x20 - \"image-gc-high-threshold=85\"\n\ + \x20 - \"image-gc-low-threshold=75\"\n"; + for meminfo in ["MemTotal: 983040 kB\n", "MemTotal: 33554432 kB\n", "nothing\n"] { + let info = dir.join("meminfo"); + std::fs::write(&info, meminfo).unwrap(); + let out = dir.join("50-pyo-memory.yaml"); + let status = std::process::Command::new("sh") + .args(["-c", helper, "pyo-memory.sh", "k3s-config"]) + .arg(&out) + .env("PYO_MEMINFO", &info) + .status() + .unwrap(); + assert!(status.success()); + let text = std::fs::read_to_string(&out).unwrap(); + assert!(text.ends_with(want), "{meminfo}: {text}"); + // One list, which k3s adds to its own arguments. + assert_eq!(text.matches("kubelet-arg").count(), 1, "{text}"); + } + let _ = std::fs::remove_dir_all(&dir); + // Image cleanup starts and ends before eviction does (95% used). + let pct = |key: &str| -> u32 { + want.split(&format!("{key}=")) + .nth(1) + .and_then(|r| r.split('"').next()) + .unwrap() + .parse() + .unwrap() + }; + assert!(pct("image-gc-low-threshold") < pct("image-gc-high-threshold")); + assert!(pct("image-gc-high-threshold") < 95); + } + + /// A server set up before the disk settings gets them, and k3s restarts + /// once for them, when its script runs again. + #[test] + fn existing_k3s_restarts_once_for_the_disk_settings() { + let dir = std::env::temp_dir().join(format!("pyo-disk-refresh-{}", std::process::id())); + let block = sandboxed_small_machine(&dir); + let d = dir.display(); + let (code, out, err) = bash(&format!( + "set -euo pipefail\nsystemctl() {{ [ \"$1\" != restart ] || echo RESTART; }}\n{block}\n\ + export PYO_MEMINFO={d}/meminfo; echo 'MemTotal: 16777216 kB' > $PYO_MEMINFO\n\ + mkdir -p {d}/config.yaml.d\n\ + printf '%s\\n' '# Managed by Pyo: what kubelet sets aside.' 'kubelet-arg+:' ' - \"kube-reserved=memory=768Mi\"' ' - \"system-reserved=memory=256Mi\"' > {d}/config.yaml.d/50-pyo-memory.yaml\n\ + : > {d}/run/pyo-k3s.env\n\ + k3s_memory_refresh\nk3s_memory_refresh" + )); + assert_eq!(code, 0, "{err}"); + assert_eq!(out.matches("RESTART").count(), 1, "{out}"); + let text = std::fs::read_to_string(dir.join("config.yaml.d/50-pyo-memory.yaml")).unwrap(); + assert!(text.contains("eviction-minimum-reclaim="), "{text}"); + let _ = std::fs::remove_dir_all(&dir); + } + /// The scripts that install k3s, Tailscale and NVIDIA's toolkit share /// their installer code (`# >>> pyo:` … `# <<< pyo:`), and /// those that carry k3s's pin carry deploy/k3s.env's. diff --git a/deploy/install.sh b/deploy/install.sh index 6866cbd9..d5123437 100644 --- a/deploy/install.sh +++ b/deploy/install.sh @@ -524,7 +524,8 @@ k3s_install() { # sets aside memory for k3s and the system (kube-reserved and # system-reserved, in a k3s config drop-in), so the scheduler only hands # containers what's left: 256 MiB under 1.5 GB, 512 MiB under 3.5 GB, -# 768 MiB under 8 GB, 1 GiB from there. +# 768 MiB under 8 GB, 1 GiB from there. The same drop-in holds when +# kubelet frees disk space (disk_settings in the helper). # K3S_UNIT: k3s's systemd unit, k3s (a server) unless the script sets # k3s-agent first (a server joined to a cluster). K3S_UNIT=${K3S_UNIT:-k3s} @@ -537,7 +538,7 @@ small_machine() { mkdir -p "/etc/systemd/system/$K3S_UNIT.service.d" cat > /usr/local/lib/pyo-memory.sh <<'MEMORY' #!/bin/sh -# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's reservations and compressed +# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's settings and compressed # swap (zram), from this machine's memory at every boot. mem=$(awk '/^MemTotal:/ { print int($2 / 1024) }' "${PYO_MEMINFO:-/proc/meminfo}") # k3s's soft memory limit in MiB: 40% of the memory, at least 768 MiB @@ -562,6 +563,19 @@ reserved() { echo "768 256" fi } +# When kubelet frees disk space, at any size. Under 5% free it deletes +# unused images, then evicts pods, and the server counts as short of disk +# (DiskPressure) until it has 1 GiB more than that. k3s's own 10% more +# kept a server whose disk was filled by something else short of disk +# for hours, evicting nearly every pod for space they didn't hold. +# Unused images go from 85% used down to 75%, well before any of that. +# eviction-hard replaces k3s's whole list, which has these two only: no +# memory or inode limits (the reservations above leave the memory room). +disk_settings() { + printf ' - "%s"\n' 'eviction-hard=imagefs.available<5%,nodefs.available<5%' \ + 'eviction-minimum-reclaim=imagefs.available=1Gi,nodefs.available=1Gi' \ + 'image-gc-high-threshold=85' 'image-gc-low-threshold=75' +} case "$1" in k3s-env) # For k3s's EnvironmentFile: GOMEMLIMIT under 3.5 GB, else nothing. @@ -570,17 +584,20 @@ case "$1" in fi ;; k3s-config) - # k3s's config drop-in ($2): kubelet's reservations; none (no file) - # when the memory can't be read. + # k3s's config drop-in ($2): kubelet's reservations (none when the + # memory can't be read) and its disk settings. [ -n "$2" ] || exit 2 - if [ "${mem:-0}" -gt 0 ]; then - set -- "$2" $(reserved) - mkdir -p "$(dirname "$1")" - printf '%s\n' "# Managed by Pyo: what kubelet sets aside, from this machine's memory at each start." \ - 'kubelet-arg+:' " - \"kube-reserved=memory=$2Mi\"" " - \"system-reserved=memory=$3Mi\"" > "$1.new" && mv -f "$1.new" "$1" - else - rm -f "$2" - fi + out=$2 + mkdir -p "$(dirname "$out")" + { + echo "# Managed by Pyo: kubelet's settings, from this machine's memory at each start." + echo 'kubelet-arg+:' + if [ "${mem:-0}" -gt 0 ]; then + set -- $(reserved) + printf ' - "%s"\n' "kube-reserved=memory=$1Mi" "system-reserved=memory=$2Mi" + fi + disk_settings + } > "$out.new" && mv -f "$out.new" "$out" ;; zram-start) [ "${mem:-0}" -gt 0 ] && [ "$mem" -lt 2816 ] || exit 0 diff --git a/scripts/join-node.sh b/scripts/join-node.sh index 8d970530..dc34c1df 100644 --- a/scripts/join-node.sh +++ b/scripts/join-node.sh @@ -104,7 +104,8 @@ K3S_UNIT=k3s-agent # sets aside memory for k3s and the system (kube-reserved and # system-reserved, in a k3s config drop-in), so the scheduler only hands # containers what's left: 256 MiB under 1.5 GB, 512 MiB under 3.5 GB, -# 768 MiB under 8 GB, 1 GiB from there. +# 768 MiB under 8 GB, 1 GiB from there. The same drop-in holds when +# kubelet frees disk space (disk_settings in the helper). # K3S_UNIT: k3s's systemd unit, k3s (a server) unless the script sets # k3s-agent first (a server joined to a cluster). K3S_UNIT=${K3S_UNIT:-k3s} @@ -117,7 +118,7 @@ small_machine() { mkdir -p "/etc/systemd/system/$K3S_UNIT.service.d" cat > /usr/local/lib/pyo-memory.sh <<'MEMORY' #!/bin/sh -# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's reservations and compressed +# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's settings and compressed # swap (zram), from this machine's memory at every boot. mem=$(awk '/^MemTotal:/ { print int($2 / 1024) }' "${PYO_MEMINFO:-/proc/meminfo}") # k3s's soft memory limit in MiB: 40% of the memory, at least 768 MiB @@ -142,6 +143,19 @@ reserved() { echo "768 256" fi } +# When kubelet frees disk space, at any size. Under 5% free it deletes +# unused images, then evicts pods, and the server counts as short of disk +# (DiskPressure) until it has 1 GiB more than that. k3s's own 10% more +# kept a server whose disk was filled by something else short of disk +# for hours, evicting nearly every pod for space they didn't hold. +# Unused images go from 85% used down to 75%, well before any of that. +# eviction-hard replaces k3s's whole list, which has these two only: no +# memory or inode limits (the reservations above leave the memory room). +disk_settings() { + printf ' - "%s"\n' 'eviction-hard=imagefs.available<5%,nodefs.available<5%' \ + 'eviction-minimum-reclaim=imagefs.available=1Gi,nodefs.available=1Gi' \ + 'image-gc-high-threshold=85' 'image-gc-low-threshold=75' +} case "$1" in k3s-env) # For k3s's EnvironmentFile: GOMEMLIMIT under 3.5 GB, else nothing. @@ -150,17 +164,20 @@ case "$1" in fi ;; k3s-config) - # k3s's config drop-in ($2): kubelet's reservations; none (no file) - # when the memory can't be read. + # k3s's config drop-in ($2): kubelet's reservations (none when the + # memory can't be read) and its disk settings. [ -n "$2" ] || exit 2 - if [ "${mem:-0}" -gt 0 ]; then - set -- "$2" $(reserved) - mkdir -p "$(dirname "$1")" - printf '%s\n' "# Managed by Pyo: what kubelet sets aside, from this machine's memory at each start." \ - 'kubelet-arg+:' " - \"kube-reserved=memory=$2Mi\"" " - \"system-reserved=memory=$3Mi\"" > "$1.new" && mv -f "$1.new" "$1" - else - rm -f "$2" - fi + out=$2 + mkdir -p "$(dirname "$out")" + { + echo "# Managed by Pyo: kubelet's settings, from this machine's memory at each start." + echo 'kubelet-arg+:' + if [ "${mem:-0}" -gt 0 ]; then + set -- $(reserved) + printf ' - "%s"\n' "kube-reserved=memory=$1Mi" "system-reserved=memory=$2Mi" + fi + disk_settings + } > "$out.new" && mv -f "$out.new" "$out" ;; zram-start) [ "${mem:-0}" -gt 0 ] && [ "$mem" -lt 2816 ] || exit 0 diff --git a/scripts/setup-host.sh b/scripts/setup-host.sh index a19d2f4e..160fe9d2 100755 --- a/scripts/setup-host.sh +++ b/scripts/setup-host.sh @@ -117,7 +117,8 @@ k3s_install() { # sets aside memory for k3s and the system (kube-reserved and # system-reserved, in a k3s config drop-in), so the scheduler only hands # containers what's left: 256 MiB under 1.5 GB, 512 MiB under 3.5 GB, -# 768 MiB under 8 GB, 1 GiB from there. +# 768 MiB under 8 GB, 1 GiB from there. The same drop-in holds when +# kubelet frees disk space (disk_settings in the helper). # K3S_UNIT: k3s's systemd unit, k3s (a server) unless the script sets # k3s-agent first (a server joined to a cluster). K3S_UNIT=${K3S_UNIT:-k3s} @@ -130,7 +131,7 @@ small_machine() { mkdir -p "/etc/systemd/system/$K3S_UNIT.service.d" cat > /usr/local/lib/pyo-memory.sh <<'MEMORY' #!/bin/sh -# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's reservations and compressed +# Managed by Pyo: k3s's GOMEMLIMIT, kubelet's settings and compressed # swap (zram), from this machine's memory at every boot. mem=$(awk '/^MemTotal:/ { print int($2 / 1024) }' "${PYO_MEMINFO:-/proc/meminfo}") # k3s's soft memory limit in MiB: 40% of the memory, at least 768 MiB @@ -155,6 +156,19 @@ reserved() { echo "768 256" fi } +# When kubelet frees disk space, at any size. Under 5% free it deletes +# unused images, then evicts pods, and the server counts as short of disk +# (DiskPressure) until it has 1 GiB more than that. k3s's own 10% more +# kept a server whose disk was filled by something else short of disk +# for hours, evicting nearly every pod for space they didn't hold. +# Unused images go from 85% used down to 75%, well before any of that. +# eviction-hard replaces k3s's whole list, which has these two only: no +# memory or inode limits (the reservations above leave the memory room). +disk_settings() { + printf ' - "%s"\n' 'eviction-hard=imagefs.available<5%,nodefs.available<5%' \ + 'eviction-minimum-reclaim=imagefs.available=1Gi,nodefs.available=1Gi' \ + 'image-gc-high-threshold=85' 'image-gc-low-threshold=75' +} case "$1" in k3s-env) # For k3s's EnvironmentFile: GOMEMLIMIT under 3.5 GB, else nothing. @@ -163,17 +177,20 @@ case "$1" in fi ;; k3s-config) - # k3s's config drop-in ($2): kubelet's reservations; none (no file) - # when the memory can't be read. + # k3s's config drop-in ($2): kubelet's reservations (none when the + # memory can't be read) and its disk settings. [ -n "$2" ] || exit 2 - if [ "${mem:-0}" -gt 0 ]; then - set -- "$2" $(reserved) - mkdir -p "$(dirname "$1")" - printf '%s\n' "# Managed by Pyo: what kubelet sets aside, from this machine's memory at each start." \ - 'kubelet-arg+:' " - \"kube-reserved=memory=$2Mi\"" " - \"system-reserved=memory=$3Mi\"" > "$1.new" && mv -f "$1.new" "$1" - else - rm -f "$2" - fi + out=$2 + mkdir -p "$(dirname "$out")" + { + echo "# Managed by Pyo: kubelet's settings, from this machine's memory at each start." + echo 'kubelet-arg+:' + if [ "${mem:-0}" -gt 0 ]; then + set -- $(reserved) + printf ' - "%s"\n' "kube-reserved=memory=$1Mi" "system-reserved=memory=$2Mi" + fi + disk_settings + } > "$out.new" && mv -f "$out.new" "$out" ;; zram-start) [ "${mem:-0}" -gt 0 ] && [ "$mem" -lt 2816 ] || exit 0 From f3d0203887c8933fc8e6a8d7ddb62910f3e8d2af Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:59:05 +0700 Subject: [PATCH 042/139] test(agent): release the fake cluster's lock before the next run --- crates/pyo-agent/src/cleanup.rs | 66 +++++++++++++++++---------------- 1 file changed, 34 insertions(+), 32 deletions(-) diff --git a/crates/pyo-agent/src/cleanup.rs b/crates/pyo-agent/src/cleanup.rs index 082d62f8..a5bb42d3 100644 --- a/crates/pyo-agent/src/cleanup.rs +++ b/crates/pyo-agent/src/cleanup.rs @@ -540,39 +540,41 @@ mod tests { storm: true } ); - let c = st.lock().unwrap(); - assert_eq!(c.deleted.len(), 57); - assert!( - c.deleted.iter().all(|(ns, name, uid)| ns == "pyo-gateway" - && name.starts_with("envoy-") - && *uid == format!("uid-{name}")), - "{:?}", - c.deleted - ); - // The newest three of the loop stay, and everything elsewhere. - assert_eq!( - c.pods - .iter() - .filter(|p| p["metadata"]["namespace"] == "pyo-gateway") - .count(), - KEEP - ); - assert_eq!(c.pods.len(), KEEP + 60 + 60 + 5); - // Only Pyo's namespaces are listed, Failed pods only, a page at a time. - let listed: Vec<&str> = c - .lists - .iter() - .map(|l| l.split('?').next().unwrap()) - .collect(); - assert_eq!(listed, ["pyo-gateway", "pyo-system"]); - assert!( - c.lists + { + let c = st.lock().unwrap(); + assert_eq!(c.deleted.len(), 57); + assert!( + c.deleted.iter().all(|(ns, name, uid)| ns == "pyo-gateway" + && name.starts_with("envoy-") + && *uid == format!("uid-{name}")), + "{:?}", + c.deleted + ); + // The newest three of the loop stay, and everything elsewhere. + assert_eq!( + c.pods + .iter() + .filter(|p| p["metadata"]["namespace"] == "pyo-gateway") + .count(), + KEEP + ); + assert_eq!(c.pods.len(), KEEP + 60 + 60 + 5); + // Only Pyo's namespaces are listed, Failed pods only, a page at a time. + let listed: Vec<&str> = c + .lists .iter() - .all(|l| l.contains("fieldSelector=status.phase%3DFailed") && l.contains("limit=")), - "{:?}", - c.lists - ); - drop(c); + .map(|l| l.split('?').next().unwrap()) + .collect(); + assert_eq!(listed, ["pyo-gateway", "pyo-system"]); + assert!( + c.lists + .iter() + .all(|l| l.contains("fieldSelector=status.phase%3DFailed") + && l.contains("limit=")), + "{:?}", + c.lists + ); + } // Nothing looping any more: the next run is in minutes. let run = once(&client, Duration::ZERO).await.unwrap(); From 02f282621a4d9b5f8853676ee1d1a91c842255c1 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 16:59:05 +0700 Subject: [PATCH 043/139] style: format the new disk pressure tests --- crates/pyo-api/src/join.rs | 11 +++++++++-- crates/pyo-proto/src/system.rs | 3 +-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/pyo-api/src/join.rs b/crates/pyo-api/src/join.rs index 70aae119..e9bc0161 100644 --- a/crates/pyo-api/src/join.rs +++ b/crates/pyo-api/src/join.rs @@ -603,7 +603,10 @@ mod tests { // Memory it can't read: no reservations, the disk settings still. let text = config("nothing\n").expect("a drop-in"); assert!(!text.contains("reserved="), "{text}"); - assert!(text.contains("\nkubelet-arg+:\n - \"eviction-hard="), "{text}"); + assert!( + text.contains("\nkubelet-arg+:\n - \"eviction-hard="), + "{text}" + ); // The unit runs it at every start, at the path small_machine writes. let block = script_block("small-machine", CONNECT_SCRIPT); assert!( @@ -631,7 +634,11 @@ mod tests { \x20 - \"eviction-minimum-reclaim=imagefs.available=1Gi,nodefs.available=1Gi\"\n\ \x20 - \"image-gc-high-threshold=85\"\n\ \x20 - \"image-gc-low-threshold=75\"\n"; - for meminfo in ["MemTotal: 983040 kB\n", "MemTotal: 33554432 kB\n", "nothing\n"] { + for meminfo in [ + "MemTotal: 983040 kB\n", + "MemTotal: 33554432 kB\n", + "nothing\n", + ] { let info = dir.join("meminfo"); std::fs::write(&info, meminfo).unwrap(); let out = dir.join("50-pyo-memory.yaml"); diff --git a/crates/pyo-proto/src/system.rs b/crates/pyo-proto/src/system.rs index 48618f56..a56b7c5c 100644 --- a/crates/pyo-proto/src/system.rs +++ b/crates/pyo-proto/src/system.rs @@ -1664,8 +1664,7 @@ mod tests { for ds in [waf_daemonset("w", "g"), tailnet_daemonset("a")] { assert_eq!(ds["kind"], "DaemonSet"); assert_eq!( - ds["spec"]["template"]["spec"]["priorityClassName"], - SERVER_CRITICAL, + ds["spec"]["template"]["spec"]["priorityClassName"], SERVER_CRITICAL, "{}", ds["metadata"]["name"] ); From 7e3ad3875eef11f0892e676710106ab9ca9bff55 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 18:29:15 +0700 Subject: [PATCH 044/139] fix(dash): reword the agent updates setting --- dash/src/routes/_app/$team/settings/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dash/src/routes/_app/$team/settings/index.tsx b/dash/src/routes/_app/$team/settings/index.tsx index 538b22be..8a5272bb 100644 --- a/dash/src/routes/_app/$team/settings/index.tsx +++ b/dash/src/routes/_app/$team/settings/index.tsx @@ -163,7 +163,7 @@ function TeamSettings({ ws }: { ws: Team }) { }); }} label="Update agents automatically" - description="Off: update each cluster from its settings." + description="When off, you update each cluster from its settings." /> From c758ae23480ec1c4aad5b6e7d476d9dbd86068fa Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 18:39:56 +0700 Subject: [PATCH 045/139] test(agent): check the gpu device plugin stays critical It already ran with system-node-critical. It now takes the shared constant, and a test holds it there. --- crates/pyo-agent/src/gpu.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/pyo-agent/src/gpu.rs b/crates/pyo-agent/src/gpu.rs index 4ae2040f..deb48066 100644 --- a/crates/pyo-agent/src/gpu.rs +++ b/crates/pyo-agent/src/gpu.rs @@ -215,7 +215,7 @@ pub fn device_plugin() -> Value { "runtimeClassName": GPU_RUNTIME_CLASS, "nodeSelector": { GPU_LABEL: "nvidia" }, "tolerations": [{ "key": GPU_RESOURCE, "operator": "Exists", "effect": "NoSchedule" }], - "priorityClassName": "system-node-critical", + "priorityClassName": pyo_proto::system::SERVER_CRITICAL, "containers": [{ "name": "nvidia-device-plugin-ctr", "image": DEVICE_PLUGIN_IMAGE, @@ -411,6 +411,12 @@ mod tests { let ds: DaemonSet = serde_json::from_value(device_plugin()).unwrap(); let spec = ds.spec.unwrap().template.spec.unwrap(); assert_eq!(spec.runtime_class_name.as_deref(), Some("nvidia")); + // Kept on a server short of disk, like Pyo's other per-server pods: + // its DaemonSet never replaces it over and over there. + assert_eq!( + spec.priority_class_name.as_deref(), + Some(pyo_proto::system::SERVER_CRITICAL) + ); assert_eq!( spec.node_selector .unwrap() From 9ea7926b0cc12d04c5e7e0f505fa385fc93382ce Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 18:39:56 +0700 Subject: [PATCH 046/139] fix(proto): update the waf when its daemonset changes The WAF bundle's version followed only its images, so a release that made its DaemonSet critical would not reach clusters that already ran it. The version now follows its objects too, and the API resends the bundle once a cluster's install is current again. --- crates/pyo-proto/src/bundles.rs | 55 ++++++++++++++++++++++++--------- 1 file changed, 40 insertions(+), 15 deletions(-) diff --git a/crates/pyo-proto/src/bundles.rs b/crates/pyo-proto/src/bundles.rs index a2268dd8..a2f8574b 100644 --- a/crates/pyo-proto/src/bundles.rs +++ b/crates/pyo-proto/src/bundles.rs @@ -687,20 +687,32 @@ pub fn never_pruned(r: &ObjectRef) -> bool { /// The web application firewall, with the installation's images (so it's /// built here, not loaded). Installed with the first service on the cluster /// that turns its WAF on, removed after the last one turns it off; its -/// version follows its images. +/// version follows its images and its objects, so a release that changes +/// its DaemonSet (its priority, say) updates it on every cluster. pub fn waf_bundle(waf_image: &str, geoip_image: &str) -> SystemBundle { use crate::system; - // FNV-1a: the same images, the same version. - let hash = format!("{waf_image}\n{geoip_image}") - .bytes() - .fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { - (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) - }); // Its settings are the agent's (waf.rs writes `config.json`), not the bundle's. let config = json!({ "apiVersion": "v1", "kind": "ConfigMap", "metadata": { "name": system::WAF_NAME, "namespace": system::WAF_NS, "labels": system::waf_labels() }, }); + let objects: Vec = [config] + .into_iter() + .chain(system::waf_access()) + .chain([ + system::waf_daemonset(waf_image, geoip_image), + system::waf_service(), + ]) + .collect(); + // FNV-1a: the same images and objects, the same version. + let hash = format!( + "{waf_image}\n{geoip_image}\n{}", + Value::Array(objects.clone()) + ) + .bytes() + .fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) + }); SystemBundle { id: WAF_ID.into(), version: format!("{:08x}", hash >> 32), @@ -715,14 +727,7 @@ pub fn waf_bundle(waf_image: &str, geoip_image: &str) -> SystemBundle { }], in_use: vec![], managed_namespace_bindings: vec![], - objects: [config] - .into_iter() - .chain(system::waf_access()) - .chain([ - system::waf_daemonset(waf_image, geoip_image), - system::waf_service(), - ]) - .collect(), + objects, } } @@ -1078,6 +1083,26 @@ mod tests { ) } + /// The WAF's version follows what it writes, not only its images: a + /// release that makes its DaemonSet critical updates it on every + /// cluster, as the API resends a bundle whose version changed. + #[test] + fn the_wafs_version_follows_its_objects() { + let b = waf_bundle("w:1", "g:1"); + assert_eq!(b.version, waf_bundle("w:1", "g:1").version); + assert_ne!(b.version, waf_bundle("w:2", "g:1").version); + assert_eq!(b.version.len(), 8); + let images_only = "w:1\ng:1".bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) + }); + assert_ne!(b.version, format!("{:08x}", images_only >> 32)); + let ds = b.objects.iter().find(|o| o["kind"] == "DaemonSet").unwrap(); + assert_eq!( + ds["spec"]["template"]["spec"]["priorityClassName"], + crate::system::SERVER_CRITICAL + ); + } + #[test] fn plurals() { assert_eq!(plural("Deployment"), "deployments"); From 12b6ca9c50ae001885034a499cd2316b82898c14 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 18:39:56 +0700 Subject: [PATCH 047/139] feat(agent): bring its own priority and tolerations with a refresh A refresh now patches the agent's Deployment with its pods' priority (system-cluster-critical) and tolerations, from rbac::AGENT_PRIORITY and rbac::agent_tolerations, which the connect manifest renders too. Existing clusters get them with the agent update, with no connect command. The admission policy now holds the agent to this on its own Deployment: only updates, and then only its image, image pins, install stamp, and a priority and tolerations that stay as they were or become exactly this release's. Its token, Pyo's address, other env, volumes and service account stay as the connect command set them. The agent's roles are unchanged, pinned by a test to 0.5.5's. --- crates/pyo-agent/src/install.rs | 227 +++++++++++++++++++++++++-- crates/pyo-api/src/install.rs | 16 +- crates/pyo-proto/src/rbac.rs | 261 +++++++++++++++++++++++++++++++- 3 files changed, 485 insertions(+), 19 deletions(-) diff --git a/crates/pyo-agent/src/install.rs b/crates/pyo-agent/src/install.rs index 1530297d..b7e1e6cd 100644 --- a/crates/pyo-agent/src/install.rs +++ b/crates/pyo-agent/src/install.rs @@ -8,8 +8,10 @@ //! 2. The admission policy is replaced as a whole (its binding only if that //! differs), then a dry run of the Deployment change below goes through //! it. If the new policy refuses that, the old one is put back. -//! 3. Last, after reporting: the Deployment's image pins and its stamp. -//! When the pins change, the agent restarts on them. +//! 3. Last, after reporting: the Deployment's image pins, its stamp, and +//! its pods' priority and tolerations (pyo-proto's `rbac::AGENT_PRIORITY` +//! and `rbac::agent_tolerations`, the connect command's too). When more +//! than the stamp changes, the agent restarts on it. //! //! On a small server under load, the API server can take longer to check //! the policy than it gives a write by default (34 s): each write here asks @@ -19,7 +21,8 @@ //! //! Every step finds what's already done, so a refresh that stops halfway //! is simply sent again. The agent's token, Pyo's address, its image and -//! everything else of its Deployment are never touched here. +//! everything else of its Deployment are never touched here, and the +//! admission policy refuses the agent any other change to it. use std::time::{Duration, Instant}; @@ -33,7 +36,7 @@ use serde_json::{Value, json}; use crate::scope::{api_for, same}; -const DEPLOYMENT: &str = "pyo-agent"; +const DEPLOYMENT: &str = rbac::AGENT_DEPLOYMENT; /// What a refresh can't do by itself. const RERUN: &str = "run the cluster's connect command to bring them up to date"; /// What each write of the admission policy (and the dry run through it) @@ -202,7 +205,9 @@ pub fn check(p: &InstallParts) -> Result<(), String> { Ok(()) } -/// The Deployment change: its pins (env by name, the rest kept) and stamp. +/// The Deployment change: its pins (env by name, the rest kept), stamp, +/// priority and tolerations (the whole list, as a strategic merge replaces +/// a list without a merge key). fn deployment_patch(p: &InstallParts) -> Value { let env: Vec = p .pins @@ -211,7 +216,11 @@ fn deployment_patch(p: &InstallParts) -> Value { .collect(); json!({ "metadata": { "annotations": { rbac::INSTALL_ANNOTATION: p.hash } }, - "spec": { "template": { "spec": { "containers": [{ "name": "agent", "env": env }] } } }, + "spec": { "template": { "spec": { + "priorityClassName": rbac::AGENT_PRIORITY, + "tolerations": rbac::agent_tolerations(), + "containers": [{ "name": "agent", "env": env }], + } } }, }) } @@ -402,8 +411,8 @@ pub async fn refresh( Ok(()) } -/// Step 3: the Deployment's pins and stamp. When the pins change, this -/// agent restarts. +/// Step 3: the Deployment's pins, stamp, priority and tolerations. When +/// more than the stamp changes, this agent restarts. pub async fn finish(client: &Client, p: &InstallParts) -> anyhow::Result<()> { Api::::namespaced(client.clone(), rbac::NS) .patch( @@ -658,6 +667,99 @@ mod tests { "no image, command or anything else" ); assert_eq!(c["env"].as_array().unwrap().len(), rbac::PINNED_ENV.len()); + let spec = &patch["spec"]["template"]["spec"]; + let mut keys: Vec<&String> = spec.as_object().unwrap().keys().collect(); + keys.sort(); + assert_eq!(keys, ["containers", "priorityClassName", "tolerations"]); + assert_eq!(spec["priorityClassName"], rbac::AGENT_PRIORITY); + assert_eq!(spec["tolerations"], rbac::agent_tolerations()); + } + + /// A strategic merge patch as the API server makes it for these fields: + /// maps merged, `containers` and `env` merged by name, other lists + /// (tolerations) replaced. + fn strategic_merge(target: &mut Value, patch: &Value) { + let (Some(t), Some(p)) = (target.as_object_mut(), patch.as_object()) else { + *target = patch.clone(); + return; + }; + for (k, v) in p { + match (t.get_mut(k), v) { + (Some(Value::Array(have)), Value::Array(new)) + if k == "containers" || k == "env" => + { + for item in new { + match have.iter_mut().find(|h| h["name"] == item["name"]) { + Some(h) => strategic_merge(h, item), + None => have.push(item.clone()), + } + } + } + (Some(have @ Value::Object(_)), Value::Object(_)) => strategic_merge(have, v), + _ => { + t.insert(k.clone(), v.clone()); + } + } + } + } + + /// An agent Deployment as an older connect command made it: no + /// priority, the GPU toleration only, older pins. + fn older_deployment() -> Value { + json!({ + "apiVersion": "apps/v1", "kind": "Deployment", + "metadata": { "name": DEPLOYMENT, "namespace": rbac::NS, "annotations": { rbac::INSTALL_ANNOTATION: "0123456789abcdef" } }, + "spec": { "replicas": 1, "template": { "metadata": { "annotations": { "pyo.dev/token": "t" } }, "spec": { + "serviceAccountName": "pyo-agent", + "tolerations": [{ "key": "nvidia.com/gpu", "operator": "Exists", "effect": "NoSchedule" }], + "containers": [{ "name": "agent", "image": "agent@sha256:00", "envFrom": [{ "secretRef": { "name": "pyo-agent" } }], + "env": [{ "name": "RUST_LOG", "value": "pyo_agent=info" }, { "name": "PYO_WAF_IMAGE", "value": "waf:old" }] }], + } } }, + }) + } + + /// A refresh brings an older Deployment the priority and tolerations + /// (whole, the GPU one kept), and its pins and stamp; the token, Pyo's + /// address and other env stay. Applied again, nothing changes. + #[test] + fn a_refresh_brings_the_priority_and_tolerations() { + let p = parts(); + let patch = deployment_patch(&p); + let mut d = older_deployment(); + strategic_merge(&mut d, &patch); + let spec = &d["spec"]["template"]["spec"]; + assert_eq!(spec["priorityClassName"], rbac::AGENT_PRIORITY); + assert_eq!(spec["tolerations"], rbac::agent_tolerations()); + assert_eq!(spec["serviceAccountName"], "pyo-agent"); + assert_eq!( + d["metadata"]["annotations"][rbac::INSTALL_ANNOTATION], + json!(p.hash) + ); + assert_eq!( + d["spec"]["template"]["metadata"]["annotations"]["pyo.dev/token"], + "t" + ); + let c = &spec["containers"][0]; + assert_eq!(c["image"], "agent@sha256:00"); + assert_eq!( + c["envFrom"], + json!([{ "secretRef": { "name": "pyo-agent" } }]) + ); + let env: std::collections::BTreeMap<&str, &str> = c["env"] + .as_array() + .unwrap() + .iter() + .map(|e| (e["name"].as_str().unwrap(), e["value"].as_str().unwrap())) + .collect(); + assert_eq!(env["RUST_LOG"], "pyo_agent=info"); + for (k, v) in &p.pins { + assert_eq!(env[k.as_str()], v, "{k}"); + } + assert_eq!(env.len(), p.pins.len() + 1); + // Sent again (a refresh that stopped halfway): the same Deployment. + let once = d.clone(); + strategic_merge(&mut d, &patch); + assert_eq!(d, once); } /// Against a throwaway cluster (1.30+), as the agent's own @@ -1114,8 +1216,115 @@ mod tests { .map(|e| (e.name, e.value.unwrap_or_default())) .collect(); assert_eq!(env, new.pins); - // Sent again: nothing to do. + // The stand-in had neither: the refresh brought both. + let d = deployments.get(DEPLOYMENT).await.unwrap(); + let generation = d.metadata.generation; + let pod = serde_json::to_value(d.spec.unwrap().template.spec.unwrap()).unwrap(); + assert_eq!(pod["priorityClassName"], rbac::AGENT_PRIORITY); + assert_eq!(pod["tolerations"], rbac::agent_tolerations()); + // Sent again: nothing to do, and the Deployment is as it was. refresh(&sa, &new, &mut Progress::default()).await.unwrap(); + finish(&sa, &new).await.unwrap(); + assert_eq!( + deployments + .get(DEPLOYMENT) + .await + .unwrap() + .metadata + .generation, + generation + ); + + // Its own Deployment, through the policy: only what a refresh or + // an update of the agent changes, to exactly this release's. + let own = Api::::namespaced(sa.clone(), rbac::NS); + let try_patch = |patch: Value| { + let own = own.clone(); + async move { + own.patch( + DEPLOYMENT, + &PatchParams { + dry_run: true, + ..Default::default() + }, + &Patch::Strategic(patch), + ) + .await + } + }; + let refused = |r: Result, what: &str| { + assert!( + r.as_ref() + .is_err_and(|e| e.to_string().contains("own Deployment")), + "{what}: {r:?}" + ) + }; + let pod_patch = |spec: Value| json!({ "spec": { "template": { "spec": spec } } }); + try_patch(pod_patch( + json!({ "containers": [{ "name": "agent", "image": "registry.k8s.io/pause:3.9" }] }), + )) + .await + .expect("an update of the agent: its image"); + try_patch(deployment_patch(&new)).await.expect("a refresh"); + refused( + try_patch(pod_patch( + json!({ "priorityClassName": "system-node-critical" }), + )) + .await, + "another priority class", + ); + let mut extra = rbac::agent_tolerations(); + extra + .as_array_mut() + .unwrap() + .push(json!({ "operator": "Exists" })); + refused( + try_patch(pod_patch(json!({ "tolerations": extra }))).await, + "an extra toleration", + ); + refused( + try_patch(pod_patch(json!({ "tolerations": [{ "key": "node.kubernetes.io/disk-pressure", "operator": "Exists", "effect": "NoSchedule" }] }))).await, + "other tolerations", + ); + refused( + try_patch(pod_patch(json!({ "containers": [{ "name": "agent", "env": [{ "name": "PYO_API_URL", "value": "https://elsewhere.example" }] }] }))).await, + "Pyo's address", + ); + refused( + try_patch(pod_patch(json!({ "containers": [{ "name": "agent", "envFrom": [{ "secretRef": { "name": "other" } }] }] }))).await, + "its token", + ); + refused( + try_patch(pod_patch(json!({ "serviceAccountName": "default" }))).await, + "its service account", + ); + refused( + try_patch(pod_patch( + json!({ "volumes": [{ "name": "x", "emptyDir": {} }] }), + )) + .await, + "a volume", + ); + refused( + try_patch(json!({ "spec": { "template": { "metadata": { "annotations": { "pyo.dev/token": "other" } } } } })).await, + "its token stamp", + ); + refused( + try_patch(json!({ "spec": { "replicas": 2 } })).await, + "its replicas", + ); + refused( + own.delete( + DEPLOYMENT, + &kube::api::DeleteParams { + dry_run: true, + ..Default::default() + }, + ) + .await + .map(|_| Deployment::default()), + "deleting it", + ); // Still enforced: a privileged pod is refused. let pod: k8s_openapi::api::core::v1::Pod = serde_json::from_value(json!({ "metadata": { "name": "pyo-test-privileged" }, "spec": { "containers": [{ "name": "x", "image": "registry.k8s.io/pause:3.10", "securityContext": { "privileged": true } }] } })).unwrap(); let refused = Api::::namespaced(sa.clone(), rbac::NS) diff --git a/crates/pyo-api/src/install.rs b/crates/pyo-api/src/install.rs index 9ccc5fbe..e9098753 100644 --- a/crates/pyo-api/src/install.rs +++ b/crates/pyo-api/src/install.rs @@ -380,13 +380,10 @@ spec: serviceAccountName: pyo-agent # It keeps running on a server short of disk or memory, and starts # there after an update: it reports that state, and cleans up what - # the evictions leave. - priorityClassName: system-cluster-critical - # It may run on a GPU server kept for GPU work. - tolerations: - - {{ key: nvidia.com/gpu, operator: Exists, effect: NoSchedule }} - - {{ key: node.kubernetes.io/disk-pressure, operator: Exists, effect: NoSchedule }} - - {{ key: node.kubernetes.io/memory-pressure, operator: Exists, effect: NoSchedule }} + # the evictions leave. It may also run on a GPU server kept for GPU + # work. A refresh brings these two to an older install. + priorityClassName: {priority} + tolerations: {tolerations} containers: - name: agent image: {image} @@ -413,6 +410,8 @@ spec: {admission}"#, annotation = pyo_proto::rbac::INSTALL_ANNOTATION, token_stamp = token_stamp(token), + priority = pyo_proto::rbac::AGENT_PRIORITY, + tolerations = pyo_proto::rbac::agent_tolerations(), ) } @@ -891,6 +890,9 @@ mod tests { .expect("the agent's Deployment")["spec"]["template"]["spec"] .clone(); assert_eq!(pod["priorityClassName"], "system-cluster-critical"); + // Exactly what a refresh brings, and the admission policy allows. + assert_eq!(pod["priorityClassName"], pyo_proto::rbac::AGENT_PRIORITY); + assert_eq!(pod["tolerations"], pyo_proto::rbac::agent_tolerations()); let tolerated: Vec<&str> = pod["tolerations"] .as_array() .unwrap() diff --git a/crates/pyo-proto/src/rbac.rs b/crates/pyo-proto/src/rbac.rs index 2e4b8e1c..8d4ecdd5 100644 --- a/crates/pyo-proto/src/rbac.rs +++ b/crates/pyo-proto/src/rbac.rs @@ -13,6 +13,8 @@ //! - Servers (labels, taints, cordon, drain, removal) in a role of their own //! that can be left out. //! - The customer's `pyo-system/pyo-policy` ConfigMap: read, never written. +//! - Its own Deployment: only its image, image pins, install stamp, and its +//! pods' priority and tolerations as this release sets them. //! //! RBAC can't say "only these names" for creating, or "only namespaces with //! this label"; the ValidatingAdmissionPolicy does, for requests made by the @@ -53,6 +55,156 @@ pub const UPGRADER: &str = "pyo-upgrade"; const RBAC: &str = "rbac.authorization.k8s.io/v1"; +/// The agent's own Deployment, in [`NS`]. +pub const AGENT_DEPLOYMENT: &str = "pyo-agent"; +/// Its pods' priority: a server short of disk or memory neither evicts the +/// agent nor refuses a new one, so it goes on reporting and cleaning up +/// there. The connect command sets it, and a refresh brings it. +pub const AGENT_PRIORITY: &str = "system-cluster-critical"; + +/// Its pods' tolerations, in this order: a GPU server kept for GPU work, +/// and a server short of disk or memory (so a new agent starts there after +/// an update). The connect command sets them, and a refresh brings them. +pub fn agent_tolerations() -> Value { + json!([ + { "key": crate::GPU_RESOURCE, "operator": "Exists", "effect": "NoSchedule" }, + { "key": "node.kubernetes.io/disk-pressure", "operator": "Exists", "effect": "NoSchedule" }, + { "key": "node.kubernetes.io/memory-pressure", "operator": "Exists", "effect": "NoSchedule" }, + ]) +} + +/// Its pod spec's fields that the agent never changes (all but its +/// containers, priority and tolerations), as of Kubernetes 1.30: a field +/// the API server doesn't know would break the whole policy. +const AGENT_POD_KEPT: [&str; 34] = [ + "activeDeadlineSeconds", + "affinity", + "automountServiceAccountToken", + "dnsConfig", + "dnsPolicy", + "enableServiceLinks", + "ephemeralContainers", + "hostAliases", + "hostIPC", + "hostNetwork", + "hostPID", + "hostUsers", + "hostname", + "imagePullSecrets", + "initContainers", + "nodeName", + "nodeSelector", + "os", + "overhead", + "preemptionPolicy", + "priority", + "readinessGates", + "resourceClaims", + "restartPolicy", + "runtimeClassName", + "schedulerName", + "schedulingGates", + "securityContext", + "serviceAccountName", + "setHostnameAsFQDN", + "shareProcessNamespace", + "subdomain", + "terminationGracePeriodSeconds", + "volumes", +]; +/// Its containers' fields that the agent never changes (all but the agent +/// container's image and the pinned env values), as of Kubernetes 1.30. +const AGENT_CONTAINER_KEPT: [&str; 20] = [ + "args", + "command", + "envFrom", + "imagePullPolicy", + "lifecycle", + "livenessProbe", + "ports", + "readinessProbe", + "resizePolicy", + "resources", + "restartPolicy", + "securityContext", + "startupProbe", + "stdin", + "stdinOnce", + "terminationMessagePath", + "terminationMessagePolicy", + "tty", + "volumeDevices", + "volumeMounts", +]; +/// The Deployment spec's fields kept as they are (all but its template). +const AGENT_SPEC_KEPT: [&str; 7] = [ + "minReadySeconds", + "paused", + "progressDeadlineSeconds", + "replicas", + "revisionHistoryLimit", + "selector", + "strategy", +]; + +/// CEL: `new.f` and `old.f` both missing, or equal. +fn kept_field(new: &str, old: &str, f: &str) -> String { + format!("(has({new}.{f}) == has({old}.{f}) && (!has({new}.{f}) || {new}.{f} == {old}.{f}))") +} + +/// CEL, for an update of the agent's own Deployment: all as it was but the +/// install stamp, the agent container's image (an update of the agent) and +/// pinned env values (a refresh), and its pods' priority and tolerations, +/// which may only become [`AGENT_PRIORITY`] and [`agent_tolerations`]. So +/// its token, Pyo's address, its other env, volumes and service account +/// stay as the connect command set them. +pub fn agent_deployment_kept() -> String { + let (n, o) = ("object", "oldObject"); + let (t, ot) = ("object.spec.template.spec", "oldObject.spec.template.spec"); + let ann = + |x: &str| format!("(has({x}.metadata.annotations) ? {x}.metadata.annotations : {{}})"); + let labels = |x: &str| format!("(has({x}.metadata.labels) ? {x}.metadata.labels : {{}})"); + let spec: Vec = AGENT_SPEC_KEPT + .iter() + .map(|f| kept_field(&format!("{n}.spec"), &format!("{o}.spec"), f)) + .collect(); + let pod: Vec = AGENT_POD_KEPT + .iter() + .map(|f| kept_field(t, ot, f)) + .collect(); + let container: Vec = AGENT_CONTAINER_KEPT + .iter() + .map(|f| kept_field("c", "p", f)) + .collect(); + let pinned = cel_literal(&json!(PINNED_ENV)); + format!( + "{labels_n} == {labels_o} && \ + {ann_n}.all(k, k == '{stamp}' || (k in {ann_o} && {ann_o}[k] == {ann_n}[k])) && {ann_o}.all(k, k == '{stamp}' || k in {ann_n}) && \ + {spec} && {template_meta} && {pod} && \ + (!has({t}.priorityClassName) ? !has({ot}.priorityClassName) : ({t}.priorityClassName == '{priority}' || (has({ot}.priorityClassName) && {ot}.priorityClassName == {t}.priorityClassName))) && \ + ((has({t}.tolerations) ? {t}.tolerations : []) == (has({ot}.tolerations) ? {ot}.tolerations : []) || (has({t}.tolerations) && {t}.tolerations == {tolerations})) && \ + size({t}.containers) == size({ot}.containers) && \ + {t}.containers.all(c, {ot}.containers.exists(p, p.name == c.name && (c.name == 'agent' || c.image == p.image) && {container} && \ + (has(c.env) ? c.env : []).all(e, e.name in {pinned} ? !has(e.valueFrom) : (has(p.env) && p.env.exists(x, x == e))) && \ + (has(p.env) ? p.env : []).all(x, x.name in {pinned} || (has(c.env) && c.env.exists(e, e == x)))))", + labels_n = labels(n), + labels_o = labels(o), + ann_n = ann(n), + ann_o = ann(o), + stamp = INSTALL_ANNOTATION, + spec = spec.join(" && "), + template_meta = kept_field( + &format!("{n}.spec.template"), + &format!("{o}.spec.template"), + "metadata" + ), + pod = pod.join(" && "), + priority = AGENT_PRIORITY, + tolerations = cel_literal(&agent_tolerations()), + container = container.join(" && "), + ) +} + fn labels() -> Value { json!({ "app.kubernetes.io/managed-by": "pyo", "app.kubernetes.io/part-of": "pyo-agent" }) } @@ -473,6 +625,13 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { "expression": "!(request.resource.resource == 'configmaps' && variables.ns == 'pyo-system' && variables.reqName == 'pyo-policy')", "message": "pyo-system/pyo-policy belongs to you: Pyo's agent only reads it.", }, + // Its own Deployment: only updated, and then only its image, image + // pins, install stamp, priority and tolerations, the last two to + // exactly this release's. + { + "expression": format!("!(request.resource.resource == 'deployments' && variables.ns == '{NS}' && variables.objName == '{AGENT_DEPLOYMENT}') || (request.operation == 'UPDATE' && variables.sub == '' && {})", agent_deployment_kept()), + "message": "Pyo's agent only changes its own Deployment's image, image pins, install stamp, priority and tolerations, as this release sets them.", + }, // No privileged containers, host namespaces or host paths, except // Pyo's own components that need them. { @@ -775,7 +934,8 @@ pub fn admission(waf_image: &str, geoip_image: &str) -> Vec { // its own. // // With the optional [`SELF_UPDATE_ROLE`] bound, the agent brings the -// admission policy and its image pins up to date itself (`RefreshInstall`): +// admission policy, its image pins and its pods' priority and tolerations up +// to date itself (`RefreshInstall`): // only when its roles are already as Pyo's are (it may read them, never // write them). Without it, the cluster's connect command does. @@ -785,8 +945,8 @@ pub const INSTALL_ANNOTATION: &str = "pyo.dev/install"; /// Optional: the agent may rewrite its own admission policy (and read its /// roles, to know they're current). Deleting its binding takes that away. pub const SELF_UPDATE_ROLE: &str = "pyo-agent-self-update"; -/// The agent Deployment's env that pins system images: the only part of -/// the Deployment a refresh changes. +/// The agent Deployment's env that pins system images: what a refresh +/// changes of it, with its pods' priority and tolerations. pub const PINNED_ENV: [&str; 10] = [ "PYO_WAF_IMAGE", "PYO_GEOIP_IMAGE", @@ -1502,6 +1662,91 @@ mod tests { } } + /// The agent's own Deployment: only updated, its priority and + /// tolerations only to exactly this release's, and its token, Pyo's + /// address, other env, volumes and account kept. + #[test] + fn the_agents_deployment_changes_only_as_a_refresh_does() { + let policy = admission("w", "g")[0].to_string(); + let rule = agent_deployment_kept(); + let escaped = serde_json::to_string(&rule).unwrap(); + assert!(policy.contains(&escaped[1..escaped.len() - 1])); + assert!(policy.contains(&format!( + "variables.objName == '{AGENT_DEPLOYMENT}') || (request.operation == 'UPDATE' && variables.sub == '' && " + ))); + assert!(rule.contains(&format!( + "object.spec.template.spec.priorityClassName == '{AGENT_PRIORITY}'" + ))); + assert!(rule.contains(&format!( + "object.spec.template.spec.tolerations == {}", + cel_literal(&agent_tolerations()) + ))); + // The two new tolerations, besides the GPU one it always had. + let tolerations = agent_tolerations(); + let keys: Vec<&str> = tolerations + .as_array() + .unwrap() + .iter() + .map(|t| t["key"].as_str().unwrap()) + .collect(); + assert_eq!( + keys, + [ + crate::GPU_RESOURCE, + "node.kubernetes.io/disk-pressure", + "node.kubernetes.io/memory-pressure" + ] + ); + // What must stay: by field, and env other than the pins. + for f in [ + "serviceAccountName", + "volumes", + "automountServiceAccountToken", + "initContainers", + ] { + assert!( + rule.contains(&format!( + "has(object.spec.template.spec.{f}) == has(oldObject.spec.template.spec.{f})" + )), + "{f}" + ); + } + for f in [ + "envFrom", + "command", + "args", + "volumeMounts", + "securityContext", + ] { + assert!(rule.contains(&format!("has(c.{f}) == has(p.{f})")), "{f}"); + } + assert!(rule.contains("(c.name == 'agent' || c.image == p.image)")); + assert!(rule.contains("e.name in [dyn('PYO_WAF_IMAGE')")); + assert!(rule.contains("object.spec.template.metadata == oldObject.spec.template.metadata")); + assert!(rule.contains(&format!("k == '{INSTALL_ANNOTATION}'"))); + // No field twice, and none it may change. + for list in [ + &AGENT_POD_KEPT[..], + &AGENT_CONTAINER_KEPT[..], + &AGENT_SPEC_KEPT[..], + ] { + let mut sorted = list.to_vec(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!(sorted.len(), list.len()); + for f in [ + "containers", + "priorityClassName", + "tolerations", + "image", + "env", + "template", + ] { + assert!(!list.contains(&f), "{f}"); + } + } + } + #[test] fn the_geoip_image_is_the_installations() { let img = "registry.example.com/pyo/geoip:7@sha256:bb"; @@ -1543,6 +1788,16 @@ mod tests { /// The roles' hash: stable for the same roles, 16 hex digits, and /// not moved by what a refresh can change (pins, the policy). + /// The disk pressure fix (critical per-server pods, the agent's own + /// priority and tolerations, the policy that allows them) changes no + /// role: 0.5.5's roles. So clusters take it through the agent's update + /// and a refresh, with no connect command. Change this only with a + /// release that means to ask for the connect command. + #[test] + fn the_roles_are_as_0_5_5s() { + assert_eq!(access_hash(), "5db0cd47517256de"); + } + #[test] fn access_hash_covers_only_the_roles() { let h = access_hash(); From 0394f3641ba3d7d65d1f57e53aa659659454d03d Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 19:00:04 +0700 Subject: [PATCH 048/139] test(api): run the tunnel against a fake cloudflare api fake.rs serves zones, records, tunnels with their routes, tokens and connections, and Origin CA certificates signed by a test CA, in Cloudflare's envelope. The real client runs against it: a token's checks, and a tunnel's whole course over HTTP. Against a throwaway Postgres, CI also runs the loop end to end: the tunnel made, a domain switched with both paths first, switched back with the record it replaced, a deleted service's record cleaned up, a free name under the default domain, and the tunnel removed in order. --- .github/workflows/ci.yml | 5 +- crates/pyo-api/src/cloudflare/fake.rs | 303 ++++++++++++++++++++ crates/pyo-api/src/cloudflare/http_tests.rs | 299 +++++++++++++++++++ 3 files changed, 605 insertions(+), 2 deletions(-) create mode 100644 crates/pyo-api/src/cloudflare/fake.rs create mode 100644 crates/pyo-api/src/cloudflare/http_tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3f87765d..92b1e532 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,11 +102,12 @@ jobs: - run: scripts/install-railpack.sh - run: cargo test --locked --workspace # Row security and teams against a real Postgres: what a person's - # requests may see and change, signing up, creating and joining teams. + # requests may see and change, signing up, creating and joining teams, + # and the Cloudflare Tunnel loop against a fake Cloudflare. - name: Teams and row security (Postgres) env: DATABASE_URL: postgres://postgres:pyo@localhost:5432/pyo - run: cargo test --locked -p pyo-api --lib -- --ignored rls::tests teams_rls_tests teamsec_tests auth::key_tests auth::invite_tests + run: cargo test --locked -p pyo-api --lib -- --ignored rls::tests teams_rls_tests teamsec_tests auth::key_tests auth::invite_tests cloudflare::http_tests # Known CVEs in the locked dependencies: Cargo.lock, bun.lock (with the # dashboard's dev dependencies) and the WAF's go.mod. A CRITICAL one diff --git a/crates/pyo-api/src/cloudflare/fake.rs b/crates/pyo-api/src/cloudflare/fake.rs new file mode 100644 index 00000000..6562391b --- /dev/null +++ b/crates/pyo-api/src/cloudflare/fake.rs @@ -0,0 +1,303 @@ +//! A fake Cloudflare API over HTTP, for tests (docs/cloudflare-tunnel.md +//! §17.3): zones with their accounts, DNS records, tunnels with their +//! routes, tokens and connections, and Origin CA certificates signed by a +//! test CA. It answers in Cloudflare's envelope (`success`, `errors`, +//! `result`), so the real client ([`super::Http`]) runs against it. +//! +//! [`FakeCf::start`] serves it on a free local port; the client points at +//! [`FakeCf::base`] (`Http::at`, or `PYO_DEV_CLOUDFLARE_API` in a debug +//! build). Every call is kept, as "METHOD /path". + +use std::sync::{Arc, Mutex}; + +use axum::{ + Router, + body::Bytes, + extract::State, + http::{HeaderMap, Method, StatusCode, Uri}, + response::{IntoResponse, Response}, +}; +use serde_json::{Value, json}; + +/// What the fake account holds. +#[derive(Default)] +pub struct Account { + /// The token it takes. + pub token: String, + /// (id, name, account id, account name). + pub zones: Vec<(String, String, String, String)>, + /// Accounts whose tunnels the token may not touch. + pub no_tunnels: Vec, + /// (zone id, record). + pub records: Vec<(String, Value)>, + /// (account id, tunnel). + pub tunnels: Vec<(String, Value)>, + /// tunnel id → (version, config). + pub configs: Vec<(String, i64, Value)>, + /// (id, hostnames, revoked). + pub certs: Vec<(String, Vec, bool)>, + pub calls: Vec, + next: u64, +} + +#[derive(Clone)] +pub struct FakeCf { + pub state: Arc>, + pub base: String, +} + +fn ok(result: Value) -> Response { + axum::Json(json!({ "success": true, "errors": [], "messages": [], "result": result, "result_info": { "page": 1, "total_pages": 1 } })) + .into_response() +} + +fn err(code: StatusCode, message: &str) -> Response { + ( + code, + axum::Json(json!({ "success": false, "errors": [{ "code": 1000 + code.as_u16(), "message": message }], "result": null })), + ) + .into_response() +} + +fn query(uri: &Uri, key: &str) -> Option { + uri.query()?.split('&').find_map(|kv| { + let (k, v) = kv.split_once('=')?; + (k == key).then(|| v.replace("%2A", "*").replace("%2a", "*")) + }) +} + +impl FakeCf { + /// Serve a fake account with this token and zones (id, name, account). + pub async fn start(token: &str, zones: &[(&str, &str, &str)]) -> FakeCf { + let state = Arc::new(Mutex::new(Account { + token: token.into(), + zones: zones + .iter() + .map(|(i, n, a)| (i.to_string(), n.to_string(), a.to_string(), format!("{a} Co"))) + .collect(), + ..Default::default() + })); + let app = Router::new() + .fallback(handle) + .with_state(state.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + FakeCf { + state, + base: format!("http://{addr}/client/v4"), + } + } + + pub fn calls(&self) -> Vec { + self.state.lock().unwrap().calls.clone() + } + + pub fn records(&self, zone: &str) -> Vec { + self.state + .lock() + .unwrap() + .records + .iter() + .filter(|(z, _)| z == zone) + .map(|(_, r)| r.clone()) + .collect() + } + + pub fn tunnels(&self) -> Vec { + self.state + .lock() + .unwrap() + .tunnels + .iter() + .map(|(_, t)| t.clone()) + .collect() + } + + /// Add a record someone made by hand. + pub fn put_record(&self, zone: &str, r: Value) { + self.state.lock().unwrap().records.push((zone.into(), r)); + } + + /// Set a tunnel's status, as its connectors make it. + pub fn set_status(&self, tunnel: &str, status: &str, colos: &[&str]) { + for (_, t) in self.state.lock().unwrap().tunnels.iter_mut() { + if t["id"] == tunnel { + t["status"] = json!(status); + t["connections"] = json!(colos.iter().map(|c| json!({ "colo_name": c, "client_id": "c1", "client_version": "2026.10.7", "opened_at": "2026-11-22T00:00:00Z", "origin_ip": "203.0.113.7" })).collect::>()); + } + } + } +} + +/// A uuid-shaped id, as Cloudflare makes for tunnels. +fn uuid(n: u64) -> String { + format!("00000000-0000-4000-8000-{n:012x}") +} + +/// Sign a CSR with a test CA, as Cloudflare's Origin CA does. +fn sign(csr: &str, days: i64) -> Option { + use rcgen::{CertificateParams, CertificateSigningRequestParams, IsCa, Issuer, KeyPair}; + let ca_key = KeyPair::generate().ok()?; + let mut ca = CertificateParams::new(vec![]).ok()?; + ca.is_ca = IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + let issuer = Issuer::new(ca, ca_key); + let mut req = CertificateSigningRequestParams::from_pem(csr).ok()?; + let now = cookie::time::OffsetDateTime::now_utc(); + req.params.not_before = now - cookie::time::Duration::days(1); + req.params.not_after = now + cookie::time::Duration::days(days); + Some(req.signed_by(&issuer).ok()?.pem()) +} + +async fn handle( + State(s): State>>, + method: Method, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + let mut a = s.lock().unwrap(); + let path = uri.path().trim_start_matches("/client/v4").to_owned(); + a.calls.push(format!("{method} {path}")); + let bearer = headers + .get("authorization") + .and_then(|h| h.to_str().ok()) + .and_then(|h| h.strip_prefix("Bearer ")) + .unwrap_or(""); + if bearer != a.token { + return err(StatusCode::FORBIDDEN, "Authentication error"); + } + let body: Value = serde_json::from_slice(&body).unwrap_or(Value::Null); + let seg: Vec<&str> = path.trim_matches('/').split('/').collect(); + let m = method.as_str(); + a.next += 1; + let n = a.next; + match (m, seg.as_slice()) { + ("GET", ["zones"]) => ok(json!(a + .zones + .iter() + .map(|(i, n, ai, an)| json!({ "id": i, "name": n, "account": { "id": ai, "name": an } })) + .collect::>())), + ("GET", ["zones", zone, "dns_records"]) => { + let name = query(&uri, "name"); + ok(json!(a + .records + .iter() + .filter(|(z, r)| z == zone && name.as_deref().is_none_or(|n| r["name"] == n)) + .map(|(_, r)| r.clone()) + .collect::>())) + } + ("POST", ["zones", zone, "dns_records"]) => { + let mut r = body.clone(); + r["id"] = json!(format!("{n:032x}")); + if r.get("ttl").is_none() { + r["ttl"] = json!(1); + } + a.records.push((zone.to_string(), r.clone())); + ok(r) + } + ("GET" | "PATCH" | "DELETE", ["zones", zone, "dns_records", id]) => { + let Some(i) = a.records.iter().position(|(z, r)| z == zone && r["id"] == *id) else { + return err(StatusCode::NOT_FOUND, "Record not found"); + }; + match m { + "GET" => ok(a.records[i].1.clone()), + "PATCH" => { + if let Some(o) = body.as_object() { + for (k, v) in o { + a.records[i].1[k] = v.clone(); + } + } + ok(a.records[i].1.clone()) + } + _ => { + a.records.remove(i); + ok(json!({ "id": id })) + } + } + } + (_, ["accounts", account, "cfd_tunnel", ..]) if a.no_tunnels.iter().any(|x| x == account) => { + err(StatusCode::FORBIDDEN, "Authentication error") + } + ("GET", ["accounts", account, "cfd_tunnel"]) => { + let name = query(&uri, "name").unwrap_or_default(); + ok(json!(a + .tunnels + .iter() + .filter(|(ac, t)| ac == account && t["name"].as_str().unwrap_or("").starts_with(&name) && t["deleted_at"].is_null()) + .map(|(_, t)| t.clone()) + .collect::>())) + } + ("POST", ["accounts", account, "cfd_tunnel"]) => { + let t = json!({ "id": uuid(n), "name": body["name"], "status": "inactive", "deleted_at": null, "connections": [], "secret": "first" }); + a.tunnels.push((account.to_string(), t.clone())); + ok(t) + } + (_, ["accounts", account, "cfd_tunnel", id, rest @ ..]) => { + let Some(i) = a.tunnels.iter().position(|(ac, t)| ac == account && t["id"] == *id) else { + return err(StatusCode::NOT_FOUND, "Tunnel not found"); + }; + match (m, rest) { + ("GET", []) => ok(a.tunnels[i].1.clone()), + ("PATCH", []) => { + a.tunnels[i].1["secret"] = body["tunnel_secret"].clone(); + ok(a.tunnels[i].1.clone()) + } + ("DELETE", []) => { + if a.tunnels[i].1["connections"].as_array().is_some_and(|c| !c.is_empty()) { + return err(StatusCode::BAD_REQUEST, "Cannot delete tunnel because it has active connections"); + } + a.tunnels[i].1["deleted_at"] = json!("2026-11-22T00:00:00Z"); + ok(a.tunnels[i].1.clone()) + } + ("GET", ["token"]) => { + let secret = a.tunnels[i].1["secret"].as_str().unwrap_or("").to_owned(); + ok(json!(format!("eyJ{id}{secret}"))) + } + ("PUT", ["configurations"]) => { + let id = id.to_string(); + let v = a.configs.iter().find(|c| c.0 == id).map_or(1, |c| c.1 + 1); + a.configs.retain(|c| c.0 != id); + a.configs.push((id.clone(), v, body["config"].clone())); + ok(json!({ "tunnel_id": id, "version": v, "config": body["config"] })) + } + ("GET", ["configurations"]) => { + let c = a.configs.iter().find(|c| c.0 == *id).cloned(); + ok(c.map_or(json!({ "version": 0, "config": null }), |c| json!({ "version": c.1, "config": c.2 }))) + } + ("DELETE", ["connections"]) => { + a.tunnels[i].1["connections"] = json!([]); + a.tunnels[i].1["status"] = json!("inactive"); + ok(json!(null)) + } + _ => err(StatusCode::NOT_FOUND, "No route"), + } + } + ("GET", ["certificates"]) => ok(json!([])), + ("POST", ["certificates"]) => { + let hosts: Vec = body["hostnames"] + .as_array() + .into_iter() + .flatten() + .filter_map(|h| h.as_str().map(str::to_owned)) + .collect(); + let days = body["requested_validity"].as_i64().unwrap_or(365); + let Some(pem) = sign(body["csr"].as_str().unwrap_or(""), days) else { + return err(StatusCode::BAD_REQUEST, "Invalid CSR"); + }; + let id = format!("{}", 100_000 + n); + a.certs.push((id.clone(), hosts.clone(), false)); + ok(json!({ "id": id, "certificate": pem, "hostnames": hosts, "request_type": body["request_type"] })) + } + ("DELETE", ["certificates", id]) => match a.certs.iter_mut().find(|c| c.0 == *id) { + Some(c) => { + c.2 = true; + ok(json!({ "id": id })) + } + None => err(StatusCode::NOT_FOUND, "Certificate not found"), + }, + _ => err(StatusCode::NOT_FOUND, "No route"), + } +} diff --git a/crates/pyo-api/src/cloudflare/http_tests.rs b/crates/pyo-api/src/cloudflare/http_tests.rs new file mode 100644 index 00000000..d111a612 --- /dev/null +++ b/crates/pyo-api/src/cloudflare/http_tests.rs @@ -0,0 +1,299 @@ +//! The real client against the fake Cloudflare API (fake.rs): what Pyo +//! sends and reads over HTTP for a tunnel, start to end. And, against a +//! throwaway Postgres, the whole tunnel loop: a cluster's tunnel made, a +//! domain switched (both paths, then only the tunnel), switched back, a +//! deleted service's record cleaned up, and the tunnel removed in order. + +use serde_json::{Value, json}; + +use super::fake::FakeCf; +use super::tunnel::{self, TunnelApi}; +use super::tunnel_loop::{Switched, ensure_tunnel, issue, revert_record, switch_record}; +use super::*; + +const TOKEN: &str = "fake-token-0123456789abcdef"; +const MARK: &str = "Made by Pyo (abc123)"; +const ZONE: &str = "023e105f4ecef8ad9ca31a8372d0c353"; +const ACCOUNT: &str = "699d98642c564d2e855e9661899b7252"; + +async fn fake() -> (FakeCf, Http) { + let cf = FakeCf::start(TOKEN, &[(ZONE, "example.com", ACCOUNT)]).await; + let http = Http::at(TOKEN, &cf.base); + (cf, http) +} + +#[tokio::test] +async fn a_token_is_checked_over_http() { + let (cf, http) = fake().await; + let zones = inspect(&http, MARK).await.unwrap(); + assert_eq!(zones.len(), 1); + assert_eq!(zones[0].account_id, ACCOUNT); + assert_eq!(zones[0].account_name, format!("{ACCOUNT} Co")); + assert!(zones[0].tunnel_ready(), "{zones:?}"); + // The probes leave nothing behind. + assert!(cf.records(ZONE).is_empty()); + assert!(cf.tunnels().iter().all(|t| !t["deleted_at"].is_null())); + // Without tunnel permission in the account: DNS only there. + cf.state.lock().unwrap().no_tunnels = vec![ACCOUNT.into()]; + let zones = inspect(&http, MARK).await.unwrap(); + assert!(!zones[0].tunnel_ready()); + assert_eq!(zones[0].tunnel.missing, [tunnel::TUNNEL_EDIT]); + // A wrong token: refused, said plainly. + let wrong = Http::at("another-token-0123456789", &cf.base); + assert!(matches!(inspect(&wrong, MARK).await, Err(CfError::Denied(_)))); +} + +#[tokio::test] +async fn a_tunnel_runs_its_course_over_http() { + let (cf, http) = fake().await; + let row = tunnel_loop::Row { + cluster_id: "cl_1".into(), + team_id: "team_1".into(), + account_id: ACCOUNT.into(), + ..Default::default() + }; + // Made, with routes and a token for the agent. + let (t, _) = ensure_tunnel(&http, &row, "abc123").await.unwrap(); + assert_eq!(t.name, "pyo-cl_1-abc123"); + let config = tunnel::ingress(&["blog.example.com".into()], Some("example.com")); + assert_eq!(http.put_config(ACCOUNT, &t.id, &config).await.unwrap(), 1); + assert_eq!(http.config(ACCOUNT, &t.id).await.unwrap(), (1, config)); + let token = http.tunnel_token(ACCOUNT, &t.id).await.unwrap(); + assert!(token.starts_with("eyJ")); + // Its certificate, issued for a CSR made here, reads as a certificate. + let names = tunnel::cert_names(&[("blog.example.com".into(), "example.com".into())], Some("example.com")).unwrap(); + let (cert, key) = issue(&http, &names).await.unwrap(); + let parsed = crate::certs::parse(&cert.pem, &key, pyo_proto::now_ms() / 1000).expect("a certificate Pyo can use"); + assert!(parsed.hostnames.contains(&"*.example.com".to_owned())); + assert!(parsed.not_after - parsed.not_before > 5000 * 86_400, "15 years"); + // A record by hand is in the way: asked first, then replaced and kept. + cf.put_record(ZONE, json!({ "id": "a1", "type": "A", "name": "blog.example.com", "content": "198.51.100.9", "proxied": true, "ttl": 300, "comment": "by hand" })); + let target = tunnel::cname_target(&t.id); + let out = switch_record(&http, ZONE, "blog.example.com", &target, false, MARK).await.unwrap(); + assert!(matches!(out, Switched::Confirm(ref r) if r[0].content == "198.51.100.9")); + let Switched::Done { record, previous } = switch_record(&http, ZONE, "blog.example.com", &target, true, MARK).await.unwrap() else { + panic!("not switched") + }; + assert_eq!(record.kind, "CNAME"); + assert!(record.proxied); + let now = cf.records(ZONE); + assert_eq!(now.len(), 1); + assert_eq!(now[0]["content"], json!(target)); + // Back exactly as it was. + revert_record(&http, ZONE, "blog.example.com", Some(&record.id), &previous, None, MARK).await.unwrap(); + let back = cf.records(ZONE); + assert_eq!(back.len(), 1); + for (k, v) in [("type", json!("A")), ("content", json!("198.51.100.9")), ("proxied", json!(true)), ("ttl", json!(300)), ("comment", json!("by hand"))] { + assert_eq!(back[0][k], v, "{k}"); + } + // Rotated, then taken apart. + http.rotate_secret(ACCOUNT, &t.id, &tunnel::new_secret()).await.unwrap(); + assert_ne!(http.tunnel_token(ACCOUNT, &t.id).await.unwrap(), token); + cf.set_status(&t.id, "healthy", &["FRA", "AMS"]); + let read = http.tunnel(ACCOUNT, &t.id).await.unwrap(); + assert_eq!((read.status.as_str(), read.connections.len()), ("healthy", 2)); + // Connected: Cloudflare refuses to delete it until they're dropped. + assert!(http.delete_tunnel(ACCOUNT, &t.id).await.is_err()); + http.drop_connections(ACCOUNT, &t.id).await.unwrap(); + http.delete_tunnel(ACCOUNT, &t.id).await.unwrap(); + assert!(http.tunnel(ACCOUNT, &t.id).await.unwrap().deleted); + http.revoke_origin_cert(&cert.id).await.unwrap(); + assert!(cf.state.lock().unwrap().certs.iter().all(|c| c.2)); +} + +// ── The whole loop, against a throwaway Postgres ─────────────────────────── + +fn run_big + Send + 'static>(f: F) { + std::thread::Builder::new() + .stack_size(64 << 20) + .spawn(|| { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap() + .block_on(f) + }) + .unwrap() + .join() + .unwrap(); +} + +/// The domain as its service has it now. +async fn domain(db: &sqlx::PgPool, service: &str) -> Value { + sqlx::query_scalar("SELECT spec->'domains'->0 FROM pyo.services WHERE id = $1") + .bind(service) + .fetch_one(db) + .await + .unwrap() +} + +/// What the agent was sent, last first. +async fn commands(db: &sqlx::PgPool, cluster: &str) -> Vec { + sqlx::query_scalar("SELECT command->>'kind' FROM pyo.commands WHERE cluster_id = $1 ORDER BY created_at DESC") + .bind(cluster) + .fetch_all(db) + .await + .unwrap() +} + +/// Against a throwaway Postgres and the fake Cloudflare: a cluster in +/// tunnel mode gets its tunnel, routes, certificate and the agent's token; +/// a domain switches with both paths first and only the tunnel once its +/// record moved, goes back with the record it replaced, a deleted +/// service's record is cleaned up, and the tunnel is taken apart. +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn the_tunnel_loop_end_to_end() { + run_big(async { + let cf = FakeCf::start(TOKEN, &[(ZONE, "example.com", ACCOUNT)]).await; + // SAFETY: set before anything here reads them; this test owns its runtime. + unsafe { + std::env::set_var("PYO_DEV_CLOUDFLARE_API", &cf.base); + if std::env::var("PYO_SECRET_KEY").is_err() { + std::env::set_var("PYO_SECRET_KEY", "11".repeat(32)); + } + } + let db = sqlx::PgPool::connect(&std::env::var("DATABASE_URL").expect("DATABASE_URL")) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + crate::vault::init(crate::vault::Vault::new(db.clone(), crate::vault::Provider::from_env())); + let s = crate::rls::tests::state(db.clone()); + let run = crate::ids::random_string(8).to_lowercase(); + let (team, cluster, project, svc, dpl) = ( + format!("team_tun{run}"), + format!("cl_tun{run}"), + format!("prj_tun{run}"), + format!("svc_tun{run}"), + format!("dpl_tun{run}"), + ); + let host = format!("blog-{run}.example.com"); + let q = |sql: &'static str| sqlx::query(sql); + q("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)").bind(&team).execute(&db).await.unwrap(); + q("INSERT INTO pyo.clusters (id, team_id, name, agent_token_hash, status, last_seen_at, traffic, capabilities) + VALUES ($1, $2, $1, $1, 'connected', now(), 'tunnel', '{\"tunnel\": true, \"agentInstall\": {\"state\": \"current\"}}')") + .bind(&cluster).bind(&team).execute(&db).await.unwrap(); + q("INSERT INTO pyo.projects (id, team_id, name, namespace) VALUES ($1, $2, 'shop', $1)").bind(&project).bind(&team).execute(&db).await.unwrap(); + let domains = json!([{ "id": "dom_1", "hostname": host, "portName": "http", "tlsMode": "auto", "tunnel": "switching", "status": "pending_dns" }]); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec, status) VALUES ($1, $2, $3, $4, 'web', jsonb_build_object('domains', $5::jsonb), 'running')") + .bind(&svc).bind(&team).bind(&project).bind(&cluster).bind(&domains).execute(&db).await.unwrap(); + let service = pyo_proto::ServiceRef { service_id: svc.clone(), name: "web".into(), namespace: project.clone(), workload_kind: "Deployment".into() }; + let spec = json!({ "service": service, "projectId": project, "ports": [{ "name": "http", "containerPort": 80, "protocol": "HTTP", "exposure": "http", "publicPort": null }] }); + q("INSERT INTO pyo.deployments (id, team_id, project_id, service_id, cluster_id, status, data, spec) VALUES ($1, $2, $3, $4, $5, 'running', '{}', $6)") + .bind(&dpl).bind(&team).bind(&project).bind(&svc).bind(&cluster).bind(&spec).execute(&db).await.unwrap(); + q("UPDATE pyo.services SET current_deployment_id = $2 WHERE id = $1").bind(&svc).bind(&dpl).execute(&db).await.unwrap(); + // The team's Cloudflare, as connecting it leaves it. + let zones = json!([{ "id": ZONE, "name": "example.com", "canEdit": true, "accountId": ACCOUNT, "accountName": "Acme", "tunnel": { "ready": true } }]); + let sealed = crate::vault::get().seal_credential(&team, TOKEN).await.unwrap(); + q("INSERT INTO pyo.cloudflare_accounts (team_id, token_sealed, zones) VALUES ($1, $2, $3)").bind(&team).bind(&sealed).bind(&zones).execute(&db).await.unwrap(); + // Someone's record on the name, then the tunnel and the switch asked for. + cf.put_record(ZONE, json!({ "id": format!("hand{run}"), "type": "A", "name": host, "content": "198.51.100.9", "proxied": false, "ttl": 300 })); + q("INSERT INTO pyo.cluster_tunnels (cluster_id, team_id, account_id, tunnel_name) VALUES ($1, $2, $3, 'pending')") + .bind(&cluster).bind(&team).bind(ACCOUNT).execute(&db).await.unwrap(); + q("INSERT INTO pyo.dns_records (service_id, domain_id, team_id, hostname, zone_id, zone_name, type, status) VALUES ($1, 'dom_1', $2, $3, $4, 'example.com', 'CNAME', 'switching')") + .bind(&svc).bind(&team).bind(&host).bind(ZONE).execute(&db).await.unwrap(); + let record = |db: sqlx::PgPool, svc: String| async move { + sqlx::query_as::<_, (String, String, Value)>("SELECT status, via, previous FROM pyo.dns_records WHERE service_id = $1") + .bind(svc) + .fetch_optional(&db) + .await + .unwrap() + }; + + // A pass: the tunnel, its routes and certificate; the record waits for a yes. + tunnel_loop::pass(&s).await.unwrap(); + let tunnel_id: String = sqlx::query_scalar("SELECT tunnel_id FROM pyo.cluster_tunnels WHERE cluster_id = $1").bind(&cluster).fetch_one(&db).await.unwrap(); + let config = cf.state.lock().unwrap().configs.iter().find(|c| c.0 == tunnel_id).map(|c| c.2.clone()).expect("routes"); + assert_eq!(config["ingress"][0]["hostname"], json!(host)); + let d = domain(&db, &svc).await; + assert_eq!((d["tlsMode"].as_str(), d["tunnel"].as_str()), (Some("custom"), Some("switching")), "the tunnel's certificate before its record moves: {d}"); + assert!(commands(&db, &cluster).await.contains(&"tunnel_set".to_owned()), "the agent's token"); + // The record waits for the agent's routes (both paths answer first). + assert_eq!(record(db.clone(), svc.clone()).await.unwrap().0, "switching"); + let agent_done = |db: sqlx::PgPool, cluster: String| async move { + sqlx::query("UPDATE pyo.commands SET status = 'done' WHERE cluster_id = $1") + .bind(cluster) + .execute(&db) + .await + .unwrap(); + }; + agent_done(db.clone(), cluster.clone()).await; + tunnel_loop::pass(&s).await.unwrap(); + let (status, via, _) = record(db.clone(), svc.clone()).await.unwrap(); + assert_eq!((status.as_str(), via.as_str()), ("conflict", "direct")); + assert_eq!(cf.records(ZONE).len(), 1, "someone's record, untouched"); + + // Replace and switch: kept, then only through the tunnel. + q("UPDATE pyo.dns_records SET status = 'switching', replace = true WHERE service_id = $1").bind(&svc).execute(&db).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + let (status, via, previous) = record(db.clone(), svc.clone()).await.unwrap(); + assert_eq!((status.as_str(), via.as_str()), ("created", "tunnel")); + assert_eq!(previous[0]["content"], "198.51.100.9"); + assert_eq!(domain(&db, &svc).await["tunnel"], "on"); + let now = cf.records(ZONE); + assert_eq!(now.len(), 1); + assert_eq!(now[0]["content"], json!(tunnel::cname_target(&tunnel_id))); + + // Switch back with the kept record: both paths first, then it's back. + q("UPDATE pyo.dns_records SET status = 'reverting', restore = true, routes_command = NULL WHERE service_id = $1").bind(&svc).execute(&db).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + assert!(record(db.clone(), svc.clone()).await.is_none()); + let d = domain(&db, &svc).await; + assert!(d.get("tunnel").is_none() && d["tlsMode"] == "auto", "{d}"); + let back = cf.records(ZONE); + assert_eq!((back.len(), back[0]["content"].as_str(), back[0]["ttl"].as_i64()), (1, Some("198.51.100.9"), Some(300))); + + // Switched again, then the service deleted: its CNAME goes with it. + cf.state.lock().unwrap().records.clear(); + q("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains,0,tunnel}', '\"switching\"') WHERE id = $1").bind(&svc).execute(&db).await.unwrap(); + q("INSERT INTO pyo.dns_records (service_id, domain_id, team_id, hostname, zone_id, zone_name, type, status) VALUES ($1, 'dom_1', $2, $3, $4, 'example.com', 'CNAME', 'switching')") + .bind(&svc).bind(&team).bind(&host).bind(ZONE).execute(&db).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + agent_done(db.clone(), cluster.clone()).await; + tunnel_loop::pass(&s).await.unwrap(); + assert_eq!(cf.records(ZONE).len(), 1); + q("DELETE FROM pyo.services WHERE id = $1").bind(&svc).execute(&db).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + assert!(cf.records(ZONE).is_empty(), "a deleted service's tunnel record goes"); + + // A default domain: its wildcard record, and a free name under it + // goes only through the tunnel, active once the wildcard is there. + let free = format!("web-{run}.example.com"); + let svc2 = format!("svc_tunf{run}"); + let domains = json!([{ "id": "dom_2", "hostname": free, "portName": "http", "tlsMode": "auto", "status": "pending_dns" }]); + q("INSERT INTO pyo.services (id, team_id, project_id, cluster_id, name, spec, status) VALUES ($1, $2, $3, $4, 'web2', jsonb_build_object('domains', $5::jsonb), 'running')") + .bind(&svc2).bind(&team).bind(&project).bind(&cluster).bind(&domains).execute(&db).await.unwrap(); + q("UPDATE pyo.cluster_tunnels SET default_domain = 'example.com', default_zone_id = $2 WHERE cluster_id = $1") + .bind(&cluster).bind(ZONE).execute(&db).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + let wildcard: Vec = cf.records(ZONE).into_iter().filter(|r| r["name"] == "*.example.com").collect(); + assert_eq!(wildcard.len(), 1); + assert_eq!(wildcard[0]["content"], json!(tunnel::cname_target(&tunnel_id))); + let d = domain(&db, &svc2).await; + assert_eq!((d["tunnel"].as_str(), d["status"].as_str()), (Some("on"), Some("active")), "{d}"); + let config = cf.state.lock().unwrap().configs.iter().find(|c| c.0 == tunnel_id).map(|c| c.2.clone()).unwrap(); + let hosts: Vec = config["ingress"].as_array().unwrap().iter().map(|r| r["hostname"].clone()).collect(); + assert_eq!(hosts.last().unwrap(), &Value::Null); + assert_eq!(hosts[hosts.len() - 2], "*.example.com", "the wildcard after every exact name"); + // The free name has no record of its own: the wildcard covers it. + assert!(cf.records(ZONE).iter().all(|r| r["name"] != json!(free))); + + // Removed: no routes but the catch-all, the tunnel deleted, its certificate revoked. + q("UPDATE pyo.clusters SET traffic = 'public' WHERE id = $1").bind(&cluster).execute(&db).await.unwrap(); + q("UPDATE pyo.cluster_tunnels SET state = 'removing', agent_status = '{}' WHERE cluster_id = $1").bind(&cluster).execute(&db).await.unwrap(); + tunnel_loop::pass(&s).await.unwrap(); + let left: i64 = sqlx::query_scalar("SELECT count(*) FROM pyo.cluster_tunnels WHERE cluster_id = $1").bind(&cluster).fetch_one(&db).await.unwrap(); + assert_eq!(left, 0); + let t = cf.tunnels().into_iter().find(|t| t["id"] == json!(tunnel_id)).unwrap(); + assert!(!t["deleted_at"].is_null()); + assert!(cf.state.lock().unwrap().certs.iter().all(|c| c.2), "revoked"); + let calls = cf.calls(); + let at = |c: &str| calls.iter().rposition(|x| x.starts_with(c)).unwrap(); + assert!(at("PUT /accounts") < at("DELETE /accounts"), "routes emptied before the tunnel goes: {calls:?}"); + assert!(cf.records(ZONE).is_empty(), "Pyo's wildcard record goes too"); + let leftovers: i64 = sqlx::query_scalar("SELECT count(*) FROM pyo.tunnel_leftovers WHERE team_id = $1").bind(&team).fetch_one(&db).await.unwrap(); + assert_eq!(leftovers, 0); + q("DELETE FROM pyo.teams WHERE id = $1").bind(&team).execute(&db).await.unwrap(); + }); +} From e36141e889bd280f36e6c8eb3bd8848763f93f8d Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 19:00:15 +0700 Subject: [PATCH 049/139] feat(api): close the tunnel's gaps and give tunnel mode free domains - A deleted service's tunnel record and a deleted cluster's tunnel are kept as leftovers (database triggers) and taken apart by the loop, so nothing Pyo made stays at Cloudflare. - A domain moved from another service or cluster waits until the old tunnel lets go of its name. - Pyo Cloud: a hostname's proof of ownership is written with the team's Cloudflare token when it covers the zone, and a free name under the team's own tunnel default domain needs none. - getClusterTunnel reads Cloudflare again when its view is older than 30 seconds. - In tunnel mode with a default domain, free domains are -., through the tunnel's wildcard (explicit names still come first). Without one there are none. The snapshot's freeDomainSuffix, compose, MCP and the CLI make that name. nip.io names stay where they are and answer again with public ports. - The Cloudflare client's base can point at a fake in debug builds (PYO_DEV_CLOUDFLARE_API), never in release builds. --- .../migrations/0040_cloudflare_tunnel.sql | 52 +++++ crates/pyo-api/src/cloudflare.rs | 115 ++++++++- crates/pyo-api/src/cloudflare/tunnel.rs | 30 +-- crates/pyo-api/src/cloudflare/tunnel_loop.rs | 219 ++++++++++++++++++ .../src/cloudflare/tunnel_loop_tests.rs | 23 ++ crates/pyo-api/src/cloudflare/tunnel_ops.rs | 7 +- crates/pyo-api/src/compose.rs | 7 +- crates/pyo-api/src/domainproof.rs | 50 +++- crates/pyo-api/src/freedomain.rs | 86 ++++++- crates/pyo-api/src/mcp.rs | 8 + crates/pyo-api/src/ops.rs | 4 + crates/pyo-api/src/snapshot.rs | 9 +- crates/pyo-cli/src/domain.rs | 29 ++- 13 files changed, 598 insertions(+), 41 deletions(-) diff --git a/crates/pyo-api/migrations/0040_cloudflare_tunnel.sql b/crates/pyo-api/migrations/0040_cloudflare_tunnel.sql index c4d6dfdd..eb9535de 100644 --- a/crates/pyo-api/migrations/0040_cloudflare_tunnel.sql +++ b/crates/pyo-api/migrations/0040_cloudflare_tunnel.sql @@ -87,3 +87,55 @@ ALTER TABLE pyo.dns_records ADD CONSTRAINT dns_records_status_check CHECK (status IN ('created', 'exists', 'conflict', 'failed', 'switching', 'reverting')); CREATE INDEX dns_records_tunnel_idx ON pyo.dns_records (service_id) WHERE status IN ('switching', 'reverting'); + +-- What's left at Cloudflare once its row is gone: a tunnel record of a +-- deleted service, or the tunnel of a deleted cluster. The tunnel loop +-- deletes them (only Pyo's own records) with the team's token. +CREATE TABLE pyo.tunnel_leftovers ( + id bigserial PRIMARY KEY, + team_id text NOT NULL REFERENCES pyo.teams (id) ON DELETE CASCADE, + -- 'record' (zone_id, record_id, hostname) or 'tunnel' (account_id, + -- tunnel_id, cf_certificates, and its wildcard record as a record). + kind text NOT NULL CHECK (kind IN ('record', 'tunnel')), + zone_id text, + record_id text, + hostname text, + account_id text, + tunnel_id text, + cf_certificates text[] NOT NULL DEFAULT '{}', + error text, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX tunnel_leftovers_team_idx ON pyo.tunnel_leftovers (team_id); +ALTER TABLE pyo.tunnel_leftovers ENABLE ROW LEVEL SECURITY; +CREATE POLICY team_rows ON pyo.tunnel_leftovers TO pyo_team + USING (team_id = ANY (pyo.team_scope())) + WITH CHECK (team_id = ANY (pyo.team_scope())); + +-- Kept when its team is still there (a team deleted takes its token too). +CREATE FUNCTION pyo.keep_tunnel_record() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.via = 'tunnel' AND OLD.record_id IS NOT NULL + AND EXISTS (SELECT 1 FROM pyo.teams WHERE id = OLD.team_id) THEN + INSERT INTO pyo.tunnel_leftovers (team_id, kind, zone_id, record_id, hostname) + VALUES (OLD.team_id, 'record', OLD.zone_id, OLD.record_id, OLD.hostname); + END IF; + RETURN OLD; +END +$$; +CREATE TRIGGER dns_records_tunnel_leftover BEFORE DELETE ON pyo.dns_records + FOR EACH ROW EXECUTE FUNCTION pyo.keep_tunnel_record(); + +CREATE FUNCTION pyo.keep_tunnel() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF (OLD.tunnel_id IS NOT NULL OR OLD.cf_certificate_id IS NOT NULL OR OLD.default_record_id IS NOT NULL) + AND EXISTS (SELECT 1 FROM pyo.teams WHERE id = OLD.team_id) THEN + INSERT INTO pyo.tunnel_leftovers (team_id, kind, zone_id, record_id, hostname, account_id, tunnel_id, cf_certificates) + VALUES (OLD.team_id, 'tunnel', OLD.default_zone_id, OLD.default_record_id, '*.' || OLD.default_domain, + OLD.account_id, OLD.tunnel_id, array_remove(ARRAY[OLD.cf_certificate_id, OLD.cf_certificate_old], NULL)); + END IF; + RETURN OLD; +END +$$; +CREATE TRIGGER cluster_tunnels_leftover BEFORE DELETE ON pyo.cluster_tunnels + FOR EACH ROW EXECUTE FUNCTION pyo.keep_tunnel(); diff --git a/crates/pyo-api/src/cloudflare.rs b/crates/pyo-api/src/cloudflare.rs index cea3445e..63c6e8ab 100644 --- a/crates/pyo-api/src/cloudflare.rs +++ b/crates/pyo-api/src/cloudflare.rs @@ -375,6 +375,21 @@ pub fn problems(zones: &[Zone]) -> Vec { pub(crate) struct Http { client: reqwest::Client, token: String, + /// [`API`], or a debug build's fake ([`api_base`]). + base: String, +} + +/// Where Cloudflare's API is: [`API`]. A debug build may point it at a fake +/// with `PYO_DEV_CLOUDFLARE_API` (`http://127.0.0.1:8787/client/v4`, for the +/// dashboard and Pyo Cloud e2e tests). Release builds never read it. +pub(crate) fn api_base() -> String { + #[cfg(debug_assertions)] + if let Ok(b) = std::env::var("PYO_DEV_CLOUDFLARE_API") + && !b.trim().is_empty() + { + return b.trim().trim_end_matches('/').to_owned(); + } + API.to_owned() } // Never print the token. @@ -414,20 +429,37 @@ fn token_code(v: &Value) -> bool { impl Http { pub fn new(token: &str) -> ApiResult { + let base = api_base(); + // Only a debug build's fake is on a private address. + let reach = Reach { + private: base != API, + }; Ok(Self { - client: outbound::client(Reach { private: false }, TIMEOUT) + client: outbound::client(reach, TIMEOUT) .map_err(|e| ApiError::from(anyhow::Error::from(e)))?, token: token.to_owned(), + base, }) } - fn url(path: &str) -> Url { - // Constant base, checked ids: always parses. - Url::parse(&format!("{API}{path}")).expect("Cloudflare URL") + /// A client for the tests' fake Cloudflare (fake.rs). + #[cfg(test)] + pub fn at(token: &str, base: &str) -> Self { + Self { + client: reqwest::Client::new(), + token: token.to_owned(), + base: base.trim_end_matches('/').to_owned(), + } + } + + fn url(&self, path: &str) -> Url { + // A fixed base and checked ids: always parses. + Url::parse(&format!("{}{path}", self.base)).expect("Cloudflare URL") } async fn call(&self, method: Method, url: Url, body: Option) -> Result { - if url.host_str() != Some("api.cloudflare.com") || url.scheme() != "https" { + let real = url.host_str() == Some("api.cloudflare.com") && url.scheme() == "https"; + if !(real || (self.base != API && url.as_str().starts_with(&self.base))) { return Err(CfError::Unreachable); } let mut rq = self.client.request(method, url).bearer_auth(&self.token); @@ -468,7 +500,7 @@ fn record_from(v: &Value) -> Result { impl Cloudflare for Http { async fn records(&self, zone_id: &str, name: &str) -> Result, CfError> { - let mut url = Self::url(&Self::record_path(zone_id, None)?); + let mut url = self.url(&Self::record_path(zone_id, None)?); url.query_pairs_mut() .append_pair("name", name) .append_pair("per_page", "100"); @@ -482,12 +514,12 @@ impl Cloudflare for Http { } async fn record(&self, zone_id: &str, id: &str) -> Result { - let url = Self::url(&Self::record_path(zone_id, Some(id))?); + let url = self.url(&Self::record_path(zone_id, Some(id))?); record_from(&self.call(Method::GET, url, None).await?["result"]) } async fn create(&self, zone_id: &str, r: &NewRecord) -> Result { - let url = Self::url(&Self::record_path(zone_id, None)?); + let url = self.url(&Self::record_path(zone_id, None)?); let body = json!({ "type": r.kind, "name": r.name, "content": r.content, "ttl": 1, "proxied": r.proxied, "comment": r.comment, @@ -496,14 +528,14 @@ impl Cloudflare for Http { } async fn set_proxied(&self, zone_id: &str, id: &str, proxied: bool) -> Result<(), CfError> { - let url = Self::url(&Self::record_path(zone_id, Some(id))?); + let url = self.url(&Self::record_path(zone_id, Some(id))?); self.call(Method::PATCH, url, Some(json!({ "proxied": proxied }))) .await .map(|_| ()) } async fn delete(&self, zone_id: &str, id: &str) -> Result<(), CfError> { - let url = Self::url(&Self::record_path(zone_id, Some(id))?); + let url = self.url(&Self::record_path(zone_id, Some(id))?); self.call(Method::DELETE, url, None).await.map(|_| ()) } } @@ -711,6 +743,65 @@ pub async fn forget_removed( Ok(()) } +// ── Proof of a domain (Pyo Cloud) ────────────────────────────────────────── + +/// Pyo Cloud's proof of owning `host` (domainproof.rs), written by Pyo: +/// the TXT record `_pyo-verify.` with the team's token, when the +/// team's Cloudflare token can edit DNS in a zone that covers it. So Cloud +/// teams with Cloudflare don't add it by hand. Whether it's there now. +pub(crate) async fn write_proof( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + host: &str, +) -> ApiResult { + let row: Option<(String, Value)> = sqlx::query_as( + "SELECT token_sealed, zones FROM pyo.cloudflare_accounts WHERE team_id = $1", + ) + .bind(team_id) + .fetch_optional(&mut **tx) + .await?; + let Some((sealed, zones)) = row else { + return Ok(false); + }; + let zones: Vec = serde_json::from_value(zones).unwrap_or_default(); + let Some(zone) = zone_for(host, &zones).filter(|z| z.can_edit).cloned() else { + return Ok(false); + }; + // Sealed by the vault, or (older keys) with PYO_SECRET_KEY. + let token = if sealed.starts_with(crate::secrets::PREFIX) { + crate::secrets::Sealer::from_env().open(&sealed) + } else { + crate::vault::get().open(&sealed).await + }; + let Ok(token) = token else { + return Ok(false); + }; + let name = crate::domainproof::record(host); + let value = crate::domainproof::token(team_id, host); + let mark = marker(&install_id(tx).await?); + let cf = Http::new(&token)?; + let found = cf.records(&zone.id, &name).await.map_err(api_error)?; + if found + .iter() + .any(|r| r.kind == "TXT" && r.content.trim_matches('"') == value) + { + return Ok(true); + } + cf.create( + &zone.id, + &NewRecord { + kind: "TXT".into(), + name, + content: format!("\"{value}\""), + proxied: false, + comment: mark, + }, + ) + .await + .map_err(api_error)?; + Ok(true) +} + // ── The connection ───────────────────────────────────────────────────────── /// Connect (or replace) a team's token: checked first, then sealed. @@ -1319,3 +1410,7 @@ pub async fn proxy_ready(s: &AppState) -> ApiResult<()> { #[cfg(test)] mod tests; +#[cfg(test)] +mod fake; +#[cfg(test)] +mod http_tests; diff --git a/crates/pyo-api/src/cloudflare/tunnel.rs b/crates/pyo-api/src/cloudflare/tunnel.rs index 2f3ddd1d..9e7faea5 100644 --- a/crates/pyo-api/src/cloudflare/tunnel.rs +++ b/crates/pyo-api/src/cloudflare/tunnel.rs @@ -213,7 +213,7 @@ impl TunnelApi for Http { async fn zone_accounts(&self) -> Result, CfError> { let mut out = vec![]; for page in 1..=20 { - let mut url = Self::url("/zones"); + let mut url = self.url("/zones"); url.query_pairs_mut() .append_pair("per_page", "50") .append_pair("page", &page.to_string()); @@ -244,7 +244,7 @@ impl TunnelApi for Http { } async fn records_kept(&self, zone_id: &str, name: &str) -> Result, CfError> { - let mut url = Self::url(&Self::record_path(zone_id, None)?); + let mut url = self.url(&Self::record_path(zone_id, None)?); url.query_pairs_mut() .append_pair("name", name) .append_pair("per_page", "100"); @@ -258,7 +258,7 @@ impl TunnelApi for Http { } async fn create_kept(&self, zone_id: &str, r: &Kept) -> Result { - let url = Self::url(&Self::record_path(zone_id, None)?); + let url = self.url(&Self::record_path(zone_id, None)?); let mut body = json!({ "type": r.kind, "name": r.name, "content": r.content, "ttl": r.ttl, "proxied": r.proxied, @@ -270,7 +270,7 @@ impl TunnelApi for Http { } async fn tunnels_named(&self, account: &str, name: &str) -> Result, CfError> { - let mut url = Self::url(&tunnel_path(account, None, "")?); + let mut url = self.url(&tunnel_path(account, None, "")?); url.query_pairs_mut() .append_pair("name", name) .append_pair("is_deleted", "false") @@ -285,23 +285,23 @@ impl TunnelApi for Http { } async fn create_tunnel(&self, account: &str, name: &str) -> Result { - let url = Self::url(&tunnel_path(account, None, "")?); + let url = self.url(&tunnel_path(account, None, "")?); let body = json!({ "name": name, "config_src": "cloudflare" }); tunnel_from(&self.call(Method::POST, url, Some(body)).await?["result"]) } async fn tunnel(&self, account: &str, id: &str) -> Result { - let url = Self::url(&tunnel_path(account, Some(id), "")?); + let url = self.url(&tunnel_path(account, Some(id), "")?); tunnel_from(&self.call(Method::GET, url, None).await?["result"]) } async fn delete_tunnel(&self, account: &str, id: &str) -> Result<(), CfError> { - let url = Self::url(&tunnel_path(account, Some(id), "")?); + let url = self.url(&tunnel_path(account, Some(id), "")?); self.call(Method::DELETE, url, None).await.map(|_| ()) } async fn tunnel_token(&self, account: &str, id: &str) -> Result { - let url = Self::url(&tunnel_path(account, Some(id), "/token")?); + let url = self.url(&tunnel_path(account, Some(id), "/token")?); let v = self.call(Method::GET, url, None).await?; v["result"] .as_str() @@ -311,7 +311,7 @@ impl TunnelApi for Http { } async fn put_config(&self, account: &str, id: &str, config: &Value) -> Result { - let url = Self::url(&tunnel_path(account, Some(id), "/configurations")?); + let url = self.url(&tunnel_path(account, Some(id), "/configurations")?); let v = self .call(Method::PUT, url, Some(json!({ "config": config }))) .await?; @@ -319,7 +319,7 @@ impl TunnelApi for Http { } async fn config(&self, account: &str, id: &str) -> Result<(i64, Value), CfError> { - let url = Self::url(&tunnel_path(account, Some(id), "/configurations")?); + let url = self.url(&tunnel_path(account, Some(id), "/configurations")?); let v = self.call(Method::GET, url, None).await?; Ok(( v["result"]["version"].as_i64().unwrap_or(0), @@ -328,14 +328,14 @@ impl TunnelApi for Http { } async fn rotate_secret(&self, account: &str, id: &str, secret: &str) -> Result<(), CfError> { - let url = Self::url(&tunnel_path(account, Some(id), "")?); + let url = self.url(&tunnel_path(account, Some(id), "")?); self.call(Method::PATCH, url, Some(json!({ "tunnel_secret": secret }))) .await .map(|_| ()) } async fn drop_connections(&self, account: &str, id: &str) -> Result<(), CfError> { - let url = Self::url(&tunnel_path(account, Some(id), "/connections")?); + let url = self.url(&tunnel_path(account, Some(id), "/connections")?); self.call(Method::DELETE, url, None).await.map(|_| ()) } @@ -343,7 +343,7 @@ impl TunnelApi for Http { if !id_ok(zone_id) { return Err(CfError::NotFound); } - let mut url = Self::url("/certificates"); + let mut url = self.url("/certificates"); url.query_pairs_mut().append_pair("zone_id", zone_id); let v = self.call(Method::GET, url, None).await?; Ok(v["result"] @@ -359,7 +359,7 @@ impl TunnelApi for Http { csr_pem: &str, hostnames: &[String], ) -> Result { - let url = Self::url("/certificates"); + let url = self.url("/certificates"); let body = json!({ "csr": csr_pem, "hostnames": hostnames, "request_type": "origin-ecc", "requested_validity": CERT_DAYS, @@ -379,7 +379,7 @@ impl TunnelApi for Http { if !cert_id_ok(id) { return Err(CfError::NotFound); } - let url = Self::url(&format!("/certificates/{id}")); + let url = self.url(&format!("/certificates/{id}")); self.call(Method::DELETE, url, None).await.map(|_| ()) } } diff --git a/crates/pyo-api/src/cloudflare/tunnel_loop.rs b/crates/pyo-api/src/cloudflare/tunnel_loop.rs index 8279bcc7..e9657fbd 100644 --- a/crates/pyo-api/src/cloudflare/tunnel_loop.rs +++ b/crates/pyo-api/src/cloudflare/tunnel_loop.rs @@ -59,6 +59,87 @@ pub async fn pass(s: &AppState) -> ApiResult<()> { tracing::warn!(cluster = %id, error = ?e.message, "tunnel pass failed"); } } + leftovers(s).await +} + +/// What's left at Cloudflare of a deleted service's tunnel domain or a +/// deleted cluster's tunnel (the migration's triggers keep them): only +/// Pyo's own records are deleted, then the tunnel and its certificates. +#[derive(sqlx::FromRow, Debug)] +struct Leftover { + id: i64, + team_id: String, + kind: String, + zone_id: Option, + record_id: Option, + hostname: Option, + account_id: Option, + tunnel_id: Option, + cf_certificates: Vec, +} + +async fn leftovers(s: &AppState) -> ApiResult<()> { + let rows: Vec = sqlx::query_as( + "SELECT id, team_id, kind, zone_id, record_id, hostname, account_id, tunnel_id, cf_certificates + FROM pyo.tunnel_leftovers ORDER BY id LIMIT 50", + ) + .fetch_all(&s.db) + .await?; + for l in rows { + let mut tx = s.db.begin().await?; + let account = super::account(s, &mut tx, &l.team_id).await.ok().flatten(); + let mark = marker(&install_id(&mut tx).await?); + tx.commit().await?; + let Some(account) = account else { + sqlx::query("UPDATE pyo.tunnel_leftovers SET error = $2 WHERE id = $1") + .bind(l.id) + .bind(TOKEN_GONE) + .execute(&s.db) + .await?; + continue; + }; + let done = clean_up(&Http::new(&account.token)?, &l, &mark).await; + match done { + Ok(()) => { + sqlx::query("DELETE FROM pyo.tunnel_leftovers WHERE id = $1") + .bind(l.id) + .execute(&s.db) + .await?; + } + Err(e) => { + sqlx::query("UPDATE pyo.tunnel_leftovers SET error = $2 WHERE id = $1") + .bind(l.id) + .bind(e.to_string()) + .execute(&s.db) + .await?; + } + } + } + Ok(()) +} + +/// One leftover, taken apart. Gone already counts as done. +async fn clean_up(cf: &C, l: &Leftover, mark: &str) -> Result<(), CfError> { + let gone = |r: Result<(), CfError>| match r { + Ok(()) | Err(CfError::NotFound) => Ok(()), + Err(e) => Err(e), + }; + if let (Some(zone), Some(id), Some(host)) = (&l.zone_id, &l.record_id, &l.hostname) { + delete_ours(cf, zone, id, host, mark).await?; + } + if l.kind == "tunnel" + && let (Some(account), Some(id)) = (&l.account_id, &l.tunnel_id) + { + match cf.put_config(account, id, &tunnel::empty_ingress()).await { + Ok(_) | Err(CfError::NotFound) => {} + Err(e) => return Err(e), + } + gone(cf.drop_connections(account, id).await)?; + gone(cf.delete_tunnel(account, id).await)?; + } + for c in &l.cf_certificates { + gone(cf.revoke_origin_cert(c).await)?; + } Ok(()) } @@ -300,6 +381,10 @@ async fn keep( } } let target = tunnel::cname_target(&t.id); + // Free domains under the default domain: through the tunnel's wildcard. + if let Some(d) = &row.default_domain { + free_domains_follow(s, &row.cluster_id, d, row.default_record_id.is_some()).await?; + } let domains = tunnel_domains(&s.db, &row.cluster_id, zones).await?; // 2. Its routes: every tunnel domain, plus the default domain's wildcard. @@ -607,6 +692,22 @@ async fn records( .fetch_all(&s.db) .await?; for w in waiting { + // The same name on its way off another tunnel (a domain moved from + // another service or cluster): that one first. + if w.status == "switching" { + let busy: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.dns_records r WHERE lower(r.hostname) = lower($1) AND r.service_id <> $2 + AND (r.status = 'reverting' OR (r.via = 'tunnel' AND r.status = 'created'))) + OR EXISTS (SELECT 1 FROM pyo.tunnel_leftovers l WHERE lower(l.hostname) = lower($1))", + ) + .bind(&w.hostname) + .bind(&w.service_id) + .fetch_one(&s.db) + .await?; + if busy { + continue; + } + } // The agent's routes first: no record moves before both paths answer. match w.routes.as_deref() { None | Some("done") => {} @@ -776,6 +877,12 @@ async fn revert_one( .await?; } None => { + // Pyo's CNAME is gone already: nothing left for the leftovers. + sqlx::query("UPDATE pyo.dns_records SET via = 'direct', record_id = NULL WHERE service_id = $1 AND domain_id = $2") + .bind(&w.service_id) + .bind(&w.domain_id) + .execute(&mut *tx) + .await?; sqlx::query("DELETE FROM pyo.dns_records WHERE service_id = $1 AND domain_id = $2") .bind(&w.service_id) .bind(&w.domain_id) @@ -855,6 +962,80 @@ pub(crate) fn take_certificate(d: &mut Value, certificate_id: &str) -> bool { true } +/// Whether `host` is a free name under the default domain `d`: one label +/// below it (`web-shop.example.com`), as the wildcard covers. +pub fn under_default(host: &str, d: &str) -> bool { + host.to_ascii_lowercase() + .strip_suffix(&format!(".{}", d.to_ascii_lowercase())) + .is_some_and(|label| !label.is_empty() && !label.contains('.')) +} + +/// A cluster's domains one label under its default domain, with no record +/// of their own (Pyo's or anyone's: an explicit record wins over the +/// wildcard), go only through the tunnel: `tunnel: "on"`, and active once +/// the wildcard record is there. +async fn free_domains_follow( + s: &AppState, + cluster_id: &str, + default_domain: &str, + wildcard: bool, +) -> ApiResult<()> { + let services: Vec<(String, Value)> = sqlx::query_as( + "SELECT a.id, coalesce(a.spec->'domains', '[]') FROM pyo.services a + WHERE a.cluster_id = $1 AND NOT a.deleting + AND EXISTS (SELECT 1 FROM jsonb_array_elements(a.spec->'domains') d + WHERE lower(d->>'hostname') LIKE '%.' || lower($2) + AND (NOT d ? 'tunnel' OR (d->>'tunnel' = 'on' AND d->>'status' <> 'active')))", + ) + .bind(cluster_id) + .bind(default_domain) + .fetch_all(&s.db) + .await?; + for (service_id, mut domains) in services { + let own: Vec = sqlx::query_scalar("SELECT domain_id FROM pyo.dns_records WHERE service_id = $1") + .bind(&service_id) + .fetch_all(&s.db) + .await?; + let mut routes = false; + let mut changed = false; + for d in domains.as_array_mut().into_iter().flatten() { + let host = d["hostname"].as_str().unwrap_or("").to_owned(); + let id = d["id"].as_str().unwrap_or("").to_owned(); + if !under_default(&host, default_domain) || own.contains(&id) { + continue; + } + if d.get("tunnel").is_none() { + d["tunnel"] = json!(pyo_proto::TUNNEL_ON); + routes = true; + changed = true; + } + if d["tunnel"] == json!(pyo_proto::TUNNEL_ON) && wildcard && d["status"] != json!("active") { + d["status"] = json!("active"); + changed = true; + } + } + if !changed { + continue; + } + let mut tx = s.db.begin().await?; + sqlx::query("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1") + .bind(&service_id) + .bind(&domains) + .execute(&mut *tx) + .await?; + let wake = if routes { + crate::routes::changed(&mut tx, &service_id, true).await? + } else { + None + }; + tx.commit().await?; + if let Some(c) = wake { + s.wake(&c).await; + } + } + Ok(()) +} + /// Change one domain of a service's spec. async fn set_domain( tx: &mut Transaction<'_, Postgres>, @@ -1161,6 +1342,36 @@ async fn status(s: &AppState, row: &Row, t: &Tunnel) -> ApiResult<()> { Ok(()) } +/// Read Cloudflare's view of a cluster's tunnel again when the last read +/// is older than 30 seconds (the tunnel endpoint's fresh read). Quiet when +/// Cloudflare can't be reached: the stored view is shown then. +pub async fn refresh(s: &AppState, cluster_id: &str) -> ApiResult<()> { + let due: Option<(String, String, Option)> = sqlx::query_as( + "SELECT team_id, account_id, tunnel_id FROM pyo.cluster_tunnels + WHERE cluster_id = $1 AND state <> 'removing' AND tunnel_id IS NOT NULL + AND (checked_at IS NULL OR checked_at < now() - interval '30 seconds')", + ) + .bind(cluster_id) + .fetch_optional(&s.db) + .await?; + let Some((team_id, account_id, Some(tunnel_id))) = due else { + return Ok(()); + }; + let mut tx = s.db.begin().await?; + let account = super::account(s, &mut tx, &team_id).await.ok().flatten(); + tx.commit().await?; + let Some(account) = account else { + return Ok(()); + }; + let Ok(t) = Http::new(&account.token)?.tunnel(&account_id, &tunnel_id).await else { + return Ok(()); + }; + if let Some(row) = load(&s.db, cluster_id).await? { + status(s, &row, &t).await?; + } + Ok(()) +} + // ── As shown ─────────────────────────────────────────────────────────────── /// A tunnel as the dashboard, CLI and API show it: never a token. @@ -1346,6 +1557,14 @@ async fn remove( } } let mut tx = s.db.begin().await?; + // Everything at Cloudflare is gone: nothing left for the leftovers. + sqlx::query( + "UPDATE pyo.cluster_tunnels SET tunnel_id = NULL, cf_certificate_id = NULL, cf_certificate_old = NULL, default_record_id = NULL + WHERE cluster_id = $1", + ) + .bind(&row.cluster_id) + .execute(&mut *tx) + .await?; sqlx::query("DELETE FROM pyo.cluster_tunnels WHERE cluster_id = $1") .bind(&row.cluster_id) .execute(&mut *tx) diff --git a/crates/pyo-api/src/cloudflare/tunnel_loop_tests.rs b/crates/pyo-api/src/cloudflare/tunnel_loop_tests.rs index 6aed3893..4a7f82d3 100644 --- a/crates/pyo-api/src/cloudflare/tunnel_loop_tests.rs +++ b/crates/pyo-api/src/cloudflare/tunnel_loop_tests.rs @@ -277,3 +277,26 @@ fn domains_take_the_tunnel_certificate_and_give_it_back() { leave_tunnel(&mut d); assert_eq!((d["tlsMode"].as_str(), d["certificateId"].as_str()), (Some("custom"), Some("crt_mine"))); } + +#[test] +fn free_names_are_one_label_under_the_default_domain() { + assert!(under_default("web-shop.example.com", "example.com")); + assert!(under_default("Web-Shop.Example.com", "example.com")); + assert!(!under_default("a.web-shop.example.com", "example.com"), "the wildcard covers one level"); + assert!(!under_default("example.com", "example.com")); + assert!(!under_default("web.notexample.com", "example.com")); + assert!(!under_default("web.example.com.evil.net", "example.com")); +} + +#[test] +fn an_explicit_record_wins_over_the_free_wildcard() { + // A name switched by hand comes before the default domain's wildcard. + let routes = tunnel::ingress(&["web-shop.example.com".into()], Some("example.com")); + let names: Vec<&str> = routes["ingress"] + .as_array() + .unwrap() + .iter() + .filter_map(|r| r["hostname"].as_str()) + .collect(); + assert_eq!(names, ["web-shop.example.com", "*.example.com"]); +} diff --git a/crates/pyo-api/src/cloudflare/tunnel_ops.rs b/crates/pyo-api/src/cloudflare/tunnel_ops.rs index 6bf8f2ac..d5c8a83b 100644 --- a/crates/pyo-api/src/cloudflare/tunnel_ops.rs +++ b/crates/pyo-api/src/cloudflare/tunnel_ops.rs @@ -589,7 +589,8 @@ pub async fn rotate( /// (`health`, `connections`, `colos`), the connectors in the cluster /// (`connectors`: each one's server, whether it's ready, and why not), its /// default domain, its certificate, and `refused` when the cluster's install -/// is older than Pyo's. Never a token. Cloudflare is read every 2 minutes. +/// is older than Pyo's. Never a token. Cloudflare's view is read again when +/// it's older than 30 seconds. #[utoipa::path(get, path = "/clusters/{id}/tunnel", operation_id = "getClusterTunnel", tag = "Clusters", params(("id" = String, Path, description = "The cluster's id (`cl_…`).")), responses( @@ -605,6 +606,10 @@ pub async fn get( let mut tx = crate::rls::begin(&s.db, &user).await?; let team_id = team_of(&mut tx, "clusters", &id).await?; require_role(&mut tx, &user, &team_id, Role::Viewer).await?; + tx.commit().await?; + // Cloudflare's view as of now (at most 30 seconds old). + super::tunnel_loop::refresh(&s, &id).await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; let traffic: String = sqlx::query_scalar("SELECT traffic FROM pyo.clusters WHERE id = $1") .bind(&id) .fetch_one(&mut *tx) diff --git a/crates/pyo-api/src/compose.rs b/crates/pyo-api/src/compose.rs index 29944432..eb8c26ce 100644 --- a/crates/pyo-api/src/compose.rs +++ b/crates/pyo-api/src/compose.rs @@ -1658,7 +1658,8 @@ pub async fn preview( use crate::error::ApiError; let mut tx = s.db.begin().await?; crate::ops::require_role(&mut tx, &user, &b.team_id, crate::ops::Role::Viewer).await?; - // Free domains go on the cluster's public address (none without one). + // Free domains go on the cluster's free-domain address, or in tunnel + // mode under its default domain (none without either). let domain_base = match &b.cluster_id { Some(id) => { sqlx::query_scalar::<_, String>( @@ -1669,9 +1670,7 @@ pub async fn preview( .fetch_optional(&mut *tx) .await? .ok_or_else(|| ApiError::not_found("Cluster"))?; - crate::freedomain::for_cluster(&mut tx, id) - .await? - .map(|ip| format!("{ip}.nip.io")) + crate::freedomain::suffix_for(&mut tx, id).await? } None => None, }; diff --git a/crates/pyo-api/src/domainproof.rs b/crates/pyo-api/src/domainproof.rs index 9e38879e..649787eb 100644 --- a/crates/pyo-api/src/domainproof.rs +++ b/crates/pyo-api/src/domainproof.rs @@ -252,6 +252,49 @@ async fn own_free_domain( Ok(Some(false)) } +/// Not proven yet: the team's Cloudflare writes the record when it can +/// (cloudflare.rs `write_proof`), and it's read again for a few seconds +/// while Cloudflare's name servers take it. +async fn prove_with_cloudflare( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + host: &str, +) -> bool { + match crate::cloudflare::write_proof(tx, team_id, host).await { + Ok(true) => {} + Ok(false) => return false, + Err(e) => { + tracing::info!(%host, error = ?e.message, "domain proof: Cloudflare didn't write it"); + return false; + } + } + for _ in 0..5 { + if proven(team_id, host).await { + return true; + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + false +} + +/// One label under the default domain of a Cloudflare Tunnel of the +/// team's (Pyo Cloud: the zone is the team's, its token edits it). +async fn own_tunnel_domain( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + host: &str, +) -> ApiResult { + let domains: Vec = sqlx::query_scalar( + "SELECT default_domain FROM pyo.cluster_tunnels WHERE team_id = $1 AND default_domain IS NOT NULL AND state <> 'removing'", + ) + .bind(team_id) + .fetch_all(&mut **tx) + .await?; + Ok(domains + .iter() + .any(|d| crate::cloudflare::tunnel_loop::under_default(host, d))) +} + /// Checks the hostnames a service is about to claim, and takes over any /// another team holds without proof. `new_hosts`: the ones it doesn't /// have yet (the ones it has stay, proven when they were claimed). @@ -267,6 +310,11 @@ pub async fn check_claims( if pyo_proto::system::is_tailnet_host(host) { continue; } + // A free name under one of the team's own tunnels' default + // domains: a zone its Cloudflare token was checked to control. + if own_tunnel_domain(tx, team_id, host).await? { + continue; + } match own_free_domain(tx, team_id, host).await? { Some(true) => continue, Some(false) => { @@ -276,7 +324,7 @@ pub async fn check_claims( } None => {} } - if !proven(team_id, host).await { + if !proven(team_id, host).await && !prove_with_cloudflare(tx, team_id, host).await { return Err(ApiError::forbidden(how_to(team_id, host))); } // Held by another team: theirs while they can still prove it. diff --git a/crates/pyo-api/src/freedomain.rs b/crates/pyo-api/src/freedomain.rs index 1accf9ac..6c634fb5 100644 --- a/crates/pyo-api/src/freedomain.rs +++ b/crates/pyo-api/src/freedomain.rs @@ -69,6 +69,10 @@ pub fn tailnet_v4(ip: &str) -> Option { pub enum Mode { Public, Tailscale, + /// Through the cluster's Cloudflare Tunnel: names under its default + /// domain (`-.example.com`), none without one. + /// From the cluster's traffic, never chosen as an address. + Tunnel, } impl Mode { @@ -84,6 +88,7 @@ impl Mode { match self { Mode::Public => "public", Mode::Tailscale => "tailscale", + Mode::Tunnel => "tunnel", } } } @@ -104,6 +109,10 @@ pub struct Cluster { /// issued the dashboard's certificate there): on the cluster Pyo runs /// on (publicdash.rs `reached`). pub reached: Option, + /// In tunnel mode (its traffic is "tunnel"). + pub tunnel: bool, + /// Its tunnel's default domain, when it has one. + pub tunnel_domain: Option, } /// Servers that take public traffic, ready ones first. @@ -198,6 +207,7 @@ impl Cluster { return None; } match (self.mode(), self.set.as_deref()) { + (Mode::Tunnel, _) => None, (Mode::Public, _) => self.public_ip(), (Mode::Tailscale, None) => self.cloud_ip(), (Mode::Tailscale, Some(_)) => None, @@ -223,6 +233,9 @@ impl Cluster { /// traffic and the internet reaches its public IP directly, else /// Tailscale. pub fn mode(&self) -> Mode { + if self.tunnel { + return Mode::Tunnel; + } self.set .as_deref() .and_then(Mode::parse) @@ -238,9 +251,21 @@ impl Cluster { match self.mode() { Mode::Public => self.public_ip(), Mode::Tailscale => self.tailnet_ip(), + Mode::Tunnel => None, + } + } + + /// What free domains end in now: "203.0.113.7.nip.io", or in tunnel + /// mode the tunnel's default domain ("example.com"). None: no free + /// domain (no address, or tunnel mode without a default domain). + pub fn suffix(&self) -> Option { + match self.mode() { + Mode::Tunnel => self.tunnel_domain.clone(), + _ => self.address().map(|ip| format!("{ip}.nip.io")), } } + /// Where a free domain on `ip` belongs now. One on a public address /// stays on the public IP (chosen when it was added: the dashboard's /// "Free domain"), while the cluster has one. Any other (Tailscale, @@ -275,6 +300,9 @@ impl Cluster { "tailnetIp": s(self.tailnet_ip()), "freeDomainAddress": self.mode().as_str(), "freeDomainIp": s(self.address()), + // What free domains end in ("203.0.113.7.nip.io", or the + // tunnel's default domain): null for none. + "freeDomainSuffix": self.suffix(), "behindNat": self.behind_nat(), }) } @@ -283,8 +311,13 @@ impl Cluster { /// "nginx-web.203.0.113.7.nip.io": the label at most 63 characters, so the /// whole name stays well within 253. pub fn hostname(service: &str, namespace: &str, ip: Ipv4Addr) -> String { + format!("{}.{ip}.nip.io", label(service, namespace)) +} + +/// A free domain's label: "nginx-web", at most 63 characters. +fn label(service: &str, namespace: &str) -> String { let label: String = format!("{service}-{namespace}").chars().take(63).collect(); - format!("{}.{ip}.nip.io", label.trim_end_matches('-')) + label.trim_end_matches('-').to_owned() } /// A free domain's parts: its label(s), address, and whether it's in the @@ -368,13 +401,16 @@ pub async fn load( tx: &mut Transaction<'_, Postgres>, cluster_id: &str, ) -> ApiResult> { - let row: Option<(String, bool, Option, Value, bool)> = sqlx::query_as( - "SELECT team_id, public_traffic, free_domain_address, capabilities, same_cluster FROM pyo.clusters WHERE id = $1", + let row: Option<(String, bool, Option, Value, bool, bool, Option)> = sqlx::query_as( + "SELECT c.team_id, c.public_traffic, c.free_domain_address, c.capabilities, c.same_cluster, + c.traffic = 'tunnel', t.default_domain + FROM pyo.clusters c LEFT JOIN pyo.cluster_tunnels t ON t.cluster_id = c.id AND t.state <> 'removing' + WHERE c.id = $1", ) .bind(cluster_id) .fetch_optional(&mut **tx) .await?; - let Some((team_id, public_traffic, set, caps, same_cluster)) = row else { + let Some((team_id, public_traffic, set, caps, same_cluster, tunnel, tunnel_domain)) = row else { return Ok(None); }; let servers: Vec = @@ -395,10 +431,20 @@ pub async fn load( } else { None }, + tunnel, + tunnel_domain, }, ))) } +/// What a cluster's free domains end in now ([`Cluster::suffix`]). +pub async fn suffix_for( + tx: &mut Transaction<'_, Postgres>, + cluster_id: &str, +) -> ApiResult> { + Ok(load(tx, cluster_id).await?.and_then(|(_, c)| c.suffix())) +} + /// A cluster's free-domain address now. pub async fn for_cluster( tx: &mut Transaction<'_, Postgres>, @@ -577,6 +623,7 @@ mod tests { tailnet_web: vec![], servers, reached: None, + ..Default::default() } } @@ -586,6 +633,35 @@ mod tests { "publicIpv4": "203.0.113.7", "nicPublicIps": ["203.0.113.7"], "tailnetIp": "100.64.0.9" }) } + /// In tunnel mode, free domains go under the tunnel's default domain + /// (its wildcard), and there's none without one. nip.io names stay + /// where they are (they stop answering until public ports are back). + #[test] + fn tunnel_mode_names_free_domains_under_the_default_domain() { + let mut c = cluster(false, None, vec![direct_server()]); + c.tunnel = true; + c.tunnel_domain = Some("example.com".into()); + assert_eq!(c.mode(), Mode::Tunnel); + assert_eq!(c.address(), None); + assert_eq!(c.suffix().as_deref(), Some("example.com")); + assert_eq!( + format!("{}.{}", label("web", "shop"), c.suffix().unwrap()), + "web-shop.example.com" + ); + assert_eq!(c.shown()["freeDomainAddress"], "tunnel"); + assert_eq!(c.shown()["freeDomainSuffix"], "example.com"); + // A nip.io domain from before stays put. + assert_eq!(moved("web-shop.203.0.113.7.nip.io", &c.known(), |ip| c.home(ip)), None); + c.tunnel_domain = None; + assert_eq!(c.suffix(), None); + + // Public ports again: the nip.io names answer as they were. + let c = cluster(true, None, vec![direct_server()]); + assert_eq!(c.suffix().as_deref(), Some("203.0.113.7.nip.io")); + assert_eq!(hostname("web", "shop", v4("203.0.113.7")), "web-shop.203.0.113.7.nip.io"); + assert_eq!(Mode::parse("tunnel"), None, "never chosen as an address"); + } + #[test] fn public_mode_uses_the_public_address_never_a_private_one() { let c = cluster(true, Some("public"), vec![nat_server()]); @@ -675,7 +751,7 @@ mod tests { assert_eq!( c.shown(), json!({ "publicIp": "129.226.158.31", "tailnetIp": "100.101.67.2", "freeDomainAddress": "tailscale", - "freeDomainIp": "100.101.67.2", "behindNat": true }) + "freeDomainIp": "100.101.67.2", "freeDomainSuffix": "100.101.67.2.nip.io", "behindNat": true }) ); // Public can still be chosen there. let c = cluster(true, Some("public"), vec![nat_server()]); diff --git a/crates/pyo-api/src/mcp.rs b/crates/pyo-api/src/mcp.rs index add281a0..337a15d6 100644 --- a/crates/pyo-api/src/mcp.rs +++ b/crates/pyo-api/src/mcp.rs @@ -1580,6 +1580,14 @@ fn cluster_at(snap: &Value, team: &str, place: &str) -> Result<(Value, String), /// "nginx-web.203.0.113.7.nip.io": resolves to the cluster's free-domain /// address (its public or Tailscale IP, as its settings say). fn free_hostname(cluster: &Value, service: &str, namespace: &str) -> Result { + // In tunnel mode, under its default domain (the tunnel's wildcard). + if cluster["traffic"] == json!("tunnel") { + let suffix = cluster["freeDomainSuffix"].as_str().ok_or( + "The cluster's Cloudflare Tunnel has no default domain, so there's no free domain for it. Pick a default domain first, or use a custom hostname.", + )?; + let label: String = format!("{service}-{namespace}").chars().take(63).collect(); + return Ok(format!("{}.{suffix}", label.trim_end_matches('-'))); + } let ip = cluster["freeDomainIp"] .as_str() .and_then(|ip| ip.parse().ok()) diff --git a/crates/pyo-api/src/ops.rs b/crates/pyo-api/src/ops.rs index 86f0ab4a..a0493934 100644 --- a/crates/pyo-api/src/ops.rs +++ b/crates/pyo-api/src/ops.rs @@ -4831,6 +4831,10 @@ async fn apply( crate::freedomain::Mode::Tailscale => { format!("Free domains on {name} use its Tailscale IP") } + // Never parsed from an address: it follows the cluster's traffic. + crate::freedomain::Mode::Tunnel => { + format!("Free domains on {name} go through its Cloudflare Tunnel") + } }; log_activity( tx, diff --git a/crates/pyo-api/src/snapshot.rs b/crates/pyo-api/src/snapshot.rs index 568f4b06..a846e833 100644 --- a/crates/pyo-api/src/snapshot.rs +++ b/crates/pyo-api/src/snapshot.rs @@ -217,6 +217,8 @@ pub async fn build(db: &PgPool, user: &User, agent_api_url: &str) -> ApiResult ApiResult ApiResult { - let ip = cluster_ip(&t, "freeDomainIp").context("The cluster has no address for free domains (its public or Tailscale IP, as its settings say), so there's no free domain for it. Use your own hostname.")?; + let tunnel = cluster_ip(&t, "traffic").as_deref() == Some("tunnel"); + // Its public or Tailscale IP's nip.io name, or in tunnel mode a + // name under the tunnel's default domain. + let suffix = match cluster_ip(&t, "freeDomainSuffix") { + Some(s) => s, + None if tunnel => bail!("The cluster's Cloudflare Tunnel has no default domain, so there's no free domain for it. Pick a default domain first, or use your own hostname."), + None => { + let ip = cluster_ip(&t, "freeDomainIp").context("The cluster has no address for free domains (its public or Tailscale IP, as its settings say), so there's no free domain for it. Use your own hostname.")?; + format!("{ip}.nip.io") + } + }; let ns = t .state .project(s["projectId"].as_str().unwrap_or("")) @@ -276,7 +286,7 @@ pub async fn add( .chars() .take(63) .collect(); - format!("{}.{ip}.nip.io", label.trim_end_matches('-')) + format!("{}.{suffix}", label.trim_end_matches('-')) } None => bail!("Give a hostname, or --free for a free domain."), }; @@ -344,7 +354,20 @@ pub async fn add( let in_cloudflare = !is_free(&host) && crate::cloudflare::zone_for(&t.state.0, team_id, &host) .is_some_and(|z| z["canEdit"] == json!(true)); - let made = if in_cloudflare && dns.cloudflare { + // Through the cluster's Cloudflare Tunnel: Pyo makes the switch (the + // tunnel's wildcard already covers a free name under its default domain). + let tunnel = cluster_ip(&t, "traffic").as_deref() == Some("tunnel"); + let free_tunnel = tunnel + && cluster_ip(&t, "freeDomainSuffix") + .is_some_and(|s| host.strip_suffix(&format!(".{s}")).is_some_and(|l| !l.contains('.'))); + let made = if free_tunnel { + true + } else if tunnel && in_cloudflare && dns.cloudflare { + crate::cloudflare::domain_tunnel(api, Some(&t.id), &host, true, false, true) + .await + .map_err(|e| eprintln!("{}", ui::red(&e.to_string()))) + .is_ok() + } else if in_cloudflare && dns.cloudflare { crate::cloudflare::create_record(api, &t.id, &id, &host, dns.proxied, false) .await .map_err(|e| eprintln!("{}", ui::red(&e.to_string()))) From d135ff0d6bc66c4350a518d2f25ec0b2efb39090 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 19:00:15 +0700 Subject: [PATCH 050/139] feat(dash): free domains in tunnel mode and the wizard's tunnel switch The add-domain dialog, new-service wizard and onboarding name free domains under the tunnel's default domain in tunnel mode, and say to pick one without it. The wizard offers Through Cloudflare Tunnel like the add-domain dialog, on by default in tunnel mode. The switch's confirm counts free nip.io domains that stop answering. --- dash/src/components/pyo/AddDomainDialog.tsx | 32 +++++++++++++++++---- dash/src/components/pyo/Tunnel.tsx | 9 +++++- dash/src/components/pyo/wizard/steps.tsx | 22 ++++++++++---- dash/src/lib/pyo/draft.ts | 2 ++ dash/src/lib/pyo/freeDomain.ts | 22 ++++++++++++++ dash/src/lib/pyo/store.ts | 20 +++++++++---- dash/src/lib/pyo/types.ts | 4 ++- dash/src/routes/_app/$team/onboarding.tsx | 16 +++++++---- 8 files changed, 105 insertions(+), 22 deletions(-) diff --git a/dash/src/components/pyo/AddDomainDialog.tsx b/dash/src/components/pyo/AddDomainDialog.tsx index 54d0dd80..8f6fdc6c 100644 --- a/dash/src/components/pyo/AddDomainDialog.tsx +++ b/dash/src/components/pyo/AddDomainDialog.tsx @@ -27,6 +27,7 @@ import { import { HOSTNAME } from "~/lib/pyo/format"; import { clusterTailnet, + freeSuffix, hostnameUsed, unusedHostname, } from "~/lib/pyo/freeDomain"; @@ -91,19 +92,22 @@ export function AddDomainDialog({ const port = portName || httpPorts[0]?.name || ""; const cluster = s.clusters.find((c) => c.id === app?.clusterId); // Free domains go on the public IP, whatever the cluster's free domains - // use by default: traffic goes straight to its servers. + // use by default: traffic goes straight to its servers. In tunnel mode, + // under the tunnel's default domain. + const tunnelMode = cluster?.traffic === "tunnel"; const freeIp = cluster?.publicIp ?? undefined; + const freeEnd = app ? freeSuffix(s, app.clusterId) : undefined; const tailnet = app ? clusterTailnet(s, app.clusterId) : undefined; const namespace = s.projects.find((p) => p.id === app?.projectId)?.namespace ?? "app"; // Picked, but the service's cluster has none: a note says why. const missing = !!app && - ((kind === "public" && !freeIp) || (kind === "tailnet" && !tailnet)); + ((kind === "public" && !freeEnd) || (kind === "tailnet" && !tailnet)); // No service yet: only your own domain, the free ones are named after it. const k: Kind = app ? kind : "own"; const suffix = - k === "public" ? `${freeIp}.nip.io` : k === "tailnet" ? tailnet : ""; + k === "public" ? freeEnd : k === "tailnet" ? tailnet : ""; const suggested = !app || k === "own" || missing ? "" @@ -248,7 +252,13 @@ export function AddDomainDialog({ /> { @@ -279,6 +289,16 @@ export function AddDomainDialog({ ) + ) : tunnelMode ? ( + <> + Pick a default domain first.{" "} + + Cluster settings + + ) : cluster.publicTraffic === false ? ( <> Public traffic is off on {cluster.name}.{" "} @@ -301,7 +321,9 @@ export function AddDomainDialog({ error={touched ? error || undefined : undefined} hint={ k === "public" - ? cluster?.behindNat + ? tunnelMode + ? "Through Cloudflare Tunnel. No DNS needed." + : cluster?.behindNat ? `Points at ${freeIp}. Forward ports 80 and 443 to the server.` : `Points at ${freeIp}. No DNS needed.` : k === "tailnet" diff --git a/dash/src/components/pyo/Tunnel.tsx b/dash/src/components/pyo/Tunnel.tsx index 0e8a1397..d305b4d1 100644 --- a/dash/src/components/pyo/Tunnel.tsx +++ b/dash/src/components/pyo/Tunnel.tsx @@ -158,7 +158,9 @@ export function TunnelSettings({ return z?.tunnel?.ready && z.accountId === account ? z.name : undefined; }; const moving = [...new Set(domains.map((d) => zoneOf(d.hostname)).filter((z): z is string => !!z))]; - const outside = domains.filter((d) => !zoneOf(d.hostname)).length; + // Free nip.io domains: no public ports, so they stop answering too. + const nip = domains.filter((d) => /\.nip\.io$/i.test(d.hostname)).length; + const outside = domains.filter((d) => !zoneOf(d.hostname) && !/\.nip\.io$/i.test(d.hostname)).length; const lines = [ moving.length ? `Websites on ${list(moving)} move to the tunnel. Records Pyo didn't make wait for your OK.` @@ -168,6 +170,11 @@ export function TunnelSettings({ : outside ? `${outside} domains aren't in your Cloudflare account. They stop answering from the internet.` : null, + nip === 1 + ? "1 free domain stops answering from the internet." + : nip + ? `${nip} free domains stop answering from the internet.` + : null, c.sameCluster ? "The public dashboard closes. Open Pyo through Tailscale or your local network." : null, diff --git a/dash/src/components/pyo/wizard/steps.tsx b/dash/src/components/pyo/wizard/steps.tsx index ba05d814..374b2b15 100644 --- a/dash/src/components/pyo/wizard/steps.tsx +++ b/dash/src/components/pyo/wizard/steps.tsx @@ -31,7 +31,8 @@ import { locationLabel, parseLocation, placesOf } from "~/lib/pyo/location"; import { Flag } from "~/components/ui/Flag"; import { clusterTailnet, - freeHostname, + freeHostnameIn, + freeSuffix, isFreeDomain, isTailnetDomain, noFreeDomain, @@ -70,6 +71,8 @@ import { } from "~/lib/pyo/draft"; import { cloudflareZoneFor, + clusterTraffic, + tunnelZoneFor, clusterSummary, clustersIn, draftProject, @@ -1182,12 +1185,17 @@ export function DomainsStep({ d, set, errors }: StepProps) { // A connected Cloudflare zone covers it: Pyo creates its record. const cfFor = (host: string) => !!cloudflareZoneFor(s, host)?.canEdit && !!cluster?.publicIp; + // Through the cluster's tunnel: on by default in tunnel mode. + const tunnelOn = (dm: { hostname: string; tunnel?: boolean }) => + !!tunnelZoneFor(s, dm.hostname, cluster) && + (dm.tunnel ?? (!!cluster && clusterTraffic(cluster) === "tunnel")); const httpPorts = d.ports.filter((p) => p.protocol === "HTTP"); const project = draftProject(s, d); // Free domains go on the public IP: traffic goes straight to the servers. - const ip = cluster?.publicIp ?? undefined; - const free = ip - ? freeHostname({ name: d.name || "app" }, project?.namespace ?? "app", ip) + // In tunnel mode, under the tunnel's default domain. + const freeEnd = freeSuffix(s, d.clusterId); + const free = freeEnd + ? freeHostnameIn({ name: d.name || "app" }, project?.namespace ?? "app", freeEnd) : ""; const tailnet = d.clusterId ? clusterTailnet(s, d.clusterId) : undefined; const tailnetFree = tailnet @@ -1310,12 +1318,14 @@ export function DomainsStep({ d, set, errors }: StepProps) { - setD({ cloudflare: v.create, proxied: v.proxied }) + setD({ cloudflare: v.create, proxied: v.proxied, tunnel: v.tunnel }) } />
    @@ -1329,6 +1339,8 @@ export function DomainsStep({ d, set, errors }: StepProps) { "Only devices on your tailnet can open it." ) : freeOne ? ( "No DNS record needed." + ) : dm.hostname && tunnelOn(dm) ? ( + "Goes through Cloudflare Tunnel." ) : dm.hostname && dm.cloudflare !== false && cfFor(dm.hostname) ? ( diff --git a/dash/src/lib/pyo/draft.ts b/dash/src/lib/pyo/draft.ts index a712da51..d2af2bae 100644 --- a/dash/src/lib/pyo/draft.ts +++ b/dash/src/lib/pyo/draft.ts @@ -52,6 +52,8 @@ export type DraftDomain = { cloudflare?: boolean; /** Proxied by Cloudflare. */ proxied?: boolean; + /** Through the cluster's Cloudflare Tunnel (unset: on in tunnel mode). */ + tunnel?: boolean; }; export type DraftVolume = { id: string; diff --git a/dash/src/lib/pyo/freeDomain.ts b/dash/src/lib/pyo/freeDomain.ts index 008fa3c9..91cc3a26 100644 --- a/dash/src/lib/pyo/freeDomain.ts +++ b/dash/src/lib/pyo/freeDomain.ts @@ -72,11 +72,33 @@ export function freeDomainIp(s: PyoState, clusterId: string) { /** Why there's no free domain (on the public IP) on the cluster, in a few words. */ export function noFreeDomain(s: PyoState, clusterId: string) { const c = s.clusters.find((x) => x.id === clusterId); + if (c?.traffic === "tunnel") return "Pick a default domain first."; return c?.publicTraffic === false ? "Public traffic is off, so no free domain." : "No public IP yet, so no free domain."; } +/** + * What a cluster's free domains end in: "203.0.113.7.nip.io" on its public + * IP, or in tunnel mode its tunnel's default domain ("example.com"). None + * without either. + */ +export function freeSuffix(s: PyoState, clusterId: string | undefined) { + const c = s.clusters.find((x) => x.id === clusterId); + if (!c) return undefined; + if (c.traffic === "tunnel") return c.freeDomainSuffix ?? undefined; + return c.publicIp ? `${c.publicIp}.nip.io` : undefined; +} + +/** "hello-storefront.example.com": one label of at most 63 characters, then the suffix. */ +export function freeHostnameIn( + app: Pick, + namespace: string, + suffix: string, +) { + return `${`${app.name}-${namespace}`.slice(0, 63).replace(/-+$/, "")}.${suffix}`; +} + /** "hello-storefront.203.0.113.7.nip.io": one label of at most 63 characters, then the address. */ export function freeHostname( app: Pick, diff --git a/dash/src/lib/pyo/store.ts b/dash/src/lib/pyo/store.ts index f38c5136..d8a8da88 100644 --- a/dash/src/lib/pyo/store.ts +++ b/dash/src/lib/pyo/store.ts @@ -1762,7 +1762,7 @@ export const api = { const serviceId = newId("svc"); let deploymentId = ""; const volumes: Volume[] = []; - const dnsRecords: { domainId: string; proxied: boolean }[] = []; + const dnsRecords: { domainId: string; proxied: boolean; tunnel?: boolean }[] = []; // No project picked: create one named after the app, before the app itself. const fresh = draft.projectId === NEW_PROJECT @@ -1834,8 +1834,16 @@ export const api = { }); const domains: Domain[] = d.domains.map((x) => { const id = newId("dom"); - // On unless turned off, when a connected zone covers it. + // Through the cluster's Cloudflare Tunnel: on by default in tunnel mode. + const draftCluster = s.clusters.find((c) => c.id === d.clusterId); if ( + !d.cron && + tunnelZoneFor(s, x.hostname, draftCluster) && + (x.tunnel ?? (!!draftCluster && clusterTraffic(draftCluster) === "tunnel")) + ) + dnsRecords.push({ domainId: id, proxied: false, tunnel: true }); + // On unless turned off, when a connected zone covers it. + else if ( x.cloudflare !== false && !d.cron && cloudflareZoneFor(s, x.hostname, d.teamId)?.canEdit && @@ -1975,9 +1983,11 @@ export const api = { // Its DNS records in Cloudflare, once the service exists. if (made) for (const r of dnsRecords) - await api.createDnsRecord(serviceId, r.domainId, { - proxied: r.proxied, - }); + await (r.tunnel + ? api.setDomainTunnel(serviceId, r.domainId, { on: true }) + : api.createDnsRecord(serviceId, r.domainId, { + proxied: r.proxied, + })); return made; })(); return { serviceId, deploymentId, done }; diff --git a/dash/src/lib/pyo/types.ts b/dash/src/lib/pyo/types.ts index 899b7d59..b51b8028 100644 --- a/dash/src/lib/pyo/types.ts +++ b/dash/src/lib/pyo/types.ts @@ -421,11 +421,13 @@ export type Cluster = { /** Tailscale on this cluster (its agent keeps the client); null when not set up. */ tailscale?: ClusterTailscale | null; /** Where its free domains point, as chosen or by default. */ - freeDomainAddress?: FreeDomainAddress; + freeDomainAddress?: FreeDomainAddress | "tunnel"; /** As chosen in its settings; null: the default. */ freeDomainAddressSet?: FreeDomainAddress | null; /** The address its free domains point at now; null: no free domains. */ freeDomainIp?: string | null; + /** What its free domains end in ("203.0.113.7.nip.io", or the tunnel's default domain); null: none. */ + freeDomainSuffix?: string | null; /** Its public IP is only what the internet sees (no server has it): ports may not be forwarded. */ behindNat?: boolean; originPull?: { diff --git a/dash/src/routes/_app/$team/onboarding.tsx b/dash/src/routes/_app/$team/onboarding.tsx index 682b89a5..bdcb08d4 100644 --- a/dash/src/routes/_app/$team/onboarding.tsx +++ b/dash/src/routes/_app/$team/onboarding.tsx @@ -29,7 +29,7 @@ import { type DeployDraft, type Issues, } from "~/lib/pyo/draft"; -import { freeHostname, freeDomainIp, reachOf } from "~/lib/pyo/freeDomain"; +import { freeHostname, freeDomainIp, freeHostnameIn, reachOf } from "~/lib/pyo/freeDomain"; import { DNS_LABEL } from "~/lib/pyo/format"; import { currentSlug } from "~/lib/pyo/paths"; import { @@ -488,10 +488,16 @@ function DeployStep({ const ip = freeDomainIp(s, cluster.id); const reach = reachOf(s, cluster.id); const port = base.ports.find((p) => p.protocol === "HTTP"); - const host = - ip && port - ? freeHostname({ name: name || "app" }, project?.namespace ?? "app", ip) - : ""; + // In tunnel mode, under the tunnel's default domain. + const tunnelEnd = + cluster.traffic === "tunnel" ? (cluster.freeDomainSuffix ?? undefined) : undefined; + const host = !port + ? "" + : tunnelEnd + ? freeHostnameIn({ name: name || "app" }, project?.namespace ?? "app", tunnelEnd) + : ip + ? freeHostname({ name: name || "app" }, project?.namespace ?? "app", ip) + : ""; const onNetwork = !host && !!port && reach === "network"; const [busy, setBusy] = useState(false); From d8e1a16d324ec803c8fe269e2735ad1a84d8e157 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 19:00:59 +0700 Subject: [PATCH 051/139] test: check the tunnel's gate against a real envoy scripts/tunnel-gate-e2e.sh builds the Envoy config Envoy Gateway makes for a switched and a switching tunnel domain and checks real requests: direct clients refused once switched, the connector's visitor taken from X-Forwarded-For, the service's own rules on that visitor, the cf-visitor redirect, and both paths while a domain switches. --- scripts/tunnel-gate-e2e.sh | 205 +++++++++++++++++++++++++++++++++++++ 1 file changed, 205 insertions(+) create mode 100755 scripts/tunnel-gate-e2e.sh diff --git a/scripts/tunnel-gate-e2e.sh b/scripts/tunnel-gate-e2e.sh new file mode 100755 index 00000000..1c2ed18a --- /dev/null +++ b/scripts/tunnel-gate-e2e.sh @@ -0,0 +1,205 @@ +#!/usr/bin/env bash +# Checks Cloudflare Tunnel's routes against a real Envoy, the version +# Envoy Gateway runs (system.rs ENVOY_GATEWAY_VERSION's default proxy image). +# +# A tunnel domain's listener reads the visitor from X-Forwarded-For only on +# connections from the tunnel's connectors, cloudflared's pods (gateway.rs, +# the "tunnel" client policy with their addresses). While its record moves +# ("switching") anyone gets through as themselves. Once it's switched +# ("on") the firewall's behind gate (firewall.rs `BEHIND_GATE_CEL`) goes +# first, so only the connectors' requests do, and a request Cloudflare took +# over plain HTTP (`cf-visitor: {"scheme":"http"}`) goes to HTTPS +# (gateway.rs `tunnel_redirect_rule`). This builds the same Envoy config +# Envoy Gateway does for that and checks, with real connections: +# +# - switched: a direct client is refused, whatever X-Forwarded-For or +# CF-Connecting-IP it sends; +# - switched: the connector's visitor gets in as themselves, the last +# address the connector appended, not one the visitor made up; +# - the service's own rules apply to that visitor; +# - a plain-HTTP visitor at Cloudflare is sent to HTTPS; +# - switching: a direct client gets through as itself, and can't pick +# its address with X-Forwarded-For. +# +# TLS is left out (plain HTTP to the listener): only the visitor and the +# gate are checked here. +# +# Run it after every Envoy Gateway upgrade: ./scripts/tunnel-gate-e2e.sh +# Needs docker. Leaves nothing behind. +set -euo pipefail + +ENVOY_IMAGE="${ENVOY_IMAGE:-docker.io/envoyproxy/envoy:distroless-v1.39.5}" +CURL_IMAGE="${CURL_IMAGE:-docker.io/curlimages/curl:8.17.0}" +NET="pyo-tunnel-gate-$$" +SUBNET="172.30.$((RANDOM % 200 + 20)).0/24" +PREFIX="${SUBNET%.0/24}" +ENVOY_IP="$PREFIX.2" +CONNECTOR_IP="$PREFIX.10" # stands in for a cloudflared pod +DIRECT_IP="$PREFIX.20" # another pod, or a visitor reaching the server +DIR="$(mktemp -d)" + +cleanup() { + docker rm -f "$NET-envoy" >/dev/null 2>&1 || true + docker network rm "$NET" >/dev/null 2>&1 || true + rm -rf "$DIR" +} +trap cleanup EXIT + +# The gate (firewall.rs behind_gate_rule: source.port != 0, as Envoy +# Gateway parses it) and a service's own rule (block 198.51.100.0/24), as +# an RBAC matcher list. Switched routes get the gate first, switching ones +# only the service's own rule. +rbac() { + local gate="$1" + cat <"$DIR/envoy.yaml" </dev/null +docker run -d --name "$NET-envoy" --network "$NET" --ip "$ENVOY_IP" \ + -v "$DIR/envoy.yaml:/etc/envoy/envoy.yaml:ro" "$ENVOY_IMAGE" \ + -c /etc/envoy/envoy.yaml --log-level warn >/dev/null + +# From an address, for a host: " ". +ask() { + local from="$1" host="$2" + shift 2 + docker run --rm --network "$NET" --ip "$from" "$CURL_IMAGE" -s -o /dev/null \ + -w '%{http_code} %header{x-visitor}%header{location}' -H "Host: $host" "$@" "http://$ENVOY_IP:10443/" +} + +for _ in $(seq 1 30); do + if [ "$(ask "$DIRECT_IP" moving.example.com | cut -d' ' -f1)" = 200 ]; then break; fi + sleep 1 +done + +fail=0 +check() { + local what="$1" want="$2" got="$3" + if [[ "$got" == $want ]]; then + echo "ok $what ($got)" + else + echo "FAIL $what: want $want, got $got" + fail=1 + fi +} + +check "switched: a direct client is refused" "403*" "$(ask "$DIRECT_IP" done.example.com)" +check "switched: a direct client naming a visitor is refused" "403*" \ + "$(ask "$DIRECT_IP" done.example.com -H 'X-Forwarded-For: 203.0.113.9')" +check "switched: a direct client sending CF-Connecting-IP is refused" "403*" \ + "$(ask "$DIRECT_IP" done.example.com -H 'CF-Connecting-IP: 203.0.113.9')" +check "switched: the connector's visitor gets in as themselves" "200 203.0.113.9" \ + "$(ask "$CONNECTOR_IP" done.example.com -H 'X-Forwarded-For: 203.0.113.9')" +check "switched: a visitor's own X-Forwarded-For doesn't count" "200 203.0.113.9" \ + "$(ask "$CONNECTOR_IP" done.example.com -H 'X-Forwarded-For: 10.9.9.9, 203.0.113.9')" +check "switched: the service's rules see the connector's visitor" "403*" \ + "$(ask "$CONNECTOR_IP" done.example.com -H 'X-Forwarded-For: 198.51.100.7')" +check "switched: plain HTTP at Cloudflare goes to HTTPS" "301 https://done.example.com/" \ + "$(ask "$CONNECTOR_IP" done.example.com -H 'X-Forwarded-For: 203.0.113.9' -H 'cf-visitor: {"scheme":"http"}')" +check "switched: HTTPS at Cloudflare isn't redirected" "200*" \ + "$(ask "$CONNECTOR_IP" done.example.com -H 'X-Forwarded-For: 203.0.113.9' -H 'cf-visitor: {"scheme":"https"}')" +check "switching: a direct client gets through as itself" "200 $DIRECT_IP" \ + "$(ask "$DIRECT_IP" moving.example.com)" +check "switching: a direct client can't pick its address" "200 $DIRECT_IP" \ + "$(ask "$DIRECT_IP" moving.example.com -H 'X-Forwarded-For: 203.0.113.9')" +check "switching: the connector's visitor gets in as themselves" "200 203.0.113.9" \ + "$(ask "$CONNECTOR_IP" moving.example.com -H 'X-Forwarded-For: 203.0.113.9')" + +exit "$fail" From 031bfe881971ec102b1633abfc8f3a80653f413a Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 19:03:00 +0700 Subject: [PATCH 052/139] docs: update the tunnel build status after phase 6 --- docs/cloudflare-tunnel.md | 45 ++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 24 deletions(-) diff --git a/docs/cloudflare-tunnel.md b/docs/cloudflare-tunnel.md index 86d3e56d..e4021c53 100644 --- a/docs/cloudflare-tunnel.md +++ b/docs/cloudflare-tunnel.md @@ -1580,10 +1580,10 @@ Not merged into `dev` until the feature is complete and tested. | Decisions applied to this spec | Done (b145440, 5284a70, bf1cc78) | | 1. Token and zones | Done, tested (e3d91dd api, adc8e62 cli, 12cf81f dash) | | 2. Agent and Gateway | Done, tested (eadce05 proto, 4db8b6f agent) | -| 3. Control plane | Done, unit tested (3b9ae43): migration 0040, tunnel_loop.rs, heartbeat and snapshot. No database test yet | +| 3. Control plane | Done (3b9ae43): migration 0040, tunnel_loop.rs, heartbeat and snapshot. Unit tested, and end to end against the fake Cloudflare and a throwaway Postgres in CI | | 4. Traffic choice, switching | API, MCP and CLI written (3b9ae43, a47f92e). Dashboard merged (06dfbba, `tsc` passes): Traffic panel, tunnel badge, record line, add and remove domain | | 5. Ports, connect.sh, alerts | Public ports Service and tunnel alerts written. connect.sh keeps its line (see Decisions) | -| 6. Docs, e2e, real-zone test, Pyo Ops | Not started (real zone and Pyo Ops need the user) | +| 6. Docs, e2e, gaps, free domains | Done except the real-zone test and Pyo Ops (both need the user): fake Cloudflare and the loop test (0394f36), gaps and free domains (e36141e, d135ff0), gate e2e written, not run (d8e1a16), pyo-docs branch `docs/cloudflare-tunnel` (011a38f, ec36fd2) | Where things are: @@ -1608,31 +1608,28 @@ CLI tunnel tests pass on it. Next: -1. Regenerate pyo-docs' `openapi/pyo.json` with the Phase 6 docs. -2. Dashboard gaps: the new-service wizard has no tunnel switch, no - warning for deeper names (a.b.example.com), and "Certificate: - " shows only through `tunnel.error`. -3. A DATABASE_URL test (ignored by default, like install.rs's) for the - migration and the ops: traffic switch, switch and revert rows, - removeCloudflare refused. -4. Phase 6: pyo-docs pages, `scripts/tunnel-gate-e2e.sh`, - `scripts/fake-cloudflare/` with `PYO_DEV_CLOUDFLARE_API`. +1. Final `cargo clippy -D warnings` and the full suites on the Phase 6 + commits (waiting for disk above 60 GB). +2. With the user's OK: run `scripts/tunnel-gate-e2e.sh` (docker), and the + real-zone test (§17.4) on a throwaway zone. +3. After 0.51.0 merges: regenerate pyo-docs' generated pages, merge + pyo-docs' `docs/cloudflare-tunnel`, then the Pyo Ops move (§14). +4. Dashboard: no warning for deeper names (a.b.example.com) when + switching, and "Certificate: " shows only through `tunnel.error`. Known gaps: -- Free domains in tunnel mode (`freedomain::Mode::Tunnel`, - `-.`) aren't built. The default - domain's wildcard record and route are. -- `GET /clusters/{id}/tunnel` returns the stored view (Cloudflare is read - every 2 minutes), not a fresh read. -- A service deleted while its domain goes through the tunnel leaves its - CNAME (its dns_records row cascades away before the loop sees it). -- Pyo Cloud's domain proof TXT (`_pyo-verify`) isn't written by Switch to - Tunnel. Domains were verified when added. -- A domain moved between clusters isn't removed from the other tunnel - first. -- The cluster-delete op doesn't wait for tunnel removal (§11). - Nothing tested against a real Cloudflare account (needs the user's - approval and a throwaway zone). + approval and a throwaway zone, §17.4). +- `scripts/tunnel-gate-e2e.sh` is written but not run: it needs docker + (pulls `envoyproxy/envoy:distroless-v1.39.5` and `curlimages/curl`). +- The loop's end-to-end test (`cloudflare::http_tests::the_tunnel_loop_end_to_end`) + needs a throwaway Postgres: CI runs it (ci.yml's Postgres job), it + wasn't run on the laptop. +- pyo-docs' generated pages (`openapi/pyo.json`, `content/cli/commands.mdx`, + `content/mcp/tools.mdx`) are regenerated once all 0.51.0 branches are + merged. `openapi::tests::docs_copy_is_current` stays red until then. +- Previews in tunnel mode still name preview domains from the cluster's + address (§11 says under the default domain). - `dash/node_modules` in the worktrees is a symlink to the main checkout's, for `tsc` only (ignored by git). From 5125840609ab8b4e996b29979a8db15dca551f02 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 19:06:11 +0700 Subject: [PATCH 053/139] feat(api): read x-pyo service settings in compose import Each Compose service's x-pyo can now set domains, behindCdn, health, replicas, placement and secrets (names only, values stay in Pyo). The plan says which settings the file sets, and imported services remember the file and their Compose name for a later sync. The keys templates use (workload, gpu, expose) are left alone, and a test runs every pyo-templates template through the parser to check they import as before. --- crates/pyo-api/src/compose.rs | 590 ++++++++++++++++++++-- crates/pyo-api/src/ops.rs | 37 ++ crates/pyo-api/src/platform_import/mod.rs | 2 + 3 files changed, 593 insertions(+), 36 deletions(-) diff --git a/crates/pyo-api/src/compose.rs b/crates/pyo-api/src/compose.rs index 29944432..9bc35bf3 100644 --- a/crates/pyo-api/src/compose.rs +++ b/crates/pyo-api/src/compose.rs @@ -73,6 +73,10 @@ pub struct PlanProject { pub name: String, /// Its slug, used in service addresses: lowercase letters, digits and dashes. pub namespace: String, + /// The Compose file's name, e.g. "compose.yaml". Its services remember + /// it, so a later sync finds them. + #[serde(default)] + pub file: String, } #[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema)] @@ -94,6 +98,34 @@ pub struct PlanService { pub container: pyo_proto::ContainerOverrides, /// Services it starts after. pub depends_on: Vec, + /// What the file sets, which a sync keeps in line with it: "source", + /// "env", "ports", "volumes", "health", "replicas", "resources.cpuLimit" + /// and the other resources, "container.command" and the other container + /// settings, and the `x-pyo` ones ("domains", "behindCdn", "placement", + /// "secrets"). The rest stays as it is in Pyo. + #[serde(default)] + pub managed: Vec, + /// `x-pyo.domains`: served on its first web port. + #[serde(default)] + pub domains: Vec, + /// `x-pyo.behindCdn`: "cloudflare", or none. + #[serde(default)] + pub behind_cdn: Option, + /// `x-pyo.placement`: `{"servers": [...], "tags": [...]}`. + #[serde(default)] + #[schema(value_type = Option)] + pub placement: Option, + /// `x-pyo.secrets`: secret variables it needs, by name. Their values + /// are set in Pyo, never in the file. + #[serde(default)] + pub secrets: Vec, +} + +impl PlanService { + /// Whether the file sets this (see `managed`). + pub fn manages(&self, field: &str) -> bool { + self.managed.iter().any(|m| m == field) + } } #[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema)] @@ -722,6 +754,174 @@ const UNSUPPORTED: &[(&str, &str)] = &[ ("oom_score_adj", "Out-of-memory priority isn't changed."), ]; +/// Service keys of `x-pyo` that templates use (pyo-templates' schema.json). +/// The template catalog reads them, so an import leaves them alone. +const TEMPLATE_KEYS: [&str; 3] = ["workload", "gpu", "expose"]; + +/// A service's own `x-pyo`: the settings Compose has no field for. +#[derive(Default)] +struct XPyo { + domains: Vec, + /// Set: `Some(None)` takes it out of a CDN. + behind_cdn: Option>, + health: Option, + replicas: Option, + placement: Option, + secrets: Vec, +} + +/// Text, or a list of it. +fn texts(v: &Value) -> Option> { + match v { + Value::Null => Some(vec![]), + Value::String(s) => Some(vec![s.clone()]), + Value::Array(a) => a.iter().map(|x| x.as_str().map(str::to_owned)).collect(), + _ => None, + } +} + +fn env_name(k: &str) -> bool { + !k.is_empty() + && !k.as_bytes()[0].is_ascii_digit() + && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') +} + +fn x_pyo(v: Option<&Value>, sn: Option<&str>, w: &mut Warnings) -> XPyo { + let mut x = XPyo::default(); + let Some(v) = v.filter(|v| !v.is_null()) else { + return x; + }; + let Some(m) = v.as_object() else { + w.add( + sn, + "x-pyo", + "x-pyo holds Pyo's settings by name (domains, replicas…), so it's left out.", + ); + return x; + }; + for (k, v) in m { + let field = format!("x-pyo.{k}"); + match k.as_str() { + "domains" => match texts(v) { + Some(ds) => { + for d in ds { + let d = d.trim().trim_end_matches('.').to_lowercase(); + if d.is_empty() { + continue; + } + if !crate::util::hostname(&d) { + w.add( + sn, + &field, + format!("{d} isn't a domain like app.example.com, so it's left out."), + ); + } else if !x.domains.contains(&d) { + x.domains.push(d); + } + } + } + None => w.add( + sn, + &field, + "domains is a list like [app.example.com], so it's left out.", + ), + }, + "behindCdn" => match v { + Value::Null | Value::Bool(false) => x.behind_cdn = Some(None), + Value::String(c) if c == "none" => x.behind_cdn = Some(None), + Value::String(c) => match crate::firewall::check_behind(Some(c)) { + Ok(c) => x.behind_cdn = Some(c), + Err(_) => w.add( + sn, + &field, + format!("{c} isn't a CDN Pyo knows: use cloudflare or none."), + ), + }, + _ => w.add(sn, &field, "behindCdn is cloudflare or none."), + }, + "health" => match v.as_str() { + Some(h) if h == "tcp" || h == "none" || h.starts_with('/') => { + x.health = Some(h.to_owned()); + } + _ => w.add( + sn, + &field, + "health is a path like /healthz, or tcp or none, so it's left out.", + ), + }, + "replicas" => match v.as_i64().filter(|n| (0..=i64::from(i32::MAX)).contains(n)) { + Some(n) => x.replicas = Some(n as i32), + None => w.add(sn, &field, "replicas is a whole number, 0 or more."), + }, + "placement" => { + let Some(p) = v.as_object() else { + w.add( + sn, + &field, + "placement has servers or tags, like {tags: [eu]}, so it's left out.", + ); + continue; + }; + let mut out = json!({ "servers": [], "tags": [] }); + let mut ok = true; + for (pk, pv) in p { + let list = texts(pv); + match (pk.as_str(), list) { + ("servers", Some(l)) => out["servers"] = json!(l), + ("tags", Some(l)) => { + if let Some(bad) = + l.iter().find(|t| pyo_proto::valid_tag(t).is_none()) + { + w.add(sn, &field, format!("{bad} isn't a tag: tags are lowercase letters, digits and dashes. Placement is left out.")); + ok = false; + } + out["tags"] = json!(l); + } + _ => { + w.add( + sn, + &field, + format!("placement.{pk} isn't used: placement has servers and tags."), + ); + } + } + } + if ok { + x.placement = Some(out); + } + } + "secrets" => match texts(v) { + Some(names) => { + for n in names { + let n = n.trim().to_owned(); + if !env_name(&n) { + w.add( + sn, + &field, + format!("{n:?} isn't a variable name, so it's left out."), + ); + } else if !x.secrets.contains(&n) { + x.secrets.push(n); + } + } + } + None => w.add( + sn, + &field, + "secrets is a list of variable names, so it's left out.", + ), + }, + k if TEMPLATE_KEYS.contains(&k) => {} + _ => w.add( + sn, + &field, + format!("x-pyo.{k} isn't a Pyo setting, so it's left out."), + ), + } + } + x +} + /// The plan for a Compose file. pub fn plan(input: &Input) -> Result { let mut w = Warnings(vec![]); @@ -796,6 +996,11 @@ pub fn plan(input: &Input) -> Result { }, 40, ), + file: input + .repo + .as_ref() + .map(|r| r.path.clone()) + .unwrap_or_default(), }; // Names in Pyo, unique, and what changed. @@ -844,6 +1049,13 @@ pub fn plan(input: &Input) -> Result { w.add(sn, field, *why); } } + let x = x_pyo(svc.get("x-pyo"), sn, &mut w); + let present = |k: &str| { + svc.get(k).is_some_and(|v| { + !v.is_null() && v.as_array().is_none_or(|a| !a.is_empty()) + }) + }; + let mut managed: Vec = vec!["source".into(), "env".into()]; // Source: an image, or a build from the repository. let image = svc @@ -1122,8 +1334,36 @@ pub fn plan(input: &Input) -> Result { "No port is declared: if other services connect to it, add the port it listens on.", ); } + if present("ports") || present("expose") { + managed.push("ports".into()); + } + let mut domains = x.domains.clone(); + if !domains.is_empty() { + let web = ports + .iter() + .position(|p| p.public && p.protocol == "HTTP") + .or_else(|| ports.iter().position(|p| p.protocol == "HTTP")); + match web { + Some(i) => { + for p in &mut ports { + p.domain = None; + } + ports[i].public = true; + ports[i].domain = domains.first().cloned(); + managed.push("domains".into()); + if !managed.iter().any(|m| m == "ports") { + managed.push("ports".into()); + } + } + None => { + w.add(sn, "x-pyo.domains", "It has no web port to serve its domains on: add the port it listens on under ports or expose."); + domains.clear(); + } + } + } if ports.iter().any(|p| p.public && p.protocol == "HTTP") && input.domain_base.is_none() + && domains.is_empty() && first_http { first_http = false; @@ -1199,6 +1439,20 @@ pub fn plan(input: &Input) -> Result { } _ => {} } + // Secrets take no value from the file. + unset.retain(|k| !x.secrets.contains(k)); + let given: Vec = env + .iter() + .filter(|e| x.secrets.contains(&e.key) && !e.value.is_empty()) + .map(|e| e.key.clone()) + .collect(); + if !given.is_empty() { + w.add(sn, "x-pyo.secrets", format!("Secrets take their values from Pyo, not the file, so the file's {} isn't used.", given.join(", "))); + } + env.retain(|e| !x.secrets.contains(&e.key)); + if !x.secrets.is_empty() { + managed.push("secrets".into()); + } if !unset.is_empty() { w.add(sn, "environment", format!("Taken from the shell in Compose and not set here, so left out: {}. Add the ones it needs.", unset.join(", "))); } @@ -1279,6 +1533,10 @@ pub fn plan(input: &Input) -> Result { } } + if present("volumes") { + managed.push("volumes".into()); + } + // Health check. let first_port = ports.first().map(|p| p.container_port); let health = svc.get("healthcheck").and_then(Value::as_object); @@ -1319,7 +1577,7 @@ pub fn plan(input: &Input) -> Result { .and_then(|v| duration_secs(&scalar(v))) .unwrap_or(5) .clamp(0, 600); - let health_check = match (disabled, command, first_port) { + let mut health_check = match (disabled, command, first_port) { (false, Some(c), p) => { json!({ "type": "exec", "command": c, "path": "", "port": p.unwrap_or(0), "initialDelaySeconds": delay, "periodSeconds": period }) } @@ -1331,6 +1589,30 @@ pub fn plan(input: &Input) -> Result { } }; + if health.is_some() { + managed.push("health".into()); + if health.is_some_and(|h| h.contains_key("interval") || h.contains_key("start_period")) { + managed.push("healthTiming".into()); + } + } + if let Some(h) = &x.health { + let web = ports + .iter() + .find(|p| p.protocol == "HTTP") + .or(ports.first()) + .map(|p| p.container_port); + let kind = if h.starts_with('/') { "http" } else { h.as_str() }; + match (kind, web) { + ("none", _) | ("http" | "tcp", Some(_)) => { + health_check = json!({ "type": kind, "command": "", "path": if kind == "http" { h.as_str() } else { "" }, "port": if kind == "none" { 0 } else { web.unwrap_or(0) }, "initialDelaySeconds": delay, "periodSeconds": period }); + if !managed.iter().any(|m| m == "health") { + managed.push("health".into()); + } + } + _ => w.add(sn, "x-pyo.health", "It has no port to check: add the port it listens on under ports or expose."), + } + } + // Replicas and resources. let deploy = svc.get("deploy").and_then(Value::as_object); if deploy @@ -1353,12 +1635,16 @@ pub fn plan(input: &Input) -> Result { ); } } - let replicas = deploy + let compose_replicas = deploy .and_then(|d| d.get("replicas")) .and_then(Value::as_i64) - .or_else(|| svc.get("scale").and_then(Value::as_i64)) - .unwrap_or(1) - .clamp(0, i32::MAX as i64) as i32; + .or_else(|| svc.get("scale").and_then(Value::as_i64)); + if compose_replicas.is_some() || x.replicas.is_some() { + managed.push("replicas".into()); + } + let replicas = x.replicas.unwrap_or_else(|| { + compose_replicas.unwrap_or(1).clamp(0, i32::MAX as i64) as i32 + }); let limits = deploy .and_then(|d| d.get("resources")) .and_then(|r| r.get("limits")); @@ -1415,6 +1701,17 @@ pub fn plan(input: &Input) -> Result { } } } + for (k, set) in [ + ("resources.cpuLimit", cpu_limit.is_some()), + ("resources.memoryLimit", mem_limit.is_some()), + ("resources.cpuRequest", cpu_request.is_some()), + ("resources.memoryRequest", mem_request.is_some()), + ("resources.gpu", !gpu_devices.is_empty()), + ] { + if set { + managed.push(k.into()); + } + } let cpu_request = cpu_request.unwrap_or_else(|| cpu_limit.map(|l| l.min(100)).unwrap_or(100)); let memory_request = @@ -1449,6 +1746,23 @@ pub fn plan(input: &Input) -> Result { } } + for (k, field) in [ + ("entrypoint", "container.entrypoint"), + ("command", "container.command"), + ("working_dir", "container.workingDir"), + ("user", "container.user"), + ] { + if svc.get(k).is_some_and(|v| !v.is_null()) { + managed.push(field.into()); + } + } + if x.behind_cdn.is_some() { + managed.push("behindCdn".into()); + } + if x.placement.is_some() { + managed.push("placement".into()); + } + let depends_on: Vec = match svc.get("depends_on") { Some(Value::Array(a)) => a.iter().map(scalar).collect(), Some(Value::Object(m)) => m.keys().cloned().collect(), @@ -1478,6 +1792,11 @@ pub fn plan(input: &Input) -> Result { resources, container, depends_on: deps, + managed, + domains, + behind_cdn: x.behind_cdn.flatten(), + placement: x.placement, + secrets: x.secrets, }); } @@ -1529,9 +1848,49 @@ pub fn plan(input: &Input) -> Result { }) } +/// A plan port as a service's port. +pub fn port_json(p: &PlanPort, id: String) -> Value { + let exposure = exposure(p); + let mut v = json!({ "id": id, "name": p.name, "protocol": p.protocol, "containerPort": p.container_port, "exposure": exposure }); + if exposure == "loadbalancer" { + // Published TCP and UDP ports go through the gateway. + v["proxy"] = json!(true); + if let Some(pp) = p.public_port { + v["publicPort"] = json!(pp); + } + } + v +} + +/// "internal", "http" (a website) or "loadbalancer" (a public TCP or UDP port). +pub fn exposure(p: &PlanPort) -> &'static str { + match (p.public, p.protocol.as_str()) { + (false, _) => "internal", + (true, "HTTP") => "http", + (true, _) => "loadbalancer", + } +} + +/// A new domain of a service, on its port `port`. +pub fn domain_json(hostname: &str, port: &str, id: String, now: i64) -> Value { + let private = crate::deploy::private_host(hostname); + json!({ "id": id, "hostname": hostname, "portName": port, "status": "pending_dns", "tls": "pending", "tlsMode": "auto", "redirectHttps": !private, "createdAt": now }) +} + +/// What a service made from a Compose file remembers of it: the file, and +/// its name there. +pub fn record(file: &str, compose_name: &str) -> Value { + let file = file.trim(); + json!({ "file": if file.is_empty() { "compose.yaml" } else { file }, "service": compose_name }) +} + /// A plan service as the service object `createService` takes. +#[allow(clippy::too_many_arguments)] pub fn service_spec( s: &PlanService, + // The Compose file it's from, which it remembers. None for a service + // that isn't kept in line with a file (a platform import's). + file: Option<&str>, id: &str, team_id: &str, project_id: &str, @@ -1539,36 +1898,39 @@ pub fn service_spec( now: i64, new_id: &dyn Fn(&str) -> String, ) -> Value { - let env: Vec = s.env.iter().map(|e| json!({ "id": new_id("env"), "key": e.key, "value": e.value, "secret": e.secret, "updatedAt": now })).collect(); + let mut env: Vec = s.env.iter().map(|e| json!({ "id": new_id("env"), "key": e.key, "value": e.value, "secret": e.secret, "updatedAt": now })).collect(); + // Secrets it needs get their values in Pyo. + for k in &s.secrets { + if !s.env.iter().any(|e| &e.key == k) { + env.push(json!({ "id": new_id("env"), "key": k, "value": "", "secret": true, "updatedAt": now })); + } + } let ports: Vec = s .ports .iter() - .map(|p| { - let exposure = match (p.public, p.protocol.as_str()) { - (false, _) => "internal", - (true, "HTTP") => "http", - (true, _) => "loadbalancer", - }; - let mut v = json!({ "id": new_id("port"), "name": p.name, "protocol": p.protocol, "containerPort": p.container_port, "exposure": exposure }); - if exposure == "loadbalancer" { - // Published TCP and UDP ports go through the gateway. - v["proxy"] = json!(true); - if let Some(pp) = p.public_port { - v["publicPort"] = json!(pp); - } - } - v - }) + .map(|p| port_json(p, new_id("port"))) .collect(); - let domains: Vec = s - .ports + let mut hosts: Vec<(String, String)> = vec![]; + for p in s.ports.iter().filter(|p| p.public && p.protocol == "HTTP") { + if let Some(d) = p + .domain + .as_ref() + .map(|d| d.trim().to_lowercase()) + .filter(|d| !d.is_empty()) + { + hosts.push((d, p.name.clone())); + } + } + if let Some(web) = s.ports.iter().find(|p| p.public && p.protocol == "HTTP") { + for d in &s.domains { + if !hosts.iter().any(|(h, _)| h == d) { + hosts.push((d.clone(), web.name.clone())); + } + } + } + let domains: Vec = hosts .iter() - .filter(|p| p.public && p.protocol == "HTTP") - .filter_map(|p| p.domain.as_ref().filter(|d| !d.trim().is_empty()).map(|d| (p, d.trim().to_lowercase()))) - .map(|(p, d)| { - let private = crate::deploy::private_host(&d); - json!({ "id": new_id("dom"), "hostname": d, "portName": p.name, "status": "pending_dns", "tls": "pending", "tlsMode": "auto", "redirectHttps": !private, "createdAt": now }) - }) + .map(|(h, p)| domain_json(h, p, new_id("dom"), now)) .collect(); let source = if s.source.kind == "git" { json!({ @@ -1587,9 +1949,15 @@ pub fn service_spec( "resources": { "cpuRequest": s.resources.cpu_request, "cpuLimit": s.resources.cpu_limit, "memoryRequest": s.resources.memory_request, "memoryLimit": s.resources.memory_limit, "gpu": s.resources.gpu }, "replicas": s.replicas, "healthCheck": s.health_check, }); + if let Some(f) = file { + spec["compose"] = record(f, &s.compose_name); + } if !s.container.is_empty() { spec["container"] = serde_json::to_value(&s.container).unwrap_or(Value::Null); } + if let Some(p) = &s.placement { + spec["placement"] = p.clone(); + } spec } @@ -1622,9 +1990,13 @@ pub struct PreviewBody { /// The project's name, when the file has none. #[serde(default)] pub name: Option, + /// The file's name, e.g. "compose.yaml". Its services remember it, so a + /// later sync finds them. A repository's file is named by its path. + #[serde(default)] + pub file_name: Option, } -#[derive(Debug, Deserialize, utoipa::ToSchema)] +#[derive(Debug, Clone, Deserialize, utoipa::ToSchema)] #[serde(rename_all = "camelCase")] pub struct RepoInput { /// "owner/repo". @@ -1655,9 +2027,19 @@ pub async fn preview( crate::auth::SessionUser(user): crate::auth::SessionUser, crate::error::Json(b): crate::error::Json, ) -> crate::error::ApiResult> { + Ok(crate::error::Json(read_plan(&s, &user, &b).await?)) +} + +/// The plan of the file a preview or a sync names, for a team its user can +/// see. +pub(crate) async fn read_plan( + s: &crate::AppState, + user: &crate::auth::User, + b: &PreviewBody, +) -> crate::error::ApiResult { use crate::error::ApiError; let mut tx = s.db.begin().await?; - crate::ops::require_role(&mut tx, &user, &b.team_id, crate::ops::Role::Viewer).await?; + crate::ops::require_role(&mut tx, user, &b.team_id, crate::ops::Role::Viewer).await?; // Free domains go on the cluster's public address (none without one). let domain_base = match &b.cluster_id { Some(id) => { @@ -1693,7 +2075,7 @@ pub async fn preview( .trim_end_matches(".git") .to_owned(); let (text, installation) = - crate::github::read_file(&s, &b.team_id, &repo, &r.branch, &r.path) + crate::github::read_file(s, &b.team_id, &repo, &r.branch, &r.path) .await? .ok_or_else(|| ApiError::not_found(&format!("{} on {}", r.path, r.branch)))?; let dir = r @@ -1730,7 +2112,7 @@ pub async fn preview( wanted.dedup(); for f in wanted.into_iter().take(20) { if let Some((t, _)) = - crate::github::read_file(&s, &b.team_id, &repo, &r.branch, &near(&f)).await? + crate::github::read_file(s, &b.team_id, &repo, &r.branch, &near(&f)).await? { files.insert(f, t); } @@ -1761,7 +2143,7 @@ pub async fn preview( .clone() .filter(|n| !n.trim().is_empty()) .unwrap_or(hint); - let plan = plan(&Input { + let mut plan = plan(&Input { file: &text, files, repo, @@ -1769,7 +2151,16 @@ pub async fn preview( domain_base, }) .map_err(ApiError::bad_request)?; - Ok(crate::error::Json(plan)) + if let Some(f) = b + .file_name + .as_deref() + .map(str::trim) + .filter(|f| !f.is_empty()) + && plan.project.file.is_empty() + { + plan.project.file = f.chars().take(200).collect(); + } + Ok(plan) } #[cfg(test)] @@ -2183,4 +2574,131 @@ mod tests { .any(|e| e.key == "API_URL" && e.value == "http://api:8000") ); } + + #[test] + fn x_pyo_settings_and_their_mistakes() { + let file = r#" +services: + web: + image: nginx:1.27 + expose: ["80"] + x-pyo: + domains: [Shop.Example.com, "not a domain", shop.example.com] + behindCdn: fastly + health: healthz + replicas: -1 + placement: { tags: [Bad_Tag] } + secrets: [API_KEY, "1BAD"] + domain: oops + workload: StatefulSet + worker: + image: busybox + x-pyo: + domains: [w.example.com] + health: tcp + placement: { servers: [fal1], tags: [eu] } + behindCdn: none +"#; + let p = plan(&Input { + file, + name_hint: "shop", + ..Default::default() + }) + .unwrap(); + let web = svc(&p, "web"); + assert_eq!(web.domains, vec!["shop.example.com"]); + assert!(web.ports[0].public, "a domain makes its web port public"); + assert_eq!(web.secrets, vec!["API_KEY"]); + assert!(web.behind_cdn.is_none() && !web.manages("behindCdn")); + assert!(web.placement.is_none() && !web.manages("replicas")); + assert_eq!(web.health_check["type"], "tcp", "the default stays"); + for field in [ + "x-pyo.domains", + "x-pyo.behindCdn", + "x-pyo.health", + "x-pyo.replicas", + "x-pyo.placement", + "x-pyo.secrets", + "x-pyo.domain", + ] { + assert!(warned(&p, Some("web"), field), "{field}"); + } + assert!(!warned(&p, Some("web"), "x-pyo.workload"), "a template's key"); + let worker = svc(&p, "worker"); + assert!(worker.domains.is_empty(), "no web port to serve it on"); + assert!(warned(&p, Some("worker"), "x-pyo.domains")); + assert!(warned(&p, Some("worker"), "x-pyo.health"), "no port to check"); + assert_eq!( + worker.placement, + Some(json!({ "servers": ["fal1"], "tags": ["eu"] })) + ); + assert!(worker.manages("behindCdn") && worker.behind_cdn.is_none()); + } + + fn without_x_pyo(v: &mut Value) { + if let Some(m) = v.as_object_mut() { + m.remove("x-pyo"); + m.values_mut().for_each(without_x_pyo); + } + if let Some(a) = v.as_array_mut() { + a.iter_mut().for_each(without_x_pyo); + } + } + + /// The templates of pyo-templates (next to this repository, or at + /// PYO_TEMPLATES_DIR) import as they did before: their `x-pyo` is for + /// the template catalog, so it changes nothing here and warns about + /// nothing. + #[test] + fn every_template_imports_as_before() { + let dir = std::env::var_os("PYO_TEMPLATES_DIR") + .map(std::path::PathBuf::from) + .or_else(|| { + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .ancestors() + .map(|a| a.join("pyo-templates/templates")) + .find(|d| d.is_dir()) + }); + let Some(dir) = dir else { + eprintln!("pyo-templates isn't next to this repository, so no templates were read"); + return; + }; + let mut names: Vec<_> = std::fs::read_dir(&dir) + .unwrap() + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.join("compose.yaml").is_file()) + .collect(); + names.sort(); + assert!(!names.is_empty(), "no templates in {}", dir.display()); + for t in &names { + let name = t.file_name().unwrap().to_string_lossy(); + let text = std::fs::read_to_string(t.join("compose.yaml")).unwrap(); + let read = |text: &str| { + plan(&Input { + file: text, + name_hint: &name, + domain_base: Some("1.2.3.4.nip.io".into()), + ..Default::default() + }) + .unwrap_or_else(|e| panic!("{name}: {e}")) + }; + let with = read(&text); + let mut doc = read_yaml(&text).unwrap(); + without_x_pyo(&mut doc); + // JSON is YAML too. + let without = read(&doc.to_string()); + assert_eq!( + serde_json::to_value(&with).unwrap(), + serde_json::to_value(&without).unwrap(), + "{name}" + ); + assert!( + with.warnings.iter().all(|w| !w.field.starts_with("x-pyo")), + "{name}: {:?}", + with.warnings + ); + } + eprintln!("{} templates imported as before", names.len()); + } } diff --git a/crates/pyo-api/src/ops.rs b/crates/pyo-api/src/ops.rs index 930493e4..872ac734 100644 --- a/crates/pyo-api/src/ops.rs +++ b/crates/pyo-api/src/ops.rs @@ -3534,6 +3534,21 @@ fn key_allows(user: &User, op: &Op) -> ApiResult<()> { } } +/// Another operation, run inside this one's transaction with its own +/// checks (a Compose sync saves, creates and deletes services this way). +pub(crate) fn nested<'a, 'c>( + s: &'a AppState, + tx: &'a mut Transaction<'c, Postgres>, + user: &'a User, + op: Op, + wake: &'a mut Vec, +) -> std::pin::Pin> + Send + 'a>> +where + 'c: 'a, +{ + Box::pin(apply(s, tx, user, op, wake)) +} + async fn apply( s: &AppState, tx: &mut Transaction<'_, Postgres>, @@ -5737,6 +5752,7 @@ async fn apply( let deployment_id = new_id("dpl"); let service = crate::compose::service_spec( svc, + Some(&plan.project.file), &id, &team_id, &project_id, @@ -5756,6 +5772,19 @@ async fn apply( None, ) .await?; + if let Some(cdn) = &svc.behind_cdn { + nested( + s, + tx, + user, + Op::SetServiceBehindCdn { + service_id: id.clone(), + cdn: Some(cdn.clone()), + }, + wake, + ) + .await?; + } made.push(json!({ "name": svc.name, "id": id, "deploymentId": deployment_id })); } Ok(json!({ "ok": true, "projectId": project_id, "services": made })) @@ -6046,6 +6075,13 @@ async fn apply( // Where it came from stays, and a secret field's value never does. crate::template_source::keep_record(&mut spec, &old_spec); crate::template_source::scrub_fields(&mut spec); + // What it remembers of the Compose file it was made from stays + // when a client leaves it out. + if spec.get("compose").is_none_or(Value::is_null) + && let Some(c) = old_spec.get("compose").filter(|c| c.is_object()) + { + spec["compose"] = c.clone(); + } // Autoscaling has its own op: a save from a tab that hasn't seen // the latest setting can't change it, or the size it manages. match old_spec.get("autoscale") { @@ -6124,6 +6160,7 @@ async fn apply( if let Some(o) = v.as_object_mut() { o.remove("description"); o.remove("autoRollback"); + o.remove("compose"); o.remove("domains"); // Goes live with the domains (routes.rs). o.remove("requestTimeout"); diff --git a/crates/pyo-api/src/platform_import/mod.rs b/crates/pyo-api/src/platform_import/mod.rs index 641d35ab..198e2cca 100644 --- a/crates/pyo-api/src/platform_import/mod.rs +++ b/crates/pyo-api/src/platform_import/mod.rs @@ -1738,6 +1738,7 @@ async fn create( let id = new_id("svc"); let mut spec = crate::compose::service_spec( &service, + None, &id, team_id, &pid, @@ -1821,6 +1822,7 @@ async fn create( let id = new_id("svc"); let mut spec = crate::compose::service_spec( cs, + None, &id, team_id, &pid, From 3b28fff27d041ac288f0f467569d16c4ed5e5f28 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 19:06:25 +0700 Subject: [PATCH 054/139] feat(api): plan and apply a compose sync POST /compose/sync-plan shows what a Compose file would change in the project made from it: each service added, changed (and what), unchanged or no longer in the file. The syncCompose operation works it out again and applies it through the usual service operations. Only what the file sets is compared, so settings changed in Pyo stay. Secrets are never opened or changed. A change that can't happen in place is listed as a manual step and skipped. Services no longer in the file are deleted only with prune, and only when made from it. --- crates/pyo-api/src/compose_sync.rs | 1272 ++++++++++++++++++++++ crates/pyo-api/src/compose_sync_tests.rs | 460 ++++++++ crates/pyo-api/src/lib.rs | 1 + crates/pyo-api/src/mcp.rs | 5 +- crates/pyo-api/src/openapi.rs | 2 + crates/pyo-api/src/ops.rs | 39 +- 6 files changed, 1777 insertions(+), 2 deletions(-) create mode 100644 crates/pyo-api/src/compose_sync.rs create mode 100644 crates/pyo-api/src/compose_sync_tests.rs diff --git a/crates/pyo-api/src/compose_sync.rs b/crates/pyo-api/src/compose_sync.rs new file mode 100644 index 00000000..fe2f58ab --- /dev/null +++ b/crates/pyo-api/src/compose_sync.rs @@ -0,0 +1,1272 @@ +//! Compose sync: a Compose file applied again to the project made from it +//! (or linked to it) changes only what the file says differently. The plan +//! lists each service as added, changed (and what), unchanged, or no longer +//! in the file. `syncCompose` works the plan out again in its own +//! transaction and applies it through the same operations the dashboard +//! uses, with their checks. +//! +//! - Only what the file sets is compared (`PlanService::managed`). A setting +//! changed in Pyo that the file doesn't mention stays as it is. +//! - Variables, ports, domains and volumes the file lists are added or +//! changed. Ones it doesn't list stay. +//! - A secret keeps its value in Pyo, whatever the file says. +//! - What can't change in place (a volume that would move, another kind of +//! source) is a manual step: listed, and left as it is. +//! - A service no longer in the file is only listed. With `prune` it's +//! deleted (its volumes are kept, detached), and only when it was made +//! from this file. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sqlx::{Postgres, Transaction}; + +use crate::compose::{self, ComposePlan, PlanService, PlanVolume, PlanWarning}; +use crate::error::{ApiError, ApiResult}; + +/// What a sync would change. +#[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct SyncPlan { + /// The project it syncs. None when there's none for this file yet: then + /// `importCompose` makes it from `file`. + pub project: Option, + /// The file's services in deploy order, then the project's services that + /// aren't in the file. + pub services: Vec, + /// What the file has that Pyo doesn't carry over. + pub warnings: Vec, + /// The file as Pyo reads it: pass it to `syncCompose` (or `importCompose`). + pub file: ComposePlan, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct SyncProject { + pub id: String, + pub name: String, + pub namespace: String, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct SyncService { + /// Its name in Pyo. + pub name: String, + /// Its name in the file. None when it isn't in the file. + #[serde(default)] + pub compose_name: Option, + /// None for a service the sync would add. + #[serde(default)] + pub service_id: Option, + /// "added", "changed", "unchanged" or "notInFile". + pub status: String, + pub changes: Vec, + /// What stays as it is in Pyo, and why. + pub notes: Vec, + /// What can't change in place. It's left as it is: change it by hand. + pub manual: Vec, + /// The sync deploys it. + pub deploy: bool, + /// For a service not in the file: it was made from this file, so + /// `prune` deletes it. + #[serde(default)] + pub from_file: bool, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SyncChange { + /// What changes, e.g. "image", "replicas", "env LOG_LEVEL", "domain app.example.com". + pub field: String, + /// As it is now. Variables' values are never shown. + #[serde(default)] + pub from: Option, + #[serde(default)] + pub to: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, utoipa::ToSchema, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SyncNote { + pub field: String, + pub message: String, +} + +/// A service of the project, as the sync sees it. +#[derive(Debug, Clone, Default)] +pub struct Existing { + pub id: String, + pub name: String, + /// As stored: secrets sealed. + pub spec: Value, + pub behind_cdn: Option, + /// Its volumes' data: name, mountPath, sizeGi. + pub volumes: Vec, +} + +impl Existing { + /// The Compose service it was made from. + fn compose_name(&self) -> Option<&str> { + self.spec["compose"]["service"].as_str() + } +} + +/// One service brought in line with the file. +#[derive(Debug, Default)] +pub struct Merged { + /// Its new spec (secrets still sealed). + pub spec: Value, + pub changes: Vec, + pub notes: Vec, + pub manual: Vec, + pub deploy: bool, + /// A new CDN setting. + pub behind_cdn: Option>, + /// Volumes to add. + pub volumes: Vec, + /// Nothing changes but what it remembers of the file. + pub record_only: bool, +} + +impl Merged { + fn change(&mut self, field: impl Into, from: Option, to: Option) { + self.changes.push(SyncChange { + field: field.into(), + from, + to, + }); + } +} + +fn note(field: impl Into, message: impl Into) -> SyncNote { + SyncNote { + field: field.into(), + message: message.into(), + } +} + +fn image_words(image: &str, reference: &str) -> String { + if reference.starts_with("sha256:") { + format!("{image}@{reference}") + } else { + format!("{image}:{reference}") + } +} + +fn source_words(kind: &str) -> String { + match kind { + "image" => "deployed from an image".into(), + "git" => "built from Git".into(), + "upload" => "built from a folder".into(), + "template" => "deployed from a template".into(), + k => format!("from {k}"), + } +} + +fn health_words(h: &Value) -> String { + let port = h["port"].as_i64().unwrap_or(0); + match h["type"].as_str().unwrap_or("none") { + "http" => format!("{} on {port}", h["path"].as_str().unwrap_or("/")), + "tcp" => format!("tcp on {port}"), + "exec" => "a command".into(), + _ => "none".into(), + } +} + +fn placement_words(p: &crate::placement::Placement) -> String { + if p.any() { + return "any server".into(); + } + let mut parts = vec![]; + if !p.servers.is_empty() { + parts.push(p.servers.join(", ")); + } + if !p.tags.is_empty() { + parts.push(format!( + "{} {}", + if p.tags.len() == 1 { "tag" } else { "tags" }, + p.tags.join(", ") + )); + } + parts.join(" and ") +} + +fn port_words(exposure: &str, public_port: Option) -> String { + match (exposure, public_port) { + ("http", _) => "public".into(), + ("loadbalancer", Some(p)) => format!("public on {p}"), + ("loadbalancer" | "nodeport", None) => "public".into(), + _ => "inside the project".into(), + } +} + +fn sorted(mut p: crate::placement::Placement) -> crate::placement::Placement { + p.servers.sort(); + p.tags.sort(); + p +} + +/// A name for a new port that none of the service's ports has. +fn free_port_name(ports: &[Value], want: &str, protocol: &str, port: u16) -> String { + let taken = |n: &str| ports.iter().any(|p| p["name"] == json!(n)); + if !taken(want) { + return want.to_owned(); + } + let base = format!("{}-{port}", protocol.to_lowercase()); + let mut name = base.clone(); + let mut n = 2; + while taken(&name) { + name = format!("{base}-{n}"); + n += 1; + } + name +} + +/// A volume's name without its service's in front, as `addVolume` takes it. +pub fn volume_label(service: &str, volume: &str) -> String { + volume + .strip_prefix(&format!("{service}-")) + .filter(|l| !l.is_empty()) + .unwrap_or(volume) + .to_owned() +} + +/// `old` brought in line with what the file sets for it (`want`). +pub fn merge( + old: &Existing, + want: &PlanService, + file: &str, + now: i64, + new_id: &dyn Fn(&str) -> String, +) -> Merged { + let mut m = Merged::default(); + let mut spec = old.spec.clone(); + if !spec.is_object() { + spec = json!({}); + } + + // Its source. + let kind = spec["source"]["type"].as_str().unwrap_or("").to_owned(); + match (kind.as_str(), want.source.kind.as_str()) { + ("image", "image") => { + let src = &mut spec["source"]; + let from = image_words( + src["image"].as_str().unwrap_or(""), + src["reference"].as_str().unwrap_or(""), + ); + let to = image_words(&want.source.image, &want.source.reference); + if from != to { + src["image"] = json!(want.source.image); + src["reference"] = json!(want.source.reference); + m.change("image", Some(from), Some(to)); + m.deploy = true; + } + } + ("git" | "upload", "git") => { + let mut fields = vec![ + ("buildContext", "build context", &want.source.build_context), + ("dockerfilePath", "Dockerfile", &want.source.dockerfile_path), + ]; + if kind == "git" && !want.source.repo_url.is_empty() { + fields.push(("repoUrl", "repository", &want.source.repo_url)); + fields.push(("branch", "branch", &want.source.branch)); + } + for (key, label, to) in fields { + let src = &mut spec["source"]; + let from = src[key].as_str().unwrap_or("").to_owned(); + if &from != to { + src[key] = json!(to); + m.change(label, Some(from), Some(to.clone())); + m.deploy = true; + } + } + for a in &want.source.build_args { + let src = &mut spec["source"]; + if !src["buildArgs"].is_array() { + src["buildArgs"] = json!([]); + } + let Some(args) = src["buildArgs"].as_array_mut() else { + continue; + }; + match args.iter_mut().find(|x| x["key"] == json!(a.key)) { + Some(x) if x["value"] == json!(a.value) => {} + Some(x) => { + x["value"] = json!(a.value); + m.change(format!("build argument {}", a.key), None, None); + m.deploy = true; + } + None => { + args.push(json!({ "key": a.key, "value": a.value })); + m.change( + format!("build argument {}", a.key), + None, + Some("added".into()), + ); + m.deploy = true; + } + } + } + } + (from, to) => m.manual.push(note( + "source", + format!( + "It's {} in Pyo and {} in the file. Change its source in the dashboard.", + source_words(from), + source_words(to) + ), + )), + } + + // Variables: the file's are added or changed, a secret's value stays. + if !spec["env"].is_array() { + spec["env"] = json!([]); + } + for e in &want.env { + let field = format!("env {}", e.key); + let Some(env) = spec["env"].as_array_mut() else { + break; + }; + match env.iter_mut().find(|o| o["key"] == json!(e.key)) { + Some(o) if o["secret"] == json!(true) => { + if !e.value.is_empty() { + m.notes + .push(note(field, "It's a secret in Pyo, so its value stays.")); + } + } + Some(o) if o["value"].as_str() == Some(e.value.as_str()) => {} + Some(o) => { + o["value"] = json!(e.value); + o["updatedAt"] = json!(now); + m.change(field, None, None); + m.deploy = true; + } + None => { + env.push(json!({ "id": new_id("env"), "key": e.key, "value": e.value, "secret": e.secret, "updatedAt": now })); + m.change(field, None, Some("added".into())); + m.deploy = true; + } + } + } + for k in &want.secrets { + let field = format!("secret {k}"); + let Some(env) = spec["env"].as_array_mut() else { + break; + }; + match env.iter().find(|o| o["key"] == json!(k)) { + Some(o) if o["secret"] == json!(true) => {} + Some(_) => m.manual.push(note( + field, + "It's a plain variable in Pyo. Make it a secret in the dashboard.", + )), + None => { + env.push(json!({ "id": new_id("env"), "key": k, "value": "", "secret": true, "updatedAt": now })); + m.change(field.clone(), None, Some("added".into())); + m.notes.push(note(field, "Set its value in Pyo, then deploy.")); + } + } + } + + // Ports, matched by number (and UDP or not). + if want.manages("ports") { + if !spec["ports"].is_array() { + spec["ports"] = json!([]); + } + for p in &want.ports { + let field = format!("port {}", p.container_port); + let udp = p.protocol == "UDP"; + let want_exposure = compose::exposure(p); + let Some(ports) = spec["ports"].as_array_mut() else { + break; + }; + let found = ports.iter().position(|o| { + o["containerPort"].as_u64() == Some(u64::from(p.container_port)) + && (o["protocol"] == json!("UDP")) == udp + }); + let Some(i) = found else { + let name = free_port_name(ports, &p.name, &p.protocol, p.container_port); + let mut v = compose::port_json(p, new_id("port")); + v["name"] = json!(name); + ports.push(v); + m.change( + field, + None, + Some(port_words(want_exposure, p.public_port.map(u64::from))), + ); + m.deploy = true; + continue; + }; + let o = &mut ports[i]; + if !udp && o["protocol"] != json!(p.protocol) { + let from = o["protocol"].as_str().unwrap_or("").to_owned(); + o["protocol"] = json!(p.protocol); + m.change(field.clone(), Some(from), Some(p.protocol.clone())); + m.deploy = true; + } + let exposure = o["exposure"].as_str().unwrap_or("internal").to_owned(); + let from = port_words(&exposure, o["publicPort"].as_u64()); + let to = port_words(want_exposure, p.public_port.map(u64::from)); + match (exposure.as_str(), want_exposure) { + (a, "loadbalancer") if a == "loadbalancer" => { + if let Some(pp) = p.public_port + && o["publicPort"].as_u64() != Some(u64::from(pp)) + { + o["publicPort"] = json!(pp); + m.change(field, Some(from), Some(to)); + m.deploy = true; + } + } + (a, b) if a == b => {} + ("http" | "loadbalancer" | "nodeport", "internal") => m + .notes + .push(note(field, "It's public in Pyo, so it stays public.")), + (_, "http") => { + // A website's port: its domains go live in place. + o["exposure"] = json!("http"); + if let Some(x) = o.as_object_mut() { + x.remove("publicPort"); + x.remove("proxy"); + } + m.change(field, Some(from), Some(to)); + if exposure != "internal" { + m.deploy = true; + } + } + _ => { + o["exposure"] = json!(want_exposure); + o["proxy"] = json!(true); + if let Some(pp) = p.public_port { + o["publicPort"] = json!(pp); + } + m.change(field, Some(from), Some(to)); + m.deploy = true; + } + } + } + } + + // Domains: the file's are added on its web port. + if want.manages("domains") { + if !spec["domains"].is_array() { + spec["domains"] = json!([]); + } + let ports = spec["ports"].as_array().cloned().unwrap_or_default(); + // The port the file serves them on, else its first website port. + let wanted_port = want + .ports + .iter() + .find(|p| p.public && p.protocol == "HTTP") + .map(|p| p.container_port); + let web = ports + .iter() + .find(|o| { + o["exposure"] == json!("http") + && wanted_port + .is_some_and(|w| o["containerPort"].as_u64() == Some(u64::from(w))) + }) + .or_else(|| ports.iter().find(|o| o["exposure"] == json!("http"))) + .and_then(|o| o["name"].as_str()) + .map(str::to_owned); + for d in &want.domains { + let Some(domains) = spec["domains"].as_array_mut() else { + break; + }; + if domains.iter().any(|o| { + o["hostname"] + .as_str() + .is_some_and(|h| h.eq_ignore_ascii_case(d)) + }) { + continue; + } + match &web { + Some(port) => { + domains.push(compose::domain_json(d, port, new_id("dom"), now)); + m.change(format!("domain {d}"), None, Some("added".into())); + } + None => m.manual.push(note( + format!("domain {d}"), + "It has no public web port in Pyo to serve it on. Make one public in the dashboard.", + )), + } + } + } + + // Health check. + if want.manages("health") { + let old_h = spec["healthCheck"].clone(); + let mut h = want.health_check.clone(); + if !want.manages("healthTiming") { + for k in ["initialDelaySeconds", "periodSeconds"] { + if let Some(v) = old_h.get(k) { + h[k] = v.clone(); + } + } + } + let same = old_h.get("auto").is_none_or(Value::is_null) + && [ + "type", + "path", + "port", + "command", + "initialDelaySeconds", + "periodSeconds", + ] + .iter() + .all(|k| old_h[*k] == h[*k]); + if !same { + m.change( + "health check", + Some(health_words(&old_h)), + Some(health_words(&h)), + ); + spec["healthCheck"] = h; + m.deploy = true; + } + } + + // Replicas, unless autoscaling sets them. + if want.manages("replicas") { + if spec.get("autoscale").is_some_and(|a| !a.is_null()) { + if spec["replicas"].as_i64() != Some(i64::from(want.replicas)) { + m.notes.push(note( + "replicas", + "Autoscaling sets them, so they stay as they are.", + )); + } + } else if spec["replicas"].as_i64() != Some(i64::from(want.replicas)) { + m.change( + "replicas", + spec["replicas"].as_i64().map(|n| n.to_string()), + Some(want.replicas.to_string()), + ); + spec["replicas"] = json!(want.replicas); + m.deploy = true; + } + } + + // Resources the file sets. + let r = &want.resources; + let mut set_resource = false; + for (field, key, value, label) in [ + ("resources.cpuLimit", "cpuLimit", r.cpu_limit, "cpu limit"), + ( + "resources.memoryLimit", + "memoryLimit", + r.memory_limit, + "memory limit", + ), + ("resources.cpuRequest", "cpuRequest", r.cpu_request, "cpu request"), + ( + "resources.memoryRequest", + "memoryRequest", + r.memory_request, + "memory request", + ), + ("resources.gpu", "gpu", r.gpu, "GPUs"), + ] { + if !want.manages(field) { + continue; + } + if !spec["resources"].is_object() { + spec["resources"] = json!({}); + } + let now_v = spec["resources"][key].as_i64(); + if now_v != Some(value) { + let unit = |n: i64| match key { + "cpuLimit" | "cpuRequest" => format!("{n}m"), + "gpu" => n.to_string(), + _ => format!("{n} MiB"), + }; + m.change(label, now_v.map(unit), Some(unit(value))); + spec["resources"][key] = json!(value); + set_resource = true; + } + } + if set_resource { + // A request is never above its limit. + for (req, lim) in [("cpuRequest", "cpuLimit"), ("memoryRequest", "memoryLimit")] { + let res = &mut spec["resources"]; + if let (Some(a), Some(b)) = (res[req].as_i64(), res[lim].as_i64()) + && a > b + { + res[req] = json!(b); + } + } + m.deploy = true; + } + + // How it starts. + let c = &want.container; + let mut container = spec + .get("container") + .cloned() + .filter(Value::is_object) + .unwrap_or_else(|| json!({})); + let mut set_container = false; + for (field, key, value, label) in [ + ( + "container.entrypoint", + "entrypoint", + json!(c.entrypoint), + "entrypoint", + ), + ("container.command", "command", json!(c.command), "command"), + ( + "container.workingDir", + "workingDir", + json!(c.working_dir), + "working directory", + ), + ] { + if !want.manages(field) { + continue; + } + let now_v = match container.get(key) { + None | Some(Value::Null) if value.is_array() => json!([]), + None | Some(Value::Null) => json!(""), + Some(v) => v.clone(), + }; + if now_v != value { + m.change(label, None, None); + container[key] = value; + set_container = true; + } + } + if want.manages("container.user") { + for (key, value) in [("runAsUser", c.run_as_user), ("runAsGroup", c.run_as_group)] { + if container.get(key).and_then(Value::as_i64) != value { + container[key] = json!(value); + set_container = true; + if !m.changes.iter().any(|x| x.field == "user") { + m.change("user", None, None); + } + } + } + } + if set_container { + // Empty ones keep the image's own. + if let Some(o) = container.as_object_mut() { + o.retain(|_, v| { + !(v.is_null() + || v.as_array().is_some_and(Vec::is_empty) + || v.as_str().is_some_and(str::is_empty)) + }); + } + if container.as_object().is_some_and(|o| o.is_empty()) { + if let Some(o) = spec.as_object_mut() { + o.remove("container"); + } + } else { + spec["container"] = container; + } + m.deploy = true; + } + + // Where it runs: changed in place. + if want.manages("placement") { + let wanted = json!({ "placement": want.placement.clone().unwrap_or(Value::Null) }); + let (from, to) = ( + sorted(crate::placement::Placement::of(&spec)), + sorted(crate::placement::Placement::of(&wanted)), + ); + if from != to { + m.change( + "placement", + Some(placement_words(&from)), + Some(placement_words(&to)), + ); + if let Some(o) = spec.as_object_mut() { + o.remove("servers"); + o.remove("serverTags"); + o.insert("placement".into(), to.to_value()); + } + } + } + + // Volumes, matched by where they're mounted. + if want.manages("volumes") { + for v in &want.volumes { + if old + .volumes + .iter() + .any(|o| o["mountPath"] == json!(v.mount_path)) + { + continue; + } + let label = volume_label(&old.name, &v.name); + let full = format!("{}-{label}", old.name); + let named = old.volumes.iter().find(|o| { + o["name"] == json!(v.name) || o["name"] == json!(full) + }); + match named { + Some(o) => m.manual.push(note( + format!("volume {}", o["name"].as_str().unwrap_or(&v.name)), + format!( + "It's mounted at {} in Pyo and {} in the file. Detach it and attach it at {} to move it.", + o["mountPath"].as_str().unwrap_or(""), + v.mount_path, + v.mount_path + ), + )), + None => { + m.change( + format!("volume {full}"), + None, + Some(format!("added at {}", v.mount_path)), + ); + m.volumes.push(v.clone()); + m.deploy = true; + } + } + } + } + + // Behind a CDN: changed in place. + if want.manages("behindCdn") && old.behind_cdn != want.behind_cdn { + m.change( + "behind CDN", + Some(old.behind_cdn.clone().unwrap_or_else(|| "none".into())), + Some(want.behind_cdn.clone().unwrap_or_else(|| "none".into())), + ); + m.behind_cdn = Some(want.behind_cdn.clone()); + } + + // What it remembers of the file. + let record = compose::record(file, &want.compose_name); + if spec.get("compose") != Some(&record) { + spec["compose"] = record; + m.record_only = m.changes.is_empty(); + } + m.spec = spec; + m +} + +/// The file's services and the project's, paired: a service made from a +/// Compose service matches it by that name, any other by its own name. +fn pair<'a>( + file: &'a ComposePlan, + existing: &'a [Existing], +) -> Vec<(Option<&'a PlanService>, Option<&'a Existing>)> { + let mut used = vec![false; existing.len()]; + let mut out = vec![]; + for want in &file.services { + let by_record = existing + .iter() + .enumerate() + .position(|(i, e)| !used[i] && e.compose_name() == Some(want.compose_name.as_str())); + let by_name = || { + existing.iter().enumerate().position(|(i, e)| { + !used[i] + && e.name == want.name + && e.compose_name().is_none_or(|c| { + !file.services.iter().any(|s| s.compose_name == c) + }) + }) + }; + match by_record.or_else(by_name) { + Some(i) => { + used[i] = true; + out.push((Some(want), Some(&existing[i]))); + } + None => out.push((Some(want), None)), + } + } + for (i, e) in existing.iter().enumerate() { + if !used[i] { + out.push((None, Some(e))); + } + } + out +} + +/// The file names a service's record and the file are compared by. +fn same_file(a: &str, b: &str) -> bool { + let base = |s: &str| s.trim().rsplit('/').next().unwrap_or("").to_owned(); + let (a, b) = ( + if a.trim().is_empty() { "compose.yaml" } else { a }, + if b.trim().is_empty() { "compose.yaml" } else { b }, + ); + base(a) == base(b) +} + +/// What syncing `file` into a project with `existing` services would do. +pub fn plan_of(project: Option, file: ComposePlan, existing: &[Existing]) -> SyncPlan { + let now = pyo_proto::now_ms(); + let new_id = |p: &str| crate::ids::new_id(p); + let mut services = vec![]; + for (want, old) in pair(&file, existing) { + match (want, old) { + (Some(w), None) => services.push(SyncService { + name: w.name.clone(), + compose_name: Some(w.compose_name.clone()), + status: "added".into(), + notes: w + .secrets + .iter() + .filter(|k| !w.env.iter().any(|e| &e.key == *k)) + .map(|k| note(format!("secret {k}"), "Set its value in Pyo, then deploy.")) + .collect(), + deploy: true, + ..Default::default() + }), + (Some(w), Some(o)) => { + let m = merge(o, w, &file.project.file, now, &new_id); + services.push(SyncService { + name: o.name.clone(), + compose_name: Some(w.compose_name.clone()), + service_id: Some(o.id.clone()), + status: if m.changes.is_empty() { + "unchanged" + } else { + "changed" + } + .into(), + deploy: m.deploy, + changes: m.changes, + notes: m.notes, + manual: m.manual, + from_file: true, + }); + } + (None, Some(o)) => { + let made_from = o.spec["compose"]["file"].as_str(); + let from_file = made_from.is_some_and(|f| same_file(f, &file.project.file)); + let notes = match made_from { + Some(f) if !from_file => { + vec![note("source", format!("It was made from {f}."))] + } + None => vec![note("source", "It wasn't made from a Compose file.")], + _ => vec![], + }; + services.push(SyncService { + name: o.name.clone(), + service_id: Some(o.id.clone()), + status: "notInFile".into(), + notes, + from_file, + ..Default::default() + }); + } + (None, None) => {} + } + } + SyncPlan { + project, + services, + warnings: file.warnings.clone(), + file, + } +} + +// ── Reading the project ────────────────────────────────────────────────────── + +/// The project's services a sync compares: not previews, not being deleted. +pub async fn existing( + tx: &mut Transaction<'_, Postgres>, + project_id: &str, +) -> ApiResult> { + let rows: Vec<(String, String, Value, Option)> = sqlx::query_as( + "SELECT id, name, spec, behind_cdn FROM pyo.services + WHERE project_id = $1 AND NOT deleting AND preview_of IS NULL + ORDER BY created_at, id", + ) + .bind(project_id) + .fetch_all(&mut **tx) + .await?; + let volumes: Vec<(String, Value)> = sqlx::query_as( + "SELECT service_id, data FROM pyo.volumes + WHERE project_id = $1 AND service_id IS NOT NULL AND NOT deleting", + ) + .bind(project_id) + .fetch_all(&mut **tx) + .await?; + let mut out = vec![]; + for (id, name, mut spec, behind_cdn) in rows { + // Variables are compared in the clear. Secrets never are: they're + // left blank, so a sync never opens them, and a save keeps them. + blank_secrets(&mut spec); + crate::vault::get().open_env(&mut spec).await?; + out.push(Existing { + volumes: volumes + .iter() + .filter(|(s, _)| *s == id) + .map(|(_, d)| d.clone()) + .collect(), + id, + name, + spec, + behind_cdn, + }); + } + Ok(out) +} + +/// The project a sync goes to: the one named, else the team's project made +/// from a Compose file of this name (its namespace). +async fn find_project( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + project_id: Option<&str>, + namespace: &str, +) -> ApiResult> { + let row: Option<(String, String, String)> = match project_id.filter(|p| !p.is_empty()) { + Some(id) => Some( + sqlx::query_as( + "SELECT id, name, namespace FROM pyo.projects WHERE id = $1 AND team_id = $2", + ) + .bind(id) + .bind(team_id) + .fetch_optional(&mut **tx) + .await? + .ok_or_else(|| ApiError::not_found("Project"))?, + ), + None => { + sqlx::query_as( + "SELECT p.id, p.name, p.namespace FROM pyo.projects p + WHERE p.team_id = $1 AND p.namespace = $2 + AND EXISTS (SELECT 1 FROM pyo.services a + WHERE a.project_id = p.id AND NOT a.deleting AND a.spec ? 'compose')", + ) + .bind(team_id) + .bind(namespace) + .fetch_optional(&mut **tx) + .await? + } + }; + Ok(row.map(|(id, name, namespace)| SyncProject { + id, + name, + namespace, + })) +} + +// ── The plan endpoint ──────────────────────────────────────────────────────── + +/// A Compose file to sync: its text, or a file in one of the team's GitHub +/// repositories, and the project it goes to. +#[derive(Debug, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct SyncBody { + /// The team it's for. + pub team_id: String, + /// The project to sync. Without it: the team's project made from a + /// Compose file of the same name, when there's one. + #[serde(default)] + pub project_id: Option, + /// The Compose file's text, when it isn't read from a repository. + #[serde(default)] + pub file: Option, + /// A .env file's text, for `${VAR}`s and `env_file: .env`. + #[serde(default)] + pub env: Option, + /// Or: a repository the team's GitHub App installations can see. + #[serde(default)] + pub repo: Option, + /// The cluster new services go to: their public web ports get a free + /// domain on it. + #[serde(default)] + pub cluster_id: Option, + /// The project's name, when the file has none. + #[serde(default)] + pub name: Option, + /// The file's name, e.g. "compose.yaml". Services remember it. + #[serde(default)] + pub file_name: Option, +} + +/// Plan a Docker Compose sync +/// +/// What applying a Compose file to the project made from it would change, +/// service by service: added, changed (and what), unchanged, or not in the +/// file. Only what the file sets is compared, so settings changed in Pyo +/// that the file doesn't mention stay. A secret's value is never changed. +/// What can't change in place is listed under `manual` and left as it is. +/// Nothing changes. Pass `file` to the `syncCompose` operation to apply it, +/// or to `importCompose` when there's no `project` yet. +/// +/// Besides Compose, each service's `x-pyo` can set `domains`, `behindCdn` +/// ("cloudflare" or "none"), `health` (a path like "/healthz", "tcp" or +/// "none"), `replicas`, `placement` (`{"servers": [...], "tags": [...]}`) +/// and `secrets` (variable names; their values are set in Pyo). +#[utoipa::path(post, path = "/compose/sync-plan", operation_id = "planComposeSync", tag = "Projects", + request_body = SyncBody, + responses( + (status = 200, description = "The plan.", body = SyncPlan), + (status = 400, description = "Not a Compose file Pyo can read, nothing importable, or no file given.", body = crate::error::ErrorBody), + (status = 404, description = "No such team, project, cluster or file.", body = crate::error::ErrorBody), + (status = 502, description = "GitHub couldn't be read.", body = crate::error::ErrorBody), + ), + extensions(("x-pyo-access" = json!("read"))))] +pub async fn plan( + axum::extract::State(s): axum::extract::State, + crate::auth::SessionUser(user): crate::auth::SessionUser, + crate::error::Json(b): crate::error::Json, +) -> ApiResult> { + let file = compose::read_plan( + &s, + &user, + &compose::PreviewBody { + team_id: b.team_id.clone(), + file: b.file, + env: b.env, + repo: b.repo, + cluster_id: b.cluster_id, + name: b.name, + file_name: b.file_name, + }, + ) + .await?; + let mut tx = crate::rls::begin(&s.db, &user).await?; + let project = find_project( + &mut tx, + &b.team_id, + b.project_id.as_deref(), + &file.project.namespace, + ) + .await?; + let existing = match &project { + Some(p) => existing(&mut tx, &p.id).await?, + None => vec![], + }; + tx.commit().await?; + Ok(crate::error::Json(plan_of(project, file, &existing))) +} + +// ── Applying it ────────────────────────────────────────────────────────────── + +/// A secret goes back blank, so the save keeps its sealed value. +fn blank_secrets(spec: &mut Value) { + for env in [&mut spec["env"], &mut spec["previews"]["env"]] { + for e in env.as_array_mut().into_iter().flatten() { + if e["secret"] == json!(true) { + e["value"] = json!(""); + } + } + } +} + +/// `syncCompose`: the plan worked out again, then applied through the +/// operations it stands for. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn apply( + s: &crate::AppState, + tx: &mut Transaction<'_, Postgres>, + user: &crate::auth::User, + project_id: &str, + cluster_id: Option, + file: ComposePlan, + prune: bool, + confirm: bool, + wake: &mut Vec, +) -> ApiResult { + use crate::ops::{Op, Role, nested, require_role, team_of}; + let team_id = team_of(tx, "projects", project_id).await?; + require_role(tx, user, &team_id, Role::Developer).await?; + if file.services.is_empty() || file.services.len() > 40 { + return Err(ApiError::bad_request( + "A Compose file has 1 to 40 services.", + )); + } + for svc in &file.services { + crate::util::require_dns_label(&svc.name, "Service name")?; + } + let (name, namespace): (String, String) = + sqlx::query_as("SELECT name, namespace FROM pyo.projects WHERE id = $1") + .bind(project_id) + .fetch_one(&mut **tx) + .await?; + let existing = existing(tx, project_id).await?; + let plan = plan_of( + Some(SyncProject { + id: project_id.to_owned(), + name: name.clone(), + namespace, + }), + file.clone(), + &existing, + ); + let now = pyo_proto::now_ms(); + let new_id = |p: &str| crate::ids::new_id(p); + let mut cluster: Option = None; + let mut done = vec![]; + for ss in &plan.services { + let want = ss + .compose_name + .as_ref() + .and_then(|c| file.services.iter().find(|w| &w.compose_name == c)); + let old = ss + .service_id + .as_ref() + .and_then(|id| existing.iter().find(|e| &e.id == id)); + match (ss.status.as_str(), want, old) { + ("added", Some(w), _) => { + if w.source.kind == "git" && w.source.repo_url.trim().is_empty() { + return Err(ApiError::bad_request(format!( + "{} is built from source: sync from its repository, or give it an image.", + w.name + ))); + } + // Where new services run: the cluster given, else where the + // project's services run, else the team's default. + if cluster.is_none() { + let c = match cluster_id.clone().filter(|c| !c.is_empty()) { + Some(c) => c, + None => sqlx::query_scalar::<_, Option>( + "SELECT COALESCE( + (SELECT cluster_id FROM pyo.services WHERE project_id = $1 AND NOT deleting + GROUP BY cluster_id ORDER BY count(*) DESC, cluster_id LIMIT 1), + (SELECT default_cluster_id FROM pyo.teams WHERE id = $2))", + ) + .bind(project_id) + .bind(&team_id) + .fetch_one(&mut **tx) + .await? + .ok_or_else(|| { + ApiError::bad_request( + "This team has no cluster to deploy to. Add a server first.", + ) + })?, + }; + if team_of(tx, "clusters", &c).await? != team_id { + return Err(ApiError::not_found("Cluster")); + } + cluster = Some(c); + } + let cluster_id = cluster.clone().unwrap_or_default(); + let id = new_id("svc"); + let deployment_id = new_id("dpl"); + let service = compose::service_spec( + w, + Some(&file.project.file), + &id, + &team_id, + project_id, + &cluster_id, + now, + &new_id, + ); + let volumes = compose::volume_specs(w, &new_id); + let r = nested( + s, + tx, + user, + Op::CreateService { + service, + deployment_id: deployment_id.clone(), + volumes, + databases: vec![], + confirm, + upload_id: None, + }, + wake, + ) + .await?; + if let Some(cdn) = &w.behind_cdn { + nested( + s, + tx, + user, + Op::SetServiceBehindCdn { + service_id: id.clone(), + cdn: Some(cdn.clone()), + }, + wake, + ) + .await?; + } + done.push(json!({ "name": w.name, "id": id, "status": "added", "deploymentId": deployment_id, "warning": r.get("warning") })); + } + ("changed" | "unchanged", Some(w), Some(o)) => { + let m = merge(o, w, &file.project.file, now, &new_id); + if m.changes.is_empty() && !m.record_only { + continue; + } + for v in &m.volumes { + nested( + s, + tx, + user, + Op::AddVolume { + id: new_id("vol"), + service_id: o.id.clone(), + name: volume_label(&o.name, &v.name), + mount_path: v.mount_path.clone(), + size_gi: v.size_gi, + }, + wake, + ) + .await?; + } + let mut spec = m.spec; + blank_secrets(&mut spec); + spec["id"] = json!(o.id); + let deployment_id = m.deploy.then(|| new_id("dpl")); + let r = nested( + s, + tx, + user, + Op::SaveService { + service: spec, + deployment_id: deployment_id.clone(), + trigger: None, + confirm, + }, + wake, + ) + .await?; + if let Some(cdn) = m.behind_cdn { + nested( + s, + tx, + user, + Op::SetServiceBehindCdn { + service_id: o.id.clone(), + cdn, + }, + wake, + ) + .await?; + } + if !m.changes.is_empty() { + done.push(json!({ "name": o.name, "id": o.id, "status": "changed", "deploymentId": deployment_id, "warning": r.get("warning") })); + } + } + ("notInFile", _, Some(o)) if prune && ss.from_file => { + nested( + s, + tx, + user, + Op::DeleteService { + id: o.id.clone(), + delete_volumes: false, + }, + wake, + ) + .await?; + done.push(json!({ "name": o.name, "id": o.id, "status": "deleted" })); + } + _ => {} + } + } + if !done.is_empty() { + let file_name = compose::record(&file.project.file, "")["file"] + .as_str() + .unwrap_or("compose.yaml") + .to_owned(); + crate::ops::log_activity( + tx, + &team_id, + &user.name, + "project.updated", + "info", + &format!("Synced {name} with {file_name}"), + json!({ "kind": "project", "id": project_id, "label": name }), + json!({ "projectId": project_id }), + ) + .await?; + } + Ok(json!({ "ok": true, "projectId": project_id, "services": done, "plan": plan })) +} + +#[cfg(test)] +#[path = "compose_sync_tests.rs"] +mod tests; diff --git a/crates/pyo-api/src/compose_sync_tests.rs b/crates/pyo-api/src/compose_sync_tests.rs new file mode 100644 index 00000000..b0b570b1 --- /dev/null +++ b/crates/pyo-api/src/compose_sync_tests.rs @@ -0,0 +1,460 @@ +use std::collections::BTreeMap; + +use serde_json::{Value, json}; + +use super::*; +use crate::compose::{Input, plan}; + +const FILE: &str = r#" +name: cloud +services: + cloud-api: + image: ghcr.io/acme/cloud-api:1.2 + environment: + LOG_LEVEL: info + DATABASE_URL: postgres://db:5432/cloud + ports: ["8080:8080"] + x-pyo: + domains: [cloud.example.com] + behindCdn: cloudflare + health: /readyz + replicas: 3 + secrets: [PYO_SECRET_KEY] + db: + image: postgres:17 + volumes: ["db-data:/var/lib/postgresql/data"] +volumes: + db-data: {} +"#; + +fn file_plan(text: &str) -> ComposePlan { + let mut p = plan(&Input { + file: text, + files: BTreeMap::new(), + name_hint: "cloud", + ..Default::default() + }) + .unwrap(); + p.project.file = "compose.yaml".into(); + p +} + +/// The project as an import of `text` leaves it. +fn imported(text: &str) -> Vec { + let p = file_plan(text); + let n = std::cell::Cell::new(0); + let new_id = |prefix: &str| { + n.set(n.get() + 1); + format!("{prefix}_{}", n.get()) + }; + p.services + .iter() + .map(|s| { + let id = format!("svc_{}", s.name); + let spec = compose::service_spec( + s, + Some(&p.project.file), + &id, + "team_a", + "prj_a", + "cl_a", + 1, + &new_id, + ); + Existing { + id, + name: s.name.clone(), + spec, + behind_cdn: s.behind_cdn.clone(), + volumes: compose::volume_specs(s, &new_id), + } + }) + .collect() +} + +fn project() -> Option { + Some(SyncProject { + id: "prj_a".into(), + name: "cloud".into(), + namespace: "cloud".into(), + }) +} + +fn sync(text: &str, existing: &[Existing]) -> SyncPlan { + plan_of(project(), file_plan(text), existing) +} + +fn service<'a>(p: &'a SyncPlan, name: &str) -> &'a SyncService { + p.services.iter().find(|s| s.name == name).unwrap() +} + +fn fields(s: &SyncService) -> Vec<&str> { + s.changes.iter().map(|c| c.field.as_str()).collect() +} + +#[test] +fn the_file_reads_its_x_pyo() { + let p = file_plan(FILE); + let api = p.services.iter().find(|s| s.name == "cloud-api").unwrap(); + assert_eq!(api.domains, vec!["cloud.example.com"]); + assert_eq!(api.behind_cdn.as_deref(), Some("cloudflare")); + assert_eq!(api.replicas, 3); + assert_eq!(api.health_check["type"], "http"); + assert_eq!(api.health_check["path"], "/readyz"); + assert_eq!(api.health_check["port"], 8080); + assert_eq!(api.secrets, vec!["PYO_SECRET_KEY"]); + for m in [ + "source", "env", "ports", "domains", "behindCdn", "health", "replicas", "secrets", + ] { + assert!(api.manages(m), "{m}"); + } + assert!(!api.manages("volumes") && !api.manages("resources.cpuLimit")); + // Its domain replaces the free one. + assert_eq!(api.ports[0].domain.as_deref(), Some("cloud.example.com")); + assert!(p.warnings.iter().all(|w| !w.field.starts_with("x-pyo"))); +} + +#[test] +fn an_import_records_the_file_and_makes_what_x_pyo_says() { + let ex = imported(FILE); + let api = &ex[0].spec; + assert_eq!( + api["compose"], + json!({ "file": "compose.yaml", "service": "cloud-api" }) + ); + assert_eq!(api["domains"][0]["hostname"], "cloud.example.com"); + assert_eq!(api["domains"].as_array().unwrap().len(), 1); + let secret = api["env"] + .as_array() + .unwrap() + .iter() + .find(|e| e["key"] == "PYO_SECRET_KEY") + .unwrap(); + assert_eq!((secret["secret"].clone(), secret["value"].clone()), (json!(true), json!(""))); +} + +#[test] +fn the_same_file_again_changes_nothing() { + let ex = imported(FILE); + let p = sync(FILE, &ex); + assert_eq!(p.services.len(), 2); + for s in &p.services { + assert_eq!(s.status, "unchanged", "{}: {:?}", s.name, s.changes); + assert!(s.manual.is_empty() && !s.deploy, "{}", s.name); + } +} + +#[test] +fn every_kind_of_compose_file_reads_back_unchanged() { + for f in [ + "plausible.yml", + "immich.yml", + "n8n.yml", + "uptime-kuma.yml", + "edge-cases.yml", + "ac-wordpress-mysql.yml", + "ac-prometheus-grafana.yml", + ] { + let text = std::fs::read_to_string(format!( + "{}/tests/fixtures/compose/{f}", + env!("CARGO_MANIFEST_DIR") + )) + .unwrap(); + let ex = imported(&text); + let p = sync(&text, &ex); + for s in &p.services { + assert_eq!(s.status, "unchanged", "{f} {}: {:?}", s.name, s.changes); + } + } +} + +#[test] +fn only_what_the_file_says_differently_changes() { + let ex = imported(FILE); + let next = FILE + .replace("cloud-api:1.2", "cloud-api:1.3") + .replace("replicas: 3", "replicas: 4") + .replace("LOG_LEVEL: info", "LOG_LEVEL: debug\n NEW_ONE: x") + .replace("[cloud.example.com]", "[cloud.example.com, api.example.com]") + .replace("health: /readyz", "health: /livez"); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(api.status, "changed"); + assert_eq!( + fields(api), + vec![ + "image", + "env LOG_LEVEL", + "env NEW_ONE", + "domain api.example.com", + "health check", + "replicas" + ] + ); + assert_eq!( + api.changes[0], + SyncChange { + field: "image".into(), + from: Some("ghcr.io/acme/cloud-api:1.2".into()), + to: Some("ghcr.io/acme/cloud-api:1.3".into()), + } + ); + // Values are never shown. + assert!(api.changes[1].from.is_none() && api.changes[1].to.is_none()); + assert!(api.deploy); + assert_eq!(service(&p, "db").status, "unchanged"); + + // The new spec has them, and keeps the rest. + let m = merge(&ex[0], &p.file.services[0], "compose.yaml", 2, &|p| format!("{p}_new")); + assert_eq!(m.spec["source"]["reference"], "1.3"); + assert_eq!(m.spec["replicas"], 4); + assert_eq!(m.spec["domains"].as_array().unwrap().len(), 2); + assert_eq!(m.spec["domains"][1]["portName"], m.spec["ports"][0]["name"]); + assert_eq!(m.spec["healthCheck"]["path"], "/livez"); +} + +#[test] +fn a_domain_alone_goes_live_without_a_deploy() { + let ex = imported(FILE); + let next = FILE.replace("[cloud.example.com]", "[cloud.example.com, b.example.com]"); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(fields(api), vec!["domain b.example.com"]); + assert!(!api.deploy); + let next = FILE.replace("behindCdn: cloudflare", "behindCdn: none"); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(fields(api), vec!["behind CDN"]); + assert!(!api.deploy); + let m = merge(&ex[0], &p.file.services[0], "compose.yaml", 2, &|p| p.to_owned()); + assert_eq!(m.behind_cdn, Some(None)); +} + +#[test] +fn settings_changed_in_pyo_stay_when_the_file_leaves_them_out() { + let mut ex = imported(FILE); + let db = &mut ex[1].spec; + // By hand: more replicas, a bigger limit, a variable, a domain, a placement. + db["replicas"] = json!(2); + db["resources"]["memoryLimit"] = json!(4096); + db["env"] + .as_array_mut() + .unwrap() + .push(json!({ "id": "env_x", "key": "EXTRA", "value": "1", "secret": false })); + db["placement"] = json!({ "servers": [], "tags": ["db"] }); + db["healthCheck"] = json!({ "type": "exec", "command": "pg_isready", "path": "", "port": 5432, "initialDelaySeconds": 5, "periodSeconds": 10 }); + let api = &mut ex[0].spec; + api["env"] + .as_array_mut() + .unwrap() + .push(json!({ "id": "env_y", "key": "BY_HAND", "value": "1", "secret": false })); + api["domains"] + .as_array_mut() + .unwrap() + .push(json!({ "id": "dom_y", "hostname": "extra.example.com", "portName": "http" })); + let p = sync(FILE, &ex); + for s in &p.services { + assert_eq!(s.status, "unchanged", "{}: {:?}", s.name, s.changes); + } +} + +#[test] +fn a_secrets_value_is_never_touched() { + let mut ex = imported(FILE); + // The secret got a value in Pyo (sealed), and LOG_LEVEL became a secret. + for e in ex[0].spec["env"].as_array_mut().unwrap() { + if e["key"] == "PYO_SECRET_KEY" { + e["value"] = json!("sealed:abc"); + } + if e["key"] == "LOG_LEVEL" { + e["secret"] = json!(true); + e["value"] = json!("sealed:def"); + } + } + let next = FILE.replace("LOG_LEVEL: info", "LOG_LEVEL: debug"); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(api.status, "unchanged", "{:?}", api.changes); + assert!(api.notes.iter().any(|n| n.field == "env LOG_LEVEL")); + let m = merge(&ex[0], &p.file.services[0], "compose.yaml", 2, &|p| p.to_owned()); + let value = |k: &str| { + m.spec["env"] + .as_array() + .unwrap() + .iter() + .find(|e| e["key"] == k) + .unwrap()["value"] + .clone() + }; + assert_eq!(value("PYO_SECRET_KEY"), "sealed:abc"); + assert_eq!(value("LOG_LEVEL"), "sealed:def"); + // And a value in the file for an x-pyo secret isn't used. + let given = FILE.replace("LOG_LEVEL: info", "LOG_LEVEL: info\n PYO_SECRET_KEY: oops"); + let fp = file_plan(&given); + assert!(fp.warnings.iter().any(|w| w.field == "x-pyo.secrets")); + assert!(!fp.services[0].env.iter().any(|e| e.key == "PYO_SECRET_KEY")); +} + +#[test] +fn a_new_secret_comes_without_a_value() { + let ex = imported(FILE); + let next = FILE.replace("[PYO_SECRET_KEY]", "[PYO_SECRET_KEY, STRIPE_KEY]"); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(fields(api), vec!["secret STRIPE_KEY"]); + assert!(!api.deploy, "it waits for its value"); + assert!(api.notes.iter().any(|n| n.field == "secret STRIPE_KEY")); + // A plain variable of that name is a manual step. + let mut ex = imported(FILE); + ex[0].spec["env"] + .as_array_mut() + .unwrap() + .push(json!({ "id": "env_s", "key": "STRIPE_KEY", "value": "x", "secret": false })); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(api.status, "unchanged"); + assert_eq!(api.manual[0].field, "secret STRIPE_KEY"); +} + +#[test] +fn what_cant_change_in_place_is_a_manual_step() { + let ex = imported(FILE); + // The volume would have to move. + let moved = FILE.replace("db-data:/var/lib/postgresql/data", "db-data:/data"); + let p = sync(&moved, &ex); + let db = service(&p, "db"); + assert_eq!(db.status, "unchanged"); + assert_eq!(db.manual.len(), 1); + assert!(db.manual[0].message.contains("/var/lib/postgresql/data")); + let m = merge(&ex[1], &p.file.services[1], "compose.yaml", 2, &|p| p.to_owned()); + assert!(m.volumes.is_empty()); + // Another kind of source. + let built = FILE.replace("image: postgres:17", "build: ./db"); + let p = sync(&built, &ex); + let db = service(&p, "db"); + assert_eq!(db.manual[0].field, "source"); + assert_eq!(db.status, "unchanged"); + // A new volume is added. + let more = FILE.replace( + "\"db-data:/var/lib/postgresql/data\"", + "\"db-data:/var/lib/postgresql/data\", \"wal:/wal\"", + ); + let p = sync(&more, &ex); + let db = service(&p, "db"); + assert_eq!(fields(db), vec!["volume db-wal"]); + assert!(db.deploy); +} + +#[test] +fn services_no_longer_in_the_file_are_only_listed() { + let mut ex = imported(FILE); + ex.push(Existing { + id: "svc_hand".into(), + name: "hand".into(), + spec: json!({ "name": "hand" }), + ..Default::default() + }); + ex.push(Existing { + id: "svc_other".into(), + name: "other".into(), + spec: json!({ "name": "other", "compose": { "file": "compose.db.yaml", "service": "other" } }), + ..Default::default() + }); + let only_api = r#" +services: + cloud-api: + image: ghcr.io/acme/cloud-api:1.2 +"#; + let p = sync(only_api, &ex); + let names: Vec<(&str, &str, bool)> = p + .services + .iter() + .map(|s| (s.name.as_str(), s.status.as_str(), s.from_file)) + .collect(); + assert_eq!( + names, + vec![ + ("cloud-api", "unchanged", true), + ("db", "notInFile", true), + ("hand", "notInFile", false), + ("other", "notInFile", false), + ] + ); +} + +#[test] +fn a_new_service_in_the_file_is_added() { + let ex = imported(FILE); + let more = format!("{FILE}\n"); + let more = more.replace( + "volumes:\n db-data: {}", + " worker:\n image: ghcr.io/acme/worker:1\nvolumes:\n db-data: {}", + ); + let p = sync(&more, &ex); + let w = service(&p, "worker"); + assert_eq!((w.status.as_str(), w.service_id.is_none(), w.deploy), ("added", true, true)); +} + +#[test] +fn autoscaling_keeps_its_replicas() { + let mut ex = imported(FILE); + ex[0].spec["autoscale"] = json!({ "min": 2, "max": 6, "cpuPercent": 70 }); + let next = FILE.replace("replicas: 3", "replicas: 5"); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(api.status, "unchanged"); + assert!(api.notes.iter().any(|n| n.field == "replicas")); +} + +#[test] +fn placement_and_resources_follow_the_file() { + let ex = imported(FILE); + let next = FILE.replace( + " replicas: 3", + " replicas: 3\n placement: { tags: [edge] }", + ); + let next = next.replace( + " ports: [\"8080:8080\"]", + " ports: [\"8080:8080\"]\n deploy: { resources: { limits: { memory: 2G } } }", + ); + let p = sync(&next, &ex); + let api = service(&p, "cloud-api"); + assert_eq!(fields(api), vec!["memory limit", "placement"]); + assert_eq!(api.changes[1].to.as_deref(), Some("tag edge")); + let m = merge(&ex[0], &p.file.services[0], "compose.yaml", 2, &|p| p.to_owned()); + assert_eq!(m.spec["placement"], json!({ "servers": [], "tags": ["edge"] })); + assert_eq!(m.spec["resources"]["memoryLimit"], 2048); + // The cpu limit isn't in the file: it stays. + assert_eq!(m.spec["resources"]["cpuLimit"], ex[0].spec["resources"]["cpuLimit"]); +} + +#[test] +fn a_linked_project_matches_by_name_and_starts_remembering() { + // Made by hand, then synced: matched by name, nothing else changes. + let mut ex = imported(FILE); + for e in &mut ex { + e.spec.as_object_mut().unwrap().remove("compose"); + } + let p = sync(FILE, &ex); + for s in &p.services { + assert_eq!(s.status, "unchanged", "{}", s.name); + assert!(s.service_id.is_some()); + } + let m = merge(&ex[0], &p.file.services[0], "compose.yaml", 2, &|p| p.to_owned()); + assert!(m.record_only); + assert_eq!(m.spec["compose"]["service"], "cloud-api"); +} + +#[test] +fn secrets_go_back_blank() { + let mut spec = json!({ "env": [ + { "key": "A", "value": "sealed:x", "secret": true }, + { "key": "B", "value": "plain", "secret": false }, + ] }); + blank_secrets(&mut spec); + assert_eq!(spec["env"][0]["value"], ""); + assert_eq!(spec["env"][1]["value"], "plain"); + assert_eq!(volume_label("db", "db-data"), "data"); + assert_eq!(volume_label("db", "uploads"), "uploads"); + let _ = Value::Null; +} diff --git a/crates/pyo-api/src/lib.rs b/crates/pyo-api/src/lib.rs index d66cb511..d35c7cd5 100644 --- a/crates/pyo-api/src/lib.rs +++ b/crates/pyo-api/src/lib.rs @@ -25,6 +25,7 @@ mod cli; mod cloud; mod cloudflare; pub mod compose; +pub mod compose_sync; mod cronruns; mod database_analytics; mod database_backups; diff --git a/crates/pyo-api/src/mcp.rs b/crates/pyo-api/src/mcp.rs index b2163bda..d58d436a 100644 --- a/crates/pyo-api/src/mcp.rs +++ b/crates/pyo-api/src/mcp.rs @@ -356,7 +356,7 @@ fn op_annotations(op: &str) -> Value { "readOnlyHint": read_only, // Undoing a server's removal takes nothing away. // A volume's restore replaces its data. - "destructiveHint": !read_only && op != "cancelServerRemoval" && (starts(&["delete", "remove", "stop", "discard", "rotate", "cancel", "revoke"]) || op == "restoreVolume"), + "destructiveHint": !read_only && op != "cancelServerRemoval" && (starts(&["delete", "remove", "stop", "discard", "rotate", "cancel", "revoke"]) || op == "restoreVolume" || op == "syncCompose"), "idempotentHint": read_only || starts(&["set", "update", "save", "scale", "remove", "delete", "stop", "verify", "replace", "detach", "attach", "resize"]), }) } @@ -688,6 +688,9 @@ async fn run_endpoint(s: &AppState, user: &User, id: &str, args: &Value) -> Resu "previewCompose" => { json_of(crate::compose::preview(st(), me(), Json(args_as(args)?)).await) } + "planComposeSync" => { + json_of(crate::compose_sync::plan(st(), me(), Json(args_as(args)?)).await) + } "getServiceConnections" => { json_of(ops::connections(st(), me(), path_id()?, Query(args_as(args)?)).await) } diff --git a/crates/pyo-api/src/openapi.rs b/crates/pyo-api/src/openapi.rs index 33852abb..dd99eb1f 100644 --- a/crates/pyo-api/src/openapi.rs +++ b/crates/pyo-api/src/openapi.rs @@ -75,6 +75,7 @@ use crate::{auth::KeyAccess, error::ErrorBody, ops::Op}; crate::git::branches, crate::git::build_file, crate::compose::preview, + crate::compose_sync::plan, crate::cloud::options, crate::audit::list, crate::tailscale::lock, @@ -223,6 +224,7 @@ fn title(op: &str) -> String { match op { "setServerLocation" => return "Set server region".into(), "importCompose" => return "Import Docker Compose".into(), + "syncCompose" => return "Sync Docker Compose".into(), _ => {} } let mut words: Vec = vec![]; diff --git a/crates/pyo-api/src/ops.rs b/crates/pyo-api/src/ops.rs index 872ac734..83aec56a 100644 --- a/crates/pyo-api/src/ops.rs +++ b/crates/pyo-api/src/ops.rs @@ -104,6 +104,7 @@ pub fn routes() -> Router { ) .route("/database-backups", post(crate::database_backups::add)) .route("/compose/preview", post(crate::compose::preview)) + .route("/compose/sync-plan", post(crate::compose_sync::plan)) .route("/cloud/options", get(crate::cloud::options)) .route("/tailnet/lock", get(crate::tailscale::lock)) .route("/audit-log", get(crate::audit::list)) @@ -2965,6 +2966,21 @@ pub(crate) enum Op { project_id: Option, plan: crate::compose::ComposePlan, }, + /// Bring a project in line with a Docker Compose file: `file` from `POST /compose/sync-plan`, which shows what this does. Only what the file says differently changes, so settings changed in Pyo that the file doesn't mention stay, and a secret's value is never changed. Services whose settings change are deployed. What can't change in place (a volume that would move, another kind of source) is left as it is. + /// A service no longer in the file stays, unless `prune`. + SyncCompose { + project_id: String, + /// Where services new in the file run. Where the project's services run when omitted. + #[serde(default)] + cluster_id: Option, + plan: crate::compose::ComposePlan, + /// Delete the services made from this file that are no longer in it. Their volumes are kept, detached. + #[serde(default)] + prune: bool, + /// Go ahead with a very large replica change: without it, one that goes to 20 or more replicas and to more than 10 times what the service had, or more than twice what its servers have room for, is refused with 409 and `needsConfirm: true`. Ask the user before sending it. + #[serde(default)] + confirm: bool, + }, } /// Make a change @@ -3376,7 +3392,8 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { | Op::UpdateProject { .. } | Op::DeleteProject { .. } | Op::SetProjectIsolation { .. } - | Op::ImportCompose { .. } => ("Projects", "prj"), + | Op::ImportCompose { .. } + | Op::SyncCompose { .. } => ("Projects", "prj"), Op::CreateService { .. } | Op::SaveService { .. } | Op::DeleteService { .. } @@ -5789,6 +5806,26 @@ async fn apply( } Ok(json!({ "ok": true, "projectId": project_id, "services": made })) } + Op::SyncCompose { + project_id, + cluster_id, + plan, + prune, + confirm, + } => { + crate::compose_sync::apply( + s, + tx, + user, + &project_id, + cluster_id, + plan, + prune, + confirm, + wake, + ) + .await + } Op::CreateProject { id, team_id, From ea0149bc64bc6b9470e177494b2f6313a163442b Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 19:06:25 +0700 Subject: [PATCH 055/139] feat(cli): sync a project with pyo deploy -f The first deploy of a Compose file still imports it. After that the same command shows what changes and applies only that. --dry-run shows the plan and changes nothing, --prune also deletes services no longer in the file (asking first unless -y), and --project names the project. --- crates/pyo-cli/src/compose.rs | 329 +++++++++++++++++++++++++++++++--- crates/pyo-cli/src/main.rs | 63 +++++-- 2 files changed, 355 insertions(+), 37 deletions(-) diff --git a/crates/pyo-cli/src/compose.rs b/crates/pyo-cli/src/compose.rs index a94d0689..a0f96808 100644 --- a/crates/pyo-cli/src/compose.rs +++ b/crates/pyo-cli/src/compose.rs @@ -1,6 +1,9 @@ -//! `pyo deploy -f compose.yml`: import a Docker Compose file as a project. -//! Pyo shows what it makes of the file (and what it leaves out), then -//! creates and deploys it once you say yes. +//! `pyo deploy -f compose.yml`: a Docker Compose file as a project. The +//! first time, Pyo shows what it makes of the file (and what it leaves out), +//! then creates and deploys it once you say yes. After that, the same +//! command syncs the project with the file: Pyo shows what changes and +//! applies only that. `--dry-run` only shows it, and `--prune` also deletes +//! the services no longer in the file. use std::path::Path; @@ -9,13 +12,17 @@ use serde_json::{Value, json}; use crate::{api::Api, ui}; -pub async fn deploy( - api: &Api, - file: &Path, - team: Option<&str>, - cluster: Option<&str>, - yes: bool, -) -> Result<()> { +pub struct Opts<'a> { + pub team: Option<&'a str>, + pub cluster: Option<&'a str>, + /// The project to sync into (name, namespace or id). + pub project: Option<&'a str>, + pub dry_run: bool, + pub prune: bool, + pub yes: bool, +} + +pub async fn deploy(api: &Api, file: &Path, o: Opts<'_>) -> Result<()> { let text = std::fs::read_to_string(file) .with_context(|| format!("Couldn't read {}", file.display()))?; let dir = file @@ -27,16 +34,107 @@ pub async fn deploy( .ok() .and_then(|d| d.file_name().map(|n| n.to_string_lossy().into_owned())) .unwrap_or_default(); + let file_name = file + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); - let (team_id, cluster_id) = team_and_cluster(api, team, cluster).await?; + let (team_id, cluster_id) = team_and_cluster(api, o.team, o.cluster).await?; + let project_id = match o.project { + Some(p) => Some(project_in(api, &team_id, p).await?), + None => None, + }; let plan = api - .post("/api/v1/compose/preview", &json!({ "teamId": team_id, "file": text, "env": env, "clusterId": cluster_id, "name": name })) + .post( + "/api/v1/compose/sync-plan", + &json!({ "teamId": team_id, "projectId": project_id, "file": text, "env": env, "clusterId": cluster_id, "name": name, "fileName": file_name }), + ) .await?; - print_plan(&plan); + if plan["project"].is_null() { + return import(api, &plan["file"], &team_id, &cluster_id, &o).await; + } + print_sync(&plan, o.prune); + let services = plan["services"].as_array().cloned().unwrap_or_default(); + let changing = services + .iter() + .filter(|s| matches!(s["status"].as_str(), Some("added" | "changed"))) + .count(); + let deleting = services + .iter() + .filter(|s| s["status"] == "notInFile" && s["fromFile"] == true && o.prune) + .count(); + if changing == 0 && deleting == 0 { + println!("Nothing to change."); + return Ok(()); + } + if o.dry_run { + println!("Dry run: nothing was changed."); + return Ok(()); + } + let project = plan["project"]["name"].as_str().unwrap_or("the project"); + if !o.yes { + let mut q = format!("Apply this to {project}?"); + if deleting > 0 { + q = format!( + "Apply this to {project} and delete {deleting} service{}?", + if deleting == 1 { "" } else { "s" } + ); + } + let a = ui::ask(&format!("{q} [y/N] "))?; + if !matches!(a.to_lowercase().as_str(), "y" | "yes") { + println!("Nothing was changed."); + return Ok(()); + } + } + let mut body = json!({ "projectId": plan["project"]["id"], "plan": plan["file"], "prune": o.prune, "confirm": o.yes }); + // New services run where the project's do, unless --cluster says. + if o.cluster.is_some() { + body["clusterId"] = json!(cluster_id); + } + let r = api.op("syncCompose", body).await?; + let mut deploying = false; + for s in r["services"].as_array().into_iter().flatten() { + let status = s["status"].as_str().unwrap_or(""); + let dep = s["deploymentId"].as_str().unwrap_or(""); + deploying |= !dep.is_empty(); + println!( + "{} {} {}", + ui::green("✓"), + s["name"].as_str().unwrap_or(""), + ui::dim(if dep.is_empty() { status } else { dep }) + ); + if let Some(w) = s["warning"].as_str() { + println!(" {} {w}", ui::yellow("!")); + } + } + if deploying { + ui::ok(&format!( + "Deploying. Follow it in the dashboard: {}", + api.base + )); + } else { + ui::ok("Done."); + } + Ok(()) +} + +/// The first time: a new project from the file. +async fn import( + api: &Api, + plan: &Value, + team_id: &str, + cluster_id: &str, + o: &Opts<'_>, +) -> Result<()> { + print_plan(plan); + if o.dry_run { + println!("Dry run: nothing was created."); + return Ok(()); + } let services = plan["services"].as_array().map(Vec::len).unwrap_or(0); - if !yes { + if !o.yes { if !std::io::IsTerminal::is_terminal(&std::io::stdin()) { bail!("No terminal to ask on: pass -y to confirm."); } @@ -71,6 +169,20 @@ pub async fn deploy( Ok(()) } +/// A project of the team by id, namespace or name. +async fn project_in(api: &Api, team_id: &str, p: &str) -> Result { + let state = api.state().await?; + state.0["projects"] + .as_array() + .into_iter() + .flatten() + .filter(|x| x["teamId"] == json!(team_id)) + .find(|x| x["id"] == json!(p) || x["namespace"] == json!(p) || x["name"] == json!(p)) + .and_then(|x| x["id"].as_str()) + .map(str::to_owned) + .with_context(|| format!("No project {p} in this team")) +} + /// The team (slug or id, else the first) and its cluster (name or id, else /// the team's default) an import goes to. pub async fn team_and_cluster( @@ -110,6 +222,98 @@ pub async fn team_and_cluster( Ok((team_id, cluster_id)) } +/// A sync plan, service by service. +pub fn sync_lines(plan: &Value, prune: bool) -> Vec { + let mut out = vec![]; + let file = plan["file"]["project"]["file"].as_str().unwrap_or(""); + out.push(format!( + "{} {}", + ui::bold(plan["project"]["name"].as_str().unwrap_or("")), + ui::dim(&format!( + "(synced with {})", + if file.is_empty() { "its Compose file" } else { file } + )) + )); + let mut manual = vec![]; + for s in plan["services"].as_array().into_iter().flatten() { + let name = s["name"].as_str().unwrap_or(""); + let from_file = s["fromFile"] == true; + let (mark, words) = match s["status"].as_str().unwrap_or("") { + "added" => (ui::green("+"), "added".to_owned()), + "changed" => (ui::yellow("~"), "changed".to_owned()), + "notInFile" if from_file && prune => { + (ui::red("-"), "not in the file, so it's deleted".to_owned()) + } + "notInFile" if from_file => ( + ui::red("-"), + "not in the file. --prune deletes it.".to_owned(), + ), + "notInFile" => (ui::dim("-"), "not in the file, kept".to_owned()), + _ => (ui::dim("="), "unchanged".to_owned()), + }; + out.push(format!(" {mark} {} {}", ui::bold(name), ui::dim(&words))); + for c in s["changes"].as_array().into_iter().flatten() { + let field = c["field"].as_str().unwrap_or(""); + let line = match (c["from"].as_str(), c["to"].as_str()) { + (Some(a), Some(b)) => format!("{field}: {a} → {b}"), + (None, Some(b)) => format!("{field}: {b}"), + _ => field.to_owned(), + }; + out.push(format!(" {line}")); + } + for n in s["notes"].as_array().into_iter().flatten() { + out.push(format!( + " {}", + ui::dim(&format!( + "{}: {}", + n["field"].as_str().unwrap_or(""), + n["message"].as_str().unwrap_or("") + )) + )); + } + for m in s["manual"].as_array().into_iter().flatten() { + manual.push(format!( + " {} {name}, {}: {}", + ui::yellow("!"), + m["field"].as_str().unwrap_or(""), + m["message"].as_str().unwrap_or("") + )); + } + } + if !manual.is_empty() { + out.push(ui::yellow("Pyo leaves these as they are. Change them by hand:")); + out.extend(manual); + } + out.extend(warning_lines(&plan["warnings"])); + out +} + +fn print_sync(plan: &Value, prune: bool) { + for l in sync_lines(plan, prune) { + println!("{l}"); + } +} + +fn warning_lines(warnings: &Value) -> Vec { + let warnings = warnings.as_array().cloned().unwrap_or_default(); + if warnings.is_empty() { + return vec![]; + } + let mut out = vec![ui::yellow("Not carried over, or changed:")]; + for w in warnings { + let who = w["service"] + .as_str() + .map(|s| format!("{s}: ")) + .unwrap_or_default(); + out.push(format!( + " {} {who}{}", + ui::yellow("!"), + w["message"].as_str().unwrap_or("") + )); + } + out +} + fn print_plan(plan: &Value) { println!( "{} {}", @@ -158,6 +362,16 @@ fn print_plan(plan: &Value) { }; println!(" {} {line}", ui::dim("port")); } + let domains: Vec<&str> = s["domains"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .skip(1) + .collect(); + if !domains.is_empty() { + println!(" {} {}", ui::dim("domains"), domains.join(", ")); + } for v in s["volumes"].as_array().into_iter().flatten() { println!( " {} {} at {} ({} GiB{})", @@ -176,20 +390,83 @@ fn print_plan(plan: &Value) { if env > 0 { println!(" {} {env}", ui::dim("variables")); } - } - let warnings = plan["warnings"].as_array().cloned().unwrap_or_default(); - if !warnings.is_empty() { - println!("{}", ui::yellow("Not carried over, or changed:")); - for w in warnings { - let who = w["service"] - .as_str() - .map(|s| format!("{s}: ")) - .unwrap_or_default(); + let secrets: Vec<&str> = s["secrets"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + if !secrets.is_empty() { println!( - " {} {who}{}", - ui::yellow("!"), - w["message"].as_str().unwrap_or("") + " {} {} {}", + ui::dim("secrets"), + secrets.join(", "), + ui::dim("(set their values in Pyo)") ); } } + for l in warning_lines(&plan["warnings"]) { + println!("{l}"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn plain(lines: Vec) -> String { + let text = lines.join("\n"); + // No colors in the comparison. + let mut out = String::new(); + let mut skip = false; + for c in text.chars() { + match (skip, c) { + (_, '\x1b') => skip = true, + (true, 'm') => skip = false, + (true, _) => {} + (false, c) => out.push(c), + } + } + out + } + + #[test] + fn a_sync_plan_reads_service_by_service() { + let plan = json!({ + "project": { "id": "prj_a", "name": "cloud", "namespace": "cloud" }, + "file": { "project": { "file": "compose.yaml" } }, + "services": [ + { "name": "cloud-api", "status": "changed", "fromFile": true, "deploy": true, + "changes": [ + { "field": "image", "from": "ghcr.io/acme/cloud-api:1.2", "to": "ghcr.io/acme/cloud-api:1.3" }, + { "field": "env LOG_LEVEL" }, + { "field": "domain api.example.com", "to": "added" }], + "notes": [{ "field": "env DATABASE_URL", "message": "It's a secret in Pyo, so its value stays." }], + "manual": [] }, + { "name": "worker", "status": "added", "changes": [], "notes": [], "manual": [] }, + { "name": "db", "status": "unchanged", "fromFile": true, "changes": [], "notes": [], + "manual": [{ "field": "volume db-data", "message": "It's mounted at /var/lib/postgresql/data in Pyo and /data in the file. Detach it and attach it at /data to move it." }] }, + { "name": "old", "status": "notInFile", "fromFile": true, "changes": [], "notes": [], "manual": [] }, + { "name": "hand", "status": "notInFile", "fromFile": false, "changes": [], "notes": [], "manual": [] } + ], + "warnings": [] + }); + let text = plain(sync_lines(&plan, false)); + assert_eq!( + text, + "cloud (synced with compose.yaml) + ~ cloud-api changed + image: ghcr.io/acme/cloud-api:1.2 → ghcr.io/acme/cloud-api:1.3 + env LOG_LEVEL + domain api.example.com: added + env DATABASE_URL: It's a secret in Pyo, so its value stays. + + worker added + = db unchanged + - old not in the file. --prune deletes it. + - hand not in the file, kept +Pyo leaves these as they are. Change them by hand: + ! db, volume db-data: It's mounted at /var/lib/postgresql/data in Pyo and /data in the file. Detach it and attach it at /data to move it." + ); + assert!(plain(sync_lines(&plan, true)).contains("- old not in the file, so it's deleted")); + } } diff --git a/crates/pyo-cli/src/main.rs b/crates/pyo-cli/src/main.rs index 06c0cd59..9dbef03d 100644 --- a/crates/pyo-cli/src/main.rs +++ b/crates/pyo-cli/src/main.rs @@ -96,8 +96,9 @@ enum Command { /// /// A service built from a folder gets this folder, packed and uploaded /// (.gitignore and .pyoignore apply). In a folder no service is linked - /// to, it makes one and links it. With -f, import a Docker Compose file - /// instead: see what it makes, then deploy it. + /// to, it makes one and links it. With -f, deploy a Docker Compose file + /// instead: the first time it makes a project of it, and after that it + /// changes only what the file says differently. Deploy { #[command(flatten)] which: Which, @@ -113,21 +114,29 @@ enum Command { /// A new service's name. Defaults to the folder's. #[arg(long, conflicts_with = "file")] name: Option, - /// A new service's project (name or id), made when there's none by that name. - #[arg(long, conflicts_with = "file")] + /// A new service's project (name or id), made when there's none by + /// that name. With -f, the project the file goes to. + #[arg(long)] project: Option, - /// A Docker Compose file to import as a new project (a .env next to - /// it is read too). + /// A Docker Compose file to deploy as a project (a .env next to it + /// is read too). #[arg(long, short = 'f')] file: Option, + /// With -f: show what would change, and change nothing. + #[arg(long, requires = "file")] + dry_run: bool, + /// With -f: also delete the services made from the file that are no + /// longer in it. Their volumes are kept. + #[arg(long, requires = "file")] + prune: bool, /// The team of a new service or Compose import (slug or id). Defaults to your first team. #[arg(long)] team: Option, /// The cluster to run it on (name or id). Defaults to the team's default cluster. #[arg(long)] cluster: Option, - /// Don't ask: import the Compose file, or go ahead with a very - /// large replica change from pyo.jsonc. + /// Don't ask: deploy the Compose file (and delete with --prune), or + /// go ahead with a very large replica change. #[arg(long, short = 'y')] yes: bool, }, @@ -818,15 +827,23 @@ async fn run(mut cli: Cli) -> anyhow::Result<()> { file: Some(f), team, cluster, + project, + dry_run, + prune, yes, .. } => { compose::deploy( &config::client(url, token)?, &f, - team.as_deref(), - cluster.as_deref(), - yes, + compose::Opts { + team: team.as_deref(), + cluster: cluster.as_deref(), + project: project.as_deref(), + dry_run, + prune, + yes, + }, ) .await } @@ -1327,6 +1344,30 @@ mod tests { }) )); assert!(parse(&["pyo", "deploy", "--local", "-f", "compose.yml"]).is_err()); + assert!(matches!( + parse(&[ + "pyo", + "deploy", + "-f", + "compose.yml", + "--project", + "cloud", + "--dry-run", + "--prune", + "-y" + ]), + Ok(Command::Deploy { + file: Some(_), + project: Some(_), + dry_run: true, + prune: true, + yes: true, + .. + }) + )); + // Planning and pruning are for a Compose file. + assert!(parse(&["pyo", "deploy", "--dry-run"]).is_err()); + assert!(parse(&["pyo", "deploy", "--prune"]).is_err()); let Ok(Command::Env { command: Some(EnvCommand::Pull { file, out, secrets, .. From 192d6312316e3dda45ac828452fb8280e233d346 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 19:06:25 +0700 Subject: [PATCH 056/139] feat(dash): show the compose file a project comes from --- dash/src/lib/pyo/types.ts | 2 ++ dash/src/routes/_app/$team/$projectId.tsx | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/dash/src/lib/pyo/types.ts b/dash/src/lib/pyo/types.ts index 5ad8668d..e8ae9766 100644 --- a/dash/src/lib/pyo/types.ts +++ b/dash/src/lib/pyo/types.ts @@ -1301,6 +1301,8 @@ export type Application = { command?: string; /** How its image starts, where it differs from the image's own (Compose imports, templates). */ container?: { entrypoint?: string[]; command?: string[]; workingDir?: string; runAsUser?: number; runAsGroup?: number }; + /** The Compose file it was made from, and its name there. `pyo deploy -f` keeps it in line with the file. */ + compose?: { file: string; service: string }; source: ServiceSource; status: ServiceStatus; currentDeploymentId?: ID; diff --git a/dash/src/routes/_app/$team/$projectId.tsx b/dash/src/routes/_app/$team/$projectId.tsx index b1e40ad1..26c4727f 100644 --- a/dash/src/routes/_app/$team/$projectId.tsx +++ b/dash/src/routes/_app/$team/$projectId.tsx @@ -4,6 +4,7 @@ import { ArrowUpRightIcon, ChartLineUpIcon, DotsThreeIcon, + FileTextIcon, CubeIcon, GlobeSimpleIcon, GearSixIcon, @@ -76,6 +77,7 @@ function ProjectLayout() { const domain = st.apps .flatMap((a) => a.domains) .find((d) => d.status === "active"); + const composeFile = st.apps.find((a) => a.compose?.file)?.compose?.file; return ( @@ -122,6 +124,17 @@ function ProjectLayout() { {project.namespace} + {composeFile ? ( + + + + From {composeFile} + + + ) : null}

    From 60c8d004de224e932b33056ba9b4fb7fc63c013c Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 19:06:36 +0700 Subject: [PATCH 057/139] feat(api): limit where the installation admin can sign in An installation setting (pyo.settings 'admin_sign_in') lets the admin allow admin sign-in only from the tailnet and/or a list of IPv4 and IPv6 addresses or ranges. Off by default. From anywhere else an admin account can't sign in on any path (password, two-factor code, passkey, sign-in link, pyo login) and gets the same answer as a wrong password, code or link. The refusal goes to the audit log and the account's email. Its browser sessions answer as signed out there. Its API keys and assistants keep working as a team member without admin powers. The address is the visitor as the trusted proxy walk finds it. The tailnet counts only for a Tailscale address that asked for a .ts.net name. Saving a limit that would shut out the request saving it is refused. A sign-in link from pyo-reset-login turns the limit off, and PYO_ADMIN_SIGNIN_ANYWHERE=1 ignores it. The new saveAdminSignIn operation is not for API keys, so it has no MCP tool. --- crates/pyo-api/src/admin_sign_in.rs | 574 ++++++++++++++++++++++++++++ crates/pyo-api/src/audit.rs | 16 +- crates/pyo-api/src/auth.rs | 73 +++- crates/pyo-api/src/cli.rs | 84 ++-- crates/pyo-api/src/install.rs | 3 +- crates/pyo-api/src/lib.rs | 1 + crates/pyo-api/src/mail.rs | 14 + crates/pyo-api/src/oauth.rs | 10 +- crates/pyo-api/src/ops.rs | 29 ++ crates/pyo-api/src/passkeys.rs | 6 + crates/pyo-api/src/ratelimit.rs | 22 ++ crates/pyo-api/src/recovery.rs | 26 +- crates/pyo-api/src/snapshot.rs | 13 +- crates/pyo-api/src/twofactor.rs | 18 +- 14 files changed, 835 insertions(+), 54 deletions(-) create mode 100644 crates/pyo-api/src/admin_sign_in.rs diff --git a/crates/pyo-api/src/admin_sign_in.rs b/crates/pyo-api/src/admin_sign_in.rs new file mode 100644 index 00000000..ed218983 --- /dev/null +++ b/crates/pyo-api/src/admin_sign_in.rs @@ -0,0 +1,574 @@ +//! Where the installation's admins may sign in from (Settings › Security). +//! +//! An admin has powers over the whole installation, and on Pyo Cloud its +//! staff sign in on the same public page as everyone else. So the admin +//! can limit where admin accounts sign in: from the tailnet, and from +//! addresses or ranges (IPv4 and IPv6). Neither, the default: anywhere. +//! It's kept in `pyo.settings` as 'admin_sign_in'. +//! +//! From anywhere else, an admin account +//! - can't sign in, on any path: a password, a two-factor code, a passkey, +//! a sign-in link, `pyo login`. The answer is the one a wrong password, +//! code or link gets, so it tells nothing of the account or the limit. +//! The account's audit log says so, and its email when Pyo sends email. +//! - has no browser session: its requests are unauthorized, as if signed +//! out. The session stays, for when it's back where it may be. A stolen +//! cookie works nowhere else. +//! - acts as a member only through API keys and assistants (OAuth): it +//! keeps its teams but loses its admin powers. Keys never change the +//! installation anyway (ops.rs `key_access_for`), and scripts and CI run +//! from anywhere. +//! +//! Nobody else is ever affected. +//! +//! Where a request comes from is its visitor (ratelimit.rs `visitor_of`): +//! the TCP peer, unless that's a trusted proxy (Pyo's Gateway, cloudflared, +//! `PYO_TRUSTED_PROXIES`), whose headers alone count. It's on the tailnet +//! when that address is Tailscale's and it asked for a tailnet name +//! (`*.ts.net`): only the tailnet Gateway serves those, and it admits +//! Tailscale's addresses and the servers only. A public Gateway has no +//! route for them, so an address in Tailscale's range that isn't one (a +//! carrier's shared NAT) never counts. pyo-forward's :8000 shows up as a +//! server's own end of the pod network: it also admits local and private +//! peers, so it's never the tailnet. +//! +//! Locked out: a sign-in link from `pyo-reset-login` on the server turns +//! the limit off (recovery.rs). `PYO_ADMIN_SIGNIN_ANYWHERE=1` on Pyo's +//! deployment ignores it while it's set, for Pyo Cloud, which has no +//! server to run that on. + +use std::{convert::Infallible, net::IpAddr}; + +use axum::{ + extract::{ConnectInfo, FromRequestParts}, + http::{HeaderMap, header, request::Parts}, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sqlx::PgConnection; + +use crate::{ + AppState, + auth::User, + error::{ApiError, ApiResult}, + ratelimit::Cidr, +}; + +/// The most addresses and ranges the limit takes. +pub const MAX_ADDRESSES: usize = 100; + +/// The env var that ignores the limit while it's set ("1" or "true"). +pub const ANYWHERE_ENV: &str = "PYO_ADMIN_SIGNIN_ANYWHERE"; + +/// Where admin accounts may sign in from. Neither: anywhere. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Limit { + /// From the tailnet. + #[serde(default)] + pub tailnet: bool, + /// From these addresses and ranges ("203.0.113.7", "2001:db8::/48"). + #[serde(default)] + pub addresses: Vec, +} + +impl Limit { + pub fn is_on(&self) -> bool { + self.tailnet || !self.addresses.is_empty() + } + + /// Whether an admin may sign in from `from`. + pub fn allows(&self, from: &Source) -> bool { + if !self.is_on() || (self.tailnet && from.tailnet) { + return true; + } + from.ip.is_some_and(|ip| { + self.addresses + .iter() + .filter_map(|a| Cidr::parse(a)) + .any(|c| c.contains(&ip)) + }) + } + + /// In words, for the activity: "the tailnet and 2 addresses". + fn summary(&self) -> String { + let n = self.addresses.len(); + let addresses = match n { + 0 => None, + 1 => Some(self.addresses[0].clone()), + n => Some(format!("{n} addresses")), + }; + match (self.tailnet, addresses) { + (true, Some(a)) => format!("the tailnet and {a}"), + (true, None) => "the tailnet".into(), + (false, Some(a)) => a, + (false, None) => "anywhere".into(), + } + } +} + +/// Where a request comes from: its visitor's address, and whether it came +/// over the tailnet. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Source { + pub ip: Option, + pub tailnet: bool, +} + +impl Source { + /// From the TCP peer and the request's headers. `authority`: the URI's, + /// for a request without a Host header (HTTP/2). + pub fn of(peer: &str, headers: &HeaderMap, authority: Option<&str>) -> Self { + Self::from_visitor( + &crate::ratelimit::visitor_of(peer, headers), + host_of(headers, authority), + ) + } + + /// From a visitor's address (already worked out from trusted proxies + /// only) and the host name it asked for. + pub fn from_visitor(visitor: &str, host: &str) -> Self { + let ip = visitor + .trim() + .trim_matches(['[', ']']) + .parse::() + .ok() + .map(|a| a.to_canonical()); + let name = host.split(':').next().unwrap_or("").trim_end_matches('.'); + let tailnet = + ip.is_some_and(|a| tailscale_address(&a)) && pyo_proto::system::is_tailnet_host(name); + Source { ip, tailnet } + } + + pub fn from_parts(parts: &Parts) -> Self { + let peer = parts + .extensions + .get::>() + .map(|c| c.0.ip().to_string()) + .unwrap_or_default(); + Self::of( + &peer, + &parts.headers, + parts.uri.authority().map(|a| a.as_str()), + ) + } + + /// The address in words. + pub fn shown(&self) -> String { + self.ip + .map(|a| a.to_string()) + .unwrap_or_else(|| "an unknown address".into()) + } +} + +impl FromRequestParts for Source { + type Rejection = Infallible; + + async fn from_request_parts(parts: &mut Parts, _: &S) -> Result { + Ok(Source::from_parts(parts)) + } +} + +/// The host name a request asked for: its Host header, else (HTTP/2) its +/// URI's authority. +pub fn host_of<'a>(headers: &'a HeaderMap, authority: Option<&'a str>) -> &'a str { + headers + .get(header::HOST) + .and_then(|v| v.to_str().ok()) + .or(authority) + .unwrap_or("") +} + +/// One of Tailscale's addresses (100.64.0.0/10, fd7a:115c:a1e0::/48). +fn tailscale_address(ip: &IpAddr) -> bool { + pyo_proto::system::TAILNET_CIDRS + .iter() + .filter_map(|c| Cidr::parse(c)) + .any(|c| c.contains(ip)) +} + +/// Whether `PYO_ADMIN_SIGNIN_ANYWHERE` is set: the limit is ignored. +pub fn anywhere() -> bool { + static A: std::sync::OnceLock = std::sync::OnceLock::new(); + *A.get_or_init(|| { + let on = matches!( + std::env::var(ANYWHERE_ENV).as_deref().map(str::trim), + Ok("1" | "true") + ); + if on { + tracing::warn!("{ANYWHERE_ENV} is set: admins may sign in from anywhere"); + } + on + }) +} + +/// The installation's limit, as saved. +pub async fn load(db: impl sqlx::PgExecutor<'_>) -> sqlx::Result { + let v: Option = + sqlx::query_scalar("SELECT value FROM pyo.settings WHERE key = 'admin_sign_in'") + .fetch_optional(db) + .await?; + Ok(v.and_then(|v| serde_json::from_value(v).ok()) + .unwrap_or_default()) +} + +/// Whether an admin account may act from `from`: what the limit allows, +/// or anywhere while `PYO_ADMIN_SIGNIN_ANYWHERE` is set. +pub async fn admits(db: impl sqlx::PgExecutor<'_>, from: &Source) -> sqlx::Result { + if anywhere() { + return Ok(true); + } + Ok(load(db).await?.allows(from)) +} + +/// A limit to save: each address or range checked and written plainly +/// (its network address, no /32 or /128), duplicates dropped. +pub fn checked(tailnet: bool, addresses: &[String]) -> ApiResult { + let mut out: Vec = vec![]; + for a in addresses.iter().map(|a| a.trim()).filter(|a| !a.is_empty()) { + let well_formed = match a.split_once('/') { + Some((_, len)) => !len.is_empty() && len.bytes().all(|b| b.is_ascii_digit()), + None => true, + }; + let cidr = Cidr::parse(a).filter(|_| well_formed).ok_or_else(|| { + ApiError::bad_request(format!("{a} isn't an IP address or range.")) + })?; + let plain = cidr.to_string(); + if !out.contains(&plain) { + out.push(plain); + } + } + if out.len() > MAX_ADDRESSES { + return Err(ApiError::bad_request(format!( + "Add up to {MAX_ADDRESSES} addresses." + ))); + } + Ok(Limit { + tailnet, + addresses: out, + }) +} + +/// A new limit must keep letting in the request that saves it, so its +/// admin can't lock themselves out. +pub fn keeps(limit: &Limit, here: &Source) -> ApiResult<()> { + if limit.allows(here) { + return Ok(()); + } + Err(ApiError::bad_request(match here.ip { + Some(ip) => format!("This would lock you out. Add your address {ip} first."), + None => "This would lock you out. Pyo can't tell your address.".to_owned(), + })) +} + +/// Saves the limit (off when it allows anywhere). Returns what it was. +pub async fn save(conn: &mut PgConnection, limit: &Limit) -> sqlx::Result { + let before = load(&mut *conn).await?; + if limit.is_on() { + sqlx::query( + "INSERT INTO pyo.settings (key, value) VALUES ('admin_sign_in', $1) + ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = now()", + ) + .bind(json!(limit)) + .execute(&mut *conn) + .await?; + } else { + sqlx::query("DELETE FROM pyo.settings WHERE key = 'admin_sign_in'") + .execute(&mut *conn) + .await?; + } + Ok(before) +} + +/// What the activity says of a change. +pub fn change_title(limit: &Limit) -> String { + if limit.is_on() { + format!("Limited admin sign-in to {}", limit.summary()) + } else { + "Let admins sign in from anywhere".into() + } +} + +/// Turns the limit off (a sign-in link made on the server). Whether it +/// was on. +pub async fn turn_off(conn: &mut PgConnection) -> sqlx::Result { + Ok(save(conn, &Limit::default()).await?.is_on()) +} + +/// Whether `user` may sign in from `from` (`how`: "with a password"). +/// Everyone may, but the installation's admins only from where the limit +/// allows. A refusal goes to the account's audit log, and its email. +/// `user.is_admin` is the account's own (`pyo.users.is_admin`). +pub async fn sign_in_allowed( + state: &AppState, + user: &User, + from: &Source, + how: &str, +) -> ApiResult { + if !user.is_admin || admits(&state.db, from).await? { + return Ok(true); + } + refused(state, user, from, how).await; + Ok(false) +} + +/// A refused admin sign-in, in the audit log and the account's email. +pub async fn refused(state: &AppState, user: &User, from: &Source, how: &str) { + tracing::warn!(user = %user.id, ip = %from.shown(), how, "admin sign-in refused: not from an allowed address"); + crate::audit::account_event( + &state.db, + &user.id, + &crate::audit::Who::person(user), + crate::audit::Entry { + action: "auth.sign_in_refused", + title: &format!("Sign-in {how} refused outside the allowed addresses"), + target: json!({}), + failed: true, + }, + ) + .await; + let (s, to, ip) = (state.clone(), user.email.clone(), from.shown()); + tokio::spawn(async move { + crate::twofactor::mail_user(&s, &to, "/security", |link| { + crate::mail::sign_in_refused(&ip, link) + }) + .await; + }); +} + +/// For the dashboard (its admin): the limit, where this request comes +/// from, whether the tailnet can be chosen, and whether the limit is +/// ignored (`PYO_ADMIN_SIGNIN_ANYWHERE`). +pub async fn snapshot(db: &sqlx::PgPool, here: &Source) -> sqlx::Result { + let limit = load(db).await?; + Ok(json!({ + "tailnet": limit.tailnet, + "addresses": limit.addresses, + "here": here.ip.map(|a| a.to_string()), + "hereTailnet": here.tailnet, + "tailnetAvailable": crate::web::addresses().tailnet.is_some() || here.tailnet, + "anywhere": anywhere(), + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::net::SocketAddr; + + fn src(ip: &str, tailnet: bool) -> Source { + Source { + ip: Some(ip.parse().unwrap()), + tailnet, + } + } + + fn limit(tailnet: bool, addresses: &[&str]) -> Limit { + checked( + tailnet, + &addresses.iter().map(|a| a.to_string()).collect::>(), + ) + .unwrap() + } + + #[test] + fn off_by_default_allows_anywhere() { + let l = Limit::default(); + assert!(!l.is_on()); + assert!(l.allows(&src("203.0.113.7", false))); + assert!(l.allows(&Source::default())); + let saved: Limit = serde_json::from_value(json!({})).unwrap(); + assert_eq!(saved, l); + } + + #[test] + fn addresses_and_ranges_v4_and_v6() { + let l = limit(false, &["203.0.113.7", "198.51.100.0/24", "2001:db8:42::/48"]); + assert!(l.allows(&src("203.0.113.7", false))); + assert!(!l.allows(&src("203.0.113.8", false))); + assert!(l.allows(&src("198.51.100.250", false))); + assert!(!l.allows(&src("198.51.101.1", false))); + assert!(l.allows(&src("2001:db8:42:1::9", false))); + assert!(!l.allows(&src("2001:db8:43::9", false))); + // IPv4 written as IPv6 is the same address. + let mapped = Source { + ip: Some("::ffff:203.0.113.7".parse::().unwrap().to_canonical()), + tailnet: false, + }; + assert!(l.allows(&mapped)); + // No address: nothing to match. + assert!(!l.allows(&Source::default())); + // The tailnet isn't on the list. + assert!(!l.allows(&src("100.101.102.103", true))); + } + + #[test] + fn tailnet_only() { + let l = limit(true, &[]); + assert!(l.is_on()); + assert!(l.allows(&src("100.101.102.103", true))); + // A Tailscale address that didn't come over the tailnet. + assert!(!l.allows(&src("100.101.102.103", false))); + assert!(!l.allows(&src("203.0.113.7", false))); + // Both: either will do. + let both = limit(true, &["203.0.113.7"]); + assert!(both.allows(&src("100.101.102.103", true))); + assert!(both.allows(&src("203.0.113.7", false))); + assert!(!both.allows(&src("203.0.113.9", false))); + } + + #[test] + fn saved_plainly_and_checked() { + let l = limit( + false, + &[" 203.0.113.7/32 ", "198.51.100.9/24", "2001:DB8::1/128", "", "203.0.113.7"], + ); + assert_eq!(l.addresses, ["203.0.113.7", "198.51.100.0/24", "2001:db8::1"]); + for bad in ["nope", "203.0.113.7/33", "203.0.113.7/", "203.0.113.7/abc", "2001:db8::/129", "10.0.0.0/8/8"] { + let e = checked(false, &[bad.to_owned()]).unwrap_err(); + assert!(e.message.contains("isn't an IP address or range"), "{bad}: {}", e.message); + } + let many: Vec = (0..=MAX_ADDRESSES).map(|i| format!("10.0.{}.{}", i / 250, i % 250)).collect(); + assert!(checked(false, &many).is_err()); + assert!(checked(false, &many[..MAX_ADDRESSES]).is_ok()); + } + + #[test] + fn saving_never_locks_out_the_one_saving() { + let here = src("203.0.113.7", false); + assert!(keeps(&limit(false, &["203.0.113.0/24"]), &here).is_ok()); + assert!(keeps(&Limit::default(), &here).is_ok()); + let e = keeps(&limit(true, &[]), &here).unwrap_err(); + assert_eq!(e.message, "This would lock you out. Add your address 203.0.113.7 first."); + assert!(keeps(&limit(false, &["198.51.100.1"]), &here).is_err()); + assert!(keeps(&limit(true, &[]), &src("100.101.102.103", true)).is_ok()); + assert!(keeps(&limit(true, &[]), &Source::default()).is_err()); + } + + #[test] + fn titles() { + assert_eq!(change_title(&Limit::default()), "Let admins sign in from anywhere"); + assert_eq!(change_title(&limit(true, &[])), "Limited admin sign-in to the tailnet"); + assert_eq!( + change_title(&limit(true, &["203.0.113.7"])), + "Limited admin sign-in to the tailnet and 203.0.113.7" + ); + assert_eq!( + change_title(&limit(false, &["203.0.113.7", "2001:db8::/32"])), + "Limited admin sign-in to 2 addresses" + ); + } + + /// A request as Pyo gets it: its TCP peer and headers. + fn parts(peer: &str, host: &str, headers: &[(&str, &str)]) -> Parts { + let mut b = axum::http::Request::builder().uri("/api/auth/login"); + if !host.is_empty() { + b = b.header("host", host); + } + for (k, v) in headers { + b = b.header(*k, *v); + } + let mut r = b.body(()).unwrap(); + r.extensions_mut() + .insert(ConnectInfo(peer.parse::().unwrap())); + r.into_parts().0 + } + + fn source(peer: &str, host: &str, headers: &[(&str, &str)]) -> Source { + Source::from_parts(&parts(peer, host, headers)) + } + + const TS: &str = "pyo.tail1234.ts.net"; + const PUBLIC: &str = "pyo.203-0-113-1.nip.io"; + + #[test] + fn the_tailnet_through_the_tailnet_gateway() { + // The tailnet Gateway (a pod) appends the device's own address. + assert_eq!( + source("10.42.0.7:5000", TS, &[("x-forwarded-for", "100.101.102.103")]), + src("100.101.102.103", true) + ); + assert_eq!( + source("10.42.0.7:5000", TS, &[("x-forwarded-for", "fd7a:115c:a1e0::5")]), + src("fd7a:115c:a1e0::5", true) + ); + // Port and a trailing dot in the host name. + assert_eq!( + source("10.42.0.7:5000", "pyo.tail1234.ts.net.:443", &[("x-forwarded-for", "100.101.102.103")]), + src("100.101.102.103", true) + ); + // HTTP/2: no Host header, the URI's authority. + let mut r = axum::http::Request::builder() + .uri(format!("https://{TS}/api/auth/login")) + .header("x-forwarded-for", "100.101.102.103") + .body(()) + .unwrap(); + r.extensions_mut() + .insert(ConnectInfo("10.42.0.7:5000".parse::().unwrap())); + assert_eq!(Source::from_parts(&r.into_parts().0), src("100.101.102.103", true)); + } + + #[test] + fn spoofed_headers_from_an_untrusted_peer_never_count() { + // Straight from the internet, whatever it claims. + for h in [ + ("x-forwarded-for", "100.101.102.103"), + ("cf-connecting-ip", "100.101.102.103"), + ("x-real-ip", "100.101.102.103"), + ("forwarded", "for=100.101.102.103"), + ] { + assert_eq!(source("203.0.113.9:5000", TS, &[h]), src("203.0.113.9", false), "{h:?}"); + } + // A listed address, claimed. + let l = limit(false, &["198.51.100.7"]); + let s = source("203.0.113.9:5000", PUBLIC, &[("x-forwarded-for", "198.51.100.7"), ("cf-connecting-ip", "198.51.100.7")]); + assert!(!l.allows(&s)); + // Through the public Gateway: what the client wrote sits to the + // left of the address the Gateway appended. + let s = source("10.42.0.7:5000", PUBLIC, &[("x-forwarded-for", "198.51.100.7, 203.0.113.9")]); + assert_eq!(s, src("203.0.113.9", false)); + assert!(!l.allows(&s)); + // And a made-up CF-Connecting-IP from the pod network (the Gateway + // passes on what its client sent) never counts. + let s = source("10.42.0.7:5000", PUBLIC, &[("cf-connecting-ip", "198.51.100.7"), ("x-forwarded-for", "203.0.113.9")]); + assert_eq!(s, src("203.0.113.9", false)); + // A server's own end of the pod network (pyo-forward's :8000, which + // admits local and private peers too) passes on nothing, and isn't + // the tailnet even with a tailnet name. + let s = source("10.42.0.1:5000", TS, &[("x-forwarded-for", "100.101.102.103")]); + assert_eq!(s, src("10.42.0.1", false)); + } + + #[test] + fn a_tailscale_address_off_the_tailnet_isn_t_the_tailnet() { + // A carrier's shared NAT (100.64.0.0/10) on a public name. + assert_eq!( + source("10.42.0.7:5000", PUBLIC, &[("x-forwarded-for", "100.64.1.2")]), + src("100.64.1.2", false) + ); + assert_eq!(source("100.64.1.2:5000", PUBLIC, &[]), src("100.64.1.2", false)); + // A tailnet name with an address that isn't Tailscale's. + assert_eq!( + source("10.42.0.7:5000", TS, &[("x-forwarded-for", "203.0.113.9")]), + src("203.0.113.9", false) + ); + } + + /// Pyo Cloud: cloudflared, then Pyo Ops' Gateway, both pods. The + /// visitor is what Cloudflare's edge put last in X-Forwarded-For, the + /// address it also sends as CF-Connecting-IP. + #[test] + fn behind_cloudflare_s_tunnel() { + let s = source( + "10.42.1.9:5000", + "cloud.pyo.dev", + &[ + ("cf-connecting-ip", "198.51.100.20"), + ("x-forwarded-for", "6.6.6.6, 198.51.100.20, 10.42.0.33"), + ], + ); + assert_eq!(s, src("198.51.100.20", false)); + assert!(limit(false, &["198.51.100.0/24"]).allows(&s)); + assert!(!limit(false, &["6.6.6.6"]).allows(&s)); + } +} diff --git a/crates/pyo-api/src/audit.rs b/crates/pyo-api/src/audit.rs index a18585fa..996bed0c 100644 --- a/crates/pyo-api/src/audit.rs +++ b/crates/pyo-api/src/audit.rs @@ -120,6 +120,8 @@ impl Who { /// What a request says about itself, for its entries. struct RequestInfo { ip: String, + /// The same address, and whether it came over the tailnet. + source: crate::admin_sign_in::Source, user_agent: String, actor: Mutex>, } @@ -140,13 +142,25 @@ fn request_info(req: &Request) -> RequestInfo { .get::>() .map(|c| c.0.ip().to_string()) .unwrap_or_default(); + let ip = crate::ratelimit::visitor_of(&peer, req.headers()); + let host = + crate::admin_sign_in::host_of(req.headers(), req.uri().authority().map(|a| a.as_str())); RequestInfo { - ip: crate::ratelimit::visitor_of(&peer, req.headers()), + source: crate::admin_sign_in::Source::from_visitor(&ip, host), + ip, user_agent: user_agent(req.headers()), actor: Mutex::new(None), } } +/// Where the request being handled comes from (admin_sign_in.rs). Outside +/// a request: nowhere known. +pub fn request_source() -> crate::admin_sign_in::Source { + REQUEST + .try_with(|r| r.source.clone()) + .unwrap_or_default() +} + /// A browser's User-Agent, cut to a sane length. pub fn user_agent(headers: &axum::http::HeaderMap) -> String { headers diff --git a/crates/pyo-api/src/auth.rs b/crates/pyo-api/src/auth.rs index 27a3c889..84d730cc 100644 --- a/crates/pyo-api/src/auth.rs +++ b/crates/pyo-api/src/auth.rs @@ -165,7 +165,8 @@ impl FromRequestParts for AnySession { .get(SESSION_COOKIE) .map(|c| c.value().to_owned()) .ok_or_else(ApiError::unauthorized)?; - let user = session_user(&state.db, &token) + let from = crate::admin_sign_in::Source::from_parts(parts); + let user = session_user(&state.db, &token, &from) .await? .ok_or_else(ApiError::unauthorized)?; if parts.method != axum::http::Method::GET @@ -178,14 +179,29 @@ impl FromRequestParts for AnySession { } } +/// A session's user, and whether the account is an admin at all. +#[derive(sqlx::FromRow)] +struct SessionRow { + #[sqlx(flatten)] + user: User, + account_admin: bool, +} + /// The user of a session cookie's token, while the session lasts. In use, /// its idle limit moves on (at most once an hour, never past the absolute /// one). An admin who must set up two-factor first isn't one until then -/// (twofactor.rs). -async fn session_user(db: &sqlx::PgPool, token: &str) -> ApiResult> { +/// (twofactor.rs). An admin account's session works only from where +/// admins may sign in (admin_sign_in.rs): elsewhere it's as if signed out, +/// and it doesn't move on. +async fn session_user( + db: &sqlx::PgPool, + token: &str, + from: &crate::admin_sign_in::Source, +) -> ApiResult> { let hash = sha256_hex(token); - let user = sqlx::query_as::<_, User>( - "SELECT u.id, u.name, u.email, u.timezone, u.is_admin AND NOT pyo.needs_two_factor(u.id, $3) AS is_admin, u.must_set_up + let row = sqlx::query_as::<_, SessionRow>( + "SELECT u.id, u.name, u.email, u.timezone, u.is_admin AND NOT pyo.needs_two_factor(u.id, $3) AS is_admin, u.must_set_up, + u.is_admin AS account_admin FROM pyo.sessions s JOIN pyo.users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > now() AND s.created_at > now() - make_interval(days => $2)", ) @@ -194,6 +210,10 @@ async fn session_user(db: &sqlx::PgPool, token: &str) -> ApiResult> .bind(crate::hosted()) .fetch_optional(db) .await?; + let user = match row { + Some(r) if r.account_admin && !crate::admin_sign_in::admits(db, from).await? => None, + r => r.map(|r| r.user), + }; if user.is_some() { let _ = sqlx::query( "UPDATE pyo.sessions SET expires_at = least(created_at + make_interval(days => $2), now() + make_interval(days => $3)) @@ -250,7 +270,19 @@ impl FromRequestParts for TokenUser { })?; let token = token.to_owned(); let Ok(ClientIp(ip)) = ClientIp::from_request_parts(parts, state).await; - Ok(TokenUser(key_user_from(&state.db, &token, &ip).await?)) + let mut user = key_user_from(&state.db, &token, &ip).await?; + // From where admins may not sign in, an admin's key acts as a + // member only (admin_sign_in.rs). + if user.is_admin + && !crate::admin_sign_in::admits( + &state.db, + &crate::admin_sign_in::Source::from_parts(parts), + ) + .await? + { + user.is_admin = false; + } + Ok(TokenUser(user)) } } @@ -774,6 +806,7 @@ struct LoginBody { async fn login( State(state): State, ClientIp(ip): ClientIp, + from: crate::admin_sign_in::Source, headers: HeaderMap, jar: CookieJar, Json(body): Json, @@ -826,16 +859,7 @@ async fn login( ) .await; } - return Err(ApiError::new( - StatusCode::UNAUTHORIZED, - "Wrong email or password.", - )); - } - ratelimit::reset(&state.db, &ratelimit::LOGIN_ACCOUNT, &email).await?; - ratelimit::forgive(&state.db, &ratelimit::LOGIN_IP, &ip).await?; - if crate::twofactor::enabled(&state.db, &id).await? { - let challenge = crate::twofactor::start_challenge(&state.db, &id, "password").await?; - return Ok((jar, Json(crate::twofactor::code_needed(&challenge)))); + return Err(wrong_password()); } let user = User { id, @@ -846,6 +870,17 @@ async fn login( must_set_up, key: None, }; + // An admin from where admins may not sign in: as a wrong password, and + // its slots stay taken. + if !crate::admin_sign_in::sign_in_allowed(&state, &user, &from, "with a password").await? { + return Err(wrong_password()); + } + ratelimit::reset(&state.db, &ratelimit::LOGIN_ACCOUNT, &user.email).await?; + ratelimit::forgive(&state.db, &ratelimit::LOGIN_IP, &ip).await?; + if crate::twofactor::enabled(&state.db, &user.id).await? { + let challenge = crate::twofactor::start_challenge(&state.db, &user.id, "password").await?; + return Ok((jar, Json(crate::twofactor::code_needed(&challenge)))); + } crate::audit::account_event( &state.db, &user.id, @@ -862,6 +897,10 @@ async fn login( Ok((jar, Json(json!(user)))) } +fn wrong_password() -> ApiError { + ApiError::new(StatusCode::UNAUTHORIZED, "Wrong email or password.") +} + /// Is this the account's password? The same check, and the same work, as /// signing in. pub(crate) async fn password_matches( @@ -1224,7 +1263,7 @@ mod invite_tests { let ask = |token: String| { let pool = pool.clone(); async move { - session_user(&pool, &token) + session_user(&pool, &token, &Default::default()) .await .unwrap() .map(|u| u.id) diff --git a/crates/pyo-api/src/cli.rs b/crates/pyo-api/src/cli.rs index e2e50de7..7e7b73c6 100644 --- a/crates/pyo-api/src/cli.rs +++ b/crates/pyo-api/src/cli.rs @@ -274,10 +274,18 @@ struct TokenBody { /// The CLI's poll: `{"status": "pending"}` until the page answers, then /// the key once (approved), or an error that says why not. -async fn token(State(s): State, Json(b): Json) -> ApiResult> { - Ok(Json(match poll_login(&s.db, &b.id, &b.verifier).await? { - None => json!({ "status": "pending" }), - Some((key, user_name, email)) => { +async fn token( + State(s): State, + from: crate::admin_sign_in::Source, + Json(b): Json, +) -> ApiResult> { + Ok(Json(match poll_login(&s.db, &b.id, &b.verifier, &from).await? { + Polled::Pending => json!({ "status": "pending" }), + Polled::Refused(user) => { + crate::admin_sign_in::refused(&s, &user, &from, "with pyo login").await; + return Err(mismatch()); + } + Polled::Key(key, user_name, email) => { let (s2, to) = (s.clone(), email.clone()); tokio::spawn(async move { crate::twofactor::mail_user(&s2, &to, "/api-keys", |link| { @@ -292,16 +300,33 @@ async fn token(State(s): State, Json(b): Json) -> ApiResult /// A request as the poll reads it: challenge, status, who approved it, /// the computer's name and the key's days. -type Polled = (String, String, Option, String, Option); +type RequestRow = (String, String, Option, String, Option); + +/// What a poll finds. +#[derive(Debug)] +enum Polled { + Pending, + /// The new key, and its user's name and email. + Key(String, String, String), + /// Approved by an admin, polled from where admins may not sign in + /// (admin_sign_in.rs): no key, and the request is gone. + Refused(crate::auth::User), +} + +/// What a verifier is told when its request isn't one it may have. +fn mismatch() -> ApiError { + ApiError::bad_request("That login doesn't match. Run pyo login again.") +} -/// None while pending, else the new key and its user's name and email. +/// A poll from `from`: pending, the key, or refused. async fn poll_login( db: &PgPool, id: &str, verifier: &str, -) -> ApiResult> { + from: &crate::admin_sign_in::Source, +) -> ApiResult { let mut tx = db.begin().await?; - let row: Option = sqlx::query_as( + let row: Option = sqlx::query_as( "SELECT challenge, status, user_id, name, key_days FROM pyo.cli_login_requests WHERE id = $1 AND expires_at > now() FOR UPDATE", ) .bind(id) @@ -311,12 +336,10 @@ async fn poll_login( return Err(expired()); }; if sha256_hex(verifier) != challenge { - return Err(ApiError::bad_request( - "That login doesn't match. Run pyo login again.", - )); + return Err(mismatch()); } let user_id = match (status.as_str(), user_id) { - ("pending", _) => return Ok(None), + ("pending", _) => return Ok(Polled::Pending), ("approved", Some(u)) => u, _ => { sqlx::query("DELETE FROM pyo.cli_login_requests WHERE id = $1") @@ -331,6 +354,16 @@ async fn poll_login( .bind(id) .execute(&mut *tx) .await?; + let user = sqlx::query_as::<_, crate::auth::User>( + "SELECT id, name, email, timezone, is_admin, must_set_up FROM pyo.users WHERE id = $1", + ) + .bind(&user_id) + .fetch_one(&mut *tx) + .await?; + if user.is_admin && !crate::admin_sign_in::admits(&mut *tx, from).await? { + tx.commit().await?; + return Ok(Polled::Refused(user)); + } let name = if name.is_empty() { "CLI".to_owned() } else { @@ -346,12 +379,6 @@ async fn poll_login( .bind(days) .execute(&mut *tx) .await?; - let user = sqlx::query_as::<_, crate::auth::User>( - "SELECT id, name, email, timezone, is_admin, must_set_up FROM pyo.users WHERE id = $1", - ) - .bind(&user_id) - .fetch_one(&mut *tx) - .await?; // A new key: the account's teams hear of it (and the account by email, // from `token`). It's the account's doing, through the CLI. crate::audit::set_actor(&user, crate::audit::Via::Api, Some(&name)); @@ -363,7 +390,7 @@ async fn poll_login( ) .await?; tx.commit().await?; - Ok(Some((key, user.name, user.email))) + Ok(Polled::Key(key, user.name, user.email)) } #[cfg(test)] @@ -437,8 +464,9 @@ mod tests { // Approved with its code: the key goes to the verifier, once. let (id, code) = start_login(&pool, &body(Some("30d"))).await.unwrap(); - assert!(poll_login(&pool, &id, &verifier).await.unwrap().is_none()); - assert!(msg(poll_login(&pool, &id, "wrong").await.unwrap_err()).contains("doesn't match")); + let here = crate::admin_sign_in::Source::default(); + assert!(matches!(poll_login(&pool, &id, &verifier, &here).await.unwrap(), Polled::Pending)); + assert!(msg(poll_login(&pool, &id, "wrong", &here).await.unwrap_err()).contains("doesn't match")); assert!( msg(approve_login(&pool, &id, &user, other(&code)) .await @@ -449,7 +477,9 @@ mod tests { .await .unwrap(); assert!(approve_login(&pool, &id, &user, &code).await.is_err()); - let (key, _, email) = poll_login(&pool, &id, &verifier).await.unwrap().unwrap(); + let Polled::Key(key, _, email) = poll_login(&pool, &id, &verifier, &here).await.unwrap() else { + panic!("no key") + }; assert_eq!(email, format!("{user}@cli.test")); let (name, days): (String, f64) = sqlx::query_as( "SELECT name, extract(epoch FROM expires_at - now())::float8 / 86400 FROM pyo.api_tokens WHERE token_hash = $1", @@ -461,7 +491,7 @@ mod tests { assert_eq!(name, "CLI · laptop"); assert!((29.9..=30.0).contains(&days), "{days}"); assert!( - msg(poll_login(&pool, &id, &verifier).await.unwrap_err()).contains("expired"), + msg(poll_login(&pool, &id, &verifier, &here).await.unwrap_err()).contains("expired"), "used" ); @@ -473,8 +503,8 @@ mod tests { .await .unwrap(); assert!(approve_login(&pool, &id, &user, &code).await.is_err()); - assert!(msg(poll_login(&pool, &id, &verifier).await.unwrap_err()).contains("refused")); - assert!(msg(poll_login(&pool, &id, &verifier).await.unwrap_err()).contains("expired")); + assert!(msg(poll_login(&pool, &id, &verifier, &here).await.unwrap_err()).contains("refused")); + assert!(msg(poll_login(&pool, &id, &verifier, &here).await.unwrap_err()).contains("expired")); // Five wrong codes end it, the right one after them too. let (id, code) = start_login(&pool, &body(None)).await.unwrap(); @@ -486,7 +516,7 @@ mod tests { ); } assert!(approve_login(&pool, &id, &user, &code).await.is_err()); - assert!(msg(poll_login(&pool, &id, &verifier).await.unwrap_err()).contains("refused")); + assert!(msg(poll_login(&pool, &id, &verifier, &here).await.unwrap_err()).contains("refused")); // Expired: nothing to approve or poll. let (id, code) = start_login(&pool, &body(None)).await.unwrap(); @@ -500,7 +530,7 @@ mod tests { assert!( msg(approve_login(&pool, &id, &user, &code).await.unwrap_err()).contains("expired") ); - assert!(msg(poll_login(&pool, &id, &verifier).await.unwrap_err()).contains("expired")); + assert!(msg(poll_login(&pool, &id, &verifier, &here).await.unwrap_err()).contains("expired")); // A bad challenge or lifetime never starts. let bad = StartBody { diff --git a/crates/pyo-api/src/install.rs b/crates/pyo-api/src/install.rs index 859ecd13..a694152e 100644 --- a/crates/pyo-api/src/install.rs +++ b/crates/pyo-api/src/install.rs @@ -1062,7 +1062,8 @@ pub async fn reset_login( ))); } }; - // Made on the server: it also turns two-factor off (recovery.rs). + // Made on the server: it also turns two-factor off, and for an admin + // where admins may sign in from (recovery.rs). let token = crate::recovery::new_host_link(&mut conn, &id).await?; tracing::info!(user = %id, "sign-in link made on the host"); Ok(crate::error::Json(serde_json::json!({ diff --git a/crates/pyo-api/src/lib.rs b/crates/pyo-api/src/lib.rs index d66cb511..8648f24a 100644 --- a/crates/pyo-api/src/lib.rs +++ b/crates/pyo-api/src/lib.rs @@ -7,6 +7,7 @@ //! background tasks, migrations, dashboard features and entitlement checks //! (see [`Extensions`]); self-hosted Pyo has none of those. +mod admin_sign_in; mod agent; mod agent_auth; mod agent_tls; diff --git a/crates/pyo-api/src/mail.rs b/crates/pyo-api/src/mail.rs index 1f5ed861..ad2cbf88 100644 --- a/crates/pyo-api/src/mail.rs +++ b/crates/pyo-api/src/mail.rs @@ -464,6 +464,19 @@ pub fn two_factor_off(link: &str) -> Email { .reason("You get this email for every change to how you sign in.") } +/// An admin sign-in with the right credentials, refused because of where +/// it came from (admin_sign_in.rs). +pub fn sign_in_refused(address: &str, link: &str) -> Email { + Email::new("A Pyo sign-in was refused", "Sign-in refused") + .para(vec![ + t("Someone used your sign-in details for your Pyo admin account from "), + b(address), + t(". Pyo refused it because admins can't sign in from there. If that wasn't you, change your password."), + ]) + .button("Open security settings", link) + .reason("You get this email for every refused sign-in to an admin account.") +} + /// A new API key was made on the account. pub fn new_api_key(name: &str, link: &str) -> Email { Email::new("A new Pyo API key was made", "New API key") @@ -521,6 +534,7 @@ mod tests { ), ("two-factor-off", two_factor_off(&c.link("/profile"))), ("new-api-key", new_api_key(key, &c.link("/api-keys"))), + ("sign-in-refused", sign_in_refused(key, &c.link("/security"))), ] } diff --git a/crates/pyo-api/src/oauth.rs b/crates/pyo-api/src/oauth.rs index 80c0d99c..54510a98 100644 --- a/crates/pyo-api/src/oauth.rs +++ b/crates/pyo-api/src/oauth.rs @@ -644,7 +644,15 @@ impl FromRequestParts for OAuthUser { } // The same limits as an API key with the access the user chose, in // all their teams: what the account and the installation allow stays - // with the dashboard. + // with the dashboard. From where admins may not sign in, an admin's + // assistant acts as a member only (admin_sign_in.rs). + let is_admin = is_admin + && crate::admin_sign_in::admits( + &s.db, + &crate::admin_sign_in::Source::from_parts(parts), + ) + .await + .map_err(|_| challenge(None))?; let user = User { id, name, diff --git a/crates/pyo-api/src/ops.rs b/crates/pyo-api/src/ops.rs index 87c95193..b2842d02 100644 --- a/crates/pyo-api/src/ops.rs +++ b/crates/pyo-api/src/ops.rs @@ -2225,6 +2225,13 @@ pub(crate) enum Op { require_two_factor: bool, audit_days: u16, }, + /// Where the installation's admins may sign in from: the tailnet, and addresses or ranges (IPv4 or IPv6, like 203.0.113.7 or 2001:db8::/48). Neither is anywhere. Only the installation's admin can do this, from the dashboard, and the address they save it from must stay allowed. + SaveAdminSignIn { + #[serde(default)] + tailnet: bool, + #[serde(default)] + addresses: Vec, + }, /// Turn observability (analytics, request logs, firewall and WAF history, usage history) on or off for the whole installation. Only the installation's admin can do this. Off stops storing and showing history and frees its memory. What was stored is kept for when it's back on. Live logs, current usage, deploys and the firewall keep working. SetObservability { enabled: bool }, /// How Pyo updates itself: "manual" or "auto" in a weekly window (UTC). @@ -3165,6 +3172,7 @@ fn installation_wide(op: &Op) -> bool { | Op::SaveObservabilitySettings { .. } | Op::SaveRetentionSettings { .. } | Op::SaveSecuritySettings { .. } + | Op::SaveAdminSignIn { .. } | Op::SaveUpdateSettings { .. } | Op::SetSandboxLimits { .. } | Op::CheckForUpdates {} @@ -3311,6 +3319,7 @@ pub(crate) fn key_access_for(op: &Op) -> Option { | Op::SaveObservabilitySettings { .. } | Op::SaveRetentionSettings { .. } | Op::SaveSecuritySettings { .. } + | Op::SaveAdminSignIn { .. } | Op::SetTeamSecurity { .. } | Op::SaveUpdateSettings { .. } | Op::SetSandboxLimits { .. } @@ -3498,6 +3507,7 @@ pub(crate) fn op_doc(op: &Op) -> (&'static str, &'static str) { | Op::SaveObservabilitySettings { .. } | Op::SaveRetentionSettings { .. } | Op::SaveSecuritySettings { .. } + | Op::SaveAdminSignIn { .. } | Op::SaveUpdateSettings { .. } | Op::SetSandboxLimits { .. } | Op::CheckForUpdates {} @@ -4277,6 +4287,25 @@ async fn apply( } Ok(ok) } + Op::SaveAdminSignIn { tailnet, addresses } => { + require_admin(user)?; + let after = crate::admin_sign_in::checked(tailnet, &addresses)?; + // Never one that shuts out the request saving it. + crate::admin_sign_in::keeps(&after, &crate::audit::request_source())?; + let before = crate::admin_sign_in::save(tx, &after).await?; + if before != after { + // The admin's teams hear of it, as of a two-factor change + // (Pyo Cloud has no team of the installation's own). + crate::twofactor::notify_teams( + tx, + user, + "auth.admin_sign_in_changed", + &crate::admin_sign_in::change_title(&after), + ) + .await?; + } + Ok(json!({ "ok": true, "addresses": after.addresses })) + } Op::SetObservability { enabled } => { require_admin(user)?; sqlx::query("INSERT INTO pyo.settings (key, value) VALUES ('observability', jsonb_build_object('enabled', $1)) ON CONFLICT (key) DO UPDATE SET value = pyo.settings.value || excluded.value, updated_at = now()") diff --git a/crates/pyo-api/src/passkeys.rs b/crates/pyo-api/src/passkeys.rs index 3b4ee3e9..47d1230d 100644 --- a/crates/pyo-api/src/passkeys.rs +++ b/crates/pyo-api/src/passkeys.rs @@ -230,6 +230,7 @@ struct LoginFinish { async fn login_finish( State(state): State, ClientIp(ip): ClientIp, + from: crate::admin_sign_in::Source, headers: HeaderMap, jar: CookieJar, Json(body): Json, @@ -238,6 +239,11 @@ async fn login_finish( // Only failures keep their slot. ratelimit::take(&state.db, &[(ratelimit::PASSKEY_FINISH_IP, &ip)]).await?; let user = verify_passkey(&state, body).await?; + // An admin from where admins may not sign in: as a passkey that didn't + // work. + if !crate::admin_sign_in::sign_in_allowed(&state, &user, &from, "with a passkey").await? { + return Err(failed("admin sign-in limit")); + } ratelimit::forgive(&state.db, &ratelimit::PASSKEY_FINISH_IP, &ip).await?; // A passkey is two factors on its own: no code after it (twofactor.rs). crate::audit::account_event( diff --git a/crates/pyo-api/src/ratelimit.rs b/crates/pyo-api/src/ratelimit.rs index f595d5da..d1efc9ee 100644 --- a/crates/pyo-api/src/ratelimit.rs +++ b/crates/pyo-api/src/ratelimit.rs @@ -264,6 +264,28 @@ impl Cidr { } } +/// Its network address, then the prefix length unless it's one address: +/// "198.51.100.0/24", "2001:db8::1". +impl std::fmt::Display for Cidr { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let (net, max) = match self.net { + IpAddr::V4(n) => { + let mask = u32::MAX.checked_shl(32 - self.len).unwrap_or(0); + (IpAddr::V4((u32::from(n) & mask).into()), 32) + } + IpAddr::V6(n) => { + let mask = u128::MAX.checked_shl(128 - self.len).unwrap_or(0); + (IpAddr::V6((u128::from(n) & mask).into()), 128) + } + }; + if self.len == max { + write!(f, "{net}") + } else { + write!(f, "{net}/{}", self.len) + } + } +} + /// k3s's pod network, where the gateway's proxies run. const DEFAULT_TRUSTED_PROXIES: &str = "10.42.0.0/16,2001:cafe:42::/56"; diff --git a/crates/pyo-api/src/recovery.rs b/crates/pyo-api/src/recovery.rs index 99163fcd..96f6d061 100644 --- a/crates/pyo-api/src/recovery.rs +++ b/crates/pyo-api/src/recovery.rs @@ -19,7 +19,9 @@ //! password: a link alone is one factor. Except a link made on the server //! itself, which turns two-factor off (whoever has the server has //! everything anyway, and it's how someone who lost their app and their -//! recovery codes gets back in). +//! recovery codes gets back in). For an admin it also turns off where +//! admins may sign in from (admin_sign_in.rs): elsewhere an admin's link +//! answers as a used one. use crate::error::Json; use crate::error::Query; @@ -174,6 +176,7 @@ struct ResetBody { async fn reset( State(state): State, ClientIp(ip): ClientIp, + from: crate::admin_sign_in::Source, headers: HeaderMap, jar: CookieJar, Json(body): Json, @@ -209,6 +212,27 @@ async fn reset( must_set_up, key: None, }; + if user.is_admin { + if clears_two_factor { + // Made on the server: the admin sign-in limit goes too, so the + // admin who locked themselves out gets back in. + if crate::admin_sign_in::turn_off(&mut tx).await? { + crate::twofactor::notify_teams( + &mut tx, + &user, + "auth.admin_sign_in_off", + "Let admins sign in from anywhere with a sign-in link from the server", + ) + .await?; + } + } else if !crate::admin_sign_in::admits(&mut *tx, &from).await? { + // From where admins may not sign in: as a used link, and + // nothing changes (the link still works where they may). + tx.rollback().await?; + crate::admin_sign_in::refused(&state, &user, &from, "with a sign-in link").await; + return Err(used_or_expired()); + } + } let had_two_factor = crate::twofactor::enabled(&mut *tx, &user.id).await?; if clears_two_factor && had_two_factor { crate::twofactor::turn_off(&mut tx, &user.id).await?; diff --git a/crates/pyo-api/src/snapshot.rs b/crates/pyo-api/src/snapshot.rs index 4325215d..cefa102f 100644 --- a/crates/pyo-api/src/snapshot.rs +++ b/crates/pyo-api/src/snapshot.rs @@ -80,6 +80,12 @@ pub async fn build(db: &PgPool, user: &User, agent_api_url: &str) -> ApiResult ApiResult ApiResult ApiError { + ApiError::new( + axum::http::StatusCode::UNAUTHORIZED, + "That code didn't work. Try the newest one.", + ) +} + async fn login_code( State(state): State, ClientIp(ip): ClientIp, + from: crate::admin_sign_in::Source, headers: HeaderMap, jar: CookieJar, Json(body): Json, @@ -357,6 +365,11 @@ async fn login_code( .bind(&user_id) .fetch_one(&state.db) .await?; + // An admin from where admins may not sign in: as a wrong code, before + // the code (a recovery code stays unused). + if !crate::admin_sign_in::sign_in_allowed(&state, &user, &from, "with a code").await? { + return Err(wrong_code()); + } let Some(used) = verify(&state, &user_id, &ip, &body.code).await? else { audit::account_event( &state.db, @@ -370,10 +383,7 @@ async fn login_code( }, ) .await; - return Err(ApiError::new( - axum::http::StatusCode::UNAUTHORIZED, - "That code didn't work. Try the newest one.", - )); + return Err(wrong_code()); }; sqlx::query("DELETE FROM pyo.sign_in_challenges WHERE token_hash = $1") .bind(&hash) From 270d11480dd44cd8c1a11543fe402c66977ef0d3 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 19:06:44 +0700 Subject: [PATCH 058/139] test(api): cover admin sign-in limits end to end --- crates/pyo-api/src/admin_sign_in_tests.rs | 243 ++++++++++++++++++++++ crates/pyo-api/src/lib.rs | 2 + 2 files changed, 245 insertions(+) create mode 100644 crates/pyo-api/src/admin_sign_in_tests.rs diff --git a/crates/pyo-api/src/admin_sign_in_tests.rs b/crates/pyo-api/src/admin_sign_in_tests.rs new file mode 100644 index 00000000..4d8cde81 --- /dev/null +++ b/crates/pyo-api/src/admin_sign_in_tests.rs @@ -0,0 +1,243 @@ +//! Where admins may sign in from, end to end, against a throwaway Postgres +//! (DATABASE_URL): saving the limit (never one that locks out the one +//! saving it), sign-in refused like a wrong password with an audit entry, +//! sessions as if signed out, API keys as a member, and everyone else +//! never affected. Through the real routes, as a browser and a script. + +use std::net::SocketAddr; + +use axum::{ + Router, + body::Body, + extract::ConnectInfo, + http::{Method, Request, StatusCode, header}, +}; +use serde_json::{Value, json}; +use sqlx::PgPool; +use tower::ServiceExt; + +use crate::ids::{random_string, sha256_hex}; +use crate::teamsec_tests::{Client, run_big}; + +const INSIDE: &str = "203.0.113.7"; +const OUTSIDE: &str = "192.0.2.50"; + +/// GET /api/v1/me with an API key, from `ip`. +async fn me_with_key(app: &Router, key: &str, ip: &str) -> (StatusCode, Value) { + let mut req = Request::builder() + .method(Method::GET) + .uri("/api/v1/me") + .header(header::AUTHORIZATION, format!("Bearer {key}")) + .body(Body::empty()) + .unwrap(); + req.extensions_mut().insert(ConnectInfo( + format!("{ip}:4000").parse::().unwrap(), + )); + let res = app.clone().oneshot(req).await.unwrap(); + let st = res.status(); + let bytes = axum::body::to_bytes(res.into_body(), 1 << 20) + .await + .unwrap(); + (st, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) +} + +#[test] +#[ignore = "needs DATABASE_URL (a throwaway Postgres)"] +fn admins_sign_in_only_from_where_the_limit_allows() { + run_big(async { + let db = PgPool::connect(&std::env::var("DATABASE_URL").expect("DATABASE_URL")) + .await + .unwrap(); + crate::migrate::run(&db).await.unwrap(); + crate::vault::init(crate::vault::Vault::new( + db.clone(), + crate::vault::Provider::from_env(), + )); + let state = crate::sandbox::e2e::test_state(db.clone()); + let app = Router::new() + .nest("/api/auth", crate::auth::routes()) + .nest("/api/v1", crate::ops::routes()) + .layer(axum::middleware::from_fn(crate::audit::middleware)) + .with_state(state); + let run = random_string(8).to_lowercase(); + let (adm, mem, team) = ( + format!("usr_adm{run}"), + format!("usr_mem{run}"), + format!("team_acl{run}"), + ); + let email = |who: &str| format!("{who}{run}@acl.test"); + let password = "correct horse battery"; + let hash = crate::auth::hash_password(password).await.unwrap(); + for (u, n, admin) in [(&adm, "adm", true), (&mem, "mem", false)] { + sqlx::query("INSERT INTO pyo.users (id, email, name, password_hash, is_admin) VALUES ($1, $2, $3, $4, $5)") + .bind(u) + .bind(email(n)) + .bind(n) + .bind(&hash) + .bind(admin) + .execute(&db) + .await + .unwrap(); + } + sqlx::query("INSERT INTO pyo.teams (id, name, slug) VALUES ($1, $1, $1)") + .bind(&team) + .execute(&db) + .await + .unwrap(); + for (m, u, n, role) in [("a", &adm, "adm", "owner"), ("m", &mem, "mem", "developer")] { + sqlx::query("INSERT INTO pyo.members (id, team_id, user_id, email, role, status) VALUES ($1, $2, $3, $4, $5, 'active')") + .bind(format!("mem_{m}{run}")) + .bind(&team) + .bind(u) + .bind(email(n)) + .bind(role) + .execute(&db) + .await + .unwrap(); + } + let key = format!("pyo_acl{run}"); + sqlx::query("INSERT INTO pyo.api_tokens (id, user_id, name, prefix, token_hash, access) VALUES ($1, $2, 'ci', 'pyo_', $3, 'full')") + .bind(format!("tok_acl{run}")) + .bind(&adm) + .bind(sha256_hex(&key)) + .execute(&db) + .await + .unwrap(); + let client = |ip: &'static str| Client { + app: app.clone(), + cookie: None, + ip, + }; + let sign_in = |who: &'static str, ip: &'static str| { + let (mut c, e) = (client(ip), email(who)); + async move { + let (st, body) = c + .call( + Method::POST, + "/api/auth/login", + Some(json!({ "email": e, "password": password })), + ) + .await; + (st, body, c) + } + }; + + // Off: the admin signs in from anywhere. + let (st, _, mut inside) = sign_in("adm", INSIDE).await; + assert_eq!(st, StatusCode::OK); + let (st, snap) = inside.call(Method::GET, "/api/v1/state", None).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(snap["adminSignIn"]["here"], INSIDE); + assert_eq!(snap["adminSignIn"]["addresses"], json!([])); + + // A limit that leaves out the admin's own address: refused. + let (st, body) = inside + .op(json!({ "op": "saveAdminSignIn", "addresses": ["198.51.100.0/24"] })) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST); + assert_eq!( + body["error"], + format!("This would lock you out. Add your address {INSIDE} first.") + ); + let (st, body) = inside + .op(json!({ "op": "saveAdminSignIn", "tailnet": true })) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); + // One that keeps it: saved plainly. + let (st, body) = inside + .op(json!({ "op": "saveAdminSignIn", "addresses": ["203.0.113.9/24", "2001:db8::/48"] })) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + assert_eq!(body["addresses"], json!(["203.0.113.0/24", "2001:db8::/48"])); + // A member can't change it. + let (_, _, mut member) = sign_in("mem", INSIDE).await; + let (st, _) = member + .op(json!({ "op": "saveAdminSignIn", "addresses": [] })) + .await; + assert_eq!(st, StatusCode::FORBIDDEN); + + // From outside, the right password answers as a wrong one, and the + // admin's teams see why. + let (st, refused, outside) = sign_in("adm", OUTSIDE).await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + assert!(outside.cookie.is_none()); + let mut wrong = client(OUTSIDE); + let (_, wrong_body) = wrong + .call( + Method::POST, + "/api/auth/login", + Some(json!({ "email": email("adm"), "password": "not the password" })), + ) + .await; + assert_eq!(refused, wrong_body); + let (_, nobody) = client(OUTSIDE) + .call( + Method::POST, + "/api/auth/login", + Some(json!({ "email": email("nobody"), "password": password })), + ) + .await; + assert_eq!(refused, nobody, "no account: the same answer"); + let refusals: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pyo.audit_events WHERE team_id = $1 AND action = 'auth.sign_in_refused' AND outcome = 'failed' AND ip = $2", + ) + .bind(&team) + .bind(OUTSIDE) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(refusals, 1); + + // The admin's session from outside: as if signed out. Inside, it + // still works. + let mut stolen = Client { + app: app.clone(), + cookie: inside.cookie.clone(), + ip: OUTSIDE, + }; + let (st, _) = stolen.call(Method::GET, "/api/v1/state", None).await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + let (st, _) = stolen.call(Method::GET, "/api/auth/me", None).await; + assert_eq!(st, StatusCode::UNAUTHORIZED); + let (st, _) = inside.call(Method::GET, "/api/v1/state", None).await; + assert_eq!(st, StatusCode::OK); + + // The admin's API key from outside: a member, not an admin. + let (st, me) = me_with_key(&app, &key, OUTSIDE).await; + assert_eq!(st, StatusCode::OK); + assert_eq!(me["isAdmin"], false); + let (_, me) = me_with_key(&app, &key, INSIDE).await; + assert_eq!(me["isAdmin"], true); + + // Everyone else, from anywhere. + let (st, _, mut member_outside) = sign_in("mem", OUTSIDE).await; + assert_eq!(st, StatusCode::OK); + let (st, _) = member_outside.call(Method::GET, "/api/v1/state", None).await; + assert_eq!(st, StatusCode::OK); + + // Off again: anywhere. + let (st, _) = inside + .op(json!({ "op": "saveAdminSignIn", "tailnet": false, "addresses": [] })) + .await; + assert_eq!(st, StatusCode::OK); + let (st, _) = stolen.call(Method::GET, "/api/v1/state", None).await; + assert_eq!(st, StatusCode::OK); + let saved: bool = + sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pyo.settings WHERE key = 'admin_sign_in')") + .fetch_one(&db) + .await + .unwrap(); + assert!(!saved); + + sqlx::query("DELETE FROM pyo.teams WHERE id = $1") + .bind(&team) + .execute(&db) + .await + .unwrap(); + sqlx::query("DELETE FROM pyo.users WHERE id = ANY ($1)") + .bind(vec![adm.clone(), mem.clone()]) + .execute(&db) + .await + .unwrap(); + }); +} diff --git a/crates/pyo-api/src/lib.rs b/crates/pyo-api/src/lib.rs index 8648f24a..9286e3ba 100644 --- a/crates/pyo-api/src/lib.rs +++ b/crates/pyo-api/src/lib.rs @@ -8,6 +8,8 @@ //! (see [`Extensions`]); self-hosted Pyo has none of those. mod admin_sign_in; +#[cfg(test)] +mod admin_sign_in_tests; mod agent; mod agent_auth; mod agent_tls; From bdc6ca00bdfa6e637c3e190517f6869135230b96 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Sun, 22 Nov 2026 19:06:44 +0700 Subject: [PATCH 059/139] feat(dash): add admin sign-in to the security settings --- dash/src/lib/pyo/store.ts | 8 ++ dash/src/lib/pyo/types.ts | 15 ++++ dash/src/routes/_app/_settings/security.tsx | 81 ++++++++++++++++++++- 3 files changed, 103 insertions(+), 1 deletion(-) diff --git a/dash/src/lib/pyo/store.ts b/dash/src/lib/pyo/store.ts index f28fa28b..11f3f976 100644 --- a/dash/src/lib/pyo/store.ts +++ b/dash/src/lib/pyo/store.ts @@ -70,6 +70,7 @@ import type { RegistryLogin, Retention, SecuritySettings, + AdminSignIn, Role, Team, TeamBackups, @@ -144,6 +145,8 @@ export type PyoState = { registryLogins: RegistryLogin[]; /** Two-factor for everyone and the audit log's retention; null unless you're the installation's admin. */ securitySettings: SecuritySettings | null; + /** Where admins may sign in from; null unless you're the installation's admin. */ + adminSignIn: AdminSignIn | null; /** Installation-wide analytics settings. */ /** Installation-wide. `small`: Pyo's server has under 3.5 GB of memory now. */ observabilitySettings: { @@ -347,6 +350,7 @@ function empty(): PyoState { alertChannels: [], registryLogins: [], securitySettings: null, + adminSignIn: null, observabilitySettings: { ipMode: "none", enabled: true, @@ -2525,6 +2529,10 @@ export const api = { }); return send("saveRetentionSettings", retention); }, + /** Where the installation's admins may sign in from (its admin). Refused when it would lock out this browser. */ + saveAdminSignIn(settings: { tailnet: boolean; addresses: string[] }) { + return send<{ addresses: string[] }>("saveAdminSignIn", settings); + }, /** Two-factor for everyone, and how long the audit log is kept (the installation's admin). */ saveSecuritySettings(settings: SecuritySettings) { update((s) => { diff --git a/dash/src/lib/pyo/types.ts b/dash/src/lib/pyo/types.ts index 5ad8668d..e29f6431 100644 --- a/dash/src/lib/pyo/types.ts +++ b/dash/src/lib/pyo/types.ts @@ -57,6 +57,21 @@ export type SecuritySettings = { auditDays: number; }; +/** Where the installation's admins may sign in from (its admin). Neither: anywhere. */ +export type AdminSignIn = { + tailnet: boolean; + /** IP addresses and ranges, IPv4 or IPv6. */ + addresses: string[]; + /** This browser's address, as Pyo sees it. */ + here: string | null; + /** This browser came over the tailnet. */ + hereTailnet: boolean; + /** Pyo has a tailnet name, or this browser came over the tailnet. */ + tailnetAvailable: boolean; + /** PYO_ADMIN_SIGNIN_ANYWHERE is set on Pyo: the limit is ignored. */ + anywhere: boolean; +}; + /** One entry of a team's audit log. */ export type AuditEvent = { id: ID; diff --git a/dash/src/routes/_app/_settings/security.tsx b/dash/src/routes/_app/_settings/security.tsx index dc06e0f2..d42519af 100644 --- a/dash/src/routes/_app/_settings/security.tsx +++ b/dash/src/routes/_app/_settings/security.tsx @@ -2,7 +2,7 @@ import { createFileRoute } from "@tanstack/react-router"; import { useState } from "react"; import { useHosted } from "~/components/pyo/Managed"; import { Button } from "~/components/ui/Button"; -import { Field, Select, Switch } from "~/components/ui/Field"; +import { Field, Select, Switch, Textarea } from "~/components/ui/Field"; import { Panel } from "~/components/ui/Panel"; import { api, usePyo } from "~/lib/pyo/store"; import { toast } from "~/lib/pyo/toast"; @@ -18,6 +18,84 @@ export const Route = createFileRoute("/_app/_settings/security")({ const DAYS = [90, 180, 365, 730]; +/** The addresses as typed: one per line (commas and spaces work too). */ +function addressList(text: string) { + return text + .split(/[\s,]+/) + .map((a) => a.trim()) + .filter(Boolean); +} + +/** Where admins may sign in from: the tailnet and IP addresses. Pyo Cloud too. */ +function AdminSignInPanel() { + const s = usePyo(); + const saved = s.adminSignIn; + const admin = !!s.user.isAdmin && !!saved; + const [tailnet, setTailnet] = useState(saved?.tailnet ?? false); + const [text, setText] = useState((saved?.addresses ?? []).join("\n")); + const [busy, setBusy] = useState(false); + const list = addressList(text); + const dirty = + !!saved && + (tailnet !== saved.tailnet || list.join("\n") !== saved.addresses.join("\n")); + const note = !admin + ? "Only the installation's admin can change this." + : saved?.anywhere + ? "PYO_ADMIN_SIGNIN_ANYWHERE is set, so admins can sign in from anywhere." + : "Where admins can sign in from. Empty allows anywhere."; + return ( + +
    + {saved?.tailnetAvailable || saved?.tailnet ? ( + + ) : null} + + {(p) => ( +