Deploy reviewed Windows sync alignment with schema 20 server
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
Bind the administrative connection-205 review to original signed history and preserve closed readiness. Include the qualified server dependency closure, UI review, native ARM64 build provenance, and guarded deployment evidence. Migration, API/gateway replacement and TLS checks passed with unchanged job authority, protected mounts and time/database services; native Windows receipt application remains separate.
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
//! 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,
|
||||
@@ -7,14 +8,25 @@ use axum::{
|
||||
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;
|
||||
@@ -126,9 +138,16 @@ async fn issue(
|
||||
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 FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND revoked_at IS NULL FOR SHARE")
|
||||
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::<uuid::Uuid, _>("asset_id") == c.asset_id
|
||||
@@ -136,8 +155,6 @@ async fn issue(
|
||||
== Some(c.enrollment_generation)
|
||||
&& u64::try_from(row.get::<i64, _>("assignment_version")).ok()
|
||||
== Some(c.assignment_generation)
|
||||
&& u64::try_from(row.get::<i64, _>("connection_generation")).ok()
|
||||
== Some(c.connection_generation)
|
||||
&& row.get::<Option<uuid::Uuid>, _>("connection_boot_id") == Some(c.windows_boot_id)
|
||||
&& row
|
||||
.get::<serde_json::Value, _>("capabilities")
|
||||
@@ -146,14 +163,476 @@ async fn issue(
|
||||
if !same {
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
let current_generation = u64::try_from(row.get::<i64, _>("connection_generation"))
|
||||
.map_err(|_| StatusCode::CONFLICT)?;
|
||||
let original_deadline = if current_generation != c.connection_generation {
|
||||
if row.get::<bool, _>("sequence_regressed") || row.get::<bool, _>("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<Self> {
|
||||
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<Vec<u8>> {
|
||||
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<u64> {
|
||||
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::<Option<serde_json::Value>, _>("result").is_none()
|
||||
&& !row.get::<bool, _>("cancel_requested")
|
||||
&& row.get::<bool, _>("start_reserved"),
|
||||
"TIME_UPDATE_ORIGINAL_JOB_CLOSED"
|
||||
);
|
||||
let raw: Vec<u8> = 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::<String, _>("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<u8> = 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::<String, _>("plan_hash")
|
||||
&& row.get::<Uuid, _>("plan_id") == plan.plan_id,
|
||||
"TIME_UPDATE_APPROVED_PLAN"
|
||||
);
|
||||
let grant: Vec<u8> = row.get("permit_payload");
|
||||
let signature: Vec<u8> = 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::<Uuid, _>("grant_id")
|
||||
&& permit.authorization_id == row.get::<Uuid, _>("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<u8> = sync.get("payload");
|
||||
let decision_signature: Vec<u8> = 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::<Uuid, _>("decision_id")
|
||||
&& decision.journal_id == sync.get::<Uuid, _>("journal_id")
|
||||
&& decision.journal_id == h.agent_journal_id
|
||||
&& Some(h.helper_journal_id) == sync.get::<Option<Uuid>, _>("helper_journal_id")
|
||||
&& decision.helper_journal_id == Some(h.helper_journal_id)
|
||||
&& u64::try_from(sync.get::<i64, _>("checkpoint"))? == decision.checkpoint
|
||||
&& u64::try_from(sync.get::<i64, _>("helper_checkpoint"))?
|
||||
== decision.helper_checkpoint
|
||||
&& u64::try_from(sync.get::<i64, _>("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::<Vec<_>>();
|
||||
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::<Vec<_>>(),
|
||||
"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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,11 +242,14 @@ async fn issue(
|
||||
let health_key_id = hash(&health_public);
|
||||
let (header, journal) =
|
||||
update::verify_inflight_proof(&input.proof, health_public).map_err(|_| denied())?;
|
||||
require(journal.phase() == Phase::ServicesStarted)?;
|
||||
let rollback = journal.phase() == Phase::RollbackServicesStarted;
|
||||
require(journal.phase() == Phase::ServicesStarted || rollback)?;
|
||||
let decoded = input.proof.decode().map_err(|_| denied())?;
|
||||
let last: Event = serde_json::from_slice(decoded.events.last().ok_or_else(denied)?)?;
|
||||
let Evidence::ServicesStarted { services, .. } = &last.evidence else {
|
||||
return Err(denied());
|
||||
let services = match &last.evidence {
|
||||
Evidence::ServicesStarted { services, .. } if !rollback => services,
|
||||
Evidence::RollbackServicesStarted { services, .. } if rollback => services,
|
||||
_ => return Err(denied()),
|
||||
};
|
||||
let started_at = last.observed_at;
|
||||
let (applied_request, applied_raw) =
|
||||
@@ -485,8 +488,9 @@ async fn issue(
|
||||
hash(&confirming_raw),
|
||||
inventory_hash,
|
||||
))?);
|
||||
let cached: Option<Value> = sqlx::query_scalar("SELECT data FROM audit_events WHERE event_type='agent_update_health' AND data->>'grant_id'=$1 ORDER BY created_at LIMIT 1")
|
||||
.bind(header.attempt.grant_id.to_string()).fetch_optional(&mut *tx).await?;
|
||||
let code_generation = if rollback { "predecessor" } else { "candidate" };
|
||||
let cached: Option<Value> = sqlx::query_scalar("SELECT data FROM audit_events WHERE event_type='agent_update_health' AND data->>'grant_id'=$1 AND COALESCE(data->>'code_generation','candidate')=$2 ORDER BY created_at LIMIT 1")
|
||||
.bind(header.attempt.grant_id.to_string()).bind(code_generation).fetch_optional(&mut *tx).await?;
|
||||
if let Some(cached) = cached {
|
||||
require(
|
||||
cached["witness_sha256"] == witness_hash && cached["health_key_id"] == health_key_id,
|
||||
@@ -495,8 +499,14 @@ async fn issue(
|
||||
journal
|
||||
.prepare(
|
||||
issued_at,
|
||||
Evidence::HealthVerified {
|
||||
receipt: original.clone(),
|
||||
if rollback {
|
||||
Evidence::RollbackHealthVerified {
|
||||
receipt: original.clone(),
|
||||
}
|
||||
} else {
|
||||
Evidence::HealthVerified {
|
||||
receipt: original.clone(),
|
||||
}
|
||||
},
|
||||
)
|
||||
.map_err(|_| denied())?;
|
||||
@@ -517,8 +527,14 @@ async fn issue(
|
||||
journal
|
||||
.prepare(
|
||||
issued_at,
|
||||
Evidence::HealthVerified {
|
||||
receipt: signed.clone(),
|
||||
if rollback {
|
||||
Evidence::RollbackHealthVerified {
|
||||
receipt: signed.clone(),
|
||||
}
|
||||
} else {
|
||||
Evidence::HealthVerified {
|
||||
receipt: signed.clone(),
|
||||
}
|
||||
},
|
||||
)
|
||||
.map_err(|_| denied())?;
|
||||
@@ -526,7 +542,7 @@ async fn issue(
|
||||
.bind(tenant).bind(Uuid::new_v4()).bind(format!("agent:{agent}"))
|
||||
.bind(json!({"grant_id":header.attempt.grant_id,"job_id":header.attempt.job_id,"attempt_id":header.attempt.attempt_id,
|
||||
"handoff_sha256":input.proof.delegation.handoff_sha256,"head_sha256":input.proof.head_sha256,"event_count":decoded.events.len(),
|
||||
"health_key_id":health_key_id,"witness_sha256":witness_hash,"receipt":signed,"evidence_only":true,"ready":false}))
|
||||
"health_key_id":health_key_id,"witness_sha256":witness_hash,"receipt":signed,"evidence_only":true,"ready":false,"code_generation":code_generation}))
|
||||
.execute(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(signed))
|
||||
|
||||
@@ -29,6 +29,7 @@ mod update_artifact_store;
|
||||
mod windows_checkpoint_review;
|
||||
mod windows_echo_probe;
|
||||
mod windows_echo_completion;
|
||||
mod windows_sync_alignment;
|
||||
mod windows_msi_catalog;
|
||||
mod windows_policy;
|
||||
|
||||
@@ -189,6 +190,7 @@ async fn main() -> Result<()> {
|
||||
routes = windows_checkpoint_review::routes(routes);
|
||||
routes = windows_echo_probe::routes(routes);
|
||||
routes = windows_echo_completion::routes(routes);
|
||||
routes = windows_sync_alignment::routes(routes);
|
||||
}
|
||||
routes = routes
|
||||
.route("/auth/config", get(auth::configuration))
|
||||
|
||||
@@ -691,6 +691,11 @@ pub async fn reconcile(
|
||||
"UPDATE_INFLIGHT_PREFIX_REGRESSION"
|
||||
);
|
||||
}
|
||||
// Retain the already fully validated original public context once
|
||||
// in this same control-lock transaction. The clock bridge never
|
||||
// infers the original generation/deadline from a historical grant.
|
||||
crate::agent_time::retain_validated_updater_context(tx, &header, &proof.delegation)
|
||||
.await?;
|
||||
let revision = local.revision.max(row.get::<i64, _>("revision") as u64);
|
||||
sqlx::query(
|
||||
"UPDATE jobs SET state='running',revision=GREATEST(revision,$2) WHERE job_id=$1",
|
||||
|
||||
@@ -45,6 +45,13 @@ struct SystemScope {
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
|
||||
)]
|
||||
allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
|
||||
#[serde(default, deserialize_with = "strict_optional_reboot")]
|
||||
allow_reboot: Option<bool>,
|
||||
}
|
||||
fn strict_optional_reboot<'de, D: serde::Deserializer<'de>>(
|
||||
d: D,
|
||||
) -> Result<Option<bool>, D::Error> {
|
||||
bool::deserialize(d).map(Some)
|
||||
}
|
||||
fn strict_optional_hashes<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
|
||||
where
|
||||
@@ -124,6 +131,7 @@ impl SystemScope {
|
||||
capabilities: &[String],
|
||||
allow_msi: bool,
|
||||
allow_scripts: bool,
|
||||
allow_reboot: bool,
|
||||
) -> bool {
|
||||
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
|
||||
self.valid()
|
||||
@@ -149,6 +157,12 @@ impl SystemScope {
|
||||
&& (1..=self.max_runtime_seconds).contains(&job.max_runtime_seconds)
|
||||
&& (1..=65536).contains(&job.max_output_bytes)
|
||||
&& match &job.action {
|
||||
Action::Reboot { .. } => {
|
||||
allow_reboot
|
||||
&& self.allow_reboot == Some(true)
|
||||
&& rmm_domain::windows_reboot::supported(job)
|
||||
&& job.action.available_for("system", capabilities)
|
||||
}
|
||||
Action::SetServiceState { unit, state } => {
|
||||
self.allowed_services.contains(unit)
|
||||
&& matches!(state.as_str(), "running" | "stopped")
|
||||
@@ -188,17 +202,19 @@ impl SystemScope {
|
||||
}
|
||||
impl SystemPolicy {
|
||||
fn valid(&self, now: DateTime<Utc>) -> bool {
|
||||
matches!(self.schema_version, 1..=3)
|
||||
matches!(self.schema_version, 1..=4)
|
||||
&& (self.schema_version >= 2
|
||||
|| self
|
||||
.scopes
|
||||
.iter()
|
||||
.all(|scope| scope.allowed_msi_recipe_sha256.is_none()))
|
||||
&& (self.schema_version == 3
|
||||
&& (self.schema_version >= 3
|
||||
|| self
|
||||
.scopes
|
||||
.iter()
|
||||
.all(|scope| scope.allowed_script_profiles.is_none()))
|
||||
&& (self.schema_version == 4
|
||||
|| self.scopes.iter().all(|scope| scope.allow_reboot.is_none()))
|
||||
&& self.profile == "development"
|
||||
&& self.expires_at > now
|
||||
&& !self.scopes.is_empty()
|
||||
@@ -219,7 +235,8 @@ impl SystemPolicy {
|
||||
job,
|
||||
capabilities,
|
||||
self.schema_version >= 2,
|
||||
self.schema_version == 3,
|
||||
self.schema_version >= 3,
|
||||
self.schema_version == 4,
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -363,6 +380,54 @@ pub async fn authorize(
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
#[test]
|
||||
fn reboot_needs_v4_independent_opt_in_capabilities_and_exact_fixed_window() {
|
||||
let (mut p, mut job, mut caps) = fixture();
|
||||
job.action = Action::Reboot {
|
||||
reason: "Einzelne Windows-MVP-Abnahme".into(),
|
||||
dependency_group: "windows-mvp".into(),
|
||||
reconnect_timeout_seconds: 180,
|
||||
};
|
||||
job.max_runtime_seconds = 60;
|
||||
p.scopes[0].max_runtime_seconds = 120;
|
||||
caps.extend(
|
||||
[
|
||||
"reboot",
|
||||
"system:reboot",
|
||||
rmm_domain::windows_reboot::CAPABILITY,
|
||||
]
|
||||
.map(str::to_string),
|
||||
);
|
||||
for version in 1..=4 {
|
||||
p.schema_version = version;
|
||||
assert!(!p.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
p.scopes[0].allow_reboot = Some(true);
|
||||
for version in 1..=3 {
|
||||
p.schema_version = version;
|
||||
assert!(!p.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
p.schema_version = 4;
|
||||
assert!(p.permits("selected", &job, &caps, Utc::now()));
|
||||
assert!(!p.permits("foreign", &job, &caps, Utc::now()));
|
||||
let complete = caps.clone();
|
||||
caps.retain(|c| c != "system:reboot");
|
||||
assert!(!p.permits("selected", &job, &caps, Utc::now()));
|
||||
caps = complete;
|
||||
job.execution_identity = "agent_service".into();
|
||||
assert!(!p.permits("selected", &job, &caps, Utc::now()));
|
||||
job.execution_identity = "system".into();
|
||||
if let Action::Reboot {
|
||||
reconnect_timeout_seconds,
|
||||
..
|
||||
} = &mut job.action
|
||||
{
|
||||
*reconnect_timeout_seconds = 181;
|
||||
}
|
||||
assert!(!p.permits("selected", &job, &caps, Utc::now()));
|
||||
let invalid = json!({"schema_version":4,"profile":"development","expires_at":Utc::now(),"scopes":[{"allow_reboot":null}]});
|
||||
assert!(serde_json::from_value::<SystemPolicy>(invalid).is_err());
|
||||
}
|
||||
fn fixture() -> (SystemPolicy, JobPayload, Vec<String>) {
|
||||
let id = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
|
||||
@@ -0,0 +1,512 @@
|
||||
//! Exact connection-205 interactive administrative closure. No job/readiness writes.
|
||||
use crate::{auth::Principal, jobs::Error, windows_checkpoint_review::access};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
routing::{get, post},
|
||||
};
|
||||
use chrono::{Duration, SubsecRound, Utc};
|
||||
use openssl::{
|
||||
pkey::{Id, PKey},
|
||||
sign::Verifier,
|
||||
};
|
||||
use prost::Message;
|
||||
use rmm_domain::{
|
||||
checkpoint_repair::{SignedReceipt, inventory_sha256},
|
||||
jobs::{ExecutionPermitPayload, JobPayload, PlanPayload, encode, hash},
|
||||
reconciliation::ReconcileDecisionPayload,
|
||||
windows_echo_completion::{Receipt as Completion, successful_outcome},
|
||||
windows_echo_probe::{AGENT, ASSET, TENANT, TEST_PRINCIPAL},
|
||||
windows_sync_alignment::{self as profile, Receipt, Witness},
|
||||
};
|
||||
use rmm_protocol::{JobOffer, SyncRequest};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
use uuid::Uuid;
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
fn mismatch() -> Error {
|
||||
Error(StatusCode::CONFLICT, "WINDOWS_SYNC_ALIGNMENT_MISMATCH")
|
||||
}
|
||||
fn browser(p: &Principal) -> Result<&str> {
|
||||
if p.name != TEST_PRINCIPAL
|
||||
|| p.tenant != TENANT
|
||||
|| !p.testsimulation
|
||||
|| !p.operator
|
||||
|| p.identity.is_some()
|
||||
|| p.scopes.is_some()
|
||||
|| p.csrf.is_none()
|
||||
{
|
||||
return Err(Error(StatusCode::FORBIDDEN, "DEV_TEST_WEBUI_REQUIRED"));
|
||||
}
|
||||
p.session_hash
|
||||
.as_deref()
|
||||
.ok_or(Error(StatusCode::FORBIDDEN, "DEV_TEST_WEBUI_REQUIRED"))
|
||||
}
|
||||
pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
|
||||
r.route(
|
||||
"/api/v1/tenants/{tenant}/windows-sync-alignment",
|
||||
get(read).post(submit),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/windows-sync-alignment/{request}/confirm",
|
||||
post(confirm),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/windows-sync-alignment/{request}/receipt",
|
||||
get(download),
|
||||
)
|
||||
}
|
||||
fn verify(s: &crate::State, bytes: &[u8], signature: &[u8]) -> Result<()> {
|
||||
let key = PKey::public_key_from_raw_bytes(&s.job_signer.public_key()?, Id::ED25519)
|
||||
.map_err(|_| mismatch())?;
|
||||
if bytes.len() > profile::MAX_WITNESS_BYTES + 8192
|
||||
|| signature.len() != 64
|
||||
|| !Verifier::new_without_digest(&key)
|
||||
.map_err(|_| mismatch())?
|
||||
.verify_oneshot(signature, bytes)
|
||||
.map_err(|_| mismatch())?
|
||||
{
|
||||
return Err(mismatch());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn original(w: &Witness, i: usize) -> Result<(SyncRequest, ReconcileDecisionPayload)> {
|
||||
let raw = &w.original_requests[i];
|
||||
let r = SyncRequest::decode(raw.as_slice()).map_err(|_| mismatch())?;
|
||||
let d: ReconcileDecisionPayload =
|
||||
serde_json::from_slice(&w.original_responses[i].decision_bytes)?;
|
||||
let (id, rid, cp, hcp) = if i == 0 {
|
||||
(profile::FIRST, profile::FIRST_REQUEST, 10135, 134)
|
||||
} else {
|
||||
(profile::SECOND, profile::SECOND_REQUEST, 10137, 135)
|
||||
};
|
||||
if r.encode_to_vec() != *raw
|
||||
|| r.request_id != rid.to_string()
|
||||
|| r.journal_id != w.agent_journal_id.to_string()
|
||||
|| r.helper_journal_id != w.helper_journal_id.to_string()
|
||||
|| r.assignment_version != 1
|
||||
|| r.checkpoint != cp
|
||||
|| r.helper_checkpoint != hcp
|
||||
|| !r.journal_complete
|
||||
|| (i == 1 && r.previous_decision_id != profile::FIRST.to_string())
|
||||
|| !d.valid_profile(d.issued_at)
|
||||
|| d.decision_id != id
|
||||
|| d.request_id != rid
|
||||
|| d.request_hash != hash(raw)
|
||||
|| (d.tenant_id, d.asset_id, d.agent_id) != (TENANT, ASSET, AGENT)
|
||||
|| d.enrollment_generation != 1
|
||||
|| d.assignment_version != 1
|
||||
|| d.boot_id != profile::BOOT
|
||||
|| d.connection_generation != 205
|
||||
|| d.journal_id != w.agent_journal_id
|
||||
|| d.helper_journal_id != Some(w.helper_journal_id)
|
||||
|| d.checkpoint != cp
|
||||
|| d.helper_checkpoint != hcp
|
||||
|| d.key_id != w.verification_key_id
|
||||
|| d.attempts.iter().any(|a| {
|
||||
a.update_inflight.is_some()
|
||||
|| ![
|
||||
(profile::ECHO_JOB, profile::ECHO_ATTEMPT),
|
||||
(profile::EXPIRED_JOB, profile::EXPIRED_ATTEMPT),
|
||||
]
|
||||
.contains(&(a.job_id, a.attempt_id))
|
||||
})
|
||||
{
|
||||
return Err(mismatch());
|
||||
}
|
||||
Ok((r, d))
|
||||
}
|
||||
async fn validate(tx: &mut Transaction<'_, Postgres>, s: &crate::State, w: &Witness) -> Result<()> {
|
||||
if !w.valid()
|
||||
|| w.verification_key_id != s.job_signer.key_id
|
||||
|| hex::encode(s.job_signer.public_key()?) != w.verification_public_key_hex
|
||||
{
|
||||
return Err(mismatch());
|
||||
}
|
||||
crate::agent_service::control_lock(tx, TENANT, AGENT).await?;
|
||||
let dev=sqlx::query("SELECT asset_id,enrollment_generation,assignment_version,connection_generation,connection_boot_id,revoked_at,sequence_regressed,sync_recovery_required FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 FOR UPDATE").bind(TENANT).bind(AGENT).fetch_one(&mut **tx).await?;
|
||||
if dev.get::<Uuid, _>("asset_id") != ASSET
|
||||
|| dev.get::<i64, _>("enrollment_generation") != 1
|
||||
|| dev.get::<i64, _>("assignment_version") != 1
|
||||
|| dev.get::<i64, _>("connection_generation") != 205
|
||||
|| dev.get::<Option<Uuid>, _>("connection_boot_id") != Some(profile::BOOT)
|
||||
|| dev
|
||||
.get::<Option<chrono::DateTime<Utc>>, _>("revoked_at")
|
||||
.is_some()
|
||||
|| dev.get::<bool, _>("sequence_regressed")
|
||||
|| dev.get::<bool, _>("sync_recovery_required")
|
||||
{
|
||||
return Err(mismatch());
|
||||
}
|
||||
let state=sqlx::query("SELECT journal_id,checkpoint,decision_id,helper_journal_id,helper_checkpoint FROM agent_sync_state WHERE tenant_id=$1 AND agent_id=$2 FOR SHARE").bind(TENANT).bind(AGENT).fetch_one(&mut **tx).await?;
|
||||
if state.get::<Uuid, _>("journal_id") != w.agent_journal_id
|
||||
|| state.get::<i64, _>("checkpoint") != 10137
|
||||
|| state.get::<Uuid, _>("decision_id") != profile::SECOND
|
||||
|| state.get::<Option<Uuid>, _>("helper_journal_id") != Some(w.helper_journal_id)
|
||||
|| state.get::<i64, _>("helper_checkpoint") != 135
|
||||
{
|
||||
return Err(mismatch());
|
||||
}
|
||||
for i in 0..2 {
|
||||
let (r, d) = original(w, i)?;
|
||||
verify(
|
||||
s,
|
||||
&w.original_responses[i].decision_bytes,
|
||||
&w.original_responses[i].signature,
|
||||
)?;
|
||||
let row=sqlx::query("SELECT request_hash,journal_id,checkpoint,connection_generation,payload,signature FROM sync_checkpoints WHERE tenant_id=$1 AND agent_id=$2 AND decision_id=$3 AND request_id=$4").bind(TENANT).bind(AGENT).bind(d.decision_id).bind(d.request_id).fetch_one(&mut **tx).await?;
|
||||
if row.get::<String, _>("request_hash") != hash(&r.encode_to_vec())
|
||||
|| row.get::<Uuid, _>("journal_id") != w.agent_journal_id
|
||||
|| row.get::<i64, _>("checkpoint")
|
||||
!= i64::try_from(d.checkpoint).map_err(|_| mismatch())?
|
||||
|| row.get::<i64, _>("connection_generation") != 205
|
||||
|| row.get::<Vec<u8>, _>("payload") != w.original_responses[i].decision_bytes
|
||||
|| row.get::<Vec<u8>, _>("signature") != w.original_responses[i].signature
|
||||
{
|
||||
return Err(mismatch());
|
||||
}
|
||||
}
|
||||
validate_jobs(tx, s, w).await
|
||||
}
|
||||
async fn validate_jobs(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
s: &crate::State,
|
||||
w: &Witness,
|
||||
) -> Result<()> {
|
||||
let jobs=sqlx::query("SELECT j.job_id,j.attempt_id,j.operation_id,j.asset_id,j.state,j.payload,j.payload_hash,j.result,a.authorization_id FROM jobs j JOIN authorizations a ON a.tenant_id=j.tenant_id AND a.operation_id=j.operation_id WHERE j.tenant_id=$1 AND j.agent_id=$2 ORDER BY j.job_id FOR SHARE OF j,a").bind(TENANT).bind(AGENT).fetch_all(&mut **tx).await?;
|
||||
let total: i64 =
|
||||
sqlx::query_scalar("SELECT count(*) FROM jobs WHERE tenant_id=$1 AND agent_id=$2")
|
||||
.bind(TENANT)
|
||||
.bind(AGENT)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
if jobs.len() != 2 || total != 2 {
|
||||
return Err(mismatch());
|
||||
}
|
||||
let echo = jobs
|
||||
.iter()
|
||||
.find(|r| r.get::<Uuid, _>("job_id") == profile::ECHO_JOB)
|
||||
.ok_or_else(mismatch)?;
|
||||
let expired = jobs
|
||||
.iter()
|
||||
.find(|r| r.get::<Uuid, _>("job_id") == profile::EXPIRED_JOB)
|
||||
.ok_or_else(mismatch)?;
|
||||
for (row, raw, id, attempt, state) in [
|
||||
(
|
||||
echo,
|
||||
&w.echo_offer,
|
||||
profile::ECHO_JOB,
|
||||
profile::ECHO_ATTEMPT,
|
||||
"succeeded",
|
||||
),
|
||||
(
|
||||
expired,
|
||||
&w.expired_offer,
|
||||
profile::EXPIRED_JOB,
|
||||
profile::EXPIRED_ATTEMPT,
|
||||
"expired",
|
||||
),
|
||||
] {
|
||||
let offer = JobOffer::decode(raw.as_slice()).map_err(|_| mismatch())?;
|
||||
let j: JobPayload = serde_json::from_slice(&offer.payload_bytes)?;
|
||||
if offer.encode_to_vec() != *raw
|
||||
|| offer.job_id != id.to_string()
|
||||
|| offer.attempt_id != attempt.to_string()
|
||||
|| row.get::<Uuid, _>("attempt_id") != attempt
|
||||
|| row.get::<Uuid, _>("asset_id") != ASSET
|
||||
|| row.get::<String, _>("state") != state
|
||||
|| row.get::<Vec<u8>, _>("payload") != offer.payload_bytes
|
||||
|| row.get::<String, _>("payload_hash") != hash(&offer.payload_bytes)
|
||||
|| offer.job_payload_hash != hash(&offer.payload_bytes)
|
||||
|| offer.authorization_id != row.get::<Uuid, _>("authorization_id").to_string()
|
||||
|| (j.tenant_id, j.asset_id, j.agent_id, j.job_id, j.attempt_id)
|
||||
!= (TENANT, ASSET, AGENT, id, attempt)
|
||||
|| j.enrollment_generation != 1
|
||||
|| j.assignment_version != 1
|
||||
|| j.execution_identity != "agent_service"
|
||||
{
|
||||
return Err(mismatch());
|
||||
}
|
||||
let plan_raw: Option<Vec<u8>> = sqlx::query_scalar("SELECT p.payload FROM authorizations a JOIN operation_plans p ON p.tenant_id=a.tenant_id AND p.plan_id=a.plan_id AND p.plan_hash=a.plan_hash WHERE a.tenant_id=$1 AND a.authorization_id=$2 AND a.operation_id=$3 AND a.plan_hash=$4 AND a.revoked_at IS NULL AND a.principal=$5 AND a.approval_origin='dev_test_browser_simulation' AND a.testsimulation")
|
||||
.bind(TENANT).bind(row.get::<Uuid,_>("authorization_id")).bind(row.get::<Uuid,_>("operation_id")).bind(&offer.plan_hash).bind(TEST_PRINCIPAL).fetch_optional(&mut **tx).await?;
|
||||
let plan_raw = plan_raw.ok_or_else(mismatch)?;
|
||||
let plan: PlanPayload = serde_json::from_slice(&plan_raw)?;
|
||||
if hash(&plan_raw) != offer.plan_hash
|
||||
|| encode(&plan)? != plan_raw
|
||||
|| plan.tenant_id != TENANT
|
||||
|| plan.jobs.len() != 1
|
||||
|| plan.jobs[0].payload != j
|
||||
|| plan.jobs[0].job_payload_hash != offer.job_payload_hash
|
||||
{
|
||||
return Err(mismatch());
|
||||
}
|
||||
}
|
||||
let grant_count:i64=sqlx::query_scalar("SELECT count(*) FROM execution_permits p JOIN jobs j ON j.tenant_id=p.tenant_id AND j.job_id=p.job_id WHERE j.tenant_id=$1 AND j.agent_id=$2").bind(TENANT).bind(AGENT).fetch_one(&mut **tx).await?;
|
||||
if grant_count != 1 {
|
||||
return Err(mismatch());
|
||||
}
|
||||
let grant=sqlx::query("SELECT grant_id,payload,signature FROM execution_permits WHERE tenant_id=$1 AND job_id=$2 AND attempt_id=$3").bind(TENANT).bind(profile::ECHO_JOB).bind(profile::ECHO_ATTEMPT).fetch_one(&mut **tx).await?;
|
||||
let graw: Vec<u8> = grant.get("payload");
|
||||
let gsig: Vec<u8> = grant.get("signature");
|
||||
verify(s, &graw, &gsig)?;
|
||||
let g: ExecutionPermitPayload = serde_json::from_slice(&graw)?;
|
||||
let start: Value = serde_json::from_slice(&w.echo_start)?;
|
||||
let gbytes: Vec<u8> = serde_json::from_value(start["request"]["permit_bytes"].clone())?;
|
||||
let gsignature: Vec<u8> = serde_json::from_value(start["request"]["signature"].clone())?;
|
||||
let jbytes: Vec<u8> = serde_json::from_value(start["request"]["job_bytes"].clone())?;
|
||||
let mut outcome = echo
|
||||
.get::<Option<Value>, _>("result")
|
||||
.ok_or_else(mismatch)?;
|
||||
if outcome["grant_id"] != g.grant_id.to_string() {
|
||||
return Err(mismatch());
|
||||
}
|
||||
outcome
|
||||
.as_object_mut()
|
||||
.ok_or_else(mismatch)?
|
||||
.remove("grant_id");
|
||||
outcome["state"] = json!("succeeded");
|
||||
let native: Value = serde_json::from_slice(&w.echo_outcome)?;
|
||||
let result: Value = serde_json::from_slice(&w.echo_result)?;
|
||||
if gbytes != graw
|
||||
|| gsignature != gsig
|
||||
|| jbytes != echo.get::<Vec<u8>, _>("payload")
|
||||
|| native != result
|
||||
|| native != outcome
|
||||
|| !successful_outcome(&outcome)
|
||||
|| g.grant_id != grant.get::<Uuid, _>("grant_id")
|
||||
|| g.key_id != w.verification_key_id
|
||||
|| (g.tenant_id, g.asset_id, g.agent_id, g.job_id, g.attempt_id)
|
||||
!= (
|
||||
TENANT,
|
||||
ASSET,
|
||||
AGENT,
|
||||
profile::ECHO_JOB,
|
||||
profile::ECHO_ATTEMPT,
|
||||
)
|
||||
|| g.enrollment_generation != 1
|
||||
|| g.assignment_version != 1
|
||||
|| g.execution_identity != "agent_service"
|
||||
|| g.action != "run_script"
|
||||
|| g.agent_update_plan_id.is_some()
|
||||
|| g.job_payload_hash != echo.get::<String, _>("payload_hash")
|
||||
|| g.authorization_id != echo.get::<Uuid, _>("authorization_id")
|
||||
{
|
||||
return Err(mismatch());
|
||||
}
|
||||
let completion: SignedReceipt = serde_json::from_slice(&w.echo_completion_receipt)?;
|
||||
verify(s, &completion.payload, &completion.signature)?;
|
||||
let c: Completion = serde_json::from_slice(&completion.payload)?;
|
||||
if !c.valid(c.issued_at)
|
||||
|| c.key_id != w.verification_key_id
|
||||
|| c.witness.scope.job_id != profile::ECHO_JOB
|
||||
|| c.witness.scope.attempt_id != profile::ECHO_ATTEMPT
|
||||
|| c.witness.boot_id != profile::BOOT
|
||||
|| c.witness.grant_id != g.grant_id
|
||||
|| c.witness.grant_payload_sha256 != hash(&graw)
|
||||
|| c.witness.grant_signature_sha256 != hash(&gsig)
|
||||
|| c.witness.outcome_sha256 != inventory_sha256(&outcome)?
|
||||
{
|
||||
return Err(mismatch());
|
||||
}
|
||||
let retained =
|
||||
sqlx::query("SELECT payload,signature FROM windows_echo_completions WHERE tenant_id=$1")
|
||||
.bind(TENANT)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
if retained.get::<Vec<u8>, _>("payload") != completion.payload
|
||||
|| retained.get::<Vec<u8>, _>("signature") != completion.signature
|
||||
{
|
||||
return Err(mismatch());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn stored(tx: &mut Transaction<'_, Postgres>) -> Result<Option<(Uuid, Witness)>> {
|
||||
let row = sqlx::query(
|
||||
"SELECT request_id,witness FROM windows_sync_alignment_reviews WHERE tenant_id=$1",
|
||||
)
|
||||
.bind(TENANT)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
row.map(|r| {
|
||||
Ok((
|
||||
r.get("request_id"),
|
||||
serde_json::from_value(r.get("witness"))?,
|
||||
))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
async fn view(tx: &mut Transaction<'_, Postgres>, id: Uuid, w: &Witness) -> Result<Value> {
|
||||
let row=sqlx::query("SELECT payload FROM windows_sync_alignment_receipts WHERE tenant_id=$1 AND request_id=$2 ORDER BY issued_at DESC,receipt_id DESC LIMIT 1").bind(TENANT).bind(id).fetch_optional(&mut **tx).await?;
|
||||
let receipt = row
|
||||
.map(|r| serde_json::from_slice::<Value>(&r.get::<Vec<u8>, _>("payload")))
|
||||
.transpose()?;
|
||||
Ok(json!({"request_id":id,"witness":w,"witness_sha256":w.digest(),"receipt":receipt}))
|
||||
}
|
||||
async fn read(
|
||||
State(s): State<crate::State>,
|
||||
Path(t): Path<Uuid>,
|
||||
h: HeaderMap,
|
||||
) -> Result<Json<Value>> {
|
||||
let p = access(&s, &h, t, false).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
|
||||
let result = if let Some((id, w)) = stored(&mut tx).await? {
|
||||
validate(&mut tx, &s, &w).await?;
|
||||
view(&mut tx, id, &w).await?
|
||||
} else {
|
||||
json!({"request_id":null})
|
||||
};
|
||||
tx.commit().await?;
|
||||
Ok(Json(result))
|
||||
}
|
||||
async fn submit(
|
||||
State(s): State<crate::State>,
|
||||
Path(t): Path<Uuid>,
|
||||
h: HeaderMap,
|
||||
Json(w): Json<Witness>,
|
||||
) -> Result<Json<Value>> {
|
||||
let p = access(&s, &h, t, true).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
|
||||
validate(&mut tx, &s, &w).await?;
|
||||
let id = if let Some((id, old)) = stored(&mut tx).await? {
|
||||
if old != w {
|
||||
return Err(mismatch());
|
||||
}
|
||||
id
|
||||
} else {
|
||||
let id = Uuid::new_v4();
|
||||
let digest = w.digest().ok_or_else(mismatch)?;
|
||||
sqlx::query("INSERT INTO windows_sync_alignment_reviews(tenant_id,request_id,agent_id,witness,witness_sha256,submitted_by) VALUES($1,$2,$3,$4,$5,$6)").bind(t).bind(id).bind(AGENT).bind(serde_json::to_value(&w)?).bind(&digest).bind(&p.name).execute(&mut *tx).await?;
|
||||
sqlx::query("INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES($1,$2,$3,'windows_sync_alignment_submitted',$4)").bind(t).bind(id).bind(&p.name).bind(json!({"witness_sha256":digest,"connection_generation":205,"ready":false,"helper_ready":false,"unlock":false})).execute(&mut *tx).await?;
|
||||
id
|
||||
};
|
||||
let result = view(&mut tx, id, &w).await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(result))
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Confirmation {
|
||||
reviewed: bool,
|
||||
witness_sha256: String,
|
||||
}
|
||||
async fn confirm(
|
||||
State(s): State<crate::State>,
|
||||
Path((t, id)): Path<(Uuid, Uuid)>,
|
||||
h: HeaderMap,
|
||||
Json(input): Json<Confirmation>,
|
||||
) -> Result<Json<Value>> {
|
||||
let p = access(&s, &h, t, true).await?;
|
||||
let session = browser(&p)?;
|
||||
if !input.reviewed {
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "REVIEW_REQUIRED"));
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
||||
let allowed: bool = sqlx::query_scalar("SELECT lock_windows_echo_probe_reviewer()")
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if !allowed {
|
||||
return Err(Error(StatusCode::FORBIDDEN, "DEV_TEST_WEBUI_REQUIRED"));
|
||||
}
|
||||
let (actual, w) = stored(&mut tx)
|
||||
.await?
|
||||
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
||||
if actual != id || w.digest().as_deref() != Some(input.witness_sha256.as_str()) {
|
||||
return Err(mismatch());
|
||||
}
|
||||
validate(&mut tx, &s, &w).await?;
|
||||
let now = Utc::now().trunc_subsecs(6);
|
||||
let r = Receipt {
|
||||
domain: profile::DOMAIN.into(),
|
||||
schema_version: 1,
|
||||
receipt_id: Uuid::new_v4(),
|
||||
request_id: id,
|
||||
witness: w.clone(),
|
||||
witness_sha256: input.witness_sha256,
|
||||
key_id: s.job_signer.key_id.clone(),
|
||||
issued_at: now,
|
||||
valid_until: now + Duration::minutes(5),
|
||||
confirmed_by: p.name.clone(),
|
||||
approval_origin: p.approval_origin().into(),
|
||||
testsimulation: true,
|
||||
ready: false,
|
||||
helper_ready: false,
|
||||
unlock: false,
|
||||
};
|
||||
if !r.valid(now) {
|
||||
return Err(mismatch());
|
||||
}
|
||||
let payload = serde_json::to_vec(&r)?;
|
||||
let signature = s.job_signer.sign(&payload)?;
|
||||
sqlx::query("INSERT INTO windows_sync_alignment_receipts(tenant_id,request_id,receipt_id,witness_sha256,payload,signature,confirmed_by,session_hash,issued_at,valid_until) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)").bind(t).bind(id).bind(r.receipt_id).bind(&r.witness_sha256).bind(&payload).bind(signature).bind(&p.name).bind(session).bind(now).bind(r.valid_until).execute(&mut *tx).await?;
|
||||
sqlx::query("INSERT INTO audit_events(tenant_id,event_id,principal,event_type,data) VALUES($1,$2,$3,'windows_sync_admin_closed_alignment_confirmed',$4)").bind(t).bind(r.receipt_id).bind(&p.name).bind(json!({"request_id":id,"witness_sha256":r.witness_sha256,"receipt_sha256":hash(&payload),"approval_origin":r.approval_origin,"testsimulation":true,"ready":false,"helper_ready":false,"unlock":false,"connection_generation":205})).execute(&mut *tx).await?;
|
||||
let result = view(&mut tx, id, &w).await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(result))
|
||||
}
|
||||
async fn download(
|
||||
State(s): State<crate::State>,
|
||||
Path((t, id)): Path<(Uuid, Uuid)>,
|
||||
h: HeaderMap,
|
||||
) -> Result<Json<SignedReceipt>> {
|
||||
let p = access(&s, &h, t, false).await?;
|
||||
browser(&p)?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "plans:approve").await?;
|
||||
let (actual, w) = stored(&mut tx)
|
||||
.await?
|
||||
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
||||
if actual != id {
|
||||
return Err(mismatch());
|
||||
}
|
||||
validate(&mut tx, &s, &w).await?;
|
||||
let row=sqlx::query("SELECT payload,signature FROM windows_sync_alignment_receipts WHERE tenant_id=$1 AND request_id=$2 ORDER BY issued_at DESC,receipt_id DESC LIMIT 1").bind(t).bind(id).fetch_optional(&mut *tx).await?.ok_or(Error(StatusCode::NOT_FOUND,"NOT_FOUND"))?;
|
||||
let signed = SignedReceipt {
|
||||
payload: row.get("payload"),
|
||||
signature: row.get("signature"),
|
||||
};
|
||||
verify(&s, &signed.payload, &signed.signature)?;
|
||||
let r: Receipt = serde_json::from_slice(&signed.payload)?;
|
||||
if !r.valid(Utc::now()) || r.witness != w {
|
||||
return Err(Error(
|
||||
StatusCode::CONFLICT,
|
||||
"WINDOWS_SYNC_ALIGNMENT_EXPIRED",
|
||||
));
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(signed))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn administrative_confirmation_requires_actual_scoped_browser_session() {
|
||||
let p = Principal {
|
||||
name: TEST_PRINCIPAL.into(),
|
||||
tenant: TENANT,
|
||||
operator: true,
|
||||
csrf: Some("csrf".into()),
|
||||
session_hash: Some("ab".repeat(32)),
|
||||
scopes: None,
|
||||
testsimulation: true,
|
||||
identity: None,
|
||||
tenants: vec![TENANT],
|
||||
};
|
||||
assert!(browser(&p).is_ok());
|
||||
for mutation in 0..5 {
|
||||
let mut bad = p.clone();
|
||||
match mutation {
|
||||
0 => bad.session_hash = None,
|
||||
1 => bad.csrf = None,
|
||||
2 => bad.scopes = Some(Default::default()),
|
||||
3 => bad.testsimulation = false,
|
||||
_ => bad.operator = false,
|
||||
};
|
||||
assert_eq!(browser(&bad).unwrap_err().0, StatusCode::FORBIDDEN);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user