//! Passive protocol clock material only: never a sync decision or job grant. //! Context comes from current mTLS identity + locked tenant installation row. use anyhow::{Context as _, ensure}; use axum::{ Extension, Json, Router, body::Bytes, extract::{DefaultBodyLimit, State}, http::{HeaderMap, StatusCode}, routing::post, }; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use chrono::Utc; use rmm_domain::{ agent_update::{self as update, UpdateDelegation}, jobs::{Action, ExecutionPermitPayload, JobPayload, PlanPayload, encode, hash}, reconciliation::ReconcileDecisionPayload, }; use rmm_time_attestation::{Request, SignedAttestation}; use rmm_updater_handoff::Handoff; use serde::{Deserialize, Serialize}; use sqlx::Row; use sqlx::{Postgres, Transaction}; use std::{os::unix::fs::MetadataExt, sync::OnceLock, time::Duration}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::UnixStream, sync::Semaphore, }; use uuid::Uuid; const SOCKET: &str = "/run/rmm-time-source/broker.sock"; const MAX_FRAME: usize = 8192; static QUERIES: OnceLock = OnceLock::new(); pub(crate) fn gateway_routes(routes: Router) -> Router { routes.route( "/agent/v1/time-attestation", post(attest).layer(DefaultBodyLimit::max(MAX_FRAME)), ) } fn protected_socket() -> anyhow::Result<(u64, u64)> { use anyhow::ensure; for path in ["/run", "/run/rmm-time-source"] { let m = std::fs::symlink_metadata(path)?; ensure!( m.is_dir() && !m.file_type().is_symlink() && m.uid() == 0 && m.mode() & 0o022 == 0, "TIME_BROKER_DIRECTORY" ); } let m = std::fs::symlink_metadata(SOCKET)?; use std::os::unix::fs::FileTypeExt; ensure!( m.file_type().is_socket() && m.uid() == 0 && m.gid() == 10001 && m.nlink() == 1 && m.mode() & 0o7777 == 0o660, "TIME_BROKER_SOCKET" ); Ok((m.dev(), m.ino())) } async fn broker(request: &Request) -> anyhow::Result { use anyhow::ensure; let owned = protected_socket()?; let mut connection = UnixStream::connect(SOCKET).await?; let peer = connection.peer_cred()?; // A host broker is in an ancestor PID namespace: Linux may report PID0 // (or the wrapper may omit it) to this container. Authorization instead // requires the kernel-mapped root UID, protected root-owned socket inode, // and the verifier's independently pinned end-to-end time signature. // Userns remapping is not compensated: unmapped UID/socket ownership denies. ensure!(peer.uid() == 0, "TIME_BROKER_PEER"); ensure!(protected_socket()? == owned, "TIME_BROKER_REPLACED"); let raw = serde_json::to_vec(request)?; ensure!( !raw.is_empty() && raw.len() <= MAX_FRAME, "TIME_REQUEST_SIZE" ); connection .write_all(&(u32::try_from(raw.len())?).to_be_bytes()) .await?; connection.write_all(&raw).await?; connection.shutdown().await?; let length = connection.read_u32().await? as usize; ensure!(length > 0 && length <= MAX_FRAME, "TIME_RESPONSE_SIZE"); let mut raw = vec![0; length]; connection.read_exact(&mut raw).await?; let mut extra = [0; 1]; ensure!( connection.read(&mut extra).await? == 0, "TIME_RESPONSE_TRAILING" ); ensure!(protected_socket()? == owned, "TIME_BROKER_REPLACED"); let response: SignedAttestation = serde_json::from_slice(&raw)?; ensure!( serde_json::to_vec(&response)? == raw, "TIME_RESPONSE_NONCANONICAL" ); // The independent verifier checks the signature, protected key and whole // challenge. This root-peer transport is not an OS/helper attestation. let payload: rmm_time_attestation::Payload = serde_json::from_str(&response.payload)?; ensure!( payload.request_sha256 == request.sha256()?, "TIME_RESPONSE_REQUEST" ); Ok(response) } async fn attest( State(s): State, Extension(peer): Extension, headers: HeaderMap, bytes: Bytes, ) -> Result, StatusCode> { tokio::time::timeout(Duration::from_millis(500), issue(&s, peer, headers, bytes)) .await .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)? } async fn issue( s: &crate::State, peer: crate::Peer, headers: HeaderMap, bytes: Bytes, ) -> Result, StatusCode> { let (tenant, agent) = crate::agent_http::identity(s, peer).await?; if headers.get("content-type").and_then(|v| v.to_str().ok()) != Some("application/json") { return Err(StatusCode::UNSUPPORTED_MEDIA_TYPE); } let request: Request = serde_json::from_slice(&bytes).map_err(|_| StatusCode::BAD_REQUEST)?; request.validate().map_err(|_| StatusCode::BAD_REQUEST)?; let c = &request.context; if c.tenant_id != tenant || c.agent_id != agent { return Err(StatusCode::FORBIDDEN); } let _slot = QUERIES .get_or_init(|| Semaphore::new(4)) .try_acquire() .map_err(|_| StatusCode::TOO_MANY_REQUESTS)?; let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant) .await .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?; if c.role == rmm_time_attestation::Role::Updater { // Same lock order as Hello/Sync/start reservation. The additional job // checks below must not invert their installation/job row lock order. crate::agent_service::control_lock(&mut tx, tenant, agent) .await .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?; } // No sync_ready precondition: the independent time check is needed before // the first signed reconciliation, including its strictly negative paths. let row = sqlx::query("SELECT asset_id,enrollment_generation,assignment_version,connection_generation,connection_boot_id,capabilities,sequence_regressed,sync_recovery_required FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND revoked_at IS NULL FOR SHARE") .bind(tenant).bind(agent).fetch_optional(&mut *tx).await .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?.ok_or(StatusCode::FORBIDDEN)?; let same = row.get::("asset_id") == c.asset_id && u64::try_from(row.get::("enrollment_generation")).ok() == Some(c.enrollment_generation) && u64::try_from(row.get::("assignment_version")).ok() == Some(c.assignment_generation) && row.get::, _>("connection_boot_id") == Some(c.windows_boot_id) && row .get::("capabilities") .as_array() .is_some_and(|v| v.iter().any(|v| v.as_str() == Some("windows.base/1"))); if !same { return Err(StatusCode::CONFLICT); } let current_generation = u64::try_from(row.get::("connection_generation")) .map_err(|_| StatusCode::CONFLICT)?; let original_deadline = if current_generation != c.connection_generation { if row.get::("sequence_regressed") || row.get::("sync_recovery_required") { return Err(StatusCode::CONFLICT); } Some( original_updater_bridge(s, &mut tx, c, current_generation) .await .map_err(|_| StatusCode::CONFLICT)?, ) } else { None }; // Hold the shared installation lock through this bounded local query: // revoke/reassignment/connection changes cannot race the signing moment. let response = tokio::time::timeout(Duration::from_millis(300), broker(&request)) .await .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)? .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?; // A broker query never extends the original job's deadline. Discard its // passive signature if the bound expired while this request was in flight. if original_deadline.is_some_and(|finish| { u64::try_from(Utc::now().timestamp()).map_or(true, |now| now >= finish) }) { return Err(StatusCode::CONFLICT); } tx.commit() .await .map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?; Ok(Json(response)) } /// Public original metadata retained once by the EXISTING validated Sync path. /// It supplies no new approval/start/ready authority and contains no key bytes. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct RetainedUpdaterContext { schema_version: u32, job_id: Uuid, attempt_id: Uuid, grant_id: Uuid, handoff_sha256: String, delegation_sha256: String, handoff_base64url: String, delegation_base64url: String, } impl RetainedUpdaterContext { fn capture(h: &Handoff, d: &UpdateDelegation) -> anyhow::Result { let handoff = h.bytes()?; let delegation = serde_json::to_vec(d)?; ensure!( d.validate() && d.handoff_sha256 == hash(&handoff) && d.owner_nonce == h.owner_nonce && d.boot_id == h.boot_id && d.updater.image_sha256 == h.updater_sha256 && d.original_helper.image_sha256 == h.predecessor.helper_sha256 && u64::try_from(d.prepared_at.timestamp())? == h.consumed_at, "TIME_UPDATE_ORIGINAL_DELEGATION" ); Ok(Self { schema_version: 1, job_id: h.attempt.job_id, attempt_id: h.attempt.attempt_id, grant_id: h.attempt.grant_id, handoff_sha256: hash(&handoff), delegation_sha256: hash(&delegation), handoff_base64url: URL_SAFE_NO_PAD.encode(handoff), delegation_base64url: URL_SAFE_NO_PAD.encode(delegation), }) } fn open(&self) -> anyhow::Result<(Handoff, UpdateDelegation)> { fn bytes(raw: &str, limit: usize) -> anyhow::Result> { ensure!( raw.len() <= limit.div_ceil(3) * 4, "TIME_UPDATE_CONTEXT_SIZE" ); let decoded = URL_SAFE_NO_PAD.decode(raw)?; ensure!( !decoded.is_empty() && decoded.len() <= limit && URL_SAFE_NO_PAD.encode(&decoded) == raw, "TIME_UPDATE_CONTEXT_BASE64" ); Ok(decoded) } let hraw = bytes(&self.handoff_base64url, 32768)?; let draw = bytes(&self.delegation_base64url, 8192)?; let h: Handoff = serde_json::from_slice(&hraw)?; let d: UpdateDelegation = serde_json::from_slice(&draw)?; ensure!( h.bytes()? == hraw && serde_json::to_vec(&d)? == draw && Self::capture(&h, &d)? == *self, "TIME_UPDATE_CONTEXT_BINDING" ); Ok((h, d)) } } /// Call only AFTER the full original UpdateInflight proof/job/permit validation /// in the same existing Sync transaction/control lock. Changed bytes under the /// original grant are refused; no ON CONFLICT ignore or replacement. pub(crate) async fn retain_validated_updater_context( tx: &mut Transaction<'_, Postgres>, h: &Handoff, d: &UpdateDelegation, ) -> anyhow::Result<()> { let value = serde_json::to_value(RetainedUpdaterContext::capture(h, d)?)?; let existing=sqlx::query_scalar::<_,serde_json::Value>("SELECT data FROM audit_events WHERE tenant_id=$1 AND event_type='agent_update_original_context' AND data->>'grant_id'=$2 LIMIT 2") .bind(h.attempt.tenant_id).bind(h.attempt.grant_id.to_string()).fetch_all(&mut **tx).await?; ensure!( existing.len() <= 1, "TIME_UPDATE_DUPLICATE_ORIGINAL_CONTEXT" ); if let Some(old) = existing.first() { ensure!(*old == value, "TIME_UPDATE_ORIGINAL_CONTEXT_CHANGED"); return Ok(()); } sqlx::query("INSERT INTO audit_events VALUES($1,$2,'job-service','agent_update_original_context',$3,now())") .bind(h.attempt.tenant_id).bind(Uuid::new_v4()).bind(value).execute(&mut **tx).await?; Ok(()) } fn signed_bytes(s: &crate::State, raw: &[u8], signature: &[u8]) -> anyhow::Result<()> { use openssl::{ pkey::{Id, PKey}, sign::Verifier, }; let key = PKey::public_key_from_raw_bytes(&s.job_signer.public_key()?, Id::ED25519)?; ensure!( signature.len() == 64 && Verifier::new_without_digest(&key)?.verify_oneshot(signature, raw)?, "TIME_UPDATE_SIGNATURE" ); Ok(()) } fn original_role_context( c: &rmm_time_attestation::Context, current: u64, original: u64, boot: Uuid, image: &str, ) -> bool { c.role == rmm_time_attestation::Role::Updater && c.binding_schema == 2 && c.helper_image_sha256.is_none() && c.updater_image_sha256.as_deref() == Some(image) && current > original && c.connection_generation == original && c.windows_boot_id == boot } async fn original_updater_bridge( s: &crate::State, tx: &mut Transaction<'_, Postgres>, c: &rmm_time_attestation::Context, current: u64, ) -> anyhow::Result { ensure!( c.role == rmm_time_attestation::Role::Updater && c.binding_schema == 2 && c.helper_image_sha256.is_none() && current > c.connection_generation, "TIME_CURRENT_GENERATION_REQUIRED" ); // An exact single active job is required, not a historical latest grant. let rows=sqlx::query("SELECT j.payload,j.payload_hash,j.state,j.result,j.cancel_requested,j.start_reserved,p.payload AS plan_payload,p.plan_hash,z.authorization_id,z.plan_id,z.principal AS approver,g.grant_id,g.payload AS permit_payload,g.signature AS permit_signature FROM jobs j JOIN operations o USING(tenant_id,operation_id) JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests a ON a.tenant_id=o.tenant_id AND a.operation_id=o.operation_id JOIN operation_plans p ON p.tenant_id=a.tenant_id AND p.plan_id=a.plan_id JOIN execution_permits g ON g.tenant_id=j.tenant_id AND g.job_id=j.job_id AND g.attempt_id=j.attempt_id WHERE j.tenant_id=$1 AND j.agent_id=$2 AND j.state IN ('running','verifying') AND a.approval_state='approved' AND z.revoked_at IS NULL LIMIT 2 FOR SHARE OF j,z,a") .bind(c.tenant_id).bind(c.agent_id).fetch_all(&mut **tx).await?; ensure!(rows.len() == 1, "TIME_UPDATE_ONE_ACTIVE_ORIGINAL_JOB"); let row = &rows[0]; ensure!( row.get::, _>("result").is_none() && !row.get::("cancel_requested") && row.get::("start_reserved"), "TIME_UPDATE_ORIGINAL_JOB_CLOSED" ); let raw: Vec = row.get("payload"); ensure!(raw.len() <= 512 * 1024, "TIME_UPDATE_JOB_SIZE"); let job: JobPayload = serde_json::from_slice(&raw)?; let Action::UpdateAgent { update } = &job.action else { anyhow::bail!("TIME_UPDATE_ACTION_REQUIRED") }; ensure!( update.validate() && update.execution_identity() == Some("system") && job.execution_identity == "system" && job.max_runtime_seconds == 600 && encode(&job)? == raw && hash(&raw) == row.get::("payload_hash") && job.tenant_id == c.tenant_id && job.asset_id == c.asset_id && job.agent_id == c.agent_id && job.enrollment_generation == c.enrollment_generation && job.assignment_version == c.assignment_generation && update.updater.binary_sha256 == c.updater_image_sha256.as_deref().unwrap_or(""), "TIME_UPDATE_IMMUTABLE_JOB_BINDING" ); let plan_raw: Vec = row.get("plan_payload"); ensure!( plan_raw.len() <= rmm_domain::MAX_MESSAGE, "TIME_UPDATE_PLAN_SIZE" ); let plan: PlanPayload = serde_json::from_slice(&plan_raw)?; crate::agent_updates::validate_job_binding(&plan, &job) .map_err(|_| anyhow::anyhow!("TIME_UPDATE_PLAN_BINDING"))?; ensure!( encode(&plan)? == plan_raw && hash(&plan_raw) == row.get::("plan_hash") && row.get::("plan_id") == plan.plan_id, "TIME_UPDATE_APPROVED_PLAN" ); let grant: Vec = row.get("permit_payload"); let signature: Vec = row.get("permit_signature"); ensure!(grant.len() <= 32768, "TIME_UPDATE_PERMIT_SIZE"); signed_bytes(s, &grant, &signature)?; let permit: ExecutionPermitPayload = serde_json::from_slice(&grant)?; ensure!( encode(&permit)? == grant && permit.domain == "rmm.execution-permit" && permit.schema_version == 1 && permit.key_id == s.job_signer.key_id && permit.agent_update_plan_id == Some(plan.plan_id) && permit.tenant_id == job.tenant_id && permit.asset_id == job.asset_id && permit.agent_id == job.agent_id && permit.enrollment_generation == job.enrollment_generation && permit.assignment_version == job.assignment_version && permit.job_id == job.job_id && permit.attempt_id == job.attempt_id && permit.execution_identity == "system" && permit.grant_id == row.get::("grant_id") && permit.authorization_id == row.get::("authorization_id") && permit.plan_hash == hash(&plan_raw) && permit.job_payload_hash == hash(&raw) && permit.action == "update_agent" && permit.max_runtime_seconds == 600, "TIME_UPDATE_SIGNED_ORIGINAL_PERMIT" ); let contexts=sqlx::query_scalar::<_,serde_json::Value>("SELECT data FROM audit_events WHERE tenant_id=$1 AND event_type='agent_update_original_context' AND data->>'grant_id'=$2 LIMIT 2") .bind(c.tenant_id).bind(permit.grant_id.to_string()).fetch_all(&mut **tx).await?; ensure!(contexts.len() == 1, "TIME_UPDATE_ORIGINAL_CONTEXT_REQUIRED"); let retained: RetainedUpdaterContext = serde_json::from_value(contexts[0].clone())?; let (h, d) = retained.open()?; ensure!( update::handoff_matches_job(&h, &job) && original_role_context( c, current, h.connection_generation, h.boot_id, &h.updater_sha256 ) && h.attempt.plan_id == plan.plan_id && h.attempt.grant_id == permit.grant_id && h.attempt.authorization_id == permit.authorization_id && h.attempt.plan_sha256 == permit.plan_hash && d.updater.role == update::ParticipantRole::WindowsUpdater && d.original_helper.role == update::ParticipantRole::WindowsHelper && d.updater.image_sha256 == update.updater.binary_sha256 && d.prepared_at >= permit.not_before && d.prepared_at < permit.start_before, "TIME_UPDATE_ORIGINAL_HEADER_BINDING" ); let original = update::OriginalHelperRequest { job_bytes: &raw, permit_bytes: &grant, signature: &signature, plan_hash: &permit.plan_hash, authorization_id: permit.authorization_id, }; ensure!( h.attempt.original_request_sha256 == hash(&encode(&original)?), "TIME_UPDATE_ORIGINAL_REQUEST" ); // The CURRENT authoritative checkpoint must retain this exact inflight // acknowledgement. Never fall back to an older matching decision. let sync=sqlx::query("SELECT c.payload,c.signature,c.decision_id,c.journal_id,c.checkpoint,c.connection_generation,s.helper_journal_id,s.helper_checkpoint FROM agent_sync_state s JOIN sync_checkpoints c ON c.tenant_id=s.tenant_id AND c.agent_id=s.agent_id AND c.decision_id=s.decision_id WHERE s.tenant_id=$1 AND s.agent_id=$2") .bind(c.tenant_id).bind(c.agent_id).fetch_optional(&mut **tx).await?.context("TIME_UPDATE_SIGNED_ACK_REQUIRED")?; let decision_raw: Vec = sync.get("payload"); let decision_signature: Vec = sync.get("signature"); ensure!(decision_raw.len() <= 512 * 1024, "TIME_UPDATE_SYNC_SIZE"); signed_bytes(s, &decision_raw, &decision_signature)?; let decision: ReconcileDecisionPayload = serde_json::from_slice(&decision_raw)?; let now = Utc::now(); ensure!( encode(&decision)? == decision_raw && decision.valid_profile(decision.issued_at) && decision.issued_at <= now && decision.key_id == s.job_signer.key_id && !decision.ready && !decision.helper_ready && decision.tenant_id == c.tenant_id && decision.asset_id == c.asset_id && decision.agent_id == c.agent_id && decision.enrollment_generation == c.enrollment_generation && decision.assignment_version == c.assignment_generation && decision.boot_id == h.boot_id && decision.connection_generation >= h.connection_generation && decision.connection_generation <= current && decision.decision_id == sync.get::("decision_id") && decision.journal_id == sync.get::("journal_id") && decision.journal_id == h.agent_journal_id && Some(h.helper_journal_id) == sync.get::, _>("helper_journal_id") && decision.helper_journal_id == Some(h.helper_journal_id) && u64::try_from(sync.get::("checkpoint"))? == decision.checkpoint && u64::try_from(sync.get::("helper_checkpoint"))? == decision.helper_checkpoint && u64::try_from(sync.get::("connection_generation"))? == decision.connection_generation, "TIME_UPDATE_CURRENT_SIGNED_ACK_BINDING" ); let attempts = decision .attempts .iter() .filter(|a| a.job_id == job.job_id && a.attempt_id == job.attempt_id) .collect::>(); ensure!(attempts.len() == 1, "TIME_UPDATE_ORIGINAL_ACK_ATTEMPT"); let ack = attempts[0]; let inflight = ack .update_inflight .as_ref() .context("TIME_UPDATE_INFLIGHT_REQUIRED")?; ensure!( ack.job_payload_hash == hash(&raw) && ack.grant_id == Some(permit.grant_id) && ack.authorization_id == Some(permit.authorization_id) && ack.plan_hash.as_deref() == Some(permit.plan_hash.as_str()) && ack.action == "update_agent" && ack.execution_identity == "system" && ack.outcome_state == "running" && ack.outcome_bytes.is_empty() && ack.outcome_sha256.is_none() && ack.previous_outcome_sha256.is_none() && ack.original_boot_id == Some(h.boot_id) && !ack.unlock && ack.reason == "AGENT_UPDATE_INFLIGHT" && inflight.handoff_sha256 == retained.handoff_sha256 && inflight.delegation_sha256 == retained.delegation_sha256 && inflight.owner_nonce == h.owner_nonce && inflight.finish_before == h.finish_before && update::digest(&inflight.head_sha256) && h.finish_before == h.consumed_at .checked_add(600) .context("TIME_UPDATE_ORIGINAL_DEADLINE")? && u64::try_from(now.timestamp())? >= h.consumed_at && u64::try_from(now.timestamp())? < h.finish_before, "TIME_UPDATE_EXACT_ORIGINAL_ACK_AND_DEADLINE" ); let approver: String = row.get("approver"); let mut actors = vec![plan.principal.as_str(), approver.as_str()]; actors.sort(); actors.dedup(); let locked=sqlx::query_scalar::<_,String>("SELECT principal FROM memberships WHERE tenant_id=$1 AND principal=ANY($2) AND revoked_at IS NULL FOR SHARE") .bind(c.tenant_id).bind(&actors).fetch_all(&mut **tx).await?; ensure!(locked.len() == actors.len(), "TIME_UPDATE_CURRENT_ACTORS"); for actor in actors { for permission in ["updates:apply", "system:execute"] { crate::permissions::require(tx, actor, permission) .await .map_err(|_| anyhow::anyhow!("TIME_UPDATE_CURRENT_PERMISSION"))?; } } Ok(h.finish_before) } #[cfg(test)] mod original_generation_tests { use super::*; fn retained_fixture() -> RetainedUpdaterContext { use serde_json::json; let id = Uuid::new_v4(); let old = "11".repeat(32); let new = "22".repeat(32); let roles = [ "agent_binary", "helper_binary", "windows_settings", "windows_pin", "windows_time_profile", ]; let h:Handoff=serde_json::from_value(json!({"schema_version":2, "attempt":{"tenant_id":id,"asset_id":id,"agent_id":id,"enrollment_generation":1,"assignment_version":1, "plan_id":id,"plan_sha256":old,"job_id":id,"attempt_id":id,"job_payload_sha256":old, "grant_id":id,"authorization_id":id,"original_request_sha256":old,"original_start_witness_sha256":old}, "agent_journal_id":id,"helper_journal_id":id,"helper_checkpoint":1,"previous_decision_id":id, "boot_id":id,"connection_generation":7,"owner_nonce":id,"updater_sha256":old,"updater_policy_sha256":old, "predecessor_record_sha256":old,"retained_state_sha256":old,"ledger_identity_sha256":old,"staged_files_sha256":old, "predecessor":{"manifest_sha256":old,"agent_sha256":old,"helper_sha256":old,"pin_sha256":old}, "target":{"manifest_sha256":new,"agent_sha256":new,"helper_sha256":new,"pin_sha256":new}, "pin_transition":"windows_code_pair_clock_v1","pin_transition_sha256":old, "files":roles.iter().map(|role|json!({"role":role,"old_sha256":old,"new_sha256":new})).collect::>(), "stop_set":["windows_agent","windows_helper"],"consumed_at":100,"finish_before":700})).unwrap(); let d: UpdateDelegation = serde_json::from_value( json!({"schema_version":1,"handoff_sha256":hash(&h.bytes().unwrap()), "owner_nonce":id,"boot_id":id,"prepared_at":"1970-01-01T00:01:40Z", "updater":{"role":"windows_updater","pid":2,"birth":1,"image_sha256":old, "security_principal":"S-1-5-18","service_instance_sha256":old}, "original_helper":{"role":"windows_helper","pid":3,"birth":1,"image_sha256":old, "security_principal":"S-1-5-18","service_instance_sha256":old}}), ) .unwrap(); RetainedUpdaterContext::capture(&h, &d).unwrap() } #[test] fn retained_original_context_binds_canonical_header_delegation_and_grant_without_reconstruction() { let original = retained_fixture(); let (h, d) = original.open().unwrap(); assert_eq!(h.connection_generation, 7); assert_eq!(h.finish_before, 700); assert_eq!(h.owner_nonce, d.owner_nonce); let mut changed = original.clone(); changed.grant_id = Uuid::new_v4(); assert!(changed.open().is_err()); let mut changed = original.clone(); changed.handoff_base64url.push('='); assert!(changed.open().is_err()); let mut changed = original.clone(); let mut raw = vec![b' ']; raw.extend_from_slice(&h.bytes().unwrap()); changed.handoff_base64url = URL_SAFE_NO_PAD.encode(raw); assert!(changed.open().is_err()); let mut changed = original; let mut other = d; other.owner_nonce = Uuid::new_v4(); let raw = serde_json::to_vec(&other).unwrap(); changed.delegation_sha256 = hash(&raw); changed.delegation_base64url = URL_SAFE_NO_PAD.encode(raw); assert!(changed.open().is_err()); } #[test] fn only_exact_original_updater_generation_can_bridge_current_agent_epoch() { use rmm_time_attestation::{Context, Role}; let boot = Uuid::new_v4(); let image = "ab".repeat(32); let mut c = Context { tenant_id: Uuid::new_v4(), asset_id: Uuid::new_v4(), agent_id: Uuid::new_v4(), enrollment_generation: 1, assignment_generation: 1, connection_generation: 7, windows_boot_id: boot, verifier_incarnation: Uuid::new_v4(), role: Role::Updater, helper_image_sha256: None, binding_schema: 2, updater_image_sha256: Some(image.clone()), }; c.validate().unwrap(); assert!(original_role_context(&c, 8, 7, boot, &image)); assert!(!original_role_context(&c, 8, 6, boot, &image)); assert!(!original_role_context(&c, 7, 7, boot, &image)); assert!(!original_role_context(&c, 6, 7, boot, &image)); assert!(!original_role_context(&c, 8, 7, Uuid::new_v4(), &image)); assert!(!original_role_context(&c, 8, 7, boot, &"cd".repeat(32))); c.role = Role::Agent; c.binding_schema = 1; c.updater_image_sha256 = None; c.validate().unwrap(); assert!(!original_role_context(&c, 8, 7, boot, &image)); c.role = Role::SystemHelper; c.helper_image_sha256 = Some(image.clone()); c.validate().unwrap(); assert!(!original_role_context(&c, 8, 7, boot, &image)); c.role = Role::Updater; c.binding_schema = 2; c.updater_image_sha256 = Some(image.clone()); assert!(c.validate().is_err()); assert!(!original_role_context(&c, 8, 7, boot, &image)); } }