Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 58 additions & 7 deletions pkgs/id/crates/id-sync/src/admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,25 @@
//! fails the commit step, leaving the operation resumable in
//! the ledger.
//!
//! # Durable construction
//!
//! [`SyncAdmission::durable`] builds the adapter's pipeline over
//! the durable id-store adapters of issue #17179 —
//! [`FileOperationLedger`] and [`FileOutboxJournal`] under one
//! directory — so replay/idempotency state and pending outbox
//! deliveries survive a process restart on the sync path exactly
//! as they do on the local paths. Commit-time reauthorization
//! durability composes the same way: wrap the caller's
//! reauthorizer in id-store's `DurableEpochReauthorizer` over a
//! [`FilePolicyEpochSource`] before handing it to the builder.
//!
//! # What this slice does not do
//!
//! The live log-sync receiver still takes raw sync bytes: routing
//! it through this adapter needs the envelope-carrying producer
//! path, which is a follow-on slice. The policy-epoch source behind
//! the [`Reauthorizer`] seam and durable [`OperationLedger`] /
//! [`OutboxJournal`] implementations for the hosted adapters are the
//! same follow-ons named by the id-store slice. The inventory
//! path (the p2panda log-sync transport carries raw chain-event
//! headers, not [`SYNC_DOMAIN`] carriers), which is the remaining
//! follow-on of issue #17198. The inventory
//! (`pkgs/id/tests/operation-path-inventory.md`, P-SY-01) records
//! the pipeline-backed entry point and keeps the row `partial`
//! until the receiver migrates.
Expand All @@ -71,15 +82,21 @@
//! [`OperationLedger`]: id_store::admission::OperationLedger
//! [`OutboxJournal`]: id_store::admission::OutboxJournal
//! [`Reauthorizer`]: id_store::admission::Reauthorizer
//! [`FileOperationLedger`]: id_store::admission::FileOperationLedger
//! [`FileOutboxJournal`]: id_store::admission::FileOutboxJournal
//! [`FilePolicyEpochSource`]: id_store::admission::FilePolicyEpochSource

use std::path::Path;
use std::sync::{Arc, Mutex};

use id_core::admission_gate::{AdmissionContext, AdmissionReceipt, AdmissionRejection};
use id_core::admission_gate::{
AdmissionContext, AdmissionGate, AdmissionReceipt, AdmissionRejection,
};
use id_core::signed_envelope::{Envelope, EnvelopeError};
use id_events::event_store::{EventStore, Ingest};
use id_store::admission::{
AdmissionPipeline, Annotation, HookId, LifecycleRejection, OperationId, PipelineOutcome,
QueuedOperation,
AdmissionPipeline, Annotation, FileOperationLedger, FileOutboxJournal, HookId,
LifecycleRejection, OperationId, PipelineOutcome, QueuedOperation, Reauthorizer,
};
use id_store::chain::{self, Event};

Expand Down Expand Up @@ -115,6 +132,40 @@ impl SyncAdmission {
}
}

/// Builds an adapter whose pipeline persists under `dir`
/// (issue #17198, on the durable adapters of issue #17179):
/// the operation ledger at `dir/admission-ledger` and the
/// outbox journal at `dir/admission-outbox`, both append-only
/// logs that fold on read, so an operation committed before
/// a restart resolves as already committed after it — the
/// commit step never re-runs, and a pending outbox delivery
/// is still pending for retry. The files are created lazily
/// on first use; a missing file is the empty state, and a
/// corrupt one halts fail-closed (see the adapters' docs).
///
/// `gate`'s policy must admit [`SYNC_DOMAIN`], as with
/// [`Self::new`]. For commit-time reauthorization that also
/// survives restarts, wrap `reauthorizer` in id-store's
/// `DurableEpochReauthorizer` over a `FilePolicyEpochSource`
/// (conventionally at `dir/policy-epoch`) before calling
/// this builder.
#[must_use]
pub fn durable(
dir: impl AsRef<Path>,
gate: AdmissionGate,
reauthorizer: Arc<dyn Reauthorizer>,
revocations: Arc<Mutex<RevocationRegistry>>,
) -> Self {
let dir = dir.as_ref();
let pipeline = AdmissionPipeline::new(
gate,
reauthorizer,
Arc::new(FileOperationLedger::new(dir.join("admission-ledger"))),
Arc::new(FileOutboxJournal::new(dir.join("admission-outbox"))),
);
Self::new(pipeline, revocations)
}

