commit 2b90ccb46a99d153e76867acc19e2a275cb52a08 parent 6a0c73088160a4aec68cb84036fbc2eb859dda52 Author: triesap <tyson@radroots.org> Date: Sat, 10 Oct 2026 08:30:35 +0000 profile: preserve complete metadata during typed edits - Keep untouched admitted fields and require an exact current baseline - Verify retained media and bound complete replacement plans - Add an explicit profile edit registry without changing version seven - Verify signing and durable provider reconstruction Diffstat:
23 files changed, 1322 insertions(+), 11 deletions(-)
diff --git a/contracts/api_baselines/radroots_event.txt b/contracts/api_baselines/radroots_event.txt @@ -441,6 +441,10 @@ pub fn radroots_event::calendar::canonical_calendar_geohash_is_valid(&str) -> bo pub fn radroots_event::calendar::canonical_calendar_tag_text_is_valid(&str) -> bool pub fn radroots_event::calendar::covered_utc_days(u64, core::option::Option<u64>) -> core::result::Result<core::ops::range::RangeInclusive<u64>, radroots_event::calendar::CalendarEventError> pub mod radroots_event::contract +pub mod radroots_event::contract::registry_v8 +pub const radroots_event::contract::registry_v8::PROFILE_METADATA_EDIT_CONTRACT_ID: &str +pub const fn radroots_event::contract::registry_v8::all_event_contracts_registry_v8() -> &'static [super::EventContract] +pub fn radroots_event::contract::registry_v8::event_contract_registry_v8(&str) -> core::option::Option<&'static super::EventContract> pub enum radroots_event::contract::ContractIdentityError pub radroots_event::contract::ContractIdentityError::ContractIdMissing pub radroots_event::contract::ContractIdentityError::ContractIdNamespace @@ -484,6 +488,7 @@ pub struct radroots_event::contract::RegistryVersion(_) impl radroots_event::contract::RegistryVersion pub const radroots_event::contract::RegistryVersion::CURRENT: Self pub const radroots_event::contract::RegistryVersion::V7: Self +pub const radroots_event::contract::RegistryVersion::V8: Self pub const fn radroots_event::contract::RegistryVersion::get(self) -> u32 pub const fn radroots_event::contract::RegistryVersion::new(u32) -> core::result::Result<Self, radroots_event::contract::ContractIdentityError> impl core::fmt::Display for radroots_event::contract::RegistryVersion @@ -2459,6 +2464,24 @@ pub radroots_event::profile::account::AccountClaim::nip05: core::option::Option< pub radroots_event::profile::account::AccountClaim::pubkey: alloc::string::String pub radroots_event::profile::account::AccountClaim::username: alloc::string::String pub const radroots_event::profile::account::KIND_ACCOUNT_CLAIM: u32 +pub mod radroots_event::profile::edit +pub enum radroots_event::profile::edit::ProfileFieldChange<T> +pub radroots_event::profile::edit::ProfileFieldChange::Clear +pub radroots_event::profile::edit::ProfileFieldChange::Keep +pub radroots_event::profile::edit::ProfileFieldChange::Set(T) +pub enum radroots_event::profile::edit::ProfileMediaChange +pub radroots_event::profile::edit::ProfileMediaChange::Clear +pub radroots_event::profile::edit::ProfileMediaChange::Keep +pub radroots_event::profile::edit::ProfileMediaChange::KeepVerified(radroots_event::media::AuthoredImage) +pub radroots_event::profile::edit::ProfileMediaChange::Set(radroots_event::media::AuthoredImage) +pub struct radroots_event::profile::edit::ProfileEdit +pub radroots_event::profile::edit::ProfileEdit::about: radroots_event::profile::edit::ProfileFieldChange<alloc::string::String> +pub radroots_event::profile::edit::ProfileEdit::banner: radroots_event::profile::edit::ProfileMediaChange +pub radroots_event::profile::edit::ProfileEdit::bot: radroots_event::profile::edit::ProfileFieldChange<bool> +pub radroots_event::profile::edit::ProfileEdit::display_name: radroots_event::profile::edit::ProfileFieldChange<alloc::string::String> +pub radroots_event::profile::edit::ProfileEdit::name: radroots_event::profile::edit::ProfileFieldChange<alloc::string::String> +pub radroots_event::profile::edit::ProfileEdit::nip05: radroots_event::profile::edit::ProfileFieldChange<radroots_event::profile::Nip05Identifier> +pub radroots_event::profile::edit::ProfileEdit::picture: radroots_event::profile::edit::ProfileMediaChange #[non_exhaustive] pub enum radroots_event::profile::AuthoredProfileError pub radroots_event::profile::AuthoredProfileError::InvalidName impl radroots_event::profile::AuthoredProfileError diff --git a/contracts/api_baselines/radroots_event_codec.txt b/contracts/api_baselines/radroots_event_codec.txt @@ -261,6 +261,8 @@ pub fn radroots_event_codec::authoring::AuthoredEventPlan::from_profile(&radroot pub fn radroots_event_codec::authoring::AuthoredEventPlan::from_rhi_evidence_attestation(&radroots_event_codec::decode::rhi::RadrootsRhiEvidenceAttestationV1, u64) -> core::result::Result<Self, radroots_event_codec::authoring::AuthoredPlanError> pub fn radroots_event_codec::authoring::AuthoredEventPlan::from_trade_mutation(radroots_event::trade::TradeMutationEnvelopeV1) -> core::result::Result<Self, radroots_event_codec::authoring::AuthoredPlanError> pub fn radroots_event_codec::authoring::AuthoredEventPlan::from_update(&radroots_event::post::AuthoredUpdate, u64, impl core::convert::AsRef<str>) -> core::result::Result<Self, radroots_event_codec::authoring::AuthoredPlanError> +impl radroots_event_codec::authoring::AuthoredEventPlan +pub fn radroots_event_codec::authoring::AuthoredEventPlan::from_profile_edit(&radroots_event_codec::admission::profile::RadrootsAdmittedProfileEvent, &radroots_event_codec::admission::profile::RadrootsAdmittedProfileEvent, &radroots_event::profile::edit::ProfileEdit, u64, impl core::convert::AsRef<str>) -> core::result::Result<Self, radroots_event_codec::encode::profile::ProfileEditError> pub struct radroots_event_codec::authoring::BlossomAuthorizationPlan impl radroots_event_codec::authoring::BlossomAuthorizationPlan pub const fn radroots_event_codec::authoring::BlossomAuthorizationPlan::author(&self) -> &radroots_identity::key::PublicKey @@ -1014,6 +1016,29 @@ pub fn radroots_event_codec::encode::post::authored_ask_to_wire_parts(&radroots_ pub fn radroots_event_codec::encode::post::authored_photo_update_to_wire_parts(&radroots_event::post::AuthoredPhotoUpdate) -> radroots_event::wire::v1::Nip01EventWireParts pub fn radroots_event_codec::encode::post::authored_update_to_wire_parts(&radroots_event::post::AuthoredUpdate) -> radroots_event::wire::v1::Nip01EventWireParts pub mod radroots_event_codec::encode::profile +#[non_exhaustive] pub enum radroots_event_codec::encode::profile::ProfileEditError +pub radroots_event_codec::encode::profile::ProfileEditError::AuthorMismatch +pub radroots_event_codec::encode::profile::ProfileEditError::BaselineTagsUnsupported +pub radroots_event_codec::encode::profile::ProfileEditError::ContentTooLarge +pub radroots_event_codec::encode::profile::ProfileEditError::ContentTooLarge::actual: usize +pub radroots_event_codec::encode::profile::ProfileEditError::ContentTooLarge::max: usize +pub radroots_event_codec::encode::profile::ProfileEditError::DurableWireTooLarge +pub radroots_event_codec::encode::profile::ProfileEditError::DurableWireTooLarge::actual: usize +pub radroots_event_codec::encode::profile::ProfileEditError::DurableWireTooLarge::max: usize +pub radroots_event_codec::encode::profile::ProfileEditError::InvalidMetadata +pub radroots_event_codec::encode::profile::ProfileEditError::InvalidName +pub radroots_event_codec::encode::profile::ProfileEditError::MediaVerificationMismatch +pub radroots_event_codec::encode::profile::ProfileEditError::MediaVerificationMismatch::field: &'static str +pub radroots_event_codec::encode::profile::ProfileEditError::MediaVerificationRequired +pub radroots_event_codec::encode::profile::ProfileEditError::MediaVerificationRequired::field: &'static str +pub radroots_event_codec::encode::profile::ProfileEditError::Plan(radroots_event_codec::authoring::AuthoredPlanError) +pub radroots_event_codec::encode::profile::ProfileEditError::StaleBaseline +pub radroots_event_codec::encode::profile::ProfileEditError::TimestampNotAdvancing +impl radroots_event_codec::encode::profile::ProfileEditError +pub const fn radroots_event_codec::encode::profile::ProfileEditError::code(&self) -> &'static str +impl core::error::Error for radroots_event_codec::encode::profile::ProfileEditError +impl core::fmt::Display for radroots_event_codec::encode::profile::ProfileEditError +pub fn radroots_event_codec::encode::profile::ProfileEditError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result #[non_exhaustive] pub enum radroots_event_codec::encode::profile::RadrootsAuthoredProfileEncodeError pub radroots_event_codec::encode::profile::RadrootsAuthoredProfileEncodeError::ContentTooLarge pub radroots_event_codec::encode::profile::RadrootsAuthoredProfileEncodeError::ContentTooLarge::actual: usize diff --git a/contracts/architecture/decisions/profile_complete_edit.v1.json b/contracts/architecture/decisions/profile_complete_edit.v1.json @@ -0,0 +1,16 @@ +{ + "schema_version": 1, + "decision_id": "radroots.profile.complete_edit.v1", + "status": "approved_scope_implementation", + "contract_id": "radroots.profile.metadata_edit.v1", + "explicit_registry_version": 8, + "default_registry_version_unchanged": 7, + "current_managed_authoring_policy": "One private shared lookup admits supported explicit V8 authorable contracts (unchanged V7 plus profile edit). Current authority and role validation use it while retaining host decisions, deprecation, actor/source, deadline and cancellation checks. Embedded historical registry membership alone is not current signing permission.", + "domain": "Typed keep/set/clear for seven profile fields; no unknown or raw-JSON setter.", + "baseline": "Exact verified admitted canonical kind-0 head, matching expected author and advancing timestamp. Nonempty baseline tags refuse. Runtime persists and rechecks the actual canonical baseline before signing or side effects.", + "preservation": "Every untouched raw JSON field value remains exact, including residual wrong types, nested duplicate names and numeric lexemes. Top-level duplicate keys remain rejected.", + "media": "Kept string media requires matching byte-verified image proof. Explicit clear or typed replacement is supported. Proof does not establish BUD-02 completion, network availability or image decode safety.", + "bounds": { "content_utf8_bytes": 131072, "durable_wire_bytes": 262144 }, + "history": "V7 source/inventory/vectors and existing strict initial/full-replacement authoring remain unchanged. V8 inherits exact V7 inventory and adds only the profile-edit operation. Existing generic signing and durable storage semantics apply.", + "exclusions": ["App editor policy", "new database", "new worker", "unknown-field authoring", "implicit trust promotion", "publication authorization"] +} diff --git a/contracts/events/profile-metadata.md b/contracts/events/profile-metadata.md @@ -101,6 +101,30 @@ lowest canonical event id, independent of relay or ingestion arrival order. ## Tolerant inbound boundary +### Complete-profile edit + +`AuthoredEventPlan::from_profile_edit` adds an explicit registry-v8 +`radroots.profile.metadata_edit.v1` operation. Registry-v7 defaults, +inventories, strict authoring and historical vectors remain unchanged. +`ProfileEdit` accepts typed keep/set/clear intent for the seven known fields. +Unknown and wrong-typed untouched values remain exact raw JSON values, +including nested duplicate names and numeric lexemes. There is no unknown-field +or raw-JSON setter. A kept string picture/banner requires a matching +byte-verified `AuthoredImage`; unsupported references refuse unless explicitly +cleared or replaced. Upload completion and decode safety remain runtime gates. + +The baseline and current head must be verified admitted kind-0 events from the +expected author with the same exact event id. Output time must advance; nonempty +baseline tags refuse rather than disappear. The runtime must supply its actual +canonical head, persist the baseline id and recheck it before signing or side +effects. The pure codec comparison does not provide storage CAS. + +Output is a complete tagless replacement, sorted by top-level field name, +bounded to 131072 content bytes and 262144 serialized durable-plan bytes. +Explicit clear removes a field. A set name retains strict name validation; +untouched admitted values retain their original meaning and trust state. +Existing initial/full-replacement authoring remains available. + `profile.parse_inbound_metadata` accepts a JSON object of at most 131072 UTF-8 bytes without requiring `name`. Correctly typed `name`, `display_name`, `about`, `picture`, `banner`, `nip05`, and `bot` fields are projected without JSON type diff --git a/crates/event/src/contract.rs b/crates/event/src/contract.rs @@ -13,6 +13,9 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION"); #[doc(hidden)] pub mod registry_v7; +/// Explicit profile-edit registry; the default registry remains frozen v7. +pub mod registry_v8; + pub use registry_v7::*; /// Maximum UTF-8 byte length of a versioned Radroots event-contract ID. @@ -86,6 +89,7 @@ pub struct RegistryVersion(u32); impl RegistryVersion { /// Frozen registry profile used by the initial authored-plan storage wire. pub const V7: Self = Self(7); + pub const V8: Self = Self(8); pub const CURRENT: Self = Self(RADROOTS_EVENT_CONTRACT_REGISTRY_VERSION); pub const fn new(value: u32) -> Result<Self, ContractIdentityError> { @@ -125,6 +129,7 @@ impl ContractKey { ) -> Result<Self, ContractIdentityError> { let contract = match registry_version { RegistryVersion::V7 => event_contract_registry_v7(contract_id.as_str()), + RegistryVersion::V8 => registry_v8::event_contract_registry_v8(contract_id.as_str()), _ => { return Err(ContractIdentityError::UnsupportedRegistryVersion { actual: registry_version.get(), @@ -157,6 +162,10 @@ impl ContractKey { match self.registry_version { RegistryVersion::V7 => event_contract_registry_v7(self.contract_id.as_str()) .expect("validated registry-v7 contract key must remain resolvable"), + RegistryVersion::V8 => { + registry_v8::event_contract_registry_v8(self.contract_id.as_str()) + .expect("validated registry-v8 contract key must remain resolvable") + } _ => unreachable!("validated contract key must have a supported registry profile"), } } @@ -327,10 +336,10 @@ mod identity_tests { ); assert!(matches!( ContractKey::new( - RegistryVersion::new(8).expect("nonzero version"), + RegistryVersion::new(9).expect("nonzero version"), ContractId::parse("radroots.social.geochat.v1").expect("contract ID") ), - Err(ContractIdentityError::UnsupportedRegistryVersion { actual: 8 }) + Err(ContractIdentityError::UnsupportedRegistryVersion { actual: 9 }) )); assert!(matches!( ContractKey::current("radroots.social.unknown.v1"), @@ -351,7 +360,7 @@ mod identity_tests { invalid["registry_version"] = serde_json::json!(0); assert!(serde_json::from_value::<ContractKey>(invalid).is_err()); let mut invalid = value.clone(); - invalid["registry_version"] = serde_json::json!(8); + invalid["registry_version"] = serde_json::json!(9); assert!(serde_json::from_value::<ContractKey>(invalid).is_err()); let mut invalid = value.clone(); invalid["contract_id"] = serde_json::json!("radroots.social.unknown.v1"); diff --git a/crates/event/src/contract/registry_v8.rs b/crates/event/src/contract/registry_v8.rs @@ -0,0 +1,30 @@ +//! Immutable explicit registry v8: unchanged v7 contracts plus complete-profile edit. + +use super::{EventContract, all_event_contracts_registry_v7}; + +pub const PROFILE_METADATA_EDIT_CONTRACT_ID: &str = "radroots.profile.metadata_edit.v1"; + +const COUNT: usize = all_event_contracts_registry_v7().len() + 1; +static CONTRACTS: [EventContract; COUNT] = { + let inherited = all_event_contracts_registry_v7(); + let mut contracts = [inherited[0]; COUNT]; + let mut index = 0; + while index < inherited.len() { + contracts[index] = inherited[index]; + index += 1; + } + let mut edit = inherited[0]; + edit.id = PROFILE_METADATA_EDIT_CONTRACT_ID; + edit.name = "Complete Profile Metadata Edit"; + edit.payload_type = "ProfileEdit / RadrootsAdmittedProfileEvent"; + contracts[index] = edit; + contracts +}; + +pub const fn all_event_contracts_registry_v8() -> &'static [EventContract] { + &CONTRACTS +} + +pub fn event_contract_registry_v8(id: &str) -> Option<&'static EventContract> { + CONTRACTS.iter().find(|contract| contract.id == id) +} diff --git a/crates/event/src/profile.rs b/crates/event/src/profile.rs @@ -1,5 +1,7 @@ //! Profile and account event models. +pub mod edit; + #[cfg(not(feature = "std"))] use alloc::string::String; use core::{fmt, str::FromStr}; diff --git a/crates/event/src/profile/edit.rs b/crates/event/src/profile/edit.rs @@ -0,0 +1,39 @@ +//! Typed intent for complete kind-0 edits against a verified baseline. + +#[cfg(not(feature = "std"))] +use alloc::string::String; + +use crate::{media::AuthoredImage, profile::Nip05Identifier}; + +/// Preserve the exact admitted value, explicitly replace it, or remove it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum ProfileFieldChange<T> { + #[default] + Keep, + Set(T), + Clear, +} + +/// Keeping string media requires proof for its exact existing descriptor URL. +/// Upload completion and image decode safety remain runtime responsibilities. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum ProfileMediaChange { + #[default] + Keep, + KeepVerified(AuthoredImage), + Set(AuthoredImage), + Clear, +} + +/// Only these fields can change; unknown admitted metadata is always preserved. +/// String lengths, name syntax and baseline freshness are checked by the codec. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ProfileEdit { + pub name: ProfileFieldChange<String>, + pub display_name: ProfileFieldChange<String>, + pub about: ProfileFieldChange<String>, + pub picture: ProfileMediaChange, + pub banner: ProfileMediaChange, + pub nip05: ProfileFieldChange<Nip05Identifier>, + pub bot: ProfileFieldChange<bool>, +} diff --git a/crates/event_codec/Cargo.toml b/crates/event_codec/Cargo.toml @@ -61,6 +61,7 @@ serde = { workspace = true, default-features = false, features = [ ], optional = true } serde_json = { workspace = true, default-features = false, features = [ "alloc", + "raw_value", ], optional = true } secp256k1 = { workspace = true } hex = { version = "0.4", default-features = false, features = ["alloc"] } diff --git a/crates/event_codec/src/authoring/typed.rs b/crates/event_codec/src/authoring/typed.rs @@ -175,6 +175,14 @@ impl std::error::Error for AuthoredPlanError {} impl AuthoredEventBody { #[cfg(feature = "json")] + pub(crate) fn from_profile_edit_parts( + contract: ContractKey, + wire: Nip01EventWireParts, + ) -> Result<Self, AuthoredPlanError> { + build_typed_body_for_key(contract, wire) + } + + #[cfg(feature = "json")] pub fn from_profile(profile: &AuthoredProfile) -> Result<Self, AuthoredPlanError> { let wire = authored_profile_to_wire_parts(profile).map_err(AuthoredPlanError::Profile)?; build_typed_body("radroots.profile.metadata.v1", wire) @@ -441,6 +449,14 @@ fn build_typed_body( ) -> Result<AuthoredEventBody, AuthoredPlanError> { let contract = ContractKey::current(contract_id).map_err(AuthoredPlanError::ContractIdentity)?; + build_typed_body_for_key(contract, wire) +} + +fn build_typed_body_for_key( + contract: ContractKey, + wire: Nip01EventWireParts, +) -> Result<AuthoredEventBody, AuthoredPlanError> { + let contract_id = contract.contract_id().as_str(); let definition = contract.contract(); if definition.authoring_policy() != EventAuthoringPolicy::TypedOnly { return Err(AuthoredPlanError::ContractNotTyped { @@ -480,6 +496,9 @@ pub(super) fn validate_historical_typed_profile( match contract_id { #[cfg(feature = "json")] "radroots.profile.metadata.v1" => validate_profile(tags, content), + "radroots.profile.metadata_edit.v1" => { + crate::profile::edit::validate_historical(tags, content) + } "radroots.social.update.v1" => validate_update(tags, content), "radroots.social.photo_update.v1" => { validate_post_profile(RadrootsPostClassification::PhotoUpdate, tags, content) diff --git a/crates/event_codec/src/authoring/wire.rs b/crates/event_codec/src/authoring/wire.rs @@ -463,11 +463,11 @@ mod tests { PlanWireV1::from_json(&schema), Err(PlanDecodeError::UnsupportedSchemaVersion { actual: 2 }) ); - let registry = mutate(|value| value["contract_registry_version"] = json!(8)); + let registry = mutate(|value| value["contract_registry_version"] = json!(9)); assert!(matches!( PlanWireV1::from_json(®istry), Err(PlanDecodeError::ContractIdentity( - ContractIdentityError::UnsupportedRegistryVersion { actual: 8 } + ContractIdentityError::UnsupportedRegistryVersion { actual: 9 } )) )); } diff --git a/crates/event_codec/src/encode.rs b/crates/event_codec/src/encode.rs @@ -115,6 +115,7 @@ pub mod post { #[cfg(feature = "json")] pub mod profile { pub use crate::profile::authored::*; + pub use crate::profile::edit::ProfileEditError; } pub mod reply { diff --git a/crates/event_codec/src/profile/edit.rs b/crates/event_codec/src/profile/edit.rs @@ -0,0 +1,274 @@ +//! Complete-profile replacement with exact verified-baseline and media fences. + +#[cfg(not(feature = "std"))] +use alloc::{ + boxed::Box, + collections::BTreeMap, + string::{String, ToString}, + vec::Vec, +}; +#[cfg(feature = "std")] +use std::{boxed::Box, collections::BTreeMap, string::String, vec::Vec}; + +use core::fmt; +use radroots_event::{ + contract::{ + ContractId, ContractKey, RegistryVersion, registry_v8::PROFILE_METADATA_EDIT_CONTRACT_ID, + }, + profile::{ + AuthoredProfile, Nip05Identifier, RADROOTS_PROFILE_METADATA_MAX_CONTENT_BYTES, + edit::{ProfileEdit, ProfileFieldChange, ProfileMediaChange}, + }, + wire::Nip01EventWireParts, +}; +use radroots_identity::PublicKey; +use serde::Serialize; +use serde_json::value::RawValue; + +use super::{admission::RadrootsAdmittedProfileEvent, inbound::parse_inbound_profile_metadata}; +use crate::authoring::{ + AuthoredEventBody, AuthoredEventPlan, AuthoredPlanError, PLAN_WIRE_MAX_BYTES, PlanWireV1, +}; + +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ProfileEditError { + StaleBaseline, + AuthorMismatch, + BaselineTagsUnsupported, + TimestampNotAdvancing, + InvalidName, + ContentTooLarge { max: usize, actual: usize }, + DurableWireTooLarge { max: usize, actual: usize }, + MediaVerificationRequired { field: &'static str }, + MediaVerificationMismatch { field: &'static str }, + InvalidMetadata, + Plan(AuthoredPlanError), +} + +impl ProfileEditError { + pub const fn code(&self) -> &'static str { + match self { + Self::StaleBaseline => "stale_profile_baseline", + Self::AuthorMismatch => "profile_author_mismatch", + Self::BaselineTagsUnsupported => "profile_baseline_tags_unsupported", + Self::TimestampNotAdvancing => "profile_timestamp_not_advancing", + Self::InvalidName => "invalid_name", + Self::ContentTooLarge { .. } => "content_too_large", + Self::DurableWireTooLarge { .. } => "profile_durable_wire_too_large", + Self::MediaVerificationRequired { .. } => "profile_media_verification_required", + Self::MediaVerificationMismatch { .. } => "profile_media_verification_mismatch", + Self::InvalidMetadata => "profile_edit_invalid_metadata", + Self::Plan(error) => error.code(), + } + } +} + +impl fmt::Display for ProfileEditError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ContentTooLarge { max, actual } | Self::DurableWireTooLarge { max, actual } => { + write!(formatter, "{}: {actual} bytes exceeds {max}", self.code()) + } + Self::MediaVerificationRequired { field } + | Self::MediaVerificationMismatch { field } => { + write!(formatter, "{}: {field}", self.code()) + } + Self::Plan(error) => write!(formatter, "{error}"), + _ => formatter.write_str(self.code()), + } + } +} + +#[cfg(feature = "std")] +impl std::error::Error for ProfileEditError {} + +type RawFields = BTreeMap<String, Box<RawValue>>; + +impl AuthoredEventPlan { + /// Builds a complete replacement from the exact verified canonical head. + /// + /// The runtime must read the real canonical head, persist its baseline id, + /// and recheck it before signing/side effects. This pure comparison is not + /// a storage CAS. Kept media proof is not upload-completion evidence. + pub fn from_profile_edit( + baseline: &RadrootsAdmittedProfileEvent, + current_head: &RadrootsAdmittedProfileEvent, + edit: &ProfileEdit, + created_at: u64, + expected_author: impl AsRef<str>, + ) -> Result<Self, ProfileEditError> { + let author = PublicKey::from_hex(expected_author.as_ref()) + .map_err(|_| ProfileEditError::AuthorMismatch)?; + if baseline.event().author() != &author || current_head.event().author() != &author { + return Err(ProfileEditError::AuthorMismatch); + } + if baseline.event().id() != current_head.event().id() { + return Err(ProfileEditError::StaleBaseline); + } + if !baseline.event().tags_as_vec().is_empty() { + return Err(ProfileEditError::BaselineTagsUnsupported); + } + if created_at <= baseline.event().created_at_u64() { + return Err(ProfileEditError::TimestampNotAdvancing); + } + for change in [&edit.name, &edit.display_name, &edit.about] { + if let ProfileFieldChange::Set(value) = change { + check_content_size(value.len())?; + } + } + if let ProfileFieldChange::Set(name) = &edit.name { + AuthoredProfile::new(name).map_err(|_| ProfileEditError::InvalidName)?; + } + let mut fields: RawFields = serde_json::from_str(baseline.metadata().raw_content()) + .map_err(|_| ProfileEditError::InvalidMetadata)?; + apply_field(&mut fields, "name", &edit.name)?; + apply_field(&mut fields, "display_name", &edit.display_name)?; + apply_field(&mut fields, "about", &edit.about)?; + apply_media(&mut fields, "picture", &edit.picture)?; + apply_media(&mut fields, "banner", &edit.banner)?; + apply_nip05(&mut fields, &edit.nip05)?; + apply_field(&mut fields, "bot", &edit.bot)?; + let content = + serde_json::to_string(&fields).map_err(|_| ProfileEditError::InvalidMetadata)?; + check_content_size(content.len())?; + let contract = ContractKey::new( + RegistryVersion::V8, + ContractId::parse(PROFILE_METADATA_EDIT_CONTRACT_ID).map_err(|error| { + ProfileEditError::Plan(AuthoredPlanError::ContractIdentity(error)) + })?, + ) + .map_err(|error| ProfileEditError::Plan(AuthoredPlanError::ContractIdentity(error)))?; + let body = AuthoredEventBody::from_profile_edit_parts( + contract, + Nip01EventWireParts { + kind: 0, + tags: Vec::new(), + content, + }, + ) + .map_err(ProfileEditError::Plan)?; + let plan = Self::bind(body, created_at, author.to_hex()).map_err(ProfileEditError::Plan)?; + let bytes = PlanWireV1::from_plan(&plan) + .to_json() + .map_err(|_| ProfileEditError::InvalidMetadata)?; + if bytes.len() > PLAN_WIRE_MAX_BYTES { + return Err(ProfileEditError::DurableWireTooLarge { + max: PLAN_WIRE_MAX_BYTES, + actual: bytes.len(), + }); + } + Ok(plan) + } +} + +fn check_content_size(actual: usize) -> Result<(), ProfileEditError> { + if actual > RADROOTS_PROFILE_METADATA_MAX_CONTENT_BYTES { + return Err(ProfileEditError::ContentTooLarge { + max: RADROOTS_PROFILE_METADATA_MAX_CONTENT_BYTES, + actual, + }); + } + Ok(()) +} + +fn set_value<T: Serialize + ?Sized>( + fields: &mut RawFields, + name: &str, + value: &T, +) -> Result<(), ProfileEditError> { + let raw = + serde_json::value::to_raw_value(value).map_err(|_| ProfileEditError::InvalidMetadata)?; + check_content_size(raw.get().len())?; + fields.insert(name.to_string(), raw); + Ok(()) +} + +fn apply_field<T: Serialize>( + fields: &mut RawFields, + name: &str, + change: &ProfileFieldChange<T>, +) -> Result<(), ProfileEditError> { + match change { + ProfileFieldChange::Keep => Ok(()), + ProfileFieldChange::Set(value) => set_value(fields, name, value), + ProfileFieldChange::Clear => { + fields.remove(name); + Ok(()) + } + } +} + +fn apply_nip05( + fields: &mut RawFields, + change: &ProfileFieldChange<Nip05Identifier>, +) -> Result<(), ProfileEditError> { + match change { + ProfileFieldChange::Keep => Ok(()), + ProfileFieldChange::Set(value) => set_value(fields, "nip05", value.as_str()), + ProfileFieldChange::Clear => { + fields.remove("nip05"); + Ok(()) + } + } +} + +fn apply_media( + fields: &mut RawFields, + name: &'static str, + change: &ProfileMediaChange, +) -> Result<(), ProfileEditError> { + match change { + ProfileMediaChange::Clear => { + fields.remove(name); + Ok(()) + } + ProfileMediaChange::Set(image) => { + set_value(fields, name, image.descriptor().url().as_str()) + } + ProfileMediaChange::Keep | ProfileMediaChange::KeepVerified(_) => { + let existing = fields + .get(name) + .and_then(|raw| serde_json::from_str::<String>(raw.get()).ok()); + match (existing, change) { + (Some(value), ProfileMediaChange::KeepVerified(image)) + if value == image.descriptor().url().as_str() => + { + Ok(()) + } + (Some(_), ProfileMediaChange::KeepVerified(_)) => { + Err(ProfileEditError::MediaVerificationMismatch { field: name }) + } + (Some(_), _) => Err(ProfileEditError::MediaVerificationRequired { field: name }), + (None, ProfileMediaChange::KeepVerified(_)) => { + Err(ProfileEditError::MediaVerificationMismatch { field: name }) + } + (None, _) => Ok(()), + } + } + } +} + +pub(crate) fn validate_historical(tags: &[Vec<String>], content: &str) -> Result<(), String> { + if !tags.is_empty() { + return Err("profile_tags_forbidden".to_string()); + } + let profile = + parse_inbound_profile_metadata(content).map_err(|error| error.code().to_string())?; + if profile + .picture() + .into_iter() + .chain(profile.banner()) + .any(|media| radroots_blossom::BlobUrl::parse(media.as_str()).is_err()) + { + return Err("profile_media_url_invalid".to_string()); + } + let fields: RawFields = + serde_json::from_str(content).map_err(|_| "profile_json_decode".to_string())?; + let canonical = + serde_json::to_string(&fields).map_err(|_| "profile_json_encode".to_string())?; + if canonical != content { + return Err("profile_edit_noncanonical".to_string()); + } + Ok(()) +} diff --git a/crates/event_codec/src/profile/mod.rs b/crates/event_codec/src/profile/mod.rs @@ -5,4 +5,7 @@ pub mod admission; pub mod authored; #[cfg(feature = "json")] +pub mod edit; + +#[cfg(feature = "json")] pub mod inbound; diff --git a/crates/event_codec/tests/profile_complete_edit.rs b/crates/event_codec/tests/profile_complete_edit.rs @@ -0,0 +1,447 @@ +#![cfg(feature = "json")] + +use nostr::{EventBuilder, Keys, Kind, Timestamp}; +use radroots_blossom::{BlobDescriptor, BlobUrl, MediaType, Sha256}; +use radroots_event::{ + contract::{ + ContractId, ContractKey, RegistryVersion, all_event_contracts, + registry_v8::{PROFILE_METADATA_EDIT_CONTRACT_ID, all_event_contracts_registry_v8}, + }, + envelope::{EventEnvelope, EventEnvelopeParts}, + media::AuthoredImage, + profile::{ + AuthoredProfile, Nip05Identifier, RADROOTS_PROFILE_METADATA_MAX_CONTENT_BYTES, + edit::{ProfileEdit, ProfileFieldChange as Change, ProfileMediaChange as Media}, + }, +}; +use radroots_event_codec::{ + admission::profile::{RadrootsAdmittedProfileEvent, verify_and_admit_profile_event}, + authoring::{AuthoredEventPlan, PLAN_WIRE_MAX_BYTES, PlanWireV1}, + encode::profile::ProfileEditError, +}; +use serde_json::{Value, value::RawValue}; +use std::collections::BTreeMap; + +fn keys() -> Keys { + Keys::parse("0101010101010101010101010101010101010101010101010101010101010101").unwrap() +} + +fn envelope(content: &str, time: u64, tags: Vec<Vec<String>>, signer: &Keys) -> EventEnvelope { + let event = EventBuilder::new(Kind::Metadata, content) + .custom_created_at(Timestamp::from_secs(time)) + .tags(tags.into_iter().map(|tag| nostr::Tag::parse(tag).unwrap())) + .sign_with_keys(signer) + .unwrap(); + EventEnvelope::new(EventEnvelopeParts { + id: event.id.to_hex(), + author: event.pubkey.to_hex(), + created_at: event.created_at.as_secs(), + kind: 0, + tags: event + .tags + .as_slice() + .iter() + .map(|tag| tag.as_slice().to_vec()) + .collect(), + content: event.content, + sig: event.sig.to_string(), + }) + .unwrap() +} + +fn admitted(content: &str, time: u64) -> RadrootsAdmittedProfileEvent { + verify_and_admit_profile_event(envelope(content, time, vec![], &keys())).unwrap() +} + +fn plan( + baseline: &RadrootsAdmittedProfileEvent, + edit: &ProfileEdit, +) -> Result<AuthoredEventPlan, ProfileEditError> { + AuthoredEventPlan::from_profile_edit( + baseline, + baseline, + edit, + baseline.event().created_at_u64() + 1, + keys().public_key().to_hex(), + ) +} + +fn image(bytes: &[u8]) -> AuthoredImage { + let hash = Sha256::digest(bytes); + let media = MediaType::parse("image/webp").unwrap(); + AuthoredImage::try_from( + BlobDescriptor::new( + BlobUrl::parse(&format!("https://media.example/{hash}.webp")).unwrap(), + hash, + bytes.len() as u64, + media.clone(), + 100, + ) + .unwrap() + .approve_reference() + .unwrap() + .verify_bytes(bytes, &media) + .unwrap(), + ) + .unwrap() +} + +#[test] +fn profile_complete_edit_display_only_preserves_all_untouched_metadata_and_signed_roundtrip() { + let picture = image(b"picture"); + let banner = image(b"banner"); + let content = format!( + r#"{{"name":"farm","display_name":"Old","about":"grows food","picture":"{}","banner":"{}","nip05":"farm@EXAMPLE.COM","bot":false,"website":"https://example.com","birthday":{{ "year":1900, "year":2000 }},"custom":900719925474099312345,"lud16":null}}"#, + picture.descriptor().url(), + banner.descriptor().url() + ); + let base = admitted(&content, 100); + let edit = ProfileEdit { + display_name: Change::Set("New".into()), + picture: Media::KeepVerified(picture), + banner: Media::KeepVerified(banner), + ..Default::default() + }; + let candidate = plan(&base, &edit).unwrap(); + let before: BTreeMap<String, Box<RawValue>> = serde_json::from_str(&content).unwrap(); + let after: BTreeMap<String, Box<RawValue>> = + serde_json::from_str(candidate.body().content()).unwrap(); + assert_eq!(before.len(), after.len()); + for (name, value) in before + .iter() + .filter(|(name, _)| name.as_str() != "display_name") + { + assert_eq!(value.get(), after[name].get(), "{name}"); + } + assert_eq!(after["display_name"].get(), r#""New""#); + assert_eq!( + candidate.body().contract().registry_version(), + RegistryVersion::V8 + ); + assert_eq!( + candidate.body().contract().contract_id().as_str(), + PROFILE_METADATA_EDIT_CONTRACT_ID + ); + let wire = PlanWireV1::from_plan(&candidate).to_json().unwrap(); + let restored = PlanWireV1::from_json(&wire).unwrap(); + assert_eq!(restored.plan(), &candidate); + let signed = verify_and_admit_profile_event(envelope( + candidate.body().content(), + candidate.created_at(), + vec![], + &keys(), + )) + .unwrap(); + assert_eq!(signed.event().id(), candidate.expected_event_id()); + assert_eq!(signed.metadata().display_name(), Some("New")); + assert!(signed.metadata().residual_fields().contains_key("custom")); + assert_eq!( + signed.metadata().nip05().unwrap().as_str(), + "farm@example.com" + ); +} + +#[test] +fn profile_complete_edit_sets_and_clears_each_typed_field_without_unknown_authoring() { + let base = admitted( + r#"{"name":"old","display_name":7,"about":null,"picture":false,"banner":[],"nip05":"invalid","bot":"wrong","unknown":{"x":1}}"#, + 100, + ); + let edit = ProfileEdit { + name: Change::Set("new".into()), + display_name: Change::Set("Display".into()), + about: Change::Set("About".into()), + picture: Media::Set(image(b"picture")), + banner: Media::Set(image(b"banner")), + nip05: Change::Set(Nip05Identifier::parse("farmer@EXAMPLE.COM").unwrap()), + bot: Change::Set(true), + }; + let result: Value = serde_json::from_str(plan(&base, &edit).unwrap().body().content()).unwrap(); + assert_eq!(result["name"], "new"); + assert_eq!(result["display_name"], "Display"); + assert_eq!(result["about"], "About"); + assert_eq!(result["nip05"], "farmer@example.com"); + assert_eq!(result["bot"], true); + assert!( + result["picture"] + .as_str() + .unwrap() + .starts_with("https://media.example/") + ); + assert!( + result["banner"] + .as_str() + .unwrap() + .starts_with("https://media.example/") + ); + let clear = ProfileEdit { + name: Change::Clear, + display_name: Change::Clear, + about: Change::Clear, + picture: Media::Clear, + banner: Media::Clear, + nip05: Change::Clear, + bot: Change::Clear, + }; + assert_eq!( + plan(&base, &clear).unwrap().body().content(), + r#"{"unknown":{"x":1}}"# + ); + assert_eq!( + plan(&base, &ProfileEdit::default()) + .unwrap() + .body() + .content(), + r#"{"about":null,"banner":[],"bot":"wrong","display_name":7,"name":"old","nip05":"invalid","picture":false,"unknown":{"x":1}}"# + ); + assert_eq!(ProfileEdit::default().name, Change::Keep); +} + +#[test] +fn profile_complete_edit_stale_foreign_tagged_and_nonadvancing_baselines_refuse() { + let base = admitted(r#"{"name":"old"}"#, 100); + let newer = admitted(r#"{"name":"new"}"#, 101); + let edit = ProfileEdit::default(); + let author = keys().public_key().to_hex(); + assert_eq!( + AuthoredEventPlan::from_profile_edit(&base, &newer, &edit, 102, &author).unwrap_err(), + ProfileEditError::StaleBaseline + ); + let equal_time = admitted(r#"{"name":"changed"}"#, 100); + assert_eq!( + AuthoredEventPlan::from_profile_edit(&base, &equal_time, &edit, 102, &author).unwrap_err(), + ProfileEditError::StaleBaseline + ); + for time in [99, 100] { + assert_eq!( + AuthoredEventPlan::from_profile_edit(&base, &base, &edit, time, &author).unwrap_err(), + ProfileEditError::TimestampNotAdvancing + ); + } + for wrong in ["bad", &"ff".repeat(32)] { + assert_eq!( + AuthoredEventPlan::from_profile_edit(&base, &base, &edit, 102, wrong).unwrap_err(), + ProfileEditError::AuthorMismatch + ); + } + let other = + Keys::parse("0202020202020202020202020202020202020202020202020202020202020202").unwrap(); + let foreign = + verify_and_admit_profile_event(envelope(r#"{"name":"foreign"}"#, 100, vec![], &other)) + .unwrap(); + assert_eq!( + AuthoredEventPlan::from_profile_edit(&base, &foreign, &edit, 102, &author).unwrap_err(), + ProfileEditError::AuthorMismatch + ); + assert_eq!( + AuthoredEventPlan::from_profile_edit(&foreign, &base, &edit, 102, &author).unwrap_err(), + ProfileEditError::AuthorMismatch + ); + let tagged = verify_and_admit_profile_event(envelope( + r#"{"name":"old"}"#, + 100, + vec![vec!["x".into(), "keep".into()]], + &keys(), + )) + .unwrap(); + assert_eq!( + plan(&tagged, &edit).unwrap_err(), + ProfileEditError::BaselineTagsUnsupported + ); +} + +#[test] +fn profile_complete_edit_kept_media_requires_exact_proof_or_explicit_clear() { + let picture = image(b"picture"); + let base = admitted( + &format!(r#"{{"picture":"{}"}}"#, picture.descriptor().url()), + 100, + ); + assert_eq!( + plan(&base, &ProfileEdit::default()).unwrap_err(), + ProfileEditError::MediaVerificationRequired { field: "picture" } + ); + let mismatch = ProfileEdit { + picture: Media::KeepVerified(image(b"other")), + ..Default::default() + }; + assert_eq!( + plan(&base, &mismatch).unwrap_err(), + ProfileEditError::MediaVerificationMismatch { field: "picture" } + ); + let empty = admitted("{}", 100); + assert_eq!( + plan(&empty, &mismatch).unwrap_err(), + ProfileEditError::MediaVerificationMismatch { field: "picture" } + ); + let unsupported = admitted(r#"{"picture":"https://legacy.example/photo"}"#, 100); + assert_eq!( + plan(&unsupported, &ProfileEdit::default()) + .unwrap_err() + .code(), + "profile_media_verification_required" + ); + assert_eq!( + plan( + &unsupported, + &ProfileEdit { + picture: Media::Clear, + ..Default::default() + } + ) + .unwrap() + .body() + .content(), + "{}" + ); + let malformed = admitted(r#"{"picture":{"url":"untrusted"}}"#, 100); + assert_eq!( + plan(&malformed, &ProfileEdit::default()) + .unwrap() + .body() + .content(), + r#"{"picture":{"url":"untrusted"}}"# + ); +} + +#[test] +fn profile_complete_edit_content_and_durable_wire_bounds_are_exact() { + let empty = admitted("{}", 100); + let overhead = r#"{"about":""}"#.len(); + let max = RADROOTS_PROFILE_METADATA_MAX_CONTENT_BYTES; + let exact = ProfileEdit { + about: Change::Set("a".repeat(max - overhead)), + ..Default::default() + }; + let accepted = plan(&empty, &exact).unwrap(); + assert_eq!(accepted.body().content().len(), max); + assert!(PlanWireV1::from_plan(&accepted).to_json().unwrap().len() <= PLAN_WIRE_MAX_BYTES); + let over = ProfileEdit { + about: Change::Set("a".repeat(max - overhead + 1)), + ..Default::default() + }; + assert_eq!(plan(&empty, &over).unwrap_err().code(), "content_too_large"); + let early = ProfileEdit { + name: Change::Set("a".repeat(max + 1)), + ..Default::default() + }; + assert_eq!( + plan(&empty, &early).unwrap_err(), + ProfileEditError::ContentTooLarge { + max, + actual: max + 1 + } + ); + for name in ["", " ", "bad\nname"] { + assert_eq!( + plan( + &empty, + &ProfileEdit { + name: Change::Set(name.into()), + ..Default::default() + } + ) + .unwrap_err(), + ProfileEditError::InvalidName + ); + } + // Valid input content can expand beyond the durable-wire bound when escaped again. + let escaped = ProfileEdit { + about: Change::Set("\"".repeat((max - overhead) / 2)), + ..Default::default() + }; + assert_eq!( + plan(&empty, &escaped).unwrap_err().code(), + "profile_durable_wire_too_large" + ); +} + +#[test] +fn profile_complete_edit_registry_is_explicit_and_v7_defaults_and_strict_wire_are_unchanged() { + assert_eq!(RegistryVersion::CURRENT, RegistryVersion::V7); + let inherited = all_event_contracts(); + let successor = all_event_contracts_registry_v8(); + assert_eq!(&successor[..inherited.len()], inherited); + assert_eq!(successor.len(), inherited.len() + 1); + assert_eq!( + successor.last().unwrap().id, + PROFILE_METADATA_EDIT_CONTRACT_ID + ); + assert!(ContractKey::current(PROFILE_METADATA_EDIT_CONTRACT_ID).is_err()); + let key = ContractKey::new( + RegistryVersion::V8, + ContractId::parse(PROFILE_METADATA_EDIT_CONTRACT_ID).unwrap(), + ) + .unwrap(); + assert_eq!(key.contract().kind, 0); + assert_eq!( + serde_json::from_slice::<ContractKey>(&serde_json::to_vec(&key).unwrap()).unwrap(), + key + ); + assert!( + ContractKey::new( + RegistryVersion::V8, + ContractId::parse("radroots.profile.unknown.v1").unwrap() + ) + .is_err() + ); + let strict = AuthoredEventPlan::from_profile( + &AuthoredProfile::new("farm").unwrap(), + 101, + keys().public_key().to_hex(), + ) + .unwrap(); + assert_eq!( + strict.body().contract().registry_version(), + RegistryVersion::V7 + ); + assert_eq!(strict.body().content(), r#"{"name":"farm"}"#); + let baseline = admitted(r#"{"custom":true,"name":"farm"}"#, 100); + let edit = plan(&baseline, &ProfileEdit::default()).unwrap(); + let mut forged: Value = + serde_json::from_slice(&PlanWireV1::from_plan(&edit).to_json().unwrap()).unwrap(); + forged["contract_registry_version"] = Value::from(7); + assert!(PlanWireV1::from_json(&serde_json::to_vec(&forged).unwrap()).is_err()); + forged["contract_id"] = Value::from("radroots.profile.metadata.v1"); + assert!(PlanWireV1::from_json(&serde_json::to_vec(&forged).unwrap()).is_err()); +} + +#[test] +fn profile_complete_edit_historical_reconstruction_refuses_ambiguous_or_unsupported_shape() { + use radroots_event_codec::authoring::PlanDecodeError; + let baseline = admitted(r#"{"name":"farm","unknown":true}"#, 100); + let candidate = plan(&baseline, &ProfileEdit::default()).unwrap(); + let original: Value = + serde_json::from_slice(&PlanWireV1::from_plan(&candidate).to_json().unwrap()).unwrap(); + for (content, code) in [ + ( + r#"{"unknown":true,"name":"farm"}"#, + "profile_edit_noncanonical", + ), + (r#"{"name":"farm","name":"other"}"#, "duplicate_field"), + ( + r#"{"picture":"https://legacy.example/image"}"#, + "profile_media_url_invalid", + ), + ("[]", "root_not_object"), + ("broken", "invalid_json"), + ] { + let mut value = original.clone(); + value["content"] = Value::from(content); + assert_eq!( + PlanWireV1::from_json(&serde_json::to_vec(&value).unwrap()), + Err(PlanDecodeError::HistoricalShape(code.into())) + ); + } + let mut tagged = original.clone(); + tagged["tags"] = serde_json::json!([["x", "extra"]]); + assert_eq!( + PlanWireV1::from_json(&serde_json::to_vec(&tagged).unwrap()), + Err(PlanDecodeError::HistoricalShape( + "profile_tags_forbidden".into() + )) + ); + let mut unsupported = original; + unsupported["contract_registry_version"] = Value::from(9); + assert!(PlanWireV1::from_json(&serde_json::to_vec(&unsupported).unwrap()).is_err()); +} diff --git a/crates/nostr/tests/profile_event_builder.rs b/crates/nostr/tests/profile_event_builder.rs @@ -59,3 +59,68 @@ fn typed_profile_builder_finalizes_the_same_plan_for_an_external_signer() { let completed = request.complete(event).expect("exact typed completion"); assert_eq!(completed.id.to_hex(), plan.expected_event_id().to_hex()); } + +#[test] +fn profile_complete_edit_external_signing_request_completes_exact_preserved_replacement() { + use nostr::JsonUtil; + use radroots_event::{ + profile::edit::{ProfileEdit, ProfileFieldChange}, + wire::Nip01EventWire, + }; + use radroots_event_codec::{ + admission::profile::verify_and_admit_profile_event, authoring::AuthoredEventPlan, + }; + use radroots_nostr::event::ExternalSigningRequest; + let keys = RadrootsNostrKeys::new( + RadrootsNostrSecretKey::from_hex(test_fixtures::FIXTURE_ALICE_SECRET_KEY_HEX).unwrap(), + ); + let signed = nostr::EventBuilder::new( + nostr::Kind::Metadata, + r#"{"name":"farm","website":"https://farm.example","custom":{"x":1}}"#, + ) + .custom_created_at(RadrootsNostrTimestamp::from_secs(100)) + .sign_with_keys(&keys) + .unwrap(); + let baseline = verify_and_admit_profile_event( + Nip01EventWire::parse_json(&signed.as_json()) + .unwrap() + .into_envelope() + .unwrap(), + ) + .unwrap(); + let plan = AuthoredEventPlan::from_profile_edit( + &baseline, + &baseline, + &ProfileEdit { + display_name: ProfileFieldChange::Set("Updated farm".into()), + ..Default::default() + }, + 101, + keys.public_key().to_hex(), + ) + .unwrap(); + let request = ExternalSigningRequest::from_authored_plan(plan.clone()).unwrap(); + assert_eq!(request.authored_plan(), Some(&plan)); + let unsigned: nostr::UnsignedEvent = + serde_json::from_value(serde_json::to_value(&request).unwrap()).unwrap(); + let completed = request + .complete(unsigned.sign_with_keys(&keys).unwrap()) + .unwrap(); + assert_eq!(completed.id.to_hex(), plan.expected_event_id().to_hex()); + let admitted = verify_and_admit_profile_event( + Nip01EventWire::parse_json(&completed.as_json()) + .unwrap() + .into_envelope() + .unwrap(), + ) + .unwrap(); + assert_eq!(admitted.metadata().display_name(), Some("Updated farm")); + assert_eq!( + admitted.metadata().raw_fields()["website"], + "https://farm.example" + ); + assert_eq!( + admitted.metadata().raw_fields()["custom"], + serde_json::json!({"x":1}) + ); +} diff --git a/crates/signing/src/authorization.rs b/crates/signing/src/authorization.rs @@ -1,6 +1,8 @@ //! Current signing authorization, separate from historical plan integrity. -use radroots_event::contract::{EventAuthoringPolicy, EventStability, event_contract}; +use radroots_event::contract::{ + EventAuthoringPolicy, EventContract, EventStability, registry_v8::event_contract_registry_v8, +}; use radroots_event_codec::authoring::AuthoredEventPlan; use crate::{Actor, actor::ActorSource}; @@ -24,9 +26,17 @@ pub trait CurrentAuthoringAuthority: Send + Sync { #[derive(Clone, Copy, Debug, Default)] pub struct CurrentRegistryAuthority; +/// Current authoring includes explicit v8 capabilities; ordinary v7 defaults +/// remain unchanged. Never authorize from an arbitrary embedded old registry. +pub(crate) fn current_authoring_contract( + plan: &AuthoredEventPlan, +) -> Option<&'static EventContract> { + event_contract_registry_v8(plan.body().contract().contract_id().as_str()) +} + impl CurrentAuthoringAuthority for CurrentRegistryAuthority { fn evaluate(&self, plan: &AuthoredEventPlan) -> CurrentAuthoringDecision { - let Some(contract) = event_contract(plan.body().contract().contract_id().as_str()) else { + let Some(contract) = current_authoring_contract(plan) else { return CurrentAuthoringDecision::Blocked { code: "contract_not_current", }; diff --git a/crates/signing/src/request.rs b/crates/signing/src/request.rs @@ -4,7 +4,6 @@ use core::{ fmt, sync::atomic::{AtomicBool, Ordering}, }; -use radroots_event::contract::event_contract; use radroots_event_codec::authoring::{AuthoredEventPlan, BlossomAuthorizationPlan, PlanDigest}; use radroots_identity::PublicKey; use radroots_protocol::runtime::v1::OperationId; @@ -18,7 +17,7 @@ use crate::{ Actor, Error, SignerRequestId, SigningIntentId, authorization::{ CurrentAuthoringAuthority, CurrentAuthoringDecision, CurrentRegistryAuthority, - DeprecatedPlanPolicy, ManagedSigningPolicy, + DeprecatedPlanPolicy, ManagedSigningPolicy, current_authoring_contract, }, error::Kind, status::SignProgress, @@ -450,8 +449,8 @@ fn authorize( return Err(Error::new(Kind::AuthorizationDenied)); } } - let contract = event_contract(plan.body().contract().contract_id().as_str()) - .ok_or_else(|| Error::new(Kind::AuthorizationDenied))?; + let contract = + current_authoring_contract(plan).ok_or_else(|| Error::new(Kind::AuthorizationDenied))?; if !actor.satisfies(contract.required_author_role()) || actor.public_key() != *plan.author() || !policy.managed_signing().permits(actor) diff --git a/crates/signing/tests/authored_signing.rs b/crates/signing/tests/authored_signing.rs @@ -88,6 +88,108 @@ fn request() -> SignRequest { .expect("request") } +fn profile_edit_plan() -> AuthoredEventPlan { + use radroots_event::profile::edit::{ProfileEdit, ProfileFieldChange}; + use radroots_event_codec::admission::profile::verify_and_admit_profile_event; + let baseline = signed_event_with( + &keys(), + 0, + r#"{"name":"farm","website":"https://farm.example","custom":{"x":1}}"#, + CREATED_AT, + Vec::new(), + ); + let baseline = verify_and_admit_profile_event(baseline.envelope().clone()).unwrap(); + AuthoredEventPlan::from_profile_edit( + &baseline, + &baseline, + &ProfileEdit { + display_name: ProfileFieldChange::Set("Updated farm".into()), + ..Default::default() + }, + CREATED_AT + 1, + public_key().to_hex(), + ) + .unwrap() +} + +#[test] +fn profile_complete_edit_managed_signing_admits_exact_current_operation_and_signature() { + use radroots_signing::authorization::CurrentRegistryAuthority; + let plan = profile_edit_plan(); + let request = SignRequest::new( + OperationId::SyncPush, + intent(41, 42), + actor(ActorSource::ExplicitPublicKey, [AuthorRole::Any]), + plan.clone(), + policy(), + ) + .expect("current complete-profile edit must enter managed signing"); + assert_eq!( + CurrentRegistryAuthority.evaluate(&plan), + CurrentAuthoringDecision::Allowed + ); + assert_eq!(request.authored_plan(), Some(&plan)); + let signed = signed_event_with( + &keys(), + 0, + plan.body().content(), + plan.created_at(), + Vec::new(), + ); + let receipt = + SignReceipt::from_signed_event(&request, signed, CREATED_AT * 1000 + 2000).unwrap(); + assert_eq!(receipt.signed_event().id(), plan.expected_event_id()); + let fields: serde_json::Value = serde_json::from_str(receipt.signed_event().content()).unwrap(); + assert_eq!(fields["website"], "https://farm.example"); + assert_eq!(fields["custom"], serde_json::json!({"x":1})); +} + +#[test] +fn profile_complete_edit_managed_signing_preserves_host_denial_and_managed_actor_policy() { + for decision in [ + CurrentAuthoringDecision::Blocked { + code: "host_denied", + }, + CurrentAuthoringDecision::Revoked { + code: "host_revoked", + }, + ] { + let error = SignRequest::new_with_authority( + OperationId::SyncPush, + intent(41, 42), + actor(ActorSource::ExplicitPublicKey, [AuthorRole::Any]), + profile_edit_plan(), + policy(), + &FixedAuthority(decision), + ) + .unwrap_err(); + assert_eq!(error.kind(), Kind::AuthorizationDenied); + } + let denied = SignRequest::new( + OperationId::SyncPush, + intent(41, 42), + actor(ActorSource::ExplicitPublicKey, [AuthorRole::Any]), + profile_edit_plan(), + policy().with_managed_signing_policy(ManagedSigningPolicy::AccountBackedOnly), + ) + .unwrap_err(); + assert_eq!(denied.kind(), Kind::AuthorizationDenied); + let local = actor( + ActorSource::LocalAccount(AccountId::from_hex(&public_key().to_hex()).unwrap()), + [AuthorRole::Any], + ); + assert!( + SignRequest::new( + OperationId::SyncPush, + intent(41, 42), + local, + profile_edit_plan(), + policy().with_managed_signing_policy(ManagedSigningPolicy::LocalAccountOnly) + ) + .is_ok() + ); +} + fn blossom_plan() -> BlossomAuthorizationPlan { let claim = AuthoredUploadClaim::new( AuthorizationContent::parse("Upload exact image").expect("content"), diff --git a/crates/storage/tests/fixtures/profile_edit_baseline.v1.json b/crates/storage/tests/fixtures/profile_edit_baseline.v1.json @@ -0,0 +1 @@ +{"id":"762bee187e9e645b81ec26ade05a69b5e8398caf527be8de0d9a45311ed0c7a0","pubkey":"585591529da0bab31b3b1b1f986611cf5f435dca84f978c89ee8a40cca7103df","created_at":1800000100,"kind":0,"tags":[],"content":"{\"display_name\":\"Moss Street Farm\",\"bot\":false,\"website\":\"https://mossstreet.example\",\"picture\":42}","sig":"4290da0bb6422986647bc8cd5f63bd52d49f41e7b665d3b47105b8109183e8d596f322c531d4061df53e1d2b70fda12d5d1c14f3720d7a56d9d0a03746af5109"} +\ No newline at end of file diff --git a/crates/storage/tests/profile_complete_edit.rs b/crates/storage/tests/profile_complete_edit.rs @@ -0,0 +1,90 @@ +use futures_executor::block_on; +use radroots_event::{ + profile::edit::{ProfileEdit, ProfileFieldChange}, + wire::Nip01EventWire, +}; +use radroots_event_codec::{ + admission::profile::verify_and_admit_profile_event, authoring::AuthoredEventPlan, +}; +use radroots_storage::{ + Error, + authored::DurableAuthoredPlan, + authored_draft::{ + AuthoredDraft, AuthoredDraftId, AuthoredDraftStage, AuthoredDraftStore, + DraftAppendDisposition, + }, + memory::MemoryStorage, +}; + +// Exact canonical profile_admit_tagless_tolerant_001 vector, packaged locally. +fn edit_draft() -> (AuthoredEventPlan, AuthoredDraft) { + let baseline = verify_and_admit_profile_event( + Nip01EventWire::parse_json(include_str!("fixtures/profile_edit_baseline.v1.json")) + .unwrap() + .into_envelope() + .unwrap(), + ) + .unwrap(); + let plan = AuthoredEventPlan::from_profile_edit( + &baseline, + &baseline, + &ProfileEdit { + display_name: ProfileFieldChange::Set("Updated farm".into()), + ..Default::default() + }, + baseline.event().created_at_u64() + 1, + baseline.event().author().to_hex(), + ) + .unwrap(); + let durable = DurableAuthoredPlan::from_plan(&plan).unwrap(); + let draft = AuthoredDraft::initial( + AuthoredDraftId::new([41; 16]).unwrap(), + *plan.author().as_bytes(), + "radroots.authored_event_plan.v1", + durable.wire_json().to_vec(), + AuthoredDraftStage::Draft, + None, + 100, + ) + .unwrap(); + (plan, draft) +} + +#[test] +fn profile_complete_edit_memory_durable_payload_replay_conflict_and_reconstruction_preserve_metadata() + { + let (plan, draft) = edit_draft(); + let store = MemoryStorage::default(); + block_on(store.append_authored_draft(draft.clone(), None)).unwrap(); + assert_eq!( + block_on(store.append_authored_draft(draft.clone(), None)) + .unwrap() + .disposition(), + DraftAppendDisposition::Replay + ); + let conflicting = AuthoredDraft::initial( + draft.draft_id(), + *draft.author(), + draft.payload_schema(), + b"conflicting".to_vec(), + AuthoredDraftStage::Draft, + None, + 100, + ) + .unwrap(); + assert_eq!( + block_on(store.append_authored_draft(conflicting, None)), + Err(Error::DraftRevisionConflict) + ); + let stored = block_on(store.authored_draft_head(draft.draft_id())) + .unwrap() + .unwrap(); + assert_eq!(stored, draft); + let restored = DurableAuthoredPlan::reconstruct(stored.payload().to_vec()).unwrap(); + assert_eq!(restored.decode().unwrap().plan(), &plan); + let fields: serde_json::Value = serde_json::from_str(plan.body().content()).unwrap(); + assert_eq!(fields["display_name"], "Updated farm"); + assert_eq!(fields["picture"], 42); + assert_eq!(fields["website"], "https://mossstreet.example"); + assert_eq!(fields["bot"], false); +} diff --git a/crates/storage_sqlite/tests/fixtures/profile_edit_baseline.v1.json b/crates/storage_sqlite/tests/fixtures/profile_edit_baseline.v1.json @@ -0,0 +1 @@ +{"id":"762bee187e9e645b81ec26ade05a69b5e8398caf527be8de0d9a45311ed0c7a0","pubkey":"585591529da0bab31b3b1b1f986611cf5f435dca84f978c89ee8a40cca7103df","created_at":1800000100,"kind":0,"tags":[],"content":"{\"display_name\":\"Moss Street Farm\",\"bot\":false,\"website\":\"https://mossstreet.example\",\"picture\":42}","sig":"4290da0bb6422986647bc8cd5f63bd52d49f41e7b665d3b47105b8109183e8d596f322c531d4061df53e1d2b70fda12d5d1c14f3720d7a56d9d0a03746af5109"} +\ No newline at end of file diff --git a/crates/storage_sqlite/tests/profile_complete_edit.rs b/crates/storage_sqlite/tests/profile_complete_edit.rs @@ -0,0 +1,128 @@ +use radroots_event::{ + profile::edit::{ProfileEdit, ProfileFieldChange}, + wire::Nip01EventWire, +}; +use radroots_event_codec::{ + admission::profile::verify_and_admit_profile_event, authoring::AuthoredEventPlan, +}; +use radroots_storage::{ + Error, + authored::DurableAuthoredPlan, + authored_draft::{ + AuthoredDraft, AuthoredDraftId, AuthoredDraftStage, AuthoredDraftStore, + DraftAppendDisposition, + }, + event::SourceGeneration, + memory::MemoryStorage, +}; +use radroots_storage_sqlite::{OpenMode, OpenOptions, Paths, SqliteStorage}; + +// Exact canonical profile_admit_tagless_tolerant_001 vector, packaged locally. +fn edit_draft() -> (AuthoredEventPlan, AuthoredDraft) { + let baseline = verify_and_admit_profile_event( + Nip01EventWire::parse_json(include_str!("fixtures/profile_edit_baseline.v1.json")) + .unwrap() + .into_envelope() + .unwrap(), + ) + .unwrap(); + let plan = AuthoredEventPlan::from_profile_edit( + &baseline, + &baseline, + &ProfileEdit { + display_name: ProfileFieldChange::Set("Updated farm".into()), + ..Default::default() + }, + baseline.event().created_at_u64() + 1, + baseline.event().author().to_hex(), + ) + .unwrap(); + let durable = DurableAuthoredPlan::from_plan(&plan).unwrap(); + let draft = AuthoredDraft::initial( + AuthoredDraftId::new([41; 16]).unwrap(), + *plan.author().as_bytes(), + "radroots.authored_event_plan.v1", + durable.wire_json().to_vec(), + AuthoredDraftStage::Draft, + None, + 100, + ) + .unwrap(); + (plan, draft) +} + +async fn exercise(store: &dyn AuthoredDraftStore, draft: &AuthoredDraft) { + store + .append_authored_draft(draft.clone(), None) + .await + .unwrap(); + assert_eq!( + store + .append_authored_draft(draft.clone(), None) + .await + .unwrap() + .disposition(), + DraftAppendDisposition::Replay + ); + let conflicting = AuthoredDraft::initial( + draft.draft_id(), + *draft.author(), + draft.payload_schema(), + b"conflicting".to_vec(), + AuthoredDraftStage::Draft, + None, + 100, + ) + .unwrap(); + assert_eq!( + store.append_authored_draft(conflicting, None).await, + Err(Error::DraftRevisionConflict) + ); + assert_eq!( + store + .authored_draft_head(draft.draft_id()) + .await + .unwrap() + .unwrap(), + *draft + ); +} + +#[tokio::test] +async fn profile_complete_edit_sqlite_and_memory_durable_replay_and_readonly_reopen_preserve_metadata() + { + let (plan, draft) = edit_draft(); + let directory = tempfile::tempdir().unwrap(); + let paths = Paths::from_directory(directory.path()).unwrap(); + let store = SqliteStorage::open( + OpenOptions::new(paths.clone(), OpenMode::Create) + .with_source_generation(SourceGeneration::new([41; 32]).unwrap(), 100) + .unwrap(), + ) + .await + .unwrap(); + exercise(&MemoryStorage::default(), &draft).await; + exercise(&store, &draft).await; + store.close().await.unwrap(); + let reader = SqliteStorage::open(OpenOptions::new(paths, OpenMode::ReadOnly)) + .await + .unwrap(); + let stored = reader + .authored_draft_head(draft.draft_id()) + .await + .unwrap() + .unwrap(); + assert_eq!(stored, draft); + let restored = DurableAuthoredPlan::reconstruct(stored.payload().to_vec()).unwrap(); + assert_eq!(restored.decode().unwrap().plan(), &plan); + assert_eq!( + reader.append_authored_draft(draft.clone(), None).await, + Err(Error::BackendUnavailable) + ); + let fields: serde_json::Value = serde_json::from_str(plan.body().content()).unwrap(); + assert_eq!(fields["display_name"], "Updated farm"); + assert_eq!(fields["picture"], 42); + assert_eq!(fields["website"], "https://mossstreet.example"); + assert_eq!(fields["bot"], false); + reader.close().await.unwrap(); +}