envy-secrets 0.5.1

A secure, deterministic, and frictionless environment variable manager
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
//! GitOps sync artifact orchestration — seal, unseal, read, and write `envy.enc`.
//!
//! This module orchestrates the full artifact lifecycle: reading secrets from the
//! vault, sealing them into an `envy.enc` artifact via the crypto layer, and
//! unsealing an artifact back into a decrypted map for the CLI layer to write.
//!
//! # Layer rules (Constitution Principle IV)
//! - MAY import from `crate::crypto` and `crate::db` only.
//! - MUST NOT import from `crate::cli`.

use std::collections::BTreeMap;
use std::path::Path;

use zeroize::Zeroizing;

use crate::crypto::artifact::{
    ARTIFACT_VERSION, ArtifactError, ArtifactPayload, EncryptedEnvelope, SyncArtifact,
    seal_envelope, unseal_envelope,
};
use crate::db::{ProjectId, Vault};

// ---------------------------------------------------------------------------
// T025 — SyncError
// ---------------------------------------------------------------------------

/// Errors at the sync artifact orchestration layer.
#[derive(Debug, thiserror::Error)]
pub enum SyncError {
    /// A low-level artifact cryptography error.
    #[error(transparent)]
    Artifact(#[from] ArtifactError),

    /// `envy.enc` does not exist at the expected path.
    #[error("envy.enc not found at {0}")]
    FileNotFound(String),

    /// A file read or write operation failed.
    #[error("failed to read/write envy.enc: {0}")]
    Io(String),

    /// The artifact uses an unsupported schema version.
    #[error("envy.enc has unsupported schema version {0}")]
    UnsupportedVersion(u32),

    /// All environments were skipped; no secrets were imported.
    ///
    /// Not returned by `unseal_artifact` itself — reserved for the CLI layer to
    /// surface when `UnsealResult.imported` is empty.
    #[error("no environments could be decrypted \u{2014} check your passphrase")]
    NothingImported,

    /// A vault read failed while sealing.
    #[error("vault error: {0}")]
    VaultError(String),
}

// ---------------------------------------------------------------------------
// T026 — UnsealResult
// ---------------------------------------------------------------------------

/// The output of a successful [`unseal_artifact`] call.
///
/// Contains all environments that were successfully decrypted, plus a list of
/// environments that could not be decrypted (wrong passphrase or malformed
/// envelope). Callers MUST surface `skipped` as an informational warning.
///
/// # Memory safety
/// All values in `imported` are [`Zeroizing<String>`] — backing memory is
/// zeroed when the `UnsealResult` is dropped (Constitution Principle I).
pub struct UnsealResult {
    /// Successfully decrypted environments: env name → (secret key → plaintext value).
    pub imported: BTreeMap<String, BTreeMap<String, Zeroizing<String>>>,
    /// Environments that could not be decrypted (added to skipped, never hard-errors).
    pub skipped: Vec<String>,
}

// ---------------------------------------------------------------------------
// T027 — seal_artifact
// ---------------------------------------------------------------------------

/// Reads all secrets for `envs` from the vault and seals them into a [`SyncArtifact`].
///
/// Each environment is sealed independently with `passphrase`. Pass
/// `envs: None` to include every environment that exists in the vault; pass
/// `envs: Some(&["development", "staging"])` to seal only those names.
///
/// # Errors
/// - [`SyncError::Artifact(ArtifactError::WeakPassphrase)`] if `passphrase` is empty.
/// - [`SyncError::VaultError`] if reading secrets from the vault fails.
pub fn seal_artifact(
    vault: &Vault,
    master_key: &[u8; 32],
    project_id: &ProjectId,
    passphrase: &str,
    envs: Option<&[&str]>,
) -> Result<SyncArtifact, SyncError> {
    // Validate passphrase early — before any vault I/O.
    if passphrase.trim().is_empty() {
        return Err(SyncError::Artifact(ArtifactError::WeakPassphrase));
    }

    // Determine which environment names to seal.
    let env_names: Vec<String> = match envs {
        Some(list) => list.iter().map(|s| s.to_lowercase()).collect(),
        None => vault
            .list_environments(project_id)
            .map_err(|e| SyncError::VaultError(e.to_string()))?
            .into_iter()
            .map(|e| e.name)
            .collect(),
    };

    let mut environments = BTreeMap::new();

    for env_name in &env_names {
        // Fetch all secrets for this environment (returns empty map if env doesn't exist yet).
        let secrets_map = crate::core::get_env_secrets(vault, master_key, project_id, env_name)
            .map_err(|e| SyncError::VaultError(e.to_string()))?;

        // get_env_secrets returns HashMap; ArtifactPayload requires BTreeMap for stable ordering.
        let secrets: BTreeMap<String, Zeroizing<String>> = secrets_map.into_iter().collect();
        let payload = ArtifactPayload { secrets };
        let envelope = seal_envelope(passphrase, &payload)?;
        environments.insert(env_name.clone(), envelope);
    }

    Ok(SyncArtifact {
        version: ARTIFACT_VERSION,
        environments,
    })
}

// ---------------------------------------------------------------------------
// T028 — unseal_artifact
// ---------------------------------------------------------------------------

/// Decrypts all accessible environments in `artifact` using `passphrase`.
///
/// Iterates every environment independently. Authentication failures (wrong
/// passphrase OR tampered ciphertext) add the environment to `skipped` —
/// the overall operation is never aborted. This is the Progressive Disclosure
/// contract: callers with a partial key import what they can access.
///
/// # Errors
/// - [`SyncError::Artifact(ArtifactError::WeakPassphrase)`] if `passphrase` is empty.
/// - [`SyncError::UnsupportedVersion`] if `artifact.version != ARTIFACT_VERSION`.
pub fn unseal_artifact(
    artifact: &SyncArtifact,
    passphrase: &str,
) -> Result<UnsealResult, SyncError> {
    if passphrase.trim().is_empty() {
        return Err(SyncError::Artifact(ArtifactError::WeakPassphrase));
    }
    if artifact.version != ARTIFACT_VERSION {
        return Err(SyncError::UnsupportedVersion(artifact.version));
    }

    let mut imported: BTreeMap<String, BTreeMap<String, Zeroizing<String>>> = BTreeMap::new();
    let mut skipped: Vec<String> = Vec::new();

    for (env_name, envelope) in &artifact.environments {
        match unseal_envelope(passphrase, env_name, envelope) {
            Ok(payload) => {
                imported.insert(env_name.clone(), payload.secrets);
            }
            Err(_) => {
                // Progressive Disclosure: ALL errors → graceful skip, never abort.
                skipped.push(env_name.clone());
            }
        }
    }

    Ok(UnsealResult { imported, skipped })
}

// ---------------------------------------------------------------------------
// T029 — write_artifact / write_artifact_atomic
// ---------------------------------------------------------------------------

/// Serializes `artifact` to pretty-printed JSON and writes it atomically.
///
/// Delegates to [`write_artifact_atomic`]. The `path` file is only replaced
/// after a successful write to the sibling `.tmp` file, guaranteeing that a
/// crash mid-write leaves the previous file intact (FR-006, SC-003).
///
/// # Errors
/// - [`SyncError::Io`] on serialization, write, or rename failure.
pub fn write_artifact(artifact: &SyncArtifact, path: &Path) -> Result<(), SyncError> {
    write_artifact_atomic(artifact, path)
}

/// Serializes `artifact` to pretty-printed JSON and writes it atomically.
///
/// Writes JSON to `envy.enc.tmp` (a sibling file in the same directory as
/// `path`), then calls `std::fs::rename` to replace `path`. Both files are on
/// the same filesystem by construction (same directory), so the rename is
/// atomic on POSIX and on Windows Vista+.
///
/// # Errors
/// - [`SyncError::Io`] on serialization, write, or rename failure.
pub fn write_artifact_atomic(artifact: &SyncArtifact, path: &Path) -> Result<(), SyncError> {
    let tmp = path
        .parent()
        .unwrap_or_else(|| Path::new("."))
        .join("envy.enc.tmp");
    let json = serde_json::to_string_pretty(artifact).map_err(|e| SyncError::Io(e.to_string()))?;
    std::fs::write(&tmp, json.as_bytes()).map_err(|e| SyncError::Io(e.to_string()))?;
    std::fs::rename(&tmp, path).map_err(|e| SyncError::Io(format!("atomic rename failed: {e}")))?;
    Ok(())
}

// ---------------------------------------------------------------------------
// seal_env — seal a single environment (T006)
// ---------------------------------------------------------------------------

/// Reads all secrets for `env_name` from the vault and seals them into one
/// [`EncryptedEnvelope`] using `passphrase`. Sync markers are committed
/// separately by [`mark_env_sealed`] after the artifact is persisted.
///
/// Used by `cmd_encrypt` to build the per-environment merge map, each env
/// potentially with its own passphrase (FR-001, FR-002).
///
/// # Errors
/// - [`SyncError::Artifact(ArtifactError::WeakPassphrase)`] if `passphrase` is empty.
/// - [`SyncError::VaultError`] if reading secrets from the vault fails.
pub fn seal_env(
    vault: &Vault,
    master_key: &[u8; 32],
    project_id: &ProjectId,
    env_name: &str,
    passphrase: &str,
) -> Result<EncryptedEnvelope, SyncError> {
    let envelope = seal_env_unmarked(vault, master_key, project_id, env_name, passphrase)?;

    mark_env_sealed(vault, project_id, env_name)?;
    Ok(envelope)
}

/// Seals one environment without changing its sync marker.
pub fn seal_env_unmarked(
    vault: &Vault,
    master_key: &[u8; 32],
    project_id: &ProjectId,
    env_name: &str,
    passphrase: &str,
) -> Result<EncryptedEnvelope, SyncError> {
    if passphrase.trim().is_empty() {
        return Err(SyncError::Artifact(ArtifactError::WeakPassphrase));
    }
    let secrets_map = crate::core::get_env_secrets(vault, master_key, project_id, env_name)
        .map_err(|e| SyncError::VaultError(e.to_string()))?;
    let secrets: BTreeMap<String, Zeroizing<String>> = secrets_map.into_iter().collect();
    let payload = ArtifactPayload { secrets };
    Ok(seal_envelope(passphrase, &payload)?)
}

/// Commits the sync marker after its artifact has been persisted successfully.
pub fn mark_env_sealed(
    vault: &Vault,
    project_id: &ProjectId,
    env_name: &str,
) -> Result<(), SyncError> {
    // Update the sync marker so `envy status` reports InSync immediately after
    // a successful encrypt (spec FR-008; Constitution Principle: marker is only
    // written if the seal itself succeeds).
    // Environment rows are stored lowercase (core::normalize_env) — normalize
    // here too, or a mixed-case caller fails with "record not found" after the
    // seal itself already succeeded.
    let name = super::ops::normalize_env(env_name);
    let env = vault
        .get_environment_by_name(project_id, &name)
        .map_err(|e| SyncError::VaultError(e.to_string()))?;

    // SAFETY: `duration_since(UNIX_EPOCH)` can only fail if the system clock is
    // set before 1970-01-01 — a hardware/OS misconfiguration we cannot recover from.
    // Defaulting to 0 avoids a panic while still recording a marker row.
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs() as i64;

    vault
        .upsert_sync_marker(&env.id, now)
        .map_err(|e| SyncError::VaultError(e.to_string()))?;

    Ok(())
}

// ---------------------------------------------------------------------------
// rotate_env — re-seal an existing envelope with a new passphrase (T002)
// ---------------------------------------------------------------------------

/// Re-seals the `env_name` envelope in `artifact` with `new_passphrase`,
/// after verifying that `current_passphrase` matches the existing envelope.
///
/// This is the core-level helper backing the `envy rotate` CLI subcommand
/// (specs/012-cli-rotate). It enforces the safety guarantee that a typo
/// in the current passphrase can never produce a silent key rotation:
/// the function returns `Err` before mutating `artifact` whenever
/// `current_passphrase` does not match the existing envelope.
///
/// # Algorithm
/// 1. Validate `new_passphrase` is non-empty and non-whitespace.
/// 2. Look up `artifact.environments[env_name]`. If missing, return an
///    error so the caller can map it to `EnvNotFound` (exit 3).
/// 3. Verify `current_passphrase` against the existing envelope via
///    [`check_envelope_passphrase`]. If it returns `false`, return
///    `DecryptionFailed` so the caller can map it to `PassphraseInput`
///    (exit 2). The `artifact` is NOT modified at this point.
/// 4. Re-seal via [`seal_env`] — this re-reads secrets from the vault and
///    generates a fresh `OsRng` nonce and KDF salt.
/// 5. Replace `artifact.environments[env_name]` with the new envelope.
///
/// # Errors
/// - [`SyncError::Artifact(ArtifactError::WeakPassphrase)`] if `new_passphrase` is empty.
/// - [`SyncError::Artifact(ArtifactError::MalformedArtifact)`] if `env_name` is not in `artifact.environments`.
/// - [`SyncError::Artifact(ArtifactError::DecryptionFailed)`] if `current_passphrase` does not match the existing envelope.
/// - [`SyncError::VaultError`] if reading secrets from the vault fails.
///
/// # Post-conditions
/// - On success, only `artifact.environments[env_name]` is replaced. All other
///   entries in `artifact.environments` are byte-identical to their prior state.
/// - On failure, `artifact` is unchanged.
pub fn rotate_env(
    vault: &Vault,
    master_key: &[u8; 32],
    project_id: &ProjectId,
    artifact: &mut SyncArtifact,
    env_name: &str,
    current_passphrase: &str,
    new_passphrase: &str,
) -> Result<(), SyncError> {
    if new_passphrase.trim().is_empty() {
        return Err(SyncError::Artifact(ArtifactError::WeakPassphrase));
    }

    // Artifact keys are lowercase (the seal path inserts normalized names);
    // reuse core::ops::normalize_env so empty/mixed-case names behave exactly
    // like the marker path.
    let env_key = super::ops::normalize_env(env_name);
    let existing_envelope = match artifact.environments.get(&env_key) {
        Some(e) => e,
        None => {
            return Err(SyncError::Artifact(ArtifactError::MalformedArtifact(
                format!("environment '{env_name}' not found in artifact"),
            )));
        }
    };

    if !check_envelope_passphrase(current_passphrase, env_name, existing_envelope) {
        return Err(SyncError::Artifact(ArtifactError::MalformedEnvelope(
            env_name.to_string(),
            "current passphrase does not match the existing envelope".to_string(),
        )));
    }

    let new_envelope = seal_env(vault, master_key, project_id, env_name, new_passphrase)?;
    artifact.environments.insert(env_key, new_envelope);

    Ok(())
}

// ---------------------------------------------------------------------------
// check_envelope_passphrase — pre-flight decryption check (T008)
// ---------------------------------------------------------------------------

/// Returns `true` if `passphrase` successfully decrypts `envelope`.
///
/// Used by `cmd_encrypt` to detect key rotation (FR-008): when the user
/// provides a passphrase that does not match the existing sealed data, the
/// CLI layer shows a rotation warning and defaults to abort.
///
/// Both wrong-passphrase and tampered-ciphertext cases return `false` —
/// AES-GCM cannot distinguish them, and both warrant a rotation warning.
pub fn check_envelope_passphrase(
    passphrase: &str,
    env_name: &str,
    envelope: &EncryptedEnvelope,
) -> bool {
    unseal_envelope(passphrase, env_name, envelope).is_ok()
}

// ---------------------------------------------------------------------------
// unseal_env — decrypt a single environment from an artifact (QA-F2)
// ---------------------------------------------------------------------------

/// Decrypts a single named environment from `artifact` using `passphrase`.
///
/// Returns `Ok(Some(secrets))` when the environment exists and the passphrase
/// is correct. Returns `Ok(None)` when either the environment is not found in
/// the artifact or the passphrase is wrong / the ciphertext is tampered
/// (Progressive Disclosure — never hard-errors on auth failure).
///
/// Used by `cmd_decrypt` to support per-environment passphrase resolution
/// (`ENVY_PASSPHRASE_<ENV>`) in headless mode (QA-F2).
pub fn unseal_env(
    artifact: &SyncArtifact,
    env_name: &str,
    passphrase: &str,
) -> Result<Option<BTreeMap<String, Zeroizing<String>>>, SyncError> {
    let envelope = match artifact.environments.get(env_name) {
        Some(e) => e,
        None => return Ok(None),
    };
    match unseal_envelope(passphrase, env_name, envelope) {
        Ok(payload) => Ok(Some(payload.secrets)),
        Err(_) => Ok(None), // Wrong passphrase or tampered data → graceful skip.
    }
}

// ---------------------------------------------------------------------------
// new_empty_artifact — construct an empty SyncArtifact (used by CLI merge)
// ---------------------------------------------------------------------------

/// Returns a new, empty [`SyncArtifact`] at the current schema version.
///
/// Used by `cmd_encrypt` to start a fresh merge base when `envy.enc` does not
/// yet exist (FR-005: first-time encrypt of a project).
pub fn new_empty_artifact() -> SyncArtifact {
    SyncArtifact {
        version: ARTIFACT_VERSION,
        environments: BTreeMap::new(),
    }
}

// ---------------------------------------------------------------------------
// T030 — read_artifact
// ---------------------------------------------------------------------------

/// Reads and parses `envy.enc` from `path`.
///
/// Validates the top-level `version` field equals [`ARTIFACT_VERSION`].
///
/// # Errors
/// - [`SyncError::FileNotFound`] if `path` does not exist.
/// - [`SyncError::Io`] on read failure.
/// - [`SyncError::Artifact(ArtifactError::MalformedArtifact)`] if the JSON is invalid.
/// - [`SyncError::UnsupportedVersion`] if `version != ARTIFACT_VERSION`.
pub fn read_artifact(path: &Path) -> Result<SyncArtifact, SyncError> {
    if !path.exists() {
        return Err(SyncError::FileNotFound(path.display().to_string()));
    }
    let content = std::fs::read_to_string(path).map_err(|e| SyncError::Io(e.to_string()))?;
    let artifact: SyncArtifact = serde_json::from_str(&content)
        .map_err(|e| SyncError::Artifact(ArtifactError::MalformedArtifact(e.to_string())))?;
    if artifact.version != ARTIFACT_VERSION {
        return Err(SyncError::UnsupportedVersion(artifact.version));
    }
    Ok(artifact)
}

// ---------------------------------------------------------------------------
// Tests (T019–T023)
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::artifact::{ArtifactPayload, EncryptedEnvelope, seal_envelope};
    use crate::db::{ProjectId, Vault};
    use std::collections::BTreeMap;
    use zeroize::Zeroizing;

