tsafe-core 1.0.13

Core runtime engine for tsafe — encrypted credential storage, process injection contracts, audit log, RBAC
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
//! Authority contracts — named, reusable runtime authority definitions.
//!
//! Contracts are the next-step policy surface for `tsafe exec`: instead of
//! spelling policy as a bundle of flags, a repo manifest can declare a named
//! contract that describes:
//!
//! - which vault profile / namespace to resolve from
//! - which secret names are allowed and required
//! - which targets may receive injected authority
//! - which trust posture (`standard`, `hardened`, or explicit `custom`) applies
//! - future intent such as network policy
//!
//! This module is core-only. It parses and validates contract manifests so a
//! higher layer (CLI, audit UI, future policy engine) can execute against a
//! stable, auditable model.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::baseline_contracts::{
    ci_deploy_contract, ops_emergency_contract, read_only_contract, AccessLevel,
};
use crate::errors::{SafeError, SafeResult};
use crate::namespace_bulk::validate_namespace_segment;
use crate::profile::validate_profile_name;
use crate::pullconfig::find_config;
use crate::rbac::RbacProfile;
use crate::vault::validate_secret_key;

/// A validated named authority contract.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorityContract {
    pub name: String,
    pub profile: Option<String>,
    pub namespace: Option<String>,
    pub access_profile: RbacProfile,
    pub allowed_secrets: Vec<String>,
    pub required_secrets: Vec<String>,
    pub allowed_targets: Vec<String>,
    pub trust: AuthorityTrust,
    pub network: AuthorityNetworkPolicy,
}

impl AuthorityContract {
    /// Resolve the trust posture into a concrete exec policy.
    pub fn resolved_exec_policy(&self) -> ResolvedAuthorityPolicy {
        match &self.trust {
            AuthorityTrust::Standard => ResolvedAuthorityPolicy {
                trust_level: AuthorityTrustLevel::Standard,
                access_profile: self.access_profile,
                inherit: AuthorityInheritMode::Full,
                deny_dangerous_env: false,
                redact_output: false,
            },
            AuthorityTrust::Hardened => ResolvedAuthorityPolicy {
                trust_level: AuthorityTrustLevel::Hardened,
                access_profile: self.access_profile,
                inherit: AuthorityInheritMode::Minimal,
                deny_dangerous_env: true,
                redact_output: true,
            },
            AuthorityTrust::Custom(custom) => ResolvedAuthorityPolicy {
                trust_level: AuthorityTrustLevel::Custom,
                access_profile: self.access_profile,
                inherit: custom.inherit,
                deny_dangerous_env: custom.deny_dangerous_env,
                redact_output: custom.redact_output,
            },
        }
    }

    /// Return whether this contract allows the given execution target.
    ///
    /// Targets are matched exactly against the provided string and, when that
    /// string is a path, also against the basename. An empty target allowlist
    /// means "no target restriction yet".
    pub fn allows_target(&self, command: &str) -> bool {
        self.evaluate_target(Some(command)).decision.is_allowed()
    }

    /// Evaluate a target command against this contract's allowlist.
    ///
    /// The result is explicit and auditable: higher layers can tell whether a
    /// command was allowed by exact match, basename match, lack of restriction,
    /// or denied outright.
    pub fn evaluate_target(&self, command: Option<&str>) -> AuthorityTargetEvaluation {
        if self.allowed_targets.is_empty() {
            return AuthorityTargetEvaluation {
                decision: AuthorityTargetDecision::Unconstrained,
                matched_allowlist_entry: None,
            };
        }

        let Some(command) = command.map(str::trim).filter(|value| !value.is_empty()) else {
            return AuthorityTargetEvaluation {
                decision: AuthorityTargetDecision::MissingTarget,
                matched_allowlist_entry: None,
            };
        };

        if let Some(matched) = self
            .allowed_targets
            .iter()
            .find(|allowed| allowed == &command)
        {
            return AuthorityTargetEvaluation {
                decision: AuthorityTargetDecision::AllowedExact,
                matched_allowlist_entry: Some(matched.clone()),
            };
        }

        let basename = Path::new(command)
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or(command);
        if let Some(matched) = self
            .allowed_targets
            .iter()
            .find(|allowed| allowed.as_str() == basename)
        {
            return AuthorityTargetEvaluation {
                decision: AuthorityTargetDecision::AllowedBasename,
                matched_allowlist_entry: Some(matched.clone()),
            };
        }

        AuthorityTargetEvaluation {
            decision: AuthorityTargetDecision::Denied,
            matched_allowlist_entry: None,
        }
    }
}

