From 8912ec9668a6b4fc724a3ba5944aa2c7839763c7 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Tue, 17 Nov 2026 11:07:48 +0700 Subject: [PATCH 001/136] feat(proto): add signed command envelopes A command can carry a signature from a separate signer: claims with the cluster, a growing sequence number, expiry, the command's kind and the SHA-256 of its exact JSON. Agents given the signer's public key check them. The signer never sees the command itself. --- crates/pyo-proto/Cargo.toml | 1 + crates/pyo-proto/src/lib.rs | 18 +++ crates/pyo-proto/src/signing.rs | 271 ++++++++++++++++++++++++++++++++ 3 files changed, 290 insertions(+) create mode 100644 crates/pyo-proto/src/signing.rs diff --git a/crates/pyo-proto/Cargo.toml b/crates/pyo-proto/Cargo.toml index 2d65ceae..cf67588f 100644 --- a/crates/pyo-proto/Cargo.toml +++ b/crates/pyo-proto/Cargo.toml @@ -24,3 +24,4 @@ regex = "1.13.1" openapi = ["dep:utoipa"] # Signing and checking sandbox tokens (pyo-api and pyo-sandbox). sandbox-token = ["dep:ring", "dep:base64"] +command-signing = ["dep:ring", "dep:base64"] diff --git a/crates/pyo-proto/src/lib.rs b/crates/pyo-proto/src/lib.rs index 3eb3c97b..42784b2e 100644 --- a/crates/pyo-proto/src/lib.rs +++ b/crates/pyo-proto/src/lib.rs @@ -16,6 +16,8 @@ pub mod flows; pub mod memory; pub mod rbac; pub mod sandbox; +#[cfg(feature = "command-signing")] +pub mod signing; pub mod site; pub mod system; @@ -872,6 +874,22 @@ pub struct VolumeReport { pub struct CommandEnvelope { pub id: String, pub command: Command, + /// The signer's signature over this command, when the API has a signer + /// (Pyo Cloud). An agent given `PYO_COMMAND_KEY` runs only signed + /// commands, and runs the signed JSON, not `command`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub signed: Option, +} + +/// [`signing::SignedCommand`] on the wire (pyo-proto's signing code is +/// behind the `command-signing` feature; the shape isn't). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SignedCommandWire { + pub claims: String, + pub sig: String, + pub kid: String, + pub command: String, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/pyo-proto/src/signing.rs b/crates/pyo-proto/src/signing.rs new file mode 100644 index 00000000..fdaf2492 --- /dev/null +++ b/crates/pyo-proto/src/signing.rs @@ -0,0 +1,271 @@ +//! Signed commands: a command the agent runs only when a signer it trusts +//! signed it for its own cluster. +//! +//! A hosted Pyo (Pyo Cloud) keeps its signing key out of the API: a separate +//! signer signs each command, so a database write or a bug in the API alone +//! can't send work to a customer's cluster. The agent is told the signer's +//! public key at install (`PYO_COMMAND_KEY`) and refuses anything else. +//! +//! ```text +//! sig = Ed25519("pyocmd1." + base64url(claims JSON)) +//! ``` +//! +//! The claims name the command (its id and kind), the cluster it's for, a +//! sequence number that only grows per cluster, when it was signed and when +//! it expires, and the SHA-256 of the command's exact JSON. The signer never +//! sees the command itself, so the secrets in it (sealed env values opened +//! for the agent) never reach it. + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64; +use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +pub const PREFIX: &str = "pyocmd1"; +/// How long a signed command may wait to be run. +pub const TTL_MS: u64 = 10 * 60 * 1000; +/// Clock difference allowed between the signer and the cluster. +pub const LEEWAY_MS: u64 = 2 * 60 * 1000; + +/// What the signer signs. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Claims { + pub v: u32, + /// The command's id (pyo.commands). + pub id: String, + /// The cluster it's for. + pub cluster: String, + /// Grows with every command signed for this cluster. + pub seq: u64, + /// Signed at, and expires at (ms since the epoch). + pub iat: u64, + pub exp: u64, + /// The command's `kind`, so the signer can refuse kinds by policy. + pub kind: String, + /// Hex SHA-256 of [`SignedCommand::command`]. + pub sha256: String, +} + +/// A command with its signature, as the API hands it to the agent. +pub use crate::SignedCommandWire as SignedCommand; + +/// A short id for a public key: hex of the first 8 bytes of its SHA-256. +pub fn key_id(public_key: &[u8]) -> String { + hex8(&Sha256::digest(public_key)) +} + +fn hex8(b: &[u8]) -> String { + b.iter().take(8).map(|x| format!("{x:02x}")).collect() +} + +pub fn sha256_hex(bytes: &[u8]) -> String { + Sha256::digest(bytes).iter().map(|x| format!("{x:02x}")).collect() +} + +fn message(claims_b64: &str) -> Vec { + format!("{PREFIX}.{claims_b64}").into_bytes() +} + +/// A signing key (the signer's), from its PKCS#8 document. +pub struct Signer { + key: Ed25519KeyPair, + kid: String, +} + +impl Signer { + pub fn from_pkcs8(pkcs8: &[u8]) -> Result { + let key = Ed25519KeyPair::from_pkcs8(pkcs8).map_err(|e| format!("not an Ed25519 key: {e}"))?; + let kid = key_id(key.public_key().as_ref()); + Ok(Self { key, kid }) + } + + /// A new key's PKCS#8 document. + pub fn generate_pkcs8() -> Result, String> { + let rng = ring::rand::SystemRandom::new(); + Ed25519KeyPair::generate_pkcs8(&rng) + .map(|d| d.as_ref().to_vec()) + .map_err(|e| format!("couldn't make a key: {e}")) + } + + /// The public key, base64url (what `PYO_COMMAND_KEY` holds). + pub fn public_key(&self) -> String { + B64.encode(self.key.public_key().as_ref()) + } + + pub fn kid(&self) -> &str { + &self.kid + } + + /// Signs claims for a command whose JSON hashes to `claims.sha256`. + /// The command itself is attached by the caller ([`SignedCommand::command`]). + pub fn sign(&self, claims: &Claims) -> (String, String) { + let c = B64.encode(serde_json::to_vec(claims).unwrap_or_default()); + let sig = self.key.sign(&message(&c)); + (c, B64.encode(sig.as_ref())) + } +} + +/// Why a command was refused. +#[derive(Debug, Clone, PartialEq)] +pub enum Refused { + Unsigned, + UnknownKey, + BadSignature, + BadClaims, + OtherCluster, + Replayed { seq: u64, last: u64 }, + Expired, + NotYetValid, + Tampered, + IdMismatch, +} + +impl std::fmt::Display for Refused { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Refused::Unsigned => write!(f, "it isn't signed"), + Refused::UnknownKey => write!(f, "it's signed with a key this cluster doesn't trust"), + Refused::BadSignature => write!(f, "its signature doesn't match"), + Refused::BadClaims => write!(f, "its signed details can't be read"), + Refused::OtherCluster => write!(f, "it was signed for another cluster"), + Refused::Replayed { seq, last } => write!(f, "it was already used (number {seq}, last run {last})"), + Refused::Expired => write!(f, "it expired"), + Refused::NotYetValid => write!(f, "it's dated in the future"), + Refused::Tampered => write!(f, "it was changed after it was signed"), + Refused::IdMismatch => write!(f, "its id doesn't match what was signed"), + } + } +} + +/// The keys an agent trusts, from `PYO_COMMAND_KEY` (base64url public keys, +/// comma separated, so a new key can be added before the old one goes). +#[derive(Clone, Debug, Default)] +pub struct TrustedKeys(Vec<(String, Vec)>); + +impl TrustedKeys { + pub fn parse(v: &str) -> Result { + let mut keys = vec![]; + for k in v.split(',').map(str::trim).filter(|k| !k.is_empty()) { + let raw = B64.decode(k).map_err(|_| format!("{k} isn't base64url"))?; + if raw.len() != 32 { + return Err(format!("{k} isn't an Ed25519 public key")); + } + keys.push((key_id(&raw), raw)); + } + if keys.is_empty() { + return Err("no keys".into()); + } + Ok(Self(keys)) + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Checks a signed command for `cluster`, given the last sequence number + /// this cluster ran. On success, the claims and the command's JSON. + pub fn verify( + &self, + signed: Option<&SignedCommand>, + envelope_id: &str, + cluster: &str, + last_seq: u64, + now_ms: u64, + ) -> Result { + let s = signed.ok_or(Refused::Unsigned)?; + let key = self + .0 + .iter() + .find(|(kid, _)| *kid == s.kid) + .map(|(_, k)| k) + .ok_or(Refused::UnknownKey)?; + let sig = B64.decode(&s.sig).map_err(|_| Refused::BadSignature)?; + UnparsedPublicKey::new(&ED25519, key) + .verify(&message(&s.claims), &sig) + .map_err(|_| Refused::BadSignature)?; + let raw = B64.decode(&s.claims).map_err(|_| Refused::BadClaims)?; + let c: Claims = serde_json::from_slice(&raw).map_err(|_| Refused::BadClaims)?; + if c.v != 1 { + return Err(Refused::BadClaims); + } + if c.cluster != cluster { + return Err(Refused::OtherCluster); + } + if c.id != envelope_id { + return Err(Refused::IdMismatch); + } + if sha256_hex(s.command.as_bytes()) != c.sha256 { + return Err(Refused::Tampered); + } + if now_ms > c.exp.saturating_add(LEEWAY_MS) { + return Err(Refused::Expired); + } + if c.iat > now_ms.saturating_add(LEEWAY_MS) { + return Err(Refused::NotYetValid); + } + if c.seq <= last_seq { + return Err(Refused::Replayed { seq: c.seq, last: last_seq }); + } + Ok(c) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn setup() -> (Signer, TrustedKeys) { + let s = Signer::from_pkcs8(&Signer::generate_pkcs8().unwrap()).unwrap(); + let t = TrustedKeys::parse(&s.public_key()).unwrap(); + (s, t) + } + + fn signed(s: &Signer, cluster: &str, seq: u64, command: &str, now: u64) -> SignedCommand { + let claims = Claims { + v: 1, + id: "cmd_1".into(), + cluster: cluster.into(), + seq, + iat: now, + exp: now + TTL_MS, + kind: "restart".into(), + sha256: sha256_hex(command.as_bytes()), + }; + let (c, sig) = s.sign(&claims); + SignedCommand { claims: c, sig, kid: s.kid().into(), command: command.into() } + } + + #[test] + fn a_good_command_passes() { + let (s, t) = setup(); + let x = signed(&s, "cl_a", 5, r#"{"kind":"restart"}"#, 1_000_000); + let c = t.verify(Some(&x), "cmd_1", "cl_a", 4, 1_000_000).unwrap(); + assert_eq!(c.seq, 5); + } + + #[test] + fn everything_else_is_refused() { + let (s, t) = setup(); + let now = 1_000_000; + let x = signed(&s, "cl_a", 5, r#"{"kind":"restart"}"#, now); + assert_eq!(t.verify(None, "cmd_1", "cl_a", 0, now), Err(Refused::Unsigned)); + assert_eq!(t.verify(Some(&x), "cmd_1", "cl_b", 0, now), Err(Refused::OtherCluster)); + assert_eq!(t.verify(Some(&x), "cmd_2", "cl_a", 0, now), Err(Refused::IdMismatch)); + assert_eq!(t.verify(Some(&x), "cmd_1", "cl_a", 5, now), Err(Refused::Replayed { seq: 5, last: 5 })); + assert_eq!(t.verify(Some(&x), "cmd_1", "cl_a", 0, now + TTL_MS + LEEWAY_MS + 1), Err(Refused::Expired)); + let mut tampered = x.clone(); + tampered.command = r#"{"kind":"delete_namespace"}"#.into(); + assert_eq!(t.verify(Some(&tampered), "cmd_1", "cl_a", 0, now), Err(Refused::Tampered)); + let mut forged = x.clone(); + forged.claims = B64.encode(br#"{"v":1}"#); + assert_eq!(t.verify(Some(&forged), "cmd_1", "cl_a", 0, now), Err(Refused::BadSignature)); + let (other, _) = setup(); + let mut wrong_key = signed(&other, "cl_a", 5, r#"{"kind":"restart"}"#, now); + assert_eq!(t.verify(Some(&wrong_key), "cmd_1", "cl_a", 0, now), Err(Refused::UnknownKey)); + // Another key's signature under a trusted key id. + wrong_key.kid = s.kid().into(); + assert_eq!(t.verify(Some(&wrong_key), "cmd_1", "cl_a", 0, now), Err(Refused::BadSignature)); + } +} From bc96c643f427bbeb22a091f0255ce3f47189af2b Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Tue, 17 Nov 2026 11:12:22 +0700 Subject: [PATCH 002/136] feat(api): sign commands through an extension signer Extensions gains a CommandSigner: when set, every command an agent polls is signed first, with the signer choosing the sequence number and expiry. The signer sees the command's kind and hash, never its secrets. When signing fails the commands go back to the queue. --- crates/pyo-api/src/agent.rs | 63 ++++++++++++++++++++++++++++++++++++- crates/pyo-api/src/lib.rs | 57 +++++++++++++++++++++++++++++++++ 2 files changed, 119 insertions(+), 1 deletion(-) diff --git a/crates/pyo-api/src/agent.rs b/crates/pyo-api/src/agent.rs index 28c1c873..a4818788 100644 --- a/crates/pyo-api/src/agent.rs +++ b/crates/pyo-api/src/agent.rs @@ -715,7 +715,7 @@ async fn poll( continue; } match serde_json::from_value(command.clone()) { - Ok(command) => out.push(CommandEnvelope { id, command }), + Ok(command) => out.push(CommandEnvelope { id, command, signed: None }), Err(e) => { tracing::error!(%id, error = %e, "unreadable command"); undeliverable(&s, &id, &command, &format!("Pyo couldn't read it: {e}")) @@ -723,6 +723,9 @@ async fn poll( } } } + if let Some(signer) = crate::command_signer() { + sign_all(&s, signer.as_ref(), &cluster.id, &mut out).await?; + } return Ok(Json(out)); } let left = deadline.saturating_duration_since(tokio::time::Instant::now()); @@ -735,6 +738,64 @@ async fn poll( } } +/// Has the signer sign each command for this cluster, in order. When it +/// can't, the commands go back to the queue and the agent asks again. +async fn sign_all( + s: &AppState, + signer: &dyn crate::CommandSigner, + cluster_id: &str, + out: &mut [CommandEnvelope], +) -> ApiResult<()> { + if out.is_empty() { + return Ok(()); + } + let mut items = Vec::with_capacity(out.len()); + let mut jsons = Vec::with_capacity(out.len()); + for e in out.iter() { + let json = serde_json::to_string(&e.command).map_err(anyhow::Error::from)?; + let kind = serde_json::from_str::(&json) + .ok() + .and_then(|v| v["kind"].as_str().map(str::to_owned)) + .unwrap_or_default(); + items.push(crate::ToSign { + id: e.id.clone(), + kind, + sha256: sha256_hex(&json), + }); + jsons.push(json); + } + match signer.sign(cluster_id, &items).await { + Ok(sigs) if sigs.len() == out.len() => { + for ((e, sig), json) in out.iter_mut().zip(sigs).zip(jsons) { + e.signed = Some(pyo_proto::SignedCommandWire { + claims: sig.claims, + sig: sig.sig, + kid: sig.kid, + command: json, + }); + } + Ok(()) + } + other => { + let why = match other { + Ok(_) => "the signer signed a different number of commands".to_owned(), + Err(e) => format!("{e:#}"), + }; + tracing::error!(cluster = %cluster_id, error = %why, "couldn't sign commands; they go back to the queue"); + let ids: Vec<&str> = out.iter().map(|e| e.id.as_str()).collect(); + sqlx::query("UPDATE pyo.commands SET status = 'pending', sent_at = NULL, sent_to = NULL WHERE cluster_id = $1 AND id = ANY($2) AND status = 'sent'") + .bind(cluster_id) + .bind(&ids) + .execute(&s.db) + .await?; + Err(ApiError::new( + StatusCode::SERVICE_UNAVAILABLE, + "Commands can't be signed right now.", + )) + } + } +} + async fn command_result( State(s): State, cluster: AgentCluster, diff --git a/crates/pyo-api/src/lib.rs b/crates/pyo-api/src/lib.rs index bbb51aad..f98aeba9 100644 --- a/crates/pyo-api/src/lib.rs +++ b/crates/pyo-api/src/lib.rs @@ -171,6 +171,45 @@ pub struct Extensions { pub features: Vec, /// Checks before a team adds a server or deploys. pub entitlements: Option>, + /// Signs every command before an agent gets it, with a key this + /// process doesn't hold. Agents installed from here are given its + /// public keys and refuse anything unsigned. + pub command_signer: Option>, + /// Hostnames need proof of ownership (a DNS TXT record) before a team + /// can claim one. For an installation shared by teams that don't trust + /// each other. + pub verify_domains: bool, +} + +/// A command to sign: its id, its `kind`, and the hex SHA-256 of its JSON. +#[derive(Debug, Clone, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ToSign { + pub id: String, + pub kind: String, + pub sha256: String, +} + +/// A signature over a command's claims (pyo-proto `signing`). +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Signature { + pub claims: String, + pub sig: String, + pub kid: String, +} + +/// Where commands get signed (pyo-proto `signing`). The signer picks each +/// command's sequence number and expiry. +pub trait CommandSigner: Send + Sync { + /// Signs commands for one cluster, in this order. + fn sign<'a>( + &'a self, + cluster_id: &'a str, + items: &'a [ToSign], + ) -> futures::future::BoxFuture<'a, anyhow::Result>>; + /// The public keys agents trust (`PYO_COMMAND_KEY`: base64url, comma separated). + fn public_keys(&self) -> String; } /// A background task: given the app state, runs until the process stops. @@ -197,6 +236,18 @@ pub trait Entitlements: Send + Sync { } static ENTITLEMENTS: std::sync::OnceLock> = std::sync::OnceLock::new(); +static SIGNER: std::sync::OnceLock> = std::sync::OnceLock::new(); +static VERIFY_DOMAINS: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// The command signer, when this build has one. +pub(crate) fn command_signer() -> Option<&'static Arc> { + SIGNER.get() +} + +/// Whether hostnames need proof of ownership (see [`Extensions::verify_domains`]). +pub(crate) fn verify_domains() -> bool { + VERIFY_DOMAINS.get().copied().unwrap_or(false) +} static FEATURES: std::sync::OnceLock> = std::sync::OnceLock::new(); /// Fails with 402 and the entitlement's message when a team may not add a server. @@ -241,8 +292,14 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { migrator: extra_migrator, features, entitlements, + command_signer, + verify_domains, } = ext; let _ = FEATURES.set(features); + let _ = VERIFY_DOMAINS.set(verify_domains); + if let Some(s) = command_signer { + let _ = SIGNER.set(s); + } if let Some(e) = entitlements { let _ = ENTITLEMENTS.set(e); } From cd213b3169450df08021deb907d55fc3b9e3fd88 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Tue, 17 Nov 2026 11:12:22 +0700 Subject: [PATCH 003/136] feat(agent): enroll over mtls and run only signed commands With PYO_AGENT_CA the agent pins that CA, makes its own key, gets a day-long client certificate with the connect command's token, and renews it at half its lifetime. With PYO_COMMAND_KEY and PYO_CLUSTER_ID it refuses commands that aren't signed for its cluster, are replayed, expired or changed, and reports why. The key, certificate and last command number live in pyo-agent-identity. --- Cargo.lock | 1 + crates/pyo-agent/Cargo.toml | 3 +- crates/pyo-agent/src/api.rs | 48 +++++- crates/pyo-agent/src/main.rs | 18 +- crates/pyo-agent/src/trust.rs | 306 ++++++++++++++++++++++++++++++++++ 5 files changed, 367 insertions(+), 9 deletions(-) create mode 100644 crates/pyo-agent/src/trust.rs diff --git a/Cargo.lock b/Cargo.lock index a2059baf..f0419a29 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3363,6 +3363,7 @@ dependencies = [ "k8s-openapi", "kube", "pyo-proto", + "rcgen", "reqwest", "rustls", "serde", diff --git a/crates/pyo-agent/Cargo.toml b/crates/pyo-agent/Cargo.toml index 8033f06c..32ff1438 100644 --- a/crates/pyo-agent/Cargo.toml +++ b/crates/pyo-agent/Cargo.toml @@ -7,7 +7,7 @@ publish.workspace = true [dependencies] anyhow = "1.0.104" -pyo-proto = { version = "0.4.5", path = "../pyo-proto" } +pyo-proto = { version = "0.4.5", path = "../pyo-proto", features = ["command-signing"] } futures = "0.3.34" http = "1.5.0" k8s-openapi = { version = "0.28.0", features = ["latest"] } @@ -21,3 +21,4 @@ tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } tokio-tungstenite = { version = "0.29", features = ["rustls-tls-native-roots"] } base64 = "0.23.1" rustls = { version = "0.23.46", default-features = false, features = ["aws_lc_rs", "std"] } +rcgen = { version = "0.14", default-features = false, features = ["aws_lc_rs", "pem"] } diff --git a/crates/pyo-agent/src/api.rs b/crates/pyo-agent/src/api.rs index ee909c5b..d8ead811 100644 --- a/crates/pyo-agent/src/api.rs +++ b/crates/pyo-agent/src/api.rs @@ -14,6 +14,10 @@ pub struct PyoApi { base: String, http: reqwest::Client, token: String, + /// With a client certificate (trust.rs): the same TLS for terminals. + tls: Option>, + /// Signed commands only (trust.rs). + verifier: Option>, } impl PyoApi { @@ -42,6 +46,17 @@ impl PyoApi { } pub fn new(url: &str, token: &str) -> anyhow::Result { + Self::with_trust(url, token, None, None) + } + + /// With Pyo Cloud's TLS (a pinned CA and a client certificate) and its + /// command signatures, when the install sets them (trust.rs). + pub fn with_trust( + url: &str, + token: &str, + tls: Option, + verifier: Option>, + ) -> anyhow::Result { let mut headers = HeaderMap::new(); let mut auth = HeaderValue::from_str(&format!("Bearer {token}")) .context("token has invalid characters")?; @@ -53,14 +68,18 @@ impl PyoApi { ); let instance = format!("{:x}{:x}", std::process::id(), pyo_proto::now_ms()); headers.insert(AGENT_INSTANCE_HEADER, HeaderValue::from_str(&instance)?); - let http = reqwest::Client::builder() + let mut http = reqwest::Client::builder() .default_headers(headers) - .connect_timeout(Duration::from_secs(10)) - .build()?; + .connect_timeout(Duration::from_secs(10)); + if let Some(tls) = &tls { + http = http.use_preconfigured_tls(tls.clone()); + } Ok(Self { base: format!("{}/api/agent/v1", url.trim_end_matches('/')), - http, + http: http.build()?, token: token.to_owned(), + tls: tls.map(std::sync::Arc::new), + verifier, }) } @@ -92,7 +111,20 @@ impl PyoApi { .timeout(Duration::from_secs(wait_secs + 15)) .send() .await?; - let items: Vec = Self::check(res).await?.json().await?; + let mut items: Vec = Self::check(res).await?.json().await?; + if let Some(v) = &self.verifier { + let (ok, refused) = v.check(items).await; + items = ok; + for (id, why) in refused { + tracing::warn!(%id, %why, "refused a command"); + let result = crate::failed(format!( + "Refused: {why}. This cluster runs only commands Pyo's signer signed for it." + )); + if let Err(e) = self.command_result(&id, &result).await { + tracing::warn!(%id, error = %e, "couldn't report a refused command"); + } + } + } let (commands, unreadable) = read_commands(items); for (id, why) in unreadable { tracing::warn!(%id, error = %why, "got a command this agent can't read; is it out of date?"); @@ -134,9 +166,13 @@ impl PyoApi { AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {}", self.token))?, ); + let connector = self + .tls + .clone() + .map(tokio_tungstenite::Connector::Rustls); let (ws, _) = tokio::time::timeout( Duration::from_secs(15), - tokio_tungstenite::connect_async(req), + tokio_tungstenite::connect_async_tls_with_config(req, None, false, connector), ) .await .context("timed out")??; diff --git a/crates/pyo-agent/src/main.rs b/crates/pyo-agent/src/main.rs index 12b6e2fb..6d18882b 100644 --- a/crates/pyo-agent/src/main.rs +++ b/crates/pyo-agent/src/main.rs @@ -39,6 +39,7 @@ mod sites; mod tailnet; mod terminal; mod tls; +mod trust; mod upgrade; mod volumes; mod waf; @@ -170,9 +171,22 @@ async fn main() -> anyhow::Result<()> { .map_err(|_| anyhow::anyhow!("PYO_AGENT_TOKEN is required"))?; let kube = kube::Client::try_default().await?; let policy = scope::read_policy(&kube).await; + // Pyo Cloud: a client certificate, and signed commands only (trust.rs). + let identity = trust::Identity::from_env(&url, &token, &kube)?.map(Arc::new); + if let Some(id) = &identity { + id.ensure().await; + tokio::spawn(id.clone().renew_loop()); + } + let verifier = trust::Verifier::from_env(&kube).await?.map(Arc::new); + let api = api::PyoApi::with_trust( + &url, + &token, + identity.as_ref().map(|i| i.tls.clone()), + verifier, + )?; let agent = Agent { kube, - api: api::PyoApi::new(&url, &token)?, + api, cancels: Default::default(), deploying: Default::default(), routes: Default::default(), @@ -404,7 +418,7 @@ impl Ordered { } async fn run_command(agent: Agent, envelope: CommandEnvelope) { - let CommandEnvelope { id, command } = envelope; + let CommandEnvelope { id, command, .. } = envelope; tracing::info!(%id, kind = command_kind(&command), "command"); // The customer's policy first: refused commands do nothing. let refused = scope::refusal( diff --git a/crates/pyo-agent/src/trust.rs b/crates/pyo-agent/src/trust.rs new file mode 100644 index 00000000..7fa7f641 --- /dev/null +++ b/crates/pyo-agent/src/trust.rs @@ -0,0 +1,306 @@ +//! What the agent trusts, when its install says so (Pyo Cloud): +//! +//! - `PYO_AGENT_CA`: the only CA the API's agent endpoint may present (no +//! public CAs). The agent proves who it is with a client certificate from +//! that CA, for its cluster only, valid a day. Its key is made here and +//! never leaves the cluster (Secret `pyo-agent-identity`). The first one +//! comes with the connect command's token, which works once; later ones +//! with the certificate it replaces, at half its lifetime. +//! - `PYO_COMMAND_KEY` and `PYO_CLUSTER_ID`: commands run only when the +//! signer signed them for this cluster, newer than the last one run, and +//! not expired (pyo-proto `signing`). The last number run is kept in the +//! same Secret, so a restart doesn't open the door to replays. +//! +//! Without them (self-hosted), nothing here runs: the token alone works. + +use std::sync::{Arc, RwLock}; +use std::time::Duration; + +use anyhow::Context; +use k8s_openapi::api::core::v1::Secret; +use kube::api::{Patch, PatchParams}; +use pyo_proto::signing::{Refused, TrustedKeys}; +use rustls::pki_types::pem::PemObject; +use rustls::pki_types::{CertificateDer, PrivateKeyDer}; +use rustls::sign::CertifiedKey; +use serde_json::{Value, json}; + +pub const IDENTITY_SECRET: &str = "pyo-agent-identity"; + +// ── Client certificate ────────────────────────────────────────────────────── + +/// The client certificate new connections present; swapped on renewal. +#[derive(Debug, Default)] +pub struct CertSlot(RwLock>>); + +impl rustls::client::ResolvesClientCert for CertSlot { + fn resolve(&self, _: &[&[u8]], _: &[rustls::SignatureScheme]) -> Option> { + self.0.read().ok()?.clone() + } + fn has_certs(&self) -> bool { + self.0.read().map(|c| c.is_some()).unwrap_or(false) + } +} + +impl CertSlot { + fn set(&self, cert_pem: &str, key_pem: &str) -> anyhow::Result<()> { + let certs = CertificateDer::pem_slice_iter(cert_pem.as_bytes()) + .collect::, _>>() + .context("the certificate isn't PEM")?; + anyhow::ensure!(!certs.is_empty(), "no certificate"); + let key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes()).context("the key isn't PEM")?; + let provider = rustls::crypto::aws_lc_rs::default_provider(); + let ck = CertifiedKey::from_der(certs, key, &provider)?; + *self.0.write().map_err(|_| anyhow::anyhow!("lock"))? = Some(Arc::new(ck)); + Ok(()) + } +} + +/// The agent's TLS to the API: Pyo's agent CA only, TLS 1.3, and the +/// client certificate in `slot`. +pub fn client_config(ca_pem: &str, slot: Arc) -> anyhow::Result { + let mut roots = rustls::RootCertStore::empty(); + for c in CertificateDer::pem_slice_iter(ca_pem.as_bytes()) { + roots.add(c.context("PYO_AGENT_CA isn't PEM")?)?; + } + anyhow::ensure!(!roots.is_empty(), "PYO_AGENT_CA holds no certificate"); + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + let mut cfg = rustls::ClientConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13])? + .with_root_certificates(roots) + .with_client_cert_resolver(slot); + cfg.alpn_protocols = vec![b"http/1.1".to_vec()]; + Ok(cfg) +} + +/// What's kept in the identity Secret. +#[derive(Default, Clone)] +struct Stored { + key: String, + cert: String, + not_after: u64, + last_seq: u64, +} + +async fn load(kube: &kube::Client) -> Stored { + let api = kube::Api::::namespaced(kube.clone(), pyo_proto::rbac::NS); + let Ok(Some(s)) = api.get_opt(IDENTITY_SECRET).await else { + return Stored::default(); + }; + let get = |k: &str| { + s.data + .as_ref() + .and_then(|d| d.get(k)) + .and_then(|v| String::from_utf8(v.0.clone()).ok()) + .unwrap_or_default() + }; + Stored { + key: get("key.pem"), + cert: get("cert.pem"), + not_after: get("not-after").trim().parse().unwrap_or(0), + last_seq: get("last-seq").trim().parse().unwrap_or(0), + } +} + +/// Writes some of the Secret's keys. Each `manager` owns its own keys +/// (server-side apply drops a manager's keys it leaves out). +async fn save(kube: &kube::Client, manager: &str, fields: Value) -> anyhow::Result<()> { + use base64::Engine as _; + let api = kube::Api::::namespaced(kube.clone(), pyo_proto::rbac::NS); + let data: serde_json::Map = fields + .as_object() + .into_iter() + .flatten() + .map(|(k, v)| { + let raw = v.as_str().unwrap_or_default(); + (k.clone(), json!(base64::engine::general_purpose::STANDARD.encode(raw))) + }) + .collect(); + let doc = json!({ + "apiVersion": "v1", + "kind": "Secret", + "metadata": { "name": IDENTITY_SECRET, "namespace": pyo_proto::rbac::NS, "labels": { "app.kubernetes.io/part-of": "pyo" } }, + "type": "Opaque", + "data": data, + }); + api.patch(IDENTITY_SECRET, &PatchParams::apply(manager).force(), &Patch::Apply(doc)) + .await + .with_context(|| format!("couldn't save {IDENTITY_SECRET}"))?; + Ok(()) +} + +/// The agent's identity at the API's agent endpoint. +pub struct Identity { + pub slot: Arc, + pub tls: rustls::ClientConfig, + base: String, + token: String, + kube: kube::Client, +} + +impl Identity { + /// From `PYO_AGENT_CA`; None when the install doesn't set it. + pub fn from_env(base: &str, token: &str, kube: &kube::Client) -> anyhow::Result> { + let Some(ca) = std::env::var("PYO_AGENT_CA").ok().filter(|v| !v.trim().is_empty()) else { + return Ok(None); + }; + let slot = Arc::new(CertSlot::default()); + let tls = client_config(&ca, slot.clone())?; + Ok(Some(Self { + slot, + tls, + base: base.trim_end_matches('/').to_owned(), + token: token.to_owned(), + kube: kube.clone(), + })) + } + + fn http(&self) -> anyhow::Result { + Ok(reqwest::Client::builder() + .use_preconfigured_tls(self.tls.clone()) + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(30)) + .build()?) + } + + /// A certificate to start with: the stored one while it has more than + /// an hour left, else a new one for the connect command's token. + /// Retries until it has one. + pub async fn ensure(&self) { + let mut wait = Duration::from_secs(2); + loop { + match self.try_ensure().await { + Ok(()) => return, + Err(e) => { + tracing::warn!(error = %format!("{e:#}"), retry_in = ?wait, "no client certificate yet"); + tokio::time::sleep(wait).await; + wait = (wait * 2).min(Duration::from_secs(60)); + } + } + } + } + + async fn try_ensure(&self) -> anyhow::Result<()> { + let s = load(&self.kube).await; + if !s.cert.is_empty() && s.not_after > pyo_proto::now_ms() as u64 + 3_600_000 { + self.slot.set(&s.cert, &s.key)?; + tracing::info!(not_after = s.not_after, "using the stored client certificate"); + return Ok(()); + } + self.request("enroll", Some(&self.token)).await + } + + /// A new key and certificate, through `/enroll` (with the token) or + /// `/renew` (with the current certificate). + async fn request(&self, how: &str, token: Option<&str>) -> anyhow::Result<()> { + let key = rcgen::KeyPair::generate()?; + let csr = rcgen::CertificateParams::new(Vec::::new())?.serialize_request(&key)?.pem()?; + let mut body = json!({ "csr": csr }); + if let Some(t) = token { + body["token"] = json!(t); + } + let res = self + .http()? + .post(format!("{}/api/agent/v1/{how}", self.base)) + .json(&body) + .send() + .await?; + let status = res.status(); + let v: Value = res.json().await.unwrap_or_default(); + anyhow::ensure!(status.is_success(), "{status}: {}", v["error"].as_str().or(v["message"].as_str()).unwrap_or("")); + let cert = v["certificate"].as_str().unwrap_or("").to_owned(); + let not_after = v["notAfter"].as_u64().unwrap_or(0); + anyhow::ensure!(!cert.is_empty() && not_after > 0, "the API sent no certificate"); + let key_pem = key.serialize_pem(); + self.slot.set(&cert, &key_pem)?; + save( + &self.kube, + "pyo-agent-identity", + json!({ "key.pem": key_pem, "cert.pem": cert, "not-after": not_after.to_string() }), + ) + .await?; + tracing::info!(how, not_after, "got a client certificate"); + Ok(()) + } + + /// Renews the certificate at half its lifetime, for as long as the agent runs. + pub async fn renew_loop(self: Arc) { + loop { + tokio::time::sleep(Duration::from_secs(600)).await; + let s = load(&self.kube).await; + let left = s.not_after.saturating_sub(pyo_proto::now_ms() as u64); + // Certificates last a day: renew once less than half is left. + if left > 12 * 3_600_000 { + continue; + } + if let Err(e) = self.request("renew", None).await { + tracing::warn!(error = %format!("{e:#}"), left_ms = left, "couldn't renew the client certificate"); + } + } + } +} + +// ── Signed commands ───────────────────────────────────────────────────────── + +/// Checks commands against the signer's keys, for this cluster. +pub struct Verifier { + keys: TrustedKeys, + cluster: String, + last: tokio::sync::Mutex, + kube: kube::Client, +} + +impl Verifier { + /// From `PYO_COMMAND_KEY` and `PYO_CLUSTER_ID`; None when the install + /// doesn't set a key. A key without the cluster's id is an error: the + /// agent would otherwise run commands signed for any cluster. + pub async fn from_env(kube: &kube::Client) -> anyhow::Result> { + let Some(k) = std::env::var("PYO_COMMAND_KEY").ok().filter(|v| !v.trim().is_empty()) else { + return Ok(None); + }; + let keys = TrustedKeys::parse(&k).map_err(|e| anyhow::anyhow!("PYO_COMMAND_KEY: {e}"))?; + let cluster = std::env::var("PYO_CLUSTER_ID") + .ok() + .filter(|v| !v.trim().is_empty()) + .context("PYO_COMMAND_KEY needs PYO_CLUSTER_ID")?; + let last = load(kube).await.last_seq; + tracing::info!(cluster = %cluster, last_seq = last, "running signed commands only"); + Ok(Some(Self { + keys, + cluster, + last: tokio::sync::Mutex::new(last), + kube: kube.clone(), + })) + } + + /// Keeps the commands that check out, each with its signed JSON in + /// place of what came beside it. The rest, by id, with why. + pub async fn check(&self, items: Vec) -> (Vec, Vec<(String, Refused)>) { + let mut last = self.last.lock().await; + let before = *last; + let mut ok = Vec::with_capacity(items.len()); + let mut refused = vec![]; + for mut item in items { + let id = item["id"].as_str().unwrap_or("").to_owned(); + let signed: Option = + serde_json::from_value(item["signed"].clone()).ok(); + match self.keys.verify(signed.as_ref(), &id, &self.cluster, *last, pyo_proto::now_ms() as u64) { + Ok(claims) => match serde_json::from_str::(&signed.map(|s| s.command).unwrap_or_default()) { + Ok(command) => { + *last = claims.seq; + item["command"] = command; + ok.push(item); + } + Err(_) => refused.push((id, Refused::BadClaims)), + }, + Err(why) => refused.push((id, why)), + } + } + if *last != before + && let Err(e) = save(&self.kube, "pyo-agent-commands", json!({ "last-seq": last.to_string() })).await + { + tracing::warn!(error = %format!("{e:#}"), "couldn't keep the last command number"); + } + (ok, refused) + } +} From 421be62e55fd2e37dd1df03579a2b9eaa0a58809 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Tue, 17 Nov 2026 11:22:08 +0700 Subject: [PATCH 004/136] feat(api): add an mtls agent endpoint with enrollment With PYO_AGENT_MTLS_ADDR, Pyo also serves the agent routes on a TLS 1.3 listener with its own CA. An agent enrolls once with its connect token and a CSR, gets a day-long certificate naming its team and cluster, and renews with that certificate. The agent extractor takes the cluster from the certificate, and PYO_AGENT_REQUIRE_CERT refuses bearer tokens alone. Rotating a cluster's token revokes its certificates. In this mode the install manifest points the agent at PYO_AGENT_ENDPOINT and pins the CA, the cluster id and the signer's keys, and connect commands use PYO_PUBLIC_API_URL. --- Cargo.lock | 2 + crates/pyo-api/Cargo.toml | 4 +- .../migrations/0020_agent_certificates.sql | 6 + crates/pyo-api/src/agent.rs | 30 ++ crates/pyo-api/src/agent_tls.rs | 444 ++++++++++++++++++ crates/pyo-api/src/install.rs | 42 +- crates/pyo-api/src/lib.rs | 13 + crates/pyo-api/src/ops.rs | 16 +- 8 files changed, 547 insertions(+), 10 deletions(-) create mode 100644 crates/pyo-api/migrations/0020_agent_certificates.sql create mode 100644 crates/pyo-api/src/agent_tls.rs diff --git a/Cargo.lock b/Cargo.lock index f0419a29..16ee4ab5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3412,7 +3412,9 @@ dependencies = [ "sha2 0.11.1", "sqlx", "thiserror 2.0.21", + "time", "tokio", + "tokio-rustls", "tokio-tungstenite", "tower-http 0.7.1", "tracing", diff --git a/crates/pyo-api/Cargo.toml b/crates/pyo-api/Cargo.toml index d9160360..88070388 100644 --- a/crates/pyo-api/Cargo.toml +++ b/crates/pyo-api/Cargo.toml @@ -47,7 +47,9 @@ futures = "0.3.34" crypto_secretbox = "0.1.1" zeroize = "1" flate2 = "1" -rcgen = { version = "0.14", default-features = false, features = ["aws_lc_rs", "pem"] } +rcgen = { version = "0.14", default-features = false, features = ["aws_lc_rs", "pem", "x509-parser"] } +time = "0.3" +tokio-rustls = { version = "0.26", default-features = false, features = ["aws_lc_rs"] } # ACME for sandbox edge certificates. Its HTTP goes through reqwest. instant-acme = { version = "0.8.5", default-features = false, features = ["aws-lc-rs", "rcgen"] } serde_norway = "0.9.42" diff --git a/crates/pyo-api/migrations/0020_agent_certificates.sql b/crates/pyo-api/migrations/0020_agent_certificates.sql new file mode 100644 index 00000000..5ec682d2 --- /dev/null +++ b/crates/pyo-api/migrations/0020_agent_certificates.sql @@ -0,0 +1,6 @@ +-- Agents with a client certificate (agent_tls.rs): the serial of the +-- cluster's current certificate and the one before it (through a renewal), +-- and the connect token already used to enroll (a token enrolls once). +ALTER TABLE pyo.clusters ADD COLUMN agent_cert_serial text; +ALTER TABLE pyo.clusters ADD COLUMN agent_cert_prev_serial text; +ALTER TABLE pyo.clusters ADD COLUMN agent_token_used_hash text; diff --git a/crates/pyo-api/src/agent.rs b/crates/pyo-api/src/agent.rs index a4818788..bbe92d64 100644 --- a/crates/pyo-api/src/agent.rs +++ b/crates/pyo-api/src/agent.rs @@ -47,6 +47,36 @@ impl FromRequestParts for AgentCluster { parts: &mut Parts, state: &AppState, ) -> Result { + // Over the mTLS endpoint: the cluster its certificate names, while + // that certificate is the cluster's current (or the one before it, + // through a renewal). Never from the request. + if let Some(peer) = parts.extensions.get::() + && let Some(cert) = &peer.cert + { + let id = crate::agent_tls::identity(cert) + .ok_or_else(|| ApiError::new(StatusCode::UNAUTHORIZED, "This certificate names no cluster."))?; + let ok: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pyo.clusters WHERE id = $1 AND team_id = $2 AND $3 IN (agent_cert_serial, agent_cert_prev_serial))", + ) + .bind(&id.cluster) + .bind(&id.team) + .bind(&id.serial) + .fetch_one(&state.db) + .await?; + if !ok { + return Err(ApiError::new( + StatusCode::UNAUTHORIZED, + "This certificate was replaced or revoked. Run the cluster's connect command again.", + )); + } + return Ok(AgentCluster { id: id.cluster, team_id: id.team }); + } + if crate::agent_tls::require_cert() { + return Err(ApiError::new( + StatusCode::UNAUTHORIZED, + "Agents connect with a client certificate here.", + )); + } let token = parts .headers .get("authorization") diff --git a/crates/pyo-api/src/agent_tls.rs b/crates/pyo-api/src/agent_tls.rs new file mode 100644 index 00000000..bbc242a9 --- /dev/null +++ b/crates/pyo-api/src/agent_tls.rs @@ -0,0 +1,444 @@ +//! The agent endpoint over mutual TLS (Pyo Cloud's agent.pyo.dev). +//! +//! With `PYO_AGENT_MTLS_ADDR` set, Pyo also listens there for agents only: +//! TLS 1.3, its own CA (the agent pins it, no public CA counts), and a +//! client certificate from that CA naming the agent's cluster +//! (`pyo://team//cluster/` as a URI name, valid a day). An +//! agent gets its first certificate at `/enroll` with the connect command's +//! token, which works once, and renews at `/renew` with the certificate it +//! has. The cluster comes from the certificate, never the request. +//! +//! With `PYO_AGENT_REQUIRE_CERT=true` the agent routes refuse a bearer +//! token alone, on this listener and the main one. +//! +//! The CA's key is a file here (`PYO_AGENT_CA_DIR`, made on first start); +//! a hosted build moves it to a KMS. + +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use axum::{ + Router, + extract::{ConnectInfo, State}, + http::StatusCode, + routing::{get, post}, +}; +use rcgen::{ + CertificateParams, CertificateSigningRequestParams, DistinguishedName, DnType, + ExtendedKeyUsagePurpose, IsCa, Issuer, KeyPair, KeyUsagePurpose, SanType, SerialNumber, +}; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject}; +use serde::Deserialize; +use serde_json::{Value, json}; + +use crate::{ + AppState, + agent::AgentCluster, + error::{ApiError, ApiResult, Json}, + ids::sha256_hex, +}; + +/// A client certificate's lifetime. +pub const CERT_HOURS: i64 = 24; + +/// Whether bearer tokens alone are refused on agent routes. +pub fn require_cert() -> bool { + static R: std::sync::OnceLock = std::sync::OnceLock::new(); + *R.get_or_init(|| { + std::env::var("PYO_AGENT_REQUIRE_CERT").is_ok_and(|v| matches!(v.trim(), "1" | "true")) + }) +} + +/// The agent CA, when this Pyo runs the mTLS endpoint. +pub fn ca() -> Option<&'static Ca> { + CA.get() +} +static CA: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Where agents reach the mTLS endpoint (`PYO_AGENT_ENDPOINT`), for the +/// install manifest. None without one. +pub fn endpoint() -> Option { + ca()?; + std::env::var("PYO_AGENT_ENDPOINT") + .ok() + .map(|v| v.trim().trim_end_matches('/').to_owned()) + .filter(|v| !v.is_empty()) +} + +pub struct Ca { + pem: String, + key_pem: String, +} + +impl Ca { + /// The CA in `dir` (ca.pem, ca.key), made there on first start. + pub fn load_or_create(dir: &std::path::Path) -> anyhow::Result { + let (cert, key) = (dir.join("ca.pem"), dir.join("ca.key")); + if cert.exists() && key.exists() { + return Ok(Self { + pem: std::fs::read_to_string(&cert)?, + key_pem: std::fs::read_to_string(&key)?, + }); + } + std::fs::create_dir_all(dir)?; + let key_pair = KeyPair::generate()?; + let mut p = CertificateParams::new(Vec::::new())?; + let mut dn = DistinguishedName::new(); + dn.push(DnType::CommonName, "Pyo agent CA"); + p.distinguished_name = dn; + p.is_ca = IsCa::Ca(rcgen::BasicConstraints::Constrained(0)); + p.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; + let now = time::OffsetDateTime::now_utc(); + p.not_before = now - time::Duration::hours(1); + p.not_after = now + time::Duration::days(3650); + let c = p.self_signed(&key_pair)?; + let key_pem = key_pair.serialize_pem(); + { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&key)?; + f.write_all(key_pem.as_bytes())?; + } + std::fs::write(&cert, c.pem())?; + tracing::info!(dir = %dir.display(), "made the agent CA"); + Ok(Self { pem: c.pem(), key_pem }) + } + + pub fn pem(&self) -> &str { + &self.pem + } + + fn issuer(&self) -> anyhow::Result> { + let key = KeyPair::from_pem(&self.key_pem)?; + Ok(Issuer::from_ca_cert_pem(&self.pem, key)?) + } + + /// A client certificate for a cluster's agent from its CSR (the agent's + /// own key): its serial (hex), PEM and expiry (ms). + pub fn issue(&self, csr_pem: &str, team: &str, cluster: &str) -> anyhow::Result<(String, String, i64)> { + let mut csr = CertificateSigningRequestParams::from_pem(csr_pem)?; + let mut p = CertificateParams::new(Vec::::new())?; + p.subject_alt_names = vec![SanType::URI( + format!("pyo://team/{team}/cluster/{cluster}").try_into()?, + )]; + let mut dn = DistinguishedName::new(); + dn.push(DnType::CommonName, cluster); + p.distinguished_name = dn; + let now = time::OffsetDateTime::now_utc(); + p.not_before = now - time::Duration::minutes(5); + let not_after = now + time::Duration::hours(CERT_HOURS); + p.not_after = not_after; + let serial: [u8; 16] = rand::random(); + // Positive, as X.509 wants. + let mut serial = serial.to_vec(); + serial[0] &= 0x7f; + let serial_hex = hex::encode(&serial).trim_start_matches("00").to_owned(); + p.serial_number = Some(SerialNumber::from(serial)); + p.key_usages = vec![KeyUsagePurpose::DigitalSignature]; + p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; + csr.params = p; + let cert = csr.signed_by(&self.issuer()?)?; + Ok((serial_hex, cert.pem(), (not_after.unix_timestamp_nanos() / 1_000_000) as i64)) + } + + /// The endpoint's own certificate, for these names (DNS names or IPs). + fn server_cert(&self, names: &[String]) -> anyhow::Result<(String, String)> { + let key = KeyPair::generate()?; + let mut p = CertificateParams::new(Vec::::new())?; + for n in names { + p.subject_alt_names.push(match n.parse::() { + Ok(ip) => SanType::IpAddress(ip), + Err(_) => SanType::DnsName(n.as_str().try_into()?), + }); + } + let mut dn = DistinguishedName::new(); + dn.push(DnType::CommonName, names.first().map(String::as_str).unwrap_or("pyo-agent-endpoint")); + p.distinguished_name = dn; + let now = time::OffsetDateTime::now_utc(); + p.not_before = now - time::Duration::hours(1); + p.not_after = now + time::Duration::days(365); + p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; + let c = p.signed_by(&key, &self.issuer()?)?; + Ok((c.pem(), key.serialize_pem())) + } +} + +/// The cluster a client certificate names, and its serial (hex). +pub struct CertIdentity { + pub team: String, + pub cluster: String, + pub serial: String, +} + +pub fn identity(der: &[u8]) -> Option { + let (_, cert) = x509_parser::parse_x509_certificate(der).ok()?; + let serial = hex::encode(cert.raw_serial()); + let san = cert.subject_alternative_name().ok()??; + for name in &san.value.general_names { + if let x509_parser::extensions::GeneralName::URI(uri) = name { + let rest = uri.strip_prefix("pyo://team/")?; + let (team, cluster) = rest.split_once("/cluster/")?; + if team.is_empty() || cluster.is_empty() || cluster.contains('/') { + return None; + } + return Some(CertIdentity { + team: team.to_owned(), + cluster: cluster.to_owned(), + // Stored without leading zero bytes' ambiguity: as issued. + serial: serial.trim_start_matches("00").to_owned(), + }); + } + } + None +} + +/// Who's on the other end of an agent-endpoint connection. +#[derive(Clone, Debug)] +pub struct AgentPeer { + pub addr: SocketAddr, + /// The verified client certificate (DER), when one was presented. + pub cert: Option>>, +} + +impl axum::extract::connect_info::Connected> for AgentPeer { + fn connect_info(s: axum::serve::IncomingStream<'_, TlsListener>) -> Self { + s.remote_addr().clone() + } +} + +/// Accepts TLS connections; handshakes run beside the accept loop, so a +/// slow client can't hold up others. +pub struct TlsListener { + rx: tokio::sync::mpsc::Receiver<(tokio_rustls::server::TlsStream, AgentPeer)>, + local: SocketAddr, +} + +impl axum::serve::Listener for TlsListener { + type Io = tokio_rustls::server::TlsStream; + type Addr = AgentPeer; + + async fn accept(&mut self) -> (Self::Io, Self::Addr) { + match self.rx.recv().await { + Some(x) => x, + // The accept loop ended: wait forever (the server stops on its own signal). + None => std::future::pending().await, + } + } + + fn local_addr(&self) -> std::io::Result { + Ok(AgentPeer { addr: self.local, cert: None }) + } +} + +fn server_config(ca: &Ca, names: &[String]) -> anyhow::Result { + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + let mut roots = rustls::RootCertStore::empty(); + for c in CertificateDer::pem_slice_iter(ca.pem.as_bytes()) { + roots.add(c?)?; + } + let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider.clone()) + // Enrolling agents have no certificate yet; every other route wants one. + .allow_unauthenticated() + .build()?; + let (cert_pem, key_pem) = ca.server_cert(names)?; + let chain = CertificateDer::pem_slice_iter(cert_pem.as_bytes()).collect::, _>>()?; + let key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes())?; + let mut cfg = rustls::ServerConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13])? + .with_client_cert_verifier(verifier) + .with_single_cert(chain, key)?; + cfg.alpn_protocols = vec![b"http/1.1".to_vec()]; + Ok(cfg) +} + +/// Starts the endpoint when `PYO_AGENT_MTLS_ADDR` is set. +pub async fn start(state: AppState, agent_routes: Router) -> anyhow::Result<()> { + let Some(addr) = std::env::var("PYO_AGENT_MTLS_ADDR").ok().filter(|v| !v.trim().is_empty()) else { + return Ok(()); + }; + let addr: SocketAddr = addr.trim().parse()?; + let dir = std::env::var("PYO_AGENT_CA_DIR").unwrap_or_else(|_| "/var/lib/pyo/agent-ca".into()); + let ca = Ca::load_or_create(std::path::Path::new(&dir))?; + // The names the endpoint answers to: its URL's host, and any extra. + let mut names: Vec = std::env::var("PYO_AGENT_TLS_NAMES") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_owned()) + .filter(|s| !s.is_empty()) + .collect(); + if let Some(host) = std::env::var("PYO_AGENT_ENDPOINT").ok().and_then(|u| { + let rest = u.trim().split("://").nth(1)?.split('/').next()?.to_owned(); + let host = if rest.starts_with('[') { + rest.trim_start_matches('[').split(']').next()?.to_owned() + } else { + rest.split(':').next()?.to_owned() + }; + Some(host) + }) { + names.insert(0, host); + } + anyhow::ensure!(!names.is_empty(), "PYO_AGENT_MTLS_ADDR needs PYO_AGENT_ENDPOINT or PYO_AGENT_TLS_NAMES"); + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config(&ca, &names)?)); + let _ = CA.set(ca); + let tcp = tokio::net::TcpListener::bind(addr).await?; + let local = tcp.local_addr()?; + let (tx, rx) = tokio::sync::mpsc::channel(256); + tokio::spawn(async move { + loop { + let Ok((sock, peer)) = tcp.accept().await else { + tokio::time::sleep(Duration::from_millis(50)).await; + continue; + }; + let acceptor = acceptor.clone(); + let tx = tx.clone(); + tokio::spawn(async move { + let Ok(Ok(tls)) = tokio::time::timeout(Duration::from_secs(10), acceptor.accept(sock)).await else { + return; + }; + let cert = tls + .get_ref() + .1 + .peer_certificates() + .and_then(|c| c.first()) + .map(|c| Arc::new(c.clone().into_owned())); + let _ = tx.send((tls, AgentPeer { addr: peer, cert })).await; + }); + } + }); + let app = Router::new() + .route("/healthz", get(|| async { "ok" })) + .nest("/api/agent/v1", agent_routes.merge(routes())) + .layer(axum::middleware::from_fn(peer_info)) + .layer(axum::extract::DefaultBodyLimit::max(4 * 1024 * 1024)) + .with_state(state); + tracing::info!(%addr, names = ?names, "agent endpoint (mTLS) listening"); + tokio::spawn(async move { + let listener = TlsListener { rx, local }; + if let Err(e) = axum::serve(listener, app.into_make_service_with_connect_info::()).await { + tracing::warn!(error = %e, "agent endpoint stopped"); + } + }); + Ok(()) +} + +/// Handlers read the peer's address as everywhere else, and the agent +/// extractor reads its certificate. +async fn peer_info( + ConnectInfo(peer): ConnectInfo, + mut req: axum::extract::Request, + next: axum::middleware::Next, +) -> axum::response::Response { + req.extensions_mut().insert(ConnectInfo(peer.addr)); + req.extensions_mut().insert(peer); + next.run(req).await +} + +fn routes() -> Router { + Router::new() + .route("/enroll", post(enroll)) + .route("/renew", post(renew)) +} + +#[derive(Deserialize)] +struct EnrollBody { + token: String, + csr: String, +} + +/// The first client certificate, for the connect command's token. Once. +async fn enroll( + State(s): State, + peer: Option>, + Json(b): Json, +) -> ApiResult> { + let ca = ca().ok_or_else(|| ApiError::not_found("Agent endpoint"))?; + if peer.is_none() { + return Err(ApiError::not_found("Agent endpoint")); + } + let hash = sha256_hex(b.token.trim()); + let mut tx = s.db.begin().await?; + let row: Option<(String, String, Option)> = sqlx::query_as( + "SELECT id, team_id, agent_token_used_hash FROM pyo.clusters WHERE agent_token_hash = $1 FOR UPDATE", + ) + .bind(&hash) + .fetch_optional(&mut *tx) + .await?; + let (cluster, team, used) = + row.ok_or_else(|| ApiError::new(StatusCode::UNAUTHORIZED, "Unknown connect token."))?; + if used.as_deref() == Some(hash.as_str()) { + return Err(ApiError::conflict( + "This connect command was used already. Get a new one in the cluster's settings.", + )); + } + let (serial, pem, not_after) = ca + .issue(&b.csr, &team, &cluster) + .map_err(|e| ApiError::bad_request(format!("Couldn't read the request: {e}")))?; + sqlx::query("UPDATE pyo.clusters SET agent_cert_prev_serial = NULL, agent_cert_serial = $2, agent_token_used_hash = $3 WHERE id = $1") + .bind(&cluster) + .bind(&serial) + .bind(&hash) + .execute(&mut *tx) + .await?; + tx.commit().await?; + tracing::info!(%cluster, "agent enrolled"); + Ok(Json(json!({ "certificate": pem, "notAfter": not_after, "ca": ca.pem() }))) +} + +#[derive(Deserialize)] +struct RenewBody { + csr: String, +} + +/// A new certificate for the one presented (its cluster, a fresh key). +async fn renew( + State(s): State, + cluster: AgentCluster, + peer: Option>, + Json(b): Json, +) -> ApiResult> { + let ca = ca().ok_or_else(|| ApiError::not_found("Agent endpoint"))?; + if !peer.is_some_and(|p| p.cert.is_some()) { + return Err(ApiError::new(StatusCode::UNAUTHORIZED, "Renewing needs the current certificate.")); + } + let (serial, pem, not_after) = ca + .issue(&b.csr, &cluster.team_id, &cluster.id) + .map_err(|e| ApiError::bad_request(format!("Couldn't read the request: {e}")))?; + sqlx::query("UPDATE pyo.clusters SET agent_cert_prev_serial = agent_cert_serial, agent_cert_serial = $2 WHERE id = $1") + .bind(&cluster.id) + .bind(&serial) + .execute(&s.db) + .await?; + Ok(Json(json!({ "certificate": pem, "notAfter": not_after, "ca": ca.pem() }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_cluster_certificate_names_its_cluster() { + let dir = std::env::temp_dir().join(format!("pyo-ca-test-{}", rand::random::())); + let ca = Ca::load_or_create(&dir).unwrap(); + let key = KeyPair::generate().unwrap(); + let csr = CertificateParams::new(Vec::::new()) + .unwrap() + .serialize_request(&key) + .unwrap() + .pem() + .unwrap(); + let (serial, pem, _) = ca.issue(&csr, "team_a", "cl_1").unwrap(); + let der = CertificateDer::from_pem_slice(pem.as_bytes()).unwrap(); + let id = identity(&der).unwrap(); + assert_eq!((id.team.as_str(), id.cluster.as_str()), ("team_a", "cl_1")); + assert_eq!(id.serial, serial); + // The same CA again from its files. + let again = Ca::load_or_create(&dir).unwrap(); + assert_eq!(again.pem(), ca.pem()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/pyo-api/src/install.rs b/crates/pyo-api/src/install.rs index ec64991d..06e0757a 100644 --- a/crates/pyo-api/src/install.rs +++ b/crates/pyo-api/src/install.rs @@ -23,14 +23,33 @@ pub async fn manifest( headers: axum::http::HeaderMap, Query(q): Query, ) -> ApiResult { - let known: bool = sqlx::query_scalar( - "SELECT EXISTS (SELECT 1 FROM pyo.clusters WHERE agent_token_hash = $1)", - ) - .bind(sha256_hex(&q.token)) - .fetch_one(&s.db) - .await?; - if !known || !q.token.bytes().all(|b| b.is_ascii_hexdigit()) { + let cluster: Option = + sqlx::query_scalar("SELECT id FROM pyo.clusters WHERE agent_token_hash = $1") + .bind(sha256_hex(&q.token)) + .fetch_optional(&s.db) + .await?; + let Some(cluster) = cluster.filter(|_| q.token.bytes().all(|b| b.is_ascii_hexdigit())) else { return Err(ApiError::not_found("Install token")); + }; + // Pyo Cloud: the agent dials the mTLS endpoint, trusts only its CA and + // runs only commands the signer signed for this cluster (agent_tls.rs, + // the agent's trust.rs). + if let Some(endpoint) = crate::agent_tls::endpoint() { + let mut env = vec![ + ("PYO_AGENT_CA", crate::agent_tls::ca().map(|c| c.pem().to_owned()).unwrap_or_default()), + ("PYO_CLUSTER_ID", cluster.clone()), + ]; + if let Some(signer) = crate::command_signer() { + env.push(("PYO_COMMAND_KEY", signer.public_keys())); + } + let yaml = render_with(&endpoint, &s.config.agent_image, &q.token, &env); + return Ok(( + [ + (header::CONTENT_TYPE, "application/yaml"), + (header::CACHE_CONTROL, "no-store"), + ], + yaml, + )); } // The agent reaches Pyo the way the installer just did, unless that was // localhost (meaningless inside a pod): then the in-cluster address. @@ -131,6 +150,11 @@ pub fn parts(upgrades: bool) -> &'static pyo_proto::rbac::InstallParts { /// The agent's manifest. On the cluster Pyo itself runs on (an in-cluster /// API address), its agent also runs Pyo's upgrader. pub fn render(api_url: &str, image: &str, token: &str) -> String { + render_with(api_url, image, token, &[]) +} + +/// [`render`], with more of the agent's env (Pyo Cloud's trust settings). +pub fn render_with(api_url: &str, image: &str, token: &str, extra_env: &[(&str, String)]) -> String { let parts = parts(pyo_proto::in_cluster_url(api_url)); let docs = |objects: &[serde_json::Value]| { objects @@ -145,10 +169,12 @@ pub fn render(api_url: &str, image: &str, token: &str) -> String { let pins: String = parts .pins .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .chain(extra_env.iter().map(|(k, v)| (*k, v.as_str()))) .map(|(k, v)| { format!( " - name: {k}\n value: {}\n", - serde_json::Value::from(v.as_str()) + serde_json::Value::from(v) ) }) .collect(); diff --git a/crates/pyo-api/src/lib.rs b/crates/pyo-api/src/lib.rs index f98aeba9..707a6142 100644 --- a/crates/pyo-api/src/lib.rs +++ b/crates/pyo-api/src/lib.rs @@ -8,6 +8,7 @@ //! (see [`Extensions`]); self-hosted Pyo has none of those. mod agent; +mod agent_tls; mod alerts; pub mod auth; mod backup; @@ -461,6 +462,7 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { .route("/readyz", get(readyz)); let extra_routes = extra_routes.unwrap_or_default(); let door_state = state.clone(); + let door_state_for_agents = state.clone(); let app = if !role.web() { // A worker answers only its probes. probes.with_state(state) @@ -557,6 +559,17 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { Err(e) => tracing::warn!(%door, error = %e, "registry door not listening"), } } + // Agents over mTLS (agent_tls.rs), when this Pyo has that endpoint. + if role.web() { + agent_tls::start( + door_state_for_agents, + agent::routes() + .merge(sites::agent_routes()) + .merge(terminal::agent_routes()) + .merge(database_imports::agent_routes()), + ) + .await?; + } let addr: SocketAddr = env("LISTEN_ADDR", "0.0.0.0:8000").parse()?; tracing::info!(%addr, web = %web_dir.display(), "pyo api listening"); let listener = tokio::net::TcpListener::bind(addr).await?; diff --git a/crates/pyo-api/src/ops.rs b/crates/pyo-api/src/ops.rs index 05805804..edc69f15 100644 --- a/crates/pyo-api/src/ops.rs +++ b/crates/pyo-api/src/ops.rs @@ -802,6 +802,19 @@ async fn connect_command( token: &str, public: Option<&str>, ) -> ApiResult<(String, bool)> { + // Agents over mTLS (Pyo Cloud): machines install from Pyo's public + // address (PYO_PUBLIC_API_URL, else the dashboard's), never a tailnet. + let configured = crate::agent_tls::endpoint().and_then(|_| { + std::env::var("PYO_PUBLIC_API_URL") + .ok() + .filter(|u| !u.trim().is_empty()) + }); + let public = configured.as_deref().or(public); + if crate::agent_tls::endpoint().is_some() && public.is_none() { + return Err(ApiError::bad_request( + "Connect from the dashboard's address: Pyo has no public address set.", + )); + } if let Some(url) = public { let url = url.trim().trim_end_matches('/'); if !(url.starts_with("https://") || url.starts_with("http://")) @@ -6329,7 +6342,8 @@ async fn apply( let team_id = team_of(tx, "clusters", &id).await?; require_role(tx, user, &team_id, Role::Admin).await?; let token = secret_token(); - sqlx::query("UPDATE pyo.clusters SET agent_token_hash = $2 WHERE id = $1") + // The agent's certificates go too: it connects again with the new command. + sqlx::query("UPDATE pyo.clusters SET agent_token_hash = $2, agent_cert_serial = NULL, agent_cert_prev_serial = NULL WHERE id = $1") .bind(&id) .bind(sha256_hex(&token)) .execute(&mut **tx) From c85299aa75a75f1f8da32068238b4679561286d3 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Tue, 17 Nov 2026 11:22:08 +0700 Subject: [PATCH 005/136] feat(connect): keep built images in the cluster's own registry With PYO_CLUSTER_REGISTRY=in-cluster, connect commands add --local-registry: connect.sh sets up a registry in pyo-system and a loopback forward on every server (127.0.0.1:5005), and builders on that cluster push there instead of to Pyo's registry door. Images stay on the customer's servers. --- crates/pyo-api/assets/connect.sh | 127 ++++++++++++++++++++++++++++++- crates/pyo-api/src/deploy.rs | 14 +++- crates/pyo-api/src/join.rs | 2 + 3 files changed, 139 insertions(+), 4 deletions(-) diff --git a/crates/pyo-api/assets/connect.sh b/crates/pyo-api/assets/connect.sh index 781d50ee..beb01c21 100644 --- a/crates/pyo-api/assets/connect.sh +++ b/crates/pyo-api/assets/connect.sh @@ -11,6 +11,8 @@ # --tailscale-key joins your tailnet first (a single-use key from Pyo) # --registry Pyo's registry door, for images Pyo builds # --registry-token this cluster's login there (pull only) +# --local-registry a registry in this cluster for the images it builds, +# instead of Pyo's (Pyo Cloud: images stay on your servers) # --version runs this Pyo release's connect.sh instead, from pyo.dev # # Or only joins this machine to the tailnet (Pyo's own machine does this @@ -234,7 +236,7 @@ quietly() { set -euo pipefail export DEBIAN_FRONTEND=noninteractive -API="" TOKEN="" TS_AUTHKEY="${TS_AUTHKEY:-}" REGISTRY="" REGISTRY_TOKEN="" +API="" TOKEN="" TS_AUTHKEY="${TS_AUTHKEY:-}" REGISTRY="" REGISTRY_TOKEN="" LOCAL_REGISTRY="" UNINSTALL="" KEEP_DATA="" YES="" DRY_RUN="" WITH_PYO="" TAILNET_ONLY="" while [ $# -gt 0 ]; do case "$1" in @@ -243,6 +245,7 @@ while [ $# -gt 0 ]; do --tailscale-key) TS_AUTHKEY="$2"; shift 2 ;; --registry) REGISTRY="$2"; shift 2 ;; --registry-token) REGISTRY_TOKEN="$2"; shift 2 ;; + --local-registry) LOCAL_REGISTRY=1; shift ;; --tailnet-only) TAILNET_ONLY=1; shift ;; --uninstall) UNINSTALL=1; shift ;; --keep-data) KEEP_DATA=1; shift ;; @@ -553,7 +556,7 @@ if [ -z "$TAILNET_ONLY" ] && [ -z "$API" ] && [ -z "$TOKEN" ] && command -v k3s case "$API" in http://*.svc:* | http://*.svc.cluster.local:*) API=http://127.0.0.1:8000 ;; esac [ -z "$API" ] || echo "Updating this cluster's Pyo agent." fi -[ -n "$TAILNET_ONLY" ] || { [ -n "$API" ] && [ -n "$TOKEN" ]; } || { echo "Usage: connect.sh --api URL --token TOKEN [--tailscale-key KEY] [--registry HOST:PORT --registry-token TOKEN]" >&2; exit 2; } +[ -n "$TAILNET_ONLY" ] || { [ -n "$API" ] && [ -n "$TOKEN" ]; } || { echo "Usage: connect.sh --api URL --token TOKEN [--tailscale-key KEY] [--registry HOST:PORT --registry-token TOKEN | --local-registry]" >&2; exit 2; } [ -z "$REGISTRY" ] || [ -n "$REGISTRY_TOKEN" ] || { echo "--registry needs --registry-token: copy the full command from Pyo." >&2; exit 2; } case "$REGISTRY_TOKEN" in *[!0-9a-fA-F]*) echo "That registry token doesn't look like one from Pyo." >&2; exit 2 ;; esac # The agent's token and its commands' secrets travel to --api: plain http @@ -1191,6 +1194,23 @@ REG ) chmod 600 /etc/rancher/k3s/registries.yaml fi +# Its own registry (--local-registry): this machine pulls the images built +# here from 127.0.0.1:5005, which pyo-registry-host forwards to the registry. +LOCAL_REGISTRY_NEW="" +if [ -n "$LOCAL_REGISTRY" ] && ! grep -qs '"127.0.0.1:5005"' /etc/rancher/k3s/registries.yaml; then + if [ -s /etc/rancher/k3s/registries.yaml ]; then + echo "/etc/rancher/k3s/registries.yaml has other settings. Add a mirror for 127.0.0.1:5005 (http://127.0.0.1:5005) to it, then run this again." >&2 + exit 1 + fi + (umask 077 && cat > /etc/rancher/k3s/registries.yaml <<'REG' +mirrors: + "127.0.0.1:5005": + endpoint: + - "http://127.0.0.1:5005" +REG + ) + LOCAL_REGISTRY_NEW=1 +fi if ! command -v k3s >/dev/null; then # Pyo's k3s (deploy/k3s.env), downloaded and checked before it's set up. quietly "Downloading k3s…" k3s_fetch "$K3S_DIR" "$PYO_K3S_VERSION" || @@ -1217,7 +1237,7 @@ else # Its memory reserve brought up to date; k3s restarts below if it changed. k3s_memory_refresh later # k3s finds a newly installed NVIDIA toolkit only when it starts. - if [ -n "$REGISTRY" ] || [ -n "$GPU_TOOLKIT_NEW" ] || [ -n "$K3S_MEMORY_CHANGED" ]; then systemctl restart k3s 2>/dev/null || true; fi + if [ -n "$REGISTRY" ] || [ -n "$LOCAL_REGISTRY_NEW" ] || [ -n "$GPU_TOOLKIT_NEW" ] || [ -n "$K3S_MEMORY_CHANGED" ]; then systemctl restart k3s 2>/dev/null || true; fi fi k3s_up() { k3s kubectl get nodes >/dev/null 2>&1; } @@ -1263,6 +1283,107 @@ gateway_crds() { } gateway_crds +# The cluster's own registry (--local-registry): builders here push to it, +# and every server pulls from it through 127.0.0.1:5005 (loopback only). +local_registry() { + k3s kubectl apply --server-side --force-conflicts --field-manager=pyo -f - >/dev/null <<'YAML' +apiVersion: v1 +kind: Namespace +metadata: + name: pyo-system + labels: { pyo.dev/managed: "true" } +--- +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: registry-data + namespace: pyo-system + labels: { app.kubernetes.io/part-of: pyo } +spec: + accessModes: [ReadWriteOnce] + resources: + requests: + storage: 20Gi +--- +apiVersion: v1 +kind: Service +metadata: + name: pyo-registry + namespace: pyo-system + labels: { app.kubernetes.io/name: registry, app.kubernetes.io/part-of: pyo } +spec: + selector: { app.kubernetes.io/name: registry } + ports: + - { name: registry, port: 5000, targetPort: registry } +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: registry + namespace: pyo-system + labels: { app.kubernetes.io/name: registry, app.kubernetes.io/part-of: pyo } +spec: + replicas: 1 + strategy: { type: Recreate } + selector: + matchLabels: { app.kubernetes.io/name: registry } + template: + metadata: + labels: { app.kubernetes.io/name: registry, app.kubernetes.io/part-of: pyo } + spec: + containers: + - name: registry + image: registry:3.1.2 + env: + - { name: REGISTRY_HTTP_ADDR, value: "0.0.0.0:5000" } + - { name: REGISTRY_STORAGE_DELETE_ENABLED, value: "true" } + - { name: OTEL_TRACES_EXPORTER, value: "none" } + - { name: REGISTRY_LOG_LEVEL, value: "warn" } + - { name: REGISTRY_LOG_ACCESSLOG_DISABLED, value: "true" } + ports: + - { name: registry, containerPort: 5000 } + readinessProbe: + httpGet: { path: /v2/, port: registry } + periodSeconds: 30 + volumeMounts: + - { name: data, mountPath: /var/lib/registry } + resources: + requests: { cpu: 10m, memory: 24Mi } + limits: { memory: 512Mi } + volumes: + - name: data + persistentVolumeClaim: { claimName: registry-data } +--- +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: pyo-registry-host + namespace: pyo-system + labels: { app.kubernetes.io/name: pyo-registry-host, app.kubernetes.io/part-of: pyo } +spec: + selector: + matchLabels: { app.kubernetes.io/name: pyo-registry-host } + template: + metadata: + labels: { app.kubernetes.io/name: pyo-registry-host, app.kubernetes.io/part-of: pyo } + spec: + hostNetwork: true + dnsPolicy: ClusterFirstWithHostNet + tolerations: + - { operator: Exists } + containers: + - name: forward + image: alpine/socat:1.8.1.3 + args: ["TCP-LISTEN:5005,bind=127.0.0.1,fork,reuseaddr", "TCP:pyo-registry.pyo-system.svc.cluster.local:5000"] + resources: + requests: { cpu: 5m, memory: 8Mi } + limits: { memory: 64Mi } +YAML +} +if [ -n "$LOCAL_REGISTRY" ]; then + quietly "Setting up this cluster's registry…" local_registry || { echo "Couldn't set up this cluster's registry (see above)." >&2; exit 1; } +fi + # >>> pyo:agent-apply (connect.sh only; join.rs tests it) # The Kubernetes minor version the API server reports; empty when it doesn't # answer. diff --git a/crates/pyo-api/src/deploy.rs b/crates/pyo-api/src/deploy.rs index 60a4cbf6..e7d2ee74 100644 --- a/crates/pyo-api/src/deploy.rs +++ b/crates/pyo-api/src/deploy.rs @@ -72,12 +72,24 @@ pub fn registry_push() -> String { .unwrap_or_default() } +/// Every other cluster keeps the images it builds in its own registry +/// (`PYO_CLUSTER_REGISTRY=in-cluster`, Pyo Cloud): connect.sh's +/// `--local-registry` sets it up, and its servers pull them from +/// 127.0.0.1:5005 as on Pyo's own. +pub fn in_cluster_registries() -> bool { + std::env::var("PYO_CLUSTER_REGISTRY").is_ok_and(|v| v.trim() == "in-cluster") +} + /// Where a builder on this cluster pushes: the door in the cluster on Pyo's -/// own, its tailnet address elsewhere (None without one). +/// own, its own registry with in-cluster registries, else Pyo's door at its +/// tailnet address (None without one). pub fn builder_registry(on_pyos_cluster: bool) -> Option { if on_pyos_cluster { return Some(DOOR_IN_CLUSTER.into()); } + if in_cluster_registries() { + return Some(INTERNAL_DEFAULT.into()); + } let push = registry_push(); (!push.is_empty()).then_some(push) } diff --git a/crates/pyo-api/src/join.rs b/crates/pyo-api/src/join.rs index a217dc08..a62fc7af 100644 --- a/crates/pyo-api/src/join.rs +++ b/crates/pyo-api/src/join.rs @@ -344,6 +344,8 @@ pub fn connect_args( if let Some((r, t)) = registry { a.push(("--registry", Some(r.to_owned()))); a.push(("--registry-token", Some(t.to_owned()))); + } else if crate::deploy::in_cluster_registries() { + a.push(("--local-registry", None)); } a } From 7b4e2cc2378a8f9c343d57e848664ee5c6c31638 Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Tue, 17 Nov 2026 11:24:49 +0700 Subject: [PATCH 006/136] feat(api): require proof of domain ownership on shared installations With Extensions::verify_domains, a team claims a new hostname only when the TXT record _pyo-verify. holds the token Pyo gives that team for it. A team that proves a hostname takes it over from a team that can't anymore. Free domains need no record but must point at one of the team's own servers. PYO_DEV_TXT_FILE reads records from a file, for tests only. --- crates/pyo-api/src/domainproof.rs | 200 ++++++++++++++++++++++++++++++ crates/pyo-api/src/freedomain.rs | 2 +- crates/pyo-api/src/lib.rs | 5 + crates/pyo-api/src/ops.rs | 12 ++ 4 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 crates/pyo-api/src/domainproof.rs diff --git a/crates/pyo-api/src/domainproof.rs b/crates/pyo-api/src/domainproof.rs new file mode 100644 index 00000000..e8a643b4 --- /dev/null +++ b/crates/pyo-api/src/domainproof.rs @@ -0,0 +1,200 @@ +//! Proof of owning a domain, before a team may claim it (Pyo Cloud). +//! +//! Hostnames are first come over every team of an installation, so where +//! teams don't trust each other one could claim another's domain first. +//! There ([`crate::verify_domains`]), a team claims a hostname only with a +//! DNS TXT record `_pyo-verify.` holding the token Pyo gives that +//! team for that host. A team that proves it can take a hostname over from +//! a team that can't (anymore). Free domains (nip.io and sslip.io) need no +//! record: their address must be one of the team's own servers. +//! +//! TXT records are read through Cloudflare's DNS over HTTPS. For tests +//! only, `PYO_DEV_TXT_FILE` names a JSON file of records to use instead +//! (`{"_pyo-verify.example.com": ["pyo-verify-…"]}`). + +use std::time::Duration; + +use serde_json::Value; +use sqlx::{Postgres, Transaction}; + +use crate::error::ApiResult; + +/// The record a team adds for `host`. +pub fn record(host: &str) -> String { + format!("_pyo-verify.{host}") +} + +/// The token a team puts in `host`'s record: the same every time, and +/// another team's never matches. +pub fn token(team_id: &str, host: &str) -> String { + let h = crate::ids::sha256_hex(&format!("pyo-verify\n{team_id}\n{}", host.to_lowercase())); + format!("pyo-verify-{}", &h[..32]) +} + +/// What to tell a team that hasn't proven `host` yet. +pub fn how_to(team_id: &str, host: &str) -> String { + format!( + "Prove you own {host} first: add a TXT record {} with the value {}, then try again.", + record(host), + token(team_id, host) + ) +} + +/// The TXT values at `name`. +async fn txt(name: &str) -> Vec { + if let Ok(path) = std::env::var("PYO_DEV_TXT_FILE") + && !path.trim().is_empty() + { + let v: Value = std::fs::read(path.trim()) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default(); + return v[name] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(); + } + let Ok(client) = reqwest::Client::builder() + .timeout(Duration::from_secs(8)) + .build() + else { + return vec![]; + }; + let Ok(res) = client + .get("https://cloudflare-dns.com/dns-query") + .query(&[("name", name), ("type", "TXT")]) + .header("accept", "application/dns-json") + .send() + .await + else { + return vec![]; + }; + let v: Value = res.json().await.unwrap_or_default(); + v["Answer"] + .as_array() + .into_iter() + .flatten() + .filter(|a| a["type"] == 16) + .filter_map(|a| a["data"].as_str()) + .map(|d| d.trim().trim_matches('"').to_owned()) + .collect() +} + +/// Whether `host`'s record holds `team_id`'s token now. +pub async fn proven(team_id: &str, host: &str) -> bool { + let want = token(team_id, host); + txt(&record(host)).await.contains(&want) +} + +/// A free domain on one of the team's own servers' addresses (it can't +/// hold a TXT record, and points only at that server anyway). +async fn own_free_domain( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + host: &str, +) -> ApiResult> { + let Some(ip) = crate::freedomain::ip_in(host) else { + return Ok(None); + }; + let clusters: Vec = sqlx::query_scalar("SELECT id FROM pyo.clusters WHERE team_id = $1") + .bind(team_id) + .fetch_all(&mut **tx) + .await?; + for c in clusters { + if let Some((_, cluster)) = crate::freedomain::load(tx, &c).await? + && cluster.known().contains(&std::net::IpAddr::V4(ip)) + { + return Ok(Some(true)); + } + } + Ok(Some(false)) +} + +/// 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). +pub async fn check_claims( + tx: &mut Transaction<'_, Postgres>, + team_id: &str, + service_id: &str, + new_hosts: &[String], +) -> ApiResult> { + use crate::error::ApiError; + let mut wake = vec![]; + for host in new_hosts { + if pyo_proto::system::is_tailnet_host(host) { + continue; + } + match own_free_domain(tx, team_id, host).await? { + Some(true) => continue, + Some(false) => { + return Err(ApiError::forbidden(format!( + "{host} points at a server that isn't one of this team's." + ))); + } + None => {} + } + if !proven(team_id, host).await { + return Err(ApiError::forbidden(how_to(team_id, host))); + } + // Held by another team: theirs while they can still prove it. + let holders: Vec<(String, String, Value)> = sqlx::query_as( + "SELECT a.id, a.team_id, a.spec->'domains' FROM pyo.services a, jsonb_array_elements(a.spec->'domains') d + WHERE a.id <> $1 AND a.team_id <> $2 AND NOT a.deleting AND lower(d->>'hostname') = $3", + ) + .bind(service_id) + .bind(team_id) + .bind(host) + .fetch_all(&mut **tx) + .await?; + for (other_service, other_team, domains) in holders { + if proven(&other_team, host).await { + return Err(ApiError::conflict(format!("{host} is already used by another service."))); + } + let kept: Vec = domains + .as_array() + .into_iter() + .flatten() + .filter(|d| d["hostname"].as_str().map(str::to_lowercase).as_deref() != Some(host.as_str())) + .cloned() + .collect(); + sqlx::query("UPDATE pyo.services SET spec = jsonb_set(spec, '{domains}', $2) WHERE id = $1") + .bind(&other_service) + .bind(Value::Array(kept)) + .execute(&mut **tx) + .await?; + if let Some(c) = crate::routes::changed(tx, &other_service, true).await? { + wake.push(c); + } + crate::ops::log_activity( + tx, + &other_team, + "Pyo", + "domain.removed", + "warning", + &format!("{host} was removed: another team proved it owns it"), + serde_json::json!({ "kind": "service", "id": other_service, "label": host }), + serde_json::json!({}), + ) + .await?; + tracing::info!(%host, from = %other_team, to = %team_id, "domain taken over by its proven owner"); + } + } + Ok(wake) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tokens_differ_by_team_and_host() { + assert_eq!(token("t1", "Example.com"), token("t1", "example.com")); + assert_ne!(token("t1", "example.com"), token("t2", "example.com")); + assert_ne!(token("t1", "example.com"), token("t1", "www.example.com")); + assert!(how_to("t1", "a.com").contains("_pyo-verify.a.com")); + } +} diff --git a/crates/pyo-api/src/freedomain.rs b/crates/pyo-api/src/freedomain.rs index 1c4e13bb..e336c8a8 100644 --- a/crates/pyo-api/src/freedomain.rs +++ b/crates/pyo-api/src/freedomain.rs @@ -240,7 +240,7 @@ impl Cluster { } /// Every address of its own: where a free domain Pyo made could point. - fn known(&self) -> Vec { + pub(crate) fn known(&self) -> Vec { let mut known: Vec = self.servers.iter().flat_map(addresses).collect(); known.extend( self.lb_ips diff --git a/crates/pyo-api/src/lib.rs b/crates/pyo-api/src/lib.rs index 707a6142..920a892c 100644 --- a/crates/pyo-api/src/lib.rs +++ b/crates/pyo-api/src/lib.rs @@ -30,6 +30,7 @@ mod database_imports; mod database_logs; mod databases; mod deploy; +mod domainproof; pub mod error; mod firewall; mod freedomain; @@ -298,6 +299,7 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { } = ext; let _ = FEATURES.set(features); let _ = VERIFY_DOMAINS.set(verify_domains); + let dev_txt = std::env::var("PYO_DEV_TXT_FILE").is_ok_and(|v| !v.trim().is_empty()); if let Some(s) = command_signer { let _ = SIGNER.set(s); } @@ -449,6 +451,9 @@ pub async fn run(ext: Extensions) -> anyhow::Result<()> { }); } tracing::info!(role = ?role, version = env!("CARGO_PKG_VERSION"), "pyo starting"); + if dev_txt { + tracing::warn!("PYO_DEV_TXT_FILE is set: domain proofs come from that file, not DNS. For tests only"); + } let web_dir = PathBuf::from(env("PYO_WEB_DIR", "dash/dist/client")); // Unknown paths are dashboard routes: hand them the app shell. diff --git a/crates/pyo-api/src/ops.rs b/crates/pyo-api/src/ops.rs index edc69f15..9881bbd7 100644 --- a/crates/pyo-api/src/ops.rs +++ b/crates/pyo-api/src/ops.rs @@ -717,6 +717,18 @@ async fn domains_unique( if hosts.is_empty() { return Ok(()); } + // Teams that don't trust each other (Pyo Cloud): a new hostname needs + // proof of owning it, and one held without proof is taken over. + if crate::verify_domains() { + let current: Vec = sqlx::query_scalar( + "SELECT lower(d->>'hostname') FROM pyo.services a, jsonb_array_elements(a.spec->'domains') d WHERE a.id = $1", + ) + .bind(service_id) + .fetch_all(&mut **tx) + .await?; + let new: Vec = hosts.iter().filter(|h| !current.contains(h)).cloned().collect(); + crate::domainproof::check_claims(tx, team_id, service_id, &new).await?; + } let taken: Option<(String, String, String)> = sqlx::query_as( "SELECT lower(d->>'hostname'), a.team_id, a.name FROM pyo.services a, jsonb_array_elements(a.spec->'domains') d WHERE a.id <> $1 AND NOT a.deleting AND lower(d->>'hostname') = ANY($2) LIMIT 1", From 98f4a14a7e97d76bf70750370a5b7fb36ecf0b1a Mon Sep 17 00:00:00 2001 From: Frans Allen Date: Tue, 17 Nov 2026 11:30:37 +0700 Subject: [PATCH 007/136] feat(dash): offer test payments on the billing page When the API says test payments are on (a development build of Pyo Cloud), Billing shows a test payment option. No money moves. --- dash/src/lib/pyo/backend.ts | 5 +++- .../routes/_app/$team/settings/billing.tsx | 27 +++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/dash/src/lib/pyo/backend.ts b/dash/src/lib/pyo/backend.ts index 17455436..c4920f02 100644 --- a/dash/src/lib/pyo/backend.ts +++ b/dash/src/lib/pyo/backend.ts @@ -832,7 +832,7 @@ export type CloudBilling = { pricePerServerUsd: number; totalUsd: number; status: "none" | "active" | "past_due" | "paused" | "canceled"; - provider: "polar" | "midtrans" | null; + provider: "polar" | "midtrans" | "test" | null; seats: number; periodEnd: number | null; graceUntil: number | null; @@ -847,6 +847,8 @@ export type CloudBilling = { topUpServers: number; topUpIdr: number; } | null; + /** A development build's payments without a provider (no money moves). */ + testPayments?: boolean; }; export const cloudBilling = { get: (team: string) => request(`/api/cloud/billing?${new URLSearchParams({ team })}`), @@ -854,4 +856,5 @@ export const cloudBilling = { polarPortal: (team: string) => request<{ url: string }>("/api/cloud/billing/polar/portal", { method: "POST", body: { team } }), midtransCheckout: (team: string, kind: "month" | "topup") => request<{ token: string; redirectUrl: string }>("/api/cloud/billing/midtrans/checkout", { method: "POST", body: { team, kind } }), + testPay: (team: string) => request<{ ok: boolean }>("/api/cloud/billing/test/pay", { method: "POST", body: { team } }), }; diff --git a/dash/src/routes/_app/$team/settings/billing.tsx b/dash/src/routes/_app/$team/settings/billing.tsx index 49acb199..b60a980f 100644 --- a/dash/src/routes/_app/$team/settings/billing.tsx +++ b/dash/src/routes/_app/$team/settings/billing.tsx @@ -1,4 +1,4 @@ -import { ArrowSquareOutIcon, CreditCardIcon, QrCodeIcon } from "@phosphor-icons/react"; +import { ArrowSquareOutIcon, CreditCardIcon, FlaskIcon, QrCodeIcon } from "@phosphor-icons/react"; import { createFileRoute } from "@tanstack/react-router"; import { useState, type ReactNode } from "react"; import { Button } from "~/components/ui/Button"; @@ -74,7 +74,7 @@ function Billing({ b, team }: { b: CloudBilling; team: string }) { {usd(b.totalUsd)}} /> - {b.provider ? : null} + {b.provider ? : null} {b.periodEnd ? : null} {b.status === "past_due" && b.graceUntil ? ( @@ -143,6 +143,29 @@ function Billing({ b, team }: { b: CloudBilling; team: string }) { } /> ) : null} + {b.testPayments ? ( +