    const TEST_KEY: [u8; 32] = [7u8; 32];

    /// Opens a temp vault, creates a project, and returns (vault, project_id).
    fn open_test_vault(tmp: &tempfile::TempDir) -> (Vault, ProjectId) {
        let path = tmp.path().join("vault.db");
        let vault = Vault::open(&path, &TEST_KEY).expect("vault must open");
        let pid = vault
            .create_project("test-project")
            .expect("project must be created");
        (vault, pid)
    }

    /// Builds an EncryptedEnvelope for `env_name` sealed with `passphrase`.
    fn make_envelope(passphrase: &str, key: &str, value: &str) -> EncryptedEnvelope {
        let mut secrets = BTreeMap::new();
        secrets.insert(key.to_string(), Zeroizing::new(value.to_string()));
        let payload = ArtifactPayload { secrets };
        seal_envelope(passphrase, &payload).expect("seal_envelope must succeed")
    }

    // T019 — seal_artifact_produces_valid_json_structure
    #[test]
    fn seal_artifact_produces_valid_json_structure() {
        let tmp = tempfile::tempdir().expect("tempdir must succeed");
        let (vault, pid) = open_test_vault(&tmp);

        crate::core::set_secret(
            &vault,
            &TEST_KEY,
            &pid,
            "development",
            "STRIPE_KEY",
            "sk_test",
        )
        .expect("set_secret must succeed");

        let artifact = seal_artifact(&vault, &TEST_KEY, &pid, "team-pass", Some(&["development"]))
            .expect("seal_artifact must succeed");

        assert_eq!(artifact.version, ARTIFACT_VERSION);
        assert!(
            artifact.environments.contains_key("development"),
            "must contain development"
        );
        let env = &artifact.environments["development"];
        assert!(!env.ciphertext.is_empty(), "ciphertext must be non-empty");
        assert!(!env.nonce.is_empty(), "nonce must be non-empty");
        assert_eq!(env.kdf.algorithm, "argon2id");
    }

