auths-sdk 0.1.3

Application services layer for Auths identity operations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
//! Signing pipeline orchestration.
//!
//! Composed pipeline: validate freeze → sign data → format SSHSIG.
//! Agent communication and passphrase prompting remain in the CLI.
//!
//! DSSE PAE (Pre-Authentication Encoding) is computed for transparency log
//! submissions where the signing key is available (ephemeral signing).

use crate::context::AuthsContext;
use crate::ports::artifact::{ArtifactDigest, ArtifactMetadata, ArtifactSource};
use auths_core::crypto::signer as core_signer;
use auths_core::crypto::ssh::{self, SecureSeed};
use auths_core::signing::{PassphraseProvider, SecureSigner};
use auths_core::storage::keychain::{IdentityDID, KeyAlias, KeyStorage};
use auths_id::attestation::core::resign_attestation;
use auths_id::attestation::create::create_signed_attestation;
use auths_id::storage::git_refs::AttestationMetadata;
use auths_verifier::core::{ResourceId, SignerType};
use auths_verifier::types::CanonicalDid;
use chrono::{DateTime, Utc};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use zeroize::Zeroizing;

/// Errors from the signing pipeline.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SigningError {
    /// The identity is in a freeze state and signing is not permitted.
    #[error("identity is frozen: {0}")]
    IdentityFrozen(String),
    /// The requested key alias could not be resolved from the keychain.
    #[error("key resolution failed: {0}")]
    KeyResolution(String),
    /// The cryptographic signing operation failed.
    #[error("signing operation failed: {0}")]
    SigningFailed(String),
    /// The supplied passphrase was incorrect.
    #[error("invalid passphrase")]
    InvalidPassphrase,
    /// SSHSIG PEM encoding failed after signing.
    #[error("PEM encoding failed: {0}")]
    PemEncoding(String),
    /// The agent is not available (platform unsupported, not installed, or not reachable).
    #[error("agent unavailable: {0}")]
    AgentUnavailable(String),
    /// The agent accepted the signing request but it failed.
    #[error("agent signing failed")]
    AgentSigningFailed(#[source] crate::ports::agent::AgentSigningError),
    /// All passphrase attempts were exhausted without a successful decryption.
    #[error("passphrase exhausted after {attempts} attempt(s)")]
    PassphraseExhausted {
        /// Number of failed attempts before giving up.
        attempts: usize,
    },
    /// The platform keychain could not be accessed.
    #[error("keychain unavailable: {0}")]
    KeychainUnavailable(String),
    /// The encrypted key material could not be decrypted.
    #[error("key decryption failed: {0}")]
    KeyDecryptionFailed(String),
}

impl auths_core::error::AuthsErrorInfo for SigningError {
    fn error_code(&self) -> &'static str {
        match self {
            Self::IdentityFrozen(_) => "AUTHS-E5901",
            Self::KeyResolution(_) => "AUTHS-E5902",
            Self::SigningFailed(_) => "AUTHS-E5903",
            Self::InvalidPassphrase => "AUTHS-E5904",
            Self::PemEncoding(_) => "AUTHS-E5905",
            Self::AgentUnavailable(_) => "AUTHS-E5906",
            Self::AgentSigningFailed(_) => "AUTHS-E5907",
            Self::PassphraseExhausted { .. } => "AUTHS-E5908",
            Self::KeychainUnavailable(_) => "AUTHS-E5909",
            Self::KeyDecryptionFailed(_) => "AUTHS-E5910",
        }
    }

    fn suggestion(&self) -> Option<&'static str> {
        match self {
            Self::IdentityFrozen(_) => Some("To unfreeze: auths emergency unfreeze"),
            Self::KeyResolution(_) => Some("Run `auths key list` to check available keys"),
            Self::SigningFailed(_) => Some(
                "The signing operation failed; verify your key is accessible with `auths key list`",
            ),
            Self::InvalidPassphrase => Some("Check your passphrase and try again"),
            Self::PemEncoding(_) => {
                Some("Failed to encode the key in PEM format; the key material may be corrupted")
            }
            Self::AgentUnavailable(_) => Some("Start the agent with `auths agent start`"),
            Self::AgentSigningFailed(_) => Some("Check agent logs with `auths agent status`"),
            Self::PassphraseExhausted { .. } => Some(
                "The passphrase you entered is incorrect (tried 3 times). Verify it matches what you set during init, or try: auths key export --key-alias <alias> --format pub",
            ),
            Self::KeychainUnavailable(_) => Some("Run `auths doctor` to diagnose keychain issues"),
            Self::KeyDecryptionFailed(_) => Some("Check your passphrase and try again"),
        }
    }
}

