greentic-deployer-dev 1.1.27411998332

Greentic deployer runtime for plan construction and deployment-pack dispatch
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
//! `gtc op credentials {requirements,bootstrap,rotate}` (`C1`).
//!
//! Per `plans/next-gen-deployment.md` §P5, credentials are first-class with
//! two modes:
//!
//! - **requirements**: validate user-supplied minimum credentials against
//!   the deployer env-pack's declared requirements.
//! - **bootstrap**: run the deployer env-pack's bootstrap pack against
//!   ephemeral admin credentials; produce low-privilege output + a
//!   reviewable rules pack.
//! - **rotate**: re-validate; rotate session tokens where the deployer
//!   supports it (Phase D — today this re-runs requirements and surfaces
//!   the up-to-date report).
//!
//! All three resolve the env's bound deployer env-pack through the A9
//! registry and invoke the
//! [`DeployerCredentials`](crate::credentials::DeployerCredentials) contract
//! shipped with that handler (C1). Deployer handlers that have not yet
//! registered a credentials contract surface as `HandlerNotRegistered`
//! (a structured CLI conflict, not a silent pass).
//!
//! Preconditions enforced at this layer (before audit, before delegating
//! to the registry):
//!
//! - The env must exist.
//! - The env must have a `Deployer` slot bound.
//! - For `requirements`/`rotate`, the env must already have a
//!   `credentials_ref` (the user supplied creds somewhere). For
//!   `bootstrap`, `credentials_ref` MUST be absent (bootstrap creates it).
//!
//! ## Admin credentials posture
//!
//! `bootstrap` reads the admin material via
//! [`load_admin_credential`](self::load_admin_credential), wraps it in
//! [`ZeroizedAdmin`], and never writes it to the env's storage. The
//! wrapper zeroizes the in-process buffer on drop where the language /
//! runtime allows it. The CLI does NOT claim process-wide memory erasure
//! is guaranteed — that's impossible (OS paging, cloud SDK internal
//! copies, ambient profile chains live outside this process). Operators
//! needing stronger guarantees should run bootstrap on a short-lived
//! process (CI runner, dedicated VM).

use std::path::PathBuf;

use greentic_deploy_spec::EnvId;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use thiserror::Error;
use zeroize::Zeroizing;

use crate::credentials::{
    RunBootstrapError, ValidateError, ZeroizedAdmin, run_bootstrap, validate_requirements,
};
use crate::env_packs::EnvPackRegistry;
use crate::environment::{EnvironmentStore, LocalFsStore};

use super::{AuditCtx, AuditGens, OpError, OpFlags, OpOutcome, audit_and_record};

