commit 56b5405787a104584fb19e16fbaca352d1596dee parent 2394cb4d5a4ae1d9891eeecd15c332937fb6cc5c Author: triesap <tyson@radroots.org> Date: Sun, 18 Oct 2026 04:40:38 +0000 storage: retain native signing claims and obtained evidence - share exact intent commitments and full-width attempt identities - commit immutable native claims before qualified signer dispatch - protect original obtained bytes through expiry and unknown completion - verify real signatures, transaction faults, bounds and portable APIs Diffstat:
43 files changed, 3694 insertions(+), 118 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock @@ -3651,8 +3651,10 @@ dependencies = [ "radroots_domain", "radroots_event", "radroots_event_codec", + "radroots_nostr", "radroots_protocol", "radroots_secrets", + "radroots_signing", "radroots_storage", "radroots_transport", "rustix 1.1.4", diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -337,6 +337,20 @@ impl serde_core::ser::Serialize for radroots_domain::Sequence pub fn radroots_domain::Sequence::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::Sequence pub fn radroots_domain::Sequence::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::SigningAttemptId(_) +impl radroots_domain::SigningAttemptId +pub const fn radroots_domain::SigningAttemptId::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::SigningAttemptId::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::SigningAttemptId::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::SigningAttemptId +pub fn radroots_domain::SigningAttemptId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::SigningAttemptId +pub type radroots_domain::SigningAttemptId::Err = radroots_domain::IdentifierError +pub fn radroots_domain::SigningAttemptId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::SigningAttemptId +pub fn radroots_domain::SigningAttemptId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::SigningAttemptId +pub fn radroots_domain::SigningAttemptId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::SourceId(_) impl radroots_domain::SourceId pub const fn radroots_domain::SourceId::as_bytes(&self) -> &[u8; 32] diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -445,6 +445,21 @@ pub const radroots_protocol::event::v1::TRADE_STATE_VOCABULARY: &[radroots_proto pub fn radroots_protocol::event::v1::schema_registry() -> core::result::Result<radroots_protocol::schema::Registry, radroots_protocol::schema::Error> pub fn radroots_protocol::event::v1::validate_catalog(&[radroots_protocol::event::v1::EventDescriptor]) -> core::result::Result<(), radroots_protocol::event::v1::Error> pub fn radroots_protocol::event::v1::validate_trade_state_vocabulary(&[radroots_protocol::event::v1::TradeState]) -> core::result::Result<(), radroots_protocol::event::v1::Error> +pub mod radroots_protocol::intent +#[non_exhaustive] pub enum radroots_protocol::intent::ArtifactRole +pub radroots_protocol::intent::ArtifactRole::BusinessSeal +pub radroots_protocol::intent::ArtifactRole::GiftWrap +pub radroots_protocol::intent::ArtifactRole::PublicEvent +pub struct radroots_protocol::intent::IntentBinding +impl radroots_protocol::intent::IntentBinding +pub const fn radroots_protocol::intent::IntentBinding::command_digest(&self) -> &[u8; 32] +pub const fn radroots_protocol::intent::IntentBinding::digest(&self) -> &[u8; 32] +pub fn radroots_protocol::intent::IntentBinding::from_components(radroots_domain::identifier::OperationId, [u8; 32], [u8; 32], radroots_protocol::intent::ArtifactRole, core::option::Option<radroots_identity::key::PublicKey>, core::num::nonzero::NonZeroU64) -> core::result::Result<Self, radroots_protocol::intent::InvalidIntentBinding> +pub const fn radroots_protocol::intent::IntentBinding::operation_id(self) -> radroots_domain::identifier::OperationId +pub struct radroots_protocol::intent::InvalidIntentBinding +impl core::error::Error for radroots_protocol::intent::InvalidIntentBinding +impl core::fmt::Display for radroots_protocol::intent::InvalidIntentBinding +pub fn radroots_protocol::intent::InvalidIntentBinding::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub mod radroots_protocol::nip01 pub enum radroots_protocol::nip01::WireError pub radroots_protocol::nip01::WireError::InvalidInput diff --git a/contracts/api_baselines/radroots_signing.txt b/contracts/api_baselines/radroots_signing.txt @@ -146,10 +146,8 @@ pub fn radroots_signing::identity::SigningOperationId::to_hex(self) -> alloc::st impl core::fmt::Debug for radroots_signing::identity::SigningOperationId pub fn radroots_signing::identity::SigningOperationId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub mod radroots_signing::issuance -#[non_exhaustive] pub enum radroots_signing::issuance::ArtifactRole -pub radroots_signing::issuance::ArtifactRole::BusinessSeal -pub radroots_signing::issuance::ArtifactRole::GiftWrap -pub radroots_signing::issuance::ArtifactRole::PublicEvent +pub use radroots_signing::issuance::ArtifactRole +pub use radroots_signing::issuance::IntentBinding #[non_exhaustive] pub enum radroots_signing::issuance::OutcomeKind pub radroots_signing::issuance::OutcomeKind::NotDispatched(radroots_signing::provider::ProviderError) pub radroots_signing::issuance::OutcomeKind::Obtained(radroots_signing::issuance::SignedArtifact) @@ -165,11 +163,6 @@ impl radroots_signing::issuance::ArtifactFingerprint pub const fn radroots_signing::issuance::ArtifactFingerprint::covered_bytes(self) -> usize pub const fn radroots_signing::issuance::ArtifactFingerprint::sha256(&self) -> &[u8; 32] pub const fn radroots_signing::issuance::ArtifactFingerprint::total_bytes(self) -> usize -pub struct radroots_signing::issuance::IntentBinding -impl radroots_signing::issuance::IntentBinding -pub const fn radroots_signing::issuance::IntentBinding::command_digest(&self) -> &[u8; 32] -pub const fn radroots_signing::issuance::IntentBinding::digest(&self) -> &[u8; 32] -pub const fn radroots_signing::issuance::IntentBinding::operation_id(self) -> radroots_domain::identifier::OperationId pub struct radroots_signing::issuance::RejectedArtifact impl radroots_signing::issuance::RejectedArtifact pub const fn radroots_signing::issuance::RejectedArtifact::fingerprint(self) -> core::option::Option<radroots_signing::issuance::ArtifactFingerprint> @@ -184,25 +177,25 @@ pub fn radroots_signing::issuance::SignedArtifact::fmt(&self, &mut core::fmt::Fo pub struct radroots_signing::issuance::SigningIntent impl radroots_signing::issuance::SigningIntent pub const fn radroots_signing::issuance::SigningIntent::author(&self) -> radroots_identity::key::PublicKey -pub const fn radroots_signing::issuance::SigningIntent::binding(&self) -> radroots_signing::issuance::IntentBinding +pub const fn radroots_signing::issuance::SigningIntent::binding(&self) -> radroots_protocol::intent::IntentBinding pub fn radroots_signing::issuance::SigningIntent::check_before_effect(&self, radroots_identity::key::PublicKey, u64) -> core::result::Result<(), radroots_signing::provider::ProviderError> pub fn radroots_signing::issuance::SigningIntent::from_chat_seal(radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, &radroots_protocol::chat::ChatSeal, radroots_signing::provider::ProviderCall) -> core::result::Result<Self, radroots_signing::provider::ProviderError> -pub fn radroots_signing::issuance::SigningIntent::new(radroots_domain::identifier::OperationId, [u8; 32], radroots_event_codec::authoring::AuthoredEventPlan, radroots_signing::issuance::ArtifactRole, core::option::Option<radroots_identity::key::PublicKey>, radroots_signing::provider::ProviderCall) -> core::result::Result<Self, radroots_signing::provider::ProviderError> +pub fn radroots_signing::issuance::SigningIntent::new(radroots_domain::identifier::OperationId, [u8; 32], radroots_event_codec::authoring::AuthoredEventPlan, radroots_protocol::intent::ArtifactRole, core::option::Option<radroots_identity::key::PublicKey>, radroots_signing::provider::ProviderCall) -> core::result::Result<Self, radroots_signing::provider::ProviderError> pub const fn radroots_signing::issuance::SigningIntent::recipient(&self) -> core::option::Option<radroots_identity::key::PublicKey> -pub const fn radroots_signing::issuance::SigningIntent::role(&self) -> radroots_signing::issuance::ArtifactRole +pub const fn radroots_signing::issuance::SigningIntent::role(&self) -> radroots_protocol::intent::ArtifactRole pub const fn radroots_signing::issuance::SigningIntent::signed_json_bytes(&self) -> usize pub fn radroots_signing::issuance::SigningIntent::with_plan<T>(&self, impl core::ops::function::FnOnce(&radroots_event_codec::authoring::AuthoredEventPlan) -> T) -> T impl core::fmt::Debug for radroots_signing::issuance::SigningIntent pub fn radroots_signing::issuance::SigningIntent::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_signing::issuance::SigningOutcome impl radroots_signing::issuance::SigningOutcome -pub const fn radroots_signing::issuance::SigningOutcome::binding(&self) -> radroots_signing::issuance::IntentBinding +pub const fn radroots_signing::issuance::SigningOutcome::binding(&self) -> radroots_protocol::intent::IntentBinding pub fn radroots_signing::issuance::SigningOutcome::capture(&radroots_signing::issuance::SigningIntent, alloc::string::String, core::option::Option<core::num::nonzero::NonZeroU64>) -> Self -pub fn radroots_signing::issuance::SigningOutcome::enforce_binding(self, radroots_signing::issuance::IntentBinding) -> Self -pub fn radroots_signing::issuance::SigningOutcome::into_parts(self) -> (radroots_signing::issuance::IntentBinding, radroots_signing::issuance::OutcomeKind) +pub fn radroots_signing::issuance::SigningOutcome::enforce_binding(self, radroots_protocol::intent::IntentBinding) -> Self +pub fn radroots_signing::issuance::SigningOutcome::into_parts(self) -> (radroots_protocol::intent::IntentBinding, radroots_signing::issuance::OutcomeKind) pub const fn radroots_signing::issuance::SigningOutcome::kind(&self) -> &radroots_signing::issuance::OutcomeKind -pub const fn radroots_signing::issuance::SigningOutcome::not_dispatched(radroots_signing::issuance::IntentBinding, radroots_signing::provider::ProviderError) -> Self -pub const fn radroots_signing::issuance::SigningOutcome::unknown(radroots_signing::issuance::IntentBinding, radroots_signing::provider::ProviderError) -> Self +pub const fn radroots_signing::issuance::SigningOutcome::not_dispatched(radroots_protocol::intent::IntentBinding, radroots_signing::provider::ProviderError) -> Self +pub const fn radroots_signing::issuance::SigningOutcome::unknown(radroots_protocol::intent::IntentBinding, radroots_signing::provider::ProviderError) -> Self pub struct radroots_signing::issuance::VerifiedDmRelayAdvertisement impl radroots_signing::issuance::VerifiedDmRelayAdvertisement pub const fn radroots_signing::issuance::VerifiedDmRelayAdvertisement::advertisement(&self) -> &radroots_protocol::chat::routes::DmRelayAdvertisement diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -763,10 +763,20 @@ pub radroots_storage::command::AdmissionOutcome::Committed(radroots_storage::com pub radroots_storage::command::AdmissionOutcome::Unknown(radroots_storage::command::CommitAttempt) impl core::fmt::Debug for radroots_storage::command::AdmissionOutcome pub fn radroots_storage::command::AdmissionOutcome::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub enum radroots_storage::command::ClaimAttemptOutcome +pub radroots_storage::command::ClaimAttemptOutcome::Claimed(radroots_storage::command::SigningAttempt) +pub radroots_storage::command::ClaimAttemptOutcome::Retained(radroots_storage::command::SigningAttempt) +pub radroots_storage::command::ClaimAttemptOutcome::Unknown(radroots_storage::command::CommitAttempt) +impl core::fmt::Debug for radroots_storage::command::ClaimAttemptOutcome +pub fn radroots_storage::command::ClaimAttemptOutcome::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub enum radroots_storage::command::EvidenceCaptureOutcome +pub radroots_storage::command::EvidenceCaptureOutcome::Committed(radroots_storage::command::EvidenceReceipt) +pub radroots_storage::command::EvidenceCaptureOutcome::Unknown(radroots_storage::command::CommitAttempt) #[non_exhaustive] pub enum radroots_storage::command::OperationError pub radroots_storage::command::OperationError::DeadlineExceeded pub radroots_storage::command::OperationError::IdempotencyConflict pub radroots_storage::command::OperationError::InvalidCommand +pub radroots_storage::command::OperationError::InvalidEvidence pub radroots_storage::command::OperationError::MissingHistory pub radroots_storage::command::OperationError::RecoveryRequired pub radroots_storage::command::OperationError::StorageFailure @@ -804,6 +814,25 @@ pub const fn radroots_storage::command::BoundSigningPlan::prepared(&self) -> &ra pub const fn radroots_storage::command::BoundSigningPlan::transaction_id(&self) -> radroots_domain::identifier::TransactionId impl core::fmt::Debug for radroots_storage::command::BoundSigningPlan pub fn radroots_storage::command::BoundSigningPlan::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::command::CapturedSeal +impl radroots_storage::command::CapturedSeal +pub const fn radroots_storage::command::CapturedSeal::attempt(&self) -> &radroots_storage::command::SigningAttempt +pub const fn radroots_storage::command::CapturedSeal::evidence(&self) -> &radroots_storage::command::SealEvidence +pub fn radroots_storage::command::CapturedSeal::from_committed_store(radroots_storage::command::SigningAttempt, radroots_storage::command::SealEvidence, radroots_domain::identifier::TransactionId) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::command::CapturedSeal::receipt(&self) -> radroots_storage::command::EvidenceReceipt +impl core::fmt::Debug for radroots_storage::command::CapturedSeal +pub fn radroots_storage::command::CapturedSeal::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::command::ClaimAttemptRequest +impl radroots_storage::command::ClaimAttemptRequest +pub const fn radroots_storage::command::ClaimAttemptRequest::binding(&self) -> &radroots_storage::workspace::WorkspaceBinding +pub const fn radroots_storage::command::ClaimAttemptRequest::command_digest(&self) -> radroots_domain::identifier::CommandDigest +pub fn radroots_storage::command::ClaimAttemptRequest::identity(&self) -> radroots_storage::command::CommitAttempt +pub const fn radroots_storage::command::ClaimAttemptRequest::new(radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, [u8; 32], radroots_identity::key::PublicKey) -> Self +pub const fn radroots_storage::command::ClaimAttemptRequest::operation_id(&self) -> radroots_domain::identifier::OperationId +pub const fn radroots_storage::command::ClaimAttemptRequest::plan_digest(&self) -> &[u8; 32] +pub const fn radroots_storage::command::ClaimAttemptRequest::recipient(&self) -> radroots_identity::key::PublicKey +impl core::fmt::Debug for radroots_storage::command::ClaimAttemptRequest +pub fn radroots_storage::command::ClaimAttemptRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage::command::CommitAttempt impl radroots_storage::command::CommitAttempt pub const fn radroots_storage::command::CommitAttempt::command_digest(self) -> radroots_domain::identifier::CommandDigest @@ -811,6 +840,18 @@ pub const fn radroots_storage::command::CommitAttempt::new(radroots_domain::iden pub const fn radroots_storage::command::CommitAttempt::operation_id(self) -> radroots_domain::identifier::OperationId pub const fn radroots_storage::command::CommitAttempt::transaction_id(self) -> core::option::Option<radroots_domain::identifier::TransactionId> pub const fn radroots_storage::command::CommitAttempt::workspace_id(self) -> radroots_domain::identifier::WorkspaceId +pub struct radroots_storage::command::EvidenceReceipt +impl radroots_storage::command::EvidenceReceipt +pub const fn radroots_storage::command::EvidenceReceipt::attempt_id(&self) -> radroots_domain::identifier::SigningAttemptId +pub const fn radroots_storage::command::EvidenceReceipt::command_digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_storage::command::EvidenceReceipt::digest(&self) -> &[u8; 32] +pub const fn radroots_storage::command::EvidenceReceipt::event_id(&self) -> radroots_domain::identifier::EnvelopeEventId +pub const fn radroots_storage::command::EvidenceReceipt::from_committed_store(&radroots_storage::command::SealEvidence, radroots_domain::identifier::TransactionId) -> Self +pub const fn radroots_storage::command::EvidenceReceipt::observed_at_unix_ms(&self) -> core::option::Option<core::num::nonzero::NonZeroU64> +pub const fn radroots_storage::command::EvidenceReceipt::operation_id(&self) -> radroots_domain::identifier::OperationId +pub const fn radroots_storage::command::EvidenceReceipt::recipient(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_storage::command::EvidenceReceipt::transaction_id(&self) -> radroots_domain::identifier::TransactionId +pub const fn radroots_storage::command::EvidenceReceipt::workspace_id(&self) -> radroots_domain::identifier::WorkspaceId pub struct radroots_storage::command::PreparedOperation impl radroots_storage::command::PreparedOperation pub fn radroots_storage::command::PreparedOperation::from_committed_store(radroots_storage::command::AdmissionRequest, radroots_domain::identifier::TransactionId, radroots_domain::context::Sequence, radroots_domain::issuance::IssuanceWindow) -> core::result::Result<Self, radroots_storage::command::OperationError> @@ -821,10 +862,46 @@ pub const fn radroots_storage::command::PreparedOperation::revision(&self) -> ra pub const fn radroots_storage::command::PreparedOperation::transaction_id(&self) -> radroots_domain::identifier::TransactionId impl core::fmt::Debug for radroots_storage::command::PreparedOperation pub fn radroots_storage::command::PreparedOperation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::command::SealEvidence +impl radroots_storage::command::SealEvidence +pub const fn radroots_storage::command::SealEvidence::attempt_id(&self) -> radroots_domain::identifier::SigningAttemptId +pub const fn radroots_storage::command::SealEvidence::command_digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_storage::command::SealEvidence::digest(&self) -> &[u8; 32] +pub const fn radroots_storage::command::SealEvidence::event_id(&self) -> radroots_domain::identifier::EnvelopeEventId +pub const fn radroots_storage::command::SealEvidence::intent(&self) -> radroots_protocol::intent::IntentBinding +pub fn radroots_storage::command::SealEvidence::matches_attempt(&self, &radroots_storage::command::SigningAttempt) -> bool +pub const fn radroots_storage::command::SealEvidence::observed_at_unix_ms(&self) -> core::option::Option<core::num::nonzero::NonZeroU64> +pub const fn radroots_storage::command::SealEvidence::operation_id(&self) -> radroots_domain::identifier::OperationId +pub const fn radroots_storage::command::SealEvidence::plan_digest(&self) -> &[u8; 32] +pub fn radroots_storage::command::SealEvidence::raw_json(&self) -> &str +pub const fn radroots_storage::command::SealEvidence::recipient(&self) -> radroots_identity::key::PublicKey +pub fn radroots_storage::command::SealEvidence::retained_copy(&self) -> Self +pub fn radroots_storage::command::SealEvidence::verify(&radroots_storage::command::SigningAttempt, &str, core::option::Option<core::num::nonzero::NonZeroU64>) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::command::SealEvidence::workspace_id(&self) -> radroots_domain::identifier::WorkspaceId +impl core::fmt::Debug for radroots_storage::command::SealEvidence +pub fn radroots_storage::command::SealEvidence::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::command::SigningAttempt +impl radroots_storage::command::SigningAttempt +pub const fn radroots_storage::command::SigningAttempt::attempt_id(&self) -> radroots_domain::identifier::SigningAttemptId +pub const fn radroots_storage::command::SigningAttempt::binding(&self) -> radroots_protocol::intent::IntentBinding +pub const fn radroots_storage::command::SigningAttempt::bound_plan(&self) -> &radroots_storage::command::BoundSigningPlan +pub const fn radroots_storage::command::SigningAttempt::claimed_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_storage::command::SigningAttempt::deadline_unix_ms(&self) -> core::num::nonzero::NonZeroU64 +pub fn radroots_storage::command::SigningAttempt::from_committed_store(radroots_storage::command::BoundSigningPlan, radroots_identity::key::PublicKey, radroots_domain::identifier::SigningAttemptId, radroots_domain::identifier::TransactionId, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::command::SigningAttempt::identity(&self) -> radroots_storage::command::CommitAttempt +pub fn radroots_storage::command::SigningAttempt::into_bound_plan(self) -> radroots_storage::command::BoundSigningPlan +pub fn radroots_storage::command::SigningAttempt::seal(&self) -> &radroots_protocol::chat::ChatSeal +pub const fn radroots_storage::command::SigningAttempt::transaction_id(&self) -> radroots_domain::identifier::TransactionId +impl core::fmt::Debug for radroots_storage::command::SigningAttempt +pub fn radroots_storage::command::SigningAttempt::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub trait radroots_storage::command::OperationJournal: radroots_storage::workspace::WorkspaceStore pub fn radroots_storage::command::OperationJournal::admit_command_and_hold(&self, radroots_storage::command::AdmissionRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::AdmissionOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::bind_signing_intents(&self, radroots_storage::workspace::WorkspaceBinding, radroots_protocol::chat::plan::ChatSigningPlan, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::PlanBindingOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::command::OperationJournal::capture_evidence<'a>(&'a self, radroots_storage::workspace::AttachmentInput, &'a radroots_storage::workspace::AttachmentProof, &'a radroots_storage::command::SealEvidence) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::command::EvidenceCaptureOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::command::OperationJournal::claim_attempt(&self, radroots_storage::command::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::ClaimAttemptOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::command::OperationJournal::obtained_evidence(&self, radroots_storage::command::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::CapturedSeal>, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::PreparedOperation>, radroots_storage::command::OperationError>> +pub fn radroots_storage::command::OperationJournal::signing_attempt(&self, radroots_storage::command::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::SigningAttempt>, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::signing_plan(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::BoundSigningPlan>, radroots_storage::command::OperationError>> pub mod radroots_storage::event pub use radroots_storage::event::BoxFuture diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -382,7 +382,11 @@ pub fn radroots_storage_sqlite::workspace::NativeWorkspace::fmt(&self, &mut core impl radroots_storage::command::OperationJournal for radroots_storage_sqlite::workspace::NativeWorkspace pub fn radroots_storage_sqlite::workspace::NativeWorkspace::admit_command_and_hold(&self, radroots_storage::command::AdmissionRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::AdmissionOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::bind_signing_intents(&self, radroots_storage::workspace::WorkspaceBinding, radroots_protocol::chat::plan::ChatSigningPlan, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::PlanBindingOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::capture_evidence<'a>(&'a self, radroots_storage::workspace::AttachmentInput, &'a radroots_storage::workspace::AttachmentProof, &'a radroots_storage::command::issuance::SealEvidence) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::command::issuance::EvidenceCaptureOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::claim_attempt(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::issuance::ClaimAttemptOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::obtained_evidence(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::issuance::CapturedSeal>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::PreparedOperation>, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::signing_attempt(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::issuance::SigningAttempt>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::signing_plan(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::BoundSigningPlan>, radroots_storage::command::OperationError>> impl radroots_storage::workspace::WorkspaceStore for radroots_storage_sqlite::workspace::NativeWorkspace pub fn radroots_storage_sqlite::workspace::NativeWorkspace::authenticate(&self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::WorkspaceError>> diff --git a/contracts/coverage-profiles.toml b/contracts/coverage-profiles.toml @@ -9,7 +9,7 @@ features = ["session", "signer_session", "client_session", "workspace_session"] test_threads = 1 [profiles.crates."radroots_protocol"] -features = ["chat"] +features = ["chat", "intent"] [profiles.crates."radroots_signing"] features = ["chat"] diff --git a/contracts/protocol/chat.v1.json b/contracts/protocol/chat.v1.json @@ -73,7 +73,7 @@ "59.md" ] }, - "remaining": "Complete owned native execution route/capability approval, signer attempt ownership, obtained evidence capture, install/outbox, exact per-recipient wrapping/delivery, full receipts, browser/bindings and final acceptance", + "remaining": "Complete owned native execution route/capability approval and ordinary client job orchestration, install/outbox, exact per-recipient wrapping/delivery, full receipts, browser/bindings and final acceptance", "structured_commerce_authoring_enabled": false, "package_publication_authorized": false, "recipient_dm_routes": { @@ -95,11 +95,29 @@ "protected_data_part_max_bytes": 16384, "max_data_parts": 24, "protected_total_max_bytes": 2097152, - "native_workspace_schema": 4, + "native_workspace_schema": 5, "predecessors": "Preserve and refuse; no inferred timestamps or automatic namespace rewrite", "queue": "32 slots plus conservative queued and in-flight reservations under 4194304 bytes", "transaction": "Current protected grant, original preparation, all indexed facts and fixed first-issue window rechecked under BEGIN IMMEDIATE; crypto work before transaction", "completion": "Confirmed commit, known rollback and original anchored unknown are distinct; accepted owner work survives observer loss", - "remaining": "Execution route/capability approval, attempt ownership and S/T2/D, complete receipts, supported consumer adoption, browser/binding runtime and final acceptance" + "remaining": "Execution route/capability approval, owned ordinary execution, T2/D, complete receipts, supported consumer adoption, browser/binding runtime and final acceptance" + }, + "native_issuance": { + "state": "native_claim_and_obtained_capture_component_implemented", + "attempt_identity": "Full 256-bit Domain SigningAttemptId; immutable original command, plan, recipient, exact v1 intent, first-issue window and transaction provenance", + "intent_data_owner": "radroots_protocol::intent; Signing reexports preserve the exact existing v1 byte layout", + "fresh_claim": "Current protected grant, complete original facts and deadline rechecked under BEGIN IMMEDIATE before dispatch; no signer invocation inside SQLite", + "retained_or_unknown_claim": "Potential issuance; never infer safe reissue", + "obtained_capture": "Append only independently verified original bytes matching the actual protected claim; original credential and scope without fresh deadline, revocation or observation-clock admission", + "caller_ownership": "Borrowed original retained by caller through error, lost observer or unknown completion", + "observation": "First original optional time is immutable; missing time remains null", + "evidence_max_bytes": 65536, + "protected_data_part_max_bytes": 16384, + "max_data_parts": 4, + "protected_total_max_bytes": 1048576, + "capture_queue_reservation_bytes": 262144, + "schema": 5, + "schema_objects": 11, + "remaining": "Ordinary client-owned orchestration and full operation receipts, route/provider approval, installation/outbox/delivery, target graph retirement and all consumer/final gates" } } diff --git a/crates/domain/src/identifier.rs b/crates/domain/src/identifier.rs @@ -162,3 +162,8 @@ identifier!( ApprovalIntentDigest, "A commitment to the exact intent presented for approval." ); + +identifier!( + SigningAttemptId, + "An exact 256-bit retained signing invocation identity, distinct from an operation or artifact." +); diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs @@ -20,7 +20,7 @@ pub use context::{ }; pub use identifier::{ ApprovalIntentDigest, CheckpointDigest, CommandDigest, EnvelopeEventId, ExecutorId, GrantId, - IdentifierError, MessageId, OperationId, OrderId, RecordId, RouteDigest, SourceId, ThreadId, - TransactionId, WorkspaceId, + IdentifierError, MessageId, OperationId, OrderId, RecordId, RouteDigest, SigningAttemptId, + SourceId, ThreadId, TransactionId, WorkspaceId, }; pub use issuance::{FIRST_ISSUANCE_MAX_SECONDS, IssuanceWindow}; diff --git a/crates/domain/tests/identifier.rs b/crates/domain/tests/identifier.rs @@ -28,6 +28,7 @@ fn captured_context_identities_preserve_full_width_and_canonical_encoding() { } }}; } + check!(radroots_domain::SigningAttemptId); check!(radroots_domain::GrantId); check!(radroots_domain::RecordId); check!(radroots_domain::SourceId); diff --git a/crates/protocol/Cargo.toml b/crates/protocol/Cargo.toml @@ -35,6 +35,7 @@ default = ["std", "serde"] serde = ["dep:serde"] std = ["serde?/std"] commands = ["serde", "dep:radroots_domain", "dep:serde_json", "dep:sha2", "dep:zeroize"] +intent = ["dep:radroots_domain", "dep:sha2"] nip01 = ["dep:radroots_identity", "dep:sha2", "dep:zeroize"] chat = ["commands", "nip01"] diff --git a/crates/protocol/README.md b/crates/protocol/README.md @@ -21,6 +21,7 @@ numbers embedded in wire and schema contracts. | `schema` | schema IDs, module generations, descriptors, and aggregate registries | | `command` (`commands` feature) | bounded closed v1 inquiry/reply data codec and exact command/approval-intent hashes | | `nip01` (`nip01` feature) | exact bounded canonical preimages, IDs and complete-event sizes | +| `intent` (`intent` feature) | exact v1 signing commitment data without execution authority | | `chat` (`chat` feature) | bounded kind-14/13 data, complete immutable signing-plan codec and observed DM route descriptors | Versioned DTOs live below an explicit generation module. The command codec @@ -38,6 +39,7 @@ they use. | `serde` | yes | derives serialization and deserialization for wire-contract types | | `commands` | no | enables the portable closed chat codec, domain values, SHA-256 and zeroizing private command buffers | | `nip01` | no | enables pure exact NIP-01 serialization and complete byte counting | +| `intent` | no | enables pure domain-separated v1 signing commitment data | | `chat` | no | enables commands, NIP-01 and the bounded known-kind chat/plan data profile | Disabling default features leaves the catalog and structural validation APIs diff --git a/crates/protocol/src/intent.rs b/crates/protocol/src/intent.rs @@ -0,0 +1,91 @@ +//! Exact v1 signing commitment data, without signer or execution authority. +use core::num::NonZeroU64; +use radroots_domain::{OperationId, PublicKey}; +use sha2::{Digest, Sha256}; + +const DOMAIN: &[u8] = b"radroots.exact_signing_intent.v1\0"; +const MAX_OBSERVATION_UNIX_MS: u64 = 253_402_300_799_999; + +/// Purpose of an exact transport artifact, separate from business permission. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum ArtifactRole { + /// A public authored event, excluding private carrier and rumor kinds. + PublicEvent, + /// One encrypted kind-13 business seal for an exact recipient. + BusinessSeal, + /// One outer kind-1059 gift wrap for an exact recipient. + GiftWrap, +} +/// Invalid descriptor data; no provider diagnostic or private input is retained. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct InvalidIntentBinding; +impl core::fmt::Display for InvalidIntentBinding { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("invalid exact intent binding") + } +} +impl core::error::Error for InvalidIntentBinding {} + +/// Immutable v1 commitment, with no signature, qualified replay guarantee, +/// command grant, dispatch permission or proof of a retained transaction. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct IntentBinding { + operation_id: OperationId, + command_digest: [u8; 32], + digest: [u8; 32], +} +impl IntentBinding { + /// Hashes exact already-captured data. The caller independently validates + /// the plan, role, current access, provider and durable execution boundary. + /// This preserves the existing v1 byte layout and domain separator. + pub fn from_components( + operation_id: OperationId, + command_digest: [u8; 32], + plan_digest: [u8; 32], + role: ArtifactRole, + recipient: Option<PublicKey>, + deadline_unix_ms: NonZeroU64, + ) -> Result<Self, InvalidIntentBinding> { + if deadline_unix_ms.get() > MAX_OBSERVATION_UNIX_MS + || matches!(role, ArtifactRole::PublicEvent) != recipient.is_none() + { + return Err(InvalidIntentBinding); + } + let mut digest = Sha256::new(); + digest.update(DOMAIN); + digest.update(operation_id.as_bytes()); + digest.update(command_digest); + digest.update(plan_digest); + digest.update([match role { + ArtifactRole::PublicEvent => 0, + ArtifactRole::BusinessSeal => 1, + ArtifactRole::GiftWrap => 2, + }]); + match recipient { + Some(peer) => { + digest.update([1]); + digest.update(peer.as_bytes()); + } + None => digest.update([0]), + } + digest.update(deadline_unix_ms.get().to_be_bytes()); + Ok(Self { + operation_id, + command_digest, + digest: digest.finalize().into(), + }) + } + /// Returns the full original operation identity, without truncation. + pub const fn operation_id(self) -> OperationId { + self.operation_id + } + /// Borrows the original semantic command commitment. + pub const fn command_digest(&self) -> &[u8; 32] { + &self.command_digest + } + /// Borrows the exact domain-separated v1 commitment. + pub const fn digest(&self) -> &[u8; 32] { + &self.digest + } +} diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs @@ -9,6 +9,10 @@ extern crate alloc; #[cfg(feature = "commands")] pub mod command; +/// Pure exact v1 signing-commitment data, without execution authority. +#[cfg(feature = "intent")] +pub mod intent; + /// Exact canonical NIP-01 bytes and complete serialization budgets. #[cfg(feature = "nip01")] pub mod nip01; diff --git a/crates/protocol/tests/fixtures/exact_intent.v1.json b/crates/protocol/tests/fixtures/exact_intent.v1.json @@ -0,0 +1,33 @@ +{ + "schema": "radroots.exact_signing_intent.v1.independent_vectors", + "oracle": "v26.10.0", + "vectors": [ + { + "operation": "1111111111111111111111111111111111111111111111111111111111111111", + "command": "2222222222222222222222222222222222222222222222222222222222222222", + "plan": "3333333333333333333333333333333333333333333333333333333333333333", + "role": "public_event", + "recipient": null, + "deadline": "1700000120000", + "digest": "24c2c2ecb795b91e7fbf0dbe284d48d77c0e8eb38671687995a868e7b17dfd36" + }, + { + "operation": "1111111111111111111111111111111111111111111111111111111111111111", + "command": "2222222222222222222222222222222222222222222222222222222222222222", + "plan": "3333333333333333333333333333333333333333333333333333333333333333", + "role": "business_seal", + "recipient": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "deadline": "1700000120000", + "digest": "812af4a16c3656efb6e0a56a929560720c4bcd352802d3b1a4396dbff4196b69" + }, + { + "operation": "1111111111111111111111111111111111111111111111111111111111111111", + "command": "2222222222222222222222222222222222222222222222222222222222222222", + "plan": "3333333333333333333333333333333333333333333333333333333333333333", + "role": "gift_wrap", + "recipient": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "deadline": "253402300799999", + "digest": "821f9001e2f9b9cecb8c2b7b4eea7c60ba1e14b530e5180035d103dbcc672e30" + } + ] +} diff --git a/crates/protocol/tests/intent.rs b/crates/protocol/tests/intent.rs @@ -0,0 +1,76 @@ +#![cfg(feature = "intent")] +use core::num::NonZeroU64; +use radroots_domain::{OperationId, PublicKey}; +use radroots_protocol::intent::{ArtifactRole, IntentBinding}; + +#[test] +fn exact_v1_commitments_match_independent_ecmascript_vectors() { + let vectors: serde_json::Value = + serde_json::from_str(include_str!("fixtures/exact_intent.v1.json")).unwrap(); + for row in vectors["vectors"].as_array().unwrap() { + let role = match row["role"].as_str().unwrap() { + "public_event" => ArtifactRole::PublicEvent, + "business_seal" => ArtifactRole::BusinessSeal, + "gift_wrap" => ArtifactRole::GiftWrap, + _ => unreachable!(), + }; + let peer = row["recipient"] + .as_str() + .map(|value| PublicKey::from_hex(value).unwrap()); + let binding = IntentBinding::from_components( + OperationId::from_bytes([0x11; 32]), + [0x22; 32], + [0x33; 32], + role, + peer, + NonZeroU64::new(row["deadline"].as_str().unwrap().parse().unwrap()).unwrap(), + ) + .unwrap(); + let expected: OperationId = row["digest"].as_str().unwrap().parse().unwrap(); + assert_eq!(binding.digest(), expected.as_bytes()); + assert_eq!(binding.operation_id().as_bytes(), &[0x11; 32]); + assert_eq!(binding.command_digest(), &[0x22; 32]); + for (operation, command, plan) in [ + (OperationId::from_bytes([0x12; 32]), [0x22; 32], [0x33; 32]), + (OperationId::from_bytes([0x11; 32]), [0x23; 32], [0x33; 32]), + (OperationId::from_bytes([0x11; 32]), [0x22; 32], [0x34; 32]), + ] { + assert_ne!( + IntentBinding::from_components( + operation, + command, + plan, + role, + peer, + NonZeroU64::new(row["deadline"].as_str().unwrap().parse().unwrap()).unwrap() + ) + .unwrap(), + binding + ); + } + } +} +#[test] +fn binding_data_rejects_invalid_role_recipient_and_time_without_authority() { + let peer = + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798") + .unwrap(); + for (role, recipient, deadline) in [ + (ArtifactRole::PublicEvent, Some(peer), 1), + (ArtifactRole::BusinessSeal, None, 1), + (ArtifactRole::GiftWrap, None, 1), + (ArtifactRole::BusinessSeal, Some(peer), 253_402_300_800_000), + ] { + let error = IntentBinding::from_components( + OperationId::from_bytes([1; 32]), + [2; 32], + [3; 32], + role, + recipient, + NonZeroU64::new(deadline).unwrap(), + ) + .unwrap_err(); + assert_eq!(error.to_string(), "invalid exact intent binding"); + assert!(core::error::Error::source(&error).is_none()); + } +} diff --git a/crates/protocol/tests/package_boundary.rs b/crates/protocol/tests/package_boundary.rs @@ -16,6 +16,7 @@ const VERSIONED_SOURCES: &[&str] = &[ include_str!("../src/schema.rs"), include_str!("../src/command.rs"), include_str!("../src/nip01.rs"), + include_str!("../src/intent.rs"), include_str!("../src/chat.rs"), include_str!("../src/chat/routes.rs"), include_str!("../src/chat/plan.rs"), @@ -30,7 +31,9 @@ fn manifest_has_approved_data_only_features_and_dependencies() { assert!(MANIFEST.contains("default = [\"std\", \"serde\"]")); assert_eq!( table_keys(MANIFEST, "[features]"), - BTreeSet::from(["chat", "commands", "default", "nip01", "serde", "std"]) + BTreeSet::from([ + "chat", "commands", "default", "intent", "nip01", "serde", "std" + ]) ); assert_eq!( table_keys(MANIFEST, "[dependencies]"), @@ -61,6 +64,7 @@ fn crate_root_exposes_only_the_approved_versioned_skeleton() { "error", "event", "nip01", + "intent", "radrootsd", "runtime", "schema" diff --git a/crates/protocol/tests/support/exact_intent_oracle.mjs b/crates/protocol/tests/support/exact_intent_oracle.mjs @@ -0,0 +1,9 @@ +import { createHash } from 'node:crypto'; +const author = '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'; +const vectors = [ ['public_event',0,null,'1700000120000'], ['business_seal',1,author,'1700000120000'], ['gift_wrap',2,author,'253402300799999'] ].map(([role,tag,recipient,deadline])=>{ + const operation='11'.repeat(32),command='22'.repeat(32),plan='33'.repeat(32),time=Buffer.alloc(8);time.writeBigUInt64BE(BigInt(deadline)); + const parts=[Buffer.from('radroots.exact_signing_intent.v1\0'),Buffer.from(operation,'hex'),Buffer.from(command,'hex'),Buffer.from(plan,'hex'),Buffer.from([tag]),Buffer.from([recipient===null?0:1])]; + if(recipient!==null)parts.push(Buffer.from(recipient,'hex'));parts.push(time); + return {operation,command,plan,role,recipient,deadline,digest:createHash('sha256').update(Buffer.concat(parts)).digest('hex')}; +}); +process.stdout.write(JSON.stringify({schema:'radroots.exact_signing_intent.v1.independent_vectors',oracle:process.version,vectors},null,2)+'\n'); diff --git a/crates/signing/Cargo.toml b/crates/signing/Cargo.toml @@ -53,7 +53,7 @@ radroots_domain = { workspace = true, default-features = false } radroots_event = { workspace = true, default-features = false } radroots_event_codec = { workspace = true, default-features = false } radroots_identity = { workspace = true, default-features = false } -radroots_protocol = { workspace = true, default-features = false, features = ["nip01"] } +radroots_protocol = { workspace = true, default-features = false, features = ["nip01", "intent"] } hex = { version = "0.4", default-features = false, features = ["alloc"] } sha2 = { workspace = true, default-features = false } zeroize = { workspace = true, default-features = false, features = ["alloc"] } diff --git a/crates/signing/README.md b/crates/signing/README.md @@ -233,6 +233,9 @@ new signer adapter or advanced host composition. `issuance::SigningIntent` binds the canonical 256-bit domain operation ID, command digest, exact authored preimage, role/recipient and captured deadline. +`issuance::ArtifactRole` and `issuance::IntentBinding` reexport the portable +Protocol data definitions; the exact v1 commitment bytes remain unchanged. +Constructing a binding proves no retained claim or dispatch authority. Its generic complete-event limit is 64 KiB, including escaped content, tags, keys and signature. Executor chat/record/rumor limits remain tighter. Values and bindings are neither authenticated command contexts nor durable admission. diff --git a/crates/signing/src/issuance.rs b/crates/signing/src/issuance.rs @@ -25,46 +25,13 @@ pub const SIGNED_EVENT_MAX_BYTES: usize = 65_536; /// Maximum supported authored timestamp in seconds (year 9999). pub const MAX_EVENT_UNIX_SECONDS: u64 = 253_402_300_799; const MAX_OBSERVATION_UNIX_MS: u64 = MAX_EVENT_UNIX_SECONDS * 1000 + 999; -const INTENT_DOMAIN: &[u8] = b"radroots.exact_signing_intent.v1\0"; #[cfg(feature = "chat")] mod dm_relays; #[cfg(feature = "chat")] pub use dm_relays::VerifiedDmRelayAdvertisement; -/// Transport artifact role, separate from a participant's command permission. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[non_exhaustive] -pub enum ArtifactRole { - /// A public authored event, without private-carrier or rumor kinds. - PublicEvent, - /// An encrypted NIP-59 seal (kind 13) for one exact recipient. - BusinessSeal, - /// An outer NIP-59 gift wrap (kind 1059) for one exact recipient. - GiftWrap, -} - -/// Fixed provenance of one captured signing intent. This value grants nothing. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct IntentBinding { - operation_id: OperationId, - command_digest: [u8; 32], - digest: [u8; 32], -} -impl IntentBinding { - /// Returns the full canonical operation identity, never a truncated alias. - pub const fn operation_id(self) -> OperationId { - self.operation_id - } - /// Returns the captured command digest. - pub const fn command_digest(&self) -> &[u8; 32] { - &self.command_digest - } - /// Returns the domain-separated exact intent commitment. - pub const fn digest(&self) -> &[u8; 32] { - &self.digest - } -} +pub use radroots_protocol::intent::{ArtifactRole, IntentBinding}; /// Bounded exact preimage and immutable provenance. It is neither an /// authenticated command context nor evidence of T0/T1 admission. @@ -119,34 +86,21 @@ impl SigningIntent { && recipients.next().is_none() }) } + _ => return Err(ProviderError::UnsupportedVersion), }; if !role_valid { return Err(ProviderError::InvalidInput); } let signed_json_bytes = signed_json_len(&plan)?; - let mut digest = Sha256::new(); - digest.update(INTENT_DOMAIN); - digest.update(operation_id.as_bytes()); - digest.update(command_digest); - digest.update(plan.digest().as_bytes()); - digest.update([match role { - ArtifactRole::PublicEvent => 0, - ArtifactRole::BusinessSeal => 1, - ArtifactRole::GiftWrap => 2, - }]); - match recipient { - Some(peer) => { - digest.update([1]); - digest.update(peer.as_bytes()); - } - None => digest.update([0]), - } - digest.update(call.deadline_unix_ms().get().to_be_bytes()); - let binding = IntentBinding { + let binding = IntentBinding::from_components( operation_id, command_digest, - digest: digest.finalize().into(), - }; + *plan.digest().as_bytes(), + role, + recipient, + call.deadline_unix_ms(), + ) + .map_err(|_| ProviderError::InvalidInput)?; Ok(Self { binding, plan, diff --git a/crates/signing/tests/package_boundary.rs b/crates/signing/tests/package_boundary.rs @@ -24,7 +24,7 @@ fn manifest_has_final_identity_features_and_dependencies() { "radroots_event = { workspace = true, default-features = false }", "radroots_event_codec = { workspace = true, default-features = false }", "radroots_identity = { workspace = true, default-features = false }", - "radroots_protocol = { workspace = true, default-features = false, features = [\"nip01\"] }", + "radroots_protocol = { workspace = true, default-features = false, features = [\"nip01\", \"intent\"] }", ] { assert!( MANIFEST.contains(required), diff --git a/crates/storage/Cargo.toml b/crates/storage/Cargo.toml @@ -35,7 +35,7 @@ name = "radroots_storage" [features] default = ["memory", "serde"] memory = [] -command_journal = ["radroots_protocol/chat"] +command_journal = ["radroots_protocol/chat", "radroots_protocol/intent"] serde = [ "dep:serde", "radroots_domain/serde", diff --git a/crates/storage/README.md b/crates/storage/README.md @@ -288,9 +288,20 @@ WARRANTIES, see LICENSE included in the `radroots_storage` distribution. ## Protected command and signing-plan transactions With `command_journal`, `command::OperationJournal` defines admission/query and -complete immutable signing-plan bind/query transactions. Concrete adapters own +complete immutable signing-plan bind/query, first-claim and obtained-evidence +capture/query transactions. Concrete adapters own current authentication, exact indexed-fact comparisons, fixed first-issue windows and observed commit/rollback completion. `PlanBindingOutcome::Unknown` retains the original workspace, operation and command anchor for reconciliation; a missing observer cannot establish rollback. `BoundSigningPlan` is a structural store report, separate from signature, business installation and delivery. + + +`ClaimAttemptOutcome::Claimed` reports an actual newly committed claim; +`Retained` and `Unknown` never establish permission to invoke again. Structural +constructors do not qualify an adapter's persistence or dispatch behavior. +`SealEvidence::verify` authenticates the bounded original signature bytes and +every expected field; native capture must additionally compare its own retained +claim. Capture borrows the caller's evidence and credential so failure cannot +consume the sole obtained copy. It preserves the first optional observation and +does not apply a new issuance deadline. Queries still require current access. diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs @@ -11,6 +11,12 @@ pub use radroots_protocol::chat::ChatSigningPlan; use radroots_protocol::command::CapturedChatCommand; use radroots_transport::BoxFuture; +mod issuance; +pub use issuance::{ + CapturedSeal, ClaimAttemptOutcome, ClaimAttemptRequest, EvidenceCaptureOutcome, + EvidenceReceipt, SealEvidence, SigningAttempt, +}; + /// Fixed operation-store failures known before a successful admission commit. #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[non_exhaustive] @@ -19,6 +25,8 @@ pub enum OperationError { Workspace(WorkspaceError), /// Captured fields do not match the selected authenticated scope. InvalidCommand, + /// Obtained bytes do not authenticate against the exact retained seal. + InvalidEvidence, /// This concrete authority cannot execute the requested action. Unauthorized, /// Required authenticated thread/order history is unavailable. @@ -40,6 +48,7 @@ impl OperationError { match self { Self::Workspace(e) => e.code(), Self::InvalidCommand => "invalid_command", + Self::InvalidEvidence => "invalid_evidence", Self::Unauthorized => "unauthorized", Self::MissingHistory => "missing_history", Self::UnverifiedApproval => "unverified_approval", @@ -245,6 +254,34 @@ impl fmt::Debug for AdmissionOutcome { /// Typed transaction port, implemented by actual shared storage adapters. /// Applications do not implement a second orchestration or stock engine here. pub trait OperationJournal: WorkspaceStore { + /// Commits a first claim before dispatch. Retained/unknown outcomes never + /// authorize another invocation; the concrete executor owns that decision. + fn claim_attempt( + &self, + request: ClaimAttemptRequest, + proof: AttachmentProof, + ) -> BoxFuture<'_, Result<ClaimAttemptOutcome, OperationError>>; + /// Reads a retained potential invocation under current workspace access. + fn signing_attempt( + &self, + request: ClaimAttemptRequest, + proof: AttachmentProof, + ) -> BoxFuture<'_, Result<Option<SigningAttempt>, OperationError>>; + /// Appends matching authenticated obtained bytes to the actual original + /// claim, without a fresh-issuance deadline or observation clock. Borrowed + /// input remains caller-owned through error, lost wait or unknown completion. + fn capture_evidence<'a>( + &'a self, + input: crate::workspace::AttachmentInput, + proof: &'a AttachmentProof, + evidence: &'a SealEvidence, + ) -> BoxFuture<'a, Result<EvidenceCaptureOutcome, OperationError>>; + /// Reads original exact captured bytes under current workspace access. + fn obtained_evidence( + &self, + request: ClaimAttemptRequest, + proof: AttachmentProof, + ) -> BoxFuture<'_, Result<Option<CapturedSeal>, OperationError>>; /// Atomically retains the complete immutable plan under current access and /// the original first-issue window. No signer invocation happens here. fn bind_signing_intents( diff --git a/crates/storage/src/command/issuance.rs b/crates/storage/src/command/issuance.rs @@ -0,0 +1,457 @@ +//! Exact attempt and independently verified obtained-seal data. Constructors +//! provide no proof that a backend retained a claim or authorized dispatch. +use super::{BoundSigningPlan, CommitAttempt, OperationError}; +use crate::workspace::WorkspaceBinding; +use core::{fmt, num::NonZeroU64}; +use radroots_domain::{ + CommandDigest, EnvelopeEventId, OperationId, PublicKey, SigningAttemptId, TransactionId, + UnixSeconds, WorkspaceId, +}; +use radroots_event::{ + GenericEventDraft, SignedEvent, + wire::{EventWireLimits, Nip01EventWire}, +}; +use radroots_event_codec::{ + authoring::AuthoredEventPlan, + verify::{self, Nip01SignatureVerifier, RawEvent}, +}; +use radroots_protocol::{ + chat::ChatSeal, + intent::{ArtifactRole, IntentBinding}, +}; +use sha2::{Digest, Sha256}; +use zeroize::Zeroizing; + +/// Frozen selectors for claiming one retained recipient intent. No constructor +/// authenticates a principal, approves a route or permits a signer invocation. +pub struct ClaimAttemptRequest { + binding: WorkspaceBinding, + operation_id: OperationId, + command_digest: CommandDigest, + plan_digest: [u8; 32], + recipient: PublicKey, +} +impl ClaimAttemptRequest { + pub const fn new( + binding: WorkspaceBinding, + operation_id: OperationId, + command_digest: CommandDigest, + plan_digest: [u8; 32], + recipient: PublicKey, + ) -> Self { + Self { + binding, + operation_id, + command_digest, + plan_digest, + recipient, + } + } + pub const fn binding(&self) -> &WorkspaceBinding { + &self.binding + } + pub const fn operation_id(&self) -> OperationId { + self.operation_id + } + pub const fn command_digest(&self) -> CommandDigest { + self.command_digest + } + pub const fn plan_digest(&self) -> &[u8; 32] { + &self.plan_digest + } + pub const fn recipient(&self) -> PublicKey { + self.recipient + } + pub fn identity(&self) -> CommitAttempt { + CommitAttempt::new( + self.binding.input().workspace_id(), + self.operation_id, + self.command_digest, + None, + ) + } +} +impl fmt::Debug for ClaimAttemptRequest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ClaimAttemptRequest(<redacted>)") + } +} + +/// Actual store report of an immutable first claim. Construction remains +/// structural. Only an actual newly committed claim may be dispatched once; +/// retrieving this snapshot never proves a previous invocation did not begin. +pub struct SigningAttempt { + bound: BoundSigningPlan, + recipient_index: usize, + attempt_id: SigningAttemptId, + transaction_id: TransactionId, + claimed_at: UnixSeconds, + binding: IntentBinding, + deadline: NonZeroU64, +} +impl SigningAttempt { + pub fn from_committed_store( + bound: BoundSigningPlan, + recipient: PublicKey, + attempt_id: SigningAttemptId, + transaction_id: TransactionId, + claimed_at: UnixSeconds, + ) -> Result<Self, OperationError> { + let window = bound.prepared().issuance_window(); + if claimed_at < bound.bound_at() || claimed_at >= window.first_issue_not_after() { + return Err(OperationError::RecoveryRequired); + } + let recipient_index = bound + .plan() + .seals() + .iter() + .position(|seal| seal.recipient() == recipient) + .ok_or(OperationError::InvalidCommand)?; + let seal = &bound.plan().seals()[recipient_index]; + let deadline = NonZeroU64::new( + window + .first_issue_not_after() + .get() + .checked_mul(1000) + .ok_or(OperationError::RecoveryRequired)?, + ) + .ok_or(OperationError::RecoveryRequired)?; + let fields = seal.fields(); + // Internal reuse of the qualified v1 authored-plan hash. No predecessor + // event model escapes this new API; downward parser retirement remains + // separately governed by the shared target architecture. + let draft = GenericEventDraft::new( + "radroots.message.seal.v1", + fields.kind, + fields.created_at, + Vec::new(), + fields.content, + fields.author.to_hex(), + ) + .map_err(|_| OperationError::InvalidCommand)?; + let plan = + AuthoredEventPlan::from_generic(draft).map_err(|_| OperationError::InvalidCommand)?; + if plan.expected_event_id().as_bytes() != &seal.event_id() { + return Err(OperationError::RecoveryRequired); + } + let binding = IntentBinding::from_components( + seal.operation_id(), + *seal.command_digest().as_bytes(), + *plan.digest().as_bytes(), + ArtifactRole::BusinessSeal, + Some(recipient), + deadline, + ) + .map_err(|_| OperationError::InvalidCommand)?; + Ok(Self { + bound, + recipient_index, + attempt_id, + transaction_id, + claimed_at, + binding, + deadline, + }) + } + /// Transfers the immutable retained plan without creating another claim. + pub fn into_bound_plan(self) -> BoundSigningPlan { + self.bound + } + pub const fn bound_plan(&self) -> &BoundSigningPlan { + &self.bound + } + /// Borrows the exact retained seal. The private index is validated once + /// against the immutable complete plan by the structural constructor. + pub fn seal(&self) -> &ChatSeal { + &self.bound.plan().seals()[self.recipient_index] + } + pub const fn attempt_id(&self) -> SigningAttemptId { + self.attempt_id + } + pub const fn transaction_id(&self) -> TransactionId { + self.transaction_id + } + pub const fn claimed_at(&self) -> UnixSeconds { + self.claimed_at + } + pub const fn binding(&self) -> IntentBinding { + self.binding + } + pub const fn deadline_unix_ms(&self) -> NonZeroU64 { + self.deadline + } + pub fn identity(&self) -> CommitAttempt { + let original = self.bound.prepared().identity(); + CommitAttempt::new( + original.workspace_id(), + original.operation_id(), + original.command_digest(), + Some(self.transaction_id), + ) + } +} +impl fmt::Debug for SigningAttempt { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SigningAttempt(<redacted>)") + } +} + +/// Confirmed new claim, retained potential issuance, or anchored uncertainty. +/// A data variant alone cannot qualify a custom adapter's commit or dispatch. +pub enum ClaimAttemptOutcome { + /// Only this actual newly committed native result permits its owning + /// executor to proceed once after route/provider/current-access checks. + Claimed(SigningAttempt), + /// Never dispatch again merely because this original record was found. + Retained(SigningAttempt), + /// Reconcile the original identity; never infer rollback/nonissuance. + Unknown(CommitAttempt), +} +impl fmt::Debug for ClaimAttemptOutcome { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Claimed(_) => "ClaimAttemptOutcome::Claimed(<redacted>)", + Self::Retained(_) => "ClaimAttemptOutcome::Retained(<redacted>)", + Self::Unknown(_) => "ClaimAttemptOutcome::Unknown(<retained>)", + }) + } +} + +/// Independently authenticated exact obtained bytes, bound to reported claim +/// data but not proof of the backend's actual retained attempt. Native capture +/// must compare its own protected claim and plan before appending this evidence. +pub struct SealEvidence { + workspace_id: WorkspaceId, + operation_id: OperationId, + command_digest: CommandDigest, + plan_digest: [u8; 32], + recipient: PublicKey, + attempt_id: SigningAttemptId, + intent: IntentBinding, + event_id: EnvelopeEventId, + raw: Zeroizing<String>, + digest: [u8; 32], + observed_at: Option<NonZeroU64>, +} +impl SealEvidence { + /// Bounds before copying and verifies ID/signature/every signed field. + /// No clock, grant-expiry or cancellation lookup may discard obtained bytes. + pub fn verify( + attempt: &SigningAttempt, + raw: &str, + observed_at: Option<NonZeroU64>, + ) -> Result<Self, OperationError> { + if raw.len() > 65536 { + return Err(OperationError::InvalidEvidence); + } + let limits = EventWireLimits { + max_raw_json_bytes: 65536, + max_extra_fields: 0, + max_total_extra_json_bytes: 0, + ..EventWireLimits::default() + }; + let wire = Nip01EventWire::parse_json_exact_with_limits(raw, limits) + .map_err(|_| OperationError::InvalidEvidence)?; + let seal = attempt.seal(); + let fields = seal.fields(); + let event_id = EnvelopeEventId::from_bytes(seal.event_id()); + if wire.id != event_id.to_string() + || wire.pubkey != fields.author.to_hex() + || wire.kind != fields.kind + || wire.created_at != fields.created_at + || wire.tags != fields.tags + || wire.content != fields.content + { + return Err(OperationError::InvalidEvidence); + } + let event = SignedEvent::from_wire_verified_id(wire, raw) + .map_err(|_| OperationError::InvalidEvidence)?; + let id = verify::id(RawEvent::new(event.envelope().clone())) + .map_err(|_| OperationError::InvalidEvidence)?; + verify::signature(id, &Nip01SignatureVerifier) + .map_err(|_| OperationError::InvalidEvidence)?; + let original = attempt.bound_plan().prepared().identity(); + Ok(Self { + workspace_id: original.workspace_id(), + operation_id: original.operation_id(), + command_digest: original.command_digest(), + plan_digest: *attempt.bound_plan().plan().digest(), + recipient: seal.recipient(), + attempt_id: attempt.attempt_id(), + intent: attempt.binding(), + event_id, + raw: Zeroizing::new(String::from(raw)), + digest: Sha256::digest(raw.as_bytes()).into(), + observed_at: observed_at.filter(|time| time.get() <= 253_402_300_799_999), + }) + } + /// Explicitly copies a bounded already-verified value for the store owner; + /// the caller keeps its sole original through actual durable completion. + pub fn retained_copy(&self) -> Self { + Self { + workspace_id: self.workspace_id, + operation_id: self.operation_id, + command_digest: self.command_digest, + plan_digest: self.plan_digest, + recipient: self.recipient, + attempt_id: self.attempt_id, + intent: self.intent, + event_id: self.event_id, + raw: Zeroizing::new(self.raw.to_string()), + digest: self.digest, + observed_at: self.observed_at, + } + } + pub fn matches_attempt(&self, attempt: &SigningAttempt) -> bool { + self.workspace_id == attempt.bound_plan().prepared().identity().workspace_id() + && self.attempt_id == attempt.attempt_id() + && self.intent == attempt.binding() + && self.operation_id == attempt.bound_plan().prepared().identity().operation_id() + && self.command_digest == attempt.bound_plan().prepared().identity().command_digest() + && &self.plan_digest == attempt.bound_plan().plan().digest() + && self.recipient == attempt.seal().recipient() + && self.event_id.as_bytes() == &attempt.seal().event_id() + } + pub const fn workspace_id(&self) -> WorkspaceId { + self.workspace_id + } + pub const fn operation_id(&self) -> OperationId { + self.operation_id + } + pub const fn command_digest(&self) -> CommandDigest { + self.command_digest + } + pub const fn plan_digest(&self) -> &[u8; 32] { + &self.plan_digest + } + pub const fn recipient(&self) -> PublicKey { + self.recipient + } + pub const fn attempt_id(&self) -> SigningAttemptId { + self.attempt_id + } + pub const fn intent(&self) -> IntentBinding { + self.intent + } + pub const fn event_id(&self) -> EnvelopeEventId { + self.event_id + } + pub fn raw_json(&self) -> &str { + &self.raw + } + pub const fn digest(&self) -> &[u8; 32] { + &self.digest + } + pub const fn observed_at_unix_ms(&self) -> Option<NonZeroU64> { + self.observed_at + } +} +impl fmt::Debug for SealEvidence { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SealEvidence(<redacted>)") + } +} + +/// Fixed reference to exact retained obtained bytes. Data construction alone +/// supplies no proof of capture, business installation or delivery. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct EvidenceReceipt { + workspace_id: WorkspaceId, + operation_id: OperationId, + command_digest: CommandDigest, + attempt_id: SigningAttemptId, + recipient: PublicKey, + event_id: EnvelopeEventId, + digest: [u8; 32], + transaction_id: TransactionId, + observed_at: Option<NonZeroU64>, +} +impl EvidenceReceipt { + pub const fn from_committed_store( + evidence: &SealEvidence, + transaction_id: TransactionId, + ) -> Self { + Self { + workspace_id: evidence.workspace_id, + operation_id: evidence.operation_id, + command_digest: evidence.command_digest, + attempt_id: evidence.attempt_id, + recipient: evidence.recipient, + event_id: evidence.event_id, + digest: evidence.digest, + transaction_id, + observed_at: evidence.observed_at, + } + } + pub const fn workspace_id(&self) -> WorkspaceId { + self.workspace_id + } + pub const fn operation_id(&self) -> OperationId { + self.operation_id + } + pub const fn command_digest(&self) -> CommandDigest { + self.command_digest + } + pub const fn attempt_id(&self) -> SigningAttemptId { + self.attempt_id + } + pub const fn recipient(&self) -> PublicKey { + self.recipient + } + pub const fn event_id(&self) -> EnvelopeEventId { + self.event_id + } + pub const fn digest(&self) -> &[u8; 32] { + &self.digest + } + pub const fn transaction_id(&self) -> TransactionId { + self.transaction_id + } + pub const fn observed_at_unix_ms(&self) -> Option<NonZeroU64> { + self.observed_at + } +} +/// Actual capture completion, separate from installing or sending a record. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum EvidenceCaptureOutcome { + Committed(EvidenceReceipt), + Unknown(CommitAttempt), +} +/// An original protected obtained record read under current workspace access. +/// Advanced adapter construction remains a structural report, not qualification. +pub struct CapturedSeal { + attempt: SigningAttempt, + evidence: SealEvidence, + receipt: EvidenceReceipt, +} +impl CapturedSeal { + pub fn from_committed_store( + attempt: SigningAttempt, + evidence: SealEvidence, + transaction_id: TransactionId, + ) -> Result<Self, OperationError> { + if !evidence.matches_attempt(&attempt) { + return Err(OperationError::RecoveryRequired); + } + let receipt = EvidenceReceipt::from_committed_store(&evidence, transaction_id); + Ok(Self { + attempt, + evidence, + receipt, + }) + } + pub const fn attempt(&self) -> &SigningAttempt { + &self.attempt + } + pub const fn evidence(&self) -> &SealEvidence { + &self.evidence + } + pub const fn receipt(&self) -> EvidenceReceipt { + self.receipt + } +} +impl fmt::Debug for CapturedSeal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CapturedSeal(<redacted>)") + } +} diff --git a/crates/storage/tests/package_boundary.rs b/crates/storage/tests/package_boundary.rs @@ -92,12 +92,17 @@ fn root_exports_are_exact_and_implementation_types_do_not_leak() { let source_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src"); let mut source = String::new(); - for entry in fs::read_dir(source_root).expect("source directory") { - let path = entry.expect("source entry").path(); - if path.extension().and_then(|value| value.to_str()) == Some("rs") { - source.push_str(&fs::read_to_string(path).expect("source file")); + fn collect(source_root: &std::path::Path, source: &mut String) { + for entry in fs::read_dir(source_root).expect("source directory") { + let path = entry.expect("source entry").path(); + if path.is_dir() { + collect(&path, source); + } else if path.extension().and_then(|value| value.to_str()) == Some("rs") { + source.push_str(&fs::read_to_string(path).expect("source file")); + } } } + collect(&source_root, &mut source); for forbidden in [ "sqlx::", "rusqlite::", diff --git a/crates/storage_sqlite/Cargo.toml b/crates/storage_sqlite/Cargo.toml @@ -60,6 +60,8 @@ zeroize = { workspace = true, features = ["alloc"] } sqlx = { workspace = true, features = ["runtime-tokio", "sqlite-bundled"] } [dev-dependencies] +radroots_signing = { workspace = true, features = ["chat"] } +radroots_nostr = { workspace = true, default-features = false, features = ["signing", "nip17"] } radroots_protocol = { workspace = true, default-features = false, features = ["chat"] } nostr = { workspace = true, default-features = false, features = ["std", "nip44"] } futures = { workspace = true } diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md @@ -214,7 +214,7 @@ under `BEGIN IMMEDIATE`, with provider work outside that transaction. A fixed first-issue window never restarts on replay. Already-bound bytes remain queryable and replayable after expiry under current access; this grants no new issuance. -The current workspace schema is version 4. Older namespaces are preserved and +The current workspace schema is version 5. Older namespaces are preserved and refused for explicit cutover, without an automatic state rewrite. Complete plans use a protected manifest and at most twenty-four 16 KiB protected data parts, with context binding the full workspace/operation/plan identity and part index. @@ -222,3 +222,17 @@ Existing secret-material/envelope bounds remain intact. Queued and in-flight request reservations share a 4 MiB byte cap alongside the 32-slot queue limit. Known rollback, confirmed commit and unknown completion remain distinct. This component performs no signer dispatch, business installation or delivery. + + +Native first claims retain a full-width attempt identity and exact command, +plan, recipient, intent, original deadline and transaction bindings before any +signer invocation. A retained claim reports potential issuance and cannot permit +another invocation. Signing remains outside this storage owner. + +Obtained seal capture independently verifies the signature and every signed +field against the actual protected claim. Its original scoped credential may +append already obtained matching bytes after revocation or expiry without an +observation clock; this grants no new issuance or read rights. The first raw +representation and optional observation are immutable. Borrowed capture input +keeps the caller's original through error or unknown completion. Evidence uses +a protected manifest and at most four 16 KiB data parts, bounded before reads. diff --git a/crates/storage_sqlite/src/workspace/admission.rs b/crates/storage_sqlite/src/workspace/admission.rs @@ -19,7 +19,7 @@ pub(super) struct Journal<'a> { pub uncertain: &'a mut bool, } impl Journal<'_> { - async fn access( + pub(super) async fn access( &mut self, binding: &WorkspaceBinding, proof: &AttachmentProof, @@ -403,7 +403,7 @@ impl Journal<'_> { } } -fn same_binding( +pub(super) fn same_binding( captured: &WorkspaceBinding, current: &WorkspaceBinding, ) -> Result<(), OperationError> { @@ -422,7 +422,7 @@ fn same_binding( clippy::too_many_arguments, reason = "Private transaction recheck borrows only the existing owner inputs" )] -async fn recheck( +pub(super) async fn recheck( transaction: &mut Transaction<'_, Sqlite>, namespace: &Namespace, selected: &AttachmentInput, diff --git a/crates/storage_sqlite/src/workspace/attempt.rs b/crates/storage_sqlite/src/workspace/attempt.rs @@ -0,0 +1,194 @@ +//! Immutable backend-owned first-claim records; no signer is invoked here. +use super::{ + AttachmentInput, + crypto::{IssuancePayload, IssuanceScope, WorkspaceCrypto}, +}; +use radroots_domain::{ + CommandDigest, EnvelopeEventId, GrantId, OperationId, PublicKey, SigningAttemptId, + TransactionId, UnixSeconds, WorkspaceId, +}; +use radroots_storage::command::{BoundSigningPlan, OperationError, SigningAttempt}; +use serde::{Deserialize, Serialize}; +use sqlx::{Row, SqliteConnection}; +use zeroize::Zeroizing; + +pub(super) const TABLE: &str = "CREATE TABLE signing_attempts (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, recipient BLOB NOT NULL CHECK(length(recipient)=32), attempt_id BLOB NOT NULL CHECK(length(attempt_id)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), plan_digest BLOB NOT NULL CHECK(length(plan_digest)=32), intent_digest BLOB NOT NULL CHECK(length(intent_digest)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id,recipient), FOREIGN KEY(workspace,operation_id) REFERENCES signing_plans(workspace,operation_id)) STRICT, WITHOUT ROWID"; +pub(super) const ID_INDEX: &str = + "CREATE UNIQUE INDEX signing_attempt_identity ON signing_attempts(workspace,attempt_id)"; +pub(super) const TX_INDEX: &str = "CREATE UNIQUE INDEX signing_attempt_transaction_identity ON signing_attempts(workspace,transaction_id)"; + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Encoded { + version: u8, + workspace: WorkspaceId, + operation_id: OperationId, + command_digest: CommandDigest, + plan_digest: [u8; 32], + recipient: PublicKey, + attempt_id: SigningAttemptId, + transaction_id: TransactionId, + claimed_at: UnixSeconds, + intent_digest: [u8; 32], + deadline_unix_ms: u64, + preparation_transaction: TransactionId, + plan_transaction: TransactionId, + grant_id: GrantId, + expected_event: EnvelopeEventId, +} +impl Encoded { + fn new(attempt: &SigningAttempt) -> Self { + let plan = attempt.bound_plan(); + let prepared = plan.prepared(); + let identity = prepared.identity(); + Self { + version: 1, + workspace: identity.workspace_id(), + operation_id: identity.operation_id(), + command_digest: identity.command_digest(), + plan_digest: *plan.plan().digest(), + recipient: attempt.seal().recipient(), + attempt_id: attempt.attempt_id(), + transaction_id: attempt.transaction_id(), + claimed_at: attempt.claimed_at(), + intent_digest: *attempt.binding().digest(), + deadline_unix_ms: attempt.deadline_unix_ms().get(), + preparation_transaction: prepared.transaction_id(), + plan_transaction: plan.transaction_id(), + grant_id: prepared.request().binding().input().grant_id(), + expected_event: EnvelopeEventId::from_bytes(attempt.seal().event_id()), + } + } +} +pub(super) fn scope(attempt: &SigningAttempt) -> IssuanceScope { + let identity = attempt.bound_plan().prepared().identity(); + IssuanceScope { + workspace: identity.workspace_id(), + operation: identity.operation_id(), + plan_digest: *attempt.bound_plan().plan().digest(), + attempt: attempt.attempt_id(), + recipient: attempt.seal().recipient(), + } +} +pub(super) async fn protect( + attempt: &SigningAttempt, + crypto: &WorkspaceCrypto, +) -> Result<Vec<u8>, OperationError> { + let bytes = Zeroizing::new( + serde_json::to_vec(&Encoded::new(attempt)).map_err(|_| OperationError::InvalidCommand)?, + ); + Ok(crypto + .seal_issuance(scope(attempt), IssuancePayload::Attempt, 0, &bytes) + .await?) +} +/// Returns the complete original plan on absence as well as a verified retained +/// claim on presence. Providers run before the caller's write transaction. +pub(super) async fn read( + connection: &mut SqliteConnection, + selected: &AttachmentInput, + bound: BoundSigningPlan, + recipient: PublicKey, + crypto: &WorkspaceCrypto, +) -> Result< + ( + BoundSigningPlan, + Option<(SigningAttemptId, TransactionId, UnixSeconds, Vec<u8>)>, + ), + OperationError, +> { + let original = bound.prepared().identity(); + let row=sqlx::query("SELECT CASE WHEN length(attempt_id)=32 THEN attempt_id END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,CASE WHEN length(plan_digest)=32 THEN plan_digest END,CASE WHEN length(intent_digest)=32 THEN intent_digest END,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM signing_attempts WHERE workspace=? AND operation_id=? AND recipient=?") + .bind(selected.workspace_id().as_bytes().as_slice()).bind(original.operation_id().as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let Some(row) = row else { + return Ok((bound, None)); + }; + let bytes = |index| { + row.try_get::<Option<Vec<u8>>, _>(index) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired) + }; + let id = SigningAttemptId::from_bytes( + bytes(0)? + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ); + let transaction = TransactionId::from_bytes( + bytes(1)? + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ); + let plan_digest = bytes(2)?; + let intent_digest = bytes(3)?; + let protected = bytes(4)?; + if plan_digest.as_slice() != bound.plan().digest() { + return Err(OperationError::RecoveryRequired); + } + let issuance_scope = IssuanceScope { + workspace: selected.workspace_id(), + operation: original.operation_id(), + plan_digest: *bound.plan().digest(), + attempt: id, + recipient, + }; + let plaintext = crypto + .open_issuance(issuance_scope, IssuancePayload::Attempt, 0, &protected) + .await?; + let encoded: Encoded = plaintext + .expose_secret(|bytes| serde_json::from_slice(bytes)) + .map_err(|_| OperationError::RecoveryRequired)?; + if encoded.version != 1 + || encoded.workspace != selected.workspace_id() + || encoded.operation_id != original.operation_id() + || encoded.command_digest != original.command_digest() + || &encoded.plan_digest != bound.plan().digest() + || encoded.recipient != recipient + || encoded.attempt_id != id + || encoded.transaction_id != transaction + || encoded.preparation_transaction != bound.prepared().transaction_id() + || encoded.plan_transaction != bound.transaction_id() + || encoded.grant_id != bound.prepared().request().binding().input().grant_id() + { + return Err(OperationError::RecoveryRequired); + } + let attempt = SigningAttempt::from_committed_store( + bound, + recipient, + id, + transaction, + encoded.claimed_at, + )?; + if encoded.intent_digest != *attempt.binding().digest() + || intent_digest.as_slice() != attempt.binding().digest() + || encoded.deadline_unix_ms != attempt.deadline_unix_ms().get() + || encoded.expected_event.as_bytes() != &attempt.seal().event_id() + { + return Err(OperationError::RecoveryRequired); + } + Ok(( + attempt.into_bound_plan(), + Some((id, transaction, encoded.claimed_at, protected)), + )) +} +pub(super) async fn insert( + connection: &mut SqliteConnection, + attempt: &SigningAttempt, + protected: &[u8], +) -> Result<(), OperationError> { + let identity = attempt.bound_plan().prepared().identity(); + sqlx::query("INSERT INTO signing_attempts(workspace,operation_id,recipient,attempt_id,transaction_id,plan_digest,intent_digest,protected) VALUES(?,?,?,?,?,?,?,?)") + .bind(identity.workspace_id().as_bytes().as_slice()).bind(identity.operation_id().as_bytes().as_slice()).bind(attempt.seal().recipient().as_bytes().as_slice()).bind(attempt.attempt_id().as_bytes().as_slice()).bind(attempt.transaction_id().as_bytes().as_slice()).bind(attempt.bound_plan().plan().digest().as_slice()).bind(attempt.binding().digest().as_slice()).bind(protected).execute(connection).await.map_err(|_|OperationError::StorageFailure)?; + Ok(()) +} +pub(super) async fn unchanged( + connection: &mut SqliteConnection, + attempt: &SigningAttempt, + protected: &[u8], +) -> Result<(), OperationError> { + let identity = attempt.bound_plan().prepared().identity(); + let count:i64=sqlx::query_scalar("SELECT count(*) FROM signing_attempts WHERE workspace=? AND operation_id=? AND recipient=? AND attempt_id=? AND transaction_id=? AND plan_digest=? AND intent_digest=? AND protected=?") + .bind(identity.workspace_id().as_bytes().as_slice()).bind(identity.operation_id().as_bytes().as_slice()).bind(attempt.seal().recipient().as_bytes().as_slice()).bind(attempt.attempt_id().as_bytes().as_slice()).bind(attempt.transaction_id().as_bytes().as_slice()).bind(attempt.bound_plan().plan().digest().as_slice()).bind(attempt.binding().digest().as_slice()).bind(protected).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if count != 1 { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -12,6 +12,20 @@ use std::{fmt, sync::Arc}; pub(super) const PRIVATE_PAYLOAD_MAX_BYTES: usize = 16 * 1024; pub(super) const PROTECTED_MAX_BYTES: usize = ENVELOPE_MAX_BYTES; +#[derive(Clone, Copy)] +pub(super) struct IssuanceScope { + pub workspace: WorkspaceId, + pub operation: OperationId, + pub plan_digest: [u8; 32], + pub attempt: radroots_domain::SigningAttemptId, + pub recipient: radroots_domain::PublicKey, +} +#[derive(Clone, Copy)] +pub(super) enum IssuancePayload { + Attempt, + Evidence, +} + /// Explicit host-owned encryption material. This is a data-encryption key, /// independent of the participant signer and the scoped bearer credential. /// The host chooses its qualified provider and access policy; no fallback or @@ -94,6 +108,34 @@ impl WorkspaceCrypto { ) .await } + pub(super) async fn seal_issuance( + &self, + scope: IssuanceScope, + payload: IssuancePayload, + part: u8, + plaintext: &[u8], + ) -> Result<Vec<u8>, WorkspaceError> { + self.seal_bound( + issuance_context(scope, payload, part)?, + PRIVATE_PAYLOAD_MAX_BYTES, + plaintext, + ) + .await + } + pub(super) async fn open_issuance( + &self, + scope: IssuanceScope, + payload: IssuancePayload, + part: u8, + protected: &[u8], + ) -> Result<SecretMaterial, WorkspaceError> { + self.open_bound( + issuance_context(scope, payload, part)?, + PRIVATE_PAYLOAD_MAX_BYTES, + protected, + ) + .await + } async fn seal_bound( &self, context: EnvelopeContext, @@ -245,3 +287,38 @@ fn plan_context( .map_err(|_| WorkspaceError::InvalidInput)?, )) } + +fn issuance_context( + scope: IssuanceScope, + payload: IssuancePayload, + part: u8, +) -> Result<EnvelopeContext, WorkspaceError> { + use sha2::{Digest, Sha256}; + let (tag, purpose, schema) = match payload { + IssuancePayload::Attempt => ( + 0u8, + "radroots.workspace.signing_attempt", + "radroots.workspace.signing_attempt.v1", + ), + IssuancePayload::Evidence => ( + 1u8, + "radroots.workspace.seal_evidence", + "radroots.workspace.seal_evidence.v1", + ), + }; + let mut hash = Sha256::new(); + hash.update(b"radroots.workspace.issuance.context.v1\0"); + hash.update([tag, part]); + hash.update(scope.workspace.as_bytes()); + hash.update(scope.operation.as_bytes()); + hash.update(scope.plan_digest); + hash.update(scope.attempt.as_bytes()); + hash.update(scope.recipient.as_bytes()); + let subject = radroots_domain::CommandDigest::from_bytes(hash.finalize().into()); + Ok(EnvelopeContext::new( + EnvelopePurpose::parse(purpose).map_err(|_| WorkspaceError::InvalidInput)?, + EnvelopeSubject::parse("workspace_issuance", subject.to_string()) + .map_err(|_| WorkspaceError::InvalidInput)?, + PayloadSchemaId::parse(schema).map_err(|_| WorkspaceError::InvalidInput)?, + )) +} diff --git a/crates/storage_sqlite/src/workspace/evidence.rs b/crates/storage_sqlite/src/workspace/evidence.rs @@ -0,0 +1,278 @@ +//! Append-only protected obtained bytes and exact original observation data. +use super::{ + attempt, + crypto::{IssuancePayload, PRIVATE_PAYLOAD_MAX_BYTES, WorkspaceCrypto}, +}; +use core::num::NonZeroU64; +use radroots_domain::{ + CommandDigest, EnvelopeEventId, OperationId, PublicKey, SigningAttemptId, TransactionId, + WorkspaceId, +}; +use radroots_storage::command::{EvidenceReceipt, OperationError, SealEvidence, SigningAttempt}; +use serde::{Deserialize, Serialize}; +use sqlx::{Row, SqliteConnection}; +use zeroize::Zeroizing; + +pub(super) const TABLE: &str = "CREATE TABLE seal_evidence (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, recipient BLOB NOT NULL, attempt_id BLOB NOT NULL CHECK(length(attempt_id)=32), event_id BLOB NOT NULL CHECK(length(event_id)=32), evidence_digest BLOB NOT NULL CHECK(length(evidence_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), part_count INTEGER NOT NULL CHECK(part_count BETWEEN 1 AND 4), byte_count INTEGER NOT NULL CHECK(byte_count BETWEEN 1 AND 65536), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id,recipient), FOREIGN KEY(workspace,operation_id,recipient) REFERENCES signing_attempts(workspace,operation_id,recipient)) STRICT, WITHOUT ROWID"; +pub(super) const PARTS: &str = "CREATE TABLE seal_evidence_parts (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, recipient BLOB NOT NULL, part INTEGER NOT NULL CHECK(part BETWEEN 1 AND 4), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id,recipient,part), FOREIGN KEY(workspace,operation_id,recipient) REFERENCES seal_evidence(workspace,operation_id,recipient)) STRICT, WITHOUT ROWID"; +pub(super) const TX_INDEX: &str = "CREATE UNIQUE INDEX seal_evidence_transaction_identity ON seal_evidence(workspace,transaction_id)"; +const MAX_PROTECTED_TOTAL: usize = 1024 * 1024; +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Manifest { + version: u8, + workspace: WorkspaceId, + operation_id: OperationId, + command_digest: CommandDigest, + plan_digest: [u8; 32], + recipient: PublicKey, + attempt_id: SigningAttemptId, + claim_transaction: TransactionId, + intent_digest: [u8; 32], + event_id: EnvelopeEventId, + evidence_digest: [u8; 32], + transaction_id: TransactionId, + observed_at: Option<u64>, + byte_count: usize, + part_count: usize, +} +pub(super) struct ProtectedEvidence { + pub manifest: Vec<u8>, + pub parts: Vec<Vec<u8>>, + pub receipt: EvidenceReceipt, + pub bytes: usize, +} +pub(super) async fn protect( + attempt: &SigningAttempt, + evidence: &SealEvidence, + transaction: TransactionId, + crypto: &WorkspaceCrypto, +) -> Result<ProtectedEvidence, OperationError> { + if !evidence.matches_attempt(attempt) { + return Err(OperationError::InvalidEvidence); + } + let bytes = evidence.raw_json().as_bytes(); + let chunks = bytes.chunks(PRIVATE_PAYLOAD_MAX_BYTES); + let receipt = EvidenceReceipt::from_committed_store(evidence, transaction); + let manifest = Manifest { + version: 1, + workspace: evidence.workspace_id(), + operation_id: evidence.operation_id(), + command_digest: evidence.command_digest(), + plan_digest: *evidence.plan_digest(), + recipient: evidence.recipient(), + attempt_id: evidence.attempt_id(), + claim_transaction: attempt.transaction_id(), + intent_digest: *evidence.intent().digest(), + event_id: evidence.event_id(), + evidence_digest: *evidence.digest(), + transaction_id: transaction, + observed_at: evidence.observed_at_unix_ms().map(NonZeroU64::get), + byte_count: bytes.len(), + part_count: chunks.len(), + }; + let plaintext = + Zeroizing::new(serde_json::to_vec(&manifest).map_err(|_| OperationError::InvalidEvidence)?); + let scope = attempt::scope(attempt); + let manifest = crypto + .seal_issuance(scope, IssuancePayload::Evidence, 0, &plaintext) + .await?; + let mut total = manifest.len(); + let mut parts = Vec::new(); + for (index, chunk) in chunks.enumerate() { + let part = crypto + .seal_issuance(scope, IssuancePayload::Evidence, (index + 1) as u8, chunk) + .await?; + total = total + .checked_add(part.len()) + .filter(|size| *size <= MAX_PROTECTED_TOTAL) + .ok_or(OperationError::InvalidEvidence)?; + parts.push(part); + } + Ok(ProtectedEvidence { + manifest, + parts, + receipt, + bytes: bytes.len(), + }) +} +pub(super) async fn read( + connection: &mut SqliteConnection, + attempt: &SigningAttempt, + crypto: &WorkspaceCrypto, +) -> Result<Option<(SealEvidence, ProtectedEvidence)>, OperationError> { + let scope = attempt::scope(attempt); + let row=sqlx::query("SELECT CASE WHEN length(attempt_id)=32 THEN attempt_id END,CASE WHEN length(event_id)=32 THEN event_id END,CASE WHEN length(evidence_digest)=32 THEN evidence_digest END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,part_count,byte_count,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM seal_evidence WHERE workspace=? AND operation_id=? AND recipient=?") + .bind(scope.workspace.as_bytes().as_slice()).bind(scope.operation.as_bytes().as_slice()).bind(scope.recipient.as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let Some(row) = row else { + return Ok(None); + }; + let value = |index| { + row.try_get::<Option<Vec<u8>>, _>(index) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired) + }; + let attempt_id = value(0)?; + let event_id = value(1)?; + let digest = value(2)?; + let transaction = value(3)?; + let manifest = value(6)?; + let count: i64 = row + .try_get(4) + .map_err(|_| OperationError::RecoveryRequired)?; + let bytes: i64 = row + .try_get(5) + .map_err(|_| OperationError::RecoveryRequired)?; + if !(1..=4).contains(&count) + || !(1..=65536).contains(&bytes) + || (bytes as usize).div_ceil(PRIVATE_PAYLOAD_MAX_BYTES) != count as usize + { + return Err(OperationError::RecoveryRequired); + } + let transaction = TransactionId::from_bytes( + transaction + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ); + let plaintext = crypto + .open_issuance(scope, IssuancePayload::Evidence, 0, &manifest) + .await?; + let decoded: Manifest = plaintext + .expose_secret(|value| serde_json::from_slice(value)) + .map_err(|_| OperationError::RecoveryRequired)?; + if decoded.version != 1 + || decoded.workspace != scope.workspace + || decoded.operation_id != scope.operation + || decoded.command_digest != attempt.bound_plan().prepared().identity().command_digest() + || decoded.plan_digest != scope.plan_digest + || decoded.recipient != scope.recipient + || decoded.attempt_id != scope.attempt + || decoded.claim_transaction != attempt.transaction_id() + || decoded.intent_digest != *attempt.binding().digest() + || decoded.event_id.as_bytes() != &attempt.seal().event_id() + || decoded.event_id.as_bytes().as_slice() != event_id + || decoded.attempt_id.as_bytes().as_slice() != attempt_id + || decoded.evidence_digest.as_slice() != digest + || decoded.transaction_id != transaction + || decoded.part_count != count as usize + || decoded.byte_count != bytes as usize + { + return Err(OperationError::RecoveryRequired); + } + let observed = match decoded.observed_at { + None => None, + Some(value) => Some( + NonZeroU64::new(value) + .filter(|time| time.get() <= 253_402_300_799_999) + .ok_or(OperationError::RecoveryRequired)?, + ), + }; + let (parts,total):(i64,i64)=sqlx::query_as("SELECT count(*),coalesce(sum(length(protected)),0) FROM seal_evidence_parts WHERE workspace=? AND operation_id=? AND recipient=?") + .bind(scope.workspace.as_bytes().as_slice()).bind(scope.operation.as_bytes().as_slice()).bind(scope.recipient.as_bytes().as_slice()).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if parts != count || total <= 0 || total > (MAX_PROTECTED_TOTAL - manifest.len()) as i64 { + return Err(OperationError::RecoveryRequired); + } + let rows=sqlx::query("SELECT part,CASE WHEN length(protected)>0 AND length(protected)<=262144 AND (SELECT coalesce(sum(length(p.protected)),0) FROM seal_evidence_parts p WHERE p.workspace=seal_evidence_parts.workspace AND p.operation_id=seal_evidence_parts.operation_id AND p.recipient=seal_evidence_parts.recipient)<=1048576 THEN protected END FROM seal_evidence_parts WHERE workspace=? AND operation_id=? AND recipient=? ORDER BY part LIMIT 5") + .bind(scope.workspace.as_bytes().as_slice()).bind(scope.operation.as_bytes().as_slice()).bind(scope.recipient.as_bytes().as_slice()).fetch_all(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if rows.len() != count as usize { + return Err(OperationError::RecoveryRequired); + } + let mut raw = Zeroizing::new(Vec::with_capacity(bytes as usize)); + let mut protected_parts = Vec::new(); + for (index, row) in rows.iter().enumerate() { + let number: i64 = row + .try_get(0) + .map_err(|_| OperationError::RecoveryRequired)?; + if number != (index + 1) as i64 { + return Err(OperationError::RecoveryRequired); + } + let protected: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(1) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + let part = crypto + .open_issuance(scope, IssuancePayload::Evidence, number as u8, &protected) + .await?; + let length = if index + 1 == rows.len() { + bytes as usize - index * PRIVATE_PAYLOAD_MAX_BYTES + } else { + PRIVATE_PAYLOAD_MAX_BYTES + }; + part.expose_secret(|value| { + if value.len() != length { + return Err(OperationError::RecoveryRequired); + } + raw.extend_from_slice(value); + Ok(()) + })?; + protected_parts.push(protected); + } + let text = core::str::from_utf8(&raw).map_err(|_| OperationError::RecoveryRequired)?; + let evidence = SealEvidence::verify(attempt, text, observed) + .map_err(|_| OperationError::RecoveryRequired)?; + if evidence.digest() != &decoded.evidence_digest { + return Err(OperationError::RecoveryRequired); + } + let receipt = EvidenceReceipt::from_committed_store(&evidence, transaction); + Ok(Some(( + evidence, + ProtectedEvidence { + manifest, + parts: protected_parts, + receipt, + bytes: bytes as usize, + }, + ))) +} +pub(super) async fn insert( + connection: &mut SqliteConnection, + value: &ProtectedEvidence, +) -> Result<(), OperationError> { + let receipt = value.receipt; + sqlx::query("INSERT INTO seal_evidence(workspace,operation_id,recipient,attempt_id,event_id,evidence_digest,transaction_id,part_count,byte_count,protected) VALUES(?,?,?,?,?,?,?,?,?,?)") + .bind(receipt.workspace_id().as_bytes().as_slice()).bind(receipt.operation_id().as_bytes().as_slice()).bind(receipt.recipient().as_bytes().as_slice()).bind(receipt.attempt_id().as_bytes().as_slice()).bind(receipt.event_id().as_bytes().as_slice()).bind(receipt.digest().as_slice()).bind(receipt.transaction_id().as_bytes().as_slice()).bind(value.parts.len() as i64).bind(value.bytes as i64).bind(&value.manifest).execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; + for (index, part) in value.parts.iter().enumerate() { + sqlx::query("INSERT INTO seal_evidence_parts(workspace,operation_id,recipient,part,protected) VALUES(?,?,?,?,?)") + .bind(receipt.workspace_id().as_bytes().as_slice()).bind(receipt.operation_id().as_bytes().as_slice()).bind(receipt.recipient().as_bytes().as_slice()).bind((index+1) as i64).bind(part).execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; + } + Ok(()) +} +pub(super) async fn unchanged( + connection: &mut SqliteConnection, + attempt: &SigningAttempt, + value: Option<&ProtectedEvidence>, +) -> Result<(), OperationError> { + let scope = attempt::scope(attempt); + let count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM seal_evidence WHERE workspace=? AND operation_id=? AND recipient=?", + ) + .bind(scope.workspace.as_bytes().as_slice()) + .bind(scope.operation.as_bytes().as_slice()) + .bind(scope.recipient.as_bytes().as_slice()) + .fetch_one(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + let parts:i64=sqlx::query_scalar("SELECT count(*) FROM seal_evidence_parts WHERE workspace=? AND operation_id=? AND recipient=?") + .bind(scope.workspace.as_bytes().as_slice()).bind(scope.operation.as_bytes().as_slice()).bind(scope.recipient.as_bytes().as_slice()).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let Some(value) = value else { + return if count == 0 && parts == 0 { + Ok(()) + } else { + Err(OperationError::RecoveryRequired) + }; + }; + let receipt = value.receipt; + let matched:i64=sqlx::query_scalar("SELECT count(*) FROM seal_evidence WHERE workspace=? AND operation_id=? AND recipient=? AND attempt_id=? AND event_id=? AND evidence_digest=? AND transaction_id=? AND part_count=? AND byte_count=? AND protected=?") + .bind(scope.workspace.as_bytes().as_slice()).bind(scope.operation.as_bytes().as_slice()).bind(scope.recipient.as_bytes().as_slice()).bind(receipt.attempt_id().as_bytes().as_slice()).bind(receipt.event_id().as_bytes().as_slice()).bind(receipt.digest().as_slice()).bind(receipt.transaction_id().as_bytes().as_slice()).bind(value.parts.len() as i64).bind(value.bytes as i64).bind(&value.manifest).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if count != 1 || matched != 1 || parts != value.parts.len() as i64 { + return Err(OperationError::RecoveryRequired); + } + for (index, part) in value.parts.iter().enumerate() { + let matched:i64=sqlx::query_scalar("SELECT count(*) FROM seal_evidence_parts WHERE workspace=? AND operation_id=? AND recipient=? AND part=? AND protected=?") + .bind(scope.workspace.as_bytes().as_slice()).bind(scope.operation.as_bytes().as_slice()).bind(scope.recipient.as_bytes().as_slice()).bind((index+1) as i64).bind(part).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if matched != 1 { + return Err(OperationError::RecoveryRequired); + } + } + Ok(()) +} diff --git a/crates/storage_sqlite/src/workspace/issuance.rs b/crates/storage_sqlite/src/workspace/issuance.rs @@ -0,0 +1,557 @@ +//! First-claim and append-only obtained-evidence turns on the existing owner. +//! This layer never invokes a signer or network capability. +use super::{ + AttachmentInput, AttachmentProof, WorkspaceError, + admission::{Journal, recheck, same_binding}, + attempt, evidence, operation, plan, + record::GrantRecord, + worker, +}; +use radroots_domain::{CommandDigest, OperationId, PublicKey, SigningAttemptId, TransactionId}; +use radroots_storage::command::{ + BoundSigningPlan, CapturedSeal, ClaimAttemptOutcome, ClaimAttemptRequest, CommitAttempt, + EvidenceCaptureOutcome, OperationError, SealEvidence, SigningAttempt, +}; +use sqlx::{Connection, SqliteConnection}; + +struct Loaded { + bound: BoundSigningPlan, + operation: Vec<u8>, + plan: plan::ProtectedPlan, +} +impl Journal<'_> { + async fn load_issuance_plan( + &mut self, + operation_id: OperationId, + digest: CommandDigest, + ) -> Result<Option<Loaded>, OperationError> { + let Some((prepared, operation)) = + operation::read(self.connection, self.selected, operation_id, self.crypto).await? + else { + return Ok(None); + }; + if prepared.request().command().context().actor().participant() + != self.selected.participant() + { + return Err(OperationError::Unauthorized); + } + operation::check_digest( + &prepared, + prepared.request().command().context().actor(), + Some(digest), + )?; + let (prepared, value) = + plan::read(self.connection, self.selected, prepared, self.crypto).await?; + let Some((plan, transaction, time, protected)) = value else { + return Ok(None); + }; + let bound = BoundSigningPlan::from_committed_store(prepared, plan, transaction, time)?; + Ok(Some(Loaded { + bound, + operation, + plan: protected, + })) + } + pub(super) async fn claim_issuance( + &mut self, + request: ClaimAttemptRequest, + proof: AttachmentProof, + ) -> Result<ClaimAttemptOutcome, OperationError> { + let (grant_record, grant, current) = self.access(request.binding(), &proof).await?; + let loaded = self + .load_issuance_plan(request.operation_id(), request.command_digest()) + .await? + .ok_or(OperationError::RecoveryRequired)?; + same_binding( + loaded.bound.prepared().request().binding(), + request.binding(), + )?; + if loaded.bound.plan().digest() != request.plan_digest() { + return Err(OperationError::IdempotencyConflict); + } + let Loaded { + bound, + operation, + plan, + } = loaded; + let (bound, existing) = attempt::read( + self.connection, + self.selected, + bound, + request.recipient(), + self.crypto, + ) + .await?; + let (snapshot, protected, fresh) = if let Some((id, transaction, time, protected)) = + existing + { + ( + SigningAttempt::from_committed_store( + bound, + request.recipient(), + id, + transaction, + time, + )?, + protected, + false, + ) + } else { + if current.observed_at() < bound.bound_at() { + return Err(WorkspaceError::Unavailable.into()); + } + if current.observed_at() >= bound.prepared().issuance_window().first_issue_not_after() { + return Err(OperationError::DeadlineExceeded); + } + let snapshot = SigningAttempt::from_committed_store( + bound, + request.recipient(), + SigningAttemptId::from_bytes(super::random()?), + TransactionId::from_bytes(super::random()?), + current.observed_at(), + )?; + let protected = attempt::protect(&snapshot, self.crypto).await?; + (snapshot, protected, true) + }; + let anchor = snapshot.identity(); + let mut transaction = self + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<(), OperationError> = async { + let now = recheck( + &mut transaction, + self.namespace, + self.selected, + &grant, + &grant_record, + request.binding(), + &proof, + self.clock, + ) + .await?; + operation::unchanged( + &mut transaction, + snapshot.bound_plan().prepared(), + &operation, + ) + .await?; + plan::unchanged( + &mut transaction, + snapshot.bound_plan().prepared(), + Some(&plan), + ) + .await?; + if fresh { + if now.observed_at() < snapshot.claimed_at() { + return Err(WorkspaceError::Unavailable.into()); + } + if now.observed_at() + >= snapshot + .bound_plan() + .prepared() + .issuance_window() + .first_issue_not_after() + { + return Err(OperationError::DeadlineExceeded); + } + absent_claim( + &mut transaction, + self.selected, + request.operation_id(), + request.recipient(), + ) + .await?; + attempt::insert(&mut transaction, &snapshot, &protected).await?; + } else { + attempt::unchanged(&mut transaction, &snapshot, &protected).await?; + } + Ok(()) + } + .await; + if let Err(error) = checked { + if transaction.rollback().await.is_err() { + *self.uncertain = true; + return Ok(ClaimAttemptOutcome::Unknown(anchor)); + } + return Err(error); + } + let completed = if fresh { + transaction.commit().await + } else { + transaction.rollback().await + }; + if completed.is_err() { + *self.uncertain = true; + return Ok(ClaimAttemptOutcome::Unknown(anchor)); + } + Ok(if fresh { + ClaimAttemptOutcome::Claimed(snapshot) + } else { + ClaimAttemptOutcome::Retained(snapshot) + }) + } + pub(super) async fn query_issuance( + &mut self, + request: ClaimAttemptRequest, + proof: AttachmentProof, + ) -> Result<Option<SigningAttempt>, OperationError> { + let (record, grant, _) = self.access(request.binding(), &proof).await?; + let loaded = self + .load_issuance_plan(request.operation_id(), request.command_digest()) + .await?; + let retained = if let Some(loaded) = loaded { + same_binding( + loaded.bound.prepared().request().binding(), + request.binding(), + )?; + if loaded.bound.plan().digest() != request.plan_digest() { + return Err(OperationError::IdempotencyConflict); + } + let (bound, value) = attempt::read( + self.connection, + self.selected, + loaded.bound, + request.recipient(), + self.crypto, + ) + .await?; + match value { + Some((id, transaction, time, protected)) => Some(( + SigningAttempt::from_committed_store( + bound, + request.recipient(), + id, + transaction, + time, + )?, + protected, + loaded.operation, + loaded.plan, + )), + None => None, + } + } else { + None + }; + let mut transaction = self + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<(), OperationError> = async { + recheck( + &mut transaction, + self.namespace, + self.selected, + &grant, + &record, + request.binding(), + &proof, + self.clock, + ) + .await?; + if let Some((snapshot, protected, operation, plan)) = &retained { + operation::unchanged( + &mut transaction, + snapshot.bound_plan().prepared(), + operation, + ) + .await?; + plan::unchanged( + &mut transaction, + snapshot.bound_plan().prepared(), + Some(plan), + ) + .await?; + attempt::unchanged(&mut transaction, snapshot, protected).await?; + } else { + absent_claim( + &mut transaction, + self.selected, + request.operation_id(), + request.recipient(), + ) + .await?; + } + Ok(()) + } + .await; + if transaction.rollback().await.is_err() { + *self.uncertain = true; + return Err(OperationError::RecoveryRequired); + } + checked?; + Ok(retained.map(|value| value.0)) + } + /// Original-scope append admission deliberately does not consult a clock, + /// revocation flag or fresh command permission. The actual existing claim, + /// immutable plan and authenticated exact bytes are independently required. + async fn capture_access( + &mut self, + input: &AttachmentInput, + proof: &AttachmentProof, + ) -> Result<(GrantRecord, Vec<u8>), OperationError> { + if *self.uncertain { + return Err(OperationError::RecoveryRequired); + } + if input != self.selected { + return Err(OperationError::Unauthorized); + } + self.namespace.validate()?; + let protected = worker::read(self.connection, self.selected).await?; + let plaintext = self + .crypto + .open( + self.selected.workspace_id(), + self.selected.grant_id(), + &protected, + ) + .await?; + let record = plaintext.expose_secret(GrantRecord::decode)?; + record.authenticate_retained_capture(input, proof)?; + self.namespace.validate()?; + Ok((record, protected)) + } + pub(super) async fn capture_issuance( + &mut self, + input: AttachmentInput, + proof: AttachmentProof, + supplied: SealEvidence, + ) -> Result<EvidenceCaptureOutcome, OperationError> { + let (record, grant) = self.capture_access(&input, &proof).await?; + if supplied.workspace_id() != self.selected.workspace_id() { + return Err(OperationError::InvalidEvidence); + } + let Loaded { + bound, + operation, + plan, + } = self + .load_issuance_plan(supplied.operation_id(), supplied.command_digest()) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let (bound, claim) = attempt::read( + self.connection, + self.selected, + bound, + supplied.recipient(), + self.crypto, + ) + .await?; + let (id, claim_transaction, claimed_at, claim_protected) = + claim.ok_or(OperationError::RecoveryRequired)?; + let snapshot = SigningAttempt::from_committed_store( + bound, + supplied.recipient(), + id, + claim_transaction, + claimed_at, + )?; + if !supplied.matches_attempt(&snapshot) { + return Err(OperationError::InvalidEvidence); + } + // The supplied typed value was already independently verified. Recheck + // it against the backend's actual immutable claim, not its descriptor. + let checked = SealEvidence::verify( + &snapshot, + supplied.raw_json(), + supplied.observed_at_unix_ms(), + )?; + let existing = evidence::read(self.connection, &snapshot, self.crypto).await?; + let (protected, fresh) = if let Some((original, protected)) = existing { + if original.raw_json() != checked.raw_json() || original.digest() != checked.digest() { + return Err(OperationError::IdempotencyConflict); + } + (protected, false) + } else { + ( + evidence::protect( + &snapshot, + &checked, + TransactionId::from_bytes(super::random()?), + self.crypto, + ) + .await?, + true, + ) + }; + let receipt = protected.receipt; + let anchor = CommitAttempt::new( + receipt.workspace_id(), + receipt.operation_id(), + receipt.command_digest(), + Some(receipt.transaction_id()), + ); + let mut transaction = self + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let captured = async { + self.namespace.validate()?; + if worker::read(&mut transaction, self.selected).await? != grant { + return Err(OperationError::RecoveryRequired); + } + record.authenticate_retained_capture(&input, &proof)?; + operation::unchanged( + &mut transaction, + snapshot.bound_plan().prepared(), + &operation, + ) + .await?; + plan::unchanged( + &mut transaction, + snapshot.bound_plan().prepared(), + Some(&plan), + ) + .await?; + attempt::unchanged(&mut transaction, &snapshot, &claim_protected).await?; + if fresh { + evidence::unchanged(&mut transaction, &snapshot, None).await?; + evidence::insert(&mut transaction, &protected).await?; + } else { + evidence::unchanged(&mut transaction, &snapshot, Some(&protected)).await?; + } + Ok(()) + } + .await; + if let Err(error) = captured { + if transaction.rollback().await.is_err() { + *self.uncertain = true; + return Ok(EvidenceCaptureOutcome::Unknown(anchor)); + } + return Err(error); + } + let completed = if fresh { + transaction.commit().await + } else { + transaction.rollback().await + }; + if completed.is_err() { + *self.uncertain = true; + return Ok(EvidenceCaptureOutcome::Unknown(anchor)); + } + Ok(EvidenceCaptureOutcome::Committed(receipt)) + } + pub(super) async fn query_captured( + &mut self, + request: ClaimAttemptRequest, + proof: AttachmentProof, + ) -> Result<Option<CapturedSeal>, OperationError> { + let (record, grant, _) = self.access(request.binding(), &proof).await?; + let loaded = self + .load_issuance_plan(request.operation_id(), request.command_digest()) + .await?; + let retained = if let Some(loaded) = loaded { + same_binding( + loaded.bound.prepared().request().binding(), + request.binding(), + )?; + if loaded.bound.plan().digest() != request.plan_digest() { + return Err(OperationError::IdempotencyConflict); + } + let (bound, value) = attempt::read( + self.connection, + self.selected, + loaded.bound, + request.recipient(), + self.crypto, + ) + .await?; + if let Some((id, transaction, time, protected)) = value { + let snapshot = SigningAttempt::from_committed_store( + bound, + request.recipient(), + id, + transaction, + time, + )?; + let captured = evidence::read(self.connection, &snapshot, self.crypto).await?; + Some((snapshot, protected, loaded.operation, loaded.plan, captured)) + } else { + None + } + } else { + None + }; + let mut transaction = self + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<(), OperationError> = async { + recheck( + &mut transaction, + self.namespace, + self.selected, + &grant, + &record, + request.binding(), + &proof, + self.clock, + ) + .await?; + if let Some((snapshot, protected, operation, plan, captured)) = &retained { + operation::unchanged( + &mut transaction, + snapshot.bound_plan().prepared(), + operation, + ) + .await?; + plan::unchanged( + &mut transaction, + snapshot.bound_plan().prepared(), + Some(plan), + ) + .await?; + attempt::unchanged(&mut transaction, snapshot, protected).await?; + evidence::unchanged( + &mut transaction, + snapshot, + captured.as_ref().map(|value| &value.1), + ) + .await?; + } else { + absent_claim( + &mut transaction, + self.selected, + request.operation_id(), + request.recipient(), + ) + .await?; + } + Ok(()) + } + .await; + if transaction.rollback().await.is_err() { + *self.uncertain = true; + return Err(OperationError::RecoveryRequired); + } + checked?; + match retained { + Some((attempt, _, _, _, Some((evidence, protected)))) => { + Ok(Some(CapturedSeal::from_committed_store( + attempt, + evidence, + protected.receipt.transaction_id(), + )?)) + } + _ => Ok(None), + } + } +} +async fn absent_claim( + connection: &mut SqliteConnection, + selected: &AttachmentInput, + operation: OperationId, + recipient: PublicKey, +) -> Result<(), OperationError> { + let count:i64=sqlx::query_scalar("SELECT (SELECT count(*) FROM signing_attempts WHERE workspace=?1 AND operation_id=?2 AND recipient=?3)+(SELECT count(*) FROM seal_evidence WHERE workspace=?1 AND operation_id=?2 AND recipient=?3)+(SELECT count(*) FROM seal_evidence_parts WHERE workspace=?1 AND operation_id=?2 AND recipient=?3)") + .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if count != 0 { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -6,8 +6,11 @@ //! Losing an observer never drops that lock ahead of the SQLite connection. mod admission; +mod attempt; mod crypto; +mod evidence; mod fs; +mod issuance; mod operation; mod plan; mod record; @@ -214,6 +217,60 @@ impl WorkspaceStore for NativeWorkspace { } } impl radroots_storage::command::OperationJournal for NativeWorkspace { + fn claim_attempt( + &self, + request: radroots_storage::command::ClaimAttemptRequest, + proof: AttachmentProof, + ) -> BoxFuture< + '_, + Result< + radroots_storage::command::ClaimAttemptOutcome, + radroots_storage::command::OperationError, + >, + > { + Box::pin(self.worker.claim_attempt(request, proof)) + } + fn signing_attempt( + &self, + request: radroots_storage::command::ClaimAttemptRequest, + proof: AttachmentProof, + ) -> BoxFuture< + '_, + Result< + Option<radroots_storage::command::SigningAttempt>, + radroots_storage::command::OperationError, + >, + > { + Box::pin(self.worker.signing_attempt(request, proof)) + } + fn capture_evidence<'a>( + &'a self, + input: AttachmentInput, + proof: &'a AttachmentProof, + evidence: &'a radroots_storage::command::SealEvidence, + ) -> BoxFuture< + 'a, + Result< + radroots_storage::command::EvidenceCaptureOutcome, + radroots_storage::command::OperationError, + >, + > { + Box::pin(self.worker.capture_evidence(input, proof, evidence)) + } + fn obtained_evidence( + &self, + request: radroots_storage::command::ClaimAttemptRequest, + proof: AttachmentProof, + ) -> BoxFuture< + '_, + Result< + Option<radroots_storage::command::CapturedSeal>, + radroots_storage::command::OperationError, + >, + > { + Box::pin(self.worker.obtained_evidence(request, proof)) + } + fn bind_signing_intents( &self, binding: WorkspaceBinding, diff --git a/crates/storage_sqlite/src/workspace/record.rs b/crates/storage_sqlite/src/workspace/record.rs @@ -86,23 +86,7 @@ impl GrantRecord { proof: &AttachmentProof, now: UnixSeconds, ) -> Result<WorkspaceBinding, WorkspaceError> { - // Check the complete secret commitment before projecting detailed state. - let observed = Zeroizing::new(verifier(&self.input, proof)); - if !bool::from(observed.as_ref().ct_eq(&self.verifier)) { - return Err(WorkspaceError::Unauthorized); - } - if self.input.workspace_id() != input.workspace_id() { - return Err(WorkspaceError::WrongNamespace); - } - if self.input.authority() != input.authority() { - return Err(WorkspaceError::StaleAuthority); - } - if self.input.checkpoint() != input.checkpoint() { - return Err(WorkspaceError::StaleCheckpoint); - } - if &self.input != input { - return Err(WorkspaceError::Unauthorized); - } + self.authenticate_retained_capture(input, proof)?; if self.revoked { return Err(WorkspaceError::GrantRevoked); } @@ -122,6 +106,33 @@ impl GrantRecord { now, ) } + /// Checks only the original protected credential and exact namespace scope. + /// This path is exclusively for appending a matching already obtained + /// artifact to an actual existing claim, never for new issuance or reads. + pub(super) fn authenticate_retained_capture( + &self, + input: &AttachmentInput, + proof: &AttachmentProof, + ) -> Result<(), WorkspaceError> { + // Check the complete secret commitment before projecting detailed state. + let observed = Zeroizing::new(verifier(&self.input, proof)); + if !bool::from(observed.as_ref().ct_eq(&self.verifier)) { + return Err(WorkspaceError::Unauthorized); + } + if self.input.workspace_id() != input.workspace_id() { + return Err(WorkspaceError::WrongNamespace); + } + if self.input.authority() != input.authority() { + return Err(WorkspaceError::StaleAuthority); + } + if self.input.checkpoint() != input.checkpoint() { + return Err(WorkspaceError::StaleCheckpoint); + } + if &self.input != input { + return Err(WorkspaceError::Unauthorized); + } + self.validate() + } pub(super) fn revoke(&mut self) -> Result<(), WorkspaceError> { self.revoked = true; self.revision = Sequence::new( diff --git a/crates/storage_sqlite/src/workspace/tests/issuance_records.rs b/crates/storage_sqlite/src/workspace/tests/issuance_records.rs @@ -0,0 +1,623 @@ +use super::*; +use crate::workspace::{ + attempt as attempt_store, crypto::IssuancePayload, evidence as evidence_store, operation, + plan as plan_store, +}; +use nostr::{JsonUtil, nips::nip44}; +use radroots_domain::{ + CommandContextData, EnvelopeEventId, OperationId, SigningAttemptId, TransactionId, +}; +use radroots_protocol::{ + chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal, ChatSigningPlan}, + command::{CapturedChatCommand, InquireInput}, +}; +use radroots_storage::command::{ + AdmissionOutcome, AdmissionRequest, BoundSigningPlan, ClaimAttemptOutcome, ClaimAttemptRequest, + EvidenceCaptureOutcome, OperationJournal, PlanBindingOutcome, SealEvidence, SigningAttempt, +}; +use serde_json::{Value, json}; +use sqlx::{Connection, SqliteConnection}; +struct Issued { + fixture: CryptoFixture, + selected: AttachmentInput, + attempt: SigningAttempt, + evidence: SealEvidence, + path: std::path::PathBuf, +} +impl Issued { + async fn new() -> Self { + let fixture = CryptoFixture::new(); + let path = fixture + ._temp + .path() + .canonicalize() + .unwrap() + .join("issuance-records"); + let (store, selected, proof) = NativeWorkspace::initialize_local_outbox( + &path, + LocalOutboxConfig::new( + participant(), + participant(), + "device", + UnixSeconds::new(200).unwrap(), + ) + .unwrap(), + fixture.crypto(), + Arc::new(FixedClock(100)), + ) + .await + .unwrap(); + let binding = store.authenticate(selected.clone(), &proof).await.unwrap(); + let operation = OperationId::from_bytes([61; 32]); + let context = CommandContextData::new( + operation, + binding.actor(), + selected.workspace_id(), + selected.authority(), + selected.route_digest(), + None, + None, + UnixSeconds::new(150).unwrap(), + None, + ) + .unwrap(); + let command = CapturedChatCommand::inquire( + context, + InquireInput::new( + radroots_domain::ThreadId::from_bytes([7; 32]), + participant(), + None, + &"\0".repeat(3500), + ) + .unwrap(), + ) + .unwrap(); + let rumor = ChatRumor::from_command(&command, UnixSeconds::new(100).unwrap()).unwrap(); + let mut scalar = [0; 32]; + scalar[31] = 1; + let keys = nostr::Keys::new(nostr::SecretKey::from_slice(&scalar).unwrap()); + let ciphertext = nip44::encrypt( + keys.secret_key(), + &keys.public_key(), + rumor.json(), + nip44::Version::V2, + ) + .unwrap(); + let seal = ChatSeal::new( + &rumor, + participant(), + UnixSeconds::new(99).unwrap(), + &ciphertext, + ) + .unwrap(); + let source = nostr::UnsignedEvent { + id: None, + pubkey: keys.public_key(), + created_at: nostr::Timestamp::from_secs(99), + kind: nostr::Kind::Custom(10050), + tags: nostr::Tags::from_list(vec![ + nostr::Tag::parse(["relay", "wss://route.example/"]).unwrap(), + ]), + content: "public routing provenance ".repeat(1000), + } + .sign_with_keys(&keys) + .unwrap(); + let route = CapturedDmRoute::from_observed_descriptor( + participant(), + EnvelopeEventId::from_bytes(*source.id.as_bytes()), + &source.as_json(), + &["wss://route.example/".into()], + ) + .unwrap(); + let plan = ChatSigningPlan::new( + &command, + UnixSeconds::new(100).unwrap(), + vec![seal], + vec![route], + ChatReplay::NonReplayable, + ) + .unwrap(); + let digest = *plan.digest(); + let command_digest = command.digest(); + let copied = + || proof.with_secret(|value| AttachmentProof::from_protected_input(value).unwrap()); + assert!(matches!( + store + .admit_command_and_hold( + AdmissionRequest::new(binding.clone(), command).unwrap(), + copied() + ) + .await + .unwrap(), + AdmissionOutcome::Committed(_) + )); + assert!(matches!( + store + .bind_signing_intents(binding.clone(), plan, copied()) + .await + .unwrap(), + PlanBindingOutcome::Committed(_) + )); + let attempt = match store + .claim_attempt( + ClaimAttemptRequest::new(binding, operation, command_digest, digest, participant()), + copied(), + ) + .await + .unwrap() + { + ClaimAttemptOutcome::Claimed(value) => value, + _ => panic!("first claim must confirm"), + }; + let fields = attempt.seal().fields(); + let signed = nostr::UnsignedEvent { + id: Some(nostr::EventId::from_slice(&attempt.seal().event_id()).unwrap()), + pubkey: keys.public_key(), + created_at: nostr::Timestamp::from_secs(fields.created_at), + kind: nostr::Kind::Custom(13), + tags: nostr::Tags::new(), + content: fields.content.into(), + } + .sign_with_keys(&keys) + .unwrap(); + signed.verify().unwrap(); + let evidence = SealEvidence::verify(&attempt, &signed.as_json(), None).unwrap(); + assert!(evidence.raw_json().len() > 16384); + assert!(matches!( + store + .capture_evidence(selected.clone(), &proof, &evidence) + .await + .unwrap(), + EvidenceCaptureOutcome::Committed(_) + )); + store.close().await.unwrap(); + Self { + fixture, + selected, + attempt, + evidence, + path, + } + } + async fn database(&self) -> SqliteConnection { + let mut connection = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(self.path.join("execution_v1.sqlite")) + .create_if_missing(false) + .foreign_keys(false), + ) + .await + .unwrap(); + sqlx::query("PRAGMA ignore_check_constraints=ON") + .execute(&mut connection) + .await + .unwrap(); + connection + } + async fn bound(&self, connection: &mut SqliteConnection) -> BoundSigningPlan { + let original = self.attempt.bound_plan().prepared().identity(); + let prepared = operation::read( + connection, + &self.selected, + original.operation_id(), + &self.fixture.crypto(), + ) + .await + .unwrap() + .unwrap() + .0; + let (prepared, value) = + plan_store::read(connection, &self.selected, prepared, &self.fixture.crypto()) + .await + .unwrap(); + let (plan, transaction, time, _) = value.unwrap(); + BoundSigningPlan::from_committed_store(prepared, plan, transaction, time).unwrap() + } +} +#[tokio::test] +async fn authenticated_attempt_headers_and_all_indexed_facts_are_checked_without_repair() { + let issued = Issued::new().await; + let mut database = issued.database().await; + let crypto = issued.fixture.crypto(); + let scope = attempt_store::scope(&issued.attempt); + let original: Vec<u8> = sqlx::query_scalar("SELECT protected FROM signing_attempts") + .fetch_one(&mut database) + .await + .unwrap(); + let encoded: Value = crypto + .open_issuance(scope, IssuancePayload::Attempt, 0, &original) + .await + .unwrap() + .expose_secret(|bytes| serde_json::from_slice(bytes).unwrap()); + let other = + PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5") + .unwrap(); + for (field, value) in [ + ("version", json!(2)), + ("workspace", json!("99".repeat(32))), + ("operation_id", json!("99".repeat(32))), + ("command_digest", json!("99".repeat(32))), + ("plan_digest", json!(vec![9u8; 32])), + ("recipient", json!(other)), + ("attempt_id", json!("99".repeat(32))), + ("transaction_id", json!("99".repeat(32))), + ("preparation_transaction", json!("99".repeat(32))), + ("plan_transaction", json!("99".repeat(32))), + ("grant_id", json!("99".repeat(32))), + ("intent_digest", json!(vec![9u8; 32])), + ("deadline_unix_ms", json!(149000)), + ("expected_event", json!("99".repeat(32))), + ("claimed_at", json!("99")), + ("claimed_at", json!("150")), + ] { + let mut changed = encoded.clone(); + changed[field] = value; + let protected = crypto + .seal_issuance( + scope, + IssuancePayload::Attempt, + 0, + &serde_json::to_vec(&changed).unwrap(), + ) + .await + .unwrap(); + sqlx::query("UPDATE signing_attempts SET protected=?") + .bind(&protected) + .execute(&mut database) + .await + .unwrap(); + let bound = issued.bound(&mut database).await; + let error = attempt_store::read( + &mut database, + &issued.selected, + bound, + participant(), + &crypto, + ) + .await + .expect_err("inconsistent authenticated claim must fail"); + assert_eq!(error.code(), "recovery_required", "{field}"); + let retained: Vec<u8> = sqlx::query_scalar("SELECT protected FROM signing_attempts") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(retained, protected); + } + sqlx::query("UPDATE signing_attempts SET protected=?") + .bind(&original) + .execute(&mut database) + .await + .unwrap(); + for change in [ + "UPDATE signing_attempts SET plan_digest=zeroblob(32)", + "UPDATE signing_attempts SET intent_digest=zeroblob(32)", + "UPDATE signing_attempts SET protected=zeroblob(262145)", + ] { + sqlx::query(change).execute(&mut database).await.unwrap(); + let bound = issued.bound(&mut database).await; + assert_eq!( + attempt_store::read( + &mut database, + &issued.selected, + bound, + participant(), + &crypto + ) + .await + .err() + .unwrap() + .code(), + "recovery_required" + ); + sqlx::query("UPDATE signing_attempts SET plan_digest=?,intent_digest=?,protected=?") + .bind(issued.attempt.bound_plan().plan().digest().as_slice()) + .bind(issued.attempt.binding().digest().as_slice()) + .bind(&original) + .execute(&mut database) + .await + .unwrap(); + } + let identity = issued.attempt.bound_plan().prepared().identity(); + for change in [ + "UPDATE signing_attempts SET workspace=zeroblob(32)", + "UPDATE signing_attempts SET operation_id=zeroblob(32)", + "UPDATE signing_attempts SET recipient=zeroblob(32)", + "UPDATE signing_attempts SET attempt_id=zeroblob(32)", + "UPDATE signing_attempts SET transaction_id=zeroblob(32)", + "UPDATE signing_attempts SET plan_digest=zeroblob(32)", + "UPDATE signing_attempts SET intent_digest=zeroblob(32)", + "UPDATE signing_attempts SET protected=zeroblob(1)", + ] { + sqlx::query(change).execute(&mut database).await.unwrap(); + let mut transaction = database.begin_with("BEGIN IMMEDIATE").await.unwrap(); + assert!( + attempt_store::unchanged(&mut transaction, &issued.attempt, &original) + .await + .is_err(), + "{change}" + ); + transaction.rollback().await.unwrap(); + sqlx::query("UPDATE signing_attempts SET workspace=?,operation_id=?,recipient=?,attempt_id=?,transaction_id=?,plan_digest=?,intent_digest=?,protected=?").bind(identity.workspace_id().as_bytes().as_slice()).bind(identity.operation_id().as_bytes().as_slice()).bind(participant().as_bytes().as_slice()).bind(issued.attempt.attempt_id().as_bytes().as_slice()).bind(issued.attempt.transaction_id().as_bytes().as_slice()).bind(issued.attempt.bound_plan().plan().digest().as_slice()).bind(issued.attempt.binding().digest().as_slice()).bind(&original).execute(&mut database).await.unwrap(); + } + database.close().await.unwrap(); +} +#[tokio::test] +async fn authenticated_evidence_manifests_parts_and_exact_original_observations_are_checked() { + let issued = Issued::new().await; + let mut database = issued.database().await; + let crypto = issued.fixture.crypto(); + let scope = attempt_store::scope(&issued.attempt); + let original: Vec<u8> = sqlx::query_scalar("SELECT protected FROM seal_evidence") + .fetch_one(&mut database) + .await + .unwrap(); + let manifest: Value = crypto + .open_issuance(scope, IssuancePayload::Evidence, 0, &original) + .await + .unwrap() + .expose_secret(|bytes| serde_json::from_slice(bytes).unwrap()); + let other = + PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5") + .unwrap(); + for (field, value) in [ + ("version", json!(2)), + ("workspace", json!("99".repeat(32))), + ("operation_id", json!("99".repeat(32))), + ("command_digest", json!("99".repeat(32))), + ("plan_digest", json!(vec![9u8; 32])), + ("recipient", json!(other)), + ("attempt_id", json!("99".repeat(32))), + ("claim_transaction", json!("99".repeat(32))), + ("intent_digest", json!(vec![9u8; 32])), + ("event_id", json!("99".repeat(32))), + ("evidence_digest", json!(vec![9u8; 32])), + ("transaction_id", json!("99".repeat(32))), + ("part_count", json!(4)), + ("byte_count", json!(1)), + ("observed_at", json!(0)), + ("observed_at", json!(253_402_300_800_000u64)), + ] { + let mut changed = manifest.clone(); + changed[field] = value; + let protected = crypto + .seal_issuance( + scope, + IssuancePayload::Evidence, + 0, + &serde_json::to_vec(&changed).unwrap(), + ) + .await + .unwrap(); + sqlx::query("UPDATE seal_evidence SET protected=?") + .bind(&protected) + .execute(&mut database) + .await + .unwrap(); + let error = evidence_store::read(&mut database, &issued.attempt, &crypto) + .await + .err() + .expect("inconsistent authenticated evidence must fail"); + assert_eq!(error.code(), "recovery_required", "{field}"); + let retained: Vec<u8> = sqlx::query_scalar("SELECT protected FROM seal_evidence") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(retained, protected); + } + sqlx::query("UPDATE seal_evidence SET protected=?") + .bind(&original) + .execute(&mut database) + .await + .unwrap(); + let header:(Vec<u8>,Vec<u8>,Vec<u8>,Vec<u8>,i64,i64)=sqlx::query_as("SELECT attempt_id,event_id,evidence_digest,transaction_id,part_count,byte_count FROM seal_evidence").fetch_one(&mut database).await.unwrap(); + for change in [ + "UPDATE seal_evidence SET attempt_id=zeroblob(32)", + "UPDATE seal_evidence SET event_id=zeroblob(32)", + "UPDATE seal_evidence SET evidence_digest=zeroblob(32)", + "UPDATE seal_evidence SET transaction_id=zeroblob(32)", + "UPDATE seal_evidence SET part_count=5", + "UPDATE seal_evidence SET byte_count=65537", + "UPDATE seal_evidence SET part_count=1", + "UPDATE seal_evidence SET protected=zeroblob(262145)", + ] { + sqlx::query(change).execute(&mut database).await.unwrap(); + assert_eq!( + evidence_store::read(&mut database, &issued.attempt, &crypto) + .await + .err() + .unwrap() + .code(), + "recovery_required", + "{change}" + ); + sqlx::query("UPDATE seal_evidence SET attempt_id=?,event_id=?,evidence_digest=?,transaction_id=?,part_count=?,byte_count=?,protected=?").bind(&header.0).bind(&header.1).bind(&header.2).bind(&header.3).bind(header.4).bind(header.5).bind(&original).execute(&mut database).await.unwrap(); + } + // A valid protected manifest matching a changed SQL digest still cannot + // redefine the hash of the original authenticated raw signature bytes. + let mut changed = manifest.clone(); + changed["evidence_digest"] = json!(vec![9u8; 32]); + let protected = crypto + .seal_issuance( + scope, + IssuancePayload::Evidence, + 0, + &serde_json::to_vec(&changed).unwrap(), + ) + .await + .unwrap(); + sqlx::query("UPDATE seal_evidence SET evidence_digest=?,protected=?") + .bind([9u8; 32].as_slice()) + .bind(&protected) + .execute(&mut database) + .await + .unwrap(); + assert_eq!( + evidence_store::read(&mut database, &issued.attempt, &crypto) + .await + .err() + .unwrap() + .code(), + "recovery_required" + ); + sqlx::query("UPDATE seal_evidence SET evidence_digest=?,protected=?") + .bind(&header.2) + .bind(&original) + .execute(&mut database) + .await + .unwrap(); + let parts: Vec<(i64, Vec<u8>)> = + sqlx::query_as("SELECT part,protected FROM seal_evidence_parts ORDER BY part") + .fetch_all(&mut database) + .await + .unwrap(); + assert!(parts.len() > 1); + for fault in 0..5 { + sqlx::query("DELETE FROM seal_evidence_parts") + .execute(&mut database) + .await + .unwrap(); + for (part, protected) in &parts { + sqlx::query("INSERT INTO seal_evidence_parts(workspace,operation_id,recipient,part,protected) VALUES(?,?,?,?,?)").bind(scope.workspace.as_bytes().as_slice()).bind(scope.operation.as_bytes().as_slice()).bind(scope.recipient.as_bytes().as_slice()).bind(part).bind(protected).execute(&mut database).await.unwrap(); + } + match fault { + 0 => { + sqlx::query("DELETE FROM seal_evidence_parts WHERE part=1") + .execute(&mut database) + .await + .unwrap(); + } + 1 => { + sqlx::query("UPDATE seal_evidence_parts SET protected=zeroblob(0)") + .execute(&mut database) + .await + .unwrap(); + } + 2 => { + sqlx::query( + "UPDATE seal_evidence_parts SET protected=zeroblob(1048577) WHERE part=1", + ) + .execute(&mut database) + .await + .unwrap(); + } + 3 => { + sqlx::query("UPDATE seal_evidence_parts SET part=0 WHERE part=1") + .execute(&mut database) + .await + .unwrap(); + } + 4 => { + let protected = crypto + .seal_issuance(scope, IssuancePayload::Evidence, 1, &[0]) + .await + .unwrap(); + sqlx::query("UPDATE seal_evidence_parts SET protected=? WHERE part=1") + .bind(protected) + .execute(&mut database) + .await + .unwrap(); + } + _ => unreachable!(), + } + assert_eq!( + evidence_store::read(&mut database, &issued.attempt, &crypto) + .await + .err() + .unwrap() + .code(), + "recovery_required", + "part fault {fault}" + ); + } + sqlx::query("DELETE FROM seal_evidence_parts") + .execute(&mut database) + .await + .unwrap(); + for (part, protected) in &parts { + sqlx::query("INSERT INTO seal_evidence_parts(workspace,operation_id,recipient,part,protected) VALUES(?,?,?,?,?)").bind(scope.workspace.as_bytes().as_slice()).bind(scope.operation.as_bytes().as_slice()).bind(scope.recipient.as_bytes().as_slice()).bind(part).bind(protected).execute(&mut database).await.unwrap(); + } + let (_, protected) = evidence_store::read(&mut database, &issued.attempt, &crypto) + .await + .unwrap() + .unwrap(); + assert!( + evidence_store::unchanged(&mut database, &issued.attempt, None) + .await + .is_err() + ); + for fault in 0..4 { + match fault { + 0 => { + sqlx::query("UPDATE seal_evidence SET transaction_id=zeroblob(32)") + .execute(&mut database) + .await + .unwrap(); + } + 1 => { + sqlx::query("UPDATE seal_evidence_parts SET protected=zeroblob(1) WHERE part=1") + .execute(&mut database) + .await + .unwrap(); + } + 2 => { + sqlx::query("DELETE FROM seal_evidence_parts WHERE part=1") + .execute(&mut database) + .await + .unwrap(); + } + 3 => { + sqlx::query("DELETE FROM seal_evidence") + .execute(&mut database) + .await + .unwrap(); + } + _ => unreachable!(), + } + assert!( + evidence_store::unchanged(&mut database, &issued.attempt, Some(&protected)) + .await + .is_err() + ); + if fault == 0 { + sqlx::query("UPDATE seal_evidence SET transaction_id=?") + .bind(&header.3) + .execute(&mut database) + .await + .unwrap(); + } + if fault == 1 { + sqlx::query("UPDATE seal_evidence_parts SET protected=? WHERE part=1") + .bind(&parts[0].1) + .execute(&mut database) + .await + .unwrap(); + } + if fault == 2 { + sqlx::query("INSERT INTO seal_evidence_parts(workspace,operation_id,recipient,part,protected) VALUES(?,?,?,1,?)").bind(scope.workspace.as_bytes().as_slice()).bind(scope.operation.as_bytes().as_slice()).bind(scope.recipient.as_bytes().as_slice()).bind(&parts[0].1).execute(&mut database).await.unwrap(); + } + } + assert!( + evidence_store::unchanged(&mut database, &issued.attempt, None) + .await + .is_err() + ); + let fake = SigningAttempt::from_committed_store( + issued.bound(&mut database).await, + participant(), + SigningAttemptId::from_bytes([77; 32]), + TransactionId::from_bytes([78; 32]), + UnixSeconds::new(100).unwrap(), + ) + .unwrap(); + assert!( + evidence_store::protect( + &fake, + &issued.evidence, + TransactionId::from_bytes([79; 32]), + &crypto + ) + .await + .is_err() + ); + database.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/src/workspace/tests/mod.rs b/crates/storage_sqlite/src/workspace/tests/mod.rs @@ -1,4 +1,5 @@ use super::*; +mod issuance_records; mod operation_records; mod plan_records; use radroots_domain::{ActorRef, SourceId}; @@ -557,7 +558,7 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r .await .unwrap(); let statement = match fault { - 0 => "PRAGMA user_version=5", + 0 => "PRAGMA user_version=6", 1 => "DELETE FROM workspace_grant", 2 => "UPDATE workspace_grant SET grant_id=zeroblob(31)", 3 => "UPDATE workspace_grant SET protected=zeroblob(0)", @@ -603,7 +604,7 @@ async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_r .fetch_one(&mut connection) .await .unwrap(); - assert_eq!(version, if fault == 0 { 5 } else { 4 }); + assert_eq!(version, if fault == 0 { 6 } else { 5 }); assert_eq!(rows, if fault == 1 { 0 } else { 1 }); if (3..=5).contains(&fault) { let size: i64 = sqlx::query_scalar("SELECT length(protected) FROM workspace_grant") diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -1,11 +1,13 @@ use super::{ AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceCrypto, - WorkspaceError, admission::Journal, fs::Namespace, operation, plan, record::GrantRecord, + WorkspaceError, admission::Journal, attempt, evidence, fs::Namespace, operation, plan, + record::GrantRecord, }; use radroots_domain::{CommandDigest, OperationId}; use radroots_storage::command::{ - AdmissionOutcome, AdmissionRequest, BoundSigningPlan, ChatSigningPlan, CommitAttempt, - OperationError, PlanBindingOutcome, PreparedOperation, + AdmissionOutcome, AdmissionRequest, BoundSigningPlan, CapturedSeal, ChatSigningPlan, + ClaimAttemptOutcome, ClaimAttemptRequest, CommitAttempt, EvidenceCaptureOutcome, + OperationError, PlanBindingOutcome, PreparedOperation, SealEvidence, SigningAttempt, }; use sqlx::{ Connection, Row, SqliteConnection, @@ -30,6 +32,27 @@ const QUEUE_CAPACITY: usize = 32; const TABLE: &str = "CREATE TABLE workspace_grant (singleton INTEGER PRIMARY KEY CHECK(singleton=1), workspace BLOB NOT NULL CHECK(length(workspace)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT"; type Reply<T, E = WorkspaceError> = oneshot::Sender<Result<T, E>>; enum Job { + Claim( + Box<ClaimAttemptRequest>, + AttachmentProof, + Reply<ClaimAttemptOutcome, OperationError>, + ), + Attempt( + Box<ClaimAttemptRequest>, + AttachmentProof, + Reply<Option<SigningAttempt>, OperationError>, + ), + Capture( + Box<AttachmentInput>, + AttachmentProof, + Box<SealEvidence>, + Reply<EvidenceCaptureOutcome, OperationError>, + ), + Captured( + Box<ClaimAttemptRequest>, + AttachmentProof, + Reply<Option<CapturedSeal>, OperationError>, + ), BindPlan( Box<WorkspaceBinding>, ChatSigningPlan, @@ -148,6 +171,58 @@ impl Handle { if ready.send(Ok(())).is_ok() { while let Ok(Queued { job, _budget }) = requests.recv() { match job { + Job::Claim(request, proof, reply) => { + let result = Journal { + connection: &mut connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + } + .claim_issuance(*request, proof) + .await; + let _ = reply.send(result); + } + Job::Attempt(request, proof, reply) => { + let result = Journal { + connection: &mut connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + } + .query_issuance(*request, proof) + .await; + let _ = reply.send(result); + } + Job::Capture(selected, proof, evidence, reply) => { + let result = Journal { + connection: &mut connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + } + .capture_issuance(*selected, proof, *evidence) + .await; + let _ = reply.send(result); + } + Job::Captured(request, proof, reply) => { + let result = Journal { + connection: &mut connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + } + .query_captured(*request, proof) + .await; + let _ = reply.send(result); + } Job::BindPlan(binding, plan, proof, reply) => { let result = Journal { connection: &mut connection, @@ -269,6 +344,7 @@ impl Handle { fn send(&self, job: Job) -> Result<(), WorkspaceError> { let bytes = match &job { Job::BindPlan(..) => 1024 * 1024, + Job::Capture(..) => 256 * 1024, Job::Admit(..) => 96 * 1024, _ => 16 * 1024, }; @@ -296,6 +372,62 @@ impl Handle { mpsc::TrySendError::Disconnected(_) => WorkspaceError::Closed, }) } + pub(super) async fn claim_attempt( + &self, + request: ClaimAttemptRequest, + proof: AttachmentProof, + ) -> Result<ClaimAttemptOutcome, OperationError> { + let anchor = request.identity(); + let (reply, result) = oneshot::channel(); + self.send(Job::Claim(Box::new(request), proof, reply))?; + match result.await { + Ok(result) => result, + Err(_) => Ok(ClaimAttemptOutcome::Unknown(anchor)), + } + } + pub(super) async fn signing_attempt( + &self, + request: ClaimAttemptRequest, + proof: AttachmentProof, + ) -> Result<Option<SigningAttempt>, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::Attempt(Box::new(request), proof, reply))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } + pub(super) async fn capture_evidence( + &self, + input: AttachmentInput, + proof: &AttachmentProof, + evidence: &SealEvidence, + ) -> Result<EvidenceCaptureOutcome, OperationError> { + let anchor = CommitAttempt::new( + evidence.workspace_id(), + evidence.operation_id(), + evidence.command_digest(), + None, + ); + let copied = proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?; + let (reply, result) = oneshot::channel(); + self.send(Job::Capture( + Box::new(input), + copied, + Box::new(evidence.retained_copy()), + reply, + ))?; + match result.await { + Ok(result) => result, + Err(_) => Ok(EvidenceCaptureOutcome::Unknown(anchor)), + } + } + pub(super) async fn obtained_evidence( + &self, + request: ClaimAttemptRequest, + proof: AttachmentProof, + ) -> Result<Option<CapturedSeal>, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::Captured(Box::new(request), proof, reply))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } pub(super) async fn bind_plan( &self, binding: WorkspaceBinding, @@ -475,7 +607,20 @@ async fn initialize( .execute(&mut *transaction) .await .map_err(|_| WorkspaceError::StorageFailure)?; - sqlx::query("PRAGMA user_version=4") + for definition in [ + attempt::TABLE, + attempt::ID_INDEX, + attempt::TX_INDEX, + evidence::TABLE, + evidence::PARTS, + evidence::TX_INDEX, + ] { + sqlx::raw_sql(definition) + .execute(&mut *transaction) + .await + .map_err(|_| WorkspaceError::StorageFailure)?; + } + sqlx::query("PRAGMA user_version=5") .execute(&mut *transaction) .await .map_err(|_| WorkspaceError::StorageFailure)?; @@ -497,11 +642,11 @@ async fn initialize( .fetch_one(&mut *connection) .await .map_err(|_| WorkspaceError::RecoveryRequired)?; - if version != 4 { + if version != 5 { return Err(WorkspaceError::RecoveryRequired); } - let catalog_matches: i64 = sqlx::query_scalar("SELECT CASE WHEN count(*)=5 AND sum(CASE WHEN type='table' AND name='workspace_grant' AND tbl_name='workspace_grant' AND sql=? THEN 1 WHEN type='table' AND name='operations' AND tbl_name='operations' AND sql=? THEN 1 WHEN type='table' AND name='signing_plans' AND tbl_name='signing_plans' AND sql=? THEN 1 WHEN type='table' AND name='signing_plan_parts' AND tbl_name='signing_plan_parts' AND sql=? THEN 1 WHEN type='index' AND name='operation_transaction_identity' AND tbl_name='operations' AND sql=? THEN 1 ELSE 0 END)=5 THEN 1 ELSE 0 END FROM sqlite_schema") - .bind(TABLE).bind(operation::TABLE).bind(plan::TABLE).bind(plan::PARTS).bind(operation::INDEX).fetch_one(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?; + let catalog_matches: i64 = sqlx::query_scalar("SELECT CASE WHEN count(*)=11 AND sum(CASE WHEN type='table' AND name='workspace_grant' AND tbl_name='workspace_grant' AND sql=? THEN 1 WHEN type='table' AND name='operations' AND tbl_name='operations' AND sql=? THEN 1 WHEN type='table' AND name='signing_plans' AND tbl_name='signing_plans' AND sql=? THEN 1 WHEN type='table' AND name='signing_plan_parts' AND tbl_name='signing_plan_parts' AND sql=? THEN 1 WHEN type='table' AND name='signing_attempts' AND tbl_name='signing_attempts' AND sql=? THEN 1 WHEN type='index' AND name='signing_attempt_identity' AND tbl_name='signing_attempts' AND sql=? THEN 1 WHEN type='index' AND name='signing_attempt_transaction_identity' AND tbl_name='signing_attempts' AND sql=? THEN 1 WHEN type='table' AND name='seal_evidence' AND tbl_name='seal_evidence' AND sql=? THEN 1 WHEN type='table' AND name='seal_evidence_parts' AND tbl_name='seal_evidence_parts' AND sql=? THEN 1 WHEN type='index' AND name='seal_evidence_transaction_identity' AND tbl_name='seal_evidence' AND sql=? THEN 1 WHEN type='index' AND name='operation_transaction_identity' AND tbl_name='operations' AND sql=? THEN 1 ELSE 0 END)=11 THEN 1 ELSE 0 END FROM sqlite_schema") + .bind(TABLE).bind(operation::TABLE).bind(plan::TABLE).bind(plan::PARTS).bind(attempt::TABLE).bind(attempt::ID_INDEX).bind(attempt::TX_INDEX).bind(evidence::TABLE).bind(evidence::PARTS).bind(evidence::TX_INDEX).bind(operation::INDEX).fetch_one(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?; if catalog_matches != 1 { return Err(WorkspaceError::RecoveryRequired); } diff --git a/crates/storage_sqlite/tests/support/workspace_issuance.rs b/crates/storage_sqlite/tests/support/workspace_issuance.rs @@ -0,0 +1,799 @@ +use super::*; +use core::{cell::Cell, num::NonZeroU64}; +use radroots_nostr::{ + key::parse_secret_key, + signing::{LocalSigner, OsNonceSource}, +}; +use radroots_signing::{ + issuance::{OutcomeKind, SigningIntent}, + provider::{ParticipantProvider, ProviderCall}, + request::CancellationSignal, +}; +use radroots_storage::command::{ + CapturedSeal, ClaimAttemptOutcome, ClaimAttemptRequest, EvidenceCaptureOutcome, SealEvidence, + SigningAttempt, +}; +thread_local! {static CALLS:Cell<usize>=const {Cell::new(0)};static MISSING:Cell<bool>=const {Cell::new(false)};} +fn signer_clock() -> Result<u64, radroots_signing::Error> { + let count = CALLS.with(|calls| { + let value = calls.get() + 1; + calls.set(value); + value + }); + if count > 1 && MISSING.with(Cell::get) { + Err(radroots_signing::Error::new( + radroots_signing::error::Kind::InternalError, + )) + } else { + Ok(100_000) + } +} +fn selection( + binding: &WorkspaceBinding, + prepared: &PreparedOperation, + plan_digest: [u8; 32], + recipient: PublicKey, +) -> ClaimAttemptRequest { + ClaimAttemptRequest::new( + binding.clone(), + prepared.identity().operation_id(), + prepared.identity().command_digest(), + plan_digest, + recipient, + ) +} +fn claim(outcome: ClaimAttemptOutcome) -> SigningAttempt { + match outcome { + ClaimAttemptOutcome::Claimed(value) => value, + _ => panic!("first actual claim must confirm its commit"), + } +} +async fn prepare( + fixture: &Fixture, + store: &NativeWorkspace, + binding: &WorkspaceBinding, + proof: &AttachmentProof, + id: u8, + large: bool, +) -> (PreparedOperation, [u8; 32], Vec<PublicKey>) { + let mut captured = peer_request(binding, id); + if large { + let mut value: serde_json::Value = + serde_json::from_slice(captured.command().protected_wire()).unwrap(); + value["input"]["text"] = "\0".repeat(3500).into(); + captured = AdmissionRequest::from_protected_wire( + binding.clone(), + &serde_json::to_vec(&value).unwrap(), + ) + .unwrap(); + } + let prepared = committed( + store + .admit_command_and_hold(captured, copy(proof)) + .await + .unwrap(), + ); + let plan = plan(prepared.request().command(), 100, "native-issuance"); + let digest = *plan.digest(); + let recipients = plan.seals().iter().map(|seal| seal.recipient()).collect(); + bound( + store + .bind_signing_intents(binding.clone(), plan, copy(proof)) + .await + .unwrap(), + ); + let _ = fixture; + (prepared, digest, recipients) +} +async fn obtain(attempt: &SigningAttempt, missing: bool) -> SealEvidence { + CALLS.with(|calls| calls.set(0)); + MISSING.with(|value| value.set(missing)); + // Published synthetic key in a qualified local provider, isolated from all host custody. + let signer = LocalSigner::with_clock( + parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") + .unwrap(), + signer_clock, + ) + .unwrap() + .with_nonce_source(Arc::new(OsNonceSource)); + let observed = signer.provider_state().await.unwrap(); + assert_eq!(observed.identity(), key()); + assert_eq!( + observed.exact_issuance(), + Some(radroots_signing::recovery::ReplayCapability::NonReplayable) + ); + let intent = SigningIntent::from_chat_seal( + attempt.binding().operation_id(), + attempt.bound_plan().prepared().identity().command_digest(), + attempt.seal(), + ProviderCall::new(key(), attempt.deadline_unix_ms(), CancellationSignal::new()), + ) + .unwrap(); + assert_eq!(intent.binding(), attempt.binding()); + let outcome = signer.sign_exact(intent).await; + assert_eq!(outcome.binding(), attempt.binding()); + let (_, kind) = outcome.into_parts(); + let OutcomeKind::Obtained(artifact) = kind else { + panic!("actual local exact signing must obtain") + }; + assert_eq!(artifact.observed_at_unix_ms().is_none(), missing); + artifact.with_json(|raw| { + SealEvidence::verify(attempt, raw, artifact.observed_at_unix_ms()).unwrap() + }) +} +fn captured(outcome: EvidenceCaptureOutcome) -> radroots_storage::command::EvidenceReceipt { + match outcome { + EvidenceCaptureOutcome::Committed(value) => value, + _ => panic!("fixture capture must confirm commit"), + } +} +#[tokio::test] +async fn real_exact_peer_and_self_signatures_capture_reopen_and_never_reclaim_original_intents() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 130, false).await; + let mut originals = Vec::new(); + for recipient in recipients { + let first = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipient), + copy(&proof), + ) + .await + .unwrap(), + ); + let signature = obtain(&first, true).await; + let raw = signature.raw_json().to_owned(); + let receipt = captured( + store + .capture_evidence(input.clone(), &proof, &signature) + .await + .unwrap(), + ); + assert_eq!(receipt.observed_at_unix_ms(), None); + let duplicate = store + .claim_attempt( + selection(&binding, &prepared, digest, recipient), + copy(&proof), + ) + .await + .unwrap(); + assert!(matches!(duplicate, ClaimAttemptOutcome::Retained(_))); + let repeated = SealEvidence::verify(&first, &raw, NonZeroU64::new(111_000)).unwrap(); + assert_eq!( + captured( + store + .capture_evidence(input.clone(), &proof, &repeated) + .await + .unwrap() + ), + receipt + ); + originals.push((recipient, raw, receipt, first.attempt_id())); + } + store.close().await.unwrap(); + fixture.clock.now.store(151, Ordering::SeqCst); + let reopened = fixture.reopen(input).await; + for (recipient, raw, receipt, id) in originals { + let original = reopened + .signing_attempt( + selection(&binding, &prepared, digest, recipient), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(original.attempt_id(), id); + let recovered: CapturedSeal = reopened + .obtained_evidence( + selection(&binding, &prepared, digest, recipient), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(recovered.evidence().raw_json(), raw); + assert_eq!(recovered.receipt(), receipt); + assert!(matches!( + reopened + .claim_attempt( + selection(&binding, &prepared, digest, recipient), + copy(&proof) + ) + .await + .unwrap(), + ClaimAttemptOutcome::Retained(_) + )); + } + reopened.close().await.unwrap(); +} +#[tokio::test] +async fn late_revoked_expired_and_missing_clock_capture_retains_bytes_without_new_rights() { + for mode in 0..3 { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 131, false).await; + let first = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap(), + ); + let evidence = obtain(&first, true).await; + if mode == 0 { + fixture.clock.now.store(201, Ordering::SeqCst); + } + if mode == 1 { + store.revoke(input.clone(), &proof).await.unwrap(); + } + if mode == 2 { + fixture.clock.now.store(0, Ordering::SeqCst); + } + let receipt = captured( + store + .capture_evidence(input.clone(), &proof, &evidence) + .await + .unwrap(), + ); + assert_eq!(receipt.observed_at_unix_ms(), None); + assert!( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[1]), + copy(&proof) + ) + .await + .is_err() + ); + store.close().await.unwrap(); + let reopened = fixture.reopen(input.clone()).await; + assert_eq!( + captured( + reopened + .capture_evidence(input, &proof, &evidence) + .await + .unwrap() + ), + receipt + ); + reopened.close().await.unwrap(); + } +} +#[tokio::test] +async fn one_recipient_obtained_does_not_invent_the_other_and_failed_capture_keeps_caller_original() +{ + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 132, true).await; + let first = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap(), + ); + let evidence = obtain(&first, false).await; + let raw = evidence.raw_json().to_owned(); + assert!(raw.len() > 16384); + let second = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[1]), + copy(&proof), + ) + .await + .unwrap(), + ); + let mut database = fixture.database().await; + sqlx::raw_sql("CREATE TRIGGER refuse_evidence BEFORE INSERT ON seal_evidence_parts WHEN NEW.part=2 BEGIN SELECT RAISE(ABORT,'synthetic capture failure'); END").execute(&mut database).await.unwrap(); + assert!(matches!( + store + .capture_evidence(input.clone(), &proof, &evidence) + .await, + Err(OperationError::StorageFailure) + )); + assert_eq!(evidence.raw_json(), raw); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM seal_evidence") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(count, 0); + sqlx::raw_sql("DROP TRIGGER refuse_evidence") + .execute(&mut database) + .await + .unwrap(); + database.close().await.unwrap(); + captured( + store + .capture_evidence(input, &proof, &evidence) + .await + .unwrap(), + ); + assert!( + store + .obtained_evidence( + selection(&binding, &prepared, digest, recipients[1]), + copy(&proof) + ) + .await + .unwrap() + .is_none() + ); + assert!(matches!( + store + .claim_attempt( + selection(&binding, &prepared, digest, second.seal().recipient()), + copy(&proof) + ) + .await + .unwrap(), + ClaimAttemptOutcome::Retained(_) + )); + store.close().await.unwrap(); +} +#[tokio::test] +async fn verification_refuses_wrong_field_signature_and_binding_before_capture() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 133, false).await; + let first = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap(), + ); + let evidence = obtain(&first, false).await; + let second = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[1]), + copy(&proof), + ) + .await + .unwrap(), + ); + assert!(!evidence.matches_attempt(&second)); + for (field, value) in [ + ("sig", serde_json::json!("00".repeat(64))), + ("id", serde_json::json!("00".repeat(32))), + ("pubkey", serde_json::json!(keys(2).public_key().to_hex())), + ("content", serde_json::json!("changed")), + ("kind", serde_json::json!(14)), + ("created_at", serde_json::json!(98)), + ("tags", serde_json::json!([["p", "changed"]])), + ] { + let mut changed: serde_json::Value = serde_json::from_str(evidence.raw_json()).unwrap(); + changed[field] = value; + assert!( + matches!( + SealEvidence::verify(&first, &changed.to_string(), None), + Err(OperationError::InvalidEvidence) + ), + "{field}" + ); + } + assert!(SealEvidence::verify(&first, &"x".repeat(65537), None).is_err()); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn lost_claim_observer_reopens_as_retained_potential_issuance_not_a_second_dispatch() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 140, false).await; + let (arrived, resume) = fixture.clock.arm(1); + let mut first = store.claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ); + assert!(futures::poll!(first.as_mut()).is_pending()); + reached(arrived).await; + drop(first); + resume.send(()).unwrap(); + store.close().await.unwrap(); + let reopened = fixture.reopen(input).await; + assert!(matches!( + reopened + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof) + ) + .await + .unwrap(), + ClaimAttemptOutcome::Retained(_) + )); + assert!( + reopened + .obtained_evidence( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof) + ) + .await + .unwrap() + .is_none() + ); + reopened.close().await.unwrap(); +} +#[tokio::test] +async fn accepted_capture_survives_lost_observer_and_conservative_byte_exhaustion() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 141, true).await; + let first = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap(), + ); + let evidence = obtain(&first, true).await; + let mut database = fixture.database().await; + let transaction = database.begin_with("BEGIN IMMEDIATE").await.unwrap(); + let mut waiting = Vec::new(); + for _ in 0..16 { + let mut call = store.capture_evidence(input.clone(), &proof, &evidence); + assert!(futures::poll!(call.as_mut()).is_pending()); + waiting.push(call); + } + assert!(matches!( + store + .capture_evidence(input.clone(), &proof, &evidence) + .await, + Err(OperationError::Workspace(WorkspaceError::Unavailable)) + )); + drop(waiting.remove(0)); + transaction.rollback().await.unwrap(); + database.close().await.unwrap(); + let mut retained = None; + for call in waiting { + let receipt = captured(call.await.unwrap()); + if let Some(original) = retained { + assert_eq!(receipt, original); + } else { + retained = Some(receipt); + } + } + store.close().await.unwrap(); + let reopened = fixture.reopen(input).await; + let original = reopened + .obtained_evidence( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(original.evidence().raw_json(), evidence.raw_json()); + assert_eq!(Some(original.receipt()), retained); + reopened.close().await.unwrap(); +} +#[tokio::test] +async fn actual_claim_commit_uncertainty_latches_and_reopen_never_infers_a_safe_reissue() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 142, false).await; + let mut database = fixture.database().await; + sqlx::raw_sql("CREATE TABLE claim_commit_fault (parent INTEGER REFERENCES workspace_grant(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER claim_commit_fault_trigger AFTER INSERT ON signing_attempts BEGIN INSERT INTO claim_commit_fault VALUES(2); END").execute(&mut database).await.unwrap(); + database.close().await.unwrap(); + let outcome = store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap(); + match outcome { + ClaimAttemptOutcome::Unknown(anchor) => { + assert_eq!(anchor.operation_id(), prepared.identity().operation_id()); + assert_eq!( + anchor.command_digest(), + prepared.identity().command_digest() + ); + assert!(anchor.transaction_id().is_some()); + } + _ => panic!("unconfirmed commit must stay unknown"), + } + assert!(matches!( + store + .signing_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof) + ) + .await, + Err(OperationError::RecoveryRequired) + )); + store.close().await.unwrap(); + let mut database = fixture.database().await; + sqlx::raw_sql("DROP TRIGGER claim_commit_fault_trigger; DROP TABLE claim_commit_fault") + .execute(&mut database) + .await + .unwrap(); + database.close().await.unwrap(); + let reopened = fixture.reopen(input).await; + assert!( + reopened + .signing_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof) + ) + .await + .unwrap() + .is_none() + ); + reopened.close().await.unwrap(); +} +#[tokio::test] +async fn uncertain_capture_keeps_original_bytes_until_safe_reopen_and_exact_retry() { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 143, true).await; + let first = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap(), + ); + let evidence = obtain(&first, true).await; + let raw = evidence.raw_json().to_owned(); + let mut database = fixture.database().await; + sqlx::raw_sql("CREATE TRIGGER capture_unknown BEFORE INSERT ON seal_evidence_parts WHEN NEW.part=2 BEGIN SELECT RAISE(ROLLBACK,'synthetic unknown capture'); END").execute(&mut database).await.unwrap(); + database.close().await.unwrap(); + let outcome = store + .capture_evidence(input.clone(), &proof, &evidence) + .await + .unwrap(); + match outcome { + EvidenceCaptureOutcome::Unknown(anchor) => { + assert_eq!(anchor.operation_id(), prepared.identity().operation_id()); + assert_eq!( + anchor.command_digest(), + prepared.identity().command_digest() + ); + } + _ => panic!("uncertain capture must not report a known commit/rollback"), + } + assert_eq!(evidence.raw_json(), raw); + store.close().await.unwrap(); + let mut database = fixture.database().await; + sqlx::raw_sql("DROP TRIGGER capture_unknown") + .execute(&mut database) + .await + .unwrap(); + database.close().await.unwrap(); + let reopened = fixture.reopen(input.clone()).await; + captured( + reopened + .capture_evidence(input, &proof, &evidence) + .await + .unwrap(), + ); + let original = reopened + .obtained_evidence( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(original.evidence().raw_json(), raw); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn missing_preparation_plan_and_attempt_are_distinct_from_wrong_plan_identity() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create().await; + let request = peer_request(&binding, 145); + let operation = request.command().context().operation_id(); + let command = request.command().digest(); + let selector = + |digest| ClaimAttemptRequest::new(binding.clone(), operation, command, digest, key()); + assert!( + store + .signing_attempt(selector([0; 32]), copy(&proof)) + .await + .unwrap() + .is_none() + ); + assert!( + store + .obtained_evidence(selector([0; 32]), copy(&proof)) + .await + .unwrap() + .is_none() + ); + assert!(matches!( + store.claim_attempt(selector([0; 32]), copy(&proof)).await, + Err(OperationError::RecoveryRequired) + )); + let prepared = committed( + store + .admit_command_and_hold(request, copy(&proof)) + .await + .unwrap(), + ); + assert!( + store + .signing_attempt(selector([0; 32]), copy(&proof)) + .await + .unwrap() + .is_none() + ); + assert!( + store + .obtained_evidence(selector([0; 32]), copy(&proof)) + .await + .unwrap() + .is_none() + ); + let retained = plan(prepared.request().command(), 100, "missing-claim"); + let digest = *retained.digest(); + bound( + store + .bind_signing_intents(binding.clone(), retained, copy(&proof)) + .await + .unwrap(), + ); + assert!( + store + .signing_attempt(selector(digest), copy(&proof)) + .await + .unwrap() + .is_none() + ); + assert!( + store + .obtained_evidence(selector(digest), copy(&proof)) + .await + .unwrap() + .is_none() + ); + assert!(matches!( + store.claim_attempt(selector([0; 32]), copy(&proof)).await, + Err(OperationError::IdempotencyConflict) + )); + assert!(matches!( + store.signing_attempt(selector([0; 32]), copy(&proof)).await, + Err(OperationError::IdempotencyConflict) + )); + assert!(matches!( + store + .obtained_evidence(selector([0; 32]), copy(&proof)) + .await, + Err(OperationError::IdempotencyConflict) + )); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn fresh_claim_refuses_rollback_and_expiry_before_and_inside_the_transaction() { + for inside in [false, true] { + for now in [99, 150] { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 146, false).await; + let request = selection(&binding, &prepared, digest, recipients[0]); + let result = if inside { + let (arrived, resume) = fixture.clock.arm(1); + let mut call = store.claim_attempt(request, copy(&proof)); + assert!(futures::poll!(call.as_mut()).is_pending()); + reached(arrived).await; + fixture.clock.now.store(now, Ordering::SeqCst); + resume.send(()).unwrap(); + call.await + } else { + fixture.clock.now.store(now, Ordering::SeqCst); + store.claim_attempt(request, copy(&proof)).await + }; + assert!( + if now == 99 { + matches!( + result, + Err(OperationError::Workspace(WorkspaceError::Unavailable)) + ) + } else { + matches!(result, Err(OperationError::DeadlineExceeded)) + }, + "inside={inside} now={now}: {result:?}" + ); + fixture.clock.now.store(100, Ordering::SeqCst); + assert!( + store + .signing_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof) + ) + .await + .unwrap() + .is_none() + ); + store.close().await.unwrap(); + let mut database = fixture.database().await; + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_attempts") + .fetch_one(&mut database) + .await + .unwrap(); + assert_eq!(count, 0); + database.close().await.unwrap(); + } + } +} + +#[tokio::test] +async fn known_claim_insert_rollback_leaves_no_invocation_and_allows_one_new_claim() { + let fixture = Fixture::new(); + let (store, _, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, 147, false).await; + let mut database = fixture.database().await; + sqlx::raw_sql("CREATE TRIGGER refuse_claim BEFORE INSERT ON signing_attempts BEGIN SELECT RAISE(ABORT,'synthetic claim failure'); END").execute(&mut database).await.unwrap(); + assert!(matches!( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof) + ) + .await, + Err(OperationError::StorageFailure) + )); + assert!( + store + .signing_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof) + ) + .await + .unwrap() + .is_none() + ); + sqlx::raw_sql("DROP TRIGGER refuse_claim") + .execute(&mut database) + .await + .unwrap(); + let original = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap(), + ); + let retained = match store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap() + { + ClaimAttemptOutcome::Retained(value) => value, + _ => panic!("second claim must remain retained"), + }; + assert_eq!(retained.attempt_id(), original.attempt_id()); + database.close().await.unwrap(); + store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/tests/support/workspace_plans.rs b/crates/storage_sqlite/tests/support/workspace_plans.rs @@ -1,4 +1,6 @@ //! Native storage tests use real synthetic NIP-44 data, never host custody. +#[path = "workspace_issuance.rs"] +mod issuance; use super::*; use nostr::{JsonUtil, nips::nip44}; use radroots_domain::EnvelopeEventId; diff --git a/crates/storage_sqlite/tests/workspace_admission.rs b/crates/storage_sqlite/tests/workspace_admission.rs @@ -763,7 +763,7 @@ async fn predecessor_grant_only_schema_is_preserved_for_explicit_cutover() { store.close().await.unwrap(); let mut database = fixture.database().await; sqlx::raw_sql( - "DROP TABLE signing_plan_parts; DROP TABLE signing_plans; DROP INDEX operation_transaction_identity; DROP TABLE operations; PRAGMA user_version=1", + "DROP TABLE seal_evidence_parts; DROP TABLE seal_evidence; DROP TABLE signing_attempts; DROP TABLE signing_plan_parts; DROP TABLE signing_plans; DROP INDEX operation_transaction_identity; DROP TABLE operations; PRAGMA user_version=1", ) .execute(&mut database) .await