/// Configuration for a signing operation.
///
/// Args:
/// * `namespace`: The SSHSIG namespace (typically "git").
///
/// Usage:
/// ```ignore
/// let config = SigningConfig {
///     namespace: "git".to_string(),
/// };
/// ```
pub struct SigningConfig {
    /// SSHSIG namespace string (e.g. `"git"` for commit signing).
    pub namespace: String,
}

/// Validate that the identity is not frozen.
///
/// Args:
/// * `repo_path`: Path to the auths repository (typically `~/.auths`).
/// * `now`: The reference time used to check if the freeze is active.
///
/// Usage:
/// ```ignore
/// validate_freeze_state(&repo_path, clock.now())?;
/// ```
pub fn validate_freeze_state(
    repo_path: &Path,
    now: chrono::DateTime<chrono::Utc>,
) -> Result<(), SigningError> {
    use auths_id::freeze::load_active_freeze;

    if let Some(state) = load_active_freeze(repo_path, now)
        .map_err(|e| SigningError::IdentityFrozen(e.to_string()))?
    {
        return Err(SigningError::IdentityFrozen(format!(
            "frozen until {}. Remaining: {}. To unfreeze: auths emergency unfreeze",
            state.frozen_until.format("%Y-%m-%d %H:%M UTC"),
            state.expires_description(now),
        )));
    }

    Ok(())
}

/// Construct the SSHSIG signed-data payload for the given data and namespace.
///
/// Args:
/// * `data`: The raw bytes to sign.
/// * `namespace`: The SSHSIG namespace (e.g. "git").
///
/// Usage:
/// ```ignore
/// let payload = construct_signature_payload(b"data", "git")?;
/// ```
pub fn construct_signature_payload(data: &[u8], namespace: &str) -> Result<Vec<u8>, SigningError> {
    ssh::construct_sshsig_signed_data(data, namespace)
        .map_err(|e| SigningError::SigningFailed(e.to_string()))
}

/// Create a complete SSHSIG PEM signature from a seed and data.
///
/// Args:
/// * `seed`: The Ed25519 signing seed.
/// * `data`: The raw bytes to sign.
/// * `namespace`: The SSHSIG namespace.
///
/// Usage:
/// ```ignore
/// let pem = sign_with_seed(&seed, b"data to sign", "git")?;
/// ```
pub fn sign_with_seed(
    seed: &SecureSeed,
    data: &[u8],
    namespace: &str,
    curve: auths_crypto::CurveType,
) -> Result<String, SigningError> {
    ssh::create_sshsig(seed, data, namespace, curve)
        .map_err(|e| SigningError::PemEncoding(e.to_string()))
}

// ---------------------------------------------------------------------------
// Artifact attestation signing
// ---------------------------------------------------------------------------

/// Selects how a signing key is supplied to `sign_artifact`.
///
/// `Alias` resolves the key from the platform keychain at call time.
/// `Direct` injects a raw seed, bypassing the keychain — intended for headless
/// CI/CD runners that have no platform keychain available.
pub enum SigningKeyMaterial {
    /// Resolve by alias from the platform keychain.
    Alias(KeyAlias),
    /// Inject a raw Ed25519 seed directly. The passphrase provider is not called.
    Direct(SecureSeed),
}

/// Parameters for the artifact attestation signing workflow.
///
/// Usage:
/// ```ignore
/// let params = ArtifactSigningParams {
///     artifact: Arc::new(my_artifact),
///     identity_key: Some(SigningKeyMaterial::Alias("my-identity".into())),
///     device_key: SigningKeyMaterial::Direct(my_seed),
///     expires_in: Some(31_536_000),
///     note: None,
///     commit_sha: None,
/// };
/// ```
pub struct ArtifactSigningParams {
    /// The artifact to attest. Provides the canonical digest and metadata.
    pub artifact: Arc<dyn ArtifactSource>,
    /// Identity key source. `None` skips the identity signature.
    pub identity_key: Option<SigningKeyMaterial>,
    /// Device key source. Required to produce a dual-signed attestation.
    pub device_key: SigningKeyMaterial,
    /// Duration in seconds until expiration (per RFC 6749).
    pub expires_in: Option<u64>,
    /// Optional human-readable annotation embedded in the attestation.
    pub note: Option<String>,
    /// Git commit SHA for provenance binding (included in signed canonical data).
    pub commit_sha: Option<String>,
}

