Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 53 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ schemars = { version = "1.2.1", features = ["derive"] }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.145"
thiserror = "2.0.17"
toml_edit = { version = "0.22", features = ["serde"] }
tokio = { version = "1.48.0", features = ["fs", "io-std", "io-util", "macros", "net", "process", "rt-multi-thread", "signal", "sync", "time"] }
tracing = "0.1.43"

Expand Down
29 changes: 27 additions & 2 deletions docs/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,7 @@ The provider manages the full browser-based login flow:
2. Starts a local TCP server on `127.0.0.1` to receive the OAuth callback.
3. Opens the system browser to the authorization endpoint.
4. Exchanges the returned code for tokens at the token endpoint.
5. Stores tokens in the system keychain via the `keyring` crate (macOS Keychain, Linux Secret
Service, or the platform's encrypted file fallback).
5. Persists tokens through a `CredentialStorage` backend (the system keychain by default; see [Credential Storage](#credential-storage)).
6. Refreshes expired tokens automatically using the stored refresh token.

```rust
Expand Down Expand Up @@ -232,6 +231,32 @@ values. The prefix is the provider name uppercased with hyphens replaced by unde
For a provider named `"primary"`, the variables are `PRIMARY_OAUTH_CLIENT_ID`,
`PRIMARY_OAUTH_AUTH_URL`, and `PRIMARY_OAUTH_TOKEN_URL`.

## Credential Storage

Tokens are persisted through the injectable `CredentialStorage` trait rather than a hard-wired keychain. Each credential is keyed by `CredentialKey { app_id, provider, env }`. Three built-in backends correspond to the `CredentialStore` modes:

- **`keyring`** (`KeyringStorage`, default) — system keychain only (macOS Keychain, Linux Secret Service, Windows Credential Manager). A keychain failure is a hard error; no file is written.
- **`auto`** (`AutoStorage`) — try the keychain, and transparently fall back to an unencrypted file when the keychain backend is unavailable.
- **`file`** (`FileStorage`) — never contact the keychain. Tokens are written as **unencrypted JSON** to `<config-base>/<app_id>/credentials/<provider>-<env>.json` (`0600` on Unix), where `<config-base>` is `$XDG_CONFIG_HOME`, `$HOME/.config`, or `%APPDATA%`.

### Selecting a mode

`file` is the recommended escape hatch on **WSL and headless Linux**, where a Secret Service daemon is often missing or awkward to run. Operators can disable the keychain without code changes, with this precedence (highest first):

1. `PkceAuthProvider::with_storage(...)` — inject a custom backend, or `PkceAuthProvider::with_credential_store(CredentialStore::File)` — force a built-in mode.
2. `--credential-store auto|keyring|file` global flag.
3. `${PREFIX}_CREDENTIAL_STORE` env var (e.g. `MY_CLI_CREDENTIAL_STORE=file`), where `${PREFIX}` is the **app id** uppercased with non-alphanumerics replaced by `_`.
4. `[credentials].store` in `<config-base>/<app_id>/config.toml`:
```toml
[credentials]
store = "file"
```
5. Default: `keyring`.

> The escape-hatch trade-off: `file`/`auto` write credentials to disk **unencrypted** (owner-only permissions on Unix). Prefer the keychain where one is available.

`with_file_fallback(bool)` is deprecated: `true` maps to `CredentialStore::Auto` and `false` to `CredentialStore::Keyring`. Use `with_credential_store` instead.

## Dispatcher

[`Dispatcher`](../src/auth/dispatcher.rs) routes auth calls by provider name:
Expand Down
68 changes: 64 additions & 4 deletions docs/concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,7 @@ Auth providers implement the `AuthProvider` trait. Providers expose credential r
status, logout, and environment-listing behavior. The framework includes:

- `ExecProvider`, which invokes an external provider command using JSON stdin/stdout.
- `PkceAuthProvider` (requires the `pkce-auth` feature), a built-in browser-based OAuth 2.0 PKCE
flow that manages the local callback server, opens the system browser, and persists tokens in the
system keychain via the `keyring` crate. Auth URL, token URL, and client ID can be overridden via
environment variables at runtime.
- `PkceAuthProvider` (requires the `pkce-auth` feature), a built-in browser-based OAuth 2.0 PKCE flow that manages the local callback server, opens the system browser, and persists tokens through a pluggable credential-storage backend (system keychain by default). Auth URL, token URL, and client ID can be overridden via environment variables at runtime.
- A `Dispatcher` that routes auth calls by provider name. Single-provider facades created from the
dispatcher remain live views of the dispatcher, so transport injectors observe later provider
registration or replacement.
Expand All @@ -331,6 +328,69 @@ Command handlers receive `Option<Credential>`. No-auth commands receive `None`.
Provider process contracts and request injectors are described in
[Authentication and Transport](auth.md).

## Credential Storage

Auth providers persist credentials through the injectable `CredentialStorage` trait (`auth::storage`), keyed by `CredentialKey { app_id, provider, env }`. Three built-in backends map to the `CredentialStore` modes:

| Mode | Backend | Behavior |
| --- | --- | --- |
| `keyring` (default) | `KeyringStorage` | System keychain only; failure is a hard error. |
| `auto` | `AutoStorage` | Keychain, with a transparent unencrypted-file fallback when the keychain backend is unavailable. |
| `file` | `FileStorage` | Never contacts the keychain; stores unencrypted JSON under the config base directory. |

`File` is the escape hatch for environments where the system keychain is unavailable or impractical (headless Linux, WSL). The selected mode is resolved with the precedence:

```text
PkceAuthProvider::with_storage / with_credential_store (explicit, highest)
> --credential-store flag
> ${PREFIX}_CREDENTIAL_STORE env var
> [credentials].store in config.toml
> keyring (default)
```

where `${PREFIX}` is the app id uppercased with non-alphanumerics replaced by `_` (e.g. `godaddy` → `GODADDY_CREDENTIAL_STORE`). Providers resolve their backend lazily, so `--schema` and `--dry-run` build no storage and never touch the keychain. A custom backend (for example an in-memory store in tests, or a remote secret manager) can be injected with `PkceAuthProvider::with_storage`.

## Configuration File

cli-engine provides a single per-application TOML config file that **consumer CLIs share with the engine**. It lives at `<config-base>/<app_id>/config.toml`, where `<config-base>` is `$XDG_CONFIG_HOME`, `$HOME/.config`, or `%APPDATA%`. Loading is best-effort: a missing/unreadable/malformed file yields an empty config (a warning is logged for malformed) rather than failing the
command.

Engine-reserved settings live in documented top-level tables (today just `[credentials]`); the consumer CLI owns **every other top-level table**:

```toml
[credentials] # engine-reserved
store = "file" # "auto" | "keyring" | "file"

[deploy] # consumer-owned
region = "us-west"
```

### Reading config

The loaded file is exposed as a `ConfigFile` and surfaced everywhere it's useful — `toml` stays an internal detail, so access is typed:

- In command handlers: `ctx.config().section::<DeployConfig>("deploy")?`
- In module registration: `module_ctx.config().section::<T>(...)`
- Engine-reserved view: `ConfigFile::engine() -> EngineConfig`
- Whole-file into a consumer root type: `ConfigFile::deserialize::<T>()`

The file is loaded once at startup and cloned into each run's middleware, so reads are cheap.

### Writing config (`config` command group)

`CliConfig::with_config_commands()` mounts a built-in `config` group (filed under the admin help category), opt-in so it never collides with a consumer's own `config` noun:

```text
mycli config path # print the file path
mycli config get deploy.region # read a dotted key
mycli config set deploy.region us-east # set + save (mutating; --dry-run aware)
mycli config list # print the whole file
```

`config set` is dry-run aware, parses the value as a bool/int/float when it looks like one (else a string), preserves existing comments and formatting (backed by `toml_edit`), and validates the engine-reserved `credentials.store` key. Programmatically, `ConfigFile::set` + `ConfigFile::save` do the same.

The `config` module also exposes `load`, `resolve_credential_store`, and the pure `resolve_credential_store_with` for testing credential-store precedence without touching process state.

## Authorization

Authorization is provided by an `Authorizer` attached to middleware. The authorizer receives:
Expand Down
5 changes: 5 additions & 0 deletions src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ pub mod exec;
/// OAuth 2.0 PKCE auth provider (requires the `pkce-auth` feature).
#[cfg(feature = "pkce-auth")]
pub mod pkce;
/// Pluggable credential storage backends (keychain, file, auto).
pub mod storage;

use async_trait::async_trait;

Expand All @@ -32,6 +34,9 @@ pub use exec::{
ACTION_AUTHENTICATE, ACTION_LIST_ENVIRONMENTS, ACTION_LIST_REALMS, ACTION_LOGOUT,
ACTION_STATUS, AuthnRequest, EnvironmentsResponse, ExecProvider,
};
#[cfg(feature = "pkce-auth")]
pub use storage::{AutoStorage, KeyringStorage};
pub use storage::{CredentialKey, CredentialStorage, FileStorage, default_storage, storage_for};

use crate::Result;
use crate::middleware::CommandMeta;
Expand Down
Loading