const NOUN: &str = "credentials";

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CredentialsRequirementsPayload {
    pub environment_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CredentialsBootstrapPayload {
    pub environment_id: String,
    /// Local profile name (e.g. AWS named profile) used for the one-time
    /// admin run. Never written to the env's storage.
    pub admin_profile: String,
    /// Path to a file holding the admin credential material. The
    /// contents are loaded into a [`ZeroizedAdmin`] wrapper and dropped
    /// (zeroized) before this call returns. Mutually exclusive with
    /// `admin_material_inline`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub admin_material_path: Option<PathBuf>,
    /// Inline admin credential material — convenient for piping (e.g.
    /// `gtc op credentials bootstrap … --answers <(...)`). Never
    /// persisted by the CLI. Mutually exclusive with `admin_material_path`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub admin_material_inline: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CredentialsRotatePayload {
    pub environment_id: String,
}

#[derive(Debug, Error)]
enum AdminLoadError {
    #[error("no admin material supplied: provide `admin_material_path` or `admin_material_inline`")]
    Missing,
    #[error("cannot supply both `admin_material_path` and `admin_material_inline`")]
    Both,
    #[error("read admin material from `{path}`: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("admin material at `{path}` is not valid UTF-8")]
    NonUtf8 { path: PathBuf },
    #[error("admin material is empty")]
    Empty,
}

/// `op credentials requirements`. Resolves the env's deployer handler
/// through the registry, runs the C1 contract's probes, returns the
/// per-check report.
pub fn requirements(
    store: &LocalFsStore,
    registry: &EnvPackRegistry,
    flags: &OpFlags,
    payload: Option<CredentialsRequirementsPayload>,
) -> Result<OpOutcome, OpError> {
    if flags.schema_only {
        return Ok(OpOutcome::new(NOUN, "requirements", req_schema()));
    }
    let payload = resolve_payload::<CredentialsRequirementsPayload>(flags, payload)?;
    let env_id = parse_env_id(&payload.environment_id)?;

    let (doc, report) =
        validate_requirements(store, registry, &env_id).map_err(map_validate_err)?;

    Ok(OpOutcome::new(
        NOUN,
        "requirements",
        json!({
            "environment_id": env_id.as_str(),
            "deployer_kind": doc.deployer_kind.as_str(),
            "credentials_ref": doc.provided_credentials_ref.as_str(),
            "mode": "requirements",
            "result": result_label(&doc.validation.result),
            "missing_capabilities": doc.validation.missing_capabilities,
            "checks": report.checks,
            "last_run_at": doc.validation.last_run_at,
        }),
    ))
}

pub fn bootstrap(
    store: &LocalFsStore,
    registry: &EnvPackRegistry,
    flags: &OpFlags,
    payload: Option<CredentialsBootstrapPayload>,
) -> Result<OpOutcome, OpError> {
    if flags.schema_only {
        return Ok(OpOutcome::new(NOUN, "bootstrap", bootstrap_schema()));
    }
    let mut payload = resolve_payload::<CredentialsBootstrapPayload>(flags, payload)?;
    let env_id = parse_env_id(&payload.environment_id)?;

    let admin = load_admin_credential(&mut payload).map_err(|e| {
        // Keep the admin-loader's specific error visible to the operator
        // — `Conflict` is the right kind for "you supplied the wrong
        // combination of options" / "the file you pointed at is empty".
        OpError::Conflict(e.to_string())
    })?;

    let ctx = AuditCtx {
        env_id: env_id.clone(),
        noun: NOUN,
        verb: "bootstrap",
        // admin material is NEVER recorded — only the user-supplied
        // profile handle (which is not a secret).
        target: json!({"admin_profile": payload.admin_profile}),
        idempotency_key: None,
    };
    audit_and_record(store, ctx, |committed| {
        // `run_bootstrap` holds the env flock for the entire flow:
        // load → absence check → handler.bootstrap → rules-pack write →
        // credentials_ref persist. No separate `transact` needed here.
        let doc = match run_bootstrap(store, registry, &env_id, &admin) {
            Ok(d) => d,
            Err(e) => return Err(map_bootstrap_err(e)),
        };
        committed.mark_committed();

        Ok((
            OpOutcome::new(
                NOUN,
                "bootstrap",
                json!({
                    "environment_id": env_id.as_str(),
                    "deployer_kind": doc.deployer_kind.as_str(),
                    "mode": "bootstrap",
                    "credentials_ref": doc.provided_credentials_ref.as_str(),
                    "rules_pack_ref": doc.bootstrap.as_ref().map(|b| b.rules_pack_ref.display().to_string()),
                    "admin_credential_consumed_at": doc.bootstrap.as_ref().map(|b| b.admin_credential_consumed_at),
                }),
            ),
            AuditGens::NONE,
        ))
    })
}

pub fn rotate(
    store: &LocalFsStore,
    _registry: &EnvPackRegistry,
    flags: &OpFlags,
    payload: Option<CredentialsRotatePayload>,
) -> Result<OpOutcome, OpError> {
    if flags.schema_only {
        return Ok(OpOutcome::new(NOUN, "rotate", rotate_schema()));
    }
    let payload = resolve_payload::<CredentialsRotatePayload>(flags, payload)?;
    let env_id = parse_env_id(&payload.environment_id)?;

    // Pre-flight: reject envs that have no credentials_ref at all
    // (same precondition as the old validate_requirements path).
    let env = store.load(&env_id).map_err(|e| match e {
        crate::environment::StoreError::NotFound(_) => {
            OpError::NotFound(format!("environment `{env_id}`"))
        }
        other => OpError::Store(other),
    })?;
    if env
        .pack_for_slot(greentic_deploy_spec::CapabilitySlot::Deployer)
        .is_none()
    {
        return Err(OpError::Conflict(format!(
            "env `{env_id}` has no deployer env-pack bound; bind one with `op env-packs add` first"
        )));
    }
    if env.credentials_ref.is_none() {
        return Err(OpError::Conflict(format!(
            "env `{env_id}` has no credentials_ref; run `op credentials bootstrap` first"
        )));
    }

    let ctx = AuditCtx {
        env_id: env_id.clone(),
        noun: NOUN,
        verb: "rotate",
        target: json!({}),
        idempotency_key: None,
    };
    audit_and_record(store, ctx, |_committed| {
        // Session-token rotation hooks (AWS STS, GCP impersonation) are
        // deployer-specific behavior that lands in Phase D. Returning
        // NotYetImplemented ensures the audit log does NOT record a
        // successful rotation when no material actually changed —
        // operators watching for leaked-credential remediation won't
        // get a false "rotated" signal.
        Err(OpError::NotYetImplemented(
            "session-token rotation hooks are Phase D \
             — use `op credentials requirements` for re-validation today"
                .to_string(),
        ))
    })
}

// --- internals -----------------------------------------------------------

fn result_label(r: &greentic_deploy_spec::CredentialsValidationResult) -> &'static str {
    match r {
        greentic_deploy_spec::CredentialsValidationResult::Pass => "pass",
        greentic_deploy_spec::CredentialsValidationResult::Fail => "fail",
    }
}