/// Result of a successful artifact attestation signing operation.
///
/// Usage:
/// ```ignore
/// let result = sign_artifact(params, &ctx)?;
/// std::fs::write(&output_path, &result.attestation_json)?;
/// println!("Signed {} (sha256:{})", result.rid, result.digest);
/// ```
#[derive(Debug)]
pub struct ArtifactSigningResult {
    /// Canonical JSON of the signed attestation.
    pub attestation_json: String,
    /// Resource identifier assigned to the attestation in the identity store.
    pub rid: ResourceId,
    /// Hex-encoded SHA-256 digest of the attested artifact.
    pub digest: String,
    /// DSSE signature over the PAE of the attestation JSON (for transparency log submission).
    /// Present when the signing function has access to the key (e.g., ephemeral signing).
    pub dsse_signature: Option<Vec<u8>>,
}

/// Errors from the artifact attestation signing workflow.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ArtifactSigningError {
    /// No auths identity was found in the configured identity storage.
    #[error("identity not found in configured identity storage")]
    IdentityNotFound,

    /// The key alias could not be resolved to usable key material.
    #[error("key resolution failed: {0}")]
    KeyResolutionFailed(String),

    /// The encrypted key material could not be decrypted (e.g. wrong passphrase).
    #[error("key decryption failed: {0}")]
    KeyDecryptionFailed(String),

    /// Computing the artifact digest failed.
    #[error("digest computation failed: {0}")]
    DigestFailed(String),

    /// Building or serializing the attestation failed.
    #[error("attestation creation failed: {0}")]
    AttestationFailed(String),

    /// Adding the device signature to a partially-signed attestation failed.
    #[error("attestation re-signing failed: {0}")]
    ResignFailed(String),

    /// The provided commit SHA has an invalid format.
    #[error("invalid commit SHA: {0} (expected 40 or 64 hex characters)")]
    InvalidCommitSha(String),
}

impl auths_core::error::AuthsErrorInfo for ArtifactSigningError {
    fn error_code(&self) -> &'static str {
        match self {
            Self::IdentityNotFound => "AUTHS-E5850",
            Self::KeyResolutionFailed(_) => "AUTHS-E5851",
            Self::KeyDecryptionFailed(_) => "AUTHS-E5852",
            Self::DigestFailed(_) => "AUTHS-E5853",
            Self::AttestationFailed(_) => "AUTHS-E5854",
            Self::ResignFailed(_) => "AUTHS-E5855",
            Self::InvalidCommitSha(_) => "AUTHS-E5856",
        }
    }

    fn suggestion(&self) -> Option<&'static str> {
        match self {
            Self::IdentityNotFound => {
                Some("Run `auths init` to create an identity, or `auths key import` to restore one")
            }
            Self::KeyResolutionFailed(_) => {
                Some("Run `auths status` to see available device aliases")
            }
            Self::KeyDecryptionFailed(_) => Some("Check your passphrase and try again"),
            Self::DigestFailed(_) => Some("Verify the file exists and is readable"),
            Self::AttestationFailed(_) => Some("Check identity storage with `auths status`"),
            Self::ResignFailed(_) => {
                Some("Verify your device key is accessible with `auths status`")
            }
            Self::InvalidCommitSha(_) => {
                Some("Provide a full SHA-1 (40 hex chars) or SHA-256 (64 hex chars) commit hash")
            }
        }
    }
}

/// A `SecureSigner` backed by pre-resolved in-memory seeds.
///
/// Seeds are keyed by alias and carry their curve so sign dispatches correctly
/// for Ed25519 + P-256 identities. The passphrase provider is never called
/// because all key material was resolved before construction.
struct SeedMapSigner {
    seeds: HashMap<String, (SecureSeed, auths_crypto::CurveType)>,
}

impl SecureSigner for SeedMapSigner {
    fn sign_with_alias(
        &self,
        alias: &auths_core::storage::keychain::KeyAlias,
        _passphrase_provider: &dyn PassphraseProvider,
        message: &[u8],
    ) -> Result<Vec<u8>, auths_core::AgentError> {
        let (seed, curve) = self
            .seeds
            .get(alias.as_str())
            .ok_or(auths_core::AgentError::KeyNotFound)?;
        let typed = match curve {
            auths_crypto::CurveType::Ed25519 => auths_crypto::TypedSeed::Ed25519(*seed.as_bytes()),
            auths_crypto::CurveType::P256 => auths_crypto::TypedSeed::P256(*seed.as_bytes()),
        };
        auths_crypto::typed_sign(&typed, message)
            .map_err(|e| auths_core::AgentError::CryptoError(e.to_string()))
    }

