synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-api / src / evidence.rs
| 1 | //! Read-only checks of evidence receipts against Synapse (ADR 0004, deliverable D4). |
| 2 | //! |
| 3 | //! Two reads, each under `Capability::Read`, neither of which writes anything or touches the |
| 4 | //! submission path: |
| 5 | //! |
| 6 | //! * [`SynapseService::evidence_base`] gives a runner the source revision and the |
| 7 | //! per-directory `CrumbContextDigest`s it must bind for a changeset, at the base and in the |
| 8 | //! changeset's own tree; |
| 9 | //! * [`SynapseService::verify_evidence_receipt`] checks a signed receipt, then recomputes |
| 10 | //! both digests per directory and reports a typed [`ReceiptVerification`]. A context that |
| 11 | //! differs on either side is reported as [`ReceiptVerification::Stale`], never accepted. |
| 12 | //! |
| 13 | //! A `Current` verdict grants nothing: AEGIS stays the sole execution and publication |
| 14 | //! authority and Radicle canonical promotion stays independent. Receipts are not stored. |
| 15 | |
| 16 | use crate::{SynapseService, TreeTarget, VirtualTreeEntry}; |
| 17 | use serde::{Deserialize, Serialize}; |
| 18 | use std::collections::{BTreeMap, BTreeSet}; |
| 19 | use synapse_auth::{AuthenticatedRequest, BoundaryKind, Capability}; |
| 20 | use synapse_core::{ChangesetEnvelope, ChangesetId, RepoId, SynapseResult, WalSeq}; |
| 21 | use synapse_crumb::{CrumbContextDigest, ROOT_DIR}; |
| 22 | use synapse_evidence::{ |
| 23 | CrumbContextBinding, EvidenceReceipt, EvidenceReceiptId, Outcome, ReceiptError, SourceRevision, |
| 24 | }; |
| 25 | |
| 26 | /// Request payload for [`SynapseService::evidence_base`]. |
| 27 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 28 | pub struct EvidenceBaseQueryPayload { |
| 29 | pub changeset_id: ChangesetId, |
| 30 | pub snapshot_seq: Option<WalSeq>, |
| 31 | } |
| 32 | |
| 33 | /// Request payload for [`SynapseService::verify_evidence_receipt`]. |
| 34 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 35 | pub struct VerifyEvidenceReceiptPayload { |
| 36 | /// Canonical receipt bytes ([`EvidenceReceipt::encode`]). |
| 37 | pub receipt: Vec<u8>, |
| 38 | pub snapshot_seq: Option<WalSeq>, |
| 39 | } |
| 40 | |
| 41 | /// What a runner must bind for a changeset. |
| 42 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 43 | pub struct EvidenceBase { |
| 44 | pub source: SourceRevision, |
| 45 | /// One per distinct directory of the changeset's mutated paths, sorted by directory, with |
| 46 | /// the context at the base and in the changeset's own tree. |
| 47 | pub crumb_contexts: Vec<CrumbContextBinding>, |
| 48 | } |
| 49 | |
| 50 | /// Which side of a changeset a stale context binding is on. |
| 51 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 52 | pub enum StaleReason { |
| 53 | /// The context bound as "at the base" (what the author saw) is not the base's context. |
| 54 | AtBase, |
| 55 | /// The context bound as "in the changeset" (what the runner tested under) is not the |
| 56 | /// context in the changeset's own tree. |
| 57 | InChangeset, |
| 58 | } |
| 59 | |
| 60 | /// One bound context that differs from what Synapse recomputes. |
| 61 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 62 | pub struct StaleContext { |
| 63 | pub dir: String, |
| 64 | pub reason: StaleReason, |
| 65 | pub in_receipt: CrumbContextDigest, |
| 66 | /// What Synapse recomputes for this directory on the `reason` side. |
| 67 | pub expected: CrumbContextDigest, |
| 68 | } |
| 69 | |
| 70 | /// Why a well-formed, correctly signed receipt does not describe this changeset. |
| 71 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 72 | pub enum ReceiptMismatch { |
| 73 | /// The receipt names another repository. |
| 74 | Repository(RepoId), |
| 75 | /// The receipt's source revision is not the changeset's base and parents. |
| 76 | SourceRevision, |
| 77 | /// The receipt binds a different directory set than the changeset's mutated paths give. |
| 78 | ContextSet { |
| 79 | missing: Vec<String>, |
| 80 | extra: Vec<String>, |
| 81 | }, |
| 82 | } |
| 83 | |
| 84 | /// Typed result of checking a receipt against Synapse. Only `Current` means the receipt |
| 85 | /// binds exactly the contexts at the changeset's base and in its tree; even then it grants nothing. |
| 86 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 87 | pub enum ReceiptVerification { |
| 88 | /// Signature, version, and structure hold, and every bound context matches on both sides. |
| 89 | Current { |
| 90 | receipt_id: EvidenceReceiptId, |
| 91 | outcome: Outcome, |
| 92 | }, |
| 93 | /// At least one bound context differs from the context Synapse recomputes, at the base or |
| 94 | /// in the changeset's tree. Each entry names its directory and side. |
| 95 | Stale { |
| 96 | receipt_id: EvidenceReceiptId, |
| 97 | stale: Vec<StaleContext>, |
| 98 | }, |
| 99 | /// The receipt is valid but describes something else. |
| 100 | Mismatch { |
| 101 | receipt_id: EvidenceReceiptId, |
| 102 | reason: ReceiptMismatch, |
| 103 | }, |
| 104 | /// The record itself is refused (bad signature, wrong domain, unknown version, malformed). |
| 105 | Refused(ReceiptError), |
| 106 | } |
| 107 | |
| 108 | impl SynapseService { |
| 109 | /// Source revision and per-directory Crumb contexts (at the base and in the changeset's |
| 110 | /// own tree) for `changeset_id` (`Capability::Read`). A runner binds these into its |
| 111 | /// receipt. |
| 112 | pub fn evidence_base( |
| 113 | &mut self, |
| 114 | req: &AuthenticatedRequest<EvidenceBaseQueryPayload>, |
| 115 | now_ms: u64, |
| 116 | ) -> SynapseResult<EvidenceBase> { |
| 117 | self.auth.authorize( |
| 118 | BoundaryKind::Api, |
| 119 | "evidence_base", |
| 120 | &self.repo_id, |
| 121 | Capability::Read, |
| 122 | req, |
| 123 | now_ms, |
| 124 | )?; |
| 125 | let p = &req.payload; |
| 126 | self.compute_evidence_base(p.changeset_id, p.snapshot_seq) |
| 127 | } |
| 128 | |
| 129 | /// Check a signed receipt and recompute its Crumb contexts at the changeset's base and in |
| 130 | /// its tree (`Capability::Read`). An unknown or invisible changeset is an error, as for `get`. |
| 131 | pub fn verify_evidence_receipt( |
| 132 | &mut self, |
| 133 | req: &AuthenticatedRequest<VerifyEvidenceReceiptPayload>, |
| 134 | now_ms: u64, |
| 135 | ) -> SynapseResult<ReceiptVerification> { |
| 136 | self.auth.authorize( |
| 137 | BoundaryKind::Api, |
| 138 | "verify_evidence_receipt", |
| 139 | &self.repo_id, |
| 140 | Capability::Read, |
| 141 | req, |
| 142 | now_ms, |
| 143 | )?; |
| 144 | let (receipt, receipt_id) = match EvidenceReceipt::decode_verified(&req.payload.receipt) { |
| 145 | Ok(v) => v, |
| 146 | Err(e) => return Ok(ReceiptVerification::Refused(e)), |
| 147 | }; |
| 148 | let body = &receipt.body; |
| 149 | if body.repo_id != self.repo_id { |
| 150 | return Ok(ReceiptVerification::Mismatch { |
| 151 | receipt_id, |
| 152 | reason: ReceiptMismatch::Repository(body.repo_id.clone()), |
| 153 | }); |
| 154 | } |
| 155 | let base = self.compute_evidence_base(body.changeset_id, req.payload.snapshot_seq)?; |
| 156 | if base.source != body.source { |
| 157 | return Ok(ReceiptVerification::Mismatch { |
| 158 | receipt_id, |
| 159 | reason: ReceiptMismatch::SourceRevision, |
| 160 | }); |
| 161 | } |
| 162 | let want: BTreeSet<&str> = base.crumb_contexts.iter().map(|c| c.dir.as_str()).collect(); |
| 163 | let got: BTreeSet<&str> = body.crumb_contexts.iter().map(|c| c.dir.as_str()).collect(); |
| 164 | if want != got { |
| 165 | return Ok(ReceiptVerification::Mismatch { |
| 166 | receipt_id, |
| 167 | reason: ReceiptMismatch::ContextSet { |
| 168 | missing: want.difference(&got).map(|d| d.to_string()).collect(), |
| 169 | extra: got.difference(&want).map(|d| d.to_string()).collect(), |
| 170 | }, |
| 171 | }); |
| 172 | } |
| 173 | // Both lists are sorted by directory and hold the same set, so they pair up. Each side |
| 174 | // is checked on its own, so a receipt can be stale on either or both. |
| 175 | let mut stale = Vec::new(); |
| 176 | for (r, b) in body.crumb_contexts.iter().zip(&base.crumb_contexts) { |
| 177 | for (reason, in_receipt, expected) in [ |
| 178 | (StaleReason::AtBase, r.at_base, b.at_base), |
| 179 | (StaleReason::InChangeset, r.in_changeset, b.in_changeset), |
| 180 | ] { |
| 181 | if in_receipt != expected { |
| 182 | stale.push(StaleContext { |
| 183 | dir: r.dir.clone(), |
| 184 | reason, |
| 185 | in_receipt, |
| 186 | expected, |
| 187 | }); |
| 188 | } |
| 189 | } |
| 190 | } |
| 191 | if stale.is_empty() { |
| 192 | Ok(ReceiptVerification::Current { |
| 193 | receipt_id, |
| 194 | outcome: body.result.outcome, |
| 195 | }) |
| 196 | } else { |
| 197 | Ok(ReceiptVerification::Stale { receipt_id, stale }) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | /// No authorization: callers authorize first. |
| 202 | fn compute_evidence_base( |
| 203 | &mut self, |
| 204 | changeset_id: ChangesetId, |
| 205 | snapshot_seq: Option<WalSeq>, |
| 206 | ) -> SynapseResult<EvidenceBase> { |
| 207 | let envelope = self |
| 208 | .store |
| 209 | .get_changeset_in_repo(&self.repo_id, changeset_id, None, snapshot_seq)? |
| 210 | .envelope; |
| 211 | let base_tree = self.base_tree(&envelope, snapshot_seq)?; |
| 212 | // The changeset's own tree is the v1 input root: the tree the runner tested. |
| 213 | let tested_tree = |
| 214 | self.materialize_virtual_tree(TreeTarget::Changeset(changeset_id), snapshot_seq)?; |
| 215 | let mut crumb_contexts = Vec::new(); |
| 216 | for dir in mutated_dirs(&envelope) { |
| 217 | let at_base = self |
| 218 | .resolve_crumb_context(&base_tree, &dir, snapshot_seq)? |
| 219 | .digest(); |
| 220 | let in_changeset = self |
| 221 | .resolve_crumb_context(&tested_tree, &dir, snapshot_seq)? |
| 222 | .digest(); |
| 223 | crumb_contexts.push(CrumbContextBinding { |
| 224 | dir, |
| 225 | at_base, |
| 226 | in_changeset, |
| 227 | }); |
| 228 | } |
| 229 | Ok(EvidenceBase { |
| 230 | source: SourceRevision { |
| 231 | base_git_oid: envelope.base_git_oid, |
| 232 | parent_changesets: envelope.parent_changesets.clone(), |
| 233 | }, |
| 234 | crumb_contexts, |
| 235 | }) |
| 236 | } |
| 237 | |
| 238 | /// The tree a changeset was built on: its base Git tree when it has no parents, else its |
| 239 | /// parents overlaid in order (the same order `materialize_virtual_tree` uses). |
| 240 | fn base_tree( |
| 241 | &mut self, |
| 242 | envelope: &ChangesetEnvelope, |
| 243 | snapshot_seq: Option<WalSeq>, |
| 244 | ) -> SynapseResult<BTreeMap<String, VirtualTreeEntry>> { |
| 245 | self.changeset_base_files(envelope, snapshot_seq) |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | /// Distinct parent directories of the mutated paths (`"."` for the root), sorted. |
| 250 | fn mutated_dirs(envelope: &ChangesetEnvelope) -> BTreeSet<String> { |
| 251 | envelope |
| 252 | .mutations |
| 253 | .iter() |
| 254 | .map(|m| { |
| 255 | m.path |
| 256 | .rsplit_once('/') |
| 257 | .map_or(ROOT_DIR.to_string(), |(dir, _)| dir.to_string()) |
| 258 | }) |
| 259 | .collect() |
| 260 | } |
| 261 | |
| 262 | #[cfg(test)] |
| 263 | mod tests { |
| 264 | use super::*; |
| 265 | use crate::{FsyncPolicy, IngestOutcome, RecoveryPolicy, StoreLimits, SubmitChangesetPayload}; |
| 266 | use ed25519_dalek::{Signer, SigningKey}; |
| 267 | use std::path::PathBuf; |
| 268 | use synapse_auth::AgentCapabilityGrant; |
| 269 | use synapse_core::{ |
| 270 | encode_did_key_ed25519, BlobDigest, FileMode, GitOid, IdempotencyKey, MutationOp, |
| 271 | PathMutation, RefusalCode, SYNAPSE_ENVELOPE_VERSION, |
| 272 | }; |
| 273 | use synapse_evidence::{ |
| 274 | ExitStatus, InputRoot, Observation, ReceiptBody, ReceiptResult, TestIdentity, |
| 275 | }; |
| 276 | |
| 277 | const ROOT: &[u8] = br#"{"schema_version":"1.0.0","name":"root","purpose":"Root."}"#; |
| 278 | const SRC: &[u8] = br#"{"schema_version":"1.0.0","name":"src","purpose":"Sources."}"#; |
| 279 | const NEW_SRC: &[u8] = br#"{"schema_version":"1.0.0","name":"src","purpose":"Edited."}"#; |
| 280 | |
| 281 | struct Fixture { |
| 282 | svc: SynapseService, |
| 283 | auth: SigningKey, |
| 284 | agent: SigningKey, |
| 285 | runner: SigningKey, |
| 286 | repo: RepoId, |
| 287 | nonce: u8, |
| 288 | dir: PathBuf, |
| 289 | } |
| 290 | |
| 291 | impl Drop for Fixture { |
| 292 | fn drop(&mut self) { |
| 293 | let _ = std::fs::remove_dir_all(&self.dir); |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | impl Fixture { |
| 298 | fn new(label: &str) -> Self { |
| 299 | let dir = std::env::temp_dir().join(format!( |
| 300 | "synapse-api-evidence-{label}-{}-{}", |
| 301 | std::process::id(), |
| 302 | std::time::SystemTime::now() |
| 303 | .duration_since(std::time::UNIX_EPOCH) |
| 304 | .unwrap() |
| 305 | .as_nanos() |
| 306 | )); |
| 307 | let repo = RepoId::new("aien-spark/synapse").unwrap(); |
| 308 | let mut svc = SynapseService::open( |
| 309 | &dir, |
| 310 | repo.clone(), |
| 311 | FsyncPolicy::EveryCommit, |
| 312 | RecoveryPolicy::StrictFailClosed, |
| 313 | StoreLimits::default(), |
| 314 | ) |
| 315 | .unwrap(); |
| 316 | let auth = SigningKey::from_bytes(&[10u8; 32]); |
| 317 | svc.register_authority(encode_did_key_ed25519(&auth.verifying_key().to_bytes())); |
| 318 | for (seed, src) in [ |
| 319 | (1u8, SRC), |
| 320 | ( |
| 321 | 2u8, |
| 322 | b"{\"schema_version\":\"1.0.0\",\"name\":\"src\",\"purpose\":\"Changed.\"}" |
| 323 | .as_slice(), |
| 324 | ), |
| 325 | ] { |
| 326 | svc.register_base_tree( |
| 327 | GitOid([seed; 20]), |
| 328 | vec![ |
| 329 | (".crumb".into(), FileMode::Regular644, ROOT.to_vec()), |
| 330 | ("src/.crumb".into(), FileMode::Regular644, src.to_vec()), |
| 331 | ( |
| 332 | "src/a.rs".into(), |
| 333 | FileMode::Regular644, |
| 334 | b"fn a() {}\n".to_vec(), |
| 335 | ), |
| 336 | ], |
| 337 | ) |
| 338 | .unwrap(); |
| 339 | } |
| 340 | Self { |
| 341 | svc, |
| 342 | auth, |
| 343 | agent: SigningKey::from_bytes(&[20u8; 32]), |
| 344 | runner: SigningKey::from_bytes(&[30u8; 32]), |
| 345 | repo, |
| 346 | nonce: 0, |
| 347 | dir, |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | fn sign<T: Serialize>(&mut self, cap: Capability, payload: T) -> AuthenticatedRequest<T> { |
| 352 | self.nonce += 1; |
| 353 | let grant = AgentCapabilityGrant::issue( |
| 354 | &self.auth, |
| 355 | [self.nonce; 32], |
| 356 | self.repo.clone(), |
| 357 | encode_did_key_ed25519(&self.agent.verifying_key().to_bytes()), |
| 358 | vec![Capability::Read, Capability::Propose], |
| 359 | 4 * 1024 * 1024, |
| 360 | 100, |
| 361 | 60_000, |
| 362 | 10, |
| 363 | 100_000, |
| 364 | ); |
| 365 | AuthenticatedRequest::sign_new( |
| 366 | &self.agent, |
| 367 | grant, |
| 368 | self.repo.clone(), |
| 369 | cap, |
| 370 | [self.nonce; 32], |
| 371 | self.now(), |
| 372 | 0, |
| 373 | payload, |
| 374 | ) |
| 375 | .unwrap() |
| 376 | } |
| 377 | |
| 378 | fn now(&self) -> u64 { |
| 379 | 1000 + u64::from(self.nonce) |
| 380 | } |
| 381 | |
| 382 | /// Submit a changeset on base `seed` upserting `src/b.rs` and `docs/x.md`. |
| 383 | fn propose(&mut self, seed: u8) -> ChangesetId { |
| 384 | self.propose_files( |
| 385 | seed, |
| 386 | &[("docs/x.md", b"# x\n"), ("src/b.rs", b"fn b() {}\n")], |
| 387 | ) |
| 388 | } |
| 389 | |
| 390 | /// Submit a changeset on base `seed` upserting `files` (sorted by path). |
| 391 | fn propose_files(&mut self, seed: u8, files: &[(&str, &[u8])]) -> ChangesetId { |
| 392 | let mut env = ChangesetEnvelope { |
| 393 | version: SYNAPSE_ENVELOPE_VERSION, |
| 394 | repo_id: self.repo.clone(), |
| 395 | base_git_oid: GitOid([seed; 20]), |
| 396 | parent_changesets: vec![], |
| 397 | author_did: String::new(), |
| 398 | idempotency_key: IdempotencyKey::from_label(&format!("ev-{seed}")), |
| 399 | created_at_ms: 100, |
| 400 | intent_summary: "evidence fixture".into(), |
| 401 | mutations: files |
| 402 | .iter() |
| 403 | .map(|(p, b)| PathMutation { |
| 404 | path: p.to_string(), |
| 405 | op: MutationOp::Upsert { |
| 406 | mode: FileMode::Regular644, |
| 407 | blob_digest: BlobDigest::compute(b), |
| 408 | size_bytes: b.len() as u64, |
| 409 | }, |
| 410 | }) |
| 411 | .collect(), |
| 412 | evidence_receipts: vec![], |
| 413 | signature: vec![], |
| 414 | }; |
| 415 | let agent = self.agent.clone(); |
| 416 | env.sign(&agent); |
| 417 | let blobs = files |
| 418 | .iter() |
| 419 | .map(|(_, b)| (BlobDigest::compute(b), b.to_vec())) |
| 420 | .collect(); |
| 421 | let req = self.sign( |
| 422 | Capability::Propose, |
| 423 | SubmitChangesetPayload { |
| 424 | envelope: env, |
| 425 | blobs, |
| 426 | }, |
| 427 | ); |
| 428 | match self.svc.submit(&req, self.now()).unwrap() { |
| 429 | IngestOutcome::Committed { changeset_id, .. } => changeset_id, |
| 430 | other => panic!("unexpected {other:?}"), |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | fn base(&mut self, cs: ChangesetId) -> EvidenceBase { |
| 435 | let req = self.sign( |
| 436 | Capability::Read, |
| 437 | EvidenceBaseQueryPayload { |
| 438 | changeset_id: cs, |
| 439 | snapshot_seq: None, |
| 440 | }, |
| 441 | ); |
| 442 | self.svc.evidence_base(&req, self.now()).unwrap() |
| 443 | } |
| 444 | |
| 445 | fn receipt(&self, cs: ChangesetId, base: EvidenceBase) -> EvidenceReceipt { |
| 446 | EvidenceReceipt::sign( |
| 447 | ReceiptBody { |
| 448 | repo_id: self.repo.clone(), |
| 449 | changeset_id: cs, |
| 450 | source: base.source, |
| 451 | crumb_contexts: base.crumb_contexts, |
| 452 | input_root: InputRoot::single_repo(self.repo.clone(), cs), |
| 453 | test: TestIdentity { |
| 454 | name: "unit".into(), |
| 455 | command: vec!["cargo".into(), "test".into()], |
| 456 | toolchain: "rustc".into(), |
| 457 | platform: "aarch64-unknown-linux-gnu".into(), |
| 458 | environment: vec![], |
| 459 | }, |
| 460 | result: ReceiptResult { |
| 461 | exit_status: ExitStatus::Code(0), |
| 462 | outcome: Outcome::Pass, |
| 463 | outputs: vec![], |
| 464 | }, |
| 465 | observation: Observation { |
| 466 | started_at_ms: 1, |
| 467 | duration_ms: 2, |
| 468 | log: b"ok\n".to_vec(), |
| 469 | }, |
| 470 | }, |
| 471 | &self.runner, |
| 472 | ) |
| 473 | .unwrap() |
| 474 | } |
| 475 | |
| 476 | fn verify(&mut self, bytes: Vec<u8>) -> SynapseResult<ReceiptVerification> { |
| 477 | let req = self.sign( |
| 478 | Capability::Read, |
| 479 | VerifyEvidenceReceiptPayload { |
| 480 | receipt: bytes, |
| 481 | snapshot_seq: None, |
| 482 | }, |
| 483 | ); |
| 484 | self.svc.verify_evidence_receipt(&req, self.now()) |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | #[test] |
| 489 | fn changeset_editing_a_crumb_binds_both_contexts() { |
| 490 | let mut fx = Fixture::new("edits-crumb"); |
| 491 | let cs = fx.propose_files(1, &[("src/.crumb", NEW_SRC), ("src/b.rs", b"fn b() {}\n")]); |
| 492 | let base = fx.base(cs); |
| 493 | let tree = fx |
| 494 | .svc |
| 495 | .materialize_virtual_tree(TreeTarget::Changeset(cs), None) |
| 496 | .unwrap(); |
| 497 | let tested = fx |
| 498 | .svc |
| 499 | .resolve_crumb_context(&tree, "src", None) |
| 500 | .unwrap() |
| 501 | .digest(); |
| 502 | let src = base.crumb_contexts.iter().find(|c| c.dir == "src").unwrap(); |
| 503 | // The runner tested under the edited `src/.crumb`; the author saw the base one. |
| 504 | assert_eq!( |
| 505 | src.in_changeset, tested, |
| 506 | "receipt must bind the tested context" |
| 507 | ); |
| 508 | assert_ne!(src.at_base, src.in_changeset); |
| 509 | let (at_base, in_changeset) = (src.at_base, src.in_changeset); |
| 510 | |
| 511 | // Binding both sides as given is Current. |
| 512 | let r = fx.receipt(cs, base.clone()); |
| 513 | assert!(matches!( |
| 514 | fx.verify(r.encode().unwrap()).unwrap(), |
| 515 | ReceiptVerification::Current { .. } |
| 516 | )); |
| 517 | |
| 518 | // A runner that claims it tested under the base context (the old single binding) is |
| 519 | // stale on the changeset side only. |
| 520 | let mut bound = base.clone(); |
| 521 | bound.crumb_contexts[0].in_changeset = at_base; |
| 522 | let r = fx.receipt(cs, bound); |
| 523 | assert_eq!( |
| 524 | fx.verify(r.encode().unwrap()).unwrap(), |
| 525 | ReceiptVerification::Stale { |
| 526 | receipt_id: r.id(), |
| 527 | stale: vec![StaleContext { |
| 528 | dir: "src".into(), |
| 529 | reason: StaleReason::InChangeset, |
| 530 | in_receipt: at_base, |
| 531 | expected: in_changeset, |
| 532 | }], |
| 533 | } |
| 534 | ); |
| 535 | |
| 536 | // Claiming the author saw the edited context is stale on the base side only. |
| 537 | let mut bound = base; |
| 538 | bound.crumb_contexts[0].at_base = in_changeset; |
| 539 | let r = fx.receipt(cs, bound); |
| 540 | assert_eq!( |
| 541 | fx.verify(r.encode().unwrap()).unwrap(), |
| 542 | ReceiptVerification::Stale { |
| 543 | receipt_id: r.id(), |
| 544 | stale: vec![StaleContext { |
| 545 | dir: "src".into(), |
| 546 | reason: StaleReason::AtBase, |
| 547 | in_receipt: in_changeset, |
| 548 | expected: at_base, |
| 549 | }], |
| 550 | } |
| 551 | ); |
| 552 | } |
| 553 | |
| 554 | #[test] |
| 555 | fn base_binds_one_context_per_mutated_directory() { |
| 556 | let mut fx = Fixture::new("base"); |
| 557 | let cs = fx.propose(1); |
| 558 | let base = fx.base(cs); |
| 559 | let dirs: Vec<&str> = base.crumb_contexts.iter().map(|c| c.dir.as_str()).collect(); |
| 560 | assert_eq!(dirs, ["docs", "src"]); |
| 561 | assert_eq!(base.source.base_git_oid, GitOid([1; 20])); |
| 562 | assert!(base.source.parent_changesets.is_empty()); |
| 563 | } |
| 564 | |
| 565 | #[test] |
| 566 | fn matching_receipt_is_current_and_grants_nothing() { |
| 567 | let mut fx = Fixture::new("current"); |
| 568 | let cs = fx.propose(1); |
| 569 | let base = fx.base(cs); |
| 570 | let r = fx.receipt(cs, base); |
| 571 | let v = fx.verify(r.encode().unwrap()).unwrap(); |
| 572 | assert_eq!( |
| 573 | v, |
| 574 | ReceiptVerification::Current { |
| 575 | receipt_id: r.id(), |
| 576 | outcome: Outcome::Pass |
| 577 | } |
| 578 | ); |
| 579 | } |
| 580 | |
| 581 | #[test] |
| 582 | fn context_from_another_base_is_stale_not_accepted() { |
| 583 | let mut fx = Fixture::new("stale"); |
| 584 | let cs1 = fx.propose(1); |
| 585 | let cs2 = fx.propose(2); |
| 586 | // The runner saw base 2's `src/.crumb` but signs for the changeset on base 1. |
| 587 | let seen = fx.base(cs2); |
| 588 | let mut bound = fx.base(cs1); |
| 589 | bound.crumb_contexts = seen.crumb_contexts.clone(); |
| 590 | let truth = fx.base(cs1); |
| 591 | let r = fx.receipt(cs1, bound); |
| 592 | match fx.verify(r.encode().unwrap()).unwrap() { |
| 593 | ReceiptVerification::Stale { receipt_id, stale } => { |
| 594 | assert_eq!(receipt_id, r.id()); |
| 595 | // Neither changeset edits `src/.crumb`, so both sides are stale, each named. |
| 596 | let (s, t) = (&seen.crumb_contexts[1], &truth.crumb_contexts[1]); |
| 597 | assert_eq!( |
| 598 | stale, |
| 599 | vec![ |
| 600 | StaleContext { |
| 601 | dir: "src".into(), |
| 602 | reason: StaleReason::AtBase, |
| 603 | in_receipt: s.at_base, |
| 604 | expected: t.at_base, |
| 605 | }, |
| 606 | StaleContext { |
| 607 | dir: "src".into(), |
| 608 | reason: StaleReason::InChangeset, |
| 609 | in_receipt: s.in_changeset, |
| 610 | expected: t.in_changeset, |
| 611 | }, |
| 612 | ] |
| 613 | ); |
| 614 | } |
| 615 | other => panic!("expected Stale, got {other:?}"), |
| 616 | } |
| 617 | } |
| 618 | |
| 619 | #[test] |
| 620 | fn wrong_source_or_directory_set_is_a_mismatch() { |
| 621 | let mut fx = Fixture::new("mismatch"); |
| 622 | let cs = fx.propose(1); |
| 623 | let mut base = fx.base(cs); |
| 624 | base.source.base_git_oid = GitOid([2; 20]); |
| 625 | let r = fx.receipt(cs, base); |
| 626 | assert!(matches!( |
| 627 | fx.verify(r.encode().unwrap()).unwrap(), |
| 628 | ReceiptVerification::Mismatch { |
| 629 | reason: ReceiptMismatch::SourceRevision, |
| 630 | .. |
| 631 | } |
| 632 | )); |
| 633 | |
| 634 | let mut base = fx.base(cs); |
| 635 | base.crumb_contexts.remove(0); |
| 636 | let r = fx.receipt(cs, base); |
| 637 | assert_eq!( |
| 638 | fx.verify(r.encode().unwrap()).unwrap(), |
| 639 | ReceiptVerification::Mismatch { |
| 640 | receipt_id: r.id(), |
| 641 | reason: ReceiptMismatch::ContextSet { |
| 642 | missing: vec!["docs".into()], |
| 643 | extra: vec![], |
| 644 | }, |
| 645 | } |
| 646 | ); |
| 647 | } |
| 648 | |
| 649 | #[test] |
| 650 | fn forged_or_unknown_receipts_are_refused() { |
| 651 | let mut fx = Fixture::new("refused"); |
| 652 | let cs = fx.propose(1); |
| 653 | let base = fx.base(cs); |
| 654 | let mut r = fx.receipt(cs, base); |
| 655 | r.signature = SigningKey::from_bytes(&[99u8; 32]) |
| 656 | .sign(&r.signable_bytes()) |
| 657 | .to_bytes(); |
| 658 | assert_eq!( |
| 659 | fx.verify(r.encode().unwrap()).unwrap(), |
| 660 | ReceiptVerification::Refused(ReceiptError::SignatureInvalid) |
| 661 | ); |
| 662 | assert_eq!( |
| 663 | fx.verify(b"not a receipt".to_vec()).unwrap(), |
| 664 | ReceiptVerification::Refused(ReceiptError::WrongDomain) |
| 665 | ); |
| 666 | // A receipt for a changeset Synapse does not have is an error, not a verdict. |
| 667 | let base = fx.base(cs); |
| 668 | let ghost = ChangesetId([0xee; 32]); |
| 669 | let r = fx.receipt(ghost, base); |
| 670 | assert_eq!( |
| 671 | fx.verify(r.encode().unwrap()).unwrap_err().code, |
| 672 | RefusalCode::ChangesetNotFound |
| 673 | ); |
| 674 | } |
| 675 | } |