| 1 | //! Envelope verification: size cap → shape → pinned key → Ed25519 → payload |
| 2 | //! parse → cross-checks → channel → schema → version scope → rollback → |
| 3 | //! expiry. Nothing in the payload is trusted before the signature verifies. |
| 4 | |
| 5 | use base64::Engine as _; |
| 6 | use base64::engine::general_purpose::STANDARD as BASE64; |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | |
| 9 | use super::keys::{ |
| 10 | AUTOMATION_CHANNEL_SUFFIX, AUTOMATION_MAX_MODELS, AUTOMATION_MAX_VALIDITY_SECS, DOMAIN, |
| 11 | ENVELOPE_VERSION, KeyRole, KeyStatus, MAX_ENVELOPE_BYTES, MAX_PAYLOAD_BYTES, |
| 12 | SUPPORTED_SCHEMA_VERSION, TrustedKey, trusted_key, |
| 13 | }; |
| 14 | use super::types::{CloudFacts, ModelFact, ModelOp}; |
| 15 | |
| 16 | /// Grace after `not_after` before facts downgrade to `stale` (48 h). |
| 17 | pub const NOT_AFTER_GRACE_SECS: u64 = 48 * 60 * 60; |
| 18 | pub const FUTURE_CLOCK_TOLERANCE_SECS: u64 = 300; |
| 19 | const MAX_SIGNATURES: usize = 8; |
| 20 | |
| 21 | /// The transport envelope as served by `/api/facts/v1/<channel>`. |
| 22 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 23 | pub struct Envelope { |
| 24 | pub envelope: u64, |
| 25 | pub channel: String, |
| 26 | pub facts_version: u64, |
| 27 | #[serde(default)] |
| 28 | pub schema_version: Option<u32>, |
| 29 | pub key_id: String, |
| 30 | pub alg: String, |
| 31 | #[serde(default)] |
| 32 | pub applies_to: Option<String>, |
| 33 | #[serde(default)] |
| 34 | pub published_at: Option<String>, |
| 35 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 36 | pub not_after: Option<String>, |
| 37 | pub payload_b64: String, |
| 38 | pub sig_b64: String, |
| 39 | #[serde(default)] |
| 40 | pub sigs: Vec<ExtraSignature>, |
| 41 | #[serde(default)] |
| 42 | pub sha256: Option<String>, |
| 43 | } |
| 44 | |
| 45 | /// Additional `(key_id, sig)` pairs carried during key rotation. |
| 46 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 47 | pub struct ExtraSignature { |
| 48 | pub key_id: String, |
| 49 | pub sig_b64: String, |
| 50 | } |
| 51 | |
| 52 | /// Why an envelope was not accepted. Every variant leaves bundled facts in use. |
| 53 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 54 | pub enum FactsRejection { |
| 55 | TooLarge { bytes: usize }, |
| 56 | BadEnvelope(String), |
| 57 | UnknownKey { key_id: String }, |
| 58 | RetiredKey { key_id: String }, |
| 59 | BadSignature, |
| 60 | BadPayload(String), |
| 61 | Mismatch(String), |
| 62 | WrongChannel { expected: String, got: String }, |
| 63 | SchemaTooNew { schema_version: u32 }, |
| 64 | BadVersionReq(String), |
| 65 | NotApplicable { applies_to: String }, |
| 66 | Rollback { got: u64, highest_seen: u64 }, |
| 67 | OutOfScope(String), |
| 68 | WrongSchema { got: String }, |
| 69 | } |
| 70 | |
| 71 | impl std::fmt::Display for FactsRejection { |
| 72 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 73 | match self { |
| 74 | Self::TooLarge { bytes } => write!(f, "envelope too large ({bytes} bytes)"), |
| 75 | Self::BadEnvelope(msg) => write!(f, "bad envelope: {msg}"), |
| 76 | Self::UnknownKey { key_id } => write!(f, "unknown key {key_id}"), |
| 77 | Self::RetiredKey { key_id } => write!(f, "retired key {key_id}"), |
| 78 | Self::BadSignature => write!(f, "bad signature"), |
| 79 | Self::BadPayload(msg) => write!(f, "bad payload: {msg}"), |
| 80 | Self::Mismatch(msg) => write!(f, "envelope/payload mismatch: {msg}"), |
| 81 | Self::WrongChannel { expected, got } => { |
| 82 | write!(f, "wrong channel (expected {expected}, got {got})") |
| 83 | } |
| 84 | Self::SchemaTooNew { schema_version } => { |
| 85 | write!(f, "schema_version {schema_version} newer than supported") |
| 86 | } |
| 87 | Self::BadVersionReq(req) => write!(f, "unparseable applies_to {req:?}"), |
| 88 | Self::NotApplicable { applies_to } => { |
| 89 | write!(f, "not applicable to this binary ({applies_to})") |
| 90 | } |
| 91 | Self::Rollback { got, highest_seen } => { |
| 92 | write!(f, "rollback (v{got} < seen v{highest_seen})") |
| 93 | } |
| 94 | Self::OutOfScope(msg) => write!(f, "outside the automation key's scope: {msg}"), |
| 95 | Self::WrongSchema { got } => write!(f, "unsupported registry schema {got:?}"), |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | /// A payload that passed every check. |
| 101 | #[derive(Debug, Clone, PartialEq)] |
| 102 | pub struct VerifiedFacts { |
| 103 | pub facts: CloudFacts, |
| 104 | /// The pinned key that authenticated the payload. |
| 105 | pub key_id: String, |
| 106 | /// Hex SHA-256 of the exact signed bytes. |
| 107 | pub sha256: String, |
| 108 | pub raw_len: usize, |
| 109 | /// `not_after` has passed by more than the grace window. |
| 110 | pub stale: bool, |
| 111 | } |
| 112 | |
| 113 | fn hex(bytes: &[u8]) -> String { |
| 114 | use std::fmt::Write as _; |
| 115 | let mut out = String::with_capacity(bytes.len() * 2); |
| 116 | for byte in bytes { |
| 117 | let _ = write!(&mut out, "{byte:02x}"); |
| 118 | } |
| 119 | out |
| 120 | } |
| 121 | |
| 122 | pub(crate) fn sha256_hex(payload: &[u8]) -> String { |
| 123 | use sha2::Digest as _; |
| 124 | hex(&sha2::Sha256::digest(payload)) |
| 125 | } |
| 126 | |
| 127 | /// The exact bytes an Ed25519 signature covers. |
| 128 | #[must_use] |
| 129 | pub fn signing_message(key_id: &str, payload: &[u8]) -> Vec<u8> { |
| 130 | let mut msg = Vec::with_capacity(DOMAIN.len() + key_id.len() + 1 + payload.len()); |
| 131 | msg.extend_from_slice(DOMAIN); |
| 132 | msg.extend_from_slice(key_id.as_bytes()); |
| 133 | msg.push(0); |
| 134 | msg.extend_from_slice(payload); |
| 135 | msg |
| 136 | } |
| 137 | |
| 138 | fn ed25519_ok(public_key: &[u8; 32], message: &[u8], signature: &[u8]) -> bool { |
| 139 | ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key) |
| 140 | .verify(message, signature) |
| 141 | .is_ok() |
| 142 | } |
| 143 | |
| 144 | /// Parse an RFC 3339 UTC timestamp (`YYYY-MM-DDTHH:MM:SS[.fff]Z`) to unix seconds. |
| 145 | /// |
| 146 | /// Offsets other than `Z` are not accepted (returns `None`); the publisher |
| 147 | /// always writes UTC. |
| 148 | #[must_use] |
| 149 | pub fn parse_rfc3339_utc(value: &str) -> Option<u64> { |
| 150 | let value = value.trim(); |
| 151 | if !value.ends_with('Z') { |
| 152 | return None; |
| 153 | } |
| 154 | let parsed = chrono::DateTime::parse_from_rfc3339(value).ok()?; |
| 155 | u64::try_from(parsed.timestamp()).ok() |
| 156 | } |
| 157 | |
| 158 | pub(crate) struct Authenticated { |
| 159 | pub envelope: Envelope, |
| 160 | pub payload: Vec<u8>, |
| 161 | pub key_id: String, |
| 162 | pub key_role: KeyRole, |
| 163 | } |
| 164 | |
| 165 | #[derive(Debug, Clone, Copy)] |
| 166 | pub(crate) struct EnvelopeLimits { |
| 167 | pub envelope_bytes: usize, |
| 168 | pub payload_bytes: usize, |
| 169 | pub facts_metadata: bool, |
| 170 | } |
| 171 | |
| 172 | pub(crate) fn authenticate( |
| 173 | bytes: &[u8], |
| 174 | expected_channel: &str, |
| 175 | keys: &[TrustedKey], |
| 176 | limits: EnvelopeLimits, |
| 177 | ) -> Result<Authenticated, FactsRejection> { |
| 178 | if bytes.len() > limits.envelope_bytes { |
| 179 | return Err(FactsRejection::TooLarge { bytes: bytes.len() }); |
| 180 | } |
| 181 | let envelope: Envelope = serde_json::from_slice(bytes) |
| 182 | .map_err(|err| FactsRejection::BadEnvelope(err.to_string()))?; |
| 183 | if envelope.envelope != ENVELOPE_VERSION { |
| 184 | return Err(FactsRejection::BadEnvelope(format!( |
| 185 | "envelope version {} (supported {ENVELOPE_VERSION})", |
| 186 | envelope.envelope |
| 187 | ))); |
| 188 | } |
| 189 | if limits.facts_metadata |
| 190 | && (envelope.schema_version.is_none() |
| 191 | || envelope.applies_to.is_none() |
| 192 | || envelope.published_at.is_none() |
| 193 | || envelope.sha256.is_none()) |
| 194 | { |
| 195 | return Err(FactsRejection::BadEnvelope( |
| 196 | "missing signed-payload metadata".into(), |
| 197 | )); |
| 198 | } |
| 199 | if envelope.alg != "ed25519" { |
| 200 | return Err(FactsRejection::BadEnvelope("unsupported alg".into())); |
| 201 | } |
| 202 | let valid_key_id = |id: &str| { |
| 203 | id.strip_prefix("cwf-").is_some_and(|suffix| { |
| 204 | !suffix.is_empty() |
| 205 | && suffix.len() <= 32 |
| 206 | && suffix |
| 207 | .bytes() |
| 208 | .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') |
| 209 | }) |
| 210 | }; |
| 211 | if envelope.sigs.len() >= MAX_SIGNATURES |
| 212 | || !valid_key_id(&envelope.key_id) |
| 213 | || envelope |
| 214 | .sigs |
| 215 | .iter() |
| 216 | .any(|signature| !valid_key_id(&signature.key_id)) |
| 217 | || envelope.sig_b64.len() > 88 |
| 218 | || envelope |
| 219 | .sigs |
| 220 | .iter() |
| 221 | .any(|signature| signature.sig_b64.len() > 88) |
| 222 | { |
| 223 | return Err(FactsRejection::BadEnvelope( |
| 224 | "invalid signature candidates".into(), |
| 225 | )); |
| 226 | } |
| 227 | if envelope.channel.is_empty() |
| 228 | || envelope.channel.len() > 32 |
| 229 | || expected_channel.len() > 32 |
| 230 | || !envelope |
| 231 | .channel |
| 232 | .bytes() |
| 233 | .next() |
| 234 | .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit()) |
| 235 | || !envelope |
| 236 | .channel |
| 237 | .bytes() |
| 238 | .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') |
| 239 | || envelope |
| 240 | .applies_to |
| 241 | .as_ref() |
| 242 | .is_some_and(|value| value.len() > 200) |
| 243 | || envelope |
| 244 | .published_at |
| 245 | .as_ref() |
| 246 | .is_some_and(|value| value.len() > 40) |
| 247 | || envelope |
| 248 | .not_after |
| 249 | .as_ref() |
| 250 | .is_some_and(|value| value.len() > 40) |
| 251 | || envelope |
| 252 | .sha256 |
| 253 | .as_ref() |
| 254 | .is_some_and(|value| value.len() != 64) |
| 255 | { |
| 256 | return Err(FactsRejection::BadEnvelope( |
| 257 | "invalid metadata bounds".into(), |
| 258 | )); |
| 259 | } |
| 260 | if envelope.payload_b64.len() > limits.payload_bytes * 4 / 3 + 4 { |
| 261 | return Err(FactsRejection::TooLarge { |
| 262 | bytes: envelope.payload_b64.len(), |
| 263 | }); |
| 264 | } |
| 265 | let payload = BASE64 |
| 266 | .decode(envelope.payload_b64.as_bytes()) |
| 267 | .map_err(|err| FactsRejection::BadEnvelope(format!("payload_b64: {err}")))?; |
| 268 | if payload.is_empty() { |
| 269 | return Err(FactsRejection::BadEnvelope("empty payload".into())); |
| 270 | } |
| 271 | if payload.len() > limits.payload_bytes { |
| 272 | return Err(FactsRejection::TooLarge { |
| 273 | bytes: payload.len(), |
| 274 | }); |
| 275 | } |
| 276 | |
| 277 | let mut candidates: Vec<(&str, &str)> = Vec::with_capacity(1 + envelope.sigs.len()); |
| 278 | candidates.push((envelope.key_id.as_str(), envelope.sig_b64.as_str())); |
| 279 | for extra in &envelope.sigs { |
| 280 | candidates.push((extra.key_id.as_str(), extra.sig_b64.as_str())); |
| 281 | } |
| 282 | let mut saw_known = false; |
| 283 | let mut saw_retired: Option<String> = None; |
| 284 | let mut verified_key: Option<(String, KeyRole)> = None; |
| 285 | for (key_id, sig_b64) in candidates { |
| 286 | let Some(key) = trusted_key(keys, key_id) else { |
| 287 | continue; |
| 288 | }; |
| 289 | if key.status == KeyStatus::Retired { |
| 290 | saw_retired.get_or_insert_with(|| key_id.to_string()); |
| 291 | continue; |
| 292 | } |
| 293 | saw_known = true; |
| 294 | let Ok(signature) = BASE64.decode(sig_b64.as_bytes()) else { |
| 295 | continue; |
| 296 | }; |
| 297 | if signature.len() != 64 { |
| 298 | continue; |
| 299 | } |
| 300 | let message = signing_message(key_id, &payload); |
| 301 | if ed25519_ok(&key.public_key, &message, &signature) { |
| 302 | if key.role == KeyRole::Founder { |
| 303 | verified_key = Some((key_id.to_string(), key.role)); |
| 304 | break; |
| 305 | } |
| 306 | verified_key.get_or_insert_with(|| (key_id.to_string(), key.role)); |
| 307 | } |
| 308 | } |
| 309 | let Some((key_id, key_role)) = verified_key else { |
| 310 | if saw_known { |
| 311 | return Err(FactsRejection::BadSignature); |
| 312 | } |
| 313 | if let Some(key_id) = saw_retired { |
| 314 | return Err(FactsRejection::RetiredKey { key_id }); |
| 315 | } |
| 316 | return Err(FactsRejection::UnknownKey { |
| 317 | key_id: envelope.key_id, |
| 318 | }); |
| 319 | }; |
| 320 | |
| 321 | Ok(Authenticated { |
| 322 | envelope, |
| 323 | payload, |
| 324 | key_id, |
| 325 | key_role, |
| 326 | }) |
| 327 | } |
| 328 | |
| 329 | /// Verify a raw envelope document. |
| 330 | /// |
| 331 | /// * `expected_channel` — the channel the client asked for. |
| 332 | /// * `current` — the running binary's version (`CARGO_PKG_VERSION`). |
| 333 | /// * `highest_seen` — highest `facts_version` this client previously accepted |
| 334 | /// for the channel (rollback protection); equal is accepted. |
| 335 | /// * `keys` — the pinned trust anchors (normally [`super::keys::TRUSTED_KEYS`]). |
| 336 | /// * `now_unix` — wall clock, injected for deterministic tests. |
| 337 | pub fn verify_envelope( |
| 338 | bytes: &[u8], |
| 339 | expected_channel: &str, |
| 340 | current: &semver::Version, |
| 341 | highest_seen: Option<u64>, |
| 342 | keys: &[TrustedKey], |
| 343 | now_unix: u64, |
| 344 | ) -> Result<VerifiedFacts, FactsRejection> { |
| 345 | let Authenticated { |
| 346 | envelope, |
| 347 | payload, |
| 348 | key_id, |
| 349 | key_role, |
| 350 | } = authenticate( |
| 351 | bytes, |
| 352 | expected_channel, |
| 353 | keys, |
| 354 | EnvelopeLimits { |
| 355 | envelope_bytes: MAX_ENVELOPE_BYTES, |
| 356 | payload_bytes: MAX_PAYLOAD_BYTES, |
| 357 | facts_metadata: true, |
| 358 | }, |
| 359 | )?; |
| 360 | |
| 361 | // Only now is the payload trusted enough to parse. |
| 362 | let facts: CloudFacts = serde_json::from_slice(&payload) |
| 363 | .map_err(|err| FactsRejection::BadPayload(err.to_string()))?; |
| 364 | if facts.channel != envelope.channel { |
| 365 | return Err(FactsRejection::Mismatch("channel".into())); |
| 366 | } |
| 367 | if facts.facts_version != envelope.facts_version { |
| 368 | return Err(FactsRejection::Mismatch(format!( |
| 369 | "facts_version {} vs {}", |
| 370 | envelope.facts_version, facts.facts_version |
| 371 | ))); |
| 372 | } |
| 373 | if let Some(outer) = envelope.applies_to.as_deref() |
| 374 | && outer != facts.applies_to |
| 375 | { |
| 376 | return Err(FactsRejection::Mismatch("applies_to".into())); |
| 377 | } |
| 378 | if let Some(outer) = envelope.schema_version |
| 379 | && outer != facts.schema_version |
| 380 | { |
| 381 | return Err(FactsRejection::Mismatch(format!( |
| 382 | "schema_version {outer} vs {}", |
| 383 | facts.schema_version |
| 384 | ))); |
| 385 | } |
| 386 | if envelope |
| 387 | .published_at |
| 388 | .as_ref() |
| 389 | .is_some_and(|outer| outer != &facts.published_at) |
| 390 | { |
| 391 | return Err(FactsRejection::Mismatch("published_at".into())); |
| 392 | } |
| 393 | if let Some(outer) = envelope.not_after.as_deref() |
| 394 | && Some(outer) != facts.not_after.as_deref() |
| 395 | { |
| 396 | return Err(FactsRejection::Mismatch("not_after".into())); |
| 397 | } |
| 398 | if facts.schema_version == 0 || facts.facts_version == 0 { |
| 399 | return Err(FactsRejection::BadPayload( |
| 400 | "schema and facts versions must be positive".into(), |
| 401 | )); |
| 402 | } |
| 403 | if facts.channel != expected_channel { |
| 404 | return Err(FactsRejection::WrongChannel { |
| 405 | expected: expected_channel.to_string(), |
| 406 | got: facts.channel, |
| 407 | }); |
| 408 | } |
| 409 | if facts.schema_version > SUPPORTED_SCHEMA_VERSION { |
| 410 | return Err(FactsRejection::SchemaTooNew { |
| 411 | schema_version: facts.schema_version, |
| 412 | }); |
| 413 | } |
| 414 | if !version_req_matches(&facts.applies_to, current)? { |
| 415 | return Err(FactsRejection::NotApplicable { |
| 416 | applies_to: facts.applies_to, |
| 417 | }); |
| 418 | } |
| 419 | if let Some(highest) = highest_seen |
| 420 | && facts.facts_version < highest |
| 421 | { |
| 422 | return Err(FactsRejection::Rollback { |
| 423 | got: facts.facts_version, |
| 424 | highest_seen: highest, |
| 425 | }); |
| 426 | } |
| 427 | let published_at = parse_rfc3339_utc(&facts.published_at) |
| 428 | .ok_or_else(|| FactsRejection::BadPayload("invalid published_at timestamp".into()))?; |
| 429 | if published_at > now_unix.saturating_add(FUTURE_CLOCK_TOLERANCE_SECS) { |
| 430 | return Err(FactsRejection::BadPayload( |
| 431 | "published_at is in the future".into(), |
| 432 | )); |
| 433 | } |
| 434 | let not_after = facts |
| 435 | .not_after |
| 436 | .as_deref() |
| 437 | .map(|value| { |
| 438 | parse_rfc3339_utc(value) |
| 439 | .ok_or_else(|| FactsRejection::BadPayload("invalid not_after timestamp".into())) |
| 440 | }) |
| 441 | .transpose()?; |
| 442 | if not_after.is_some_and(|expires| expires <= published_at) { |
| 443 | return Err(FactsRejection::BadPayload( |
| 444 | "not_after does not follow published_at".into(), |
| 445 | )); |
| 446 | } |
| 447 | if key_role == KeyRole::Automation { |
| 448 | let raw: serde_json::Value = serde_json::from_slice(&payload) |
| 449 | .map_err(|err| FactsRejection::BadPayload(err.to_string()))?; |
| 450 | if let Some(violation) = |
| 451 | automation_scope_violation(&facts, &raw, expected_channel, published_at, not_after) |
| 452 | { |
| 453 | return Err(FactsRejection::OutOfScope(violation)); |
| 454 | } |
| 455 | } |
| 456 | let stale = |
| 457 | not_after.is_some_and(|expires| now_unix > expires.saturating_add(NOT_AFTER_GRACE_SECS)); |
| 458 | |
| 459 | let sha256 = sha256_hex(&payload); |
| 460 | if envelope |
| 461 | .sha256 |
| 462 | .as_ref() |
| 463 | .is_some_and(|outer| outer != &sha256) |
| 464 | { |
| 465 | return Err(FactsRejection::Mismatch("sha256".into())); |
| 466 | } |
| 467 | Ok(VerifiedFacts { |
| 468 | facts, |
| 469 | key_id, |
| 470 | sha256, |
| 471 | raw_len: payload.len(), |
| 472 | stale, |
| 473 | }) |
| 474 | } |
| 475 | |
| 476 | const AUTOMATION_PAYLOAD_FIELDS: &[&str] = &[ |
| 477 | "schema_version", |
| 478 | "channel", |
| 479 | "facts_version", |
| 480 | "published_at", |
| 481 | "not_after", |
| 482 | "applies_to", |
| 483 | "models", |
| 484 | "provider_defaults", |
| 485 | "release", |
| 486 | "announcements", |
| 487 | ]; |
| 488 | const AUTOMATION_MODEL_FIELDS: &[&str] = &[ |
| 489 | "provider", |
| 490 | "id", |
| 491 | "op", |
| 492 | "context_window", |
| 493 | "max_output", |
| 494 | "reasoning", |
| 495 | "display_name", |
| 496 | "deprecated_at", |
| 497 | "replacement", |
| 498 | "note", |
| 499 | "applies_to", |
| 500 | "pricing_withheld", |
| 501 | ]; |
| 502 | |
| 503 | fn plain_text(value: Option<&str>, max_chars: usize) -> bool { |
| 504 | value |
| 505 | .is_none_or(|text| text.chars().count() <= max_chars && !text.chars().any(char::is_control)) |
| 506 | } |
| 507 | |
| 508 | fn whole_second_utc(value: &str) -> bool { |
| 509 | let bytes = value.as_bytes(); |
| 510 | bytes.len() == 20 |
| 511 | && bytes.iter().enumerate().all(|(index, byte)| match index { |
| 512 | 4 | 7 => *byte == b'-', |
| 513 | 10 => *byte == b'T', |
| 514 | 13 | 16 => *byte == b':', |
| 515 | 19 => *byte == b'Z', |
| 516 | _ => byte.is_ascii_digit(), |
| 517 | }) |
| 518 | } |
| 519 | |
| 520 | #[must_use] |
| 521 | pub fn automation_scope_violation( |
| 522 | facts: &CloudFacts, |
| 523 | raw: &serde_json::Value, |
| 524 | expected_channel: &str, |
| 525 | published_at: u64, |
| 526 | not_after: Option<u64>, |
| 527 | ) -> Option<String> { |
| 528 | let CloudFacts { |
| 529 | schema_version: _, |
| 530 | channel: _, |
| 531 | facts_version, |
| 532 | published_at: published_text, |
| 533 | not_after: not_after_text, |
| 534 | applies_to, |
| 535 | models, |
| 536 | provider_defaults, |
| 537 | release, |
| 538 | announcements, |
| 539 | unknown, |
| 540 | } = facts; |
| 541 | if !expected_channel |
| 542 | .strip_suffix(AUTOMATION_CHANNEL_SUFFIX) |
| 543 | .is_some_and(|prefix| { |
| 544 | prefix |
| 545 | .bytes() |
| 546 | .next() |
| 547 | .is_some_and(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit()) |
| 548 | }) |
| 549 | { |
| 550 | return Some(format!( |
| 551 | "channel {expected_channel:?} is not an automation channel" |
| 552 | )); |
| 553 | } |
| 554 | if !plain_text(Some(applies_to), 200) { |
| 555 | return Some("applies_to is too long or not plain".into()); |
| 556 | } |
| 557 | if !provider_defaults.is_empty() { |
| 558 | return Some("provider defaults".into()); |
| 559 | } |
| 560 | if release.is_some() { |
| 561 | return Some("release facts".into()); |
| 562 | } |
| 563 | if !announcements.is_empty() { |
| 564 | return Some("announcements".into()); |
| 565 | } |
| 566 | let unknown_top = raw.as_object().and_then(|object| { |
| 567 | object |
| 568 | .keys() |
| 569 | .find(|field| !AUTOMATION_PAYLOAD_FIELDS.contains(&field.as_str())) |
| 570 | }); |
| 571 | if let Some(field) = unknown_top.or_else(|| unknown.keys().next()) { |
| 572 | return Some(format!("field {field:?} is not allowed")); |
| 573 | } |
| 574 | if models.len() > AUTOMATION_MAX_MODELS { |
| 575 | return Some(format!("more than {AUTOMATION_MAX_MODELS} models")); |
| 576 | } |
| 577 | let raw_models = raw.get("models").and_then(serde_json::Value::as_array); |
| 578 | if raw_models.map_or(0, Vec::len) != models.len() { |
| 579 | return Some("models do not match the signed bytes".into()); |
| 580 | } |
| 581 | for (model, raw_model) in models.iter().zip(raw_models.into_iter().flatten()) { |
| 582 | let ModelFact { |
| 583 | provider, |
| 584 | id, |
| 585 | op, |
| 586 | allow_unlisted, |
| 587 | context_window, |
| 588 | max_output, |
| 589 | pricing, |
| 590 | pricing_withheld, |
| 591 | reasoning: _, |
| 592 | reasoning_options, |
| 593 | display_name, |
| 594 | deprecated_at, |
| 595 | replacement, |
| 596 | note, |
| 597 | applies_to, |
| 598 | } = model; |
| 599 | let name = format!("{provider}/{id}"); |
| 600 | if provider.is_empty() || id.is_empty() { |
| 601 | return Some("malformed model entry".into()); |
| 602 | } |
| 603 | let unknown_field = raw_model.as_object().and_then(|object| { |
| 604 | object |
| 605 | .keys() |
| 606 | .find(|field| !AUTOMATION_MODEL_FIELDS.contains(&field.as_str())) |
| 607 | }); |
| 608 | if let Some(field) = unknown_field { |
| 609 | return Some(format!("{name}: field {field:?} is not allowed")); |
| 610 | } |
| 611 | let null_field = raw_model.as_object().and_then(|object| { |
| 612 | object |
| 613 | .iter() |
| 614 | .find_map(|(field, value)| value.is_null().then_some(field.as_str())) |
| 615 | }); |
| 616 | if let Some(field) = null_field { |
| 617 | return Some(format!("{name}: field {field:?} is null")); |
| 618 | } |
| 619 | if *allow_unlisted || pricing.is_some() || reasoning_options.is_some() { |
| 620 | return Some(format!("{name}: field outside the automation model fields")); |
| 621 | } |
| 622 | if !matches!(op, ModelOp::Upsert | ModelOp::Deprecate) { |
| 623 | return Some(format!("{name} is not an upsert or deprecation")); |
| 624 | } |
| 625 | if !plain_text(Some(provider), 64) |
| 626 | || !plain_text(Some(id), 200) |
| 627 | || !plain_text(display_name.as_deref(), 120) |
| 628 | || !plain_text(deprecated_at.as_deref(), 40) |
| 629 | || !plain_text(replacement.as_deref(), 200) |
| 630 | || !plain_text(note.as_deref(), 300) |
| 631 | || !plain_text(applies_to.as_deref(), 200) |
| 632 | || !plain_text(pricing_withheld.as_deref(), 300) |
| 633 | { |
| 634 | return Some(format!("{name}: text too long or not plain")); |
| 635 | } |
| 636 | let window_ok = context_window.is_none_or(|window| (1_024..=20_000_000).contains(&window)); |
| 637 | let output_ok = max_output.is_none_or(|output| { |
| 638 | (1..=2_000_000).contains(&output) |
| 639 | && context_window.is_none_or(|window| output <= window) |
| 640 | }); |
| 641 | if !window_ok || !output_ok { |
| 642 | return Some(format!("{name}: limit out of range")); |
| 643 | } |
| 644 | } |
| 645 | if !whole_second_utc(published_text) |
| 646 | || not_after_text |
| 647 | .as_deref() |
| 648 | .is_some_and(|text| !whole_second_utc(text)) |
| 649 | { |
| 650 | return Some("timestamp is not whole-second UTC".into()); |
| 651 | } |
| 652 | if *facts_version != published_at { |
| 653 | return Some("facts_version is not the publication time".into()); |
| 654 | } |
| 655 | automation_window_violation(published_at, not_after).map(str::to_string) |
| 656 | } |
| 657 | |
| 658 | pub const MAX_AUTOMATION_WINDOW_SECS: u64 = AUTOMATION_MAX_VALIDITY_SECS; |
| 659 | |
| 660 | #[must_use] |
| 661 | pub fn automation_window_violation( |
| 662 | published_at: u64, |
| 663 | not_after: Option<u64>, |
| 664 | ) -> Option<&'static str> { |
| 665 | match not_after { |
| 666 | None => Some("no not_after"), |
| 667 | Some(expires) |
| 668 | if expires <= published_at || expires - published_at > MAX_AUTOMATION_WINDOW_SECS => |
| 669 | { |
| 670 | Some("validity outside the automation limit") |
| 671 | } |
| 672 | Some(_) => None, |
| 673 | } |
| 674 | } |
| 675 | |
| 676 | pub fn check_automation_window( |
| 677 | published_at: u64, |
| 678 | not_after: Option<u64>, |
| 679 | now_unix: u64, |
| 680 | ) -> Result<u64, FactsRejection> { |
| 681 | if let Some(violation) = automation_window_violation(published_at, not_after) { |
| 682 | return Err(FactsRejection::OutOfScope(violation.into())); |
| 683 | } |
| 684 | let expires = not_after.expect("checked above"); |
| 685 | if now_unix >= expires { |
| 686 | return Err(FactsRejection::OutOfScope("not_after has expired".into())); |
| 687 | } |
| 688 | Ok(expires) |
| 689 | } |
| 690 | |
| 691 | /// Evaluate a Cargo-style semver requirement against the running version. |
| 692 | /// |
| 693 | /// `*` matches everything; an empty requirement is invalid. Prerelease binaries (`0.9.12-beta.1`) only |
| 694 | /// match requirements that name a prerelease on the same `major.minor.patch`, |
| 695 | /// which is semver's rule; the beta channel must set `applies_to` explicitly. |
| 696 | pub fn version_req_matches(req: &str, current: &semver::Version) -> Result<bool, FactsRejection> { |
| 697 | let trimmed = req.trim(); |
| 698 | if trimmed.is_empty() || trimmed.len() > 200 { |
| 699 | return Err(FactsRejection::BadVersionReq(String::new())); |
| 700 | } |
| 701 | if trimmed == "*" { |
| 702 | return Ok(true); |
| 703 | } |
| 704 | let parsed = semver::VersionReq::parse(trimmed) |
| 705 | .map_err(|_| FactsRejection::BadVersionReq(trimmed.to_string()))?; |
| 706 | Ok(parsed.matches(current)) |
| 707 | } |
| 708 | |
| 709 | /// Lenient per-item variant: unparseable requirements simply do not match. |
| 710 | #[must_use] |
| 711 | pub fn item_applies(req: Option<&str>, current: &semver::Version) -> bool { |
| 712 | match req { |
| 713 | None => true, |
| 714 | Some(req) => version_req_matches(req, current).unwrap_or(false), |
| 715 | } |
| 716 | } |
| 717 |