    fn sign_for_identity(
        &self,
        _identity_did: &IdentityDID,
        _passphrase_provider: &dyn PassphraseProvider,
        _message: &[u8],
    ) -> Result<Vec<u8>, auths_core::AgentError> {
        Err(auths_core::AgentError::KeyNotFound)
    }
}

struct ResolvedKey {
    alias: KeyAlias,
    /// None for hardware backends (SE) — signing goes through the keychain directly.
    seed: Option<SecureSeed>,
    public_key_bytes: Vec<u8>,
    curve: auths_crypto::CurveType,
    /// True if this key is backed by hardware (Secure Enclave, HSM).
    is_hardware: bool,
}

fn resolve_optional_key(
    material: Option<&SigningKeyMaterial>,
    synthetic_alias: &'static str,
    keychain: &(dyn KeyStorage + Send + Sync),
    passphrase_provider: &dyn PassphraseProvider,
    passphrase_prompt: &str,
) -> Result<Option<ResolvedKey>, ArtifactSigningError> {
    match material {
        None => Ok(None),
        Some(SigningKeyMaterial::Alias(alias)) => {
            // Hardware backends (Secure Enclave): resolve pubkey only; signing happens
            // later via StorageSigner so private key material never leaves the enclave.
            // MIRROR: keep in sync with workflows/signing.rs (SE branch)
            if keychain.is_hardware_backend() {
                let (pubkey, curve) = auths_core::storage::keychain::extract_public_key_bytes(
                    keychain,
                    alias,
                    passphrase_provider,
                )
                .map_err(|e| ArtifactSigningError::KeyResolutionFailed(e.to_string()))?;
                return Ok(Some(ResolvedKey {
                    alias: alias.clone(),
                    seed: None,
                    public_key_bytes: pubkey,
                    curve,
                    is_hardware: true,
                }));
            }

            let (_, _role, encrypted) = keychain
                .load_key(alias)
                .map_err(|e| ArtifactSigningError::KeyResolutionFailed(e.to_string()))?;
            let passphrase = passphrase_provider
                .get_passphrase(passphrase_prompt)
                .map_err(|e| ArtifactSigningError::KeyDecryptionFailed(e.to_string()))?;
            // Defense-in-depth: SE keys must never reach the software decrypt path.
            debug_assert!(
                !keychain.is_hardware_backend(),
                "SE keys must never reach decrypt_keypair"
            );
            let pkcs8 = core_signer::decrypt_keypair(&encrypted, &passphrase)
                .map_err(|e| ArtifactSigningError::KeyDecryptionFailed(e.to_string()))?;
            let (seed, pubkey, curve) = core_signer::load_seed_and_pubkey(&pkcs8)
                .map_err(|e| ArtifactSigningError::KeyDecryptionFailed(e.to_string()))?;
            Ok(Some(ResolvedKey {
                alias: alias.clone(),
                seed: Some(seed),
                public_key_bytes: pubkey.to_vec(),
                curve,
                is_hardware: false,
            }))
        }
        Some(SigningKeyMaterial::Direct(seed)) => {
            let typed = auths_crypto::TypedSeed::Ed25519(*seed.as_bytes());
            let pubkey = auths_crypto::typed_public_key(&typed)
                .map_err(|e| ArtifactSigningError::KeyDecryptionFailed(e.to_string()))?;
            Ok(Some(ResolvedKey {
                alias: KeyAlias::new_unchecked(synthetic_alias),
                seed: Some(SecureSeed::new(*seed.as_bytes())),
                public_key_bytes: pubkey,
                curve: auths_crypto::CurveType::Ed25519,
                is_hardware: false,
            }))
        }
    }
}

fn resolve_required_key(
    material: &SigningKeyMaterial,
    synthetic_alias: &'static str,
    keychain: &(dyn KeyStorage + Send + Sync),
    passphrase_provider: &dyn PassphraseProvider,
    passphrase_prompt: &str,
) -> Result<ResolvedKey, ArtifactSigningError> {
    resolve_optional_key(
        Some(material),
        synthetic_alias,
        keychain,
        passphrase_provider,
        passphrase_prompt,
    )
    .map(|opt| {
        opt.ok_or(ArtifactSigningError::KeyDecryptionFailed(
            "expected key material but got None".into(),
        ))
    })?
}