/// Load admin credential material into a [`ZeroizedAdmin`] wrapper.
///
/// Takes `&mut` so the inline path can `std::mem::take` the material out
/// of the payload, leaving `None` behind — explicit single-use semantics
/// that prevents the caller from accidentally retaining the cleartext.
///
/// File path: reads into `Zeroizing<Vec<u8>>`, then converts via strict
/// `String::from_utf8` (not lossy — lossy substitution silently corrupts
/// credentials). The intermediate `Vec<u8>` is zeroized on drop.
fn load_admin_credential(
    payload: &mut CredentialsBootstrapPayload,
) -> Result<ZeroizedAdmin, AdminLoadError> {
    match (&payload.admin_material_path, &payload.admin_material_inline) {
        (None, None) => Err(AdminLoadError::Missing),
        (Some(_), Some(_)) => Err(AdminLoadError::Both),
        (Some(path), None) => {
            let mut bytes =
                Zeroizing::new(std::fs::read(path).map_err(|source| AdminLoadError::Io {
                    path: path.clone(),
                    source,
                })?);
            // Take the raw bytes out of the Zeroizing wrapper. The
            // wrapper drops with an empty Vec (no-op zeroize); the
            // bytes move into String::from_utf8. On UTF-8 success the
            // String takes ownership of the same allocation; on failure
            // the bytes are returned inside the error and dropped here.
            let raw = std::mem::take(&mut *bytes);
            let material = String::from_utf8(raw)
                .map_err(|_| AdminLoadError::NonUtf8 { path: path.clone() })?;
            if material.trim().is_empty() {
                return Err(AdminLoadError::Empty);
            }
            Ok(ZeroizedAdmin::new(&payload.admin_profile, material))
        }
        (None, Some(_)) => {
            // Take the inline material out of the payload — the field
            // becomes `None` after extraction, enforcing single-use.
            let taken = std::mem::take(&mut payload.admin_material_inline)
                .expect("matched Some branch; take cannot be None");
            if taken.trim().is_empty() {
                return Err(AdminLoadError::Empty);
            }
            Ok(ZeroizedAdmin::new(&payload.admin_profile, taken))
        }
    }
}