    // T020 — unseal_artifact_progressive_disclosure
    #[test]
    fn unseal_artifact_progressive_disclosure() {
        let dev_envelope = make_envelope("dev-pass", "API_KEY", "dev-value");
        let prod_envelope = make_envelope("prod-pass", "DB_URL", "prod-db");

        let mut environments = BTreeMap::new();
        environments.insert("development".to_string(), dev_envelope);
        environments.insert("production".to_string(), prod_envelope);

        let artifact = SyncArtifact {
            version: ARTIFACT_VERSION,
            environments,
        };

        let result = unseal_artifact(&artifact, "dev-pass").expect("unseal must succeed");

        assert!(
            result.imported.contains_key("development"),
            "development must be imported"
        );
        assert!(
            result.skipped.contains(&"production".to_string()),
            "production must be skipped"
        );
        assert_eq!(result.imported.len(), 1);
        assert_eq!(result.skipped.len(), 1);
    }

    // T021 — write_read_artifact_round_trip
    #[test]
    fn write_read_artifact_round_trip() {
        let tmp = tempfile::tempdir().expect("tempdir must succeed");
        let path = tmp.path().join("envy.enc");

        let dev_envelope = make_envelope("pass", "KEY", "val");
        let mut environments = BTreeMap::new();
        environments.insert("development".to_string(), dev_envelope);

        let artifact = SyncArtifact {
            version: ARTIFACT_VERSION,
            environments,
        };

        write_artifact(&artifact, &path).expect("write must succeed");
        let recovered = read_artifact(&path).expect("read must succeed");

        assert_eq!(recovered.version, ARTIFACT_VERSION);
        assert!(recovered.environments.contains_key("development"));
    }

