1use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::sync::{Arc, OnceLock};
23
24use crate::adapters::caps::{Caps, CommandRef, EnvRefSyntax, FieldSet};
25use crate::brand;
26use crate::env::Env;
27use crate::error::{CoreError, ErrorCode};
28use crate::fs::Fs;
29use crate::model::server::{DeliveryMode, Transport};
30use crate::secrets::catalog::{CATALOG_FILE, Catalog};
31use crate::secrets::grammar::SecretRef;
32use crate::secrets::providers::keyring::KeyringBackend;
33use crate::secrets::providers::onepassword::{OpCli, OpFeature};
34use crate::secrets::scanner::SecretMemory;
35use crate::secrets::status::SecretStatus;
36
37pub const SERVICE_ACCOUNT_VAR: &str = "OP_SERVICE_ACCOUNT_TOKEN";
39pub const SERVICE_ACCOUNT_KEYRING_ACCOUNT: &str = "OP_SERVICE_ACCOUNT_TOKEN";
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub enum Mode {
47 Env,
48 Command,
49 Launch,
50 Inline,
51}
52
53impl Mode {
54 pub const fn as_str(self) -> &'static str {
55 match self {
56 Mode::Env => "env",
57 Mode::Command => "command",
58 Mode::Launch => "launch",
59 Mode::Inline => "inline",
60 }
61 }
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum Sharing {
68 Private,
70 Shared,
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum Source {
78 Env { name: String },
81 Provider {
84 alias: String,
85 reference: SecretRef,
86 env_name: String,
88 },
89}
90
91impl Source {
92 pub fn variable(&self) -> &str {
94 match self {
95 Source::Env { name } => name,
96 Source::Provider { env_name, .. } => env_name,
97 }
98 }
99
100 pub fn reference(&self) -> SecretRef {
102 match self {
103 Source::Env { name } => SecretRef::Env { name: name.clone() },
104 Source::Provider { reference, .. } => reference.clone(),
105 }
106 }
107
108 pub fn is_provider(&self) -> bool {
109 matches!(self, Source::Provider { .. })
110 }
111
112 pub fn label(&self) -> &str {
114 match self {
115 Source::Env { name } => name,
116 Source::Provider { alias, .. } => alias,
117 }
118 }
119}
120
121pub fn source_of_alias(catalog: &Catalog, alias: &str) -> Result<Source, CoreError> {
124 let entry = catalog.get(alias).ok_or_else(|| {
125 CoreError::new(
126 ErrorCode::MissingSecret,
127 format!(
128 "{alias} is not defined in {CATALOG_FILE}; set it with `{} secrets set {alias} ...`",
129 brand::BIN_NAME
130 ),
131 )
132 })?;
133 Ok(match entry.parsed()? {
134 SecretRef::Env { name } => Source::Env { name },
135 reference => Source::Provider {
136 alias: alias.to_owned(),
137 reference,
138 env_name: entry.env_name().to_owned(),
139 },
140 })
141}
142
143#[derive(Debug, Clone, Copy)]
145pub struct Slot<'a> {
146 pub field: FieldSet,
147 pub transport: Transport,
148 pub whole: bool,
150 pub forwardable: bool,
153 pub sources: &'a [Source],
154}
155
156#[derive(Debug, Clone, Copy)]
159pub struct Policy<'a> {
160 pub requested: DeliveryMode,
161 pub caps: &'a Caps,
162 pub client: &'a str,
164 pub sharing: Sharing,
165 pub export_provider_secrets: bool,
167}
168
169pub fn env_syntax(caps: &Caps, field: FieldSet) -> Option<EnvRefSyntax> {
173 caps.env_ref
174 .filter(|syntax| *syntax != EnvRefSyntax::CodexForward)
175 .filter(|_| field != FieldSet::NONE && caps.env_ref_fields.contains(field))
176}
177
178impl Policy<'_> {
179 pub fn env_syntax(&self, field: FieldSet) -> Option<EnvRefSyntax> {
182 env_syntax(self.caps, field)
183 }
184
185 pub fn forwards(&self) -> bool {
187 self.caps.env_ref == Some(EnvRefSyntax::CodexForward)
188 }
189
190 fn command_ok(&self, slot: &Slot<'_>) -> bool {
194 let environment = slot.sources.iter().any(|source| {
195 matches!(
196 source,
197 Source::Provider {
198 reference: SecretRef::OnePasswordEnvironment { .. },
199 ..
200 }
201 )
202 });
203 if environment {
204 return false;
205 }
206 match self.caps.command_ref {
207 Some(CommandRef::Bang) => matches!(slot.field, FieldSet::ENV | FieldSet::HEADERS),
208 Some(CommandRef::HeadersHelper) => {
209 slot.field == FieldSet::HEADERS && slot.transport != Transport::Stdio
210 }
211 None => false,
212 }
213 }
214
215 pub fn choose(&self, slot: &Slot<'_>) -> Result<Mode, CoreError> {
218 let env_ok = self.env_syntax(slot.field).is_some() || slot.forwardable;
219 let launch_ok =
220 slot.transport == Transport::Stdio && slot.field == FieldSet::ENV && slot.whole;
221 let command_ok = self.command_ok(slot);
222 let provider = slot.sources.iter().any(Source::is_provider);
223 let field = field_name(slot.field);
224 let unavailable = |mode: &str, why: &str| {
225 Err(CoreError::new(
226 ErrorCode::DeliveryUnavailable,
227 format!(
228 "`{mode}` delivery cannot bring a reference in `{field}` to {}: {why}",
229 self.client
230 ),
231 ))
232 };
233 match self.requested {
234 DeliveryMode::Env if env_ok => Ok(Mode::Env),
235 DeliveryMode::Env => unavailable(
236 "env",
237 if self.forwards() {
238 "it forwards whole variables under their own name only"
239 } else {
240 "it does not expand variables in this field"
241 },
242 ),
243 DeliveryMode::Launch if launch_ok => Ok(Mode::Launch),
244 DeliveryMode::Launch => unavailable(
245 "launch",
246 "`surject exec` sets whole `env` values of stdio servers only",
247 ),
248 DeliveryMode::Command if command_ok => Ok(Mode::Command),
249 DeliveryMode::Command => unavailable("command", "it runs no command for this field"),
250 DeliveryMode::Inline => self.inline(),
251 DeliveryMode::Auto if !provider => {
252 if env_ok {
253 Ok(Mode::Env)
254 } else if launch_ok {
255 Ok(Mode::Launch)
256 } else {
257 self.inline()
258 }
259 }
260 DeliveryMode::Auto => {
261 if launch_ok {
262 Ok(Mode::Launch)
263 } else if command_ok && slot.transport != Transport::Stdio {
264 Ok(Mode::Command)
265 } else if (slot.forwardable && slot.field == FieldSet::HEADERS)
266 || (self.export_provider_secrets && env_ok)
267 {
268 Ok(Mode::Env)
271 } else {
272 let labels: Vec<&str> = slot
273 .sources
274 .iter()
275 .filter(|source| source.is_provider())
276 .map(Source::label)
277 .collect();
278 Err(CoreError::new(
279 ErrorCode::NoSecretFreeDelivery,
280 format!(
281 "{} cannot get {} in `{field}` without the value in its config file; \
282 fixes: export it to the environment (`{bin} env --export`, then \
283 `[delivery] export_provider_secrets = true` in this machine's overlay), \
284 or allow inline for this server (`[delivery] mode = \"inline\"`)",
285 self.client,
286 labels.join(", "),
287 bin = brand::BIN_NAME,
288 ),
289 ))
290 }
291 }
292 }
293 }
294
295 fn inline(&self) -> Result<Mode, CoreError> {
296 match self.sharing {
297 Sharing::Private => Ok(Mode::Inline),
298 Sharing::Shared => Err(CoreError::new(
299 ErrorCode::SecretInSharedFile,
300 "inline delivery would write a secret value into a shared file; use `env` or \
301 `launch` delivery, or move the server to the project-local layer",
302 )),
303 }
304 }
305}
306
307pub fn field_name(field: FieldSet) -> &'static str {
309 match field {
310 FieldSet::COMMAND => "command",
311 FieldSet::ARGS => "args",
312 FieldSet::ENV => "env",
313 FieldSet::CWD => "cwd",
314 FieldSet::URL => "url",
315 FieldSet::HEADERS => "headers",
316 _ => "client fields",
317 }
318}
319
320pub struct DeliveryEnv {
323 launcher: Option<PathBuf>,
324 keyring: Arc<dyn KeyringBackend>,
325 op: OnceLock<OpCli>,
326 keyring_uses: AtomicU64,
329}
330
331impl DeliveryEnv {
332 pub fn new(launcher: Option<PathBuf>, keyring: Arc<dyn KeyringBackend>) -> Self {
336 Self {
337 launcher,
338 keyring,
339 op: OnceLock::new(),
340 keyring_uses: AtomicU64::new(0),
341 }
342 }
343
344 pub fn with_op(self, op: OpCli) -> Self {
346 let _ = self.op.set(op);
347 self
348 }
349
350 pub fn launcher_path(&self) -> Option<&Path> {
351 self.launcher.as_deref()
352 }
353
354 pub fn keyring(&self) -> &dyn KeyringBackend {
358 self.keyring_uses.fetch_add(1, Ordering::Relaxed);
359 self.keyring.as_ref()
360 }
361
362 pub fn provider_reads(&self) -> u64 {
365 self.keyring_uses.load(Ordering::Relaxed)
366 }
367
368 pub fn op(&self, env: &Env, fs: &dyn Fs) -> &OpCli {
370 self.op.get_or_init(|| OpCli::detect(env, fs))
371 }
372
373 pub fn launcher(&self, sharing: Sharing) -> Result<String, CoreError> {
376 match (sharing, &self.launcher) {
377 (Sharing::Shared, _) => Ok(brand::BIN_NAME.to_owned()),
378 (Sharing::Private, Some(path)) => Ok(path.to_string_lossy().into_owned()),
379 (Sharing::Private, None) => Err(CoreError::new(
380 ErrorCode::LauncherNotFound,
381 format!(
382 "the path of the `{}` binary is not known, so the server cannot be started \
383 through `{} exec`",
384 brand::BIN_NAME,
385 brand::BIN_NAME
386 ),
387 )),
388 }
389 }
390}
391
392impl std::fmt::Debug for DeliveryEnv {
393 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
394 f.debug_struct("DeliveryEnv")
395 .field("launcher", &self.launcher)
396 .field("keyring", &self.keyring.name())
397 .field("op", &self.op.get())
398 .finish()
399 }
400}
401
402pub const ACCOUNT_VAR: &str = "OP_ACCOUNT";
404
405pub fn op_env(env: &Env, keyring: &dyn KeyringBackend, account: Option<&str>) -> Env {
411 let env = match account {
412 Some(account) if env.var(ACCOUNT_VAR).is_none() => env.with_var(ACCOUNT_VAR, account),
413 _ => env.clone(),
414 };
415 if env.var(SERVICE_ACCOUNT_VAR).is_some() {
416 return env;
417 }
418 match keyring.get_own(SERVICE_ACCOUNT_KEYRING_ACCOUNT) {
419 Ok(Some(token)) => env.with_var(SERVICE_ACCOUNT_VAR, token.expose()),
420 _ => env,
421 }
422}
423
424pub fn check_available(
430 source: &Source,
431 env: &Env,
432 fs: &dyn Fs,
433 delivery: &DeliveryEnv,
434 memory: &SecretMemory,
435) -> Result<(), CoreError> {
436 let Source::Provider {
437 alias, reference, ..
438 } = source
439 else {
440 return Ok(());
442 };
443 let feature = match reference {
444 SecretRef::OnePassword { .. } => OpFeature::ItemRead,
445 SecretRef::OnePasswordEnvironment { .. } => OpFeature::Environments,
446 SecretRef::Keyring { service, account } => {
447 return match delivery.keyring().get(service, account) {
448 Ok(Some(value)) => {
449 memory.record(value.expose());
450 Ok(())
451 }
452 Ok(None) => Err(CoreError::new(
453 ErrorCode::MissingSecret,
454 format!(
455 "{alias}: no {} entry for {reference}; store one with \
456 `{} secrets set {alias} --keyring`",
457 delivery.keyring().name(),
458 brand::BIN_NAME
459 ),
460 )),
461 Err(resolution) if resolution.status == SecretStatus::ProviderUnavailable => {
462 Err(resolution.into_error(alias))
463 }
464 Err(_) => Ok(()),
466 };
467 }
468 SecretRef::Env { .. } => return Ok(()),
469 };
470 delivery
471 .op(env, fs)
472 .require(feature)
473 .map(|_| ())
474 .map_err(|resolution| {
475 let not_found = resolution.status == SecretStatus::ProviderUnavailable;
476 let err = resolution.into_error(alias);
477 if !not_found {
478 return err;
479 }
480 CoreError::new(
481 err.code(),
482 format!(
483 "{}; install it or map {alias} to keyring/env for this machine (`{} secrets \
484 set {alias} --this-machine --keyring` or `--ref env:NAME`)",
485 err.message(),
486 brand::BIN_NAME
487 ),
488 )
489 })
490}