/// High-level trust posture for a contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthorityTrustLevel {
    Standard,
    Hardened,
    Custom,
}

impl AuthorityTrustLevel {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Standard => "standard",
            Self::Hardened => "hardened",
            Self::Custom => "custom",
        }
    }
}

/// Resolved trust model for a contract.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthorityTrust {
    Standard,
    Hardened,
    Custom(CustomAuthorityTrust),
}

/// Explicit trust overrides for `trust_level: custom`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CustomAuthorityTrust {
    pub inherit: AuthorityInheritMode,
    pub deny_dangerous_env: bool,
    pub redact_output: bool,
}

/// Parent-environment inheritance mode for exec authority.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthorityInheritMode {
    Full,
    Minimal,
    Clean,
}

impl AuthorityInheritMode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::Minimal => "minimal",
            Self::Clean => "clean",
        }
    }
}

/// Future network-intent policy for a contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum AuthorityNetworkPolicy {
    #[default]
    Inherit,
    Restricted,
}

impl AuthorityNetworkPolicy {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Inherit => "inherit",
            Self::Restricted => "restricted",
        }
    }
}

/// Concrete exec policy derived from a contract trust posture.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResolvedAuthorityPolicy {
    pub trust_level: AuthorityTrustLevel,
    pub access_profile: RbacProfile,
    pub inherit: AuthorityInheritMode,
    pub deny_dangerous_env: bool,
    pub redact_output: bool,
}

/// Explicit result of checking a command against a contract allowlist.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthorityTargetDecision {
    Unconstrained,
    AllowedExact,
    AllowedBasename,
    MissingTarget,
    Denied,
}

impl AuthorityTargetDecision {
    pub fn is_allowed(self) -> bool {
        matches!(
            self,
            Self::Unconstrained | Self::AllowedExact | Self::AllowedBasename
        )
    }
}

/// Outcome of one contract target evaluation, including the allowlist entry
/// that matched when the decision was positive.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthorityTargetEvaluation {
    pub decision: AuthorityTargetDecision,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub matched_allowlist_entry: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
struct RawContractsFile {
    #[serde(default)]
    contracts: BTreeMap<String, RawAuthorityContract>,
}

#[derive(Debug, Default, Deserialize)]
struct RawAuthorityContract {
    /// Optional built-in template to inherit defaults from.
    /// Available: "read_only", "ci_deploy", "ops_emergency".
    /// Explicit fields override template defaults.
    #[serde(default)]
    template: Option<String>,
    #[serde(default)]
    profile: Option<String>,
    #[serde(default)]
    namespace: Option<String>,
    #[serde(default)]
    access_profile: Option<RbacProfile>,
    #[serde(default)]
    allowed_secrets: Vec<String>,
    #[serde(default)]
    required_secrets: Vec<String>,
    #[serde(default)]
    allowed_targets: Vec<String>,
    #[serde(default)]
    trust_level: Option<AuthorityTrustLevel>,
    #[serde(default)]
    inherit: Option<AuthorityInheritMode>,
    #[serde(default)]
    deny_dangerous_env: Option<bool>,
    #[serde(default)]
    redact_output: Option<bool>,
    #[serde(default)]
    network: AuthorityNetworkPolicy,
}

/// Search upward from `start` for a repo manifest that may contain contracts.
pub fn find_contracts_manifest(start: &Path) -> Option<PathBuf> {
    find_config(start)
}

