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 forbidden_landing_keys: &'a [Vec<u8>],
1027    pub known_job_associations: &'a [(Vec<u8>, Vec<u8>)],
1028}
1029impl<'a> ImportBundleOwnerExpectation<'a> {
1030    fn at(self, time: i64, associations: &'a [(Vec<u8>, Vec<u8>)]) -> ImportOwnerExpectation<'a> {
1031        ImportOwnerExpectation {
1032            identity: self.identity,
1033            owner_public_key: self.owner_public_key,
1034            owner_chain_digest: self.owner_chain_digest,
1035            authority_expires_at_seconds: self.authority_expires_at_seconds,
1036            now_unix_seconds: time,
1037            forbidden_job_keys: self.forbidden_job_keys,
1038            known_job_associations: associations,
1039        }
1040    }
1041}
1042/// Inputs MUST come from the selected, independently verified effective state.
1043/// Historical verification selects the state at its authenticated observation.
1044pub fn effective_owner_authority_expiry(
1045    deferred_human: bool,
1046    claimable_until: i64,
1047) -> Result<i64, Reject> {
1048    if deferred_human {
1049        if claimable_until <= 0 {
1050            return Err(Reject::Scope);
1051        }
1052        Ok(claimable_until)
1053    } else {
1054        Ok(i64::MAX)
1055    }
1056}
1057pub fn verify_member_permission(
1058    signed: &SignedImportMemberPermissionV1,
1059    expected: &ImportOwnerExpectation<'_>,
1060) -> Result<(), Reject> {
1061    verify_member_permission_inner(signed, expected, true)
1062}
1063fn verify_member_permission_inner(
1064    signed: &SignedImportMemberPermissionV1,
1065    expected: &ImportOwnerExpectation<'_>,
1066    current: bool,
1067) -> Result<(), Reject> {
1068    let p = signed.body.as_ref().ok_or(Reject::ImportPermission)?;
1069    if p.format_version != 1 || p.purpose != 1 {
1070        return Err(Reject::ImportPermission);
1071    }
1072    identity(p.identity.as_ref().ok_or(Reject::Canonical)?)?;
1073    if p.identity.as_ref() != Some(expected.identity)
1074        || p.owner_chain_digest != expected.owner_chain_digest
1075    {
1076        return Err(Reject::Root);
1077    }
1078    width(&p.logical_job_id, 16)?;
1079    width(&p.retry_lineage_id, 16)?;
1080    width(&p.subject_public_key, 32)?;
1081    width(&p.cancellation_id, 32)?;
1082    width(&p.nonce, 32)?;
1083    width(&p.owner_chain_digest, 32)?;
1084    validate_scope(p.scope.as_ref().ok_or(Reject::Canonical)?)?;
1085    validity(
1086        p.not_before_unix_seconds,
1087        p.expires_at_unix_seconds,
1088        expected.now_unix_seconds,
1089        current,
1090    )?;
1091    if p.expires_at_unix_seconds > expected.authority_expires_at_seconds {
1092        return Err(Reject::Scope);
1093    }
1094    verify_authorization_signature(
1095        expected.owner_public_key,
1096        PERMISSION_DOMAIN,
1097        p,
1098        signed.owner_signature.as_ref().ok_or(Reject::Signature)?,
1099    )
1100}
1101
1102#[derive(Debug, Clone, PartialEq)]
1103pub struct VerifiedImportDelegation {
1104    body: ImportJobDelegationV1,
1105    digest: Vec<u8>,
1106    member: Option<SignedImportMemberPermissionV1>,
1107}
1108impl VerifiedImportDelegation {
1109    pub fn body(&self) -> &ImportJobDelegationV1 {
1110        &self.body
1111    }
1112    pub fn digest(&self) -> &[u8] {
1113        &self.digest
1114    }
1115}
1116pub fn verify_delegation(
1117    signed: &SignedImportJobDelegationV1,
1118    member: Option<&SignedImportMemberPermissionV1>,
1119    expected: &ImportOwnerExpectation<'_>,
1120) -> Result<VerifiedImportDelegation, Reject> {
1121    verify_delegation_inner(signed, member, expected, true)
1122}
1123fn verify_delegation_inner(
1124    signed: &SignedImportJobDelegationV1,
1125    member: Option<&SignedImportMemberPermissionV1>,
1126    expected: &ImportOwnerExpectation<'_>,
1127    current: bool,
1128) -> Result<VerifiedImportDelegation, Reject> {
1129    let d = signed.body.as_ref().ok_or(Reject::Canonical)?;
1130    if d.format_version != 1 || d.purpose != 1 {
1131        return Err(Reject::Version);
1132    }
1133    identity(d.identity.as_ref().ok_or(Reject::Canonical)?)?;
1134    if d.identity.as_ref() != Some(expected.identity)
1135        || d.owner_chain_digest != expected.owner_chain_digest
1136    {
1137        return Err(Reject::Root);
1138    }
1139    for v in [&d.delegation_id, &d.logical_job_id, &d.retry_lineage_id] {
1140        width(v, 16)?;
1141        if v.iter().all(|b| *b == 0) {
1142            return Err(Reject::Canonical);
1143        }
1144    }
1145    for v in [
1146        &d.job_public_key,
1147        &d.job_key_id,
1148        &d.delegating_public_key,
1149        &d.parent_permission_digest,
1150        &d.owner_chain_digest,
1151        &d.cancellation_id,
1152    ] {
1153        width(v, 32)?;
1154    }
1155    if d.job_key_id != key_id(&d.job_public_key) {
1156        return Err(Reject::Canonical);
1157    }
1158    if d.job_public_key == d.delegating_public_key
1159        || d.job_public_key == expected.owner_public_key
1160        || expected.forbidden_job_keys.contains(&d.job_public_key)
1161    {
1162        return Err(Reject::KeyRole);
1163    }
1164    if expected
1165        .known_job_associations
1166        .iter()
1167        .any(|(k, j)| k == &d.job_public_key && j != &d.logical_job_id)
1168    {
1169        return Err(Reject::Scope);
1170    }
1171    let scope = d.scope.as_ref().ok_or(Reject::Canonical)?;
1172    validate_scope(scope)?;
1173    if d.branch_manifest.len() != scope.branches.len() {
1174        return Err(Reject::Scope);
1175    }
1176    for (m, b) in d.branch_manifest.iter().zip(&scope.branches) {
1177        width(&m.genesis_authority_digest, 32)?;
1178        if m.limit.as_ref() != Some(b) {
1179            return Err(Reject::Scope);
1180        }
1181    }
1182    if i128::from(d.expires_at_unix_seconds) - i128::from(d.not_before_unix_seconds)
1183        > i128::from(MAX_DELEGATION_WINDOW_SECONDS)
1184    {
1185        return Err(Reject::ValidityBounds);
1186    }
1187    validity(
1188        d.not_before_unix_seconds,
1189        d.expires_at_unix_seconds,
1190        expected.now_unix_seconds,
1191        current,
1192    )?;
1193    if d.expires_at_unix_seconds > expected.authority_expires_at_seconds {
1194        return Err(Reject::Scope);
1195    }
1196    if d.delegating_public_key == expected.owner_public_key {
1197        if member.is_some() || d.parent_permission_digest != vec![0; 32] {
1198            return Err(Reject::ImportPermission);
1199        }
1200    } else {
1201        let member = member.ok_or(Reject::ImportPermission)?;
1202        verify_member_permission_inner(member, expected, current)?;
1203        let p = member.body.as_ref().ok_or(Reject::ImportPermission)?;
1204        if d.parent_permission_digest != signed_permission_digest(member)?
1205            || d.delegating_public_key != p.subject_public_key
1206            || d.logical_job_id != p.logical_job_id
1207            || d.retry_lineage_id != p.retry_lineage_id
1208            || d.not_before_unix_seconds < p.not_before_unix_seconds
1209            || d.expires_at_unix_seconds > p.expires_at_unix_seconds
1210            || !scope_subset(scope, p.scope.as_ref().ok_or(Reject::Canonical)?)
1211        {
1212            return Err(Reject::Scope);
1213        }
1214    }
1215    verify_authorization_signature(
1216        &d.delegating_public_key,
1217        DELEGATION_DOMAIN,
1218        d,
1219        signed
1220            .delegating_signature
1221            .as_ref()
1222            .ok_or(Reject::Signature)?,
1223    )?;
1224    Ok(VerifiedImportDelegation {
1225        body: d.clone(),
1226        digest: signed_delegation_digest(signed)?,
1227        member: member.cloned(),
1228    })
1229}
1230/// Frozen canonical projection. The browser completes only the fields absent
1231/// here; it cannot normalize or reduce even an otherwise authorized scope.
1232pub fn delegation_preparation(d: &ImportJobDelegationV1) -> ImportJobPreparationV1 {
1233    ImportJobPreparationV1 {
1234        format_version: d.format_version,
1235        identity: d.identity.clone(),
1236        delegation_id: d.delegation_id.clone(),
1237        logical_job_id: d.logical_job_id.clone(),
1238        retry_lineage_id: d.retry_lineage_id.clone(),
1239        job_public_key: d.job_public_key.clone(),
1240        job_key_id: d.job_key_id.clone(),
1241        owner_chain_digest: d.owner_chain_digest.clone(),
1242        purpose: d.purpose,
1243        scope: d.scope.clone(),
1244        cancellation_id: d.cancellation_id.clone(),
1245    }
1246}
1247
1248/// Validate Commit against the HOST-STORED preparation and independently
1249/// selected current authority. Native genesis/envelope verification, online
1250/// revocation, custody uniqueness and transactional activation remain host gates.
1251pub fn verify_prepared_delegation(
1252    prepared: &PrepareImportJobResponse,
1253    signed: &SignedImportJobDelegationV1,
1254    member: Option<&SignedImportMemberPermissionV1>,
1255    geneses: &[SignedImportGenesisAuthorityV1],
1256    expected: &ImportOwnerExpectation<'_>,
1257) -> Result<VerifiedImportDelegation, Reject> {
1258    verify_prepared_inner(prepared, signed, member, geneses, expected, false)
1259}
1260/// Browser signing preflight only: no execution or admission token is returned.
1261pub fn preflight_prepared_delegation(
1262    prepared: &PrepareImportJobResponse,
1263    signed: &SignedImportJobDelegationV1,
1264    member: Option<&SignedImportMemberPermissionV1>,
1265    geneses: &[SignedImportGenesisAuthorityV1],
1266    expected: &ImportOwnerExpectation<'_>,
1267) -> Result<(), Reject> {
1268    verify_prepared_inner(prepared, signed, member, geneses, expected, true).map(|_| ())
1269}
1270fn verify_prepared_inner(
1271    prepared: &PrepareImportJobResponse,
1272    signed: &SignedImportJobDelegationV1,
1273    member: Option<&SignedImportMemberPermissionV1>,
1274    geneses: &[SignedImportGenesisAuthorityV1],
1275    expected: &ImportOwnerExpectation<'_>,
1276    browser: bool,
1277) -> Result<VerifiedImportDelegation, Reject> {
1278    let proposal = prepared.proposal.as_ref().ok_or(Reject::Canonical)?;
1279    let d = signed.body.as_ref().ok_or(Reject::Canonical)?;
1280    if canonical(proposal)? != canonical(&delegation_preparation(d))? {
1281        return Err(Reject::PreparedFields);
1282    }
1283    let scope = proposal.scope.as_ref().ok_or(Reject::Canonical)?;
1284    if d.branch_manifest.len() != scope.branches.len() {
1285        return Err(Reject::PreparedFields);
1286    }
1287    for (m, b) in d.branch_manifest.iter().zip(&scope.branches) {
1288        let limit = m.limit.as_ref().ok_or(Reject::PreparedFields)?;
1289        if canonical(limit)? != canonical(b)? {
1290            return Err(Reject::PreparedFields);
1291        }
1292    }
1293    // Use i128 for host arithmetic so extreme advertised uint64 bounds cannot
1294    // wrap. Skew permits a future not-before, never grace after expiry.
1295    let now = i128::from(expected.now_unix_seconds);
1296    let start = i128::from(d.not_before_unix_seconds);
1297    let end = i128::from(d.expires_at_unix_seconds);
1298    let at = i128::from(prepared.prepared_at_unix_seconds);
1299    let skew = i128::from(prepared.clock_skew_allowance_seconds);
1300    if at < 0
1301        || now < 0
1302        || if browser { now + skew < at } else { now < at }
1303        || i128::from(prepared.reservation_expires_at_unix_seconds) != at + 3600
1304        || now >= i128::from(prepared.reservation_expires_at_unix_seconds)
1305    {
1306        return Err(Reject::Expired);
1307    }
1308    if prepared.max_validity_duration_seconds == 0
1309        || prepared.max_validity_duration_seconds > MAX_DELEGATION_WINDOW_SECONDS
1310        || start < 0
1311        || start < at - skew
1312        || start > now + skew
1313        || end <= start
1314        || end <= now
1315        || end - start > i128::from(prepared.max_validity_duration_seconds)
1316    {
1317        return Err(Reject::ValidityBounds);
1318    }
1319    if let Some(parent) = member {
1320        if browser {
1321            let p = parent.body.as_ref().ok_or(Reject::ImportPermission)?;
1322            verify_member_permission_inner(parent, expected, false)?;
1323            if i128::from(p.not_before_unix_seconds) > now + skew
1324                || i128::from(p.expires_at_unix_seconds) <= now
1325            {
1326                return Err(Reject::Expired);
1327            }
1328        } else {
1329            verify_member_permission(parent, expected)?;
1330        }
1331    }
1332    // Future not-before within skew can be committed, but verify_new_operation
1333    // still refuses execution until that exact signed time. Parent/owner expiry
1334    // and containment are checked without extending them by skew.
1335    let at_start = ImportOwnerExpectation {
1336        now_unix_seconds: expected.now_unix_seconds.max(d.not_before_unix_seconds),
1337        ..*expected
1338    };
1339    let verified = verify_delegation_inner(
1340        signed,
1341        member,
1342        if browser { expected } else { &at_start },
1343        !browser,
1344    )?;
1345    if geneses.len() != d.branch_manifest.len() {
1346        return Err(Reject::GenesisBinding);
1347    }
1348    for m in &d.branch_manifest {
1349        let branch = m.limit.as_ref().ok_or(Reject::Canonical)?;
1350        let g = geneses
1351            .iter()
1352            .find(|g| signed_genesis_digest(g).is_ok_and(|h| h == m.genesis_authority_digest))
1353            .ok_or(Reject::GenesisBinding)?;
1354        let body = g.body.as_ref().ok_or(Reject::GenesisBinding)?;
1355        if body.genesis_digest != branch.genesis_digest {
1356            return Err(Reject::GenesisBinding);
1357        }
1358        {
1359            verify_genesis_authority(
1360                g,
1361                &verified,
1362                &branch.genesis_digest,
1363                &body.original_creator_signature,
1364                &body.creator_authority_envelope_digest,
1365            )?;
1366        }
1367    }
1368    Ok(verified)
1369}
1370
1371pub fn verify_genesis_authority(
1372    signed: &SignedImportGenesisAuthorityV1,
1373    delegation: &VerifiedImportDelegation,
1374    original_genesis_digest: &[u8],
1375    original_signature: &[u8],
1376    envelope_digest: &[u8],
1377) -> Result<(), Reject> {
1378    let g = signed.body.as_ref().ok_or(Reject::Canonical)?;
1379    let d = &delegation.body;
1380    if g.format_version != 1 {
1381        return Err(Reject::Version);
1382    }
1383    width(&g.original_creator_signature, 64)?;
1384    for v in [
1385        &g.genesis_digest,
1386        &g.creator_public_key,
1387        &g.creator_authority_envelope_digest,
1388        &g.parent_permission_digest,
1389        &g.owner_chain_digest,
1390    ] {
1391        width(v, 32)?;
1392    }
1393    if g.identity != d.identity
1394        || g.creator_public_key != d.delegating_public_key
1395        || g.parent_permission_digest != d.parent_permission_digest
1396        || g.owner_chain_digest != d.owner_chain_digest
1397        || g.genesis_digest != original_genesis_digest
1398        || g.original_creator_signature != original_signature
1399        || g.creator_authority_envelope_digest != envelope_digest
1400        || !d.branch_manifest.iter().any(|m| {
1401            m.limit
1402                .as_ref()
1403                .is_some_and(|b| b.genesis_digest == g.genesis_digest)
1404                && signed_genesis_digest(signed).is_ok_and(|h| h == m.genesis_authority_digest)
1405        })
1406    {
1407        return Err(Reject::Scope);
1408    }
1409    verify_authorization_signature(
1410        &g.creator_public_key,
1411        GENESIS_DOMAIN,
1412        g,
1413        signed.creator_signature.as_ref().ok_or(Reject::Signature)?,
1414    )
1415}
1416/// Structural signature + scoped operation only. This does not establish
1417/// publication, current policy, cancellation, leases or conversion correctness.
1418pub fn verify_operation(
1419    signed: &SignedDelegatedImportOperationV1,
1420    delegation: &VerifiedImportDelegation,
1421) -> Result<(), Reject> {
1422    let o = signed.body.as_ref().ok_or(Reject::Canonical)?;
1423    let d = &delegation.body;
1424    if o.format_version != 1 {
1425        return Err(Reject::Version);
1426    }
1427    let id = d.identity.as_ref().ok_or(Reject::Canonical)?;
1428    width(&o.physical_operation_id, 16)?;
1429    for v in [
1430        &o.spool_genesis_digest,
1431        &o.delegation_digest,
1432        &o.genesis_digest,
1433        &o.target_thread_id,
1434        &o.expected_frontier_digest,
1435        &o.resulting_frontier_digest,
1436        &o.resulting_content_digest,
1437        &o.options_digest,
1438    ] {
1439        width(v, 32)?;
1440    }
1441    width(&o.spool_uuid, 16)?;
1442    width(&o.logical_job_id, 16)?;
1443    width(&o.retry_lineage_id, 16)?;
1444    let scope = d.scope.as_ref().ok_or(Reject::Canonical)?;
1445    let b = scope
1446        .branches
1447        .iter()
1448        .find(|b| b.ref_name == o.ref_name && b.slot_id == o.slot_id)
1449        .ok_or(Reject::Scope)?;
1450    let oid_len = match o.hash_algorithm {
1451        1 => 20,
1452        2 => 32,
1453        _ => return Err(Reject::Version),
1454    };
1455    width(&o.observed_commit_oid, oid_len)?;
1456    if o.spool_uuid != id.spool_uuid
1457        || o.spool_genesis_digest != id.spool_genesis_digest
1458        || o.logical_job_id != d.logical_job_id
1459        || o.retry_lineage_id != d.retry_lineage_id
1460        || o.delegation_digest != delegation.digest
1461        || o.hash_algorithm != b.hash_algorithm
1462        || (b.ref_mode == 1 && o.observed_commit_oid != b.pinned_commit_oid)
1463        || o.genesis_digest != b.genesis_digest
1464        || o.target_thread_id != b.target_thread_id
1465        || o.expected_frontier_digest != b.expected_frontier_digest
1466        || o.result_bytes > scope.max_result_bytes
1467        || o.result_bytes == 0
1468        || o.options_digest != scope.options_digest
1469        || o.converter_version != scope.converter_version
1470    {
1471        return Err(Reject::Scope);
1472    }
1473    verify_authorization_signature(
1474        &d.job_public_key,
1475        OPERATION_DOMAIN,
1476        o,
1477        signed.job_signature.as_ref().ok_or(Reject::Signature)?,
1478    )
1479}
1480pub fn verify_new_operation(
1481    signed: &SignedDelegatedImportOperationV1,
1482    delegation: &VerifiedImportDelegation,
1483    now_seconds: i64,
1484    committed_before: &ImportResultManifestV1,
1485) -> Result<(), Reject> {
1486    interval(
1487        delegation.body.not_before_unix_seconds,
1488        delegation.body.expires_at_unix_seconds,
1489        now_seconds,
1490    )?;
1491    check_import_publication_budget(signed, delegation, committed_before)
1492}
1493pub fn validate_manifest(m: &ImportResultManifestV1) -> Result<(), Reject> {
1494    if m.format_version != 1 {
1495        return Err(Reject::Version);
1496    }
1497    width(&m.logical_job_id, 16)?;
1498    width(&m.retry_lineage_id, 16)?;
1499    if m.slots.len() > MAX_BRANCHES {
1500        return Err(Reject::Bounds);
1501    }
1502    for (i, s) in m.slots.iter().enumerate() {
1503        width(&s.signed_operation_digest, 32)?;
1504        width(&s.resulting_frontier_digest, 32)?;
1505        if !s.ref_name.starts_with("refs/heads/") || !s.ref_name.is_ascii() {
1506            return Err(Reject::Canonical);
1507        }
1508        if s.ref_name.len() > 1024 || s.result_bytes == 0 {
1509            return Err(Reject::Bounds);
1510        }
1511        if i > 0 && (&m.slots[i - 1].ref_name, m.slots[i - 1].slot_id) >= (&s.ref_name, s.slot_id) {
1512            return Err(Reject::Canonical);
1513        }
1514    }
1515    Ok(())
1516}
1517
1518/// Persistent unique slot identity: logical job/ref/slot. Exact replay returns
1519/// the old receipt/manifest, never another publication or fresh witness.
1520pub fn check_slot_replay(
1521    committed: &ImportResultManifestV1,
1522    signed: &SignedDelegatedImportOperationV1,
1523) -> Result<bool, Reject> {
1524    validate_manifest(committed)?;
1525    let o = signed.body.as_ref().ok_or(Reject::Canonical)?;
1526    if committed.logical_job_id != o.logical_job_id
1527        || committed.retry_lineage_id != o.retry_lineage_id
1528    {
1529        return Err(Reject::Scope);
1530    }
1531    match committed
1532        .slots
1533        .iter()
1534        .find(|s| s.ref_name == o.ref_name && s.slot_id == o.slot_id)
1535    {
1536        Some(s)
1537            if s.signed_operation_digest == signed_operation_digest(signed)?
1538                && s.resulting_frontier_digest == o.resulting_frontier_digest
1539                && s.result_bytes == o.result_bytes =>
1540        {
1541            Ok(true)
1542        }
1543        Some(_) => Err(Reject::SlotConflict),
1544        None => Ok(false),
1545    }
1546}
1547/// Verify exact committed publication in addition to job signature/scope. The
1548/// owner/keyring verifier must resolve the statement's accepted state/order;
1549/// witness signature alone cannot establish that user authority or disclosure.
1550pub fn verify_publication(
1551    operation: &SignedDelegatedImportOperationV1,
1552    delegation: &VerifiedImportDelegation,
1553    manifest: &ImportResultManifestV1,
1554    statement: &crate::heddle::api::common::SignedHostedWitnessStatementV1,
1555    set: &crate::witness_trust::VerifiedWitnessSet,
1556    proof: Option<&crate::heddle::api::common::HostedWitnessHistoryProofV1>,
1557    now_ms: i64,
1558) -> Result<crate::witness_trust::ResolvedWitnessStatement, Reject> {
1559    validate_statement_boundary(statement.body.as_ref().ok_or(Reject::Canonical)?)?;
1560    verify_operation(operation, delegation)?;
1561    if !check_slot_replay(manifest, operation)? {
1562        return Err(Reject::Scope);
1563    }
1564    let mut before = manifest.clone();
1565    let o = operation.body.as_ref().ok_or(Reject::Canonical)?;
1566    before
1567        .slots
1568        .retain(|slot| slot.ref_name != o.ref_name || slot.slot_id != o.slot_id);
1569    check_import_publication_budget(operation, delegation, &before)?;
1570    let d = &delegation.body;
1571    let id = d.identity.as_ref().ok_or(Reject::Canonical)?;
1572    let s = statement.body.as_ref().ok_or(Reject::Canonical)?;
1573    let payload = ImportPublicationWitnessV1 {
1574        format_version: 1,
1575        signed_operation_digest: signed_operation_digest(operation)?,
1576        delegation_digest: delegation.digest.clone(),
1577        logical_job_id: o.logical_job_id.clone(),
1578        retry_lineage_id: o.retry_lineage_id.clone(),
1579        physical_operation_id: o.physical_operation_id.clone(),
1580        ref_name: o.ref_name.clone(),
1581        slot_id: o.slot_id,
1582        hash_algorithm: o.hash_algorithm,
1583        observed_commit_oid: o.observed_commit_oid.clone(),
1584        expected_frontier_digest: o.expected_frontier_digest.clone(),
1585        resulting_frontier_digest: o.resulting_frontier_digest.clone(),
1586        terminal_manifest_digest: manifest_digest(manifest)?,
1587    };
1588    if s.purpose != 3
1589        || s.spool_uuid != id.spool_uuid
1590        || s.spool_genesis_digest != id.spool_genesis_digest
1591        || s.owner_id != id.owner_id
1592        || s.owner_state_hash != id.owner_state_hash
1593        || s.ownership_transfer_sequence != id.ownership_transfer_sequence
1594        || s.authority_digest != delegation.digest
1595        || s.original_signatures_digest
1596            != hash(&[&operation
1597                .job_signature
1598                .as_ref()
1599                .ok_or(Reject::Signature)?
1600                .signature])
1601        || s.canonical_payload != canonical(&payload)?
1602        || s.basis != 1
1603    {
1604        return Err(Reject::Scope);
1605    }
1606    interval(
1607        d.not_before_unix_seconds,
1608        d.expires_at_unix_seconds,
1609        s.observed_at_unix_millis / 1000,
1610    )?;
1611    crate::witness_trust::resolve_statement(set, statement, proof, false, now_ms)
1612}
1613pub fn require_hybrid_peer(
1614    protocol: Option<&crate::heddle::api::common::ProtocolCompatibility>,
1615) -> Result<(), Reject> {
1616    let protocol = protocol.ok_or(Reject::Protocol)?;
1617    if protocol.protocol_version != 2 || protocol.mandatory_features != [1] {
1618        return Err(Reject::Protocol);
1619    }
1620    Ok(())
1621}
1622
1623/// Producer-owned logical-job/lease fence for RetryImportSource and final
1624/// publication. The physical retry row never supplies a new logical identity.
1625pub fn check_job_fence(
1626    logical_job_id: &[u8],
1627    active_delegation_digest: &[u8],
1628    expected_epoch: u64,
1629    active: &VerifiedImportDelegation,
1630    durable_epoch: u64,
1631) -> Result<(), Reject> {
1632    if logical_job_id != active.body.logical_job_id {
1633        return Err(Reject::Scope);
1634    }
1635    if expected_epoch != durable_epoch || active_delegation_digest != active.digest {
1636        return Err(Reject::StaleContext);
1637    }
1638    Ok(())
1639}
1640pub fn validate_public_bundle(bundle: &ImportPublicProofBundleV1) -> Result<(), Reject> {
1641    validate_bundle_bounds(bundle)?;
1642    validate_bundle_history(bundle, true)
1643}
1644fn validate_bundle_bounds(bundle: &ImportPublicProofBundleV1) -> Result<(), Reject> {
1645    use prost::Message;
1646    if bundle.format_version != 1 {
1647        return Err(Reject::Version);
1648    }
1649    if bundle.encoded_len() > MAX_BUNDLE_BYTES
1650        || bundle.owner_histories.len() > 64
1651        || bundle.ownership_transfers.len() > 64
1652        || bundle.genesis_authorities.len() > MAX_BRANCHES
1653        || bundle.delegations.len() != 1
1654        || bundle.operations.len() > MAX_BRANCHES
1655        || bundle.statements.len() > 1024
1656        || bundle.history_proofs.len() > 1024
1657        || bundle.policies.len() > 256
1658        || bundle.original_geneses.len() > MAX_BRANCHES
1659        || bundle.creator_authority_envelopes.len() > MAX_BRANCHES
1660        || bundle.manifests.len() > MAX_BRANCHES
1661        || bundle.genesis_witnesses.len() > 256
1662        || bundle.authority_witnesses.len() > 256
1663        || bundle.landing_witnesses.len() > 256
1664    {
1665        return Err(Reject::Bounds);
1666    }
1667    Ok(())
1668}
1669
1670/// Typed adapter boundary: an authentic unrelated capability/online role must
1671/// never be selected as the parent of an import certificate.
1672pub enum ImportPermissionEvidence<'a> {
1673    Import(&'a SignedImportMemberPermissionV1),
1674    OwnerCapability(&'a SignedOwnerCapability),
1675    OnlineRole(&'a str),
1676}
1677pub fn select_import_permission(
1678    evidence: ImportPermissionEvidence<'_>,
1679) -> Result<&SignedImportMemberPermissionV1, Reject> {
1680    match evidence {
1681        ImportPermissionEvidence::Import(p) => Ok(p),
1682        ImportPermissionEvidence::OwnerCapability(_) | ImportPermissionEvidence::OnlineRole(_) => {
1683            Err(Reject::ImportPermission)
1684        }
1685    }
1686}
1687/// Hybrid dispatch has no legacy execution arm, even for an authentic witness.
1688pub fn require_import_operation_format(format: &str) -> Result<(), Reject> {
1689    if format != OPERATION_DOMAIN {
1690        return Err(Reject::Protocol);
1691    }
1692    Ok(())
1693}
1694pub fn frontier_digest(frontier: &ImportFrontierV1) -> Result<Vec<u8>, Reject> {
1695    if frontier.format_version != 1 {
1696        return Err(Reject::Version);
1697    }
1698    width(&frontier.thread_id, 32)?;
1699    if frontier.operation_ids.len() > 128 {
1700        return Err(Reject::Bounds);
1701    }
1702    for id in &frontier.operation_ids {
1703        width(id, 32)?;
1704    }
1705    if frontier.operation_ids.windows(2).any(|w| w[0] >= w[1]) {
1706        return Err(Reject::Canonical);
1707    }
1708    signing_digest("heddle-import-frontier-v1", frontier)
1709}
1710pub fn content_digest(content: &ImportContentV1) -> Result<Vec<u8>, Reject> {
1711    if content.format_version != 1 {
1712        return Err(Reject::Version);
1713    }
1714    if content.canonical_capture.is_empty() {
1715        return Err(Reject::Bounds);
1716    }
1717    signing_digest("heddle-import-content-v1", content)
1718}
1719pub fn signed_native_digest(record: &SignedRecord) -> Result<Vec<u8>, Reject> {
1720    signing_digest("heddle-signed-native-record-v1", record)
1721}
1722pub(crate) fn verify_native(record: &SignedRecord, format: &str) -> Result<(), Reject> {
1723    if record.format != format {
1724        return Err(Reject::Version);
1725    }
1726    if record.canonical_record.is_empty()
1727        || record.canonical_record.len() > MAX_RECORD_BYTES
1728        || record.signatures.is_empty()
1729        || record.signatures.len() > 16
1730    {
1731        return Err(Reject::Bounds);
1732    }
1733    let mut previous: Option<&[u8]> = None;
1734    let input = [format.as_bytes(), b"\0", &record.canonical_record].concat();
1735    for s in &record.signatures {
1736        if previous.is_some_and(|p| p >= s.public_key.as_slice()) {
1737            return Err(Reject::Canonical);
1738        }
1739        verify(&s.public_key, &input, &s.signature)?;
1740        previous = Some(&s.public_key);
1741    }
1742    Ok(())
1743}
1744/// Recompute transport commitments from exact native evidence. The caller's
1745/// native verifier additionally authenticates manifest membership, receipt
1746/// subjects/bases, accepting authority and canonical native encoding.
1747pub fn verify_boundary_acceptance(e: &ImportBoundaryAcceptanceV1) -> Result<(), Reject> {
1748    let binding = e.binding.as_ref().ok_or(Reject::BoundaryAcceptance)?;
1749    validate_boundary_binding(binding)?;
1750    let acceptance = e
1751        .signed_acceptance
1752        .as_ref()
1753        .ok_or(Reject::BoundaryAcceptance)?;
1754    verify_native(acceptance, "heddle-original-boundary-acceptance-v1")?;
1755    if acceptance.signatures.len() != 1 {
1756        return Err(Reject::Signature);
1757    }
1758    if e.originals_manifest.is_empty()
1759        || e.publication_intent.is_empty()
1760        || e.originals_manifest.len() > MAX_RECORD_BYTES
1761        || e.publication_intent.len() > MAX_RECORD_BYTES
1762        || e.original_receipts.is_empty()
1763        || e.original_receipts.len() > 128
1764    {
1765        return Err(Reject::Bounds);
1766    }
1767    if binding.acceptance_id != native_id(acceptance)
1768        || binding.signed_acceptance_digest != signed_native_digest(acceptance)?
1769        || binding.originals_manifest_digest
1770            != boundary_octets_digest(
1771                "heddle-boundary-originals-manifest-v1",
1772                &e.originals_manifest,
1773            )
1774        || binding.publication_intent_digest
1775            != boundary_octets_digest(
1776                "heddle-boundary-publication-intent-v1",
1777                &e.publication_intent,
1778            )
1779    {
1780        return Err(Reject::BoundaryAcceptance);
1781    }
1782    let native: NativeBoundarySelection =
1783        rmp_serde::from_slice(&acceptance.canonical_record).map_err(|_| Reject::Canonical)?;
1784    if native.originals_manifest.as_slice()
1785        != native_octets_id(
1786            "heddle-original-publication-manifest-v1",
1787            &e.originals_manifest,
1788        )
1789        || native.publication_intent.as_slice()
1790            != native_octets_id(
1791                "heddle-original-publication-intent-v1",
1792                &e.publication_intent,
1793            )
1794    {
1795        return Err(Reject::BoundaryAcceptance);
1796    }
1797    let mut digests = Vec::new();
1798    for receipt in &e.original_receipts {
1799        if ![
1800            "heddle-thread-genesis-admission-v2",
1801            "heddle-thread-authority-admission-v3",
1802        ]
1803        .contains(&receipt.format.as_str())
1804        {
1805            return Err(Reject::Version);
1806        }
1807        verify_native(receipt, &receipt.format)?;
1808        if receipt.signatures.len() != 1 {
1809            return Err(Reject::Signature);
1810        }
1811        let native: NativeBoundaryReceipt =
1812            rmp_serde::from_slice(&receipt.canonical_record).map_err(|_| Reject::Canonical)?;
1813        if native.basis
1814            != (NativeBoundaryBasis::BoundaryAcceptance {
1815                acceptance: binding
1816                    .acceptance_id
1817                    .as_slice()
1818                    .try_into()
1819                    .map_err(|_| Reject::Canonical)?,
1820            })
1821        {
1822            return Err(Reject::BoundaryAcceptance);
1823        }
1824        digests.push(signed_native_digest(receipt)?);
1825    }
1826    if digests != binding.original_receipt_digests {
1827        return Err(Reject::BoundaryAcceptance);
1828    }
1829    Ok(())
1830}
1831// These readers extract only the native commitment selectors. Full native
1832// canonicality, model validity, membership and authority remain the native gate.
1833#[derive(serde::Deserialize)]
1834struct NativeBoundarySelection {
1835    originals_manifest: [u8; 32],
1836    publication_intent: [u8; 32],
1837}
1838#[derive(serde::Deserialize, PartialEq)]
1839enum NativeBoundaryBasis {
1840    OriginalAuthority,
1841    BoundaryAcceptance { acceptance: [u8; 32] },
1842}
1843#[derive(serde::Deserialize)]
1844struct NativeBoundaryReceipt {
1845    basis: NativeBoundaryBasis,
1846    thread: [u8; 32],
1847    subject: Option<NativeBoundarySubject>,
1848}
1849#[derive(serde::Deserialize)]
1850enum NativeBoundarySubject {
1851    Operation([u8; 32]),
1852    OwnershipClaim([u8; 32]),
1853    OwnershipResolution([u8; 32]),
1854}
1855fn native_octets_id(format: &str, bytes: &[u8]) -> Vec<u8> {
1856    let mut h = blake3::Hasher::new();
1857    h.update(format.as_bytes());
1858    h.update(&(bytes.len() as u64).to_le_bytes());
1859    h.update(b"\0");
1860    h.update(bytes);
1861    h.finalize().as_bytes().to_vec()
1862}
1863pub(crate) fn boundary_original(
1864    e: &ImportBoundaryAcceptanceV1,
1865    original: &SignedRecord,
1866) -> Result<(), Reject> {
1867    let id = native_id(original);
1868    for receipt in &e.original_receipts {
1869        let value: NativeBoundaryReceipt =
1870            rmp_serde::from_slice(&receipt.canonical_record).map_err(|_| Reject::Canonical)?;
1871        let (format, subject) = match value.subject {
1872            None if receipt.format == "heddle-thread-genesis-admission-v2" => {
1873                ("heddle-thread-genesis-v1", value.thread)
1874            }
1875            Some(NativeBoundarySubject::Operation(id)) => ("heddle-thread-operation-v1", id),
1876            Some(NativeBoundarySubject::OwnershipClaim(id)) => {
1877                ("heddle-thread-ownership-claim-v1", id)
1878            }
1879            Some(NativeBoundarySubject::OwnershipResolution(id)) => {
1880                ("heddle-thread-ownership-resolution-v1", id)
1881            }
1882            _ => return Err(Reject::BoundaryAcceptance),
1883        };
1884        if original.format == format && id == subject {
1885            return Ok(());
1886        }
1887    }
1888    Err(Reject::BoundaryAcceptance)
1889}
1890pub fn boundary_octets_digest(domain: &str, bytes: &[u8]) -> Vec<u8> {
1891    hash(&[
1892        domain.as_bytes(),
1893        &(bytes.len() as u32).to_be_bytes(),
1894        bytes,
1895    ])
1896}
1897pub fn validate_boundary_binding(
1898    b: &crate::heddle::api::common::HostedWitnessBoundaryAcceptanceV1,
1899) -> Result<(), Reject> {
1900    if b.format_version != 1 {
1901        return Err(Reject::Version);
1902    }
1903    for digest in [
1904        &b.acceptance_id,
1905        &b.signed_acceptance_digest,
1906        &b.originals_manifest_digest,
1907        &b.publication_intent_digest,
1908    ] {
1909        width(digest, 32)?;
1910    }
1911    if b.original_receipt_digests.is_empty() || b.original_receipt_digests.len() > 128 {
1912        return Err(Reject::Bounds);
1913    }
1914    for digest in &b.original_receipt_digests {
1915        width(digest, 32)?;
1916    }
1917    if b.original_receipt_digests.windows(2).any(|w| w[0] >= w[1]) {
1918        return Err(Reject::Canonical);
1919    }
1920    Ok(())
1921}
1922pub fn validate_statement_boundary(
1923    s: &crate::heddle::api::common::HostedWitnessStatementV1,
1924) -> Result<(), Reject> {
1925    match (s.basis, s.boundary_acceptance.as_ref()) {
1926        (1, None) => Ok(()),
1927        (2, Some(b)) if s.purpose == 1 || s.purpose == 2 => validate_boundary_binding(b),
1928        _ => Err(Reject::BoundaryAcceptance),
1929    }
1930}
1931pub(crate) fn match_boundary(
1932    s: &crate::heddle::api::common::HostedWitnessStatementV1,
1933    evidence: &[ImportBoundaryAcceptanceV1],
1934) -> Result<(), Reject> {
1935    validate_statement_boundary(s)?;
1936    let mut previous = None;
1937    for e in evidence {
1938        verify_boundary_acceptance(e)?;
1939        let b = e.binding.as_ref().ok_or(Reject::BoundaryAcceptance)?;
1940        if previous.is_some_and(|p: &[u8]| p >= b.acceptance_id.as_slice()) {
1941            return Err(Reject::Canonical);
1942        }
1943        previous = Some(b.acceptance_id.as_slice());
1944    }
1945    if let Some(binding) = &s.boundary_acceptance
1946        && !evidence.iter().any(|e| e.binding.as_ref() == Some(binding))
1947    {
1948        return Err(Reject::BoundaryAcceptance);
1949    }
1950    Ok(())
1951}
1952fn native_dependencies(
1953    records: &[SignedRecord],
1954    evidence: &[ImportBoundaryAcceptanceV1],
1955) -> Result<(), Reject> {
1956    if records.len() > 128 {
1957        return Err(Reject::Bounds);
1958    }
1959    let mut previous = None;
1960    for record in records {
1961        match record.format.as_str() {
1962            "heddle-thread-genesis-v1"
1963            | "heddle-thread-operation-v1"
1964            | "heddle-thread-ownership-claim-v1"
1965            | "heddle-thread-ownership-resolution-v1" => (),
1966            "heddle-original-boundary-acceptance-v1"
1967            | "heddle-thread-genesis-admission-v2"
1968            | "heddle-thread-authority-admission-v3" => {
1969                if !evidence.iter().any(|e| {
1970                    e.signed_acceptance.as_ref() == Some(record)
1971                        || e.original_receipts.contains(record)
1972                }) {
1973                    return Err(Reject::BoundaryAcceptance);
1974                }
1975            }
1976            _ => return Err(Reject::Version),
1977        }
1978        verify_native(record, &record.format)?;
1979        let digest = signed_native_digest(record)?;
1980        if previous.as_ref().is_some_and(|p| p >= &digest) {
1981            return Err(Reject::Canonical);
1982        }
1983        previous = Some(digest);
1984    }
1985    Ok(())
1986}
1987pub(crate) fn original_signatures(
1988    records: &[&SignedRecord],
1989    extra: &[RecordSignature],
1990) -> Result<Vec<u8>, Reject> {
1991    let signatures = records
1992        .iter()
1993        .flat_map(|r| r.signatures.iter())
1994        .chain(extra.iter())
1995        .collect::<Vec<_>>();
1996    let mut out = (signatures.len() as u32).to_be_bytes().to_vec();
1997    for s in signatures {
1998        s.write(&mut out)?;
1999    }
2000    Ok(hash(&[b"heddle-hosted-original-signatures-v1", &out]))
2001}
2002use crate::hybrid_codec::Canonical;
2003/// Portable request-role refusal. Receiver facts include known job and forbidden request keys.
2004pub fn verify_landing_key_roles(
2005    payload: &HostedLandingWitnessV1,
2006    known_job_keys: &[Vec<u8>],
2007    forbidden_keys: &[Vec<u8>],
2008) -> Result<(), Reject> {
2009    let key = &payload
2010        .request
2011        .as_ref()
2012        .and_then(|r| r.signature.as_ref())
2013        .ok_or(Reject::Signature)?
2014        .public_key;
2015    if known_job_keys.contains(key) || forbidden_keys.contains(key) {
2016        return Err(Reject::KeyRole);
2017    }
2018    Ok(())
2019}
2020
2021/// Exact matching and original signatures do not replace native causal/authority/landing checks.
2022pub enum WitnessPayload<'a> {
2023    Genesis(&'a ImportGenesisWitnessV1),
2024    Authority(&'a ImportAuthorityWitnessV1),
2025    Landing(&'a HostedLandingWitnessV1),
2026}
2027pub fn verify_witness_payload(
2028    statement: &crate::heddle::api::common::HostedWitnessStatementV1,
2029    payload: WitnessPayload<'_>,
2030) -> Result<(), Reject> {
2031    let (purpose, bytes, authority, signatures, publisher) = match payload {
2032        WitnessPayload::Genesis(p) => {
2033            if p.format_version != 1 {
2034                return Err(Reject::Version);
2035            }
2036            let original = p.original_genesis.as_ref().ok_or(Reject::Canonical)?;
2037            let binding = p.binding.as_ref().ok_or(Reject::Canonical)?;
2038            let b = binding.body.as_ref().ok_or(Reject::Canonical)?;
2039            match_boundary(
2040                statement,
2041                &p.boundary_acceptance.iter().cloned().collect::<Vec<_>>(),
2042            )?;
2043            if let Some(e) = &p.boundary_acceptance {
2044                boundary_original(e, original)?;
2045            }
2046            if (statement.basis == 2) != p.boundary_acceptance.is_some() {
2047                return Err(Reject::BoundaryAcceptance);
2048            }
2049            verify_native(original, "heddle-thread-genesis-v1")?;
2050            if native_id(original) != b.genesis_digest {
2051                return Err(Reject::Scope);
2052            }
2053            if let Some(id) = &b.identity {
2054                if statement.spool_uuid != id.spool_uuid
2055                    || statement.spool_genesis_digest != id.spool_genesis_digest
2056                    || statement.owner_id != id.owner_id
2057                    || statement.owner_state_hash != id.owner_state_hash
2058                    || statement.ownership_transfer_sequence != id.ownership_transfer_sequence
2059                {
2060                    return Err(Reject::Scope);
2061                }
2062            } else {
2063                return Err(Reject::Canonical);
2064            }
2065            let creator = original
2066                .signatures
2067                .iter()
2068                .find(|s| s.public_key == b.creator_public_key)
2069                .ok_or(Reject::Signature)?;
2070            if b.original_creator_signature != creator.signature
2071                || b.creator_authority_envelope_digest != hash(&[&p.creator_authority_envelope])
2072            {
2073                return Err(Reject::Scope);
2074            }
2075            verify_authorization_signature(
2076                &b.creator_public_key,
2077                GENESIS_DOMAIN,
2078                b,
2079                binding
2080                    .creator_signature
2081                    .as_ref()
2082                    .ok_or(Reject::Signature)?,
2083            )?;
2084            (
2085                1,
2086                canonical(p)?,
2087                signed_genesis_digest(binding)?,
2088                original_signatures(&[original], &[])?,
2089                key_id(&b.creator_public_key),
2090            )
2091        }
2092        WitnessPayload::Authority(p) => {
2093            if p.format_version != 1 {
2094                return Err(Reject::Version);
2095            }
2096            let original = p.original.as_ref().ok_or(Reject::Canonical)?;
2097            let format = match p.kind {
2098                1 => "heddle-thread-operation-v1",
2099                2 => "heddle-thread-ownership-claim-v1",
2100                3 => "heddle-thread-ownership-resolution-v1",
2101                _ => return Err(Reject::Version),
2102            };
2103            verify_native(original, format)?;
2104            if (p.kind == 2 || p.kind == 3) && original.signatures.len() != 2 {
2105                return Err(Reject::Signature);
2106            }
2107            if !original
2108                .signatures
2109                .iter()
2110                .any(|s| key_id(&s.public_key) == statement.publisher_key_id)
2111            {
2112                return Err(Reject::Signature);
2113            }
2114            if p.authority_envelope.is_empty() || p.authority_envelope.len() > MAX_RECORD_BYTES {
2115                return Err(Reject::Bounds);
2116            }
2117            match_boundary(statement, &p.boundary_acceptances)?;
2118            if let Some(b) = &statement.boundary_acceptance {
2119                let e = p
2120                    .boundary_acceptances
2121                    .iter()
2122                    .find(|e| e.binding.as_ref() == Some(b))
2123                    .ok_or(Reject::BoundaryAcceptance)?;
2124                boundary_original(e, original)?;
2125            }
2126            native_dependencies(&p.dependencies, &p.boundary_acceptances)?;
2127            let records = std::iter::once(original)
2128                .chain(p.dependencies.iter())
2129                .collect::<Vec<_>>();
2130            (
2131                2,
2132                canonical(p)?,
2133                hash(&[
2134                    b"heddle-hosted-authority-envelope-v1",
2135                    &(p.authority_envelope.len() as u32).to_be_bytes(),
2136                    &p.authority_envelope,
2137                ]),
2138                original_signatures(&records, &[])?,
2139                statement.publisher_key_id.clone(),
2140            )
2141        }
2142        WitnessPayload::Landing(p) => {
2143            if p.format_version != 1 {
2144                return Err(Reject::Version);
2145            }
2146            let execution = p.execution.as_ref().ok_or(Reject::Canonical)?;
2147            let source = p.source_operation.as_ref().ok_or(Reject::Canonical)?;
2148            let request = p.request.as_ref().ok_or(Reject::Canonical)?;
2149            if request.format_version != 1
2150                || request.method_path != "/heddle.api.v1alpha2.ThreadService/LandThread"
2151            {
2152                return Err(Reject::Version);
2153            }
2154            verify_native(execution, "heddle-thread-operation-v1")?;
2155            verify_native(source, "heddle-thread-operation-v1")?;
2156            match_boundary(statement, &[])?;
2157            native_dependencies(&p.review_evidence, &[])?;
2158            let signature = request.signature.as_ref().ok_or(Reject::Signature)?;
2159            if request.signing_identity
2160                != format!(
2161                    "principal:device-key:{}",
2162                    hex::encode(&signature.public_key)
2163                )
2164            {
2165                return Err(Reject::Signature);
2166            }
2167            width(&request.nonce, 16)?;
2168            if request.timestamp_millis <= 0
2169                || request.request_body.is_empty()
2170                || request.request_body.len() > MAX_RECORD_BYTES
2171                || p.authority_envelope.is_empty()
2172                || p.authority_envelope.len() > MAX_RECORD_BYTES
2173            {
2174                return Err(Reject::Bounds);
2175            }
2176            let input = crate::signing::unary_bytes(
2177                &request.signing_identity,
2178                &request.method_path,
2179                request.timestamp_millis,
2180                &request.nonce,
2181                &request.request_body,
2182            );
2183            verify(&signature.public_key, &input, &signature.signature)?;
2184            let records = [execution, source]
2185                .into_iter()
2186                .chain(p.review_evidence.iter())
2187                .collect::<Vec<_>>();
2188            (
2189                4,
2190                canonical(p)?,
2191                hash(&[
2192                    b"heddle-hosted-authority-envelope-v1",
2193                    &(p.authority_envelope.len() as u32).to_be_bytes(),
2194                    &p.authority_envelope,
2195                ]),
2196                original_signatures(&records, std::slice::from_ref(signature))?,
2197                key_id(&signature.public_key),
2198            )
2199        }
2200    };
2201    if bytes.len() > MAX_RECORD_BYTES {
2202        return Err(Reject::Bounds);
2203    }
2204    if statement.purpose != purpose
2205        || statement.canonical_payload != bytes
2206        || statement.authority_digest != authority
2207        || statement.original_signatures_digest != signatures
2208        || statement.publisher_key_id != publisher
2209    {
2210        return Err(Reject::Scope);
2211    }
2212    Ok(())
2213}
2214
2215pub fn resolve_bundle_permission<'a>(
2216    bundle: &'a ImportPublicProofBundleV1,
2217    digest: &[u8],
2218) -> Result<Option<&'a SignedImportMemberPermissionV1>, Reject> {
2219    width(digest, 32)?;
2220    if digest == [0; 32] {
2221        return Ok(None);
2222    }
2223    bundle
2224        .member_permission
2225        .iter()
2226        .find(|p| signed_permission_digest(p).is_ok_and(|d| d == digest))
2227        .map(Some)
2228        .ok_or(Reject::ImportPermission)
2229}
2230pub fn resolve_bundle_manifest<'a>(
2231    bundle: &'a ImportPublicProofBundleV1,
2232    digest: &[u8],
2233) -> Result<&'a ImportResultManifestV1, Reject> {
2234    width(digest, 32)?;
2235    bundle
2236        .manifests
2237        .iter()
2238        .find(|m| manifest_digest(m).is_ok_and(|d| d == digest))
2239        .ok_or(Reject::StaleManifest)
2240}
2241pub fn publication_payload(
2242    operation: &SignedDelegatedImportOperationV1,
2243    manifest: &ImportResultManifestV1,
2244) -> Result<ImportPublicationWitnessV1, Reject> {
2245    let o = operation.body.as_ref().ok_or(Reject::Canonical)?;
2246    Ok(ImportPublicationWitnessV1 {
2247        format_version: 1,
2248        signed_operation_digest: signed_operation_digest(operation)?,
2249        delegation_digest: o.delegation_digest.clone(),
2250        logical_job_id: o.logical_job_id.clone(),
2251        retry_lineage_id: o.retry_lineage_id.clone(),
2252        physical_operation_id: o.physical_operation_id.clone(),
2253        ref_name: o.ref_name.clone(),
2254        slot_id: o.slot_id,
2255        hash_algorithm: o.hash_algorithm,
2256        observed_commit_oid: o.observed_commit_oid.clone(),
2257        expected_frontier_digest: o.expected_frontier_digest.clone(),
2258        resulting_frontier_digest: o.resulting_frontier_digest.clone(),
2259        terminal_manifest_digest: manifest_digest(manifest)?,
2260    })
2261}
2262/// Completeness and digest addressing only. Trust/signature verification still
2263/// uses independently selected owner contexts at each witnessed historical time.
2264fn validate_bundle_history(
2265    bundle: &ImportPublicProofBundleV1,
2266    require_admissions: bool,
2267) -> Result<(), Reject> {
2268    fn sorted<T>(
2269        values: &[T],
2270        digest: impl Fn(&T) -> Result<Vec<u8>, Reject>,
2271    ) -> Result<(), Reject> {
2272        let mut previous = None;
2273        for value in values {
2274            let d = digest(value)?;
2275            if previous.as_ref().is_some_and(|p| p >= &d) {
2276                return Err(Reject::Canonical);
2277            }
2278            previous = Some(d);
2279        }
2280        Ok(())
2281    }
2282    let mut foreign = crate::foreign_dependencies::References::new(
2283        &bundle.foreign_dependencies,
2284        ForeignDependencyOrigin::Import,
2285    )?;
2286    for p in &bundle.authority_witnesses {
2287        let subject_thread =
2288            crate::foreign_dependencies::thread(p.original.as_ref().ok_or(Reject::Canonical)?)?;
2289        if !bundle.genesis_witnesses.iter().any(|g| {
2290            g.original_genesis
2291                .as_ref()
2292                .is_some_and(|g| native_id(g) == subject_thread)
2293        }) {
2294            return Err(Reject::Scope);
2295        }
2296    }
2297    let job_keys = bundle
2298        .delegations
2299        .iter()
2300        .filter_map(|d| d.body.as_ref().map(|d| d.job_public_key.clone()))
2301        .collect::<Vec<_>>();
2302    for p in &bundle.landing_witnesses {
2303        verify_landing_key_roles(p, &job_keys, &[])?;
2304        let execution = p.execution.as_ref().ok_or(Reject::Canonical)?;
2305        let thread = crate::foreign_dependencies::thread(execution)?;
2306        if !bundle.genesis_witnesses.iter().any(|p| {
2307            p.original_genesis
2308                .as_ref()
2309                .is_some_and(|g| native_id(g) == thread)
2310        }) {
2311            return Err(Reject::Scope);
2312        }
2313    }
2314    // In-carrier genesis witnesses establish origin membership, never permission.
2315    for original in bundle
2316        .authority_witnesses
2317        .iter()
2318        .flat_map(|p| p.original.iter().chain(p.dependencies.iter()))
2319        .chain(bundle.landing_witnesses.iter().flat_map(|p| {
2320            p.execution
2321                .iter()
2322                .chain(p.source_operation.iter())
2323                .chain(p.review_evidence.iter())
2324        }))
2325    {
2326        if [
2327            "heddle-original-boundary-acceptance-v1",
2328            "heddle-thread-genesis-admission-v2",
2329            "heddle-thread-authority-admission-v3",
2330        ]
2331        .contains(&original.format.as_str())
2332        {
2333            continue;
2334        }
2335        let thread = crate::foreign_dependencies::thread(original)?;
2336        if !bundle.genesis_witnesses.iter().any(|p| {
2337            p.original_genesis
2338                .as_ref()
2339                .is_some_and(|g| native_id(g) == thread)
2340        }) {
2341            foreign.require(original)?;
2342        } else if original.format == "heddle-thread-genesis-v1"
2343            && !bundle
2344                .genesis_witnesses
2345                .iter()
2346                .any(|p| p.original_genesis.as_ref() == Some(original))
2347        {
2348            return Err(Reject::Scope);
2349        }
2350    }
2351    foreign.finish()?;
2352    for operation in &bundle.operations {
2353        if operation.body.is_none() {
2354            return Err(Reject::Canonical);
2355        }
2356    }
2357    for statement in &bundle.statements {
2358        let s = statement.body.as_ref().ok_or(Reject::Canonical)?;
2359        validate_statement_boundary(s)?;
2360        require_policy_history(
2361            &bundle.policies,
2362            &s.spool_uuid,
2363            s.policy_sequence,
2364            &s.policy_state_hash,
2365        )?;
2366    }
2367    sorted(&bundle.manifests, manifest_digest)?;
2368    if let Some(p) = &bundle.member_permission
2369        && resolve_bundle_permission(bundle, &signed_permission_digest(p)?)? != Some(p)
2370    {
2371        return Err(Reject::ImportPermission);
2372    }
2373    let terminal = bundle.terminal_manifest.as_ref().ok_or(Reject::Canonical)?;
2374    if resolve_bundle_manifest(bundle, &manifest_digest(terminal)?)? != terminal {
2375        return Err(Reject::Canonical);
2376    }
2377    if bundle.delegations.len() != 1 {
2378        return Err(Reject::Canonical);
2379    }
2380    for d in &bundle.delegations {
2381        let body = d.body.as_ref().ok_or(Reject::Canonical)?;
2382        resolve_bundle_permission(bundle, &body.parent_permission_digest)?;
2383        for branch in &body.branch_manifest {
2384            let g = bundle
2385                .genesis_authorities
2386                .iter()
2387                .find(|g| {
2388                    signed_genesis_digest(g).is_ok_and(|h| h == branch.genesis_authority_digest)
2389                })
2390                .ok_or(Reject::Scope)?;
2391            let b = g.body.as_ref().ok_or(Reject::Canonical)?;
2392            resolve_bundle_permission(bundle, &b.parent_permission_digest)?;
2393            if !bundle
2394                .original_geneses
2395                .iter()
2396                .any(|o| native_id(o) == b.genesis_digest)
2397                || !bundle
2398                    .creator_authority_envelopes
2399                    .iter()
2400                    .any(|e| hash(&[e]) == b.creator_authority_envelope_digest)
2401            {
2402                return Err(Reject::Scope);
2403            }
2404            // Every published branch needs its original admission, not merely its
2405            // binding. Proof-only retirement lookup cannot recover a payload.
2406            if require_admissions
2407                && bundle.operations.iter().any(|o| {
2408                    o.body
2409                        .as_ref()
2410                        .is_some_and(|o| o.genesis_digest == b.genesis_digest)
2411                })
2412                && !bundle.genesis_witnesses.iter().any(|payload| {
2413                    payload.binding.as_ref() == Some(g)
2414                        && payload.original_genesis.as_ref().is_some_and(|o| {
2415                            native_id(o) == b.genesis_digest && bundle.original_geneses.contains(o)
2416                        })
2417                        && hash(&[&payload.creator_authority_envelope])
2418                            == b.creator_authority_envelope_digest
2419                        && canonical(payload).is_ok_and(|bytes| {
2420                            bundle.statements.iter().any(|s| {
2421                                s.body
2422                                    .as_ref()
2423                                    .is_some_and(|s| s.purpose == 1 && s.canonical_payload == bytes)
2424                            })
2425                        })
2426                })
2427            {
2428                return Err(Reject::Scope);
2429            }
2430        }
2431    }
2432    for manifest in &bundle.manifests {
2433        validate_manifest(manifest)?;
2434        if manifest.logical_job_id != terminal.logical_job_id
2435            || manifest.retry_lineage_id != terminal.retry_lineage_id
2436        {
2437            return Err(Reject::Scope);
2438        }
2439        for slot in &manifest.slots {
2440            let operation = bundle
2441                .operations
2442                .iter()
2443                .find(|o| {
2444                    signed_operation_digest(o).is_ok_and(|d| d == slot.signed_operation_digest)
2445                })
2446                .ok_or(Reject::Scope)?;
2447            if !check_slot_replay(manifest, operation)? || !check_slot_replay(terminal, operation)?
2448            {
2449                return Err(Reject::Scope);
2450            }
2451        }
2452    }
2453    for operation in &bundle.operations {
2454        let o = operation.body.as_ref().ok_or(Reject::Canonical)?;
2455        if !bundle
2456            .delegations
2457            .iter()
2458            .any(|d| signed_delegation_digest(d).is_ok_and(|h| h == o.delegation_digest))
2459            || !check_slot_replay(terminal, operation)?
2460        {
2461            return Err(Reject::Scope);
2462        }
2463        if !bundle.manifests.iter().any(|m| {
2464            check_slot_replay(m, operation) == Ok(true)
2465                && publication_payload(operation, m)
2466                    .and_then(|p| canonical(&p))
2467                    .is_ok_and(|p| {
2468                        bundle.statements.iter().any(|s| {
2469                            s.body
2470                                .as_ref()
2471                                .is_some_and(|s| s.purpose == 3 && s.canonical_payload == p)
2472                        })
2473                    })
2474        }) {
2475            return Err(Reject::Scope);
2476        }
2477    }
2478    for statement in &bundle.statements {
2479        let s = statement.body.as_ref().ok_or(Reject::Canonical)?;
2480        let found = match s.purpose {
2481            1 => bundle
2482                .genesis_witnesses
2483                .iter()
2484                .any(|p| canonical(p).is_ok_and(|p| p == s.canonical_payload)),
2485            2 => bundle
2486                .authority_witnesses
2487                .iter()
2488                .any(|p| canonical(p).is_ok_and(|p| p == s.canonical_payload)),
2489            3 => bundle.operations.iter().any(|o| {
2490                bundle.manifests.iter().any(|m| {
2491                    publication_payload(o, m)
2492                        .and_then(|p| canonical(&p))
2493                        .is_ok_and(|p| p == s.canonical_payload)
2494                })
2495            }),
2496            4 => bundle
2497                .landing_witnesses
2498                .iter()
2499                .any(|p| canonical(p).is_ok_and(|p| p == s.canonical_payload)),
2500            _ => return Err(Reject::Version),
2501        };
2502        if !found {
2503            return Err(Reject::Scope);
2504        }
2505    }
2506    Ok(())
2507}
2508/// Reference completeness only. Native verification must authenticate every
2509/// selected policy, its owner context and the receipt before using its time.
2510pub(crate) fn require_policy_history(
2511    policies: &[SignedSpoolPolicyRecord],
2512    spool: &[u8],
2513    mut sequence: u64,
2514    state_hash: &[u8],
2515) -> Result<(), Reject> {
2516    let mut state_hash = state_hash.to_vec();
2517    for _ in 0..=policies.len() {
2518        width(&state_hash, 32)?;
2519        if sequence == 0 {
2520            return if state_hash == [0; 32] {
2521                Ok(())
2522            } else {
2523                Err(Reject::Scope)
2524            };
2525        }
2526        let mut matches = policies.iter().filter_map(|p| p.body.as_ref()).filter(|p| {
2527            p.spool_uuid == spool && p.sequence == sequence && p.policy_state_hash == state_hash
2528        });
2529        let policy = matches.next().ok_or(Reject::Scope)?;
2530        if matches.next().is_some() {
2531            return Err(Reject::Canonical);
2532        }
2533        let head = policy.expected_head.as_ref().ok_or(Reject::Canonical)?;
2534        if head.sequence.checked_add(1) != Some(sequence) {
2535            return Err(Reject::Scope);
2536        }
2537        sequence = head.sequence;
2538        state_hash = head.state_hash.clone();
2539    }
2540    Err(Reject::Scope)
2541}
2542pub(crate) fn native_id(record: &SignedRecord) -> Vec<u8> {
2543    let mut h = blake3::Hasher::new();
2544    h.update(record.format.as_bytes());
2545    h.update(&(record.canonical_record.len() as u64).to_le_bytes());
2546    h.update(b"\0");
2547    h.update(&record.canonical_record);
2548    h.finalize().as_bytes().to_vec()
2549}
2550
2551/// Caller-generated non-nil UUID, reserved as the first physical operation ID.
2552/// Occupancy is checked under the host's reservation/activation transaction.
2553pub fn initial_operation_id(lineage: &[u8], occupied: bool) -> Result<String, Reject> {
2554    width(lineage, 16)?;
2555    if lineage.iter().all(|b| *b == 0) {
2556        return Err(Reject::Canonical);
2557    }
2558    if occupied {
2559        return Err(Reject::OperationIdReused);
2560    }
2561    let h = hex::encode(lineage);
2562    Ok(format!(
2563        "{}-{}-{}-{}-{}",
2564        &h[..8],
2565        &h[8..12],
2566        &h[12..16],
2567        &h[16..20],
2568        &h[20..]
2569    ))
2570}
2571
2572/// Evaluate inside the cancellation transaction, after caller-scoped replay lookup.
2573/// The selector names only the ACTIVE delegation. Parent revocation is independent.
2574pub fn check_cancel_request(
2575    request: &CancelImportJobRequest,
2576    active: &SignedImportJobDelegationV1,
2577    durable_epoch: u64,
2578    cancelled: bool,
2579) -> Result<(), Reject> {
2580    let d = active.body.as_ref().ok_or(Reject::Canonical)?;
2581    width(&request.logical_job_id, 16)?;
2582    width(&request.cancellation_id, 32)?;
2583    let id = d.identity.as_ref().ok_or(Reject::Canonical)?;
2584    if request.client_operation_id.is_empty()
2585        || request.destination.as_ref().is_none_or(|s| {
2586            initial_operation_id(&id.spool_uuid, false).map_or(true, |uuid| s.id != uuid)
2587        })
2588        || request.logical_job_id != d.logical_job_id
2589    {
2590        return Err(Reject::Scope);
2591    }
2592    if durable_epoch == 0 || request.expected_authority_epoch != durable_epoch {
2593        return Err(Reject::StaleContext);
2594    }
2595    if request.cancellation_id != d.cancellation_id {
2596        return Err(Reject::Scope);
2597    }
2598    if cancelled {
2599        return Err(Reject::Revoked);
2600    }
2601    Ok(())
2602}
2603/// Exact replay acknowledges the stored cancellation without advancing the epoch.
2604pub fn check_cancel_replay(
2605    request: &CancelImportJobRequest,
2606    stored: &CancelImportJobRequest,
2607) -> Result<(), Reject> {
2608    if request != stored {
2609        return Err(Reject::OperationIdReused);
2610    }
2611    Ok(())
2612}
2613/// Check both independent revocation selectors, regardless of Cancel's selector.
2614pub fn check_import_revocations(
2615    delegation: &SignedImportJobDelegationV1,
2616    member: Option<&SignedImportMemberPermissionV1>,
2617    revoked: &[Vec<u8>],
2618) -> Result<(), Reject> {
2619    let d = delegation.body.as_ref().ok_or(Reject::Canonical)?;
2620    width(&d.cancellation_id, 32)?;
2621    if revoked.contains(&d.cancellation_id) {
2622        return Err(Reject::Revoked);
2623    }
2624    if let Some(parent) = member {
2625        let p = parent.body.as_ref().ok_or(Reject::ImportPermission)?;
2626        width(&p.cancellation_id, 32)?;
2627        if revoked.contains(&p.cancellation_id) {
2628            return Err(Reject::Revoked);
2629        }
2630    }
2631    Ok(())
2632}
2633
2634/// Compute the exact remaining total and slots from an authenticated manifest.
2635/// An empty result is completed work and cannot pass new-scope validation.
2636pub fn remaining_import_scope(
2637    scope: &ImportPermissionScopeV1,
2638    committed: &ImportResultManifestV1,
2639) -> Result<ImportPermissionScopeV1, Reject> {
2640    validate_scope(scope)?;
2641    validate_manifest(committed)?;
2642    let mut remaining = scope.clone();
2643    for slot in &committed.slots {
2644        if !scope
2645            .branches
2646            .iter()
2647            .any(|b| b.ref_name == slot.ref_name && b.slot_id == slot.slot_id)
2648        {
2649            return Err(Reject::Scope);
2650        }
2651        {
2652            remaining.max_result_bytes = remaining
2653                .max_result_bytes
2654                .checked_sub(slot.result_bytes)
2655                .ok_or(Reject::Scope)?;
2656            remaining.max_operations = remaining
2657                .max_operations
2658                .checked_sub(1)
2659                .ok_or(Reject::Scope)?;
2660        }
2661    }
2662    remaining.branches.retain(|b| {
2663        !committed
2664            .slots
2665            .iter()
2666            .any(|s| s.ref_name == b.ref_name && s.slot_id == b.slot_id)
2667    });
2668    Ok(remaining)
2669}
2670
2671/// Validate discovery metadata only; a well-shaped selector grants no authority.
2672pub fn validate_hybrid_import_job_selector(
2673    selector: &HybridImportJobSelector,
2674) -> Result<(), Reject> {
2675    width(&selector.logical_job_id, 16)?;
2676    if selector.logical_job_id.iter().all(|byte| *byte == 0) {
2677        return Err(Reject::Canonical);
2678    }
2679    Ok(())
2680}
2681
2682/// Project a visible operation's durable HYBRID association into the existing
2683/// writer-only state read. Missing/unknown subject or selector is unavailable.
2684/// Malformed present metadata is rejected; never substitute an attempt ID.
2685/// This validates shape, not operation visibility, writer access or signatures.
2686pub fn import_job_state_request_from_operation(
2687    operation: &OperationRecord,
2688) -> Result<Option<GetImportJobStateRequest>, Reject> {
2689    let Some(operation_subject::Subject::Import(subject)) = operation
2690        .subject
2691        .as_ref()
2692        .and_then(|subject| subject.subject.as_ref())
2693    else {
2694        return Ok(None);
2695    };
2696    let Some(selector) = subject.hybrid_job.as_ref() else {
2697        return Ok(None);
2698    };
2699    validate_hybrid_import_job_selector(selector)?;
2700    let request = GetImportJobStateRequest {
2701        destination: operation
2702            .r#ref
2703            .as_ref()
2704            .and_then(|record| record.spool.clone()),
2705        logical_job_id: selector.logical_job_id.clone(),
2706    };
2707    validate_job_state_request(&request)?;
2708    Ok(Some(request))
2709}
2710
2711/// Finite destination-writer read; transport authentication/authorization belongs
2712/// to the generated RPC contract. Validate before any storage lookup.
2713pub fn validate_job_state_request(request: &GetImportJobStateRequest) -> Result<(), Reject> {
2714    use prost::Message;
2715    if request.encoded_len() > 4096 {
2716        return Err(Reject::Bounds);
2717    }
2718    initial_operation_id(&request.logical_job_id, false)?;
2719    let destination = request.destination.as_ref().ok_or(Reject::Scope)?;
2720    let compact = destination.id.replace('-', "");
2721    let raw = hex::decode(&compact).map_err(|_| Reject::Scope)?;
2722    if initial_operation_id(&raw, false).map_or(true, |id| id != destination.id) {
2723        return Err(Reject::Scope);
2724    }
2725    Ok(())
2726}
2727
2728/// Supply the authenticated read, never an incoming untrusted state assertion.
2729pub fn validate_job_state_response(
2730    request: &GetImportJobStateRequest,
2731    response: &GetImportJobStateResponse,
2732) -> Result<(), Reject> {
2733    use prost::Message;
2734    validate_job_state_request(request)?;
2735    if response.encoded_len() > 4096 {
2736        return Err(Reject::Bounds);
2737    }
2738    if !(1..=5).contains(&response.status) || response.authority_epoch == 0 {
2739        return Err(Reject::Canonical);
2740    }
2741    width(&response.active_cancellation_id, 32)?;
2742    width(&response.active_delegation_digest, 32)?;
2743    validate_retry_availability(response, request.destination.as_ref().ok_or(Reject::Scope)?)
2744}
2745
2746/// Independently installed descriptor pin; never learned from a response.
2747#[derive(Debug, Clone, PartialEq)]
2748pub struct ImportWitnessRootPin {
2749    pub authority: String,
2750    pub root_id: String,
2751    pub public_key: Vec<u8>,
2752    pub epoch: u64,
2753}
2754/// Receiver-owned durable data, committed atomically with accepted history.
2755/// Do not deserialize this from the incoming proof or lower its clock floor.
2756#[derive(Debug, Clone, PartialEq)]
2757pub struct ImportWitnessSnapshot {
2758    pub root: ImportWitnessRootPin,
2759    pub witness_set: crate::heddle::api::common::SignedHostedWitnessSetV1,
2760    pub clock_floor_unix_millis: i64,
2761    pub job_associations: Vec<(Vec<u8>, Vec<u8>)>,
2762    pub accepted_history: Vec<ImportPublicProofBundleV1>,
2763}
2764/// Witnessed requires an authenticated observation for every accepted delegation.
2765/// Recovery can retain witnessed history but grants no admission for the active tail.
2766#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2767pub enum ImportBundleEvidence {
2768    Recovery,
2769    Witnessed,
2770}
2771#[derive(Debug, Clone, PartialEq)]
2772pub struct VerifiedImportBundleWitnesses {
2773    pub evidence: ImportBundleEvidence,
2774    pub accepted_history: ImportResultManifestV1,
2775    pub snapshot: Option<ImportWitnessSnapshot>,
2776    pub snapshot_advanced: bool,
2777    pub owner_check_time_unix_seconds: Option<i64>,
2778}
2779/// Check the host's signed same-transaction assertion for a P1 and its consumed P3.
2780/// Receivers verify consistency; only the issuing host can ensure atomic visibility.
2781pub fn check_import_genesis_publication_pair(
2782    delegation: &VerifiedImportDelegation,
2783    admission: &crate::heddle::api::common::HostedWitnessStatementV1,
2784    publication: &crate::heddle::api::common::HostedWitnessStatementV1,
2785) -> Result<(), Reject> {
2786    validity(
2787        delegation.body.not_before_unix_seconds,
2788        delegation.body.expires_at_unix_seconds,
2789        admission.observed_at_unix_millis / 1000,
2790        true,
2791    )?;
2792    if admission.purpose != 1
2793        || publication.purpose != 3
2794        || admission.observed_at_unix_millis != publication.observed_at_unix_millis
2795        || admission.host_transaction_id != publication.host_transaction_id
2796        || admission.executor_id != publication.executor_id
2797        || admission.admission_order >= publication.admission_order
2798    {
2799        return Err(Reject::Transition);
2800    }
2801    Ok(())
2802}
2803
2804/// Verify public Fetch/export evidence. Owner contexts
2805/// are resolved independently at each authenticated time. The verifier derives times
2806/// from the first authenticated publication of the sole delegation.
2807/// Unwitnessed certificates are time-free recovery only.
2808/// The mandatory hook verifies the selected policy chain and owner/native context
2809/// at each authenticated statement time (heddle capability-verifier / WASM).
2810/// With no statements it receives None and verifies time-free policy closure.
2811/// No result is returned on failure. Recovery without a witnessed prefix or new
2812/// authenticated set returns the input snapshot unchanged. A witnessed prefix
2813/// extends rollback protection; recovery cannot persist job history. A new set
2814/// can additionally advance set trust and clock. None remains None when no
2815/// set is carried and no input exists. Persist under the trust lock; inspect
2816/// snapshot_advanced for actual durable change, independently of evidence.
2817pub fn verify_import_bundle_witnesses<'a>(
2818    bundle: &ImportPublicProofBundleV1,
2819    pin: &ImportWitnessRootPin,
2820    snapshot: Option<&ImportWitnessSnapshot>,
2821    now_ms: i64,
2822    mut owner_at: impl FnMut(Option<i64>) -> Result<ImportBundleOwnerExpectation<'a>, Reject>,
2823    mut verify_policy: impl FnMut(
2824        &ImportPublicProofBundleV1,
2825        Option<&crate::heddle::api::common::HostedWitnessStatementV1>,
2826    ) -> Result<(), Reject>,
2827) -> Result<VerifiedImportBundleWitnesses, Reject> {
2828    use crate::witness_trust as trust;
2829    width(&pin.public_key, 32)?;
2830    if pin.epoch == 0 {
2831        return Err(Reject::StaleContext);
2832    }
2833    validate_bundle_bounds(bundle)?;
2834    let terminal = bundle.terminal_manifest.as_ref().ok_or(Reject::Canonical)?;
2835    validate_bundle_history(bundle, !terminal.slots.is_empty())?;
2836    let mut associations = snapshot.map_or_else(Vec::new, |s| s.job_associations.clone());
2837    for d in &bundle.delegations {
2838        let b = d.body.as_ref().ok_or(Reject::Canonical)?;
2839        if associations
2840            .iter()
2841            .any(|(key, job)| *key == b.job_public_key && *job != b.logical_job_id)
2842        {
2843            return Err(Reject::KeyRole);
2844        }
2845        if !associations.iter().any(|(key, _)| *key == b.job_public_key) {
2846            associations.push((b.job_public_key.clone(), b.logical_job_id.clone()));
2847        }
2848    }
2849    let job_keys = associations
2850        .iter()
2851        .map(|(key, _)| key.clone())
2852        .collect::<Vec<_>>();
2853    fn expectation<'a>(
2854        root: &'a ImportWitnessRootPin,
2855        floor: i64,
2856        now: i64,
2857        keys: &'a [Vec<u8>],
2858    ) -> trust::SetExpectation<'a> {
2859        trust::SetExpectation {
2860            authority: &root.authority,
2861            root_id: &root.root_id,
2862            root_public_key: &root.public_key,
2863            root_epoch: root.epoch,
2864            now_unix_millis: now,
2865            clock_floor_unix_millis: floor,
2866            known_job_keys: keys,
2867        }
2868    }
2869    let previous = if let Some(s) = snapshot {
2870        if s.root.authority != pin.authority {
2871            return Err(Reject::Root);
2872        }
2873        let restored = trust::restore_history_snapshot(
2874            &s.witness_set,
2875            &expectation(&s.root, 0, now_ms, &job_keys),
2876        )?;
2877        Some(restored)
2878    } else {
2879        None
2880    };
2881    let carried = bundle.witness_set.as_ref();
2882    if carried.is_none() && !bundle.statements.is_empty() {
2883        return Err(Reject::Canonical);
2884    }
2885    let new_set =
2886        carried.is_some_and(|c| snapshot.is_none_or(|s| s.root != *pin || s.witness_set != *c));
2887    let selected = expectation(
2888        pin,
2889        snapshot.map_or(0, |s| s.clock_floor_unix_millis),
2890        now_ms,
2891        &job_keys,
2892    );
2893    let set = carried
2894        .map(|carried| {
2895            if snapshot.is_some_and(|s| s.root != *pin) {
2896                trust::verify_set_after_root_replacement(
2897                    carried,
2898                    &selected,
2899                    previous.as_ref().ok_or(Reject::StaleContext)?,
2900                )
2901            } else {
2902                trust::verify_set(carried, &selected, previous.as_ref())
2903            }
2904        })
2905        .transpose()?;
2906    // Authenticate statements before using their observation times or policies.
2907    let mut resolved = Vec::new();
2908    for signed in &bundle.statements {
2909        let s = signed.body.as_ref().ok_or(Reject::Canonical)?;
2910        let set = set.as_ref().ok_or(Reject::Canonical)?;
2911        let entry = set
2912            .body()
2913            .entries
2914            .iter()
2915            .find(|e| e.executor_id == s.executor_id)
2916            .ok_or(Reject::Root)?;
2917        let proof = if entry.state == 2 {
2918            let leaf = trust::leaf_digest(s.purpose, &canonical(s)?, &signed.signature)?;
2919            bundle.history_proofs.iter().find(|p| {
2920                p.purpose == s.purpose && trust::verify_inclusion(&leaf, p, entry).is_ok()
2921            })
2922        } else {
2923            None
2924        };
2925        let context = trust::resolve_statement(set, signed, proof, false, now_ms)?;
2926        verify_policy(bundle, Some(s))?;
2927        resolved.push((context, proof));
2928    }
2929    if bundle.statements.is_empty() {
2930        // Time-free policy/owner/native closure; this asserts no admission event.
2931        verify_policy(bundle, None)?;
2932    }
2933    // Derive owner-selection times only from authenticated receipts. Prefer the
2934    // first publication for each delegation; initial admissions stand alone too.
2935    // Select precisely the P3 each progressive prefix consumes, independent of
2936    // statement array order. Every carried P3 must be consumed exactly once.
2937    let mut prefix = ImportResultManifestV1 {
2938        slots: vec![],
2939        ..terminal.clone()
2940    };
2941    let mut selected_publications = Vec::new();
2942    for operation in &bundle.operations {
2943        let digest = signed_operation_digest(operation)?;
2944        let slot = terminal
2945            .slots
2946            .iter()
2947            .find(|slot| slot.signed_operation_digest == digest)
2948            .ok_or(Reject::Scope)?;
2949        prefix.slots.push(slot.clone());
2950        prefix
2951            .slots
2952            .sort_by(|a, b| (&a.ref_name, a.slot_id).cmp(&(&b.ref_name, b.slot_id)));
2953        let payload = canonical(&publication_payload(operation, &prefix)?)?;
2954        let matches = bundle
2955            .statements
2956            .iter()
2957            .filter(|signed| {
2958                signed
2959                    .body
2960                    .as_ref()
2961                    .is_some_and(|s| s.purpose == 3 && s.canonical_payload == payload)
2962            })
2963            .collect::<Vec<_>>();
2964        if matches.len() != 1 {
2965            return Err(Reject::Transition);
2966        }
2967        selected_publications.push(matches[0]);
2968    }
2969    if bundle.statements.iter().any(|signed| {
2970        signed
2971            .body
2972            .as_ref()
2973            .is_some_and(|s| s.purpose == 3 && !selected_publications.contains(&signed))
2974    }) {
2975        return Err(Reject::Transition);
2976    }
2977    let mut admitted_geneses = std::collections::BTreeSet::<Vec<u8>>::new();
2978    let mut times = vec![None; bundle.delegations.len()];
2979    let mut publications = Vec::new();
2980    for signed in &bundle.statements {
2981        let statement = signed.body.as_ref().ok_or(Reject::Canonical)?;
2982        if statement.purpose != 3 {
2983            continue;
2984        }
2985        let (operation, manifest) = bundle
2986            .operations
2987            .iter()
2988            .flat_map(|o| bundle.manifests.iter().map(move |m| (o, m)))
2989            .find(|(o, m)| {
2990                publication_payload(o, m)
2991                    .and_then(|p| canonical(&p))
2992                    .is_ok_and(|b| b == statement.canonical_payload)
2993            })
2994            .ok_or(Reject::Scope)?;
2995        let digest = &operation
2996            .body
2997            .as_ref()
2998            .ok_or(Reject::Canonical)?
2999            .delegation_digest;
3000        let index = bundle
3001            .delegations
3002            .iter()
3003            .position(|d| signed_delegation_digest(d).is_ok_and(|h| h == *digest))
3004            .ok_or(Reject::Scope)?;
3005        let time = statement.observed_at_unix_millis / 1000;
3006        // First means accepted publication order, independent of array order.
3007        if times[index].is_none_or(|(order, _)| statement.admission_order < order) {
3008            times[index] = Some((statement.admission_order, time));
3009        }
3010        publications.push((signed, operation, manifest, index));
3011    }
3012    // Resolve only after authentication. Facts must cover the selected time;
3013    // current claimed state cannot stand in for an earlier deferred state.
3014    let mut resolve_owner = |time: Option<i64>| {
3015        let facts = owner_at(time)?;
3016        if facts.effective_from_unix_seconds < 0
3017            || facts
3018                .effective_until_unix_seconds
3019                .is_some_and(|end| end <= facts.effective_from_unix_seconds)
3020            || time.is_some_and(|t| {
3021                t < facts.effective_from_unix_seconds
3022                    || facts
3023                        .effective_until_unix_seconds
3024                        .is_some_and(|end| t >= end)
3025            })
3026        {
3027            return Err(Reject::Scope);
3028        }
3029        for (key, job) in facts.known_job_associations {
3030            if associations.iter().any(|(k, j)| k == key && j != job) {
3031                return Err(Reject::KeyRole);
3032            }
3033            if !associations.iter().any(|(k, _)| k == key) {
3034                associations.push((key.clone(), job.clone()));
3035            }
3036        }
3037        if facts
3038            .forbidden_job_keys
3039            .iter()
3040            .any(|key| associations.iter().any(|(known, _)| known == key))
3041        {
3042            return Err(Reject::KeyRole);
3043        }
3044        // Also keep newly supplied known job keys disjoint from witness roles.
3045        if set.as_ref().is_some_and(|set| {
3046            facts.known_job_associations.iter().any(|(key, _)| {
3047                *key == pin.public_key || set.body().entries.iter().any(|e| e.public_key == *key)
3048            })
3049        }) {
3050            return Err(Reject::KeyRole);
3051        }
3052        Ok((facts, associations.clone()))
3053    };
3054    let mut verified = Vec::new();
3055    for (i, d) in bundle.delegations.iter().enumerate() {
3056        let body = d.body.as_ref().ok_or(Reject::Canonical)?;
3057        let parent = resolve_bundle_permission(bundle, &body.parent_permission_digest)?;
3058        let time = times[i].map(|(_, time)| time);
3059        let (facts, selected_associations) = resolve_owner(time)?;
3060        let owner = facts.at(time.unwrap_or(0), &selected_associations);
3061        let token = verify_delegation_inner(d, parent, &owner, times[i].is_some())?;
3062        verified.push(token);
3063    }
3064    let initial = verified.first().ok_or(Reject::Canonical)?;
3065    for branch in &initial.body.branch_manifest {
3066        let limit = branch.limit.as_ref().ok_or(Reject::Canonical)?;
3067        let binding = bundle
3068            .genesis_authorities
3069            .iter()
3070            .find(|g| signed_genesis_digest(g).is_ok_and(|h| h == branch.genesis_authority_digest))
3071            .ok_or(Reject::Scope)?;
3072        let original = bundle
3073            .original_geneses
3074            .iter()
3075            .find(|o| native_id(o) == limit.genesis_digest)
3076            .ok_or(Reject::Scope)?;
3077        let g = binding.body.as_ref().ok_or(Reject::Canonical)?;
3078        let envelope = bundle
3079            .creator_authority_envelopes
3080            .iter()
3081            .find(|e| hash(&[e]) == g.creator_authority_envelope_digest)
3082            .ok_or(Reject::Scope)?;
3083        verify_native(original, "heddle-thread-genesis-v1")?;
3084        let signature = original
3085            .signatures
3086            .iter()
3087            .find(|s| s.public_key == g.creator_public_key)
3088            .ok_or(Reject::Scope)?;
3089        verify_genesis_authority(
3090            binding,
3091            initial,
3092            &limit.genesis_digest,
3093            &signature.signature,
3094            &hash(&[envelope]),
3095        )?;
3096    }
3097    for ((context, proof), signed) in resolved.iter().zip(&bundle.statements) {
3098        let s = signed.body.as_ref().ok_or(Reject::Canonical)?;
3099        if !verified.iter().any(|d| {
3100            d.body.identity.as_ref().is_some_and(|id| {
3101                s.spool_uuid == id.spool_uuid
3102                    && s.spool_genesis_digest == id.spool_genesis_digest
3103                    && s.owner_id == id.owner_id
3104                    && s.owner_state_hash == id.owner_state_hash
3105                    && s.ownership_transfer_sequence == id.ownership_transfer_sequence
3106            })
3107        }) {
3108            return Err(Reject::Scope);
3109        }
3110        match s.purpose {
3111            1 => {
3112                // Every original admission must independently satisfy [N,E).
3113                let time = s.observed_at_unix_millis / 1000;
3114                let (facts, selected_associations) = resolve_owner(Some(time))?;
3115                let owner = facts.at(time, &selected_associations);
3116                verify_delegation(
3117                    &bundle.delegations[0],
3118                    resolve_bundle_permission(bundle, &initial.body.parent_permission_digest)?,
3119                    &owner,
3120                )?;
3121                let payload = bundle
3122                    .genesis_witnesses
3123                    .iter()
3124                    .find(|p| canonical(*p).is_ok_and(|b| b == s.canonical_payload))
3125                    .ok_or(Reject::Scope)?;
3126                let genesis = &payload
3127                    .binding
3128                    .as_ref()
3129                    .and_then(|g| g.body.as_ref())
3130                    .ok_or(Reject::Canonical)?
3131                    .genesis_digest;
3132                if !admitted_geneses.insert(genesis.clone()) {
3133                    return Err(Reject::Transition);
3134                }
3135                let publication = bundle
3136                    .operations
3137                    .iter()
3138                    .zip(&selected_publications)
3139                    .find(|(o, _)| {
3140                        o.body
3141                            .as_ref()
3142                            .is_some_and(|o| &o.genesis_digest == genesis)
3143                    })
3144                    .and_then(|(_, s)| s.body.as_ref())
3145                    .ok_or(Reject::Transition)?;
3146                check_import_genesis_publication_pair(initial, s, publication)?;
3147                verify_witness_payload(
3148                    s,
3149                    WitnessPayload::Genesis(
3150                        bundle
3151                            .genesis_witnesses
3152                            .iter()
3153                            .find(|p| canonical(*p).is_ok_and(|b| b == s.canonical_payload))
3154                            .ok_or(Reject::Scope)?,
3155                    ),
3156                )?;
3157            }
3158            2 => verify_witness_payload(
3159                s,
3160                WitnessPayload::Authority(
3161                    bundle
3162                        .authority_witnesses
3163                        .iter()
3164                        .find(|p| canonical(*p).is_ok_and(|b| b == s.canonical_payload))
3165                        .ok_or(Reject::Scope)?,
3166                ),
3167            )?,
3168            4 => {
3169                let payload = bundle
3170                    .landing_witnesses
3171                    .iter()
3172                    .find(|p| canonical(*p).is_ok_and(|b| b == s.canonical_payload))
3173                    .ok_or(Reject::Scope)?;
3174                let (facts, selected_associations) =
3175                    resolve_owner(Some(s.observed_at_unix_millis / 1000))?;
3176                let known = selected_associations
3177                    .iter()
3178                    .map(|(key, _)| key.clone())
3179                    .collect::<Vec<_>>();
3180                verify_landing_key_roles(payload, &known, facts.forbidden_landing_keys)?;
3181                verify_witness_payload(s, WitnessPayload::Landing(payload))?;
3182            }
3183            3 => {
3184                let (_, operation, manifest, index) = publications
3185                    .iter()
3186                    .find(|(statement, _, _, _)| *statement == signed)
3187                    .ok_or(Reject::Scope)?;
3188                let d = &bundle.delegations[*index];
3189                let body = d.body.as_ref().ok_or(Reject::Canonical)?;
3190                let time = s.observed_at_unix_millis / 1000;
3191                let (facts, selected_associations) = resolve_owner(Some(time))?;
3192                let owner = facts.at(time, &selected_associations);
3193                let delegation = verify_delegation(
3194                    d,
3195                    resolve_bundle_permission(bundle, &body.parent_permission_digest)?,
3196                    &owner,
3197                )?;
3198                verify_publication(
3199                    operation,
3200                    &delegation,
3201                    manifest,
3202                    signed,
3203                    set.as_ref().ok_or(Reject::Canonical)?,
3204                    *proof,
3205                    now_ms,
3206                )?;
3207            }
3208            _ => return Err(Reject::Version),
3209        }
3210        trust::recheck_context(
3211            context,
3212            set.as_ref().ok_or(Reject::Canonical)?,
3213            signed,
3214            now_ms,
3215        )?;
3216    }
3217    // Operations are accepted publication order, while manifest slots are sorted.
3218    let mut progressive = ImportResultManifestV1 {
3219        slots: vec![],
3220        ..terminal.clone()
3221    };
3222    let mut order = 0;
3223    let mut observed = 0;
3224    let mut consumed = std::collections::BTreeMap::<(Vec<u8>, Vec<u8>), (u32, u64)>::new();
3225    let mut total_bytes = 0_u64;
3226    for o in &bundle.operations {
3227        let digest = signed_operation_digest(o)?;
3228        let slot = terminal
3229            .slots
3230            .iter()
3231            .find(|s| s.signed_operation_digest == digest)
3232            .ok_or(Reject::Scope)?;
3233        progressive.slots.push(slot.clone());
3234        progressive
3235            .slots
3236            .sort_by(|a, b| (&a.ref_name, a.slot_id).cmp(&(&b.ref_name, b.slot_id)));
3237        let payload = canonical(&publication_payload(o, &progressive)?)?;
3238        let s = bundle
3239            .statements
3240            .iter()
3241            .filter_map(|s| s.body.as_ref())
3242            .find(|s| s.purpose == 3 && s.canonical_payload == payload)
3243            .ok_or(Reject::Transition)?;
3244        if s.admission_order <= order || s.observed_at_unix_millis < observed {
3245            return Err(Reject::Transition);
3246        }
3247        order = s.admission_order;
3248        observed = s.observed_at_unix_millis;
3249        let digest = &o.body.as_ref().ok_or(Reject::Canonical)?.delegation_digest;
3250        let index = verified
3251            .iter()
3252            .position(|d| d.digest == *digest)
3253            .ok_or(Reject::Scope)?;
3254        let result_bytes = o.body.as_ref().ok_or(Reject::Canonical)?.result_bytes;
3255        total_bytes = total_bytes
3256            .checked_add(result_bytes)
3257            .ok_or(Reject::Bounds)?;
3258        let original_scope = initial.body.scope.as_ref().ok_or(Reject::Canonical)?;
3259        if total_bytes > original_scope.max_result_bytes
3260            || progressive.slots.len() > original_scope.max_operations as usize
3261        {
3262            return Err(Reject::Scope);
3263        }
3264        let delegation = &verified[index];
3265        let mut committed_before = progressive.clone();
3266        let operation_digest = signed_operation_digest(o)?;
3267        committed_before
3268            .slots
3269            .retain(|s| s.signed_operation_digest != operation_digest);
3270        check_import_publication_budget(o, delegation, &committed_before)?;
3271        let scope = delegation.body.scope.as_ref().ok_or(Reject::Canonical)?;
3272        let mut budgets = vec![(&delegation.digest, scope)];
3273        if let Some(parent) = &delegation.member {
3274            budgets.push((
3275                &delegation.body.parent_permission_digest,
3276                parent
3277                    .body
3278                    .as_ref()
3279                    .and_then(|p| p.scope.as_ref())
3280                    .ok_or(Reject::Canonical)?,
3281            ));
3282        }
3283        for (digest, scope) in budgets {
3284            let (operations, bytes) = consumed
3285                .entry((digest.clone(), delegation.body.logical_job_id.clone()))
3286                .or_default();
3287            *operations = operations.checked_add(1).ok_or(Reject::Bounds)?;
3288            *bytes = bytes.checked_add(result_bytes).ok_or(Reject::Bounds)?;
3289            if *operations > scope.max_operations || *bytes > scope.max_result_bytes {
3290                return Err(Reject::Scope);
3291            }
3292        }
3293    }
3294    if progressive != *terminal {
3295        return Err(Reject::Scope);
3296    }
3297    let mut history = snapshot.map_or_else(Vec::new, |s| s.accepted_history.clone());
3298    if let Some(old) = history.iter_mut().find(|b| {
3299        b.terminal_manifest
3300            .as_ref()
3301            .is_some_and(|m| m.logical_job_id == terminal.logical_job_id)
3302            && b.delegations
3303                .first()
3304                .and_then(|d| d.body.as_ref())
3305                .and_then(|d| d.identity.as_ref())
3306                .map(|id| &id.spool_uuid)
3307                == bundle
3308                    .delegations
3309                    .first()
3310                    .and_then(|d| d.body.as_ref())
3311                    .and_then(|d| d.identity.as_ref())
3312                    .map(|id| &id.spool_uuid)
3313    }) {
3314        if !bundle.delegations.starts_with(&old.delegations)
3315            || !bundle.operations.starts_with(&old.operations)
3316            || bundle.owner_genesis != old.owner_genesis
3317            || !bundle
3318                .ownership_transfers
3319                .starts_with(&old.ownership_transfers)
3320            || !old
3321                .owner_histories
3322                .iter()
3323                .all(|v| bundle.owner_histories.contains(v))
3324            || bundle.member_permission != old.member_permission
3325            || !old
3326                .genesis_authorities
3327                .iter()
3328                .all(|v| bundle.genesis_authorities.contains(v))
3329            || !old
3330                .original_geneses
3331                .iter()
3332                .all(|v| bundle.original_geneses.contains(v))
3333            || !old
3334                .creator_authority_envelopes
3335                .iter()
3336                .all(|v| bundle.creator_authority_envelopes.contains(v))
3337            || !old.manifests.iter().all(|v| bundle.manifests.contains(v))
3338            || !old.statements.iter().all(|v| bundle.statements.contains(v))
3339            || !old.policies.iter().all(|v| bundle.policies.contains(v))
3340            || !old
3341                .genesis_witnesses
3342                .iter()
3343                .all(|v| bundle.genesis_witnesses.contains(v))
3344            || !old
3345                .authority_witnesses
3346                .iter()
3347                .all(|v| bundle.authority_witnesses.contains(v))
3348            || !old
3349                .landing_witnesses
3350                .iter()
3351                .all(|v| bundle.landing_witnesses.contains(v))
3352            || !old
3353                .foreign_dependencies
3354                .iter()
3355                .all(|v| bundle.foreign_dependencies.contains(v))
3356        {
3357            return Err(Reject::HighWater);
3358        }
3359        *old = bundle.clone();
3360    } else {
3361        history.push(bundle.clone());
3362    }
3363    let witnessed = times[0].is_some();
3364    let witnessed_prefix = usize::from(witnessed);
3365    let mut persisted = snapshot.cloned();
3366    if witnessed_prefix > 0 || new_set {
3367        let mut persisted_associations =
3368            snapshot.map_or_else(Vec::new, |s| s.job_associations.clone());
3369        if witnessed_prefix > 0 {
3370            for d in &bundle.delegations[..witnessed_prefix] {
3371                let b = d.body.as_ref().ok_or(Reject::Canonical)?;
3372                if !persisted_associations
3373                    .iter()
3374                    .any(|(key, _)| *key == b.job_public_key)
3375                {
3376                    persisted_associations
3377                        .push((b.job_public_key.clone(), b.logical_job_id.clone()));
3378                }
3379            }
3380        }
3381        persisted = Some(ImportWitnessSnapshot {
3382            root: pin.clone(),
3383            witness_set: carried.ok_or(Reject::Canonical)?.clone(),
3384            clock_floor_unix_millis: now_ms,
3385            job_associations: persisted_associations,
3386            accepted_history: if witnessed_prefix > 0 {
3387                history
3388            } else {
3389                snapshot.map_or_else(Vec::new, |s| s.accepted_history.clone())
3390            },
3391        });
3392    }
3393    Ok(VerifiedImportBundleWitnesses {
3394        evidence: if witnessed {
3395            ImportBundleEvidence::Witnessed
3396        } else {
3397            ImportBundleEvidence::Recovery
3398        },
3399        snapshot_advanced: persisted.as_ref() != snapshot,
3400        owner_check_time_unix_seconds: times[0].map(|(_, time)| time),
3401        accepted_history: terminal.clone(),
3402        snapshot: persisted,
3403    })
3404}
3405
3406/// Independently authenticated current caller facts for source custody checks.
3407pub struct ImportControlCaller<'a> {
3408    pub authenticated_pop: bool,
3409    pub destination_writer: bool,
3410    pub caller_account: &'a str,
3411    pub connection_owner_account: Option<&'a str>,
3412    pub authorized_source: Option<&'a ImportSourceSelectionV1>,
3413    pub exact_grants_current: bool,
3414    pub selected_commits_available: bool,
3415}
3416#[derive(Clone, Copy)]
3417pub enum ImportControlAction {
3418    Cancel,
3419    Retry,
3420}
3421
3422/// Destination control is independent of source custody. Cancel never fetches.
3423/// Run at Retry admission after checking signed authority.
3424pub fn check_import_control_caller(
3425    action: ImportControlAction,
3426    retained: &ImportSourceSelectionV1,
3427    scope: &ImportPermissionScopeV1,
3428    caller: &ImportControlCaller<'_>,
3429) -> Result<(), Reject> {
3430    if !caller.authenticated_pop || !caller.destination_writer || caller.caller_account.is_empty() {
3431        return Err(Reject::Scope);
3432    }
3433    if matches!(action, ImportControlAction::Cancel) {
3434        return Ok(());
3435    }
3436    validate_retained_import_source(retained, scope)?;
3437    if retained.connection.is_some()
3438        && (caller.connection_owner_account != Some(caller.caller_account)
3439            || caller.authorized_source != Some(retained)
3440            || !caller.exact_grants_current)
3441    {
3442        return Err(Reject::SourceSelection);
3443    }
3444    if !caller.selected_commits_available {
3445        return Err(Reject::SourceSelection);
3446    }
3447    Ok(())
3448}
3449
3450fn validate_retry_availability(
3451    response: &GetImportJobStateResponse,
3452    destination: &SpoolRef,
3453) -> Result<(), Reject> {
3454    use get_import_job_state_response::RetryAvailability;
3455    match response
3456        .retry_availability
3457        .as_ref()
3458        .ok_or(Reject::Canonical)?
3459    {
3460        RetryAvailability::EligibleRetryTarget(target) => {
3461            if response.status != 1 {
3462                return Err(Reject::Canonical);
3463            }
3464            let operation = target.operation_ref.as_ref().ok_or(Reject::Canonical)?;
3465            let raw = hex::decode(operation.id.replace('-', "")).map_err(|_| Reject::Canonical)?;
3466            if initial_operation_id(&raw, false)? != operation.id {
3467                return Err(Reject::Canonical);
3468            }
3469            if operation.spool.as_ref() != Some(destination) {
3470                return Err(Reject::Scope);
3471            }
3472            if target.operation_version.is_empty() || target.operation_version.len() > 256 {
3473                return Err(Reject::Bounds);
3474            }
3475        }
3476        RetryAvailability::RetryUnavailable(reason) => {
3477            if !matches!(
3478                (response.status, *reason),
3479                (1, 1 | 2 | 6) | (2, 3) | (3, 4) | (4, 5) | (5, 7)
3480            ) {
3481                return Err(Reject::Canonical);
3482            }
3483        }
3484    }
3485    Ok(())
3486}
3487
3488/// Validate the minimal writer snapshot and its retry target.
3489pub fn validate_retry_state_response(
3490    request: &GetImportJobStateRequest,
3491    response: &GetImportJobStateResponse,
3492) -> Result<(), Reject> {
3493    validate_job_state_response(request, response)?;
3494    validate_retry_availability(response, request.destination.as_ref().ok_or(Reject::Scope)?)
3495}
3496
3497/// Receiver-owned facts locked together with job/authority/source state. The
3498/// operation-lineage association is durable host state, not an ID inference.
3499pub struct ImportRetryAdmission<'a> {
3500    pub read: &'a GetImportJobStateResponse,
3501    pub original: &'a OperationRecord,
3502    pub retry_lineage_id: &'a [u8],
3503    pub logical_job_terminal: bool,
3504    pub retained_source: &'a ImportSourceSelectionV1,
3505    pub committed_manifest: &'a ImportResultManifestV1,
3506    pub now_unix_seconds: i64,
3507}
3508
3509/// Run after caller-scoped frozen replay lookup, under ONE admission transaction.
3510/// Full owner/policy/revocation/lease checks and allocation remain host gates.
3511pub fn check_retry_admission(
3512    request: &RetryImportSourceRequest,
3513    context: &ImportRetryAdmission<'_>,
3514    active: &VerifiedImportDelegation,
3515    caller: &ImportControlCaller<'_>,
3516) -> Result<(), Reject> {
3517    use get_import_job_state_response::RetryAvailability;
3518    let destination = request
3519        .original_operation
3520        .as_ref()
3521        .and_then(|r| r.spool.clone());
3522    let read_request = GetImportJobStateRequest {
3523        destination,
3524        logical_job_id: request.logical_job_id.clone(),
3525    };
3526    validate_retry_state_response(&read_request, context.read)?;
3527    if request.client_operation_id.is_empty() || request.client_operation_id.len() > 128 {
3528        return Err(Reject::Canonical);
3529    }
3530    if context.logical_job_terminal || context.read.status != 1 {
3531        return Err(Reject::Revoked);
3532    }
3533    let Some(RetryAvailability::EligibleRetryTarget(target)) = &context.read.retry_availability
3534    else {
3535        return Err(Reject::StaleContext);
3536    };
3537    let target_ref = target.operation_ref.as_ref().ok_or(Reject::Canonical)?;
3538    let original_ref = context.original.r#ref.as_ref().ok_or(Reject::Scope)?;
3539    if request.original_operation.as_ref() != Some(original_ref)
3540        || original_ref.spool != target_ref.spool
3541        || original_ref.id != target_ref.id
3542        || context.retry_lineage_id != active.body.retry_lineage_id
3543        || import_job_state_request_from_operation(context.original)?.as_ref()
3544            != Some(&read_request)
3545    {
3546        return Err(Reject::Scope);
3547    }
3548    if request.expected_operation_version != target.operation_version
3549        || context.original.version != target.operation_version
3550        || context.original.superseded_by.is_some()
3551        || !matches!(context.original.state, 4 | 5)
3552    {
3553        return Err(Reject::StaleContext);
3554    }
3555    let state = context.read;
3556    if state.active_delegation_digest != active.digest
3557        || state.active_cancellation_id != active.body.cancellation_id
3558    {
3559        return Err(Reject::StaleContext);
3560    }
3561    check_job_fence(
3562        &request.logical_job_id,
3563        &request.active_delegation_digest,
3564        request.expected_authority_epoch,
3565        active,
3566        state.authority_epoch,
3567    )?;
3568    interval(
3569        active.body.not_before_unix_seconds,
3570        active.body.expires_at_unix_seconds,
3571        context.now_unix_seconds,
3572    )?;
3573    let manifest = context.committed_manifest;
3574    validate_manifest(manifest)?;
3575    if manifest.logical_job_id != active.body.logical_job_id
3576        || manifest.retry_lineage_id != active.body.retry_lineage_id
3577    {
3578        return Err(Reject::Scope);
3579    }
3580    let scope = active.body.scope.as_ref().ok_or(Reject::Canonical)?;
3581    if !scope.branches.iter().any(|b| {
3582        !manifest
3583            .slots
3584            .iter()
3585            .any(|s| s.ref_name == b.ref_name && s.slot_id == b.slot_id)
3586    }) {
3587        return Err(Reject::StaleContext);
3588    }
3589    check_import_control_caller(
3590        ImportControlAction::Retry,
3591        context.retained_source,
3592        scope,
3593        caller,
3594    )
3595}
3596
3597/// Check a host-generated UUID against the COMPLETE durable attempt set, including
3598/// the first lineage UUID. Persist the allocation, both direct links and receipt
3599/// atomically; do not generate a UUID from the request idempotency key.
3600pub fn validate_retry_response(
3601    request: &RetryImportSourceRequest,
3602    response: &MutationResponse,
3603    prior_attempt_ids: &[String],
3604) -> Result<(), Reject> {
3605    let receipt = response.receipt.as_ref().ok_or(Reject::PendingOperation)?;
3606    let Some(mutation_receipt::Outcome::PendingOperation(operation)) = &receipt.outcome else {
3607        return Err(Reject::PendingOperation);
3608    };
3609    let original = request
3610        .original_operation
3611        .as_ref()
3612        .ok_or(Reject::PendingOperation)?;
3613    let raw = hex::decode(operation.id.replace('-', "")).map_err(|_| Reject::PendingOperation)?;
3614    if initial_operation_id(&raw, false).map_or(true, |id| id != operation.id)
3615        || request.client_operation_id.is_empty()
3616        || receipt.client_operation_id != request.client_operation_id
3617        || original.spool.is_none()
3618        || operation.spool != original.spool
3619        || operation.id == original.id
3620        || operation.id == request.client_operation_id
3621        || prior_attempt_ids.contains(&operation.id)
3622    {
3623        return Err(Reject::PendingOperation);
3624    }
3625    Ok(())
3626}
3627
3628/// Exact frozen Retry replay returns the stored receipt without allocating.
3629pub fn check_retry_replay(request_bytes: &[u8], stored_bytes: &[u8]) -> Result<(), Reject> {
3630    if request_bytes.len() > 2 * MAX_BUNDLE_BYTES {
3631        return Err(Reject::Bounds);
3632    }
3633    if request_bytes != stored_bytes {
3634        return Err(Reject::OperationIdReused);
3635    }
3636    Ok(())
3637}
3638
3639/// Under the publication transaction, use the complete cumulative manifest of
3640/// this logical job. All operations consume the same single delegation total.
3641pub fn check_import_publication_budget(
3642    signed: &SignedDelegatedImportOperationV1,
3643    active: &VerifiedImportDelegation,
3644    committed_before: &ImportResultManifestV1,
3645) -> Result<(), Reject> {
3646    verify_operation(signed, active)?;
3647    let scope = active.body.scope.as_ref().ok_or(Reject::Canonical)?;
3648    if committed_before.logical_job_id != active.body.logical_job_id
3649        || committed_before.retry_lineage_id != active.body.retry_lineage_id
3650    {
3651        return Err(Reject::Scope);
3652    }
3653    let remaining = remaining_import_scope(scope, committed_before)?;
3654    if check_slot_replay(committed_before, signed)? {
3655        return Ok(());
3656    }
3657    let o = signed.body.as_ref().ok_or(Reject::Canonical)?;
3658    if remaining.max_operations == 0 || o.result_bytes > remaining.max_result_bytes {
3659        return Err(Reject::Scope);
3660    }
3661    Ok(())
3662}