1use std::collections::{BTreeMap, BTreeSet};
11
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14use unicode_normalization::UnicodeNormalization;
15
16use crate::actor_registration::{require_lower_hex, require_sha256_root};
17use crate::events::{
18 EVENT_KIND_FRONTIER_REPOSITORY_BOUND, EVENT_SCHEMA, FRONTIER_CREATED_SCHEMA_V1, NULL_HASH,
19 StateActor, StateEvent, StateTarget, compute_event_id, event_content_preimage_bytes,
20};
21
22pub const FRONTIER_IDENTITY_SCHEMA: &str = "vela.frontier-identity.v1";
23pub const LEGACY_FRONTIER_ORIGIN_SCHEMA: &str = "vela.legacy-frontier-origin.v1";
24pub const FRONTIER_REPOSITORY_BOUNDARY_SCHEMA: &str = "vela.frontier-repository-boundary.v1";
25pub const RETAINED_OBJECT_MANIFEST_SCHEMA: &str = "vela.retained-object-manifest.v1";
26
27#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
28#[serde(rename_all = "snake_case")]
29pub enum FrontierIdentityOrigin {
30 Genesis,
31 LegacyBoundary,
32}
33
34#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
35#[serde(rename_all = "lowercase")]
36pub enum GitObjectFormat {
37 Sha1,
38 Sha256,
39}
40
41impl GitObjectFormat {
42 fn digest_len(self) -> usize {
43 match self {
44 Self::Sha1 => 40,
45 Self::Sha256 => 64,
46 }
47 }
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
51#[serde(deny_unknown_fields)]
52pub struct FrontierIdentityV1 {
53 pub schema: String,
54 pub frontier_id: String,
55 pub origin: FrontierIdentityOrigin,
56 pub origin_commitment: String,
57 pub legacy_identity_preimage_root: Option<String>,
58}
59
60impl FrontierIdentityV1 {
61 pub fn from_genesis_event(event: &StateEvent) -> Result<Self, String> {
64 validate_profile_v1_genesis_event(event)?;
65 let digest = hex::encode(Sha256::digest(event_content_preimage_bytes(event)));
66 Ok(Self {
67 schema: FRONTIER_IDENTITY_SCHEMA.to_string(),
68 frontier_id: format!("vfr_{}", &digest[..16]),
69 origin: FrontierIdentityOrigin::Genesis,
70 origin_commitment: format!("sha256:{digest}"),
71 legacy_identity_preimage_root: None,
72 })
73 }
74
75 pub fn validate(&self) -> Result<(), String> {
82 if self.schema != FRONTIER_IDENTITY_SCHEMA {
83 return Err(format!(
84 "identity.schema must be {FRONTIER_IDENTITY_SCHEMA}"
85 ));
86 }
87 require_frontier_id("identity.frontier_id", &self.frontier_id)?;
88 require_sha256_root("identity.origin_commitment", &self.origin_commitment)?;
89 match (self.origin, self.legacy_identity_preimage_root.as_deref()) {
90 (FrontierIdentityOrigin::Genesis, None) => Ok(()),
91 (FrontierIdentityOrigin::Genesis, Some(_)) => {
92 Err("genesis identity must use a null legacy_identity_preimage_root".to_string())
93 }
94 (FrontierIdentityOrigin::LegacyBoundary, Some(root)) => {
95 require_sha256_root("identity.legacy_identity_preimage_root", root)
96 }
97 (FrontierIdentityOrigin::LegacyBoundary, None) => {
98 Err("legacy_boundary identity requires legacy_identity_preimage_root".to_string())
99 }
100 }
101 }
102
103 pub fn root(&self) -> Result<String, String> {
104 self.validate()?;
105 canonical_root(self)
106 }
107
108 pub fn verify_root(&self, expected: &str) -> Result<(), String> {
109 require_sha256_root("identity_root", expected)?;
110 if self.root()? != expected {
111 return Err("identity_root does not match the closed identity preimage".to_string());
112 }
113 Ok(())
114 }
115}
116
117#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
118#[serde(deny_unknown_fields)]
119pub struct LegacyFrontierOriginV1 {
120 pub schema: String,
121 pub frontier_id: String,
122 pub legacy_identity_preimage_root: String,
123 pub git_object_format: GitObjectFormat,
124 pub anchor_git_commit: String,
125 pub anchor_git_tree: String,
126 pub anchor_event_log_root: String,
127 pub anchor_event_count: u64,
128}
129
130impl LegacyFrontierOriginV1 {
131 pub fn validate(&self) -> Result<(), String> {
132 if self.schema != LEGACY_FRONTIER_ORIGIN_SCHEMA {
133 return Err(format!(
134 "legacy origin schema must be {LEGACY_FRONTIER_ORIGIN_SCHEMA}"
135 ));
136 }
137 require_frontier_id("legacy_origin.frontier_id", &self.frontier_id)?;
138 require_sha256_root(
139 "legacy_origin.legacy_identity_preimage_root",
140 &self.legacy_identity_preimage_root,
141 )?;
142 require_git_object(
143 "legacy_origin.anchor_git_commit",
144 &self.anchor_git_commit,
145 self.git_object_format,
146 )?;
147 require_git_object(
148 "legacy_origin.anchor_git_tree",
149 &self.anchor_git_tree,
150 self.git_object_format,
151 )?;
152 require_sha256_root(
153 "legacy_origin.anchor_event_log_root",
154 &self.anchor_event_log_root,
155 )?;
156 if self.anchor_event_count == 0 {
157 return Err("legacy origin requires a non-empty anchored event log".to_string());
158 }
159 Ok(())
160 }
161
162 pub fn origin_commitment(&self) -> Result<String, String> {
163 self.validate()?;
164 canonical_root(self)
165 }
166
167 pub fn identity(&self) -> Result<FrontierIdentityV1, String> {
168 Ok(FrontierIdentityV1 {
169 schema: FRONTIER_IDENTITY_SCHEMA.to_string(),
170 frontier_id: self.frontier_id.clone(),
171 origin: FrontierIdentityOrigin::LegacyBoundary,
172 origin_commitment: self.origin_commitment()?,
173 legacy_identity_preimage_root: Some(self.legacy_identity_preimage_root.clone()),
174 })
175 }
176
177 pub fn identity_root(&self) -> Result<String, String> {
178 self.identity()?.root()
179 }
180}
181
182#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
183#[serde(deny_unknown_fields)]
184pub struct ExactFrontierDependencyV1 {
185 pub frontier_id: String,
186 pub identity_root: String,
187 pub scientific_state_root: String,
188 pub git_object_format: GitObjectFormat,
189 pub git_commit: String,
190 pub git_tree: String,
191}
192
193impl ExactFrontierDependencyV1 {
194 pub fn validate(&self) -> Result<(), String> {
195 require_frontier_id("dependency.frontier_id", &self.frontier_id)?;
196 require_sha256_root("dependency.identity_root", &self.identity_root)?;
197 require_sha256_root(
198 "dependency.scientific_state_root",
199 &self.scientific_state_root,
200 )?;
201 require_git_object(
202 "dependency.git_commit",
203 &self.git_commit,
204 self.git_object_format,
205 )?;
206 require_git_object(
207 "dependency.git_tree",
208 &self.git_tree,
209 self.git_object_format,
210 )
211 }
212
213 fn canonical_key(&self) -> (&str, &str) {
214 (&self.frontier_id, &self.identity_root)
215 }
216}
217
218pub fn validate_exact_dependencies(
219 dependencies: &[ExactFrontierDependencyV1],
220) -> Result<(), String> {
221 let mut previous: Option<(&str, &str)> = None;
222 for dependency in dependencies {
223 dependency.validate()?;
224 let key = dependency.canonical_key();
225 if let Some(prior) = previous {
226 if key == prior {
227 return Err(format!(
228 "duplicate dependency key ({}, {})",
229 dependency.frontier_id, dependency.identity_root
230 ));
231 }
232 if key < prior {
233 return Err(
234 "dependencies must be sorted by (frontier_id, identity_root)".to_string(),
235 );
236 }
237 }
238 previous = Some(key);
239 }
240 Ok(())
241}
242
243pub fn exact_dependency_root(dependencies: &[ExactFrontierDependencyV1]) -> Result<String, String> {
244 validate_exact_dependencies(dependencies)?;
245 canonical_root(dependencies)
246}
247
248#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
249#[serde(deny_unknown_fields)]
250pub struct RetainedObjectEntryV1 {
251 pub path: String,
252 pub git_mode: String,
253 pub size: u64,
254 pub sha256: String,
256}
257
258impl RetainedObjectEntryV1 {
259 pub fn validate(&self) -> Result<(), String> {
260 validate_repository_path(&self.path)?;
261 if !matches!(self.git_mode.as_str(), "100644" | "100755") {
262 return Err(
263 "retained object git_mode must be tracked regular-file mode 100644 or 100755"
264 .to_string(),
265 );
266 }
267 require_lower_hex("retained object sha256", &self.sha256, 64)
268 }
269}
270
271#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
275#[serde(transparent)]
276pub struct RetainedObjectManifestV1(pub Vec<RetainedObjectEntryV1>);
277
278impl RetainedObjectManifestV1 {
279 pub fn validate(&self) -> Result<(), String> {
280 let mut previous_path: Option<&str> = None;
281 let mut portable_collision_keys = BTreeSet::new();
282 for entry in &self.0 {
283 entry.validate()?;
284 if let Some(previous) = previous_path {
285 if entry.path == previous {
286 return Err(format!("duplicate retained object path {:?}", entry.path));
287 }
288 if entry.path.as_str() < previous {
289 return Err("retained object entries must be sorted by path".to_string());
290 }
291 }
292 previous_path = Some(&entry.path);
293
294 let collision_key = entry
299 .path
300 .nfc()
301 .flat_map(char::to_lowercase)
302 .collect::<String>();
303 if !portable_collision_keys.insert(collision_key) {
304 return Err(format!(
305 "retained object path {:?} has a portable case-fold collision",
306 entry.path
307 ));
308 }
309 }
310 Ok(())
311 }
312
313 pub fn root(&self) -> Result<String, String> {
314 self.validate()?;
315 canonical_root(&self.0)
316 }
317
318 pub fn verify_root(&self, expected: &str) -> Result<(), String> {
319 require_sha256_root("retained_object_manifest_root", expected)?;
320 if self.root()? != expected {
321 return Err(
322 "retained-object manifest root does not match its canonical entries".to_string(),
323 );
324 }
325 Ok(())
326 }
327}
328
329#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
330#[serde(rename_all = "snake_case")]
331pub enum FrontierRepositoryBoundaryMode {
332 TemporalizeExisting,
333 UpdateDependencies,
334}
335
336#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
337#[serde(rename_all = "snake_case")]
338pub enum FrontierRepositoryTrustMode {
339 Tofu,
340 Genesis,
341 PreviousBoundary,
342}
343
344#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
345#[serde(deny_unknown_fields)]
346pub struct FrontierRepositoryBoundaryPayloadV1 {
347 pub schema: String,
348 pub mode: FrontierRepositoryBoundaryMode,
349 pub frontier_id: String,
350 pub identity_root: String,
351 pub observed_profile_root: String,
352 pub dependency_root: String,
353 pub dependencies: Vec<ExactFrontierDependencyV1>,
354 pub previous_identity_event_root: Option<String>,
358 pub legacy_identity_preimage_root: Option<String>,
359 pub administrator_actor_id: String,
360 pub administrator_public_key: String,
361 pub administrator_algorithm: String,
362 pub trust_mode: FrontierRepositoryTrustMode,
363 pub git_object_format: GitObjectFormat,
364 pub anchor_git_commit: String,
365 pub anchor_git_tree: String,
366 pub anchor_event_log_root: String,
367 pub anchor_event_count: u64,
368 pub anchor_snapshot_root: String,
369 pub anchor_snapshot_schema: String,
370 pub anchor_proposal_root: String,
371 pub anchor_actor_registry_root: String,
372 pub anchor_artifact_registry_root: String,
373 pub anchor_canonical_store_root: String,
374}
375
376impl FrontierRepositoryBoundaryPayloadV1 {
377 pub fn validate(&self) -> Result<(), String> {
383 if self.schema != FRONTIER_REPOSITORY_BOUNDARY_SCHEMA {
384 return Err(format!(
385 "payload.schema must be {FRONTIER_REPOSITORY_BOUNDARY_SCHEMA}"
386 ));
387 }
388 require_frontier_id("payload.frontier_id", &self.frontier_id)?;
389 for (field, root) in [
390 ("payload.identity_root", self.identity_root.as_str()),
391 (
392 "payload.observed_profile_root",
393 self.observed_profile_root.as_str(),
394 ),
395 ("payload.dependency_root", self.dependency_root.as_str()),
396 (
397 "payload.anchor_event_log_root",
398 self.anchor_event_log_root.as_str(),
399 ),
400 (
401 "payload.anchor_snapshot_root",
402 self.anchor_snapshot_root.as_str(),
403 ),
404 (
405 "payload.anchor_proposal_root",
406 self.anchor_proposal_root.as_str(),
407 ),
408 (
409 "payload.anchor_actor_registry_root",
410 self.anchor_actor_registry_root.as_str(),
411 ),
412 (
413 "payload.anchor_artifact_registry_root",
414 self.anchor_artifact_registry_root.as_str(),
415 ),
416 (
417 "payload.anchor_canonical_store_root",
418 self.anchor_canonical_store_root.as_str(),
419 ),
420 ] {
421 require_sha256_root(field, root)?;
422 }
423 if let Some(root) = self.previous_identity_event_root.as_deref() {
424 require_sha256_root("payload.previous_identity_event_root", root)?;
425 }
426 if let Some(root) = self.legacy_identity_preimage_root.as_deref() {
427 require_sha256_root("payload.legacy_identity_preimage_root", root)?;
428 }
429 require_git_object(
430 "payload.anchor_git_commit",
431 &self.anchor_git_commit,
432 self.git_object_format,
433 )?;
434 require_git_object(
435 "payload.anchor_git_tree",
436 &self.anchor_git_tree,
437 self.git_object_format,
438 )?;
439 if self.anchor_event_count == 0 {
440 return Err("repository boundary requires a non-empty anchored event log".to_string());
441 }
442 require_text(
443 "payload.anchor_snapshot_schema",
444 &self.anchor_snapshot_schema,
445 )?;
446 if !(self.administrator_actor_id.starts_with("reviewer:")
447 || self.administrator_actor_id.starts_with("steward:"))
448 {
449 return Err(
450 "payload.administrator_actor_id must identify a reviewer: or steward: human actor"
451 .to_string(),
452 );
453 }
454 require_lower_hex(
455 "payload.administrator_public_key",
456 &self.administrator_public_key,
457 64,
458 )?;
459 if self.administrator_algorithm != "ed25519" {
460 return Err("payload.administrator_algorithm must be ed25519".to_string());
461 }
462
463 let computed_dependency_root = exact_dependency_root(&self.dependencies)?;
464 if computed_dependency_root != self.dependency_root {
465 return Err(
466 "payload.dependency_root does not match the canonical dependency list".to_string(),
467 );
468 }
469
470 match self.mode {
471 FrontierRepositoryBoundaryMode::TemporalizeExisting => {
472 if self.trust_mode != FrontierRepositoryTrustMode::Tofu {
473 return Err("temporalize_existing requires trust_mode tofu".to_string());
474 }
475 if self.previous_identity_event_root.is_some() {
476 return Err(
477 "temporalize_existing requires a null previous_identity_event_root"
478 .to_string(),
479 );
480 }
481 let legacy_root =
482 self.legacy_identity_preimage_root
483 .as_deref()
484 .ok_or_else(|| {
485 "temporalize_existing requires legacy_identity_preimage_root"
486 .to_string()
487 })?;
488 let legacy_origin = LegacyFrontierOriginV1 {
489 schema: LEGACY_FRONTIER_ORIGIN_SCHEMA.to_string(),
490 frontier_id: self.frontier_id.clone(),
491 legacy_identity_preimage_root: legacy_root.to_string(),
492 git_object_format: self.git_object_format,
493 anchor_git_commit: self.anchor_git_commit.clone(),
494 anchor_git_tree: self.anchor_git_tree.clone(),
495 anchor_event_log_root: self.anchor_event_log_root.clone(),
496 anchor_event_count: self.anchor_event_count,
497 };
498 if legacy_origin.identity_root()? != self.identity_root {
499 return Err(
500 "payload.identity_root does not match the temporalized legacy identity"
501 .to_string(),
502 );
503 }
504 }
505 FrontierRepositoryBoundaryMode::UpdateDependencies => {
506 if !matches!(
507 self.trust_mode,
508 FrontierRepositoryTrustMode::Genesis
509 | FrontierRepositoryTrustMode::PreviousBoundary
510 ) {
511 return Err(
512 "update_dependencies requires trust_mode genesis or previous_boundary"
513 .to_string(),
514 );
515 }
516 if self.previous_identity_event_root.is_none() {
517 return Err(
518 "update_dependencies requires previous_identity_event_root".to_string()
519 );
520 }
521 if self.trust_mode == FrontierRepositoryTrustMode::Genesis
522 && self.legacy_identity_preimage_root.is_some()
523 {
524 return Err(
525 "a genesis-chained dependency update cannot carry a legacy identity root"
526 .to_string(),
527 );
528 }
529 }
530 }
531 Ok(())
532 }
533
534 pub fn validate_chain(&self, previous_event: &StateEvent) -> Result<(), String> {
539 self.validate()?;
540 if self.mode != FrontierRepositoryBoundaryMode::UpdateDependencies {
541 return Err("only update_dependencies has a previous identity chain".to_string());
542 }
543 let previous_root = repository_identity_event_content_root(previous_event)?;
544 if self.previous_identity_event_root.as_deref() != Some(previous_root.as_str()) {
545 return Err(
546 "previous_identity_event_root does not match the preceding event preimage"
547 .to_string(),
548 );
549 }
550 if previous_event.kind.as_str() == "frontier.created" {
551 if self.trust_mode != FrontierRepositoryTrustMode::Genesis {
552 return Err("a frontier.created parent requires trust_mode genesis".to_string());
553 }
554 let identity = FrontierIdentityV1::from_genesis_event(previous_event)?;
555 if self.frontier_id != identity.frontier_id
556 || self.identity_root != identity.root()?
557 || self.legacy_identity_preimage_root.is_some()
558 {
559 return Err(
560 "genesis-chained boundary does not preserve the derived Frontier identity"
561 .to_string(),
562 );
563 }
564 } else {
565 if self.trust_mode != FrontierRepositoryTrustMode::PreviousBoundary {
566 return Err(
567 "a repository-boundary parent requires trust_mode previous_boundary"
568 .to_string(),
569 );
570 }
571 let previous = repository_boundary_payload_from_event_shape(previous_event)?;
572 if self.anchor_event_count <= previous.anchor_event_count {
573 return Err(
574 "repository boundary anchor_event_count must advance beyond its parent"
575 .to_string(),
576 );
577 }
578 if self.frontier_id != previous.frontier_id
579 || self.identity_root != previous.identity_root
580 || self.legacy_identity_preimage_root != previous.legacy_identity_preimage_root
581 || self.administrator_actor_id != previous.administrator_actor_id
582 || self.administrator_public_key != previous.administrator_public_key
583 || self.administrator_algorithm != previous.administrator_algorithm
584 {
585 return Err(
586 "repository boundary chain changed immutable identity or administrator fields"
587 .to_string(),
588 );
589 }
590 }
591 Ok(())
592 }
593}
594
595pub fn new_repository_boundary_event(
596 payload: FrontierRepositoryBoundaryPayloadV1,
597 reason: &str,
598 timestamp: &str,
599) -> Result<StateEvent, String> {
600 payload.validate()?;
601 require_text("event.reason", reason)?;
602 chrono::DateTime::parse_from_rfc3339(timestamp)
603 .map_err(|error| format!("event.timestamp must be RFC3339: {error}"))?;
604 let mut event = StateEvent {
605 schema: EVENT_SCHEMA.to_string(),
606 id: String::new(),
607 kind: EVENT_KIND_FRONTIER_REPOSITORY_BOUND.into(),
608 target: StateTarget {
609 r#type: "frontier".to_string(),
610 id: payload.frontier_id.clone(),
611 },
612 actor: StateActor {
613 r#type: "human".to_string(),
614 id: payload.administrator_actor_id.clone(),
615 },
616 timestamp: timestamp.to_string(),
617 reason: reason.to_string(),
618 before_hash: NULL_HASH.to_string(),
619 after_hash: NULL_HASH.to_string(),
620 payload: serde_json::to_value(payload)
621 .map_err(|error| format!("serialize repository-boundary payload: {error}"))?,
622 caveats: vec![],
623 signature: None,
624 };
625 event.id = compute_event_id(&event);
626 Ok(event)
627}
628
629pub fn repository_boundary_payload_from_event_shape(
634 event: &StateEvent,
635) -> Result<FrontierRepositoryBoundaryPayloadV1, String> {
636 if event.schema != EVENT_SCHEMA {
637 return Err(format!(
638 "repository boundary event schema must be {EVENT_SCHEMA}"
639 ));
640 }
641 if event.kind.as_str() != EVENT_KIND_FRONTIER_REPOSITORY_BOUND {
642 return Err(format!(
643 "expected {EVENT_KIND_FRONTIER_REPOSITORY_BOUND}, got {}",
644 event.kind
645 ));
646 }
647 if event.id != compute_event_id(event) {
648 return Err(
649 "repository boundary event id does not match its canonical content".to_string(),
650 );
651 }
652 if event.target.r#type != "frontier" {
653 return Err("repository boundary target.type must be frontier".to_string());
654 }
655 if event.actor.r#type != "human" {
656 return Err("repository boundary actor.type must be human".to_string());
657 }
658 if event.before_hash != NULL_HASH || event.after_hash != NULL_HASH {
659 return Err("repository boundary must use null before_hash and after_hash".to_string());
660 }
661 require_text("event.reason", &event.reason)?;
662 chrono::DateTime::parse_from_rfc3339(&event.timestamp)
663 .map_err(|error| format!("event.timestamp must be RFC3339: {error}"))?;
664 if event.signature.is_none() {
665 return Err("repository boundary must carry an ordinary event signature".to_string());
666 }
667 let payload: FrontierRepositoryBoundaryPayloadV1 =
668 serde_json::from_value(event.payload.clone())
669 .map_err(|error| format!("invalid repository-boundary payload: {error}"))?;
670 payload.validate()?;
671 if event.target.id != payload.frontier_id {
672 return Err("repository boundary target.id must equal payload.frontier_id".to_string());
673 }
674 if event.actor.id != payload.administrator_actor_id {
675 return Err(
676 "repository boundary actor.id must equal payload.administrator_actor_id".to_string(),
677 );
678 }
679 Ok(payload)
680}
681
682pub fn verify_repository_boundary_signature_only(
689 event: &StateEvent,
690 expected_public_key: &str,
691) -> Result<FrontierRepositoryBoundaryPayloadV1, String> {
692 require_lower_hex("expected administrator public key", expected_public_key, 64)?;
693 let payload = repository_boundary_payload_from_event_shape(event)?;
694 if payload.administrator_public_key != expected_public_key {
695 return Err(
696 "repository boundary payload key does not match the expected administrator key"
697 .to_string(),
698 );
699 }
700 if !crate::sign::verify_event_signature(event, expected_public_key)? {
701 return Err("repository boundary event signature does not verify".to_string());
702 }
703 Ok(payload)
704}
705
706pub fn repository_boundary_event_content_root(event: &StateEvent) -> Result<String, String> {
707 repository_boundary_payload_from_event_shape(event)?;
708 Ok(event_content_root(event))
709}
710
711pub fn repository_identity_event_content_root(event: &StateEvent) -> Result<String, String> {
713 match event.kind.as_str() {
714 "frontier.created" => {
715 validate_profile_v1_genesis_event(event)?;
716 Ok(event_content_root(event))
717 }
718 EVENT_KIND_FRONTIER_REPOSITORY_BOUND => repository_boundary_event_content_root(event),
719 other => Err(format!(
720 "repository identity parent must be frontier.created or {EVENT_KIND_FRONTIER_REPOSITORY_BOUND}, got {other}"
721 )),
722 }
723}
724
725pub fn validate_repository_boundary_event_set(events: &[StateEvent]) -> Vec<String> {
732 struct Boundary<'a> {
733 event: &'a StateEvent,
734 payload: FrontierRepositoryBoundaryPayloadV1,
735 }
736
737 let mut boundaries = BTreeMap::<String, Boundary<'_>>::new();
738 let mut errors = Vec::new();
739
740 for event in events
741 .iter()
742 .filter(|event| event.kind.as_str() == EVENT_KIND_FRONTIER_REPOSITORY_BOUND)
743 {
744 let payload = match repository_boundary_payload_from_event_shape(event) {
745 Ok(payload) => payload,
746 Err(error) => {
747 errors.push(format!("repository boundary {} invalid: {error}", event.id));
748 continue;
749 }
750 };
751 if let Err(error) =
752 verify_repository_boundary_signature_only(event, &payload.administrator_public_key)
753 {
754 errors.push(format!(
755 "repository boundary {} signature invalid: {error}",
756 event.id
757 ));
758 continue;
759 }
760 let root = event_content_root(event);
761 if boundaries
762 .insert(root.clone(), Boundary { event, payload })
763 .is_some()
764 {
765 errors.push(format!("duplicate repository boundary content root {root}"));
766 }
767 }
768
769 if boundaries.is_empty() {
770 return errors;
771 }
772
773 let mut genesis = BTreeMap::new();
774 for event in events.iter().filter(|event| {
775 event.kind.as_str() == "frontier.created"
776 && event
777 .payload
778 .get("schema")
779 .and_then(serde_json::Value::as_str)
780 == Some(FRONTIER_CREATED_SCHEMA_V1)
781 }) {
782 match repository_identity_event_content_root(event) {
783 Ok(root) => {
784 if genesis.insert(root.clone(), event).is_some() {
785 errors.push(format!("duplicate frontier.created content root {root}"));
786 }
787 }
788 Err(error) => errors.push(format!("frontier.created {} invalid: {error}", event.id)),
789 }
790 }
791 if genesis.len() > 1 {
792 errors.push(format!(
793 "repository boundary graph cannot contain {} distinct frontier.created roots",
794 genesis.len()
795 ));
796 }
797
798 let mut roots = 0usize;
799 let mut children = BTreeMap::<String, Vec<String>>::new();
800 for (root, boundary) in &boundaries {
801 match boundary.payload.mode {
802 FrontierRepositoryBoundaryMode::TemporalizeExisting => {
803 roots += 1;
804 if !genesis.is_empty() {
805 errors.push(format!(
806 "legacy temporal boundary {root} cannot coexist with frontier.created"
807 ));
808 }
809 }
810 FrontierRepositoryBoundaryMode::UpdateDependencies => {
811 let Some(parent_root) = boundary.payload.previous_identity_event_root.as_deref()
812 else {
813 errors.push(format!("repository boundary {root} has no identity parent"));
816 continue;
817 };
818 children
819 .entry(parent_root.to_string())
820 .or_default()
821 .push(root.clone());
822
823 let parent = boundaries
824 .get(parent_root)
825 .map(|parent| parent.event)
826 .or_else(|| genesis.get(parent_root).copied());
827 let Some(parent) = parent else {
828 errors.push(format!(
829 "repository boundary {root} references missing identity parent {parent_root}"
830 ));
831 continue;
832 };
833 if parent.kind.as_str() == "frontier.created" {
834 roots += 1;
835 }
836 if let Err(error) = boundary.payload.validate_chain(parent) {
837 errors.push(format!("repository boundary {root} chain invalid: {error}"));
838 }
839 }
840 }
841 }
842
843 for (parent, child_roots) in &children {
844 if child_roots.len() > 1 {
845 errors.push(format!(
846 "repository identity event {parent} has conflicting children {}",
847 child_roots.join(", ")
848 ));
849 }
850 }
851 if roots != 1 {
852 errors.push(format!(
853 "repository boundary graph must have exactly one identity-chain root, found {roots}"
854 ));
855 }
856
857 for start in boundaries.keys() {
858 let mut current = start.as_str();
859 let mut visited = BTreeSet::new();
860 loop {
861 if !visited.insert(current.to_string()) {
862 errors.push(format!(
863 "repository boundary graph contains a cycle through {current}"
864 ));
865 break;
866 }
867 let Some(boundary) = boundaries.get(current) else {
868 break;
869 };
870 if boundary.payload.mode == FrontierRepositoryBoundaryMode::TemporalizeExisting {
871 break;
872 }
873 let Some(parent) = boundary.payload.previous_identity_event_root.as_deref() else {
874 break;
875 };
876 if genesis.contains_key(parent) {
877 break;
878 }
879 current = parent;
880 }
881 }
882
883 errors.sort();
884 errors.dedup();
885 errors
886}
887
888fn validate_genesis_event(event: &StateEvent) -> Result<(), String> {
889 if event.schema != EVENT_SCHEMA {
890 return Err(format!("genesis event schema must be {EVENT_SCHEMA}"));
891 }
892 if event.kind.as_str() != "frontier.created" {
893 return Err(format!("expected frontier.created, got {}", event.kind));
894 }
895 if event.id != compute_event_id(event) {
896 return Err("frontier.created id does not match its canonical content".to_string());
897 }
898 if event.target.r#type != "frontier" || event.actor.r#type != "frontier" {
899 return Err("frontier.created target and actor types must be frontier".to_string());
900 }
901 if event.before_hash != NULL_HASH || event.after_hash != NULL_HASH {
902 return Err("frontier.created must use null before_hash and after_hash".to_string());
903 }
904 crate::events::validate_event_payload("frontier.created", &event.payload)?;
905 let payload = event
906 .payload
907 .as_object()
908 .ok_or_else(|| "frontier.created payload must be an object".to_string())?;
909 if payload.get("schema").and_then(serde_json::Value::as_str) == Some(FRONTIER_CREATED_SCHEMA_V1)
910 {
911 if event.signature.is_some() || !event.caveats.is_empty() {
912 return Err(
913 "Profile v1 frontier.created must be unsigned and carry no caveats".to_string(),
914 );
915 }
916 if payload
917 .get("name_at_creation")
918 .and_then(serde_json::Value::as_str)
919 != Some(event.target.id.as_str())
920 || payload.get("creator").and_then(serde_json::Value::as_str)
921 != Some(event.actor.id.as_str())
922 || payload
923 .get("created_at")
924 .and_then(serde_json::Value::as_str)
925 != Some(event.timestamp.as_str())
926 {
927 return Err(
928 "Profile v1 frontier.created payload identity disagrees with its event core"
929 .to_string(),
930 );
931 }
932 let empty_dependency_root = exact_dependency_root(&[])?;
933 if payload
934 .get("dependency_root")
935 .and_then(serde_json::Value::as_str)
936 != Some(empty_dependency_root.as_str())
937 {
938 return Err(
939 "Profile v1 frontier.created must bind the canonical empty dependency root"
940 .to_string(),
941 );
942 }
943 } else {
944 if payload.get("name").and_then(serde_json::Value::as_str) != Some(event.target.id.as_str())
945 || payload.get("creator").and_then(serde_json::Value::as_str)
946 != Some(event.actor.id.as_str())
947 {
948 return Err(
949 "historical frontier.created payload identity disagrees with its event core"
950 .to_string(),
951 );
952 }
953 if let Some(compiled_at) = payload
954 .get("compiled_at")
955 .and_then(serde_json::Value::as_str)
956 && compiled_at != event.timestamp
957 {
958 return Err(
959 "historical frontier.created compiled_at disagrees with event timestamp"
960 .to_string(),
961 );
962 }
963 }
964 Ok(())
965}
966
967fn validate_profile_v1_genesis_event(event: &StateEvent) -> Result<(), String> {
972 validate_genesis_event(event)?;
973 if event
974 .payload
975 .get("schema")
976 .and_then(serde_json::Value::as_str)
977 != Some(FRONTIER_CREATED_SCHEMA_V1)
978 {
979 return Err(format!(
980 "repository identity genesis must use payload.schema {FRONTIER_CREATED_SCHEMA_V1}"
981 ));
982 }
983 Ok(())
984}
985
986fn event_content_root(event: &StateEvent) -> String {
987 format!(
988 "sha256:{}",
989 hex::encode(Sha256::digest(event_content_preimage_bytes(event)))
990 )
991}
992
993fn canonical_root<T: Serialize + ?Sized>(value: &T) -> Result<String, String> {
994 Ok(format!(
995 "sha256:{}",
996 crate::canonical::sha256_canonical(value)?
997 ))
998}
999
1000fn require_frontier_id(field: &str, value: &str) -> Result<(), String> {
1001 let Some(hex) = value.strip_prefix("vfr_") else {
1002 return Err(format!("{field} must use the vfr_<16 lowercase hex> form"));
1003 };
1004 require_lower_hex(field, hex, 16)
1005}
1006
1007fn require_git_object(
1008 field: &str,
1009 value: &str,
1010 object_format: GitObjectFormat,
1011) -> Result<(), String> {
1012 require_lower_hex(field, value, object_format.digest_len())
1013}
1014
1015fn require_text(field: &str, value: &str) -> Result<(), String> {
1016 if value.trim().is_empty() {
1017 return Err(format!("{field} must be non-empty"));
1018 }
1019 if value.nfc().collect::<String>() != value {
1020 return Err(format!("{field} must already be Unicode NFC"));
1021 }
1022 if value.chars().any(char::is_control) {
1023 return Err(format!("{field} contains a forbidden control character"));
1024 }
1025 Ok(())
1026}
1027
1028fn validate_repository_path(path: &str) -> Result<(), String> {
1029 require_text("retained object path", path)?;
1030 if path.starts_with('/') || path.ends_with('/') || path.contains('\\') {
1031 return Err(
1032 "retained object path must be a normalized relative repository path".to_string(),
1033 );
1034 }
1035 if path
1036 .split('/')
1037 .any(|component| component.is_empty() || matches!(component, "." | ".."))
1038 {
1039 return Err(
1040 "retained object path contains an empty, dot, or traversal segment".to_string(),
1041 );
1042 }
1043 Ok(())
1044}
1045
1046#[cfg(test)]
1047mod tests {
1048 use super::*;
1049
1050 fn root(character: char) -> String {
1051 format!("sha256:{}", character.to_string().repeat(64))
1052 }
1053
1054 #[test]
1055 fn frontier_repository_bound_legacy_identity_root_is_deterministic() {
1056 let origin = LegacyFrontierOriginV1 {
1057 schema: LEGACY_FRONTIER_ORIGIN_SCHEMA.to_string(),
1058 frontier_id: "vfr_1234567890abcdef".to_string(),
1059 legacy_identity_preimage_root: root('1'),
1060 git_object_format: GitObjectFormat::Sha1,
1061 anchor_git_commit: "2".repeat(40),
1062 anchor_git_tree: "3".repeat(40),
1063 anchor_event_log_root: root('4'),
1064 anchor_event_count: 1,
1065 };
1066 let identity = origin.identity().unwrap();
1067 let expected = canonical_root(&identity).unwrap();
1068 assert_eq!(origin.identity_root().unwrap(), expected);
1069 identity.verify_root(&expected).unwrap();
1070
1071 let mut changed = origin;
1072 changed.anchor_event_count = 2;
1073 assert_ne!(changed.identity_root().unwrap(), expected);
1074 }
1075
1076 #[test]
1077 fn frontier_identity_record_shape_rejects_a_genesis_legacy_root() {
1078 let valid = FrontierIdentityV1 {
1079 schema: FRONTIER_IDENTITY_SCHEMA.to_string(),
1080 frontier_id: "vfr_1234567890abcdef".to_string(),
1081 origin: FrontierIdentityOrigin::Genesis,
1082 origin_commitment: root('1'),
1083 legacy_identity_preimage_root: None,
1084 };
1085 assert!(valid.root().is_ok());
1086
1087 let mut invalid = valid;
1088 invalid.legacy_identity_preimage_root = Some(root('2'));
1089 assert!(invalid.validate().is_err());
1090 }
1091
1092 #[test]
1093 fn frontier_repository_bound_manifest_wire_value_is_the_exact_list() {
1094 let manifest = RetainedObjectManifestV1(vec![RetainedObjectEntryV1 {
1095 path: "records/receipt.json".to_string(),
1096 git_mode: "100644".to_string(),
1097 size: 7,
1098 sha256: "a".repeat(64),
1099 }]);
1100 let value = serde_json::to_value(&manifest).unwrap();
1101 assert!(value.is_array());
1102 assert_eq!(
1103 manifest.root().unwrap(),
1104 canonical_root(&manifest.0).unwrap()
1105 );
1106 }
1107}