/// Load and validate all authority contracts from a repo manifest file.
///
/// The manifest may also contain other top-level sections (for example `pulls`);
/// this loader ignores everything except `contracts`.
pub fn load_contracts(path: &Path) -> SafeResult<BTreeMap<String, AuthorityContract>> {
    let content = std::fs::read_to_string(path)?;
    let raw: RawContractsFile = if is_json(path) {
        serde_json::from_str(&content).map_err(|e| SafeError::InvalidVault {
            reason: format!("invalid authority contract JSON: {e}"),
        })?
    } else {
        serde_yaml::from_str(&content).map_err(|e| SafeError::InvalidVault {
            reason: format!("invalid authority contract YAML: {e}"),
        })?
    };

    raw.contracts
        .into_iter()
        .map(|(name, raw)| Ok((name.clone(), validate_contract(name, raw)?)))
        .collect()
}

/// Load a single named authority contract from a manifest file.
pub fn load_contract(path: &Path, name: &str) -> SafeResult<AuthorityContract> {
    let contracts = load_contracts(path)?;
    contracts
        .get(name)
        .cloned()
        .ok_or_else(|| SafeError::InvalidVault {
            reason: format!(
                "authority contract '{name}' not found in {}",
                path.display()
            ),
        })
}

fn apply_template_defaults(contract_name: &str, raw: &mut RawAuthorityContract) -> SafeResult<()> {
    let tmpl_name = match raw.template.as_deref() {
        Some(n) => n,
        None => return Ok(()),
    };
    let baseline = match tmpl_name {
        "read_only" => read_only_contract(),
        "ci_deploy" => ci_deploy_contract(vec!["terraform".to_string(), "ansible".to_string()]),
        "ops_emergency" => ops_emergency_contract(),
        other => {
            return Err(SafeError::InvalidVault {
                reason: format!(
                    "contract '{contract_name}': unknown template '{other}' \
                     (available: read_only, ci_deploy, ops_emergency)"
                ),
            })
        }
    };
    // Fill in unset fields from the template. Explicit YAML fields win.
    if raw.trust_level.is_none() {
        raw.trust_level = Some(match baseline.required_trust_profile.as_str() {
            "hardened" => AuthorityTrustLevel::Hardened,
            _ => AuthorityTrustLevel::Standard,
        });
    }
    if raw.access_profile.is_none() {
        raw.access_profile = Some(match baseline.access_level {
            AccessLevel::ReadOnly => RbacProfile::ReadOnly,
            AccessLevel::ReadWrite => RbacProfile::ReadWrite,
        });
    }
    if raw.allowed_secrets.is_empty() {
        raw.allowed_secrets = baseline.secret_constraints.allowed_secrets;
    }
    if raw.required_secrets.is_empty() {
        raw.required_secrets = baseline.secret_constraints.required_secrets;
    }
    if raw.allowed_targets.is_empty() {
        if let Some(targets) = baseline.target_constraints {
            raw.allowed_targets = targets;
        }
    }
    Ok(())
}

