Skip to main content

surjection_core/secrets/providers/
mod.rs

1//! Secret providers (SPEC 11.2, 11.11): the process environment, the OS
2//! keyring and the 1Password CLI. A [`Resolver`] dispatches a reference to
3//! its provider and records every value it hands out in the process's
4//! [`SecretMemory`], so the leak scanner can refuse a commit that holds it.
5
6pub mod env;
7pub mod keyring;
8pub mod onepassword;
9
10use std::sync::Arc;
11
12use crate::env::Env;
13use crate::secrets::SecretValue;
14use crate::secrets::grammar::SecretRef;
15use crate::secrets::providers::keyring::KeyringBackend;
16use crate::secrets::providers::onepassword::{OpCli, OpFeature};
17use crate::secrets::scanner::SecretMemory;
18use crate::secrets::status::{Resolution, SecretStatus};
19
20/// Which provider resolves a reference.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub enum ProviderKind {
23    /// `env:NAME`
24    Env,
25    /// `keyring://service/account`
26    Keyring,
27    /// `op://...` and `op-env://...`
28    OnePassword,
29}
30
31impl ProviderKind {
32    /// Stable `snake_case` name.
33    pub const fn as_str(self) -> &'static str {
34        match self {
35            ProviderKind::Env => "env",
36            ProviderKind::Keyring => "keyring",
37            ProviderKind::OnePassword => "onepassword",
38        }
39    }
40}
41
42/// Whether a provider can be used on this machine.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum ProviderState {
45    Available,
46    /// Not installed or not running ("1Password CLI not found").
47    Unavailable,
48    /// Installed, but its version could not be read.
49    Error,
50}
51
52impl ProviderState {
53    pub const fn as_str(self) -> &'static str {
54        match self {
55            ProviderState::Available => "available",
56            ProviderState::Unavailable => "unavailable",
57            ProviderState::Error => "error",
58        }
59    }
60}
61
62/// One provider as `surject secrets providers` reports it. Detection only:
63/// nothing here signs in or prompts (SPEC 11.11).
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct ProviderInfo {
66    pub kind: ProviderKind,
67    pub state: ProviderState,
68    /// English detail ("1Password CLI not found", "Windows Credential
69    /// Manager", the `op` path).
70    pub detail: String,
71    pub version: Option<String>,
72    /// Version-gated features and whether this machine has them.
73    pub features: Vec<(OpFeature, bool)>,
74}
75
76/// The providers of this machine, by kind.
77pub fn describe(keyring: &dyn KeyringBackend, op: &OpCli) -> Vec<ProviderInfo> {
78    vec![
79        ProviderInfo {
80            kind: ProviderKind::Env,
81            state: ProviderState::Available,
82            detail: "process environment".to_owned(),
83            version: None,
84            features: Vec::new(),
85        },
86        ProviderInfo {
87            kind: ProviderKind::Keyring,
88            state: ProviderState::Available,
89            detail: keyring.name().to_owned(),
90            version: None,
91            features: Vec::new(),
92        },
93        op.info(),
94    ]
95}
96
97/// Resolves references with this machine's providers.
98pub struct Resolver<'a> {
99    env: &'a Env,
100    keyring: &'a dyn KeyringBackend,
101    op: &'a OpCli,
102    memory: Arc<SecretMemory>,
103}
104
105impl<'a> Resolver<'a> {
106    /// `memory` is the process's [`SecretMemory`] (`Store::secret_memory`).
107    pub fn new(
108        env: &'a Env,
109        keyring: &'a dyn KeyringBackend,
110        op: &'a OpCli,
111        memory: Arc<SecretMemory>,
112    ) -> Self {
113        Self {
114            env,
115            keyring,
116            op,
117            memory,
118        }
119    }
120
121    /// The value of `reference`. 1Password Environment variables have no
122    /// value here: `op run --environment` hands them to the server process
123    /// at start (SPEC 11.5); Surjection never calls `op environment read`.
124    pub fn resolve(&self, reference: &SecretRef) -> Result<SecretValue, Resolution> {
125        let value = match reference {
126            SecretRef::Env { name } => env::resolve(self.env, name),
127            SecretRef::Keyring { service, account } => {
128                keyring::resolve(self.keyring, service, account)
129            }
130            SecretRef::OnePassword { .. } => self.op.read(self.env, &reference.to_string()),
131            SecretRef::OnePasswordEnvironment { .. } => {
132                self.op.require(OpFeature::Environments)?;
133                Err(Resolution::new(
134                    SecretStatus::Unverifiable,
135                    "1Password Environment variables are read by `op run --environment` when a \
136                     server starts, never by Surjection itself",
137                ))
138            }
139        }?;
140        self.memory.record(value.expose());
141        Ok(value)
142    }
143
144    /// The status of `reference`; the value, if fetched, is dropped. May
145    /// prompt (1Password approval), so only on an explicit check.
146    pub fn check(&self, reference: &SecretRef) -> Resolution {
147        match reference {
148            SecretRef::OnePasswordEnvironment { environment, name } => self
149                .op
150                .check_environment_variable(self.env, environment, name),
151            _ => match self.resolve(reference) {
152                Ok(_) => Resolution::resolved(),
153                Err(resolution) => resolution,
154            },
155        }
156    }
157
158    /// Stores `value` in the OS keyring and remembers it for the scanner.
159    pub fn set_keyring(
160        &self,
161        service: &str,
162        account: &str,
163        value: &SecretValue,
164    ) -> Result<(), Resolution> {
165        self.memory.record(value.expose());
166        self.keyring.set(service, account, value)
167    }
168
169    /// Deletes a keyring entry; `false` when there was none.
170    pub fn delete_keyring(&self, service: &str, account: &str) -> Result<bool, Resolution> {
171        self.keyring.delete(service, account)
172    }
173}