/// Validate and normalize a commit SHA (40-char SHA-1 or 64-char SHA-256).
///
/// Args:
/// * `sha`: The raw commit SHA string to validate.
///
/// Usage:
/// ```ignore
/// let normalized = validate_commit_sha("AbCd1234...")?;
/// ```
pub fn validate_commit_sha(sha: &str) -> Result<String, ArtifactSigningError> {
    let normalized = sha.to_ascii_lowercase();
    let len = normalized.len();
    if (len != 40 && len != 64) || !normalized.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Err(ArtifactSigningError::InvalidCommitSha(sha.to_string()));
    }
    Ok(normalized)
}

/// Full artifact attestation signing pipeline.
///
/// Loads the identity, resolves key material (supporting both keychain aliases
/// and direct in-memory seed injection), computes the artifact digest, and
/// produces a dual-signed attestation JSON.
///
/// Args:
/// * `params`: All inputs required for signing, including key material and artifact source.
/// * `ctx`: Runtime context providing identity storage, key storage, passphrase provider, and clock.
///
/// Usage:
/// ```ignore
/// let params = ArtifactSigningParams {
///     artifact: Arc::new(FileArtifact::new(Path::new("release.tar.gz"))),
///     identity_key: Some(SigningKeyMaterial::Alias("my-key".into())),
///     device_key: SigningKeyMaterial::Direct(seed),
///     expires_in: Some(31_536_000),
///     note: None,
///     commit_sha: None,
/// };
/// let result = sign_artifact(params, &ctx)?;
/// ```
pub fn sign_artifact(
    params: ArtifactSigningParams,
    ctx: &AuthsContext,
) -> Result<ArtifactSigningResult, ArtifactSigningError> {
    let managed = ctx
        .identity_storage
        .load_identity()
        .map_err(|_| ArtifactSigningError::IdentityNotFound)?;

    let keychain = ctx.key_storage.as_ref();
    let passphrase_provider = ctx.passphrase_provider.as_ref();

    let identity_resolved = resolve_optional_key(
        params.identity_key.as_ref(),
        "__artifact_identity__",
        keychain,
        passphrase_provider,
        "Enter passphrase for identity key:",
    )?;

    let device_resolved = resolve_required_key(
        &params.device_key,
        "__artifact_device__",
        keychain,
        passphrase_provider,
        "Enter passphrase for device key:",
    )?;

    let mut seeds: HashMap<String, (SecureSeed, auths_crypto::CurveType)> = HashMap::new();
    let identity_alias: Option<KeyAlias> = identity_resolved.map(|r| {
        let alias = r.alias.clone();
        let curve = r.curve;
        if let Some(seed) = r.seed {
            seeds.insert(r.alias.into_inner(), (seed, curve));
        }
        alias
    });
    let device_alias = device_resolved.alias.clone();
    let device_is_hardware = device_resolved.is_hardware;
    let device_curve = device_resolved.curve;
    if let Some(seed) = device_resolved.seed {
        seeds.insert(device_resolved.alias.into_inner(), (seed, device_curve));
    }
    let device_pk_bytes = device_resolved.public_key_bytes;

    let device_did = CanonicalDid::from_public_key_did_key(&device_pk_bytes, device_resolved.curve);

    let artifact_meta = params
        .artifact
        .metadata()
        .map_err(|e| ArtifactSigningError::DigestFailed(e.to_string()))?;

    let rid = ResourceId::new(format!("sha256:{}", artifact_meta.digest.hex));
    let now = ctx.clock.now();
    let meta = AttestationMetadata {
        timestamp: Some(now),
        expires_at: params
            .expires_in
            .map(|s| now + chrono::Duration::seconds(s as i64)),
        note: params.note,
    };

    let payload = serde_json::to_value(&artifact_meta)
        .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;

    let validated_commit_sha = params
        .commit_sha
        .map(|sha| validate_commit_sha(&sha))
        .transpose()?;

    let attestation_json = create_and_sign_attestation(
        ctx,
        seeds,
        device_is_hardware,
        now,
        &rid,
        &managed.controller_did,
        &device_did,
        &device_pk_bytes,
        device_curve,
        payload,
        &meta,
        identity_alias.as_ref(),
        &device_alias,
        validated_commit_sha,
    )?;

    if let Some(ref alias) = identity_alias {
        anchor_artifact_attestation(ctx, &managed.controller_did, alias, &attestation_json, now)?;
    }

    Ok(ArtifactSigningResult {
        attestation_json,
        rid,
        digest: artifact_meta.digest.hex,
        dsse_signature: None,
    })
}