/// The pipeline this adapter runs operations through, for hook
/// registration and outbox retry.
#[must_use]
Expand Down
251 changes: 251 additions & 0 deletions pkgs/id/tests/sync_admission_durable.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
//! id-sync retained-data ingress over the durable admission
//! adapters (issue #17198, building on the durable adapters of
//! issue #17179).
//!
//! Oracle: **model** — the #10192 oracle extended per #17179 and
//! #17198: the same invariants hold across a process restart
//! with the durable adapters, on the sync receiver path.
//! Concretely, against [`SyncAdmission::durable`]:
//!
//! - An operation committed before the restart resolves as
//! `AlreadyCommitted` after it — the receiving store is not
//! re-ingested (replay does not double-apply) — and its
//! operation ID cannot be rebound to a different envelope.
//! - Commit-time reauthorization reads the durable policy
//! epoch: with no epoch record the commit refuses
//! fail-closed; once the epoch is stamped, the same admission
//! commits and reports that epoch.
//!
//! [`SyncAdmission::durable`]: id::sync_admission::SyncAdmission::durable

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

mod common;

use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use common::ingest::MemStorage;
use ed25519_dalek::SigningKey;
use id::admission::{
DurableEpochReauthorizer, FilePolicyEpochSource, LifecycleRejection, OperationId,
PolicyEpochSource, Reauthorizer,
};
use id::admission_gate::{
AdmissionContext, AdmissionGate, AdmissionReceipt, AdmissionRejection, GatePolicy,
ScopeBindingAuthorizer, StaticSignerDirectory,
};
use id::chain::{ChainExt, Event, sign};
use id::event_store::EventStore;
use id::sync_admission::{SYNC_DOMAIN, SyncAdmission, SyncAdmissionOutcome};
use id::waiting::WaitingLimits;
use id_core::id_shape::HashProfile;
use id_core::signed_envelope::{Body, Envelope, PayloadId, SUITE_ED25519};
use id_sync::federation::slices::b02_key_revocation::RevocationRegistry;
use p2panda_core::{Hash, SeqNum, SigningKey as ChainSigningKey};

const RAW: HashProfile = HashProfile::RawBlake3_256;
const TENANT: &str = "tenant-a";

fn signing_key(seed: u8) -> SigningKey {
SigningKey::from_bytes(&[seed; 32])
}

fn chain_key(seed: u8) -> ChainSigningKey {
ChainSigningKey::from_bytes(&[seed; 32])
}

fn signed_event(seed: u8, seq: SeqNum, backlink: Option<Hash>) -> Event {
let key = chain_key(seed);
let ext = ChainExt {
kind: "message".to_owned(),
group: None,
after: Vec::new(),
tag: None,
document: None,
removes: None,
note: None,
link: None,
checkpoint: None,
rotation: None,
chat: None,
anchor: None,
thread: None,
};
sign(&key, seq, backlink, None, ext).unwrap()
}

fn alice_envelope(event: &Event) -> Envelope {
let key = signing_key(11);
let payload = event.bytes.clone();
let body = Body {
domain: SYNC_DOMAIN.to_string(),
context: TENANT.to_string(),
subject: None,
graph: None,
predecessor: None,
signer_id: "alice".to_string(),
key: key.verifying_key().to_bytes(),
suite: SUITE_ED25519.to_string(),
payload_id: PayloadId::of(RAW, &payload).unwrap(),
payload_length: payload.len() as u64,
};
Envelope::sign(body, payload, &key).unwrap()
}

fn context() -> AdmissionContext {
AdmissionContext::new("alice", TENANT, "admission:write").unwrap()
}

fn gate() -> AdmissionGate {
let mut directory = StaticSignerDirectory::new();
directory.register("alice", signing_key(11).verifying_key().to_bytes());
AdmissionGate::new(
GatePolicy::admitting([SYNC_DOMAIN.to_string()]),
directory,
ScopeBindingAuthorizer,
)
}

struct AlwaysOk;

