| 1 | use std::collections::BTreeMap; |
| 2 | |
| 3 | use base64::Engine as _; |
| 4 | use base64::engine::general_purpose::STANDARD as BASE64; |
| 5 | use ring::signature::KeyPair as _; |
| 6 | use serde_json::{Value, json}; |
| 7 | |
| 8 | use super::catalog_patch::apply_model_patches; |
| 9 | use super::keys::{AUTOMATION_MAX_VALIDITY_SECS, KeyRole, KeyStatus, TrustedKey}; |
| 10 | use super::overlay; |
| 11 | use super::provenance::{CloudFactsState, CloudFactsStatus, FactsOrigin}; |
| 12 | use super::scope::{base_url_allowed, scoped_view}; |
| 13 | use super::types::ModelOp; |
| 14 | use super::verify::{FactsRejection, parse_rfc3339_utc, signing_message, verify_envelope}; |
| 15 | use crate::catalog::{CatalogCompiler, CatalogOffering, CatalogSource}; |
| 16 | |
| 17 | /// Cross-language fixture signed by `web/scripts/facts-publish.mjs` with the |
| 18 | /// TEST-ONLY key (`docs/cloud-facts/fixtures/test-only-signing-key.pem`). |
| 19 | const FIXTURE_V7: &str = include_str!("../../../cloud-facts/fixtures/envelope-stable-v7.json"); |
| 20 | const FIXTURE_FUTURE_V8: &str = |
| 21 | include_str!("../../../cloud-facts/fixtures/envelope-future-only-v8.json"); |
| 22 | const TEST_ONLY_PUB_B64: &str = "8+FLDW4OorUETUVks0hpQAi5Lj4wg3kjKjfYFzLbJ7U="; |
| 23 | const NOW: u64 = 1_790_000_000; // 2026-09-21T...Z |
| 24 | |
| 25 | fn test_only_key(status: KeyStatus) -> TrustedKey { |
| 26 | let raw = BASE64.decode(TEST_ONLY_PUB_B64).expect("pub b64"); |
| 27 | let mut public_key = [0u8; 32]; |
| 28 | public_key.copy_from_slice(&raw); |
| 29 | TrustedKey { |
| 30 | key_id: "cwf-test-only", |
| 31 | public_key, |
| 32 | status, |
| 33 | role: KeyRole::Founder, |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | fn v(s: &str) -> semver::Version { |
| 38 | semver::Version::parse(s).expect("semver") |
| 39 | } |
| 40 | |
| 41 | /// Ephemeral signer for in-Rust variants (tamper, rotation, schema bumps). |
| 42 | struct Signer { |
| 43 | key_id: &'static str, |
| 44 | pair: ring::signature::Ed25519KeyPair, |
| 45 | } |
| 46 | |
| 47 | impl Signer { |
| 48 | fn new(key_id: &'static str) -> Self { |
| 49 | let rng = ring::rand::SystemRandom::new(); |
| 50 | let pkcs8 = ring::signature::Ed25519KeyPair::generate_pkcs8(&rng).expect("pkcs8"); |
| 51 | let pair = ring::signature::Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).expect("pair"); |
| 52 | Self { key_id, pair } |
| 53 | } |
| 54 | |
| 55 | fn trusted(&self, status: KeyStatus) -> TrustedKey { |
| 56 | let mut public_key = [0u8; 32]; |
| 57 | public_key.copy_from_slice(self.pair.public_key().as_ref()); |
| 58 | TrustedKey { |
| 59 | key_id: self.key_id, |
| 60 | public_key, |
| 61 | status, |
| 62 | role: KeyRole::Founder, |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | fn automation(&self) -> TrustedKey { |
| 67 | TrustedKey { |
| 68 | role: KeyRole::Automation, |
| 69 | ..self.trusted(KeyStatus::Active) |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | fn sign(&self, payload: &[u8]) -> String { |
| 74 | BASE64.encode(self.pair.sign(&signing_message(self.key_id, payload))) |
| 75 | } |
| 76 | |
| 77 | fn envelope(&self, payload: &Value) -> Value { |
| 78 | let bytes = serde_json::to_vec(payload).expect("payload json"); |
| 79 | use sha2::Digest as _; |
| 80 | let digest = sha2::Sha256::digest(&bytes) |
| 81 | .iter() |
| 82 | .map(|byte| format!("{byte:02x}")) |
| 83 | .collect::<String>(); |
| 84 | json!({ |
| 85 | "envelope": 1, |
| 86 | "channel": payload["channel"], |
| 87 | "facts_version": payload["facts_version"], |
| 88 | "schema_version": payload["schema_version"], |
| 89 | "key_id": self.key_id, |
| 90 | "alg": "ed25519", |
| 91 | "applies_to": payload["applies_to"], |
| 92 | "published_at": payload["published_at"], |
| 93 | "sha256": digest, |
| 94 | "payload_b64": BASE64.encode(&bytes), |
| 95 | "sig_b64": self.sign(&bytes), |
| 96 | "sigs": [], |
| 97 | }) |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | fn payload(channel: &str, version: u64, applies_to: &str) -> Value { |
| 102 | json!({ |
| 103 | "schema_version": 1, |
| 104 | "channel": channel, |
| 105 | "facts_version": version, |
| 106 | "published_at": "2026-08-30T00:00:00Z", |
| 107 | "applies_to": applies_to, |
| 108 | "models": [], |
| 109 | "provider_defaults": {}, |
| 110 | "release": null, |
| 111 | "announcements": [], |
| 112 | }) |
| 113 | } |
| 114 | |
| 115 | fn verify(bytes: &[u8], keys: &[TrustedKey]) -> Result<super::VerifiedFacts, FactsRejection> { |
| 116 | verify_envelope(bytes, "stable", &v("0.9.11"), None, keys, NOW) |
| 117 | } |
| 118 | |
| 119 | #[test] |
| 120 | fn node_signed_fixture_verifies_under_the_test_only_key() { |
| 121 | let keys = [test_only_key(KeyStatus::Active)]; |
| 122 | let verified = verify(FIXTURE_V7.as_bytes(), &keys).expect("fixture verifies"); |
| 123 | assert_eq!(verified.key_id, "cwf-test-only"); |
| 124 | assert_eq!(verified.facts.facts_version, 7); |
| 125 | assert_eq!(verified.facts.channel, "stable"); |
| 126 | assert_eq!(verified.facts.models.len(), 6); |
| 127 | assert!(!verified.stale); |
| 128 | // sha256 in the envelope matches the recomputed digest of the signed bytes. |
| 129 | let env: Value = serde_json::from_str(FIXTURE_V7).expect("json"); |
| 130 | assert_eq!(env["sha256"].as_str(), Some(verified.sha256.as_str())); |
| 131 | } |
| 132 | |
| 133 | #[test] |
| 134 | fn fixture_is_rejected_with_no_trusted_keys() { |
| 135 | let err = verify(FIXTURE_V7.as_bytes(), &[]).expect_err("no keys"); |
| 136 | assert!(matches!(err, FactsRejection::UnknownKey { .. }), "{err:?}"); |
| 137 | } |
| 138 | |
| 139 | #[test] |
| 140 | fn retired_key_is_rejected_distinctly() { |
| 141 | let keys = [test_only_key(KeyStatus::Retired)]; |
| 142 | let err = verify(FIXTURE_V7.as_bytes(), &keys).expect_err("retired"); |
| 143 | assert_eq!( |
| 144 | err, |
| 145 | FactsRejection::RetiredKey { |
| 146 | key_id: "cwf-test-only".into() |
| 147 | } |
| 148 | ); |
| 149 | } |
| 150 | |
| 151 | #[test] |
| 152 | fn flipping_payload_signature_or_key_id_bytes_breaks_verification() { |
| 153 | let keys = [test_only_key(KeyStatus::Active)]; |
| 154 | let mut env: Value = serde_json::from_str(FIXTURE_V7).expect("json"); |
| 155 | |
| 156 | // Payload tamper (decode → flip → encode keeps the envelope well-formed). |
| 157 | let mut bytes = BASE64.decode(env["payload_b64"].as_str().unwrap()).unwrap(); |
| 158 | bytes[10] ^= 0x01; |
| 159 | let mut tampered = env.clone(); |
| 160 | tampered["payload_b64"] = Value::String(BASE64.encode(&bytes)); |
| 161 | let err = verify(&serde_json::to_vec(&tampered).unwrap(), &keys).unwrap_err(); |
| 162 | assert_eq!(err, FactsRejection::BadSignature); |
| 163 | |
| 164 | // Signature tamper. |
| 165 | let mut sig = BASE64.decode(env["sig_b64"].as_str().unwrap()).unwrap(); |
| 166 | sig[3] ^= 0x80; |
| 167 | let mut tampered = env.clone(); |
| 168 | tampered["sig_b64"] = Value::String(BASE64.encode(&sig)); |
| 169 | let err = verify(&serde_json::to_vec(&tampered).unwrap(), &keys).unwrap_err(); |
| 170 | assert_eq!(err, FactsRejection::BadSignature); |
| 171 | |
| 172 | // Re-labelling under another pinned key id must fail: key_id is signed. |
| 173 | let other = TrustedKey { |
| 174 | key_id: "cwf-other", |
| 175 | ..test_only_key(KeyStatus::Active) |
| 176 | }; |
| 177 | env["key_id"] = Value::String("cwf-other".into()); |
| 178 | let err = verify(&serde_json::to_vec(&env).unwrap(), &[other]).unwrap_err(); |
| 179 | assert_eq!(err, FactsRejection::BadSignature); |
| 180 | } |
| 181 | |
| 182 | #[test] |
| 183 | fn envelope_shape_errors_come_before_crypto() { |
| 184 | let keys = [test_only_key(KeyStatus::Active)]; |
| 185 | let base: Value = serde_json::from_str(FIXTURE_V7).expect("json"); |
| 186 | |
| 187 | let mut e = base.clone(); |
| 188 | e["alg"] = json!("rsa"); |
| 189 | assert!(matches!( |
| 190 | verify(&serde_json::to_vec(&e).unwrap(), &keys).unwrap_err(), |
| 191 | FactsRejection::BadEnvelope(_) |
| 192 | )); |
| 193 | |
| 194 | let mut e = base.clone(); |
| 195 | e["envelope"] = json!(2); |
| 196 | assert!(matches!( |
| 197 | verify(&serde_json::to_vec(&e).unwrap(), &keys).unwrap_err(), |
| 198 | FactsRejection::BadEnvelope(_) |
| 199 | )); |
| 200 | |
| 201 | let big = vec![b' '; super::MAX_ENVELOPE_BYTES + 1]; |
| 202 | assert!(matches!( |
| 203 | verify(&big, &keys).unwrap_err(), |
| 204 | FactsRejection::TooLarge { .. } |
| 205 | )); |
| 206 | |
| 207 | // Oversized payload_b64 is refused before base64 decode / crypto. |
| 208 | let mut e = base.clone(); |
| 209 | e["payload_b64"] = Value::String("A".repeat(super::MAX_PAYLOAD_BYTES * 4 / 3 + 64)); |
| 210 | assert!(matches!( |
| 211 | verify(&serde_json::to_vec(&e).unwrap(), &keys).unwrap_err(), |
| 212 | FactsRejection::TooLarge { .. } |
| 213 | )); |
| 214 | } |
| 215 | |
| 216 | #[test] |
| 217 | fn outer_inner_mismatch_wrong_channel_and_schema_too_new_are_rejected() { |
| 218 | let signer = Signer::new("cwf-unit"); |
| 219 | let keys = [signer.trusted(KeyStatus::Active)]; |
| 220 | |
| 221 | let mut env = signer.envelope(&payload("stable", 3, "*")); |
| 222 | env["facts_version"] = json!(4); |
| 223 | let err = verify(&serde_json::to_vec(&env).unwrap(), &keys).unwrap_err(); |
| 224 | assert!(matches!(err, FactsRejection::Mismatch(_)), "{err:?}"); |
| 225 | |
| 226 | let env = signer.envelope(&payload("beta", 3, "*")); |
| 227 | let err = verify(&serde_json::to_vec(&env).unwrap(), &keys).unwrap_err(); |
| 228 | assert_eq!( |
| 229 | err, |
| 230 | FactsRejection::WrongChannel { |
| 231 | expected: "stable".into(), |
| 232 | got: "beta".into() |
| 233 | } |
| 234 | ); |
| 235 | |
| 236 | let mut p = payload("stable", 3, "*"); |
| 237 | p["schema_version"] = json!(2); |
| 238 | let env = signer.envelope(&p); |
| 239 | let err = verify(&serde_json::to_vec(&env).unwrap(), &keys).unwrap_err(); |
| 240 | assert_eq!(err, FactsRejection::SchemaTooNew { schema_version: 2 }); |
| 241 | } |
| 242 | |
| 243 | #[test] |
| 244 | fn applies_to_scopes_the_whole_payload_by_binary_version() { |
| 245 | let keys = [test_only_key(KeyStatus::Active)]; |
| 246 | let err = verify(FIXTURE_FUTURE_V8.as_bytes(), &keys).unwrap_err(); |
| 247 | assert_eq!( |
| 248 | err, |
| 249 | FactsRejection::NotApplicable { |
| 250 | applies_to: ">=99.0.0".into() |
| 251 | } |
| 252 | ); |
| 253 | // Same envelope is accepted by a binary inside the range. |
| 254 | let ok = verify_envelope( |
| 255 | FIXTURE_FUTURE_V8.as_bytes(), |
| 256 | "stable", |
| 257 | &v("99.1.0"), |
| 258 | None, |
| 259 | &keys, |
| 260 | NOW, |
| 261 | ); |
| 262 | assert!(ok.is_ok(), "{ok:?}"); |
| 263 | |
| 264 | let signer = Signer::new("cwf-unit"); |
| 265 | let keys = [signer.trusted(KeyStatus::Active)]; |
| 266 | let env = signer.envelope(&payload("stable", 1, "not a range")); |
| 267 | let err = verify(&serde_json::to_vec(&env).unwrap(), &keys).unwrap_err(); |
| 268 | assert!(matches!(err, FactsRejection::BadVersionReq(_))); |
| 269 | |
| 270 | // Prerelease binaries follow semver: a plain range does not match them. |
| 271 | let env = signer.envelope(&payload("stable", 1, ">=0.9.0, <1.0.0")); |
| 272 | let bytes = serde_json::to_vec(&env).unwrap(); |
| 273 | assert!(verify_envelope(&bytes, "stable", &v("0.9.12-beta.1"), None, &keys, NOW).is_err()); |
| 274 | assert!(verify_envelope(&bytes, "stable", &v("0.9.12"), None, &keys, NOW).is_ok()); |
| 275 | } |
| 276 | |
| 277 | #[test] |
| 278 | fn rollback_protection_accepts_equal_and_higher_only() { |
| 279 | let signer = Signer::new("cwf-unit"); |
| 280 | let keys = [signer.trusted(KeyStatus::Active)]; |
| 281 | let env = serde_json::to_vec(&signer.envelope(&payload("stable", 5, "*"))).unwrap(); |
| 282 | assert!(verify_envelope(&env, "stable", &v("0.9.11"), Some(4), &keys, NOW).is_ok()); |
| 283 | assert!(verify_envelope(&env, "stable", &v("0.9.11"), Some(5), &keys, NOW).is_ok()); |
| 284 | let err = verify_envelope(&env, "stable", &v("0.9.11"), Some(6), &keys, NOW).unwrap_err(); |
| 285 | assert_eq!( |
| 286 | err, |
| 287 | FactsRejection::Rollback { |
| 288 | got: 5, |
| 289 | highest_seen: 6 |
| 290 | } |
| 291 | ); |
| 292 | } |
| 293 | |
| 294 | #[test] |
| 295 | fn not_after_only_downgrades_to_stale_after_grace() { |
| 296 | let signer = Signer::new("cwf-unit"); |
| 297 | let keys = [signer.trusted(KeyStatus::Active)]; |
| 298 | let mut p = payload("stable", 5, "*"); |
| 299 | p["not_after"] = json!("2026-09-01T00:00:00Z"); |
| 300 | let env = serde_json::to_vec(&signer.envelope(&p)).unwrap(); |
| 301 | let not_after = parse_rfc3339_utc("2026-09-01T00:00:00Z").unwrap(); |
| 302 | let fresh = verify_envelope(&env, "stable", &v("0.9.11"), None, &keys, not_after - 1).unwrap(); |
| 303 | assert!(!fresh.stale); |
| 304 | let in_grace = |
| 305 | verify_envelope(&env, "stable", &v("0.9.11"), None, &keys, not_after + 3600).unwrap(); |
| 306 | assert!(!in_grace.stale); |
| 307 | let stale = verify_envelope( |
| 308 | &env, |
| 309 | "stable", |
| 310 | &v("0.9.11"), |
| 311 | None, |
| 312 | &keys, |
| 313 | not_after + super::verify::NOT_AFTER_GRACE_SECS + 1, |
| 314 | ) |
| 315 | .unwrap(); |
| 316 | assert!(stale.stale, "past grace must be stale, not rejected"); |
| 317 | } |
| 318 | |
| 319 | #[test] |
| 320 | fn rotation_accepts_any_pinned_active_signature() { |
| 321 | let old = Signer::new("cwf-old"); |
| 322 | let new = Signer::new("cwf-new"); |
| 323 | let p = payload("stable", 9, "*"); |
| 324 | let bytes = serde_json::to_vec(&p).unwrap(); |
| 325 | // Primary signature by the old key, extra by the new key. |
| 326 | let mut env = old.envelope(&p); |
| 327 | env["sigs"] = json!([{ "key_id": "cwf-new", "sig_b64": new.sign(&bytes) }]); |
| 328 | let bytes = serde_json::to_vec(&env).unwrap(); |
| 329 | // A client that only pins the new key still accepts it. |
| 330 | let ok = verify(&bytes, &[new.trusted(KeyStatus::Active)]).unwrap(); |
| 331 | assert_eq!(ok.key_id, "cwf-new"); |
| 332 | // A client that retired the old key and pins the new one accepts it too. |
| 333 | let ok = verify( |
| 334 | &bytes, |
| 335 | &[ |
| 336 | old.trusted(KeyStatus::Retired), |
| 337 | new.trusted(KeyStatus::Active), |
| 338 | ], |
| 339 | ) |
| 340 | .unwrap(); |
| 341 | assert_eq!(ok.key_id, "cwf-new"); |
| 342 | // A client pinning only the old key (still active) accepts via primary. |
| 343 | let ok = verify(&bytes, &[old.trusted(KeyStatus::Active)]).unwrap(); |
| 344 | assert_eq!(ok.key_id, "cwf-old"); |
| 345 | } |
| 346 | |
| 347 | #[test] |
| 348 | fn unknown_payload_fields_are_preserved_not_acted_on() { |
| 349 | let signer = Signer::new("cwf-unit"); |
| 350 | let keys = [signer.trusted(KeyStatus::Active)]; |
| 351 | let mut p = payload("stable", 5, "*"); |
| 352 | p["policy"] = json!({ "deny": ["everything"] }); |
| 353 | let env = serde_json::to_vec(&signer.envelope(&p)).unwrap(); |
| 354 | let ok = verify(&env, &keys).unwrap(); |
| 355 | assert!(ok.facts.unknown.contains_key("policy")); |
| 356 | let scoped = scoped_view(&ok, &v("0.9.11"), NOW); |
| 357 | assert!(scoped.models.is_empty() && scoped.provider_defaults.is_empty()); |
| 358 | } |
| 359 | |
| 360 | #[test] |
| 361 | fn scoped_view_filters_items_and_enforces_the_base_url_allowlist() { |
| 362 | let keys = [test_only_key(KeyStatus::Active)]; |
| 363 | let verified = verify(FIXTURE_V7.as_bytes(), &keys).unwrap(); |
| 364 | let scoped = scoped_view(&verified, &v("0.9.11"), NOW); |
| 365 | |
| 366 | let ids: Vec<&str> = scoped.models.iter().map(|m| m.id.as_str()).collect(); |
| 367 | assert!( |
| 368 | !ids.contains(&"future-only"), |
| 369 | "per-item applies_to must filter: {ids:?}" |
| 370 | ); |
| 371 | assert_eq!(scoped.models.len(), 5); |
| 372 | |
| 373 | assert_eq!( |
| 374 | scoped.provider_defaults["deepseek"] |
| 375 | .default_model |
| 376 | .as_deref(), |
| 377 | Some("deepseek-v4-pro") |
| 378 | ); |
| 379 | assert_eq!( |
| 380 | scoped.provider_defaults["deepseek"].base_url.as_deref(), |
| 381 | Some("https://api.deepseek.com/beta") |
| 382 | ); |
| 383 | assert!( |
| 384 | !scoped.provider_defaults.contains_key("openai"), |
| 385 | "off-family base_url must be dropped entirely" |
| 386 | ); |
| 387 | assert!( |
| 388 | !scoped.provider_defaults.contains_key("ollama"), |
| 389 | "local providers accept no cloud base_url" |
| 390 | ); |
| 391 | assert!( |
| 392 | scoped |
| 393 | .dropped |
| 394 | .iter() |
| 395 | .any(|d| d.contains("official HTTPS endpoint")) |
| 396 | ); |
| 397 | |
| 398 | let announcements: Vec<&str> = scoped.announcements.iter().map(|a| a.id.as_str()).collect(); |
| 399 | assert_eq!(announcements, vec!["fixture-live"]); |
| 400 | assert_eq!(scoped.release.as_ref().unwrap().yanked, vec!["0.9.10"]); |
| 401 | } |
| 402 | |
| 403 | #[test] |
| 404 | fn base_url_allowlist_is_https_and_official_host_family_only() { |
| 405 | assert!(base_url_allowed( |
| 406 | "deepseek", |
| 407 | "https://api.deepseek.com/beta" |
| 408 | )); |
| 409 | assert!(!base_url_allowed( |
| 410 | "deepseek", |
| 411 | "https://eu.api.deepseek.com/v1" |
| 412 | )); |
| 413 | assert!(!base_url_allowed( |
| 414 | "deepseek", |
| 415 | "https://api.deepseek.com/other" |
| 416 | )); |
| 417 | assert!(!base_url_allowed( |
| 418 | "deepseek", |
| 419 | "https://evil.example\\api.deepseek.com/v1" |
| 420 | )); |
| 421 | assert!(!base_url_allowed( |
| 422 | "deepseek", |
| 423 | "http://api.deepseek.com/beta" |
| 424 | )); |
| 425 | assert!(!base_url_allowed( |
| 426 | "deepseek", |
| 427 | "https://api.deepseek.com.evil.example/" |
| 428 | )); |
| 429 | assert!(!base_url_allowed( |
| 430 | "deepseek", |
| 431 | "https://user@api.deepseek.com/" |
| 432 | )); |
| 433 | assert!(!base_url_allowed("openai", "https://evil.example/v1")); |
| 434 | assert!(!base_url_allowed("ollama", "https://localhost:11434/v1")); |
| 435 | assert!(!base_url_allowed("no-such-provider", "https://x.example/")); |
| 436 | } |
| 437 | |
| 438 | #[test] |
| 439 | fn catalog_layer_15_patches_sit_between_models_dev_and_provider_live() { |
| 440 | let keys = [test_only_key(KeyStatus::Active)]; |
| 441 | let verified = verify(FIXTURE_V7.as_bytes(), &keys).unwrap(); |
| 442 | let scoped = scoped_view(&verified, &v("0.9.11"), NOW); |
| 443 | |
| 444 | let row = |id: &str, source: CatalogSource| CatalogOffering { |
| 445 | provider: "deepseek".into(), |
| 446 | wire_model_id: id.into(), |
| 447 | endpoint_key: "chat".into(), |
| 448 | limit: Some(crate::models_dev::ModelsDevLimit { |
| 449 | context: Some(1000), |
| 450 | input: None, |
| 451 | output: Some(10), |
| 452 | }), |
| 453 | reasoning: Some(false), |
| 454 | source, |
| 455 | ..CatalogOffering::default() |
| 456 | }; |
| 457 | let snapshot = CatalogCompiler::new() |
| 458 | .with_bundled(vec![ |
| 459 | row("deepseek-v4-pro", CatalogSource::Bundled), |
| 460 | row("deepseek-chat", CatalogSource::Bundled), |
| 461 | row("deepseek-reasoner", CatalogSource::Bundled), |
| 462 | ]) |
| 463 | .with_cloud_facts(&scoped, NOW) |
| 464 | .with_provider_live(vec![row( |
| 465 | "deepseek-reasoner", |
| 466 | CatalogSource::Live { |
| 467 | base_url_fingerprint: "fp".into(), |
| 468 | fetched_at: NOW, |
| 469 | }, |
| 470 | )]) |
| 471 | .compile(); |
| 472 | |
| 473 | let find = |id: &str| { |
| 474 | snapshot |
| 475 | .offerings |
| 476 | .iter() |
| 477 | .find(|o| o.wire_model_id == id) |
| 478 | .cloned() |
| 479 | }; |
| 480 | // Upsert patched only the fields it set; untouched fields survive. |
| 481 | let pro = find("deepseek-v4-pro").expect("patched row"); |
| 482 | assert_eq!(pro.limit.as_ref().unwrap().context, Some(262_144)); |
| 483 | assert_eq!(pro.limit.as_ref().unwrap().output, Some(32_768)); |
| 484 | assert_eq!(pro.reasoning, Some(false), "unpatched field must survive"); |
| 485 | assert!(matches!( |
| 486 | pro.source, |
| 487 | CatalogSource::CloudFacts { |
| 488 | facts_version: 7, |
| 489 | .. |
| 490 | } |
| 491 | )); |
| 492 | // New row materialized because it carried a context window. |
| 493 | let new_row = find("fixture-new-model").expect("new row"); |
| 494 | assert_eq!(new_row.reasoning, Some(true)); |
| 495 | // Patch without context for a missing row is skipped. |
| 496 | assert!(find("fixture-needs-context").is_none()); |
| 497 | // Deprecate annotates, never removes. |
| 498 | let chat = find("deepseek-chat").expect("deprecated row stays"); |
| 499 | assert!( |
| 500 | chat.reasoning_options |
| 501 | .iter() |
| 502 | .any(|v| v["cloud_facts"]["op"] == "deprecated") |
| 503 | ); |
| 504 | // Hide removed the bundled row, but the provider-live row above layer 15 |
| 505 | // re-adds it: cloud can never hide a gateway's own live row. |
| 506 | let reasoner = find("deepseek-reasoner").expect("provider-live row wins"); |
| 507 | assert!(matches!(reasoner.source, CatalogSource::Live { .. })); |
| 508 | |
| 509 | // Direct map application: hide on a higher-layer row is a receipt, not a removal. |
| 510 | let mut rows: BTreeMap<(String, String), CatalogOffering> = BTreeMap::new(); |
| 511 | rows.insert( |
| 512 | ("deepseek".into(), "deepseek-reasoner".into()), |
| 513 | row("deepseek-reasoner", CatalogSource::UserOverride), |
| 514 | ); |
| 515 | let skipped = apply_model_patches(&mut rows, &scoped, NOW); |
| 516 | assert!(rows.contains_key(&("deepseek".into(), "deepseek-reasoner".into()))); |
| 517 | assert!(skipped.iter().any(|s| s.id == "deepseek-reasoner")); |
| 518 | assert_eq!(scoped.models[0].op, ModelOp::Upsert); |
| 519 | } |
| 520 | |
| 521 | /// The overlay is process-global: a test that configures it while another is |
| 522 | /// mid-sequence invalidates that test's ticket. Every overlay test holds this. |
| 523 | static OVERLAY_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); |
| 524 | |
| 525 | pub(crate) fn overlay_test_guard() -> std::sync::MutexGuard<'static, ()> { |
| 526 | OVERLAY_TESTS |
| 527 | .lock() |
| 528 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 529 | } |
| 530 | |
| 531 | #[test] |
| 532 | fn overlay_supplies_provider_defaults_only_from_the_scoped_view() { |
| 533 | let _overlay = overlay_test_guard(); |
| 534 | let keys = [test_only_key(KeyStatus::Active)]; |
| 535 | let verified = verify(FIXTURE_V7.as_bytes(), &keys).unwrap(); |
| 536 | let scoped = scoped_view(&verified, &v("0.9.11"), NOW); |
| 537 | |
| 538 | overlay::clear(); |
| 539 | assert!(overlay::cloud_default_model("deepseek").is_none()); |
| 540 | let ticket = overlay::configure(true, "config-default-test").unwrap(); |
| 541 | assert!(overlay::publish( |
| 542 | &ticket, |
| 543 | Some(scoped), |
| 544 | CloudFactsStatus::default() |
| 545 | )); |
| 546 | let (model, source) = overlay::cloud_default_model("deepseek").expect("cloud default"); |
| 547 | assert_eq!(model, "deepseek-v4-pro"); |
| 548 | assert_eq!( |
| 549 | source, |
| 550 | overlay::DefaultSource::CloudFacts { facts_version: 7 } |
| 551 | ); |
| 552 | assert!(overlay::cloud_default_base_url("openai").is_none()); |
| 553 | overlay::clear(); |
| 554 | assert!(overlay::cloud_default_model("deepseek").is_none()); |
| 555 | } |
| 556 | |
| 557 | #[test] |
| 558 | fn status_labels_cover_every_state() { |
| 559 | let now = NOW; |
| 560 | let label = |state: CloudFactsState| { |
| 561 | CloudFactsStatus { |
| 562 | state, |
| 563 | ..CloudFactsStatus::default() |
| 564 | } |
| 565 | .label(now) |
| 566 | }; |
| 567 | assert_eq!(label(CloudFactsState::Off), "off (bundled)"); |
| 568 | assert!(label(CloudFactsState::Inert).contains("inert")); |
| 569 | assert!(label(CloudFactsState::BundledOnly).contains("bundled")); |
| 570 | let verified = label(CloudFactsState::Verified { |
| 571 | channel: "stable".into(), |
| 572 | facts_version: 42, |
| 573 | key_id: "cwf-2026-08".into(), |
| 574 | fetched_at: now - 12 * 60, |
| 575 | origin: FactsOrigin::Network, |
| 576 | stale: false, |
| 577 | patches: 3, |
| 578 | defaults: 1, |
| 579 | announcements: 0, |
| 580 | }); |
| 581 | assert_eq!( |
| 582 | verified, |
| 583 | "stable v42 · verified cwf-2026-08 · fetched 12m ago (network) · 3 patches, 1 default, 0 notices" |
| 584 | ); |
| 585 | assert!( |
| 586 | label(CloudFactsState::Rejected { |
| 587 | reason: "bad signature".into(), |
| 588 | at: now |
| 589 | }) |
| 590 | .contains("bundled in use") |
| 591 | ); |
| 592 | assert!( |
| 593 | label(CloudFactsState::NotApplicable { |
| 594 | applies_to: ">=1.0".into() |
| 595 | }) |
| 596 | .contains(">=1.0") |
| 597 | ); |
| 598 | assert!( |
| 599 | label(CloudFactsState::Failed { |
| 600 | last_error: "HTTP 503".into(), |
| 601 | at: now - 3 * 86_400, |
| 602 | keeping: Some(42) |
| 603 | }) |
| 604 | .contains("keeping v42") |
| 605 | ); |
| 606 | } |
| 607 | |
| 608 | #[test] |
| 609 | fn rfc3339_utc_parser_matches_known_epochs() { |
| 610 | assert_eq!(parse_rfc3339_utc("1970-01-01T00:00:00Z"), Some(0)); |
| 611 | assert_eq!( |
| 612 | parse_rfc3339_utc("2026-08-30T00:00:00Z"), |
| 613 | Some(1_788_048_000) |
| 614 | ); |
| 615 | assert_eq!( |
| 616 | parse_rfc3339_utc("2026-08-30T00:00:00.123Z"), |
| 617 | Some(1_788_048_000) |
| 618 | ); |
| 619 | assert_eq!(parse_rfc3339_utc("2026-08-30T00:00:00+02:00"), None); |
| 620 | assert_eq!(parse_rfc3339_utc("garbage"), None); |
| 621 | } |
| 622 | |
| 623 | #[test] |
| 624 | fn pinned_keys_are_well_formed() { |
| 625 | for key in super::TRUSTED_KEYS { |
| 626 | assert!(key.key_id.starts_with("cwf-")); |
| 627 | assert_ne!(key.public_key, [0u8; 32]); |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | #[test] |
| 632 | fn signed_envelope_rejects_metadata_digest_future_and_malformed_times() { |
| 633 | let signer = Signer::new("cwf-contract"); |
| 634 | let keys = [signer.trusted(KeyStatus::Active)]; |
| 635 | let valid = signer.envelope(&payload("stable", 5, "*")); |
| 636 | for field in ["schema_version", "applies_to", "published_at", "sha256"] { |
| 637 | let mut bad = valid.clone(); |
| 638 | bad.as_object_mut().unwrap().remove(field); |
| 639 | assert!( |
| 640 | verify(&serde_json::to_vec(&bad).unwrap(), &keys).is_err(), |
| 641 | "{field}" |
| 642 | ); |
| 643 | } |
| 644 | for (field, value) in [ |
| 645 | ("published_at", json!("2026-08-31T00:00:00Z")), |
| 646 | ("sha256", json!("0".repeat(64))), |
| 647 | ] { |
| 648 | let mut bad = valid.clone(); |
| 649 | bad[field] = value; |
| 650 | assert!(matches!( |
| 651 | verify(&serde_json::to_vec(&bad).unwrap(), &keys), |
| 652 | Err(FactsRejection::Mismatch(_)) |
| 653 | )); |
| 654 | } |
| 655 | for (field, value) in [ |
| 656 | ("schema_version", json!(0)), |
| 657 | ("facts_version", json!(0)), |
| 658 | ("applies_to", json!("")), |
| 659 | ("published_at", json!("2099-01-01T00:00:00Z")), |
| 660 | ("not_after", json!("2026-02-30T00:00:00Z")), |
| 661 | ("not_after", json!("2026-01-01T00:00:00Z")), |
| 662 | ("not_after", json!("2026-08-30T00:00:00Z")), |
| 663 | ] { |
| 664 | let mut bad = payload("stable", 5, "*"); |
| 665 | bad[field] = value; |
| 666 | assert!( |
| 667 | verify(&serde_json::to_vec(&signer.envelope(&bad)).unwrap(), &keys).is_err(), |
| 668 | "{field}" |
| 669 | ); |
| 670 | } |
| 671 | let mut excessive = valid.clone(); |
| 672 | excessive["sigs"] = json!(vec![ |
| 673 | json!({"key_id":"cwf-contract", "sig_b64":valid["sig_b64"]}); |
| 674 | 8 |
| 675 | ]); |
| 676 | assert!(matches!( |
| 677 | verify(&serde_json::to_vec(&excessive).unwrap(), &keys), |
| 678 | Err(FactsRejection::BadEnvelope(_)) |
| 679 | )); |
| 680 | for invalid in [ |
| 681 | "2026-02-30T00:00:00Z", |
| 682 | "2026-13-01T00:00:00Z", |
| 683 | "2026-01-01T25:00:00Z", |
| 684 | ] { |
| 685 | assert!(parse_rfc3339_utc(invalid).is_none()); |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | #[test] |
| 690 | fn capability_patch_preserves_cost_authority_and_price_block_is_atomic() { |
| 691 | use super::scope::ScopedFacts; |
| 692 | use super::types::{ModelFact, PricingFact}; |
| 693 | use crate::models_dev::ModelsDevCost; |
| 694 | let key = ("openai".to_string(), "fixture".to_string()); |
| 695 | let row = CatalogOffering { |
| 696 | provider: key.0.clone(), |
| 697 | wire_model_id: key.1.clone(), |
| 698 | source: CatalogSource::ModelsDevLive { fetched_at: 123 }, |
| 699 | cost: Some(ModelsDevCost { |
| 700 | input: Some(1.0), |
| 701 | output: Some(2.0), |
| 702 | cache_read: Some(0.1), |
| 703 | cache_write: Some(3.0), |
| 704 | ..Default::default() |
| 705 | }), |
| 706 | ..Default::default() |
| 707 | }; |
| 708 | let mut rows = BTreeMap::from([(key.clone(), row)]); |
| 709 | let mut facts = ScopedFacts { |
| 710 | facts_version: 7, |
| 711 | key_id: "cwf-test-only".into(), |
| 712 | models: vec![ModelFact { |
| 713 | provider: key.0.clone(), |
| 714 | id: key.1.clone(), |
| 715 | context_window: Some(9000), |
| 716 | ..Default::default() |
| 717 | }], |
| 718 | ..Default::default() |
| 719 | }; |
| 720 | apply_model_patches(&mut rows, &facts, NOW); |
| 721 | assert!(matches!( |
| 722 | rows[&key].source, |
| 723 | CatalogSource::CloudFacts { .. } |
| 724 | )); |
| 725 | assert_eq!( |
| 726 | rows[&key].pricing_source(), |
| 727 | &CatalogSource::ModelsDevLive { fetched_at: 123 } |
| 728 | ); |
| 729 | assert_eq!(rows[&key].cost.as_ref().unwrap().cache_write, Some(3.0)); |
| 730 | facts.models[0].pricing = Some(PricingFact { |
| 731 | input_per_m: Some(4.0), |
| 732 | ..Default::default() |
| 733 | }); |
| 734 | apply_model_patches(&mut rows, &facts, NOW); |
| 735 | assert!(matches!( |
| 736 | rows[&key].pricing_source(), |
| 737 | CatalogSource::CloudFacts { .. } |
| 738 | )); |
| 739 | assert_eq!( |
| 740 | rows[&key].cost, |
| 741 | Some(ModelsDevCost { |
| 742 | input: Some(4.0), |
| 743 | output: None, |
| 744 | cache_read: None, |
| 745 | cache_write: None, |
| 746 | ..Default::default() |
| 747 | }) |
| 748 | ); |
| 749 | facts.valid_until = Some(0); |
| 750 | facts.models[0].pricing.as_mut().unwrap().input_per_m = Some(999.0); |
| 751 | apply_model_patches(&mut rows, &facts, NOW); |
| 752 | assert_eq!(rows[&key].cost.as_ref().unwrap().input, Some(4.0)); |
| 753 | } |
| 754 | |
| 755 | #[test] |
| 756 | fn overlay_tickets_disable_expiry_and_source_changes_keep_channel_rollback_floors() { |
| 757 | let _overlay = overlay_test_guard(); |
| 758 | use super::scope::ScopedFacts; |
| 759 | let facts = |channel: &str, version| ScopedFacts { |
| 760 | channel: channel.into(), |
| 761 | facts_version: version, |
| 762 | ..Default::default() |
| 763 | }; |
| 764 | let first = overlay::configure(true, "gate-test-first").unwrap(); |
| 765 | assert!(overlay::publish( |
| 766 | &first, |
| 767 | Some(facts("gate-stable", 7)), |
| 768 | CloudFactsStatus::default() |
| 769 | )); |
| 770 | let generation = overlay::snapshot().generation; |
| 771 | let second = overlay::configure(true, "gate-test-second").unwrap(); |
| 772 | assert!(overlay::snapshot().generation > generation); |
| 773 | let mut wrote = false; |
| 774 | assert!(!overlay::publish_with( |
| 775 | &first, |
| 776 | Some(facts("gate-stable", 8)), |
| 777 | CloudFactsStatus::default(), |
| 778 | || wrote = true |
| 779 | )); |
| 780 | assert!(!wrote); |
| 781 | assert!(!overlay::publish( |
| 782 | &second, |
| 783 | Some(facts("gate-stable", 6)), |
| 784 | CloudFactsStatus::default() |
| 785 | )); |
| 786 | assert!(overlay::publish( |
| 787 | &second, |
| 788 | Some(facts("gate-beta", 2)), |
| 789 | CloudFactsStatus::default() |
| 790 | )); |
| 791 | overlay::clear(); |
| 792 | assert!(overlay::overlay().is_none()); |
| 793 | assert!(!overlay::is_current(&second)); |
| 794 | let third = overlay::configure(true, "gate-test-first").unwrap(); |
| 795 | assert_eq!(overlay::highest_seen("gate-stable"), Some(7)); |
| 796 | assert_eq!(overlay::highest_seen("gate-beta"), Some(2)); |
| 797 | assert!(!overlay::publish( |
| 798 | &third, |
| 799 | Some(facts("gate-stable", 6)), |
| 800 | CloudFactsStatus::default() |
| 801 | )); |
| 802 | let mut expired = facts("gate-stable", 8); |
| 803 | expired.valid_until = Some(0); |
| 804 | assert!(overlay::publish( |
| 805 | &third, |
| 806 | Some(expired), |
| 807 | CloudFactsStatus::default() |
| 808 | )); |
| 809 | let generation = overlay::snapshot().generation; |
| 810 | assert!(overlay::overlay().is_none()); |
| 811 | assert_eq!(overlay::snapshot().generation, generation); |
| 812 | assert_eq!(overlay::highest_seen("gate-stable"), Some(8)); |
| 813 | overlay::clear(); |
| 814 | } |
| 815 | |
| 816 | #[test] |
| 817 | fn cloud_endpoint_contract_rejects_dynamic_origins_and_prefix_expansion() { |
| 818 | assert!(base_url_allowed( |
| 819 | "codewhale", |
| 820 | crate::DEFAULT_CODEWHALE_BASE_URL |
| 821 | )); |
| 822 | assert!(!base_url_allowed("codewhale", "https://private.example/v1")); |
| 823 | assert!(base_url_allowed( |
| 824 | "moonshot", |
| 825 | "https://api.kimi.com/coding/v1" |
| 826 | )); |
| 827 | for url in [ |
| 828 | "https://api.kimi.com/coding/private", |
| 829 | "https://api.kimi.com/coding/v1?key=fixture", |
| 830 | "https://api.kimi.com/coding/v1#fixture", |
| 831 | "https://fixture@api.kimi.com/coding/v1", |
| 832 | "https://api.kimi.com/coding/v1\\private", |
| 833 | ] { |
| 834 | assert!(!base_url_allowed("moonshot", url), "{url}"); |
| 835 | } |
| 836 | assert!(!base_url_allowed( |
| 837 | "xiaomimimo", |
| 838 | "https://api.xiaomimimo.com/v1/private" |
| 839 | )); |
| 840 | } |
| 841 | |
| 842 | #[test] |
| 843 | fn legacy_live_and_operator_layers_cannot_be_overwritten_by_cloud_patches() { |
| 844 | use super::{ModelFact, PricingFact, ScopedFacts}; |
| 845 | let key = ("openai".to_string(), "layer-fixture".to_string()); |
| 846 | let facts = ScopedFacts { |
| 847 | facts_version: 1, |
| 848 | models: vec![ModelFact { |
| 849 | provider: key.0.clone(), |
| 850 | id: key.1.clone(), |
| 851 | context_window: Some(9000), |
| 852 | pricing: Some(PricingFact { |
| 853 | input_per_m: Some(999.0), |
| 854 | ..Default::default() |
| 855 | }), |
| 856 | ..Default::default() |
| 857 | }], |
| 858 | ..Default::default() |
| 859 | }; |
| 860 | for source in [ |
| 861 | CatalogSource::Live { |
| 862 | base_url_fingerprint: "fixture".into(), |
| 863 | fetched_at: NOW, |
| 864 | }, |
| 865 | CatalogSource::ConfigOverride, |
| 866 | CatalogSource::UserOverride, |
| 867 | ] { |
| 868 | let row = CatalogOffering { |
| 869 | provider: key.0.clone(), |
| 870 | wire_model_id: key.1.clone(), |
| 871 | source, |
| 872 | ..Default::default() |
| 873 | }; |
| 874 | let mut rows = BTreeMap::from([(key.clone(), row.clone())]); |
| 875 | assert_eq!(apply_model_patches(&mut rows, &facts, NOW).len(), 1); |
| 876 | assert_eq!(rows[&key], row); |
| 877 | } |
| 878 | let row = CatalogOffering { |
| 879 | provider: key.0.clone(), |
| 880 | wire_model_id: key.1.clone(), |
| 881 | source: CatalogSource::Live { |
| 882 | base_url_fingerprint: "fixture".into(), |
| 883 | fetched_at: NOW, |
| 884 | }, |
| 885 | ..Default::default() |
| 886 | }; |
| 887 | let snapshot = CatalogCompiler::new() |
| 888 | .with_live(vec![row.clone()]) |
| 889 | .with_cloud_facts(&facts, NOW) |
| 890 | .compile(); |
| 891 | assert_eq!(snapshot.offerings, vec![row]); |
| 892 | } |
| 893 | |
| 894 | /// The complement of the layer test above: a correction must actually *reach* a |
| 895 | /// live Models.dev row, because that layer describes most of the models a user |
| 896 | /// sees. Both sides go through [`crate::catalog::CatalogCompiler::with_live`], |
| 897 | /// which routes a row by its own source, and the enriched rows come from the |
| 898 | /// real producer — so this fails if the refresh ever goes back to stamping |
| 899 | /// `Live`, which put every enriched row above the layer meant to correct it and |
| 900 | /// left a published rate change reaching nobody without a reinstall. |
| 901 | #[test] |
| 902 | fn signed_facts_correct_a_live_models_dev_row_but_never_the_provider_roster() { |
| 903 | use super::{ModelFact, PricingFact, ScopedFacts}; |
| 904 | use crate::catalog::live_offerings_from_models_dev; |
| 905 | use crate::models_dev::ModelsDevCatalog; |
| 906 | |
| 907 | let raw = r#"{ |
| 908 | "models": {}, |
| 909 | "providers": { |
| 910 | "deepseek": { |
| 911 | "id": "deepseek", |
| 912 | "models": { |
| 913 | "deepseek-chat": { |
| 914 | "id": "deepseek-chat", |
| 915 | "modalities": { "input": ["text"], "output": ["text"] }, |
| 916 | "limit": { "context": 65536, "output": 4096 }, |
| 917 | "cost": { "input": 2.0, "output": 8.0 } |
| 918 | } |
| 919 | } |
| 920 | } |
| 921 | } |
| 922 | }"#; |
| 923 | let catalog = ModelsDevCatalog::parse_json(raw).expect("fixture parses"); |
| 924 | let enriched = live_offerings_from_models_dev(&catalog, NOW); |
| 925 | assert_eq!(enriched.len(), 1, "one text-chat row"); |
| 926 | |
| 927 | let facts = ScopedFacts { |
| 928 | facts_version: 3, |
| 929 | key_id: "cwf-test-only".into(), |
| 930 | models: vec![ModelFact { |
| 931 | provider: "deepseek".into(), |
| 932 | id: "deepseek-chat".into(), |
| 933 | context_window: Some(131_072), |
| 934 | pricing: Some(PricingFact { |
| 935 | input_per_m: Some(0.5), |
| 936 | output_per_m: Some(1.5), |
| 937 | ..Default::default() |
| 938 | }), |
| 939 | ..Default::default() |
| 940 | }], |
| 941 | ..Default::default() |
| 942 | }; |
| 943 | |
| 944 | let corrected = CatalogCompiler::new() |
| 945 | .with_live(enriched.clone()) |
| 946 | .with_cloud_facts(&facts, NOW) |
| 947 | .compile(); |
| 948 | let row = corrected |
| 949 | .offerings |
| 950 | .iter() |
| 951 | .find(|row| row.wire_model_id == "deepseek-chat") |
| 952 | .expect("the row survives its own correction"); |
| 953 | let limit = row.limit.as_ref().expect("limits are kept"); |
| 954 | assert_eq!( |
| 955 | limit.context, |
| 956 | Some(131_072), |
| 957 | "the stale window is corrected" |
| 958 | ); |
| 959 | assert_eq!( |
| 960 | limit.output, |
| 961 | Some(4_096), |
| 962 | "and only what the payload states is replaced" |
| 963 | ); |
| 964 | assert_eq!(row.cost.as_ref().and_then(|cost| cost.input), Some(0.5)); |
| 965 | assert_eq!(row.cost.as_ref().and_then(|cost| cost.output), Some(1.5)); |
| 966 | assert!(matches!( |
| 967 | row.pricing_source(), |
| 968 | CatalogSource::CloudFacts { .. } |
| 969 | )); |
| 970 | |
| 971 | // The same payload, same wire, once the provider's own roster owns the id: |
| 972 | // an authenticated endpoint outranks a signed correction, field for field. |
| 973 | let roster = CatalogOffering { |
| 974 | source: CatalogSource::Live { |
| 975 | base_url_fingerprint: "deepseek-endpoint".into(), |
| 976 | fetched_at: NOW, |
| 977 | }, |
| 978 | ..enriched[0].clone() |
| 979 | }; |
| 980 | let untouched = CatalogCompiler::new() |
| 981 | .with_live(vec![roster.clone()]) |
| 982 | .with_cloud_facts(&facts, NOW) |
| 983 | .compile(); |
| 984 | assert_eq!(untouched.offerings, vec![roster]); |
| 985 | } |
| 986 | |
| 987 | #[test] |
| 988 | fn unsigned_metadata_cannot_amplify_rejection_messages() { |
| 989 | let signer = Signer::new("cwf-bounds"); |
| 990 | let keys = [signer.trusted(KeyStatus::Active)]; |
| 991 | for field in ["alg", "channel", "applies_to", "published_at", "sha256"] { |
| 992 | let mut envelope = signer.envelope(&payload("stable", 1, "*")); |
| 993 | envelope[field] = json!("x".repeat(16_384)); |
| 994 | let error = verify(&serde_json::to_vec(&envelope).unwrap(), &keys).unwrap_err(); |
| 995 | assert!(error.to_string().len() < 256, "{field}"); |
| 996 | } |
| 997 | } |
| 998 | |
| 999 | /// The unlisted assertion is the only thing that may override a provider |
| 1000 | /// roster's own omission, so the scoped view is where it is bounded: an |
| 1001 | /// `upsert` in a payload that expires. The rest of the patch survives either |
| 1002 | /// way — only the assertion is withdrawn, with a receipt. |
| 1003 | #[test] |
| 1004 | fn unlisted_assertion_needs_an_upsert_in_an_expiring_payload() { |
| 1005 | let signer = Signer::new("cwf-unlisted"); |
| 1006 | let keys = [signer.trusted(KeyStatus::Active)]; |
| 1007 | let models = json!([ |
| 1008 | {"provider": "deepseek", "id": "preview-a", "allow_unlisted": true}, |
| 1009 | {"provider": "deepseek", "id": "preview-b", "op": "hide", "allow_unlisted": true}, |
| 1010 | {"provider": "deepseek", "id": "listed-c", "context_window": 1000}, |
| 1011 | ]); |
| 1012 | |
| 1013 | let mut bounded = payload("stable", 11, "*"); |
| 1014 | bounded["models"] = models.clone(); |
| 1015 | bounded["not_after"] = json!("2026-12-31T00:00:00Z"); |
| 1016 | let verified = verify( |
| 1017 | &serde_json::to_vec(&signer.envelope(&bounded)).unwrap(), |
| 1018 | &keys, |
| 1019 | ) |
| 1020 | .unwrap(); |
| 1021 | let scoped = scoped_view(&verified, &v("0.9.11"), NOW); |
| 1022 | assert!(scoped.valid_until.is_some()); |
| 1023 | assert_eq!(scoped.models.len(), 3, "patches themselves are not dropped"); |
| 1024 | assert!(super::catalog_patch::is_unlisted_attested( |
| 1025 | &scoped, |
| 1026 | "deepseek", |
| 1027 | "preview-a" |
| 1028 | )); |
| 1029 | assert!( |
| 1030 | !super::catalog_patch::is_unlisted_attested(&scoped, "deepseek", "preview-b"), |
| 1031 | "a hide cannot carry an existence assertion" |
| 1032 | ); |
| 1033 | assert!(!super::catalog_patch::is_unlisted_attested( |
| 1034 | &scoped, "deepseek", "listed-c" |
| 1035 | )); |
| 1036 | assert!( |
| 1037 | !super::catalog_patch::is_unlisted_attested(&scoped, "deepseek", "preview-a-x"), |
| 1038 | "the assertion names one exact id, never a prefix" |
| 1039 | ); |
| 1040 | |
| 1041 | let mut unbounded = payload("stable", 12, "*"); |
| 1042 | unbounded["models"] = models; |
| 1043 | let verified = verify( |
| 1044 | &serde_json::to_vec(&signer.envelope(&unbounded)).unwrap(), |
| 1045 | &keys, |
| 1046 | ) |
| 1047 | .unwrap(); |
| 1048 | let scoped = scoped_view(&verified, &v("0.9.11"), NOW); |
| 1049 | assert!(scoped.valid_until.is_none()); |
| 1050 | assert_eq!(scoped.models.len(), 3); |
| 1051 | assert!( |
| 1052 | !super::catalog_patch::is_unlisted_attested(&scoped, "deepseek", "preview-a"), |
| 1053 | "an assertion that cannot expire is not honored" |
| 1054 | ); |
| 1055 | assert_eq!( |
| 1056 | scoped |
| 1057 | .dropped |
| 1058 | .iter() |
| 1059 | .filter(|receipt| receipt.contains("allow_unlisted")) |
| 1060 | .count(), |
| 1061 | 2 |
| 1062 | ); |
| 1063 | } |
| 1064 | |
| 1065 | /// An attested id needs no invented context window to be listed, and gets no |
| 1066 | /// invented anything else either. |
| 1067 | #[test] |
| 1068 | fn attested_id_only_upsert_creates_a_row_with_everything_unknown() { |
| 1069 | use super::{ModelFact, ScopedFacts}; |
| 1070 | let bare = |allow_unlisted| ModelFact { |
| 1071 | provider: "deepseek".into(), |
| 1072 | id: "preview-a".into(), |
| 1073 | allow_unlisted, |
| 1074 | ..Default::default() |
| 1075 | }; |
| 1076 | let key = ("deepseek".to_string(), "preview-a".to_string()); |
| 1077 | |
| 1078 | let mut rows = BTreeMap::new(); |
| 1079 | let skipped = apply_model_patches( |
| 1080 | &mut rows, |
| 1081 | &ScopedFacts { |
| 1082 | models: vec![bare(false)], |
| 1083 | ..Default::default() |
| 1084 | }, |
| 1085 | NOW, |
| 1086 | ); |
| 1087 | assert!(rows.is_empty(), "an id alone still creates nothing"); |
| 1088 | assert_eq!(skipped.len(), 1); |
| 1089 | assert!( |
| 1090 | skipped[0] |
| 1091 | .reason |
| 1092 | .contains("context_window or allow_unlisted") |
| 1093 | ); |
| 1094 | |
| 1095 | let mut rows = BTreeMap::new(); |
| 1096 | assert!( |
| 1097 | apply_model_patches( |
| 1098 | &mut rows, |
| 1099 | &ScopedFacts { |
| 1100 | facts_version: 3, |
| 1101 | key_id: "cwf-unlisted".into(), |
| 1102 | valid_until: Some(crate::catalog::now_unix() + 3600), |
| 1103 | models: vec![bare(true)], |
| 1104 | ..Default::default() |
| 1105 | }, |
| 1106 | NOW, |
| 1107 | ) |
| 1108 | .is_empty() |
| 1109 | ); |
| 1110 | let row = &rows[&key]; |
| 1111 | assert_eq!(row.wire_model_id, "preview-a"); |
| 1112 | assert_eq!(row.limit, None, "no limits were stated, so none are known"); |
| 1113 | assert_eq!(row.cost, None); |
| 1114 | assert_eq!(row.cost_source, None); |
| 1115 | assert_eq!(row.reasoning, None); |
| 1116 | assert_eq!(row.tool_call, None); |
| 1117 | assert_eq!(row.modalities, None); |
| 1118 | assert_eq!(row.attachment, None); |
| 1119 | assert!(matches!(row.source, CatalogSource::CloudFacts { .. })); |
| 1120 | } |
| 1121 | |
| 1122 | /// A roster that answers with ids alone has said nothing about limits — not |
| 1123 | /// that they are unknown. Completion fills only that silence. |
| 1124 | #[test] |
| 1125 | fn provider_live_rows_are_completed_only_where_the_provider_is_silent() { |
| 1126 | use super::catalog_patch::complete_provider_live_row; |
| 1127 | use super::{ModelFact, PricingFact, ScopedFacts}; |
| 1128 | use crate::models_dev::{ModelsDevCost, ModelsDevLimit}; |
| 1129 | let live = CatalogSource::Live { |
| 1130 | base_url_fingerprint: "fixture".into(), |
| 1131 | fetched_at: NOW, |
| 1132 | }; |
| 1133 | let facts = ScopedFacts { |
| 1134 | facts_version: 4, |
| 1135 | key_id: "cwf-unlisted".into(), |
| 1136 | models: vec![ModelFact { |
| 1137 | provider: "deepseek".into(), |
| 1138 | id: "roster-model".into(), |
| 1139 | context_window: Some(131_072), |
| 1140 | max_output: Some(8_192), |
| 1141 | reasoning: Some(true), |
| 1142 | pricing: Some(PricingFact { |
| 1143 | input_per_m: Some(1.0), |
| 1144 | output_per_m: Some(2.0), |
| 1145 | ..Default::default() |
| 1146 | }), |
| 1147 | ..Default::default() |
| 1148 | }], |
| 1149 | ..Default::default() |
| 1150 | }; |
| 1151 | let id_only = CatalogOffering { |
| 1152 | provider: "deepseek".into(), |
| 1153 | wire_model_id: "roster-model".into(), |
| 1154 | source: live.clone(), |
| 1155 | ..Default::default() |
| 1156 | }; |
| 1157 | |
| 1158 | let mut row = id_only.clone(); |
| 1159 | assert!(complete_provider_live_row(&mut row, &facts)); |
| 1160 | assert_eq!(row.limit.as_ref().unwrap().context, Some(131_072)); |
| 1161 | assert_eq!(row.limit.as_ref().unwrap().output, Some(8_192)); |
| 1162 | assert_eq!(row.reasoning, Some(true)); |
| 1163 | assert_eq!(row.source, live, "the row is still the provider's"); |
| 1164 | assert_eq!(row.cost, None, "a signed price is not billable here"); |
| 1165 | assert_eq!(row.cost_source, None); |
| 1166 | |
| 1167 | // Anything the provider actually stated wins, field by field. |
| 1168 | let mut row = CatalogOffering { |
| 1169 | limit: Some(ModelsDevLimit { |
| 1170 | context: Some(64_000), |
| 1171 | ..Default::default() |
| 1172 | }), |
| 1173 | reasoning: Some(false), |
| 1174 | cost: Some(ModelsDevCost { |
| 1175 | input: Some(9.0), |
| 1176 | ..Default::default() |
| 1177 | }), |
| 1178 | ..id_only.clone() |
| 1179 | }; |
| 1180 | assert!(complete_provider_live_row(&mut row, &facts)); |
| 1181 | assert_eq!(row.limit.as_ref().unwrap().context, Some(64_000)); |
| 1182 | assert_eq!(row.limit.as_ref().unwrap().output, Some(8_192)); |
| 1183 | assert_eq!(row.reasoning, Some(false)); |
| 1184 | assert_eq!(row.cost.as_ref().unwrap().input, Some(9.0)); |
| 1185 | |
| 1186 | // Only provider-live rows are completed, and only by current facts. |
| 1187 | for source in [ |
| 1188 | CatalogSource::Bundled, |
| 1189 | CatalogSource::ConfigOverride, |
| 1190 | CatalogSource::UserOverride, |
| 1191 | CatalogSource::ModelsDevLive { fetched_at: NOW }, |
| 1192 | ] { |
| 1193 | let mut row = CatalogOffering { |
| 1194 | source, |
| 1195 | ..id_only.clone() |
| 1196 | }; |
| 1197 | let before = row.clone(); |
| 1198 | assert!(!complete_provider_live_row(&mut row, &facts)); |
| 1199 | assert_eq!(row, before); |
| 1200 | } |
| 1201 | let mut row = id_only.clone(); |
| 1202 | let expired = ScopedFacts { |
| 1203 | valid_until: Some(0), |
| 1204 | ..facts.clone() |
| 1205 | }; |
| 1206 | assert!(!complete_provider_live_row(&mut row, &expired)); |
| 1207 | assert_eq!(row, id_only); |
| 1208 | } |
| 1209 | |
| 1210 | /// Producer/consumer parity for the additive field: an older payload without it |
| 1211 | /// keeps roster dominance, and a newer one round-trips through the same wire |
| 1212 | /// shape the publisher signs. |
| 1213 | #[test] |
| 1214 | fn allow_unlisted_defaults_to_false_and_round_trips() { |
| 1215 | use super::ModelFact; |
| 1216 | let without: ModelFact = |
| 1217 | serde_json::from_value(json!({"provider": "deepseek", "id": "preview-a"})).unwrap(); |
| 1218 | assert!(!without.allow_unlisted); |
| 1219 | assert_eq!( |
| 1220 | serde_json::to_value(&without) |
| 1221 | .unwrap() |
| 1222 | .get("allow_unlisted"), |
| 1223 | None, |
| 1224 | "an unset assertion must not appear in the signed bytes" |
| 1225 | ); |
| 1226 | let with: ModelFact = serde_json::from_value( |
| 1227 | json!({"provider": "deepseek", "id": "preview-a", "allow_unlisted": true}), |
| 1228 | ) |
| 1229 | .unwrap(); |
| 1230 | assert!(with.allow_unlisted); |
| 1231 | assert_eq!( |
| 1232 | serde_json::to_value(&with).unwrap()["allow_unlisted"], |
| 1233 | json!(true) |
| 1234 | ); |
| 1235 | } |
| 1236 | |
| 1237 | #[test] |
| 1238 | fn cloud_route_identity_preserves_legacy_wire_endpoint_boundaries() { |
| 1239 | let chat = crate::default_base_url_for_provider(crate::ProviderKind::Minimax); |
| 1240 | let anthropic = crate::default_base_url_for_provider(crate::ProviderKind::MinimaxAnthropic); |
| 1241 | assert!(base_url_allowed("minimax", chat)); |
| 1242 | assert!(base_url_allowed("minimax-anthropic", anthropic)); |
| 1243 | assert!(!base_url_allowed("minimax-anthropic", chat)); |
| 1244 | assert!(!base_url_allowed("minimax", anthropic)); |
| 1245 | assert!( |
| 1246 | !base_url_allowed("minimax_anthropic", anthropic), |
| 1247 | "signed identities must use their exact canonical spelling" |
| 1248 | ); |
| 1249 | let signer = Signer::new("cwf-wire-identity"); |
| 1250 | let mut p = payload("stable", 1, "*"); |
| 1251 | p["models"] = |
| 1252 | json!([{"provider":"minimax-anthropic", "id":"MiniMax-M3", "context_window":1000}]); |
| 1253 | p["provider_defaults"] = |
| 1254 | json!({"minimax-anthropic":{"default_model":"MiniMax-M3", "base_url":anthropic}}); |
| 1255 | let verified = verify( |
| 1256 | &serde_json::to_vec(&signer.envelope(&p)).unwrap(), |
| 1257 | &[signer.trusted(KeyStatus::Active)], |
| 1258 | ) |
| 1259 | .unwrap(); |
| 1260 | let scoped = scoped_view(&verified, &v("0.9.11"), NOW); |
| 1261 | assert_eq!(scoped.models[0].provider, "minimax-anthropic"); |
| 1262 | assert_eq!( |
| 1263 | scoped.provider_defaults["minimax-anthropic"] |
| 1264 | .base_url |
| 1265 | .as_deref(), |
| 1266 | Some(anthropic) |
| 1267 | ); |
| 1268 | assert!(!scoped.provider_defaults.contains_key("minimax")); |
| 1269 | } |
| 1270 | |
| 1271 | const AUTOMATION_CASES: &str = |
| 1272 | include_str!("../../../cloud-facts/fixtures/automation-scope-cases.json"); |
| 1273 | |
| 1274 | fn automation_cases() -> (u64, Vec<Value>) { |
| 1275 | let fixture: Value = serde_json::from_str(AUTOMATION_CASES).expect("fixture json"); |
| 1276 | ( |
| 1277 | fixture["now"].as_u64().expect("now"), |
| 1278 | fixture["cases"].as_array().expect("cases").clone(), |
| 1279 | ) |
| 1280 | } |
| 1281 | |
| 1282 | #[test] |
| 1283 | fn automation_scope_cases_are_judged_as_the_shared_fixture_says() { |
| 1284 | let signer = Signer::new("cwf-auto"); |
| 1285 | let (now, cases) = automation_cases(); |
| 1286 | assert_eq!(cases.len(), 25); |
| 1287 | for case in cases { |
| 1288 | let name = case["name"].as_str().unwrap(); |
| 1289 | let channel = case["channel"].as_str().unwrap(); |
| 1290 | let bytes = serde_json::to_vec(&signer.envelope(&case["payload"])).unwrap(); |
| 1291 | let check = |
| 1292 | |keys: &[TrustedKey]| verify_envelope(&bytes, channel, &v("0.9.11"), None, keys, now); |
| 1293 | match (case["out_of_scope"].as_str(), check(&[signer.automation()])) { |
| 1294 | (None, Ok(verified)) => { |
| 1295 | assert_eq!(verified.key_id, "cwf-auto", "{name}"); |
| 1296 | assert!(!verified.stale, "{name}"); |
| 1297 | } |
| 1298 | (Some(expected), Err(FactsRejection::OutOfScope(reason))) => { |
| 1299 | assert!(reason.contains(expected), "{name}: got {reason}"); |
| 1300 | } |
| 1301 | (expected, other) => panic!("{name}: expected {expected:?}, got {other:?}"), |
| 1302 | } |
| 1303 | assert!( |
| 1304 | check(&[signer.trusted(KeyStatus::Active)]).is_ok(), |
| 1305 | "{name}: a founder key is not bound by the automation scope" |
| 1306 | ); |
| 1307 | } |
| 1308 | } |
| 1309 | |
| 1310 | #[test] |
| 1311 | fn a_founder_signature_lifts_the_automation_scope_in_either_order() { |
| 1312 | let auto = Signer::new("cwf-auto"); |
| 1313 | let founder = Signer::new("cwf-founder"); |
| 1314 | let (now, cases) = automation_cases(); |
| 1315 | let case = cases |
| 1316 | .iter() |
| 1317 | .find(|case| case["name"] == "default model") |
| 1318 | .unwrap(); |
| 1319 | let bytes = serde_json::to_vec(&case["payload"]).unwrap(); |
| 1320 | let keys = [auto.automation(), founder.trusted(KeyStatus::Active)]; |
| 1321 | let check = |env: &Value| { |
| 1322 | verify_envelope( |
| 1323 | &serde_json::to_vec(env).unwrap(), |
| 1324 | "stable-models", |
| 1325 | &v("0.9.11"), |
| 1326 | None, |
| 1327 | &keys, |
| 1328 | now, |
| 1329 | ) |
| 1330 | }; |
| 1331 | |
| 1332 | let mut auto_first = auto.envelope(&case["payload"]); |
| 1333 | auto_first["sigs"] = json!([{ "key_id": "cwf-founder", "sig_b64": founder.sign(&bytes) }]); |
| 1334 | assert_eq!(check(&auto_first).unwrap().key_id, "cwf-founder"); |
| 1335 | |
| 1336 | let mut founder_first = founder.envelope(&case["payload"]); |
| 1337 | founder_first["sigs"] = json!([{ "key_id": "cwf-auto", "sig_b64": auto.sign(&bytes) }]); |
| 1338 | assert_eq!(check(&founder_first).unwrap().key_id, "cwf-founder"); |
| 1339 | |
| 1340 | let mut forged = auto.envelope(&case["payload"]); |
| 1341 | forged["sigs"] = json!([{ "key_id": "cwf-founder", "sig_b64": auto.sign(&bytes) }]); |
| 1342 | assert!(matches!(check(&forged), Err(FactsRejection::OutOfScope(_)))); |
| 1343 | |
| 1344 | let retired = [auto.automation(), founder.trusted(KeyStatus::Retired)]; |
| 1345 | assert!(matches!( |
| 1346 | verify_envelope( |
| 1347 | &serde_json::to_vec(&auto_first).unwrap(), |
| 1348 | "stable-models", |
| 1349 | &v("0.9.11"), |
| 1350 | None, |
| 1351 | &retired, |
| 1352 | now |
| 1353 | ), |
| 1354 | Err(FactsRejection::OutOfScope(_)) |
| 1355 | )); |
| 1356 | } |
| 1357 | |
| 1358 | #[test] |
| 1359 | fn an_automation_key_cannot_raise_the_founder_channel_floor() { |
| 1360 | let auto = Signer::new("cwf-auto"); |
| 1361 | let (now, cases) = automation_cases(); |
| 1362 | let mut payload = cases[0]["payload"].clone(); |
| 1363 | payload["channel"] = json!("stable"); |
| 1364 | let bytes = serde_json::to_vec(&auto.envelope(&payload)).unwrap(); |
| 1365 | let rejected = verify_envelope( |
| 1366 | &bytes, |
| 1367 | "stable", |
| 1368 | &v("0.9.11"), |
| 1369 | None, |
| 1370 | &[auto.automation()], |
| 1371 | now, |
| 1372 | ); |
| 1373 | assert!( |
| 1374 | matches!(rejected, Err(FactsRejection::OutOfScope(reason)) if reason.contains("channel")) |
| 1375 | ); |
| 1376 | } |
| 1377 | |
| 1378 | #[test] |
| 1379 | fn automation_limits_and_the_empty_production_roster() { |
| 1380 | assert_eq!(AUTOMATION_MAX_VALIDITY_SECS, 604_800); |
| 1381 | assert_eq!(super::AUTOMATION_CHANNEL_SUFFIX, "-models"); |
| 1382 | assert_eq!(super::AUTOMATION_MAX_MODELS, 256); |
| 1383 | assert!( |
| 1384 | super::TRUSTED_KEYS |
| 1385 | .iter() |
| 1386 | .all(|key| key.role == KeyRole::Founder) |
| 1387 | ); |
| 1388 | let auto = Signer::new("cwf-auto"); |
| 1389 | let dup = TrustedKey { |
| 1390 | key_id: "cwf-founder-alias", |
| 1391 | role: KeyRole::Founder, |
| 1392 | ..auto.automation() |
| 1393 | }; |
| 1394 | let (now, cases) = automation_cases(); |
| 1395 | let bytes = serde_json::to_vec(&auto.envelope(&cases[0]["payload"])).unwrap(); |
| 1396 | assert!(matches!( |
| 1397 | verify_envelope( |
| 1398 | &bytes, |
| 1399 | "stable-models", |
| 1400 | &v("0.9.11"), |
| 1401 | None, |
| 1402 | &[auto.automation(), dup], |
| 1403 | now |
| 1404 | ), |
| 1405 | Err(FactsRejection::UnknownKey { .. }) |
| 1406 | )); |
| 1407 | } |
| 1408 |