synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-git / src / lib.rs
| 1 | //! Deterministic Git loose object materialization (`blob`, `tree`, `commit`), |
| 2 | //! bidirectional `ChangesetId <-> GitOid` index, explicit ref namespace contract |
| 3 | //! (`refs/synapse/*` vs human `refs/heads/*`), and GitHub Pull Request projection |
| 4 | //! builder (`synapse-git`, Gate 3). |
| 5 | //! |
| 6 | //! ADR 0003 step H1 (the Git bridge) adds the native Git object layer: [`object`] (object |
| 7 | //! kinds, IDs and links), [`inflate`] (zlib and DEFLATE decoding), [`pack`] (version 2 packs |
| 8 | //! and indexes, delta resolution), and [`repo`] (reading a repository's full history and |
| 9 | //! exporting an object set as a new bare repository with one pack). |
| 10 | |
| 11 | pub mod bridge; |
| 12 | pub mod inflate; |
| 13 | pub mod object; |
| 14 | pub mod pack; |
| 15 | pub mod repo; |
| 16 | |
| 17 | pub use bridge::{export_store, import_history, import_repository, ImportReceipt}; |
| 18 | pub use object::{GitObject, GitTreeEntry, ObjectKind}; |
| 19 | pub use pack::{PackIndexEntry, PackReader, WrittenPack}; |
| 20 | pub use repo::{export_repository, ExportReceipt, GitHistory, GitRepository, ReadLimits}; |
| 21 | |
| 22 | use serde::{Deserialize, Serialize}; |
| 23 | use sha1::Sha1; |
| 24 | use sha2::{Digest, Sha256}; |
| 25 | use std::cmp::Ordering; |
| 26 | use std::collections::BTreeMap; |
| 27 | use std::fs::{self, File}; |
| 28 | use std::io::Write; |
| 29 | use std::path::Path; |
| 30 | use std::process::Command; |
| 31 | use synapse_api::{SynapseService, TreeTarget, VirtualTreeEntry}; |
| 32 | use synapse_auth::AuthenticatedRequest; |
| 33 | use synapse_core::{ |
| 34 | ChangesetId, GitHubPullRequestProjection, GitOid, RefusalCode, SynapseError, SynapseResult, |
| 35 | WalSeq, |
| 36 | }; |
| 37 | |
| 38 | /// Explicit ref namespace for a materialized Synapse changeset commit. |
| 39 | pub fn changeset_git_ref(changeset_id: ChangesetId) -> String { |
| 40 | format!("refs/synapse/changesets/{}", changeset_id.to_hex()) |
| 41 | } |
| 42 | |
| 43 | /// Explicit ref namespace consumed by CLI/autonomous agent workers on `lane`. |
| 44 | pub fn agent_lane_head_ref(lane: &str) -> String { |
| 45 | format!("refs/synapse/agent-head/{lane}") |
| 46 | } |
| 47 | |
| 48 | /// Explicit ref namespace recording the verified Radicle canonical head projection. |
| 49 | pub fn canonical_projection_ref(branch: &str) -> String { |
| 50 | format!("refs/synapse/canonical/{branch}") |
| 51 | } |
| 52 | |
| 53 | /// Bidirectional mapping between `ChangesetId` and materialized Git commit `GitOid`, |
| 54 | /// plus associated root tree `GitOid`. |
| 55 | #[derive(Debug, Clone, Default, Serialize, Deserialize)] |
| 56 | pub struct GitProjectionIndex { |
| 57 | changeset_to_commit: BTreeMap<ChangesetId, GitOid>, |
| 58 | changeset_to_tree: BTreeMap<ChangesetId, GitOid>, |
| 59 | commit_to_changeset: BTreeMap<GitOid, ChangesetId>, |
| 60 | } |
| 61 | |
| 62 | impl GitProjectionIndex { |
| 63 | pub fn new() -> Self { |
| 64 | Self::default() |
| 65 | } |
| 66 | |
| 67 | pub fn record(&mut self, changeset_id: ChangesetId, commit_oid: GitOid, tree_oid: GitOid) { |
| 68 | self.changeset_to_commit.insert(changeset_id, commit_oid); |
| 69 | self.changeset_to_tree.insert(changeset_id, tree_oid); |
| 70 | self.commit_to_changeset.insert(commit_oid, changeset_id); |
| 71 | } |
| 72 | |
| 73 | pub fn commit_for_changeset(&self, changeset_id: ChangesetId) -> Option<GitOid> { |
| 74 | self.changeset_to_commit.get(&changeset_id).copied() |
| 75 | } |
| 76 | |
| 77 | pub fn tree_for_changeset(&self, changeset_id: ChangesetId) -> Option<GitOid> { |
| 78 | self.changeset_to_tree.get(&changeset_id).copied() |
| 79 | } |
| 80 | |
| 81 | pub fn changeset_for_commit(&self, commit_oid: GitOid) -> Option<ChangesetId> { |
| 82 | self.commit_to_changeset.get(&commit_oid).copied() |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// Receipt returned when a Synapse changeset is materialized into a Git repository. |
| 87 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 88 | pub struct MaterializedGitCommit { |
| 89 | pub changeset_id: ChangesetId, |
| 90 | pub commit_oid: GitOid, |
| 91 | pub tree_oid: GitOid, |
| 92 | pub parent_commit_oids: Vec<GitOid>, |
| 93 | pub changeset_ref: String, |
| 94 | pub agent_lane_ref: Option<String>, |
| 95 | } |
| 96 | |
| 97 | /// Request payload for projecting a changeset to a GitHub Pull Request. |
| 98 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 99 | pub struct GitHubPrProjectionRequest { |
| 100 | pub pr_number: u64, |
| 101 | pub changeset_id: ChangesetId, |
| 102 | pub pr_branch_ref: String, |
| 103 | pub title: String, |
| 104 | pub github_merged: bool, |
| 105 | } |
| 106 | |
| 107 | /// Request payload for advancing a human-facing Git branch (`refs/heads/<branch>`) |
| 108 | /// to a fast-forward descendant commit (`Capability::Publish` at `BoundaryKind::Export`). |
| 109 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 110 | pub struct HumanBranchAdvanceRequest { |
| 111 | pub branch: String, |
| 112 | pub new_commit_oid: GitOid, |
| 113 | } |
| 114 | |
| 115 | /// Compute RFC 1950 Adler-32 checksum over `data`. |
| 116 | pub fn adler32(data: &[u8]) -> u32 { |
| 117 | const MOD_ADLER: u32 = 65521; |
| 118 | let mut a: u32 = 1; |
| 119 | let mut b: u32 = 0; |
| 120 | for &byte in data { |
| 121 | a = (a + u32::from(byte)) % MOD_ADLER; |
| 122 | b = (b + a) % MOD_ADLER; |
| 123 | } |
| 124 | (b << 16) | a |
| 125 | } |
| 126 | |
| 127 | /// Compress `raw` into RFC 1950 zlib stream using uncompressed DEFLATE store blocks (`BTYPE=00`). |
| 128 | /// Standard Git (`git fsck --full`, `git cat-file`, `git clone`, `git fetch`) natively accepts |
| 129 | /// RFC 1950 store-block streams with zero external C dependency. |
| 130 | pub fn zlib_compress_store(raw: &[u8]) -> Vec<u8> { |
| 131 | let mut out = Vec::with_capacity(raw.len() + (raw.len() / 65535 + 1) * 5 + 6); |
| 132 | // RFC 1950 header: CMF = 0x78 (Deflate, 32K window), FLG = 0x01 (no dict, FCHECK valid: 0x7801 % 31 == 0) |
| 133 | out.push(0x78); |
| 134 | out.push(0x01); |
| 135 | |
| 136 | if raw.is_empty() { |
| 137 | // Single final empty store block |
| 138 | out.push(0x01); // BFINAL=1, BTYPE=00 |
| 139 | out.extend_from_slice(&0u16.to_le_bytes()); |
| 140 | out.extend_from_slice(&(!0u16).to_le_bytes()); |
| 141 | } else { |
| 142 | let chunks: Vec<&[u8]> = raw.chunks(65_535).collect(); |
| 143 | for (i, chunk) in chunks.iter().enumerate() { |
| 144 | let is_last = i + 1 == chunks.len(); |
| 145 | out.push(u8::from(is_last)); // BFINAL=1 on last chunk, BTYPE=00 |
| 146 | let len = chunk.len() as u16; |
| 147 | let nlen = !len; |
| 148 | out.extend_from_slice(&len.to_le_bytes()); |
| 149 | out.extend_from_slice(&nlen.to_le_bytes()); |
| 150 | out.extend_from_slice(chunk); |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | let checksum = adler32(raw); |
| 155 | out.extend_from_slice(&checksum.to_be_bytes()); |
| 156 | out |
| 157 | } |
| 158 | |
| 159 | /// Write a standard Git loose object (`blob`, `tree`, or `commit`) into `<git_dir>/objects/<xx>/<38-hex>` |
| 160 | /// and return its deterministic 20-byte SHA-1 `GitOid`. |
| 161 | pub fn write_git_loose_object(git_dir: &Path, kind: &str, payload: &[u8]) -> SynapseResult<GitOid> { |
| 162 | let header = format!("{kind} {}\0", payload.len()); |
| 163 | let mut full = Vec::with_capacity(header.len() + payload.len()); |
| 164 | full.extend_from_slice(header.as_bytes()); |
| 165 | full.extend_from_slice(payload); |
| 166 | |
| 167 | let oid_bytes: [u8; 20] = Sha1::digest(&full).into(); |
| 168 | let oid = GitOid(oid_bytes); |
| 169 | let hex = oid.to_hex(); |
| 170 | |
| 171 | let shard_dir = git_dir.join("objects").join(&hex[0..2]); |
| 172 | let obj_path = shard_dir.join(&hex[2..40]); |
| 173 | if obj_path.exists() { |
| 174 | return Ok(oid); |
| 175 | } |
| 176 | |
| 177 | fs::create_dir_all(&shard_dir) |
| 178 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 179 | let compressed = zlib_compress_store(&full); |
| 180 | let tmp_path = shard_dir.join(format!("{}.tmp.{}", &hex[2..40], std::process::id())); |
| 181 | { |
| 182 | let mut f = File::create(&tmp_path) |
| 183 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 184 | f.write_all(&compressed) |
| 185 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 186 | f.sync_all() |
| 187 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 188 | } |
| 189 | fs::rename(&tmp_path, &obj_path) |
| 190 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 191 | Ok(oid) |
| 192 | } |
| 193 | |
| 194 | #[derive(Default)] |
| 195 | struct DirNode { |
| 196 | files: BTreeMap<String, VirtualTreeEntry>, |
| 197 | subdirs: BTreeMap<String, DirNode>, |
| 198 | } |
| 199 | |
| 200 | /// Compare two tree entry names using Git's exact tree sort rule: |
| 201 | /// directory entries are compared as if they had a trailing `'/'`. |
| 202 | fn git_tree_entry_cmp(name_a: &str, is_dir_a: bool, name_b: &str, is_dir_b: bool) -> Ordering { |
| 203 | let bytes_a = name_a.as_bytes(); |
| 204 | let bytes_b = name_b.as_bytes(); |
| 205 | let min_len = bytes_a.len().min(bytes_b.len()); |
| 206 | match bytes_a[..min_len].cmp(&bytes_b[..min_len]) { |
| 207 | Ordering::Equal => { |
| 208 | let next_a = if bytes_a.len() > min_len { |
| 209 | Some(bytes_a[min_len]) |
| 210 | } else if is_dir_a { |
| 211 | Some(b'/') |
| 212 | } else { |
| 213 | None |
| 214 | }; |
| 215 | let next_b = if bytes_b.len() > min_len { |
| 216 | Some(bytes_b[min_len]) |
| 217 | } else if is_dir_b { |
| 218 | Some(b'/') |
| 219 | } else { |
| 220 | None |
| 221 | }; |
| 222 | next_a.cmp(&next_b) |
| 223 | } |
| 224 | non_eq => non_eq, |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | fn write_dir_node_recursive(git_dir: &Path, node: &DirNode) -> SynapseResult<GitOid> { |
| 229 | // 1. Materialize all child subdirectories first |
| 230 | let mut entries: Vec<(String, bool, &'static str, GitOid)> = |
| 231 | Vec::with_capacity(node.files.len() + node.subdirs.len()); |
| 232 | |
| 233 | for (name, entry) in &node.files { |
| 234 | entries.push(( |
| 235 | name.clone(), |
| 236 | false, |
| 237 | entry.mode.git_octal_str(), |
| 238 | entry.git_blob_oid, |
| 239 | )); |
| 240 | } |
| 241 | for (dir_name, subnode) in &node.subdirs { |
| 242 | let sub_oid = write_dir_node_recursive(git_dir, subnode)?; |
| 243 | entries.push((dir_name.clone(), true, "40000", sub_oid)); |
| 244 | } |
| 245 | |
| 246 | // 2. Sort entries using Git's canonical tree comparator |
| 247 | entries.sort_by(|(na, da, _, _), (nb, db, _, _)| git_tree_entry_cmp(na, *da, nb, *db)); |
| 248 | |
| 249 | // 3. Encode binary Git tree payload: "<mode> <name>\0<20-byte raw oid>" |
| 250 | let mut tree_payload = Vec::new(); |
| 251 | for (name, _, mode_str, oid) in entries { |
| 252 | tree_payload.extend_from_slice(mode_str.as_bytes()); |
| 253 | tree_payload.push(b' '); |
| 254 | tree_payload.extend_from_slice(name.as_bytes()); |
| 255 | tree_payload.push(0); |
| 256 | tree_payload.extend_from_slice(&oid.0); |
| 257 | } |
| 258 | |
| 259 | write_git_loose_object(git_dir, "tree", &tree_payload) |
| 260 | } |
| 261 | |
| 262 | /// Write a Synapse namespace Git ref file (`refs/synapse/...`) atomically inside `git_dir`. |
| 263 | /// Human-facing refs (`refs/heads/...`) must go through [`advance_human_branch_fast_forward`]. |
| 264 | pub fn write_git_ref(git_dir: &Path, ref_name: &str, oid: GitOid) -> SynapseResult<()> { |
| 265 | if !ref_name.starts_with("refs/synapse/") || ref_name.contains("..") { |
| 266 | return Err(SynapseError::new( |
| 267 | RefusalCode::PathInvalid, |
| 268 | format!("invalid or unauthenticated human git ref name: {ref_name}"), |
| 269 | )); |
| 270 | } |
| 271 | write_git_ref_raw(git_dir, ref_name, oid) |
| 272 | } |
| 273 | |
| 274 | fn write_git_ref_raw(git_dir: &Path, ref_name: &str, oid: GitOid) -> SynapseResult<()> { |
| 275 | if !ref_name.starts_with("refs/") || ref_name.contains("..") { |
| 276 | return Err(SynapseError::new( |
| 277 | RefusalCode::PathInvalid, |
| 278 | format!("invalid git ref name: {ref_name}"), |
| 279 | )); |
| 280 | } |
| 281 | let ref_path = git_dir.join(ref_name); |
| 282 | if let Some(parent) = ref_path.parent() { |
| 283 | fs::create_dir_all(parent) |
| 284 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 285 | } |
| 286 | let tmp_path = ref_path.with_extension(format!("lock.{}", std::process::id())); |
| 287 | let content = format!("{}\n", oid.to_hex()); |
| 288 | { |
| 289 | let mut f = File::create(&tmp_path) |
| 290 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 291 | f.write_all(content.as_bytes()) |
| 292 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 293 | f.sync_all() |
| 294 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 295 | } |
| 296 | fs::rename(&tmp_path, &ref_path) |
| 297 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 298 | Ok(()) |
| 299 | } |
| 300 | |
| 301 | /// Deterministically materialize a committed Synapse `ChangesetId` into standard Git |
| 302 | /// `blob`, `tree`, and `commit` objects in `git_dir`, updating `refs/synapse/changesets/<id>` |
| 303 | /// and optionally `refs/synapse/agent-head/<lane>` without touching human `refs/heads/*` branches. |
| 304 | pub fn materialize_changeset_to_git( |
| 305 | service: &mut SynapseService, |
| 306 | index: &mut GitProjectionIndex, |
| 307 | git_dir: &Path, |
| 308 | changeset_id: ChangesetId, |
| 309 | agent_lane: Option<&str>, |
| 310 | snapshot_seq: Option<WalSeq>, |
| 311 | ) -> SynapseResult<MaterializedGitCommit> { |
| 312 | let stored = service |
| 313 | .store() |
| 314 | .get_changeset(changeset_id, None, snapshot_seq)?; |
| 315 | let virtual_tree = |
| 316 | service.materialize_virtual_tree(TreeTarget::Changeset(changeset_id), snapshot_seq)?; |
| 317 | |
| 318 | // 1. Write all blobs in the virtual tree into `<git_dir>/objects` |
| 319 | let mut root_node = DirNode::default(); |
| 320 | for entry in virtual_tree.values() { |
| 321 | let raw_bytes = service.read_blob_bytes(entry.blob_digest, snapshot_seq)?; |
| 322 | let written_blob_oid = write_git_loose_object(git_dir, "blob", &raw_bytes)?; |
| 323 | if written_blob_oid != entry.git_blob_oid { |
| 324 | return Err(SynapseError::new( |
| 325 | RefusalCode::GitObjectCorrupt, |
| 326 | format!( |
| 327 | "materialized blob OID {} != virtual tree OID {}", |
| 328 | written_blob_oid, entry.git_blob_oid |
| 329 | ), |
| 330 | )); |
| 331 | } |
| 332 | |
| 333 | // Insert into hierarchical DirNode |
| 334 | let segments: Vec<&str> = entry.path.split('/').collect(); |
| 335 | let mut curr = &mut root_node; |
| 336 | for &dir_seg in &segments[..segments.len() - 1] { |
| 337 | curr = curr.subdirs.entry(dir_seg.to_string()).or_default(); |
| 338 | } |
| 339 | let file_name = segments.last().expect("non-empty path").to_string(); |
| 340 | curr.files.insert(file_name, entry.clone()); |
| 341 | } |
| 342 | |
| 343 | // 2. Write recursive Git tree objects |
| 344 | let tree_oid = write_dir_node_recursive(git_dir, &root_node)?; |
| 345 | |
| 346 | // 3. Resolve parent Git commit OIDs: |
| 347 | // If `parent_changesets` is empty, parent is `base_git_oid` (unless `base_git_oid == GitOid::ZERO`). |
| 348 | // Otherwise, materialize/lookup each parent changeset's `GitOid`. |
| 349 | let mut parent_commit_oids = Vec::new(); |
| 350 | if stored.envelope.parent_changesets.is_empty() { |
| 351 | if stored.envelope.base_git_oid != GitOid::ZERO { |
| 352 | parent_commit_oids.push(stored.envelope.base_git_oid); |
| 353 | } |
| 354 | } else { |
| 355 | for &parent_cs in &stored.envelope.parent_changesets { |
| 356 | let parent_oid = if let Some(existing) = index.commit_for_changeset(parent_cs) { |
| 357 | existing |
| 358 | } else { |
| 359 | materialize_changeset_to_git( |
| 360 | service, |
| 361 | index, |
| 362 | git_dir, |
| 363 | parent_cs, |
| 364 | None, |
| 365 | snapshot_seq, |
| 366 | )? |
| 367 | .commit_oid |
| 368 | }; |
| 369 | parent_commit_oids.push(parent_oid); |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | // 4. Format deterministic Git commit payload |
| 374 | let timestamp_sec = stored.envelope.created_at_ms / 1000; |
| 375 | let mut commit_payload = String::new(); |
| 376 | commit_payload.push_str(&format!("tree {}\n", tree_oid.to_hex())); |
| 377 | for p in &parent_commit_oids { |
| 378 | commit_payload.push_str(&format!("parent {}\n", p.to_hex())); |
| 379 | } |
| 380 | commit_payload.push_str(&format!( |
| 381 | "author {} <agent@synapse.aienos.local> {} +0000\n", |
| 382 | stored.envelope.author_did, timestamp_sec |
| 383 | )); |
| 384 | commit_payload.push_str(&format!( |
| 385 | "committer Synapse Engine <synapse@aienos.local> {} +0000\n\n", |
| 386 | timestamp_sec |
| 387 | )); |
| 388 | commit_payload.push_str(&stored.envelope.intent_summary); |
| 389 | commit_payload.push_str(&format!( |
| 390 | "\n\nSynapse-Changeset-Id: {}\nSynapse-Wal-Seq: {}\n", |
| 391 | changeset_id.to_hex(), |
| 392 | stored.committed_seq.0 |
| 393 | )); |
| 394 | |
| 395 | let commit_oid = write_git_loose_object(git_dir, "commit", commit_payload.as_bytes())?; |
| 396 | index.record(changeset_id, commit_oid, tree_oid); |
| 397 | |
| 398 | // 5. Write explicit Synapse changeset ref and optional agent lane ref (never touching human branches!) |
| 399 | let cs_ref = changeset_git_ref(changeset_id); |
| 400 | write_git_ref(git_dir, &cs_ref, commit_oid)?; |
| 401 | |
| 402 | let lane_ref = if let Some(lane) = agent_lane { |
| 403 | let r = agent_lane_head_ref(lane); |
| 404 | write_git_ref(git_dir, &r, commit_oid)?; |
| 405 | Some(r) |
| 406 | } else { |
| 407 | None |
| 408 | }; |
| 409 | |
| 410 | Ok(MaterializedGitCommit { |
| 411 | changeset_id, |
| 412 | commit_oid, |
| 413 | tree_oid, |
| 414 | parent_commit_oids, |
| 415 | changeset_ref: cs_ref, |
| 416 | agent_lane_ref: lane_ref, |
| 417 | }) |
| 418 | } |
| 419 | |
| 420 | fn validate_human_branch_name(branch: &str) -> SynapseResult<()> { |
| 421 | if branch.is_empty() |
| 422 | || branch.starts_with('/') |
| 423 | || branch.ends_with('/') |
| 424 | || branch.starts_with('.') |
| 425 | || branch.ends_with(".lock") |
| 426 | || branch.contains("..") |
| 427 | || branch.contains("//") |
| 428 | || branch.contains("@{") |
| 429 | || branch.contains('\\') |
| 430 | || branch |
| 431 | .bytes() |
| 432 | .any(|b| b <= b' ' || b == 0x7f || matches!(b, b'~' | b'^' | b':' | b'?' | b'*' | b'[')) |
| 433 | { |
| 434 | return Err(SynapseError::new( |
| 435 | RefusalCode::PathInvalid, |
| 436 | format!("invalid human branch name: {branch}"), |
| 437 | )); |
| 438 | } |
| 439 | Ok(()) |
| 440 | } |
| 441 | |
| 442 | /// Unauthenticated crate-private helper that advances `refs/heads/<branch>` only if |
| 443 | /// `new_commit_oid` is a fast-forward descendant of the current branch head. |
| 444 | fn advance_human_branch_fast_forward_unchecked( |
| 445 | git_dir: &Path, |
| 446 | branch: &str, |
| 447 | new_commit_oid: GitOid, |
| 448 | ) -> SynapseResult<()> { |
| 449 | validate_human_branch_name(branch)?; |
| 450 | let ref_name = format!("refs/heads/{branch}"); |
| 451 | let rev_out = Command::new("git") |
| 452 | .arg("--git-dir") |
| 453 | .arg(git_dir) |
| 454 | .arg("rev-parse") |
| 455 | .arg("--verify") |
| 456 | .arg(&ref_name) |
| 457 | .output() |
| 458 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 459 | |
| 460 | if rev_out.status.success() { |
| 461 | let current_hex = String::from_utf8_lossy(&rev_out.stdout).trim().to_string(); |
| 462 | let ff_check = Command::new("git") |
| 463 | .arg("--git-dir") |
| 464 | .arg(git_dir) |
| 465 | .arg("merge-base") |
| 466 | .arg("--is-ancestor") |
| 467 | .arg(¤t_hex) |
| 468 | .arg(new_commit_oid.to_hex()) |
| 469 | .status() |
| 470 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 471 | if !ff_check.success() { |
| 472 | return Err(SynapseError::new( |
| 473 | RefusalCode::GitRefNonFastForward, |
| 474 | format!( |
| 475 | "refusing non-fast-forward update of human branch {ref_name} from {current_hex} to {new_commit_oid}" |
| 476 | ), |
| 477 | )); |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | write_git_ref_raw(git_dir, &ref_name, new_commit_oid) |
| 482 | } |
| 483 | |
| 484 | /// Advance a human-facing branch (`refs/heads/<branch>`) after authorizing `Capability::Publish` |
| 485 | /// at `BoundaryKind::Export` via `SynapseService::authorize_export`, and ONLY if `new_commit_oid` |
| 486 | /// is a fast-forward descendant of the current branch head (refusing non-fast-forward updates |
| 487 | /// with `RefusalCode::GitRefNonFastForward`). |
| 488 | pub fn advance_human_branch_fast_forward( |
| 489 | service: &mut SynapseService, |
| 490 | git_dir: &Path, |
| 491 | req: &AuthenticatedRequest<HumanBranchAdvanceRequest>, |
| 492 | now_ms: u64, |
| 493 | ) -> SynapseResult<()> { |
| 494 | service.authorize_export("advance_human_branch_fast_forward", req, now_ms)?; |
| 495 | advance_human_branch_fast_forward_unchecked( |
| 496 | git_dir, |
| 497 | &req.payload.branch, |
| 498 | req.payload.new_commit_oid, |
| 499 | ) |
| 500 | } |
| 501 | |
| 502 | /// Build and record a bounded `GitHubPullRequestProjection` (`Capability::Publish` at `BoundaryKind::Export`). |
| 503 | /// Summarizes evidence digests in markdown while keeping bulky machine logs inside Synapse. |
| 504 | pub fn project_github_pull_request( |
| 505 | service: &mut SynapseService, |
| 506 | index: &GitProjectionIndex, |
| 507 | req: &AuthenticatedRequest<GitHubPrProjectionRequest>, |
| 508 | now_ms: u64, |
| 509 | ) -> SynapseResult<GitHubPullRequestProjection> { |
| 510 | let repo_id = service.repo_id().clone(); |
| 511 | service.authorize_export("project_github_pr", req, now_ms)?; |
| 512 | |
| 513 | let stored = |
| 514 | service |
| 515 | .store() |
| 516 | .get_changeset_in_repo(&repo_id, req.payload.changeset_id, None, None)?; |
| 517 | let head_git_oid = index |
| 518 | .commit_for_changeset(req.payload.changeset_id) |
| 519 | .ok_or_else(|| { |
| 520 | SynapseError::new( |
| 521 | RefusalCode::GitObjectCorrupt, |
| 522 | format!( |
| 523 | "changeset {} must be materialized to Git before projecting a GitHub PR", |
| 524 | req.payload.changeset_id |
| 525 | ), |
| 526 | ) |
| 527 | })?; |
| 528 | |
| 529 | let mut hasher = Sha256::new(); |
| 530 | hasher.update(b"SYNAPSE_GH_PR_EVIDENCE_V1\0"); |
| 531 | let mut table_rows = String::new(); |
| 532 | for ev in &stored.evaluations { |
| 533 | hasher.update(ev.gate_name.as_bytes()); |
| 534 | hasher.update([u8::from(ev.passed)]); |
| 535 | hasher.update(ev.artifact_digest); |
| 536 | table_rows.push_str(&format!( |
| 537 | "| `{}` | `{}` | `{}` | {} |\n", |
| 538 | ev.gate_name, |
| 539 | if ev.passed { "PASS" } else { "FAIL" }, |
| 540 | hex::encode(&ev.artifact_digest[..8]), |
| 541 | ev.summary |
| 542 | )); |
| 543 | } |
| 544 | let evidence_summary_digest: [u8; 32] = hasher.finalize().into(); |
| 545 | |
| 546 | let body_markdown = format!( |
| 547 | "### Synapse Projection Summary\n\ |
| 548 | * **ChangesetId**: `{}`\n\ |
| 549 | * **Git Commit OID**: `{}`\n\ |
| 550 | * **Base Git OID**: `{}`\n\ |
| 551 | * **Author DID**: `{}`\n\ |
| 552 | * **Evidence Summary Digest**: `{}`\n\n\ |
| 553 | | Gate | Verdict | Artifact Digest (prefix) | Summary |\n\ |
| 554 | | :--- | :--- | :--- | :--- |\n\ |
| 555 | {}", |
| 556 | req.payload.changeset_id, |
| 557 | head_git_oid, |
| 558 | stored.envelope.base_git_oid, |
| 559 | stored.envelope.author_did, |
| 560 | hex::encode(evidence_summary_digest), |
| 561 | table_rows |
| 562 | ); |
| 563 | |
| 564 | let projection = GitHubPullRequestProjection { |
| 565 | repo_id, |
| 566 | pr_number: req.payload.pr_number, |
| 567 | changeset_id: req.payload.changeset_id, |
| 568 | head_git_oid, |
| 569 | base_git_oid: stored.envelope.base_git_oid, |
| 570 | pr_branch_ref: req.payload.pr_branch_ref.clone(), |
| 571 | title: req.payload.title.clone(), |
| 572 | body_markdown, |
| 573 | evidence_summary_digest, |
| 574 | github_merged: req.payload.github_merged, |
| 575 | }; |
| 576 | |
| 577 | service |
| 578 | .store_mut() |
| 579 | .record_github_projection(projection.clone())?; |
| 580 | Ok(projection) |
| 581 | } |
| 582 | |
| 583 | #[cfg(test)] |
| 584 | mod tests { |
| 585 | use super::*; |
| 586 | use ed25519_dalek::SigningKey; |
| 587 | use synapse_api::SubmitChangesetPayload; |
| 588 | use synapse_auth::{AgentCapabilityGrant, Capability}; |
| 589 | use synapse_core::{ |
| 590 | encode_did_key_ed25519, BlobDigest, ChangesetEnvelope, EvidenceAttachment, FileMode, |
| 591 | IdempotencyKey, MutationOp, PathMutation, RepoId, SYNAPSE_ENVELOPE_VERSION, |
| 592 | }; |
| 593 | use synapse_store::{FsyncPolicy, IngestOutcome, RecoveryPolicy, StoreLimits}; |
| 594 | |
| 595 | fn temp_dir(label: &str) -> std::path::PathBuf { |
| 596 | let dir = std::env::temp_dir().join(format!( |
| 597 | "synapse-git-test-{}-{}-{}", |
| 598 | label, |
| 599 | std::process::id(), |
| 600 | std::time::SystemTime::now() |
| 601 | .duration_since(std::time::UNIX_EPOCH) |
| 602 | .unwrap() |
| 603 | .as_nanos() |
| 604 | )); |
| 605 | let _ = fs::remove_dir_all(&dir); |
| 606 | fs::create_dir_all(&dir).unwrap(); |
| 607 | dir |
| 608 | } |
| 609 | |
| 610 | #[test] |
| 611 | fn test_git_materialization_fsck_clone_fetch_and_human_branch_protection() { |
| 612 | let work = temp_dir("materialize-clone"); |
| 613 | let bare_git_dir = work.join("origin.git"); |
| 614 | let clone_dir = work.join("client-clone"); |
| 615 | let svc_dir = work.join("synapse-service"); |
| 616 | |
| 617 | // 1. Initialize bare Git repository |
| 618 | Command::new("git") |
| 619 | .args(["init", "--bare"]) |
| 620 | .arg(&bare_git_dir) |
| 621 | .output() |
| 622 | .unwrap(); |
| 623 | |
| 624 | let repo_id = RepoId::new("aien-spark/synapse").unwrap(); |
| 625 | let mut svc = SynapseService::open( |
| 626 | &svc_dir, |
| 627 | repo_id.clone(), |
| 628 | FsyncPolicy::EveryCommit, |
| 629 | RecoveryPolicy::StrictFailClosed, |
| 630 | StoreLimits::default(), |
| 631 | ) |
| 632 | .unwrap(); |
| 633 | |
| 634 | let auth_key = SigningKey::from_bytes(&[40u8; 32]); |
| 635 | let auth_did = encode_did_key_ed25519(&auth_key.verifying_key().to_bytes()); |
| 636 | svc.register_authority(auth_did); |
| 637 | |
| 638 | let agent_key = SigningKey::from_bytes(&[41u8; 32]); |
| 639 | let agent_did = encode_did_key_ed25519(&agent_key.verifying_key().to_bytes()); |
| 640 | let grant = AgentCapabilityGrant::issue( |
| 641 | &auth_key, |
| 642 | [1u8; 32], |
| 643 | repo_id.clone(), |
| 644 | agent_did, |
| 645 | vec![ |
| 646 | Capability::Read, |
| 647 | Capability::Propose, |
| 648 | Capability::Evaluate, |
| 649 | Capability::Publish, |
| 650 | ], |
| 651 | 1024 * 1024, |
| 652 | 100, |
| 653 | 60_000, |
| 654 | 10, |
| 655 | 100_000, |
| 656 | ); |
| 657 | |
| 658 | // Register empty initial base tree (`GitOid::ZERO`) |
| 659 | svc.register_base_tree(GitOid::ZERO, vec![]).unwrap(); |
| 660 | |
| 661 | // 2. Submit Changeset 1 with nested directories + files |
| 662 | let cargo_toml = b"[package]\nname = \"demo\"\nversion = \"0.1.0\"\n"; |
| 663 | let main_rs = b"fn main() {\n println!(\"hello from synapse-git\");\n}\n"; |
| 664 | let d_cargo = BlobDigest::compute(cargo_toml); |
| 665 | let d_main = BlobDigest::compute(main_rs); |
| 666 | |
| 667 | let mut env1 = ChangesetEnvelope { |
| 668 | version: SYNAPSE_ENVELOPE_VERSION, |
| 669 | repo_id: repo_id.clone(), |
| 670 | base_git_oid: GitOid::ZERO, |
| 671 | parent_changesets: vec![], |
| 672 | author_did: String::new(), |
| 673 | idempotency_key: IdempotencyKey::from_label("git-cs1"), |
| 674 | created_at_ms: 1_700_000_000_000, |
| 675 | intent_summary: "Initial commit via Synapse".to_string(), |
| 676 | mutations: vec![ |
| 677 | PathMutation { |
| 678 | path: "Cargo.toml".to_string(), |
| 679 | op: MutationOp::Upsert { |
| 680 | mode: FileMode::Regular644, |
| 681 | blob_digest: d_cargo, |
| 682 | size_bytes: cargo_toml.len() as u64, |
| 683 | }, |
| 684 | }, |
| 685 | PathMutation { |
| 686 | path: "src/main.rs".to_string(), |
| 687 | op: MutationOp::Upsert { |
| 688 | mode: FileMode::Regular644, |
| 689 | blob_digest: d_main, |
| 690 | size_bytes: main_rs.len() as u64, |
| 691 | }, |
| 692 | }, |
| 693 | ], |
| 694 | evidence_receipts: vec![], |
| 695 | signature: vec![], |
| 696 | }; |
| 697 | env1.sign(&agent_key); |
| 698 | let sub1 = AuthenticatedRequest::sign_new( |
| 699 | &agent_key, |
| 700 | grant.clone(), |
| 701 | repo_id.clone(), |
| 702 | Capability::Propose, |
| 703 | [1u8; 32], |
| 704 | 1_000, |
| 705 | 0, |
| 706 | SubmitChangesetPayload { |
| 707 | envelope: env1, |
| 708 | blobs: vec![(d_cargo, cargo_toml.to_vec()), (d_main, main_rs.to_vec())], |
| 709 | }, |
| 710 | ) |
| 711 | .unwrap(); |
| 712 | let cs1_id = match svc.submit(&sub1, 1_000).unwrap() { |
| 713 | IngestOutcome::Committed { changeset_id, .. } => changeset_id, |
| 714 | _ => unreachable!(), |
| 715 | }; |
| 716 | |
| 717 | // 3. Materialize cs1 into `bare_git_dir` using pure-Rust loose object writer |
| 718 | let mut index = GitProjectionIndex::new(); |
| 719 | let mat1 = materialize_changeset_to_git( |
| 720 | &mut svc, |
| 721 | &mut index, |
| 722 | &bare_git_dir, |
| 723 | cs1_id, |
| 724 | Some("lane-alpha"), |
| 725 | None, |
| 726 | ) |
| 727 | .unwrap(); |
| 728 | // Materializing a second time must produce the exact same deterministic GitOid |
| 729 | let mat1_repeat = materialize_changeset_to_git( |
| 730 | &mut svc, |
| 731 | &mut index, |
| 732 | &bare_git_dir, |
| 733 | cs1_id, |
| 734 | Some("lane-alpha"), |
| 735 | None, |
| 736 | ) |
| 737 | .unwrap(); |
| 738 | assert_eq!(mat1.commit_oid, mat1_repeat.commit_oid); |
| 739 | assert_eq!(index.changeset_for_commit(mat1.commit_oid), Some(cs1_id)); |
| 740 | |
| 741 | // Fast-forward human `main` branch to `mat1.commit_oid` |
| 742 | let adv1_req = AuthenticatedRequest::sign_new( |
| 743 | &agent_key, |
| 744 | grant.clone(), |
| 745 | repo_id.clone(), |
| 746 | Capability::Publish, |
| 747 | [11u8; 32], |
| 748 | 1_500, |
| 749 | 0, |
| 750 | HumanBranchAdvanceRequest { |
| 751 | branch: "main".to_string(), |
| 752 | new_commit_oid: mat1.commit_oid, |
| 753 | }, |
| 754 | ) |
| 755 | .unwrap(); |
| 756 | advance_human_branch_fast_forward(&mut svc, &bare_git_dir, &adv1_req, 1_500).unwrap(); |
| 757 | |
| 758 | // 4. Verify `git fsck --full --strict` passes with zero errors or warnings |
| 759 | let fsck_out = Command::new("git") |
| 760 | .arg("--git-dir") |
| 761 | .arg(&bare_git_dir) |
| 762 | .args(["fsck", "--full", "--strict"]) |
| 763 | .output() |
| 764 | .unwrap(); |
| 765 | assert!( |
| 766 | fsck_out.status.success(), |
| 767 | "git fsck failed: {}", |
| 768 | String::from_utf8_lossy(&fsck_out.stderr) |
| 769 | ); |
| 770 | |
| 771 | // 5. Ordinary `git clone` of `bare_git_dir` into `clone_dir` |
| 772 | let clone_out = Command::new("git") |
| 773 | .args(["clone", "--branch", "main"]) |
| 774 | .arg(&bare_git_dir) |
| 775 | .arg(&clone_dir) |
| 776 | .output() |
| 777 | .unwrap(); |
| 778 | assert!( |
| 779 | clone_out.status.success(), |
| 780 | "git clone failed: {}", |
| 781 | String::from_utf8_lossy(&clone_out.stderr) |
| 782 | ); |
| 783 | assert_eq!(fs::read(clone_dir.join("Cargo.toml")).unwrap(), cargo_toml); |
| 784 | assert_eq!(fs::read(clone_dir.join("src/main.rs")).unwrap(), main_rs); |
| 785 | |
| 786 | // 6. Submit stacked Changeset 2 and materialize it to `refs/synapse/agent-head/lane-alpha`, |
| 787 | // then verify `git fetch origin refs/synapse/agent-head/lane-alpha` works in `clone_dir`! |
| 788 | let readme = b"# Demo\n"; |
| 789 | let d_readme = BlobDigest::compute(readme); |
| 790 | let mut env2 = ChangesetEnvelope { |
| 791 | version: SYNAPSE_ENVELOPE_VERSION, |
| 792 | repo_id: repo_id.clone(), |
| 793 | base_git_oid: GitOid::ZERO, |
| 794 | parent_changesets: vec![cs1_id], |
| 795 | author_did: String::new(), |
| 796 | idempotency_key: IdempotencyKey::from_label("git-cs2"), |
| 797 | created_at_ms: 1_700_000_060_000, |
| 798 | intent_summary: "Add README.md on lane-alpha".to_string(), |
| 799 | mutations: vec![PathMutation { |
| 800 | path: "README.md".to_string(), |
| 801 | op: MutationOp::Upsert { |
| 802 | mode: FileMode::Regular644, |
| 803 | blob_digest: d_readme, |
| 804 | size_bytes: readme.len() as u64, |
| 805 | }, |
| 806 | }], |
| 807 | evidence_receipts: vec![], |
| 808 | signature: vec![], |
| 809 | }; |
| 810 | env2.sign(&agent_key); |
| 811 | let sub2 = AuthenticatedRequest::sign_new( |
| 812 | &agent_key, |
| 813 | grant.clone(), |
| 814 | repo_id.clone(), |
| 815 | Capability::Propose, |
| 816 | [2u8; 32], |
| 817 | 2_000, |
| 818 | 0, |
| 819 | SubmitChangesetPayload { |
| 820 | envelope: env2, |
| 821 | blobs: vec![(d_readme, readme.to_vec())], |
| 822 | }, |
| 823 | ) |
| 824 | .unwrap(); |
| 825 | let cs2_id = match svc.submit(&sub2, 2_000).unwrap() { |
| 826 | IngestOutcome::Committed { changeset_id, .. } => changeset_id, |
| 827 | _ => unreachable!(), |
| 828 | }; |
| 829 | let mat2 = materialize_changeset_to_git( |
| 830 | &mut svc, |
| 831 | &mut index, |
| 832 | &bare_git_dir, |
| 833 | cs2_id, |
| 834 | Some("lane-alpha"), |
| 835 | None, |
| 836 | ) |
| 837 | .unwrap(); |
| 838 | assert_eq!(mat2.parent_commit_oids, vec![mat1.commit_oid]); |
| 839 | |
| 840 | let fetch_out = Command::new("git") |
| 841 | .current_dir(&clone_dir) |
| 842 | .args(["fetch", "origin", "refs/synapse/agent-head/lane-alpha"]) |
| 843 | .output() |
| 844 | .unwrap(); |
| 845 | assert!(fetch_out.status.success()); |
| 846 | |
| 847 | // 7. Verify non-fast-forward human branch protection: |
| 848 | // Advance human `main` to `mat2.commit_oid` (fast-forward succeeds), |
| 849 | // then attempt to move human `main` backwards to `mat1.commit_oid` -> refused with GitRefNonFastForward! |
| 850 | let adv2_req = AuthenticatedRequest::sign_new( |
| 851 | &agent_key, |
| 852 | grant.clone(), |
| 853 | repo_id.clone(), |
| 854 | Capability::Publish, |
| 855 | [12u8; 32], |
| 856 | 2_500, |
| 857 | 0, |
| 858 | HumanBranchAdvanceRequest { |
| 859 | branch: "main".to_string(), |
| 860 | new_commit_oid: mat2.commit_oid, |
| 861 | }, |
| 862 | ) |
| 863 | .unwrap(); |
| 864 | advance_human_branch_fast_forward(&mut svc, &bare_git_dir, &adv2_req, 2_500).unwrap(); |
| 865 | let adv_back_req = AuthenticatedRequest::sign_new( |
| 866 | &agent_key, |
| 867 | grant.clone(), |
| 868 | repo_id.clone(), |
| 869 | Capability::Publish, |
| 870 | [13u8; 32], |
| 871 | 2_600, |
| 872 | 0, |
| 873 | HumanBranchAdvanceRequest { |
| 874 | branch: "main".to_string(), |
| 875 | new_commit_oid: mat1.commit_oid, |
| 876 | }, |
| 877 | ) |
| 878 | .unwrap(); |
| 879 | let non_ff_err = |
| 880 | advance_human_branch_fast_forward(&mut svc, &bare_git_dir, &adv_back_req, 2_600) |
| 881 | .unwrap_err(); |
| 882 | assert_eq!(non_ff_err.code, RefusalCode::GitRefNonFastForward); |
| 883 | |
| 884 | // 8. Attach evaluation receipt and build GitHub PR projection (`Capability::Publish`) |
| 885 | svc.store_mut() |
| 886 | .attach_evaluation( |
| 887 | cs2_id, |
| 888 | EvidenceAttachment { |
| 889 | gate_name: "cargo-test".to_string(), |
| 890 | passed: true, |
| 891 | artifact_digest: [0xab; 32], |
| 892 | summary: "14 passed, 0 failed".to_string(), |
| 893 | }, |
| 894 | ) |
| 895 | .unwrap(); |
| 896 | |
| 897 | // A shared store must not expose another repository through PR projection. |
| 898 | let mut foreign = svc |
| 899 | .store() |
| 900 | .get_changeset(cs2_id, None, None) |
| 901 | .unwrap() |
| 902 | .envelope; |
| 903 | foreign.repo_id = RepoId::new("example/foreign").unwrap(); |
| 904 | foreign.parent_changesets.clear(); |
| 905 | foreign.idempotency_key = IdempotencyKey::from_label("foreign-projection"); |
| 906 | foreign.sign(&agent_key); |
| 907 | let foreign_id = match svc.store_mut().ingest_changeset(foreign, &[]).unwrap() { |
| 908 | IngestOutcome::Committed { changeset_id, .. } => changeset_id, |
| 909 | _ => unreachable!(), |
| 910 | }; |
| 911 | let foreign_req = AuthenticatedRequest::sign_new( |
| 912 | &agent_key, |
| 913 | grant.clone(), |
| 914 | repo_id.clone(), |
| 915 | Capability::Publish, |
| 916 | Sha256::digest(b"foreign-projection-request").into(), |
| 917 | 2_900, |
| 918 | 0, |
| 919 | GitHubPrProjectionRequest { |
| 920 | pr_number: 43, |
| 921 | changeset_id: foreign_id, |
| 922 | pr_branch_ref: "refs/synapse/agent-head/foreign".to_string(), |
| 923 | title: "must not expose foreign evidence".to_string(), |
| 924 | github_merged: false, |
| 925 | }, |
| 926 | ) |
| 927 | .unwrap(); |
| 928 | assert_eq!( |
| 929 | project_github_pull_request(&mut svc, &index, &foreign_req, 2_900) |
| 930 | .unwrap_err() |
| 931 | .code, |
| 932 | RefusalCode::ChangesetNotFound |
| 933 | ); |
| 934 | |
| 935 | let pr_req = AuthenticatedRequest::sign_new( |
| 936 | &agent_key, |
| 937 | grant, |
| 938 | repo_id, |
| 939 | Capability::Publish, |
| 940 | [3u8; 32], |
| 941 | 3_000, |
| 942 | 0, |
| 943 | GitHubPrProjectionRequest { |
| 944 | pr_number: 42, |
| 945 | changeset_id: cs2_id, |
| 946 | pr_branch_ref: "refs/synapse/agent-head/lane-alpha".to_string(), |
| 947 | title: "feat: Add README.md".to_string(), |
| 948 | github_merged: false, |
| 949 | }, |
| 950 | ) |
| 951 | .unwrap(); |
| 952 | let proj = project_github_pull_request(&mut svc, &index, &pr_req, 3_000).unwrap(); |
| 953 | assert_eq!(proj.head_git_oid, mat2.commit_oid); |
| 954 | assert!(proj.body_markdown.contains("cargo-test")); |
| 955 | |
| 956 | let _ = fs::remove_dir_all(&work); |
| 957 | } |
| 958 | |
| 959 | #[test] |
| 960 | fn test_advance_human_branch_requires_publish_capability_and_rejects_bypass() { |
| 961 | let work = temp_dir("publish-gate"); |
| 962 | let bare_git_dir = work.join("origin.git"); |
| 963 | let svc_dir = work.join("synapse-service"); |
| 964 | |
| 965 | Command::new("git") |
| 966 | .args(["init", "--bare"]) |
| 967 | .arg(&bare_git_dir) |
| 968 | .output() |
| 969 | .unwrap(); |
| 970 | |
| 971 | let repo_id = RepoId::new("aien-spark/synapse").unwrap(); |
| 972 | let mut svc = SynapseService::open( |
| 973 | &svc_dir, |
| 974 | repo_id.clone(), |
| 975 | FsyncPolicy::EveryCommit, |
| 976 | RecoveryPolicy::StrictFailClosed, |
| 977 | StoreLimits::default(), |
| 978 | ) |
| 979 | .unwrap(); |
| 980 | |
| 981 | let auth_key = SigningKey::from_bytes(&[50u8; 32]); |
| 982 | let auth_did = encode_did_key_ed25519(&auth_key.verifying_key().to_bytes()); |
| 983 | svc.register_authority(auth_did); |
| 984 | svc.register_base_tree(GitOid::ZERO, vec![]).unwrap(); |
| 985 | |
| 986 | let author_key = SigningKey::from_bytes(&[51u8; 32]); |
| 987 | let author_did = encode_did_key_ed25519(&author_key.verifying_key().to_bytes()); |
| 988 | let no_publish_grant = AgentCapabilityGrant::issue( |
| 989 | &auth_key, |
| 990 | [21u8; 32], |
| 991 | repo_id.clone(), |
| 992 | author_did.clone(), |
| 993 | vec![ |
| 994 | Capability::Read, |
| 995 | Capability::Propose, |
| 996 | Capability::Evaluate, |
| 997 | Capability::Review, |
| 998 | ], |
| 999 | 1024 * 1024, |
| 1000 | 100, |
| 1001 | 60_000, |
| 1002 | 10, |
| 1003 | 100_000, |
| 1004 | ); |
| 1005 | |
| 1006 | let body = b"fn gated() {} |
| 1007 | "; |
| 1008 | let d_body = BlobDigest::compute(body); |
| 1009 | let mut env = ChangesetEnvelope { |
| 1010 | version: SYNAPSE_ENVELOPE_VERSION, |
| 1011 | repo_id: repo_id.clone(), |
| 1012 | base_git_oid: GitOid::ZERO, |
| 1013 | parent_changesets: vec![], |
| 1014 | author_did: String::new(), |
| 1015 | idempotency_key: IdempotencyKey::from_label("publish-gate-cs1"), |
| 1016 | created_at_ms: 1_700_000_000_000, |
| 1017 | intent_summary: "Propose gated change".to_string(), |
| 1018 | mutations: vec![PathMutation { |
| 1019 | path: "src/lib.rs".to_string(), |
| 1020 | op: MutationOp::Upsert { |
| 1021 | mode: FileMode::Regular644, |
| 1022 | blob_digest: d_body, |
| 1023 | size_bytes: body.len() as u64, |
| 1024 | }, |
| 1025 | }], |
| 1026 | evidence_receipts: vec![], |
| 1027 | signature: vec![], |
| 1028 | }; |
| 1029 | env.sign(&author_key); |
| 1030 | let sub_req = AuthenticatedRequest::sign_new( |
| 1031 | &author_key, |
| 1032 | no_publish_grant.clone(), |
| 1033 | repo_id.clone(), |
| 1034 | Capability::Propose, |
| 1035 | [22u8; 32], |
| 1036 | 1_000, |
| 1037 | 0, |
| 1038 | SubmitChangesetPayload { |
| 1039 | envelope: env, |
| 1040 | blobs: vec![(d_body, body.to_vec())], |
| 1041 | }, |
| 1042 | ) |
| 1043 | .unwrap(); |
| 1044 | let cs_id = match svc.submit(&sub_req, 1_000).unwrap() { |
| 1045 | IngestOutcome::Committed { changeset_id, .. } => changeset_id, |
| 1046 | _ => unreachable!(), |
| 1047 | }; |
| 1048 | |
| 1049 | // Attach a passing evaluation receipt to verify that passing validation never grants Publish. |
| 1050 | svc.store_mut() |
| 1051 | .attach_evaluation( |
| 1052 | cs_id, |
| 1053 | EvidenceAttachment { |
| 1054 | gate_name: "cargo-test".to_string(), |
| 1055 | passed: true, |
| 1056 | artifact_digest: [0xcd; 32], |
| 1057 | summary: "all tests passed".to_string(), |
| 1058 | }, |
| 1059 | ) |
| 1060 | .unwrap(); |
| 1061 | |
| 1062 | let mut index = GitProjectionIndex::new(); |
| 1063 | let mat = materialize_changeset_to_git( |
| 1064 | &mut svc, |
| 1065 | &mut index, |
| 1066 | &bare_git_dir, |
| 1067 | cs_id, |
| 1068 | Some("lane-beta"), |
| 1069 | None, |
| 1070 | ) |
| 1071 | .unwrap(); |
| 1072 | |
| 1073 | // Direct write_git_ref to refs/heads/main is refused as PathInvalid. |
| 1074 | let direct_err = |
| 1075 | write_git_ref(&bare_git_dir, "refs/heads/main", mat.commit_oid).unwrap_err(); |
| 1076 | assert_eq!(direct_err.code, RefusalCode::PathInvalid); |
| 1077 | assert!(!bare_git_dir.join("refs/heads/main").exists()); |
| 1078 | |
| 1079 | // 1. Grant without Capability::Publish is refused with AuthCapabilityDenied; ref does not move. |
| 1080 | let unauth_req = AuthenticatedRequest::sign_new( |
| 1081 | &author_key, |
| 1082 | no_publish_grant.clone(), |
| 1083 | repo_id.clone(), |
| 1084 | Capability::Publish, |
| 1085 | [23u8; 32], |
| 1086 | 1_100, |
| 1087 | 0, |
| 1088 | HumanBranchAdvanceRequest { |
| 1089 | branch: "main".to_string(), |
| 1090 | new_commit_oid: mat.commit_oid, |
| 1091 | }, |
| 1092 | ) |
| 1093 | .unwrap(); |
| 1094 | let err = advance_human_branch_fast_forward(&mut svc, &bare_git_dir, &unauth_req, 1_100) |
| 1095 | .unwrap_err(); |
| 1096 | assert_eq!(err.code, RefusalCode::AuthCapabilityDenied); |
| 1097 | assert!(!bare_git_dir.join("refs/heads/main").exists()); |
| 1098 | |
| 1099 | // 2. Request signed with Capability::Propose instead of Capability::Publish is refused. |
| 1100 | let wrong_cap_req = AuthenticatedRequest::sign_new( |
| 1101 | &author_key, |
| 1102 | no_publish_grant, |
| 1103 | repo_id.clone(), |
| 1104 | Capability::Propose, |
| 1105 | [24u8; 32], |
| 1106 | 1_200, |
| 1107 | 0, |
| 1108 | HumanBranchAdvanceRequest { |
| 1109 | branch: "main".to_string(), |
| 1110 | new_commit_oid: mat.commit_oid, |
| 1111 | }, |
| 1112 | ) |
| 1113 | .unwrap(); |
| 1114 | let err = advance_human_branch_fast_forward(&mut svc, &bare_git_dir, &wrong_cap_req, 1_200) |
| 1115 | .unwrap_err(); |
| 1116 | assert_eq!(err.code, RefusalCode::AuthCapabilityDenied); |
| 1117 | assert!(!bare_git_dir.join("refs/heads/main").exists()); |
| 1118 | |
| 1119 | // 3. Cross-repo grant is refused with AuthCrossRepoDenied. |
| 1120 | let other_repo = RepoId::new("aien-spark/other").unwrap(); |
| 1121 | let cross_grant = AgentCapabilityGrant::issue( |
| 1122 | &auth_key, |
| 1123 | [25u8; 32], |
| 1124 | other_repo.clone(), |
| 1125 | author_did.clone(), |
| 1126 | vec![Capability::Publish], |
| 1127 | 1024 * 1024, |
| 1128 | 100, |
| 1129 | 60_000, |
| 1130 | 10, |
| 1131 | 100_000, |
| 1132 | ); |
| 1133 | let cross_req = AuthenticatedRequest::sign_new( |
| 1134 | &author_key, |
| 1135 | cross_grant, |
| 1136 | other_repo, |
| 1137 | Capability::Publish, |
| 1138 | [26u8; 32], |
| 1139 | 1_300, |
| 1140 | 0, |
| 1141 | HumanBranchAdvanceRequest { |
| 1142 | branch: "main".to_string(), |
| 1143 | new_commit_oid: mat.commit_oid, |
| 1144 | }, |
| 1145 | ) |
| 1146 | .unwrap(); |
| 1147 | let err = advance_human_branch_fast_forward(&mut svc, &bare_git_dir, &cross_req, 1_300) |
| 1148 | .unwrap_err(); |
| 1149 | assert_eq!(err.code, RefusalCode::AuthCrossRepoDenied); |
| 1150 | assert!(!bare_git_dir.join("refs/heads/main").exists()); |
| 1151 | |
| 1152 | // 4. Expired Publish grant is refused with AuthGrantExpired. |
| 1153 | let publish_grant = AgentCapabilityGrant::issue( |
| 1154 | &auth_key, |
| 1155 | [27u8; 32], |
| 1156 | repo_id.clone(), |
| 1157 | author_did, |
| 1158 | vec![Capability::Publish], |
| 1159 | 1024 * 1024, |
| 1160 | 100, |
| 1161 | 60_000, |
| 1162 | 10, |
| 1163 | 5_000, |
| 1164 | ); |
| 1165 | let exp_req = AuthenticatedRequest::sign_new( |
| 1166 | &author_key, |
| 1167 | publish_grant.clone(), |
| 1168 | repo_id.clone(), |
| 1169 | Capability::Publish, |
| 1170 | [28u8; 32], |
| 1171 | 6_000, |
| 1172 | 0, |
| 1173 | HumanBranchAdvanceRequest { |
| 1174 | branch: "main".to_string(), |
| 1175 | new_commit_oid: mat.commit_oid, |
| 1176 | }, |
| 1177 | ) |
| 1178 | .unwrap(); |
| 1179 | let err = advance_human_branch_fast_forward(&mut svc, &bare_git_dir, &exp_req, 6_000) |
| 1180 | .unwrap_err(); |
| 1181 | assert_eq!(err.code, RefusalCode::AuthGrantExpired); |
| 1182 | assert!(!bare_git_dir.join("refs/heads/main").exists()); |
| 1183 | |
| 1184 | // 5. Path traversal or malformed branch name is refused even with valid Publish grant. |
| 1185 | let bad_branch_req = AuthenticatedRequest::sign_new( |
| 1186 | &author_key, |
| 1187 | publish_grant.clone(), |
| 1188 | repo_id.clone(), |
| 1189 | Capability::Publish, |
| 1190 | [29u8; 32], |
| 1191 | 2_000, |
| 1192 | 0, |
| 1193 | HumanBranchAdvanceRequest { |
| 1194 | branch: "../synapse/agent-head/lane-beta".to_string(), |
| 1195 | new_commit_oid: mat.commit_oid, |
| 1196 | }, |
| 1197 | ) |
| 1198 | .unwrap(); |
| 1199 | let err = |
| 1200 | advance_human_branch_fast_forward(&mut svc, &bare_git_dir, &bad_branch_req, 2_000) |
| 1201 | .unwrap_err(); |
| 1202 | assert_eq!(err.code, RefusalCode::PathInvalid); |
| 1203 | assert!(!bare_git_dir.join("refs/heads/main").exists()); |
| 1204 | |
| 1205 | // 6. Valid Publish grant succeeds and advances refs/heads/main; replay of the same nonce is refused. |
| 1206 | let valid_req = AuthenticatedRequest::sign_new( |
| 1207 | &author_key, |
| 1208 | publish_grant, |
| 1209 | repo_id, |
| 1210 | Capability::Publish, |
| 1211 | [30u8; 32], |
| 1212 | 2_100, |
| 1213 | 0, |
| 1214 | HumanBranchAdvanceRequest { |
| 1215 | branch: "main".to_string(), |
| 1216 | new_commit_oid: mat.commit_oid, |
| 1217 | }, |
| 1218 | ) |
| 1219 | .unwrap(); |
| 1220 | advance_human_branch_fast_forward(&mut svc, &bare_git_dir, &valid_req, 2_100).unwrap(); |
| 1221 | let head = fs::read_to_string(bare_git_dir.join("refs/heads/main")).unwrap(); |
| 1222 | assert_eq!(head.trim(), mat.commit_oid.to_hex()); |
| 1223 | |
| 1224 | let replay_err = |
| 1225 | advance_human_branch_fast_forward(&mut svc, &bare_git_dir, &valid_req, 2_101) |
| 1226 | .unwrap_err(); |
| 1227 | assert_eq!(replay_err.code, RefusalCode::AuthReplayDetected); |
| 1228 | |
| 1229 | let _ = fs::remove_dir_all(&work); |
| 1230 | } |
| 1231 | } |