    // T022 — read_artifact_malformed_json_returns_error
    #[test]
    fn read_artifact_malformed_json_returns_error() {
        let tmp = tempfile::tempdir().expect("tempdir must succeed");
        let path = tmp.path().join("envy.enc");
        std::fs::write(&path, b"not json at all").expect("write must succeed");

        let result = read_artifact(&path);
        assert!(
            matches!(
                result,
                Err(SyncError::Artifact(ArtifactError::MalformedArtifact(_)))
            ),
            "malformed JSON must return MalformedArtifact, got: {:?}",
            result.err()
        );
    }

    // T023 — read_artifact_unknown_version_returns_error
    #[test]
    fn read_artifact_unknown_version_returns_error() {
        let tmp = tempfile::tempdir().expect("tempdir must succeed");
        let path = tmp.path().join("envy.enc");
        std::fs::write(&path, b"{\"version\":999,\"environments\":{}}")
            .expect("write must succeed");

        let result = read_artifact(&path);
        assert!(
            matches!(result, Err(SyncError::UnsupportedVersion(999))),
            "unknown version must return UnsupportedVersion(999), got: {:?}",
            result.err()
        );
    }

    // T010 — write_artifact_atomic_writes_correctly_and_removes_tmp
    #[test]
    fn write_artifact_atomic_writes_correctly_and_removes_tmp() {
        let tmp_dir = tempfile::tempdir().expect("tempdir must succeed");
        let path = tmp_dir.path().join("envy.enc");
        let tmp_path = tmp_dir.path().join("envy.enc.tmp");

        let dev_envelope = make_envelope("pass", "KEY", "val");
        let mut environments = BTreeMap::new();
        environments.insert("development".to_string(), dev_envelope);
        let artifact = SyncArtifact {
            version: ARTIFACT_VERSION,
            environments,
        };

        write_artifact_atomic(&artifact, &path).expect("atomic write must succeed");

        // envy.enc must exist and be parseable.
        let recovered = read_artifact(&path).expect("read must succeed after atomic write");
        assert!(recovered.environments.contains_key("development"));

        // The .tmp file must NOT exist after a successful rename.
        assert!(
            !tmp_path.exists(),
            "envy.enc.tmp must be removed after successful atomic write"
        );
    }