fn anchor_artifact_attestation(
    ctx: &AuthsContext,
    controller_did: &auths_core::storage::keychain::IdentityDID,
    alias: &KeyAlias,
    attestation_json: &str,
    now: DateTime<Utc>,
) -> Result<(), ArtifactSigningError> {
    let prefix = auths_id::keri::parse_did_keri(controller_did.as_str())
        .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;
    let att: auths_verifier::core::Attestation = serde_json::from_str(attestation_json)
        .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;
    let storage_signer = auths_core::signing::StorageSigner::new(Arc::clone(&ctx.key_storage));
    let mut batch = auths_id::storage::registry::backend::AtomicWriteBatch::new();
    batch.stage_attestation(att.clone());
    auths_id::keri::anchor_and_persist_via_backend(
        ctx.registry.as_ref(),
        &storage_signer,
        alias,
        ctx.passphrase_provider.as_ref(),
        &prefix,
        &att,
        &mut batch,
        &ctx.witness_params(),
        now,
    )
    .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;
    Ok(())
}

/// Create, sign, and serialize an attestation. Handles both hardware and software signers.
#[allow(clippy::too_many_arguments)]
fn create_and_sign_attestation(
    ctx: &AuthsContext,
    seeds: HashMap<String, (SecureSeed, auths_crypto::CurveType)>,
    device_is_hardware: bool,
    now: DateTime<Utc>,
    rid: &ResourceId,
    controller_did: &IdentityDID,
    subject: &CanonicalDid,
    device_pk_bytes: &[u8],
    device_curve: auths_crypto::CurveType,
    payload: serde_json::Value,
    meta: &AttestationMetadata,
    identity_alias: Option<&KeyAlias>,
    device_alias: &KeyAlias,
    commit_sha: Option<String>,
) -> Result<String, ArtifactSigningError> {
    let seed_signer = SeedMapSigner { seeds };
    let storage_signer = auths_core::signing::StorageSigner::new(Arc::clone(&ctx.key_storage));
    let signer: &dyn SecureSigner = if device_is_hardware {
        &storage_signer
    } else {
        &seed_signer
    };
    let noop_provider = auths_core::PrefilledPassphraseProvider::new("");

    let mut attestation = create_signed_attestation(
        now,
        auths_id::attestation::create::AttestationInput {
            rid: rid.as_str(),
            identity_did: controller_did,
            subject,
            device_public_key: device_pk_bytes,
            device_curve,
            payload: Some(payload),
            meta,
            identity_alias,
            device_alias: Some(device_alias),
            delegated_by: None,
            commit_sha,
            signer_type: None,
        },
        signer,
        &noop_provider,
    )
    .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;

    resign_attestation(
        &mut attestation,
        signer,
        &noop_provider,
        identity_alias,
        device_alias,
    )
    .map_err(|e| ArtifactSigningError::ResignFailed(e.to_string()))?;

    serde_json::to_string_pretty(&attestation)
        .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))
}