// Shared message helpers — both mappers below enrich the library-level
// error with operator-action guidance (e.g. "bind one with `op env-packs
// add` first"). The source `#[error(...)]` strings on `ValidateError` /
// `RunBootstrapError` are deliberately library-shaped (no CLI verb hints),
// so the CLI mapper layer owns the operator-facing wording.
fn no_deployer_bound_msg(env_id: &EnvId) -> String {
    format!("env `{env_id}` has no deployer env-pack bound; bind one with `op env-packs add` first")
}

fn handler_not_registered_msg(kind: &str) -> String {
    format!(
        "deployer env-pack `{kind}` has no native credentials handler registered (Phase D plug-in)"
    )
}

fn map_validate_err(e: ValidateError) -> OpError {
    match e {
        ValidateError::NoDeployerBound(env_id) => OpError::Conflict(no_deployer_bound_msg(&env_id)),
        ValidateError::NoCredentialsRef(env_id) => OpError::Conflict(format!(
            "env `{env_id}` has no credentials_ref; run `op credentials bootstrap` first"
        )),
        ValidateError::HandlerNotRegistered { kind } => {
            OpError::Conflict(handler_not_registered_msg(&kind))
        }
        ValidateError::Store(s) => OpError::Store(s),
        ValidateError::Registry(r) => OpError::Conflict(r.to_string()),
    }
}

fn map_bootstrap_err(e: RunBootstrapError) -> OpError {
    use crate::credentials::BootstrapError;
    match e {
        RunBootstrapError::NoDeployerBound(env_id) => {
            OpError::Conflict(no_deployer_bound_msg(&env_id))
        }
        RunBootstrapError::AlreadyBootstrapped(env_id) => OpError::Conflict(format!(
            "env `{env_id}` already has credentials_ref; use `rotate` instead of `bootstrap`"
        )),
        RunBootstrapError::HandlerNotRegistered { kind } => {
            OpError::Conflict(handler_not_registered_msg(&kind))
        }
        RunBootstrapError::Store(s) => OpError::Store(s),
        RunBootstrapError::Registry(r) => OpError::Conflict(r.to_string()),
        RunBootstrapError::Bootstrap(BootstrapError::NotApplicable(msg)) => OpError::Conflict(msg),
        RunBootstrapError::Bootstrap(BootstrapError::AdminRejected(msg)) => {
            OpError::Conflict(format!("admin credential rejected: {msg}"))
        }
        RunBootstrapError::Bootstrap(BootstrapError::ProvisioningFailed { step, message }) => {
            OpError::Conflict(format!("bootstrap failed during {step}: {message}"))
        }
        RunBootstrapError::RulesExport(r) => OpError::Conflict(format!("rules export: {r}")),
    }
}

fn resolve_payload<T: serde::de::DeserializeOwned>(
    flags: &OpFlags,
    payload: Option<T>,
) -> Result<T, OpError> {
    if let Some(p) = payload {
        return Ok(p);
    }
    if let Some(path) = &flags.answers {
        return super::load_answers::<T>(path);
    }
    Err(OpError::InvalidArgument(
        "no payload provided: pass --answers <path> or supply the payload directly".to_string(),
    ))
}

fn parse_env_id(raw: &str) -> Result<EnvId, OpError> {
    EnvId::try_from(raw).map_err(|e| OpError::InvalidArgument(format!("environment_id: {e}")))
}

fn req_schema() -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": "CredentialsRequirementsPayload",
        "type": "object",
        "required": ["environment_id"],
        "additionalProperties": false,
        "properties": {"environment_id": {"type": "string"}}
    })
}

