synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-api / src / crumb.rs
| 1 | //! Read-only Directory Crumb context over `VirtualTree` snapshots (ADR 0004, deliverable D1). |
| 2 | //! |
| 3 | //! Reads go through `materialize_virtual_tree` and `read_blob_bytes`, the same path |
| 4 | //! `read_file` uses, after one `Capability::Read` authorization. Nothing is written and no |
| 5 | //! new capability exists: a Crumb context grants nothing. |
| 6 | |
| 7 | use crate::{SynapseService, TreeTarget, VirtualTreeEntry}; |
| 8 | use serde::{Deserialize, Serialize}; |
| 9 | use std::collections::BTreeMap; |
| 10 | use synapse_auth::{AuthenticatedRequest, BoundaryKind, Capability}; |
| 11 | use synapse_core::{ |
| 12 | validate_repo_relative_path, FileMode, RefusalCode, SynapseError, SynapseResult, WalSeq, |
| 13 | }; |
| 14 | use synapse_crumb::{CrumbContext, CrumbFile, MAX_CRUMB_BYTES, ROOT_DIR}; |
| 15 | |
| 16 | /// Request payload for [`SynapseService::crumb_context`]. |
| 17 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 18 | pub struct CrumbContextQueryPayload { |
| 19 | pub target: TreeTarget, |
| 20 | /// `"."` for the repository root, else a repository-relative file or directory. |
| 21 | pub path: String, |
| 22 | pub snapshot_seq: Option<WalSeq>, |
| 23 | } |
| 24 | |
| 25 | impl SynapseService { |
| 26 | /// Directory Crumb context for `path` in the `target` snapshot (`Capability::Read`). |
| 27 | /// |
| 28 | /// A file path resolves to its parent directory. A path absent from the snapshot is |
| 29 | /// refused with `BlobNotFound`, as `read_file` does. |
| 30 | pub fn crumb_context( |
| 31 | &mut self, |
| 32 | req: &AuthenticatedRequest<CrumbContextQueryPayload>, |
| 33 | now_ms: u64, |
| 34 | ) -> SynapseResult<CrumbContext> { |
| 35 | self.auth.authorize( |
| 36 | BoundaryKind::Api, |
| 37 | "crumb_context", |
| 38 | &self.repo_id, |
| 39 | Capability::Read, |
| 40 | req, |
| 41 | now_ms, |
| 42 | )?; |
| 43 | let payload = &req.payload; |
| 44 | let view = self.snapshot_view(payload.target, payload.snapshot_seq)?; |
| 45 | let dir = target_dir(view.tree(), &payload.path)?; |
| 46 | self.resolve_crumb_context(view.tree(), &dir, payload.snapshot_seq) |
| 47 | } |
| 48 | |
| 49 | /// Resolve the context chain for `dir` in an already materialized `tree`. No |
| 50 | /// authorization: callers authorize once before materializing. |
| 51 | pub(crate) fn resolve_crumb_context( |
| 52 | &self, |
| 53 | tree: &BTreeMap<String, VirtualTreeEntry>, |
| 54 | dir: &str, |
| 55 | snapshot_seq: Option<WalSeq>, |
| 56 | ) -> SynapseResult<CrumbContext> { |
| 57 | CrumbContext::resolve(dir, |crumb_path| match tree.get(crumb_path) { |
| 58 | None => Ok(CrumbFile::Missing), |
| 59 | Some(e) if e.mode == FileMode::Symlink120000 => Ok(CrumbFile::NotRegularFile { |
| 60 | blob_digest: e.blob_digest, |
| 61 | }), |
| 62 | Some(e) if e.size_bytes > MAX_CRUMB_BYTES => Ok(CrumbFile::Oversized { |
| 63 | blob_digest: e.blob_digest, |
| 64 | size: e.size_bytes, |
| 65 | }), |
| 66 | Some(e) => self |
| 67 | .read_blob_bytes(e.blob_digest, snapshot_seq) |
| 68 | .map(CrumbFile::Bytes), |
| 69 | }) |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | /// Directory whose context is wanted: the path itself if it is a directory in `tree`, |
| 74 | /// its parent if it is a file. |
| 75 | fn target_dir(tree: &BTreeMap<String, VirtualTreeEntry>, path: &str) -> SynapseResult<String> { |
| 76 | if path == ROOT_DIR { |
| 77 | return Ok(ROOT_DIR.to_string()); |
| 78 | } |
| 79 | validate_repo_relative_path(path)?; |
| 80 | if tree.contains_key(path) { |
| 81 | return Ok(path |
| 82 | .rsplit_once('/') |
| 83 | .map_or(ROOT_DIR.to_string(), |(parent, _)| parent.to_string())); |
| 84 | } |
| 85 | let prefix = format!("{path}/"); |
| 86 | if tree |
| 87 | .range(prefix.clone()..) |
| 88 | .next() |
| 89 | .is_some_and(|(k, _)| k.starts_with(&prefix)) |
| 90 | { |
| 91 | return Ok(path.to_string()); |
| 92 | } |
| 93 | Err(SynapseError::new( |
| 94 | RefusalCode::BlobNotFound, |
| 95 | format!("path {path} not found in virtual tree"), |
| 96 | )) |
| 97 | } |
| 98 | |
| 99 | #[cfg(test)] |
| 100 | mod tests { |
| 101 | use super::*; |
| 102 | use crate::FsyncPolicy; |
| 103 | use crate::RecoveryPolicy; |
| 104 | use crate::StoreLimits; |
| 105 | use ed25519_dalek::SigningKey; |
| 106 | use std::fs; |
| 107 | use synapse_auth::AgentCapabilityGrant; |
| 108 | use synapse_core::{encode_did_key_ed25519, BlobDigest, GitOid, RepoId}; |
| 109 | use synapse_crumb::{Dialect, DirectoryCrumb, EntryStatus, InvalidReason}; |
| 110 | |
| 111 | const ROOT: &[u8] = |
| 112 | br#"{"schema_version":"1.0.0","name":"root","purpose":"Root.","invariants":["root rule"]}"#; |
| 113 | const SRC: &[u8] = br#"{"schema_version":"1.0.0","name":"src","purpose":"Sources."}"#; |
| 114 | |
| 115 | struct Fixture { |
| 116 | svc: SynapseService, |
| 117 | agent: SigningKey, |
| 118 | auth: SigningKey, |
| 119 | repo: RepoId, |
| 120 | nonce: u8, |
| 121 | dir: std::path::PathBuf, |
| 122 | } |
| 123 | |
| 124 | impl Fixture { |
| 125 | fn new(label: &str) -> Self { |
| 126 | let dir = std::env::temp_dir().join(format!( |
| 127 | "synapse-api-crumb-{label}-{}-{}", |
| 128 | std::process::id(), |
| 129 | std::time::SystemTime::now() |
| 130 | .duration_since(std::time::UNIX_EPOCH) |
| 131 | .unwrap() |
| 132 | .as_nanos() |
| 133 | )); |
| 134 | let repo = RepoId::new("aien-spark/synapse").unwrap(); |
| 135 | let mut svc = SynapseService::open( |
| 136 | &dir, |
| 137 | repo.clone(), |
| 138 | FsyncPolicy::EveryCommit, |
| 139 | RecoveryPolicy::StrictFailClosed, |
| 140 | StoreLimits::default(), |
| 141 | ) |
| 142 | .unwrap(); |
| 143 | let auth = SigningKey::from_bytes(&[10u8; 32]); |
| 144 | svc.register_authority(encode_did_key_ed25519(&auth.verifying_key().to_bytes())); |
| 145 | Self { |
| 146 | svc, |
| 147 | agent: SigningKey::from_bytes(&[20u8; 32]), |
| 148 | auth, |
| 149 | repo, |
| 150 | nonce: 0, |
| 151 | dir, |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | fn query( |
| 156 | &mut self, |
| 157 | caps: Vec<Capability>, |
| 158 | target: TreeTarget, |
| 159 | path: &str, |
| 160 | ) -> SynapseResult<CrumbContext> { |
| 161 | self.nonce += 1; |
| 162 | let grant = AgentCapabilityGrant::issue( |
| 163 | &self.auth, |
| 164 | [self.nonce; 32], |
| 165 | self.repo.clone(), |
| 166 | encode_did_key_ed25519(&self.agent.verifying_key().to_bytes()), |
| 167 | caps, |
| 168 | 1024 * 1024, |
| 169 | 100, |
| 170 | 60_000, |
| 171 | 10, |
| 172 | 100_000, |
| 173 | ); |
| 174 | let req = AuthenticatedRequest::sign_new( |
| 175 | &self.agent, |
| 176 | grant, |
| 177 | self.repo.clone(), |
| 178 | Capability::Read, |
| 179 | [self.nonce; 32], |
| 180 | 1000 + u64::from(self.nonce), |
| 181 | 0, |
| 182 | CrumbContextQueryPayload { |
| 183 | target, |
| 184 | path: path.to_string(), |
| 185 | snapshot_seq: None, |
| 186 | }, |
| 187 | )?; |
| 188 | self.svc.crumb_context(&req, 1000 + u64::from(self.nonce)) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | impl Drop for Fixture { |
| 193 | fn drop(&mut self) { |
| 194 | let _ = fs::remove_dir_all(&self.dir); |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | fn base(fx: &mut Fixture, seed: u8, files: Vec<(&str, FileMode, Vec<u8>)>) -> TreeTarget { |
| 199 | let oid = GitOid([seed; 20]); |
| 200 | fx.svc |
| 201 | .register_base_tree( |
| 202 | oid, |
| 203 | files |
| 204 | .into_iter() |
| 205 | .map(|(p, m, b)| (p.to_string(), m, b)) |
| 206 | .collect(), |
| 207 | ) |
| 208 | .unwrap(); |
| 209 | TreeTarget::BaseGitCommit(oid) |
| 210 | } |
| 211 | |
| 212 | #[test] |
| 213 | fn reads_chain_from_snapshot_for_files_and_directories() { |
| 214 | let mut fx = Fixture::new("chain"); |
| 215 | let t = base( |
| 216 | &mut fx, |
| 217 | 1, |
| 218 | vec![ |
| 219 | (".crumb", FileMode::Regular644, ROOT.to_vec()), |
| 220 | ("src/.crumb", FileMode::Regular644, SRC.to_vec()), |
| 221 | ( |
| 222 | "src/net/http.rs", |
| 223 | FileMode::Regular644, |
| 224 | b"fn x() {}\n".to_vec(), |
| 225 | ), |
| 226 | ], |
| 227 | ); |
| 228 | let by_file = fx |
| 229 | .query(vec![Capability::Read], t, "src/net/http.rs") |
| 230 | .unwrap(); |
| 231 | assert_eq!(by_file.target_dir(), "src/net"); |
| 232 | let dirs: Vec<&str> = by_file.entries().iter().map(|e| e.dir.as_str()).collect(); |
| 233 | assert_eq!(dirs, [".", "src", "src/net"]); |
| 234 | assert_eq!(by_file.leaf().status, EntryStatus::Missing); |
| 235 | assert_eq!(by_file.nearest().unwrap().dir, "src"); |
| 236 | assert_eq!(by_file.inherited_invariants(), vec![(".", "root rule")]); |
| 237 | assert_eq!( |
| 238 | by_file.entries()[1].blob_digest, |
| 239 | Some(BlobDigest::compute(SRC)) |
| 240 | ); |
| 241 | |
| 242 | let by_dir = fx.query(vec![Capability::Read], t, "src/net").unwrap(); |
| 243 | assert_eq!(by_dir.digest(), by_file.digest()); |
| 244 | |
| 245 | let root = fx.query(vec![Capability::Read], t, ".").unwrap(); |
| 246 | assert_eq!(root.entries().len(), 1); |
| 247 | assert!(matches!( |
| 248 | root.leaf().crumb(), |
| 249 | Some(DirectoryCrumb::Rfc0001(c)) if c.name == "root" |
| 250 | )); |
| 251 | } |
| 252 | |
| 253 | #[test] |
| 254 | fn different_snapshots_give_different_digests() { |
| 255 | let mut fx = Fixture::new("snapshots"); |
| 256 | let a = base( |
| 257 | &mut fx, |
| 258 | 1, |
| 259 | vec![(".crumb", FileMode::Regular644, ROOT.to_vec())], |
| 260 | ); |
| 261 | let b = base( |
| 262 | &mut fx, |
| 263 | 2, |
| 264 | vec![(".crumb", FileMode::Regular644, b"{not json".to_vec())], |
| 265 | ); |
| 266 | let ca = fx.query(vec![Capability::Read], a, ".").unwrap(); |
| 267 | let cb = fx.query(vec![Capability::Read], b, ".").unwrap(); |
| 268 | assert!(matches!( |
| 269 | cb.leaf().status, |
| 270 | EntryStatus::Invalid(InvalidReason::Json(_)) |
| 271 | )); |
| 272 | assert_ne!(ca.digest(), cb.digest()); |
| 273 | } |
| 274 | |
| 275 | #[test] |
| 276 | fn oversized_and_symlink_crumbs_are_invalid_without_parsing() { |
| 277 | let mut fx = Fixture::new("bounds"); |
| 278 | let big = vec![b' '; MAX_CRUMB_BYTES as usize + 1]; |
| 279 | let t = base( |
| 280 | &mut fx, |
| 281 | 3, |
| 282 | vec![ |
| 283 | (".crumb", FileMode::Regular644, big.clone()), |
| 284 | ("a/.crumb", FileMode::Symlink120000, b"../.crumb".to_vec()), |
| 285 | ("a/f", FileMode::Regular644, b"x".to_vec()), |
| 286 | ], |
| 287 | ); |
| 288 | let c = fx.query(vec![Capability::Read], t, "a").unwrap(); |
| 289 | assert_eq!( |
| 290 | c.entries()[0].status, |
| 291 | EntryStatus::Invalid(InvalidReason::TooLarge { |
| 292 | size: MAX_CRUMB_BYTES + 1 |
| 293 | }) |
| 294 | ); |
| 295 | assert_eq!(c.entries()[0].blob_digest, Some(BlobDigest::compute(&big))); |
| 296 | assert_eq!( |
| 297 | c.leaf().status, |
| 298 | EntryStatus::Invalid(InvalidReason::NotRegularFile) |
| 299 | ); |
| 300 | assert!(c.nearest().is_none()); |
| 301 | assert_eq!(c.leaf().dialect(), None::<Dialect>); |
| 302 | } |
| 303 | |
| 304 | #[test] |
| 305 | fn refuses_without_read_capability_and_for_unknown_paths() { |
| 306 | let mut fx = Fixture::new("refuse"); |
| 307 | let t = base( |
| 308 | &mut fx, |
| 309 | 4, |
| 310 | vec![("a/f", FileMode::Regular644, b"x".to_vec())], |
| 311 | ); |
| 312 | let denied = fx.query(vec![Capability::Propose], t, "a").unwrap_err(); |
| 313 | assert_eq!(denied.code, RefusalCode::AuthCapabilityDenied); |
| 314 | let missing = fx.query(vec![Capability::Read], t, "nope").unwrap_err(); |
| 315 | assert_eq!(missing.code, RefusalCode::BlobNotFound); |
| 316 | // "a/f" exists as a file, so "a/f/g" is not a directory in the tree. |
| 317 | let under_file = fx.query(vec![Capability::Read], t, "a/f/g").unwrap_err(); |
| 318 | assert_eq!(under_file.code, RefusalCode::BlobNotFound); |
| 319 | let bad = fx.query(vec![Capability::Read], t, "../a").unwrap_err(); |
| 320 | assert_eq!(bad.code, RefusalCode::PathInvalid); |
| 321 | } |
| 322 | } |