interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-coord / src / identity.rs

279 lines · 11271 bytes Raw Blame History
1//! Store identity marker and coordination-root resolution (issue #15).
2//!
3//! crumb.c and Synapse agree on one coordination store only by configuration. A wrong root
4//! used to fail silently: each tool granted a claim on the same file in its own store (split
5//! brain). The marker `<root>/STORE_ID` gives every store a random identity, so a Synapse
6//! agent can be opened *expecting* the identity registered for its repository and is refused
7//! when the configured root has a different marker or none.
8//!
9//! crumb.c (aien-architecture 29780e5) never names `STORE_ID`: it only touches `.lock`,
10//! `dirs/`, `agents/`, `continuations/` and `ledger/` under the root, and its `collect_json`
11//! walks only `dirs/`, `agents/` and `continuations/`. So the marker is invisible to it and
12//! survives its mutations and pruning (checked against the real binary by
13//! `scripts/crumb-coord-interop.sh`, I11).
14//!
15//! The hardened crumb.c (aien-architecture dbc688c8, PR #235) does read the marker: with a
16//! registered store id it refuses a root whose marker differs or is missing, and in unregistered
17//! mode it keeps the Rust-written marker byte-identical (same script, I13-I20).
18
19use crate::CoordError;
20use std::ffi::OsStr;
21use std::path::{Path, PathBuf};
22
23/// File name of the marker, directly under the store root.
24pub const STORE_ID_FILE: &str = "STORE_ID";
25/// Format tag, first token of the marker. A different tag is refused, never guessed.
26pub const STORE_ID_FORMAT: &str = "crumb-coord-store-id/1";
27
28/// Random 128-bit identity of one coordination store.
29#[derive(Clone, Copy, PartialEq, Eq, Hash)]
30pub struct StoreId([u8; 16]);
31
32impl StoreId {
33 /// 16 bytes from the OS random source (`/dev/urandom`).
34 pub fn random() -> std::io::Result<StoreId> {
35 use std::io::Read;
36 let mut b = [0u8; 16];
37 std::fs::File::open("/dev/urandom")?.read_exact(&mut b)?;
38 Ok(StoreId(b))
39 }
40
41 /// Lowercase hex, 32 characters.
42 pub fn to_hex(&self) -> String {
43 self.0.iter().map(|b| format!("{b:02x}")).collect()
44 }
45
46 /// Exactly 32 lowercase hex characters (the form [`StoreId::to_hex`] prints).
47 pub fn parse_hex(s: &str) -> Option<StoreId> {
48 let s = s.as_bytes();
49 if s.len() != 32 {
50 return None;
51 }
52 let nib = |c: u8| match c {
53 b'0'..=b'9' => Some(c - b'0'),
54 b'a'..=b'f' => Some(c - b'a' + 10),
55 _ => None,
56 };
57 let mut b = [0u8; 16];
58 for (i, out) in b.iter_mut().enumerate() {
59 *out = nib(s[2 * i])? << 4 | nib(s[2 * i + 1])?;
60 }
61 Some(StoreId(b))
62 }
63
64 /// Marker file bytes: `crumb-coord-store-id/1 <hex>\n`.
65 pub fn encode(&self) -> Vec<u8> {
66 format!("{STORE_ID_FORMAT} {}\n", self.to_hex()).into_bytes()
67 }
68
69 /// Parse marker file bytes. Anything but the exact v1 line is an error string.
70 pub fn decode(bytes: &[u8]) -> Result<StoreId, String> {
71 let s = std::str::from_utf8(bytes).map_err(|_| "not UTF-8".to_string())?;
72 let line = s
73 .strip_suffix('\n')
74 .ok_or_else(|| "no trailing newline (torn or foreign file)".to_string())?;
75 let (tag, hex) = line
76 .split_once(' ')
77 .ok_or_else(|| "expected `<format> <id>`".to_string())?;
78 if tag != STORE_ID_FORMAT {
79 return Err(format!("unsupported format {tag:?}"));
80 }
81 StoreId::parse_hex(hex).ok_or_else(|| format!("bad id {hex:?}"))
82 }
83}
84
85impl std::fmt::Display for StoreId {
86 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87 f.write_str(&self.to_hex())
88 }
89}
90
91impl std::fmt::Debug for StoreId {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 write!(f, "StoreId({})", self.to_hex())
94 }
95}
96
97/// Read `<root>/STORE_ID`. `Ok(None)` when absent.
98pub(crate) fn read_marker(root: &Path) -> Result<Option<StoreId>, CoordError> {
99 let p = root.join(STORE_ID_FILE);
100 // Bounded, non-blocking, never following a link (issue #58): a FIFO, device, symlink or
101 // oversized file as `STORE_ID` is a typed `RefusedRecord`, never a hang.
102 match crate::record::read_bounded(&p, crate::MAX_MARKER_BYTES)? {
103 Some(b) => StoreId::decode(&b)
104 .map(Some)
105 .map_err(|reason| CoordError::StoreIdUnreadable { path: p, reason }),
106 None => Ok(None),
107 }
108}
109
110/// Create the marker if absent and return the store's id. Call only while holding the
111/// store's transaction lock (in-process mutex plus `fcntl` on `.lock`), so concurrent first
112/// opens agree on one id. On top of the lock, the marker is published with `link(2)`, which
113/// never replaces an existing file, so even a writer outside the lock cannot overwrite it.
114/// A crash before the link leaves only a `STORE_ID.tmp<pid>` file and no marker.
115pub(crate) fn ensure_marker_locked(root: &Path) -> Result<StoreId, CoordError> {
116 if let Some(id) = read_marker(root)? {
117 return Ok(id);
118 }
119 let p = root.join(STORE_ID_FILE);
120 let tmp = root.join(format!("{STORE_ID_FILE}.tmp{}", std::process::id()));
121 let id = StoreId::random().map_err(|source| CoordError::Io {
122 path: PathBuf::from("/dev/urandom"),
123 source,
124 })?;
125 {
126 use std::io::Write;
127 let mut f = crate::record::create_temp(&tmp)?;
128 f.write_all(&id.encode()).map_err(crate::io_err(&tmp))?;
129 f.sync_all().map_err(crate::io_err(&tmp))?;
130 }
131 crate::fault_point("storeid-before-link");
132 let linked = std::fs::hard_link(&tmp, &p);
133 let _ = std::fs::remove_file(&tmp);
134 match linked {
135 Ok(()) => {}
136 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
137 Err(source) => return Err(CoordError::Io { path: p, source }),
138 }
139 crate::fsync_dir(root)?;
140 read_marker(root)?.ok_or(CoordError::StoreIdMissing {
141 root: root.to_path_buf(),
142 })
143}
144
145/// Which input decided the coordination root.
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147pub enum RootSource {
148 /// `CRUMB_COORD_ROOT`, non-empty.
149 Env,
150 /// `git config --get crumb.coordinationRoot`, non-empty.
151 GitConfig,
152 /// `<git-common-dir>/crumb/v1`.
153 GitCommonDir,
154}
155
156/// A coordination root as crumb.c would choose it.
157#[derive(Clone, Debug, PartialEq, Eq)]
158pub struct ResolvedRoot {
159 pub path: PathBuf,
160 pub source: RootSource,
161}
162
163/// crumb.c reads `git` output into a 512-byte buffer, so it keeps at most this many bytes.
164pub const GIT_OUTPUT_MAX: usize = 511;
165
166/// Mirror of crumb.c `plane_resolve` (29780e5) root order, as a pure function: the caller
167/// supplies the three inputs (this crate never runs Git).
168///
169/// 1. `env` = `CRUMB_COORD_ROOT`; used as given when non-empty.
170/// 2. `git_config` = raw output of `git config --get crumb.coordinationRoot`; trailing `\n`
171/// and `\r` are stripped as crumb.c does, then used as given when non-empty.
172/// 3. `git_common_dir` = the repository's common directory, already made absolute and
173/// `realpath`-resolved (crumb.c resolves `git rev-parse --git-common-dir` against the
174/// working directory and calls `realpath`); the root is `<it>/crumb/v1`.
175///
176/// crumb.c does not canonicalize values from 1 or 2, so a relative value there means
177/// "relative to the crumb process's working directory"; it is returned unchanged. A config
178/// value of [`GIT_OUTPUT_MAX`] bytes or more is refused: crumb.c would silently truncate it
179/// and pick a different directory. A relative common directory is refused (it cannot be
180/// resolved without the filesystem).
181pub fn resolve_coord_root(
182 env: Option<&OsStr>,
183 git_config: Option<&str>,
184 git_common_dir: Option<&Path>,
185) -> Result<ResolvedRoot, CoordError> {
186 if let Some(e) = env.filter(|e| !e.is_empty()) {
187 return Ok(ResolvedRoot {
188 path: PathBuf::from(e),
189 source: RootSource::Env,
190 });
191 }
192 if let Some(raw) = git_config {
193 if raw.len() >= GIT_OUTPUT_MAX {
194 return Err(CoordError::RootUnresolved(format!(
195 "crumb.coordinationRoot is {} bytes; crumb.c truncates git output at {GIT_OUTPUT_MAX}",
196 raw.len()
197 )));
198 }
199 let v = raw.trim_end_matches(['\n', '\r']);
200 if !v.is_empty() {
201 return Ok(ResolvedRoot {
202 path: PathBuf::from(v),
203 source: RootSource::GitConfig,
204 });
205 }
206 }
207 match git_common_dir {
208 Some(cd) if cd.is_absolute() => Ok(ResolvedRoot {
209 path: cd.join("crumb/v1"),
210 source: RootSource::GitCommonDir,
211 }),
212 Some(cd) => Err(CoordError::RootUnresolved(format!(
213 "git common directory {} is relative; pass it resolved (realpath)",
214 cd.display()
215 ))),
216 None => Err(CoordError::RootUnresolved(
217 "no CRUMB_COORD_ROOT, no crumb.coordinationRoot, and no git common directory".into(),
218 )),
219 }
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 #[test]
227 fn hex_and_marker_round_trip() {
228 let id = StoreId::random().unwrap();
229 assert_eq!(StoreId::parse_hex(&id.to_hex()), Some(id));
230 assert_eq!(StoreId::decode(&id.encode()), Ok(id));
231 assert_ne!(StoreId::random().unwrap(), id);
232 assert!(StoreId::parse_hex("0123456789ABCDEF0123456789abcdef").is_none());
233 assert!(StoreId::parse_hex("0123456789abcdef0123456789abcde").is_none());
234 }
235
236 #[test]
237 fn marker_decode_refuses_foreign_or_torn() {
238 let id = StoreId::random().unwrap();
239 let good = id.encode();
240 assert!(StoreId::decode(&good[..good.len() - 1]).is_err(), "torn");
241 let v2 = format!("crumb-coord-store-id/2 {}\n", id.to_hex());
242 assert!(StoreId::decode(v2.as_bytes()).is_err(), "future format");
243 assert!(StoreId::decode(b"crumb-coord-store-id/1 xyz\n").is_err());
244 assert!(StoreId::decode(b"{}\n").is_err());
245 assert!(StoreId::decode(&[0xff, b'\n']).is_err());
246 }
247
248 #[test]
249 fn root_resolution_order_matches_crumb_c() {
250 let cd = Path::new("/repo/.git");
251 let r = |e: Option<&str>, c: Option<&str>, d: Option<&Path>| {
252 resolve_coord_root(e.map(OsStr::new), c, d)
253 };
254 let env = r(Some("/e"), Some("/c\n"), Some(cd)).unwrap();
255 assert_eq!(
256 (env.path.as_path(), env.source),
257 (Path::new("/e"), RootSource::Env)
258 );
259 let cfg = r(Some(""), Some("/c\r\n"), Some(cd)).unwrap();
260 assert_eq!(
261 (cfg.path.as_path(), cfg.source),
262 (Path::new("/c"), RootSource::GitConfig)
263 );
264 let def = r(None, Some("\n"), Some(cd)).unwrap();
265 assert_eq!(
266 (def.path.as_path(), def.source),
267 (Path::new("/repo/.git/crumb/v1"), RootSource::GitCommonDir)
268 );
269 assert_eq!(
270 r(None, Some("rel/store"), None).unwrap().path,
271 PathBuf::from("rel/store"),
272 "relative config value is kept as crumb.c keeps it"
273 );
274 assert!(r(None, None, Some(Path::new(".git"))).is_err());
275 assert!(r(None, None, None).is_err());
276 let long = format!("/{}", "x".repeat(GIT_OUTPUT_MAX));
277 assert!(r(None, Some(&long), Some(cd)).is_err());
278 }
279}