/// Signs artifact bytes with a one-time ephemeral Ed25519 key. No keychain, no
/// identity storage, no passphrase — the key is generated, used, and zeroized
/// within this function call.
///
/// The ephemeral key signs "this artifact was built from this commit." Trust
/// derives transitively: consumers verify the commit is signed by a maintainer,
/// then verify this attestation's ephemeral signature covers the artifact hash
/// and commit SHA.
///
/// Args:
/// * `now` - Current UTC time (injected per clock pattern).
/// * `data` - Raw artifact bytes to sign.
/// * `artifact_name` - Optional human-readable name for the artifact.
/// * `commit_sha` - Git commit SHA this artifact was built from (required, 40 or 64 hex chars).
/// * `expires_in` - Optional TTL in seconds.
/// * `note` - Optional attestation note.
/// * `ci_env` - Optional CI environment metadata (serialized into payload, covered by signature).
///
/// Usage:
/// ```ignore
/// let result = sign_artifact_ephemeral(
///     Utc::now(), b"artifact bytes", Some("release.tar.gz".into()),
///     "abc123def456abc123def456abc123def456abc1".into(), None, None, None,
/// )?;
/// ```
pub fn sign_artifact_ephemeral(
    now: DateTime<Utc>,
    data: &[u8],
    artifact_name: Option<String>,
    commit_sha: String,
    expires_in: Option<u64>,
    note: Option<String>,
    ci_env: Option<serde_json::Value>,
) -> Result<ArtifactSigningResult, ArtifactSigningError> {
    // 1. Generate ephemeral P-256 seed and zeroize on drop
    let mut seed_bytes = Zeroizing::new([0u8; 32]);
    ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), seed_bytes.as_mut())
        .map_err(|_| ArtifactSigningError::AttestationFailed("RNG failure".into()))?;

    // 2. Derive pubkey and DIDs using P-256 (default curve)
    let typed_seed = auths_crypto::TypedSeed::P256(*seed_bytes);
    let pubkey_vec = auths_crypto::typed_public_key(&typed_seed)
        .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;

    let device_did =
        CanonicalDid::from_public_key_did_key(&pubkey_vec, auths_crypto::CurveType::P256);
    #[allow(clippy::disallowed_methods)]
    let identity_did = IdentityDID::new_unchecked(device_did.as_str());

    // 3. Build artifact metadata with optional CI environment in payload
    let digest_hex = hex::encode(Sha256::digest(data));
    let artifact_meta = ArtifactMetadata {
        artifact_type: "file".to_string(),
        digest: ArtifactDigest {
            algorithm: "sha256".to_string(),
            hex: digest_hex,
        },
        name: artifact_name,
        size: Some(data.len() as u64),
    };

    let mut payload_value = serde_json::to_value(&artifact_meta)
        .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;

    if let Some(env) = ci_env
        && let serde_json::Value::Object(ref mut map) = payload_value
    {
        map.insert("ci_environment".to_string(), env);
    }

    let rid = ResourceId::new(format!("sha256:{}", artifact_meta.digest.hex));
    let meta = AttestationMetadata {
        timestamp: Some(now),
        expires_at: expires_in.map(|s| now + chrono::Duration::seconds(s as i64)),
        note,
    };

    // 4. Validate commit SHA
    let validated_sha = validate_commit_sha(&commit_sha)?;

    // 5. Set up ephemeral signer
    let identity_alias = KeyAlias::new_unchecked("__ephemeral_identity__");
    let device_alias = KeyAlias::new_unchecked("__ephemeral_device__");

    let mut seeds: HashMap<String, (SecureSeed, auths_crypto::CurveType)> = HashMap::new();
    seeds.insert(
        identity_alias.as_str().to_string(),
        (SecureSeed::new(*seed_bytes), auths_crypto::CurveType::P256),
    );
    seeds.insert(
        device_alias.as_str().to_string(),
        (SecureSeed::new(*seed_bytes), auths_crypto::CurveType::P256),
    );
    let signer = SeedMapSigner { seeds };
    let noop_provider = auths_core::PrefilledPassphraseProvider::new("");

    // 6. Create signed attestation with Workload signer type
    let attestation = create_signed_attestation(
        now,
        auths_id::attestation::create::AttestationInput {
            rid: rid.as_str(),
            identity_did: &identity_did,
            subject: &device_did,
            device_public_key: &pubkey_vec,
            device_curve: auths_crypto::CurveType::P256,
            payload: Some(payload_value),
            meta: &meta,
            identity_alias: Some(&identity_alias),
            device_alias: Some(&device_alias),
            delegated_by: None,
            commit_sha: Some(validated_sha),
            signer_type: Some(SignerType::Workload),
        },
        &signer,
        &noop_provider,
    )
    .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;

    let attestation_json = serde_json::to_string_pretty(&attestation)
        .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;

    // Compute DSSE signature for transparency log submission (key still in scope)
    let pae = dsse_pae("application/vnd.auths+json", attestation_json.as_bytes());
    let dsse_sig = auths_crypto::typed_sign(&typed_seed, &pae)
        .map_err(|e| ArtifactSigningError::AttestationFailed(format!("DSSE sign: {e}")))?;

    Ok(ArtifactSigningResult {
        attestation_json,
        rid,
        digest: artifact_meta.digest.hex,
        dsse_signature: Some(dsse_sig),
    })
}