impl Reauthorizer for AlwaysOk {
fn policy_epoch(&self) -> u64 {
3
}

fn reauthorize(
&self,
_receipt: &AdmissionReceipt,
_context: &AdmissionContext,
) -> Result<(), AdmissionRejection> {
Ok(())
}
}

fn admission_dir(tag: &str) -> PathBuf {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"id-sync-admission-durable-it-{}-{tag}-{n}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
dir
}

fn durable_admission(dir: &PathBuf) -> SyncAdmission {
SyncAdmission::durable(
dir,
gate(),
Arc::new(AlwaysOk),
Arc::new(Mutex::new(RevocationRegistry::new())),
)
}

fn fresh_store() -> (EventStore, MemStorage) {
let storage = MemStorage::default();
let store = EventStore::open_with(&storage, WaitingLimits::default(), 0).unwrap();
(store, storage)
}

#[test]
fn committed_sync_operation_replays_as_already_committed_after_restart() {
let dir = admission_dir("replay");
let event = signed_event(11, 0, None);
let envelope = alice_envelope(&event);
let op = OperationId::new("op-sync-1").unwrap();

// First "process": the carrier is admitted and ingested.
let first_receipt = {
let admission = durable_admission(&dir);
let (mut store, _storage) = fresh_store();
match admission
.admit(&mut store, op.clone(), &envelope, &context(), 0)
.unwrap()
{
SyncAdmissionOutcome::Committed { receipt, .. } => receipt,
other => panic!("expected Committed, got {other:?}"),
}
};

// Restart: a fresh adapter over the same directory and a
// fresh receiving store. The re-presented operation resolves
// by ledger readback — AlreadyCommitted with the original
// receipt — and the new store is never ingested into.
let admission = durable_admission(&dir);
let (mut store, _storage) = fresh_store();
match admission
.admit(&mut store, op.clone(), &envelope, &context(), 0)
.unwrap()
{
SyncAdmissionOutcome::AlreadyCommitted { receipt } => {
assert_eq!(receipt, first_receipt);
}
other => panic!("expected AlreadyCommitted after restart, got {other:?}"),
}
assert!(
store.event_by_id(&event.id).unwrap().is_none(),
"replay after restart must not re-ingest into the store"
);

// The committed operation ID stays bound to its envelope:
// a different carrier under the same ID is a replay
// rejection, even after the restart.
let other_event = signed_event(11, 1, Some(event.id));
let other_envelope = alice_envelope(&other_event);
match admission.admit(&mut store, op, &other_envelope, &context(), 0) {
Err(LifecycleRejection::Replay { .. }) => {}
other => panic!("expected Replay rejection after restart, got {other:?}"),
}

let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn durable_epoch_gates_commit_fail_closed_until_stamped() {
let dir = admission_dir("epoch");
let epoch_path = dir.join("policy-epoch");
let event = signed_event(11, 0, None);
let envelope = alice_envelope(&event);
let op = OperationId::new("op-sync-epoch").unwrap();

let admission = SyncAdmission::durable(
&dir,
gate(),
Arc::new(DurableEpochReauthorizer::new(
FilePolicyEpochSource::new(epoch_path.clone()),
AlwaysOk,
)),
Arc::new(Mutex::new(RevocationRegistry::new())),
);
let (mut store, _storage) = fresh_store();

// No epoch record exists: commit-time reauthorization reads
// the durable epoch fail-closed and refuses the commit; the
// event never reaches the store.
match admission.admit(&mut store, op.clone(), &envelope, &context(), 0) {
Err(LifecycleRejection::Reauthorization(_)) => {}
other => panic!("expected Reauthorization refusal with no epoch record, got {other:?}"),
}
assert!(store.event_by_id(&event.id).unwrap().is_none());

// Stamp the epoch: the same admission now commits and
// reports the durable epoch as its policy epoch.
FilePolicyEpochSource::new(epoch_path)
.advance_to(5)
.unwrap();
match admission
.admit(&mut store, op, &envelope, &context(), 0)
.unwrap()
{
SyncAdmissionOutcome::Committed { policy_epoch, .. } => {
assert_eq!(policy_epoch, 5);
}
other => panic!("expected Committed after the epoch stamp, got {other:?}"),
}
assert!(store.event_by_id(&event.id).unwrap().is_some());

let _ = std::fs::remove_dir_all(&dir);
}