fn validate_contract(name: String, mut raw: RawAuthorityContract) -> SafeResult<AuthorityContract> {
    validate_contract_name(&name)?;
    apply_template_defaults(&name, &mut raw)?;

    let trust_level = raw.trust_level.ok_or_else(|| SafeError::InvalidVault {
        reason: format!("contract '{name}': trust_level is required (or use template: <name>)"),
    })?;
    if matches!(
        trust_level,
        AuthorityTrustLevel::Standard | AuthorityTrustLevel::Hardened
    ) {
        reject_custom_overrides(&name, &raw)?;
    }

    let profile = raw.profile.map(|profile| profile.trim().to_string());
    if let Some(profile) = profile.as_deref() {
        validate_profile_name(profile)?;
    }

    let namespace = raw.namespace.map(|namespace| namespace.trim().to_string());
    if let Some(namespace) = namespace.as_deref() {
        validate_namespace_segment(namespace)?;
    }

    let allowed_secrets =
        normalize_contract_secret_names(&name, "allowed_secrets", raw.allowed_secrets)?;
    let required_secrets =
        normalize_contract_secret_names(&name, "required_secrets", raw.required_secrets)?;
    for secret in &required_secrets {
        if !allowed_secrets.iter().any(|allowed| allowed == secret) {
            return Err(SafeError::InvalidVault {
                reason: format!(
                    "contract '{name}': required secret '{secret}' must also appear in allowed_secrets"
                ),
            });
        }
    }

    let trust = match trust_level {
        AuthorityTrustLevel::Standard => AuthorityTrust::Standard,
        AuthorityTrustLevel::Hardened => AuthorityTrust::Hardened,
        AuthorityTrustLevel::Custom => AuthorityTrust::Custom(CustomAuthorityTrust {
            inherit: raw.inherit.unwrap_or(AuthorityInheritMode::Full),
            deny_dangerous_env: raw.deny_dangerous_env.unwrap_or(false),
            redact_output: raw.redact_output.unwrap_or(false),
        }),
    };
    let allowed_targets = normalize_allowed_targets(&name, raw.allowed_targets)?;

    Ok(AuthorityContract {
        name,
        profile,
        namespace,
        access_profile: raw.access_profile.unwrap_or_default(),
        allowed_secrets,
        required_secrets,
        allowed_targets,
        trust,
        network: raw.network,
    })
}

fn reject_custom_overrides(name: &str, raw: &RawAuthorityContract) -> SafeResult<()> {
    if raw.inherit.is_some() || raw.deny_dangerous_env.is_some() || raw.redact_output.is_some() {
        return Err(SafeError::InvalidVault {
            reason: format!(
                "contract '{name}': inherit / deny_dangerous_env / redact_output are only valid with trust_level: custom"
            ),
        });
    }
    Ok(())
}

fn normalize_contract_secret_names(
    contract_name: &str,
    field: &str,
    names: Vec<String>,
) -> SafeResult<Vec<String>> {
    let mut out = Vec::new();
    for name in names {
        let trimmed = name.trim();
        if trimmed.is_empty() {
            return Err(SafeError::InvalidVault {
                reason: format!("contract '{contract_name}': {field} contains an empty name"),
            });
        }
        if trimmed.contains('/') {
            return Err(SafeError::InvalidVault {
                reason: format!(
                    "contract '{contract_name}': {field} entry '{trimmed}' must be a post-namespace secret/env name, not a namespaced vault key"
                ),
            });
        }
        validate_secret_key(trimmed)?;
        if !out.iter().any(|existing: &String| existing == trimmed) {
            out.push(trimmed.to_string());
        }
    }
    out.sort();
    Ok(out)
}

fn normalize_allowed_targets(contract_name: &str, targets: Vec<String>) -> SafeResult<Vec<String>> {
    let mut out = Vec::new();
    for target in targets {
        let trimmed = target.trim();
        if trimmed.is_empty() {
            return Err(SafeError::InvalidVault {
                reason: format!(
                    "contract '{contract_name}': allowed_targets contains an empty target"
                ),
            });
        }
        if trimmed.chars().any(char::is_control) {
            return Err(SafeError::InvalidVault {
                reason: format!(
                    "contract '{contract_name}': target '{trimmed}' contains control characters"
                ),
            });
        }
        if !out.iter().any(|existing: &String| existing == trimmed) {
            out.push(trimmed.to_string());
        }
    }
    out.sort();
    Ok(out)
}

fn validate_contract_name(name: &str) -> SafeResult<()> {
    if name.is_empty() {
        return Err(SafeError::InvalidVault {
            reason: "contract name cannot be empty".into(),
        });
    }
    if !name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
    {
        return Err(SafeError::InvalidVault {
            reason: format!(
                "contract '{name}': only ASCII letters, digits, '-', '_' and '.' are allowed"
            ),
        });
    }
    Ok(())
}

