cli_engine/middleware.rs
1use std::{
2 collections::BTreeMap,
3 future::Future,
4 sync::Arc,
5 time::{Duration, Instant},
6};
7
8use async_trait::async_trait;
9use serde::{Deserialize, Serialize};
10use serde_json::{Map, Value, json};
11use tokio::sync::{Mutex, OnceCell};
12
13use crate::{
14 CommandResult, Credential, CredentialRequest, Dispatcher, Result, SchemaRegistry, Tier,
15 error::{CliCoreError, exit_code_for_error},
16 output::{
17 Envelope, HumanViewRegistry, OutputFormat, PipelineOpts, apply_pipeline,
18 build_error_envelope, is_valid_output_format, render_human_with_registry_selected,
19 },
20};
21
22/// JSON object map used for command args and metadata.
23pub type ValueMap = Map<String, Value>;
24
25/// Per-command metadata consumed by middleware.
26///
27/// Command specs build this metadata automatically. Applications can also
28/// adjust it through `CliConfig::meta_resolver`.
29#[derive(Clone, Debug, Default, Eq, PartialEq)]
30pub struct CommandMeta {
31 /// Whether `--dry-run` should short-circuit command business logic.
32 pub dry_run_prompt: bool,
33 /// Provider-specific auth metadata.
34 pub auth_metadata: BTreeMap<String, String>,
35 /// OAuth-style scopes derived from `auth_metadata["scopes"]`.
36 pub scopes: Vec<String>,
37}
38
39impl CommandMeta {
40 /// Returns the selected auth provider, if one is present.
41 #[must_use]
42 pub fn provider(&self) -> Option<&str> {
43 self.auth_metadata.get("provider").map(String::as_str)
44 }
45
46 /// Returns the risk tier, defaulting to [`Tier::Read`].
47 #[must_use]
48 pub fn tier(&self) -> Tier {
49 self.auth_metadata
50 .get("tier")
51 .and_then(|value| value.parse::<Tier>().ok())
52 .unwrap_or(Tier::Read)
53 }
54
55 /// Returns a fixed auth environment override, if present.
56 #[must_use]
57 pub fn fixed_env(&self) -> Option<&str> {
58 self.auth_metadata.get("fixed_env").map(String::as_str)
59 }
60
61 /// Sets the OAuth scopes, keeping [`scopes`](CommandMeta::scopes) and
62 /// `auth_metadata["scopes"]` consistent.
63 ///
64 /// `scopes` is documented as derived from `auth_metadata["scopes"]`, so any
65 /// code that synthesizes or widens scopes (e.g. runtime step-up) should use
66 /// this rather than assigning the field directly, so metadata-aware providers
67 /// reading `auth_metadata` see the same set. An empty list removes the key.
68 pub fn set_scopes(&mut self, scopes: Vec<String>) {
69 if scopes.is_empty() {
70 self.auth_metadata.remove("scopes");
71 } else {
72 self.auth_metadata
73 .insert("scopes".to_owned(), scopes.join(" "));
74 }
75 self.scopes = scopes;
76 }
77}
78
79/// Declares whether a command requires an authenticated credential.
80///
81/// This is the policy that the engine enforces; it is separate from the
82/// *mechanism* of resolution (see [`CredentialResolver`]). The default is
83/// [`Required`](AuthRequirement::Required), which fails closed: the engine
84/// resolves the credential before the handler runs, so a command that should be
85/// gated behind authentication cannot execute unauthenticated even if its
86/// handler never reads the credential, and audit/activity identity is always
87/// populated for it.
88///
89/// `--schema` and `--dry-run` short-circuit before the engine resolves a
90/// `Required` credential, so they never trigger an authentication flow on their
91/// own regardless of requirement.
92#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
93#[non_exhaustive]
94pub enum AuthRequirement {
95 /// The engine resolves the credential before the handler runs (fail-closed).
96 ///
97 /// A failure to resolve is rendered as an `auth-error` and the handler never
98 /// runs. This is the default.
99 #[default]
100 Required,
101 /// Resolution is deferred to the handler.
102 ///
103 /// The engine does not resolve a credential on the command's behalf; the
104 /// handler (or an authorizer) triggers the auth flow only by calling
105 /// [`CredentialResolver::resolve`]/[`try_resolve`](CredentialResolver::try_resolve).
106 /// Use for commands that behave differently when authenticated but must still
107 /// run when the user is logged out.
108 Optional,
109 /// The command never authenticates and has no credential.
110 ///
111 /// Equivalent to the legacy `no_auth(true)` marker: default-env injection is
112 /// suppressed and [`CredentialResolver::resolve`] returns an error.
113 None,
114}
115
116impl AuthRequirement {
117 /// Returns `true` when the command never authenticates.
118 #[must_use]
119 pub fn is_none(self) -> bool {
120 matches!(self, Self::None)
121 }
122
123 /// Returns `true` when the engine must resolve the credential before the handler runs.
124 #[must_use]
125 pub fn is_required(self) -> bool {
126 matches!(self, Self::Required)
127 }
128
129 /// Returns `true` when resolution is deferred to the handler.
130 #[must_use]
131 pub fn is_optional(self) -> bool {
132 matches!(self, Self::Optional)
133 }
134}
135
136/// Resolves the credential for a single command invocation, memoizing the result.
137///
138/// Resolution — including any interactive browser/OAuth flow — runs once for a
139/// given scope set: a handler and an authorizer that both ask share a single
140/// resolution, and the engine resolves it up front for
141/// [`AuthRequirement::Required`] commands. For [`Optional`](AuthRequirement::Optional)
142/// commands resolution is deferred until a handler or authorizer calls
143/// [`resolve`](Self::resolve) or [`try_resolve`](Self::try_resolve), and
144/// `--schema`/`--dry-run` short-circuit before any resolution happens.
145///
146/// [`resolve_with_scopes`](Self::resolve_with_scopes) may trigger an *additional*
147/// resolution when it needs scopes the memoized credential does not yet cover
148/// (OAuth scope step-up); a scope-aware provider then re-authenticates for the
149/// wider set. Resolutions are serialized, so concurrent callers never launch
150/// overlapping interactive flows.
151///
152/// The resolved credential is memoized: callers that need no new scopes share a
153/// single resolution. Clones share the same underlying state, so the engine can
154/// observe (via [`peek`](Self::peek)) whatever a handler resolved.
155#[derive(Clone)]
156pub struct CredentialResolver {
157 inner: Arc<ResolverInner>,
158}
159
160#[derive(Debug)]
161struct ResolverInner {
162 auth: Dispatcher,
163 provider: String,
164 env: String,
165 command_path: String,
166 tier: String,
167 no_auth: bool,
168 /// Static command metadata; `meta.scopes` are always requested.
169 meta: CommandMeta,
170 /// Authoritative resolved credential plus the scopes it was requested with.
171 /// Serializes concurrent resolution and lets scope step-up replace a
172 /// previously-resolved (narrower) credential.
173 state: Mutex<ResolveState>,
174 /// Write-once mirror of the first resolved credential so [`CredentialResolver::peek`]
175 /// can lend a reference without holding a lock. `peek` (used for audit/activity
176 /// identity) therefore reflects the *first* resolved credential and is not
177 /// replaced by a later step-up. That is sound because step-up is required to
178 /// re-authenticate the *same* identity: [`resolve_scopes`](CredentialResolver::resolve_scopes)
179 /// aborts if a step-up returns a different account, so the mirrored identity
180 /// always matches the identity that performed every action in the command.
181 cell: OnceCell<Credential>,
182}
183
184#[derive(Debug, Default)]
185struct ResolveState {
186 credential: Option<Credential>,
187 requested: Vec<String>,
188}
189
190impl std::fmt::Debug for CredentialResolver {
191 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192 formatter
193 .debug_struct("CredentialResolver")
194 .field("provider", &self.inner.provider)
195 .field("env", &self.inner.env)
196 .field("no_auth", &self.inner.no_auth)
197 .field("resolved", &self.inner.cell.get().is_some())
198 .finish_non_exhaustive()
199 }
200}
201
202impl CredentialResolver {
203 fn new(
204 auth: Dispatcher,
205 provider: String,
206 env: String,
207 command_path: String,
208 tier: String,
209 no_auth: bool,
210 meta: CommandMeta,
211 ) -> Self {
212 Self {
213 inner: Arc::new(ResolverInner {
214 auth,
215 provider,
216 env,
217 command_path,
218 tier,
219 no_auth,
220 meta,
221 state: Mutex::new(ResolveState::default()),
222 cell: OnceCell::new(),
223 }),
224 }
225 }
226
227 /// Resolves the credential, memoizing the result after the first success.
228 ///
229 /// # Errors
230 ///
231 /// Returns an error when the command is marked [`no_auth`](crate::CommandSpec::no_auth)
232 /// (such commands have no credential), or when the auth provider fails to
233 /// produce one.
234 pub async fn resolve(&self) -> Result<Credential> {
235 if self.inner.no_auth {
236 return Err(CliCoreError::message(
237 "command is marked no_auth and has no credential",
238 ));
239 }
240 self.resolve_scopes(&[]).await
241 }
242
243 /// Resolves a credential that additionally covers `extra` scopes (on top of
244 /// the command's declared [`CommandMeta::scopes`]).
245 ///
246 /// Used by handlers whose required scopes are only known at runtime (for
247 /// example a generic `api call` that derives scopes from the target
248 /// endpoint). A scope-aware auth provider re-authenticates when the cached
249 /// token does not already cover the requested set.
250 ///
251 /// # Ordering with the transport injector
252 ///
253 /// The HTTP transport's bearer injector resolves its token through the
254 /// provider's scope-*unaware* path and caches the first token it sees for the
255 /// injector's lifetime. So when a handler both steps up scopes and makes HTTP
256 /// calls through that injector, call `resolve_with_scopes` (or
257 /// [`CommandContext::credential_with_scopes`](crate::CommandContext::credential_with_scopes))
258 /// **before** the first request: that populates the provider cache with the
259 /// wider-scoped token, which the injector then picks up. Resolving after the
260 /// injector's first `inject` would send the narrower token.
261 ///
262 /// # Errors
263 ///
264 /// Returns an error when the command is marked
265 /// [`no_auth`](crate::CommandSpec::no_auth), or when the auth provider fails
266 /// to produce a credential.
267 pub async fn resolve_with_scopes(&self, extra: &[String]) -> Result<Credential> {
268 if self.inner.no_auth {
269 return Err(CliCoreError::message(
270 "command is marked no_auth and has no credential",
271 ));
272 }
273 self.resolve_scopes(extra).await
274 }
275
276 /// Shared resolution: returns the memoized credential when it already covers
277 /// the wanted scopes, otherwise (re)authenticates requesting the union and
278 /// updates the memoized credential.
279 async fn resolve_scopes(&self, extra: &[String]) -> Result<Credential> {
280 let inner = &self.inner;
281 let mut want = inner.meta.scopes.clone();
282 for scope in extra {
283 if !want.contains(scope) {
284 want.push(scope.clone());
285 }
286 }
287
288 let mut state = inner.state.lock().await;
289 if let Some(credential) = &state.credential
290 && want.iter().all(|scope| state.requested.contains(scope))
291 {
292 return Ok(credential.clone());
293 }
294
295 let mut requested = state.requested.clone();
296 for scope in &want {
297 if !requested.contains(scope) {
298 requested.push(scope.clone());
299 }
300 }
301 let mut meta = inner.meta.clone();
302 meta.set_scopes(requested.clone());
303 let req = CredentialRequest::new(&inner.env, &inner.command_path, &inner.tier, &meta);
304 let credential = inner
305 .auth
306 .get_credential_for(&inner.provider, &req)
307 .await
308 // Mark resolution failures so the engine can classify them as
309 // `auth-error` based on the error a handler actually returns.
310 .map_err(|source| auth_resolution_error(&inner.provider, source))?;
311 // Guard against a step-up that re-authenticates as a *different* identity.
312 // `peek` (audit/activity identity) reflects the first resolution, so a
313 // silent account switch would misattribute the elevated action. Abort
314 // rather than proceed under a mismatched identity.
315 if let Some(previous) = &state.credential {
316 let previous_key = identity_key(previous);
317 let new_key = identity_key(&credential);
318 if !previous_key.is_empty() && !new_key.is_empty() && previous_key != new_key {
319 return Err(CliCoreError::message(format!(
320 "scope step-up authenticated as a different identity \
321 (was {previous_key:?}, now {new_key:?}); aborting"
322 )));
323 }
324 }
325 state.credential = Some(credential.clone());
326 state.requested = requested;
327 // Mirror the first resolution for `peek`; ignored once already set.
328 drop(inner.cell.set(credential.clone()));
329 Ok(credential)
330 }
331
332 /// Resolves the credential when one is available.
333 ///
334 /// Returns `Ok(None)` for no-auth commands, `Ok(Some(_))` on success, and
335 /// propagates the provider error on failure. Use this for commands whose
336 /// auth is genuinely optional; most commands should call
337 /// [`resolve`](Self::resolve) instead.
338 ///
339 /// # Errors
340 ///
341 /// Propagates the auth provider error when resolution is attempted and fails.
342 pub async fn try_resolve(&self) -> Result<Option<Credential>> {
343 if self.inner.no_auth {
344 return Ok(None);
345 }
346 self.resolve().await.map(Some)
347 }
348
349 /// Returns the memoized credential without triggering resolution.
350 ///
351 /// Yields `None` until something resolves the credential. Used by the engine
352 /// to record identity in audit/activity output after a handler runs.
353 #[must_use]
354 pub fn peek(&self) -> Option<&Credential> {
355 self.inner.cell.get()
356 }
357}
358
359/// Marks a credential-resolution failure so its auth origin is detectable via
360/// [`CliCoreError::is_auth`], leaving errors that are already auth-typed
361/// unchanged. Display is preserved except for the `auth: provider …:` prefix that
362/// the [`AuthProvider`](CliCoreError::AuthProvider) wrapper adds.
363fn auth_resolution_error(provider: &str, source: CliCoreError) -> CliCoreError {
364 match source {
365 auth @ (CliCoreError::MissingAuthProvider(_) | CliCoreError::AuthProvider { .. }) => auth,
366 other => CliCoreError::AuthProvider {
367 provider: provider.to_owned(),
368 source: Box::new(other),
369 },
370 }
371}
372
373/// Stable identity discriminator for a credential: the subject (`sub`) when set,
374/// otherwise the human identity. Empty when the provider exposes neither, in
375/// which case the step-up identity guard cannot (and does not) compare.
376fn identity_key(credential: &Credential) -> &str {
377 if credential.sub.is_empty() {
378 credential.identity.as_str()
379 } else {
380 credential.sub.as_str()
381 }
382}
383
384#[async_trait]
385/// Authorization hook called before business logic.
386///
387/// The authorizer receives a [`CredentialResolver`] rather than an
388/// already-resolved credential so authorization remains lazy: an authorizer that
389/// does not need identity never triggers a credential/auth flow. Call
390/// [`CredentialResolver::try_resolve`] only when a decision actually depends on
391/// the credential.
392pub trait Authorizer: Send + Sync + std::fmt::Debug {
393 /// Verifies whether `command_path` may run with the provided args, reason, and tier.
394 async fn authorize(
395 &self,
396 command_path: &str,
397 args: &ValueMap,
398 credential: &CredentialResolver,
399 reason: &str,
400 tier: Tier,
401 ) -> Result<()>;
402}
403
404#[async_trait]
405/// Audit hook called for success, error, denied, auth-error, and dry-run outcomes.
406pub trait Auditor: Send + Sync + std::fmt::Debug {
407 /// Appends an audit record.
408 async fn append(
409 &self,
410 command_path: &str,
411 args: &ValueMap,
412 identity: &str,
413 result: &str,
414 reason: &str,
415 ) -> Result<()>;
416}
417
418#[async_trait]
419/// Activity hook for structured command lifecycle events.
420pub trait ActivityEmitter: Send + Sync + std::fmt::Debug {
421 /// Emits one completed command event.
422 async fn emit(&self, event: ActivityEvent) -> Result<()>;
423}
424
425/// Structured activity event emitted after command execution paths.
426#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
427pub struct ActivityEvent {
428 /// UTC timestamp in RFC3339 seconds format.
429 pub timestamp: String,
430 /// CLI application id.
431 pub app: String,
432 /// Colon-separated command path.
433 pub command: String,
434 /// Selected environment.
435 pub env: String,
436 /// Backend/system id.
437 pub backend: String,
438 /// Human identity from the resolved credential.
439 pub identity: String,
440 /// Subject identifier from the resolved credential.
441 pub sub: String,
442 /// Account type from the resolved credential.
443 pub account_type: String,
444 /// Outcome such as `ok`, `error`, `denied`, `auth-error`, or `dry-run`.
445 pub status: String,
446 /// Error message for failed outcomes.
447 pub error: String,
448 /// User-provided reason.
449 pub reason: String,
450 /// Effective command args.
451 pub args: ValueMap,
452 /// Command duration in milliseconds.
453 pub duration_ms: i64,
454 /// Reserved extension metadata.
455 pub meta: ValueMap,
456}
457
458/// Cross-cutting command execution state and dependencies.
459///
460/// Middleware is intentionally a plain, cloneable struct so tests and command
461/// handlers can inspect what will be used for a run. Application setup usually
462/// mutates it through `CliConfig` hooks or `ModuleContext`.
463#[derive(Clone, Debug, Default)]
464pub struct Middleware {
465 /// Optional authorization provider.
466 pub authz: Option<Arc<dyn Authorizer>>,
467 /// Auth provider dispatcher.
468 pub auth: Dispatcher,
469 /// Optional audit sink.
470 pub auditor: Option<Arc<dyn Auditor>>,
471 /// Optional activity sink.
472 pub activity: Option<Arc<dyn ActivityEmitter>>,
473 /// Application id used in output metadata.
474 pub app_id: String,
475 /// Fallback auth provider for commands without an explicit provider.
476 pub default_auth_provider: String,
477 /// Output format: `json`, `human`, or `toon`.
478 pub output_format: String,
479 /// Selected environment.
480 pub env: String,
481 /// Metadata verbosity selector.
482 pub verbose: String,
483 /// Whether mutating commands should short-circuit.
484 pub dry_run: bool,
485 /// User field projection.
486 pub fields: String,
487 /// JMESPath per-item list predicate.
488 pub filter: String,
489 /// JMESPath whole-result expression.
490 pub expr: String,
491 /// Client-side page size.
492 pub limit: i64,
493 /// Client-side page offset.
494 pub offset: i64,
495 /// User reason passed to authorization and audit.
496 pub reason: String,
497 /// Whether schema rendering was requested.
498 pub schema: bool,
499 /// Optional command deadline.
500 pub timeout: Option<Duration>,
501 /// Debug selector, interpreted by applications.
502 pub debug: String,
503 /// Search query, interpreted before command execution.
504 pub search: String,
505 /// Output schema registry.
506 pub schema_registry: SchemaRegistry,
507 /// Human output view registry.
508 pub human_views: HumanViewRegistry,
509 /// Loaded per-application config file, shared across the run.
510 ///
511 /// Populated once at startup from `<config-base>/<app_id>/config.toml`.
512 /// Command handlers read it via
513 /// [`CommandContext::config`](crate::command::CommandContext::config) and
514 /// module registration via
515 /// [`ModuleContext::config`](crate::module::ModuleContext::config).
516 pub config: Arc<crate::config::ConfigFile>,
517 /// Optional first-class environment system.
518 ///
519 /// Set by [`CliConfig::with_environments`](crate::CliConfig::with_environments)
520 /// and cloned into each per-run middleware snapshot. Handlers resolve the
521 /// active environment through
522 /// [`CommandContext::environment`](crate::command::CommandContext::environment).
523 pub environments: Option<Arc<crate::environments::Environments>>,
524}
525
526/// Rendered result produced by middleware.
527#[derive(Clone, Debug, PartialEq)]
528pub struct MiddlewareOutput {
529 /// Prepared output envelope.
530 pub envelope: Envelope,
531 /// Rendered output string.
532 pub rendered: String,
533 /// Process-style exit code.
534 pub exit_code: i32,
535}
536
537/// Inputs for one middleware-managed command execution.
538#[derive(Clone, Debug, PartialEq)]
539pub struct MiddlewareRequest<'request> {
540 /// Per-command metadata used by authentication, authorization, dry-run, audit, and activity.
541 pub meta: CommandMeta,
542 /// Colon-separated command path.
543 pub command_path: &'request str,
544 /// Backend/system id used in output metadata and generic error attribution.
545 pub system: &'request str,
546 /// Arguments explicitly supplied by the user.
547 pub user_args: ValueMap,
548 /// Effective arguments, including defaults.
549 pub args: ValueMap,
550 /// Default field projection when `--fields` is absent.
551 pub default_fields: &'request str,
552 /// Id of the human view this command declared, if any.
553 ///
554 /// The command path for an inline [`with_view`](crate::CommandSpec::with_view),
555 /// or the shared id from [`with_view_id`](crate::CommandSpec::with_view_id).
556 /// `None` renders generic human output.
557 pub view_id: Option<&'request str>,
558 /// Authentication requirement enforced by the engine for this command.
559 pub auth: AuthRequirement,
560}
561
562impl Middleware {
563 /// Creates middleware with empty registries and default dependencies.
564 #[must_use]
565 pub fn new() -> Self {
566 Self::default()
567 }
568
569 /// Runs the middleware chain for a command.
570 pub async fn run<F, Fut, Output>(
571 &self,
572 request: MiddlewareRequest<'_>,
573 command: F,
574 ) -> Result<MiddlewareOutput>
575 where
576 F: FnOnce(CredentialResolver) -> Fut + Send,
577 Fut: Future<Output = Result<Output>> + Send,
578 Output: Into<CommandResult>,
579 {
580 let start = Instant::now();
581 let MiddlewareRequest {
582 meta,
583 command_path,
584 system,
585 user_args,
586 mut args,
587 default_fields,
588 view_id,
589 auth,
590 } = request;
591 let no_auth = auth.is_none();
592 let command_system = effective_request_system(system, command_path);
593 if !no_auth && !self.env.is_empty() && !args.contains_key("env") {
594 args.insert("env".to_owned(), Value::String(self.env.clone()));
595 }
596
597 // Build a lazy resolver instead of resolving eagerly. No auth flow runs
598 // until a handler or authorizer actually asks for the credential, so
599 // commands that never use it (and `--schema`/`--dry-run`) skip auth.
600 let provider_name = meta
601 .provider()
602 .filter(|provider| !provider.is_empty())
603 .unwrap_or(&self.default_auth_provider)
604 .to_owned();
605 let resolved_env = meta.fixed_env().unwrap_or(&self.env).to_owned();
606 let tier_text = meta
607 .auth_metadata
608 .get("tier")
609 .map_or("", String::as_str)
610 .to_owned();
611 let resolver = CredentialResolver::new(
612 self.auth.clone(),
613 provider_name.clone(),
614 resolved_env,
615 command_path.to_owned(),
616 tier_text,
617 no_auth,
618 meta.clone(),
619 );
620
621 if no_auth
622 && let Some(output) =
623 self.render_schema_if_requested(command_path, start, &user_args, &args, "")?
624 {
625 return Ok(output);
626 }
627
628 if let Some(authz) = &self.authz
629 && let Err(err) = authz
630 .authorize(command_path, &args, &resolver, &self.reason, meta.tier())
631 .await
632 {
633 // An authorizer may have resolved the credential to make its
634 // decision; reflect whatever it resolved in audit identity.
635 let identity = resolver.peek().map_or("", |cred| cred.identity.as_str());
636 // Classify by the error the authorizer returned: a propagated
637 // resolution failure is auth-typed; a policy denial is not.
638 let had_auth_error = err.is_auth();
639 let result_tag = if had_auth_error {
640 "auth-error"
641 } else {
642 "denied"
643 };
644 // Attribute auth-provider failures to the provider so telemetry can
645 // distinguish them from command backends.
646 let backend = if had_auth_error {
647 provider_name.as_str()
648 } else {
649 command_path
650 };
651 self.write_audit(command_path, &args, identity, result_tag)
652 .await;
653 self.emit_activity(
654 command_path,
655 &args,
656 resolver.peek(),
657 result_tag,
658 backend,
659 &err.to_string(),
660 start,
661 )
662 .await;
663 return self.render_error(&err, command_path, start, &user_args, &args, identity);
664 }
665
666 // If the authorizer resolved the credential, include its identity in the
667 // schema output metadata. `peek()` never triggers resolution, so schema
668 // still doesn't provoke auth on its own.
669 let schema_identity = resolver.peek().map_or("", |cred| cred.identity.as_str());
670 if let Some(output) = self.render_schema_if_requested(
671 command_path,
672 start,
673 &user_args,
674 &args,
675 schema_identity,
676 )? {
677 return Ok(output);
678 }
679
680 if self.dry_run && meta.dry_run_prompt {
681 let identity = resolver.peek().map_or("", |cred| cred.identity.as_str());
682 self.write_audit(command_path, &args, identity, "dry-run")
683 .await;
684 self.emit_activity(
685 command_path,
686 &args,
687 resolver.peek(),
688 "dry-run",
689 command_path,
690 "",
691 start,
692 )
693 .await;
694 let envelope = Envelope::success(
695 json!({
696 "command": command_path,
697 "action": "dry-run: would execute",
698 }),
699 command_path,
700 )
701 .with_dry_run();
702 return self.render_envelope(
703 envelope,
704 "",
705 "",
706 command_path,
707 start,
708 &user_args,
709 &args,
710 identity,
711 );
712 }
713
714 // Fail closed by default: for `Required` commands the engine resolves the
715 // credential before the handler runs, so a command that must be
716 // authenticated cannot execute unauthenticated even if its handler never
717 // reads the credential, and its audit/activity identity is always
718 // populated. `--schema`/`--dry-run` return above, so they never reach this
719 // point; `Optional`/`None` commands defer resolution to the handler.
720 if auth.is_required()
721 && let Err(err) = resolver.resolve().await
722 {
723 // Mirror the handler-path auth-error treatment: classify as
724 // `auth-error` and attribute the activity backend to the auth provider
725 // so telemetry can distinguish auth-provider failures from command
726 // backends. Resolution failed, so there is no identity to record.
727 self.write_audit(command_path, &args, "", "auth-error")
728 .await;
729 self.emit_activity(
730 command_path,
731 &args,
732 resolver.peek(),
733 "auth-error",
734 provider_name.as_str(),
735 &err.to_string(),
736 start,
737 )
738 .await;
739 return self.render_error(&err, command_path, start, &user_args, &args, "");
740 }
741
742 let result = match command(resolver.clone()).await {
743 Ok(result) => result.into(),
744 Err(err) => {
745 // A deferred `resolve()` failure surfaces as a handler error;
746 // classify it as `auth-error` when the error the handler returned
747 // is itself auth-typed. A handler that swallows a resolution
748 // failure and then fails for another reason returns a non-auth
749 // error here, so it is not misclassified.
750 let identity = resolver.peek().map_or("", |cred| cred.identity.as_str());
751 let (result_tag, error_system, activity_backend) = if err.is_auth() {
752 // Render against the command path, but attribute the activity
753 // backend to the auth provider so telemetry can distinguish
754 // auth-provider failures from command backends.
755 ("auth-error", command_path, provider_name.as_str())
756 } else {
757 let system = err.system().unwrap_or(&command_system);
758 ("error", system, system)
759 };
760 self.write_audit(command_path, &args, identity, result_tag)
761 .await;
762 self.emit_activity(
763 command_path,
764 &args,
765 resolver.peek(),
766 result_tag,
767 activity_backend,
768 &err.to_string(),
769 start,
770 )
771 .await;
772 return self.render_error(&err, error_system, start, &user_args, &args, identity);
773 }
774 };
775 // The handler may have resolved the credential; surface its identity.
776 let identity = resolver.peek().map_or("", |cred| cred.identity.as_str());
777 self.write_audit(command_path, &args, identity, "ok").await;
778 self.emit_activity(
779 command_path,
780 &args,
781 resolver.peek(),
782 "ok",
783 &command_system,
784 "",
785 start,
786 )
787 .await;
788
789 let CommandResult { data, metadata } = result;
790 self.render_envelope(
791 Envelope::success(data, command_system).with_next_actions(metadata.next_actions),
792 default_fields,
793 view_id.unwrap_or_default(),
794 command_path,
795 start,
796 &user_args,
797 &args,
798 identity,
799 )
800 }
801
802 #[doc(hidden)]
803 pub async fn run_no_auth<F, Fut>(
804 &self,
805 meta: CommandMeta,
806 command_path: &str,
807 user_args: ValueMap,
808 args: ValueMap,
809 default_fields: &str,
810 command: F,
811 ) -> Result<MiddlewareOutput>
812 where
813 F: FnOnce() -> Fut + Send,
814 Fut: Future<Output = Result<CommandResult>> + Send,
815 {
816 self.run(
817 MiddlewareRequest {
818 meta,
819 command_path,
820 system: fallback_system(command_path),
821 user_args,
822 args,
823 default_fields,
824 view_id: None,
825 auth: AuthRequirement::None,
826 },
827 async move |_resolver| command().await,
828 )
829 .await
830 }
831
832 async fn write_audit(&self, command_path: &str, args: &ValueMap, identity: &str, result: &str) {
833 if let Some(auditor) = &self.auditor
834 && let Err(err) = auditor
835 .append(command_path, args, identity, result, &self.reason)
836 .await
837 {
838 tracing::warn!(command = command_path, error = %err, "audit log write failed");
839 }
840 }
841
842 #[allow(clippy::too_many_arguments)]
843 async fn emit_activity(
844 &self,
845 command_path: &str,
846 args: &ValueMap,
847 credential: Option<&Credential>,
848 result: &str,
849 backend: &str,
850 error: &str,
851 start: Instant,
852 ) {
853 let Some(activity) = &self.activity else {
854 return;
855 };
856 let (identity, sub, account_type) = credential.map_or_else(
857 || (String::new(), String::new(), String::new()),
858 |credential| {
859 (
860 credential.identity.clone(),
861 credential.sub.clone(),
862 credential.account_type.clone(),
863 )
864 },
865 );
866 let duration_ms = i64::try_from(start.elapsed().as_millis()).unwrap_or(i64::MAX);
867 let event = ActivityEvent {
868 timestamp: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
869 app: self.app_id.clone(),
870 command: command_path.to_owned(),
871 env: self.env.clone(),
872 backend: backend.to_owned(),
873 identity,
874 sub,
875 account_type,
876 status: result.to_owned(),
877 error: error.to_owned(),
878 reason: self.reason.clone(),
879 args: args.clone(),
880 duration_ms,
881 meta: ValueMap::new(),
882 };
883 if let Err(err) = activity.emit(event).await {
884 tracing::warn!(command = command_path, error = %err, "activity emit failed");
885 }
886 }
887
888 fn render_schema_if_requested(
889 &self,
890 command_path: &str,
891 start: Instant,
892 user_args: &ValueMap,
893 effective_args: &ValueMap,
894 identity: &str,
895 ) -> Result<Option<MiddlewareOutput>> {
896 if self.schema {
897 // Registered schema: dump it. Otherwise don't silently run the
898 // command — report that no schema exists. (We deliberately don't
899 // suggest "run it with --fields all" here: that would execute the
900 // command, which is exactly wrong for a mutation.)
901 let envelope = match self.schema_registry.get_by_path(command_path) {
902 Some(schema) => Envelope::success(schema, self.app_id.clone()),
903 // Shared with the `Cli::run` `--schema` bypass so both paths emit
904 // an identical no-schema body: the same `{command, fields}` shape
905 // as a real SchemaInfo response (empty `fields`) plus an additive
906 // `message`.
907 None => Envelope::success(
908 crate::output::no_schema_response(command_path),
909 self.app_id.clone(),
910 ),
911 };
912 return self
913 .render_envelope(
914 envelope,
915 "",
916 "",
917 command_path,
918 start,
919 user_args,
920 effective_args,
921 identity,
922 )
923 .map(Some);
924 }
925 Ok(None)
926 }
927
928 #[allow(clippy::too_many_arguments)]
929 fn render_envelope(
930 &self,
931 mut envelope: Envelope,
932 default_fields: &str,
933 view_id: &str,
934 command_path: &str,
935 start: Instant,
936 user_args: &ValueMap,
937 effective_args: &ValueMap,
938 identity: &str,
939 ) -> Result<MiddlewareOutput> {
940 if !is_valid_output_format(&self.output_format) {
941 let err = CliCoreError::InvalidOutputFormat(self.output_format.clone());
942 return self.render_error(
943 &err,
944 &self.app_id,
945 start,
946 user_args,
947 effective_args,
948 identity,
949 );
950 }
951 let output_format = self.output_format.parse::<OutputFormat>()?;
952 // The effective field selection: an explicit `--fields` wins, otherwise
953 // the command's `default_fields` is the default. The same selection is
954 // applied two ways. With a registered human view, it narrows which of the
955 // view's columns show, so the view reads the full payload — the data is
956 // not projected, which would otherwise blank out the kept columns.
957 // Everywhere else (JSON/TOON, or generic human output) it projects the
958 // output data. Empty / `all` / `*` keeps everything.
959 let effective_fields = if self.fields.is_empty() {
960 default_fields
961 } else {
962 self.fields.as_str()
963 };
964 let human_view = output_format == OutputFormat::Human && self.human_views.has_view(view_id);
965 let projection_fields = if human_view { "" } else { effective_fields };
966 if let Some(data) = &mut envelope.data {
967 let pagination = apply_pipeline(
968 data,
969 &PipelineOpts {
970 filter: self.filter.clone(),
971 limit: self.limit,
972 offset: self.offset,
973 expr: self.expr.clone(),
974 fields: projection_fields.to_owned(),
975 },
976 )?;
977 if let Some(pagination) = pagination
978 && let Some(metadata) = &mut envelope.metadata
979 {
980 metadata.pagination = Some(pagination);
981 }
982 }
983 envelope.with_context(
984 command_path,
985 &self.env,
986 identity,
987 start.elapsed(),
988 Some(Value::Object(user_args.clone())),
989 Some(Value::Object(effective_args.clone())),
990 );
991 let prepared = envelope.prepare_for_render(&self.verbose);
992 let rendered = if output_format == OutputFormat::Human {
993 render_human_with_registry_selected(
994 &prepared,
995 &self.human_views,
996 view_id,
997 effective_fields,
998 )
999 } else {
1000 crate::output::render(output_format, &prepared)?
1001 };
1002 Ok(MiddlewareOutput {
1003 envelope: prepared,
1004 rendered,
1005 exit_code: 0,
1006 })
1007 }
1008
1009 fn render_error(
1010 &self,
1011 err: &(dyn std::error::Error + 'static),
1012 system: &str,
1013 start: Instant,
1014 user_args: &ValueMap,
1015 effective_args: &ValueMap,
1016 identity: &str,
1017 ) -> Result<MiddlewareOutput> {
1018 let mut envelope = build_error_envelope(err, system);
1019 envelope.with_context(
1020 "",
1021 &self.env,
1022 identity,
1023 start.elapsed(),
1024 Some(Value::Object(user_args.clone())),
1025 Some(Value::Object(effective_args.clone())),
1026 );
1027 let prepared = envelope.prepare_for_render(&self.verbose);
1028 let rendered = crate::output::render_format(&self.output_format, &prepared)?;
1029 Ok(MiddlewareOutput {
1030 envelope: prepared,
1031 rendered,
1032 exit_code: exit_code_for_error(err),
1033 })
1034 }
1035}
1036
1037/// Convenience helper for building a JSON object map.
1038#[must_use]
1039pub fn value_map(entries: impl IntoIterator<Item = (impl Into<String>, Value)>) -> ValueMap {
1040 entries
1041 .into_iter()
1042 .map(|(key, value)| (key.into(), value))
1043 .collect()
1044}
1045
1046fn effective_request_system(system: &str, command_path: &str) -> String {
1047 if system.is_empty() {
1048 return fallback_system(command_path).to_owned();
1049 }
1050 system.to_owned()
1051}
1052
1053fn fallback_system(command_path: &str) -> &str {
1054 command_path
1055 .split_once(':')
1056 .map_or(command_path, |(system, _)| system)
1057}
1058
1059impl From<CliCoreError> for Value {
1060 fn from(error: CliCoreError) -> Self {
1061 Value::String(error.to_string())
1062 }
1063}
1064
1065#[cfg(test)]
1066mod env_wire_tests {
1067 use super::*;
1068
1069 #[test]
1070 fn middleware_carries_optional_environments() {
1071 use std::sync::Arc;
1072 let mut mw = Middleware::new();
1073 assert!(mw.environments.is_none());
1074 mw.environments = Some(Arc::new(crate::environments::Environments::new("prod")));
1075 assert_eq!(
1076 mw.environments
1077 .as_ref()
1078 .map(|envs| envs.default_env().to_owned()),
1079 Some("prod".to_owned())
1080 );
1081 }
1082}