Skip to content
Python

fix(azure): validate live CLI tokens and provider receipts

Rohit P5091a0a7adf8
diff --git a/harness/service-cli/src/deployment_azure_api.rs b/harness/service-cli/src/deployment_azure_api.rs
index 3b5a6807..a19ca274 100644
--- a/harness/service-cli/src/deployment_azure_api.rs
+++ b/harness/service-cli/src/deployment_azure_api.rs
@@ -100,54 +100,7 @@ impl Azure {
.await?
.context("Missing identity response")?
} else {
- // Azure CLI only supplies a short-lived token in memory. Neither its
- // stderr nor response body may be copied into diagnostics/journals.
- let mut cmd = tokio::process::Command::new("az");
- cmd.args([
- "account",
- "get-access-token",
- "--subscription",
- &self.subscription,
- "--tenant",
- &self.tenant,
- "--resource",
- resource,
- "--only-show-errors",
- "-o",
- "json",
- ])
- .env("AZURE_EXTENSION_USE_DYNAMIC_INSTALL", "no")
- .env("AZURE_CORE_COLLECT_TELEMETRY", "false")
- .kill_on_drop(true);
- use tokio::io::AsyncReadExt;
- cmd.stdout(std::process::Stdio::piped())
- .stderr(std::process::Stdio::null())
- .stdin(std::process::Stdio::null());
- let mut child = cmd.spawn().context("Token command unavailable")?;
- let stdout = child.stdout.take().unwrap();
- let mut bytes = Zeroizing::new(Vec::new());
- let mut bounded_stdout = stdout.take(65537);
- let operation = async {
- let (status, _) =
- tokio::try_join!(child.wait(), bounded_stdout.read_to_end(&mut bytes))?;
- Ok::<_, std::io::Error>(status)
- };
- let status = tokio::time::timeout(Duration::from_secs(20), operation)
- .await
- .context("Token command timed out")?
- .context("Token command failed")?;
- ensure!(
- status.success() && bytes.len() <= 65536,
- "Token acquisition failed"
- );
- let v: Value = serde_json::from_slice(&bytes).context("Invalid credential response")?;
- bytes.clear();
- ensure!(
- v["tenant"].as_str() == Some(&self.tenant)
- && v["subscription"].as_str() == Some(&self.subscription),
- "Token target mismatch"
- );
- v
+ cli_token_response("az", &self.subscription, &self.tenant, resource).await?
};
let token = v
.get("accessToken")
@@ -331,6 +284,58 @@ async fn bounded(mut r: reqwest::Response, limit: usize) -> Result<Option<Value>
.context("Malformed provider response; outcome unknown")
}
+async fn cli_token_response(
+ program: &str,
+ subscription: &str,
+ tenant: &str,
+ resource: &str,
+) -> Result<Value> {
+ // Azure CLI only supplies a short-lived token in memory. Neither its
+ // stderr nor response body may be copied into diagnostics/journals.
+ let mut cmd = tokio::process::Command::new(program);
+ cmd.args([
+ "account",
+ "get-access-token",
+ "--subscription",
+ subscription,
+ "--resource",
+ resource,
+ "--only-show-errors",
+ "-o",
+ "json",
+ ])
+ .env("AZURE_EXTENSION_USE_DYNAMIC_INSTALL", "no")
+ .env("AZURE_CORE_COLLECT_TELEMETRY", "false")
+ .kill_on_drop(true);
+ use tokio::io::AsyncReadExt;
+ cmd.stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::null())
+ .stdin(std::process::Stdio::null());
+ let mut child = cmd.spawn().context("Token command unavailable")?;
+ let stdout = child.stdout.take().unwrap();
+ let mut bytes = Zeroizing::new(Vec::new());
+ let mut bounded_stdout = stdout.take(65537);
+ let operation = async {
+ let (status, _) = tokio::try_join!(child.wait(), bounded_stdout.read_to_end(&mut bytes))?;
+ Ok::<_, std::io::Error>(status)
+ };
+ let status = tokio::time::timeout(Duration::from_secs(20), operation)
+ .await
+ .context("Token command timed out")?
+ .context("Token command failed")?;
+ ensure!(
+ status.success() && bytes.len() <= 65536,
+ "Token acquisition failed"
+ );
+ let v: Value = serde_json::from_slice(&bytes).context("Invalid credential response")?;
+ bytes.clear();
+ ensure!(
+ v["tenant"].as_str() == Some(tenant) && v["subscription"].as_str() == Some(subscription),
+ "Token target mismatch"
+ );
+ Ok(v)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -340,6 +345,44 @@ mod tests {
net::TcpListener,
sync::{Arc, Mutex},
};
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn cli_token_uses_subscription_only_and_validates_returned_tenant() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+ let program = dir.path().join("az");
+ let script = |tenant: &str| {
+ format!(
+ r#"#!/bin/sh
+case " $* " in *" --tenant "*) exit 2;; esac
+[ "$1 $2 $3 $4 $5 $6" = "account get-access-token --subscription expected-sub --resource expected-resource" ] || exit 3
+printf '%s' '{{"tenant":"{tenant}","subscription":"expected-sub","accessToken":"fixture-secret-canary"}}'
+"#
+ )
+ };
+ std::fs::write(&program, script("expected-tenant")).unwrap();
+ std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o700)).unwrap();
+ assert!(cli_token_response(
+ program.to_str().unwrap(),
+ "expected-sub",
+ "expected-tenant",
+ "expected-resource"
+ )
+ .await
+ .is_ok());
+ std::fs::write(&program, script("wrong-tenant")).unwrap();
+ let error = cli_token_response(
+ program.to_str().unwrap(),
+ "expected-sub",
+ "expected-tenant",
+ "expected-resource",
+ )
+ .await
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("Token target mismatch"));
+ assert!(!error.contains("fixture-secret-canary"));
+ }
fn fixture(
responses: Vec<Option<String>>,
) -> (Azure, Arc<Mutex<Vec<String>>>, std::thread::JoinHandle<()>) {
diff --git a/harness/service-cli/src/deployment_azure_lifecycle.rs b/harness/service-cli/src/deployment_azure_lifecycle.rs
index dc225693..23e8ba6c 100644
--- a/harness/service-cli/src/deployment_azure_lifecycle.rs
+++ b/harness/service-cli/src/deployment_azure_lifecycle.rs
@@ -120,7 +120,9 @@ struct GuardReceipt {
impl GuardReceipt {
fn validate(&self) -> Result<()> {
ensure!(
- chrono::DateTime::parse_from_rfc3339(&self.created_at).is_ok(),
+ chrono::DateTime::parse_from_rfc3339(&self.created_at).is_ok()
+ || chrono::NaiveDateTime::parse_from_str(&self.created_at, "%Y-%m-%dT%H:%M:%S%.f")
+ .is_ok(),
"Invalid controller creation receipt"
);
for value in [&self.principal_id, &self.client_id] {
@@ -1335,6 +1337,21 @@ mod tests {
assert!(c.writes.is_empty());
}
#[test]
+ fn azure_creation_receipt_preserves_timezone_less_fractional_timestamp() {
+ let mut s = state();
+ s.guard = None;
+ let mut body = fixture_job(&s);
+ body["systemData"]["createdAt"] = json!("2026-11-10T18:49:20.2965605");
+ let receipt = guard_body(&s, &body).unwrap();
+ assert_eq!(receipt.created_at, "2026-11-10T18:49:20.2965605");
+ s.guard = Some(receipt);
+ body["systemData"]["createdAt"] = json!("2026-11-10T18:49:20.2965606");
+ assert!(guard_body(&s, &body).is_err());
+ s.guard = None;
+ body["systemData"]["createdAt"] = json!("not-a-timestamp");
+ assert!(guard_body(&s, &body).is_err());
+ }
+ #[test]
fn private_registry_pulls_bind_cleanup_identity_and_reject_credential_drift() {
let mut s = state();
let input = s.plan.azure_infrastructure.as_mut().unwrap();
diff --git a/harness/service-cli/src/deployment_azure_preflight.rs b/harness/service-cli/src/deployment_azure_preflight.rs
index 8082c1e3..612cab81 100644
--- a/harness/service-cli/src/deployment_azure_preflight.rs
+++ b/harness/service-cli/src/deployment_azure_preflight.rs
@@ -40,7 +40,7 @@ impl Az {
return Err("operation_not_allowed");
}
if command == ["rest"]
- && !(args.len() == 4
+ && !((args.len() == 4 || (args.len() == 6 && args[4] == "--query"))
&& args[0] == "--method"
&& args[1] == "get"
&& args[2] == "--url"
@@ -417,47 +417,55 @@ pub async fn preflight(o: &Preflight) -> Result<()> {
if scope_ok {
if let Some(config) = &p.azure_infrastructure {
let size = &config.node_vm_size;
- sku_verified = check(
- &mut checks,
- "selected_node_sku",
- api.read(
- &["vm", "list-skus"],
+ // Use the documented server-side location filter. `az vm list-skus`
+ // can enumerate the entire subscription before filtering locally.
+ let mut url = reqwest::Url::parse(&format!("https://management.azure.com/subscriptions/{subscription}/providers/Microsoft.Compute/skus"))?;
+ url.query_pairs_mut()
+ .append_pair("api-version", "2021-07-01")
+ .append_pair("$filter", &format!("location eq '{location}'"));
+ let selection = if config.management_access.is_some() {
+ format!("(name=='{size}' || name=='Standard_D2as_v7')")
+ } else {
+ format!("name=='{size}'")
+ };
+ let query = format!(
+ "{{skus:value[?resourceType=='virtualMachines' && {selection}],nextLink:nextLink}}"
+ );
+ let catalog = api
+ .read(
+ &["rest"],
&[
- "--location".into(),
- location.clone(),
- "--resource-type".into(),
- "virtualMachines".into(),
- "--size".into(),
- size.clone(),
- "--all".into(),
+ "--method".into(),
+ "get".into(),
+ "--url".into(),
+ url.to_string(),
"--query".into(),
- format!("[?name=='{size}']"),
+ query,
],
)
- .await
- .and_then(|v| selected_sku(v, size, location)),
+ .await;
+ let select = |value: Value, name: &str| -> Observed {
+ if !value["nextLink"].is_null() {
+ return Err("sku_catalog_truncated");
+ }
+ let rows = value["skus"].as_array().ok_or("sku_invalid_response")?;
+ selected_sku(
+ Value::Array(rows.iter().filter(|r| r["name"] == name).cloned().collect()),
+ name,
+ location,
+ )
+ };
+ sku_verified = check(
+ &mut checks,
+ "selected_node_sku",
+ catalog.clone().and_then(|v| select(v, size)),
true,
);
if config.management_access.is_some() {
check(
&mut checks,
"management_sku",
- api.read(
- &["vm", "list-skus"],
- &[
- "--location".into(),
- location.clone(),
- "--resource-type".into(),
- "virtualMachines".into(),
- "--size".into(),
- "Standard_D2as_v7".into(),
- "--all".into(),
- "--query".into(),
- "[?name=='Standard_D2as_v7']".into(),
- ],
- )
- .await
- .and_then(|v| selected_sku(v, "Standard_D2as_v7", location)),
+ catalog.and_then(|v| select(v, "Standard_D2as_v7")),
true,
);
}
diff --git a/harness/service-cli/tests/azure.rs b/harness/service-cli/tests/azure.rs
index b6bd3609..727339e9 100644
--- a/harness/service-cli/tests/azure.rs
+++ b/harness/service-cli/tests/azure.rs
@@ -733,6 +733,7 @@ fn selected_compute_restrictions_architecture_and_consumed_quota_block_preflight
for (scenario, code) in [
("restricted-sku", "sku_location_restricted"),
("arm-sku", "sku_capability_mismatch"),
+ ("sku-pagination", "sku_catalog_truncated"),
("quota-zero", "insufficient_compute_quota"),
("quota-used", "insufficient_compute_quota"),
] {
diff --git a/harness/service-cli/tests/fixtures/azure-bootstrap.py b/harness/service-cli/tests/fixtures/azure-bootstrap.py
index 7470b534..e2115fbc 100644
--- a/harness/service-cli/tests/fixtures/azure-bootstrap.py
+++ b/harness/service-cli/tests/fixtures/azure-bootstrap.py
@@ -91,20 +91,23 @@ if args[:3] == ["role", "assignment", "list"]:
if args[:2] == ["provider", "show"]:
provider = value("--namespace")
emit({"namespace": provider, "registrationState": "NotRegistered" if scenario == "missing-provider" else "Registered"})
-if args[:2] == ["vm", "list-skus"]:
- size = value("--size")
- assert value("--location") == target["location"]
- assert value("--resource-type") == "virtualMachines" and "--all" in args
- assert value("--query") == "[?name=='" + size + "']"
+def sku(size):
family = "StandardDasv7Family" if size in ["Standard_D4as_v7", "Standard_D2as_v7"] else "standardDSv5Family"
- caps = {"CpuArchitectureType": "x64", "vCPUs": "8" if size == "Standard_D8s_v5" else "2" if size == "Standard_D2as_v7" else "4", "MemoryGB": "16", "PremiumIO": "True"}
+ caps = {"CpuArchitectureType":"x64", "vCPUs":"8" if size == "Standard_D8s_v5" else "2" if size == "Standard_D2as_v7" else "4", "MemoryGB":"16", "PremiumIO":"True"}
if scenario == "arm-sku": caps["CpuArchitectureType"] = "Arm64"
- emit([{"name":size,"family":family,"resourceType":"virtualMachines","locations":[target["location"]],"capabilities":[{"name":k,"value":v} for k,v in caps.items()],"restrictions":[{"type":"Location","reasonCode":"NotAvailableForSubscription"}] if scenario == "restricted-sku" else []}])
+ return {"name":size,"family":family,"resourceType":"virtualMachines","locations":[target["location"]],"capabilities":[{"name":k,"value":v} for k,v in caps.items()],"restrictions":[{"type":"Location","reasonCode":"NotAvailableForSubscription"}] if scenario == "restricted-sku" else []}
if args[:2] == ["vm", "list-usage"]:
assert value("--location") == target["location"]
emit([{"name":{"value":name},"currentValue":"4" if scenario == "quota-used" else "0","limit":"0" if scenario == "quota-zero" else "12" if name == "cores" else "10"} for name in ["cores","StandardDasv7Family","standardDSv5Family"]])
if args[0] == "rest":
url = value("--url")
+ if "/Microsoft.Compute/skus?" in url:
+ from urllib.parse import urlparse, parse_qs
+ assert value("--method") == "get"
+ assert parse_qs(urlparse(url).query)["$filter"] == ["location eq '" + target["location"] + "'"]
+ query=value("--query")
+ names=[name for name in ["Standard_D4as_v7","Standard_D2as_v7","Standard_D4s_v5","Standard_D8s_v5"] if "name=='"+name+"'" in query]
+ emit({"skus":[sku(name) for name in names],"nextLink":"https://untrusted.invalid/page" if scenario == "sku-pagination" else None})
assert url in [ident["roleUrl"], ident["assignmentUrl"]], "Unknown URL"
is_role = url == ident["roleUrl"]
payload = json.loads((bundle / ("azure-setup-role.json" if is_role else "azure-setup-assignment.json")).read_text())