fn bootstrap_schema() -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": "CredentialsBootstrapPayload",
        "type": "object",
        "required": ["environment_id", "admin_profile"],
        "additionalProperties": false,
        "properties": {
            "environment_id": {"type": "string"},
            "admin_profile": {"type": "string"},
            "admin_material_path": {"type": "string", "description": "path to a file holding the admin credential material (zeroized on drop)"},
            "admin_material_inline": {"type": "string", "description": "inline admin credential material (zeroized on drop); mutually exclusive with admin_material_path"}
        }
    })
}

fn rotate_schema() -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": "CredentialsRotatePayload",
        "type": "object",
        "required": ["environment_id"],
        "additionalProperties": false,
        "properties": {"environment_id": {"type": "string"}}
    })
}

// Backwards-compat shim so existing dispatch sites that call into the
// 3-arg form (without an explicit registry) still build. Callers that
// don't yet pass a registry get the built-in set (5 default `local`
// handlers); Phase D registers more through `EnvPackRegistry::register`.
//
// Kept private — `dispatch::dispatch_credentials` is updated to pass a
// registry explicitly. Tests use this shim for convenience.
#[cfg(test)]
pub(crate) fn requirements_default(
    store: &LocalFsStore,
    flags: &OpFlags,
    payload: Option<CredentialsRequirementsPayload>,
) -> Result<OpOutcome, OpError> {
    requirements(store, &EnvPackRegistry::with_builtins(), flags, payload)
}

#[cfg(test)]
pub(crate) fn bootstrap_default(
    store: &LocalFsStore,
    flags: &OpFlags,
    payload: Option<CredentialsBootstrapPayload>,
) -> Result<OpOutcome, OpError> {
    bootstrap(store, &EnvPackRegistry::with_builtins(), flags, payload)
}