/// Signs artifact bytes with a raw Ed25519 seed, bypassing keychain and identity storage.
///
/// This is the raw-key equivalent of [`sign_artifact`]. It does not require an
/// [`AuthsContext`] or any filesystem/keychain access. The same seed is used for
/// both identity and device signing roles.
///
/// Args:
/// * `now` - Current UTC time (injected per clock pattern).
/// * `seed` - Ed25519 32-byte seed.
/// * `identity_did` - Parsed identity DID (must be `did:keri:` — caller validates via `IdentityDID::parse()`).
/// * `data` - Raw artifact bytes to sign.
/// * `expires_in` - Optional TTL in seconds.
/// * `note` - Optional attestation note.
/// * `commit_sha` - Optional git commit SHA for provenance binding (40 or 64 hex chars).
///
/// Usage:
/// ```ignore
/// let did = IdentityDID::parse("did:keri:E...")?;
/// let result = sign_artifact_raw(Utc::now(), &seed, &did, b"payload", None, None, None)?;
/// ```
pub fn sign_artifact_raw(
    now: DateTime<Utc>,
    seed: &SecureSeed,
    identity_did: &IdentityDID,
    data: &[u8],
    expires_in: Option<u64>,
    note: Option<String>,
    commit_sha: Option<String>,
) -> Result<ArtifactSigningResult, ArtifactSigningError> {
    // Default to P-256 per workspace convention. The raw seed is 32 bytes for both curves.
    let curve = auths_crypto::CurveType::default();
    let typed = match curve {
        auths_crypto::CurveType::Ed25519 => auths_crypto::TypedSeed::Ed25519(*seed.as_bytes()),
        auths_crypto::CurveType::P256 => auths_crypto::TypedSeed::P256(*seed.as_bytes()),
    };
    let pubkey = auths_crypto::typed_public_key(&typed)
        .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;

    let device_did = CanonicalDid::from_public_key_did_key(&pubkey, curve);

    let digest_hex = hex::encode(Sha256::digest(data));
    let artifact_meta = ArtifactMetadata {
        artifact_type: "bytes".to_string(),
        digest: ArtifactDigest {
            algorithm: "sha256".to_string(),
            hex: digest_hex,
        },
        name: None,
        size: Some(data.len() as u64),
    };

    let rid = ResourceId::new(format!("sha256:{}", artifact_meta.digest.hex));
    let meta = AttestationMetadata {
        timestamp: Some(now),
        expires_at: expires_in.map(|s| now + chrono::Duration::seconds(s as i64)),
        note,
    };

    let payload = serde_json::to_value(&artifact_meta)
        .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;

    let identity_alias = KeyAlias::new_unchecked("__raw_identity__");
    let device_alias = KeyAlias::new_unchecked("__raw_device__");

    let mut seeds: HashMap<String, (SecureSeed, auths_crypto::CurveType)> = HashMap::new();
    seeds.insert(
        identity_alias.as_str().to_string(),
        (SecureSeed::new(*seed.as_bytes()), curve),
    );
    seeds.insert(
        device_alias.as_str().to_string(),
        (SecureSeed::new(*seed.as_bytes()), curve),
    );
    let signer = SeedMapSigner { seeds };
    // Seeds are already resolved — passphrase provider will not be called.
    let noop_provider = auths_core::PrefilledPassphraseProvider::new("");

    let validated_commit_sha = commit_sha
        .map(|sha| validate_commit_sha(&sha))
        .transpose()?;

    let attestation = create_signed_attestation(
        now,
        auths_id::attestation::create::AttestationInput {
            rid: rid.as_str(),
            identity_did,
            subject: &device_did,
            device_public_key: &pubkey,
            device_curve: curve,
            payload: Some(payload),
            meta: &meta,
            identity_alias: Some(&identity_alias),
            device_alias: Some(&device_alias),
            delegated_by: None,
            commit_sha: validated_commit_sha,
            signer_type: None,
        },
        &signer,
        &noop_provider,
    )
    .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;

    let attestation_json = serde_json::to_string_pretty(&attestation)
        .map_err(|e| ArtifactSigningError::AttestationFailed(e.to_string()))?;

    Ok(ArtifactSigningResult {
        attestation_json,
        rid,
        digest: artifact_meta.digest.hex,
        dsse_signature: None,
    })
}

/// Compute the DSSE Pre-Authentication Encoding (PAE).
///
/// Format per the DSSE spec:
/// `"DSSEv1" SP len(payloadType) SP payloadType SP len(payload) SP payload`
pub fn dsse_pae(payload_type: &str, payload: &[u8]) -> Vec<u8> {
    let header = format!(
        "DSSEv1 {} {} {} ",
        payload_type.len(),
        payload_type,
        payload.len()
    );
    let mut result = Vec::with_capacity(header.len() + payload.len());
    result.extend_from_slice(header.as_bytes());
    result.extend_from_slice(payload);
    result
}