Skip to main content

heddle_api/
import_authority.rs

1//! HYBRID canonical import authority. The existing heddle capability verifier
2//! supplies independently selected owner history/current permission. This
3//! module verifies the NEW typed parent grant and its bounded job child;
4//! it neither enrolls incoming roots nor substitutes for owner verification.
5use crate::heddle::api::v1alpha2::*;
6pub use crate::hybrid_codec::{Reject, strict_decode};
7use crate::hybrid_codec::{canonical, field, hash, key_id, record, signing_digest, verify, width};
8
9pub const PERMISSION_DOMAIN: &str = "heddle-import-member-permission-v1";
10pub const GENESIS_DOMAIN: &str = "heddle-import-genesis-authority-v1";
11pub const DELEGATION_DOMAIN: &str = "heddle-import-job-delegation-v1";
12pub const OPERATION_DOMAIN: &str = "heddle-delegated-import-operation-v1";
13pub const MANIFEST_DOMAIN: &str = "heddle-import-result-manifest-v1";
14pub const PUBLICATION_DOMAIN: &str = "heddle-import-publication-payload-v1";
15pub const MAX_BRANCHES: usize = 256;
16pub const MAX_RECORD_BYTES: usize = 64 * 1024;
17pub const MAX_BUNDLE_BYTES: usize = 1024 * 1024;
18pub const MAX_DELEGATION_WINDOW_SECONDS: u64 = 7 * 24 * 60 * 60;
19pub const MAX_COMMIT_REQUEST_BYTES: usize = 2 * MAX_BUNDLE_BYTES;
20pub const CANCELLATION_NAMESPACE: &str = "heddle-import-cancel-v1";
21
22record!(AuthorizationSignature, signer_key_id:b, signature:b);
23record!(RecordSignature, public_key:b, signature:b);
24record!(SignedRecord, format:s, canonical_record:b, signatures:l);
25record!(ImportFrontierV1, format_version:u, thread_id:b, operation_ids:h);
26record!(ImportContentV1, format_version:u, canonical_capture:b);
27record!(ImportBoundaryAcceptanceV1, binding:m, signed_acceptance:m, originals_manifest:b, publication_intent:b, original_receipts:l);
28record!(ImportGenesisWitnessV1, format_version:u, binding:m, original_genesis:m, creator_authority_envelope:b, boundary_acceptance:o);
29record!(ImportAuthorityWitnessV1, format_version:u, kind:e, original:m, dependencies:l, authority_envelope:b, boundary_acceptances:l);
30record!(HostedLandingRequestProofV1, format_version:u, signing_identity:s, method_path:s, timestamp_millis:u, nonce:b, request_body:b, signature:m);
31record!(HostedLandingWitnessV1, format_version:u, execution:m, request:m, source_operation:m, review_evidence:l, authority_envelope:b);
32record!(ImportIdentityV1, spool_uuid:b, spool_genesis_digest:b, owner_id:b,
33    owner_account_uuid:b, owner_state_hash:b, ownership_transfer_sequence:u);
34record!(ImportOwnerChainV1, spool_genesis_digest:b, owner_state_hashes:q, transfer_audit_hashes:q);
35record!(ImportBranchLimitV1, ref_name:s, hash_algorithm:e, ref_mode:e, pinned_commit_oid:b,
36    genesis_digest:b, target_thread_id:b, expected_frontier_digest:b, slot_id:u, ref_disclosure:e);
37record!(ImportPermissionScopeV1, provider:s, source_url:s, branches:l, destination_version:b,
38    options_digest:b, converter_version:s, max_operations:u, max_result_bytes:u);
39record!(ImportMemberPermissionV1, format_version:u, identity:m, logical_job_id:b,
40    retry_lineage_id:b, subject_public_key:b, purpose:e, scope:m, not_before_unix_seconds:u,
41    expires_at_unix_seconds:u, cancellation_id:b, owner_chain_digest:b, nonce:b);
42record!(SignedImportMemberPermissionV1, body:m, owner_signature:m);
43record!(ImportGenesisAuthorityV1, format_version:u, identity:m, genesis_digest:b,
44    original_creator_signature:b, creator_public_key:b, creator_authority_envelope_digest:b,
45    parent_permission_digest:b, owner_chain_digest:b);
46record!(SignedImportGenesisAuthorityV1, body:m, creator_signature:m);
47record!(ImportBranchManifestV1, limit:m, genesis_authority_digest:b);
48record!(ImportJobDelegationV1, format_version:u, identity:m, delegation_id:b, logical_job_id:b,
49    retry_lineage_id:b, job_public_key:b, job_key_id:b, delegating_public_key:b,
50    parent_permission_digest:b, owner_chain_digest:b, purpose:e, scope:m, branch_manifest:l,
51    not_before_unix_seconds:u, expires_at_unix_seconds:u, cancellation_id:b);
52record!(ImportJobPreparationV1, format_version:u, identity:m, delegation_id:b, logical_job_id:b,
53    retry_lineage_id:b, job_public_key:b, job_key_id:b, owner_chain_digest:b, purpose:e,
54    scope:m, cancellation_id:b);
55record!(SignedImportJobDelegationV1, body:m, delegating_signature:m);
56record!(ImportCommittedSlotV1, ref_name:s, slot_id:u, signed_operation_digest:b,
57    resulting_frontier_digest:b, result_bytes:u);
58record!(ImportResultManifestV1, format_version:u, logical_job_id:b, retry_lineage_id:b, slots:l);
59record!(DelegatedImportOperationV1, format_version:u, spool_uuid:b, spool_genesis_digest:b,
60    logical_job_id:b, retry_lineage_id:b, physical_operation_id:b, delegation_digest:b,
61    ref_name:s, slot_id:u, hash_algorithm:e, observed_commit_oid:b, genesis_digest:b,
62    target_thread_id:b, expected_frontier_digest:b, resulting_frontier_digest:b,
63    resulting_content_digest:b, result_bytes:u, options_digest:b, converter_version:s);
64record!(SignedDelegatedImportOperationV1, body:m, job_signature:m);
65record!(ImportPublicationWitnessV1, format_version:u, signed_operation_digest:b, delegation_digest:b,
66    logical_job_id:b, retry_lineage_id:b, physical_operation_id:b, ref_name:s, slot_id:u,
67    hash_algorithm:e, observed_commit_oid:b, expected_frontier_digest:b, resulting_frontier_digest:b,
68    terminal_manifest_digest:b);
69
70pub fn signed_permission_digest(v: &SignedImportMemberPermissionV1) -> Result<Vec<u8>, Reject> {
71    signing_digest("heddle-signed-import-member-permission-v1", v)
72}
73pub fn owner_chain_digest(v: &ImportOwnerChainV1) -> Result<Vec<u8>, Reject> {
74    width(&v.spool_genesis_digest, 32)?;
75    if v.owner_state_hashes.is_empty()
76        || v.owner_state_hashes.len() > 64
77        || v.transfer_audit_hashes.len() > 64
78    {
79        return Err(Reject::Bounds);
80    }
81    for h in v.owner_state_hashes.iter().chain(&v.transfer_audit_hashes) {
82        width(h, 32)?;
83    }
84    if v.owner_state_hashes.windows(2).any(|w| w[0] >= w[1]) {
85        return Err(Reject::Canonical);
86    }
87    signing_digest("heddle-import-owner-chain-v1", v)
88}
89pub fn signed_genesis_digest(v: &SignedImportGenesisAuthorityV1) -> Result<Vec<u8>, Reject> {
90    signing_digest("heddle-signed-import-genesis-authority-v1", v)
91}
92pub fn signed_delegation_digest(v: &SignedImportJobDelegationV1) -> Result<Vec<u8>, Reject> {
93    signing_digest("heddle-signed-import-job-delegation-v1", v)
94}
95pub fn signed_operation_digest(v: &SignedDelegatedImportOperationV1) -> Result<Vec<u8>, Reject> {
96    signing_digest("heddle-signed-delegated-import-operation-v1", v)
97}
98pub fn manifest_digest(v: &ImportResultManifestV1) -> Result<Vec<u8>, Reject> {
99    signing_digest(MANIFEST_DOMAIN, v)
100}
101pub fn verify_authorization_signature(
102    key: &[u8],
103    domain: &str,
104    body: &impl crate::hybrid_codec::Canonical,
105    signature: &AuthorizationSignature,
106) -> Result<(), Reject> {
107    if signature.signer_key_id != key_id(key) {
108        return Err(Reject::Signature);
109    }
110    let bytes = canonical(body)?;
111    if bytes.len() > MAX_RECORD_BYTES {
112        return Err(Reject::Bounds);
113    }
114    verify(
115        key,
116        &hash(&[domain.as_bytes(), &bytes]),
117        &signature.signature,
118    )
119}
120
121/// Conservative canonical URL grammar for v1: lowercase DNS HTTPS host, no
122/// userinfo/query/fragment/port/escapes, ASCII unreserved path segments. No
123/// implicit URL normalization is performed by a signing implementation.
124pub fn canonical_https(value: &str, origin: bool) -> Result<(), Reject> {
125    if value.len() > 2048 {
126        return Err(Reject::Bounds);
127    }
128    let rest = value.strip_prefix("https://").ok_or(Reject::Canonical)?;
129    let (host, path) = rest.split_once('/').unwrap_or((rest, ""));
130    if host.is_empty()
131        || host.len() > 253
132        || host.split('.').any(|part| {
133            part.is_empty()
134                || part.len() > 63
135                || part.starts_with('-')
136                || part.ends_with('-')
137                || !part
138                    .bytes()
139                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
140        })
141        || (origin && rest != host)
142        || (!origin && path.is_empty())
143        || path.split('/').any(|p| {
144            p.is_empty() && !origin
145                || p == "."
146                || p == ".."
147                || !p
148                    .bytes()
149                    .all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b))
150        })
151    {
152        return Err(Reject::Canonical);
153    }
154    Ok(())
155}
156fn identity(value: &ImportIdentityV1) -> Result<(), Reject> {
157    for v in [&value.spool_uuid, &value.owner_account_uuid] {
158        width(v, 16)?;
159        if v.iter().all(|b| *b == 0) {
160            return Err(Reject::Canonical);
161        }
162    }
163    for v in [
164        &value.spool_genesis_digest,
165        &value.owner_id,
166        &value.owner_state_hash,
167    ] {
168        width(v, 32)?;
169    }
170    Ok(())
171}
172fn interval(start: i64, end: i64, now: i64) -> Result<(), Reject> {
173    if start < 0 || end <= start {
174        return Err(Reject::Semantic);
175    }
176    if now < start || now >= end {
177        return Err(Reject::Expired);
178    }
179    Ok(())
180}
181// Structural validation never substitutes a synthetic historical clock.
182fn validity(start: i64, end: i64, now: i64, current: bool) -> Result<(), Reject> {
183    if start < 0 || end <= start {
184        return Err(Reject::Semantic);
185    }
186    if current {
187        interval(start, end, now)?;
188    }
189    Ok(())
190}
191fn branch(value: &ImportBranchLimitV1) -> Result<(), Reject> {
192    if !value.ref_name.starts_with("refs/heads/")
193        || value.ref_name.len() > 1024
194        || value.ref_name.ends_with('/')
195        || value.ref_name.ends_with('.')
196        || value.ref_name.contains("..")
197        || value.ref_name.contains("//")
198        || value.ref_name.contains("@{")
199        || value
200            .ref_name
201            .split('/')
202            .any(|p| p.starts_with('.') || p.ends_with(".lock"))
203        || !value
204            .ref_name
205            .bytes()
206            .all(|b| b.is_ascii_alphanumeric() || b"/_-.".contains(&b))
207    {
208        return Err(Reject::Canonical);
209    }
210    let size = match value.hash_algorithm {
211        1 => 20,
212        2 => 32,
213        _ => return Err(Reject::Version),
214    };
215    match value.ref_mode {
216        1 => {
217            width(&value.pinned_commit_oid, size)?;
218            if value.ref_disclosure != 0 {
219                return Err(Reject::RefDisclosure);
220            }
221        }
222        2 if value.pinned_commit_oid.is_empty() => {
223            if value.ref_disclosure != 1 {
224                return Err(Reject::RefDisclosure);
225            }
226        }
227        _ => return Err(Reject::Semantic),
228    }
229    for v in [
230        &value.genesis_digest,
231        &value.target_thread_id,
232        &value.expected_frontier_digest,
233    ] {
234        width(v, 32)?;
235    }
236    Ok(())
237}
238
239/// Check independently observed OID knowledge before signing/preparation.
240/// Empty/unknown is None, never an implicit observe-mode selection or consent.
241pub fn validate_ref_selection(
242    value: &ImportBranchLimitV1,
243    known_commit_oid: Option<&[u8]>,
244) -> Result<(), Reject> {
245    branch(value)?;
246    if let Some(oid) = known_commit_oid {
247        width(oid, if value.hash_algorithm == 1 { 20 } else { 32 })?;
248        if value.ref_mode != 1 || value.pinned_commit_oid != oid {
249            return Err(Reject::RefPinning);
250        }
251    }
252    Ok(())
253}
254
255/// Converter option octets are selected verbatim from authenticated discovery.
256pub fn conversion_options_digest(version: &str, options: &[u8]) -> Result<Vec<u8>, Reject> {
257    if version.is_empty() || version.len() > 128 || !version.is_ascii() {
258        return Err(Reject::Canonical);
259    }
260    if options.len() > 4096 {
261        return Err(Reject::Bounds);
262    }
263    let mut bytes = Vec::new();
264    crate::hybrid_codec::counted(&mut bytes, version.as_bytes())?;
265    crate::hybrid_codec::counted(&mut bytes, options)?;
266    Ok(hash(&[b"heddle-import-conversion-options-v1", &bytes]))
267}
268
269/// Resolve explicit custody using a CURRENT authenticated connection provider.
270/// Public URLs never select an adapter by domain. Network/grant checks remain host gates.
271pub fn resolve_import_provider(
272    source: &ProviderRepository,
273    connection_provider: Option<&str>,
274) -> Result<&'static str, Reject> {
275    canonical_https(&source.clone_url, false)?;
276    if source.provider_repository_id.len() > 4096 || source.name.len() > 4096 {
277        return Err(Reject::Bounds);
278    }
279    if let Some(connection) = &source.connection {
280        let positive = |v: &str| {
281            !v.is_empty()
282                && v.bytes().all(|b| b.is_ascii_digit())
283                && v.parse::<u64>().is_ok_and(|id| id > 0)
284        };
285        if connection_provider != Some("github")
286            || connection.spool.is_some()
287            || connection.id.is_empty()
288            || !positive(&source.provider_repository_id)
289            || !positive(&source.installation_id)
290        {
291            return Err(Reject::SourceSelection);
292        }
293        let path = source
294            .clone_url
295            .strip_prefix("https://github.com/")
296            .ok_or(Reject::SourceSelection)?;
297        let parts: Vec<_> = path.split('/').collect();
298        if parts.len() != 2
299            || parts[0].is_empty()
300            || parts[1].strip_suffix(".git").is_none_or(str::is_empty)
301        {
302            return Err(Reject::SourceSelection);
303        }
304        Ok("github")
305    } else {
306        if connection_provider.is_some()
307            || source.private
308            || !source.installation_id.is_empty()
309            || (!source.provider_repository_id.is_empty()
310                && source.provider_repository_id != source.clone_url)
311        {
312            return Err(Reject::SourceSelection);
313        }
314        Ok("public-git")
315    }
316}
317
318/// Advisory Git size in KiB. UNKNOWN is explicit and must carry zero.
319pub fn validate_repository_size_estimate(source: &ProviderRepository) -> Result<(), Reject> {
320    match source.size_estimate_state {
321        0 if source.git_size_kib == 0 => Ok(()),
322        1 if source.connection.is_some() => Ok(()),
323        _ => Err(Reject::Canonical),
324    }
325}
326
327/// Preserve selected identity exactly. Redirect/SSRF and current grants are host gates.
328pub fn validate_resolve_import_source_response(
329    request: &ResolveImportSourceRequest,
330    response: &ResolveImportSourceResponse,
331    connection_provider: Option<&str>,
332) -> Result<(), Reject> {
333    use prost::Message;
334    if response.encoded_len() > MAX_BUNDLE_BYTES {
335        return Err(Reject::Bounds);
336    }
337    let selected = request.source.as_ref().ok_or(Reject::SourceSelection)?;
338    let resolved = response.source.as_ref().ok_or(Reject::SourceSelection)?;
339    let provider = resolve_import_provider(selected, connection_provider)?;
340    if resolve_import_provider(resolved, connection_provider)? != provider
341        || selected.clone_url != resolved.clone_url
342        || selected.connection != resolved.connection
343        || selected.installation_id != resolved.installation_id
344        || selected.private != resolved.private
345        || (selected.provider_repository_id != resolved.provider_repository_id
346            && (selected.connection.is_some() || !selected.provider_repository_id.is_empty()))
347        || (resolved.connection.is_none() && resolved.provider_repository_id != selected.clone_url)
348    {
349        return Err(Reject::SourceSelection);
350    }
351    validate_repository_size_estimate(resolved)?;
352    validate_repository_hash_algorithm(resolved, false)
353}
354
355/// Structural binding to signed provider/URL; durable custody association is a host invariant.
356fn validate_retained_import_source(
357    selector: &ImportSourceSelectionV1,
358    scope: &ImportPermissionScopeV1,
359) -> Result<(), Reject> {
360    let source = ProviderRepository {
361        connection: selector.connection.clone(),
362        provider_repository_id: selector.provider_repository_id.clone(),
363        installation_id: selector.installation_id.clone(),
364        private: selector.private,
365        clone_url: scope.source_url.clone(),
366        ..Default::default()
367    };
368    let provider =
369        resolve_import_provider(&source, selector.connection.as_ref().map(|_| "github"))?;
370    if scope.provider != provider
371        || (selector.connection.is_none() && selector.provider_repository_id != scope.source_url)
372    {
373        return Err(Reject::SourceSelection);
374    }
375    Ok(())
376}
377
378/// Discovery may report unknown. Preparing/signing requires known=true; no SHA-1 fallback.
379pub fn validate_repository_hash_algorithm(
380    source: &ProviderRepository,
381    known: bool,
382) -> Result<(), Reject> {
383    let size = match source.hash_algorithm {
384        1 => Some(40),
385        2 => Some(64),
386        0 if !known => None,
387        _ => return Err(Reject::Version),
388    };
389    if source.refs.len() > 512 {
390        return Err(Reject::Bounds);
391    }
392    for (i, r) in source.refs.iter().enumerate() {
393        if r.hash_algorithm != source.hash_algorithm {
394            return Err(Reject::SourceSelection);
395        }
396        if i > 0 && source.refs[i - 1].name >= r.name {
397            return Err(Reject::Canonical);
398        }
399        if !r.head_oid.is_empty() {
400            let size = size.ok_or(Reject::Version)?;
401            if r.head_oid.len() != size {
402                return Err(Reject::SourceSelection);
403            }
404            if !r
405                .head_oid
406                .bytes()
407                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
408            {
409                return Err(Reject::Canonical);
410            }
411        }
412    }
413    Ok(())
414}
415
416/// Compare independent repository discovery before signing, including known-OID pinning.
417pub fn validate_discovered_import_scope(
418    scope: &ImportPermissionScopeV1,
419    source: &ProviderRepository,
420) -> Result<(), Reject> {
421    validate_discovered_import_scope_inner(scope, source)
422}
423
424fn validate_discovered_import_scope_inner(
425    scope: &ImportPermissionScopeV1,
426    source: &ProviderRepository,
427) -> Result<(), Reject> {
428    validate_repository_hash_algorithm(source, true)?;
429    if scope.source_url != source.clone_url {
430        return Err(Reject::SourceSelection);
431    }
432    for b in &scope.branches {
433        if b.hash_algorithm != source.hash_algorithm {
434            return Err(Reject::SourceSelection);
435        }
436        let oid = source
437            .refs
438            .iter()
439            .find(|r| r.name == b.ref_name)
440            .filter(|r| !r.head_oid.is_empty())
441            .map(|r| hex::decode(&r.head_oid).map_err(|_| Reject::Canonical))
442            .transpose()?;
443        validate_ref_selection(b, oid.as_deref())?;
444    }
445    Ok(())
446}
447
448/// Host resolves the selector anew and checks current grants and selected-commit
449/// availability before issuing a reservation, for a new job. Source state
450/// MUST come from an authenticated job-state read or receiver-owned durable state;
451/// the current source resolver binds independently verified discovery to the proposal.
452pub fn prepare_import_source_scope(
453    request: &PrepareImportJobRequest,
454    current_source: &ProviderRepository,
455    connection_provider: Option<&str>,
456    configuration: &GetImportConfigurationResponse,
457    current_destination_version: &[u8],
458) -> Result<ImportPermissionScopeV1, Reject> {
459    let selector = request.source.as_ref().ok_or(Reject::SourceSelection)?;
460    if selector.connection != current_source.connection
461        || (selector.provider_repository_id != current_source.provider_repository_id
462            && (selector.connection.is_some() || !selector.provider_repository_id.is_empty()))
463        || selector.installation_id != current_source.installation_id
464        || selector.private != current_source.private
465    {
466        return Err(Reject::SourceSelection);
467    }
468    let scope = request.proposed_scope.as_ref().ok_or(Reject::Canonical)?;
469    let provider = resolve_import_provider(current_source, connection_provider)?;
470    if scope.provider != provider {
471        return Err(Reject::SourceSelection);
472    }
473    validate_discovered_import_scope(scope, current_source)?;
474    validate_import_configuration(configuration)?;
475    prepare_scope(scope, configuration, current_destination_version)
476}
477
478fn validate_provider_support(
479    provider: &str,
480    configuration: &GetImportConfigurationResponse,
481) -> Result<(), Reject> {
482    if !configuration
483        .providers
484        .iter()
485        .any(|p| p.provider == provider)
486    {
487        return Err(Reject::SourceSelection);
488    }
489    Ok(())
490}
491
492pub fn validate_import_configuration(v: &GetImportConfigurationResponse) -> Result<(), Reject> {
493    use prost::Message;
494    if v.encoded_len() > MAX_BUNDLE_BYTES || v.converters.is_empty() || v.converters.len() > 32 {
495        return Err(Reject::Bounds);
496    }
497    for (i, c) in v.converters.iter().enumerate() {
498        for text in [&c.converter_version, &c.options_encoding] {
499            if text.is_empty() || text.len() > 128 || !text.is_ascii() {
500                return Err(Reject::Canonical);
501            }
502        }
503        if i > 0 && v.converters[i - 1].converter_version >= c.converter_version {
504            return Err(Reject::Canonical);
505        }
506        if c.canonical_options.is_empty()
507            || c.canonical_options.len() > 64
508            || c.canonical_options.iter().any(|o| o.len() > 4096)
509        {
510            return Err(Reject::Bounds);
511        }
512        if c.canonical_options.windows(2).any(|w| w[0] >= w[1])
513            || !c.canonical_options.contains(&c.default_options)
514        {
515            return Err(Reject::Canonical);
516        }
517    }
518    if v.providers.is_empty() || v.providers.len() > 2 {
519        return Err(Reject::Bounds);
520    }
521    for (i, p) in v.providers.iter().enumerate() {
522        if i > 0 && v.providers[i - 1].provider >= p.provider {
523            return Err(Reject::Canonical);
524        }
525        let mode = match p.provider.as_str() {
526            "github" => 1,
527            "public-git" => 2,
528            _ => return Err(Reject::SourceSelection),
529        };
530        if p.source_modes != [mode] {
531            return Err(Reject::SourceSelection);
532        }
533    }
534    if let Some(default) = &v.default_converter_version
535        && !v.converters.iter().any(|c| &c.converter_version == default)
536    {
537        return Err(Reject::Canonical);
538    }
539    let l = v.limits.as_ref().ok_or(Reject::Canonical)?;
540    if l.max_branches == 0
541        || l.max_branches as usize > MAX_BRANCHES
542        || l.max_operations == 0
543        || l.max_operations as usize > MAX_BRANCHES
544        || l.max_result_bytes == 0
545    {
546        return Err(Reject::Bounds);
547    }
548    Ok(())
549}
550
551/// Host-side negotiation with a CURRENT authenticated configuration and CAS.
552/// Only an empty destination token is filled; all other choices survive exactly.
553pub fn prepare_scope(
554    proposed: &ImportPermissionScopeV1,
555    configuration: &GetImportConfigurationResponse,
556    current_destination_version: &[u8],
557) -> Result<ImportPermissionScopeV1, Reject> {
558    use ImportPreparationRefusalReason as Reason;
559    validate_import_configuration(configuration)?;
560    width(current_destination_version, 32)?;
561    if !proposed.destination_version.is_empty() && proposed.destination_version.len() != 32 {
562        return Err(Reject::PreparationRefused(Reason::InvalidScope));
563    }
564    if !proposed.destination_version.is_empty()
565        && proposed.destination_version != current_destination_version
566    {
567        return Err(Reject::PreparationRefused(Reason::DestinationConflict));
568    }
569    let mut selected = proposed.clone();
570    selected.destination_version = current_destination_version.to_vec();
571    validate_scope(&selected).map_err(|_| Reject::PreparationRefused(Reason::InvalidScope))?;
572    validate_provider_support(&selected.provider, configuration)
573        .map_err(|_| Reject::PreparationRefused(Reason::InvalidScope))?;
574    let converter = configuration
575        .converters
576        .iter()
577        .find(|c| c.converter_version == selected.converter_version)
578        .ok_or(Reject::PreparationRefused(Reason::UnsupportedConverter))?;
579    let supported = converter
580        .canonical_options
581        .iter()
582        .try_fold(false, |found, o| {
583            Ok::<_, Reject>(
584                found
585                    || conversion_options_digest(&converter.converter_version, o)?
586                        == selected.options_digest,
587            )
588        })?;
589    if !supported {
590        return Err(Reject::PreparationRefused(Reason::UnsupportedOptions));
591    }
592    let limits = configuration.limits.as_ref().ok_or(Reject::Canonical)?;
593    if selected.branches.len() > limits.max_branches as usize
594        || selected.max_operations > limits.max_operations
595        || selected.max_result_bytes > limits.max_result_bytes
596    {
597        return Err(Reject::PreparationRefused(Reason::BudgetExceeded));
598    }
599    Ok(selected)
600}
601
602/// Independently retained refs/slots for one non-terminal logical job. Include
603/// Prepared jobs and all original refs until logical termination, not just the
604/// current certificate's remaining scope. Hosts provide the complete inventory
605/// under the same transaction that reserves/activates; this helper stores nothing.
606pub struct ImportSpoolReservation<'a> {
607    pub spool_uuid: &'a [u8],
608    pub logical_job_id: &'a [u8],
609    pub branches: &'a [ImportBranchLimitV1],
610}
611
612/// Per-spool full refs and (full ref, slot_id) keys are exclusive across jobs,
613/// regardless of provider/source. Same-job checks retain exact branch identity.
614/// Run after scope negotiation and before atomically reserving every ref/slot.
615pub fn check_import_spool_reservations(
616    spool_uuid: &[u8],
617    logical_job_id: &[u8],
618    scope: &ImportPermissionScopeV1,
619    reservations: &[ImportSpoolReservation<'_>],
620) -> Result<(), Reject> {
621    initial_operation_id(spool_uuid, false)?;
622    initial_operation_id(logical_job_id, false)?;
623    validate_scope(scope)?;
624    for reservation in reservations {
625        initial_operation_id(reservation.spool_uuid, false)?;
626        initial_operation_id(reservation.logical_job_id, false)?;
627        if reservation.spool_uuid != spool_uuid {
628            continue;
629        }
630        let same_job = reservation.logical_job_id == logical_job_id;
631        for selected in &scope.branches {
632            let conflict = if same_job {
633                !reservation.branches.contains(selected)
634            } else {
635                reservation.branches.iter().any(|held| {
636                    held.ref_name == selected.ref_name
637                        || held.target_thread_id == selected.target_thread_id
638                        || held.genesis_digest == selected.genesis_digest
639                })
640            };
641            if conflict {
642                return Err(Reject::PreparationRefused(
643                    ImportPreparationRefusalReason::DestinationConflict,
644                ));
645            }
646        }
647    }
648    Ok(())
649}
650
651/// Commit-only wire mapping for reservation conflicts and stale destination CAS.
652/// These admission failures destroy prepared custody and do not freeze a receipt.
653pub fn import_commit_conflict_failure(
654    rejection: &Reject,
655) -> Option<crate::heddle::api::common::CallFailure> {
656    use crate::heddle::api::common::{CallFailure, CallFailureCode, ErrorDetail, ErrorReason};
657    let (code, reason) = match rejection {
658        Reject::PreparationRefused(ImportPreparationRefusalReason::DestinationConflict) => (
659            CallFailureCode::AlreadyExists,
660            ErrorReason::ImportDestinationConflict,
661        ),
662        Reject::StaleContext => (CallFailureCode::Aborted, ErrorReason::VersionConflict),
663        _ => return None,
664    };
665    Some(CallFailure {
666        code: code as i32,
667        message: String::new(),
668        error: Some(ErrorDetail {
669            reason: reason as i32,
670            ..Default::default()
671        }),
672    })
673}
674
675/// Current destination configuration/ownership/policy CAS at activation. Other
676/// imports do not advance this token. Exact stored replay is resolved first.
677pub fn check_import_destination_version(
678    scope: &ImportPermissionScopeV1,
679    current_destination_version: &[u8],
680) -> Result<(), Reject> {
681    width(&scope.destination_version, 32)?;
682    width(current_destination_version, 32)?;
683    if scope.destination_version != current_destination_version {
684        return Err(Reject::StaleContext);
685    }
686    Ok(())
687}
688
689/// Browser-side comparison before signing. A host cannot silently negotiate.
690pub fn validate_preparation_response(
691    request: &PrepareImportJobRequest,
692    response: &PrepareImportJobResponse,
693) -> Result<(), Reject> {
694    if let Some(refusal) = &response.refusal {
695        let reason = ImportPreparationRefusalReason::try_from(refusal.reason)
696            .map_err(|_| Reject::Version)?;
697        if reason == ImportPreparationRefusalReason::Unspecified
698            || refusal.field.len() > 256
699            || !refusal.field.is_ascii()
700            || response.proposal.is_some()
701            || response.reservation_expires_at_unix_seconds != 0
702            || response.prepared_at_unix_seconds != 0
703            || response.max_validity_duration_seconds != 0
704            || response.clock_skew_allowance_seconds != 0
705        {
706            return Err(Reject::Canonical);
707        }
708        return Err(Reject::PreparationRefused(reason));
709    }
710    let p = response.proposal.as_ref().ok_or(Reject::Canonical)?;
711    let returned = p.scope.as_ref().ok_or(Reject::Canonical)?;
712    let mut requested = request.proposed_scope.clone().ok_or(Reject::Canonical)?;
713    if requested.destination_version.is_empty() {
714        requested.destination_version = returned.destination_version.clone();
715    }
716    if canonical(&requested)? != canonical(returned)?
717        || p.identity != request.identity
718        || p.retry_lineage_id != request.retry_lineage_id
719    {
720        return Err(Reject::PreparedFields);
721    }
722    validate_scope(returned)?;
723    Ok(())
724}
725
726/// Enforce inclusive decoded protobuf sizes before semantic admission.
727/// Transport must also bound the whole uncompressed payload before decoding.
728pub fn validate_commit_request_bounds(request: &CommitImportJobRequest) -> Result<(), Reject> {
729    use prost::Message;
730    if request.encoded_len() > MAX_COMMIT_REQUEST_BYTES
731        || request
732            .proof
733            .as_ref()
734            .ok_or(Reject::Canonical)?
735            .encoded_len()
736            > MAX_BUNDLE_BYTES
737    {
738        return Err(Reject::Bounds);
739    }
740    Ok(())
741}
742
743/// Source association/provider comes from the host's authenticated resolver,
744/// never a projection hint. Native base decoding/identity and current grants
745/// remain host gates; this validates carrier, bounds and exact originals.
746pub fn validate_commit_request(
747    request: &CommitImportJobRequest,
748    resolved_provider: &str,
749    current_source: &ProviderRepository,
750    configuration: &GetImportConfigurationResponse,
751) -> Result<(), Reject> {
752    use prost::Message;
753    validate_commit_request_bounds(request)?;
754    let source = request.source.as_ref().ok_or(Reject::SourceSelection)?;
755    let proof = request.proof.as_ref().ok_or(Reject::Canonical)?;
756    if request.client_operation_id.is_empty()
757        || request.client_operation_id.len() > 128
758        || request.destination.as_ref().is_none_or(|d| d.id.is_empty())
759    {
760        return Err(Reject::Canonical);
761    }
762    if request.initial_base_state.len() > 4096 || proof.encoded_len() > MAX_BUNDLE_BYTES {
763        return Err(Reject::Bounds);
764    }
765    if proof.format_version != 1
766        || proof.delegations.len() != 1
767        || !proof.operations.is_empty()
768        || proof.terminal_manifest.is_some()
769        || !proof.manifests.is_empty()
770    {
771        return Err(Reject::Canonical);
772    }
773    let d = proof.delegations[0]
774        .body
775        .as_ref()
776        .ok_or(Reject::Canonical)?;
777    let scope = d.scope.as_ref().ok_or(Reject::Canonical)?;
778    validate_scope(scope)?;
779    let id = d.identity.as_ref().ok_or(Reject::Canonical)?;
780    identity(id)?;
781    let uuid = hex::encode(&id.spool_uuid);
782    let destination_id = format!(
783        "{}-{}-{}-{}-{}",
784        &uuid[..8],
785        &uuid[8..12],
786        &uuid[12..16],
787        &uuid[16..20],
788        &uuid[20..]
789    );
790    if request
791        .destination
792        .as_ref()
793        .is_none_or(|s| s.id != destination_id)
794    {
795        return Err(Reject::Scope);
796    }
797    if source.clone_url != scope.source_url
798        || resolved_provider != scope.provider
799        || source.provider_repository_id.len() > 4096
800        || source.name.len() > 4096
801    {
802        return Err(Reject::SourceSelection);
803    }
804    if source.connection != current_source.connection
805        || (source.provider_repository_id != current_source.provider_repository_id
806            && (source.connection.is_some() || !source.provider_repository_id.is_empty()))
807        || source.clone_url != current_source.clone_url
808        || source.installation_id != current_source.installation_id
809        || source.private != current_source.private
810    {
811        return Err(Reject::SourceSelection);
812    }
813    let provider = resolve_import_provider(
814        current_source,
815        current_source
816            .connection
817            .as_ref()
818            .map(|_| resolved_provider),
819    )?;
820    if provider != resolved_provider {
821        return Err(Reject::SourceSelection);
822    }
823    validate_import_configuration(configuration)?;
824    validate_provider_support(provider, configuration)?;
825    validate_repository_hash_algorithm(current_source, true)?;
826    if source.hash_algorithm != current_source.hash_algorithm {
827        return Err(Reject::SourceSelection);
828    }
829    // A frozen pin names the selected commit, even if the branch head moves.
830    // OBSERVE still cannot hide a currently known selected OID by clearing hints.
831    for b in &scope.branches {
832        if b.hash_algorithm != current_source.hash_algorithm {
833            return Err(Reject::SourceSelection);
834        }
835        if b.ref_mode == 2
836            && current_source
837                .refs
838                .iter()
839                .any(|r| r.name == b.ref_name && !r.head_oid.is_empty())
840        {
841            return Err(Reject::RefPinning);
842        }
843    }
844    // Current converter/options/budget support is also rechecked at activation.
845    prepare_scope(scope, configuration, &scope.destination_version)?;
846    if proof.original_geneses.len() != scope.branches.len()
847        || proof.creator_authority_envelopes.len() != scope.branches.len()
848        || proof.genesis_authorities.len() != scope.branches.len()
849        || d.branch_manifest.len() != scope.branches.len()
850    {
851        return Err(Reject::GenesisBinding);
852    }
853    // Arrays are ordered exactly like the signed branch manifest, no second
854    // association-by-name payload and no incoming regenerated branch originals.
855    for (i, b) in scope.branches.iter().enumerate() {
856        let original = &proof.original_geneses[i];
857        let binding = &proof.genesis_authorities[i];
858        let g = binding.body.as_ref().ok_or(Reject::GenesisBinding)?;
859        let m = &d.branch_manifest[i];
860        if native_id(original) != b.genesis_digest
861            || g.genesis_digest != b.genesis_digest
862            || m.limit.as_ref() != Some(b)
863            || m.genesis_authority_digest != signed_genesis_digest(binding)?
864            || g.creator_authority_envelope_digest != hash(&[&proof.creator_authority_envelopes[i]])
865            || proof.creator_authority_envelopes[i].is_empty()
866            || proof.creator_authority_envelopes[i].len() > MAX_RECORD_BYTES
867            || !original.signatures.iter().any(|s| {
868                s.public_key == g.creator_public_key && s.signature == g.original_creator_signature
869            })
870        {
871            return Err(Reject::GenesisBinding);
872        }
873        verify_native(original, "heddle-thread-genesis-v1")?;
874    }
875    Ok(())
876}
877
878/// This closed route has no initial-submission or authority-attachment role.
879pub fn validate_import_source(_: &ImportSourceRequest) -> Result<(), Reject> {
880    Err(Reject::ImportSourceRequiresCommit)
881}
882
883/// Complete initial validation, excluding native model/owner history, live
884/// source access and transaction checks owned by the hosted implementation.
885pub fn verify_commit_submission(
886    request: &CommitImportJobRequest,
887    prepared: &PrepareImportJobResponse,
888    resolved_provider: &str,
889    current_source: &ProviderRepository,
890    configuration: &GetImportConfigurationResponse,
891    expected: &ImportOwnerExpectation<'_>,
892) -> Result<VerifiedImportDelegation, Reject> {
893    validate_commit_request(request, resolved_provider, current_source, configuration)?;
894    let proof = request.proof.as_ref().ok_or(Reject::Canonical)?;
895    let member = proof.member_permission.as_ref();
896    verify_prepared_delegation(
897        prepared,
898        &proof.delegations[0],
899        member,
900        &proof.genesis_authorities,
901        expected,
902    )
903}
904
905pub fn validate_commit_response(
906    request: &CommitImportJobRequest,
907    response: &MutationResponse,
908) -> Result<(), Reject> {
909    let receipt = response.receipt.as_ref().ok_or(Reject::PendingOperation)?;
910    let Some(mutation_receipt::Outcome::PendingOperation(operation)) = &receipt.outcome else {
911        return Err(Reject::PendingOperation);
912    };
913    if request.client_operation_id.is_empty()
914        || receipt.client_operation_id != request.client_operation_id
915        || request.destination.is_none()
916        || operation.spool != request.destination
917        || operation.id
918            != initial_operation_id(
919                &request
920                    .proof
921                    .as_ref()
922                    .ok_or(Reject::PendingOperation)?
923                    .delegations
924                    .first()
925                    .and_then(|d| d.body.as_ref())
926                    .ok_or(Reject::PendingOperation)?
927                    .retry_lineage_id,
928                false,
929            )?
930    {
931        return Err(Reject::PendingOperation);
932    }
933    Ok(())
934}
935
936/// Use a durable caller-scoped idempotency row BEFORE rechecking expired job
937/// authority. Host stores the original request/receipt atomically with activation.
938/// Changed inputs refuse OperationIdReused only for an ID with an accepted receipt.
939pub fn check_commit_replay(
940    request: &CommitImportJobRequest,
941    stored: &CommitImportJobRequest,
942    response: &MutationResponse,
943) -> Result<(), Reject> {
944    if request != stored {
945        return Err(Reject::OperationIdReused);
946    }
947    validate_commit_response(request, response)
948}
949pub fn validate_scope(value: &ImportPermissionScopeV1) -> Result<(), Reject> {
950    canonical_https(&value.source_url, false)?;
951    if value.provider.is_empty()
952        || value.provider.len() > 64
953        || !value
954            .provider
955            .bytes()
956            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
957        || value.converter_version.is_empty()
958        || value.converter_version.len() > 128
959        || !value.converter_version.is_ascii()
960    {
961        return Err(Reject::Canonical);
962    }
963    width(&value.destination_version, 32)?;
964    width(&value.options_digest, 32)?;
965    if value.branches.is_empty()
966        || value.branches.len() > MAX_BRANCHES
967        || value.max_operations == 0
968        || value.max_operations as usize > MAX_BRANCHES
969        || value.max_result_bytes == 0
970    {
971        return Err(Reject::Bounds);
972    }
973    if (value.max_operations as usize) < value.branches.len() {
974        return Err(Reject::Scope);
975    }
976    for (i, b) in value.branches.iter().enumerate() {
977        branch(b)?;
978        if value.branches[..i].iter().any(|other| {
979            other.target_thread_id == b.target_thread_id || other.genesis_digest == b.genesis_digest
980        }) {
981            return Err(Reject::Scope);
982        }
983        if i > 0 && value.branches[i - 1].ref_name.as_bytes() >= b.ref_name.as_bytes() {
984            return Err(Reject::Canonical);
985        }
986    }
987    Ok(())
988}
989fn scope_subset(child: &ImportPermissionScopeV1, parent: &ImportPermissionScopeV1) -> bool {
990    child.provider == parent.provider
991        && child.source_url == parent.source_url
992        && child.destination_version == parent.destination_version
993        && child.options_digest == parent.options_digest
994        && child.converter_version == parent.converter_version
995        && child.max_operations <= parent.max_operations
996        && child.max_result_bytes <= parent.max_result_bytes
997        && child.branches.iter().all(|c| parent.branches.contains(c))
998}
999
1000/// Public context from the existing owner/keyring verifier, not from fields in
1001/// the incoming bundle. now is receiver/host time for new work or independently
1002/// verified witness observation time for retained history, NEVER author time.
1003pub struct ImportOwnerExpectation<'a> {
1004    pub identity: &'a ImportIdentityV1,
1005    pub owner_public_key: &'a [u8],
1006    pub owner_chain_digest: &'a [u8],
1007    /// From the independently verified EFFECTIVE owner state at `now`, not
1008    /// the immutable root. Accepted claim/deferral clearing is unbounded.
1009    pub authority_expires_at_seconds: i64,
1010    pub now_unix_seconds: i64,
1011    pub forbidden_job_keys: &'a [Vec<u8>], // Every user/root/witness key, including tombstones.
1012    pub known_job_associations: &'a [(Vec<u8>, Vec<u8>)], // key -> logical job.
1013}
1014/// Independently verified owner facts for retained bundle verification. Historical
1015/// check times are selected internally from authenticated receipts, never callers.
1016#[derive(Clone, Copy)]
1017pub struct ImportBundleOwnerExpectation<'a> {
1018    pub identity: &'a ImportIdentityV1,
1019    pub owner_public_key: &'a [u8],
1020    pub owner_chain_digest: &'a [u8],
1021    pub authority_expires_at_seconds: i64,
1022    /// Effective interval of these independently authenticated owner facts.
1023    pub effective_from_unix_seconds: i64,
1024    pub effective_until_unix_seconds: Option<i64>,
1025    pub forbidden_job_keys: &'a [Vec<u8>],
1026    pub known_job_associations: &'a [(Vec<u8>, Vec<u8>)],
1027}
1028impl<'a> ImportBundleOwnerExpectation<'a> {
1029    fn at(self, time: i64, associations: &'a [(Vec<u8>, Vec<u8>)]) -> ImportOwnerExpectation<'a> {
1030        ImportOwnerExpectation {
1031            identity: self.identity,
1032            owner_public_key: self.owner_public_key,
1033            owner_chain_digest: self.owner_chain_digest,
1034            authority_expires_at_seconds: self.authority_expires_at_seconds,
1035            now_unix_seconds: time,
1036            forbidden_job_keys: self.forbidden_job_keys,
1037            known_job_associations: associations,
1038        }
1039    }
1040}
1041/// Inputs MUST come from the selected, independently verified effective state.
1042/// Historical verification selects the state at its authenticated observation.
1043pub fn effective_owner_authority_expiry(
1044    deferred_human: bool,
1045    claimable_until: i64,
1046) -> Result<i64, Reject> {
1047    if deferred_human {
1048        if claimable_until <= 0 {
1049            return Err(Reject::Scope);
1050        }
1051        Ok(claimable_until)
1052    } else {
1053        Ok(i64::MAX)
1054    }
1055}
1056pub fn verify_member_permission(
1057    signed: &SignedImportMemberPermissionV1,
1058    expected: &ImportOwnerExpectation<'_>,
1059) -> Result<(), Reject> {
1060    verify_member_permission_inner(signed, expected, true)
1061}
1062fn verify_member_permission_inner(
1063    signed: &SignedImportMemberPermissionV1,
1064    expected: &ImportOwnerExpectation<'_>,
1065    current: bool,
1066) -> Result<(), Reject> {
1067    let p = signed.body.as_ref().ok_or(Reject::ImportPermission)?;
1068    if p.format_version != 1 || p.purpose != 1 {
1069        return Err(Reject::ImportPermission);
1070    }
1071    identity(p.identity.as_ref().ok_or(Reject::Canonical)?)?;
1072    if p.identity.as_ref() != Some(expected.identity)
1073        || p.owner_chain_digest != expected.owner_chain_digest
1074    {
1075        return Err(Reject::Root);
1076    }
1077    width(&p.logical_job_id, 16)?;
1078    width(&p.retry_lineage_id, 16)?;
1079    width(&p.subject_public_key, 32)?;
1080    width(&p.cancellation_id, 32)?;
1081    width(&p.nonce, 32)?;
1082    width(&p.owner_chain_digest, 32)?;
1083    validate_scope(p.scope.as_ref().ok_or(Reject::Canonical)?)?;
1084    validity(
1085        p.not_before_unix_seconds,
1086        p.expires_at_unix_seconds,
1087        expected.now_unix_seconds,
1088        current,
1089    )?;
1090    if p.expires_at_unix_seconds > expected.authority_expires_at_seconds {
1091        return Err(Reject::Scope);
1092    }
1093    verify_authorization_signature(
1094        expected.owner_public_key,
1095        PERMISSION_DOMAIN,
1096        p,
1097        signed.owner_signature.as_ref().ok_or(Reject::Signature)?,
1098    )
1099}
1100
1101#[derive(Debug, Clone, PartialEq)]
1102pub struct VerifiedImportDelegation {
1103    body: ImportJobDelegationV1,
1104    digest: Vec<u8>,
1105    member: Option<SignedImportMemberPermissionV1>,
1106}
1107impl VerifiedImportDelegation {
1108    pub fn body(&self) -> &ImportJobDelegationV1 {
1109        &self.body
1110    }
1111    pub fn digest(&self) -> &[u8] {
1112        &self.digest
1113    }
1114}
1115pub fn verify_delegation(
1116    signed: &SignedImportJobDelegationV1,
1117    member: Option<&SignedImportMemberPermissionV1>,
1118    expected: &ImportOwnerExpectation<'_>,
1119) -> Result<VerifiedImportDelegation, Reject> {
1120    verify_delegation_inner(signed, member, expected, true)
1121}
1122fn verify_delegation_inner(
1123    signed: &SignedImportJobDelegationV1,
1124    member: Option<&SignedImportMemberPermissionV1>,
1125    expected: &ImportOwnerExpectation<'_>,
1126    current: bool,
1127) -> Result<VerifiedImportDelegation, Reject> {
1128    let d = signed.body.as_ref().ok_or(Reject::Canonical)?;
1129    if d.format_version != 1 || d.purpose != 1 {
1130        return Err(Reject::Version);
1131    }
1132    identity(d.identity.as_ref().ok_or(Reject::Canonical)?)?;
1133    if d.identity.as_ref() != Some(expected.identity)
1134        || d.owner_chain_digest != expected.owner_chain_digest
1135    {
1136        return Err(Reject::Root);
1137    }
1138    for v in [&d.delegation_id, &d.logical_job_id, &d.retry_lineage_id] {
1139        width(v, 16)?;
1140        if v.iter().all(|b| *b == 0) {
1141            return Err(Reject::Canonical);
1142        }
1143    }
1144    for v in [
1145        &d.job_public_key,
1146        &d.job_key_id,
1147        &d.delegating_public_key,
1148        &d.parent_permission_digest,
1149        &d.owner_chain_digest,
1150        &d.cancellation_id,
1151    ] {
1152        width(v, 32)?;
1153    }
1154    if d.job_key_id != key_id(&d.job_public_key) {
1155        return Err(Reject::Canonical);
1156    }
1157    if d.job_public_key == d.delegating_public_key
1158        || d.job_public_key == expected.owner_public_key
1159        || expected.forbidden_job_keys.contains(&d.job_public_key)
1160    {
1161        return Err(Reject::KeyRole);
1162    }
1163    if expected
1164        .known_job_associations
1165        .iter()
1166        .any(|(k, j)| k == &d.job_public_key && j != &d.logical_job_id)
1167    {
1168        return Err(Reject::Scope);
1169    }
1170    let scope = d.scope.as_ref().ok_or(Reject::Canonical)?;
1171    validate_scope(scope)?;
1172    if d.branch_manifest.len() != scope.branches.len() {
1173        return Err(Reject::Scope);
1174    }
1175    for (m, b) in d.branch_manifest.iter().zip(&scope.branches) {
1176        width(&m.genesis_authority_digest, 32)?;
1177        if m.limit.as_ref() != Some(b) {
1178            return Err(Reject::Scope);
1179        }
1180    }
1181    if i128::from(d.expires_at_unix_seconds) - i128::from(d.not_before_unix_seconds)
1182        > i128::from(MAX_DELEGATION_WINDOW_SECONDS)
1183    {
1184        return Err(Reject::ValidityBounds);
1185    }
1186    validity(
1187        d.not_before_unix_seconds,
1188        d.expires_at_unix_seconds,
1189        expected.now_unix_seconds,
1190        current,
1191    )?;
1192    if d.expires_at_unix_seconds > expected.authority_expires_at_seconds {
1193        return Err(Reject::Scope);
1194    }
1195    if d.delegating_public_key == expected.owner_public_key {
1196        if member.is_some() || d.parent_permission_digest != vec![0; 32] {
1197            return Err(Reject::ImportPermission);
1198        }
1199    } else {
1200        let member = member.ok_or(Reject::ImportPermission)?;
1201        verify_member_permission_inner(member, expected, current)?;
1202        let p = member.body.as_ref().ok_or(Reject::ImportPermission)?;
1203        if d.parent_permission_digest != signed_permission_digest(member)?
1204            || d.delegating_public_key != p.subject_public_key
1205            || d.logical_job_id != p.logical_job_id
1206            || d.retry_lineage_id != p.retry_lineage_id
1207            || d.not_before_unix_seconds < p.not_before_unix_seconds
1208            || d.expires_at_unix_seconds > p.expires_at_unix_seconds
1209            || !scope_subset(scope, p.scope.as_ref().ok_or(Reject::Canonical)?)
1210        {
1211            return Err(Reject::Scope);
1212        }
1213    }
1214    verify_authorization_signature(
1215        &d.delegating_public_key,
1216        DELEGATION_DOMAIN,
1217        d,
1218        signed
1219            .delegating_signature
1220            .as_ref()
1221            .ok_or(Reject::Signature)?,
1222    )?;
1223    Ok(VerifiedImportDelegation {
1224        body: d.clone(),
1225        digest: signed_delegation_digest(signed)?,
1226        member: member.cloned(),
1227    })
1228}
1229/// Frozen canonical projection. The browser completes only the fields absent
1230/// here; it cannot normalize or reduce even an otherwise authorized scope.
1231pub fn delegation_preparation(d: &ImportJobDelegationV1) -> ImportJobPreparationV1 {
1232    ImportJobPreparationV1 {
1233        format_version: d.format_version,
1234        identity: d.identity.clone(),
1235        delegation_id: d.delegation_id.clone(),
1236        logical_job_id: d.logical_job_id.clone(),
1237        retry_lineage_id: d.retry_lineage_id.clone(),
1238        job_public_key: d.job_public_key.clone(),
1239        job_key_id: d.job_key_id.clone(),
1240        owner_chain_digest: d.owner_chain_digest.clone(),
1241        purpose: d.purpose,
1242        scope: d.scope.clone(),
1243        cancellation_id: d.cancellation_id.clone(),
1244    }
1245}
1246
1247/// Validate Commit against the HOST-STORED preparation and independently
1248/// selected current authority. Native genesis/envelope verification, online
1249/// revocation, custody uniqueness and transactional activation remain host gates.
1250pub fn verify_prepared_delegation(
1251    prepared: &PrepareImportJobResponse,
1252    signed: &SignedImportJobDelegationV1,
1253    member: Option<&SignedImportMemberPermissionV1>,
1254    geneses: &[SignedImportGenesisAuthorityV1],
1255    expected: &ImportOwnerExpectation<'_>,
1256) -> Result<VerifiedImportDelegation, Reject> {
1257    verify_prepared_inner(prepared, signed, member, geneses, expected, false)
1258}
1259/// Browser signing preflight only: no execution or admission token is returned.
1260pub fn preflight_prepared_delegation(
1261    prepared: &PrepareImportJobResponse,
1262    signed: &SignedImportJobDelegationV1,
1263    member: Option<&SignedImportMemberPermissionV1>,
1264    geneses: &[SignedImportGenesisAuthorityV1],
1265    expected: &ImportOwnerExpectation<'_>,
1266) -> Result<(), Reject> {
1267    verify_prepared_inner(prepared, signed, member, geneses, expected, true).map(|_| ())
1268}
1269fn verify_prepared_inner(
1270    prepared: &PrepareImportJobResponse,
1271    signed: &SignedImportJobDelegationV1,
1272    member: Option<&SignedImportMemberPermissionV1>,
1273    geneses: &[SignedImportGenesisAuthorityV1],
1274    expected: &ImportOwnerExpectation<'_>,
1275    browser: bool,
1276) -> Result<VerifiedImportDelegation, Reject> {
1277    let proposal = prepared.proposal.as_ref().ok_or(Reject::Canonical)?;
1278    let d = signed.body.as_ref().ok_or(Reject::Canonical)?;
1279    if canonical(proposal)? != canonical(&delegation_preparation(d))? {
1280        return Err(Reject::PreparedFields);
1281    }
1282    let scope = proposal.scope.as_ref().ok_or(Reject::Canonical)?;
1283    if d.branch_manifest.len() != scope.branches.len() {
1284        return Err(Reject::PreparedFields);
1285    }
1286    for (m, b) in d.branch_manifest.iter().zip(&scope.branches) {
1287        let limit = m.limit.as_ref().ok_or(Reject::PreparedFields)?;
1288        if canonical(limit)? != canonical(b)? {
1289            return Err(Reject::PreparedFields);
1290        }
1291    }
1292    // Use i128 for host arithmetic so extreme advertised uint64 bounds cannot
1293    // wrap. Skew permits a future not-before, never grace after expiry.
1294    let now = i128::from(expected.now_unix_seconds);
1295    let start = i128::from(d.not_before_unix_seconds);
1296    let end = i128::from(d.expires_at_unix_seconds);
1297    let at = i128::from(prepared.prepared_at_unix_seconds);
1298    let skew = i128::from(prepared.clock_skew_allowance_seconds);
1299    if at < 0
1300        || now < 0
1301        || if browser { now + skew < at } else { now < at }
1302        || i128::from(prepared.reservation_expires_at_unix_seconds) != at + 3600
1303        || now >= i128::from(prepared.reservation_expires_at_unix_seconds)
1304    {
1305        return Err(Reject::Expired);
1306    }
1307    if prepared.max_validity_duration_seconds == 0
1308        || prepared.max_validity_duration_seconds > MAX_DELEGATION_WINDOW_SECONDS
1309        || start < 0
1310        || start < at - skew
1311        || start > now + skew
1312        || end <= start
1313        || end <= now
1314        || end - start > i128::from(prepared.max_validity_duration_seconds)
1315    {
1316        return Err(Reject::ValidityBounds);
1317    }
1318    if let Some(parent) = member {
1319        if browser {
1320            let p = parent.body.as_ref().ok_or(Reject::ImportPermission)?;
1321            verify_member_permission_inner(parent, expected, false)?;
1322            if i128::from(p.not_before_unix_seconds) > now + skew
1323                || i128::from(p.expires_at_unix_seconds) <= now
1324            {
1325                return Err(Reject::Expired);
1326            }
1327        } else {
1328            verify_member_permission(parent, expected)?;
1329        }
1330    }
1331    // Future not-before within skew can be committed, but verify_new_operation
1332    // still refuses execution until that exact signed time. Parent/owner expiry
1333    // and containment are checked without extending them by skew.
1334    let at_start = ImportOwnerExpectation {
1335        now_unix_seconds: expected.now_unix_seconds.max(d.not_before_unix_seconds),
1336        ..*expected
1337    };
1338    let verified = verify_delegation_inner(
1339        signed,
1340        member,
1341        if browser { expected } else { &at_start },
1342        !browser,
1343    )?;
1344    if geneses.len() != d.branch_manifest.len() {
1345        return Err(Reject::GenesisBinding);
1346    }
1347    for m in &d.branch_manifest {
1348        let branch = m.limit.as_ref().ok_or(Reject::Canonical)?;
1349        let g = geneses
1350            .iter()
1351            .find(|g| signed_genesis_digest(g).is_ok_and(|h| h == m.genesis_authority_digest))
1352            .ok_or(Reject::GenesisBinding)?;
1353        let body = g.body.as_ref().ok_or(Reject::GenesisBinding)?;
1354        if body.genesis_digest != branch.genesis_digest {
1355            return Err(Reject::GenesisBinding);
1356        }
1357        {
1358            verify_genesis_authority(
1359                g,
1360                &verified,
1361                &branch.genesis_digest,
1362                &body.original_creator_signature,
1363                &body.creator_authority_envelope_digest,
1364            )?;
1365        }
1366    }
1367    Ok(verified)
1368}
1369
1370pub fn verify_genesis_authority(
1371    signed: &SignedImportGenesisAuthorityV1,
1372    delegation: &VerifiedImportDelegation,
1373    original_genesis_digest: &[u8],
1374    original_signature: &[u8],
1375    envelope_digest: &[u8],
1376) -> Result<(), Reject> {
1377    let g = signed.body.as_ref().ok_or(Reject::Canonical)?;
1378    let d = &delegation.body;
1379    if g.format_version != 1 {
1380        return Err(Reject::Version);
1381    }
1382    width(&g.original_creator_signature, 64)?;
1383    for v in [
1384        &g.genesis_digest,
1385        &g.creator_public_key,
1386        &g.creator_authority_envelope_digest,
1387        &g.parent_permission_digest,
1388        &g.owner_chain_digest,
1389    ] {
1390        width(v, 32)?;
1391    }
1392    if g.identity != d.identity
1393        || g.creator_public_key != d.delegating_public_key
1394        || g.parent_permission_digest != d.parent_permission_digest
1395        || g.owner_chain_digest != d.owner_chain_digest
1396        || g.genesis_digest != original_genesis_digest
1397        || g.original_creator_signature != original_signature
1398        || g.creator_authority_envelope_digest != envelope_digest
1399        || !d.branch_manifest.iter().any(|m| {
1400            m.limit
1401                .as_ref()
1402                .is_some_and(|b| b.genesis_digest == g.genesis_digest)
1403                && signed_genesis_digest(signed).is_ok_and(|h| h == m.genesis_authority_digest)
1404        })
1405    {
1406        return Err(Reject::Scope);
1407    }
1408    verify_authorization_signature(
1409        &g.creator_public_key,
1410        GENESIS_DOMAIN,
1411        g,
1412        signed.creator_signature.as_ref().ok_or(Reject::Signature)?,
1413    )
1414}
1415/// Structural signature + scoped operation only. This does not establish
1416/// publication, current policy, cancellation, leases or conversion correctness.
1417pub fn verify_operation(
1418    signed: &SignedDelegatedImportOperationV1,
1419    delegation: &VerifiedImportDelegation,
1420) -> Result<(), Reject> {
1421    let o = signed.body.as_ref().ok_or(Reject::Canonical)?;
1422    let d = &delegation.body;
1423    if o.format_version != 1 {
1424        return Err(Reject::Version);
1425    }
1426    let id = d.identity.as_ref().ok_or(Reject::Canonical)?;
1427    width(&o.physical_operation_id, 16)?;
1428    for v in [
1429        &o.spool_genesis_digest,
1430        &o.delegation_digest,
1431        &o.genesis_digest,
1432        &o.target_thread_id,
1433        &o.expected_frontier_digest,
1434        &o.resulting_frontier_digest,
1435        &o.resulting_content_digest,
1436        &o.options_digest,
1437    ] {
1438        width(v, 32)?;
1439    }
1440    width(&o.spool_uuid, 16)?;
1441    width(&o.logical_job_id, 16)?;
1442    width(&o.retry_lineage_id, 16)?;
1443    let scope = d.scope.as_ref().ok_or(Reject::Canonical)?;
1444    let b = scope
1445        .branches
1446        .iter()
1447        .find(|b| b.ref_name == o.ref_name && b.slot_id == o.slot_id)
1448        .ok_or(Reject::Scope)?;
1449    let oid_len = match o.hash_algorithm {
1450        1 => 20,
1451        2 => 32,
1452        _ => return Err(Reject::Version),
1453    };
1454    width(&o.observed_commit_oid, oid_len)?;
1455    if o.spool_uuid != id.spool_uuid
1456        || o.spool_genesis_digest != id.spool_genesis_digest
1457        || o.logical_job_id != d.logical_job_id
1458        || o.retry_lineage_id != d.retry_lineage_id
1459        || o.delegation_digest != delegation.digest
1460        || o.hash_algorithm != b.hash_algorithm
1461        || (b.ref_mode == 1 && o.observed_commit_oid != b.pinned_commit_oid)
1462        || o.genesis_digest != b.genesis_digest
1463        || o.target_thread_id != b.target_thread_id
1464        || o.expected_frontier_digest != b.expected_frontier_digest
1465        || o.result_bytes > scope.max_result_bytes
1466        || o.result_bytes == 0
1467        || o.options_digest != scope.options_digest
1468        || o.converter_version != scope.converter_version
1469    {
1470        return Err(Reject::Scope);
1471    }
1472    verify_authorization_signature(
1473        &d.job_public_key,
1474        OPERATION_DOMAIN,
1475        o,
1476        signed.job_signature.as_ref().ok_or(Reject::Signature)?,
1477    )
1478}
1479pub fn verify_new_operation(
1480    signed: &SignedDelegatedImportOperationV1,
1481    delegation: &VerifiedImportDelegation,
1482    now_seconds: i64,
1483    committed_before: &ImportResultManifestV1,
1484) -> Result<(), Reject> {
1485    interval(
1486        delegation.body.not_before_unix_seconds,
1487        delegation.body.expires_at_unix_seconds,
1488        now_seconds,
1489    )?;
1490    check_import_publication_budget(signed, delegation, committed_before)
1491}
1492pub fn validate_manifest(m: &ImportResultManifestV1) -> Result<(), Reject> {
1493    if m.format_version != 1 {
1494        return Err(Reject::Version);
1495    }
1496    width(&m.logical_job_id, 16)?;
1497    width(&m.retry_lineage_id, 16)?;
1498    if m.slots.len() > MAX_BRANCHES {
1499        return Err(Reject::Bounds);
1500    }
1501    for (i, s) in m.slots.iter().enumerate() {
1502        width(&s.signed_operation_digest, 32)?;
1503        width(&s.resulting_frontier_digest, 32)?;
1504        if !s.ref_name.starts_with("refs/heads/") || !s.ref_name.is_ascii() {
1505            return Err(Reject::Canonical);
1506        }
1507        if s.ref_name.len() > 1024 || s.result_bytes == 0 {
1508            return Err(Reject::Bounds);
1509        }
1510        if i > 0 && (&m.slots[i - 1].ref_name, m.slots[i - 1].slot_id) >= (&s.ref_name, s.slot_id) {
1511            return Err(Reject::Canonical);
1512        }
1513    }
1514    Ok(())
1515}
1516
1517/// Persistent unique slot identity: logical job/ref/slot. Exact replay returns
1518/// the old receipt/manifest, never another publication or fresh witness.
1519pub fn check_slot_replay(
1520    committed: &ImportResultManifestV1,
1521    signed: &SignedDelegatedImportOperationV1,
1522) -> Result<bool, Reject> {
1523    validate_manifest(committed)?;
1524    let o = signed.body.as_ref().ok_or(Reject::Canonical)?;
1525    if committed.logical_job_id != o.logical_job_id
1526        || committed.retry_lineage_id != o.retry_lineage_id
1527    {
1528        return Err(Reject::Scope);
1529    }
1530    match committed
1531        .slots
1532        .iter()
1533        .find(|s| s.ref_name == o.ref_name && s.slot_id == o.slot_id)
1534    {
1535        Some(s)
1536            if s.signed_operation_digest == signed_operation_digest(signed)?
1537                && s.resulting_frontier_digest == o.resulting_frontier_digest
1538                && s.result_bytes == o.result_bytes =>
1539        {
1540            Ok(true)
1541        }
1542        Some(_) => Err(Reject::SlotConflict),
1543        None => Ok(false),
1544    }
1545}
1546/// Verify exact committed publication in addition to job signature/scope. The
1547/// owner/keyring verifier must resolve the statement's accepted state/order;
1548/// witness signature alone cannot establish that user authority or disclosure.
1549pub fn verify_publication(
1550    operation: &SignedDelegatedImportOperationV1,
1551    delegation: &VerifiedImportDelegation,
1552    manifest: &ImportResultManifestV1,
1553    statement: &crate::heddle::api::common::SignedHostedWitnessStatementV1,
1554    set: &crate::witness_trust::VerifiedWitnessSet,
1555    proof: Option<&crate::heddle::api::common::HostedWitnessHistoryProofV1>,
1556    now_ms: i64,
1557) -> Result<crate::witness_trust::ResolvedWitnessStatement, Reject> {
1558    validate_statement_boundary(statement.body.as_ref().ok_or(Reject::Canonical)?)?;
1559    verify_operation(operation, delegation)?;
1560    if !check_slot_replay(manifest, operation)? {
1561        return Err(Reject::Scope);
1562    }
1563    let mut before = manifest.clone();
1564    let o = operation.body.as_ref().ok_or(Reject::Canonical)?;
1565    before
1566        .slots
1567        .retain(|slot| slot.ref_name != o.ref_name || slot.slot_id != o.slot_id);
1568    check_import_publication_budget(operation, delegation, &before)?;
1569    let d = &delegation.body;
1570    let id = d.identity.as_ref().ok_or(Reject::Canonical)?;
1571    let s = statement.body.as_ref().ok_or(Reject::Canonical)?;
1572    let payload = ImportPublicationWitnessV1 {
1573        format_version: 1,
1574        signed_operation_digest: signed_operation_digest(operation)?,
1575        delegation_digest: delegation.digest.clone(),
1576        logical_job_id: o.logical_job_id.clone(),
1577        retry_lineage_id: o.retry_lineage_id.clone(),
1578        physical_operation_id: o.physical_operation_id.clone(),
1579        ref_name: o.ref_name.clone(),
1580        slot_id: o.slot_id,
1581        hash_algorithm: o.hash_algorithm,
1582        observed_commit_oid: o.observed_commit_oid.clone(),
1583        expected_frontier_digest: o.expected_frontier_digest.clone(),
1584        resulting_frontier_digest: o.resulting_frontier_digest.clone(),
1585        terminal_manifest_digest: manifest_digest(manifest)?,
1586    };
1587    if s.purpose != 3
1588        || s.spool_uuid != id.spool_uuid
1589        || s.spool_genesis_digest != id.spool_genesis_digest
1590        || s.owner_id != id.owner_id
1591        || s.owner_state_hash != id.owner_state_hash
1592        || s.ownership_transfer_sequence != id.ownership_transfer_sequence
1593        || s.authority_digest != delegation.digest
1594        || s.original_signatures_digest
1595            != hash(&[&operation
1596                .job_signature
1597                .as_ref()
1598                .ok_or(Reject::Signature)?
1599                .signature])
1600        || s.canonical_payload != canonical(&payload)?
1601        || s.basis != 1
1602    {
1603        return Err(Reject::Scope);
1604    }
1605    interval(
1606        d.not_before_unix_seconds,
1607        d.expires_at_unix_seconds,
1608        s.observed_at_unix_millis / 1000,
1609    )?;
1610    crate::witness_trust::resolve_statement(set, statement, proof, false, now_ms)
1611}
1612pub fn require_hybrid_peer(
1613    protocol: Option<&crate::heddle::api::common::ProtocolCompatibility>,
1614) -> Result<(), Reject> {
1615    let protocol = protocol.ok_or(Reject::Protocol)?;
1616    if protocol.protocol_version != 2 || protocol.mandatory_features != [1] {
1617        return Err(Reject::Protocol);
1618    }
1619    Ok(())
1620}
1621
1622/// Producer-owned logical-job/lease fence for RetryImportSource and final
1623/// publication. The physical retry row never supplies a new logical identity.
1624pub fn check_job_fence(
1625    logical_job_id: &[u8],
1626    active_delegation_digest: &[u8],
1627    expected_epoch: u64,
1628    active: &VerifiedImportDelegation,
1629    durable_epoch: u64,
1630) -> Result<(), Reject> {
1631    if logical_job_id != active.body.logical_job_id {
1632        return Err(Reject::Scope);
1633    }
1634    if expected_epoch != durable_epoch || active_delegation_digest != active.digest {
1635        return Err(Reject::StaleContext);
1636    }
1637    Ok(())
1638}
1639pub fn validate_public_bundle(bundle: &ImportPublicProofBundleV1) -> Result<(), Reject> {
1640    validate_bundle_bounds(bundle)?;
1641    validate_bundle_history(bundle, true)
1642}
1643fn validate_bundle_bounds(bundle: &ImportPublicProofBundleV1) -> Result<(), Reject> {
1644    use prost::Message;
1645    if bundle.format_version != 1 {
1646        return Err(Reject::Version);
1647    }
1648    if bundle.encoded_len() > MAX_BUNDLE_BYTES
1649        || bundle.owner_histories.len() > 64
1650        || bundle.ownership_transfers.len() > 64
1651        || bundle.genesis_authorities.len() > MAX_BRANCHES
1652        || bundle.delegations.len() != 1
1653        || bundle.operations.len() > MAX_BRANCHES
1654        || bundle.statements.len() > 1024
1655        || bundle.history_proofs.len() > 1024
1656        || bundle.policies.len() > 256
1657        || bundle.original_geneses.len() > MAX_BRANCHES
1658        || bundle.creator_authority_envelopes.len() > MAX_BRANCHES
1659        || bundle.manifests.len() > MAX_BRANCHES
1660        || bundle.genesis_witnesses.len() > 256
1661        || bundle.authority_witnesses.len() > 256
1662        || bundle.landing_witnesses.len() > 256
1663    {
1664        return Err(Reject::Bounds);
1665    }
1666    Ok(())
1667}
1668
1669/// Typed adapter boundary: an authentic unrelated capability/online role must
1670/// never be selected as the parent of an import certificate.
1671pub enum ImportPermissionEvidence<'a> {
1672    Import(&'a SignedImportMemberPermissionV1),
1673    OwnerCapability(&'a SignedOwnerCapability),
1674    OnlineRole(&'a str),
1675}
1676pub fn select_import_permission(
1677    evidence: ImportPermissionEvidence<'_>,
1678) -> Result<&SignedImportMemberPermissionV1, Reject> {
1679    match evidence {
1680        ImportPermissionEvidence::Import(p) => Ok(p),
1681        ImportPermissionEvidence::OwnerCapability(_) | ImportPermissionEvidence::OnlineRole(_) => {
1682            Err(Reject::ImportPermission)
1683        }
1684    }
1685}
1686/// Hybrid dispatch has no legacy execution arm, even for an authentic witness.
1687pub fn require_import_operation_format(format: &str) -> Result<(), Reject> {
1688    if format != OPERATION_DOMAIN {
1689        return Err(Reject::Protocol);
1690    }
1691    Ok(())
1692}
1693pub fn frontier_digest(frontier: &ImportFrontierV1) -> Result<Vec<u8>, Reject> {
1694    if frontier.format_version != 1 {
1695        return Err(Reject::Version);
1696    }
1697    width(&frontier.thread_id, 32)?;
1698    if frontier.operation_ids.len() > 128 {
1699        return Err(Reject::Bounds);
1700    }
1701    for id in &frontier.operation_ids {
1702        width(id, 32)?;
1703    }
1704    if frontier.operation_ids.windows(2).any(|w| w[0] >= w[1]) {
1705        return Err(Reject::Canonical);
1706    }
1707    signing_digest("heddle-import-frontier-v1", frontier)
1708}
1709pub fn content_digest(content: &ImportContentV1) -> Result<Vec<u8>, Reject> {
1710    if content.format_version != 1 {
1711        return Err(Reject::Version);
1712    }
1713    if content.canonical_capture.is_empty() {
1714        return Err(Reject::Bounds);
1715    }
1716    signing_digest("heddle-import-content-v1", content)
1717}
1718pub fn signed_native_digest(record: &SignedRecord) -> Result<Vec<u8>, Reject> {
1719    signing_digest("heddle-signed-native-record-v1", record)
1720}
1721pub(crate) fn verify_native(record: &SignedRecord, format: &str) -> Result<(), Reject> {
1722    if record.format != format {
1723        return Err(Reject::Version);
1724    }
1725    if record.canonical_record.is_empty()
1726        || record.canonical_record.len() > MAX_RECORD_BYTES
1727        || record.signatures.is_empty()
1728        || record.signatures.len() > 16
1729    {
1730        return Err(Reject::Bounds);
1731    }
1732    let mut previous: Option<&[u8]> = None;
1733    let input = [format.as_bytes(), b"\0", &record.canonical_record].concat();
1734    for s in &record.signatures {
1735        if previous.is_some_and(|p| p >= s.public_key.as_slice()) {
1736            return Err(Reject::Canonical);
1737        }
1738        verify(&s.public_key, &input, &s.signature)?;
1739        previous = Some(&s.public_key);
1740    }
1741    Ok(())
1742}
1743/// Recompute transport commitments from exact native evidence. The caller's
1744/// native verifier additionally authenticates manifest membership, receipt
1745/// subjects/bases, accepting authority and canonical native encoding.
1746pub fn verify_boundary_acceptance(e: &ImportBoundaryAcceptanceV1) -> Result<(), Reject> {
1747    let binding = e.binding.as_ref().ok_or(Reject::BoundaryAcceptance)?;
1748    validate_boundary_binding(binding)?;
1749    let acceptance = e
1750        .signed_acceptance
1751        .as_ref()
1752        .ok_or(Reject::BoundaryAcceptance)?;
1753    verify_native(acceptance, "heddle-original-boundary-acceptance-v1")?;
1754    if acceptance.signatures.len() != 1 {
1755        return Err(Reject::Signature);
1756    }
1757    if e.originals_manifest.is_empty()
1758        || e.publication_intent.is_empty()
1759        || e.originals_manifest.len() > MAX_RECORD_BYTES
1760        || e.publication_intent.len() > MAX_RECORD_BYTES
1761        || e.original_receipts.is_empty()
1762        || e.original_receipts.len() > 128
1763    {
1764        return Err(Reject::Bounds);
1765    }
1766    if binding.acceptance_id != native_id(acceptance)
1767        || binding.signed_acceptance_digest != signed_native_digest(acceptance)?
1768        || binding.originals_manifest_digest
1769            != boundary_octets_digest(
1770                "heddle-boundary-originals-manifest-v1",
1771                &e.originals_manifest,
1772            )
1773        || binding.publication_intent_digest
1774            != boundary_octets_digest(
1775                "heddle-boundary-publication-intent-v1",
1776                &e.publication_intent,
1777            )
1778    {
1779        return Err(Reject::BoundaryAcceptance);
1780    }
1781    let native: NativeBoundarySelection =
1782        rmp_serde::from_slice(&acceptance.canonical_record).map_err(|_| Reject::Canonical)?;
1783    if native.originals_manifest.as_slice()
1784        != native_octets_id(
1785            "heddle-original-publication-manifest-v1",
1786            &e.originals_manifest,
1787        )
1788        || native.publication_intent.as_slice()
1789            != native_octets_id(
1790                "heddle-original-publication-intent-v1",
1791                &e.publication_intent,
1792            )
1793    {
1794        return Err(Reject::BoundaryAcceptance);
1795    }
1796    let mut digests = Vec::new();
1797    for receipt in &e.original_receipts {
1798        if ![
1799            "heddle-thread-genesis-admission-v2",
1800            "heddle-thread-authority-admission-v3",
1801        ]
1802        .contains(&receipt.format.as_str())
1803        {
1804            return Err(Reject::Version);
1805        }
1806        verify_native(receipt, &receipt.format)?;
1807        if receipt.signatures.len() != 1 {
1808            return Err(Reject::Signature);
1809        }
1810        let native: NativeBoundaryReceipt =
1811            rmp_serde::from_slice(&receipt.canonical_record).map_err(|_| Reject::Canonical)?;
1812        if native.basis
1813            != (NativeBoundaryBasis::BoundaryAcceptance {
1814                acceptance: binding
1815                    .acceptance_id
1816                    .as_slice()
1817                    .try_into()
1818                    .map_err(|_| Reject::Canonical)?,
1819            })
1820        {
1821            return Err(Reject::BoundaryAcceptance);
1822        }
1823        digests.push(signed_native_digest(receipt)?);
1824    }
1825    if digests != binding.original_receipt_digests {
1826        return Err(Reject::BoundaryAcceptance);
1827    }
1828    Ok(())
1829}
1830// These readers extract only the native commitment selectors. Full native
1831// canonicality, model validity, membership and authority remain the native gate.
1832#[derive(serde::Deserialize)]
1833struct NativeBoundarySelection {
1834    originals_manifest: [u8; 32],
1835    publication_intent: [u8; 32],
1836}
1837#[derive(serde::Deserialize, PartialEq)]
1838enum NativeBoundaryBasis {
1839    OriginalAuthority,
1840    BoundaryAcceptance { acceptance: [u8; 32] },
1841}
1842#[derive(serde::Deserialize)]
1843struct NativeBoundaryReceipt {
1844    basis: NativeBoundaryBasis,
1845    thread: [u8; 32],
1846    subject: Option<NativeBoundarySubject>,
1847}
1848#[derive(serde::Deserialize)]
1849enum NativeBoundarySubject {
1850    Operation([u8; 32]),
1851    OwnershipClaim([u8; 32]),
1852    OwnershipResolution([u8; 32]),
1853}
1854fn native_octets_id(format: &str, bytes: &[u8]) -> Vec<u8> {
1855    let mut h = blake3::Hasher::new();
1856    h.update(format.as_bytes());
1857    h.update(&(bytes.len() as u64).to_le_bytes());
1858    h.update(b"\0");
1859    h.update(bytes);
1860    h.finalize().as_bytes().to_vec()
1861}
1862pub(crate) fn boundary_original(
1863    e: &ImportBoundaryAcceptanceV1,
1864    original: &SignedRecord,
1865) -> Result<(), Reject> {
1866    let id = native_id(original);
1867    for receipt in &e.original_receipts {
1868        let value: NativeBoundaryReceipt =
1869            rmp_serde::from_slice(&receipt.canonical_record).map_err(|_| Reject::Canonical)?;
1870        let (format, subject) = match value.subject {
1871            None if receipt.format == "heddle-thread-genesis-admission-v2" => {
1872                ("heddle-thread-genesis-v1", value.thread)
1873            }
1874            Some(NativeBoundarySubject::Operation(id)) => ("heddle-thread-operation-v1", id),
1875            Some(NativeBoundarySubject::OwnershipClaim(id)) => {
1876                ("heddle-thread-ownership-claim-v1", id)
1877            }
1878            Some(NativeBoundarySubject::OwnershipResolution(id)) => {
1879                ("heddle-thread-ownership-resolution-v1", id)
1880            }
1881            _ => return Err(Reject::BoundaryAcceptance),
1882        };
1883        if original.format == format && id == subject {
1884            return Ok(());
1885        }
1886    }
1887    Err(Reject::BoundaryAcceptance)
1888}
1889pub fn boundary_octets_digest(domain: &str, bytes: &[u8]) -> Vec<u8> {
1890    hash(&[
1891        domain.as_bytes(),
1892        &(bytes.len() as u32).to_be_bytes(),
1893        bytes,
1894    ])
1895}
1896pub fn validate_boundary_binding(
1897    b: &crate::heddle::api::common::HostedWitnessBoundaryAcceptanceV1,
1898) -> Result<(), Reject> {
1899    if b.format_version != 1 {
1900        return Err(Reject::Version);
1901    }
1902    for digest in [
1903        &b.acceptance_id,
1904        &b.signed_acceptance_digest,
1905        &b.originals_manifest_digest,
1906        &b.publication_intent_digest,
1907    ] {
1908        width(digest, 32)?;
1909    }
1910    if b.original_receipt_digests.is_empty() || b.original_receipt_digests.len() > 128 {
1911        return Err(Reject::Bounds);
1912    }
1913    for digest in &b.original_receipt_digests {
1914        width(digest, 32)?;
1915    }
1916    if b.original_receipt_digests.windows(2).any(|w| w[0] >= w[1]) {
1917        return Err(Reject::Canonical);
1918    }
1919    Ok(())
1920}
1921pub fn validate_statement_boundary(
1922    s: &crate::heddle::api::common::HostedWitnessStatementV1,
1923) -> Result<(), Reject> {
1924    match (s.basis, s.boundary_acceptance.as_ref()) {
1925        (1, None) => Ok(()),
1926        (2, Some(b)) if s.purpose == 1 || s.purpose == 2 => validate_boundary_binding(b),
1927        _ => Err(Reject::BoundaryAcceptance),
1928    }
1929}
1930pub(crate) fn match_boundary(
1931    s: &crate::heddle::api::common::HostedWitnessStatementV1,
1932    evidence: &[ImportBoundaryAcceptanceV1],
1933) -> Result<(), Reject> {
1934    validate_statement_boundary(s)?;
1935    let mut previous = None;
1936    for e in evidence {
1937        verify_boundary_acceptance(e)?;
1938        let b = e.binding.as_ref().ok_or(Reject::BoundaryAcceptance)?;
1939        if previous.is_some_and(|p: &[u8]| p >= b.acceptance_id.as_slice()) {
1940            return Err(Reject::Canonical);
1941        }
1942        previous = Some(b.acceptance_id.as_slice());
1943    }
1944    if let Some(binding) = &s.boundary_acceptance
1945        && !evidence.iter().any(|e| e.binding.as_ref() == Some(binding))
1946    {
1947        return Err(Reject::BoundaryAcceptance);
1948    }
1949    Ok(())
1950}
1951fn native_dependencies(
1952    records: &[SignedRecord],
1953    evidence: &[ImportBoundaryAcceptanceV1],
1954) -> Result<(), Reject> {
1955    if records.len() > 128 {
1956        return Err(Reject::Bounds);
1957    }
1958    let mut previous = None;
1959    for record in records {
1960        match record.format.as_str() {
1961            "heddle-thread-genesis-v1"
1962            | "heddle-thread-operation-v1"
1963            | "heddle-thread-ownership-claim-v1"
1964            | "heddle-thread-ownership-resolution-v1" => (),
1965            "heddle-original-boundary-acceptance-v1"
1966            | "heddle-thread-genesis-admission-v2"
1967            | "heddle-thread-authority-admission-v3" => {
1968                if !evidence.iter().any(|e| {
1969                    e.signed_acceptance.as_ref() == Some(record)
1970                        || e.original_receipts.contains(record)
1971                }) {
1972                    return Err(Reject::BoundaryAcceptance);
1973                }
1974            }
1975            _ => return Err(Reject::Version),
1976        }
1977        verify_native(record, &record.format)?;
1978        let digest = signed_native_digest(record)?;
1979        if previous.as_ref().is_some_and(|p| p >= &digest) {
1980            return Err(Reject::Canonical);
1981        }
1982        previous = Some(digest);
1983    }
1984    Ok(())
1985}
1986pub(crate) fn original_signatures(
1987    records: &[&SignedRecord],
1988    extra: &[RecordSignature],
1989) -> Result<Vec<u8>, Reject> {
1990    let signatures = records
1991        .iter()
1992        .flat_map(|r| r.signatures.iter())
1993        .chain(extra.iter())
1994        .collect::<Vec<_>>();
1995    let mut out = (signatures.len() as u32).to_be_bytes().to_vec();
1996    for s in signatures {
1997        s.write(&mut out)?;
1998    }
1999    Ok(hash(&[b"heddle-hosted-original-signatures-v1", &out]))
2000}
2001use crate::hybrid_codec::Canonical;
2002/// Caller constructs this from independently verified native originals and
2003/// accepted owner/policy/landing context. This matching layer verifies original
2004/// signatures and exact payload commitments separately from witness trust; it
2005/// does not replace native causal, authority or landing-model verification.
2006pub enum WitnessPayload<'a> {
2007    Genesis(&'a ImportGenesisWitnessV1),
2008    Authority(&'a ImportAuthorityWitnessV1),
2009    Landing(&'a HostedLandingWitnessV1),
2010}
2011pub fn verify_witness_payload(
2012    statement: &crate::heddle::api::common::HostedWitnessStatementV1,
2013    payload: WitnessPayload<'_>,
2014) -> Result<(), Reject> {
2015    let (purpose, bytes, authority, signatures, publisher) = match payload {
2016        WitnessPayload::Genesis(p) => {
2017            if p.format_version != 1 {
2018                return Err(Reject::Version);
2019            }
2020            let original = p.original_genesis.as_ref().ok_or(Reject::Canonical)?;
2021            let binding = p.binding.as_ref().ok_or(Reject::Canonical)?;
2022            let b = binding.body.as_ref().ok_or(Reject::Canonical)?;
2023            match_boundary(
2024                statement,
2025                &p.boundary_acceptance.iter().cloned().collect::<Vec<_>>(),
2026            )?;
2027            if let Some(e) = &p.boundary_acceptance {
2028                boundary_original(e, original)?;
2029            }
2030            if (statement.basis == 2) != p.boundary_acceptance.is_some() {
2031                return Err(Reject::BoundaryAcceptance);
2032            }
2033            verify_native(original, "heddle-thread-genesis-v1")?;
2034            if native_id(original) != b.genesis_digest {
2035                return Err(Reject::Scope);
2036            }
2037            if let Some(id) = &b.identity {
2038                if statement.spool_uuid != id.spool_uuid
2039                    || statement.spool_genesis_digest != id.spool_genesis_digest
2040                    || statement.owner_id != id.owner_id
2041                    || statement.owner_state_hash != id.owner_state_hash
2042                    || statement.ownership_transfer_sequence != id.ownership_transfer_sequence
2043                {
2044                    return Err(Reject::Scope);
2045                }
2046            } else {
2047                return Err(Reject::Canonical);
2048            }
2049            let creator = original
2050                .signatures
2051                .iter()
2052                .find(|s| s.public_key == b.creator_public_key)
2053                .ok_or(Reject::Signature)?;
2054            if b.original_creator_signature != creator.signature
2055                || b.creator_authority_envelope_digest != hash(&[&p.creator_authority_envelope])
2056            {
2057                return Err(Reject::Scope);
2058            }
2059            verify_authorization_signature(
2060                &b.creator_public_key,
2061                GENESIS_DOMAIN,
2062                b,
2063                binding
2064                    .creator_signature
2065                    .as_ref()
2066                    .ok_or(Reject::Signature)?,
2067            )?;
2068            (
2069                1,
2070                canonical(p)?,
2071                signed_genesis_digest(binding)?,
2072                original_signatures(&[original], &[])?,
2073                key_id(&b.creator_public_key),
2074            )
2075        }
2076        WitnessPayload::Authority(p) => {
2077            if p.format_version != 1 {
2078                return Err(Reject::Version);
2079            }
2080            let original = p.original.as_ref().ok_or(Reject::Canonical)?;
2081            let format = match p.kind {
2082                1 => "heddle-thread-operation-v1",
2083                2 => "heddle-thread-ownership-claim-v1",
2084                3 => "heddle-thread-ownership-resolution-v1",
2085                _ => return Err(Reject::Version),
2086            };
2087            verify_native(original, format)?;
2088            if (p.kind == 2 || p.kind == 3) && original.signatures.len() != 2 {
2089                return Err(Reject::Signature);
2090            }
2091            if !original
2092                .signatures
2093                .iter()
2094                .any(|s| key_id(&s.public_key) == statement.publisher_key_id)
2095            {
2096                return Err(Reject::Signature);
2097            }
2098            if p.authority_envelope.is_empty() || p.authority_envelope.len() > MAX_RECORD_BYTES {
2099                return Err(Reject::Bounds);
2100            }
2101            match_boundary(statement, &p.boundary_acceptances)?;
2102            if let Some(b) = &statement.boundary_acceptance {
2103                let e = p
2104                    .boundary_acceptances
2105                    .iter()
2106                    .find(|e| e.binding.as_ref() == Some(b))
2107                    .ok_or(Reject::BoundaryAcceptance)?;
2108                boundary_original(e, original)?;
2109            }
2110            native_dependencies(&p.dependencies, &p.boundary_acceptances)?;
2111            let records = std::iter::once(original)
2112                .chain(p.dependencies.iter())
2113                .collect::<Vec<_>>();
2114            (
2115                2,
2116                canonical(p)?,
2117                hash(&[
2118                    b"heddle-hosted-authority-envelope-v1",
2119                    &(p.authority_envelope.len() as u32).to_be_bytes(),
2120                    &p.authority_envelope,
2121                ]),
2122                original_signatures(&records, &[])?,
2123                statement.publisher_key_id.clone(),
2124            )
2125        }
2126        WitnessPayload::Landing(p) => {
2127            if p.format_version != 1 {
2128                return Err(Reject::Version);
2129            }
2130            let execution = p.execution.as_ref().ok_or(Reject::Canonical)?;
2131            let source = p.source_operation.as_ref().ok_or(Reject::Canonical)?;
2132            let request = p.request.as_ref().ok_or(Reject::Canonical)?;
2133            if request.format_version != 1
2134                || request.method_path != "/heddle.api.v1alpha2.ThreadService/LandThread"
2135            {
2136                return Err(Reject::Version);
2137            }
2138            verify_native(execution, "heddle-thread-operation-v1")?;
2139            verify_native(source, "heddle-thread-operation-v1")?;
2140            match_boundary(statement, &[])?;
2141            native_dependencies(&p.review_evidence, &[])?;
2142            let signature = request.signature.as_ref().ok_or(Reject::Signature)?;
2143            if request.signing_identity
2144                != format!(
2145                    "principal:device-key:{}",
2146                    hex::encode(&signature.public_key)
2147                )
2148            {
2149                return Err(Reject::Signature);
2150            }
2151            width(&request.nonce, 16)?;
2152            if request.timestamp_millis <= 0
2153                || request.request_body.is_empty()
2154                || request.request_body.len() > MAX_RECORD_BYTES
2155                || p.authority_envelope.is_empty()
2156                || p.authority_envelope.len() > MAX_RECORD_BYTES
2157            {
2158                return Err(Reject::Bounds);
2159            }
2160            let input = crate::signing::unary_bytes(
2161                &request.signing_identity,
2162                &request.method_path,
2163                request.timestamp_millis,
2164                &request.nonce,
2165                &request.request_body,
2166            );
2167            verify(&signature.public_key, &input, &signature.signature)?;
2168            let records = [execution, source]
2169                .into_iter()
2170                .chain(p.review_evidence.iter())
2171                .collect::<Vec<_>>();
2172            (
2173                4,
2174                canonical(p)?,
2175                hash(&[
2176                    b"heddle-hosted-authority-envelope-v1",
2177                    &(p.authority_envelope.len() as u32).to_be_bytes(),
2178                    &p.authority_envelope,
2179                ]),
2180                original_signatures(&records, std::slice::from_ref(signature))?,
2181                key_id(&signature.public_key),
2182            )
2183        }
2184    };
2185    if bytes.len() > MAX_RECORD_BYTES {
2186        return Err(Reject::Bounds);
2187    }
2188    if statement.purpose != purpose
2189        || statement.canonical_payload != bytes
2190        || statement.authority_digest != authority
2191        || statement.original_signatures_digest != signatures
2192        || statement.publisher_key_id != publisher
2193    {
2194        return Err(Reject::Scope);
2195    }
2196    Ok(())
2197}
2198
2199pub fn resolve_bundle_permission<'a>(
2200    bundle: &'a ImportPublicProofBundleV1,
2201    digest: &[u8],
2202) -> Result<Option<&'a SignedImportMemberPermissionV1>, Reject> {
2203    width(digest, 32)?;
2204    if digest == [0; 32] {
2205        return Ok(None);
2206    }
2207    bundle
2208        .member_permission
2209        .iter()
2210        .find(|p| signed_permission_digest(p).is_ok_and(|d| d == digest))
2211        .map(Some)
2212        .ok_or(Reject::ImportPermission)
2213}
2214pub fn resolve_bundle_manifest<'a>(
2215    bundle: &'a ImportPublicProofBundleV1,
2216    digest: &[u8],
2217) -> Result<&'a ImportResultManifestV1, Reject> {
2218    width(digest, 32)?;
2219    bundle
2220        .manifests
2221        .iter()
2222        .find(|m| manifest_digest(m).is_ok_and(|d| d == digest))
2223        .ok_or(Reject::StaleManifest)
2224}
2225pub fn publication_payload(
2226    operation: &SignedDelegatedImportOperationV1,
2227    manifest: &ImportResultManifestV1,
2228) -> Result<ImportPublicationWitnessV1, Reject> {
2229    let o = operation.body.as_ref().ok_or(Reject::Canonical)?;
2230    Ok(ImportPublicationWitnessV1 {
2231        format_version: 1,
2232        signed_operation_digest: signed_operation_digest(operation)?,
2233        delegation_digest: o.delegation_digest.clone(),
2234        logical_job_id: o.logical_job_id.clone(),
2235        retry_lineage_id: o.retry_lineage_id.clone(),
2236        physical_operation_id: o.physical_operation_id.clone(),
2237        ref_name: o.ref_name.clone(),
2238        slot_id: o.slot_id,
2239        hash_algorithm: o.hash_algorithm,
2240        observed_commit_oid: o.observed_commit_oid.clone(),
2241        expected_frontier_digest: o.expected_frontier_digest.clone(),
2242        resulting_frontier_digest: o.resulting_frontier_digest.clone(),
2243        terminal_manifest_digest: manifest_digest(manifest)?,
2244    })
2245}
2246/// Completeness and digest addressing only. Trust/signature verification still
2247/// uses independently selected owner contexts at each witnessed historical time.
2248fn validate_bundle_history(
2249    bundle: &ImportPublicProofBundleV1,
2250    require_admissions: bool,
2251) -> Result<(), Reject> {
2252    fn sorted<T>(
2253        values: &[T],
2254        digest: impl Fn(&T) -> Result<Vec<u8>, Reject>,
2255    ) -> Result<(), Reject> {
2256        let mut previous = None;
2257        for value in values {
2258            let d = digest(value)?;
2259            if previous.as_ref().is_some_and(|p| p >= &d) {
2260                return Err(Reject::Canonical);
2261            }
2262            previous = Some(d);
2263        }
2264        Ok(())
2265    }
2266    for operation in &bundle.operations {
2267        if operation.body.is_none() {
2268            return Err(Reject::Canonical);
2269        }
2270    }
2271    for statement in &bundle.statements {
2272        let s = statement.body.as_ref().ok_or(Reject::Canonical)?;
2273        validate_statement_boundary(s)?;
2274        require_policy_history(
2275            &bundle.policies,
2276            &s.spool_uuid,
2277            s.policy_sequence,
2278            &s.policy_state_hash,
2279        )?;
2280    }
2281    sorted(&bundle.manifests, manifest_digest)?;
2282    if let Some(p) = &bundle.member_permission
2283        && resolve_bundle_permission(bundle, &signed_permission_digest(p)?)? != Some(p)
2284    {
2285        return Err(Reject::ImportPermission);
2286    }
2287    let terminal = bundle.terminal_manifest.as_ref().ok_or(Reject::Canonical)?;
2288    if resolve_bundle_manifest(bundle, &manifest_digest(terminal)?)? != terminal {
2289        return Err(Reject::Canonical);
2290    }
2291    if bundle.delegations.len() != 1 {
2292        return Err(Reject::Canonical);
2293    }
2294    for d in &bundle.delegations {
2295        let body = d.body.as_ref().ok_or(Reject::Canonical)?;
2296        resolve_bundle_permission(bundle, &body.parent_permission_digest)?;
2297        for branch in &body.branch_manifest {
2298            let g = bundle
2299                .genesis_authorities
2300                .iter()
2301                .find(|g| {
2302                    signed_genesis_digest(g).is_ok_and(|h| h == branch.genesis_authority_digest)
2303                })
2304                .ok_or(Reject::Scope)?;
2305            let b = g.body.as_ref().ok_or(Reject::Canonical)?;
2306            resolve_bundle_permission(bundle, &b.parent_permission_digest)?;
2307            if !bundle
2308                .original_geneses
2309                .iter()
2310                .any(|o| native_id(o) == b.genesis_digest)
2311                || !bundle
2312                    .creator_authority_envelopes
2313                    .iter()
2314                    .any(|e| hash(&[e]) == b.creator_authority_envelope_digest)
2315            {
2316                return Err(Reject::Scope);
2317            }
2318            // Every published branch needs its original admission, not merely its
2319            // binding. Proof-only retirement lookup cannot recover a payload.
2320            if require_admissions
2321                && bundle.operations.iter().any(|o| {
2322                    o.body
2323                        .as_ref()
2324                        .is_some_and(|o| o.genesis_digest == b.genesis_digest)
2325                })
2326                && !bundle.genesis_witnesses.iter().any(|payload| {
2327                    payload.binding.as_ref() == Some(g)
2328                        && payload.original_genesis.as_ref().is_some_and(|o| {
2329                            native_id(o) == b.genesis_digest && bundle.original_geneses.contains(o)
2330                        })
2331                        && hash(&[&payload.creator_authority_envelope])
2332                            == b.creator_authority_envelope_digest
2333                        && canonical(payload).is_ok_and(|bytes| {
2334                            bundle.statements.iter().any(|s| {
2335                                s.body
2336                                    .as_ref()
2337                                    .is_some_and(|s| s.purpose == 1 && s.canonical_payload == bytes)
2338                            })
2339                        })
2340                })
2341            {
2342                return Err(Reject::Scope);
2343            }
2344        }
2345    }
2346    for manifest in &bundle.manifests {
2347        validate_manifest(manifest)?;
2348        if manifest.logical_job_id != terminal.logical_job_id
2349            || manifest.retry_lineage_id != terminal.retry_lineage_id
2350        {
2351            return Err(Reject::Scope);
2352        }
2353        for slot in &manifest.slots {
2354            let operation = bundle
2355                .operations
2356                .iter()
2357                .find(|o| {
2358                    signed_operation_digest(o).is_ok_and(|d| d == slot.signed_operation_digest)
2359                })
2360                .ok_or(Reject::Scope)?;
2361            if !check_slot_replay(manifest, operation)? || !check_slot_replay(terminal, operation)?
2362            {
2363                return Err(Reject::Scope);
2364            }
2365        }
2366    }
2367    for operation in &bundle.operations {
2368        let o = operation.body.as_ref().ok_or(Reject::Canonical)?;
2369        if !bundle
2370            .delegations
2371            .iter()
2372            .any(|d| signed_delegation_digest(d).is_ok_and(|h| h == o.delegation_digest))
2373            || !check_slot_replay(terminal, operation)?
2374        {
2375            return Err(Reject::Scope);
2376        }
2377        if !bundle.manifests.iter().any(|m| {
2378            check_slot_replay(m, operation) == Ok(true)
2379                && publication_payload(operation, m)
2380                    .and_then(|p| canonical(&p))
2381                    .is_ok_and(|p| {
2382                        bundle.statements.iter().any(|s| {
2383                            s.body
2384                                .as_ref()
2385                                .is_some_and(|s| s.purpose == 3 && s.canonical_payload == p)
2386                        })
2387                    })
2388        }) {
2389            return Err(Reject::Scope);
2390        }
2391    }
2392    for statement in &bundle.statements {
2393        let s = statement.body.as_ref().ok_or(Reject::Canonical)?;
2394        let found = match s.purpose {
2395            1 => bundle
2396                .genesis_witnesses
2397                .iter()
2398                .any(|p| canonical(p).is_ok_and(|p| p == s.canonical_payload)),
2399            2 => bundle
2400                .authority_witnesses
2401                .iter()
2402                .any(|p| canonical(p).is_ok_and(|p| p == s.canonical_payload)),
2403            3 => bundle.operations.iter().any(|o| {
2404                bundle.manifests.iter().any(|m| {
2405                    publication_payload(o, m)
2406                        .and_then(|p| canonical(&p))
2407                        .is_ok_and(|p| p == s.canonical_payload)
2408                })
2409            }),
2410            4 => bundle
2411                .landing_witnesses
2412                .iter()
2413                .any(|p| canonical(p).is_ok_and(|p| p == s.canonical_payload)),
2414            _ => return Err(Reject::Version),
2415        };
2416        if !found {
2417            return Err(Reject::Scope);
2418        }
2419    }
2420    Ok(())
2421}
2422/// Reference completeness only. Native verification must authenticate every
2423/// selected policy, its owner context and the receipt before using its time.
2424pub(crate) fn require_policy_history(
2425    policies: &[SignedSpoolPolicyRecord],
2426    spool: &[u8],
2427    mut sequence: u64,
2428    state_hash: &[u8],
2429) -> Result<(), Reject> {
2430    let mut state_hash = state_hash.to_vec();
2431    for _ in 0..=policies.len() {
2432        width(&state_hash, 32)?;
2433        if sequence == 0 {
2434            return if state_hash == [0; 32] {
2435                Ok(())
2436            } else {
2437                Err(Reject::Scope)
2438            };
2439        }
2440        let mut matches = policies.iter().filter_map(|p| p.body.as_ref()).filter(|p| {
2441            p.spool_uuid == spool && p.sequence == sequence && p.policy_state_hash == state_hash
2442        });
2443        let policy = matches.next().ok_or(Reject::Scope)?;
2444        if matches.next().is_some() {
2445            return Err(Reject::Canonical);
2446        }
2447        let head = policy.expected_head.as_ref().ok_or(Reject::Canonical)?;
2448        if head.sequence.checked_add(1) != Some(sequence) {
2449            return Err(Reject::Scope);
2450        }
2451        sequence = head.sequence;
2452        state_hash = head.state_hash.clone();
2453    }
2454    Err(Reject::Scope)
2455}
2456pub(crate) fn native_id(record: &SignedRecord) -> Vec<u8> {
2457    let mut h = blake3::Hasher::new();
2458    h.update(record.format.as_bytes());
2459    h.update(&(record.canonical_record.len() as u64).to_le_bytes());
2460    h.update(b"\0");
2461    h.update(&record.canonical_record);
2462    h.finalize().as_bytes().to_vec()
2463}
2464
2465/// Caller-generated non-nil UUID, reserved as the first physical operation ID.
2466/// Occupancy is checked under the host's reservation/activation transaction.
2467pub fn initial_operation_id(lineage: &[u8], occupied: bool) -> Result<String, Reject> {
2468    width(lineage, 16)?;
2469    if lineage.iter().all(|b| *b == 0) {
2470        return Err(Reject::Canonical);
2471    }
2472    if occupied {
2473        return Err(Reject::OperationIdReused);
2474    }
2475    let h = hex::encode(lineage);
2476    Ok(format!(
2477        "{}-{}-{}-{}-{}",
2478        &h[..8],
2479        &h[8..12],
2480        &h[12..16],
2481        &h[16..20],
2482        &h[20..]
2483    ))
2484}
2485
2486/// Evaluate inside the cancellation transaction, after caller-scoped replay lookup.
2487/// The selector names only the ACTIVE delegation. Parent revocation is independent.
2488pub fn check_cancel_request(
2489    request: &CancelImportJobRequest,
2490    active: &SignedImportJobDelegationV1,
2491    durable_epoch: u64,
2492    cancelled: bool,
2493) -> Result<(), Reject> {
2494    let d = active.body.as_ref().ok_or(Reject::Canonical)?;
2495    width(&request.logical_job_id, 16)?;
2496    width(&request.cancellation_id, 32)?;
2497    let id = d.identity.as_ref().ok_or(Reject::Canonical)?;
2498    if request.client_operation_id.is_empty()
2499        || request.destination.as_ref().is_none_or(|s| {
2500            initial_operation_id(&id.spool_uuid, false).map_or(true, |uuid| s.id != uuid)
2501        })
2502        || request.logical_job_id != d.logical_job_id
2503    {
2504        return Err(Reject::Scope);
2505    }
2506    if durable_epoch == 0 || request.expected_authority_epoch != durable_epoch {
2507        return Err(Reject::StaleContext);
2508    }
2509    if request.cancellation_id != d.cancellation_id {
2510        return Err(Reject::Scope);
2511    }
2512    if cancelled {
2513        return Err(Reject::Revoked);
2514    }
2515    Ok(())
2516}
2517/// Exact replay acknowledges the stored cancellation without advancing the epoch.
2518pub fn check_cancel_replay(
2519    request: &CancelImportJobRequest,
2520    stored: &CancelImportJobRequest,
2521) -> Result<(), Reject> {
2522    if request != stored {
2523        return Err(Reject::OperationIdReused);
2524    }
2525    Ok(())
2526}
2527/// Check both independent revocation selectors, regardless of Cancel's selector.
2528pub fn check_import_revocations(
2529    delegation: &SignedImportJobDelegationV1,
2530    member: Option<&SignedImportMemberPermissionV1>,
2531    revoked: &[Vec<u8>],
2532) -> Result<(), Reject> {
2533    let d = delegation.body.as_ref().ok_or(Reject::Canonical)?;
2534    width(&d.cancellation_id, 32)?;
2535    if revoked.contains(&d.cancellation_id) {
2536        return Err(Reject::Revoked);
2537    }
2538    if let Some(parent) = member {
2539        let p = parent.body.as_ref().ok_or(Reject::ImportPermission)?;
2540        width(&p.cancellation_id, 32)?;
2541        if revoked.contains(&p.cancellation_id) {
2542            return Err(Reject::Revoked);
2543        }
2544    }
2545    Ok(())
2546}
2547
2548/// Compute the exact remaining total and slots from an authenticated manifest.
2549/// An empty result is completed work and cannot pass new-scope validation.
2550pub fn remaining_import_scope(
2551    scope: &ImportPermissionScopeV1,
2552    committed: &ImportResultManifestV1,
2553) -> Result<ImportPermissionScopeV1, Reject> {
2554    validate_scope(scope)?;
2555    validate_manifest(committed)?;
2556    let mut remaining = scope.clone();
2557    for slot in &committed.slots {
2558        if !scope
2559            .branches
2560            .iter()
2561            .any(|b| b.ref_name == slot.ref_name && b.slot_id == slot.slot_id)
2562        {
2563            return Err(Reject::Scope);
2564        }
2565        {
2566            remaining.max_result_bytes = remaining
2567                .max_result_bytes
2568                .checked_sub(slot.result_bytes)
2569                .ok_or(Reject::Scope)?;
2570            remaining.max_operations = remaining
2571                .max_operations
2572                .checked_sub(1)
2573                .ok_or(Reject::Scope)?;
2574        }
2575    }
2576    remaining.branches.retain(|b| {
2577        !committed
2578            .slots
2579            .iter()
2580            .any(|s| s.ref_name == b.ref_name && s.slot_id == b.slot_id)
2581    });
2582    Ok(remaining)
2583}
2584
2585/// Validate discovery metadata only; a well-shaped selector grants no authority.
2586pub fn validate_hybrid_import_job_selector(
2587    selector: &HybridImportJobSelector,
2588) -> Result<(), Reject> {
2589    width(&selector.logical_job_id, 16)?;
2590    if selector.logical_job_id.iter().all(|byte| *byte == 0) {
2591        return Err(Reject::Canonical);
2592    }
2593    Ok(())
2594}
2595
2596/// Project a visible operation's durable HYBRID association into the existing
2597/// writer-only state read. Missing/unknown subject or selector is unavailable.
2598/// Malformed present metadata is rejected; never substitute an attempt ID.
2599/// This validates shape, not operation visibility, writer access or signatures.
2600pub fn import_job_state_request_from_operation(
2601    operation: &OperationRecord,
2602) -> Result<Option<GetImportJobStateRequest>, Reject> {
2603    let Some(operation_subject::Subject::Import(subject)) = operation
2604        .subject
2605        .as_ref()
2606        .and_then(|subject| subject.subject.as_ref())
2607    else {
2608        return Ok(None);
2609    };
2610    let Some(selector) = subject.hybrid_job.as_ref() else {
2611        return Ok(None);
2612    };
2613    validate_hybrid_import_job_selector(selector)?;
2614    let request = GetImportJobStateRequest {
2615        destination: operation
2616            .r#ref
2617            .as_ref()
2618            .and_then(|record| record.spool.clone()),
2619        logical_job_id: selector.logical_job_id.clone(),
2620    };
2621    validate_job_state_request(&request)?;
2622    Ok(Some(request))
2623}
2624
2625/// Finite destination-writer read; transport authentication/authorization belongs
2626/// to the generated RPC contract. Validate before any storage lookup.
2627pub fn validate_job_state_request(request: &GetImportJobStateRequest) -> Result<(), Reject> {
2628    use prost::Message;
2629    if request.encoded_len() > 4096 {
2630        return Err(Reject::Bounds);
2631    }
2632    initial_operation_id(&request.logical_job_id, false)?;
2633    let destination = request.destination.as_ref().ok_or(Reject::Scope)?;
2634    let compact = destination.id.replace('-', "");
2635    let raw = hex::decode(&compact).map_err(|_| Reject::Scope)?;
2636    if initial_operation_id(&raw, false).map_or(true, |id| id != destination.id) {
2637        return Err(Reject::Scope);
2638    }
2639    Ok(())
2640}
2641
2642/// Supply the authenticated read, never an incoming untrusted state assertion.
2643pub fn validate_job_state_response(
2644    request: &GetImportJobStateRequest,
2645    response: &GetImportJobStateResponse,
2646) -> Result<(), Reject> {
2647    use prost::Message;
2648    validate_job_state_request(request)?;
2649    if response.encoded_len() > 4096 {
2650        return Err(Reject::Bounds);
2651    }
2652    if !(1..=5).contains(&response.status) || response.authority_epoch == 0 {
2653        return Err(Reject::Canonical);
2654    }
2655    width(&response.active_cancellation_id, 32)?;
2656    width(&response.active_delegation_digest, 32)?;
2657    validate_retry_availability(response, request.destination.as_ref().ok_or(Reject::Scope)?)
2658}
2659
2660/// Independently installed descriptor pin; never learned from a response.
2661#[derive(Debug, Clone, PartialEq)]
2662pub struct ImportWitnessRootPin {
2663    pub authority: String,
2664    pub root_id: String,
2665    pub public_key: Vec<u8>,
2666    pub epoch: u64,
2667}
2668/// Receiver-owned durable data, committed atomically with accepted history.
2669/// Do not deserialize this from the incoming proof or lower its clock floor.
2670#[derive(Debug, Clone, PartialEq)]
2671pub struct ImportWitnessSnapshot {
2672    pub root: ImportWitnessRootPin,
2673    pub witness_set: crate::heddle::api::common::SignedHostedWitnessSetV1,
2674    pub clock_floor_unix_millis: i64,
2675    pub job_associations: Vec<(Vec<u8>, Vec<u8>)>,
2676    pub accepted_history: Vec<ImportPublicProofBundleV1>,
2677}
2678/// Witnessed requires an authenticated observation for every accepted delegation.
2679/// Recovery can retain witnessed history but grants no admission for the active tail.
2680#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2681pub enum ImportBundleEvidence {
2682    Recovery,
2683    Witnessed,
2684}
2685#[derive(Debug, Clone, PartialEq)]
2686pub struct VerifiedImportBundleWitnesses {
2687    pub evidence: ImportBundleEvidence,
2688    pub accepted_history: ImportResultManifestV1,
2689    pub snapshot: Option<ImportWitnessSnapshot>,
2690    pub snapshot_advanced: bool,
2691    pub owner_check_time_unix_seconds: Option<i64>,
2692}
2693/// Check the host's signed same-transaction assertion for a P1 and its consumed P3.
2694/// Receivers verify consistency; only the issuing host can ensure atomic visibility.
2695pub fn check_import_genesis_publication_pair(
2696    delegation: &VerifiedImportDelegation,
2697    admission: &crate::heddle::api::common::HostedWitnessStatementV1,
2698    publication: &crate::heddle::api::common::HostedWitnessStatementV1,
2699) -> Result<(), Reject> {
2700    validity(
2701        delegation.body.not_before_unix_seconds,
2702        delegation.body.expires_at_unix_seconds,
2703        admission.observed_at_unix_millis / 1000,
2704        true,
2705    )?;
2706    if admission.purpose != 1
2707        || publication.purpose != 3
2708        || admission.observed_at_unix_millis != publication.observed_at_unix_millis
2709        || admission.host_transaction_id != publication.host_transaction_id
2710        || admission.executor_id != publication.executor_id
2711        || admission.admission_order >= publication.admission_order
2712    {
2713        return Err(Reject::Transition);
2714    }
2715    Ok(())
2716}
2717
2718/// Verify public Fetch/export evidence. Owner contexts
2719/// are resolved independently at each authenticated time. The verifier derives times
2720/// from the first authenticated publication of the sole delegation.
2721/// Unwitnessed certificates are time-free recovery only.
2722/// The mandatory hook verifies the selected policy chain and owner/native context
2723/// at each authenticated statement time (heddle capability-verifier / WASM).
2724/// With no statements it receives None and verifies time-free policy closure.
2725/// No result is returned on failure. Recovery without a witnessed prefix or new
2726/// authenticated set returns the input snapshot unchanged. A witnessed prefix
2727/// extends rollback protection; recovery cannot persist job history. A new set
2728/// can additionally advance set trust and clock. None remains None when no
2729/// set is carried and no input exists. Persist under the trust lock; inspect
2730/// snapshot_advanced for actual durable change, independently of evidence.
2731pub fn verify_import_bundle_witnesses<'a>(
2732    bundle: &ImportPublicProofBundleV1,
2733    pin: &ImportWitnessRootPin,
2734    snapshot: Option<&ImportWitnessSnapshot>,
2735    now_ms: i64,
2736    mut owner_at: impl FnMut(Option<i64>) -> Result<ImportBundleOwnerExpectation<'a>, Reject>,
2737    mut verify_policy: impl FnMut(
2738        &ImportPublicProofBundleV1,
2739        Option<&crate::heddle::api::common::HostedWitnessStatementV1>,
2740    ) -> Result<(), Reject>,
2741) -> Result<VerifiedImportBundleWitnesses, Reject> {
2742    use crate::witness_trust as trust;
2743    width(&pin.public_key, 32)?;
2744    if pin.epoch == 0 {
2745        return Err(Reject::StaleContext);
2746    }
2747    validate_bundle_bounds(bundle)?;
2748    let terminal = bundle.terminal_manifest.as_ref().ok_or(Reject::Canonical)?;
2749    validate_bundle_history(bundle, !terminal.slots.is_empty())?;
2750    let mut associations = snapshot.map_or_else(Vec::new, |s| s.job_associations.clone());
2751    for d in &bundle.delegations {
2752        let b = d.body.as_ref().ok_or(Reject::Canonical)?;
2753        if associations
2754            .iter()
2755            .any(|(key, job)| *key == b.job_public_key && *job != b.logical_job_id)
2756        {
2757            return Err(Reject::KeyRole);
2758        }
2759        if !associations.iter().any(|(key, _)| *key == b.job_public_key) {
2760            associations.push((b.job_public_key.clone(), b.logical_job_id.clone()));
2761        }
2762    }
2763    let job_keys = associations
2764        .iter()
2765        .map(|(key, _)| key.clone())
2766        .collect::<Vec<_>>();
2767    fn expectation<'a>(
2768        root: &'a ImportWitnessRootPin,
2769        floor: i64,
2770        now: i64,
2771        keys: &'a [Vec<u8>],
2772    ) -> trust::SetExpectation<'a> {
2773        trust::SetExpectation {
2774            authority: &root.authority,
2775            root_id: &root.root_id,
2776            root_public_key: &root.public_key,
2777            root_epoch: root.epoch,
2778            now_unix_millis: now,
2779            clock_floor_unix_millis: floor,
2780            known_job_keys: keys,
2781        }
2782    }
2783    let previous = if let Some(s) = snapshot {
2784        if s.root.authority != pin.authority {
2785            return Err(Reject::Root);
2786        }
2787        let restored = trust::restore_history_snapshot(
2788            &s.witness_set,
2789            &expectation(&s.root, 0, now_ms, &job_keys),
2790        )?;
2791        Some(restored)
2792    } else {
2793        None
2794    };
2795    let carried = bundle.witness_set.as_ref();
2796    if carried.is_none() && !bundle.statements.is_empty() {
2797        return Err(Reject::Canonical);
2798    }
2799    let new_set =
2800        carried.is_some_and(|c| snapshot.is_none_or(|s| s.root != *pin || s.witness_set != *c));
2801    let selected = expectation(
2802        pin,
2803        snapshot.map_or(0, |s| s.clock_floor_unix_millis),
2804        now_ms,
2805        &job_keys,
2806    );
2807    let set = carried
2808        .map(|carried| {
2809            if snapshot.is_some_and(|s| s.root != *pin) {
2810                trust::verify_set_after_root_replacement(
2811                    carried,
2812                    &selected,
2813                    previous.as_ref().ok_or(Reject::StaleContext)?,
2814                )
2815            } else {
2816                trust::verify_set(carried, &selected, previous.as_ref())
2817            }
2818        })
2819        .transpose()?;
2820    // Authenticate statements before using their observation times or policies.
2821    let mut resolved = Vec::new();
2822    for signed in &bundle.statements {
2823        let s = signed.body.as_ref().ok_or(Reject::Canonical)?;
2824        let set = set.as_ref().ok_or(Reject::Canonical)?;
2825        let entry = set
2826            .body()
2827            .entries
2828            .iter()
2829            .find(|e| e.executor_id == s.executor_id)
2830            .ok_or(Reject::Root)?;
2831        let proof = if entry.state == 2 {
2832            let leaf = trust::leaf_digest(s.purpose, &canonical(s)?, &signed.signature)?;
2833            bundle.history_proofs.iter().find(|p| {
2834                p.purpose == s.purpose && trust::verify_inclusion(&leaf, p, entry).is_ok()
2835            })
2836        } else {
2837            None
2838        };
2839        let context = trust::resolve_statement(set, signed, proof, false, now_ms)?;
2840        verify_policy(bundle, Some(s))?;
2841        resolved.push((context, proof));
2842    }
2843    if bundle.statements.is_empty() {
2844        // Time-free policy/owner/native closure; this asserts no admission event.
2845        verify_policy(bundle, None)?;
2846    }
2847    // Derive owner-selection times only from authenticated receipts. Prefer the
2848    // first publication for each delegation; initial admissions stand alone too.
2849    // Select precisely the P3 each progressive prefix consumes, independent of
2850    // statement array order. Every carried P3 must be consumed exactly once.
2851    let mut prefix = ImportResultManifestV1 {
2852        slots: vec![],
2853        ..terminal.clone()
2854    };
2855    let mut selected_publications = Vec::new();
2856    for operation in &bundle.operations {
2857        let digest = signed_operation_digest(operation)?;
2858        let slot = terminal
2859            .slots
2860            .iter()
2861            .find(|slot| slot.signed_operation_digest == digest)
2862            .ok_or(Reject::Scope)?;
2863        prefix.slots.push(slot.clone());
2864        prefix
2865            .slots
2866            .sort_by(|a, b| (&a.ref_name, a.slot_id).cmp(&(&b.ref_name, b.slot_id)));
2867        let payload = canonical(&publication_payload(operation, &prefix)?)?;
2868        let matches = bundle
2869            .statements
2870            .iter()
2871            .filter(|signed| {
2872                signed
2873                    .body
2874                    .as_ref()
2875                    .is_some_and(|s| s.purpose == 3 && s.canonical_payload == payload)
2876            })
2877            .collect::<Vec<_>>();
2878        if matches.len() != 1 {
2879            return Err(Reject::Transition);
2880        }
2881        selected_publications.push(matches[0]);
2882    }
2883    if bundle.statements.iter().any(|signed| {
2884        signed
2885            .body
2886            .as_ref()
2887            .is_some_and(|s| s.purpose == 3 && !selected_publications.contains(&signed))
2888    }) {
2889        return Err(Reject::Transition);
2890    }
2891    let mut admitted_geneses = std::collections::BTreeSet::<Vec<u8>>::new();
2892    let mut times = vec![None; bundle.delegations.len()];
2893    let mut publications = Vec::new();
2894    for signed in &bundle.statements {
2895        let statement = signed.body.as_ref().ok_or(Reject::Canonical)?;
2896        if statement.purpose != 3 {
2897            continue;
2898        }
2899        let (operation, manifest) = bundle
2900            .operations
2901            .iter()
2902            .flat_map(|o| bundle.manifests.iter().map(move |m| (o, m)))
2903            .find(|(o, m)| {
2904                publication_payload(o, m)
2905                    .and_then(|p| canonical(&p))
2906                    .is_ok_and(|b| b == statement.canonical_payload)
2907            })
2908            .ok_or(Reject::Scope)?;
2909        let digest = &operation
2910            .body
2911            .as_ref()
2912            .ok_or(Reject::Canonical)?
2913            .delegation_digest;
2914        let index = bundle
2915            .delegations
2916            .iter()
2917            .position(|d| signed_delegation_digest(d).is_ok_and(|h| h == *digest))
2918            .ok_or(Reject::Scope)?;
2919        let time = statement.observed_at_unix_millis / 1000;
2920        // First means accepted publication order, independent of array order.
2921        if times[index].is_none_or(|(order, _)| statement.admission_order < order) {
2922            times[index] = Some((statement.admission_order, time));
2923        }
2924        publications.push((signed, operation, manifest, index));
2925    }
2926    // Resolve only after authentication. Facts must cover the selected time;
2927    // current claimed state cannot stand in for an earlier deferred state.
2928    let mut resolve_owner = |time: Option<i64>| {
2929        let facts = owner_at(time)?;
2930        if facts.effective_from_unix_seconds < 0
2931            || facts
2932                .effective_until_unix_seconds
2933                .is_some_and(|end| end <= facts.effective_from_unix_seconds)
2934            || time.is_some_and(|t| {
2935                t < facts.effective_from_unix_seconds
2936                    || facts
2937                        .effective_until_unix_seconds
2938                        .is_some_and(|end| t >= end)
2939            })
2940        {
2941            return Err(Reject::Scope);
2942        }
2943        for (key, job) in facts.known_job_associations {
2944            if associations.iter().any(|(k, j)| k == key && j != job) {
2945                return Err(Reject::KeyRole);
2946            }
2947            if !associations.iter().any(|(k, _)| k == key) {
2948                associations.push((key.clone(), job.clone()));
2949            }
2950        }
2951        if facts
2952            .forbidden_job_keys
2953            .iter()
2954            .any(|key| associations.iter().any(|(known, _)| known == key))
2955        {
2956            return Err(Reject::KeyRole);
2957        }
2958        // Also keep newly supplied known job keys disjoint from witness roles.
2959        if set.as_ref().is_some_and(|set| {
2960            facts.known_job_associations.iter().any(|(key, _)| {
2961                *key == pin.public_key || set.body().entries.iter().any(|e| e.public_key == *key)
2962            })
2963        }) {
2964            return Err(Reject::KeyRole);
2965        }
2966        Ok((facts, associations.clone()))
2967    };
2968    let mut verified = Vec::new();
2969    for (i, d) in bundle.delegations.iter().enumerate() {
2970        let body = d.body.as_ref().ok_or(Reject::Canonical)?;
2971        let parent = resolve_bundle_permission(bundle, &body.parent_permission_digest)?;
2972        let time = times[i].map(|(_, time)| time);
2973        let (facts, selected_associations) = resolve_owner(time)?;
2974        let owner = facts.at(time.unwrap_or(0), &selected_associations);
2975        let token = verify_delegation_inner(d, parent, &owner, times[i].is_some())?;
2976        verified.push(token);
2977    }
2978    let initial = verified.first().ok_or(Reject::Canonical)?;
2979    for branch in &initial.body.branch_manifest {
2980        let limit = branch.limit.as_ref().ok_or(Reject::Canonical)?;
2981        let binding = bundle
2982            .genesis_authorities
2983            .iter()
2984            .find(|g| signed_genesis_digest(g).is_ok_and(|h| h == branch.genesis_authority_digest))
2985            .ok_or(Reject::Scope)?;
2986        let original = bundle
2987            .original_geneses
2988            .iter()
2989            .find(|o| native_id(o) == limit.genesis_digest)
2990            .ok_or(Reject::Scope)?;
2991        let g = binding.body.as_ref().ok_or(Reject::Canonical)?;
2992        let envelope = bundle
2993            .creator_authority_envelopes
2994            .iter()
2995            .find(|e| hash(&[e]) == g.creator_authority_envelope_digest)
2996            .ok_or(Reject::Scope)?;
2997        verify_native(original, "heddle-thread-genesis-v1")?;
2998        let signature = original
2999            .signatures
3000            .iter()
3001            .find(|s| s.public_key == g.creator_public_key)
3002            .ok_or(Reject::Scope)?;
3003        verify_genesis_authority(
3004            binding,
3005            initial,
3006            &limit.genesis_digest,
3007            &signature.signature,
3008            &hash(&[envelope]),
3009        )?;
3010    }
3011    for ((context, proof), signed) in resolved.iter().zip(&bundle.statements) {
3012        let s = signed.body.as_ref().ok_or(Reject::Canonical)?;
3013        if !verified.iter().any(|d| {
3014            d.body.identity.as_ref().is_some_and(|id| {
3015                s.spool_uuid == id.spool_uuid
3016                    && s.spool_genesis_digest == id.spool_genesis_digest
3017                    && s.owner_id == id.owner_id
3018                    && s.owner_state_hash == id.owner_state_hash
3019                    && s.ownership_transfer_sequence == id.ownership_transfer_sequence
3020            })
3021        }) {
3022            return Err(Reject::Scope);
3023        }
3024        match s.purpose {
3025            1 => {
3026                // Every original admission must independently satisfy [N,E).
3027                let time = s.observed_at_unix_millis / 1000;
3028                let (facts, selected_associations) = resolve_owner(Some(time))?;
3029                let owner = facts.at(time, &selected_associations);
3030                verify_delegation(
3031                    &bundle.delegations[0],
3032                    resolve_bundle_permission(bundle, &initial.body.parent_permission_digest)?,
3033                    &owner,
3034                )?;
3035                let payload = bundle
3036                    .genesis_witnesses
3037                    .iter()
3038                    .find(|p| canonical(*p).is_ok_and(|b| b == s.canonical_payload))
3039                    .ok_or(Reject::Scope)?;
3040                let genesis = &payload
3041                    .binding
3042                    .as_ref()
3043                    .and_then(|g| g.body.as_ref())
3044                    .ok_or(Reject::Canonical)?
3045                    .genesis_digest;
3046                if !admitted_geneses.insert(genesis.clone()) {
3047                    return Err(Reject::Transition);
3048                }
3049                let publication = bundle
3050                    .operations
3051                    .iter()
3052                    .zip(&selected_publications)
3053                    .find(|(o, _)| {
3054                        o.body
3055                            .as_ref()
3056                            .is_some_and(|o| &o.genesis_digest == genesis)
3057                    })
3058                    .and_then(|(_, s)| s.body.as_ref())
3059                    .ok_or(Reject::Transition)?;
3060                check_import_genesis_publication_pair(initial, s, publication)?;
3061                verify_witness_payload(
3062                    s,
3063                    WitnessPayload::Genesis(
3064                        bundle
3065                            .genesis_witnesses
3066                            .iter()
3067                            .find(|p| canonical(*p).is_ok_and(|b| b == s.canonical_payload))
3068                            .ok_or(Reject::Scope)?,
3069                    ),
3070                )?;
3071            }
3072            2 => verify_witness_payload(
3073                s,
3074                WitnessPayload::Authority(
3075                    bundle
3076                        .authority_witnesses
3077                        .iter()
3078                        .find(|p| canonical(*p).is_ok_and(|b| b == s.canonical_payload))
3079                        .ok_or(Reject::Scope)?,
3080                ),
3081            )?,
3082            4 => verify_witness_payload(
3083                s,
3084                WitnessPayload::Landing(
3085                    bundle
3086                        .landing_witnesses
3087                        .iter()
3088                        .find(|p| canonical(*p).is_ok_and(|b| b == s.canonical_payload))
3089                        .ok_or(Reject::Scope)?,
3090                ),
3091            )?,
3092            3 => {
3093                let (_, operation, manifest, index) = publications
3094                    .iter()
3095                    .find(|(statement, _, _, _)| *statement == signed)
3096                    .ok_or(Reject::Scope)?;
3097                let d = &bundle.delegations[*index];
3098                let body = d.body.as_ref().ok_or(Reject::Canonical)?;
3099                let time = s.observed_at_unix_millis / 1000;
3100                let (facts, selected_associations) = resolve_owner(Some(time))?;
3101                let owner = facts.at(time, &selected_associations);
3102                let delegation = verify_delegation(
3103                    d,
3104                    resolve_bundle_permission(bundle, &body.parent_permission_digest)?,
3105                    &owner,
3106                )?;
3107                verify_publication(
3108                    operation,
3109                    &delegation,
3110                    manifest,
3111                    signed,
3112                    set.as_ref().ok_or(Reject::Canonical)?,
3113                    *proof,
3114                    now_ms,
3115                )?;
3116            }
3117            _ => return Err(Reject::Version),
3118        }
3119        trust::recheck_context(
3120            context,
3121            set.as_ref().ok_or(Reject::Canonical)?,
3122            signed,
3123            now_ms,
3124        )?;
3125    }
3126    // Operations are accepted publication order, while manifest slots are sorted.
3127    let mut progressive = ImportResultManifestV1 {
3128        slots: vec![],
3129        ..terminal.clone()
3130    };
3131    let mut order = 0;
3132    let mut observed = 0;
3133    let mut consumed = std::collections::BTreeMap::<(Vec<u8>, Vec<u8>), (u32, u64)>::new();
3134    let mut total_bytes = 0_u64;
3135    for o in &bundle.operations {
3136        let digest = signed_operation_digest(o)?;
3137        let slot = terminal
3138            .slots
3139            .iter()
3140            .find(|s| s.signed_operation_digest == digest)
3141            .ok_or(Reject::Scope)?;
3142        progressive.slots.push(slot.clone());
3143        progressive
3144            .slots
3145            .sort_by(|a, b| (&a.ref_name, a.slot_id).cmp(&(&b.ref_name, b.slot_id)));
3146        let payload = canonical(&publication_payload(o, &progressive)?)?;
3147        let s = bundle
3148            .statements
3149            .iter()
3150            .filter_map(|s| s.body.as_ref())
3151            .find(|s| s.purpose == 3 && s.canonical_payload == payload)
3152            .ok_or(Reject::Transition)?;
3153        if s.admission_order <= order || s.observed_at_unix_millis < observed {
3154            return Err(Reject::Transition);
3155        }
3156        order = s.admission_order;
3157        observed = s.observed_at_unix_millis;
3158        let digest = &o.body.as_ref().ok_or(Reject::Canonical)?.delegation_digest;
3159        let index = verified
3160            .iter()
3161            .position(|d| d.digest == *digest)
3162            .ok_or(Reject::Scope)?;
3163        let result_bytes = o.body.as_ref().ok_or(Reject::Canonical)?.result_bytes;
3164        total_bytes = total_bytes
3165            .checked_add(result_bytes)
3166            .ok_or(Reject::Bounds)?;
3167        let original_scope = initial.body.scope.as_ref().ok_or(Reject::Canonical)?;
3168        if total_bytes > original_scope.max_result_bytes
3169            || progressive.slots.len() > original_scope.max_operations as usize
3170        {
3171            return Err(Reject::Scope);
3172        }
3173        let delegation = &verified[index];
3174        let mut committed_before = progressive.clone();
3175        let operation_digest = signed_operation_digest(o)?;
3176        committed_before
3177            .slots
3178            .retain(|s| s.signed_operation_digest != operation_digest);
3179        check_import_publication_budget(o, delegation, &committed_before)?;
3180        let scope = delegation.body.scope.as_ref().ok_or(Reject::Canonical)?;
3181        let mut budgets = vec![(&delegation.digest, scope)];
3182        if let Some(parent) = &delegation.member {
3183            budgets.push((
3184                &delegation.body.parent_permission_digest,
3185                parent
3186                    .body
3187                    .as_ref()
3188                    .and_then(|p| p.scope.as_ref())
3189                    .ok_or(Reject::Canonical)?,
3190            ));
3191        }
3192        for (digest, scope) in budgets {
3193            let (operations, bytes) = consumed
3194                .entry((digest.clone(), delegation.body.logical_job_id.clone()))
3195                .or_default();
3196            *operations = operations.checked_add(1).ok_or(Reject::Bounds)?;
3197            *bytes = bytes.checked_add(result_bytes).ok_or(Reject::Bounds)?;
3198            if *operations > scope.max_operations || *bytes > scope.max_result_bytes {
3199                return Err(Reject::Scope);
3200            }
3201        }
3202    }
3203    if progressive != *terminal {
3204        return Err(Reject::Scope);
3205    }
3206    let mut history = snapshot.map_or_else(Vec::new, |s| s.accepted_history.clone());
3207    if let Some(old) = history.iter_mut().find(|b| {
3208        b.terminal_manifest
3209            .as_ref()
3210            .is_some_and(|m| m.logical_job_id == terminal.logical_job_id)
3211            && b.delegations
3212                .first()
3213                .and_then(|d| d.body.as_ref())
3214                .and_then(|d| d.identity.as_ref())
3215                .map(|id| &id.spool_uuid)
3216                == bundle
3217                    .delegations
3218                    .first()
3219                    .and_then(|d| d.body.as_ref())
3220                    .and_then(|d| d.identity.as_ref())
3221                    .map(|id| &id.spool_uuid)
3222    }) {
3223        if !bundle.delegations.starts_with(&old.delegations)
3224            || !bundle.operations.starts_with(&old.operations)
3225            || bundle.owner_genesis != old.owner_genesis
3226            || !bundle
3227                .ownership_transfers
3228                .starts_with(&old.ownership_transfers)
3229            || !old
3230                .owner_histories
3231                .iter()
3232                .all(|v| bundle.owner_histories.contains(v))
3233            || bundle.member_permission != old.member_permission
3234            || !old
3235                .genesis_authorities
3236                .iter()
3237                .all(|v| bundle.genesis_authorities.contains(v))
3238            || !old
3239                .original_geneses
3240                .iter()
3241                .all(|v| bundle.original_geneses.contains(v))
3242            || !old
3243                .creator_authority_envelopes
3244                .iter()
3245                .all(|v| bundle.creator_authority_envelopes.contains(v))
3246            || !old.manifests.iter().all(|v| bundle.manifests.contains(v))
3247            || !old.statements.iter().all(|v| bundle.statements.contains(v))
3248            || !old.policies.iter().all(|v| bundle.policies.contains(v))
3249            || !old
3250                .genesis_witnesses
3251                .iter()
3252                .all(|v| bundle.genesis_witnesses.contains(v))
3253            || !old
3254                .authority_witnesses
3255                .iter()
3256                .all(|v| bundle.authority_witnesses.contains(v))
3257            || !old
3258                .landing_witnesses
3259                .iter()
3260                .all(|v| bundle.landing_witnesses.contains(v))
3261        {
3262            return Err(Reject::HighWater);
3263        }
3264        *old = bundle.clone();
3265    } else {
3266        history.push(bundle.clone());
3267    }
3268    let witnessed = times[0].is_some();
3269    let witnessed_prefix = usize::from(witnessed);
3270    let mut persisted = snapshot.cloned();
3271    if witnessed_prefix > 0 || new_set {
3272        let mut persisted_associations =
3273            snapshot.map_or_else(Vec::new, |s| s.job_associations.clone());
3274        if witnessed_prefix > 0 {
3275            for d in &bundle.delegations[..witnessed_prefix] {
3276                let b = d.body.as_ref().ok_or(Reject::Canonical)?;
3277                if !persisted_associations
3278                    .iter()
3279                    .any(|(key, _)| *key == b.job_public_key)
3280                {
3281                    persisted_associations
3282                        .push((b.job_public_key.clone(), b.logical_job_id.clone()));
3283                }
3284            }
3285        }
3286        persisted = Some(ImportWitnessSnapshot {
3287            root: pin.clone(),
3288            witness_set: carried.ok_or(Reject::Canonical)?.clone(),
3289            clock_floor_unix_millis: now_ms,
3290            job_associations: persisted_associations,
3291            accepted_history: if witnessed_prefix > 0 {
3292                history
3293            } else {
3294                snapshot.map_or_else(Vec::new, |s| s.accepted_history.clone())
3295            },
3296        });
3297    }
3298    Ok(VerifiedImportBundleWitnesses {
3299        evidence: if witnessed {
3300            ImportBundleEvidence::Witnessed
3301        } else {
3302            ImportBundleEvidence::Recovery
3303        },
3304        snapshot_advanced: persisted.as_ref() != snapshot,
3305        owner_check_time_unix_seconds: times[0].map(|(_, time)| time),
3306        accepted_history: terminal.clone(),
3307        snapshot: persisted,
3308    })
3309}
3310
3311/// Independently authenticated current caller facts for source custody checks.
3312pub struct ImportControlCaller<'a> {
3313    pub authenticated_pop: bool,
3314    pub destination_writer: bool,
3315    pub caller_account: &'a str,
3316    pub connection_owner_account: Option<&'a str>,
3317    pub authorized_source: Option<&'a ImportSourceSelectionV1>,
3318    pub exact_grants_current: bool,
3319    pub selected_commits_available: bool,
3320}
3321#[derive(Clone, Copy)]
3322pub enum ImportControlAction {
3323    Cancel,
3324    Retry,
3325}
3326
3327/// Destination control is independent of source custody. Cancel never fetches.
3328/// Run at Retry admission after checking signed authority.
3329pub fn check_import_control_caller(
3330    action: ImportControlAction,
3331    retained: &ImportSourceSelectionV1,
3332    scope: &ImportPermissionScopeV1,
3333    caller: &ImportControlCaller<'_>,
3334) -> Result<(), Reject> {
3335    if !caller.authenticated_pop || !caller.destination_writer || caller.caller_account.is_empty() {
3336        return Err(Reject::Scope);
3337    }
3338    if matches!(action, ImportControlAction::Cancel) {
3339        return Ok(());
3340    }
3341    validate_retained_import_source(retained, scope)?;
3342    if retained.connection.is_some()
3343        && (caller.connection_owner_account != Some(caller.caller_account)
3344            || caller.authorized_source != Some(retained)
3345            || !caller.exact_grants_current)
3346    {
3347        return Err(Reject::SourceSelection);
3348    }
3349    if !caller.selected_commits_available {
3350        return Err(Reject::SourceSelection);
3351    }
3352    Ok(())
3353}
3354
3355fn validate_retry_availability(
3356    response: &GetImportJobStateResponse,
3357    destination: &SpoolRef,
3358) -> Result<(), Reject> {
3359    use get_import_job_state_response::RetryAvailability;
3360    match response
3361        .retry_availability
3362        .as_ref()
3363        .ok_or(Reject::Canonical)?
3364    {
3365        RetryAvailability::EligibleRetryTarget(target) => {
3366            if response.status != 1 {
3367                return Err(Reject::Canonical);
3368            }
3369            let operation = target.operation_ref.as_ref().ok_or(Reject::Canonical)?;
3370            let raw = hex::decode(operation.id.replace('-', "")).map_err(|_| Reject::Canonical)?;
3371            if initial_operation_id(&raw, false)? != operation.id {
3372                return Err(Reject::Canonical);
3373            }
3374            if operation.spool.as_ref() != Some(destination) {
3375                return Err(Reject::Scope);
3376            }
3377            if target.operation_version.is_empty() || target.operation_version.len() > 256 {
3378                return Err(Reject::Bounds);
3379            }
3380        }
3381        RetryAvailability::RetryUnavailable(reason) => {
3382            if !matches!(
3383                (response.status, *reason),
3384                (1, 1 | 2 | 6) | (2, 3) | (3, 4) | (4, 5) | (5, 7)
3385            ) {
3386                return Err(Reject::Canonical);
3387            }
3388        }
3389    }
3390    Ok(())
3391}
3392
3393/// Validate the minimal writer snapshot and its retry target.
3394pub fn validate_retry_state_response(
3395    request: &GetImportJobStateRequest,
3396    response: &GetImportJobStateResponse,
3397) -> Result<(), Reject> {
3398    validate_job_state_response(request, response)?;
3399    validate_retry_availability(response, request.destination.as_ref().ok_or(Reject::Scope)?)
3400}
3401
3402/// Receiver-owned facts locked together with job/authority/source state. The
3403/// operation-lineage association is durable host state, not an ID inference.
3404pub struct ImportRetryAdmission<'a> {
3405    pub read: &'a GetImportJobStateResponse,
3406    pub original: &'a OperationRecord,
3407    pub retry_lineage_id: &'a [u8],
3408    pub logical_job_terminal: bool,
3409    pub retained_source: &'a ImportSourceSelectionV1,
3410    pub committed_manifest: &'a ImportResultManifestV1,
3411    pub now_unix_seconds: i64,
3412}
3413
3414/// Run after caller-scoped frozen replay lookup, under ONE admission transaction.
3415/// Full owner/policy/revocation/lease checks and allocation remain host gates.
3416pub fn check_retry_admission(
3417    request: &RetryImportSourceRequest,
3418    context: &ImportRetryAdmission<'_>,
3419    active: &VerifiedImportDelegation,
3420    caller: &ImportControlCaller<'_>,
3421) -> Result<(), Reject> {
3422    use get_import_job_state_response::RetryAvailability;
3423    let destination = request
3424        .original_operation
3425        .as_ref()
3426        .and_then(|r| r.spool.clone());
3427    let read_request = GetImportJobStateRequest {
3428        destination,
3429        logical_job_id: request.logical_job_id.clone(),
3430    };
3431    validate_retry_state_response(&read_request, context.read)?;
3432    if request.client_operation_id.is_empty() || request.client_operation_id.len() > 128 {
3433        return Err(Reject::Canonical);
3434    }
3435    if context.logical_job_terminal || context.read.status != 1 {
3436        return Err(Reject::Revoked);
3437    }
3438    let Some(RetryAvailability::EligibleRetryTarget(target)) = &context.read.retry_availability
3439    else {
3440        return Err(Reject::StaleContext);
3441    };
3442    let target_ref = target.operation_ref.as_ref().ok_or(Reject::Canonical)?;
3443    let original_ref = context.original.r#ref.as_ref().ok_or(Reject::Scope)?;
3444    if request.original_operation.as_ref() != Some(original_ref)
3445        || original_ref.spool != target_ref.spool
3446        || original_ref.id != target_ref.id
3447        || context.retry_lineage_id != active.body.retry_lineage_id
3448        || import_job_state_request_from_operation(context.original)?.as_ref()
3449            != Some(&read_request)
3450    {
3451        return Err(Reject::Scope);
3452    }
3453    if request.expected_operation_version != target.operation_version
3454        || context.original.version != target.operation_version
3455        || context.original.superseded_by.is_some()
3456        || !matches!(context.original.state, 4 | 5)
3457    {
3458        return Err(Reject::StaleContext);
3459    }
3460    let state = context.read;
3461    if state.active_delegation_digest != active.digest
3462        || state.active_cancellation_id != active.body.cancellation_id
3463    {
3464        return Err(Reject::StaleContext);
3465    }
3466    check_job_fence(
3467        &request.logical_job_id,
3468        &request.active_delegation_digest,
3469        request.expected_authority_epoch,
3470        active,
3471        state.authority_epoch,
3472    )?;
3473    interval(
3474        active.body.not_before_unix_seconds,
3475        active.body.expires_at_unix_seconds,
3476        context.now_unix_seconds,
3477    )?;
3478    let manifest = context.committed_manifest;
3479    validate_manifest(manifest)?;
3480    if manifest.logical_job_id != active.body.logical_job_id
3481        || manifest.retry_lineage_id != active.body.retry_lineage_id
3482    {
3483        return Err(Reject::Scope);
3484    }
3485    let scope = active.body.scope.as_ref().ok_or(Reject::Canonical)?;
3486    if !scope.branches.iter().any(|b| {
3487        !manifest
3488            .slots
3489            .iter()
3490            .any(|s| s.ref_name == b.ref_name && s.slot_id == b.slot_id)
3491    }) {
3492        return Err(Reject::StaleContext);
3493    }
3494    check_import_control_caller(
3495        ImportControlAction::Retry,
3496        context.retained_source,
3497        scope,
3498        caller,
3499    )
3500}
3501
3502/// Check a host-generated UUID against the COMPLETE durable attempt set, including
3503/// the first lineage UUID. Persist the allocation, both direct links and receipt
3504/// atomically; do not generate a UUID from the request idempotency key.
3505pub fn validate_retry_response(
3506    request: &RetryImportSourceRequest,
3507    response: &MutationResponse,
3508    prior_attempt_ids: &[String],
3509) -> Result<(), Reject> {
3510    let receipt = response.receipt.as_ref().ok_or(Reject::PendingOperation)?;
3511    let Some(mutation_receipt::Outcome::PendingOperation(operation)) = &receipt.outcome else {
3512        return Err(Reject::PendingOperation);
3513    };
3514    let original = request
3515        .original_operation
3516        .as_ref()
3517        .ok_or(Reject::PendingOperation)?;
3518    let raw = hex::decode(operation.id.replace('-', "")).map_err(|_| Reject::PendingOperation)?;
3519    if initial_operation_id(&raw, false).map_or(true, |id| id != operation.id)
3520        || request.client_operation_id.is_empty()
3521        || receipt.client_operation_id != request.client_operation_id
3522        || original.spool.is_none()
3523        || operation.spool != original.spool
3524        || operation.id == original.id
3525        || operation.id == request.client_operation_id
3526        || prior_attempt_ids.contains(&operation.id)
3527    {
3528        return Err(Reject::PendingOperation);
3529    }
3530    Ok(())
3531}
3532
3533/// Exact frozen Retry replay returns the stored receipt without allocating.
3534pub fn check_retry_replay(request_bytes: &[u8], stored_bytes: &[u8]) -> Result<(), Reject> {
3535    if request_bytes.len() > 2 * MAX_BUNDLE_BYTES {
3536        return Err(Reject::Bounds);
3537    }
3538    if request_bytes != stored_bytes {
3539        return Err(Reject::OperationIdReused);
3540    }
3541    Ok(())
3542}
3543
3544/// Under the publication transaction, use the complete cumulative manifest of
3545/// this logical job. All operations consume the same single delegation total.
3546pub fn check_import_publication_budget(
3547    signed: &SignedDelegatedImportOperationV1,
3548    active: &VerifiedImportDelegation,
3549    committed_before: &ImportResultManifestV1,
3550) -> Result<(), Reject> {
3551    verify_operation(signed, active)?;
3552    let scope = active.body.scope.as_ref().ok_or(Reject::Canonical)?;
3553    if committed_before.logical_job_id != active.body.logical_job_id
3554        || committed_before.retry_lineage_id != active.body.retry_lineage_id
3555    {
3556        return Err(Reject::Scope);
3557    }
3558    let remaining = remaining_import_scope(scope, committed_before)?;
3559    if check_slot_replay(committed_before, signed)? {
3560        return Ok(());
3561    }
3562    let o = signed.body.as_ref().ok_or(Reject::Canonical)?;
3563    if remaining.max_operations == 0 || o.result_bytes > remaining.max_result_bytes {
3564        return Err(Reject::Scope);
3565    }
3566    Ok(())
3567}