#[cfg(test)]
pub(crate) fn rotate_default(
    store: &LocalFsStore,
    flags: &OpFlags,
    payload: Option<CredentialsRotatePayload>,
) -> Result<OpOutcome, OpError> {
    rotate(store, &EnvPackRegistry::with_builtins(), flags, payload)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::tests_common::{make_binding, make_env};
    use crate::environment::EnvironmentStore;
    use greentic_deploy_spec::{CapabilitySlot, SecretRef};
    use tempfile::tempdir;

    #[test]
    fn requirements_rejects_env_without_deployer() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&make_env("local")).unwrap();
        let err = requirements_default(
            &store,
            &OpFlags::default(),
            Some(CredentialsRequirementsPayload {
                environment_id: "local".to_string(),
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::Conflict(_)), "got {err:?}");
    }

    /// A no-material deployer (like local-process) passes requirements
    /// even without a `credentials_ref` on the env.
    #[test]
    fn requirements_passes_for_no_material_deployer_without_credentials_ref() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let mut env = make_env("local");
        env.packs.push(make_binding(
            CapabilitySlot::Deployer,
            "greentic.deployer.local-process@0.1.0",
        ));
        store.save(&env).unwrap();
        let outcome = requirements_default(
            &store,
            &OpFlags::default(),
            Some(CredentialsRequirementsPayload {
                environment_id: "local".to_string(),
            }),
        )
        .unwrap();
        assert_eq!(outcome.result["mode"], "requirements");
        assert_eq!(outcome.result["result"], "pass");
    }

    /// With no native credentials handler registered for the bound
    /// deployer, the CLI surfaces a structured `Conflict` (not a silent
    /// pass-through). C2 wires the local-process handler so this case
    /// passes; here we exercise an arbitrary deployer kind to confirm
    /// the "no handler" path.
    #[test]
    fn requirements_with_unregistered_deployer_kind_yields_conflict() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let mut env = make_env("local");
        env.packs.push(make_binding(
            CapabilitySlot::Deployer,
            // No handler is registered for this fictional kind — the
            // registry's built-in set covers local-process (C2) and (when
            // `creds-aws` is on) aws-ecs (C3). A bare fictional kind
            // exercises the resolve-failure path without depending on
            // which env-packs are or aren't registered today.
            "acme.deployer.fictional@1.0.0",
        ));
        env.credentials_ref = Some(SecretRef::try_new("secret://local/credentials/aws").unwrap());
        store.save(&env).unwrap();
        let err = requirements_default(
            &store,
            &OpFlags::default(),
            Some(CredentialsRequirementsPayload {
                environment_id: "local".to_string(),
            }),
        )
        .unwrap_err();
        // The deployer kind isn't registered → registry resolve fails
        // with `Unknown(kind)`; map_validate_err converts that to a
        // Conflict carrying the registry message.
        assert!(matches!(err, OpError::Conflict(_)), "got {err:?}");
    }

    #[test]
    fn bootstrap_rejects_when_creds_already_set() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let mut env = make_env("local");
        env.packs.push(make_binding(
            CapabilitySlot::Deployer,
            "greentic.deployer.aws-ecs@1.0.0",
        ));
        env.credentials_ref = Some(SecretRef::try_new("secret://local/credentials/aws").unwrap());
        store.save(&env).unwrap();
        let err = bootstrap_default(
            &store,
            &OpFlags::default(),
            Some(CredentialsBootstrapPayload {
                environment_id: "local".to_string(),
                admin_profile: "admin".to_string(),
                admin_material_path: None,
                admin_material_inline: Some("ADMIN_TOKEN".to_string()),
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::Conflict(_)), "got {err:?}");
    }

    #[test]
    fn bootstrap_requires_admin_material() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let mut env = make_env("local");
        env.packs.push(make_binding(
            CapabilitySlot::Deployer,
            "greentic.deployer.aws-ecs@1.0.0",
        ));
        store.save(&env).unwrap();
        let err = bootstrap_default(
            &store,
            &OpFlags::default(),
            Some(CredentialsBootstrapPayload {
                environment_id: "local".to_string(),
                admin_profile: "admin".to_string(),
                admin_material_path: None,
                admin_material_inline: None,
            }),
        )
        .unwrap_err();
        assert!(
            matches!(err, OpError::Conflict(ref m) if m.contains("no admin material")),
            "got {err:?}"
        );
    }

    #[test]
    fn bootstrap_rejects_both_path_and_inline() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let mut env = make_env("local");
        env.packs.push(make_binding(
            CapabilitySlot::Deployer,
            "greentic.deployer.aws-ecs@1.0.0",
        ));
        store.save(&env).unwrap();
        let err = bootstrap_default(
            &store,
            &OpFlags::default(),
            Some(CredentialsBootstrapPayload {
                environment_id: "local".to_string(),
                admin_profile: "admin".to_string(),
                admin_material_path: Some("/tmp/x".into()),
                admin_material_inline: Some("y".into()),
            }),
        )
        .unwrap_err();
        assert!(
            matches!(err, OpError::Conflict(ref m) if m.contains("cannot supply both")),
            "got {err:?}"
        );
    }

    /// C2 end-to-end: a fully-configured `local` env with the C2
    /// LocalProcessDeployerHandler bound returns a structured pass
    /// report for both capabilities. Exercises the full chain:
    /// CLI → registry → DeployerCredentials → probes → OpOutcome.
    #[test]
    fn requirements_against_c2_local_process_handler_returns_pass() {
        use crate::defaults::LOCAL_DEPLOYER_PACK;

        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let mut env = make_env("local");
        env.packs
            .push(make_binding(CapabilitySlot::Deployer, LOCAL_DEPLOYER_PACK));
        env.credentials_ref =
            Some(SecretRef::try_new("secret://local/credentials/local-process").unwrap());
        store.save(&env).unwrap();

        // Pick a high port range that's almost certainly free on a test
        // runner — same trick the C2 unit tests use.
        let registry = {
            let mut r = EnvPackRegistry::new();
            for h in crate::env_packs::BUILTIN_HANDLERS {
                r.register(Box::new(*h)).unwrap();
            }
            r.register(Box::new(
                crate::env_packs::LocalProcessDeployerHandler::with_port_range(49000..=49100),
            ))
            .unwrap();
            r
        };

        let outcome = requirements(
            &store,
            &registry,
            &OpFlags::default(),
            Some(CredentialsRequirementsPayload {
                environment_id: "local".to_string(),
            }),
        )
        .expect("requirements should succeed against c2 local-process");
        assert_eq!(outcome.op, "requirements");
        assert_eq!(outcome.noun, NOUN);
        assert_eq!(outcome.result["result"], "pass");
        assert!(
            outcome.result["missing_capabilities"]
                .as_array()
                .map(|a| a.is_empty())
                .unwrap_or(false),
            "no missing caps; got {outcome:?}"
        );
        let checks = outcome.result["checks"].as_array().unwrap();
        assert_eq!(checks.len(), 2);
    }

    /// C2 end-to-end: bootstrap against local-process refuses with
    /// `NotApplicable`, surfaced as `OpError::Conflict` and recorded in
    /// the audit log.
    #[test]
    fn bootstrap_against_c2_local_process_handler_refuses_as_not_applicable() {
        use crate::defaults::LOCAL_DEPLOYER_PACK;

        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let mut env = make_env("local");
        env.packs
            .push(make_binding(CapabilitySlot::Deployer, LOCAL_DEPLOYER_PACK));
        store.save(&env).unwrap();

        let err = bootstrap_default(
            &store,
            &OpFlags::default(),
            Some(CredentialsBootstrapPayload {
                environment_id: "local".to_string(),
                admin_profile: "admin".to_string(),
                admin_material_path: None,
                admin_material_inline: Some("any-admin-token".to_string()),
            }),
        )
        .unwrap_err();
        match err {
            OpError::Conflict(msg) => {
                assert!(
                    msg.contains("no admin escalation") || msg.contains("requirements"),
                    "Conflict message should point user at `requirements`, got: {msg}"
                );
            }
            other => panic!("expected Conflict (NotApplicable mapped), got {other:?}"),
        }
        // The reload-into-env step never happened: credentials_ref stays None.
        let reloaded = store.load(&"local".try_into().unwrap()).unwrap();
        assert!(reloaded.credentials_ref.is_none());
    }

    #[test]
    fn rotate_rejects_env_without_credentials_ref() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let mut env = make_env("local");
        env.packs.push(make_binding(
            CapabilitySlot::Deployer,
            "greentic.deployer.aws-ecs@1.0.0",
        ));
        store.save(&env).unwrap();
        let err = rotate_default(
            &store,
            &OpFlags::default(),
            Some(CredentialsRotatePayload {
                environment_id: "local".to_string(),
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::Conflict(_)), "got {err:?}");
    }

    /// Rotate returns `NotYetImplemented` (not a misleading success).
    #[test]
    fn rotate_returns_not_yet_implemented() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let mut env = make_env("local");
        env.packs.push(make_binding(
            CapabilitySlot::Deployer,
            "greentic.deployer.local-process@0.1.0",
        ));
        env.credentials_ref = Some(SecretRef::try_new("secret://local/credentials/test").unwrap());
        store.save(&env).unwrap();
        let err = rotate_default(
            &store,
            &OpFlags::default(),
            Some(CredentialsRotatePayload {
                environment_id: "local".to_string(),
            }),
        )
        .unwrap_err();
        assert!(
            matches!(err, OpError::NotYetImplemented(_)),
            "rotate should return NotYetImplemented, got {err:?}"
        );
    }

    /// A no-material deployer handler works against an env with no
    /// `credentials_ref` — the validate_requirements runner uses a
    /// sentinel ref instead of rejecting with NoCredentialsRef.
    #[test]
    fn no_material_deployer_requirements_without_credentials_ref() {
        use crate::credentials::{
            BootstrapError, BootstrapInput, BootstrapOutcome, Capability, DeployerCredentials,
            RequirementsReport, ValidationContext,
        };
        use crate::env_packs::EnvPackHandler;

        #[derive(Debug)]
        struct NoMaterialHandler;

        impl EnvPackHandler for NoMaterialHandler {
            fn slot(&self) -> CapabilitySlot {
                CapabilitySlot::Deployer
            }
            fn descriptor_path(&self) -> &str {
                "test.deployer.no-material"
            }
            fn supported_versions(&self) -> semver::VersionReq {
                "^0.1.0".parse().unwrap()
            }
            fn deployer_credentials(&self) -> Option<&dyn DeployerCredentials> {
                Some(&NoMaterialCreds)
            }
        }

        #[derive(Debug)]
        struct NoMaterialCreds;

        impl DeployerCredentials for NoMaterialCreds {
            fn requires_credentials_material(&self) -> bool {
                false
            }
            fn required_capabilities(&self) -> Vec<Capability> {
                Vec::new()
            }
            fn validate(&self, _ctx: &ValidationContext<'_>) -> RequirementsReport {
                RequirementsReport::new(Vec::new())
            }
            fn bootstrap(
                &self,
                _input: &BootstrapInput<'_>,
            ) -> Result<BootstrapOutcome, BootstrapError> {
                Err(BootstrapError::NotApplicable(
                    "no admin escalation".to_string(),
                ))
            }
        }

        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let mut env = make_env("local");
        env.packs.push(make_binding(
            CapabilitySlot::Deployer,
            "test.deployer.no-material@0.1.0",
        ));
        // No credentials_ref set.
        store.save(&env).unwrap();

        let mut registry = EnvPackRegistry::new();
        registry.register(Box::new(NoMaterialHandler)).unwrap();

        let outcome = requirements(
            &store,
            &registry,
            &OpFlags::default(),
            Some(CredentialsRequirementsPayload {
                environment_id: "local".to_string(),
            }),
        )
        .unwrap();
        assert_eq!(outcome.result["mode"], "requirements");
        assert_eq!(outcome.result["result"], "pass");
        // The sentinel ref is used when no real ref is present.
        assert!(
            outcome.result["credentials_ref"]
                .as_str()
                .unwrap()
                .contains("no-material-required"),
            "expected sentinel credentials_ref, got {:?}",
            outcome.result["credentials_ref"]
        );
    }

    /// Fix 1 (Codex C2 #1): the stock default registry
    /// (`EnvPackRegistry::with_builtins()`) must pass requirements for a
    /// `local` env bound to the default `LOCAL_DEPLOYER_PACK` WITHOUT a
    /// `credentials_ref` set. This proves the dead-end circular flow
    /// (requirements → "run bootstrap" → "use requirements instead") is
    /// closed on the operator-facing path.
    #[test]
    fn requirements_default_passes_for_local_deployer_without_credentials_ref() {
        use crate::defaults::LOCAL_DEPLOYER_PACK;

        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        let mut env = make_env("local");
        env.packs
            .push(make_binding(CapabilitySlot::Deployer, LOCAL_DEPLOYER_PACK));
        // No credentials_ref set — this is the exact operator-facing scenario.
        store.save(&env).unwrap();

        let outcome = requirements_default(
            &store,
            &OpFlags::default(),
            Some(CredentialsRequirementsPayload {
                environment_id: "local".to_string(),
            }),
        )
        .expect("default registry requirements should pass for local-process");
        assert_eq!(outcome.result["result"], "pass");
        let checks = outcome.result["checks"].as_array().unwrap();
        assert_eq!(
            checks.len(),
            2,
            "local-process declares 2 capabilities (fs + port)"
        );
        // Sentinel ref used when no material is needed.
        assert!(
            outcome.result["credentials_ref"]
                .as_str()
                .unwrap()
                .contains("no-material-required"),
            "expected sentinel ref, got {:?}",
            outcome.result["credentials_ref"]
        );
    }
}