fn is_json(path: &Path) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .map(|e| e == "json")
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn parse_yaml_contracts_ignores_other_manifest_sections() {
        let yaml = r#"
pulls:
  - source: akv
    vault_url: https://example.vault.azure.net
contracts:
  deploy:
    profile: work
    namespace: infra
    allowed_secrets:
      - DB_PASSWORD
      - API_KEY
    required_secrets:
      - DB_PASSWORD
    allowed_targets:
      - terraform
      - /usr/bin/tofu
    access_profile: read_only
    trust_level: hardened
    network: restricted
"#;
        let dir = tempdir().unwrap();
        let path = dir.path().join(".tsafe.yml");
        std::fs::write(&path, yaml).unwrap();

        let contracts = load_contracts(&path).unwrap();
        let deploy = contracts.get("deploy").unwrap();
        assert_eq!(deploy.profile.as_deref(), Some("work"));
        assert_eq!(deploy.namespace.as_deref(), Some("infra"));
        assert_eq!(deploy.allowed_secrets, vec!["API_KEY", "DB_PASSWORD"]);
        assert_eq!(deploy.required_secrets, vec!["DB_PASSWORD"]);
        assert_eq!(deploy.allowed_targets, vec!["/usr/bin/tofu", "terraform"]);
        assert_eq!(deploy.access_profile, RbacProfile::ReadOnly);
        assert_eq!(deploy.network, AuthorityNetworkPolicy::Restricted);
        assert_eq!(
            deploy.resolved_exec_policy().access_profile,
            RbacProfile::ReadOnly
        );
        assert_eq!(
            deploy.resolved_exec_policy().inherit,
            AuthorityInheritMode::Minimal
        );
        assert!(deploy.resolved_exec_policy().deny_dangerous_env);
        assert!(deploy.resolved_exec_policy().redact_output);
    }

    #[test]
    fn parse_json_contract_with_custom_trust() {
        let json = r#"{
  "contracts": {
    "deploy": {
      "allowed_secrets": ["DB_PASSWORD", "DB_PASSWORD"],
      "required_secrets": ["DB_PASSWORD"],
      "trust_level": "custom",
      "inherit": "clean",
      "deny_dangerous_env": true,
      "redact_output": true
    }
  }
}"#;
        let dir = tempdir().unwrap();
        let path = dir.path().join(".tsafe.json");
        std::fs::write(&path, json).unwrap();

        let deploy = load_contract(&path, "deploy").unwrap();
        assert_eq!(deploy.allowed_secrets, vec!["DB_PASSWORD"]);
        assert_eq!(
            deploy.trust,
            AuthorityTrust::Custom(CustomAuthorityTrust {
                inherit: AuthorityInheritMode::Clean,
                deny_dangerous_env: true,
                redact_output: true,
            })
        );
    }

    #[test]
    fn missing_trust_level_is_rejected() {
        let yaml = r#"
contracts:
  deploy:
    allowed_secrets: [DB_PASSWORD]
"#;
        let dir = tempdir().unwrap();
        let path = dir.path().join(".tsafe.yml");
        std::fs::write(&path, yaml).unwrap();

        let err = load_contracts(&path).unwrap_err();
        assert!(matches!(
            err,
            SafeError::InvalidVault { ref reason } if reason.contains("trust_level is required")
        ));
    }

    #[test]
    fn standard_or_hardened_reject_custom_overrides() {
        let yaml = r#"
contracts:
  deploy:
    allowed_secrets: [DB_PASSWORD]
    trust_level: hardened
    inherit: clean
"#;
        let dir = tempdir().unwrap();
        let path = dir.path().join(".tsafe.yml");
        std::fs::write(&path, yaml).unwrap();

        let err = load_contracts(&path).unwrap_err();
        assert!(matches!(
            err,
            SafeError::InvalidVault { ref reason }
                if reason.contains("only valid with trust_level: custom")
        ));
    }

    #[test]
    fn required_secrets_must_be_allowed() {
        let yaml = r#"
contracts:
  deploy:
    allowed_secrets: [API_KEY]
    required_secrets: [DB_PASSWORD]
    trust_level: standard
"#;
        let dir = tempdir().unwrap();
        let path = dir.path().join(".tsafe.yml");
        std::fs::write(&path, yaml).unwrap();

        let err = load_contracts(&path).unwrap_err();
        assert!(matches!(
            err,
            SafeError::InvalidVault { ref reason }
                if reason.contains("must also appear in allowed_secrets")
        ));
    }

    #[test]
    fn evaluate_target_returns_explicit_decisions() {
        let contract = AuthorityContract {
            name: "deploy".into(),
            profile: None,
            namespace: None,
            access_profile: RbacProfile::ReadWrite,
            allowed_secrets: vec!["DB_PASSWORD".into()],
            required_secrets: vec!["DB_PASSWORD".into()],
            allowed_targets: vec!["terraform".into(), "/usr/bin/tofu".into()],
            trust: AuthorityTrust::Hardened,
            network: AuthorityNetworkPolicy::Inherit,
        };

        assert_eq!(
            contract.evaluate_target(Some("terraform")),
            AuthorityTargetEvaluation {
                decision: AuthorityTargetDecision::AllowedExact,
                matched_allowlist_entry: Some("terraform".into()),
            }
        );
        assert_eq!(
            contract.evaluate_target(Some("/usr/local/bin/terraform")),
            AuthorityTargetEvaluation {
                decision: AuthorityTargetDecision::AllowedBasename,
                matched_allowlist_entry: Some("terraform".into()),
            }
        );
        assert_eq!(
            contract.evaluate_target(Some("/usr/bin/tofu")),
            AuthorityTargetEvaluation {
                decision: AuthorityTargetDecision::AllowedExact,
                matched_allowlist_entry: Some("/usr/bin/tofu".into()),
            }
        );
        assert_eq!(
            contract.evaluate_target(Some("bash")),
            AuthorityTargetEvaluation {
                decision: AuthorityTargetDecision::Denied,
                matched_allowlist_entry: None,
            }
        );
        assert_eq!(
            contract.evaluate_target(None),
            AuthorityTargetEvaluation {
                decision: AuthorityTargetDecision::MissingTarget,
                matched_allowlist_entry: None,
            }
        );
        assert!(contract.allows_target("terraform"));
        assert!(!contract.allows_target("bash"));
    }

    #[test]
    fn evaluate_target_is_unconstrained_without_allowlist() {
        let contract = AuthorityContract {
            name: "deploy".into(),
            profile: None,
            namespace: None,
            access_profile: RbacProfile::ReadWrite,
            allowed_secrets: vec!["DB_PASSWORD".into()],
            required_secrets: vec!["DB_PASSWORD".into()],
            allowed_targets: Vec::new(),
            trust: AuthorityTrust::Standard,
            network: AuthorityNetworkPolicy::Inherit,
        };

        assert_eq!(
            contract.evaluate_target(None),
            AuthorityTargetEvaluation {
                decision: AuthorityTargetDecision::Unconstrained,
                matched_allowlist_entry: None,
            }
        );
    }

    #[test]
    fn find_contracts_manifest_uses_repo_search_rules() {
        let dir = tempdir().unwrap();
        let nested = dir.path().join("a/b/c");
        std::fs::create_dir_all(&nested).unwrap();
        let manifest = dir.path().join(".tsafe.yml");
        std::fs::write(&manifest, "contracts: {}").unwrap();

        assert_eq!(find_contracts_manifest(&nested), Some(manifest));
    }

    #[test]
    fn contracts_default_to_read_write_access_profile() {
        let yaml = r#"
contracts:
  deploy:
    allowed_secrets: [DB_PASSWORD]
    trust_level: standard
"#;
        let dir = tempdir().unwrap();
        let path = dir.path().join(".tsafe.yml");
        std::fs::write(&path, yaml).unwrap();

        let deploy = load_contract(&path, "deploy").unwrap();
        assert_eq!(deploy.access_profile, RbacProfile::ReadWrite);
        assert_eq!(
            deploy.resolved_exec_policy().access_profile,
            RbacProfile::ReadWrite
        );
    }
}