Skip to main content

cli_engine/auth/
mod.rs

1//! Auth provider abstraction and built-in auth helpers.
2//!
3//! Consumer CLIs normally register one or more [`AuthProvider`] implementations
4//! with [`crate::CliConfig`]. Middleware then resolves credentials before
5//! business logic runs and passes a [`Credential`] to command handlers.
6//!
7//! The module also contains an [`crate::auth::exec::ExecProvider`] for provider
8//! binaries that speak the JSON stdin/stdout contract.
9//!
10//! When the `pkce-auth` feature is enabled, `pkce::PkceAuthProvider` adds a
11//! built-in browser-based OAuth 2.0 PKCE flow with system keychain storage.
12
13/// Built-in `auth login`, `auth status`, and `auth logout` command helpers.
14pub mod commands;
15mod credential;
16mod dispatcher;
17/// External process auth provider implementation.
18pub mod exec;
19/// OAuth 2.0 PKCE auth provider (requires the `pkce-auth` feature).
20#[cfg(feature = "pkce-auth")]
21pub mod pkce;
22
23use async_trait::async_trait;
24
25pub use commands::{
26    AuthLoginResult, AuthStatusEntry, auth_command_group, login_and_build,
27    login_and_build_with_scopes, logout_result, status_result, to_status_entry,
28};
29pub use credential::{CACHE_TTL, Credential};
30pub use dispatcher::{Dispatcher, SingleProvider, StatusEntry};
31pub use exec::{
32    ACTION_AUTHENTICATE, ACTION_LIST_ENVIRONMENTS, ACTION_LIST_REALMS, ACTION_LOGOUT,
33    ACTION_STATUS, AuthnRequest, EnvironmentsResponse, ExecProvider,
34};
35
36use crate::Result;
37use crate::middleware::CommandMeta;
38
39/// Everything an [`AuthProvider`] may inspect about the command requesting a
40/// credential.
41///
42/// This bundles the routing fields passed to [`AuthProvider::get_credential`]
43/// (`env`, colon command path, and tier) together with the command's
44/// [`CommandMeta`], so a provider can read richer metadata — for example an
45/// OAuth provider reading [`CommandMeta::scopes`] to decide whether the cached
46/// token is sufficient. Providers that do not need metadata can ignore it.
47///
48/// Marked `#[non_exhaustive]` because the framework constructs it (providers only
49/// read it) and more request fields may be added over time; build one with
50/// [`CredentialRequest::new`] rather than a struct literal so adding a field is
51/// not a breaking change for downstream crates.
52#[derive(Clone, Copy, Debug)]
53#[non_exhaustive]
54pub struct CredentialRequest<'req> {
55    /// Target environment name.
56    pub env: &'req str,
57    /// Colon-separated command path, for example `project:list`.
58    pub command: &'req str,
59    /// Risk tier as a string, for example `read` or `mutate`.
60    pub tier: &'req str,
61    /// Metadata for the command requesting the credential.
62    pub meta: &'req CommandMeta,
63}
64
65impl<'req> CredentialRequest<'req> {
66    /// Creates a request from the routing fields and command metadata.
67    #[must_use]
68    pub fn new(
69        env: &'req str,
70        command: &'req str,
71        tier: &'req str,
72        meta: &'req CommandMeta,
73    ) -> Self {
74        Self {
75            env,
76            command,
77            tier,
78            meta,
79        }
80    }
81}
82
83#[async_trait]
84/// Named auth provider used by middleware and transport injectors.
85///
86/// Implementations own their credential cache strategy. The framework only
87/// routes calls and passes command context (`env`, colon command path, and tier).
88pub trait AuthProvider: Send + Sync + std::fmt::Debug {
89    /// Stable provider registration name, for example `primary` or `oauth`.
90    fn name(&self) -> &str;
91
92    /// Returns a credential for `env`, `command`, and `tier`.
93    async fn get_credential(&self, env: &str, command: &str, tier: &str) -> Result<Credential>;
94
95    /// Returns a credential for a command, given its full [`CredentialRequest`].
96    ///
97    /// The default implementation ignores the metadata and delegates to
98    /// [`get_credential`](AuthProvider::get_credential). Providers that act on
99    /// command metadata — such as an OAuth provider performing scope step-up
100    /// from [`CommandMeta::scopes`] — override this. The framework calls this
101    /// method (not `get_credential`) when resolving credentials, so an override
102    /// receives the command's metadata.
103    async fn get_credential_for(&self, req: &CredentialRequest<'_>) -> Result<Credential> {
104        self.get_credential(req.env, req.command, req.tier).await
105    }
106
107    /// Returns cached credential status for one environment.
108    async fn status(&self, env: &str) -> Result<Credential>;
109
110    /// Clears cached credentials for one environment.
111    async fn logout(&self, env: &str) -> Result<()>;
112
113    /// Lists environments with cached credentials.
114    async fn list_environments(&self) -> Result<Vec<String>>;
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    fn credential_request_new_sets_all_fields() {
123        let meta = CommandMeta::default();
124        let req = CredentialRequest::new("dev", "app:list", "read", &meta);
125        assert_eq!(req.env, "dev");
126        assert_eq!(req.command, "app:list");
127        assert_eq!(req.tier, "read");
128        // `Copy` is preserved (using `req` after copying it must compile).
129        let copy = req;
130        assert_eq!(copy.env, req.env);
131    }
132}