    // T011 — check_envelope_passphrase_correct_and_wrong
    #[test]
    fn check_envelope_passphrase_correct_and_wrong() {
        let correct_envelope = make_envelope("pass-A", "SECRET", "value");

        assert!(
            check_envelope_passphrase("pass-A", "development", &correct_envelope),
            "correct passphrase must return true"
        );
        assert!(
            !check_envelope_passphrase("pass-B", "development", &correct_envelope),
            "wrong passphrase must return false"
        );
    }

    // T034 — seal_env writes sync marker after successful seal (FR-008)
    #[test]
    fn seal_env_writes_sync_marker() {
        let tmp = tempfile::tempdir().expect("tempdir must succeed");
        let (vault, pid) = open_test_vault(&tmp);
        crate::core::set_secret(&vault, &TEST_KEY, &pid, "development", "API_KEY", "secret")
            .expect("set_secret must succeed");

        seal_env(&vault, &TEST_KEY, &pid, "development", "test-passphrase")
            .expect("seal_env must succeed");
        mark_env_sealed(&vault, &pid, "development").expect("marker must succeed");

        let statuses = vault.environment_status(&pid).expect("environment_status");
        let dev = statuses
            .iter()
            .find(|s| s.name == "development")
            .expect("development must be present");
        assert!(
            dev.sealed_at.is_some(),
            "sealed_at must be Some after seal_env"
        );
        assert!(
            dev.sealed_at.unwrap() > 0,
            "sealed_at must be a positive Unix timestamp"
        );
    }

    // FR-059 regression: mixed-case env names must normalize in the marker
    // path — the raw lookup used to fail with "record not found" AFTER the
    // seal itself had already succeeded.
    #[test]
    fn mark_env_sealed_accepts_mixed_case_name() {
        let tmp = tempfile::tempdir().expect("tempdir must succeed");
        let (vault, pid) = open_test_vault(&tmp);
        crate::core::set_secret(&vault, &TEST_KEY, &pid, "Development", "API_KEY", "secret")
            .expect("set_secret must succeed");

        mark_env_sealed(&vault, &pid, "Development").expect("marker must normalize the name");

        let statuses = vault.environment_status(&pid).expect("environment_status");
        let dev = statuses
            .iter()
            .find(|s| s.name == "development")
            .expect("development row must exist");
        assert!(dev.sealed_at.is_some(), "marker must be committed");
    }

    // T005 — rotate_env happy path replaces envelope
    #[test]
    fn rotate_env_happy_path_replaces_envelope() {
        let tmp = tempfile::tempdir().expect("tempdir must succeed");
        let (vault, pid) = open_test_vault(&tmp);
        crate::core::set_secret(&vault, &TEST_KEY, &pid, "development", "API_KEY", "secret")
            .expect("set_secret must succeed");

        // Build an initial artifact sealed with passphrase A.
        let mut artifact = seal_artifact(&vault, &TEST_KEY, &pid, "pass-A", Some(&["development"]))
            .expect("seal_artifact must succeed");
        let dev_before = artifact.environments["development"].clone();
        let dev_ciphertext_before = dev_before.ciphertext.clone();
        let dev_nonce_before = dev_before.nonce.clone();

        // Rotate: A → B.
        rotate_env(
            &vault,
            &TEST_KEY,
            &pid,
            &mut artifact,
            "development",
            "pass-A",
            "pass-B",
        )
        .expect("rotate_env must succeed with correct current passphrase");

        // The new envelope must be byte-different from the old one.
        let dev_after = &artifact.environments["development"];
        assert_ne!(
            dev_after.ciphertext, dev_ciphertext_before,
            "ciphertext must change after rotation"
        );
        assert_ne!(
            dev_after.nonce, dev_nonce_before,
            "nonce must be regenerated after rotation"
        );

        // The new passphrase must decrypt the new envelope.
        assert!(
            check_envelope_passphrase("pass-B", "development", dev_after),
            "new passphrase must decrypt the new envelope"
        );

        // The old passphrase must NOT decrypt the new envelope.
        assert!(
            !check_envelope_passphrase("pass-A", "development", dev_after),
            "old passphrase must NOT decrypt the new envelope"
        );
    }

    // T006 — rotate_env wrong current passphrase leaves artifact unchanged
    #[test]
    fn rotate_env_wrong_current_passphrase_leaves_artifact_unchanged() {
        let tmp = tempfile::tempdir().expect("tempdir must succeed");
        let (vault, pid) = open_test_vault(&tmp);
        crate::core::set_secret(&vault, &TEST_KEY, &pid, "development", "API_KEY", "secret")
            .expect("set_secret must succeed");

        let mut artifact = seal_artifact(&vault, &TEST_KEY, &pid, "pass-A", Some(&["development"]))
            .expect("seal_artifact must succeed");
        let dev_before = artifact.environments["development"].clone();
        let staging_before = make_envelope("pass-X", "OTHER", "value");
        artifact
            .environments
            .insert("staging".to_string(), staging_before.clone());

        // Attempt rotation with wrong current passphrase.
        let result = rotate_env(
            &vault,
            &TEST_KEY,
            &pid,
            &mut artifact,
            "development",
            "WRONG-pass",
            "pass-B",
        );

        assert!(
            matches!(
                result,
                Err(SyncError::Artifact(
                    crate::crypto::artifact::ArtifactError::MalformedEnvelope(_, _)
                ))
            ),
            "wrong current passphrase must return MalformedEnvelope, got: {:?}",
            result.err()
        );

        // The development envelope must be byte-identical to before.
        let dev_after = &artifact.environments["development"];
        assert_eq!(
            dev_after.ciphertext, dev_before.ciphertext,
            "ciphertext must be unchanged after wrong-pass attempt"
        );
        assert_eq!(
            dev_after.nonce, dev_before.nonce,
            "nonce must be unchanged after wrong-pass attempt"
        );

        // Other envelopes must also be unchanged.
        assert_eq!(
            artifact.environments["staging"].ciphertext, staging_before.ciphertext,
            "other envelopes must be unchanged"
        );
    }
}