From da71811b0c7015aaa221bde68908bcf30c0b65da Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Tue, 17 Nov 2026 18:31:00 +0000 Subject: [PATCH 01/11] feat: report remaining usage from Codex app-server --- README.md | 2 +- docs/commands.md | 2 +- docs/plans/cli-spec.md | 29 +- plans/codex-app-server-usage-integration.md | 141 +++++ src/cli/args.rs | 17 +- src/cli/commands/usage.rs | 533 ++++++++++++++++-- src/provider/usage/codex_app_server.rs | 594 ++++++++++++++++++++ src/provider/usage/mod.rs | 1 + src/provider/usage/openai.rs | 24 +- tests/fixtures/codex_app_server.rs | 196 +++++++ 10 files changed, 1452 insertions(+), 87 deletions(-) create mode 100644 plans/codex-app-server-usage-integration.md create mode 100644 src/provider/usage/codex_app_server.rs create mode 100644 tests/fixtures/codex_app_server.rs diff --git a/README.md b/README.md index 2bb87a9..d5a72a4 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ cleared when the daemon stops. | `eggpass login` | Sign in to a provider. | | `eggpass logout` | Revoke and remove a provider credential. | | `eggpass status` | Show provider login and server state. | -| `eggpass usage` | Read subscription usage where available. | +| `eggpass usage` | Show remaining subscription usage where available. | | `eggpass run` | Start the server. Use `--foreground` to keep it in the terminal. | | `eggpass stop` / `restart` | Stop or restart the server. | | `eggpass port` / `host` | Show or change the listen address. Changes restart the server. | diff --git a/docs/commands.md b/docs/commands.md index 4727d28..e519921 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -66,7 +66,7 @@ eggpass usage --provider xai # query one provider eggpass usage --json # machine-readable report ``` -Queries provider usage directly, without needing the daemon. This is a fresh request, not a cached or polled reading. The report describes usage as reported by each provider. On the default xAI `api` upstream, the reported consumer-subscription quota is separate from inference requests, which are billed to the xAI API tier. The report's caption reflects the configured upstream. If quota is unavailable, the report may include the latest inference HTTP status kept by the daemon in memory. That endpoint reports only per-provider client-facing HTTP status codes, not prompts or response bodies. +Queries provider usage directly, without needing the daemon. This is a fresh request, not a cached or polled reading. Human-readable output shows the percentage and bar for the allowance left, plus each available reset time and countdown; JSON preserves the provider-reported fields. On the default xAI `api` upstream, the reported consumer-subscription quota is separate from inference requests, which are billed to the xAI API tier. The report's caption reflects the configured upstream. If quota is unavailable, the report may include the latest inference HTTP status kept by the daemon in memory. That endpoint reports only per-provider client-facing HTTP status codes, not prompts or response bodies. **Exit codes:** `0` if at least one provider is signed in and not every selected provider failed operationally, `1` if every selected provider failed operationally, `2` if none is signed in. diff --git a/docs/plans/cli-spec.md b/docs/plans/cli-spec.md index bf564f4..6c6312e 100644 --- a/docs/plans/cli-spec.md +++ b/docs/plans/cli-spec.md @@ -658,7 +658,7 @@ be read or written, or the arguments were wrong. ## `eggpass usage` -Report how much of the subscription allowance is used. +Report how much of the subscription allowance remains. ``` eggpass usage # every provider you are signed in to @@ -690,9 +690,9 @@ between blocks, no colour: ``` x.ai · SuperGrok - Weekly ████░░░░░░░░░░░░░░░░ 20% used - Resets Nov 20, 03:07 (UTC) - Api ██░░░░░░░░░░░░░░░░░░ 10% used + Weekly ████████████████░░░░ 80% left + Resets Nov 20, 03:07 (UTC) · in 2d 15hr + Api ██████████████████░░ 90% left Prepaid $0.00 This is your Grok subscription. `eggpass` requests are billed separately against the xAI API tier. @@ -710,18 +710,25 @@ ChatGPT - **The label column is twelve characters wide**, so every value starts in the same place. -- **The bar is twenty cells**, `█` filled and `░` empty. A non-zero - percentage always shows at least one cell, and the bar is omitted entirely - when the percentage is unavailable. -- **The number is the amount *used*.** It reads `20% used`, never `20% left`. +- **The bar is twenty cells**, `█` filled and `░` empty. It represents the + allowance left; a non-zero remainder always shows at least one cell, and the + bar is omitted entirely when the percentage is unavailable. +- **The number is the amount remaining.** It reads `80% left`. The JSON report + still preserves the provider's `used_percent` field unchanged. - **Missing is not zero.** The Grok billing endpoint is proto3 JSON and omits zero-valued scalars, so an absent percentage means the provider did not - say. It reads `unavailable`, never `0% used`. + say. It reads `unavailable`, never `0% left`. +- **A supplied duration labels its window**, such as `5-hour` or `7-day`, in + place of a generic `Primary` or `Secondary` label. Multiple Codex buckets keep + their bucket names when needed to distinguish otherwise identical windows. + A window is not invented when the provider does not report it, and there is + no separate Duration row. - **An explicit state replaces the percentage.** When the provider says the account is not eligible, that is the answer and no number is shown. - **The reset time is local**, with its offset, because `Nov 18, 09:00` alone - is ambiguous. The year appears only when it differs from the current year. - A reset more than an hour in the past is marked `(stale)`. + is ambiguous. Future resets also show a compact countdown (for example, + `in 3hr 21m` or `in 3d 15hr`); the year appears only when it differs from + the current year. A reset more than an hour in the past is marked `(stale)`. - **The caption is not optional.** On the default `api` upstream, `eggpass`'s inference is metered against the xAI API tier and does **not** draw from the consumer subscription the billing endpoint reports. The caption says diff --git a/plans/codex-app-server-usage-integration.md b/plans/codex-app-server-usage-integration.md new file mode 100644 index 0000000..a3aebb0 --- /dev/null +++ b/plans/codex-app-server-usage-integration.md @@ -0,0 +1,141 @@ +# Codex App-Server Usage Integration — Implementation Plan + +**Status:** Implementation complete. Formatting, Clippy, and all 394 workspace tests pass on macOS; the fake app-server covers the documented stdio flow without a live Codex account. Human-readable usage shows remaining percentages, provider-supplied window durations, and reset countdowns. A Windows MSVC cross-check was attempted but could not compile the existing `ring` C dependency because this macOS host lacks Windows C headers. + +**Scope:** Add an optional, local Codex app-server source for `eggpass usage` only. The existing Sign in with ChatGPT (SIWC) OAuth mechanism remains the sole authentication mechanism for Eggpass inference and is not changed by this work. + +**Research checked:** 2026-11-17 against OpenAI's Codex app-server documentation and protocol source, plus the current Eggpass usage path. + +## Goal + +When a user runs `eggpass usage`, report ChatGPT rate-limit windows from the user's existing Codex installation when the Codex CLI is installed, its app-server can start, and it has a ChatGPT-managed account. Do not require Eggpass ChatGPT OAuth for this usage-only result. If this optional source cannot answer, preserve the existing Eggpass usage behavior and output. + +The integration is a read-only consumer of Codex's documented local JSON-RPC account methods. It must not participate in inference, authorization, refresh-token exchange, account switching, login, or logout. + +## Recommended behavior + +1. In the OpenAI provider's `usage` collection path, try a local Codex app-server query before the existing Eggpass-token check. This ordering is necessary: `src/cli/commands/usage.rs:159-171` currently returns `NotSignedIn` before reaching the provider collector when Eggpass itself has no OpenAI token. +2. If Codex returns a valid ChatGPT rate-limit snapshot, convert it to the existing normalized `UsageReport` and report its source as `Codex app-server`. Make that source visible in both terminal and JSON output; the Codex account may differ from the account used for Eggpass inference. Do not print the Codex account email or other identity details. +3. If Codex is absent, unauthenticated, configured for a non-ChatGPT auth mode, incompatible, times out, exits, or returns an error/malformed response, fall through to the existing collector and exit behavior without turning the optional lookup into a command failure: + - If Eggpass has its own OpenAI token, retain the existing `Unavailable` result and message from `src/provider/usage/openai.rs:63-72`. + - If Eggpass has no OpenAI token, retain the existing `NotSignedIn` block and exit semantics from `src/cli/commands/usage.rs:95-106,192-202`. + - Render provider results through the shared human-readable formatter, which shows remaining percentages and reset countdowns where available. +4. Query only when the OpenAI provider is included in the command. Leave xAI collection, inference, and all non-usage commands unchanged. + +## App-server protocol flow + +Use the installed `codex` executable directly, without invoking a shell: + +```text +codex app-server +``` + +The official default transport is stdio with newline-delimited JSON-RPC messages. A minimal session is: + +1. Spawn the process with piped stdin/stdout; keep stderr separate from protocol output. +2. Send `initialize` with a stable Eggpass `clientInfo` name/title/version and wait for the matching response. +3. Send the `initialized` notification. +4. Send `account/read` with `refreshToken: false`; proceed only when `result.account.type` is `chatgpt`. Do not display the returned email. This is a mode check, not a login request. +5. Send `account/rateLimits/read` and wait for the matching response. No thread or turn is needed. +6. Close stdin and terminate/reap the child when the request finishes. + +Use normal account methods without opting into `experimentalApi`. Match responses by JSON-RPC `id`, tolerate/ignore unrelated notifications, and treat JSON-RPC errors as an unavailable optional source. Bound startup/RPC time, stdout line size, and total response size. On timeout or protocol failure, kill/reap the child and continue through Eggpass's existing fallback. Do not let a blocking pipe read hang `eggpass usage` indefinitely; implement a deadline-safe reader/process boundary and test it on supported platforms. + +Do not read or parse `$CODEX_HOME/auth.json`, copy Codex credentials, pass Eggpass SIWC tokens into Codex, call `account/login/*` or `account/logout`, or make direct requests to ChatGPT's internal usage endpoints. The app-server itself owns its local Codex authentication and any normal token lifecycle. Avoid exposing raw app-server output, stderr, credentials, or RPC errors in terminal output or logs. + +## Mapping rate-limit results + +OpenAI documents these fields in `account/rateLimits/read`: + +- `rateLimitsByLimitId`: optional map of metered buckets, for example `codex`. +- `rateLimits`: backward-compatible single-bucket view. +- Each bucket can include `primary` and `secondary` windows with `usedPercent`, `windowDurationMins`, and `resetsAt`. +- Buckets may also include `planType` and `rateLimitReachedType`. + +Mapping rules: + +- Prefer a non-empty `rateLimitsByLimitId` map and do not also emit its duplicate top-level `rateLimits` view. If the map is absent or empty, use `rateLimits`. +- Preserve all returned buckets and distinguish them in output. Human-readable rows use the supplied duration (for example, `5-hour` or `7-day`) instead of a generic primary/secondary label; keep the bucket name when multiple buckets would otherwise be ambiguous. +- Map `usedPercent` to the existing optional percentage, `resetsAt` to Unix seconds, and `windowDurationMins` to seconds with checked conversion. Do not assume a fixed quota period or hard-code a reset schedule. +- Missing or `null` fields mean unavailable, never zero. If no usable quota data is present, fall back to current behavior rather than displaying a zero-usage report. +- Map plan/state fields only where their meaning matches the existing model. Do not collapse distinct workspace-credit or usage-limit states into a misleading generic state; extend the normalized representation only if required to preserve the server's meaning. +- Add separate source metadata to the usage entry rather than reusing `caption`, which describes which pool the reported quota belongs to. Keep the JSON addition optional/additive when the source is not Codex. + +The existing `UsageReport`/`QuotaWindow` model already represents optional percentages, reset timestamps, and durations (`src/provider/usage/mod.rs:32-75`). The formatter uses supplied durations as inline window labels, keeps provider labels when duration is missing, shows remaining percentages and future reset countdowns, and leaves the JSON `used_percent` data unchanged. Bucket names are included when multiple Codex buckets need disambiguation; xAI collection semantics remain unchanged. + +## `account/usage/read` scope + +`account/usage/read` is documented as ChatGPT token-activity summaries and optional daily token buckets (for example lifetime tokens, peak daily tokens, and per-day tokens). It is not quota remaining or a rate-limit window. It is not required to solve the current missing-quota problem, so defer it from the first implementation unless a separate product decision expands `eggpass usage` to include a distinct token-activity section. If added later, keep it separate from quota percentages, preserve nullable/missing values, and update terminal/JSON output and tests explicitly. + +## Implementation stages + +### Stage 0 — Confirm local process compatibility + +- Confirm the supported Codex CLI executable invocation and stdio behavior on the project's supported operating systems; use `codex app-server` with default stdio transport. +- Prototype the initialize/initialized/account-read/rate-limits exchange against a test/fake app-server process. Do not inspect or alter any user's Codex credentials and do not require a live account in CI. +- Resolve process deadlines, child cleanup, executable-not-found behavior, and bounded stdout/stderr handling before integrating the query. +- Use existing `serde_json` and standard process/I/O facilities where practical; add a dependency only if a safe, portable timeout/reader implementation requires it. + +**Exit:** A bounded helper can complete the RPC flow, distinguish ChatGPT from unsupported/no account, and cleanly terminate the child on success and failure. + +### Stage 1 — Integrate the OpenAI usage fallback + +- Add a small app-server usage adapter under the provider usage code. Keep process launching and JSON-RPC concerns out of the inference provider implementation. +- Clarify the existing OpenAI collector's module comments as the SIWC-only fallback; do not leave wording that implies the new app-server source is impossible or unavailable. +- Call it for OpenAI usage before the Eggpass token short-circuit. If it returns no valid report, execute the current token-check/provider-collector logic unchanged. +- Convert bucket windows to the current report model; add optional source labeling to text and JSON output. Clearly identify that the result came from the Codex account, which may not be the Eggpass inference account. +- Do not change OAuth configuration, credentials, token storage, auth commands, `ProviderRuntime` inference behavior, upstream requests, or xAI usage. + +**Exit:** A Codex-authenticated ChatGPT account can supply usage when Eggpass OpenAI OAuth is absent; all unavailable cases retain existing output/exit behavior. + +### Stage 2 — Test the optional boundary and regressions + +Use a fake `codex` executable or injected executable path to test deterministic protocol behavior without network/account access: + +- executable missing; spawn failure; early exit; startup/RPC timeout; malformed/oversized JSONL; total-output limit; JSON-RPC error; missing or wrong response ID; notification bursts without dropping responses; +- successful initialize handshake and both account RPCs; +- ChatGPT account, no account, API-key account, and another unsupported mode; +- legacy `rateLimits` only; populated and empty `rateLimitsByLimitId`; primary/secondary windows; multiple buckets; null/missing values; zero percent; reset and duration conversion; unknown plan/state variants; +- no false zero report and no duplicate reporting of `rateLimits` plus the bucket map; +- fallback to the exact current OpenAI response when Codex is missing/unusable, both with and without Eggpass OpenAI credentials; +- Codex usage is reported without Eggpass OpenAI credentials, so `eggpass usage --provider openai` does not incorrectly return the current not-signed-in exit code; +- source labeling in text and JSON; no email, token, raw child output, or credential material in output/logs; +- existing xAI usage tests and OpenAI inference/auth tests remain unchanged and pass. + +**Exit:** All new tests use a fake process and no live service. Existing CLI, OAuth, and inference tests pass; `git diff --check`, formatting, Clippy, and workspace tests pass. + +## Out of scope + +- Replacing, extending, or otherwise changing Eggpass's current SIWC OAuth mechanism for inference. +- Supplying Eggpass tokens or account identifiers to Codex app-server. +- Any Codex login, logout, account-switching, or credential-management UI/flow. +- Direct calls to undocumented ChatGPT backend endpoints or reading Codex credential files. +- Making inference depend on Codex being installed or signed in. +- Adding `account/usage/read` token activity to the initial quota-focused implementation. +- Changes to release workflows, package publication, daemon behavior, or xAI usage. + +## Acceptance checklist + +- [x] OpenAI `usage` can query the local Codex app-server without requiring Eggpass OpenAI OAuth. +- [x] `codex app-server` is optional; missing, unauthenticated, unsupported, incompatible, malformed, or timed-out Codex falls back to current Eggpass behavior. +- [x] Codex reads are limited to account state and documented usage/rate-limit read methods; no login/logout or direct private HTTP endpoint is used. +- [x] Usage output clearly labels the Codex source and buckets, without exposing account email or secrets. +- [x] `account/usage/read` remains deferred unless separately approved as distinct token-activity output. +- [x] Eggpass inference OAuth, token storage, provider requests, xAI usage, and non-usage commands are unchanged. +- [x] Fake-process tests cover protocol success/failure, fallback behavior, and output safety; full existing Rust checks pass. + +## References + +Official OpenAI documentation and schema reviewed 2026-11-17: + +- [Codex App Server protocol and stdio transport](https://developers.openai.com/codex/app-server.md) — JSONL/JSON-RPC framing, `initialize` then `initialized`, local CLI startup, account methods, and the usage response examples. +- [Codex app-server account protocol source](https://github.com/openai/codex/blob/main/codex-rs/app-server-protocol/src/protocol/v2/account.rs) — response structures for rate-limit buckets/windows and token usage summary. + +Repository context: + +- `src/cli/commands/usage.rs:53-118` — provider collection, output, and all-not-signed-in exit behavior. +- `src/cli/commands/usage.rs:159-171` — current Eggpass token check before provider usage collection. +- `src/cli/commands/usage.rs:186-232` — current unavailable/not-signed-in terminal rendering. +- `src/provider/usage/openai.rs:57-72` — existing ChatGPT unavailable result and fallback text. +- `src/provider/usage/mod.rs:32-75,161-192` — normalized report, quota window, and provider result types. +- `Cargo.toml:63-69` — current `serde_json` and Tokio dependencies; do not make runtime dependencies a prerequisite for inference. diff --git a/src/cli/args.rs b/src/cli/args.rs index 4789e0a..a8b300f 100644 --- a/src/cli/args.rs +++ b/src/cli/args.rs @@ -28,7 +28,7 @@ pub enum Command { }, /// Report account and daemon state. Status, - /// Report how much of the subscription allowance is used. + /// Report how much of the subscription allowance remains. Usage { /// The provider to ask, when it was named. provider: Option, @@ -529,7 +529,7 @@ pub fn global_help() -> String { login Authenticate with a provider over OAuth\n \ logout Revoke and remove stored credentials\n \ status Show account and daemon state\n \ - usage Show how much of the subscription allowance is used\n \ + usage Show how much of the subscription allowance remains\n \ run Start the server as a background daemon\n \ stop Stop the running daemon\n \ restart Stop the daemon, then start it again\n \ @@ -567,7 +567,7 @@ pub fn command_help(name: &str) -> String { "status" => "eggpass status\n\nShow account state and daemon state.\n".to_string(), "usage" => { "eggpass usage [--json]\n\n\ - Show how much of the subscription allowance is used. Each provider\n\ + Show how much of the subscription allowance remains. Each provider\n\ is asked once, on this run, and the answer is printed and the\n\ command ends. Without --provider every provider you are signed in\n\ to is asked.\n\n\ @@ -794,6 +794,17 @@ mod tests { assert!(text.contains("--device"), "{text}"); } + #[test] + fn usage_help_describes_remaining_usage() { + assert!( + global_help() + .contains("usage Show how much of the subscription allowance remains") + ); + let usage = command_help("usage"); + assert!(usage.contains("allowance remains"), "{usage}"); + assert!(!usage.contains("allowance is used"), "{usage}"); + } + #[test] fn version_is_available() { assert!(matches!( diff --git a/src/cli/commands/usage.rs b/src/cli/commands/usage.rs index 2b30b8f..8bb2ee0 100644 --- a/src/cli/commands/usage.rs +++ b/src/cli/commands/usage.rs @@ -21,14 +21,14 @@ //! body carries the account's email, its user id and its balances; it goes //! to the provider and stops there. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::time::Duration; use serde::Serialize; use crate::cli::{CommandError, Context}; use crate::daemon::{self, DaemonState}; -use crate::provider::usage::{ProviderUsage, UsageReport}; +use crate::provider::usage::{ProviderUsage, UsageReport, WindowLabel}; use crate::provider::{ProviderId, ProviderRuntime}; use crate::timeutil; @@ -50,7 +50,7 @@ const EMPTY: char = '░'; /// How far past a reset time a window counts as stale, in seconds. const STALE_AFTER: i64 = 3_600; -/// Show how much of the subscription allowance is used. +/// Show how much of the subscription allowance remains. pub fn usage( context: &Context, provider: Option, @@ -68,16 +68,23 @@ pub fn usage( let entries: Vec = providers .into_iter() - .map(|provider| ProviderEntry { - provider, - outcome: collect_one(context, provider), - // The caption travels with the report, in the JSON as well as in - // the bars: a machine-readable number without it is as misleading - // as a number without it on the terminal. - caption: caption_for(provider, &context.config), - // The last inference is the only evidence there is about a - // provider that publishes no quota of its own. - last_inference: inferences.get(&provider).copied(), + .map(|provider| { + let (outcome, source) = collect_one(context, provider); + ProviderEntry { + provider, + outcome, + // The source is distinct from `caption`: a source identifies + // which account supplied the snapshot, while a caption names + // the pool the quota belongs to. + source, + // The caption travels with the report, in the JSON as well as in + // the bars: a machine-readable number without it is as misleading + // as a number without it on the terminal. + caption: caption_for(provider, &context.config), + // The last inference is the only evidence there is about a + // provider that publishes no quota of its own. + last_inference: inferences.get(&provider).copied(), + } }) .collect(); @@ -92,6 +99,11 @@ pub fn usage( print!("{}", render(&entries)); } + usage_exit_result(&entries) +} + +/// Decide the command status after output has been rendered. +fn usage_exit_result(entries: &[ProviderEntry]) -> Result<(), CommandError> { // A provider that is not signed in still gets a block, so the output does // not change shape — but a run in which nobody is signed in has nothing // to report at all. @@ -126,6 +138,9 @@ struct ProviderEntry { /// What it had to say. #[serde(flatten)] outcome: ProviderUsage, + /// Which account or local source supplied the usage snapshot, when relevant. + #[serde(skip_serializing_if = "Option::is_none")] + source: Option<&'static str>, /// Which pool the numbers belong to, when the provider reported any. caption: Option, /// The HTTP status the last inference to this provider was answered with. @@ -158,17 +173,51 @@ fn caption_for(provider: ProviderId, config: &crate::config::Config) -> Option ProviderUsage { - let runtime = ProviderRuntime::new(provider, &context.config, &context.paths); +/// Codex is consulted only for OpenAI usage and before Eggpass's own +/// credential check. If it cannot provide a report, the existing provider +/// path below remains the fallback. +fn collect_one(context: &Context, provider: ProviderId) -> (ProviderUsage, Option<&'static str>) { + let codex_report = (provider == ProviderId::OpenAi) + .then(crate::provider::usage::codex_app_server::collect) + .flatten(); + collect_one_with_codex_result(context, provider, codex_report) +} + +/// Apply an optional Codex report, otherwise run the existing token/collector path. +fn collect_one_with_codex_result( + context: &Context, + provider: ProviderId, + codex_report: Option, +) -> (ProviderUsage, Option<&'static str>) { + if let Some(codex_usage) = codex_outcome(provider, codex_report) { + return codex_usage; + } - match runtime.tokens.current() { + let runtime = ProviderRuntime::new(provider, &context.config, &context.paths); + let outcome = match runtime.tokens.current() { Ok(None) => ProviderUsage::NotSignedIn, Ok(Some(_)) => runtime.usage(), Err(err) => ProviderUsage::Failed { reason: format!("could not read the stored credentials ({err})"), }, + }; + (outcome, None) +} + +/// Use Codex's report only for the OpenAI usage entry. +fn codex_outcome( + provider: ProviderId, + report: Option, +) -> Option<(ProviderUsage, Option<&'static str>)> { + if provider != ProviderId::OpenAi { + return None; } + report.map(|report| { + ( + ProviderUsage::Reported { report }, + Some(crate::provider::usage::codex_app_server::SOURCE_LABEL), + ) + }) } /// Render the whole report. @@ -186,9 +235,13 @@ fn render(entries: &[ProviderEntry]) -> String { /// Render one provider's block. fn render_block(out: &mut String, entry: &ProviderEntry) { match &entry.outcome { - ProviderUsage::Reported { report } => { - render_reported(out, entry.provider, report, entry.caption.as_deref()) - } + ProviderUsage::Reported { report } => render_reported( + out, + entry.provider, + report, + entry.caption.as_deref(), + entry.source, + ), ProviderUsage::NotSignedIn => { out.push_str(entry.provider.display_name()); out.push('\n'); @@ -256,6 +309,15 @@ fn render_caption(out: &mut String, caption: Option<&str>) { out.push_str(&format!(" {caption}\n")); } +/// Render the account/source note when the reported snapshot came from Codex. +fn render_source(out: &mut String, source: Option<&str>) { + let Some(source) = source else { + return; + }; + out.push_str(&field("Source", source)); + out.push('\n'); +} + /// Render the row that says what the last inference was answered with. /// /// It is printed when the quota could not be read, and only then: a block @@ -334,6 +396,7 @@ fn render_reported( provider: ProviderId, report: &UsageReport, caption: Option<&str>, + source: Option<&str>, ) { // The heading names the plan when the provider named one. match &report.plan { @@ -347,24 +410,47 @@ fn render_reported( out.push('\n'); let now = timeutil::now_unix(); + let buckets: BTreeSet<&str> = report + .windows + .iter() + .filter_map(|window| bucket_id(&window.label)) + .collect(); + let multiple_buckets = buckets.len() > 1; for window in &report.windows { + // Use the provider's window duration when it is known. This turns + // Codex's generic Primary/Secondary buckets into useful labels such as + // 5-hour and 7-day, while preserving named windows like Grok's Weekly + // when no duration is supplied. Keep bucket names when they are needed + // to distinguish multiple reported buckets. + let label = match ( + window.duration_secs.filter(|duration| *duration > 0), + multiple_buckets.then(|| bucket_id(&window.label)).flatten(), + ) { + (Some(duration), Some(bucket)) => { + format!("{bucket} {}", duration_label(duration)) + } + (Some(duration), None) => duration_label(duration), + (None, _) => window.label.display(), + }; + // An explicit state is the provider's answer, and it replaces the // percentage entirely. if let Some(state) = &report.state { - out.push_str(&field(&window.label.display(), state.display())); + out.push_str(&field(&label, state.display())); out.push('\n'); } else { match window.used_percent { Some(percent) => { + let left = left_percent(percent); out.push_str(&field( - &window.label.display(), - &format!("{} {} used", bar(percent), percent_text(percent)), + &label, + &format!("{} {} left", bar(left), percent_text(left)), )); } // No bar at all: a bar with a question mark in it would be a // number we do not have. - None => out.push_str(&field(&window.label.display(), "unavailable")), + None => out.push_str(&field(&label, "unavailable")), } out.push('\n'); } @@ -375,7 +461,12 @@ fn render_reported( // The offset is the one in force at the reset instant, so a // reset on the far side of a daylight-saving change is right. let offset = timeutil::local_offset_seconds(resets_at).unwrap_or(0); - out.push_str(&field("Resets", &reset_text(resets_at, now, offset))); + let mut reset = reset_text(resets_at, now, offset); + if let Some(remaining) = reset_countdown(resets_at, now) { + reset.push_str(" · in "); + reset.push_str(&remaining); + } + out.push_str(&field("Resets", &reset)); out.push('\n'); } } @@ -387,11 +478,12 @@ fn render_reported( for product in &report.breakdown { match product.used_percent { Some(percent) => { + let left = left_percent(percent); out.push_str(&format!( - " {: String { - format!(" {label:= LABEL_WIDTH { + " " + } else { + "" + }; + format!(" {label: String { format!(" {: String { let rounded = round_percent(percent); let mut filled = (rounded / 100.0 * BAR_CELLS as f64).round() as i64; @@ -483,6 +580,52 @@ fn percent_text(percent: f64) -> String { } } +/// Convert the provider's used percentage into the percentage left. +fn left_percent(used_percent: f64) -> f64 { + (100.0 - used_percent).clamp(0.0, 100.0) +} + +/// A compact label for a quota-window duration. +/// +/// Exact days and hours use the adjective form that fits beside the bar +/// (`7-day`, `5-hour`). Unusual durations stay precise without a separate +/// Duration row. +fn duration_label(duration_secs: i64) -> String { + if duration_secs > 0 && duration_secs % 86_400 == 0 { + format!("{}-day", duration_secs / 86_400) + } else if duration_secs > 0 && duration_secs % 3_600 == 0 { + format!("{}-hour", duration_secs / 3_600) + } else if duration_secs > 0 && duration_secs % 60 == 0 { + format!("{}-min", duration_secs / 60) + } else { + let hours = duration_secs / 3_600; + let minutes = duration_secs % 3_600 / 60; + let seconds = duration_secs % 60; + match (hours, minutes, seconds) { + (hours, minutes, _) if hours > 0 && minutes > 0 => { + format!("{hours}h {minutes}m") + } + (hours, _, _) if hours > 0 => format!("{hours}h"), + (_, minutes, seconds) if minutes > 0 && seconds > 0 => { + format!("{minutes}m {seconds}s") + } + (_, minutes, _) if minutes > 0 => format!("{minutes}m"), + (_, _, seconds) => format!("{seconds}s"), + } + } +} + +/// Extract a Codex bucket name from its `bucket Primary/Secondary` label. +fn bucket_id(label: &WindowLabel) -> Option<&str> { + let WindowLabel::Other(label) = label else { + return None; + }; + label + .strip_suffix(" Primary") + .or_else(|| label.strip_suffix(" Secondary")) + .filter(|bucket| !bucket.is_empty()) +} + /// The reset time, in the local timezone, with its offset. /// /// The offset is printed because `Nov 18, 09:00` alone is ambiguous: a user @@ -507,6 +650,36 @@ fn reset_text(resets_at: i64, now: i64, offset: i64) -> String { text } +/// Time remaining until a future reset, at a glance precision. +fn reset_countdown(resets_at: i64, now: i64) -> Option { + let seconds = resets_at.saturating_sub(now); + if seconds <= 0 { + return None; + } + + let days = seconds / 86_400; + let hours = seconds % 86_400 / 3_600; + let minutes = seconds % 3_600 / 60; + + Some(if days > 0 { + if hours > 0 { + format!("{days}d {hours}hr") + } else { + format!("{days}d") + } + } else if hours > 0 { + if minutes > 0 { + format!("{hours}hr {minutes}m") + } else { + format!("{hours}hr") + } + } else if minutes > 0 { + format!("{minutes}m") + } else { + "under 1m".to_string() + }) +} + /// An amount in cents, as dollars. fn money(cents: i64) -> String { let sign = if cents < 0 { "-" } else { "" }; @@ -552,6 +725,7 @@ mod tests { ProviderEntry { provider: ProviderId::Xai, outcome, + source: None, caption: None, last_inference: None, } @@ -562,6 +736,7 @@ mod tests { ProviderEntry { provider: ProviderId::OpenAi, outcome, + source: None, caption: None, last_inference: Some(status), } @@ -688,25 +863,28 @@ mod tests { } #[test] - fn a_tiny_percentage_does_not_contradict_its_bar() { - // A percentage that rounds to zero reads `0% used`, so its bar is - // empty. A filled cell beside `0% used` would say otherwise. - assert_eq!(percent_text(0.04), "0%"); - assert_eq!(bar(0.04).chars().filter(|c| *c == FILLED).count(), 0); - assert_eq!(bar(0.04).chars().count(), 20); - - // A percentage that rounds to something above zero gets a cell. - assert_eq!(percent_text(0.1), "0.1%"); - assert_eq!(bar(0.1).chars().filter(|c| *c == FILLED).count(), 1); - assert_eq!(bar(0.1).chars().count(), 20); + fn a_tiny_remaining_percentage_does_not_contradict_its_bar() { + // When almost all the allowance is used, a remainder that rounds to + // zero reads `0% left` and has an empty bar. + let left = left_percent(99.96); + assert_eq!(percent_text(left), "0%"); + assert_eq!(bar(left).chars().filter(|c| *c == FILLED).count(), 0); + assert_eq!(bar(left).chars().count(), 20); + + // A remainder that rounds above zero gets a cell. + let left = left_percent(99.9); + assert_eq!(percent_text(left), "0.1%"); + assert_eq!(bar(left).chars().filter(|c| *c == FILLED).count(), 1); + assert_eq!(bar(left).chars().count(), 20); } #[test] fn the_chatgpt_block_names_the_error_codes() { let entry = ProviderEntry { provider: ProviderId::OpenAi, - caption: None, outcome: chatgpt_unavailable(), + source: None, + caption: None, last_inference: None, }; @@ -911,11 +1089,10 @@ mod tests { } #[test] - fn the_percentage_reads_as_used() { - // The number is how much is *used*, never how much is left. + fn the_bar_and_percentage_show_remaining_allowance() { let text = render(&[entry(reported(Some(40.0)))]); - assert!(text.contains("40% used"), "{text}"); - assert!(!text.contains("40% left"), "{text}"); + assert!(text.contains(&format!("{} 60% left", bar(60.0))), "{text}"); + assert!(!text.contains("40% used"), "{text}"); } #[test] @@ -934,9 +1111,9 @@ mod tests { let text = render(&[entry(ProviderUsage::Reported { report })]); assert!(text.contains("GrokBuild"), "{text}"); - assert!(text.contains("50% used"), "{text}"); + assert!(text.contains("50% left"), "{text}"); assert!(text.contains("GrokChat"), "{text}"); - assert!(text.contains("20% used"), "{text}"); + assert!(text.contains("80% left"), "{text}"); } #[test] @@ -987,8 +1164,9 @@ mod tests { fn the_json_report_names_the_provider_and_the_status() { let entries = vec![ProviderEntry { provider: ProviderId::OpenAi, - caption: None, outcome: ProviderUsage::NotSignedIn, + source: None, + caption: None, last_inference: None, }]; @@ -998,5 +1176,254 @@ mod tests { let text = serde_json::to_string(&report).unwrap(); assert!(text.contains("\"provider\":\"openai\""), "{text}"); assert!(text.contains("\"status\":\"not_signed_in\""), "{text}"); + assert!(!text.contains("\"source\":null"), "{text}"); + } + + fn context_for(directory: &std::path::Path) -> Context { + Context { + paths: crate::paths::Paths::in_directory(directory), + config: crate::config::Config::default(), + cli: crate::cli::args::Cli { + command: crate::cli::args::Command::Usage { + provider: Some(ProviderId::OpenAi), + json: false, + }, + config_path: None, + verbose: false, + }, + } + } + + fn codex_report() -> UsageReport { + UsageReport { + provider: ProviderId::OpenAi, + plan: None, + windows: vec![QuotaWindow { + label: WindowLabel::Other("codex Primary".to_string()), + used_percent: Some(25.0), + resets_at: Some(1_800_000_000), + duration_secs: Some(18_000), + }], + breakdown: Vec::new(), + credits: None, + state: None, + } + } + + #[test] + fn a_codex_report_precedes_the_missing_eggpass_credential_check() { + let directory = tempfile::tempdir().unwrap(); + let context = context_for(directory.path()); + let (outcome, source) = + collect_one_with_codex_result(&context, ProviderId::OpenAi, Some(codex_report())); + let entry = ProviderEntry { + provider: ProviderId::OpenAi, + outcome, + source, + caption: None, + last_inference: None, + }; + + assert!(matches!(&entry.outcome, ProviderUsage::Reported { .. })); + assert_eq!( + entry.source, + Some(crate::provider::usage::codex_app_server::SOURCE_LABEL) + ); + assert!(usage_exit_result(std::slice::from_ref(&entry)).is_ok()); + } + + #[test] + fn an_unavailable_codex_source_preserves_both_existing_fallbacks() { + let directory = tempfile::tempdir().unwrap(); + let context = context_for(directory.path()); + let (outcome, source) = collect_one_with_codex_result(&context, ProviderId::OpenAi, None); + assert!(matches!(&outcome, ProviderUsage::NotSignedIn)); + assert_eq!(source, None); + let error = usage_exit_result(&[ProviderEntry { + provider: ProviderId::OpenAi, + outcome, + source, + caption: None, + last_inference: None, + }]) + .unwrap_err(); + assert_eq!(error.code, 2); + assert_eq!( + error.message.as_deref(), + Some("not signed in — run `eggpass login`") + ); + + let credential = crate::auth::store::StoredAuth { + access_token: "test-only-access-token".to_string(), + refresh_token: None, + id_token: None, + token_type: "Bearer".to_string(), + scope: None, + client_id: "test-client".to_string(), + issuer: "https://auth.openai.com".to_string(), + expires_at: Some(crate::timeutil::now_unix() + 3_600), + obtained_at: crate::timeutil::now_unix(), + user_id: None, + email: None, + ext_agent_host_id: None, + plan_enabled: false, + }; + crate::auth::store::save( + &context.paths.credential_file(ProviderId::OpenAi.as_str()), + &credential, + ) + .unwrap(); + let (outcome, source) = collect_one_with_codex_result(&context, ProviderId::OpenAi, None); + assert_eq!(source, None); + assert!( + matches!( + outcome, + ProviderUsage::Unavailable { + ref reason, + ref source, + ref hint, + ref signals, + } if reason == "Sign in with ChatGPT does not expose a quota API" + && source.as_deref() == Some("not exposed by OAuth") + && hint.as_deref() == Some("https://chatgpt.com/settings/usage") + && signals.len() == 3 + ), + "unexpected fallback: {outcome:?}" + ); + } + + #[test] + fn codex_source_and_bucket_are_visible_in_text_and_json_without_identity() { + let mut entry = ProviderEntry { + provider: ProviderId::OpenAi, + outcome: ProviderUsage::Reported { + report: codex_report(), + }, + source: Some(crate::provider::usage::codex_app_server::SOURCE_LABEL), + caption: None, + last_inference: None, + }; + let text = render(std::slice::from_ref(&entry)); + assert!(text.contains("5-hour"), "{text}"); + assert!(text.contains("75% left"), "{text}"); + assert!(!text.contains("codex Primary"), "{text}"); + assert!(!text.contains("Duration"), "{text}"); + assert!(text.contains("Source Codex app-server"), "{text}"); + assert!(!text.contains("@"), "{text}"); + + let report = UsageReportJson { + providers: std::slice::from_ref(&entry), + }; + let value = serde_json::to_value(report).unwrap(); + let encoded = value.to_string(); + assert!( + encoded.contains("\"source\":\"Codex app-server"), + "{encoded}" + ); + assert!(encoded.contains("codex Primary"), "{encoded}"); + assert!(encoded.contains("\"duration_secs\":18000"), "{encoded}"); + assert!(!encoded.contains("@"), "{encoded}"); + + entry.source = None; + let legacy_json = serde_json::to_value(UsageReportJson { + providers: std::slice::from_ref(&entry), + }) + .unwrap(); + assert!(legacy_json["providers"][0].get("source").is_none()); + } + + #[test] + fn codex_usage_is_not_assigned_to_xai() { + assert!(codex_outcome(ProviderId::Xai, Some(codex_report())).is_none()); + } + + #[test] + fn durations_become_compact_window_labels() { + assert_eq!(duration_label(18_000), "5-hour"); + assert_eq!(duration_label(604_800), "7-day"); + assert_eq!(duration_label(300), "5-min"); + assert_eq!(duration_label(5_400), "90-min"); + assert_eq!(duration_label(3_661), "1h 1m"); + + let text = render(&[entry(reported(Some(40.0)))]); + assert!(text.contains("Weekly"), "{text}"); + assert!(!text.contains("Duration"), "{text}"); + } + + #[test] + fn a_named_weekly_window_is_not_relabelled_or_expanded() { + let mut report = reported_report(Some(1.0)); + report.windows[0].resets_at = + Some(timeutil::now_unix() + 3 * 86_400 + 15 * 3_600 + 30 * 60); + let text = render(&[entry(ProviderUsage::Reported { report })]); + + assert!(text.contains("Weekly"), "{text}"); + assert!(text.contains("99% left"), "{text}"); + assert!(text.contains("in 3d 15hr"), "{text}"); + assert!(!text.contains("5-hour"), "{text}"); + assert!(!text.contains("7-day"), "{text}"); + } + + #[test] + fn reset_countdowns_are_compact_and_omit_past_resets() { + let now = timeutil::parse_rfc3339_to_unix("2026-11-14T12:00:00Z").unwrap(); + assert_eq!( + reset_countdown(now + 3 * 86_400 + 15 * 3_600 + 42 * 60, now), + Some("3d 15hr".to_string()) + ); + assert_eq!( + reset_countdown(now + 3 * 3_600 + 21 * 60 + 12, now), + Some("3hr 21m".to_string()) + ); + assert_eq!(reset_countdown(now + 20, now), Some("under 1m".to_string())); + assert_eq!(reset_countdown(now, now), None); + assert_eq!(reset_countdown(now - 30, now), None); + } + + #[test] + fn each_provider_window_shows_duration_left_and_its_reset_countdown() { + let now = timeutil::now_unix(); + let mut report = codex_report(); + report.windows = vec![ + QuotaWindow { + label: WindowLabel::Other("codex Primary".to_string()), + used_percent: Some(69.0), + resets_at: Some(now + 3 * 3_600 + 21 * 60), + duration_secs: Some(18_000), + }, + QuotaWindow { + label: WindowLabel::Other("codex Secondary".to_string()), + used_percent: Some(95.0), + resets_at: Some(now + 3 * 86_400 + 15 * 3_600 + 30 * 60), + duration_secs: Some(604_800), + }, + ]; + let text = render(&[entry(ProviderUsage::Reported { report })]); + + assert!(text.contains("5-hour"), "{text}"); + assert!(text.contains("31% left"), "{text}"); + assert!(text.contains("7-day"), "{text}"); + assert!(text.contains("5% left"), "{text}"); + assert!(text.contains("in 3hr 21m"), "{text}"); + assert!(text.contains("in 3d 15hr"), "{text}"); + assert!(!text.contains("Primary"), "{text}"); + assert!(!text.contains("Secondary"), "{text}"); + assert!(!text.contains("Duration"), "{text}"); + } + + #[test] + fn multiple_codex_buckets_remain_distinguishable_with_duration_labels() { + let mut report = codex_report(); + report.windows.push(QuotaWindow { + label: WindowLabel::Other("other-model Primary".to_string()), + used_percent: Some(50.0), + resets_at: None, + duration_secs: Some(18_000), + }); + let text = render(&[entry(ProviderUsage::Reported { report })]); + + assert!(text.contains("codex 5-hour"), "{text}"); + assert!(text.contains("other-model 5-hour"), "{text}"); + assert!(!text.contains("Primary"), "{text}"); } } diff --git a/src/provider/usage/codex_app_server.rs b/src/provider/usage/codex_app_server.rs new file mode 100644 index 0000000..25a4b89 --- /dev/null +++ b/src/provider/usage/codex_app_server.rs @@ -0,0 +1,594 @@ +//! Optional ChatGPT rate-limit reads from the local Codex app-server. +//! +//! This is a usage-only source. It invokes `codex app-server` over its +//! documented stdio JSON-RPC protocol, reads the account mode without +//! refreshing it, and asks only for rate limits. It never reads Codex +//! credential files or participates in Eggpass authentication or inference. + +#[cfg(test)] +use std::ffi::OsStr; +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::process::{Child, ChildStderr, ChildStdin, Command, Stdio}; +use std::sync::mpsc::{self, Receiver, SyncSender}; +use std::thread; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use super::{QuotaWindow, UsageReport, WindowLabel}; +use crate::provider::ProviderId; + +/// The fixed label shown when a quota came from Codex rather than Eggpass OAuth. +pub const SOURCE_LABEL: &str = "Codex app-server (may differ from Eggpass inference account)"; + +/// One deadline covers process startup and the complete RPC exchange. +const SESSION_TIMEOUT: Duration = Duration::from_secs(8); +/// Maximum bytes accepted on one JSONL record. +const MAX_LINE_BYTES: usize = 256 * 1024; +/// Maximum total stdout bytes accepted during one app-server session. +const MAX_STDOUT_BYTES: usize = 1024 * 1024; +/// A small bounded queue prevents a noisy child from buffering unlimited lines. +const QUEUED_LINES: usize = 16; + +/// Query the installed Codex CLI, returning `None` for every optional-source failure. +pub fn collect() -> Option { + let mut command = Command::new("codex"); + command.arg("app-server"); + collect_with_command(command, SESSION_TIMEOUT) +} + +/// Run one app-server session. Kept injectable so tests can use a fake process. +fn collect_with_command(mut command: Command, timeout: Duration) -> Option { + let deadline = Instant::now().checked_add(timeout)?; + command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + + let child = command.spawn().ok()?; + let mut process = ManagedChild::new(child); + let stdin = process.child.stdin.take()?; + process.stdin = Some(stdin); + let stdout = process.child.stdout.take()?; + let stderr = process.child.stderr.take()?; + + // Stderr is drained on a separate thread and discarded. No child output is + // retained, logged, or allowed to block the JSON-RPC channel. + drain_stderr(stderr).ok()?; + let responses = spawn_stdout_reader(stdout)?; + + let initialize = json!({ + "id": 1, + "method": "initialize", + "params": { + "clientInfo": { + "name": "eggpass", + "title": "Eggpass", + "version": env!("CARGO_PKG_VERSION") + }, + "capabilities": {} + } + }); + if !send_message(process.stdin.as_mut()?, &initialize) + || receive_response(&responses, 1, deadline).is_none() + { + return None; + } + + if !send_message(process.stdin.as_mut()?, &json!({ "method": "initialized" })) { + return None; + } + + let account_request = json!({ + "id": 2, + "method": "account/read", + "params": { "refreshToken": false } + }); + if !send_message(process.stdin.as_mut()?, &account_request) { + return None; + } + let account = receive_response(&responses, 2, deadline)?; + if account + .get("account") + .and_then(|account| account.get("type")) + .and_then(Value::as_str) + != Some("chatgpt") + { + return None; + } + + let rate_limits_request = json!({ + "id": 3, + "method": "account/rateLimits/read" + }); + if !send_message(process.stdin.as_mut()?, &rate_limits_request) { + return None; + } + let rate_limits = receive_response(&responses, 3, deadline)?; + map_rate_limits(&rate_limits) +} + +/// Ensure the direct child is closed and reaped on every return path. +struct ManagedChild { + child: Child, + stdin: Option, +} + +impl ManagedChild { + fn new(child: Child) -> Self { + Self { child, stdin: None } + } +} + +impl Drop for ManagedChild { + fn drop(&mut self) { + // Closing stdin lets a well-behaved server observe EOF before it is + // terminated. kill + wait also handles a server that ignores EOF. + self.stdin.take(); + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// Drain the child's stderr without retaining its contents. +fn drain_stderr(stderr: ChildStderr) -> io::Result<()> { + thread::Builder::new() + .name("eggpass-codex-stderr".to_string()) + .spawn(move || { + let mut stderr = stderr; + let mut buffer = [0_u8; 8192]; + loop { + match stderr.read(&mut buffer) { + Ok(0) | Err(_) => break, + Ok(_) => {} + } + } + }) + .map(|_| ()) +} + +/// Start a bounded stdout reader; protocol bytes never accumulate unboundedly. +fn spawn_stdout_reader(stdout: std::process::ChildStdout) -> Option, ()>>> { + let (sender, receiver) = mpsc::sync_channel(QUEUED_LINES); + thread::Builder::new() + .name("eggpass-codex-stdout".to_string()) + .spawn(move || read_stdout_lines(stdout, sender)) + .ok()?; + Some(receiver) +} + +fn read_stdout_lines(stdout: std::process::ChildStdout, sender: SyncSender, ()>>) { + let mut reader = BufReader::new(stdout); + let mut total_bytes = 0_usize; + loop { + match read_bounded_line(&mut reader, MAX_LINE_BYTES) { + Ok(Some(line)) => { + total_bytes = match total_bytes.checked_add(line.len().saturating_add(1)) { + Some(total) if total <= MAX_STDOUT_BYTES => total, + _ => { + let _ = sender.send(Err(())); + break; + } + }; + if sender.send(Ok(line)).is_err() { + break; + } + } + Ok(None) => break, + Err(_) => { + let _ = sender.try_send(Err(())); + break; + } + } + } +} + +/// Read one newline-terminated record without allowing it to exceed `limit`. +fn read_bounded_line(reader: &mut impl BufRead, limit: usize) -> io::Result>> { + let mut line = Vec::new(); + loop { + let available = reader.fill_buf()?; + if available.is_empty() { + if line.is_empty() { + return Ok(None); + } + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "unterminated JSONL record", + )); + } + + let newline = available.iter().position(|byte| *byte == b'\n'); + let consumed = newline.map_or(available.len(), |index| index + 1); + let content_len = newline.map_or(consumed, |index| index); + if line + .len() + .checked_add(content_len) + .is_none_or(|length| length > limit) + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "JSONL record exceeds the limit", + )); + } + line.extend_from_slice(&available[..content_len]); + reader.consume(consumed); + if newline.is_some() { + return Ok(Some(line)); + } + } +} + +fn send_message(stdin: &mut ChildStdin, message: &Value) -> bool { + serde_json::to_vec(message).ok().is_some_and(|message| { + stdin.write_all(&message).is_ok() && stdin.write_all(b"\n").is_ok() && stdin.flush().is_ok() + }) +} + +/// Read a response matching `id`; notifications and other response IDs are ignored. +fn receive_response( + responses: &Receiver, ()>>, + id: u64, + deadline: Instant, +) -> Option { + loop { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return None; + } + let line = responses.recv_timeout(remaining).ok()?.ok()?; + let value: Value = serde_json::from_slice(&line).ok()?; + let object = value.as_object()?; + + let Some(response_id) = object.get("id") else { + // A JSON-RPC notification has a method and no id. Other id-less + // objects are malformed and cannot be a useful response. + if object.get("method").and_then(Value::as_str).is_some() { + continue; + } + return None; + }; + if response_id != &Value::from(id) { + continue; + } + if object.contains_key("error") { + return None; + } + return object.get("result").cloned(); + } +} + +/// Convert the documented rate-limit result without inventing missing values. +fn map_rate_limits(result: &Value) -> Option { + let mut windows = Vec::new(); + let buckets = result + .get("rateLimitsByLimitId") + .and_then(Value::as_object) + .filter(|buckets| !buckets.is_empty()); + + if let Some(buckets) = buckets { + for (bucket_id, snapshot) in buckets { + append_snapshot_windows(&mut windows, snapshot, Some(bucket_id)); + } + } else if let Some(snapshot) = result.get("rateLimits") { + append_snapshot_windows(&mut windows, snapshot, None); + } + + if windows.is_empty() { + return None; + } + + Some(UsageReport { + provider: ProviderId::OpenAi, + plan: None, + windows, + breakdown: Vec::new(), + credits: None, + state: None, + }) +} + +fn append_snapshot_windows( + windows: &mut Vec, + snapshot: &Value, + bucket_id: Option<&str>, +) { + for (field, role) in [("primary", "Primary"), ("secondary", "Secondary")] { + let Some(window) = snapshot.get(field).filter(|window| window.is_object()) else { + continue; + }; + let used_percent = window + .get("usedPercent") + .and_then(Value::as_f64) + .filter(|percent| percent.is_finite() && (0.0..=100.0).contains(percent)); + let resets_at = window.get("resetsAt").and_then(Value::as_i64); + let duration_secs = window + .get("windowDurationMins") + .and_then(Value::as_i64) + .filter(|minutes| *minutes >= 0) + .and_then(|minutes| minutes.checked_mul(60)); + + // A window with no usable quota fields is not a zero-usage report. + if used_percent.is_none() && resets_at.is_none() && duration_secs.is_none() { + continue; + } + + let label = match bucket_id { + Some(bucket_id) => format!("{} {role}", safe_bucket_id(bucket_id)), + None => role.to_string(), + }; + windows.push(QuotaWindow { + label: WindowLabel::Other(label), + used_percent, + resets_at, + duration_secs, + }); + } +} + +/// Escape control and non-ASCII bucket-id bytes before they reach terminal output. +fn safe_bucket_id(bucket_id: &str) -> String { + let mut safe = String::new(); + for byte in bucket_id.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-') { + safe.push(char::from(byte)); + } else { + use std::fmt::Write as _; + let _ = write!(safe, "%{byte:02X}"); + } + if safe.len() >= 64 { + safe.truncate(64); + safe.push_str("..."); + break; + } + } + if safe.is_empty() { + "unknown".to_string() + } else { + safe + } +} + +#[cfg(test)] +fn executable_command(executable: &OsStr) -> Command { + let mut command = Command::new(executable); + command.arg("app-server"); + command +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + use std::sync::OnceLock; + + static FAKE_SERVER: OnceLock<(tempfile::TempDir, PathBuf)> = OnceLock::new(); + + fn fake_server() -> &'static PathBuf { + let (_, executable) = FAKE_SERVER.get_or_init(|| { + let directory = tempfile::tempdir().expect("temporary fake-server directory"); + let source = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/codex_app_server.rs"); + let executable = directory.path().join(if cfg!(windows) { + "fake-codex.exe" + } else { + "fake-codex" + }); + let output = Command::new("rustc") + .arg("--edition=2024") + .arg(source) + .arg("-o") + .arg(&executable) + .output() + .expect("rustc is available while running Cargo tests"); + assert!( + output.status.success(), + "fake app-server failed to compile: {}", + String::from_utf8_lossy(&output.stderr) + ); + (directory, executable) + }); + executable + } + + fn fake_command(mode: &str) -> Command { + let mut command = executable_command(fake_server().as_os_str()); + command.env("EGGPASS_CODEX_TEST_MODE", mode); + command + } + + fn collect_fake_with_timeout(mode: &str, timeout: Duration) -> Option { + collect_with_command(fake_command(mode), timeout) + } + + fn collect_fake(mode: &str) -> Option { + collect_fake_with_timeout(mode, Duration::from_secs(2)) + } + + #[test] + fn account_rpc_flow_uses_only_read_methods_and_chatgpt_mode() { + let report = collect_fake("success").expect("the fake account has quota data"); + assert_eq!(report.provider, ProviderId::OpenAi); + assert_eq!(report.windows.len(), 2); + assert_eq!(report.windows[0].used_percent, Some(42.0)); + let serialized = serde_json::to_string(&report).unwrap(); + assert!(!serialized.contains("private-codex-account@example.invalid")); + + let stderr_report = collect_fake("stderr").expect("stderr does not break protocol reads"); + let stderr_report = serde_json::to_string(&stderr_report).unwrap(); + assert!(!stderr_report.contains("do-not-print-this-private-diagnostic")); + } + + #[test] + fn a_burst_of_unrelated_notifications_does_not_hide_the_matching_response() { + let report = collect_fake("notification_burst") + .expect("the bounded reader must backpressure rather than drop notifications"); + assert_eq!(report.windows.len(), 2); + } + + #[test] + fn account_modes_without_chatgpt_usage_are_unavailable() { + for mode in ["no_account", "api_key", "other_account"] { + assert!(collect_fake(mode).is_none(), "mode {mode} must not be used"); + } + } + + #[test] + fn missing_executable_and_spawn_failure_are_optional() { + let missing = tempfile::tempdir().unwrap().path().join("missing-codex"); + assert!( + collect_with_command( + executable_command(missing.as_os_str()), + Duration::from_millis(100) + ) + .is_none() + ); + } + + #[test] + fn early_exit_rpc_errors_and_malformed_output_are_optional() { + for mode in [ + "early_exit", + "initialize_error", + "account_error", + "rate_limits_error", + "malformed", + "oversized", + "stdout_total", + ] { + assert!(collect_fake(mode).is_none(), "mode {mode} must fall back"); + } + } + + #[test] + fn a_stalled_or_mismatched_rpc_cannot_hold_usage_open() { + for mode in [ + "stall_initialize", + "stall_account", + "stall_rate_limits", + "wrong_id", + "missing_id", + ] { + let started = Instant::now(); + assert!( + collect_fake_with_timeout(mode, Duration::from_millis(200)).is_none(), + "mode {mode} must fall back" + ); + assert!( + started.elapsed() < Duration::from_secs(3), + "mode {mode} exceeded the deadline" + ); + } + } + + #[test] + fn a_populated_bucket_map_is_preferred_and_keeps_all_windows() { + let report = collect_fake("multiple_buckets").expect("the map has quota data"); + assert_eq!(report.windows.len(), 3); + let labels: Vec<_> = report + .windows + .iter() + .map(|window| window.label.display()) + .collect(); + assert_eq!( + labels, + ["codex Primary", "codex Secondary", "other-model Primary"] + ); + assert_eq!(report.windows[0].used_percent, Some(42.0)); + assert_eq!(report.windows[0].resets_at, Some(1_800_000_000)); + assert_eq!(report.windows[0].duration_secs, Some(18_000)); + assert!( + !report + .windows + .iter() + .any(|window| window.used_percent == Some(99.0)) + ); + } + + #[test] + fn legacy_and_empty_bucket_map_results_are_supported() { + for mode in ["legacy", "empty_buckets"] { + let report = collect_fake(mode).expect("legacy quota data is available"); + assert_eq!(report.windows.len(), 1); + assert_eq!(report.windows[0].label.display(), "Primary"); + assert_eq!(report.windows[0].used_percent, Some(9.0)); + } + } + + #[test] + fn null_and_missing_fields_stay_unavailable_instead_of_becoming_zero() { + let report = collect_fake("nullable_fields").expect("a real zero percentage is usable"); + assert_eq!(report.windows.len(), 1); + assert_eq!(report.windows[0].used_percent, Some(0.0)); + assert_eq!(report.windows[0].duration_secs, Some(300)); + assert_eq!(report.windows[0].resets_at, None); + + assert!(collect_fake("no_data").is_none()); + } + + #[test] + fn unknown_plan_and_limit_states_do_not_masquerade_as_generic_states() { + let report = collect_fake("unknown_variants").expect("the quota window is usable"); + assert_eq!(report.plan, None); + assert_eq!(report.state, None); + } + + #[test] + fn invalid_values_are_ignored_and_duration_conversion_is_checked() { + let invalid_percent = json!({ + "rateLimits": { "primary": { "usedPercent": 150, "resetsAt": 1_800_000_000 } } + }); + let report = map_rate_limits(&invalid_percent).expect("the reset is still useful"); + assert_eq!(report.windows[0].used_percent, None); + assert_eq!(report.windows[0].resets_at, Some(1_800_000_000)); + + let overflow = json!({ + "rateLimits": { "primary": { "usedPercent": null, "windowDurationMins": i64::MAX } } + }); + assert!(map_rate_limits(&overflow).is_none()); + } + + #[test] + fn bucket_ids_cannot_inject_terminal_control_sequences() { + let result = json!({ + "rateLimitsByLimitId": { + "codex\u{1b}[31m": { "primary": { "usedPercent": 10 } } + } + }); + let report = map_rate_limits(&result).unwrap(); + assert_eq!(report.windows[0].label.display(), "codex%1B%5B31m Primary"); + } + + #[test] + fn each_jsonl_record_is_bounded_and_must_be_terminated() { + assert!(read_bounded_line(&mut BufReader::new(&b"12345\n"[..]), 4).is_err()); + assert!(read_bounded_line(&mut BufReader::new(&b"unterminated"[..]), 20).is_err()); + assert_eq!( + read_bounded_line(&mut BufReader::new(&b"{}\n"[..]), 2).unwrap(), + Some(b"{}".to_vec()) + ); + } + + #[test] + fn notification_records_are_ignored_until_the_matching_id_arrives() { + let (sender, receiver) = mpsc::channel(); + sender + .send(Ok(br#"{"method":"account/updated"}"#.to_vec())) + .unwrap(); + sender + .send(Ok(br#"{"id":99,"result":{}}"#.to_vec())) + .unwrap(); + sender + .send(Ok(br#"{"id":1,"result":{"ready":true}}"#.to_vec())) + .unwrap(); + let result = receive_response(&receiver, 1, Instant::now() + Duration::from_secs(1)); + assert_eq!(result, Some(json!({"ready": true}))); + } + + #[test] + fn source_label_does_not_expose_the_account_identity() { + assert!(SOURCE_LABEL.contains("Codex app-server")); + assert!(SOURCE_LABEL.contains("may differ from Eggpass inference account")); + assert!(!SOURCE_LABEL.contains('@')); + } +} diff --git a/src/provider/usage/mod.rs b/src/provider/usage/mod.rs index be86db0..15ca8b5 100644 --- a/src/provider/usage/mod.rs +++ b/src/provider/usage/mod.rs @@ -22,6 +22,7 @@ //! truth is "the provider did not say". Every percentage is therefore an //! [`Option`], and there is no `unwrap_or(0.0)` anywhere on this path. +pub mod codex_app_server; pub mod openai; pub mod xai; diff --git a/src/provider/usage/openai.rs b/src/provider/usage/openai.rs index 7a64610..77adb4b 100644 --- a/src/provider/usage/openai.rs +++ b/src/provider/usage/openai.rs @@ -1,22 +1,10 @@ -//! The ChatGPT usage collector. +//! The Sign in with ChatGPT (SIWC) usage fallback. //! -//! ChatGPT has no usable quota endpoint for a Sign in with ChatGPT -//! credential, and that is not a gap in this implementation — it is the -//! documented shape of the thing. -//! -//! The Codex app-server does expose `account/rateLimits/read`, and the -//! response shape is exactly right: `usedPercent` is an integer 0–100, -//! `resetsAt` is unix seconds, `planType` enumerates the plans. But the -//! app-server reads a *Codex-managed* ChatGPT login out of -//! `$CODEX_HOME/auth.json`, and behind that call it reaches a private, -//! undocumented consumer backend, `chatgpt.com/backend-api/wham/usage`, which -//! needs a `chatgpt-account-id` header. A Sign in with ChatGPT credential -//! carries no workspace id, and there is no documented way to read one out of -//! it: the SIWC documentation says plainly that *"Email and `sub` are not -//! workspace identifiers"* — the workspace is bound server-side to the issued -//! client id. Refreshing there would break as well, because Codex refreshes -//! with its own client id and a foreign refresh token does not refresh -//! there. +//! The optional Codex app-server source is queried separately by +//! [`super::codex_app_server`]. This collector describes only what Eggpass's +//! own SIWC credential can report: the SIWC API does not expose quota windows, +//! so the honest fallback is an unavailable result with the provider's +//! documented signals and usage page. //! //! The SIWC documentation enumerates every endpoint it defines, and none of //! them returns quota. The only quota signals it publishes are error codes, diff --git a/tests/fixtures/codex_app_server.rs b/tests/fixtures/codex_app_server.rs new file mode 100644 index 0000000..ed8d418 --- /dev/null +++ b/tests/fixtures/codex_app_server.rs @@ -0,0 +1,196 @@ +use std::io::{self, BufRead, Write}; +use std::thread; +use std::time::Duration; + +fn main() { + let mode = std::env::var("EGGPASS_CODEX_TEST_MODE").unwrap_or_default(); + let stdin = io::stdin(); + let mut stdout = io::stdout().lock(); + let mut stage = 0_u8; + + for line in stdin.lock().lines() { + let Ok(line) = line else { return }; + let method = if line.contains("\"method\":\"initialize\"") { + Some("initialize") + } else if line.contains("\"method\":\"initialized\"") { + Some("initialized") + } else if line.contains("\"method\":\"account/read\"") { + Some("account/read") + } else if line.contains("\"method\":\"account/rateLimits/read\"") { + Some("account/rateLimits/read") + } else { + None + }; + let Some(method) = method else { return }; + + if mode == "early_exit" { + return; + } + if mode == "stall_initialize" && method == "initialize" { + thread::sleep(Duration::from_secs(30)); + return; + } + if mode == "stall_account" && method == "account/read" { + thread::sleep(Duration::from_secs(30)); + return; + } + if mode == "stall_rate_limits" && method == "account/rateLimits/read" { + thread::sleep(Duration::from_secs(30)); + return; + } + + match method { + "initialize" => { + if stage != 0 + || !line.contains("\"name\":\"eggpass\"") + || !line.contains("\"version\":") + || line.contains("\"experimentalApi\":true") + { + send_error(&mut stdout, id(&line), "bad initialize request"); + return; + } + stage = 1; + if mode == "malformed" { + let _ = writeln!(stdout, "not-json"); + let _ = stdout.flush(); + return; + } + if mode == "oversized" { + let _ = writeln!(stdout, "{}", "x".repeat(300 * 1024)); + let _ = stdout.flush(); + return; + } + if mode == "stdout_total" { + let payload = "x".repeat(220 * 1024); + for _ in 0..5 { + let _ = writeln!( + stdout, + "{{\"method\":\"noise\",\"params\":{{\"data\":\"{payload}\"}}}}" + ); + } + let _ = stdout.flush(); + thread::sleep(Duration::from_secs(30)); + return; + } + if mode == "stderr" { + eprintln!("do-not-print-this-private-diagnostic"); + } + if mode == "initialize_error" { + send_error(&mut stdout, id(&line), "initialization failed"); + return; + } + if mode == "wrong_id" { + send_response( + &mut stdout, + Some(id(&line).unwrap_or(0) + 99), + "{\"ready\":true}", + ); + continue; + } + if mode == "missing_id" { + let _ = writeln!(stdout, "{{\"result\":{{\"ready\":true}}}}"); + let _ = stdout.flush(); + continue; + } + if mode == "notification_burst" { + for _ in 0..64 { + let _ = + writeln!(stdout, "{{\"method\":\"account/updated\",\"params\":{{}}}}"); + } + send_response(&mut stdout, id(&line), "{\"ready\":true}"); + continue; + } + let _ = writeln!(stdout, "{{\"method\":\"account/updated\",\"params\":{{}}}}"); + send_response(&mut stdout, id(&line), "{\"ready\":true}"); + } + "initialized" => { + if stage != 1 { + return; + } + stage = 2; + } + "account/read" => { + if stage != 2 || !line.contains("\"refreshToken\":false") { + send_error(&mut stdout, id(&line), "bad account request"); + return; + } + stage = 3; + if mode == "account_error" { + send_error(&mut stdout, id(&line), "account read failed"); + return; + } + let account = match mode.as_str() { + "no_account" => "null", + "api_key" => "{\"type\":\"apiKey\"}", + "other_account" => "{\"type\":\"gcp\"}", + _ => { + "{\"type\":\"chatgpt\",\"email\":\"private-codex-account@example.invalid\"}" + } + }; + send_response( + &mut stdout, + id(&line), + &format!("{{\"account\":{account}}}"), + ); + } + "account/rateLimits/read" => { + if stage != 3 { + send_error(&mut stdout, id(&line), "bad rate-limits request"); + return; + } + if mode == "rate_limits_error" { + send_error(&mut stdout, id(&line), "rate limits read failed"); + return; + } + let result = rate_limits(&mode); + send_response(&mut stdout, id(&line), result); + return; + } + _ => return, + } + } +} + +fn id(line: &str) -> Option { + let tail = line.split_once("\"id\":")?.1; + let digits: String = tail.chars().take_while(char::is_ascii_digit).collect(); + digits.parse().ok() +} + +fn send_response(stdout: &mut impl Write, id: Option, result: &str) { + let Some(id) = id else { return }; + let _ = writeln!(stdout, "{{\"id\":{id},\"result\":{result}}}"); + let _ = stdout.flush(); +} + +fn send_error(stdout: &mut impl Write, id: Option, message: &str) { + let Some(id) = id else { return }; + let _ = writeln!( + stdout, + "{{\"id\":{id},\"error\":{{\"code\":-32000,\"message\":\"{message}\"}}}}" + ); + let _ = stdout.flush(); +} + +fn rate_limits(mode: &str) -> &'static str { + match mode { + "multiple_buckets" => { + r#"{"rateLimitsByLimitId":{"codex":{"primary":{"usedPercent":42,"windowDurationMins":300,"resetsAt":1800000000},"secondary":{"usedPercent":0,"windowDurationMins":10080,"resetsAt":1801000000},"planType":"future_plan","rateLimitReachedType":"workspace_owner_credits_depleted"},"other-model":{"primary":{"usedPercent":25}}},"rateLimits":{"primary":{"usedPercent":99}}}"# + } + "legacy" | "empty_buckets" => { + r#"{"rateLimitsByLimitId":{},"rateLimits":{"primary":{"usedPercent":9,"windowDurationMins":60,"resetsAt":1800000000}}}"# + } + "nullable_fields" => { + r#"{"rateLimitsByLimitId":{"codex":{"primary":{"usedPercent":null,"windowDurationMins":null,"resetsAt":null},"secondary":{"usedPercent":0,"windowDurationMins":5}},"empty":{"primary":{"usedPercent":null,"windowDurationMins":null,"resetsAt":null}}}}"# + } + "no_data" => { + r#"{"rateLimitsByLimitId":{},"rateLimits":{"primary":{"usedPercent":null,"windowDurationMins":null,"resetsAt":null}}}"# + } + "unknown_variants" => { + r#"{"rateLimits":{"primary":{"usedPercent":12,"planType":"future_plan","rateLimitReachedType":"workspace_member_credits_depleted"}}}"# + } + _ => { + r#"{"rateLimits":{"primary":{"usedPercent":42,"windowDurationMins":300,"resetsAt":1800000000},"secondary":{"usedPercent":7,"windowDurationMins":10080,"resetsAt":1801000000}}}"# + } + } +} From bd8c5313f9ceafc296cc0eba17db3ee2fe620c2c Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Tue, 17 Nov 2026 19:04:38 +0000 Subject: [PATCH 02/11] fix: satisfy latest Clippy in Codex usage reader --- src/provider/usage/codex_app_server.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/provider/usage/codex_app_server.rs b/src/provider/usage/codex_app_server.rs index 25a4b89..46ca086 100644 --- a/src/provider/usage/codex_app_server.rs +++ b/src/provider/usage/codex_app_server.rs @@ -200,7 +200,7 @@ fn read_bounded_line(reader: &mut impl BufRead, limit: usize) -> io::Result Date: Wed, 18 Nov 2026 19:49:34 +0000 Subject: [PATCH 03/11] feat: add cached daemon usage API --- docs/commands.md | 10 +- docs/configuration.md | 2 +- docs/how-it-works.md | 8 +- plans/daemon-usage-api-implementation.md | 129 ++++ src/cli/commands/run.rs | 33 +- src/cli/commands/usage.rs | 151 +++-- src/provider/mod.rs | 8 - src/provider/usage/codex_app_server.rs | 23 +- src/provider/usage/mod.rs | 23 +- src/provider/usage/openai.rs | 13 +- src/provider/usage/report.rs | 173 +++++ src/provider/usage/xai.rs | 145 +++-- src/server/chat.rs | 2 +- src/server/mod.rs | 18 +- src/server/models.rs | 2 +- src/server/router.rs | 5 + src/server/tests.rs | 170 ++++- src/server/usage.rs | 769 +++++++++++++++++++++++ 18 files changed, 1506 insertions(+), 178 deletions(-) create mode 100644 plans/daemon-usage-api-implementation.md create mode 100644 src/provider/usage/report.rs create mode 100644 src/server/usage.rs diff --git a/docs/commands.md b/docs/commands.md index e519921..a714334 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -66,10 +66,18 @@ eggpass usage --provider xai # query one provider eggpass usage --json # machine-readable report ``` -Queries provider usage directly, without needing the daemon. This is a fresh request, not a cached or polled reading. Human-readable output shows the percentage and bar for the allowance left, plus each available reset time and countdown; JSON preserves the provider-reported fields. On the default xAI `api` upstream, the reported consumer-subscription quota is separate from inference requests, which are billed to the xAI API tier. The report's caption reflects the configured upstream. If quota is unavailable, the report may include the latest inference HTTP status kept by the daemon in memory. That endpoint reports only per-provider client-facing HTTP status codes, not prompts or response bodies. +Queries provider usage directly, without needing the daemon. By default it queries only providers enabled in configuration. `--provider` can select one enabled provider; selecting a disabled provider, or running the command when none are enabled, returns an actionable configuration error. Human-readable output shows the percentage and bar for the allowance left, plus each available reset time and countdown; JSON preserves the provider-reported fields. On the default xAI `api` upstream, the reported consumer-subscription quota is separate from inference requests, which are billed to the xAI API tier. The report's caption reflects the configured upstream. If quota is unavailable, the report may include the latest inference HTTP status kept by the daemon in memory. That endpoint reports only per-provider client-facing HTTP status codes, not prompts or response bodies. **Exit codes:** `0` if at least one provider is signed in and not every selected provider failed operationally, `1` if every selected provider failed operationally, `2` if none is signed in. +### Authenticated daemon endpoint: GET /v1/usage + +The daemon also serves `GET /v1/usage` for clients that need a usage report over HTTP. Send the configured or issued Eggpass client key in `Authorization: Bearer ` or `X-Api-Key: `. The response body uses the same `{"providers":[...]}` JSON structure as `eggpass usage --json`; it includes only enabled providers. If every provider is disabled, the endpoint returns a completed empty list. OpenAI/ChatGPT usage is queried only when that provider is enabled; the optional Codex app-server result may describe a different account from Eggpass's inference credential. + +A complete report is retained only in daemon memory for 600 seconds from completion. Cache hits do not contact providers. A cold or expired request starts one shared refresh and its initiating client waits at most 30 seconds; if still running, that client receives `504` and the refresh continues. Other requests while it is active receive `202` with `Retry-After`. Timed-out providers alone are retried, for at most three retries after the initial attempt, spaced 5, 15, and 30 seconds apart. xAI usage HTTP requests have bounded 15-second request/body timeouts (and a 5-second connect cap); OAuth refresh requests have a 60-second total deadline, and the optional local Codex session has an 8-second deadline. + +On success, responses include `Cache-Control: private, no-store`, `X-Eggpass-Usage-Age` (integer seconds), and `X-Eggpass-Usage-Updated-At` (RFC 3339 UTC). `last_inference` is attached from the daemon's current in-memory state on each response. After all timeout retries fail, the last successful report is returned with `X-Eggpass-Usage-Stale: true` during a 600-second cooldown; if no successful report exists, the endpoint returns `503` with `Retry-After`. A process restart clears the snapshot and cooldown. There is no polling, disk persistence, or force-refresh operation. + ## `run`, `stop`, and `restart` ```sh diff --git a/docs/configuration.md b/docs/configuration.md index b3251a1..5b8d3ed 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -74,7 +74,7 @@ The advanced `[oauth.xai]` settings are `client_id`, `issuer`, `scopes`, and `re A client key is required to start the server, including when it listens only on loopback. Use `eggpass key add` to create a numbered, revocable key, or set `api_key` for one static key. The static key is readable in the config. Issued keys are shown once and stored as salted hashes. Clients may send either as `Authorization: Bearer ` or `X-Api-Key: `. -The server listens on loopback by default. Binding to a non-loopback address exposes the proxy and the provider accounts it can use to the network. A key is required for that bind. The `GET /health` and `GET /v1/last-inference` probes are unauthenticated: health returns a JSON object with `status`, `service`, and a version string; last-inference returns only per-provider client-facing HTTP status codes. All other API requests require a valid key. +The server listens on loopback by default. Binding to a non-loopback address exposes the proxy and the provider accounts it can use to the network. A key is required for that bind. The `GET /health` and `GET /v1/last-inference` probes are unauthenticated: health returns a JSON object with `status`, `service`, and a version string; last-inference returns only per-provider client-facing HTTP status codes. `GET /v1/usage` is not an unauthenticated probe: it requires a valid Eggpass client key like every other data endpoint. It returns quota data for enabled providers, so do not expose it without protecting the server. Eggpass runs locally, but inference requests are sent to the provider selected by routing. Prompts and request content are transmitted to xAI or ChatGPT for inference; they do not stay on this machine. `eggpass usage` also contacts providers directly to query usage, and `eggpass status` may contact them to count available models. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 518a5b7..acca352 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -73,11 +73,9 @@ Streaming responses are forwarded as chunks arrive. The proxy does not buffer the full answer before sending it to the client. Provider errors keep their status codes and error details where supported. -The `eggpass usage` command fetches current usage where a provider exposes it. -For ChatGPT, the OAuth flow has no quota endpoint, so the command reports usage -as unavailable rather than estimating it. The daemon keeps only the most recent -client-facing inference status for each provider in memory. It is not written -to a file and disappears when the daemon stops. +The `eggpass usage` command fetches current usage where a provider exposes it, and both it and the daemon endpoint query only providers enabled in configuration. For ChatGPT, the OAuth flow has no quota endpoint, so usage is unavailable rather than estimated; when OpenAI is enabled, the optional local Codex app-server may provide a report from a separate account. + +The authenticated `GET /v1/usage` endpoint returns the CLI-compatible JSON report. It caches one complete snapshot in memory for 10 minutes, starts at most one demand-triggered refresh, and never polls or writes usage data to disk. Its initiating request waits up to 30 seconds; if that deadline expires it gets `504` while the finite refresh continues. Concurrent requests get `202` with `Retry-After`. A refresh retries only timed-out providers, up to three times at 5/15/30-second intervals. Each xAI billing/settings request is capped at 15 seconds; OAuth refresh has a 60-second total deadline and Codex has an 8-second session deadline. Success adds age and update-time headers; after retry exhaustion, a previous successful snapshot is marked stale during a 10-minute cooldown, or `503` is returned if no good snapshot exists. A daemon restart clears the cache. The latest inference status is read afresh for every report response. ## Updates diff --git a/plans/daemon-usage-api-implementation.md b/plans/daemon-usage-api-implementation.md new file mode 100644 index 0000000..1256b6a --- /dev/null +++ b/plans/daemon-usage-api-implementation.md @@ -0,0 +1,129 @@ +# On-Demand Daemon Usage API — Implementation Plan + +**Status:** Implemented; final automated checks and installed-binary smoke test passed. + +**Implementation and verification:** Added the authenticated in-memory usage API, enabled-provider reporting shared with the CLI, finite timeout retries, freshness metadata, tests, and endpoint documentation. `cargo fmt --all`, `cargo check --workspace --all-targets --locked`, `cargo test --workspace --all-targets --locked`, strict workspace Clippy, and `git diff --check` passed (368 Eggpass tests, 30 auth-crate tests, and 10 OAuth integration tests). Installed from this checkout with `cargo install --path . --locked --force`; `/Users/davidbowman/.cargo/bin/eggpass --version` reports `0.1.1`. An isolated installed-binary smoke test verified unauthenticated `401`, authenticated `200` with `{"providers":[]}` when both providers are disabled, `Cache-Control`/age/update headers, and reuse of the cached timestamp. The smoke test made no live provider calls. + +**Research checked:** 2026-11-18 against the current `eggpass` source and docs. + +**Scope:** Add an authenticated daemon endpoint that returns the same machine-readable usage report as `eggpass usage --json`, with both paths collecting only providers enabled in configuration. Collect only when requested, retain one recent report in daemon memory for a 10-minute TTL, and allow only a finite, demand-triggered background retry job after a client wait timeout; no scheduled/background polling or file persistence. + +## Goal + +Provide Gregg and other authorized clients a stable JSON usage endpoint without letting frequent polling cause frequent provider queries. For a given cache snapshot, requests inside the TTL reuse the same report. Once it is absent or expired, one request triggers a refresh; concurrent misses share that refresh. The cache disappears on daemon shutdown/restart. + +The initial endpoint is proposed as `GET /v1/usage`. It must not expose provider credentials, account email, or raw upstream payloads. + +## Repository baseline and implementation seams + +- `src/cli/commands/usage.rs:127-180` currently builds a report for all `ProviderId`s by default, adds each provider's source/caption and last-inference status, then prints either human-readable text or JSON. The JSON wrapper is `{"providers":[...]}`. The CLI's `ProviderEntry` and `UsageReportJson` types and collection functions are private (`src/cli/commands/usage.rs:211-299`). The selected behavior is to change the CLI and API collection to include only providers enabled in configuration. +- The serialized provider outcomes are already structured and reusable: `ProviderUsage` has `reported`, `not_signed_in`, `unavailable`, and `failed` states, and `UsageReport` carries normalized windows, breakdown, credits, and state (`src/provider/usage/mod.rs:33-48,162-193`). xAI's caption explains which billing pool the numbers represent. +- xAI collection calls the billing endpoint, then best-effort fetches settings for the plan name (`src/provider/usage/xai.rs:71-153,188-206`). Those requests use the configured provider timeouts. The defaults allow up to 30 minutes for the global/body timeout (`src/config.rs:252-274`; `src/upstream.rs:138-148`). +- OpenAI usage first tries the local `codex app-server`, then falls back to the Eggpass Sign in with ChatGPT collector (`src/cli/commands/usage.rs:252-282`). The Codex helper has an eight-second session deadline (`src/provider/usage/codex_app_server.rs:21-38`). The SIWC fallback does not query quota; it returns an explicit unavailable result (`src/provider/usage/openai.rs:45-61`). A daemon using this path needs `codex` available on its `PATH` to return the optional Codex result, and that account may differ from the Eggpass inference account. +- The daemon already keeps last inference statuses in memory (`src/server/mod.rs:89-94`, `src/inference.rs:10-35`) and serves them at `/v1/last-inference` (`src/server/inference.rs:19-27`). +- Routes are added in `src/server/router.rs:5-45`; request routing and authorization are in `src/server/mod.rs:231-335`. Only `/health` and `/v1/last-inference` are exempt from API-key authorization. The authority guard remains active for them as well (`src/server/guard.rs:20-48`). The HTTP server handles connections on separate threads (`src/server/http.rs:197-245`). +- `ServerContext` currently has no usage cache, full config, or paths (`src/server/mod.rs:60-94`). The daemon creates `ProviderHandle`s only for enabled providers (`src/cli/commands/run.rs:198-215`), while the CLI usage command currently iterates all providers. The selected behavior is to change the CLI to use the daemon's enabled-provider scope; when OpenAI/ChatGPT is disabled, do not invoke the optional Codex usage process. A shared collector must not create independent `TokenManager`s for enabled providers: separate refresh mutexes could race while rotating the same credentials. +- The historical shipped plan notes that `GET /v1/usage` was deferred when no reliable usage path existed (`plans/shipped-2026-11-13.md:161-163`). The CLI usage collectors now provide the report path this API can reuse. + +## Proposed first-release behavior + +1. **Route and methods:** Add `GET /v1/usage`. Existing path normalization means `/usage` also resolves consistently for clients whose base URL already ends in `/v1`. Other methods return the existing `405` response with `Allow: GET`. Treat this as a bodyless GET in the request-body gate (`src/server/mod.rs:240-249`). +2. **Authorization:** Require a valid Eggpass client key. Do not add this route to the unauthenticated probe exceptions. Reject unauthorized requests before consulting the cache or starting collection. Preserve the existing Host/authority guard. +3. **Response compatibility and provider scope:** Reuse the CLI JSON schema: top-level `providers` array, provider outcome/status, optional source, caption, and last-inference field. Change both the CLI and API to collect only providers enabled in configuration; omit disabled providers from the array and do not invoke Codex when OpenAI is disabled. Return HTTP 200 when a report is complete, including provider-level `failed`, `unavailable`, or `not_signed_in` outcomes. A request that reaches its refresh wait deadline before a report is ready returns a timeout response instead. +4. **Cache policy:** Keep one most-recent complete usage snapshot and its completion time in process memory, shared through `ServerContext`. Use `Instant` for expiry and a 600-second TTL from a completed collection; structured provider outcomes such as unavailable or non-timeout failures are still complete results. Do not persist the report or add a periodic polling task. A restart starts cold. +5. **Demand-triggered refresh and client deadline:** A cache miss/expiry starts one refresh job. The initiating request waits at most 30 seconds; if the refresh is still running, return an HTTP timeout to that client while allowing the already-started job to continue. Do not hold the cache mutex while provider calls or process startup run. No client timeout may start a duplicate job. +6. **Finite background retries:** If a provider collection times out, keep the same demand-triggered job alive and retry only that provider, up to three times after the initial attempt, with delays of 5, 15, and 30 seconds. Do not repeat successful provider collections. If retries succeed, atomically store the completed report and start its 600-second TTL then. This is a finite retry sequence, not scheduled/background polling. If the client wait expires, return 504; later requests during the active job return 202 with `Retry-After`. On exhaustion, preserve the last good report as stale and apply a 600-second cooldown; if no good report exists, return 503 with `Retry-After`. +7. **Last inference:** Attach the daemon's current `InferenceState` snapshot when serializing each response. The CLI obtains last-inference information afresh (`src/cli/commands/usage.rs:412-449`); caching the complete assembled JSON would make that field stale for up to ten minutes. +8. **Freshness and HTTP caching:** Keep the JSON body compatible and return `Cache-Control: private, no-store`. Add `X-Eggpass-Usage-Age` as integer seconds and `X-Eggpass-Usage-Updated-At` as an RFC 3339 UTC timestamp. Add `X-Eggpass-Usage-Stale: true` when returning a previously successful snapshot after refresh retries have been exhausted. +9. **Bounded collection:** Use a 30-second client wait deadline independent of the existing provider timeout defaults, which allow up to 30 minutes for an xAI request (`src/config.rs:252-274`; `src/upstream.rs:138-148`). The background retry job must also be finite and must not keep a request handler occupied after the client deadline. + +## User-selected decisions + +On 2026-11-18, the user selected: + +- **Provider scope:** Query only providers enabled in configuration. Change the CLI usage command to match the API; omit disabled providers from the `providers` array. If OpenAI/ChatGPT is disabled, do not invoke the Codex usage process. +- **Client wait deadline and retries:** Give a client at most 30 seconds to wait for a cache-miss/expired-cache refresh. If the response deadline expires, return a timeout to that client but continue the same finite refresh job in the background, with up to three spaced retries after a timeout. Store the result in memory if a retry succeeds. The retry job is demand-triggered and must not become periodic polling. +- **Freshness metadata:** Preserve the CLI-compatible JSON body and add `X-Eggpass-Usage-Age` (integer seconds) and `X-Eggpass-Usage-Updated-At` (RFC 3339 UTC timestamp) response headers. Also set `Cache-Control: private, no-store`. + +## Confirmed timeout/retry policy + +On 2026-11-18, the user selected the following details: + +- One initial attempt plus up to three retries (four attempts maximum), with retry delays of 5, 15, and 30 seconds. Retry only the provider whose collection timed out; do not repeat successful provider collections. +- The request that starts a cold/expired refresh waits up to 30 seconds, then returns HTTP 504 if the report is still being refreshed. The demand-triggered refresh job continues independently of that response. +- A later request while the same job is active returns HTTP 202 with `Retry-After`, rather than holding another request thread open or starting another refresh. +- If retries are exhausted, retain the previous successful report as stale and start an in-memory 600-second retry cooldown. Return the stale report with its age/update headers plus `X-Eggpass-Usage-Stale: true`. If no successful report exists, return HTTP 503 with `Retry-After` during the cooldown. + +The 600-second success-cache TTL begins when a new report is stored. The separate cooldown begins after the final failed attempt. Neither a timeout response nor a pending response writes to disk or starts periodic polling. + +## Implementation stages + +### Stage 0 — Confirm API and cache contract + +- Implement the selected `GET /v1/usage` contract: API-key authentication, enabled providers only in both CLI and API, 30-second client wait, finite timeout retries, freshness headers, and a 600-second in-memory success-cache TTL. +- Implement the confirmed retry count/spacing, 202 pending response, stale-snapshot, and 600-second cooldown behavior after retries are exhausted. +- Keep the implementation process-local and single-snapshot; no database, file, cross-process cache, or periodic refresh scheduler. + +**Exit:** The route, report provider set, freshness contract, retry lifecycle, failure behavior, and latency bounds are explicit. + +### Stage 1 — Extract reusable usage collection/report assembly + +- Move the serializable report DTO and provider collection/assembly logic out of the CLI-only private implementation into a shared usage service or provider-usage module. +- Preserve the CLI JSON schema, source labels, xAI caption, provider order, and Codex-first OpenAI behavior for providers enabled in configuration. +- Change the CLI's provider selection to filter by `config.providers.get(id).enabled`; disabled providers are omitted, and a disabled OpenAI provider must not start `codex app-server`. +- Provide daemon collection access to the necessary configuration and provider credentials without duplicating `TokenManager` refresh locks. +- Keep `last_inference` supplied from current daemon state at response time. + +**Exit:** CLI tests preserve the existing JSON/text formatting for enabled providers while explicitly covering the new disabled-provider filtering; the shared collector can be called from both CLI and daemon paths without live-account requirements in tests. + +### Stage 2 — Add the daemon route and TTL cache + +- Add the `Usage` route and `GET` dispatch; make it bodyless and subject to existing authority and client-key checks. +- Add a small cache state to the shared server context: optional last successful snapshot, monotonic completion time, one demand-triggered refresh job, in-progress coordination, and a retry cooldown. +- Implement cache-hit, cold-miss, expiry, single-flight, and 30-second client wait behavior. A timed-out client does not cancel the finite retry job; later requests while it is active receive `202` with `Retry-After`. Keep provider calls outside the cache lock and avoid logging report bodies or credentials. +- Preserve completed provider outcomes in the active refresh candidate and retry only timed-out providers, up to three retries after the initial attempt (5/15/30 seconds). Do not repeat successful provider collections. Commit the complete candidate atomically on success; after exhaustion, retain the last complete report as stale with a 600-second cooldown, or return `503` with `Retry-After` if no good report exists. Set `Retry-After` to the next scheduled retry or the remaining cooldown, as applicable. + +- Serialize the shared report in the existing schema and add `Cache-Control: private, no-store`, age/update headers, and a stale marker on stale responses. + +**Exit:** Fresh requests are served from memory; a miss starts one finite refresh job; concurrent misses do not duplicate provider calls; the 504/202/stale/503 behavior is implemented; no periodic refresh or disk activity is introduced. + +### Stage 3 — Test behavior without live provider calls + +- Unit-test the cache/refresh worker with an injected collector and controllable clock: cold miss, fresh hit, expiry, 30-second caller timeout without job cancellation, spaced retries, single-flight across concurrent callers, success timestamp/TTL, retry exhaustion, and empty cache after a new daemon instance. +- Extend server integration tests for path routing, `GET`/405 behavior, bodyless handling, required key, Host guard, JSON shape, freshness headers, 202/504/503 responses and `Retry-After`, and no collection on unauthorized requests. +- Use fake upstream/collector seams to assert the number of billing/settings requests across cold, fresh, timeout, retry, and expired requests. Existing xAI collection uses hard-coded live endpoints, so provide injection for tests instead of calling those endpoints. +- Cover OpenAI's Codex success/fallback behavior using its existing fake-process pattern; assert that disabled OpenAI does not launch Codex and that no email, token, or raw upstream/process payload appears in the API body or logs. +- Verify `last_inference` freshness behavior, provider-level failure responses, CLI filtering to enabled providers, and preservation of the CLI JSON schema/format for enabled providers. Test 504 on the initial client deadline, 202 plus `Retry-After` while the shared job remains active, stale-data headers/cooldown after retry exhaustion, and 503 plus `Retry-After` when no prior report exists. + +**Exit:** Cache and route tests are deterministic, parallel expiry tests prove one refresh, and no test depends on a live account or external provider service. + +### Stage 4 — Document and review + +- Document the endpoint, response examples, key requirement, 10-minute report TTL, 30-second client wait, finite timeout-retry schedule, 202/504/503 behavior, freshness/stale headers, cooldown, restart behavior, and the optional Codex account distinction. +- Update current endpoint and security references in `docs/configuration.md`, `docs/how-it-works.md`, `docs/commands.md`, and any maintained API route list. +- Run formatting, Clippy, workspace tests, relevant server/usage tests, and `git diff --check`; review the scoped diff and preserve unrelated worktree changes. + +**Exit:** API docs agree with route/auth behavior; checks pass; no unrelated changes are staged or overwritten. + +## Acceptance checklist + +- [x] `GET /v1/usage` returns the CLI-compatible `providers` JSON shape for enabled providers only. +- [x] The CLI also collects only providers enabled in configuration; disabled OpenAI never invokes Codex, and disabled providers are omitted from the report. +- [x] Route requires an Eggpass key and keeps the authority guard; unauthorized requests never collect usage. +- [x] A cold/expired request waits at most 30 seconds; on expiry the client receives 504 while the single refresh job continues. +- [x] Timed-out provider collections get at most three retries after the initial attempt, at 5/15/30-second spacing; only the timed-out provider is retried, and success stores the complete report with a 600-second TTL. +- [x] Later requests during an active refresh receive 202 with `Retry-After`; they neither block another server thread nor start duplicate upstream collection. +- [x] After exhausted retries, a previous report is returned as stale with age/update/stale headers during a 600-second cooldown; with no prior report, the API returns 503 with `Retry-After`. +- [x] Response headers expose age and update time; the body remains CLI-compatible and uses no-store HTTP caching. +- [x] Usage data exists only in daemon memory; there is no scheduled or open-ended polling, disk persistence, or forced-refresh endpoint. +- [x] Last-inference values are fresh per response. +- [x] Tests use controlled collectors/stubs; no live account/provider service is required. +- [x] CLI formatting/schema remains compatible for enabled providers; docs describe provider filtering, auth, cache/retry behavior, latency, headers, and Codex account sourcing. + +## Out of scope + +- Changing provider OAuth, inference, token storage, or the `eggpass usage` command's meaning. +- Periodic or open-ended provider polling, writing usage snapshots to files, or retaining usage history. A finite set of spaced retries is in scope only for a refresh already triggered by an API request. +- Adding a public unauthenticated usage route, force-refresh query parameter, or configurable TTL in the first version. +- Adding OpenAI quota support through undocumented ChatGPT endpoints; the existing SIWC fallback remains unavailable unless Codex app-server supplies a report. +- Inspecting or changing the `eggstack/gregg` repository as part of this daemon-only implementation plan. diff --git a/src/cli/commands/run.rs b/src/cli/commands/run.rs index 4c9085b..f03abed 100644 --- a/src/cli/commands/run.rs +++ b/src/cli/commands/run.rs @@ -210,7 +210,7 @@ fn serve(context: &Context) -> Result<(), CommandError> { ProviderHandle { spec: runtime.spec, upstream, - tokens: runtime.tokens, + tokens: std::sync::Arc::new(runtime.tokens), }, ); } @@ -229,6 +229,36 @@ fn serve(context: &Context) -> Result<(), CommandError> { .map_err(|err| CommandError::new(err.to_string()))?, ); + let usage_provider_ids: Vec = ProviderId::all() + .into_iter() + .filter(|provider| providers.contains_key(provider)) + .collect(); + let usage_tokens: HashMap> = + providers + .iter() + .map(|(provider, handle)| (*provider, std::sync::Arc::clone(&handle.tokens))) + .collect(); + let usage_xai_upstream = context.config.providers.xai.upstream; + let usage_timeouts = crate::provider::usage::report::bounded_timeouts(context.config.timeouts); + let usage_cache = std::sync::Arc::new(crate::server::usage::UsageCache::new( + usage_provider_ids, + move |provider| { + let tokens = usage_tokens + .get(&provider) + .expect("the usage provider is enabled in the daemon"); + let codex = (provider == ProviderId::OpenAi) + .then(crate::provider::usage::codex_app_server::collect_detailed); + crate::provider::usage::report::collect_entry( + provider, + usage_xai_upstream, + tokens, + usage_timeouts, + codex, + crate::provider::usage::xai::BILLING_BASE_URL, + ) + }, + )); + let server_context = Arc::new(ServerContext { host: context.config.host.clone(), port: context.config.port, @@ -242,6 +272,7 @@ fn serve(context: &Context) -> Result<(), CommandError> { // The status of the last inference to each provider, kept in memory // for `eggpass usage` to report. inferences: Arc::new(crate::inference::InferenceState::new()), + usage_cache, }); daemon::write_info( diff --git a/src/cli/commands/usage.rs b/src/cli/commands/usage.rs index 8bb2ee0..7d68345 100644 --- a/src/cli/commands/usage.rs +++ b/src/cli/commands/usage.rs @@ -24,10 +24,11 @@ use std::collections::{BTreeMap, BTreeSet}; use std::time::Duration; -use serde::Serialize; - use crate::cli::{CommandError, Context}; use crate::daemon::{self, DaemonState}; +#[cfg(test)] +use crate::provider::usage::report::codex_outcome; +use crate::provider::usage::report::{ProviderEntry, UsageReportJson, enabled_provider_ids}; use crate::provider::usage::{ProviderUsage, UsageReport, WindowLabel}; use crate::provider::{ProviderId, ProviderRuntime}; use crate::timeutil; @@ -56,10 +57,7 @@ pub fn usage( provider: Option, json: bool, ) -> Result<(), CommandError> { - let providers: Vec = match provider { - Some(provider) => vec![provider], - None => ProviderId::all().to_vec(), - }; + let providers = selected_provider_ids(provider, &context.config)?; // What the last inference to each provider was answered with. The daemon // keeps it in memory, so there is nothing to read when it is not @@ -102,6 +100,30 @@ pub fn usage( usage_exit_result(&entries) } +/// Resolve the CLI's explicit provider choice against the enabled-provider policy. +fn selected_provider_ids( + requested: Option, + config: &crate::config::Config, +) -> Result, CommandError> { + match requested { + Some(provider) if config.providers.get(provider).enabled => Ok(vec![provider]), + Some(provider) => Err(CommandError::new(format!( + "provider {} is disabled in configuration", + provider.as_str() + ))), + None => { + let enabled = enabled_provider_ids(config); + if enabled.is_empty() { + Err(CommandError::new( + "no providers are enabled in configuration", + )) + } else { + Ok(enabled) + } + } + } +} + /// Decide the command status after output has been rendered. fn usage_exit_result(entries: &[ProviderEntry]) -> Result<(), CommandError> { // A provider that is not signed in still gets a block, so the output does @@ -130,34 +152,6 @@ fn usage_exit_result(entries: &[ProviderEntry]) -> Result<(), CommandError> { Ok(()) } -/// One provider's answer, with the provider it belongs to. -#[derive(Serialize)] -struct ProviderEntry { - /// The provider. - provider: ProviderId, - /// What it had to say. - #[serde(flatten)] - outcome: ProviderUsage, - /// Which account or local source supplied the usage snapshot, when relevant. - #[serde(skip_serializing_if = "Option::is_none")] - source: Option<&'static str>, - /// Which pool the numbers belong to, when the provider reported any. - caption: Option, - /// The HTTP status the last inference to this provider was answered with. - /// - /// It is here for every provider, including the ones that reported a - /// quota: a machine-readable report should carry the facts, not only the - /// ones that happen to be printed. - last_inference: Option, -} - -/// The machine-readable form of the report. -#[derive(Serialize)] -struct UsageReportJson<'a> { - /// One entry per provider. - providers: &'a [ProviderEntry], -} - /// The note that says which pool a provider's numbers belong to. /// /// Only x.ai has one: the billing endpoint reports the consumer @@ -171,53 +165,45 @@ fn caption_for(provider: ProviderId, config: &crate::config::Config) -> Option (ProviderUsage, Option<&'static str>) { - let codex_report = (provider == ProviderId::OpenAi) - .then(crate::provider::usage::codex_app_server::collect) - .flatten(); - collect_one_with_codex_result(context, provider, codex_report) + let codex = (provider == ProviderId::OpenAi) + .then(crate::provider::usage::codex_app_server::collect_detailed); + collect_one_with_codex_collection(context, provider, codex) } -/// Apply an optional Codex report, otherwise run the existing token/collector path. +/// Compatibility wrapper used by the existing CLI collector tests. +#[cfg(test)] fn collect_one_with_codex_result( context: &Context, provider: ProviderId, codex_report: Option, ) -> (ProviderUsage, Option<&'static str>) { - if let Some(codex_usage) = codex_outcome(provider, codex_report) { - return codex_usage; - } - - let runtime = ProviderRuntime::new(provider, &context.config, &context.paths); - let outcome = match runtime.tokens.current() { - Ok(None) => ProviderUsage::NotSignedIn, - Ok(Some(_)) => runtime.usage(), - Err(err) => ProviderUsage::Failed { - reason: format!("could not read the stored credentials ({err})"), + let codex = (provider == ProviderId::OpenAi).then_some( + crate::provider::usage::codex_app_server::CodexCollection { + report: codex_report, + timed_out: false, }, - }; - (outcome, None) + ); + collect_one_with_codex_collection(context, provider, codex) } -/// Use Codex's report only for the OpenAI usage entry. -fn codex_outcome( +fn collect_one_with_codex_collection( + context: &Context, provider: ProviderId, - report: Option, -) -> Option<(ProviderUsage, Option<&'static str>)> { - if provider != ProviderId::OpenAi { - return None; - } - report.map(|report| { - ( - ProviderUsage::Reported { report }, - Some(crate::provider::usage::codex_app_server::SOURCE_LABEL), - ) - }) + codex: Option, +) -> (ProviderUsage, Option<&'static str>) { + let runtime = ProviderRuntime::new(provider, &context.config, &context.paths); + let collected = crate::provider::usage::report::collect_entry( + provider, + context.config.providers.xai.upstream, + &runtime.tokens, + context.config.timeouts, + codex, + crate::provider::usage::xai::BILLING_BASE_URL, + ); + (collected.entry.outcome, collected.entry.source) } /// Render the whole report. @@ -1179,6 +1165,33 @@ mod tests { assert!(!text.contains("\"source\":null"), "{text}"); } + #[test] + fn usage_selects_only_enabled_providers_and_rejects_disabled_selections() { + let mut config = crate::config::Config::default(); + config.providers.xai.enabled = false; + assert_eq!( + selected_provider_ids(None, &config).unwrap(), + vec![ProviderId::OpenAi] + ); + + let error = selected_provider_ids(Some(ProviderId::Xai), &config).unwrap_err(); + assert!( + error + .message + .unwrap_or_default() + .contains("xai is disabled") + ); + + config.providers.openai.enabled = false; + let error = selected_provider_ids(None, &config).unwrap_err(); + assert!( + error + .message + .unwrap_or_default() + .contains("no providers are enabled") + ); + } + fn context_for(directory: &std::path::Path) -> Context { Context { paths: crate::paths::Paths::in_directory(directory), diff --git a/src/provider/mod.rs b/src/provider/mod.rs index e708d3e..573a5f9 100644 --- a/src/provider/mod.rs +++ b/src/provider/mod.rs @@ -185,8 +185,6 @@ pub struct ProviderRuntime { pub client: crate::auth::OAuthClient, /// The token manager. pub tokens: crate::auth::TokenManager, - /// How long a request to this provider may take. - pub timeouts: crate::config::Timeouts, } impl ProviderRuntime { @@ -211,14 +209,8 @@ impl ProviderRuntime { spec, client, tokens, - timeouts: config.timeouts, } } - - /// What this provider can say about its own allowance. - pub fn usage(&self) -> usage::ProviderUsage { - usage::collect(self.spec.id, self) - } } /// The client id in the stored credential, when there is one. diff --git a/src/provider/usage/codex_app_server.rs b/src/provider/usage/codex_app_server.rs index 46ca086..deb4e7d 100644 --- a/src/provider/usage/codex_app_server.rs +++ b/src/provider/usage/codex_app_server.rs @@ -30,11 +30,28 @@ const MAX_STDOUT_BYTES: usize = 1024 * 1024; /// A small bounded queue prevents a noisy child from buffering unlimited lines. const QUEUED_LINES: usize = 16; -/// Query the installed Codex CLI, returning `None` for every optional-source failure. -pub fn collect() -> Option { +/// A Codex usage read, distinguishing an elapsed session deadline from other +/// optional-source failures so the daemon retries only an actual timeout. +#[derive(Debug, Clone)] +pub(crate) struct CodexCollection { + pub report: Option, + pub timed_out: bool, +} + +/// Query Codex and retain whether its bounded session deadline elapsed. +pub(crate) fn collect_detailed() -> CodexCollection { let mut command = Command::new("codex"); command.arg("app-server"); - collect_with_command(command, SESSION_TIMEOUT) + collect_detailed_with_command(command, SESSION_TIMEOUT) +} + +fn collect_detailed_with_command(command: Command, timeout: Duration) -> CodexCollection { + let started = Instant::now(); + let report = collect_with_command(command, timeout); + CodexCollection { + timed_out: report.is_none() && started.elapsed() >= timeout, + report, + } } /// Run one app-server session. Kept injectable so tests can use a fake process. diff --git a/src/provider/usage/mod.rs b/src/provider/usage/mod.rs index 15ca8b5..247e1b3 100644 --- a/src/provider/usage/mod.rs +++ b/src/provider/usage/mod.rs @@ -24,11 +24,21 @@ pub mod codex_app_server; pub mod openai; +pub mod report; pub mod xai; use serde::Serialize; -use crate::provider::{ProviderId, ProviderRuntime}; +use crate::provider::ProviderId; + +/// One provider usage attempt and whether it ended because of a timeout. +#[derive(Debug, Clone)] +pub struct ProviderCollection { + /// The provider's structured answer. + pub outcome: ProviderUsage, + /// Whether a bounded attempt timed out and should be retried. + pub timed_out: bool, +} /// What a provider can say about its own allowance. #[derive(Debug, Clone, Serialize)] @@ -216,17 +226,6 @@ impl std::fmt::Display for UsageError { impl std::error::Error for UsageError {} -/// Ask a provider what it can say about its allowance. -/// -/// The caller decides which providers to ask; this only routes the question -/// to the provider that can answer it. -pub fn collect(provider: ProviderId, runtime: &ProviderRuntime) -> ProviderUsage { - match provider { - ProviderId::Xai => xai::collect(runtime), - ProviderId::OpenAi => openai::collect(runtime), - } -} - /// Strip the proto enum prefix from a period type. /// /// `USAGE_PERIOD_TYPE_WEEKLY` reads as `WEEKLY`; a type from another diff --git a/src/provider/usage/openai.rs b/src/provider/usage/openai.rs index 77adb4b..e339dc2 100644 --- a/src/provider/usage/openai.rs +++ b/src/provider/usage/openai.rs @@ -23,7 +23,6 @@ //! honest answer is that the number is unavailable, with the reasons and the //! codes the provider does publish. -use crate::provider::ProviderRuntime; use crate::provider::usage::ProviderUsage; /// The page OpenAI points users at for their own usage. @@ -51,7 +50,8 @@ pub const SIGNALS: &[&str] = &[ /// a quota API. It does not say "ChatGPT has no usage information": the user /// has usage information, OpenAI just does not publish a way to read it with /// this credential. -pub fn collect(_runtime: &ProviderRuntime) -> ProviderUsage { +/// The structured fallback when no Codex usage report is available. +pub fn unavailable() -> ProviderUsage { ProviderUsage::Unavailable { reason: "Sign in with ChatGPT does not expose a quota API".to_string(), source: Some(SOURCE.to_string()), @@ -63,7 +63,6 @@ pub fn collect(_runtime: &ProviderRuntime) -> ProviderUsage { #[cfg(test)] mod tests { use super::*; - use crate::provider::ProviderId; #[test] fn the_signals_name_the_documented_codes() { @@ -85,13 +84,7 @@ mod tests { #[test] fn the_answer_names_the_source_and_the_place_to_look() { - let runtime = crate::provider::ProviderRuntime::new( - ProviderId::OpenAi, - &crate::config::Config::default(), - &crate::paths::Paths::in_directory(std::path::Path::new(".")), - ); - - match collect(&runtime) { + match unavailable() { ProviderUsage::Unavailable { reason, source, diff --git a/src/provider/usage/report.rs b/src/provider/usage/report.rs new file mode 100644 index 0000000..36a9db2 --- /dev/null +++ b/src/provider/usage/report.rs @@ -0,0 +1,173 @@ +//! Shared machine-readable usage report assembly for the CLI and daemon API. + +use serde::Serialize; + +use crate::auth::refresh::TokenManager; +use crate::config::{Timeouts, Upstream}; +use crate::provider::usage::{ProviderUsage, UsageReport, xai}; +use crate::provider::{ProviderId, usage::codex_app_server::CodexCollection}; + +/// One provider's answer, with the provider it belongs to. +#[derive(Debug, Clone, Serialize)] +pub(crate) struct ProviderEntry { + pub provider: ProviderId, + #[serde(flatten)] + pub outcome: ProviderUsage, + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option<&'static str>, + pub caption: Option, + pub last_inference: Option, +} + +/// The machine-readable form shared with eggpass usage --json. +#[derive(Serialize)] +pub(crate) struct UsageReportJson<'a> { + pub providers: &'a [ProviderEntry], +} + +/// A provider collection plus whether a retry is warranted. +#[derive(Debug, Clone)] +pub(crate) struct CollectedEntry { + pub entry: ProviderEntry, + pub timed_out: bool, +} + +/// Providers which are enabled in the effective configuration, in display order. +pub(crate) fn enabled_provider_ids(config: &crate::config::Config) -> Vec { + ProviderId::all() + .into_iter() + .filter(|provider| config.providers.get(*provider).enabled) + .collect() +} + +/// Use Codex's report only for the OpenAI usage entry. +pub(crate) fn codex_outcome( + provider: ProviderId, + report: Option, +) -> Option<(ProviderUsage, Option<&'static str>)> { + if provider != ProviderId::OpenAi { + return None; + } + report.map(|report| { + ( + ProviderUsage::Reported { report }, + Some(crate::provider::usage::codex_app_server::SOURCE_LABEL), + ) + }) +} + +/// Collect one provider using the existing shared token manager. +pub(crate) fn collect_entry( + provider: ProviderId, + xai_upstream: Upstream, + tokens: &TokenManager, + timeouts: Timeouts, + codex: Option, + billing_base_url: &str, +) -> CollectedEntry { + let codex_timed_out = codex.as_ref().is_some_and(|result| result.timed_out); + let codex_report = codex.and_then(|result| result.report); + + let (outcome, source, timed_out) = if provider == ProviderId::OpenAi { + if let Some((outcome, source)) = codex_outcome(provider, codex_report) { + (outcome, source, false) + } else { + let outcome = match tokens.current() { + Ok(None) => ProviderUsage::NotSignedIn, + Ok(Some(_)) => crate::provider::usage::openai::unavailable(), + Err(err) => ProviderUsage::Failed { + reason: format!("could not read the stored credentials ({err})"), + }, + }; + (outcome, None, codex_timed_out) + } + } else { + match tokens.current() { + Ok(None) => (ProviderUsage::NotSignedIn, None, false), + Ok(Some(_)) => { + let result = xai::collect_detailed(tokens, timeouts, billing_base_url); + (result.outcome, None, result.timed_out) + } + Err(err) => ( + ProviderUsage::Failed { + reason: format!("could not read the stored credentials ({err})"), + }, + None, + false, + ), + } + }; + + CollectedEntry { + entry: ProviderEntry { + provider, + outcome, + source, + caption: (provider == ProviderId::Xai).then(|| xai::caption(xai_upstream).to_string()), + last_inference: None, + }, + timed_out, + } +} + +/// Apply a fresh daemon inference snapshot without changing the cached report. +pub(crate) fn attach_inferences( + entries: &[ProviderEntry], + inferences: &std::collections::BTreeMap, +) -> Vec { + entries + .iter() + .cloned() + .map(|mut entry| { + entry.last_inference = inferences.get(&entry.provider).copied(); + entry + }) + .collect() +} + +/// Keep an API-triggered xAI attempt bounded even when inference requests have long timeouts. +/// The configured timeout remains in force for inference and for the interactive CLI. +pub(crate) fn bounded_timeouts(timeouts: Timeouts) -> Timeouts { + const MAX_USAGE_REQUEST: u64 = 15; + const MAX_CONNECT: u64 = 5; + Timeouts { + connect_seconds: timeouts.connect_seconds.min(MAX_CONNECT), + global_seconds: timeouts.global_seconds.min(MAX_USAGE_REQUEST), + body_seconds: timeouts.body_seconds.min(MAX_USAGE_REQUEST), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn enabled_provider_filter_preserves_display_order() { + let mut config = crate::config::Config::default(); + config.providers.xai.enabled = false; + assert_eq!(enabled_provider_ids(&config), vec![ProviderId::OpenAi]); + config.providers.openai.enabled = false; + assert!(enabled_provider_ids(&config).is_empty()); + } + + #[test] + fn api_timeouts_are_capped_without_extending_user_limits() { + let bounded = bounded_timeouts(Timeouts { + connect_seconds: 30, + global_seconds: 1_800, + body_seconds: 1_800, + }); + assert_eq!(bounded.connect_seconds, 5); + assert_eq!(bounded.global_seconds, 15); + assert_eq!(bounded.body_seconds, 15); + + let shorter = bounded_timeouts(Timeouts { + connect_seconds: 2, + global_seconds: 8, + body_seconds: 9, + }); + assert_eq!(shorter.connect_seconds, 2); + assert_eq!(shorter.global_seconds, 8); + assert_eq!(shorter.body_seconds, 9); + } +} diff --git a/src/provider/usage/xai.rs b/src/provider/usage/xai.rs index a26c2b3..412fa2e 100644 --- a/src/provider/usage/xai.rs +++ b/src/provider/usage/xai.rs @@ -18,7 +18,6 @@ use serde_json::Value; -use crate::provider::ProviderRuntime; use crate::provider::usage::{ Credits, ProductUsage, ProviderUsage, QuotaState, QuotaWindow, UsageError, UsageReport, WindowLabel, @@ -68,62 +67,48 @@ pub fn caption(upstream: crate::config::Upstream) -> &'static str { } } -/// Ask x.ai what it can say about the allowance. -pub fn collect(runtime: &ProviderRuntime) -> ProviderUsage { - // The request goes to the URL the docs above name. The assertion catches - // a path that drifted away from it. +/// Collect usage with an explicit timeout and endpoint, preserving timeout +/// classification for the daemon's finite retry policy. +pub fn collect_detailed( + tokens: &crate::auth::refresh::TokenManager, + timeouts: crate::config::Timeouts, + base_url: &str, +) -> crate::provider::usage::ProviderCollection { debug_assert_eq!(format!("{BILLING_BASE_URL}{BILLING_PATH}"), BILLING_URL); debug_assert_eq!(format!("{BILLING_BASE_URL}{SETTINGS_PATH}"), SETTINGS_URL); - let client = - UpstreamClient::for_endpoint(BILLING_BASE_URL, &headers(runtime), runtime.timeouts); - - let mut response = match send_with_auth( - &client, - &runtime.tokens, - Method::Get, - BILLING_PATH, - &[], - None, - ) { + let client = UpstreamClient::for_endpoint(base_url, &headers(tokens), timeouts); + let mut response = match send_with_auth(&client, tokens, Method::Get, BILLING_PATH, &[], None) { Ok(response) => response, - Err(err) => { - return ProviderUsage::Failed { - reason: describe(&err), - }; - } + Err(err) => return failed(describe(&err), is_timeout(&err)), }; match response.status { 200 => {} - 401 => { - return ProviderUsage::Failed { - reason: "the provider rejected the token".to_string(), - }; - } + 401 => return failed("the provider rejected the token".to_string(), false), 404 => { - return ProviderUsage::Failed { - reason: "the endpoint is not available (HTTP 404)".to_string(), - }; + return failed( + "the endpoint is not available (HTTP 404)".to_string(), + false, + ); } 429 => { - return ProviderUsage::Failed { - reason: "the provider is rate-limiting this account".to_string(), - }; - } - status => { - return ProviderUsage::Failed { - reason: format!("the provider answered HTTP {status}"), - }; + return failed( + "the provider is rate-limiting this account".to_string(), + false, + ); } + status => return failed(format!("the provider answered HTTP {status}"), false), } let body = match response.read_to_vec() { Ok(body) => body, Err(err) => { - return ProviderUsage::Failed { - reason: format!("could not read the provider's answer ({err})"), - }; + let timed_out = err.kind() == std::io::ErrorKind::TimedOut; + return failed( + format!("could not read the provider's answer ({err})"), + timed_out, + ); } }; @@ -131,26 +116,50 @@ pub fn collect(runtime: &ProviderRuntime) -> ProviderUsage { Ok(report) => report, Err(err) => { crate::logging::warn(&format!("billing response: {err}")); - return ProviderUsage::Failed { - reason: err.to_string(), - }; + return failed(err.to_string(), false); } }; - // The plan name is enrichment, not the feature. A failure here omits the - // label; the usage still prints. - report.plan = fetch_plan(&client, runtime); + // Plan lookup is best-effort enrichment. A settings timeout does not make + // an otherwise complete billing report incomplete or retryable. + report.plan = fetch_plan(&client, tokens); - if report.says_nothing() { - return ProviderUsage::Unavailable { + let outcome = if report.says_nothing() { + ProviderUsage::Unavailable { reason: "the provider reported no usage information".to_string(), source: None, hint: None, signals: Vec::new(), - }; + } + } else { + ProviderUsage::Reported { report } + }; + crate::provider::usage::ProviderCollection { + outcome, + timed_out: false, } +} - ProviderUsage::Reported { report } +fn failed(reason: String, timed_out: bool) -> crate::provider::usage::ProviderCollection { + crate::provider::usage::ProviderCollection { + outcome: ProviderUsage::Failed { reason }, + timed_out, + } +} + +fn is_timeout(err: &UpstreamError) -> bool { + match err { + UpstreamError::Network(message) => is_timeout_message(message), + UpstreamError::Token(crate::auth::refresh::TokenError::Auth(err)) => { + is_timeout_message(&err.to_string()) + } + _ => false, + } +} + +fn is_timeout_message(message: &str) -> bool { + let message = message.to_ascii_lowercase(); + message.contains("timed out") || message.contains("timeout") } /// The headers the billing request carries. @@ -160,7 +169,7 @@ pub fn collect(runtime: &ProviderRuntime) -> ProviderUsage { /// `x-grok-client-identifier` or `x-authenticateresponse`: those belong to /// proxy-routed inference, not to billing, and `eggpass`'s own provider spec /// attaches the identifier to inference requests. -fn headers(runtime: &ProviderRuntime) -> Vec<(&'static str, String)> { +fn headers(tokens: &crate::auth::refresh::TokenManager) -> Vec<(&'static str, String)> { let mut headers = vec![ (TOKEN_AUTH_HEADER, TOKEN_AUTH_VALUE.to_string()), ("Accept", "application/json".to_string()), @@ -172,8 +181,7 @@ fn headers(runtime: &ProviderRuntime) -> Vec<(&'static str, String)> { // The official client sends the user id; it is not required here, but it // costs nothing and the proxy is happier with it. - if let Some(user_id) = runtime - .tokens + if let Some(user_id) = tokens .current() .ok() .flatten() @@ -188,16 +196,12 @@ fn headers(runtime: &ProviderRuntime) -> Vec<(&'static str, String)> { /// The plan name, from the settings endpoint. /// /// Best effort: any failure means no plan name, not a failed report. -fn fetch_plan(client: &UpstreamClient, runtime: &ProviderRuntime) -> Option { - let mut response = send_with_auth( - client, - &runtime.tokens, - Method::Get, - SETTINGS_PATH, - &[], - None, - ) - .ok()?; +fn fetch_plan( + client: &UpstreamClient, + tokens: &crate::auth::refresh::TokenManager, +) -> Option { + let mut response = + send_with_auth(client, tokens, Method::Get, SETTINGS_PATH, &[], None).ok()?; if response.status != 200 { return None; } @@ -691,4 +695,19 @@ mod tests { let build = caption(crate::config::Upstream::Build); assert!(build.contains("draws from"), "{build}"); } + + #[test] + fn only_transport_or_oauth_deadlines_are_retryable_timeouts() { + assert!(is_timeout(&UpstreamError::Network( + "operation timed out".to_string() + ))); + assert!(!is_timeout(&UpstreamError::Network( + "connection refused".to_string() + ))); + assert!(is_timeout_message("OAuth HTTP request timed out")); + assert!(!is_timeout_message("OAuth network request failed")); + assert!(!is_timeout(&UpstreamError::Protocol( + "invalid response".to_string() + ))); + } } diff --git a/src/server/chat.rs b/src/server/chat.rs index 507f565..f25001d 100644 --- a/src/server/chat.rs +++ b/src/server/chat.rs @@ -90,7 +90,7 @@ pub fn complete(request: &Request, context: &ServerContext) -> Response { let mut response = match upstream::send_with_auth( &handle.upstream, - &handle.tokens, + handle.tokens.as_ref(), Method::Post, &target, &forwarded, diff --git a/src/server/mod.rs b/src/server/mod.rs index 02220c5..124efab 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -15,6 +15,7 @@ pub mod models; pub mod router; pub mod sse; pub mod translate; +pub mod usage; #[cfg(test)] mod tests; @@ -27,6 +28,7 @@ mod keep_body_tests { fn health_does_not_keep_a_body() { assert!(!keep_body_for("/health")); assert!(!keep_body_for("/healthz")); + assert!(!keep_body_for("/v1/usage")); assert!(keep_body_for("/v1/chat/completions")); assert!(keep_body_for("/v1/models")); } @@ -54,7 +56,7 @@ pub struct ProviderHandle { /// The client the requests go out through. pub upstream: UpstreamClient, /// Hands out access tokens, refreshing them when needed. - pub tokens: TokenManager, + pub tokens: Arc, } /// Everything a request handler needs. @@ -91,6 +93,8 @@ pub struct ServerContext { /// It is kept in memory and nowhere else: `eggpass usage` reports it for /// a provider that does not publish a quota of its own. pub inferences: Arc, + /// One in-memory on-demand usage snapshot and its refresh coordinator. + pub usage_cache: Arc, } impl ServerContext { @@ -244,7 +248,7 @@ fn gate_decision(request: &Request, context: &ServerContext) -> http::GateDecisi fn keep_body_for(path: &str) -> bool { !matches!( router::route(path), - router::Route::Health | router::Route::LastInference + router::Route::Health | router::Route::LastInference | router::Route::Usage ) } @@ -315,6 +319,10 @@ fn handle_request(request: Request, context: &ServerContext) -> Response { "GET" => inference::handle(context), _ => method_not_allowed(method, "GET"), }, + router::Route::Usage => match method { + "GET" => usage::handle(context), + _ => method_not_allowed(method, "GET"), + }, router::Route::Models => match method { "GET" => models::list(&request, context), _ => method_not_allowed(method, "GET"), @@ -486,6 +494,9 @@ mod authorisation_tests { upstream_in_flight: Arc::new(AtomicUsize::new(0)), max_upstream_requests: DEFAULT_MAX_UPSTREAM_REQUESTS, inferences: Arc::new(crate::inference::InferenceState::new()), + usage_cache: Arc::new(usage::UsageCache::new(Vec::new(), |_| { + unreachable!("no providers") + })), } } @@ -674,6 +685,9 @@ mod authorisation_tests { upstream_in_flight: Arc::new(AtomicUsize::new(0)), max_upstream_requests: 2, inferences: Arc::new(crate::inference::InferenceState::new()), + usage_cache: Arc::new(usage::UsageCache::new(Vec::new(), |_| { + unreachable!("no providers") + })), }; assert!(context.take_upstream_slot()); diff --git a/src/server/models.rs b/src/server/models.rs index e503f6a..6079865 100644 --- a/src/server/models.rs +++ b/src/server/models.rs @@ -71,7 +71,7 @@ fn merged_catalogue(context: &ServerContext) -> Result, String> { let mut response = match upstream::send_with_auth( &handle.upstream, - &handle.tokens, + handle.tokens.as_ref(), Method::Get, "/v1/models", &[], diff --git a/src/server/router.rs b/src/server/router.rs index 611c408..1bcf83f 100644 --- a/src/server/router.rs +++ b/src/server/router.rs @@ -15,6 +15,8 @@ pub enum Route { Model(String), /// `GET /v1/last-inference` LastInference, + /// `GET /v1/usage` + Usage, /// `GET /health` Health, /// Anything else. @@ -37,6 +39,7 @@ pub fn route(path: &str) -> Route { "/v1/responses" => Route::Responses, "/v1/models" => Route::Models, "/v1/last-inference" => Route::LastInference, + "/v1/usage" => Route::Usage, other => match other.strip_prefix("/v1/models/") { Some(id) if !id.is_empty() => Route::Model(id.to_string()), _ => Route::NotFound, @@ -63,6 +66,8 @@ mod tests { assert_eq!(route("/healthz"), Route::Health); assert_eq!(route("/v1/last-inference"), Route::LastInference); assert_eq!(route("/last-inference"), Route::LastInference); + assert_eq!(route("/v1/usage"), Route::Usage); + assert_eq!(route("/usage"), Route::Usage); } #[test] diff --git a/src/server/tests.rs b/src/server/tests.rs index f09bda1..fb948b9 100644 --- a/src/server/tests.rs +++ b/src/server/tests.rs @@ -223,6 +223,7 @@ struct Harness { inferences: Arc, /// The provider the harness serves. provider: ProviderId, + usage_calls: Arc, _directory: tempfile::TempDir, } @@ -358,7 +359,7 @@ fn harness_with_spec( ProviderHandle { spec: spec.clone(), upstream, - tokens, + tokens: Arc::new(tokens), }, ); @@ -368,6 +369,35 @@ fn harness_with_spec( let inferences = Arc::new(crate::inference::InferenceState::new()); + let usage_calls = Arc::new(AtomicUsize::new(0)); + let usage_calls_for_collector = Arc::clone(&usage_calls); + let usage_tokens = Arc::clone( + &providers + .get(&spec.id) + .expect("provider is registered") + .tokens, + ); + let usage_base_url = stub.base_url(); + let usage_timeouts = crate::config::Timeouts { + connect_seconds: 1, + global_seconds: 1, + body_seconds: 1, + }; + let usage_cache = Arc::new(crate::server::usage::UsageCache::new( + vec![spec.id], + move |provider| { + usage_calls_for_collector.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + crate::provider::usage::report::collect_entry( + provider, + crate::config::Upstream::Api, + usage_tokens.as_ref(), + usage_timeouts, + None, + &usage_base_url, + ) + }, + )); + let context = Arc::new(ServerContext { host: "127.0.0.1".to_string(), port, @@ -379,6 +409,7 @@ fn harness_with_spec( upstream_in_flight: Arc::new(AtomicUsize::new(0)), max_upstream_requests: crate::server::DEFAULT_MAX_UPSTREAM_REQUESTS, inferences: Arc::clone(&inferences), + usage_cache, }); let running = Arc::clone(&server); @@ -392,6 +423,7 @@ fn harness_with_spec( keys, inferences, provider: spec.id, + usage_calls, _directory: directory, } } @@ -1190,6 +1222,142 @@ fn a_streamed_response_without_a_content_type_reaches_a_streaming_client() { assert!(text.contains("[DONE]"), "{text}"); } +#[test] +fn usage_route_is_authenticated_cached_and_attaches_fresh_inference_state() { + let stub = Stub::start(|request| { + if request.path == crate::provider::usage::xai::BILLING_PATH { + Reply::json( + 200, + r#"{"config":{"currentPeriod":{"type":"USAGE_PERIOD_TYPE_WEEKLY","start":"2026-11-13T03:07:08Z","end":"2026-11-20T03:07:08Z"},"creditUsagePercent":42.0,"productUsage":[{"product":"GrokChat","usagePercent":42.0}]}}"#, + ) + } else if request.path == crate::provider::usage::xai::SETTINGS_PATH { + Reply::json(200, r#"{"plan":"SuperGrok"}"#) + } else { + Reply::json(404, "{}") + } + }); + let harness = harness(&stub, "secret-key", "grok-token"); + + let unauthorized = agent() + .get(harness.url("/usage")) + .call() + .expect("the proxy answers"); + assert_eq!(unauthorized.status(), 401); + assert_eq!( + harness + .usage_calls + .load(std::sync::atomic::Ordering::SeqCst), + 0 + ); + assert!( + stub.requests().is_empty(), + "unauthorized requests must not collect" + ); + + let first = agent() + .get(harness.url("/usage")) + .header("Authorization", "Bearer secret-key") + .call() + .expect("the usage route answers"); + assert_eq!(first.status(), 200); + let headers = first.headers(); + assert_eq!( + headers + .get("cache-control") + .and_then(|value| value.to_str().ok()), + Some("private, no-store") + ); + assert!( + headers + .get("x-eggpass-usage-age") + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .is_some(), + "age header must be integer seconds" + ); + assert!( + headers + .get("x-eggpass-usage-updated-at") + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value.ends_with('Z')), + "updated-at must be an RFC 3339 UTC timestamp" + ); + let first_body = read_json_body(first); + assert_eq!(first_body["providers"].as_array().unwrap().len(), 1); + assert_eq!(first_body["providers"][0]["provider"], "xai"); + assert_eq!(first_body["providers"][0]["status"], "reported"); + assert_eq!( + first_body["providers"][0]["last_inference"], + serde_json::Value::Null + ); + assert!(!first_body.to_string().contains("user@example.com")); + assert!(!first_body.to_string().contains("grok-token")); + + let upstream = stub.requests(); + assert_eq!( + upstream.len(), + 2, + "cold collection calls billing and settings once" + ); + assert!( + upstream + .iter() + .any(|request| request.path == crate::provider::usage::xai::BILLING_PATH) + ); + assert!( + upstream + .iter() + .any(|request| request.path == crate::provider::usage::xai::SETTINGS_PATH) + ); + assert_eq!( + harness + .usage_calls + .load(std::sync::atomic::Ordering::SeqCst), + 1 + ); + + harness.inferences.record(ProviderId::Xai, 429); + let cached = agent() + .get(harness.url("/v1/usage")) + .header("Authorization", "Bearer secret-key") + .call() + .expect("the cached report answers"); + assert_eq!(cached.status(), 200); + let cached_body = read_json_body(cached); + assert_eq!(cached_body["providers"][0]["last_inference"], 429); + assert_eq!( + harness + .usage_calls + .load(std::sync::atomic::Ordering::SeqCst), + 1 + ); + assert_eq!( + stub.requests().len(), + 2, + "a fresh cache hit must not query upstream" + ); + + let method = agent() + .post(harness.url("/v1/usage")) + .header("Authorization", "Bearer secret-key") + .send("{}") + .expect("the route reports its allowed method"); + assert_eq!(method.status(), 405); + assert_eq!( + method + .headers() + .get("allow") + .and_then(|value| value.to_str().ok()), + Some("GET") + ); + assert_eq!( + harness + .usage_calls + .load(std::sync::atomic::Ordering::SeqCst), + 1 + ); +} + #[test] fn a_native_responses_request_is_forwarded_untouched() { // A Responses-only provider speaks the Responses API natively. A request diff --git a/src/server/usage.rs b/src/server/usage.rs new file mode 100644 index 0000000..b4202e3 --- /dev/null +++ b/src/server/usage.rs @@ -0,0 +1,769 @@ +//! Authenticated daemon usage route and its process-local refresh cache. + +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard}; +use std::thread; +use std::time::{Duration, Instant}; + +use crate::provider::ProviderId; +use crate::provider::usage::{ + ProviderUsage, + report::{CollectedEntry, ProviderEntry, UsageReportJson, attach_inferences}, +}; +use crate::timeutil; + +const CACHE_TTL: Duration = Duration::from_secs(600); +const CLIENT_WAIT: Duration = Duration::from_secs(30); +const RETRY_DELAYS: [Duration; 3] = [ + Duration::from_secs(5), + Duration::from_secs(15), + Duration::from_secs(30), +]; +const FAILURE_COOLDOWN: Duration = Duration::from_secs(600); +const CACHE_CONTROL: &str = "private, no-store"; + +/// Usage collection callback, supplied by the daemon with shared token managers. +type Collector = dyn Fn(ProviderId) -> CollectedEntry + Send + Sync + 'static; + +/// Tunable only inside deterministic cache tests; production uses DEFAULT_POLICY. +#[derive(Debug, Clone, Copy)] +struct CachePolicy { + ttl: Duration, + client_wait: Duration, + retry_delays: [Duration; 3], + cooldown: Duration, +} + +const DEFAULT_POLICY: CachePolicy = CachePolicy { + ttl: CACHE_TTL, + client_wait: CLIENT_WAIT, + retry_delays: RETRY_DELAYS, + cooldown: FAILURE_COOLDOWN, +}; + +/// A complete cached report. Monotonic time controls expiry; wall time is only +/// used for the public RFC 3339 update header. +#[derive(Clone)] +struct Snapshot { + entries: Vec, + completed_at: Instant, + updated_at_unix: i64, +} + +#[derive(Default)] +struct CacheState { + snapshot: Option, + refresh: Option, + cooldown_until: Option, +} + +struct RefreshState { + next_retry_at: Option, + retry_after_hint: u64, +} + +/// What the route should return from the cache coordinator. +enum CacheResponse { + Complete { snapshot: Snapshot, stale: bool }, + Pending { retry_after: u64 }, + TimedOut { retry_after: u64 }, + Unavailable { retry_after: u64 }, +} + +/// One process-local usage cache and one finite, request-triggered refresh job. +pub struct UsageCache { + providers: Vec, + collector: Arc, + state: Arc>, + changed: Arc, + policy: CachePolicy, +} + +impl UsageCache { + /// Create a cold cache over only the providers selected for this daemon. + pub fn new(providers: Vec, collector: F) -> UsageCache + where + F: Fn(ProviderId) -> CollectedEntry + Send + Sync + 'static, + { + UsageCache::with_policy(providers, collector, DEFAULT_POLICY) + } + + fn with_policy(providers: Vec, collector: F, policy: CachePolicy) -> UsageCache + where + F: Fn(ProviderId) -> CollectedEntry + Send + Sync + 'static, + { + UsageCache { + providers, + collector: Arc::new(collector), + state: Arc::new(Mutex::new(CacheState::default())), + changed: Arc::new(Condvar::new()), + policy, + } + } + + /// Return a fresh snapshot, or trigger/share one finite refresh. + fn get(&self) -> CacheResponse { + let now = Instant::now(); + let mut state = lock(&self.state); + if let Some(response) = response_for_state(&state, now, self.policy) { + // A request arriving after another one started never waits on its + // handler thread; it gets 202 and the scheduled retry hint. + return response; + } + + state.cooldown_until = None; + state.refresh = Some(RefreshState { + next_retry_at: None, + retry_after_hint: self.policy.retry_delays[0].as_secs().max(1), + }); + drop(state); + + let providers = self.providers.clone(); + let collector = Arc::clone(&self.collector); + let worker_state = Arc::clone(&self.state); + let changed = Arc::clone(&self.changed); + let policy = self.policy; + if thread::Builder::new() + .name("eggpass-usage-refresh".to_string()) + .spawn(move || run_refresh(providers, collector, worker_state, changed, policy)) + .is_err() + { + let mut state = lock(&self.state); + state.refresh = None; + self.changed.notify_all(); + return CacheResponse::Unavailable { retry_after: 1 }; + } + + self.wait_for_started_refresh() + } + + fn wait_for_started_refresh(&self) -> CacheResponse { + let deadline = Instant::now() + self.policy.client_wait; + let mut state = lock(&self.state); + loop { + let now = Instant::now(); + if state.refresh.is_none() { + if let Some(response) = response_for_state(&state, now, self.policy) { + return response; + } + return CacheResponse::Unavailable { retry_after: 1 }; + } + + let remaining = deadline.saturating_duration_since(now); + if remaining.is_zero() { + return CacheResponse::TimedOut { + retry_after: retry_after(&state, now), + }; + } + let (next, timeout) = self + .changed + .wait_timeout(state, remaining) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + state = next; + if timeout.timed_out() && state.refresh.is_some() { + return CacheResponse::TimedOut { + retry_after: retry_after(&state, Instant::now()), + }; + } + } + } +} + +fn run_refresh( + providers: Vec, + collector: Arc, + state: Arc>, + changed: Arc, + policy: CachePolicy, +) { + let mut entries = Vec::with_capacity(providers.len()); + let mut timed_out = Vec::new(); + for provider in providers { + let result = collect_safely(collector.as_ref(), provider); + if result.timed_out { + timed_out.push(provider); + } + entries.push(result.entry); + } + + if timed_out.is_empty() { + finish_success(entries, &state, &changed); + return; + } + + for (retry_index, delay) in policy.retry_delays.iter().copied().enumerate() { + { + let mut current = lock(&state); + if let Some(refresh) = current.refresh.as_mut() { + refresh.next_retry_at = Some(Instant::now() + delay); + refresh.retry_after_hint = delay.as_secs().max(1); + } + changed.notify_all(); + } + thread::sleep(delay); + { + let mut current = lock(&state); + if let Some(refresh) = current.refresh.as_mut() { + refresh.next_retry_at = None; + refresh.retry_after_hint = policy + .retry_delays + .get(retry_index + 1) + .map(|next| next.as_secs().max(1)) + .unwrap_or(1); + } + } + + let retrying = std::mem::take(&mut timed_out); + for provider in retrying { + let result = collect_safely(collector.as_ref(), provider); + if let Some(entry) = entries.iter_mut().find(|entry| entry.provider == provider) { + *entry = result.entry; + } + if result.timed_out { + timed_out.push(provider); + } + } + + if timed_out.is_empty() { + finish_success(entries, &state, &changed); + return; + } + } + + let mut current = lock(&state); + current.refresh = None; + current.cooldown_until = Some(Instant::now() + policy.cooldown); + changed.notify_all(); +} + +fn collect_safely(collector: &Collector, provider: ProviderId) -> CollectedEntry { + match catch_unwind(AssertUnwindSafe(|| collector(provider))) { + Ok(result) => result, + Err(_) => CollectedEntry { + entry: ProviderEntry { + provider, + outcome: ProviderUsage::Failed { + reason: "the usage collector failed unexpectedly".to_string(), + }, + source: None, + caption: None, + last_inference: None, + }, + timed_out: false, + }, + } +} + +fn finish_success(entries: Vec, state: &Mutex, changed: &Condvar) { + let mut current = lock(state); + current.snapshot = Some(Snapshot { + entries, + completed_at: Instant::now(), + updated_at_unix: timeutil::now_unix(), + }); + current.refresh = None; + current.cooldown_until = None; + changed.notify_all(); +} + +fn response_for_state( + state: &CacheState, + now: Instant, + policy: CachePolicy, +) -> Option { + if let Some(snapshot) = &state.snapshot + && now.saturating_duration_since(snapshot.completed_at) < policy.ttl + { + return Some(CacheResponse::Complete { + snapshot: snapshot.clone(), + stale: false, + }); + } + + if let Some(until) = state.cooldown_until.filter(|until| *until > now) { + let retry_after = seconds_ceil(until.saturating_duration_since(now)); + return Some(match &state.snapshot { + Some(snapshot) => CacheResponse::Complete { + snapshot: snapshot.clone(), + stale: true, + }, + None => CacheResponse::Unavailable { retry_after }, + }); + } + + state.refresh.as_ref().map(|_| CacheResponse::Pending { + retry_after: retry_after(state, now), + }) +} + +fn retry_after(state: &CacheState, now: Instant) -> u64 { + state.refresh.as_ref().map_or(1, |refresh| { + refresh + .next_retry_at + .map(|at| seconds_ceil(at.saturating_duration_since(now))) + .unwrap_or(refresh.retry_after_hint.max(1)) + }) +} + +fn seconds_ceil(duration: Duration) -> u64 { + duration.as_secs() + u64::from(duration.subsec_nanos() > 0) +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +/// Serve the authenticated usage route after the common request guard passed. +pub(crate) fn handle(context: &super::ServerContext) -> super::Response { + match context.usage_cache.get() { + CacheResponse::Complete { snapshot, stale } => { + let inferences = context.inferences.snapshot(); + let entries = attach_inferences(&snapshot.entries, &inferences); + let body = match serde_json::to_string(&UsageReportJson { + providers: &entries, + }) { + Ok(body) => body, + Err(_) => { + return api_error( + 500, + "the usage report could not be serialized", + "usage_report_serialization_failed", + None, + ); + } + }; + let age = Instant::now() + .saturating_duration_since(snapshot.completed_at) + .as_secs(); + let mut response = super::Response::json(200, body); + response.headers.extend([ + ("Cache-Control".to_string(), CACHE_CONTROL.to_string()), + ("X-Eggpass-Usage-Age".to_string(), age.to_string()), + ( + "X-Eggpass-Usage-Updated-At".to_string(), + timeutil::format_rfc3339(snapshot.updated_at_unix), + ), + ]); + if stale { + response + .headers + .push(("X-Eggpass-Usage-Stale".to_string(), "true".to_string())); + } + response + } + CacheResponse::Pending { retry_after } => api_error( + 202, + "a usage report refresh is already in progress", + "usage_refresh_pending", + Some(retry_after), + ), + CacheResponse::TimedOut { retry_after } => api_error( + 504, + "the usage report refresh did not finish within 30 seconds", + "usage_refresh_timeout", + Some(retry_after), + ), + CacheResponse::Unavailable { retry_after } => api_error( + 503, + "the usage report is temporarily unavailable", + "usage_refresh_unavailable", + Some(retry_after), + ), + } +} + +fn api_error(status: u16, message: &str, code: &str, retry_after: Option) -> super::Response { + let mut response = super::openai_error_with_code(status, message, "server_error", Some(code)); + response + .headers + .push(("Cache-Control".to_string(), CACHE_CONTROL.to_string())); + if let Some(seconds) = retry_after { + response + .headers + .push(("Retry-After".to_string(), seconds.max(1).to_string())); + } + response +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::mpsc::{self, Receiver}; + + fn policy(client_wait: Duration, retry_delays: [Duration; 3]) -> CachePolicy { + CachePolicy { + ttl: Duration::from_secs(600), + client_wait, + retry_delays, + cooldown: Duration::from_millis(100), + } + } + + fn entry(provider: ProviderId, timed_out: bool) -> CollectedEntry { + CollectedEntry { + entry: ProviderEntry { + provider, + outcome: if timed_out { + ProviderUsage::Failed { + reason: "provider request timed out".to_string(), + } + } else { + ProviderUsage::Unavailable { + reason: "test fixture outcome".to_string(), + source: None, + hint: None, + signals: Vec::new(), + } + }, + source: None, + caption: None, + last_inference: None, + }, + timed_out, + } + } + + fn wait_until_idle(cache: &UsageCache, timeout: Duration) -> bool { + let deadline = Instant::now() + timeout; + let mut state = lock(&cache.state); + while state.refresh.is_some() { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return false; + } + let (next, result) = cache + .changed + .wait_timeout(state, remaining) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + state = next; + if result.timed_out() && state.refresh.is_some() { + return false; + } + } + true + } + + #[test] + fn production_policy_matches_the_selected_contract() { + assert_eq!(DEFAULT_POLICY.ttl, Duration::from_secs(600)); + assert_eq!(DEFAULT_POLICY.client_wait, Duration::from_secs(30)); + assert_eq!( + DEFAULT_POLICY.retry_delays, + [ + Duration::from_secs(5), + Duration::from_secs(15), + Duration::from_secs(30), + ] + ); + assert_eq!(DEFAULT_POLICY.cooldown, Duration::from_secs(600)); + } + + #[test] + fn a_fresh_snapshot_is_reused_and_an_expired_snapshot_refreshes_once() { + let calls = Arc::new(AtomicUsize::new(0)); + let counted = Arc::clone(&calls); + let policy = policy(Duration::from_millis(300), [Duration::ZERO; 3]); + let cache = UsageCache::with_policy( + vec![ProviderId::Xai], + move |provider| { + counted.fetch_add(1, Ordering::SeqCst); + entry(provider, false) + }, + policy, + ); + + assert!(matches!( + cache.get(), + CacheResponse::Complete { stale: false, .. } + )); + assert!(matches!( + cache.get(), + CacheResponse::Complete { stale: false, .. } + )); + assert_eq!(calls.load(Ordering::SeqCst), 1); + + { + let mut state = lock(&cache.state); + state.snapshot.as_mut().unwrap().completed_at = + Instant::now() - policy.ttl - Duration::from_millis(1); + } + assert!(matches!( + cache.get(), + CacheResponse::Complete { stale: false, .. } + )); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[test] + fn a_client_timeout_does_not_cancel_or_duplicate_the_active_refresh() { + let calls = Arc::new(AtomicUsize::new(0)); + let counted = Arc::clone(&calls); + let (release_tx, release_rx) = mpsc::channel(); + let release_rx = Arc::new(Mutex::new(release_rx)); + let wait_for_release = Arc::clone(&release_rx); + let cache = UsageCache::with_policy( + vec![ProviderId::Xai], + move |provider| { + counted.fetch_add(1, Ordering::SeqCst); + let _ = recv_release(&wait_for_release); + entry(provider, false) + }, + policy(Duration::from_millis(10), [Duration::ZERO; 3]), + ); + + assert!(matches!(cache.get(), CacheResponse::TimedOut { .. })); + assert!(matches!( + cache.get(), + CacheResponse::Pending { retry_after: 1.. } + )); + assert_eq!(calls.load(Ordering::SeqCst), 1); + release_tx.send(()).unwrap(); + assert!(wait_until_idle(&cache, Duration::from_millis(300))); + assert!(matches!( + cache.get(), + CacheResponse::Complete { stale: false, .. } + )); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + fn recv_release(receiver: &Arc>>) -> Result<(), mpsc::RecvTimeoutError> { + receiver + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .recv_timeout(Duration::from_secs(1)) + } + + #[test] + fn retries_only_the_timed_out_provider_and_respects_each_delay() { + let xai_calls = Arc::new(AtomicUsize::new(0)); + let openai_calls = Arc::new(AtomicUsize::new(0)); + let observed = Arc::new(Mutex::new(Vec::new())); + let xai_counter = Arc::clone(&xai_calls); + let openai_counter = Arc::clone(&openai_calls); + let observed_times = Arc::clone(&observed); + let delays = [ + Duration::from_millis(2), + Duration::from_millis(5), + Duration::from_millis(8), + ]; + let cache = UsageCache::with_policy( + vec![ProviderId::Xai, ProviderId::OpenAi], + move |provider| match provider { + ProviderId::Xai => { + observed_times.lock().unwrap().push(Instant::now()); + let attempt = xai_counter.fetch_add(1, Ordering::SeqCst); + entry(provider, attempt < 3) + } + ProviderId::OpenAi => { + openai_counter.fetch_add(1, Ordering::SeqCst); + entry(provider, false) + } + }, + policy(Duration::from_millis(300), delays), + ); + + assert!(matches!( + cache.get(), + CacheResponse::Complete { stale: false, .. } + )); + assert_eq!(xai_calls.load(Ordering::SeqCst), 4); + assert_eq!(openai_calls.load(Ordering::SeqCst), 1); + let observed = observed.lock().unwrap(); + assert_eq!(observed.len(), 4); + for (index, delay) in delays.iter().enumerate() { + assert!(observed[index + 1].duration_since(observed[index]) >= *delay); + } + } + + #[test] + fn retry_exhaustion_serves_only_the_previous_report_as_stale() { + let calls = Arc::new(AtomicUsize::new(0)); + let counted = Arc::clone(&calls); + let policy = policy(Duration::from_millis(300), [Duration::ZERO; 3]); + let cache = UsageCache::with_policy( + vec![ProviderId::Xai], + move |provider| { + counted.fetch_add(1, Ordering::SeqCst); + entry(provider, true) + }, + policy, + ); + { + let mut state = lock(&cache.state); + state.snapshot = Some(Snapshot { + entries: vec![entry(ProviderId::Xai, false).entry], + completed_at: Instant::now() - policy.ttl - Duration::from_secs(1), + updated_at_unix: 1_800_000_000, + }); + } + + assert!(matches!( + cache.get(), + CacheResponse::Complete { stale: true, .. } + )); + assert_eq!(calls.load(Ordering::SeqCst), 4); + assert!(matches!( + cache.get(), + CacheResponse::Complete { stale: true, .. } + )); + assert_eq!(calls.load(Ordering::SeqCst), 4); + } + + #[test] + fn retry_exhaustion_without_a_good_snapshot_returns_503_during_cooldown() { + let calls = Arc::new(AtomicUsize::new(0)); + let counted = Arc::clone(&calls); + let cache = UsageCache::with_policy( + vec![ProviderId::Xai], + move |provider| { + counted.fetch_add(1, Ordering::SeqCst); + entry(provider, true) + }, + policy(Duration::from_millis(300), [Duration::ZERO; 3]), + ); + + assert!(matches!( + cache.get(), + CacheResponse::Unavailable { retry_after: 1.. } + )); + assert_eq!(calls.load(Ordering::SeqCst), 4); + assert!(matches!( + cache.get(), + CacheResponse::Unavailable { retry_after: 1.. } + )); + assert_eq!(calls.load(Ordering::SeqCst), 4); + } + + #[test] + fn a_new_empty_cache_is_cold_and_returns_an_empty_provider_list() { + let calls = Arc::new(AtomicUsize::new(0)); + let counted = Arc::clone(&calls); + let cache = UsageCache::new(Vec::new(), move |provider| { + counted.fetch_add(1, Ordering::SeqCst); + entry(provider, false) + }); + match cache.get() { + CacheResponse::Complete { + snapshot, + stale: false, + } => assert!(snapshot.entries.is_empty()), + _ => panic!("an empty enabled-provider set completes with an empty report"), + } + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert!(lock(&cache.state).snapshot.is_some()); + } + + fn route_context(cache: UsageCache) -> (crate::server::ServerContext, tempfile::TempDir) { + let directory = tempfile::tempdir().unwrap(); + let keys = + Arc::new(crate::keys::KeyStore::open(directory.path().join("keys.json")).unwrap()); + let context = crate::server::ServerContext { + host: "127.0.0.1".to_string(), + port: 8484, + api_key: "route-test-key".to_string(), + keys, + providers: std::collections::HashMap::new(), + default_provider: ProviderId::Xai, + routing: crate::config::Routing::default(), + upstream_in_flight: Arc::new(std::sync::atomic::AtomicUsize::new(0)), + max_upstream_requests: crate::server::DEFAULT_MAX_UPSTREAM_REQUESTS, + inferences: Arc::new(crate::inference::InferenceState::new()), + usage_cache: Arc::new(cache), + }; + (context, directory) + } + + fn response_header<'a>(response: &'a crate::server::Response, name: &str) -> Option<&'a str> { + response + .headers + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.as_str()) + } + + #[test] + fn the_route_returns_504_then_202_while_one_refresh_continues() { + let (release_tx, release_rx) = mpsc::channel(); + let release_rx = Arc::new(Mutex::new(release_rx)); + let wait_for_release = Arc::clone(&release_rx); + let cache = UsageCache::with_policy( + vec![ProviderId::Xai], + move |provider| { + let _ = recv_release(&wait_for_release); + entry(provider, false) + }, + policy(Duration::from_millis(10), [Duration::ZERO; 3]), + ); + let (context, _directory) = route_context(cache); + + let timed_out = handle(&context); + assert_eq!(timed_out.status, 504); + assert_eq!(response_header(&timed_out, "Retry-After"), Some("1")); + assert_eq!( + response_header(&timed_out, "Cache-Control"), + Some(CACHE_CONTROL) + ); + + let pending = handle(&context); + assert_eq!(pending.status, 202); + assert!(response_header(&pending, "Retry-After").is_some()); + release_tx.send(()).unwrap(); + assert!(wait_until_idle( + &context.usage_cache, + Duration::from_millis(300) + )); + assert_eq!(handle(&context).status, 200); + } + + #[test] + fn the_route_marks_a_stale_snapshot_and_returns_503_without_one() { + let policy = policy(Duration::from_millis(300), [Duration::ZERO; 3]); + let stale_cache = UsageCache::with_policy( + vec![ProviderId::Xai], + |provider| entry(provider, true), + policy, + ); + { + let mut state = lock(&stale_cache.state); + state.snapshot = Some(Snapshot { + entries: vec![entry(ProviderId::Xai, false).entry], + completed_at: Instant::now() - policy.ttl - Duration::from_secs(1), + updated_at_unix: 1_800_000_000, + }); + } + let (stale_context, _stale_directory) = route_context(stale_cache); + let stale = handle(&stale_context); + assert_eq!(stale.status, 200); + assert_eq!( + response_header(&stale, "X-Eggpass-Usage-Stale"), + Some("true") + ); + assert!( + response_header(&stale, "X-Eggpass-Usage-Age") + .and_then(|value| value.parse::().ok()) + .is_some_and(|age| age >= 600) + ); + assert_eq!( + response_header(&stale, "Cache-Control"), + Some(CACHE_CONTROL) + ); + + let empty_cache = UsageCache::with_policy( + vec![ProviderId::Xai], + |provider| entry(provider, true), + policy, + ); + let (empty_context, _empty_directory) = route_context(empty_cache); + let empty = handle(&empty_context); + assert_eq!(empty.status, 503); + assert!(response_header(&empty, "Retry-After").is_some()); + assert_eq!( + response_header(&empty, "Cache-Control"), + Some(CACHE_CONTROL) + ); + assert_eq!(handle(&empty_context).status, 503); + } +} From a626ef7561e096342a4d83f7d2ca452b9b52b873 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Wed, 18 Nov 2026 20:05:33 +0000 Subject: [PATCH 04/11] fix: avoid Windows Instant underflow in usage tests --- src/server/usage.rs | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/src/server/usage.rs b/src/server/usage.rs index b4202e3..36caf97 100644 --- a/src/server/usage.rs +++ b/src/server/usage.rs @@ -103,7 +103,10 @@ impl UsageCache { /// Return a fresh snapshot, or trigger/share one finite refresh. fn get(&self) -> CacheResponse { - let now = Instant::now(); + self.get_at(Instant::now()) + } + + fn get_at(&self, now: Instant) -> CacheResponse { let mut state = lock(&self.state); if let Some(response) = response_for_state(&state, now, self.policy) { // A request arriving after another one started never waits on its @@ -485,13 +488,9 @@ mod tests { )); assert_eq!(calls.load(Ordering::SeqCst), 1); - { - let mut state = lock(&cache.state); - state.snapshot.as_mut().unwrap().completed_at = - Instant::now() - policy.ttl - Duration::from_millis(1); - } + let expired_at = Instant::now() + cache.policy.ttl; assert!(matches!( - cache.get(), + cache.get_at(expired_at), CacheResponse::Complete { stale: false, .. } )); assert_eq!(calls.load(Ordering::SeqCst), 2); @@ -582,7 +581,8 @@ mod tests { fn retry_exhaustion_serves_only_the_previous_report_as_stale() { let calls = Arc::new(AtomicUsize::new(0)); let counted = Arc::clone(&calls); - let policy = policy(Duration::from_millis(300), [Duration::ZERO; 3]); + let mut policy = policy(Duration::from_millis(300), [Duration::ZERO; 3]); + policy.ttl = Duration::ZERO; let cache = UsageCache::with_policy( vec![ProviderId::Xai], move |provider| { @@ -595,7 +595,7 @@ mod tests { let mut state = lock(&cache.state); state.snapshot = Some(Snapshot { entries: vec![entry(ProviderId::Xai, false).entry], - completed_at: Instant::now() - policy.ttl - Duration::from_secs(1), + completed_at: Instant::now(), updated_at_unix: 1_800_000_000, }); } @@ -720,7 +720,8 @@ mod tests { #[test] fn the_route_marks_a_stale_snapshot_and_returns_503_without_one() { - let policy = policy(Duration::from_millis(300), [Duration::ZERO; 3]); + let mut policy = policy(Duration::from_millis(300), [Duration::ZERO; 3]); + policy.ttl = Duration::ZERO; let stale_cache = UsageCache::with_policy( vec![ProviderId::Xai], |provider| entry(provider, true), @@ -730,7 +731,7 @@ mod tests { let mut state = lock(&stale_cache.state); state.snapshot = Some(Snapshot { entries: vec![entry(ProviderId::Xai, false).entry], - completed_at: Instant::now() - policy.ttl - Duration::from_secs(1), + completed_at: Instant::now(), updated_at_unix: 1_800_000_000, }); } @@ -744,8 +745,9 @@ mod tests { assert!( response_header(&stale, "X-Eggpass-Usage-Age") .and_then(|value| value.parse::().ok()) - .is_some_and(|age| age >= 600) + .is_some() ); + assert!(response_header(&stale, "X-Eggpass-Usage-Updated-At").is_some()); assert_eq!( response_header(&stale, "Cache-Control"), Some(CACHE_CONTROL) From 3167f895c4b33c38a6dff2b06ca52a0a6a5ed8dd Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Thu, 19 Nov 2026 18:09:58 +0000 Subject: [PATCH 05/11] test: isolate Windows usage-key ACL validation --- Cargo.toml | 2 +- src/cli/commands/run.rs | 8 + src/main.rs | 1 + src/paths.rs | 15 +- src/server/mod.rs | 166 +++++++++++- src/server/tests.rs | 34 +++ src/server/usage.rs | 1 + src/usage_key.rs | 545 ++++++++++++++++++++++++++++++++++++++++ 8 files changed, 768 insertions(+), 4 deletions(-) create mode 100644 src/usage_key.rs diff --git a/Cargo.toml b/Cargo.toml index a2a1861..6ea8b16 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -72,7 +72,7 @@ daemonize = "0.5.0" nix = { version = "0.31.3", features = ["signal", "process", "term"] } [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_Threading"] } +windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Threading"] } [dev-dependencies] tempfile = "3.27.0" diff --git a/src/cli/commands/run.rs b/src/cli/commands/run.rs index f03abed..52edab5 100644 --- a/src/cli/commands/run.rs +++ b/src/cli/commands/run.rs @@ -259,10 +259,18 @@ fn serve(context: &Context) -> Result<(), CommandError> { }, )); + let usage_key = + crate::usage_key::UsageKey::create(context.paths.usage_key_file()).map_err(|err| { + CommandError::new(format!( + "could not create the private daemon usage credential: {err}" + )) + })?; + let server_context = Arc::new(ServerContext { host: context.config.host.clone(), port: context.config.port, api_key: context.config.api_key.clone(), + usage_key: usage_key.token().to_string(), keys, providers, default_provider, diff --git a/src/main.rs b/src/main.rs index cdab860..bd6b566 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,6 +19,7 @@ mod server; mod timeutil; mod update; mod upstream; +mod usage_key; use cli::args::ParseOutcome; diff --git a/src/paths.rs b/src/paths.rs index f5d60be..74552c3 100644 --- a/src/paths.rs +++ b/src/paths.rs @@ -3,12 +3,12 @@ //! Resolution order for the configuration directory: //! //! 1. `$EGGPASS_HOME` when set — relocates *every* file (config, credentials, -//! pid, log). Useful for tests and for running a second instance. +//! usage key, pid, log). Useful for tests and for running a second instance. //! 2. `$XDG_CONFIG_HOME/eggpass` when set. //! 3. `~/.config/eggpass`. //! //! The `--config ` flag overrides only the configuration *file*; the -//! credential, pid and log files stay in the resolved directory. +//! credential, usage-key, pid and log files stay in the resolved directory. use std::path::{Path, PathBuf}; @@ -22,6 +22,8 @@ pub const LOG_FILE_NAME: &str = "eggpass.log"; pub const CREDENTIALS_DIR_NAME: &str = "credentials"; /// Name of the file holding the keys `eggpass` issues to its clients. pub const KEY_STORE_FILE_NAME: &str = "keys.json"; +/// Name of the daemon-managed CLI-only usage credential file. +pub const USAGE_KEY_FILE_NAME: &str = "usage.key"; /// The legacy single-provider credential file, kept for the migration. pub const LEGACY_AUTH_FILE_NAME: &str = "auth.json"; /// The name this project had before the rename. @@ -120,6 +122,11 @@ impl Paths { self.dir.join(KEY_STORE_FILE_NAME) } + /// The daemon-managed usage-only credential (not moved by `--config`). + pub fn usage_key_file(&self) -> PathBuf { + self.dir.join(USAGE_KEY_FILE_NAME) + } + /// The daemon pid file. pub fn pid_file(&self) -> PathBuf { self.dir.join(PID_FILE_NAME) @@ -294,6 +301,10 @@ mod tests { paths.pid_file(), Path::new("/tmp/eggpass-test-home/eggpass.pid") ); + assert_eq!( + paths.usage_key_file(), + Path::new("/tmp/eggpass-test-home/usage.key") + ); } #[test] diff --git a/src/server/mod.rs b/src/server/mod.rs index 124efab..079ab73 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -73,6 +73,10 @@ pub struct ServerContext { /// Empty means there is no such key. The keys `eggpass` issued are /// accepted as well. pub api_key: String, + /// The exact runtime bearer secret authorized only for bodyless `GET /v1/usage`. + /// + /// This is never counted as a configured client key. + pub usage_key: String, /// The keys `eggpass` issued to its clients. pub keys: Arc, /// The providers that are available. @@ -390,7 +394,40 @@ pub fn is_authorized(context: &ServerContext, request: &Request) -> bool { } } - false + usage_key_authorized(context, request) +} + +/// Whether the dedicated runtime secret is presented for its sole allowed request. +fn usage_key_authorized(context: &ServerContext, request: &Request) -> bool { + if context.usage_key.is_empty() + || request.method != "GET" + || request.target != "/v1/usage" + || !request.body.is_empty() + || request + .headers + .iter() + .any(|(name, _)| name.eq_ignore_ascii_case("transfer-encoding")) + { + return false; + } + + if request + .headers + .iter() + .any(|(name, value)| name.eq_ignore_ascii_case("content-length") && value.trim() != "0") + { + return false; + } + + request.headers.iter().any(|(name, value)| { + if !name.eq_ignore_ascii_case("authorization") { + return false; + } + let Some(token) = strip_bearer(value.trim()) else { + return false; + }; + crate::keys::constant_time_eq(token.as_bytes(), context.usage_key.as_bytes()) + }) } /// The keys a request presents. @@ -487,6 +524,7 @@ mod authorisation_tests { host: "127.0.0.1".to_string(), port: 8484, api_key: key.to_string(), + usage_key: "usage-only-secret".to_string(), keys: empty_store(), providers: HashMap::new(), default_provider: ProviderId::Xai, @@ -513,6 +551,19 @@ mod authorisation_tests { } } + fn request_at(method: &str, target: &str, headers: Vec<(&str, &str)>, body: &[u8]) -> Request { + Request { + method: method.to_string(), + target: target.to_string(), + version: "HTTP/1.1".to_string(), + headers: headers + .into_iter() + .map(|(name, value)| (name.to_string(), value.to_string())) + .collect(), + body: body.to_vec(), + } + } + fn health_request() -> Request { Request { method: "GET".to_string(), @@ -523,6 +574,118 @@ mod authorisation_tests { } } + #[test] + fn the_usage_secret_is_limited_to_the_exact_bearer_usage_get() { + let context = context_with_key("regular-secret"); + let valid = request_at( + "GET", + "/v1/usage", + vec![("Authorization", "Bearer usage-only-secret")], + &[], + ); + assert!(is_authorized(&context, &valid)); + + for request in [ + request_at( + "POST", + "/v1/usage", + vec![("Authorization", "Bearer usage-only-secret")], + &[], + ), + request_at("GET", "/v1/usage?key=usage-only-secret", vec![], &[]), + request_at( + "GET", + "/usage", + vec![("Authorization", "Bearer usage-only-secret")], + &[], + ), + request_at( + "GET", + "/v1/models", + vec![("Authorization", "Bearer usage-only-secret")], + &[], + ), + request_at( + "GET", + "/v1/usage", + vec![("X-Api-Key", "usage-only-secret")], + &[], + ), + request_at( + "GET", + "/v1/usage", + vec![("Authorization", "Bearer usage-only-secretx")], + &[], + ), + request_at( + "GET", + "/v1/usage", + vec![("Authorization", "Bearer sage-only-secret")], + &[], + ), + request_at( + "GET", + "/v1/usage", + vec![ + ("Authorization", "Bearer usage-only-secret"), + ("Content-Length", "1"), + ], + &[], + ), + request_at( + "GET", + "/v1/usage", + vec![ + ("Authorization", "Bearer usage-only-secret"), + ("Transfer-Encoding", "chunked"), + ], + &[], + ), + request_at( + "GET", + "/v1/usage", + vec![("Authorization", "Bearer usage-only-secret")], + b"body", + ), + ] { + assert!( + !is_authorized(&context, &request), + "scoped credential accepted an out-of-scope request" + ); + } + + // The same regular key keeps its existing full route scope and accepted presentations. + assert!(is_authorized( + &context, + &request_at( + "GET", + "/v1/models", + vec![("Authorization", "Bearer regular-secret")], + &[] + ), + )); + } + + #[test] + fn the_usage_secret_does_not_count_as_a_configured_client_key() { + let context = context_with_key(""); + let request = request_at( + "GET", + "/v1/usage", + vec![("Authorization", "Bearer usage-only-secret")], + &[], + ); + assert!(!keys_configured(&context)); + assert!(!is_authorized(&context, &request)); + assert_eq!( + pre_authorize(&request, &context) + .expect("no regular key") + .status, + 401 + ); + assert!(context.keys.is_empty()); + } + #[test] fn a_server_with_no_key_refuses_everything() { let context = context_with_key(""); @@ -678,6 +841,7 @@ mod authorisation_tests { host: "127.0.0.1".to_string(), port: 8484, api_key: String::new(), + usage_key: String::new(), keys: empty_store(), providers: HashMap::new(), default_provider: ProviderId::Xai, diff --git a/src/server/tests.rs b/src/server/tests.rs index fb948b9..2107824 100644 --- a/src/server/tests.rs +++ b/src/server/tests.rs @@ -402,6 +402,7 @@ fn harness_with_spec( host: "127.0.0.1".to_string(), port, api_key: api_key.to_string(), + usage_key: "server-test-usage-key".to_string(), keys: Arc::clone(&keys), providers, default_provider: spec.id, @@ -1358,6 +1359,39 @@ fn usage_route_is_authenticated_cached_and_attaches_fresh_inference_state() { ); } +#[test] +fn the_daemon_usage_credential_cannot_authorize_other_routes() { + let stub = Stub::start(|_| Reply::json(404, "{}")); + let harness = harness(&stub, "regular-client-key", "provider-token"); + let secret = "server-test-usage-key"; + + let usage = agent() + .get(harness.url("/v1/usage")) + .header("Authorization", &format!("Bearer {secret}")) + .call() + .expect("the scoped usage request answers"); + assert_eq!(usage.status(), 200); + + let models = agent() + .get(harness.url("/v1/models")) + .header("Authorization", &format!("Bearer {secret}")) + .call() + .expect("the proxy rejects out-of-scope credentials"); + assert_eq!(models.status(), 401); + + let inference = agent() + .post(harness.url("/v1/chat/completions")) + .header("Authorization", &format!("Bearer {secret}")) + .header("Content-Type", "application/json") + .send(chat_body().to_string()) + .expect("the proxy rejects the scoped credential"); + assert_eq!(inference.status(), 401); + assert!( + harness.keys.is_empty(), + "the runtime secret is not an issued client key" + ); +} + #[test] fn a_native_responses_request_is_forwarded_untouched() { // A Responses-only provider speaks the Responses API natively. A request diff --git a/src/server/usage.rs b/src/server/usage.rs index 36caf97..2c946eb 100644 --- a/src/server/usage.rs +++ b/src/server/usage.rs @@ -664,6 +664,7 @@ mod tests { host: "127.0.0.1".to_string(), port: 8484, api_key: "route-test-key".to_string(), + usage_key: String::new(), keys, providers: std::collections::HashMap::new(), default_provider: ProviderId::Xai, diff --git a/src/usage_key.rs b/src/usage_key.rs new file mode 100644 index 0000000..a48d819 --- /dev/null +++ b/src/usage_key.rs @@ -0,0 +1,545 @@ +//! Daemon-managed, route-scoped runtime credential for the CLI usage report. +//! +//! This secret is intentionally separate from the regular client-key store. +//! It is generated on every daemon start, stored only in a private runtime +//! file, and removed on graceful shutdown when the file still contains this +//! daemon's token. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use rand::Rng; + +const TOKEN_BYTES: usize = 32; +const TOKEN_CHARS: usize = 43; +const TEMP_ATTEMPTS: usize = 8; + +/// A runtime usage secret and its cleanup lease. +pub(crate) struct UsageKey { + path: PathBuf, + token: String, +} + +impl UsageKey { + /// Generate and atomically persist a fresh daemon token. + pub(crate) fn create(path: impl Into) -> io::Result { + let path = path.into(); + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + fs::create_dir_all(parent)?; + protect_path(parent, true)?; + + let token = generate_token(); + write_private_atomic(&path, token.as_bytes())?; + Ok(Self { path, token }) + } + + /// The exact bearer token held by the daemon. + pub(crate) fn token(&self) -> &str { + &self.token + } + + /// Read a bounded, correctly shaped token without including its contents in errors. + pub(crate) fn read(path: &Path) -> io::Result { + let file = File::open(path)?; + let metadata = file.metadata()?; + if metadata.len() != TOKEN_CHARS as u64 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid usage credential file", + )); + } + + let mut bytes = Vec::with_capacity(TOKEN_CHARS); + file.take((TOKEN_CHARS + 1) as u64) + .read_to_end(&mut bytes)?; + if !valid_token_bytes(&bytes) { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid usage credential file", + )); + } + String::from_utf8(bytes).map_err(|_| { + io::Error::new(io::ErrorKind::InvalidData, "invalid usage credential file") + }) + } +} + +impl Drop for UsageKey { + fn drop(&mut self) { + let Ok(file) = File::open(&self.path) else { + return; + }; + let Ok(metadata) = file.metadata() else { + return; + }; + if metadata.len() != self.token.len() as u64 { + return; + } + let mut bytes = Vec::with_capacity(self.token.len()); + if file + .take((self.token.len() + 1) as u64) + .read_to_end(&mut bytes) + .is_err() + { + return; + } + if crate::keys::constant_time_eq(&bytes, self.token.as_bytes()) { + let _ = fs::remove_file(&self.path); + } + } +} + +fn generate_token() -> String { + let mut bytes = [0u8; TOKEN_BYTES]; + rand::rng().fill_bytes(&mut bytes); + URL_SAFE_NO_PAD.encode(bytes) +} + +fn valid_token_bytes(bytes: &[u8]) -> bool { + bytes.len() == TOKEN_CHARS + && bytes + .iter() + .all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-' || *byte == b'_') +} + +fn write_private_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let file_name = path.file_name().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "usage credential path has no file name", + ) + })?; + + for _ in 0..TEMP_ATTEMPTS { + let temporary = parent.join(format!( + ".{}.tmp.{}.{}", + file_name.to_string_lossy(), + std::process::id(), + random_component(), + )); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + + let mut file = match options.open(&temporary) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + }; + + let result = (|| { + // On Windows this installs a protected, current-user-only DACL + // before any token bytes are written. Unix uses mode 0600 above. + protect_path(&temporary, false)?; + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + replace_file(&temporary, path) + })(); + if result.is_err() { + let _ = fs::remove_file(&temporary); + return result; + } + + // Persist the directory entry when the platform supports syncing it. + if let Ok(directory) = File::open(parent) { + let _ = directory.sync_all(); + } + return Ok(()); + } + + Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "could not allocate a unique usage credential temporary file", + )) +} + +fn random_component() -> String { + let mut bytes = [0u8; 16]; + rand::rng().fill_bytes(&mut bytes); + URL_SAFE_NO_PAD.encode(bytes) +} + +#[cfg(unix)] +fn protect_path(path: &Path, directory: bool) -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions( + path, + fs::Permissions::from_mode(if directory { 0o700 } else { 0o600 }), + ) +} + +#[cfg(windows)] +fn protect_path(path: &Path, directory: bool) -> io::Result<()> { + use std::ffi::OsStr; + use std::iter::once; + use std::os::windows::ffi::OsStrExt; + use std::ptr::{null, null_mut}; + + use windows_sys::Win32::Foundation::{CloseHandle, LocalFree}; + use windows_sys::Win32::Security::Authorization::{ + ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, + SDDL_REVISION_1, + }; + use windows_sys::Win32::Security::{ + DACL_SECURITY_INFORMATION, EqualSid, GetTokenInformation, + PROTECTED_DACL_SECURITY_INFORMATION, SetFileSecurityW, TOKEN_QUERY, TOKEN_USER, TokenUser, + }; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + + // SAFETY: the process pseudo-handle is valid and the output handle is writable. + let mut token_handle = null_mut(); + if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token_handle) } == 0 { + return Err(io::Error::last_os_error()); + } + struct TokenHandle(windows_sys::Win32::Foundation::HANDLE); + impl Drop for TokenHandle { + fn drop(&mut self) { + // SAFETY: this wrapper owns the handle returned by OpenProcessToken. + unsafe { CloseHandle(self.0) }; + } + } + let token_handle = TokenHandle(token_handle); + + let mut needed = 0u32; + // SAFETY: this is the documented size query; no output buffer is supplied. + unsafe { + GetTokenInformation(token_handle.0, TokenUser, null_mut(), 0, &mut needed); + } + if needed == 0 { + return Err(io::Error::last_os_error()); + } + let mut token_user = vec![0usize; (needed as usize).div_ceil(std::mem::size_of::())]; + // SAFETY: the aligned buffer is sized from the preceding TokenUser query. + if unsafe { + GetTokenInformation( + token_handle.0, + TokenUser, + token_user.as_mut_ptr().cast(), + needed, + &mut needed, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + // SAFETY: GetTokenInformation filled a correctly aligned TOKEN_USER value. + let user = unsafe { &*token_user.as_ptr().cast::() }; + let mut sid_text = null_mut(); + // SAFETY: the SID came from the current process token and sid_text is writable. + if unsafe { ConvertSidToStringSidW(user.User.Sid, &mut sid_text) } == 0 { + return Err(io::Error::last_os_error()); + } + let sid = unsafe { + let mut length = 0usize; + while *sid_text.add(length) != 0 { + length += 1; + } + String::from_utf16_lossy(std::slice::from_raw_parts(sid_text, length)) + }; + // SAFETY: sid_text was allocated by ConvertSidToStringSidW. + unsafe { LocalFree(sid_text.cast()) }; + + let inheritance = if directory { "OICI" } else { "" }; + let descriptor_text: Vec = OsStr::new(&format!("D:P(A;{inheritance};FA;;;{sid})")) + .encode_wide() + .chain(once(0)) + .collect(); + let mut descriptor = null_mut(); + // SAFETY: descriptor_text is nul-terminated, descriptor is writable, and + // the descriptor is freed below with LocalFree. + if unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorW( + descriptor_text.as_ptr(), + SDDL_REVISION_1, + &mut descriptor, + null_mut(), + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + + let path_wide: Vec = path.as_os_str().encode_wide().chain(once(0)).collect(); + // SAFETY: both pointers remain valid for the call; the descriptor contains + // a protected DACL granting full access only to the current token's user SID. + let result = unsafe { + SetFileSecurityW( + path_wide.as_ptr(), + DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, + descriptor, + ) + }; + let error = (result == 0).then(io::Error::last_os_error); + // SAFETY: descriptor was allocated by the Windows SDDL conversion API. + unsafe { LocalFree(descriptor.cast()) }; + error.map_or(Ok(()), Err) +} + +#[cfg(not(any(unix, windows)))] +fn protect_path(_path: &Path, _directory: bool) -> io::Result<()> { + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "private usage credential permissions are unsupported on this platform", + )) +} + +#[cfg(unix)] +fn replace_file(from: &Path, to: &Path) -> io::Result<()> { + fs::rename(from, to) +} + +#[cfg(windows)] +fn replace_file(from: &Path, to: &Path) -> io::Result<()> { + use std::iter::once; + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Storage::FileSystem::{ + MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW, + }; + + let from_wide: Vec = from.as_os_str().encode_wide().chain(once(0)).collect(); + let to_wide: Vec = to.as_os_str().encode_wide().chain(once(0)).collect(); + // SAFETY: both paths are valid nul-terminated UTF-16 strings. The replace + // flag gives rotation atomic replacement semantics on Windows. + if unsafe { + MoveFileExW( + from_wide.as_ptr(), + to_wide.as_ptr(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH, + ) + } == 0 + { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } +} + +#[cfg(not(any(unix, windows)))] +fn replace_file(from: &Path, to: &Path) -> io::Result<()> { + fs::rename(from, to) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rotation_replaces_the_token_and_old_cleanup_cannot_remove_it() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("usage.key"); + let first = UsageKey::create(&path).unwrap(); + let first_token = first.token().to_owned(); + assert!(valid_token_bytes(first_token.as_bytes())); + assert!(crate::keys::constant_time_eq( + UsageKey::read(&path).unwrap().as_bytes(), + first_token.as_bytes() + )); + + let second = UsageKey::create(&path).unwrap(); + let second_token = second.token().to_owned(); + assert!( + !crate::keys::constant_time_eq(first_token.as_bytes(), second_token.as_bytes()), + "daemon starts rotate the usage credential" + ); + + drop(first); + assert!(crate::keys::constant_time_eq( + UsageKey::read(&path).unwrap().as_bytes(), + second_token.as_bytes() + )); + drop(second); + assert!(!path.exists(), "matching graceful cleanup removes the file"); + } + + #[test] + fn a_failed_private_file_creation_is_reported() { + let directory = tempfile::tempdir().unwrap(); + let not_a_directory = directory.path().join("file"); + fs::write(¬_a_directory, "not a directory").unwrap(); + let error = UsageKey::create(not_a_directory.join("usage.key")) + .err() + .expect("creation under a file fails"); + assert_ne!(error.kind(), io::ErrorKind::NotFound); + } + + #[cfg(unix)] + #[test] + fn the_directory_and_secret_file_are_owner_only() { + use std::os::unix::fs::PermissionsExt; + + let directory = tempfile::tempdir().unwrap(); + let data = directory.path().join("eggpass"); + let path = data.join("usage.key"); + let key = UsageKey::create(&path).unwrap(); + let dir_mode = fs::metadata(&data).unwrap().permissions().mode() & 0o777; + let file_mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(dir_mode, 0o700); + assert_eq!(file_mode, 0o600); + drop(key); + } + + #[cfg(windows)] + #[test] + fn the_directory_and_secret_file_have_current_user_only_dacls() { + let directory = tempfile::tempdir().unwrap(); + let data = directory.path().join("eggpass"); + let path = data.join("usage.key"); + let key = UsageKey::create(&path).unwrap(); + assert!(windows_acl_is_current_user_only(&data, true)); + assert!(windows_acl_is_current_user_only(&path, false)); + drop(key); + } + + #[cfg(windows)] + fn windows_acl_is_current_user_only(path: &Path, directory: bool) -> bool { + use std::iter::once; + use std::os::windows::ffi::OsStrExt; + use std::ptr::null_mut; + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::Security::{ + ACCESS_ALLOWED_ACE, ACCESS_ALLOWED_ACE_TYPE, ACL_SIZE_INFORMATION, AclSizeInformation, + CONTAINER_INHERIT_ACE, DACL_SECURITY_INFORMATION, EqualSid, GetAce, GetAclInformation, + GetFileSecurityW, GetSecurityDescriptorDacl, GetTokenInformation, OBJECT_INHERIT_ACE, + TOKEN_QUERY, TOKEN_USER, TokenUser, + }; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + + let path_wide: Vec = path.as_os_str().encode_wide().chain(once(0)).collect(); + let mut required = 0u32; + // SAFETY: size query for the DACL security descriptor. + unsafe { + GetFileSecurityW( + path_wide.as_ptr(), + DACL_SECURITY_INFORMATION, + null_mut(), + 0, + &mut required, + ) + }; + if required == 0 { + return false; + } + let mut descriptor = + vec![0usize; (required as usize).div_ceil(std::mem::size_of::())]; + // SAFETY: the aligned descriptor buffer has the required size. + if unsafe { + GetFileSecurityW( + path_wide.as_ptr(), + DACL_SECURITY_INFORMATION, + descriptor.as_mut_ptr().cast(), + required, + &mut required, + ) + } == 0 + { + return false; + } + let mut dacl_present = 0; + let mut dacl = null_mut(); + let mut dacl_defaulted = 0; + // SAFETY: descriptor contains the DACL requested above. + if unsafe { + GetSecurityDescriptorDacl( + descriptor.as_mut_ptr().cast(), + &mut dacl_present, + &mut dacl, + &mut dacl_defaulted, + ) + } == 0 + || dacl_present == 0 + || dacl.is_null() + { + return false; + } + let mut acl_info = ACL_SIZE_INFORMATION { + AceCount: 0, + AclBytesInUse: 0, + AclBytesFree: 0, + }; + // SAFETY: dacl is valid and acl_info is writable. + if unsafe { + GetAclInformation( + dacl, + (&mut acl_info as *mut ACL_SIZE_INFORMATION).cast(), + std::mem::size_of::() as u32, + AclSizeInformation, + ) + } == 0 + || acl_info.AceCount != 1 + { + return false; + } + let mut ace_ptr = null_mut(); + // SAFETY: index 0 exists because AceCount is one. + if unsafe { GetAce(dacl, 0, &mut ace_ptr) } == 0 || ace_ptr.is_null() { + return false; + } + let ace = unsafe { &*ace_ptr.cast::() }; + let ace_sid = (&ace.SidStart as *const u32).cast_mut().cast(); + + let mut token = null_mut(); + // SAFETY: the process pseudo-handle is valid and token output is writable. + if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 { + return false; + } + let mut needed = 0u32; + // SAFETY: size query for TokenUser. + unsafe { GetTokenInformation(token, TokenUser, null_mut(), 0, &mut needed) }; + if needed == 0 { + unsafe { CloseHandle(token) }; + return false; + } + let mut user_buffer = + vec![0usize; (needed as usize).div_ceil(std::mem::size_of::())]; + // SAFETY: the aligned buffer has the queried size. + if unsafe { + GetTokenInformation( + token, + TokenUser, + user_buffer.as_mut_ptr().cast(), + needed, + &mut needed, + ) + } == 0 + { + unsafe { CloseHandle(token) }; + return false; + } + let user = unsafe { &*user_buffer.as_ptr().cast::() }; + let same_user = unsafe { EqualSid(ace_sid, user.User.Sid) } != 0; + unsafe { CloseHandle(token) }; + let expected_flags = if directory { + OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE + } else { + 0 + }; + same_user + && ace.Header.AceType == ACCESS_ALLOWED_ACE_TYPE + && ace.Header.AceFlags == expected_flags + } + + #[test] + fn invalid_usage_file_is_rejected_without_echoing_contents() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("usage.key"); + fs::write(&path, "not-a-token").unwrap(); + let error = UsageKey::read(&path).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert_eq!(error.to_string(), "invalid usage credential file"); + } +} From 7039a9ff99b4a2c98b838dd7c5b67ff8a13764dd Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Thu, 19 Nov 2026 18:17:00 +0000 Subject: [PATCH 06/11] chore: update ci.yml --- .github/workflows/ci.yml | 14 +- .github/workflows/publish-crates.yml | 10 +- .../workflows/publish-eggpass-auth-pypi.yml | 326 ++++ .github/workflows/publish-eggpass-auth.yml | 66 + .github/workflows/python-auth.yml | 263 ++++ .github/workflows/release.yml | 371 ++++- .gitignore | 3 + .../skills/eggpass-eggpack-release/SKILL.md | 71 + CHANGELOG.md | 15 +- Cargo.lock | 83 +- Cargo.toml | 8 +- README.md | 10 +- async-auth-library-requirements.md | 57 + async-auth-migration-cost.md | 39 + crates/eggpass-auth/Cargo.toml | 31 + crates/eggpass-auth/LICENSE | 21 + crates/eggpass-auth/README.md | 63 + crates/eggpass-auth/examples/downstream.rs | 21 + crates/eggpass-auth/src/authorization.rs | 390 +++++ crates/eggpass-auth/src/client.rs | 966 ++++++++++++ crates/eggpass-auth/src/error.rs | 210 +++ crates/eggpass-auth/src/lib.rs | 77 + crates/eggpass-auth/src/manager.rs | 273 ++++ crates/eggpass-auth/src/pkce.rs | 43 + crates/eggpass-auth/src/provider.rs | 669 +++++++++ crates/eggpass-auth/src/token.rs | 538 +++++++ crates/eggpass-auth/tests/oauth_stub.rs | 513 +++++++ docs/README.md | 1 + docs/commands.md | 6 +- docs/configuration.md | 7 +- docs/how-it-works.md | 8 +- docs/releasing.md | 151 +- docs/updating.md | 14 +- plans/async-auth-library-implementation.md | 143 ++ .../daemon-usage-cli-cache-implementation.md | 126 ++ plans/python-pyo3-bindings-implementation.md | 124 ++ plans/python-pypi-release-implementation.md | 130 ++ python/eggpass-auth/Cargo.lock | 1333 +++++++++++++++++ python/eggpass-auth/Cargo.toml | 23 + python/eggpass-auth/LICENSE | 21 + python/eggpass-auth/README.md | 86 ++ python/eggpass-auth/pyproject.toml | 43 + .../eggpass-auth/src/eggpass_auth/__init__.py | 70 + .../src/eggpass_auth/__init__.pyi | 151 ++ python/eggpass-auth/src/eggpass_auth/py.typed | 1 + python/eggpass-auth/src/lib.rs | 897 +++++++++++ python/eggpass-auth/tests/test_async_api.py | 389 +++++ python/eggpass-auth/tests/typecheck_api.py | 23 + python/eggpass-auth/tools/sync_core.py | 69 + .../vendor/eggpass-auth/Cargo.toml | 31 + .../eggpass-auth/vendor/eggpass-auth/LICENSE | 21 + .../vendor/eggpass-auth/README.md | 63 + .../eggpass-auth/examples/downstream.rs | 21 + .../vendor/eggpass-auth/src/authorization.rs | 390 +++++ .../vendor/eggpass-auth/src/client.rs | 966 ++++++++++++ .../vendor/eggpass-auth/src/error.rs | 210 +++ .../vendor/eggpass-auth/src/lib.rs | 77 + .../vendor/eggpass-auth/src/manager.rs | 273 ++++ .../vendor/eggpass-auth/src/pkce.rs | 43 + .../vendor/eggpass-auth/src/provider.rs | 669 +++++++++ .../vendor/eggpass-auth/src/token.rs | 538 +++++++ release/eggpack/github-policy.json | 2 +- src/auth/bridge.rs | 114 ++ src/auth/client.rs | 1008 ++++--------- src/auth/flow.rs | 227 ++- src/auth/mod.rs | 2 +- src/auth/pkce.rs | 83 - src/auth/store.rs | 46 +- src/cli/commands/login.rs | 26 +- src/cli/commands/usage.rs | 792 +++++++++- src/provider/mod.rs | 10 + src/provider/usage/mod.rs | 18 +- src/provider/usage/openai.rs | 2 +- src/provider/usage/report.rs | 8 +- 74 files changed, 13495 insertions(+), 1112 deletions(-) create mode 100644 .github/workflows/publish-eggpass-auth-pypi.yml create mode 100644 .github/workflows/publish-eggpass-auth.yml create mode 100644 .github/workflows/python-auth.yml create mode 100644 .minimax/skills/eggpass-eggpack-release/SKILL.md create mode 100644 async-auth-library-requirements.md create mode 100644 async-auth-migration-cost.md create mode 100644 crates/eggpass-auth/Cargo.toml create mode 100644 crates/eggpass-auth/LICENSE create mode 100644 crates/eggpass-auth/README.md create mode 100644 crates/eggpass-auth/examples/downstream.rs create mode 100644 crates/eggpass-auth/src/authorization.rs create mode 100644 crates/eggpass-auth/src/client.rs create mode 100644 crates/eggpass-auth/src/error.rs create mode 100644 crates/eggpass-auth/src/lib.rs create mode 100644 crates/eggpass-auth/src/manager.rs create mode 100644 crates/eggpass-auth/src/pkce.rs create mode 100644 crates/eggpass-auth/src/provider.rs create mode 100644 crates/eggpass-auth/src/token.rs create mode 100644 crates/eggpass-auth/tests/oauth_stub.rs create mode 100644 plans/async-auth-library-implementation.md create mode 100644 plans/daemon-usage-cli-cache-implementation.md create mode 100644 plans/python-pyo3-bindings-implementation.md create mode 100644 plans/python-pypi-release-implementation.md create mode 100644 python/eggpass-auth/Cargo.lock create mode 100644 python/eggpass-auth/Cargo.toml create mode 100644 python/eggpass-auth/LICENSE create mode 100644 python/eggpass-auth/README.md create mode 100644 python/eggpass-auth/pyproject.toml create mode 100644 python/eggpass-auth/src/eggpass_auth/__init__.py create mode 100644 python/eggpass-auth/src/eggpass_auth/__init__.pyi create mode 100644 python/eggpass-auth/src/eggpass_auth/py.typed create mode 100644 python/eggpass-auth/src/lib.rs create mode 100644 python/eggpass-auth/tests/test_async_api.py create mode 100644 python/eggpass-auth/tests/typecheck_api.py create mode 100644 python/eggpass-auth/tools/sync_core.py create mode 100644 python/eggpass-auth/vendor/eggpass-auth/Cargo.toml create mode 100644 python/eggpass-auth/vendor/eggpass-auth/LICENSE create mode 100644 python/eggpass-auth/vendor/eggpass-auth/README.md create mode 100644 python/eggpass-auth/vendor/eggpass-auth/examples/downstream.rs create mode 100644 python/eggpass-auth/vendor/eggpass-auth/src/authorization.rs create mode 100644 python/eggpass-auth/vendor/eggpass-auth/src/client.rs create mode 100644 python/eggpass-auth/vendor/eggpass-auth/src/error.rs create mode 100644 python/eggpass-auth/vendor/eggpass-auth/src/lib.rs create mode 100644 python/eggpass-auth/vendor/eggpass-auth/src/manager.rs create mode 100644 python/eggpass-auth/vendor/eggpass-auth/src/pkce.rs create mode 100644 python/eggpass-auth/vendor/eggpass-auth/src/provider.rs create mode 100644 python/eggpass-auth/vendor/eggpass-auth/src/token.rs create mode 100644 src/auth/bridge.rs delete mode 100644 src/auth/pkce.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 24c4c07..a725c76 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,13 +28,21 @@ jobs: run: cargo fmt --all -- --check - name: Run clippy - run: cargo clippy --all-targets -- -D warnings + run: cargo clippy --all-targets --locked -- -D warnings - name: Run the tests - run: cargo test --all-targets + run: cargo test --all-targets --locked + + - name: Package eggpass-auth + run: cargo package --locked --allow-dirty -p eggpass-auth + + - name: Package eggpass + run: >- + cargo package --locked --allow-dirty -p eggpass + --config 'patch.crates-io.eggpass-auth.path="crates/eggpass-auth"' - name: Build the release binary - run: cargo build --release + run: cargo build --release --locked windows-msvc: name: Windows MSVC tests and release build diff --git a/.github/workflows/publish-crates.yml b/.github/workflows/publish-crates.yml index acc9b7b..166aa78 100644 --- a/.github/workflows/publish-crates.yml +++ b/.github/workflows/publish-crates.yml @@ -23,6 +23,10 @@ permissions: jobs: publish: + if: >- + github.event_name == 'workflow_dispatch' || + (github.event_name == 'release' && + startsWith(github.event.release.tag_name, 'v')) name: publish runs-on: ubuntu-latest steps: @@ -52,10 +56,10 @@ jobs: fi - name: Verify the package - run: cargo package --locked --allow-dirty + run: cargo package --locked --allow-dirty -p eggpass - name: Publish the crate - if: ${{ github.event_name == 'release' && !(inputs.dry_run == true) }} - run: cargo publish --locked + if: ${{ github.event_name == 'release' && startsWith(github.event.release.tag_name, 'v') && !(inputs.dry_run == true) }} + run: cargo publish --locked -p eggpass env: CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} diff --git a/.github/workflows/publish-eggpass-auth-pypi.yml b/.github/workflows/publish-eggpass-auth-pypi.yml new file mode 100644 index 0000000..2910e06 --- /dev/null +++ b/.github/workflows/publish-eggpass-auth-pypi.yml @@ -0,0 +1,326 @@ +name: Publish eggpass-auth to PyPI + +# Python releases use eggpass-auth-python-vX.Y.Z and are independent of the +# Rust auth crate (eggpass-auth-vX.Y.Z) and the Eggpass CLI (vX.Y.Z). +on: + release: + types: [published] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pypi-${{ github.event.release.tag_name || github.ref }} + cancel-in-progress: false + +jobs: + verify-source: + name: Verify Python release tag and version + if: >- + github.event_name == 'workflow_dispatch' || + (github.event_name == 'release' && + github.event.action == 'published' && + startsWith(github.event.release.tag_name, 'eggpass-auth-python-v')) + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.version.outputs.value }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.release.tag_name || github.ref }} + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Verify package versions and release tag + id: version + env: + EVENT_NAME: ${{ github.event_name }} + RELEASE_TAG: ${{ github.event.release.tag_name || '' }} + working-directory: python/eggpass-auth + run: | + python - <<'PY' + import os + import re + import tomllib + from pathlib import Path + + with Path("pyproject.toml").open("rb") as manifest: + python_version = tomllib.load(manifest)["project"]["version"] + with Path("Cargo.toml").open("rb") as manifest: + rust_version = tomllib.load(manifest)["package"]["version"] + + if python_version != rust_version: + raise SystemExit( + f"pyproject.toml version {python_version} does not match " + f"Cargo.toml {rust_version}" + ) + + if os.environ["EVENT_NAME"] == "release": + tag = os.environ["RELEASE_TAG"] + tag_pattern = r"eggpass-auth-python-v\d+\.\d+\.\d+" + if not re.fullmatch(tag_pattern, tag): + raise SystemExit(f"invalid Python release tag: {tag}") + if tag != f"eggpass-auth-python-v{python_version}": + raise SystemExit( + f"tag {tag} does not match package version " + f"{python_version}" + ) + + output_path = Path(os.environ["GITHUB_OUTPUT"]) + with output_path.open("a", encoding="utf-8") as output: + output.write(f"value={python_version}\n") + print(f"Verified eggpass-auth Python version {python_version}") + PY + + build-wheels: + name: Build ${{ matrix.platform.name }} wheel + needs: verify-source + runs-on: ${{ matrix.platform.runner }} + strategy: + fail-fast: false + matrix: + platform: + - name: linux-x86_64 + runner: ubuntu-24.04 + manylinux: "2014" + interpreter: python3.11 + - name: linux-aarch64 + runner: ubuntu-24.04-arm + manylinux: "2014" + interpreter: python3.11 + - name: macos-x86_64 + runner: macos-15-intel + manylinux: "off" + interpreter: python + - name: macos-arm64 + runner: macos-15 + manylinux: "off" + interpreter: python + - name: windows-x86_64 + runner: windows-2025 + manylinux: "off" + interpreter: python + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.release.tag_name || github.ref }} + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Check the vendored Rust source snapshot + run: python tools/sync_core.py --check + working-directory: python/eggpass-auth + + - name: Build stable-ABI wheel + uses: PyO3/maturin-action@v1 + with: + maturin-version: v1.16.0 + manylinux: ${{ matrix.platform.manylinux }} + args: >- + --release --locked --interpreter ${{ matrix.platform.interpreter }} + --out dist + working-directory: python/eggpass-auth + + - uses: actions/upload-artifact@v4 + with: + name: python-dist-${{ matrix.platform.name }} + path: python/eggpass-auth/dist/*.whl + if-no-files-found: error + retention-days: 14 + + build-sdist: + name: Build source distribution + needs: verify-source + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.release.tag_name || github.ref }} + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal --no-self-update + rustup default stable + + - name: Install Maturin + run: python -m pip install "maturin==1.16.0" + + - name: Check the vendored Rust source snapshot + run: python tools/sync_core.py --check + working-directory: python/eggpass-auth + + - name: Build source distribution + run: maturin sdist --out dist + working-directory: python/eggpass-auth + + - uses: actions/upload-artifact@v4 + with: + name: python-dist-sdist + path: python/eggpass-auth/dist/*.tar.gz + if-no-files-found: error + retention-days: 14 + + validate-artifacts: + name: Validate release distributions + needs: [verify-source, build-wheels, build-sdist] + runs-on: ubuntu-24.04 + steps: + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - uses: actions/download-artifact@v4 + with: + pattern: python-dist-* + path: dist + merge-multiple: true + + - name: Install distribution checker + run: python -m pip install twine packaging + + - name: Validate metadata and target coverage + env: + PACKAGE_VERSION: ${{ needs.verify-source.outputs.version }} + run: | + python -m twine check dist/* + python - <<'PY' + import os + import tarfile + from pathlib import Path + from packaging.utils import ( + canonicalize_name, + parse_sdist_filename, + parse_wheel_filename, + ) + + version = os.environ["PACKAGE_VERSION"] + files = sorted(Path("dist").iterdir()) + wheels = [path for path in files if path.suffix == ".whl"] + sdists = [path for path in files if path.name.endswith(".tar.gz")] + if len(wheels) != 5 or len(sdists) != 1 or len(files) != 6: + names = [path.name for path in files] + raise SystemExit( + f"expected five wheels and one sdist; found {names}" + ) + + wheel_platforms = [] + for wheel in wheels: + _name, wheel_version, _build, tags = parse_wheel_filename( + wheel.name + ) + if canonicalize_name(_name) != canonicalize_name("eggpass-auth"): + raise SystemExit(f"unexpected distribution in {wheel.name}") + if str(wheel_version) != version: + raise SystemExit(f"unexpected wheel version in {wheel.name}") + abi3 = any( + tag.interpreter == "cp311" and tag.abi == "abi3" + for tag in tags + ) + if not abi3: + raise SystemExit( + f"wheel is not tagged cp311-abi3: {wheel.name}" + ) + wheel_platforms.append({tag.platform for tag in tags}) + + def has_platform(platforms, prefix, suffix): + return any( + platform.startswith(prefix) and platform.endswith(suffix) + for platform in platforms + ) + + expected = { + "Linux x86_64": ("manylinux", "_x86_64"), + "Linux aarch64": ("manylinux", "_aarch64"), + "macOS x86_64": ("macosx_", "_x86_64"), + "macOS arm64": ("macosx_", "_arm64"), + "Windows x86_64": ("win_amd64", ""), + } + unmatched = list(wheel_platforms) + for label, (prefix, suffix) in expected.items(): + if label == "Windows x86_64": + matches = lambda platforms: prefix in platforms + else: + matches = lambda platforms: has_platform( + platforms, prefix, suffix + ) + index = next( + ( + i + for i, platforms in enumerate(unmatched) + if matches(platforms) + ), + None, + ) + if index is None: + raise SystemExit( + f"missing {label} wheel; wheel tags were " + f"{wheel_platforms}" + ) + unmatched.pop(index) + + sdist = sdists[0] + distribution, sdist_version = parse_sdist_filename(sdist.name) + expected_name = canonicalize_name("eggpass-auth") + if canonicalize_name(distribution) != expected_name: + raise SystemExit(f"unexpected distribution in {sdist.name}") + if str(sdist_version) != version: + raise SystemExit(f"unexpected sdist version in {sdist.name}") + with tarfile.open(sdist) as archive: + members = archive.getnames() + required = ( + "/README.md", + "/LICENSE", + "/Cargo.toml", + "/Cargo.lock", + "/src/lib.rs", + "/vendor/eggpass-auth/Cargo.toml", + "/vendor/eggpass-auth/src/lib.rs", + ) + missing = [ + suffix + for suffix in required + if not any(name.endswith(suffix) for name in members) + ] + if missing: + raise SystemExit(f"sdist is missing required files: {missing}") + print(f"Validated {len(wheels)} wheels and {sdist.name}") + PY + + - uses: actions/upload-artifact@v4 + with: + name: verified-distributions + path: dist/* + if-no-files-found: error + retention-days: 14 + + publish: + name: Publish verified files to PyPI + needs: validate-artifacts + if: >- + github.event_name == 'release' && + github.event.action == 'published' && + startsWith(github.event.release.tag_name, 'eggpass-auth-python-v') + runs-on: ubuntu-24.04 + environment: + name: pypi + permissions: + id-token: write + steps: + - uses: actions/download-artifact@v4 + with: + name: verified-distributions + path: dist + + - name: Publish with PyPI Trusted Publishing + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: dist diff --git a/.github/workflows/publish-eggpass-auth.yml b/.github/workflows/publish-eggpass-auth.yml new file mode 100644 index 0000000..c027fdd --- /dev/null +++ b/.github/workflows/publish-eggpass-auth.yml @@ -0,0 +1,66 @@ +name: Publish eggpass-auth to crates.io + +# Auth crate versions and releases are independent of the Eggpass binary. +# Publishing only follows a human-published eggpass-auth-vX.Y.Z release. + +on: + release: + types: [published] + workflow_dispatch: + inputs: + dry_run: + description: "Verify the package without publishing it" + required: false + type: boolean + default: true + +permissions: + contents: read + +jobs: + publish: + if: >- + (github.event_name == 'release' && + startsWith(github.event.release.tag_name, 'eggpass-auth-v')) || + (github.event_name == 'workflow_dispatch' && + startsWith(github.ref, 'refs/tags/eggpass-auth-v')) + name: publish + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + # Build the exact source associated with a published auth release. + ref: ${{ github.event.release.tag_name || github.ref }} + + - name: Install the toolchain + run: | + rustup toolchain install stable --profile minimal --no-self-update + rustup default stable + + - uses: Swatinem/rust-cache@v2 + + - name: Check the version matches the release tag + env: + TAG: ${{ github.event.release.tag_name || github.ref_name }} + shell: bash + run: | + set -euo pipefail + if [[ ! "$TAG" =~ ^eggpass-auth-v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "::error::Expected an eggpass-auth-vX.Y.Z tag, got $TAG" + exit 1 + fi + version="$(sed -n 's/^version = \"\(.*\)\"$/\1/p' crates/eggpass-auth/Cargo.toml | head -1)" + tag_version="${TAG#eggpass-auth-v}" + if [[ "$version" != "$tag_version" ]]; then + echo "::error::crates/eggpass-auth/Cargo.toml says $version but the release tag says $tag_version" + exit 1 + fi + + - name: Verify the package + run: cargo package --locked -p eggpass-auth + + - name: Publish the crate + if: ${{ github.event_name == 'release' && startsWith(github.event.release.tag_name, 'eggpass-auth-v') && !(inputs.dry_run == true) }} + run: cargo publish --locked -p eggpass-auth + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} diff --git a/.github/workflows/python-auth.yml b/.github/workflows/python-auth.yml new file mode 100644 index 0000000..8a5f037 --- /dev/null +++ b/.github/workflows/python-auth.yml @@ -0,0 +1,263 @@ +name: Python eggpass-auth + +on: + push: + branches: [main] + paths: + - "python/eggpass-auth/**" + - "crates/eggpass-auth/**" + - ".github/workflows/python-auth.yml" + - ".github/workflows/publish-eggpass-auth-pypi.yml" + pull_request: + branches: [main] + paths: + - "python/eggpass-auth/**" + - "crates/eggpass-auth/**" + - ".github/workflows/python-auth.yml" + - ".github/workflows/publish-eggpass-auth-pypi.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: python-auth-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + CARGO_TERM_COLOR: always + +jobs: + rust-and-local-tests: + name: Rust checks and local Python tests + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: python/eggpass-auth + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal --no-self-update + rustup default stable + + - name: Install Python build and test tools + run: python -m pip install "maturin==1.16.0" pytest mypy + + - name: Check the vendored Rust source snapshot + run: python tools/sync_core.py --check + + - name: Check Rust formatting, lint, and tests + run: | + cargo fmt --all -- --check + cargo clippy --workspace --all-targets --locked -- -D warnings + cargo test --workspace --all-targets --locked + + - name: Build and install the local extension + run: maturin develop --release --locked + + - name: Check stubs and run local-stub tests + run: | + mypy --strict tests/typecheck_api.py + pytest -q + + build-wheels: + name: Build ${{ matrix.platform.name }} wheel + runs-on: ${{ matrix.platform.runner }} + strategy: + fail-fast: false + matrix: + platform: + - name: linux-x86_64 + runner: ubuntu-24.04 + manylinux: "2014" + interpreter: python3.11 + - name: linux-aarch64 + runner: ubuntu-24.04-arm + manylinux: "2014" + interpreter: python3.11 + - name: macos-x86_64 + runner: macos-15-intel + manylinux: "off" + interpreter: python + - name: macos-arm64 + runner: macos-15 + manylinux: "off" + interpreter: python + - name: windows-x86_64 + runner: windows-2025 + manylinux: "off" + interpreter: python + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Check the vendored Rust source snapshot + run: python tools/sync_core.py --check + working-directory: python/eggpass-auth + + - name: Build stable-ABI wheel + uses: PyO3/maturin-action@v1 + with: + maturin-version: v1.16.0 + manylinux: ${{ matrix.platform.manylinux }} + args: >- + --release --locked --interpreter ${{ matrix.platform.interpreter }} + --out dist + working-directory: python/eggpass-auth + + - uses: actions/upload-artifact@v4 + with: + name: wheel-${{ matrix.platform.name }} + path: python/eggpass-auth/dist/*.whl + if-no-files-found: error + retention-days: 14 + + test-wheels: + name: Test ${{ matrix.platform.name }} on Python ${{ matrix.python }} + needs: build-wheels + runs-on: ${{ matrix.platform.runner }} + strategy: + fail-fast: false + matrix: + platform: + - name: linux-x86_64 + runner: ubuntu-24.04 + - name: linux-aarch64 + runner: ubuntu-24.04-arm + - name: macos-x86_64 + runner: macos-15-intel + - name: macos-arm64 + runner: macos-15 + - name: windows-x86_64 + runner: windows-2025 + python: ["3.11", "3.12", "3.13", "3.14", "3.15"] + defaults: + run: + working-directory: python/eggpass-auth + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + + - uses: actions/download-artifact@v4 + with: + name: wheel-${{ matrix.platform.name }} + path: python/eggpass-auth/dist + + - name: Install wheel and test the installed package + shell: bash + run: | + python -m pip install --upgrade pip pytest mypy + python -m pip install --no-deps dist/*.whl + python -m pip check + python -c "import eggpass_auth; print(eggpass_auth.__all__)" + mypy --strict tests/typecheck_api.py + pytest -q + + build-sdist: + name: Build and inspect source distribution + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: python/eggpass-auth + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal --no-self-update + rustup default stable + + - name: Install Maturin and metadata checker + run: python -m pip install "maturin==1.16.0" twine + + - name: Check the vendored Rust source snapshot + run: python tools/sync_core.py --check + + - name: Build and validate source distribution metadata + run: | + maturin sdist --out dist + python -m twine check dist/*.tar.gz + python - <<'PY' + from pathlib import Path + import tarfile + + archives = list(Path("dist").glob("*.tar.gz")) + assert len(archives) == 1, f"expected one sdist, found {archives}" + with tarfile.open(archives[0]) as archive: + members = archive.getnames() + required = ( + "/README.md", + "/LICENSE", + "/Cargo.toml", + "/Cargo.lock", + "/src/lib.rs", + "/vendor/eggpass-auth/Cargo.toml", + "/vendor/eggpass-auth/src/lib.rs", + ) + missing = [ + suffix + for suffix in required + if not any(name.endswith(suffix) for name in members) + ] + assert not missing, f"sdist is missing required files: {missing}" + PY + + - uses: actions/upload-artifact@v4 + with: + name: python-sdist + path: python/eggpass-auth/dist/*.tar.gz + if-no-files-found: error + retention-days: 14 + + test-sdist: + name: Build and test sdist on Python ${{ matrix.python }} + needs: build-sdist + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + python: ["3.11", "3.12", "3.13", "3.14", "3.15"] + defaults: + run: + working-directory: python/eggpass-auth + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal --no-self-update + rustup default stable + + - uses: actions/download-artifact@v4 + with: + name: python-sdist + path: python/eggpass-auth/dist + + - name: Install source distribution and run package checks + run: | + python -m pip install --upgrade pip pytest mypy + python -m pip install --no-deps dist/*.tar.gz + python -m pip check + python -c "import eggpass_auth; print(eggpass_auth.__all__)" + mypy --strict tests/typecheck_api.py + pytest -q diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 13619a4..4be3dc0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,17 +16,40 @@ jobs: runs-on: "ubuntu-latest" permissions: contents: read + outputs: + source_sha: ${{ steps.resolve_tag.outputs.source_sha }} timeout-minutes: 90 steps: + - name: Resolve and validate immutable release source + id: resolve_tag + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ \"${#tag}\" -gt 255 ] || [ -z \"$tag\" ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\naskpass=\"$RUNNER_TEMP/eggpack-tag-askpass\"\nverify_repo=\"$RUNNER_TEMP/eggpack-tag-verify.git\"\ntrap 'rm -f -- \"$askpass\"' EXIT\ncat >\"$askpass\" <<'ASKPASS'\n#!/bin/sh\ncase \"$1\" in\n *Username*) printf '%s\\n' x-access-token ;;\n *Password*) printf '%s\\n' \"$EGGPACK_GIT_TOKEN\" ;;\n *) exit 1 ;;\nesac\nASKPASS\nchmod 700 \"$askpass\"\nremote=\"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git\"\nrefs=\"$(GIT_ASKPASS=\"$askpass\" GIT_TERMINAL_PROMPT=0 EGGPACK_GIT_TOKEN=\"$GITHUB_TOKEN\" git ls-remote --exit-code \"$remote\" \"$ref\" \"$ref^{}\")\"\ndirect=\npeeled=\nwhile IFS=\"$(printf '\\t')\" read -r oid name; do\n case \"$name\" in\n \"$ref\") [ -z \"$direct\" ] || { echo 'duplicate tag ref result' >&2; exit 1; }; direct=\"$oid\" ;;\n \"$ref^{}\") [ -z \"$peeled\" ] || { echo 'duplicate peeled ref result' >&2; exit 1; }; peeled=\"$oid\" ;;\n *) echo 'unexpected tag resolution result' >&2; exit 1 ;;\n esac\ndone <<< \"$refs\"\nsource_sha=\"${peeled:-$direct}\"\nif [[ ! \"$source_sha\" =~ ^[0-9a-f]{40}$ ]]; then\n echo 'tag did not resolve to one full object OID' >&2\n exit 1\nfi\ngit init --bare \"$verify_repo\" >/dev/null\nGIT_ASKPASS=\"$askpass\" GIT_TERMINAL_PROMPT=0 EGGPACK_GIT_TOKEN=\"$GITHUB_TOKEN\" git --git-dir=\"$verify_repo\" fetch --no-tags --depth=1 \"$remote\" \"$ref\" >/dev/null\nfetched_commit=\"$(git --git-dir=\"$verify_repo\" rev-parse --verify 'FETCH_HEAD^{commit}')\"\nif [ \"$fetched_commit\" != \"$source_sha\" ]; then\n echo 'tag did not resolve to the advertised commit object' >&2\n exit 1\nfi\nprintf 'source_sha=%s\\n' \"$source_sha\" >> \"$GITHUB_OUTPUT\"\n" - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ steps.resolve_tag.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ steps.resolve_tag.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ steps.resolve_tag.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Check Cargo availability shell: bash run: cargo --version resolve: needs: preflight + outputs: + source_sha: ${{ needs.preflight.outputs.source_sha }} runs-on: "ubuntu-latest" permissions: contents: read @@ -35,24 +58,35 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" - - name: Validate exact-tag source + ref: "${{ needs.preflight.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.preflight.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification shell: bash - run: "test -n \"${{ inputs.release_tag }}\"" + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.preflight.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Install pinned Eggpack tool shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Create runtime identity directory shell: bash run: "mkdir -p './eggpack-runtime'" - name: Resolve runtime release identity shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" run: | head_sha="$(git rev-parse --verify HEAD^{commit})" - 'eggpack' 'ci' '_resolve-release' '--contract' 'release/eggpack/distribution.toml' '--pack-config' 'release/eggpack/pack.toml' '--build-bindings' 'release/eggpack/build-bindings.toml' '--qualification-bindings' 'release/eggpack/qualification-bindings.toml' '--consumer-validators' 'release/eggpack/consumer-validators.json' '--selected' 'linux-x64,linux-arm64,macos-x64,macos-arm64,windows-x64' '--tag' '${{ inputs.release_tag }}' '--source-revision' "$head_sha" '--template' 'release/eggpack/github-template.json' '--source-root' '${{ github.workspace }}' '--output-plan' './eggpack-runtime/release-plan.json' '--output-ci-plan' './eggpack-runtime/release-ci-plan.json' '--output-github-policy' './eggpack-runtime/github-draft.json' + 'eggpack' 'ci' '_resolve-release' '--contract' 'release/eggpack/distribution.toml' '--pack-config' 'release/eggpack/pack.toml' '--build-bindings' 'release/eggpack/build-bindings.toml' '--qualification-bindings' 'release/eggpack/qualification-bindings.toml' '--consumer-validators' 'release/eggpack/consumer-validators.json' '--selected' 'linux-x64,linux-arm64,macos-x64,macos-arm64,windows-x64' '--tag' "$EGGPACK_RELEASE_TAG" '--source-revision' "$head_sha" '--template' 'release/eggpack/github-template.json' '--source-root' '${{ github.workspace }}' '--output-plan' './eggpack-runtime/release-plan.json' '--output-ci-plan' './eggpack-runtime/release-ci-plan.json' '--output-github-policy' './eggpack-runtime/github-draft.json' - name: Upload runtime release identity uses: "actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02" with: @@ -71,7 +105,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -90,7 +136,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -121,7 +167,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -140,7 +198,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -171,7 +229,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -190,7 +260,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -221,7 +291,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -240,7 +322,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -271,7 +353,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -290,7 +384,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -311,7 +405,7 @@ jobs: if-no-files-found: error retention-days: 7 qualify_build_aarch64_apple_darwin: - needs: build_aarch64_apple_darwin + needs: [ build_aarch64_apple_darwin, resolve ] runs-on: "macos-15" permissions: contents: read @@ -321,7 +415,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -332,7 +438,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -353,7 +459,7 @@ jobs: if-no-files-found: error retention-days: 7 qualify_build_aarch64_unknown_linux_gnu: - needs: build_aarch64_unknown_linux_gnu + needs: [ build_aarch64_unknown_linux_gnu, resolve ] runs-on: "ubuntu-24.04-arm" permissions: contents: read @@ -363,7 +469,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -374,7 +492,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -395,7 +513,7 @@ jobs: if-no-files-found: error retention-days: 7 qualify_build_x86_64_apple_darwin: - needs: build_x86_64_apple_darwin + needs: [ build_x86_64_apple_darwin, resolve ] runs-on: "macos-15-intel" permissions: contents: read @@ -405,7 +523,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -416,7 +546,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -437,7 +567,7 @@ jobs: if-no-files-found: error retention-days: 7 qualify_build_x86_64_pc_windows_msvc: - needs: build_x86_64_pc_windows_msvc + needs: [ build_x86_64_pc_windows_msvc, resolve ] runs-on: "windows-latest" permissions: contents: read @@ -447,7 +577,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -458,7 +600,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -479,7 +621,7 @@ jobs: if-no-files-found: error retention-days: 7 qualify_build_x86_64_unknown_linux_gnu: - needs: build_x86_64_unknown_linux_gnu + needs: [ build_x86_64_unknown_linux_gnu, resolve ] runs-on: "ubuntu-latest" permissions: contents: read @@ -489,7 +631,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -500,7 +654,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -521,7 +675,7 @@ jobs: if-no-files-found: error retention-days: 7 validate_build_aarch64_apple_darwin: - needs: qualify_build_aarch64_apple_darwin + needs: [ qualify_build_aarch64_apple_darwin, resolve ] runs-on: "macos-15" permissions: contents: read @@ -531,7 +685,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -542,7 +708,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -566,7 +732,7 @@ jobs: if-no-files-found: error retention-days: 7 validate_build_aarch64_unknown_linux_gnu: - needs: qualify_build_aarch64_unknown_linux_gnu + needs: [ qualify_build_aarch64_unknown_linux_gnu, resolve ] runs-on: "ubuntu-24.04-arm" permissions: contents: read @@ -576,7 +742,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -587,7 +765,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -611,7 +789,7 @@ jobs: if-no-files-found: error retention-days: 7 validate_build_x86_64_apple_darwin: - needs: qualify_build_x86_64_apple_darwin + needs: [ qualify_build_x86_64_apple_darwin, resolve ] runs-on: "macos-15-intel" permissions: contents: read @@ -621,7 +799,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -632,7 +822,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -656,7 +846,7 @@ jobs: if-no-files-found: error retention-days: 7 validate_build_x86_64_pc_windows_msvc: - needs: qualify_build_x86_64_pc_windows_msvc + needs: [ qualify_build_x86_64_pc_windows_msvc, resolve ] runs-on: "windows-latest" permissions: contents: read @@ -666,7 +856,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -677,7 +879,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -701,7 +903,7 @@ jobs: if-no-files-found: error retention-days: 7 validate_build_x86_64_unknown_linux_gnu: - needs: qualify_build_x86_64_unknown_linux_gnu + needs: [ qualify_build_x86_64_unknown_linux_gnu, resolve ] runs-on: "ubuntu-latest" permissions: contents: read @@ -711,7 +913,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -722,7 +936,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -746,7 +960,7 @@ jobs: if-no-files-found: error retention-days: 7 required_gate: - needs: [validate_build_aarch64_apple_darwin, validate_build_aarch64_unknown_linux_gnu, validate_build_x86_64_apple_darwin, validate_build_x86_64_pc_windows_msvc, validate_build_x86_64_unknown_linux_gnu] + needs: [ validate_build_aarch64_apple_darwin, validate_build_aarch64_unknown_linux_gnu, validate_build_x86_64_apple_darwin, validate_build_x86_64_pc_windows_msvc, validate_build_x86_64_unknown_linux_gnu, resolve ] runs-on: "ubuntu-latest" permissions: contents: read @@ -755,7 +969,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -766,7 +992,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -828,7 +1054,7 @@ jobs: shell: bash run: "'eggpack' 'ci' '_evaluate-gate' '--ci-plan' 'eggpack-runtime/release-ci-plan.json' '--inputs-dir' './eggpack-inputs' '--output' './eggpack-gate/gate-outcome.json'" aggregate: - needs: required_gate + needs: [ required_gate, resolve ] runs-on: "ubuntu-latest" permissions: contents: read @@ -837,7 +1063,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -848,7 +1086,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -917,31 +1155,48 @@ jobs: if-no-files-found: error retention-days: 7 stage: - needs: aggregate + needs: [ aggregate, resolve ] if: github.event_name == 'workflow_dispatch' runs-on: "ubuntu-latest" permissions: contents: write timeout-minutes: 90 steps: + - name: Resolve and validate immutable release source + id: confirm_tag_source + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ \"${#tag}\" -gt 255 ] || [ -z \"$tag\" ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\naskpass=\"$RUNNER_TEMP/eggpack-tag-askpass\"\nverify_repo=\"$RUNNER_TEMP/eggpack-tag-verify.git\"\ntrap 'rm -f -- \"$askpass\"' EXIT\ncat >\"$askpass\" <<'ASKPASS'\n#!/bin/sh\ncase \"$1\" in\n *Username*) printf '%s\\n' x-access-token ;;\n *Password*) printf '%s\\n' \"$EGGPACK_GIT_TOKEN\" ;;\n *) exit 1 ;;\nesac\nASKPASS\nchmod 700 \"$askpass\"\nremote=\"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git\"\nrefs=\"$(GIT_ASKPASS=\"$askpass\" GIT_TERMINAL_PROMPT=0 EGGPACK_GIT_TOKEN=\"$GITHUB_TOKEN\" git ls-remote --exit-code \"$remote\" \"$ref\" \"$ref^{}\")\"\ndirect=\npeeled=\nwhile IFS=\"$(printf '\\t')\" read -r oid name; do\n case \"$name\" in\n \"$ref\") [ -z \"$direct\" ] || { echo 'duplicate tag ref result' >&2; exit 1; }; direct=\"$oid\" ;;\n \"$ref^{}\") [ -z \"$peeled\" ] || { echo 'duplicate peeled ref result' >&2; exit 1; }; peeled=\"$oid\" ;;\n *) echo 'unexpected tag resolution result' >&2; exit 1 ;;\n esac\ndone <<< \"$refs\"\nsource_sha=\"${peeled:-$direct}\"\nif [[ ! \"$source_sha\" =~ ^[0-9a-f]{40}$ ]]; then\n echo 'tag did not resolve to one full object OID' >&2\n exit 1\nfi\ngit init --bare \"$verify_repo\" >/dev/null\nGIT_ASKPASS=\"$askpass\" GIT_TERMINAL_PROMPT=0 EGGPACK_GIT_TOKEN=\"$GITHUB_TOKEN\" git --git-dir=\"$verify_repo\" fetch --no-tags --depth=1 \"$remote\" \"$ref\" >/dev/null\nfetched_commit=\"$(git --git-dir=\"$verify_repo\" rev-parse --verify 'FETCH_HEAD^{commit}')\"\nif [ \"$fetched_commit\" != \"$source_sha\" ]; then\n echo 'tag did not resolve to the advertised commit object' >&2\n exit 1\nfi\nif [ \"$source_sha\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag moved after preflight resolution' >&2\n exit 1\nfi\n" - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ inputs.release_tag }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: name: "eggpack-runtime-identity" path: "./eggpack-runtime" if-no-files-found: error - - name: Validate exact-tag source - shell: bash - run: "test -n \"${{ inputs.release_tag }}\"" - name: Install pinned Eggpack tool shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash diff --git a/.gitignore b/.gitignore index 65306e1..6a1756a 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,9 @@ out/ # Dependencies node_modules/ vendor/ +!python/eggpass-auth/vendor/ +!python/eggpass-auth/vendor/eggpass-auth/ +!python/eggpass-auth/vendor/eggpass-auth/** __pycache__/ *.py[cod] .venv/ diff --git a/.minimax/skills/eggpass-eggpack-release/SKILL.md b/.minimax/skills/eggpass-eggpack-release/SKILL.md new file mode 100644 index 0000000..21c99bc --- /dev/null +++ b/.minimax/skills/eggpass-eggpack-release/SKILL.md @@ -0,0 +1,71 @@ +--- +name: eggpass-eggpack-release +description: | + Prepare, validate, and publish releases of `eggstack/eggpass` with the checked-in + Eggpack workflow. Trigger when asked to cut an Eggpass release, run Eggpack, + inspect its GitHub draft, or publish the release to GitHub/crates.io. Do not use + for ordinary code changes or another repository's release process. +--- + +# Eggpass Eggpack Release + +## Inputs to collect + +- The intended `X.Y.Z` release version and source branch/commit, if not clear from context. +- Whether the request is to prepare a draft or to publish it. Publishing is a separate, public action that also triggers crates.io publication. + +## Procedure + +1. Read `docs/releasing.md`, the release workflow, `Cargo.toml`, and the changelog. Check the working tree, current version, tag, and existing GitHub release. Releases are immutable: use a new version/tag; do not move or overwrite a published tag or release. For the v0.1.1 release lineage, preserve the v0.1.0 tag at `21e14c93d1b4292b410ce6c0707c064e63c98dc0`. +2. Confirm the release commit has the intended Cargo version (`X.Y.Z`, no `v`) and accurate release notes. Run the repository's CI/release checks before tagging, including formatting, all-target tests, Clippy with warnings denied, and package validation. Fix failures before continuing. +3. Push the release commit, then create and push the annotated tag `vX.Y.Z` pointing at that exact commit. Eggpack does not create or push tags; do not run it against an unpushed or ambiguous tag. +4. Dispatch the checked-in release workflow for the exact tag: + + ```sh + gh workflow run release.yml --repo eggstack/eggpass --field release_tag=vX.Y.Z + ``` + + Watch the resulting run to completion. The workflow should build and qualify all five targets, produce the manifest and checksum sidecars, and stage a **draft** GitHub release. A successful aggregate/gate alone is insufficient; inspect all matrix jobs and artifacts. +5. Inspect the draft's release notes and download every asset. Verify the manifest independently of CI: + - `schema_version` is `1`, `product_id` is `eggpass`, and `release_id` is plain `X.Y.Z` (no leading `v`). + - `source_revision` is the exact 40-character commit the tag peels to. + - The manifest names exactly the five expected target assets below; each recorded size and lowercase SHA-256 matches the downloaded binary. + - Each `.sha256` sidecar also validates against its corresponding binary. + - The release notes agree with the changelog and link to the actual downloads/checksums. + + Expected assets (the Windows executable keeps its `.exe` suffix): + - `eggpass-aarch64-apple-darwin` + - `eggpass-aarch64-unknown-linux-gnu` + - `eggpass-x86_64-apple-darwin` + - `eggpass-x86_64-pc-windows-msvc.exe` + - `eggpass-x86_64-unknown-linux-gnu` + + Do not treat CI's binary `--version` validation as proof that the manifest `release_id` is correct; `scripts/validate-release-version.py` validates the executable against Cargo metadata, not the manifest field. +6. If only the current draft's manifest is wrong and the binaries/sidecars are otherwise verified, correct that draft asset alone with `gh release upload vX.Y.Z --repo eggstack/eggpass --clobber`, then download it again and repeat the manifest/artifact checks. Do not edit the release generator or pipeline as an incidental part of a release; propose that as a separate code change if future runs need a permanent fix. Keep the release a draft until every check passes. +7. Immediately before making it public, obtain explicit user confirmation for this exact tag and its crates.io consequence. A broad initial request to “release” is not the final confirmation. After confirmation, publish the draft: + + ```sh + gh release edit vX.Y.Z --repo eggstack/eggpass --draft=false + ``` + + This public action fires `.github/workflows/publish-crates.yml`, which publishes the crate. Do not expose or print credentials; rely on the configured GitHub CLI session and repository secret. +8. Watch the release-triggered crates.io workflow through its publish step. Confirm the GitHub release is public and the exact `eggpass` version is present on crates.io. If available, run `eggpass update --check` as a final consumer-side check and report its result separately. + +## Output contract + +Report the source commit and tag; workflow run and matrix outcome; draft/public status; five-target manifest and checksum result; GitHub release URL; crates.io workflow and version result; and any checks skipped or still unverified. Never call a draft “published.” + +## Failure handling + +- Any failed workflow job, missing target, mismatched checksum/size/revision/version, or inaccurate release notes blocks publication. Leave the release as a draft and report the evidence. +- If an API request is rate-limited, inspect the relevant run/release state and rate limit before retrying; do not repeat an unchanged failing request in a tight loop. +- If the published version/tag already exists, stop rather than overwrite it. A correction must use the documented recovery path or a new release, never silently retarget history. +- Do not request, read, or paste registry tokens or other credentials into chat or logs. + +## Windows (win32) platform notes + +The Cargo and `gh` commands above also work in PowerShell. Use PowerShell paths and `Get-FileHash -Algorithm SHA256` to compute a local digest; compare its lowercase `Hash` value with the manifest and `.sha256` sidecar. Do not assume `shasum` or `sha256sum` exists. + +## Example + +For v0.1.1, keep the existing v0.1.0 tag unchanged, stage v0.1.1 as a draft, and verify `release_id` is `0.1.1` (not `v0.1.1`) before publication. The v0.1.1 draft's verified `source_revision` was `578a1eb7f3703cdf76861607d2c8a9bbc9807fe5`; the manifest was corrected and re-downloaded before the user authorized publication. diff --git a/CHANGELOG.md b/CHANGELOG.md index aebf49a..bc481d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,20 @@ Notable changes to eggpass are listed here. The format follows ## [Unreleased] -## [0.1.1] - 2026-11-16 +### Added + +- Add a cached `GET /v1/usage` endpoint and let `eggpass usage` reuse the + daemon's report through a separate usage-only runtime credential. +- Add the independently versioned async `eggpass-auth` Rust library and its + Python `asyncio` bindings. + +### Security + +- Restrict the usage-only runtime credential to a bodyless + `GET /v1/usage`; it cannot authorize inference or satisfy the regular client + key required to start the server. + +## [0.1.1] - 2026-11-17 ### Added diff --git a/Cargo.lock b/Cargo.lock index 6c56e75..92aedb7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -324,6 +324,37 @@ dependencies = [ "webpki-roots 0.26.11", ] +[[package]] +name = "eggfetch-core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c22bdfc6ab683ddf5d5fcf0321b60dfc86c0ec1311284a33c31f536d12c1d2ae" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "getrandom 0.2.17", + "http", + "http-body", + "http-body-util", + "httpdate", + "hyper", + "hyper-rustls", + "hyper-util", + "pem-rfc7468", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-native-certs", + "thiserror", + "tokio", + "tokio-rustls", + "tower-service", + "url", + "webpki-roots 0.26.11", +] + [[package]] name = "eggfetch-http-connect" version = "0.2.2" @@ -352,6 +383,7 @@ dependencies = [ "base64", "daemonize", "dirs", + "eggpass-auth", "eggup-acquisition", "eggup-core", "eggup-eggfetch", @@ -364,6 +396,7 @@ dependencies = [ "sha2 0.11.1", "signal-hook", "tempfile", + "tokio", "toml", "ureq", "url", @@ -371,6 +404,22 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "eggpass-auth" +version = "0.1.0" +dependencies = [ + "base64", + "eggfetch-core 0.3.0", + "rand", + "serde", + "serde_json", + "sha2 0.11.1", + "tempfile", + "tokio", + "tokio-util", + "url", +] + [[package]] name = "eggup-acquisition" version = "0.2.0" @@ -406,7 +455,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fc8f6480cd6717ed854ac764d0cfc18c6325b7367940149ea2f45f2d5658721" dependencies = [ - "eggfetch-core", + "eggfetch-core 0.2.2", "eggup-acquisition", "futures-util", "tokio", @@ -511,6 +560,23 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" version = "0.3.34" @@ -524,6 +590,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-macro", "futures-task", "pin-project-lite", "slab", @@ -1520,6 +1587,20 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "futures-util", + "pin-project-lite", + "tokio", +] + [[package]] name = "toml" version = "1.2.1+spec-1.1.0" diff --git a/Cargo.toml b/Cargo.toml index 6ea8b16..ad46f89 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,7 @@ +[workspace] +members = ["crates/eggpass-auth"] +resolver = "3" + [package] name = "eggpass" version = "0.1.1" @@ -9,7 +13,7 @@ readme = "README.md" repository = "https://github.com/eggstack/eggpass" documentation = "https://docs.rs/eggpass" keywords = ["grok", "chatgpt", "openai", "proxy", "oauth"] -categories = ["command-line-utilities", "api-bindings"] +categories = ["command-line-utilities"] # The published crate carries the source and the documentation, and nothing # else: no CI definitions, no live-verification script, no build output. @@ -28,6 +32,7 @@ include = [ ] [dependencies] +eggpass-auth = { version = "0.1.0", path = "crates/eggpass-auth" } base64 = "0.23.1" dirs = "7.0.0" # Self-update mechanics. Acquisition, transport, release-manifest projection, @@ -60,6 +65,7 @@ serde_json = "1.0.154" sha2 = "0.11.1" signal-hook = "0.4.6" toml = "1.2.1" +tokio = { version = "1.54.1", features = ["io-util", "macros", "net", "rt-multi-thread", "sync", "time"] } ureq = "3.5.2" # WHATWG parser for the device-flow URL check. Pinned to the copy already # in Cargo.lock; the check is the parser, so do not bump it in passing. diff --git a/README.md b/README.md index d5a72a4..ffbd43c 100644 --- a/README.md +++ b/README.md @@ -18,16 +18,18 @@ need a separate provider API key. ## Install +Install the published CLI from crates.io: + ```sh -cargo install eggpass --git https://github.com/eggstack/eggpass +cargo install eggpass ``` -Or install from a local checkout: +To build the current repository checkout instead: ```sh git clone https://github.com/eggstack/eggpass cd eggpass -cargo install --path . +cargo install --path . --locked --force ``` ## Quick start @@ -126,7 +128,7 @@ cleared when the daemon stops. | `eggpass usage` | Show remaining subscription usage where available. | | `eggpass run` | Start the server. Use `--foreground` to keep it in the terminal. | | `eggpass stop` / `restart` | Stop or restart the server. | -| `eggpass port` / `host` | Show or change the listen address. Changes restart the server. | +| `eggpass port` / `host` | Show or change the listen address. Changes restart a running server; when stopped, they take effect at the next start. | | `eggpass key` | Add, list, or revoke client keys. | | `eggpass edit` | Edit the config file. | | `eggpass croncheck` | Start the server if it is not running. | diff --git a/async-auth-library-requirements.md b/async-auth-library-requirements.md new file mode 100644 index 0000000..b723aec --- /dev/null +++ b/async-auth-library-requirements.md @@ -0,0 +1,57 @@ +# Requirements for a public async Eggpass auth library + +## Recommendation and boundary + +The deliverable should be a separate, small Rust library crate—provisionally `eggpass-auth`—rather than making the whole Eggpass application async. Eggpass currently has only a binary target: `src/main.rs` declares `mod auth`, and the OAuth types are not exported to downstream crates (`src/main.rs:8-21`). Its server deliberately uses blocking sockets, one thread per connection, and synchronous SSE writes (`src/server/http.rs:166-253, 748-772`). None of that needs to change for async downstream consumers to call reusable auth functions. + +The library should expose an async OAuth core that accepts or can be built around an `eggfetch_core::Client`, but should not create a Tokio runtime, print to the terminal, open a browser, or assume that credentials live in Eggpass’s home-directory files. Keep CLI conveniences and the current synchronous `TokenProvider` integration in Eggpass as host-side adapters. That preserves the existing proxy architecture while letting async consumers call the library inside their own runtime. + +At the time of this research, crates.io’s API returned “crate does not exist” for `eggpass-auth`; the name appears available but must be checked again before publishing. Eggfetch 0.3.0 is the current documented async API. Eggpass’s updater currently brings in Eggfetch 0.2.2 through `eggup-eggfetch` 0.2.0, which depends on the 0.2 line. A new direct 0.3 dependency will therefore coexist with 0.2.x until the updater adapter moves forward or the duplicate is accepted. + +## Public API requirements + +**Provider configuration must be auth-specific.** Do not export Eggpass’s full `ProviderSpec`: it mixes OAuth endpoints and scopes with inference URLs, request policies, headers, and catalogue formats (`src/provider/mod.rs:65-160`). Define a focused `OAuthProviderConfig` containing issuer/endpoints, client ID policy, scopes, callback path, and the provider-specific parameters the OAuth requests need. Include the current x.ai and OpenAI profiles, while allowing callers to construct a compatible profile without importing Eggpass server/config modules. Preserve OpenAI’s issued-client-ID behavior and registration-only parameters, and x.ai’s client ID, `referrer` fallback, and device-flow support (`src/provider/xai.rs:75-100`; `src/provider/openai.rs:149-198`). + +**Separate protocol from user interaction.** The core should offer async operations for authorization-code exchange, refresh, revocation, user-info, device-code creation, and polling. For browser authorization, provide a session/transaction API that returns the authorization URL and later accepts a validated callback; keep the verifier, state, and nonce inside an opaque pending-session value. An optional loopback helper can bind a random loopback port, but terminal prompts, browser launching, and stdin handling belong in an optional adapter or in the downstream application. For device authorization, return the verification URI and user code as data; let the caller decide how to present them, then poll asynchronously with cancellation support. + +**Make credentials caller-owned by default.** Provide token parsing and refresh operations independently of the current `~/.config/eggpass/auth.json` path and Grok CLI import. A downstream service may want to store credentials in its own database or secret store. A generic storage seam or an explicit-token API should enable that; Eggpass’s restrictive, atomic file store and `~/.grok/auth.json` import can remain optional adapters (`src/auth/store.rs:1-18, 130-195`). Document the concurrency guarantee: the current manager’s mutex coalesces refreshes within a process but is not a cross-process lock (`src/auth/refresh.rs:67-187`). Either make the store contract support cross-process coordination or state that boundary clearly. + +**Make Eggfetch ergonomic without hiding its ownership.** Accept a caller-supplied, cloneable `eggfetch_core::Client` so downstream code can reuse its connection pool and configuration. Offer a builder/default convenience only if it does not create a runtime or hide timeout policy. Keep Eggfetch response internals out of public return types; translate them to the library’s own status, OAuth, parsing, timeout, and network errors. The library’s async methods should simply be awaited in the caller’s runtime. Eggfetch’s [0.3.0 Client API](https://docs.rs/eggfetch-core/0.3.0/eggfetch_core/client/struct.Client.html) is async-first; its [Timeout API](https://docs.rs/eggfetch-core/0.3.0/eggfetch_core/timeout/struct.Timeout.html) supports separate pool/connect/write/read/total budgets. + +**Keep public types semver-manageable.** Use builders for provider/client configuration, avoid exposing internal module paths, mark extensible error enums non-exhaustive, document ownership and `Send`/`Sync` guarantees, and include compiling Tokio/Eggfetch examples. If the public constructor accepts the Eggfetch `Client` type, the library is coupled to that Eggfetch version line; downstream consumers must align to a compatible line to pass their client directly. Avoid a generic async transport trait in the first version unless transport substitution is a real requirement—it adds API and implementation complexity without helping the stated Eggfetch-first consumers. + +## Security and protocol acceptance criteria + +The library must retain the safeguards already present in the current auth code and make them part of its public contract: + +- Authorization-code flows use PKCE S256, high-entropy state, and nonce; callback state and the exact redirect path are validated. For native apps, [RFC 8252](https://www.rfc-editor.org/rfc/rfc8252.html) requires PKCE for public clients and recommends an external user-agent. Loopback listeners must bind only to loopback, use a short-lived random port, and close after completion. Do not introduce embedded-login pages. +- Device verification URIs are checked against the provider’s trusted-host policy before the library opens or presents them. Device-code values are not shown to users or placed in logs. +- Async cancellation, request deadlines, and response-size bounds are explicit. Preserve current OAuth timeouts intentionally rather than inheriting Eggfetch defaults accidentally. Do not blindly retry token exchanges or refreshes; document the retry policy, especially around refresh-token rotation. +- The manager preserves the current proactive refresh skew, 401 compare-and-refresh behavior, one-refresh-under-concurrency guarantee, atomic persistence, and rule that a missing rotated refresh token does not erase the existing one (`src/auth/refresh.rs:119-179, 190-225`). +- Public errors may expose status and OAuth error codes, but should not automatically include arbitrary response bodies. Token-bearing values need redacted `Debug` implementations and should never be logged by the library. + +Two concrete porting issues need resolution before declaring parity. First, `TokenSet`, `DeviceCode`, and `StoredAuth` currently derive `Debug` while containing access/refresh tokens or device codes (`src/auth/client.rs:51-67, 130-145`; `src/auth/store.rs:44-87`). A public crate should redact those fields (or use secret wrappers) before downstream users can accidentally log them. Second, the current device-flow loop increments the polling interval by **one** second after `slow_down` (`src/auth/flow.rs:277-279`), but [RFC 8628 §3.5](https://www.rfc-editor.org/rfc/rfc8628.html#section-3.5) requires increasing it by five seconds for that and subsequent polls. The loop also clamps `expires_in` to at least 60 seconds (`src/auth/flow.rs:259-264`); review that against the server-provided expiry rather than copying it unquestioned. Async cancellation and timeout retries should also follow RFC 8628’s polling guidance. + +## Package, dependency, tests, and release work + +A separate `eggpass-auth` workspace package is the cleaner boundary than adding a library target to the existing binary package. The current `Cargo.toml` has a broad CLI/server dependency list and an explicit root-package include list (`Cargo.toml:1-28, 30-77`). A dedicated package can keep its dependency surface focused on Eggfetch, serde/JSON, time/PKCE utilities, and optional storage/loopback adapters. Keep the existing MSRV at Rust 1.89 if using Eggfetch 0.3.0, which also declares Rust 1.89. + +The current `.github/workflows/publish-crates.yml` checks and publishes only the root `eggpass` package (`.github/workflows/publish-crates.yml:41-61`). A public auth crate therefore needs its own package verification and publish path, or a deliberate workspace-aware release workflow. Decide whether the auth crate is versioned independently or must ship in lockstep with the CLI; test the exact crate with `cargo package --locked` before publication. Do not assume the existing Eggpack release job or crates.io workflow will automatically publish a second package. + +Minimum acceptance tests should cover request form encoding and provider-specific parameters; success, OAuth error, non-JSON error, timeout, and oversized-body handling; PKCE/state/nonce and callback validation; device `authorization_pending`, `slow_down`, denial, expiry, and cancellation; OpenAI issued-client-ID reuse; refresh-token rotation; concurrent access-token refresh; and atomic credential persistence. Run tests against a local stub endpoint using the real Eggfetch client, then compile a small downstream-style consumer that supplies its Eggfetch client and awaits login/refresh without Eggpass CLI or server modules. Keep network-dependent live provider checks separate from deterministic CI. + +## Decisions to settle before implementation + +1. **MVP flow scope:** async OAuth/token operations only, or also complete browser loopback and device-login orchestration? Recommended: core transaction/polling APIs in the first release; UI and loopback conveniences as optional adapters. +2. **Storage contract:** caller-owned token storage only, or include a default file store? Recommended: caller-owned storage in core; optional Eggpass-compatible file adapter. +3. **Crate/release boundary:** separate `eggpass-auth` package with independent versioning, or couple its release to `eggpass`? Recommended: separate package and explicit publication workflow. +4. **Eggfetch alignment:** accept the current dual 0.2/0.3 dependency graph temporarily, or first update/release the Eggup adapter against Eggfetch 0.3.0? This affects dependency duplication, not the downstream API design. +5. **Provider extensibility:** only the built-in x.ai/OpenAI profiles, or a documented generic OAuth provider configuration as well? Recommended: support the two built-ins and a minimal custom OAuth profile, but keep provider-specific registration semantics explicit. + +## Sources + +- Eggpass source: `src/main.rs:8-21`; `src/auth/client.rs:51-67, 130-145, 162-220, 298-545`; `src/auth/flow.rs:127-289`; `src/auth/refresh.rs:67-225`; `src/auth/store.rs:1-18, 44-87, 130-195`; `src/provider/xai.rs:75-100`; `src/provider/openai.rs:149-198`; `src/server/http.rs:166-253, 748-772`; `.github/workflows/publish-crates.yml:41-61`. +- [RFC 8252 — OAuth 2.0 for Native Apps](https://www.rfc-editor.org/rfc/rfc8252.html). +- [RFC 8628 — OAuth 2.0 Device Authorization Grant](https://www.rfc-editor.org/rfc/rfc8628.html). +- [Eggfetch `eggfetch-core` 0.3.0](https://docs.rs/eggfetch-core/0.3.0/eggfetch_core/) and [Eggup Eggfetch adapter 0.2.0](https://docs.rs/eggup-eggfetch/0.2.0/eggup_eggfetch/). +- [crates.io `eggpass-auth` lookup](https://crates.io/api/v1/crates/eggpass-auth) (not found at research time; availability can change). diff --git a/async-auth-migration-cost.md b/async-auth-migration-cost.md new file mode 100644 index 0000000..5e247d5 --- /dev/null +++ b/async-auth-migration-cost.md @@ -0,0 +1,39 @@ +# Cost of an async Eggpass auth library + +## Recommendation + +For downstream Rust repositories that already run async code and use Eggfetch, the useful migration target is a **public async authentication library**, not an async rewrite of Eggpass’s proxy server. The auth module is currently private to the `eggpass` binary (`src/main.rs:8-21`), so changing ureq calls to Eggfetch alone would not make the code consumable downstream. A focused `eggpass-auth` library—async OAuth/token methods and, if required, login flows—addresses the stated goal while leaving the custom blocking server and its SSE path intact. + +My rough estimate for that full reusable auth surface, including keeping Eggpass’s current CLI and server operational, is **8–15 engineer-days (about 2–3 working weeks for one experienced Rust engineer)**. A narrower async OAuth client plus a small public API and consumer example, without porting the token manager or interactive login flows, is approximately **3–5 engineer-days**. A full Eggpass server conversion is a separate, substantially larger project; I would not undertake it for this downstream-reuse goal. These are code-review estimates, not measured implementation times; they assume provider behavior stays unchanged and carry roughly ±50% uncertainty until downstream API requirements are known. + +## Where the work is + +`OAuthClient` owns a ureq agent and synchronous exchange, device-code, refresh, revocation, and user-info calls (`src/auth/client.rs:167-220, 298-545`). Replacing those calls with Eggfetch is mechanically bounded: Eggfetch’s `Client` has async request methods, and request builders send with `.await`; response bodies can be collected or streamed asynchronously. The work is principally translating request construction, status/body/error mapping, user-agent and timeout policy, and the existing local-server tests—not reimplementing OAuth. + +The larger change is state and flow behavior. `TokenManager::access_token` and `force_refresh` are synchronous, use `std::sync::Mutex`, and deliberately re-check credentials after taking the lock to collapse concurrent refreshes (`src/auth/refresh.rs:67-187`). Its async version must preserve that single-refresh property across `await`, preserve refresh-token rotation, and save credentials atomically. The current store uses synchronous filesystem operations and restrictive permissions (`src/auth/store.rs:1-18, 130-195`); it can remain a small synchronous boundary initially, but should not be accidentally weakened during extraction. + +Login flows add another layer: device login polls with `std::thread::sleep`, while browser login uses a blocking loopback `TcpListener` and an optional stdin thread (`src/auth/flow.rs:127-289, 370-517`). A complete async login API needs to make polling cancellable and awaitable, and decide how to host the callback listener and terminal input. Separately, auth types depend on Eggpass’s combined provider description and credential paths, while the synchronous `TokenProvider` trait is declared in `src/upstream.rs:54-70` and consumed by request handling (`src/upstream.rs:207-229`). A downstream package should have a smaller OAuth-only provider configuration and storage boundary rather than importing server/config internals. + +Eggpass’s server is intentionally blocking: it uses a standard `TcpListener`, spawns one OS thread per connection, and writes and flushes SSE chunks synchronously (`src/server/http.rs:166-253, 748-772`). That creates an integration boundary, but not a reason to make the HTTP server async. Eggpass can keep a small host-owned compatibility adapter for the current CLI/server while downstream crates call the auth library’s async API directly. Keep runtime bridging at that host boundary; do not hide runtime construction inside a reusable library. Tokio’s own guidance discusses explicit sync/async bridging and using blocking work at appropriate boundaries ([Tokio bridging](https://tokio.rs/tokio/topics/bridging), [Tokio `spawn_blocking`](https://docs.rs/tokio/latest/tokio/task/fn.spawn_blocking.html)). + +## Effort by scope + +| Scope | Estimate | Included work | +|---|---:|---| +| Async OAuth transport only | 3–5 engineer-days | Convert `OAuthClient` endpoint calls to Eggfetch; preserve timeouts, user-agent, status/error semantics; update HTTP tests; add a minimal consumer example. This does not make the current private module reusable unless a public library surface is added. | +| Recommended reusable auth package | 8–15 engineer-days | Add a public crate/API; isolate OAuth provider configuration from inference/config types; async OAuth and token refresh; preserve refresh serialization and credential-store guarantees; port device and loopback login as required; add a synchronous host adapter for Eggpass; test a downstream-style Eggfetch consumer. | +| Entire Eggpass application async | Several additional weeks; separate estimate | Replace or adapt the custom server, upstream request path, connection management, and synchronous streaming writer. This is outside the stated purpose and would increase risk without improving downstream auth ergonomics proportionally. | + +The full package estimate assumes both browser and device login should remain supported. If downstream callers only need to exchange/refresh tokens after handling user interaction themselves, omitting the login-flow port should reduce the estimate by several days. Publishing a new crate also adds ongoing compatibility, documentation, and semver obligations beyond the initial implementation. + +## Eggfetch version and integration cost + +Eggfetch’s current published `eggfetch-core` is 0.3.0 (released 31 October 2026); its documentation describes it as async-first and demonstrates `.send().await` and async body reads ([0.3.0 docs](https://docs.rs/eggfetch-core/0.3.0/eggfetch_core/), [Client API](https://docs.rs/eggfetch-core/0.3.0/eggfetch_core/client/struct.Client.html)). Eggpass’s lockfile currently resolves `eggfetch-core` 0.2.2 through `eggup-eggfetch` 0.2.0, as confirmed by `cargo tree --locked --offline`. The published updater adapter remains at 0.2.0 and depends on `eggfetch-core ^0.2.0` ([adapter docs](https://docs.rs/eggup-eggfetch/0.2.0/eggup_eggfetch/); [crates.io version metadata](https://crates.io/api/v1/crates/eggup-eggfetch)). Therefore, adding a direct 0.3.x dependency for the new auth library will currently leave both 0.2.x and 0.3.x in Eggpass’s dependency graph. That is manageable, but has compile/binary-size and maintenance cost; it can be avoided later if the updater adapter is released against 0.3.x. Downstream consumers on 0.3.x should use the same major/minor line if the library accepts an Eggfetch `Client` from the caller. + +Eggfetch’s `Timeout` supports separate pool, connect, write, read, and total deadlines ([timeout API](https://docs.rs/eggfetch-core/0.3.0/eggfetch_core/timeout/struct.Timeout.html)). The port still needs to deliberately map Eggpass’s existing OAuth agent policy (60-second global and 180-second body receive timeouts in `src/auth/client.rs:189-194`); phase-aware defaults should not silently change login behavior. ureq is explicitly a blocking-I/O client ([ureq 3.5.2 docs](https://docs.rs/ureq/3.5.2/ureq/)). + +## Suggested implementation boundary + +Create a small library crate with an OAuth-specific provider config, `OAuthClient` constructed with or accepting a clone of `eggfetch_core::Client`, and async token/refresh methods. Keep provider policy and token parsing in the crate; make credential persistence configurable or portable. Port the device and browser flow only if downstream callers need Eggpass to own those interactions. In the binary, adapt its current synchronous token-provider contract at the boundary, so the proxy’s ureq inference path and SSE implementation need not move in the same change. + +Do not count this as a complete removal of ureq: it remains used by upstream inference, daemon health probes, and usage queries (`src/upstream.rs:91-204`, `src/daemon.rs:210-223`, `src/cli/commands/usage.rs:291-309`). Removing ureq from the dependency graph would require a broader, separately justified migration. diff --git a/crates/eggpass-auth/Cargo.toml b/crates/eggpass-auth/Cargo.toml new file mode 100644 index 0000000..f39d24f --- /dev/null +++ b/crates/eggpass-auth/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "eggpass-auth" +version = "0.1.0" +edition = "2024" +rust-version = "1.89" +description = "Async OAuth authentication flows for applications using Eggfetch" +license = "MIT" +readme = "README.md" +repository = "https://github.com/eggstack/eggpass" +documentation = "https://docs.rs/eggpass-auth" +keywords = ["oauth", "authentication", "async"] +categories = ["asynchronous", "authentication"] +include = ["/src", "/README.md", "/LICENSE", "/examples"] + +[dependencies] +base64 = "0.23.1" +eggfetch-core = { version = "0.3.0", default-features = false, features = ["http1", "logical-retry", "redirects", "tls-rustls", "tls-native-roots"] } +rand = "0.10.3" +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +sha2 = "0.11.1" +tokio = { version = "1.54.1", features = ["macros", "rt", "sync", "time"] } +tokio-util = { version = "0.7", features = ["rt"] } +url = "2.5.8" + +[dev-dependencies] +tempfile = "3.27.0" +tokio = { version = "1.54.1", features = ["io-util", "macros", "net", "rt-multi-thread", "test-util", "time"] } + +[package.metadata.docs.rs] +all-features = true diff --git a/crates/eggpass-auth/LICENSE b/crates/eggpass-auth/LICENSE new file mode 100644 index 0000000..329eea1 --- /dev/null +++ b/crates/eggpass-auth/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 David Bowman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/eggpass-auth/README.md b/crates/eggpass-auth/README.md new file mode 100644 index 0000000..295310c --- /dev/null +++ b/crates/eggpass-auth/README.md @@ -0,0 +1,63 @@ +# eggpass-auth + +Async OAuth authentication primitives for applications using Eggfetch. The crate is independently versioned from the Eggpass CLI and accepts an Eggfetch 0.3 `Client` owned by the caller. + +## Boundary + +The library does not create a Tokio runtime, launch a browser, print to a terminal, bind a callback listener, read stdin, or assume a credential file path. The host application owns the runtime, user interface, callback transport, and persistence. The async methods are awaited on the application's runtime. + +## Browser authorization + +```rust,no_run +use eggfetch_core::Client; +use eggpass_auth::{OAuthClient, OAuthProviderConfig}; + +# async fn example() -> Result<(), Box> { +let auth = OAuthClient::new(Client::new(), OAuthProviderConfig::xai()); +let pending = auth.begin_authorization("http://127.0.0.1:43123/callback", None)?; +let url_for_external_browser = pending.authorization_url(); +// Present the URL, receive the callback in the host application, then pass its +// full URL to complete_authorization. The crate does not create the listener. +let _ = url_for_external_browser; +# Ok(()) +# } +``` + +`begin_authorization` creates PKCE S256, state, nonce, and the authorization URL. `complete_authorization` consumes the opaque pending transaction and rejects callback origin/path mismatches, missing or mismatched state, and an ID-token nonce mismatch. The ID-token nonce claim is checked; this crate does not validate ID-token signatures. Use the provider's user-info endpoint or a separate OIDC verifier when signature/issuer/audience validation is required. + +## Device authorization + +`request_device_code().await` returns a `DeviceCode` containing a verification URI and user code. Before returning it, the library requires HTTPS and an exact provider-configured host match for both regular and pre-filled URIs. The caller presents these values. `poll_device_authorization(&device, &cancel, timeout).await` sleeps before the first poll, honors server expiry (including short lifetimes), applies the RFC 8628 five-second increment after each `slow_down`, and supports cancellation and a caller timeout. + +## Profiles + +- `OAuthProviderConfig::xai()` uses the public x.ai client ID, full scopes, `referrer=eggpass`, device authorization, and the exact x.ai verification-host allowlist. +- `OAuthProviderConfig::xai_compatibility_fallback()` returns the `grok-build` referrer and the reference client's shorter scope set for a new user authorization after a client-configuration refusal. Token exchange and refresh are never retried automatically. +- `OAuthProviderConfig::openai()` uses the `dynamic_agent_client` registration entrypoint, OpenAI resource parameters, and registration-only `agent_name_hint=eggpass`. OpenAI's issued ID is returned in `Credentials::client_id()` and should be persisted/reused. `openai_with_host_id(...)` adds a caller-owned stable `ext_agent_host_id`. +- `OAuthProviderConfig::custom(...)` starts a builder for custom endpoints and scopes. Endpoints require HTTPS, except localhost/loopback HTTP for local tests. Add verification hosts before using device flow. + +Custom parameters should contain OAuth protocol parameters, not secrets. Profile and pending-authorization `Debug` output redacts IDs, parameter values, URLs, verifier, state, and nonce. + +## Explicit token operations + +The low-level operations `exchange_authorization_code`, `refresh_token`, `revoke`, and `userinfo` are async and accept explicit caller-owned token values. `refresh_token` returns the provider's token set without retrying. When an issued refresh response omits a new refresh token, preserve the previous one when saving credentials. Prefer `refresh_credentials` or `TokenManager` for this merge behavior. + +## Storage and refresh manager + +Implement `CredentialStore` for the application's database or secret store. Its `save` operation should atomically replace a credential set. `TokenManager` performs proactive refresh with a five-minute default skew, compares the failed 401 token before refreshing, coalesces refreshes in one manager/process, and retains an old refresh token when rotation is omitted. It does not provide a cross-process lock. The crate has no built-in filesystem adapter. + +## HTTP safety defaults + +Each request explicitly sets finite Eggfetch phase and total timeouts (pool/connect/write 10–15 seconds, read 30 seconds, total 60 seconds by default) and caps decoded response bodies at 1 MiB. Tune them with `ClientOptions`. Requests disable redirects, automatic retries, and caller-configured default authentication; the user-info call sets its own bearer token. OAuth errors expose status and a sanitized error code, not arbitrary response bodies. Timeout and transport diagnostics are deliberately generic to avoid leaking request details. + +## Validation + +Run the downstream-style example and deterministic local OAuth stub tests with: + +```sh +cargo test -p eggpass-auth --locked +cargo check -p eggpass-auth --example downstream --locked +cargo package -p eggpass-auth --locked --allow-dirty +``` + +Provider-live requests are not part of deterministic CI. diff --git a/crates/eggpass-auth/examples/downstream.rs b/crates/eggpass-auth/examples/downstream.rs new file mode 100644 index 0000000..4063e5a --- /dev/null +++ b/crates/eggpass-auth/examples/downstream.rs @@ -0,0 +1,21 @@ +use std::error::Error; + +use eggfetch_core::Client; +use eggpass_auth::{OAuthClient, OAuthProviderConfig}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // The application owns this runtime and HTTP client. eggpass-auth creates + // neither and simply returns futures for the application to await. + let oauth = OAuthClient::new(Client::new(), OAuthProviderConfig::xai()); + let _pending = oauth.begin_authorization("http://127.0.0.1:43123/callback", None)?; + + // Optional opt-in demonstration of an async refresh using a caller-supplied + // token. The token itself is never printed. This example does not launch a + // browser or start a callback listener. + if let Ok(refresh_token) = std::env::var("EGGPASS_AUTH_REFRESH_TOKEN") { + let refreshed = oauth.refresh_token(&refresh_token, None).await?; + println!("Refresh succeeded; expiry: {:?}", refreshed.expires_at()); + } + Ok(()) +} diff --git a/crates/eggpass-auth/src/authorization.rs b/crates/eggpass-auth/src/authorization.rs new file mode 100644 index 0000000..1c9a4c2 --- /dev/null +++ b/crates/eggpass-auth/src/authorization.rs @@ -0,0 +1,390 @@ +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use rand::Rng; +use serde_json::Value; +use sha2::{Digest, Sha256}; + +use crate::client::{OAuthClient, PendingAuthorization, validate_redirect_uri}; +use crate::provider::ClientIdPolicy; +use crate::token::{Credentials, TokenSet}; +use crate::{Error, Result}; + +pub(crate) fn begin_authorization( + client: &OAuthClient, + redirect_uri: &str, + existing: Option<&Credentials>, +) -> Result { + let redirect = validate_redirect_uri(redirect_uri, &client.provider.callback_path)?; + if let Some(credentials) = existing + && !credentials.issuer().is_empty() + && credentials.issuer() != client.provider.issuer + { + return Err(Error::InvalidConfiguration( + "existing credentials belong to a different issuer", + )); + } + + let existing_client_id = existing + .map(Credentials::client_id) + .filter(|client_id| !client_id.is_empty()); + let registration = client.provider.client_id_policy == ClientIdPolicy::IssuedOnRegistration + && existing_client_id.is_none(); + let client_id = if client.provider.client_id_policy == ClientIdPolicy::IssuedOnRegistration { + existing_client_id + .unwrap_or(&client.provider.client_id) + .to_string() + } else { + client.provider.client_id.clone() + }; + let code_verifier = random_urlsafe(32); + let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(code_verifier.as_bytes())); + let state = random_urlsafe(32); + let nonce = random_urlsafe(32); + + let scope = client.provider.scopes.join(" "); + let mut authorization_url = url::Url::parse(&client.provider.authorization_endpoint) + .map_err(|_| Error::InvalidConfiguration("authorization endpoint URL is invalid"))?; + { + let mut query = authorization_url.query_pairs_mut(); + query.append_pair("response_type", "code"); + query.append_pair("client_id", &client_id); + query.append_pair("redirect_uri", redirect_uri); + query.append_pair("scope", &scope); + query.append_pair("code_challenge", &challenge); + query.append_pair("code_challenge_method", "S256"); + query.append_pair("state", &state); + query.append_pair("nonce", &nonce); + for (name, value) in &client.provider.authorization_parameters { + query.append_pair(name, value); + } + if registration { + for (name, value) in &client.provider.registration_parameters { + query.append_pair(name, value); + } + } + if !registration && let Some(id_token) = existing.and_then(Credentials::id_token) { + query.append_pair("id_token_hint", id_token); + } + } + + Ok(PendingAuthorization { + authorization_url: authorization_url.into(), + redirect_uri: redirect.to_string(), + code_verifier, + state, + nonce, + client_id, + registration, + }) +} + +pub(crate) async fn complete_authorization( + client: &OAuthClient, + pending: PendingAuthorization, + callback_url: &str, +) -> Result { + let callback = url::Url::parse(callback_url).map_err(|_| Error::CallbackMismatch)?; + let redirect = url::Url::parse(&pending.redirect_uri).map_err(|_| Error::CallbackMismatch)?; + if callback.path() != client.provider.callback_path + || !same_origin(&callback, &redirect) + || callback.path() != redirect.path() + || !callback.username().is_empty() + || callback.password().is_some() + || callback.fragment().is_some() + { + return Err(Error::CallbackMismatch); + } + + let state = unique_query_value(&callback, "state")?.ok_or(Error::StateMismatch)?; + if state != pending.state { + return Err(Error::StateMismatch); + } + if let Some(error) = unique_query_value(&callback, "error")? { + return Err(Error::ProviderDenied(sanitize_oauth_code(&error))); + } + let code = unique_query_value(&callback, "code")? + .ok_or(Error::InvalidResponse("authorization callback has no code"))?; + if code.is_empty() || code.chars().any(char::is_control) { + return Err(Error::InvalidResponse( + "authorization callback code is invalid", + )); + } + + let callback_client_id = unique_query_value(&callback, "client_id")?; + let client_id = match client.provider.client_id_policy { + ClientIdPolicy::Fixed => pending.client_id.clone(), + ClientIdPolicy::IssuedOnRegistration if pending.registration => callback_client_id + .filter(|issued| !issued.trim().is_empty()) + .ok_or(Error::InvalidResponse( + "provider callback has no issued client ID", + ))?, + ClientIdPolicy::IssuedOnRegistration => { + if callback_client_id + .as_ref() + .is_some_and(|issued| issued != &pending.client_id) + { + return Err(Error::CallbackMismatch); + } + pending.client_id.clone() + } + }; + let callback_scope = unique_query_value(&callback, "scope")?; + + complete_pending_authorization(client, pending, code, client_id, callback_scope).await +} + +pub(crate) async fn complete_authorization_with_code( + client: &OAuthClient, + pending: PendingAuthorization, + code: &str, +) -> Result { + if client.provider.client_id_policy == ClientIdPolicy::IssuedOnRegistration { + return Err(Error::Unsupported( + "pasted authorization codes for issued-client-ID providers", + )); + } + if code.is_empty() || code.chars().any(char::is_control) { + return Err(Error::InvalidResponse( + "pasted authorization code is invalid", + )); + } + let client_id = pending.client_id.clone(); + complete_pending_authorization(client, pending, code.to_string(), client_id, None).await +} + +async fn complete_pending_authorization( + client: &OAuthClient, + pending: PendingAuthorization, + code: String, + client_id: String, + callback_scope: Option, +) -> Result { + let mut parameters = vec![ + ("grant_type".to_string(), "authorization_code".to_string()), + ("code".to_string(), code), + ("redirect_uri".to_string(), pending.redirect_uri), + ("client_id".to_string(), client_id.clone()), + ("code_verifier".to_string(), pending.code_verifier), + ]; + parameters.extend(client.provider.token_parameters.clone()); + let value = client + .post_form_json(&client.provider.token_endpoint, ¶meters) + .await?; + let tokens = TokenSet::from_json(&value, Credentials::now_unix())?; + if client.provider.scopes.iter().any(|scope| scope == "openid") { + validate_nonce(tokens.id_token(), &pending.nonce)?; + } else if let Some(id_token) = tokens.id_token() { + validate_nonce(Some(id_token), &pending.nonce)?; + } + let mut credentials = Credentials::from_tokens( + tokens, + client_id, + client.provider.issuer.clone(), + Credentials::now_unix(), + ); + if credentials.scope.is_none() { + credentials.scope = callback_scope; + } + Ok(credentials) +} + +fn unique_query_value(url: &url::Url, name: &str) -> Result> { + let mut values = url.query_pairs().filter(|(key, _)| key == name); + let value = values.next().map(|(_, value)| value.into_owned()); + if values.next().is_some() { + return Err(Error::CallbackMismatch); + } + Ok(value) +} + +fn same_origin(left: &url::Url, right: &url::Url) -> bool { + left.scheme() == right.scheme() + && left.host_str().is_some_and(|host| { + right + .host_str() + .is_some_and(|other| host.eq_ignore_ascii_case(other)) + }) + && left.port_or_known_default() == right.port_or_known_default() +} + +fn validate_nonce(id_token: Option<&str>, expected_nonce: &str) -> Result<()> { + let Some(id_token) = id_token else { + return Err(Error::NonceMismatch); + }; + let Some(payload) = id_token.split('.').nth(1) else { + return Err(Error::NonceMismatch); + }; + let decoded = URL_SAFE_NO_PAD + .decode(payload) + .map_err(|_| Error::NonceMismatch)?; + let claims: Value = serde_json::from_slice(&decoded).map_err(|_| Error::NonceMismatch)?; + if claims.get("nonce").and_then(Value::as_str) == Some(expected_nonce) { + Ok(()) + } else { + Err(Error::NonceMismatch) + } +} + +fn sanitize_oauth_code(value: &str) -> String { + crate::error::safe_oauth_error_code(value) + .unwrap_or("unknown_error") + .to_string() +} + +fn random_urlsafe(bytes: usize) -> String { + let mut value = vec![0; bytes]; + rand::rng().fill_bytes(&mut value); + URL_SAFE_NO_PAD.encode(value) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::client::OAuthClient; + use crate::provider::OAuthProviderConfig; + use eggfetch_core::Client; + + fn client() -> OAuthClient { + OAuthClient::new(Client::new(), OAuthProviderConfig::xai()) + } + + #[test] + fn authorization_transaction_uses_pkce_state_nonce_and_callback_path() { + let pending = client() + .begin_authorization("http://127.0.0.1:34567/callback", None) + .unwrap(); + let url = url::Url::parse(pending.authorization_url()).unwrap(); + let values: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect(); + assert_eq!( + values.get("code_challenge_method").map(String::as_str), + Some("S256") + ); + assert_eq!( + values.get("redirect_uri").map(String::as_str), + Some("http://127.0.0.1:34567/callback") + ); + assert_eq!( + values.get("state").map(String::as_str), + Some(pending.state.as_str()) + ); + assert_eq!( + values.get("nonce").map(String::as_str), + Some(pending.nonce.as_str()) + ); + assert!(values.contains_key("code_challenge")); + assert!(pending.authorization_url().contains("referrer=eggpass")); + let debug = format!("{pending:?}"); + assert!(!debug.contains(&pending.state)); + assert!(!debug.contains(&pending.code_verifier)); + assert!(!debug.contains(&pending.nonce)); + } + + #[test] + fn openai_registration_hint_is_only_sent_for_first_authorization() { + let client = OAuthClient::new(Client::new(), OAuthProviderConfig::openai()); + let first = client + .begin_authorization("http://127.0.0.1:45678/auth/callback", None) + .unwrap(); + let first_url = url::Url::parse(first.authorization_url()).unwrap(); + let first_values: std::collections::HashMap<_, _> = + first_url.query_pairs().into_owned().collect(); + assert_eq!( + first_values.get("client_id").map(String::as_str), + Some("dynamic_agent_client") + ); + assert_eq!( + first_values.get("agent_name_hint").map(String::as_str), + Some("eggpass") + ); + assert!(first.registration); + assert!(first_values.contains_key("resource")); + + let existing = Credentials { + client_id: "issued-client-id".into(), + issuer: crate::provider::OPENAI_ISSUER.into(), + ..Credentials::default() + }; + let next = client + .begin_authorization("http://127.0.0.1:45678/auth/callback", Some(&existing)) + .unwrap(); + let next_url = url::Url::parse(next.authorization_url()).unwrap(); + let next_values: std::collections::HashMap<_, _> = + next_url.query_pairs().into_owned().collect(); + assert_eq!( + next_values.get("client_id").map(String::as_str), + Some("issued-client-id") + ); + assert!(!next.registration); + assert!(!next_values.contains_key("agent_name_hint")); + } + + #[tokio::test] + async fn callback_completion_rejects_wrong_origin_path_state_and_duplicates() { + let client = client(); + for case in ["origin", "path", "state", "duplicate-state", "missing-code"] { + let pending = client + .begin_authorization("http://127.0.0.1:34567/callback", None) + .unwrap(); + let state = pending.state.clone(); + let (callback, expected_callback_error) = match case { + "origin" => ( + format!("http://127.0.0.2:34567/callback?code=c&state={state}"), + true, + ), + "path" => ( + format!("http://127.0.0.1:34567/other?code=c&state={state}"), + true, + ), + "state" => ( + "http://127.0.0.1:34567/callback?code=c&state=wrong".to_string(), + false, + ), + "duplicate-state" => ( + format!("http://127.0.0.1:34567/callback?code=c&state={state}&state={state}"), + true, + ), + _ => ( + format!("http://127.0.0.1:34567/callback?state={state}"), + false, + ), + }; + let error = client + .complete_authorization(pending, &callback) + .await + .unwrap_err(); + if expected_callback_error { + assert!( + matches!(error, Error::CallbackMismatch), + "{case}: {error:?}" + ); + } else if case == "state" { + assert!(matches!(error, Error::StateMismatch)); + } else { + assert!(matches!(error, Error::InvalidResponse(_))); + } + } + } + + #[test] + fn callback_error_codes_never_reflect_arbitrary_provider_values() { + assert_eq!(sanitize_oauth_code("access_denied"), "access_denied"); + assert_eq!(sanitize_oauth_code("refresh-secret-123"), "unknown_error"); + } + + #[test] + fn nonce_claim_must_match_exactly() { + let nonce = "expected-nonce"; + let payload = URL_SAFE_NO_PAD + .encode(serde_json::to_vec(&serde_json::json!({ "nonce": nonce })).unwrap()); + let token = format!("header.{payload}.signature"); + assert!(validate_nonce(Some(&token), nonce).is_ok()); + assert!(matches!( + validate_nonce(Some(&token), "wrong"), + Err(Error::NonceMismatch) + )); + assert!(matches!( + validate_nonce(None, nonce), + Err(Error::NonceMismatch) + )); + } +} diff --git a/crates/eggpass-auth/src/client.rs b/crates/eggpass-auth/src/client.rs new file mode 100644 index 0000000..486c217 --- /dev/null +++ b/crates/eggpass-auth/src/client.rs @@ -0,0 +1,966 @@ +use std::future::Future; +use std::time::Duration; + +use eggfetch_core::timeout::Timeout; +use eggfetch_core::{Client as HttpClient, redirect::RedirectPolicy}; +use serde_json::Value; +use tokio_util::sync::CancellationToken; + +use crate::provider::{ClientIdPolicy, OAuthProviderConfig}; +use crate::token::{Credentials, DeviceCode, DevicePoll, TokenSet, UserInfo}; +use crate::{Error, Result}; + +/// Per-request timeout and response-size policy for OAuth HTTP exchanges. +/// +/// Every OAuth request explicitly overrides the supplied Eggfetch client's +/// timeout, redirect, retry, and default-auth settings. This avoids inheriting +/// accidental unbounded waits, redirects carrying credentials, or automatic +/// retries of one-shot code/refresh exchanges. +#[derive(Clone, Copy, Debug)] +pub struct ClientOptions { + /// Eggfetch phase timeouts, including an absolute request-wide deadline. + pub timeout: Timeout, + /// Maximum decoded response body size in bytes. + pub max_response_body_bytes: usize, +} + +impl Default for ClientOptions { + fn default() -> Self { + Self { + timeout: Timeout { + pool: Some(Duration::from_secs(10)), + connect: Some(Duration::from_secs(15)), + write: Some(Duration::from_secs(15)), + read: Some(Duration::from_secs(30)), + total: Some(Duration::from_secs(60)), + }, + max_response_body_bytes: 1024 * 1024, + } + } +} + +/// Async OAuth protocol client for one provider. +/// +/// The caller supplies and owns the cloneable Eggfetch client. This type never +/// creates a Tokio runtime. Methods are awaited on the caller's runtime. +pub struct OAuthClient { + pub(crate) http: HttpClient, + pub(crate) provider: OAuthProviderConfig, + pub(crate) options: ClientOptions, +} + +impl std::fmt::Debug for OAuthClient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("OAuthClient") + .field("provider", &self.provider) + .field("options", &self.options) + .field("http", &"") + .finish() + } +} + +impl Clone for OAuthClient { + fn clone(&self) -> Self { + Self { + http: self.http.clone(), + provider: self.provider.clone(), + options: self.options, + } + } +} + +impl OAuthClient { + /// Construct a client around a caller-owned Eggfetch client and validated + /// provider profile. No runtime is created or retained by this library. + pub fn new(http: HttpClient, provider: OAuthProviderConfig) -> Self { + Self { + http, + provider, + options: ClientOptions::default(), + } + } + + /// Set the explicit request timeout and response body cap. + pub fn with_options(mut self, options: ClientOptions) -> Result { + if options.max_response_body_bytes == 0 { + return Err(Error::InvalidConfiguration( + "response body limit must be greater than zero", + )); + } + self.options = options; + Ok(self) + } + + /// Provider profile used by this client. + pub fn provider(&self) -> &OAuthProviderConfig { + &self.provider + } + + /// Start an authorization-code transaction. The returned value contains + /// the authorization URL and private PKCE/state/nonce material; pass it to + /// [`Self::complete_authorization`] after the caller receives the callback. + pub fn begin_authorization( + &self, + redirect_uri: &str, + existing: Option<&Credentials>, + ) -> Result { + crate::authorization::begin_authorization(self, redirect_uri, existing) + } + + /// Complete a pending transaction from a full callback URL. This validates + /// callback origin and exact path, state, and (when OpenID Connect is + /// requested) ID-token nonce before returning credentials. + pub async fn complete_authorization( + &self, + pending: PendingAuthorization, + callback_url: &str, + ) -> Result { + crate::authorization::complete_authorization(self, pending, callback_url).await + } + + /// Complete an authorization when the provider displayed a code for the + /// user to copy instead of redirecting to the registered callback. + /// + /// The pending PKCE verifier and nonce are still used and the ID-token + /// nonce is still validated. This is available only for fixed-client-ID + /// profiles; providers that issue a client ID need the callback metadata. + pub async fn complete_authorization_with_code( + &self, + pending: PendingAuthorization, + code: &str, + ) -> Result { + crate::authorization::complete_authorization_with_code(self, pending, code).await + } + + /// Exchange an authorization code using caller-supplied PKCE material. + /// + /// Prefer [`Self::begin_authorization`] and [`Self::complete_authorization`] + /// for browser flows; the lower-level form is for callers that manage the + /// transaction themselves. `client_id` is an issued ID for providers that + /// have [`ClientIdPolicy::IssuedOnRegistration`], or `None` to use the + /// configured entry ID. + pub async fn exchange_authorization_code( + &self, + code: &str, + redirect_uri: &str, + code_verifier: &str, + client_id: Option<&str>, + ) -> Result { + validate_nonempty(code, "authorization code")?; + validate_nonempty(code_verifier, "PKCE verifier")?; + validate_redirect_uri(redirect_uri, &self.provider.callback_path)?; + let client_id = self.client_id(client_id)?; + let mut parameters = vec![ + ("grant_type".to_string(), "authorization_code".to_string()), + ("code".to_string(), code.to_string()), + ("redirect_uri".to_string(), redirect_uri.to_string()), + ("client_id".to_string(), client_id.clone()), + ("code_verifier".to_string(), code_verifier.to_string()), + ]; + parameters.extend(self.provider.token_parameters.clone()); + let value = self + .post_form_json(&self.provider.token_endpoint, ¶meters) + .await?; + let tokens = TokenSet::from_json(&value, Credentials::now_unix())?; + Ok(Credentials::from_tokens( + tokens, + client_id, + self.provider.issuer.clone(), + Credentials::now_unix(), + )) + } + + /// Exchange a refresh token and return only the provider response tokens. + /// + /// This operation is not automatically retried. A successful response may + /// rotate the refresh token; callers using explicit tokens must persist the + /// returned token when present and retain their previous refresh token when + /// the provider omits rotation. + pub async fn refresh_token( + &self, + refresh_token: &str, + client_id: Option<&str>, + ) -> Result { + validate_nonempty(refresh_token, "refresh token")?; + let client_id = self.client_id(client_id)?; + let mut parameters = vec![ + ("grant_type".to_string(), "refresh_token".to_string()), + ("refresh_token".to_string(), refresh_token.to_string()), + ("client_id".to_string(), client_id), + ]; + parameters.extend(self.provider.token_parameters.clone()); + let value = self + .post_form_json(&self.provider.token_endpoint, ¶meters) + .await?; + TokenSet::from_json(&value, Credentials::now_unix()) + } + + /// Refresh a stored credential set and merge it safely. The existing + /// refresh token is retained if the provider omits a rotated token. + pub async fn refresh_credentials(&self, current: &Credentials) -> Result { + self.validate_credentials(current)?; + let refresh_token = current.refresh_token().ok_or(Error::NoRefreshToken)?; + let tokens = self + .refresh_token(refresh_token, Some(current.client_id())) + .await?; + Ok(current.merged_refresh(tokens, Credentials::now_unix())) + } + + /// Revoke a token when the provider publishes a revocation endpoint. + pub async fn revoke(&self, token: &str, client_id: Option<&str>) -> Result<()> { + validate_nonempty(token, "token")?; + let endpoint = self + .provider + .revocation_endpoint + .as_deref() + .ok_or(Error::Unsupported("token revocation"))?; + let client_id = self.client_id(client_id)?; + let parameters = vec![ + ("token".to_string(), token.to_string()), + ("token_type_hint".to_string(), "refresh_token".to_string()), + ("client_id".to_string(), client_id), + ]; + let response = self.post_form_raw(endpoint, ¶meters).await?; + if (200..300).contains(&response.status) { + Ok(()) + } else { + Err(oauth_error(response.status, &response.body)) + } + } + + /// Fetch non-secret user details using an explicit access token. + pub async fn userinfo(&self, access_token: &str) -> Result { + validate_nonempty(access_token, "access token")?; + let endpoint = self + .provider + .userinfo_endpoint + .as_deref() + .ok_or(Error::Unsupported("user-info lookup"))?; + let builder = self + .http + .get(endpoint) + .map_err(map_eggfetch_error)? + .without_auth() + .header("Authorization", &format!("Bearer {access_token}")) + .timeout(self.options.timeout) + .max_decoded_body_size(self.options.max_response_body_bytes) + .without_retry() + .redirect_policy(RedirectPolicy::new(false, 0)); + let mut response = builder.send().await.map_err(map_eggfetch_error)?; + let status = response.status().as_u16(); + let body = read_limited_body(&mut response, self.options.max_response_body_bytes).await?; + if !(200..300).contains(&status) { + return Err(oauth_error(status, &body)); + } + let value: Value = serde_json::from_slice(&body) + .map_err(|_| Error::InvalidResponse("user-info response is not valid JSON"))?; + Ok(UserInfo { + user_id: first_string( + &value, + &["sub", "user_id", "userId", "preferred_username", "username"], + ), + email: first_string(&value, &["email", "email_address", "emailAddress"]), + }) + } + + /// Request a device authorization. The verification URI and any completed + /// verification URI are checked against the provider's exact HTTPS host + /// allowlist before being returned to the caller. + pub async fn request_device_code(&self) -> Result { + let endpoint = self + .provider + .device_authorization_endpoint + .as_deref() + .ok_or(Error::Unsupported("device authorization"))?; + let scope = self.provider.scopes.join(" "); + let mut parameters = vec![ + ("client_id".to_string(), self.provider.client_id.clone()), + ("scope".to_string(), scope), + ]; + parameters.extend(self.provider.device_parameters.clone()); + let value = self.post_form_json(endpoint, ¶meters).await?; + + let device_code = value + .get("device_code") + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .ok_or(Error::InvalidResponse("device response has no device_code"))? + .to_string(); + let user_code = value + .get("user_code") + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .ok_or(Error::InvalidResponse("device response has no user_code"))? + .to_string(); + let verification_uri = value + .get("verification_uri") + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .ok_or(Error::InvalidResponse( + "device response has no verification_uri", + ))? + .to_string(); + let verification_uri_complete = value + .get("verification_uri_complete") + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .map(str::to_owned); + let expires_in = value + .get("expires_in") + .and_then(Value::as_u64) + .filter(|seconds| *seconds > 0) + .ok_or(Error::InvalidResponse( + "device response expires_in must be positive", + ))?; + let interval = value + .get("interval") + .and_then(Value::as_u64) + .unwrap_or(5) + .max(1); + + require_trusted_verification_url(&verification_uri, &self.provider.trusted_device_hosts)?; + if let Some(complete) = &verification_uri_complete { + require_trusted_verification_url(complete, &self.provider.trusted_device_hosts)?; + } + + let expires_in = Duration::from_secs(expires_in); + let expires_at = + tokio::time::Instant::now() + .checked_add(expires_in) + .ok_or(Error::InvalidResponse( + "device response expiry is out of range", + ))?; + + Ok(DeviceCode { + device_code, + user_code, + verification_uri, + verification_uri_complete, + expires_in, + expires_at, + interval: Duration::from_secs(interval), + }) + } + + /// Perform one device poll. For a cancellable polling loop, use + /// [`Self::poll_device_authorization`]. + pub async fn poll_device_code(&self, device_code: &str) -> Result { + validate_nonempty(device_code, "device code")?; + let client_id = self.client_id(None)?; + let parameters = vec![ + ( + "grant_type".to_string(), + "urn:ietf:params:oauth:grant-type:device_code".to_string(), + ), + ("device_code".to_string(), device_code.to_string()), + ("client_id".to_string(), client_id), + ]; + let response = self + .post_form_raw(&self.provider.token_endpoint, ¶meters) + .await?; + if (200..300).contains(&response.status) { + let value: Value = serde_json::from_slice(&response.body) + .map_err(|_| Error::InvalidResponse("device token response is not valid JSON"))?; + return Ok(DevicePoll::Complete(TokenSet::from_json( + &value, + Credentials::now_unix(), + )?)); + } + let code = oauth_error_code(&response.body); + match code.as_deref() { + Some("authorization_pending") => Ok(DevicePoll::Pending), + Some("slow_down") => Ok(DevicePoll::SlowDown), + Some("access_denied" | "authorization_denied") => Ok(DevicePoll::Denied), + Some("expired_token") => Ok(DevicePoll::Expired), + _ => Err(oauth_error(response.status, &response.body)), + } + } + + /// Poll a device authorization until success, denial, server expiry, + /// caller deadline, or cancellation. The loop sleeps before its first poll; + /// each `slow_down` adds five seconds to all subsequent intervals. + pub async fn poll_device_authorization( + &self, + device: &DeviceCode, + cancellation: &CancellationToken, + caller_timeout: Duration, + ) -> Result { + let client_id = self.client_id(None)?; + poll_device_until( + device, + cancellation, + caller_timeout, + client_id, + self.provider.issuer.clone(), + |device_code| async move { self.poll_device_code(&device_code).await }, + ) + .await + } + + pub(crate) fn validate_credentials(&self, credentials: &Credentials) -> Result<()> { + credentials.validate()?; + if !credentials.issuer().is_empty() && credentials.issuer() != self.provider.issuer { + return Err(Error::InvalidConfiguration( + "stored credentials belong to a different issuer", + )); + } + Ok(()) + } + + pub(crate) fn client_id(&self, override_id: Option<&str>) -> Result { + match (self.provider.client_id_policy, override_id) { + (ClientIdPolicy::IssuedOnRegistration, Some(value)) if !value.trim().is_empty() => { + Ok(value.to_string()) + } + (ClientIdPolicy::IssuedOnRegistration, _) => Ok(self.provider.client_id.clone()), + (ClientIdPolicy::Fixed, Some(value)) if !value.trim().is_empty() => { + Ok(value.to_string()) + } + (ClientIdPolicy::Fixed, _) => Ok(self.provider.client_id.clone()), + } + } + + pub(crate) async fn post_form_json( + &self, + endpoint: &str, + parameters: &[(String, String)], + ) -> Result { + let response = self.post_form_raw(endpoint, parameters).await?; + if !(200..300).contains(&response.status) { + return Err(oauth_error(response.status, &response.body)); + } + serde_json::from_slice(&response.body) + .map_err(|_| Error::InvalidResponse("OAuth response is not valid JSON")) + } + + pub(crate) async fn post_form_raw( + &self, + endpoint: &str, + parameters: &[(String, String)], + ) -> Result { + let body = { + let mut encoded = url::form_urlencoded::Serializer::new(String::new()); + encoded.extend_pairs( + parameters + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())), + ); + encoded.finish() + }; + let builder = self + .http + .post(endpoint) + .map_err(map_eggfetch_error)? + .without_auth() + .header("Content-Type", "application/x-www-form-urlencoded") + .body(body) + .timeout(self.options.timeout) + .max_decoded_body_size(self.options.max_response_body_bytes) + .without_retry() + .redirect_policy(RedirectPolicy::new(false, 0)); + let mut response = builder.send().await.map_err(map_eggfetch_error)?; + let status = response.status().as_u16(); + let body = read_limited_body(&mut response, self.options.max_response_body_bytes).await?; + Ok(RawResponse { status, body }) + } +} + +async fn poll_device_until( + device: &DeviceCode, + cancellation: &CancellationToken, + caller_timeout: Duration, + client_id: String, + issuer: String, + mut poll: F, +) -> Result +where + F: FnMut(String) -> Fut, + Fut: Future>, +{ + if device.expires_in.is_zero() { + return Err(Error::DeviceExpired); + } + let start = tokio::time::Instant::now(); + let caller_deadline = start + .checked_add(caller_timeout) + .ok_or(Error::InvalidResponse( + "device authorization deadline is out of range", + ))?; + let server_is_deadline = device.expires_at <= caller_deadline; + let deadline = device.expires_at.min(caller_deadline); + let mut interval = device.interval; + + loop { + let now = tokio::time::Instant::now(); + if now >= deadline { + return if server_is_deadline { + Err(Error::DeviceExpired) + } else { + Err(Error::Timeout("device authorization")) + }; + } + let remaining = deadline.saturating_duration_since(now); + let wake = now + interval.min(remaining); + tokio::select! { + _ = cancellation.cancelled() => return Err(Error::Cancelled), + _ = tokio::time::sleep_until(wake) => {} + } + if tokio::time::Instant::now() >= deadline { + return if server_is_deadline { + Err(Error::DeviceExpired) + } else { + Err(Error::Timeout("device authorization")) + }; + } + let poll_future = poll(device.device_code.clone()); + let result = tokio::select! { + _ = cancellation.cancelled() => return Err(Error::Cancelled), + result = tokio::time::timeout_at(deadline, poll_future) => match result { + Ok(result) => result?, + Err(_) => return if server_is_deadline { + Err(Error::DeviceExpired) + } else { + Err(Error::Timeout("device authorization")) + }, + } + }; + match result { + DevicePoll::Pending => {} + DevicePoll::SlowDown => interval = interval.saturating_add(Duration::from_secs(5)), + DevicePoll::Denied => return Err(Error::ProviderDenied("access_denied".to_string())), + DevicePoll::Expired => return Err(Error::DeviceExpired), + DevicePoll::Complete(tokens) => { + return Ok(Credentials::from_tokens( + tokens, + client_id, + issuer, + Credentials::now_unix(), + )); + } + } + } +} + +/// Opaque, one-use authorization transaction. Sensitive fields are private and +/// redacted from `Debug`; it is consumed by callback completion. +pub struct PendingAuthorization { + pub(crate) authorization_url: String, + pub(crate) redirect_uri: String, + pub(crate) code_verifier: String, + pub(crate) state: String, + pub(crate) nonce: String, + pub(crate) client_id: String, + pub(crate) registration: bool, +} + +impl PendingAuthorization { + /// URL to present to the user in an external browser or another UI. + pub fn authorization_url(&self) -> &str { + &self.authorization_url + } +} + +impl std::fmt::Debug for PendingAuthorization { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PendingAuthorization") + .field("authorization_url", &"") + .field("redirect_uri", &self.redirect_uri) + .field("code_verifier", &"") + .field("state", &"") + .field("nonce", &"") + .field("client_id", &"") + .field("registration", &self.registration) + .finish() + } +} + +pub(crate) struct RawResponse { + pub status: u16, + pub body: Vec, +} + +async fn read_limited_body( + response: &mut eggfetch_core::Response, + maximum: usize, +) -> Result> { + if response + .content_length() + .is_some_and(|size| size > maximum as u64) + { + return Err(Error::ResponseTooLarge); + } + let bytes = response.bytes().await.map_err(map_eggfetch_error)?; + if bytes.len() > maximum { + return Err(Error::ResponseTooLarge); + } + Ok(bytes.to_vec()) +} + +pub(crate) fn oauth_error(status: u16, body: &[u8]) -> Error { + if let Some(code) = oauth_error_code(body) { + Error::OAuth { status, code } + } else { + Error::HttpStatus { status } + } +} + +fn oauth_error_code(body: &[u8]) -> Option { + let value: Value = serde_json::from_slice(body).ok()?; + let code = value.get("error")?.as_str()?; + crate::error::safe_oauth_error_code(code).map(str::to_string) +} + +fn map_eggfetch_error(error: eggfetch_core::error::Error) -> Error { + use eggfetch_core::error::Error as FetchError; + match error { + FetchError::DecodedBodyTooLarge => Error::ResponseTooLarge, + FetchError::Timeout { .. } | FetchError::TransportIoTimeout { .. } => { + Error::Timeout("HTTP request") + } + _ => Error::Transport, + } +} + +fn validate_nonempty(value: &str, label: &'static str) -> Result<()> { + if value.is_empty() || value.chars().any(char::is_control) { + return Err(Error::InvalidConfiguration(match label { + "authorization code" => { + "authorization code must not be empty or contain control characters" + } + "PKCE verifier" => "PKCE verifier must not be empty or contain control characters", + "refresh token" => "refresh token must not be empty or contain control characters", + "access token" => "access token must not be empty or contain control characters", + "device code" => "device code must not be empty or contain control characters", + _ => "token value must not be empty or contain control characters", + })); + } + Ok(()) +} + +pub(crate) fn validate_redirect_uri(redirect_uri: &str, expected_path: &str) -> Result { + let redirect = url::Url::parse(redirect_uri) + .map_err(|_| Error::InvalidConfiguration("redirect URI is invalid"))?; + let loopback_http = match redirect.host() { + Some(url::Host::Ipv4(address)) => address.is_loopback(), + Some(url::Host::Ipv6(address)) => address.is_loopback(), + Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"), + None => false, + }; + if !matches!(redirect.scheme(), "https" | "http") + || (redirect.scheme() == "http" && !loopback_http) + || !redirect.username().is_empty() + || redirect.password().is_some() + || redirect.query().is_some() + || redirect.fragment().is_some() + || redirect.path() != expected_path + { + return Err(Error::InvalidConfiguration( + "redirect URI must use HTTPS or loopback HTTP and the exact configured callback path", + )); + } + Ok(redirect) +} + +fn first_string(value: &Value, names: &[&str]) -> Option { + names + .iter() + .find_map(|name| value.get(*name).and_then(Value::as_str).map(str::to_owned)) +} + +pub(crate) fn require_trusted_verification_url(url: &str, trusted_hosts: &[String]) -> Result<()> { + if trusted_hosts.is_empty() + || url + .bytes() + .any(|byte| byte == b'\\' || byte.is_ascii_whitespace() || byte < 0x20) + { + return Err(Error::UntrustedVerificationUrl { host: None }); + } + let parsed = match url::Url::parse(url) { + Ok(parsed) => parsed, + Err(_) => return Err(Error::UntrustedVerificationUrl { host: None }), + }; + let host = parsed + .host_str() + .map(|host| host.strip_suffix('.').unwrap_or(host).to_ascii_lowercase()); + let trusted = parsed.scheme() == "https" + && parsed.username().is_empty() + && parsed.password().is_none() + && host.as_ref().is_some_and(|host| { + trusted_hosts + .iter() + .any(|candidate| candidate.eq_ignore_ascii_case(host)) + }); + if trusted { + Ok(()) + } else { + let host = host.filter(|host| host.len() <= 253 && host.is_ascii()); + Err(Error::UntrustedVerificationUrl { host }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_timeouts_are_finite_and_response_limit_is_bounded() { + let options = ClientOptions::default(); + assert!(options.timeout.connect.is_some()); + assert!(options.timeout.read.is_some()); + assert!(options.timeout.total.is_some()); + assert!(options.max_response_body_bytes > 0); + } + + #[test] + fn redirect_uri_path_is_exact_and_http_requires_loopback() { + assert!(validate_redirect_uri("http://127.0.0.1:1234/callback", "/callback").is_ok()); + assert!(validate_redirect_uri("https://example.test/callback", "/callback").is_ok()); + assert!(validate_redirect_uri("http://example.test/callback", "/callback").is_err()); + assert!(validate_redirect_uri("http://127.0.0.1:1234/other", "/callback").is_err()); + } + + #[test] + fn oauth_errors_keep_codes_but_never_descriptions_or_body() { + let error = oauth_error( + 400, + br#"{"error":"invalid_scope","error_description":"secret detail"}"#, + ); + assert_eq!(error.oauth_code(), Some("invalid_scope")); + let display = error.to_string(); + assert!(!display.contains("secret detail")); + assert!(!format!("{error:?}").contains("secret detail")); + + let echoed_secret = oauth_error(400, br#"{"error":"refresh-secret-123"}"#); + assert!(matches!(echoed_secret, Error::HttpStatus { status: 400 })); + assert!(!echoed_secret.to_string().contains("refresh-secret-123")); + assert!(!format!("{echoed_secret:?}").contains("refresh-secret-123")); + } + + #[tokio::test] + async fn refresh_credentials_rejects_a_different_issuer_before_network_access() { + let client = OAuthClient::new( + eggfetch_core::Client::new(), + crate::provider::OAuthProviderConfig::xai(), + ); + let credentials = Credentials { + access_token: "access-secret".into(), + refresh_token: Some("refresh-secret".into()), + client_id: crate::provider::XAI_CLIENT_ID.into(), + issuer: crate::provider::OPENAI_ISSUER.into(), + ..Credentials::default() + }; + + assert!(matches!( + client.refresh_credentials(&credentials).await, + Err(Error::InvalidConfiguration(_)) + )); + } + + #[test] + fn trusted_verification_url_requires_exact_https_host_and_rejects_parser_delimiters() { + let hosts = vec!["accounts.x.ai".to_string(), "auth.x.ai".to_string()]; + assert!( + require_trusted_verification_url("https://accounts.x.ai/verify?user_code=ABCD", &hosts) + .is_ok() + ); + assert!( + require_trusted_verification_url("https://accounts.x.ai.evil.test/", &hosts).is_err() + ); + assert!( + require_trusted_verification_url("https://accounts.x.ai\\@evil.test/", &hosts).is_err() + ); + assert!(require_trusted_verification_url("http://accounts.x.ai/", &hosts).is_err()); + } + + fn test_device(expires: u64, interval: u64) -> DeviceCode { + let expires_in = Duration::from_secs(expires); + DeviceCode { + device_code: "device-secret".into(), + user_code: "user-secret".into(), + verification_uri: "https://accounts.x.ai/device".into(), + verification_uri_complete: None, + expires_in, + expires_at: tokio::time::Instant::now() + expires_in, + interval: Duration::from_secs(interval), + } + } + + #[test] + fn device_code_debug_redacts_device_codes_and_verification_urls() { + let mut device = test_device(30, 5); + device.verification_uri = "https://accounts.x.ai/device?verification-secret=hidden".into(); + device.verification_uri_complete = + Some("https://accounts.x.ai/device?user_code=hidden-code".into()); + + let debug = format!("{device:?}"); + for secret in [ + "device-secret", + "user-secret", + "verification-secret", + "hidden-code", + ] { + assert!(!debug.contains(secret)); + } + } + + fn test_tokens() -> TokenSet { + TokenSet { + access_token: "access".into(), + refresh_token: Some("refresh".into()), + id_token: None, + token_type: "Bearer".into(), + scope: None, + expires_at: Some(10_000), + } + } + + #[tokio::test(start_paused = true)] + async fn device_slow_down_increases_all_later_intervals_by_five_seconds() { + use std::sync::{Arc, Mutex}; + + let observations = Arc::new(Mutex::new(Vec::new())); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let observed = observations.clone(); + let counter = calls.clone(); + let result = poll_device_until( + &test_device(30, 1), + &CancellationToken::new(), + Duration::from_secs(30), + "client".into(), + "https://auth.x.ai".into(), + move |_| { + let observed = observed.clone(); + let index = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + async move { + observed.lock().unwrap().push(tokio::time::Instant::now()); + Ok(match index { + 0 => DevicePoll::SlowDown, + 1 => DevicePoll::Pending, + _ => DevicePoll::Complete(test_tokens()), + }) + } + }, + ) + .await + .unwrap(); + assert_eq!(result.access_token(), "access"); + let observations = observations.lock().unwrap(); + assert_eq!(observations.len(), 3); + assert_eq!( + observations[1].duration_since(observations[0]), + Duration::from_secs(6) + ); + assert_eq!( + observations[2].duration_since(observations[1]), + Duration::from_secs(6) + ); + } + + #[tokio::test(start_paused = true)] + async fn device_expiry_is_measured_from_code_issuance_not_polling_start() { + let device = test_device(2, 1); + tokio::time::advance(Duration::from_secs(3)).await; + let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = calls.clone(); + let error = poll_device_until( + &device, + &CancellationToken::new(), + Duration::from_secs(10), + "client".into(), + "https://auth.x.ai".into(), + move |_| { + let count = count.clone(); + async move { + count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(DevicePoll::Pending) + } + }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::DeviceExpired)); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0); + } + + #[tokio::test(start_paused = true)] + async fn device_flow_honors_short_expiry_and_caller_deadline() { + let cancellation = CancellationToken::new(); + let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = calls.clone(); + let error = poll_device_until( + &test_device(2, 5), + &cancellation, + Duration::from_secs(20), + "client".into(), + "https://auth.x.ai".into(), + move |_| { + let count = count.clone(); + async move { + count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(DevicePoll::Pending) + } + }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::DeviceExpired)); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0); + + let error = poll_device_until( + &test_device(30, 5), + &cancellation, + Duration::from_secs(2), + "client".into(), + "https://auth.x.ai".into(), + |_| async { Ok(DevicePoll::Pending) }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout("device authorization"))); + } + + #[tokio::test(start_paused = true)] + async fn device_flow_supports_cancellation_denial_and_server_expiry() { + let cancellation = CancellationToken::new(); + let cancel_signal = cancellation.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(100)).await; + cancel_signal.cancel(); + }); + let error = poll_device_until( + &test_device(30, 10), + &cancellation, + Duration::from_secs(20), + "client".into(), + "https://auth.x.ai".into(), + |_| async { Ok(DevicePoll::Pending) }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::Cancelled)); + + let error = poll_device_until( + &test_device(30, 1), + &CancellationToken::new(), + Duration::from_secs(20), + "client".into(), + "https://auth.x.ai".into(), + |_| async { Ok(DevicePoll::Denied) }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::ProviderDenied(_))); + + let error = poll_device_until( + &test_device(30, 1), + &CancellationToken::new(), + Duration::from_secs(20), + "client".into(), + "https://auth.x.ai".into(), + |_| async { Ok(DevicePoll::Expired) }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::DeviceExpired)); + } +} diff --git a/crates/eggpass-auth/src/error.rs b/crates/eggpass-auth/src/error.rs new file mode 100644 index 0000000..629d134 --- /dev/null +++ b/crates/eggpass-auth/src/error.rs @@ -0,0 +1,210 @@ +use std::fmt; + +/// Result type returned by the library. +pub type Result = std::result::Result; + +/// Return only recognized protocol error codes; never reflect arbitrary provider text. +pub(crate) fn safe_oauth_error_code(value: &str) -> Option<&'static str> { + const SAFE_CODES: &[&str] = &[ + "invalid_request", + "unauthorized_client", + "access_denied", + "unsupported_response_type", + "invalid_scope", + "server_error", + "temporarily_unavailable", + "invalid_client", + "invalid_grant", + "unsupported_grant_type", + "invalid_token", + "insufficient_scope", + "authorization_pending", + "slow_down", + "expired_token", + "authorization_denied", + "login_required", + "interaction_required", + "account_selection_required", + "consent_required", + "invalid_request_uri", + "invalid_request_object", + "request_not_supported", + "request_uri_not_supported", + "registration_not_supported", + ]; + SAFE_CODES.iter().copied().find(|code| *code == value) +} + +/// Errors returned by the OAuth client and credential manager. +/// +/// Response bodies, authorization codes, URLs, access tokens, refresh tokens, +/// device codes, and request URLs are deliberately not included in errors. +#[non_exhaustive] +pub enum Error { + /// Configuration or a response contained an invalid or missing value. + InvalidResponse(&'static str), + /// Provider or request configuration failed validation. + InvalidConfiguration(&'static str), + /// The HTTP server returned an unexpected status. + HttpStatus { status: u16 }, + /// The server returned a standard OAuth error code. + OAuth { status: u16, code: String }, + /// The provider denied an authorization callback. + ProviderDenied(String), + /// Callback origin or exact path did not match the pending transaction. + CallbackMismatch, + /// Callback state did not match the issued state. + StateMismatch, + /// The ID-token nonce did not match the pending authorization. + NonceMismatch, + /// The response body exceeded the configured limit. + ResponseTooLarge, + /// The HTTP exchange failed. Eggfetch error details are not exposed because + /// they can contain request URLs or caller configuration. + Transport, + /// A configured request or authorization deadline elapsed. + Timeout(&'static str), + /// The provider has no endpoint for the requested operation. + Unsupported(&'static str), + /// The device authorization expired before approval. + DeviceExpired, + /// Device polling was cancelled by the caller. + Cancelled, + /// The verification URL did not match the exact configured host allowlist. + UntrustedVerificationUrl { host: Option }, + /// No credentials were returned by the caller-owned store. + NotLoggedIn, + /// Stored credentials have no refresh token. + NoRefreshToken, + /// Caller-owned credential storage failed. + Storage(StorageError), +} + +impl Error { + /// HTTP status associated with an HTTP or OAuth error, when available. + pub fn status(&self) -> Option { + match self { + Self::HttpStatus { status } | Self::OAuth { status, .. } => Some(*status), + _ => None, + } + } + + /// OAuth error code associated with a provider response, when available. + pub fn oauth_code(&self) -> Option<&str> { + match self { + Self::OAuth { code, .. } | Self::ProviderDenied(code) => Some(code), + _ => None, + } + } +} + +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidResponse(reason) => { + f.debug_tuple("InvalidResponse").field(reason).finish() + } + Self::InvalidConfiguration(reason) => { + f.debug_tuple("InvalidConfiguration").field(reason).finish() + } + Self::HttpStatus { status } => f + .debug_struct("HttpStatus") + .field("status", status) + .finish(), + Self::OAuth { status, code } => f + .debug_struct("OAuth") + .field("status", status) + .field("code", code) + .finish(), + Self::ProviderDenied(code) => f.debug_tuple("ProviderDenied").field(code).finish(), + Self::CallbackMismatch => f.write_str("CallbackMismatch"), + Self::StateMismatch => f.write_str("StateMismatch"), + Self::NonceMismatch => f.write_str("NonceMismatch"), + Self::ResponseTooLarge => f.write_str("ResponseTooLarge"), + Self::Transport => f.write_str("Transport"), + Self::Timeout(operation) => f.debug_tuple("Timeout").field(operation).finish(), + Self::Unsupported(operation) => f.debug_tuple("Unsupported").field(operation).finish(), + Self::DeviceExpired => f.write_str("DeviceExpired"), + Self::Cancelled => f.write_str("Cancelled"), + Self::UntrustedVerificationUrl { host } => f + .debug_struct("UntrustedVerificationUrl") + .field("host", host) + .finish(), + Self::NotLoggedIn => f.write_str("NotLoggedIn"), + Self::NoRefreshToken => f.write_str("NoRefreshToken"), + Self::Storage(_) => f.write_str("Storage()"), + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidResponse(reason) => write!(f, "invalid OAuth response: {reason}"), + Self::InvalidConfiguration(reason) => { + write!(f, "invalid OAuth configuration: {reason}") + } + Self::HttpStatus { status } => write!(f, "HTTP {status} from OAuth endpoint"), + Self::OAuth { status, code } => { + write!(f, "OAuth endpoint returned HTTP {status} ({code})") + } + Self::ProviderDenied(code) => write!(f, "provider denied authorization ({code})"), + Self::CallbackMismatch => { + f.write_str("callback did not match the pending authorization") + } + Self::StateMismatch => { + f.write_str("callback state did not match the pending authorization") + } + Self::NonceMismatch => { + f.write_str("ID-token nonce did not match the pending authorization") + } + Self::ResponseTooLarge => { + f.write_str("OAuth response exceeded the configured body limit") + } + Self::Transport => f.write_str("OAuth HTTP request failed"), + Self::Timeout(operation) => write!(f, "OAuth {operation} timed out"), + Self::Unsupported(operation) => write!(f, "provider does not support {operation}"), + Self::DeviceExpired => f.write_str("device authorization expired"), + Self::Cancelled => f.write_str("device authorization was cancelled"), + Self::UntrustedVerificationUrl { host: Some(host) } => { + write!(f, "untrusted device verification host: {host}") + } + Self::UntrustedVerificationUrl { host: None } => { + f.write_str("device verification URL could not be parsed safely") + } + Self::NotLoggedIn => f.write_str("no credentials are stored"), + Self::NoRefreshToken => f.write_str("stored credentials contain no refresh token"), + Self::Storage(_) => f.write_str("credential storage failed"), + } + } +} + +impl std::error::Error for Error {} + +/// A safe, caller-provided description of a credential-storage failure. +/// +/// Do not put credentials or other secrets in this message. `Debug` always +/// redacts it; `Display` returns it so an application may decide whether to +/// present its own storage diagnostics. +pub struct StorageError(String); + +impl StorageError { + /// Construct a storage error using a message that contains no secrets. + pub fn new(message: impl Into) -> Self { + Self(message.into()) + } +} + +impl fmt::Debug for StorageError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("StorageError()") + } +} + +impl fmt::Display for StorageError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for StorageError {} diff --git a/crates/eggpass-auth/src/lib.rs b/crates/eggpass-auth/src/lib.rs new file mode 100644 index 0000000..d61d663 --- /dev/null +++ b/crates/eggpass-auth/src/lib.rs @@ -0,0 +1,77 @@ +//! Async OAuth authentication building blocks for Eggfetch applications. +//! +//! This crate accepts a caller-owned [`EggfetchClient`], never creates a Tokio +//! runtime, and does not launch a browser, print to a terminal, open a listener, +//! or read/write credential files. Applications own their runtime, user +//! interaction, callback receiver, and credential storage. Owned API values +//! such as [`OAuthClient`], [`PendingAuthorization`], [`Credentials`], +//! [`TokenSet`], and [`DeviceCode`] are `Send + Sync`. [`CredentialStore`] +//! implementations are also `Send + Sync` and return `Send` futures. +//! +//! # Authorization-code flow +//! +//! ```no_run +//! use eggfetch_core::Client; +//! use eggpass_auth::{OAuthClient, OAuthProviderConfig}; +//! +//! # async fn login() -> Result<(), Box> { +//! let oauth = OAuthClient::new(Client::new(), OAuthProviderConfig::xai()); +//! // The redirect URI must use the provider profile's exact callback path. +//! let pending = oauth.begin_authorization("http://127.0.0.1:43123/callback", None)?; +//! let browser_url = pending.authorization_url(); +//! // Present browser_url using the caller's UI, then receive the redirect URL +//! // in a caller-owned loopback listener or another registered callback. +//! let _ = browser_url; +//! # Ok(()) +//! # } +//! ``` +//! +//! The [`PendingAuthorization`] value keeps the PKCE verifier, state, and nonce +//! private and redacts them in `Debug`. Call [`OAuthClient::complete_authorization`] +//! with the full callback URL to validate origin, exact path, state, and the +//! returned ID-token nonce before credentials are released. +//! +//! # Device authorization +//! +//! [`OAuthClient::request_device_code`] returns a host-checked verification URI +//! and user code as data. The caller decides how to present them. Polling accepts +//! a [`CancellationToken`] and a caller timeout; the server expiry is honored, +//! and each `slow_down` response adds five seconds to subsequent intervals. +//! +//! # Credential storage and refresh +//! +//! [`Credentials`] is serializable for caller-owned storage and redacts secrets +//! from `Debug`. [`CredentialStore`] and [`TokenManager`] provide an optional +//! async refresh manager. Its single-flight guarantee applies to one manager in +//! one process only. Store implementations should atomically replace credential +//! sets and add cross-process coordination when needed. +//! +//! # Security and transport behavior +//! +//! OAuth requests use explicit finite timeouts and a bounded decoded response +//! size. Redirects and automatic retries are disabled for each request, and +//! caller-configured Eggfetch default authentication is suppressed before the +//! library sets any explicit bearer header. Errors expose status and sanitized +//! OAuth codes but not response bodies, URLs, authorization codes, or tokens. +//! Custom OAuth endpoints must use HTTPS, except for loopback HTTP endpoints +//! used by local tests. + +mod authorization; +mod client; +mod error; +mod manager; +mod pkce; +mod provider; +mod token; + +pub use client::{ClientOptions, OAuthClient, PendingAuthorization}; +pub use eggfetch_core::Client as EggfetchClient; +pub use error::{Error, Result, StorageError}; +pub use manager::{CredentialStore, TokenManager}; +pub use pkce::{challenge_for, random_verifier}; +pub use provider::{ + ClientIdPolicy, OAuthProviderConfig, OAuthProviderConfigBuilder, OPENAI_ENTRY_CLIENT_ID, + OPENAI_ISSUER, OPENAI_RESOURCE, XAI_CLIENT_ID, XAI_ISSUER, +}; +pub use token::{Credentials, DeviceCode, DevicePoll, TokenSet, UserInfo}; +pub use tokio_util::sync::CancellationToken; diff --git a/crates/eggpass-auth/src/manager.rs b/crates/eggpass-auth/src/manager.rs new file mode 100644 index 0000000..e26f163 --- /dev/null +++ b/crates/eggpass-auth/src/manager.rs @@ -0,0 +1,273 @@ +use std::future::Future; + +use tokio::sync::Mutex; + +use crate::client::OAuthClient; +use crate::error::StorageError; +use crate::token::Credentials; +use crate::{Error, Result}; + +/// Caller-owned asynchronous credential storage. +/// +/// Implementations should make `save` an atomic replacement of one credential +/// set. This contract does not itself coordinate separate processes; an +/// application needing cross-process refresh coordination must implement it in +/// its storage layer. The trait is generic/RPITIT-based and is not a `dyn` +/// trait; this keeps store errors and futures allocation-free. +pub trait CredentialStore: Send + Sync { + /// Load the current credentials, or `None` when the user is not logged in. + fn load( + &self, + ) -> impl Future, StorageError>> + Send; + + /// Atomically replace the stored credentials. + fn save( + &self, + credentials: Credentials, + ) -> impl Future> + Send; + + /// Remove credentials. Removing an absent entry should succeed. + fn clear(&self) -> impl Future> + Send; +} + +/// Async token manager over caller-owned credential storage. +/// +/// One manager coalesces proactive and compare-and-refresh requests within this +/// process. It is not a cross-process lock; storage implementations must add +/// coordination if multiple processes can refresh the same account. +pub struct TokenManager { + client: OAuthClient, + store: S, + refresh_lock: Mutex<()>, + refresh_skew_seconds: i64, +} + +impl std::fmt::Debug for TokenManager { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TokenManager") + .field("client", &self.client) + .field("refresh_skew_seconds", &self.refresh_skew_seconds) + .field("store", &"") + .finish() + } +} + +impl TokenManager { + /// Create a manager using the standard five-minute proactive refresh skew. + pub fn new(client: OAuthClient, store: S) -> Self { + Self { + client, + store, + refresh_lock: Mutex::new(()), + refresh_skew_seconds: 5 * 60, + } + } + + /// Configure how long before expiry a token should be refreshed. + pub fn with_refresh_skew(mut self, seconds: i64) -> Self { + self.refresh_skew_seconds = seconds.max(0); + self + } + + /// Read credentials without refreshing. + pub async fn current(&self) -> Result> { + let credentials = self.store.load().await.map_err(Error::Storage)?; + if let Some(credentials) = &credentials { + self.client.validate_credentials(credentials)?; + } + Ok(credentials) + } + + /// Store credentials obtained from an authorization or device flow. + pub async fn save(&self, credentials: Credentials) -> Result<()> { + credentials.validate()?; + self.store.save(credentials).await.map_err(Error::Storage) + } + + /// Remove credentials from the caller-owned store. + pub async fn clear(&self) -> Result<()> { + self.store.clear().await.map_err(Error::Storage) + } + + /// Get a usable access token, refreshing proactively when it is near expiry. + pub async fn access_token(&self) -> Result { + let current = self.current().await?.ok_or(Error::NotLoggedIn)?; + if current.is_fresh(Credentials::now_unix(), self.refresh_skew_seconds) { + return Ok(current.access_token().to_string()); + } + + let _guard = self.refresh_lock.lock().await; + let current = self.current().await?.ok_or(Error::NotLoggedIn)?; + if current.is_fresh(Credentials::now_unix(), self.refresh_skew_seconds) { + return Ok(current.access_token().to_string()); + } + self.refresh_current(¤t).await + } + + /// Refresh after an upstream request was rejected with HTTP 401. + /// + /// The refresh is performed only if `failed_access_token` is still current; + /// if another task already replaced it, that newer token is returned. + pub async fn force_refresh(&self, failed_access_token: &str) -> Result { + let _guard = self.refresh_lock.lock().await; + let current = self.current().await?.ok_or(Error::NotLoggedIn)?; + if current.access_token() != failed_access_token { + return Ok(current.access_token().to_string()); + } + self.refresh_current(¤t).await + } + + async fn refresh_current(&self, current: &Credentials) -> Result { + let refreshed = self.client.refresh_credentials(current).await?; + let access_token = refreshed.access_token().to_string(); + self.store.save(refreshed).await.map_err(Error::Storage)?; + Ok(access_token) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + use crate::token::TokenSet; + + #[derive(Clone, Default)] + struct MemoryStore(Arc>>); + + impl CredentialStore for MemoryStore { + fn load( + &self, + ) -> impl Future, StorageError>> + Send + { + let inner = self.0.clone(); + async move { Ok(inner.lock().await.clone()) } + } + + fn save( + &self, + credentials: Credentials, + ) -> impl Future> + Send { + let inner = self.0.clone(); + async move { + *inner.lock().await = Some(credentials); + Ok(()) + } + } + + fn clear(&self) -> impl Future> + Send { + let inner = self.0.clone(); + async move { + *inner.lock().await = None; + Ok(()) + } + } + } + + fn credentials() -> Credentials { + Credentials { + access_token: "access-secret".into(), + refresh_token: Some("refresh-secret".into()), + id_token: Some("id-secret".into()), + token_type: "Bearer".into(), + scope: Some("openid offline_access".into()), + client_id: "client".into(), + issuer: "https://auth.x.ai".into(), + expires_at: Some(1), + obtained_at: 0, + } + } + + #[test] + fn secret_bearing_credentials_have_redacted_debug() { + let credentials = credentials(); + let debug = format!("{credentials:?}"); + for secret in ["access-secret", "refresh-secret", "id-secret"] { + assert!(!debug.contains(secret)); + } + } + + #[test] + fn refresh_merge_retains_refresh_token_when_rotation_is_omitted() { + let current = credentials(); + let tokens = TokenSet { + access_token: "new-access".into(), + refresh_token: None, + id_token: None, + token_type: "Bearer".into(), + scope: None, + expires_at: Some(10_000), + }; + let merged = current.merged_refresh(tokens, 500); + assert_eq!(merged.access_token(), "new-access"); + assert_eq!(merged.refresh_token(), Some("refresh-secret")); + assert_eq!(merged.id_token(), Some("id-secret")); + assert_eq!(merged.client_id(), "client"); + } + + #[tokio::test] + async fn manager_rejects_missing_credentials_and_supports_clear() { + let store = MemoryStore::default(); + let client = OAuthClient::new( + eggfetch_core::Client::new(), + crate::provider::OAuthProviderConfig::xai(), + ); + let manager = TokenManager::new(client, store.clone()); + assert!(matches!( + manager.access_token().await, + Err(Error::NotLoggedIn) + )); + manager.save(credentials()).await.unwrap(); + assert!(manager.current().await.unwrap().is_some()); + manager.clear().await.unwrap(); + assert!(manager.current().await.unwrap().is_none()); + } + + #[tokio::test] + async fn manager_rejects_credentials_for_a_different_issuer() { + let store = MemoryStore::default(); + let client = OAuthClient::new( + eggfetch_core::Client::new(), + crate::provider::OAuthProviderConfig::xai(), + ); + let manager = TokenManager::new(client, store.clone()); + let mut wrong_issuer = credentials(); + wrong_issuer.issuer = crate::provider::OPENAI_ISSUER.into(); + store.save(wrong_issuer).await.unwrap(); + + assert!(matches!( + manager.current().await, + Err(Error::InvalidConfiguration(_)) + )); + } + + #[tokio::test] + async fn force_refresh_uses_a_newer_token_without_another_refresh() { + let store = MemoryStore::default(); + let client = OAuthClient::new( + eggfetch_core::Client::new(), + crate::provider::OAuthProviderConfig::xai(), + ); + let manager = TokenManager::new(client, store.clone()); + let mut current = credentials(); + current.access_token = "newer-access".into(); + store.save(current).await.unwrap(); + + assert_eq!( + manager.force_refresh("failed-old-access").await.unwrap(), + "newer-access" + ); + } + + #[test] + fn public_owned_api_types_are_send_and_sync() { + fn assert_send_sync() {} + + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::>(); + } +} diff --git a/crates/eggpass-auth/src/pkce.rs b/crates/eggpass-auth/src/pkce.rs new file mode 100644 index 0000000..02f5dd2 --- /dev/null +++ b/crates/eggpass-auth/src/pkce.rs @@ -0,0 +1,43 @@ +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use rand::Rng; +use sha2::{Digest, Sha256}; + +/// Generate a cryptographically random PKCE verifier (RFC 7636, 32 random bytes). +pub fn random_verifier() -> String { + random_urlsafe(32) +} + +/// Return the RFC 7636 S256 code challenge for an ASCII verifier. +pub fn challenge_for(verifier: &str) -> String { + URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) +} + +fn random_urlsafe(bytes: usize) -> String { + let mut value = vec![0; bytes]; + rand::rng().fill_bytes(&mut value); + URL_SAFE_NO_PAD.encode(value) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_the_rfc_7636_s256_test_vector() { + assert_eq!( + challenge_for("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + ); + } + + #[test] + fn verifier_is_base64url_without_padding_and_has_256_bits_of_entropy() { + let verifier = random_verifier(); + assert_eq!(verifier.len(), 43); + assert!(!verifier.contains('=')); + assert!(!verifier.contains('+')); + assert!(!verifier.contains('/')); + assert_ne!(verifier, random_verifier()); + } +} diff --git a/crates/eggpass-auth/src/provider.rs b/crates/eggpass-auth/src/provider.rs new file mode 100644 index 0000000..3877223 --- /dev/null +++ b/crates/eggpass-auth/src/provider.rs @@ -0,0 +1,669 @@ +use std::fmt; + +use crate::{Error, Result}; + +/// The x.ai OAuth issuer. +pub const XAI_ISSUER: &str = "https://auth.x.ai"; +/// The public x.ai / Grok CLI client identifier. +pub const XAI_CLIENT_ID: &str = "b1a00492-073a-47ea-816f-4c329264a828"; +/// The OpenAI OAuth issuer. +pub const OPENAI_ISSUER: &str = "https://auth.openai.com"; +/// The temporary client identifier used to register an OpenAI agent. +pub const OPENAI_ENTRY_CLIENT_ID: &str = "dynamic_agent_client"; +/// The OpenAI resource sent during authorization and token requests. +pub const OPENAI_RESOURCE: &str = "https://api.openai.com/v1"; + +const XAI_SCOPES: &[&str] = &[ + "openid", + "profile", + "email", + "offline_access", + "grok-cli:access", + "api:access", + "conversations:read", + "conversations:write", + "workspaces:read", + "workspaces:write", +]; +const XAI_FALLBACK_SCOPES: &[&str] = &[ + "openid", + "profile", + "email", + "offline_access", + "grok-cli:access", + "api:access", +]; +const OPENAI_SCOPES: &[&str] = &[ + "openid", + "profile", + "email", + "offline_access", + "resource.invoke", + "chatgpt.tokens.use.direct", +]; + +/// Whether a provider uses a fixed client ID or issues one during registration. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ClientIdPolicy { + /// The configured public client ID is used for every operation. + Fixed, + /// The provider returns a client ID during the first authorization; callers + /// must persist it and pass it back for later login and refresh operations. + IssuedOnRegistration, +} + +/// Auth-specific OAuth endpoints and parameters for one provider. +/// +/// This type intentionally excludes inference URLs, request policies, and other +/// application-specific provider metadata. Use [`OAuthProviderConfig::xai`], +/// [`OAuthProviderConfig::openai`], or [`OAuthProviderConfig::custom`] to +/// construct a validated profile. +#[derive(Clone)] +pub struct OAuthProviderConfig { + pub(crate) display_name: String, + pub(crate) issuer: String, + pub(crate) authorization_endpoint: String, + pub(crate) token_endpoint: String, + pub(crate) device_authorization_endpoint: Option, + pub(crate) userinfo_endpoint: Option, + pub(crate) revocation_endpoint: Option, + pub(crate) callback_path: String, + pub(crate) client_id: String, + pub(crate) client_id_policy: ClientIdPolicy, + pub(crate) scopes: Vec, + pub(crate) authorization_parameters: Vec<(String, String)>, + pub(crate) registration_parameters: Vec<(String, String)>, + pub(crate) token_parameters: Vec<(String, String)>, + pub(crate) device_parameters: Vec<(String, String)>, + pub(crate) trusted_device_hosts: Vec, + pub(crate) xai_referrer_fallback: Option, +} + +impl fmt::Debug for OAuthProviderConfig { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("OAuthProviderConfig") + .field("display_name", &self.display_name) + .field("issuer", &self.issuer) + .field("authorization_endpoint", &self.authorization_endpoint) + .field("token_endpoint", &self.token_endpoint) + .field( + "device_authorization_endpoint", + &self.device_authorization_endpoint, + ) + .field("userinfo_endpoint", &self.userinfo_endpoint) + .field("revocation_endpoint", &self.revocation_endpoint) + .field("callback_path", &self.callback_path) + .field("client_id", &"") + .field("client_id_policy", &self.client_id_policy) + .field("scopes", &self.scopes) + .field( + "authorization_parameter_names", + ¶meter_names(&self.authorization_parameters), + ) + .field( + "registration_parameter_names", + ¶meter_names(&self.registration_parameters), + ) + .field( + "token_parameter_names", + ¶meter_names(&self.token_parameters), + ) + .field( + "device_parameter_names", + ¶meter_names(&self.device_parameters), + ) + .field("trusted_device_hosts", &self.trusted_device_hosts) + .finish() + } +} + +fn parameter_names(parameters: &[(String, String)]) -> Vec<&str> { + parameters.iter().map(|(name, _)| name.as_str()).collect() +} + +impl OAuthProviderConfig { + /// The built-in x.ai OAuth profile with the full Grok CLI scope set. + /// + /// The profile sends `referrer=eggpass`, as Eggpass does. If x.ai returns a + /// client-configuration OAuth error, applications may start a new + /// authorization transaction with [`Self::xai_compatibility_fallback`]; + /// token exchanges and refreshes are never automatically retried. + pub fn xai() -> Self { + Self::xai_builder(false) + .build() + .expect("built-in x.ai profile is valid") + } + + /// The x.ai fallback profile used when a provider rejects the primary + /// referrer or full scope set. It uses `referrer=grok-build` and the shorter + /// reference-client scope set. Start a new user authorization with it; do + /// not retry an authorization-code exchange or refresh request. + pub fn xai_compatibility_fallback() -> Self { + Self::xai_builder(true) + .build() + .expect("built-in x.ai fallback profile is valid") + } + + fn xai_builder(fallback: bool) -> OAuthProviderConfigBuilder { + let scopes = if fallback { + XAI_FALLBACK_SCOPES + } else { + XAI_SCOPES + }; + let referrer = if fallback { "grok-build" } else { "eggpass" }; + OAuthProviderConfigBuilder::new("x.ai", XAI_ISSUER, XAI_CLIENT_ID) + .authorization_endpoint(format!("{XAI_ISSUER}/oauth2/authorize")) + .token_endpoint(format!("{XAI_ISSUER}/oauth2/token")) + .device_authorization_endpoint(format!("{XAI_ISSUER}/oauth2/device/code")) + .userinfo_endpoint(format!("{XAI_ISSUER}/oauth2/userinfo")) + .revocation_endpoint(format!("{XAI_ISSUER}/oauth2/revoke")) + .callback_path("/callback") + .scopes(scopes.iter().copied()) + .authorization_parameter("referrer", referrer) + .device_parameter("referrer", referrer) + .trusted_device_host("accounts.x.ai") + .trusted_device_host("auth.x.ai") + .trusted_device_host("x.ai") + .xai_referrer_fallback(if fallback { "eggpass" } else { "grok-build" }) + } + + /// The built-in Sign in with ChatGPT for Open Source profile. + /// + /// OpenAI issues a client ID during the first registration. Save the + /// callback's issued ID in the returned [`Credentials`] and pass it to the + /// next authorization/refresh call. The built-in registration hint is + /// `eggpass`; callers may build a custom profile to use another hint. + pub fn openai() -> Self { + Self::openai_builder(None) + .build() + .expect("built-in OpenAI profile is valid") + } + + /// OpenAI's profile with a caller-owned, stable host identifier. + pub fn openai_with_host_id(host_id: impl Into) -> Result { + Self::openai_builder(Some(host_id.into())).build() + } + + fn openai_builder(host_id: Option) -> OAuthProviderConfigBuilder { + let mut builder = + OAuthProviderConfigBuilder::new("OpenAI", OPENAI_ISSUER, OPENAI_ENTRY_CLIENT_ID) + .authorization_endpoint(format!("{OPENAI_ISSUER}/api/accounts/authorize")) + .token_endpoint(format!("{OPENAI_ISSUER}/api/accounts/oauth/token")) + .userinfo_endpoint(format!("{OPENAI_ISSUER}/api/accounts/oauth/userinfo")) + .revocation_endpoint(format!("{OPENAI_ISSUER}/api/accounts/oauth/revoke")) + .callback_path("/auth/callback") + .client_id_policy(ClientIdPolicy::IssuedOnRegistration) + .scopes(OPENAI_SCOPES.iter().copied()) + .authorization_parameter("resource", OPENAI_RESOURCE) + .registration_parameter("agent_name_hint", "eggpass") + .token_parameter("resource", OPENAI_RESOURCE); + if let Some(host_id) = host_id { + builder = builder.authorization_parameter("ext_agent_host_id", host_id); + } + builder + } + + /// Start a custom OAuth profile. Set the absolute authorization and token + /// endpoint URLs and add only the optional endpoints/parameters the + /// provider supports, then call [`OAuthProviderConfigBuilder::build`]. + pub fn custom( + display_name: impl Into, + issuer: impl Into, + client_id: impl Into, + ) -> OAuthProviderConfigBuilder { + OAuthProviderConfigBuilder::new(display_name, issuer, client_id) + } + + /// Provider display name, safe to show in UI. + pub fn display_name(&self) -> &str { + &self.display_name + } + + /// The issuer associated with credentials from this profile. + pub fn issuer(&self) -> &str { + &self.issuer + } + + /// The configured callback path. + pub fn callback_path(&self) -> &str { + &self.callback_path + } + + /// The configured client ID to use before a provider-issued ID is stored. + pub fn entry_client_id(&self) -> &str { + &self.client_id + } + + /// How this provider assigns client IDs. + pub fn client_id_policy(&self) -> ClientIdPolicy { + self.client_id_policy + } + + /// The scopes requested by this profile. + pub fn scopes(&self) -> &[String] { + &self.scopes + } + + /// Return a profile with a different client ID, useful for a caller-owned + /// provider registration or a changed public client ID. + pub fn with_client_id(mut self, client_id: impl Into) -> Result { + let client_id = client_id.into(); + if client_id.trim().is_empty() { + return Err(Error::InvalidConfiguration("client ID must not be empty")); + } + self.client_id = client_id; + Ok(self) + } + + /// Add or replace a non-secret authorization parameter. Existing values + /// with the same name are replaced. + pub fn with_authorization_parameter( + mut self, + name: impl Into, + value: impl Into, + ) -> Result { + insert_parameter( + &mut self.authorization_parameters, + name.into(), + value.into(), + )?; + Ok(self) + } + + /// Add or replace a non-secret registration-only authorization parameter. + pub fn with_registration_parameter( + mut self, + name: impl Into, + value: impl Into, + ) -> Result { + insert_parameter(&mut self.registration_parameters, name.into(), value.into())?; + Ok(self) + } + + /// Add or replace a non-secret parameter sent with every token request. + pub fn with_token_parameter( + mut self, + name: impl Into, + value: impl Into, + ) -> Result { + insert_parameter(&mut self.token_parameters, name.into(), value.into())?; + Ok(self) + } +} + +/// Builder for an [`OAuthProviderConfig`]. +/// +/// Endpoint URLs must be HTTPS, except for loopback HTTP endpoints used by +/// deterministic local tests. Callback paths are compared exactly when a +/// callback is completed. +pub struct OAuthProviderConfigBuilder { + config: OAuthProviderConfig, +} + +impl OAuthProviderConfigBuilder { + fn new( + display_name: impl Into, + issuer: impl Into, + client_id: impl Into, + ) -> Self { + Self { + config: OAuthProviderConfig { + display_name: display_name.into(), + issuer: issuer.into(), + authorization_endpoint: String::new(), + token_endpoint: String::new(), + device_authorization_endpoint: None, + userinfo_endpoint: None, + revocation_endpoint: None, + callback_path: "/callback".to_string(), + client_id: client_id.into(), + client_id_policy: ClientIdPolicy::Fixed, + scopes: Vec::new(), + authorization_parameters: Vec::new(), + registration_parameters: Vec::new(), + token_parameters: Vec::new(), + device_parameters: Vec::new(), + trusted_device_hosts: Vec::new(), + xai_referrer_fallback: None, + }, + } + } + + pub fn authorization_endpoint(mut self, endpoint: impl Into) -> Self { + self.config.authorization_endpoint = endpoint.into(); + self + } + + pub fn token_endpoint(mut self, endpoint: impl Into) -> Self { + self.config.token_endpoint = endpoint.into(); + self + } + + pub fn device_authorization_endpoint(mut self, endpoint: impl Into) -> Self { + self.config.device_authorization_endpoint = Some(endpoint.into()); + self + } + + pub fn userinfo_endpoint(mut self, endpoint: impl Into) -> Self { + self.config.userinfo_endpoint = Some(endpoint.into()); + self + } + + pub fn revocation_endpoint(mut self, endpoint: impl Into) -> Self { + self.config.revocation_endpoint = Some(endpoint.into()); + self + } + + pub fn callback_path(mut self, path: impl Into) -> Self { + self.config.callback_path = path.into(); + self + } + + pub fn client_id_policy(mut self, policy: ClientIdPolicy) -> Self { + self.config.client_id_policy = policy; + self + } + + pub fn scopes(mut self, scopes: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.config.scopes = scopes.into_iter().map(Into::into).collect(); + self + } + + pub fn authorization_parameter( + mut self, + name: impl Into, + value: impl Into, + ) -> Self { + let _ = insert_parameter( + &mut self.config.authorization_parameters, + name.into(), + value.into(), + ); + self + } + + pub fn registration_parameter( + mut self, + name: impl Into, + value: impl Into, + ) -> Self { + let _ = insert_parameter( + &mut self.config.registration_parameters, + name.into(), + value.into(), + ); + self + } + + pub fn token_parameter(mut self, name: impl Into, value: impl Into) -> Self { + let _ = insert_parameter(&mut self.config.token_parameters, name.into(), value.into()); + self + } + + pub fn device_parameter(mut self, name: impl Into, value: impl Into) -> Self { + let _ = insert_parameter( + &mut self.config.device_parameters, + name.into(), + value.into(), + ); + self + } + + pub fn trusted_device_host(mut self, host: impl Into) -> Self { + self.config + .trusted_device_hosts + .push(host.into().to_ascii_lowercase()); + self + } + + fn xai_referrer_fallback(mut self, value: impl Into) -> Self { + self.config.xai_referrer_fallback = Some(value.into()); + self + } + + /// Validate endpoint URLs, callback path, client ID, and OAuth parameters. + pub fn build(mut self) -> Result { + if self.config.display_name.trim().is_empty() { + return Err(Error::InvalidConfiguration( + "provider display name must not be empty", + )); + } + if self.config.client_id.trim().is_empty() { + return Err(Error::InvalidConfiguration("client ID must not be empty")); + } + validate_endpoint(&self.config.issuer, "issuer")?; + validate_endpoint( + &self.config.authorization_endpoint, + "authorization endpoint", + )?; + validate_endpoint(&self.config.token_endpoint, "token endpoint")?; + for (endpoint, name) in [ + ( + self.config.device_authorization_endpoint.as_deref(), + "device endpoint", + ), + ( + self.config.userinfo_endpoint.as_deref(), + "userinfo endpoint", + ), + ( + self.config.revocation_endpoint.as_deref(), + "revocation endpoint", + ), + ] { + if let Some(endpoint) = endpoint { + validate_endpoint(endpoint, name)?; + } + } + validate_callback_path(&self.config.callback_path)?; + if self + .config + .scopes + .iter() + .any(|scope| scope.is_empty() || scope.chars().any(char::is_whitespace)) + { + return Err(Error::InvalidConfiguration( + "each OAuth scope must be a non-empty token", + )); + } + validate_parameters(&self.config.authorization_parameters)?; + validate_parameters(&self.config.registration_parameters)?; + validate_parameters(&self.config.token_parameters)?; + validate_parameters(&self.config.device_parameters)?; + for host in &self.config.trusted_device_hosts { + if host.is_empty() + || host.starts_with('.') + || host.ends_with('.') + || host.contains('/') + || host.contains(':') + || !host.is_ascii() + { + return Err(Error::InvalidConfiguration( + "trusted device hosts must be plain DNS hostnames", + )); + } + } + self.config.trusted_device_hosts.sort(); + self.config.trusted_device_hosts.dedup(); + Ok(self.config) + } +} + +fn validate_endpoint(value: &str, label: &'static str) -> Result<()> { + let url = url::Url::parse(value) + .map_err(|_| Error::InvalidConfiguration("OAuth endpoint URL is invalid"))?; + if !matches!(url.scheme(), "https" | "http") + || url.host_str().is_none() + || !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + { + return Err(Error::InvalidConfiguration(match label { + "issuer" => "issuer must be an HTTP(S) origin without credentials, query, or fragment", + _ => "OAuth endpoints must be HTTP(S) URLs without credentials, query, or fragment", + })); + } + if url.scheme() != "https" && !is_loopback_url(&url) { + return Err(Error::InvalidConfiguration( + "plain HTTP is permitted only for loopback OAuth endpoints", + )); + } + Ok(()) +} + +fn is_loopback_url(url: &url::Url) -> bool { + match url.host() { + Some(url::Host::Ipv4(address)) => address.is_loopback(), + Some(url::Host::Ipv6(address)) => address.is_loopback(), + Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"), + None => false, + } +} + +fn validate_callback_path(path: &str) -> Result<()> { + if !path.starts_with('/') + || path.starts_with("//") + || path.contains('?') + || path.contains('#') + || path.contains('\r') + || path.contains('\n') + { + return Err(Error::InvalidConfiguration( + "callback path must be an absolute path without query or fragment", + )); + } + Ok(()) +} + +fn validate_parameters(parameters: &[(String, String)]) -> Result<()> { + for (name, value) in parameters { + if name.is_empty() + || name.chars().any(|c| c.is_control()) + || value.chars().any(|c| c.is_control()) + { + return Err(Error::InvalidConfiguration( + "OAuth parameter names and values must not contain control characters", + )); + } + } + Ok(()) +} + +fn insert_parameter( + parameters: &mut Vec<(String, String)>, + name: String, + value: String, +) -> Result<()> { + if name.is_empty() + || name.chars().any(|c| c.is_control()) + || value.chars().any(|c| c.is_control()) + { + return Err(Error::InvalidConfiguration( + "OAuth parameter names and values must not contain control characters", + )); + } + if let Some((_, previous)) = parameters + .iter_mut() + .find(|(existing, _)| existing == &name) + { + *previous = value; + } else { + parameters.push((name, value)); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn xai_has_referrer_device_flow_and_trusted_hosts() { + let config = OAuthProviderConfig::xai(); + assert_eq!(config.client_id, XAI_CLIENT_ID); + assert_eq!( + config.device_authorization_endpoint.as_deref(), + Some("https://auth.x.ai/oauth2/device/code") + ); + assert!( + config + .trusted_device_hosts + .iter() + .any(|host| host == "accounts.x.ai") + ); + assert!( + config + .authorization_parameters + .contains(&("referrer".into(), "eggpass".into())) + ); + let fallback = OAuthProviderConfig::xai_compatibility_fallback(); + assert!( + fallback + .authorization_parameters + .contains(&("referrer".into(), "grok-build".into())) + ); + assert_eq!(fallback.scopes.len(), 6); + } + + #[test] + fn openai_registration_parameters_and_issued_id_policy_are_explicit() { + let config = OAuthProviderConfig::openai(); + assert_eq!( + config.client_id_policy, + ClientIdPolicy::IssuedOnRegistration + ); + assert!( + config + .authorization_parameters + .contains(&("resource".into(), OPENAI_RESOURCE.into())) + ); + assert!( + config + .token_parameters + .contains(&("resource".into(), OPENAI_RESOURCE.into())) + ); + assert!( + config + .registration_parameters + .contains(&("agent_name_hint".into(), "eggpass".into())) + ); + let with_host = OAuthProviderConfig::openai_with_host_id("urn:uuid:test").unwrap(); + assert!( + with_host + .authorization_parameters + .contains(&("ext_agent_host_id".into(), "urn:uuid:test".into())) + ); + } + + #[test] + fn custom_profiles_reject_plain_http_outside_loopback_and_invalid_callback_paths() { + let insecure = OAuthProviderConfig::custom("example", "https://issuer.example", "client") + .authorization_endpoint("http://issuer.example/authorize") + .token_endpoint("https://issuer.example/token") + .build(); + assert!(matches!(insecure, Err(Error::InvalidConfiguration(_)))); + + let invalid_path = + OAuthProviderConfig::custom("example", "https://issuer.example", "client") + .authorization_endpoint("https://issuer.example/authorize") + .token_endpoint("https://issuer.example/token") + .callback_path("/callback?wrong=1") + .build(); + assert!(matches!(invalid_path, Err(Error::InvalidConfiguration(_)))); + } + + #[test] + fn configuration_debug_redacts_client_and_parameter_values() { + let config = OAuthProviderConfig::xai(); + let debug = format!("{config:?}"); + assert!(!debug.contains(XAI_CLIENT_ID)); + assert!(!debug.contains("eggpass")); + assert!(debug.contains("referrer")); + } +} diff --git a/crates/eggpass-auth/src/token.rs b/crates/eggpass-auth/src/token.rs new file mode 100644 index 0000000..c13aaa9 --- /dev/null +++ b/crates/eggpass-auth/src/token.rs @@ -0,0 +1,538 @@ +use std::fmt; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::{Error, Result}; + +/// OAuth tokens returned by an authorization-code, device, or refresh grant. +/// +/// Secret fields are private and `Debug` redacts their values. Use the accessors +/// to pass tokens to the caller's storage or authenticated API client. +#[derive(Clone, Default)] +pub struct TokenSet { + pub(crate) access_token: String, + pub(crate) refresh_token: Option, + pub(crate) id_token: Option, + pub(crate) token_type: String, + pub(crate) scope: Option, + pub(crate) expires_at: Option, +} + +impl TokenSet { + pub(crate) fn from_json(value: &Value, now: i64) -> Result { + let access_token = value + .get("access_token") + .and_then(Value::as_str) + .filter(|token| !token.is_empty()) + .ok_or(Error::InvalidResponse("token response has no access_token"))? + .to_string(); + let refresh_token = optional_string(value, "refresh_token"); + let id_token = optional_string(value, "id_token"); + let token_type = value + .get("token_type") + .and_then(Value::as_str) + .filter(|token_type| !token_type.is_empty()) + .unwrap_or("Bearer") + .to_string(); + let scope = optional_string(value, "scope"); + + let expires_at = if let Some(expiry) = value.get("expires_in") { + let seconds = expiry.as_i64().ok_or(Error::InvalidResponse( + "token response expires_in is not an integer", + ))?; + if seconds < 0 { + return Err(Error::InvalidResponse( + "token response expires_in is negative", + )); + } + Some(now.checked_add(seconds).ok_or(Error::InvalidResponse( + "token response expiry is out of range", + ))?) + } else { + match value.get("expires_at") { + Some(Value::Number(number)) => number.as_i64(), + Some(Value::String(timestamp)) => parse_rfc3339_to_unix(timestamp), + _ => None, + } + }; + + Ok(Self { + access_token, + refresh_token, + id_token, + token_type, + scope, + expires_at, + }) + } + + /// Bearer access token. + pub fn access_token(&self) -> &str { + &self.access_token + } + + /// Refresh token, when the provider returned one. + pub fn refresh_token(&self) -> Option<&str> { + self.refresh_token.as_deref() + } + + /// OpenID Connect ID token, when the provider returned one. + pub fn id_token(&self) -> Option<&str> { + self.id_token.as_deref() + } + + /// Token type, normally `Bearer`. + pub fn token_type(&self) -> &str { + &self.token_type + } + + /// Granted scope string, when returned by the provider. + pub fn scope(&self) -> Option<&str> { + self.scope.as_deref() + } + + /// Absolute expiry in Unix seconds, when returned or derived from + /// `expires_in`. + pub fn expires_at(&self) -> Option { + self.expires_at + } +} + +impl fmt::Debug for TokenSet { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TokenSet") + .field("access_token", &"") + .field( + "refresh_token", + &self.refresh_token.as_ref().map(|_| ""), + ) + .field("id_token", &self.id_token.as_ref().map(|_| "")) + .field("token_type", &self.token_type) + .field("scope", &self.scope) + .field("expires_at", &self.expires_at) + .finish() + } +} + +/// Credentials to keep in caller-owned storage. +/// +/// The type is serializable for storage adapters, but its `Debug` output always +/// redacts token values. The library does not write it to disk or assume a +/// filesystem location. +#[derive(Clone, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Credentials { + #[serde(default)] + pub(crate) access_token: String, + #[serde(default)] + pub(crate) refresh_token: Option, + #[serde(default)] + pub(crate) id_token: Option, + #[serde(default = "default_token_type")] + pub(crate) token_type: String, + #[serde(default)] + pub(crate) scope: Option, + #[serde(default)] + pub(crate) client_id: String, + #[serde(default)] + pub(crate) issuer: String, + #[serde(default)] + pub(crate) expires_at: Option, + #[serde(default)] + pub(crate) obtained_at: i64, +} + +fn default_token_type() -> String { + "Bearer".to_string() +} + +impl Credentials { + pub(crate) fn from_tokens( + tokens: TokenSet, + client_id: String, + issuer: String, + obtained_at: i64, + ) -> Self { + Self { + access_token: tokens.access_token, + refresh_token: tokens.refresh_token, + id_token: tokens.id_token, + token_type: if tokens.token_type.is_empty() { + default_token_type() + } else { + tokens.token_type + }, + scope: tokens.scope, + client_id, + issuer, + expires_at: tokens.expires_at, + obtained_at, + } + } + + pub(crate) fn validate(&self) -> Result<()> { + if self.access_token.is_empty() { + return Err(Error::InvalidResponse( + "stored credentials have no access token", + )); + } + if self.client_id.is_empty() { + return Err(Error::InvalidResponse( + "stored credentials have no client ID", + )); + } + Ok(()) + } + + pub(crate) fn merged_refresh(&self, tokens: TokenSet, now: i64) -> Self { + Self { + access_token: tokens.access_token, + refresh_token: tokens.refresh_token.or_else(|| self.refresh_token.clone()), + id_token: tokens.id_token.or_else(|| self.id_token.clone()), + token_type: if tokens.token_type.is_empty() { + self.token_type.clone() + } else { + tokens.token_type + }, + scope: tokens.scope.or_else(|| self.scope.clone()), + client_id: self.client_id.clone(), + issuer: if self.issuer.is_empty() { + String::new() + } else { + self.issuer.clone() + }, + expires_at: tokens.expires_at, + obtained_at: now, + } + } + + /// Access token for authenticated requests. + pub fn access_token(&self) -> &str { + &self.access_token + } + + /// Refresh token, when available. + pub fn refresh_token(&self) -> Option<&str> { + self.refresh_token.as_deref() + } + + /// ID token, when available. + pub fn id_token(&self) -> Option<&str> { + self.id_token.as_deref() + } + + /// Token type, normally `Bearer`. + pub fn token_type(&self) -> &str { + &self.token_type + } + + /// Granted scopes. + pub fn scope(&self) -> Option<&str> { + self.scope.as_deref() + } + + /// The client ID to reuse for refresh and future authorizations. + pub fn client_id(&self) -> &str { + &self.client_id + } + + /// Issuer associated with these credentials. + pub fn issuer(&self) -> &str { + &self.issuer + } + + /// Absolute expiry in Unix seconds, when known. + pub fn expires_at(&self) -> Option { + self.expires_at + } + + /// Unix time when these credentials were obtained. + pub fn obtained_at(&self) -> i64 { + self.obtained_at + } + + /// Whether the access token remains fresh after the requested refresh skew. + pub fn is_fresh(&self, now: i64, skew_seconds: i64) -> bool { + let fallback_expiry = self.obtained_at.saturating_add(30 * 86_400); + now.saturating_add(skew_seconds.max(0)) < self.expires_at.unwrap_or(fallback_expiry) + } + + /// Unix seconds since the system epoch. Returns zero if the system clock is + /// before the Unix epoch. + pub fn now_unix() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_secs().min(i64::MAX as u64) as i64) + .unwrap_or_default() + } +} + +impl fmt::Debug for Credentials { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Credentials") + .field("access_token", &"") + .field( + "refresh_token", + &self.refresh_token.as_ref().map(|_| ""), + ) + .field("id_token", &self.id_token.as_ref().map(|_| "")) + .field("token_type", &self.token_type) + .field("scope", &self.scope) + .field("client_id", &"") + .field("issuer", &self.issuer) + .field("expires_at", &self.expires_at) + .field("obtained_at", &self.obtained_at) + .finish() + } +} + +fn parse_rfc3339_to_unix(value: &str) -> Option { + let (local, offset_seconds) = + if let Some(local) = value.strip_suffix('Z').or_else(|| value.strip_suffix('z')) { + (local, 0) + } else { + let offset_index = value + .char_indices() + .skip(10) + .find_map(|(index, character)| matches!(character, '+' | '-').then_some(index))?; + let (local, offset) = value.split_at(offset_index); + (local, parse_timezone_offset(offset)?) + }; + let (date, time) = local.split_once('T').or_else(|| local.split_once('t'))?; + if date.len() != 10 { + return None; + } + let mut date_parts = date.split('-'); + let year = parse_decimal(date_parts.next()?, 4)?; + let month = parse_decimal(date_parts.next()?, 2)?; + let day = parse_decimal(date_parts.next()?, 2)?; + if date_parts.next().is_some() || !(1..=12).contains(&month) { + return None; + } + let leap_year = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + let days_in_month = match month { + 2 if leap_year => 29, + 2 => 28, + 4 | 6 | 9 | 11 => 30, + _ => 31, + }; + if !(1..=days_in_month).contains(&day) { + return None; + } + + let (time, fraction) = match time.split_once('.') { + Some((time, fraction)) => { + if fraction.is_empty() || !fraction.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + (time, Some(fraction)) + } + None => (time, None), + }; + let _ = fraction; + if time.len() != 8 + || time.as_bytes().get(2) != Some(&b':') + || time.as_bytes().get(5) != Some(&b':') + { + return None; + } + let hour = parse_decimal(&time[0..2], 2)?; + let minute = parse_decimal(&time[3..5], 2)?; + let second = parse_decimal(&time[6..8], 2)?; + if hour > 23 || minute > 59 || second > 60 { + return None; + } + + let adjusted_year = year - i64::from(month <= 2); + let era = adjusted_year.div_euclid(400); + let year_of_era = adjusted_year - era * 400; + let month_prime = month + if month > 2 { -3 } else { 9 }; + let day_of_year = (153 * month_prime + 2) / 5 + day - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + let days = era * 146_097 + day_of_era - 719_468; + days.checked_mul(86_400)? + .checked_add(hour * 3_600 + minute * 60 + second)? + .checked_sub(offset_seconds) +} + +fn parse_timezone_offset(value: &str) -> Option { + let (sign, offset) = match value.as_bytes().first()? { + b'+' => (1, &value[1..]), + b'-' => (-1, &value[1..]), + _ => return None, + }; + if offset.len() != 5 || offset.as_bytes().get(2) != Some(&b':') { + return None; + } + let hours = parse_decimal(&offset[0..2], 2)?; + let minutes = parse_decimal(&offset[3..5], 2)?; + if hours > 23 || minutes > 59 { + return None; + } + Some(sign * (hours * 3_600 + minutes * 60)) +} + +fn parse_decimal(value: &str, digits: usize) -> Option { + if value.len() != digits || !value.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + value.parse().ok() +} + +fn optional_string(value: &Value, key: &str) -> Option { + value + .get(key) + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .map(str::to_owned) +} + +/// Non-secret account details returned by an OpenID user-info endpoint. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct UserInfo { + /// Provider account identifier, when available. + pub user_id: Option, + /// Account email, when available. + pub email: Option, +} + +/// Data returned by a device authorization endpoint. +#[derive(Clone)] +pub struct DeviceCode { + pub(crate) device_code: String, + pub(crate) user_code: String, + pub(crate) verification_uri: String, + pub(crate) verification_uri_complete: Option, + pub(crate) expires_in: std::time::Duration, + pub(crate) expires_at: tokio::time::Instant, + pub(crate) interval: std::time::Duration, +} + +impl DeviceCode { + /// Secret device code used only for token polling. + pub fn device_code(&self) -> &str { + &self.device_code + } + + /// Short code the user enters at the verification page. + pub fn user_code(&self) -> &str { + &self.user_code + } + + /// Verification page URL. + pub fn verification_uri(&self) -> &str { + &self.verification_uri + } + + /// Verification page URL with the user code pre-filled, when provided. + pub fn verification_uri_complete(&self) -> Option<&str> { + self.verification_uri_complete.as_deref() + } + + /// Server-provided authorization lifetime. The library does not increase + /// short values to a local minimum. + pub fn expires_in(&self) -> std::time::Duration { + self.expires_in + } + + /// Initial server-provided polling interval. + pub fn interval(&self) -> std::time::Duration { + self.interval + } +} + +impl fmt::Debug for DeviceCode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DeviceCode") + .field("device_code", &"") + .field("user_code", &"") + .field("verification_uri", &"") + .field( + "verification_uri_complete", + &self + .verification_uri_complete + .as_ref() + .map(|_| ""), + ) + .field("expires_in", &self.expires_in) + .field("interval", &self.interval) + .finish() + } +} + +/// Result of one device-code poll. +#[derive(Debug)] +#[non_exhaustive] +pub enum DevicePoll { + /// The user has not approved the request yet. + Pending, + /// The server asked the client to increase its interval by five seconds. + SlowDown, + /// The user denied the request. + Denied, + /// The device grant expired. + Expired, + /// Authorization succeeded. + Complete(TokenSet), +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn token_response_parses_rfc3339_expiry_and_numeric_expiry() { + let rfc3339 = TokenSet::from_json( + &serde_json::json!({ + "access_token": "access", + "expires_at": "2026-12-13T05:12:18Z" + }), + 0, + ) + .unwrap(); + assert_eq!(rfc3339.expires_at(), Some(1_797_138_738)); + + let offset = TokenSet::from_json( + &serde_json::json!({ + "access_token": "access", + "expires_at": "1970-01-01T01:00:00+01:00" + }), + 0, + ) + .unwrap(); + assert_eq!(offset.expires_at(), Some(0)); + + let numeric = TokenSet::from_json( + &serde_json::json!({"access_token": "access", "expires_at": 1234}), + 0, + ) + .unwrap(); + assert_eq!(numeric.expires_at(), Some(1234)); + } + + #[test] + fn credential_freshness_respects_the_requested_refresh_skew() { + let credentials = Credentials { + expires_at: Some(1_000), + obtained_at: 0, + ..Credentials::default() + }; + assert!(credentials.is_fresh(699, 300)); + assert!(!credentials.is_fresh(700, 300)); + } + + #[test] + fn malformed_rfc3339_expiry_is_ignored_without_panicking() { + let tokens = TokenSet::from_json( + &serde_json::json!({ + "access_token": "access", + "expires_at": "2026-99-99T25:61:61Z" + }), + 0, + ) + .unwrap(); + assert_eq!(tokens.expires_at(), None); + } +} diff --git a/crates/eggpass-auth/tests/oauth_stub.rs b/crates/eggpass-auth/tests/oauth_stub.rs new file mode 100644 index 0000000..67bc3e3 --- /dev/null +++ b/crates/eggpass-auth/tests/oauth_stub.rs @@ -0,0 +1,513 @@ +use std::future::Future; +use std::sync::Arc; +use std::time::Duration; + +use eggfetch_core::Client; +use eggfetch_core::timeout::Timeout; +use eggpass_auth::{ + ClientIdPolicy, ClientOptions, CredentialStore, Credentials, Error, OAuthClient, + OAuthProviderConfig, StorageError, TokenManager, +}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::task::JoinHandle; + +async fn stub_once(status: u16, body: &'static [u8]) -> (String, JoinHandle>) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let task = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let request = read_request(&mut stream).await; + write_response(&mut stream, status, body).await; + request + }); + (format!("http://{address}"), task) +} + +async fn read_request(stream: &mut TcpStream) -> Vec { + let mut request = Vec::new(); + let mut chunk = [0u8; 1024]; + let header_end; + loop { + let read = stream.read(&mut chunk).await.unwrap(); + assert!(read > 0, "connection closed before request headers"); + request.extend_from_slice(&chunk[..read]); + if let Some(index) = request.windows(4).position(|window| window == b"\r\n\r\n") { + header_end = index + 4; + break; + } + } + let headers = String::from_utf8_lossy(&request[..header_end]); + let content_length = headers + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().unwrap()) + }) + .unwrap_or(0); + while request.len() < header_end + content_length { + let read = stream.read(&mut chunk).await.unwrap(); + assert!(read > 0, "connection closed before request body"); + request.extend_from_slice(&chunk[..read]); + } + request +} + +async fn write_response(stream: &mut TcpStream, status: u16, body: &[u8]) { + let reason = match status { + 200 => "OK", + 302 => "Found", + 400 => "Bad Request", + 503 => "Service Unavailable", + _ => "Test Response", + }; + let response = format!( + "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + stream.write_all(response.as_bytes()).await.unwrap(); + stream.write_all(body).await.unwrap(); + stream.flush().await.unwrap(); +} + +fn oauth(base: &str, client: Client) -> OAuthClient { + let config = OAuthProviderConfig::custom("stub", base, "public-client") + .authorization_endpoint(format!("{base}/authorize")) + .token_endpoint(format!("{base}/token")) + .device_authorization_endpoint(format!("{base}/device")) + .userinfo_endpoint(format!("{base}/userinfo")) + .revocation_endpoint(format!("{base}/revoke")) + .callback_path("/callback") + .scopes(["offline_access"]) + .trusted_device_host("accounts.test") + .build() + .unwrap(); + OAuthClient::new(client, config) +} + +fn options(total: Duration, body_limit: usize) -> ClientOptions { + ClientOptions { + timeout: Timeout { + pool: Some(Duration::from_secs(1)), + connect: Some(Duration::from_secs(1)), + write: Some(Duration::from_secs(1)), + read: Some(Duration::from_secs(1)), + total: Some(total), + }, + max_response_body_bytes: body_limit, + } +} + +#[tokio::test] +async fn real_eggfetch_posts_encoded_authorization_code_without_leaking_bearer_auth() { + let (base, server) = stub_once( + 200, + br#"{"access_token":"access-secret","refresh_token":"refresh-secret","token_type":"Bearer","expires_in":3600}"#, + ) + .await; + let oauth = oauth(&base, Client::new()) + .with_options(options(Duration::from_secs(2), 4096)) + .unwrap(); + let credentials = oauth + .exchange_authorization_code( + "code /+&", + "http://127.0.0.1:43123/callback", + "verifier-123456789", + None, + ) + .await + .unwrap(); + let request = String::from_utf8(server.await.unwrap()).unwrap(); + assert!(request.starts_with("POST /token HTTP/1.1"), "{request}"); + assert!( + request + .to_ascii_lowercase() + .contains("content-type: application/x-www-form-urlencoded") + ); + assert!(!request.to_ascii_lowercase().contains("authorization:")); + let body = request.split("\r\n\r\n").nth(1).unwrap(); + let parameters: std::collections::HashMap<_, _> = url::form_urlencoded::parse(body.as_bytes()) + .into_owned() + .collect(); + assert_eq!(parameters.get("code").map(String::as_str), Some("code /+&")); + assert_eq!( + parameters.get("code_verifier").map(String::as_str), + Some("verifier-123456789") + ); + assert_eq!( + parameters.get("grant_type").map(String::as_str), + Some("authorization_code") + ); + assert_eq!(credentials.access_token(), "access-secret"); + assert_eq!(credentials.refresh_token(), Some("refresh-secret")); + assert!(!format!("{credentials:?}").contains("access-secret")); +} + +#[tokio::test] +async fn revocation_and_userinfo_use_their_configured_endpoints() { + let (base, server) = stub_once(200, b"{}").await; + let revoker = oauth(&base, Client::new()); + revoker.revoke("refresh-secret", None).await.unwrap(); + let request = String::from_utf8(server.await.unwrap()).unwrap(); + assert!(request.starts_with("POST /revoke HTTP/1.1")); + assert!(!request.to_ascii_lowercase().contains("authorization:")); + let body = request.split("\r\n\r\n").nth(1).unwrap(); + let form: std::collections::HashMap<_, _> = url::form_urlencoded::parse(body.as_bytes()) + .into_owned() + .collect(); + assert_eq!( + form.get("token").map(String::as_str), + Some("refresh-secret") + ); + assert_eq!( + form.get("token_type_hint").map(String::as_str), + Some("refresh_token") + ); + + let (base, server) = stub_once(200, br#"{"sub":"account-7","email":"a@example.test"}"#).await; + let oauth = oauth(&base, Client::new()); + let info = oauth.userinfo("access-secret").await.unwrap(); + let request = String::from_utf8(server.await.unwrap()).unwrap(); + assert!(request.starts_with("GET /userinfo HTTP/1.1")); + assert!( + request + .to_ascii_lowercase() + .contains("authorization: bearer access-secret") + ); + assert_eq!(info.user_id.as_deref(), Some("account-7")); + assert_eq!(info.email.as_deref(), Some("a@example.test")); +} + +#[tokio::test] +async fn device_code_request_and_poll_use_real_eggfetch_requests() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut first, _) = listener.accept().await.unwrap(); + let first_request = read_request(&mut first).await; + write_response( + &mut first, + 200, + br#"{"device_code":"device-secret","user_code":"human-code","verification_uri":"https://accounts.test/activate","verification_uri_complete":"https://accounts.test/activate?user_code=human-code","expires_in":15,"interval":1}"#, + ) + .await; + drop(first); + + let (mut second, _) = listener.accept().await.unwrap(); + let second_request = read_request(&mut second).await; + write_response( + &mut second, + 200, + br#"{"access_token":"device-access","expires_in":3600}"#, + ) + .await; + (first_request, second_request) + }); + + let base = format!("http://{address}"); + let oauth = oauth(&base, Client::new()); + let device = oauth.request_device_code().await.unwrap(); + assert_eq!(device.user_code(), "human-code"); + assert_eq!(device.verification_uri(), "https://accounts.test/activate"); + let debug = format!("{device:?}"); + assert!(!debug.contains("device-secret")); + assert!(!debug.contains("human-code")); + let credentials = oauth + .poll_device_authorization( + &device, + &tokio_util::sync::CancellationToken::new(), + Duration::from_secs(3), + ) + .await + .unwrap(); + assert_eq!(credentials.access_token(), "device-access"); + + let (first, second) = server.await.unwrap(); + let first = String::from_utf8(first).unwrap(); + assert!(first.starts_with("POST /device HTTP/1.1")); + let first_body = first.split("\r\n\r\n").nth(1).unwrap(); + let first_form: std::collections::HashMap<_, _> = + url::form_urlencoded::parse(first_body.as_bytes()) + .into_owned() + .collect(); + assert_eq!( + first_form.get("client_id").map(String::as_str), + Some("public-client") + ); + + let second = String::from_utf8(second).unwrap(); + assert!(second.starts_with("POST /token HTTP/1.1")); + let second_body = second.split("\r\n\r\n").nth(1).unwrap(); + let second_form: std::collections::HashMap<_, _> = + url::form_urlencoded::parse(second_body.as_bytes()) + .into_owned() + .collect(); + assert_eq!( + second_form.get("device_code").map(String::as_str), + Some("device-secret") + ); + assert_eq!( + second_form.get("grant_type").map(String::as_str), + Some("urn:ietf:params:oauth:grant-type:device_code") + ); +} + +#[tokio::test] +async fn issued_client_id_is_exchanged_and_reused_after_registration() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let request = read_request(&mut stream).await; + write_response( + &mut stream, + 200, + br#"{"access_token":"registered-access","expires_in":3600}"#, + ) + .await; + request + }); + + let base = format!("http://{address}"); + let profile = OAuthProviderConfig::custom("registered", &base, "entry-client") + .authorization_endpoint(format!("{base}/authorize")) + .token_endpoint(format!("{base}/token")) + .callback_path("/callback") + .client_id_policy(ClientIdPolicy::IssuedOnRegistration) + .registration_parameter("agent_name_hint", "consumer") + .build() + .unwrap(); + let oauth = OAuthClient::new(Client::new(), profile); + let redirect = format!("{base}/callback"); + let pending = oauth.begin_authorization(&redirect, None).unwrap(); + let authorization_url = url::Url::parse(pending.authorization_url()).unwrap(); + let state = authorization_url + .query_pairs() + .find(|(key, _)| key == "state") + .map(|(_, value)| value.into_owned()) + .unwrap(); + let callback = + format!("{redirect}?code=registration-code&state={state}&client_id=issued-client"); + let credentials = oauth + .complete_authorization(pending, &callback) + .await + .unwrap(); + assert_eq!(credentials.client_id(), "issued-client"); + + let request = String::from_utf8(server.await.unwrap()).unwrap(); + assert!(request.starts_with("POST /token HTTP/1.1")); + let body = request.split("\r\n\r\n").nth(1).unwrap(); + let form: std::collections::HashMap<_, _> = url::form_urlencoded::parse(body.as_bytes()) + .into_owned() + .collect(); + assert_eq!( + form.get("client_id").map(String::as_str), + Some("issued-client") + ); + + let next = oauth + .begin_authorization(&redirect, Some(&credentials)) + .unwrap(); + let next_url = url::Url::parse(next.authorization_url()).unwrap(); + let next_values: std::collections::HashMap<_, _> = + next_url.query_pairs().into_owned().collect(); + assert_eq!( + next_values.get("client_id").map(String::as_str), + Some("issued-client") + ); + assert!(!next_values.contains_key("agent_name_hint")); +} + +#[tokio::test] +async fn non_json_error_does_not_escape_response_body() { + let (base, server) = stub_once(503, b"proxy diagnostic contains hidden-secret").await; + let oauth = oauth(&base, Client::new()); + let error = oauth + .refresh_token("refresh-secret", None) + .await + .unwrap_err(); + let request = server.await.unwrap(); + assert!(!request.is_empty()); + assert!(matches!(error, Error::HttpStatus { status: 503 })); + assert!(!error.to_string().contains("hidden-secret")); + assert!(!format!("{error:?}").contains("hidden-secret")); +} + +#[tokio::test] +async fn oauth_error_code_is_returned_without_description_or_body() { + let (base, server) = stub_once( + 400, + br#"{"error":"invalid_client","error_description":"hidden-secret details"}"#, + ) + .await; + let oauth = oauth(&base, Client::new()); + let error = oauth + .refresh_token("refresh-secret", None) + .await + .unwrap_err(); + let _ = server.await.unwrap(); + assert!(matches!(error, Error::OAuth { status: 400, .. })); + assert_eq!(error.oauth_code(), Some("invalid_client")); + assert!(!error.to_string().contains("hidden-secret")); + assert!(!format!("{error:?}").contains("hidden-secret")); +} + +#[tokio::test] +async fn decoded_body_limit_is_enforced_with_the_real_eggfetch_client() { + let (base, server) = stub_once( + 200, + b"{\"access_token\":\"this-response-is-over-the-limit\"}", + ) + .await; + let oauth = oauth(&base, Client::new()) + .with_options(options(Duration::from_secs(2), 16)) + .unwrap(); + let error = oauth + .refresh_token("refresh-secret", None) + .await + .unwrap_err(); + let _ = server.await.unwrap(); + assert!(matches!(error, Error::ResponseTooLarge)); +} + +#[tokio::test] +async fn request_deadline_is_normalized_without_transport_details() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let _ = read_request(&mut stream).await; + tokio::time::sleep(Duration::from_millis(250)).await; + let _ = write_response(&mut stream, 200, br#"{"access_token":"late"}"#).await; + }); + let oauth = oauth(&format!("http://{address}"), Client::new()) + .with_options(options(Duration::from_millis(50), 4096)) + .unwrap(); + let error = oauth + .refresh_token("refresh-secret", None) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout("HTTP request"))); + server.await.unwrap(); +} + +#[tokio::test] +async fn redirects_are_not_followed_even_for_a_caller_owned_client() { + let (base, server) = stub_once(302, br#"{"next":"/redirected"}"#).await; + let oauth = oauth(&base, Client::new()); + let error = oauth + .refresh_token("refresh-secret", None) + .await + .unwrap_err(); + let request = String::from_utf8(server.await.unwrap()).unwrap(); + assert!(request.starts_with("POST /token HTTP/1.1")); + assert!(matches!(error, Error::HttpStatus { status: 302 })); +} + +#[derive(Clone, Default)] +struct MemoryStore(Arc>>); + +impl CredentialStore for MemoryStore { + fn load(&self) -> impl Future, StorageError>> + Send { + let inner = self.0.clone(); + async move { Ok(inner.lock().await.clone()) } + } + + fn save( + &self, + credentials: Credentials, + ) -> impl Future> + Send { + let inner = self.0.clone(); + async move { + *inner.lock().await = Some(credentials); + Ok(()) + } + } + + fn clear(&self) -> impl Future> + Send { + let inner = self.0.clone(); + async move { + *inner.lock().await = None; + Ok(()) + } + } +} + +#[tokio::test] +async fn manager_coalesces_concurrent_refresh_and_retains_rotated_refresh_token() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let first = read_request(&mut stream).await; + write_response( + &mut stream, + 200, + br#"{"access_token":"fresh-access","expires_in":3600}"#, + ) + .await; + let second = tokio::time::timeout(Duration::from_millis(100), listener.accept()).await; + (first, second.is_ok()) + }); + + let base = format!("http://{address}"); + let mut profile = OAuthProviderConfig::custom("stub", &base, "public-client") + .authorization_endpoint(format!("{base}/authorize")) + .token_endpoint(format!("{base}/token")) + .callback_path("/callback") + .scopes(["offline_access"]) + .build() + .unwrap(); + profile = profile.with_client_id("public-client").unwrap(); + let client = OAuthClient::new(Client::new(), profile); + let store = MemoryStore::default(); + let stale: Credentials = serde_json::from_str( + r#"{ + "access_token":"stale-access", + "refresh_token":"preserved-refresh", + "id_token":null, + "token_type":"Bearer", + "scope":"offline_access", + "client_id":"public-client", + "issuer":"PLACEHOLDER_ISSUER", + "expires_at":0, + "obtained_at":0 + }"# + .replace("PLACEHOLDER_ISSUER", &base) + .as_str(), + ) + .unwrap(); + store.save(stale).await.unwrap(); + let manager = Arc::new(TokenManager::new(client, store.clone())); + + let mut tasks = tokio::task::JoinSet::new(); + for _ in 0..12 { + let manager = manager.clone(); + tasks.spawn(async move { manager.access_token().await }); + } + while let Some(result) = tasks.join_next().await { + assert_eq!(result.unwrap().unwrap(), "fresh-access"); + } + + let (request, saw_second_refresh) = server.await.unwrap(); + assert!(request.starts_with(b"POST /token HTTP/1.1")); + assert!( + !saw_second_refresh, + "manager issued more than one refresh request" + ); + let header_end = request + .windows(4) + .position(|window| window == b"\r\n\r\n") + .expect("request contains the end of headers"); + let body = &request[header_end + 4..]; + let form: std::collections::HashMap<_, _> = + url::form_urlencoded::parse(body).into_owned().collect(); + assert_eq!( + form.get("refresh_token").map(String::as_str), + Some("preserved-refresh") + ); + let stored = store.load().await.unwrap().unwrap(); + assert_eq!(stored.access_token(), "fresh-access"); + assert_eq!(stored.refresh_token(), Some("preserved-refresh")); +} diff --git a/docs/README.md b/docs/README.md index b45cbe2..dcfc532 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,3 +19,4 @@ | Understand routing and security | [how-it-works.md](how-it-works.md) | | Fix an error | [troubleshooting.md](troubleshooting.md) | | Update eggpass | [updating.md](updating.md) | +| Use the Python `eggpass-auth` library | [Python auth guide](https://github.com/eggstack/eggpass/blob/main/python/eggpass-auth/README.md) | diff --git a/docs/commands.md b/docs/commands.md index a714334..7f227f8 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -66,13 +66,13 @@ eggpass usage --provider xai # query one provider eggpass usage --json # machine-readable report ``` -Queries provider usage directly, without needing the daemon. By default it queries only providers enabled in configuration. `--provider` can select one enabled provider; selecting a disabled provider, or running the command when none are enabled, returns an actionable configuration error. Human-readable output shows the percentage and bar for the allowance left, plus each available reset time and countdown; JSON preserves the provider-reported fields. On the default xAI `api` upstream, the reported consumer-subscription quota is separate from inference requests, which are billed to the xAI API tier. The report's caption reflects the configured upstream. If quota is unavailable, the report may include the latest inference HTTP status kept by the daemon in memory. That endpoint reports only per-provider client-facing HTTP status codes, not prompts or response bodies. +`eggpass usage` first prefers the running daemon's in-memory usage report, including a stale last-successful report when marked stale. It sends a separate private runtime credential as a Bearer token; the credential is generated and rotated on daemon start, stored as `usage.key` in the resolved data directory (not config or `keys.json`), and removed on graceful shutdown only if it still matches. It authorizes only a bodyless `GET /v1/usage`, is not a regular client key, and cannot satisfy the daemon's startup key requirement. If the daemon is stopped or stale, the credential file is missing or unreadable, or the endpoint returns `404`, the CLI uses the existing direct provider collectors. A connection failure falls back only after a state recheck confirms the daemon is stopped or stale. `202`, `503`, `504`, authentication failures, malformed success responses, and connection failures while the daemon still appears running are surfaced instead of bypassing the daemon. A stale-cache warning goes to stderr only, so JSON stdout remains machine-readable. Usage reports contain sensitive account data. By default it queries only providers enabled in configuration. `--provider` can select one enabled provider; selecting a disabled provider, or running the command when none are enabled, returns an actionable configuration error. Human-readable output shows the percentage and bar for the allowance left, plus each available reset time and countdown; JSON preserves the provider-reported fields. On the default xAI `api` upstream, the reported consumer-subscription quota is separate from inference requests, which are billed to the xAI API tier. The report's caption reflects the configured upstream. If quota is unavailable, the report may include the latest inference HTTP status kept by the daemon in memory. That endpoint reports only per-provider client-facing HTTP status codes, not prompts or response bodies. **Exit codes:** `0` if at least one provider is signed in and not every selected provider failed operationally, `1` if every selected provider failed operationally, `2` if none is signed in. ### Authenticated daemon endpoint: GET /v1/usage -The daemon also serves `GET /v1/usage` for clients that need a usage report over HTTP. Send the configured or issued Eggpass client key in `Authorization: Bearer ` or `X-Api-Key: `. The response body uses the same `{"providers":[...]}` JSON structure as `eggpass usage --json`; it includes only enabled providers. If every provider is disabled, the endpoint returns a completed empty list. OpenAI/ChatGPT usage is queried only when that provider is enabled; the optional Codex app-server result may describe a different account from Eggpass's inference credential. +The daemon also serves `GET /v1/usage` for clients that need a usage report over HTTP. A configured or issued regular client key retains its normal full-route access and accepted transports, including `Authorization: Bearer ` and `X-Api-Key: `. The CLI's separate runtime credential is sent only as `Authorization: Bearer ` and is accepted only for a bodyless `GET /v1/usage`; it is not listed or stored with regular keys. The response body uses the same `{"providers":[...]}` JSON structure as `eggpass usage --json`; it includes only enabled providers. If every provider is disabled, the endpoint returns a completed empty list. OpenAI/ChatGPT usage is queried only when that provider is enabled; the optional Codex app-server result may describe a different account from Eggpass's inference credential. A complete report is retained only in daemon memory for 600 seconds from completion. Cache hits do not contact providers. A cold or expired request starts one shared refresh and its initiating client waits at most 30 seconds; if still running, that client receives `504` and the refresh continues. Other requests while it is active receive `202` with `Retry-After`. Timed-out providers alone are retried, for at most three retries after the initial attempt, spaced 5, 15, and 30 seconds apart. xAI usage HTTP requests have bounded 15-second request/body timeouts (and a 5-second connect cap); OAuth refresh requests have a 60-second total deadline, and the optional local Codex session has an 8-second deadline. @@ -153,7 +153,7 @@ eggpass croncheck ```sh eggpass update # install the latest release -eggpass update 0.2.0 # install an exact version +eggpass update 0.1.0 # install an exact version eggpass update --check # report the plan without changing files ``` diff --git a/docs/configuration.md b/docs/configuration.md index 5b8d3ed..1bc0463 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -74,9 +74,9 @@ The advanced `[oauth.xai]` settings are `client_id`, `issuer`, `scopes`, and `re A client key is required to start the server, including when it listens only on loopback. Use `eggpass key add` to create a numbered, revocable key, or set `api_key` for one static key. The static key is readable in the config. Issued keys are shown once and stored as salted hashes. Clients may send either as `Authorization: Bearer ` or `X-Api-Key: `. -The server listens on loopback by default. Binding to a non-loopback address exposes the proxy and the provider accounts it can use to the network. A key is required for that bind. The `GET /health` and `GET /v1/last-inference` probes are unauthenticated: health returns a JSON object with `status`, `service`, and a version string; last-inference returns only per-provider client-facing HTTP status codes. `GET /v1/usage` is not an unauthenticated probe: it requires a valid Eggpass client key like every other data endpoint. It returns quota data for enabled providers, so do not expose it without protecting the server. +The server listens on loopback by default. Binding to a non-loopback address exposes the proxy and the provider accounts it can use to the network. A key is required for that bind. The `GET /health` and `GET /v1/last-inference` probes are unauthenticated: health returns a JSON object with `status`, `service`, and a version string; last-inference returns only per-provider client-facing HTTP status codes. `GET /v1/usage` is not an unauthenticated probe: it accepts a regular client key with its normal scope, or the daemon's separate usage-only runtime credential as an `Authorization: Bearer` token on the exact bodyless GET. The runtime credential is generated for each daemon start and stored in `usage.key` under the resolved data directory; it is not a configured or issued client key and cannot replace the regular key required at startup. Usage reports are sensitive account data. It returns quota data for enabled providers, so do not expose it without protecting the server. -Eggpass runs locally, but inference requests are sent to the provider selected by routing. Prompts and request content are transmitted to xAI or ChatGPT for inference; they do not stay on this machine. `eggpass usage` also contacts providers directly to query usage, and `eggpass status` may contact them to count available models. +Eggpass runs locally, but inference requests are sent to the provider selected by routing. Prompts and request content are transmitted to xAI or ChatGPT for inference; they do not stay on this machine. `eggpass usage` prefers the running daemon's cached report and directly queries providers only when the daemon is stopped or stale, the runtime usage credential file is missing or unreadable, or an older daemon returns `404`. A rejected credential or daemon refresh/cooldown status is surfaced rather than bypassed. `eggpass status` may contact providers to count available models. Use `eggpass host` and `eggpass port` to change a live server's address. These commands update the config and restart the server when needed. Manual config edits take effect when the server next starts. See [commands.md](commands.md) for the commands and an SSH tunnel example. @@ -86,12 +86,13 @@ Use `eggpass host` and `eggpass port` to change a live server's address. These c | --- | --- | | `config.toml` | Settings, possibly including the readable `api_key`. Normally mode `0600`. | | `keys.json` | Issued-key numbers, labels, visible prefixes, salts, and hashes. It does not contain the full keys. Mode `0600`. | +| `usage.key` | Random daemon runtime Bearer credential, restricted to bodyless `GET /v1/usage`; rotated at each start and removed on graceful shutdown when it still matches. Never a regular client key. | | `credentials/xai.json` | xAI OAuth credentials, including tokens. Mode `0600`. | | `credentials/openai.json` | ChatGPT OAuth credentials, including tokens. Mode `0600`. | | `eggpass.pid` | Daemon process ID and the address and port it serves. | | `eggpass.log` | Daemon log. | -The data directory and `credentials` directory are restricted to mode `0700`; credential and key files use `0600` on Unix-like systems. Keep any custom config file containing `api_key` private too. +The data directory and `credentials` directory are restricted to mode `0700`; credential and key files use `0600` on Unix-like systems. On Windows, daemon startup applies protected current-user-only ACLs to the data directory and `usage.key`, and fails closed if that protection cannot be established. A crash or forced termination may leave a stale `usage.key`; the next daemon start replaces it before serving. Keep any custom config file containing `api_key` private too. With the default data directory, xAI credentials may be read from `~/.grok/auth.json` when `credentials/xai.json` is absent. If an imported refresh token is rotated, eggpass stores its replacement in its own credential file; the Grok CLI's original file is not updated. Setting `EGGPASS_HOME` disables this import to keep the relocated installation isolated. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index acca352..7d4cbe8 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -37,7 +37,11 @@ clients. Client keys are separate from provider credentials. `eggpass key add` shows a key once and stores only a salted hash. The key is checked locally on each -request. Add or revoke issued keys without restarting the server. +request. Add or revoke issued keys without restarting the server. The CLI's +usage request uses a separate private runtime Bearer credential, generated for +each daemon start and accepted only for a bodyless `GET /v1/usage`. It is not +stored in config or the regular key store, cannot authorize inference or other +routes, and cannot satisfy the regular-key startup requirement. ## Model routing and discovery @@ -73,7 +77,7 @@ Streaming responses are forwarded as chunks arrive. The proxy does not buffer the full answer before sending it to the client. Provider errors keep their status codes and error details where supported. -The `eggpass usage` command fetches current usage where a provider exposes it, and both it and the daemon endpoint query only providers enabled in configuration. For ChatGPT, the OAuth flow has no quota endpoint, so usage is unavailable rather than estimated; when OpenAI is enabled, the optional local Codex app-server may provide a report from a separate account. +The `eggpass usage` command first uses the running daemon's cached report and queries only providers enabled in configuration. It uses direct provider collection when the daemon is stopped or stale, the runtime usage credential file is missing or unreadable, or an older daemon returns `404`; a connection failure falls back only after a stopped/stale recheck. Authentication failures, malformed reports, and refresh/cooldown statuses are surfaced without bypassing the daemon. Stale cache is still displayed with a stderr warning. For ChatGPT, the OAuth flow has no quota endpoint, so usage is unavailable rather than estimated; when OpenAI is enabled, the optional local Codex app-server may provide a report from a separate account. The authenticated `GET /v1/usage` endpoint returns the CLI-compatible JSON report. It caches one complete snapshot in memory for 10 minutes, starts at most one demand-triggered refresh, and never polls or writes usage data to disk. Its initiating request waits up to 30 seconds; if that deadline expires it gets `504` while the finite refresh continues. Concurrent requests get `202` with `Retry-After`. A refresh retries only timed-out providers, up to three times at 5/15/30-second intervals. Each xAI billing/settings request is capped at 15 seconds; OAuth refresh has a 60-second total deadline and Codex has an 8-second session deadline. Success adds age and update-time headers; after retry exhaustion, a previous successful snapshot is marked stale during a 10-minute cooldown, or `503` is returned if no good snapshot exists. A daemon restart clears the cache. The latest inference status is read afresh for every report response. diff --git a/docs/releasing.md b/docs/releasing.md index 235c181..9ebac7d 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -10,8 +10,9 @@ release" that every installed `eggpass` then pulls. - Push access to `eggstack/eggpass`. - The `CARGO_REGISTRY_TOKEN` repository secret, which must be a crates.io - API token with the `publish` scope for this crate. Without it, the crates.io - step fails, but the GitHub release is unaffected. + API token with the `publish` scope for the package being released (`eggpass` + or `eggpass-auth`). Without it, the crates.io step fails, but the GitHub + release is unaffected. - The release workflow is generated from `release/eggpack/`. Its pinned Eggpack revision is in `github-policy.json`; CI checks the generated workflow for drift. @@ -23,9 +24,9 @@ gh secret set CARGO_REGISTRY_TOKEN --repo eggstack/eggpass | Fact | Value | | --- | --- | -| Git tag | `v0.1.0` (version with a `v`) | -| `Cargo.toml` version | `0.1.0` (version without a `v`) | -| Manifest `release_id` | `0.1.0` (**no `v`**) | +| Git tag | `vX.Y.Z` (the version prefixed with `v`) | +| `Cargo.toml` version | `X.Y.Z` (without the `v`) | +| Manifest `release_id` | The same plain `X.Y.Z` version | | Manifest `product_id` | `eggpass` | | Manifest `source_revision` | the 40-character commit the tag peels to | | Manifest file name | `release-manifest.json` | @@ -51,20 +52,27 @@ value is `eggpass`. ## Cutting a release -1. **Bump the version** in `Cargo.toml`, commit, and push. +1. **Bump and commit the version.** Update the root `eggpass` package version + in `Cargo.toml`; keep independently versioned packages unchanged unless + they are part of this release. Stage only the files intended for release, + then run the checks and commit the prepared changes. Do not stage the whole + worktree when unrelated changes are present. Push the release commit to + `main` before tagging it. ```sh - # edit the version in Cargo.toml - cargo test && cargo clippy --all-targets -- -D warnings && cargo fmt --all -- --check - git commit -am "chore: release 0.1.0" - git push origin main + cargo test --workspace --all-targets --locked + cargo clippy --workspace --all-targets --locked -- -D warnings + cargo fmt --all -- --check ``` 2. **Tag the commit.** The workflow does not create tags. ```sh - git tag -a v0.1.0 -m "eggpass 0.1.0" - git push origin v0.1.0 + set -eu + release_version="$(cargo metadata --no-deps --format-version 1 | python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"] == "eggpass"))')" + release_tag="v${release_version}" + git tag -a "$release_tag" -m "eggpass ${release_version}" + git push origin "$release_tag" ``` The release workflow does not create or push tags. @@ -74,14 +82,20 @@ value is `eggpass`. manifest and checksum sidecars, then stages a **draft** release. ```sh - gh workflow run release.yml --repo eggstack/eggpass -f release_tag=v0.1.0 + set -eu + release_version="$(cargo metadata --no-deps --format-version 1 | python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"] == "eggpass"))')" + release_tag="v${release_version}" + gh workflow run release.yml --repo eggstack/eggpass -f "release_tag=$release_tag" ``` 4. **Check the draft.** ```sh - gh release view v0.1.0 --repo eggstack/eggpass - gh release download v0.1.0 --repo eggstack/eggpass --pattern '*' --dir /tmp/eggpass-check + set -eu + release_version="$(cargo metadata --no-deps --format-version 1 | python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"] == "eggpass"))')" + release_tag="v${release_version}" + gh release view "$release_tag" --repo eggstack/eggpass + gh release download "$release_tag" --repo eggstack/eggpass --pattern '*' --dir /tmp/eggpass-check ``` The manifest should name every asset with its exact size and digest: @@ -99,7 +113,10 @@ value is `eggpass`. 5. **Publish the draft.** This is the human action. ```sh - gh release edit v0.1.0 --repo eggstack/eggpass --draft=false + set -eu + release_version="$(cargo metadata --no-deps --format-version 1 | python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"] == "eggpass"))')" + release_tag="v${release_version}" + gh release edit "$release_tag" --repo eggstack/eggpass --draft=false ``` Publishing the release fires `.github/workflows/publish-crates.yml`, which @@ -114,44 +131,80 @@ value is `eggpass`. It should report the published release and the asset it would install. -## The manifest +## Independent auth crate release -The manifest is the whole input the updater reads. It uses eggstack's -release-manifest v1 schema, defined by -[`eggpack-manifest`](https://crates.io/crates/eggpack-manifest): - -```json -{ - "schema_version": 1, - "product_id": "eggpass", - "release_id": "0.1.0", - "source_revision": "0f1e2d3c4b5a69788796a5b4c3d2e1f0a9b8c7d6", - "targets": [ - { - "target": "aarch64-apple-darwin", - "form": { - "kind": "direct", - "artifact": { - "name": "eggpass-aarch64-apple-darwin", - "size": 4088320, - "sha256": "9f2c…64 lowercase hex characters…" - }, - "install": "eggpass" - } - } - ] -} +`eggpass-auth` is versioned independently in +`crates/eggpass-auth/Cargo.toml`; do not use the root `Cargo.toml` version for +it. Root Eggpass releases keep the `vX.Y.Z` tag convention, while auth releases +use `eggpass-auth-vX.Y.Z` (for example, `eggpass-auth-v0.1.0`). The auth +workflow packages and publishes only `eggpass-auth`. Because the root Eggpass +crate depends on this library, publish the auth crate first before the next +Eggpass crates.io release; otherwise Cargo cannot resolve the dependency from +crates.io. The root package check patches `eggpass-auth` to the workspace path so CI can package-check Eggpass without a registry release of that dependency. + +To verify the exact tagged source without creating a GitHub release, dispatch +the auth workflow against the tag with its default dry-run enabled: + +```sh +gh workflow run publish-eggpass-auth.yml --repo eggstack/eggpass \ + --ref eggpass-auth-v0.1.0 -f dry_run=true ``` -The rules the reader enforces: +Dispatch is verification-only and cannot publish, even if `dry_run` is changed. +The workflow checks that the tag version matches the auth crate manifest and +runs `cargo package --locked -p eggpass-auth`. + +After reviewing a successful dry run and rechecking crate-name availability +and dependency versions, publishing still requires a fresh, explicit human +authorization. Publishing a GitHub release for the exact auth tag is the +publication gate and triggers crates.io publication; this implementation work +does not authorize that public action. + +## Independent Python PyPI release + +The Python distribution in `python/eggpass-auth` is versioned independently of both the Rust auth crate and the Eggpass CLI. The CI and PyPI workflows build five stable-ABI wheels for GIL-enabled CPython: Linux x86_64/aarch64 with manylinux2014, macOS x86_64/arm64, and Windows x86_64. CI installs and tests each wheel on CPython 3.11–3.15. The workflows do not build musllinux, free-threaded Python, or 32-bit ARM wheels. A compatible 64-bit Raspberry Pi OS may be able to use the Linux aarch64 wheel, but that combination is not separately qualified. + +The Python tag is `eggpass-auth-python-vX.Y.Z` (for example, `eggpass-auth-python-v0.1.0`). Keep the version in `python/eggpass-auth/pyproject.toml` equal to the package version in `python/eggpass-auth/Cargo.toml`. Do not use `eggpass-auth-vX.Y.Z` (the Rust auth release) or `vX.Y.Z` (the Eggpass CLI release). + +### One-time PyPI and GitHub setup -- `schema_version` is exactly `1`. -- `release_id` is a plain `X.Y.Z`. -- Every target's `artifact.name` is the exact asset name, `artifact.size` is - its exact byte count, and `artifact.sha256` is its digest in lowercase hex. -- `install` is the name the artifact takes on disk: `eggpass`. +Before the first release: -Unknown fields fail closed, and so does an unsupported schema version. +1. Recheck that `eggpass-auth` is available and confirm the PyPI project owner. The PyPI endpoint returned `Not Found` on 2026-11-19; this is only a point-in-time lookup and does not reserve the project name. +2. Configure a PyPI Trusted Publisher for GitHub Actions with repository owner `eggstack`, repository `eggpass`, workflow file `publish-eggpass-auth-pypi.yml`, and environment name `pypi`. If the project does not exist yet, configure a pending publisher for the new project. +3. Create the GitHub `pypi` environment and require an authorized reviewer. The publish job receives `id-token: write`; build and validation jobs do not. Do not add a long-lived PyPI token. + +### Candidate and publication procedure + +1. Review and commit only the intended Python package, CI, publisher, and documentation changes; preserve unrelated worktree files. Require the Python CI workflow to pass, including wheel-install tests for every platform/Python combination and sdist build/install tests on CPython 3.11–3.15. Do not claim a platform combination as release-qualified unless its required CI checks pass; Raspberry Pi OS compatibility remains a separate device-specific check. +2. Run the publisher workflow manually with `workflow_dispatch` for a verification-only build, or prepare the exact versioned source commit and tag. Manual dispatch builds and validates files but cannot publish. +3. Create a draft GitHub release for `eggpass-auth-python-vX.Y.Z`. Publishing that GitHub release starts the Python-only workflow; it checks the tag/version, builds the five wheels and sdist, validates metadata/tags/contents, and uploads the validated files as an Actions artifact. +4. Inspect the completed build and validated artifact in the Actions run. The final publish job is held at the protected `pypi` environment. Approve it only after reviewing the exact files and, for the first public upload, after fresh explicit authorization. Publishing the GitHub release or approving that job is an externally visible release action; this implementation does not authorize either. + +The publisher job has no checkout or build step and uses `pypa/gh-action-pypi-publish@release/v1` with GitHub OIDC. PyPI publish attestations are produced by the official action by default. The Python tag does not match the root `vX.Y.Z` crates publisher or the Rust auth `eggpass-auth-vX.Y.Z` publisher. A published PyPI file/version cannot be overwritten; correct mistakes with a new version or yank the release where appropriate. + +## The manifest + +Eggpack generates the `release-manifest.json` file using eggstack's +release-manifest v1 schema, defined by +[`eggpack-manifest`](https://crates.io/crates/eggpack-manifest). Do not hand-edit +a release manifest. Its required fields are: + +| Field | Required value | +| --- | --- | +| `schema_version` | `1` | +| `product_id` | `eggpass` | +| `release_id` | The package version as plain `X.Y.Z`, without `v` | +| `source_revision` | The full 40-character commit SHA that the release tag peels to | +| `targets[].target` | The exact Rust target triple | +| `targets[].form.kind` | `direct` | +| `targets[].form.artifact.name` | The exact release asset name | +| `targets[].form.artifact.size` | The asset's exact byte count | +| `targets[].form.artifact.sha256` | The full 64-character lowercase SHA-256 digest | +| `targets[].form.install` | `eggpass` | + +The updater checks the manifest version and the selected asset's size and digest +before replacing the binary. ## Integrity, not authenticity diff --git a/docs/updating.md b/docs/updating.md index 7d465f1..186d516 100644 --- a/docs/updating.md +++ b/docs/updating.md @@ -2,7 +2,7 @@ ```sh eggpass update # install the latest published release -eggpass update 0.2.0 # install an exact version +eggpass update 0.1.0 # install an exact version eggpass update --check # show the proposed update without changing anything ``` @@ -32,17 +32,19 @@ update process. ## Cargo installations -If you installed with Cargo, update with Cargo instead. The updater prints the -appropriate command. For a local checkout: +If you installed with Cargo, the updater refuses to replace that binary and +prints a command with `--locked --force --root` set to the detected Cargo +installation. Run that command unchanged so Cargo updates the correct +installation. For a default crates.io installation, the equivalent is: ```sh -cargo install --path . +cargo install eggpass --locked --force ``` -For the Git repository: +To reinstall from the current repository checkout instead: ```sh -cargo install eggpass --git https://github.com/eggstack/eggpass +cargo install --path . --locked --force ``` ## Exact versions and rollback diff --git a/plans/async-auth-library-implementation.md b/plans/async-auth-library-implementation.md new file mode 100644 index 0000000..d747527 --- /dev/null +++ b/plans/async-auth-library-implementation.md @@ -0,0 +1,143 @@ +# Async Auth Library Implementation Plan + +**Status:** Local implementation and validation complete. No public release or publication occurred or is authorized. + +**Basis:** [`async-auth-library-requirements.md`](../async-auth-library-requirements.md) and the existing Eggpass auth, provider, and release code cited below. + +## Goal + +Create a small, independently versioned public Rust crate—provisionally `eggpass-auth`—that lets downstream async applications reuse Eggpass’s OAuth behavior with their own `eggfetch_core::Client`, runtime, UI, and credential storage. Preserve Eggpass as a synchronous CLI/proxy; do not make its server or request path async as part of this work. + +## Proposed defaults to approve before implementation + +1. **Package boundary:** Add `crates/eggpass-auth` as a separate workspace package, not a library target inside the existing `eggpass` binary package. Give it its own version and crate metadata. Keep the root binary’s version and release identity independent. +2. **Dependency:** Target the researched Eggfetch 0.3 line directly and accept the temporary Eggfetch 0.2/0.3 dependency duplication from the updater unless updating `eggup-eggfetch` is independently justified. Recheck current versions and package availability before coding and again before publication. +3. **Core scope:** Include async authorization-code exchange, refresh, revocation, user-info, browser-authorization transaction creation/completion, device-code creation, and cancellable device polling. Return URLs and device instructions as data. Do not print, launch a browser, read stdin, bind loopback sockets, or create a runtime in the core crate. Consider loopback/browser conveniences only as a later optional adapter. +4. **Providers:** Ship focused built-in x.ai and OpenAI profiles plus a minimal documented custom OAuth profile. Preserve x.ai’s `referrer` behavior and device-flow support, and OpenAI’s registration-only parameters and issued-client-ID reuse. Do not expose the inference-oriented `ProviderSpec`. +5. **Credentials:** Make explicit-token operations and caller-owned storage the default. Add a generic storage seam for a manager only if it can preserve the existing refresh behavior; an Eggpass-compatible file adapter is optional and must not make the core assume `~/.config/eggpass/auth.json` or import Grok CLI paths. Document that in-process refresh coalescing is not a cross-process lock unless the storage contract provides coordination. +6. **Sync Eggpass adapter:** Before extracting or replacing the current sync auth path, prove a narrow host-owned async-to-sync bridge that does not create a runtime in the library or change the proxy/server architecture. If the bridge is unsafe or causes behavior regressions, pause that integration rather than rewrite the server or silently maintain two divergent OAuth implementations. +7. **Release boundary:** Version and publish the auth crate independently. Use an auth-specific release tag/workflow and ensure the existing root `publish-crates.yml` cannot treat an auth release as an Eggpass release. The current root publisher listens to all published releases, so this isolation is a required release-workflow change, not an assumption. + +These are recommended planning defaults, not decisions already made by the user. The scope, sync bridge, storage contract, Eggfetch alignment, and versioning choice are go/no-go decisions before implementation begins. + +## Stage 0 decisions and execution record + +The user asked to work through the plan in full. I am proceeding with the proposed defaults below; this authorizes local implementation and dry-run validation only, not a public release or crates.io publication. + +- Package: separate `crates/eggpass-auth` workspace member, independently versioned from the `eggpass` binary. Initial library version: `0.1.0`; auth release tags: `eggpass-auth-v0.1.0` and the same prefix for later versions. +- Eggfetch: use the `eggfetch-core` 0.3 line and accept temporary 0.2/0.3 duplication. Checked 2026-11-17: crates.io lists 0.3.0 as latest; it declares Rust 1.89. `eggup-eggfetch` 0.2.0 still requires `eggfetch-core ^0.2.0`. +- Scope: async token operations, auth-code transaction/callback completion, device flow, both built-in profiles, and custom OAuth configuration. Core creates no runtime and owns no UI, listener, filesystem path, or terminal interaction. +- Storage: caller-owned credentials by default, with a generic async credential-store seam and a manager whose single-flight guarantee is scoped to one manager instance/process. Eggpass’s filesystem adapter stays host-owned. +- Sync bridge: host-owned Tokio runtime calls the async library only at Eggpass’s synchronous auth boundary. The proxy/server remains synchronous. A local-stub bridge test is required before replacing the existing auth path. +- Provider profile parameters: preserve x.ai `referrer`/device flow and OpenAI registration-only `agent_name_hint`, resource parameters, and issued-client-ID reuse; support custom profiles. +- Release boundary: auth-specific tag/workflow; root publishing is limited to root `vX.Y.Z` tags. Validate package workflows dry-run only; do not create or publish a GitHub release. + +## Out of scope + +- Making Eggpass’s blocking HTTP server, upstream calls, daemon, or SSE path async. +- Replacing unrelated `ureq` uses in `src/upstream.rs`, `src/daemon.rs`, or usage reporting. +- Introducing embedded login pages, UI, browser launching, or terminal interaction into the public core. +- Live OAuth checks as a CI requirement. +- Publishing a crate, creating or publishing a GitHub release, or changing existing release artifacts/tags without a separate, fresh confirmation. + +## Staged work + +### Stage 0 — Resolve the implementation gates + +- Recheck `eggpass-auth` name availability, the current Eggfetch API/MSRV, and whether Eggup’s adapter has moved beyond Eggfetch 0.2.x. +- Choose the five defaults above or record alternatives. In particular, settle the manager/storage API and how synchronous Eggpass calls will drive the async library. +- Prototype only the sync bridge needed to establish feasibility; do not start extracting auth flows until it is demonstrated on the existing CLI path. +- Record the first crate version and tag convention separately from the Eggpass binary version. + +**Exit:** Decisions are explicit, the package name is available, dependency/MSRV compatibility is checked, and the sync bridge has a safe direction or is explicitly deferred. + +### Stage 1 — Establish the crate and public type boundary + +- Add the crate under `crates/eggpass-auth`, with a narrow dependency set, Rust 1.89 MSRV unless dependency revalidation changes it, a crate-local README/examples, and an explicit package include list. +- Add it to the Cargo workspace while preserving the existing root `eggpass` package, binary target, root package version, package include rules, and Eggpack identity. +- Define stable public modules and builders for `OAuthProviderConfig` and the client. Accept/clone a caller-supplied Eggfetch client; expose no Eggfetch response internals or Eggpass server/config modules. +- Define non-exhaustive public errors that carry useful status/OAuth codes but not arbitrary response bodies. Document ownership and `Send`/`Sync` guarantees. +- Ensure token-bearing values, device codes, pending authorization secrets, and stored credentials have redacted `Debug`; do not log secrets. + +**Exit:** The crate compiles independently and as a workspace member; a minimal consumer can construct a provider/client without importing Eggpass’s private modules. + +### Stage 2 — Port the async OAuth protocol client + +- Implement form/query encoding and provider-specific request parameters for authorization, token exchange, refresh, revocation, user-info, device-code creation, and polling. +- Make connect/read/total timeout policy explicit in configuration; do not accidentally inherit Eggfetch defaults. Bound response bodies and avoid blind retries for exchanges or refreshes, especially where refresh-token rotation may occur. +- Normalize status, OAuth, malformed-response, timeout, and network failures into the crate’s own errors. Avoid returning or displaying arbitrary response bodies. +- Preserve the current OAuth request semantics and the special OpenAI issued-client-ID lifecycle. + +**Exit:** Deterministic local-stub tests cover encoded parameters, success/error/non-JSON responses, timeout and oversized-body handling, and client-ID/registration behavior. + +### Stage 3 — Implement authorization and device-flow transactions + +- Implement an authorization transaction that returns an authorization URL and opaque pending state containing PKCE verifier, high-entropy state, nonce, redirect URI, and expected callback path. Completion validates state and the exact callback path before exchanging the code. Keep sensitive transaction fields private and redacted. +- Require PKCE S256; preserve nonce/state validation. A loopback listener, if added later, must bind only to loopback, use a short-lived random port, and close after completion; no embedded user-agent. +- Implement device-code start and async polling with caller-controlled cancellation/deadline. Return the verification URI and user code as values; validate verification hosts before presenting/opening them, and never log device codes. +- Follow RFC 8628 polling semantics: honor the server’s expiry rather than clamping short values to 60 seconds; after `slow_down`, add five seconds to the interval for subsequent polls. Cover `authorization_pending`, denial, expiry, and cancellation. + +**Exit:** Local deterministic tests verify PKCE/state/nonce, callback rejection cases, trusted-host checks, polling interval/deadline behavior, and cancellation. + +### Stage 4 — Add token lifecycle, storage seam, and Eggpass adapter + +- Provide token parsing/refresh independently from filesystem paths. If a manager is included, preserve proactive refresh skew, 401 compare-and-refresh, one refresh per process under concurrency, and merge behavior that retains the existing refresh token when rotation is omitted. +- Define whether storage operations are atomic and whether they coordinate across processes. A file adapter, if selected, must retain restrictive permissions and atomic replacement; do not imply that an in-process mutex is a cross-process lock. +- Complete the host-side Eggpass adapter only after the Stage 0 bridge is proven. Keep CLI prompts, browser launching, stdin handling, path resolution, Grok CLI import, and the synchronous `TokenProvider` interface in Eggpass host modules. Do not change the proxy server’s execution model. +- Resolve the current parity defects before calling the port complete: redact secret-bearing `Debug`, correct `slow_down` to the RFC-required five-second increase, and handle short server expiry values without the current 60-second minimum. + +**Exit:** Refresh rotation, concurrent refresh, storage guarantees, and the existing sync CLI integration pass focused regression tests without requiring downstream users to adopt Eggpass paths or UI. + +### Stage 5 — Downstream contract, CI, and package validation + +- Add a compiling downstream-style example that supplies an Eggfetch client and awaits authorization/refresh using the consumer’s runtime; it must not depend on Eggpass CLI/server modules. +- Run the library against a local OAuth stub using the real Eggfetch client. Keep provider-live tests opt-in and outside deterministic CI. +- Extend CI to format, lint, test, and package the workspace/library. Keep root binary tests and builds. Validate the library on supported platforms, including Windows if the selected storage adapter is cross-platform. +- Check dependency resolution explicitly for both Eggfetch lines and confirm `--locked` works. Run `cargo package --locked` for `eggpass-auth` and the existing root package; inspect the packaged file list for omissions or accidental inclusion. +- Verify all five existing Eggpass release targets before any later Eggpass binary release; library validation does not replace that release gate. + +**Exit:** Required protocol/security tests pass, the downstream example compiles, both packages pass locked packaging checks, and existing Eggpass CI/build/release behavior remains intact. + +### Stage 6 — Prepare a separate publication path (no publication in this plan) + +- Add an auth-specific, dry-run-first verification/publish path with independent version/tag validation and explicit package selection. +- Scope the existing root crates.io workflow to Eggpass release tags, and test that an auth-tagged release neither builds nor publishes the root `eggpass` crate. Keep the existing Eggpack binary release process and its draft-review-before-publish gate intact. +- Update maintainer release documentation with package-specific versioning, tag convention, package verification, and publication effects. Recheck crate-name availability and exact dependency versions before a first publish. +- Stop at a verified dry run. Any public GitHub release publication (which can trigger crates.io publication) requires separate, fresh user confirmation immediately before that action. + +**Exit:** Local package dry runs passed and workflow lint/source checks confirm the release boundary. A GitHub workflow dispatch was not run; no public release has been created or published. + +### Completion record + +- Passed on the local macOS host: `cargo fmt --all -- --check`, strict workspace Clippy, locked workspace tests (329 Eggpass, 30 auth unit, 10 local-stub tests), downstream example check, and locked Rust 1.89 workspace tests. +- Passed local package/build checks: `cargo package --locked --allow-dirty -p eggpass-auth`; root `eggpass` package verification with a local Cargo patch to `crates/eggpass-auth` (the auth crate is intentionally not yet on crates.io); and `cargo build --release --locked`. +- Passed `actionlint` on CI and both publisher workflows, ShellCheck on publisher shell snippets, and `git diff --check`. +- Not run: remote GitHub Actions dispatch, Windows MSVC job, or the five-target Eggpass release build. CI defines Windows 1.89 checks; all five targets remain mandatory before any future Eggpass binary release. +- No crate was published and no GitHub release was created. Publish `eggpass-auth` before any future Eggpass crates.io package release; the publisher workflows remain separately gated. + +## Acceptance checklist + +- [x] Public crate API accepts a caller-owned Eggfetch client, creates no runtime, owns no UI, and has no Eggpass home-directory assumption. +- [x] Built-in x.ai/OpenAI profiles and custom-provider configuration preserve required provider-specific parameters and issued-client-ID behavior. +- [x] PKCE S256, entropy, state/nonce and exact callback validation are tested; device verification URIs are host-checked. +- [x] Device polling handles pending, `slow_down` (+5 seconds), denial, actual expiry, timeout, and cancellation. +- [x] Timeouts, response-size bounds, error sanitization, retry rules, and secret-safe debug/log behavior are tested/documented. +- [x] Refresh preserves proactive skew, compare-and-refresh, one-process single-flight, and refresh-token rotation semantics; storage atomicity/cross-process guarantees are explicit. +- [x] Local OAuth stub tests use the real Eggfetch client; a downstream-style async consumer compiles without Eggpass application modules. +- [x] Root Eggpass sync behavior and server architecture are unchanged; the sync adapter bridge is proven or deferred explicitly. +- [x] Both packages pass formatting, lint, tests, and locked packaging; CI covers the selected platform/storage support. +- [x] Existing five-target Eggpass release gates remain intact; auth release tags cannot invoke root Eggpass publication; no public publication occurs without fresh confirmation. + +## Current code and research references + +- Requirements and dependency/version findings: [`async-auth-library-requirements.md`](../async-auth-library-requirements.md), especially sections “Recommendation and boundary,” “Security and protocol acceptance criteria,” and “Package, dependency, tests, and release work.” +- Private binary-only boundary: `src/main.rs:8-21`. +- Current synchronous OAuth client and secret-bearing token/device types: `src/auth/client.rs:51-67,130-180`. +- Browser/device flows, trusted verification URLs, expiry clamp, and current `slow_down` increment: `src/auth/flow.rs:127-289`. +- Refresh coalescing and rotated-token merge behavior: `src/auth/refresh.rs:67-225`. +- Current credential format, restrictive atomic file persistence, and Grok CLI import: `src/auth/store.rs:1-18,44-87,130-210`. +- Provider-specific profile behaviors: `src/provider/xai.rs:75-100`; `src/provider/openai.rs:149-198`. +- Existing root package metadata and explicit package include list: `Cargo.toml:1-28,30-77`. +- Existing root publisher trigger and root-only package/version checks: `.github/workflows/publish-crates.yml:10-19,41-61`. +- Eggpass binary release shape and human publication gate: `docs/releasing.md:22-115`; five-target candidate builds are in `.github/workflows/release.yml`. +- OAuth protocol references and Eggfetch API links are collected in the requirements memo. diff --git a/plans/daemon-usage-cli-cache-implementation.md b/plans/daemon-usage-cli-cache-implementation.md new file mode 100644 index 0000000..e0b1115 --- /dev/null +++ b/plans/daemon-usage-cli-cache-implementation.md @@ -0,0 +1,126 @@ +# Reuse the daemon usage cache from the CLI + +**Status:** Local implementation and validation are complete. The latest Windows CI job passed on the prior commit, but the ACL implementation is not on that commit; ACL-specific CI validation remains pending. + +## Goal + +Change `eggpass usage` to prefer the daemon's existing cached usage report, while retaining today's direct provider collection when the daemon is unavailable. Give the CLI a separate, daemon-managed usage credential that can read only the usage endpoint. Do not change the meaning or scope of regular Eggpass API keys. + +This is a CLI/authentication integration plan, not a plan to build another usage cache. The authenticated `GET /v1/usage` route, its in-memory 600-second cache, single-flight refresh, finite retries, response shape, and freshness headers already exist in the current source. The CLI currently collects provider usage directly on each run and only makes a separate best-effort daemon request for last-inference state. + +## Research findings and design decision + +- The CLI collection is in `src/cli/commands/usage.rs:129-178, 246-284`; its report DTO and enabled-provider selection are in `src/provider/usage/report.rs`. Existing output includes provider results, source/caption, and last-inference status. +- The daemon cache and `GET /v1/usage` response are in `src/server/usage.rs`. The route is registered in `src/server/router.rs`, and request auth/dispatch is centralized in `src/server/mod.rs`. +- All protected routes currently require a configured regular key. The daemon also refuses to start without one (`src/cli/commands/run.rs`). Issued regular keys are salted hashes in `src/keys.rs`; the daemon verifies them through the shared auth path. Preserve these properties. +- Paths are rooted in the resolved Eggpass data directory. A `--config` override changes only the config file path, not the key store or other runtime files (`src/paths.rs`). The existing Unix private writer uses atomic replacement and 0700/0600 modes, but the current permission helper is a no-op on Windows. A new secret cannot rely on that no-op as adequate Windows protection. +- **Recommendation:** use a separate, high-entropy runtime secret and authorize it by exact match only for `GET /v1/usage`. Do not infer its scope from a prefix/suffix, strip a marker, or insert it into the regular key store. A recognizable prefix is unnecessary; if ever used for display, it is only a label and must not affect authorization. +- Keep the secret in a dedicated runtime file under the resolved data directory, not in `config.toml`, the ordinary key store, command output, or logs. Rotate it for each daemon start. The CLI reads it locally and sends it in an Authorization Bearer header; do not put it in the URL/query string. + +## Security and compatibility contract + +1. **Least privilege:** the usage secret is accepted only for a bodyless `GET` to the usage route. It must fail authentication for inference, model, health/other, and any other route, including when an illustrative marker is removed or altered. Compare the entire token; never strip characters and never dispatch to a usage-key lookup solely because a candidate has a prefix. +2. **Regular keys unchanged:** regular config keys and issued keys retain their current accepted transports and full route scope. A valid regular key continues to work on the usage endpoint and every route it works on today. Do not change regular-key verification, listing, labels, hashing, or revocation behavior. +3. **No elevation of daemon startup:** the usage secret does not count as a configured client key, is not returned by key-list commands, and cannot satisfy `require_key`. Preserve the current fail-closed behavior when there are no regular keys, including for loopback clients. +4. **No loopback exception:** keep the existing authority/Host guard and authenticated-route checks. The usage token is not a reason to exempt localhost or weaken auth. +5. **Credential handling:** generate at least 256 bits of cryptographically secure randomness. Store the complete token only in its dedicated private file and in daemon memory. Use exact constant-time comparison. Do not log it, include it in errors, or expose it through a command, API response, config dump, debug output, or key listing. Treat usage data itself as sensitive even though the token has narrower access. +6. **File security and lifecycle:** add a path accessor such as `Paths::usage_key_file()`, rooted beside other Eggpass runtime files and unaffected by `--config`. Write atomically; create the Unix file as 0600 inside the 0700 data directory. On Windows, establish and test a current-user-only ACL for both directory and file; fail daemon startup closed if user-only protection cannot be established. Do not treat the existing non-Unix permission no-op as protection. Rotate/replace the token before the daemon reports ready. On graceful shutdown, remove the file only if it still contains this daemon's token; a crash may leave a stale file, but the next start must replace it before serving. A stopped daemon's leftover file must not authorize anything. +7. **Header scope:** accept the usage secret only from the Authorization Bearer header used by the CLI. Do not accept it from a query parameter. Keep existing regular-key header/query behavior unchanged. + +## CLI behavior + +Refactor `eggpass usage` into a daemon-attempt phase followed by the existing direct-collection phase. Keep formatting, JSON stdout, exit status rules, provider selection, and direct collector behavior compatible. + +- Resolve daemon state using the existing pid/host/port mechanism. If it is stopped or stale, use the existing direct provider collector without attempting the daemon request. +- If the daemon is running, read the dedicated usage-secret file. If the file is missing or cannot be read, use direct collection; do not print the secret or a file's contents in an error. +- Request `GET /v1/usage` with the secret as a Bearer header. Use bounded connect/overall timeouts appropriate for a local cache endpoint and status-aware HTTP handling. Never place the secret in a URL. +- On HTTP 200, parse the existing CLI-compatible JSON shape into the same report model and use the existing render/JSON/exit-result path. Respect an explicit provider selection by selecting that provider from the response. The daemon's fresh last-inference field should be used rather than making a second request. Preserve the JSON body shape and stdout; if the response has `X-Eggpass-Usage-Stale: true`, explain that cached data is stale on stderr only. +- On HTTP 404, use direct collection for compatibility with a running daemon that does not implement this route. +- If the request has a connection failure, recheck daemon state. Use direct collection only if that recheck confirms the daemon stopped or stale. If it still appears to be running, report the daemon communication failure instead of silently bypassing its cache. +- Do **not** fall back to direct provider calls for HTTP 202, 503, or 504. Those statuses represent an active refresh or cooldown, and fetching providers directly would bypass the daemon's single-flight/retry policy. Surface an actionable CLI error while preserving the HTTP status/retry context where practical. +- Treat HTTP 401/403 and malformed successful responses as errors, not as permission to silently fall back. This makes a stale/mismatched secret visible and prevents fallback from hiding an authentication/configuration defect. Do not retry by stripping a prefix or trying variants of the secret. +- A valid regular API key is not needed by the CLI for the daemon request; the scoped secret is sufficient for this route only. Direct fallback continues to use the existing local provider credential flow, not the scoped secret. + +## Implementation stages + +### Stage 1 — Add the runtime secret lifecycle + +- Add the dedicated path to `Paths`; document that config-file overrides do not relocate it. +- Add a focused secret-file helper or safely extract/reuse the private atomic-file writer without changing regular-key semantics. Use an unpredictable temporary filename opened with create-new semantics; avoid following attacker-planted temporary symlinks. Apply restrictive permissions/ACL before the secret can be read by another process. +- Generate a new URL-safe opaque token from a cryptographic RNG for each daemon launch. Do not add a prefix-based auth class. Atomically write the token, load the same exact bytes into server context, and ensure startup cannot report ready if creation/protection fails. +- Remove the matching secret on graceful shutdown without deleting a different daemon's rotated token. Do not persist or modify a config field. + +**Exit:** the daemon has one high-entropy runtime secret, stored only in the dedicated protected file and process memory; rotation/restart and shutdown behavior are defined and tested on supported platforms. + +### Stage 2 — Add route-specific authentication + +- Keep common authority validation and regular-key checks as they are. Add a separate exact-match usage-secret check in the shared auth path, gated by both the usage route and GET method, and by Authorization Bearer presentation only. +- Ensure the regular-key-present guard still executes: the runtime usage secret must not satisfy startup or `keys_configured` requirements and must not open a server whose regular keys have been removed. +- Ensure other methods/routes do not become authorized via the usage secret. Do not change the unauthenticated health/last-inference exceptions. + +**Exit:** existing normal-key behavior is unchanged; only the exact current usage secret can authorize GET usage, and it cannot authorize inference or any other route. + +### Stage 3 — Prefer the cached daemon response in `eggpass usage` + +- Add a small typed result for the daemon attempt (use cached report, fall back to direct collection, or return an error) so status handling is explicit and testable. +- Reuse the daemon-state and local HTTP patterns, but send the scoped Bearer key and request the existing endpoint. Add bounded transport timeouts and response parsing without logging credentials or provider payloads. +- Feed a successful daemon report through the existing CLI render/JSON and exit-code logic. Keep stdout exactly in the current schema; send stale-cache notice to stderr. Preserve provider override behavior and use last-inference already present in the API report. +- Keep direct collectors untouched as the fallback path. Apply the state-recheck rule on connection failure and never bypass 202/503/504. + +**Exit:** a live daemon's complete or stale cached response avoids provider calls; unavailable/unsupported daemon cases retain direct checks; pending/cooldown/auth failures have explicit non-bypass behavior. + +### Stage 4 — Deterministic security, fallback, and regression tests + +- **Secret files:** test resolved path behavior, config override separation, rotation, atomic replacement, restrictive Unix modes, Windows current-user ACL, failure-closed startup, and matching-token cleanup. Ensure no test output includes token bytes. +- **Authorization:** integration-test the scoped key on GET usage, and rejection on inference/models/other routes and wrong method. Test wrong/modified token and a token with any illustrative prefix removed; assert route scope comes from exact full-token matching, not parsing. Test that regular configured and issued keys still work unchanged. Verify the scoped token is absent from key listing and does not let a no-regular-key daemon start or serve protected routes. Retain authority/Host guard tests for loopback. +- **CLI HTTP behavior:** use a local stub server and injected collector counter. Assert HTTP 200 uses the cached report and makes zero direct provider calls; stale 200 warns only on stderr; 404 uses direct collection; stopped/stale daemon and missing key use direct collection; a connection failure falls back only after a stopped/stale recheck; a still-running connection failure, 401/403, malformed body, 202, 503, and 504 do not call direct collectors. Verify response timeout, headers, key transport, and absence of the secret from URL/log/error output. +- **Output compatibility:** test unchanged text and JSON stdout shape, provider filtering, exit-code semantics, and last-inference data for daemon and direct paths. Ensure stderr notices do not contaminate piped JSON. +- Use fake/local responses only; no provider credentials, live provider requests, real daemon network, or secret-bearing test snapshots are required. + +**Exit:** all new behavior is covered without live accounts or providers, including the security boundary and every fallback branch. + +### Stage 5 — Documentation and validation + +- Document that `eggpass usage` uses the daemon cache when available, that a separate private usage-only runtime key is generated/rotated, that it is not a regular API key, and that regular keys remain unchanged. Document stale/pending/cooldown and direct fallback behavior without exposing implementation tokens or implying that usage data is non-sensitive. +- Update current daemon usage/auth and CLI command documentation; keep API response docs consistent with the already-implemented cache route. +- Run formatting, workspace tests, strict Clippy, and `git diff --check`; add targeted server/auth/CLI tests. The existing Windows MSVC all-target job passed on commit `a626ef7561e096342a4d83f7d2ca452b9b52b873`, but `src/usage_key.rs` was absent from that commit, so the ACL test did not run there. Run the Windows job on a ref containing this implementation before checking the Windows acceptance item. Review only the scoped diff and preserve unrelated worktree changes; do not stage or commit unrelated files. + +**Exit:** docs match actual behavior; local formatting, workspace tests, Clippy, and diff checks pass. The prior Windows job passed, but Windows CI for the ACL implementation remains the final platform validation. + +## Acceptance checklist + +- [x] CLI prefers the daemon's existing cached usage report when the daemon is reachable and the scoped credential is usable. +- [x] Direct provider collection remains the fallback when daemon is stopped/stale, route is unsupported, or scoped key is absent/unreadable; connection errors fall back only after confirming the daemon is stopped/stale. +- [x] HTTP 202/503/504 never trigger direct provider calls; authentication/parse errors are visible and do not trigger a silent bypass. +- [x] The usage-only secret is random, private, rotated per daemon start, and separate from config and regular keys. +- [x] Exact secret grants only GET usage; it cannot authorize inference, another route, or wrong method, even if any illustrative prefix/suffix is removed. +- [x] Regular client-key scope/behavior, key listing/revocation, startup key requirement, and loopback/authority protections are unchanged. +- [ ] Windows file/directory access is protected by a current-user-only ACL; inability to protect the secret fails closed. +- [x] CLI text and JSON stdout remain compatible; stale-cache information is written to stderr only. +- [x] Tests cover security and fallback behavior without live provider access; docs describe credential storage, scope, rotation, and fallback. +- [x] Unrelated worktree changes remain untouched and unstaged. + +## Completion record + +- Local macOS validation passed: cargo fmt --all -- --check; cargo test --workspace --all-targets --locked (422 tests); cargo clippy --workspace --all-targets --locked -- -D warnings; git diff --check. +- GitHub Actions run [#25](https://github.com/eggstack/eggpass/actions/runs/44387410491) succeeded, including the [Windows MSVC tests and release build](https://github.com/eggstack/eggpass/actions/runs/44387410491/job/135095608545), at commit `a626ef7561e096342a4d83f7d2ca452b9b52b873`. The untracked `src/usage_key.rs` was absent from that SHA, so this run does not validate the usage-key ACL implementation. Local Windows cross-compilation also could not complete because this machine lacks the Windows target/toolchain headers; ACL-specific CI validation remains pending. +- No changes were staged or committed; unrelated worktree changes were preserved. + +## Out of scope + +- Reimplementing or changing the existing daemon usage cache, its TTL, refresh/retry policy, endpoint schema, or freshness headers. +- Making any endpoint unauthenticated, weakening loopback authentication, or accepting the scoped secret for inference. +- Adding the scoped secret to `keys.json`, `eggpass key list`, normal config, or regular-key verification/storage semantics. +- Replacing direct provider collection as a fallback or performing direct collection when the daemon reports an active refresh/cooldown. +- Provider API/OAuth changes, config rewrite/migration, periodic usage polling, or exposing credentials in command output/logs. + +## Relevant source references + +- `src/cli/commands/usage.rs:129-178, 246-284, 400-435` — direct collection, output, daemon-state/last-inference probe. +- `src/server/usage.rs:321-357` — existing cache response and freshness behavior. +- `src/server/mod.rs:231-298, 363-435` — request guard, shared authentication, key presentation. +- `src/server/router.rs:5-45` — existing route map. +- `src/cli/commands/run.rs:98-129, 189-295` — regular-key startup guard, providers and cache setup. +- `src/keys.rs:182-205, 236-249, 346-407` — regular key issue/verify and private file writer. +- `src/paths.rs:5-11, 156-195, 198-219` — data-directory resolution, config override semantics, platform permission helper. +- `docs/commands.md:73-79` — current CLI/daemon usage documentation. diff --git a/plans/python-pyo3-bindings-implementation.md b/plans/python-pyo3-bindings-implementation.md new file mode 100644 index 0000000..ae18ade --- /dev/null +++ b/plans/python-pyo3-bindings-implementation.md @@ -0,0 +1,124 @@ +# Python Bindings for `eggpass-auth` — Implementation Plan + +**Status:** Implemented locally. The macOS arm64 CPython 3.14 wheel and a clean sdist install pass; the separate Linux CI matrix is configured but not yet run. PyPI/crates.io publication remains out of scope. + +**Basis:** Current `eggpass-auth` API and the completed PyO3/UniFFI research. Preserve the existing Rust crate and its independent release boundary. + +## Implementation outcome + +- The separate package lives at `python/eggpass-auth`, imports as `eggpass_auth`, and builds the private `eggpass_auth._native` extension. It uses PyO3 0.30.1, `pyo3-async-runtimes` 0.30.0 with Tokio, Maturin 1.9.5, Rust 1.89, and the `abi3-py39` stable ABI. +- The Python Cargo crate is its own nested workspace. Because the canonical core crate is a member of the repository’s Cargo workspace, the Python package includes a source snapshot at `vendor/eggpass-auth`; `tools/sync_core.py --check` verifies it against `crates/eggpass-auth`. A narrow `.gitignore` exception ensures the snapshot is included in checkout/CI. The sdist packages it and installs without depending on the repository checkout. +- Python `TokenManager` and async storage callbacks are deferred. This implementation did not establish a robust atomic Python-store adapter; V1 exposes explicit credential and refresh operations only. +- Python task cancellation was tested to stop the polling future; it does not set a shared `CancellationToken`. Calling `CancellationToken.cancel()` explicitly produces the Rust cancellation result. +- Local wheel, sdist, integration tests, and type stubs were validated on macOS arm64 / CPython 3.14. The separate workflow configures Ubuntu x86_64 jobs for CPython 3.9 and 3.14, but those GitHub jobs have not run in this implementation session. Windows and other architectures are not qualified. + +## Goal + +Provide a supported Python package that reuses `eggpass-auth` OAuth protocol behavior from Python applications. Python callers should be able to await authorization, device-flow, token-refresh, and related operations from `asyncio`, while retaining ownership of UI, callback reception, and credential persistence. + +## Recommendation and proposed defaults + +1. **Binding technology:** Use PyO3 for the Python-native extension, `pyo3-async-runtimes` with its Tokio integration for Rust-future/Python-`asyncio` conversion, and Maturin for the Python package and wheels. The PyO3 v0.30.1 guide still marks its built-in `async fn` bindings as actively developing; use the dedicated runtime bridge unless a later review establishes a stable replacement. +2. **Package boundary:** Keep `crates/eggpass-auth` independent of Python and PyO3. Add a separate Python binding/package project under `python/eggpass-auth`, with a public `eggpass_auth` Python package and private `_native` module. The binding uses its own nested Cargo workspace and remains outside the root Cargo workspace. +3. **Async contract:** Export awaitable Python methods backed by Tokio. Never call `block_on` from Python methods and never create a fresh Tokio runtime per operation. Clone or move owned Rust values into `Send + 'static` futures; do not hold Python/GIL-bound borrows across Rust `.await` points. The Python caller’s event loop remains the public async interface. +4. **HTTP client ownership:** Python cannot pass an arbitrary Python HTTP session to `OAuthClient::new`, which requires a Rust `EggfetchClient`. The binding constructs and owns a Rust Eggfetch client and exposes the finite request timeout and decoded-body cap. V1 does not expose proxy, custom-root, or arbitrary transport settings; it does not imply that Python requests/aiohttp clients can be injected directly. +5. **V1 API:** Expose provider presets, validated custom profiles, `OAuthClient`, opaque pending authorization, credentials/token values, authorization-code operations, device-code operations, refresh/revoke/userinfo, and typed/sanitized errors. Leave browser launching, callback listeners, terminal/UI behavior, and filesystem paths to the Python host. Pass the full callback URL into Rust completion so existing origin/path/state/nonce checks remain authoritative. +6. **Credential storage:** Do not expose the generic Rust `CredentialStore` trait as though a Python class could implement it directly: it is generic/RPITIT-based and not object-safe (`crates/eggpass-auth/src/manager.rs:10-30`). Prototype a concrete binding-side Python-store adapter before promising Python `TokenManager` support. The adapter must safely bridge Python async `load`/`save`/`clear` callbacks into Tokio and preserve atomic whole-credential replacement. If that prototype is not robust, V1 should expose explicit refresh operations and credentials, leaving persistence and refresh orchestration to Python; record `TokenManager` support as a follow-up rather than changing the core trait solely for bindings. +7. **Versioning and release:** Version the Python distribution separately from the Rust crate. The package is `eggpass-auth` version `0.1.0`, targets CPython 3.9+ via `abi3-py39`, and uses PyO3 0.30.1 / `pyo3-async-runtimes` 0.30.0 with Maturin 1.9.5. Registry lookups found no existing `eggpass-auth` package on PyPI or crates.io; no publication workflow or release was added. + +## Current API constraints to preserve + +- `eggpass-auth` accepts a caller-owned Rust Eggfetch client and creates no runtime; the binding is the host adapter (`crates/eggpass-auth/src/lib.rs:1-9`; `crates/eggpass-auth/src/client.rs:72-80`). +- `PendingAuthorization` holds private PKCE verifier, state, nonce, client ID, and redirect information; it is one-use and its Rust `Debug` redacts sensitive fields (`crates/eggpass-auth/src/client.rs:99-118,544-575`). The Python wrapper must retain it as an opaque object, redact `repr`, and prevent reuse after completion. +- Device polling accepts a `CancellationToken` and caller timeout (`crates/eggpass-auth/src/client.rs:379-397`). Specify and test how Python cancellation signals that token; do not silently claim that cancelling an `asyncio.Task` has the same semantics until verified. +- `Credentials` is serializable for caller-owned storage but contains access, refresh, and ID tokens (`crates/eggpass-auth/src/token.rs:119-145`). Any Python serialization API is secret-bearing; document that callers must protect it. Python `repr`, logs, and exception messages must redact secrets. +- Rust errors intentionally omit response bodies, request URLs, authorization codes, and tokens (`crates/eggpass-auth/src/error.rs:38-42`). Map them to Python exception classes without adding those values back. +- `TokenManager` provides only per-manager/process single-flight, not cross-process coordination (`crates/eggpass-auth/src/manager.rs:33-43`). A Python store/manager adapter must not overstate that guarantee. + +## Staged work + +### Stage 0 — Prove the binding and resolve package gates + +- Recheck current PyO3, `pyo3-async-runtimes`, Maturin, Python, and Rust MSRV compatibility. The current core crate declares Rust 1.89 (`crates/eggpass-auth/Cargo.toml:1-5`); lock compatible versions rather than assuming the latest versions work together. +- Build a minimal extension prototype with one Rust async function returned through `pyo3_async_runtimes::tokio::future_into_py`; verify it is awaited inside a running `asyncio` event loop. Test event-loop reuse and the documented calling pattern; do not drive the returned awaitable with a second/nested event loop. +- Prototype cancellation for device polling, including normal completion, Python task cancellation, and explicit cancellation-token signaling. +- A Python async storage adapter was not proven safe and atomic in this implementation. V1 therefore defers `TokenManager` and exposes explicit credential and refresh operations without changing the core storage trait. +- The wheel uses `abi3-py39`. The sdist uses a self-contained `vendor/eggpass-auth` snapshot checked by `tools/sync_core.py`; a maintainer-only path outside the package is not required. Local macOS arm64 wheel/sdist installs passed; Ubuntu x86_64 CPython 3.9/3.14 checks are configured in CI but remain unrun, and Windows/other architectures remain unqualified. + +**Exit:** A minimal importable wheel calls an async Rust stub under `asyncio`; cancellation and event-loop behavior are understood; the store-adapter and sdist-source strategy are explicit. + +### Stage 1 — Establish the independent Python package + +- Add a separate binding crate and Maturin `pyproject.toml`; configure a mixed package such as `eggpass_auth._native` plus a small Python facade. +- Keep PyO3 and binding-only dependencies out of `crates/eggpass-auth/Cargo.toml` and the normal Rust workspace test path unless Stage 0 demonstrates a safe alternative. +- Add package metadata, license/readme inclusion, a `py.typed` marker and Python stubs or inline typing. Verify Cargo formatting, lint, and existing Rust CI remain unchanged. +- Ensure clean-checkout wheel and sdist builds work in isolation, including the selected source strategy for `eggpass-auth`. + +**Exit:** `import eggpass_auth` works after installing the built wheel in a clean environment; the sdist can rebuild without relying on files outside its declared contents. + +### Stage 2 — Bind the OAuth API and map lifecycle values + +- Wrap the Rust client and provider configuration in Python-facing types. Provide xAI and OpenAI profile constructors, the xAI compatibility profile, and a validated custom-profile builder that exposes only supported non-secret protocol parameters. +- Construct the Rust Eggfetch client inside the wrapper from explicit configuration; expose `ClientOptions`-equivalent request timeout and decoded-body cap. Document any transport settings that are not available in V1. +- Implement each network operation as an awaitable using the Tokio bridge. Keep `begin_authorization` synchronous if it remains purely local; make completion, exchange, refresh, revocation, userinfo, device-code request, and polling awaitable. +- Wrap `PendingAuthorization` as opaque, one-use state; completion consumes it and receives the full callback URL. Do not expose verifier/state/nonce or accept a callback code/state pair that bypasses Rust validation. +- Map `Credentials`, `TokenSet`, `DeviceCode`, `DevicePoll`, and `UserInfo` to typed Python values. Keep secret access explicit and `repr` redacted. Map `eggpass_auth::Error` variants into a Python exception hierarchy preserving only safe status/code facts. +- If Stage 0 approves the store adapter, expose a typed Python async store protocol through a concrete Rust adapter and then expose the core token manager. Otherwise limit V1 to explicit credential and refresh operations. + +**Exit:** Python API coverage matches the approved V1 scope; callback validation, refresh-token merge, cancellation, and error redaction match the Rust library’s behavior. + +### Stage 3 — Add Python integration and security tests + +- Add `pytest` tests that import the built extension and run under `asyncio`; use a local deterministic OAuth stub, not provider-live CI. +- Cover successful and rejected authorization callbacks (wrong origin/path/state, duplicate or missing query values, nonce mismatch), client-ID registration behavior, refresh-token rotation/omission, device pending/slow-down/denial/expiry/cancellation, and sanitized errors. +- Test one-use pending transactions, Python cancellation mapping, multiple operations on the same event loop, event-loop shutdown/recreation, and concurrent refresh behavior within the documented guarantee. +- Assert `repr`, exceptions, and captured logs do not contain access/refresh/ID tokens, authorization codes, device codes, PKCE verifier, state, nonce, or full authorization URLs. +- If storage callbacks are included, test atomic replacement and callback failures, and verify no cross-process guarantee is claimed. + +**Exit:** Rust local-stub tests and Python integration tests pass without provider access; existing Rust tests and sync Eggpass paths remain unchanged. + +### Stage 4 — Validate wheel/sdist and maintainer workflow + +- Build and install wheels for every declared OS/architecture/interpreter target. Use Maturin’s manylinux-compatible Linux build path; test the selected `abi3` or version-specific wheel strategy rather than assuming it eliminates platform-specific wheels. +- Build an sdist and install it in a clean environment; verify the Rust crate source and all build metadata are present or fetched from the selected immutable version source. +- Add a separate Python-package CI job for formatting/linting, Rust checks for the binding crate, Python typing, pytest, wheel build, sdist build, and clean installation. Do not make Python tooling a prerequisite for the existing Rust-only CI unless approved. +- Document API lifecycle, callback ownership, event-loop usage, transport limitations, secure persistence, Python cancellation, supported platforms/Python versions, and the difference between Rust crate and Python package versions. +- Stop at local/CI packaging validation. Do not add or run a PyPI publication workflow in this plan. + +**Exit:** The declared wheels and sdist build/install in clean environments; the current Rust workspace and release workflows remain unaffected; no public package is uploaded. + +## Out of scope + +- Adding PyO3 or Python runtime dependencies to the core `eggpass-auth` crate. +- Making Eggpass’s synchronous CLI, proxy server, or SSE path async. +- Python-owned browser launching, callback listener, UI, terminal prompts, or credential file paths. +- Accepting an arbitrary Python HTTP client as the Rust Eggfetch client. +- Publishing to PyPI, publishing a Rust crate, or changing the existing crates.io release workflows. +- UniFFI, CFFI, or raw C ABI support unless a future multi-language or non-CPython requirement justifies it. + +## Acceptance checklist + +- [x] The Python binding is a separate package; core `eggpass-auth` remains Python-free. +- [x] Awaitable Rust operations integrate with `asyncio` via the Tokio bridge; no nested `block_on` or per-call runtime is used. +- [x] The Python API owns/configures its Rust Eggfetch client explicitly and documents transport limitations. +- [x] Pending authorization stays opaque and one-use; callback validation remains inside Rust. +- [x] Device-flow cancellation, credentials, errors, and debug/repr behavior preserve the Rust security contract. +- [x] Python storage/`TokenManager` support is explicitly deferred; no object-safe Python trait is implied. +- [x] Local-stub Python tests cover authorization, refresh, device polling/cancellation, security, and event-loop behavior; provider-live calls are absent from CI. +- [ ] Full wheel/sdist platform-matrix validation remains pending: local macOS arm64 passes; Ubuntu x86_64 CPython 3.9/3.14 is configured but unrun; Windows and other architectures are unqualified. +- [x] Existing root Rust workspace checks pass; no PyPI or crates.io publication occurred. + +## Research references + +Local implementation and conventions: + +- Existing Rust API contract and example: `crates/eggpass-auth/README.md`, `crates/eggpass-auth/src/lib.rs`, `crates/eggpass-auth/src/client.rs`, `crates/eggpass-auth/src/token.rs`, `crates/eggpass-auth/src/manager.rs`, `crates/eggpass-auth/src/error.rs`, `crates/eggpass-auth/examples/downstream.rs`. +- Existing implementation plan and crate/workspace release context: `plans/async-auth-library-implementation.md`, `Cargo.toml`, `.github/workflows/ci.yml`. + +Current official binding and packaging guidance reviewed 2026-11-17: + +- [PyO3 async/await guide](https://pyo3.rs/v0.30.1/async-await) — native async binding status, future bounds, cancellation, interpreter attachment. +- [PyO3 ecosystem async guide](https://pyo3.rs/v0.30.1/ecosystem/async-await) — recommends `pyo3-async-runtimes` for Python/Rust async interoperability. +- [pyo3-async-runtimes](https://github.com/PyO3/pyo3-async-runtimes) — Tokio runtime integration and `future_into_py` pattern. +- [Maturin project layout](https://www.maturin.rs/project_layout), [bindings](https://www.maturin.rs/bindings), and [distribution](https://www.maturin.rs/distribution) — mixed packages, PyO3/UniFFI/CFFI modes, wheels, source distributions, and platform portability. +- [UniFFI async support](https://mozilla.github.io/uniffi-rs/0.32/futures.html) — async Python bindings and cancellation/runtime tradeoffs; retained as an alternative, not the proposed route. diff --git a/plans/python-pypi-release-implementation.md b/plans/python-pypi-release-implementation.md new file mode 100644 index 0000000..e0e33a5 --- /dev/null +++ b/plans/python-pypi-release-implementation.md @@ -0,0 +1,130 @@ +# Python `eggpass-auth` — PyPI Release Implementation Plan + +**Status:** Implementation prepared; local checks passed on macOS arm64 / CPython 3.14. The full GitHub target matrix, GitHub/PyPI publisher configuration, reviewed commit/tag/release, Raspberry Pi device check, and first public upload remain outstanding. This document and the implementation do not authorize publication. + +**Research checked:** 2026-11-17. + +**Scope:** Prepare the independent `python/eggpass-auth` distribution for a first PyPI release, with documented Python support, reviewed wheel coverage, and a secure, separate publish path. This extends the packaging/validation work in [`python-pyo3-bindings-implementation.md`](python-pyo3-bindings-implementation.md); it does not redo the binding implementation. + +## Goal + +Publish a reviewed `eggpass-auth` Python release with accurate package metadata and user documentation, tested distributions for a clearly defined set of CPython/platform targets, and an isolated PyPI Trusted Publishing workflow. Keep the Rust crate and Eggpass CLI release identities and workflows independent. + +This implementation prepares release-readiness files in the worktree. It does not authorize a public PyPI upload; the first upload requires fresh, explicit confirmation immediately before publication. + +## Pre-implementation baseline and known gaps + +The following records the state found during research, before the implementation described below. + +- `python/eggpass-auth/pyproject.toml` declares package `eggpass-auth` version `0.1.0`, `requires-python = ">=3.9"`, `readme = "README.md"`, and Python classifiers through 3.14. The README reference is correctly relative to the package root; keep it pointed at the package's auth-library guide rather than the root CLI README. +- The package README already has Python authorization-code, device-flow, and profile examples. `docs/README.md` does not currently link to that guide. Link the guide; do not duplicate or replace the root CLI README. +- `.github/workflows/python-auth.yml` tests Ubuntu x86_64 on Python 3.9 and 3.14 and separately builds/installs an sdist. The package README reports a local macOS arm64 / CPython 3.14 wheel and sdist install, but the GitHub workflow has not run; Windows and other architectures remain unqualified. +- The current binding enables PyO3 `abi3-py39` and `extension-module`, and CI pins Maturin 1.9.5. The stable ABI can reduce the number of per-Python-version wheels for GIL-enabled CPython, but each OS/architecture still needs its own wheel. PyO3's current guide recommends migrating away from `extension-module`; review this alongside the CI/build changes. +- The existing auth Rust publisher is crates.io-only and follows `eggpass-auth-vX.Y.Z`. There is no separate PyPI publisher in the checked workflow set. Do not reuse the Rust auth tag for Python releases. +- The observed worktree contains numerous modified and untracked files, including the Python package and workflows. Review and commit the intended release inputs explicitly; never stage the entire worktree as part of this plan. +- The live `https://pypi.org/pypi/eggpass-auth/json` endpoint returned `Not Found` on 2026-11-17. Treat this only as a point-in-time availability check, not a reservation or guarantee. + +## Approved first-release policy + +The user selected these support boundaries on 2026-11-17; metadata, docs, and CI should stay aligned with them. + +1. **Python policy:** Declare and test GIL-enabled CPython 3.11–3.15. Set `requires-python = ">=3.11"` and PyO3's stable ABI floor to `abi3-py311`; test the same `cp311-abi3` wheels on each supported CPython minor. Require Maturin `>=1.16.0,<2.0` and pin CI/release builds to 1.16.0. +2. **Free-threaded CPython 3.15:** Exclude 3.15t from the first-release claim. Reconsider only after separately building/testing the required `abi3t` wheels and auditing native thread-safety. +3. **Baseline PyPI wheels:** Target Linux x86_64 and aarch64, macOS x86_64 and arm64, and Windows x86_64, plus an sdist. Use the manylinux2014 compatibility target for Linux wheels. Musllinux and Windows arm64 are not included. +4. **32-bit ARM / Raspberry Pi:** The selected initial path is a Linux aarch64 wheel plus an sdist. Do not claim armv7l/armv6l or universal Raspberry Pi support; a compatible 64-bit Pi OS must still be checked on-device before claiming it as qualified. sdist and piwheels builds for Pi are not guaranteed until tested. Maturin supports additional targets, but PyPI ARM wheels must demonstrate portability beyond Raspberry Pi hardware. +5. **Release identity:** Keep the current Python package version `0.1.0` aligned between `pyproject.toml` and the binding crate manifest. Use `eggpass-auth-python-vX.Y.Z`, separate from `eggpass-auth-vX.Y.Z` and the root `vX.Y.Z` CLI tag, with a protected GitHub `pypi` environment. +6. **README/docs:** Keep `python/eggpass-auth/README.md` as the PyPI long-description source, preserve its Python auth-library examples, and link it from the docs index. Keep the root README focused on the CLI. + +The PyPI JSON endpoint returned `Not Found` when rechecked on 2026-11-17. This is not a name reservation or proof that the project will remain available. No PyPI Publisher or GitHub Environment configuration, tag, commit, GitHub release, TestPyPI upload, or PyPI upload has been performed by this implementation. + +## Implementation progress + +- **Stage 0 — Policy:** The user approved CPython 3.11–3.15 (GIL-enabled), the five-platform wheel matrix, a Linux aarch64 wheel plus sdist, and no 32-bit ARM/Pi or free-threaded claim. The PyPI name endpoint was rechecked; ownership and account settings still need maintainer action. +- **Stage 1 — Metadata/docs:** Updated Python minimum/classifiers, `abi3-py311`, Maturin build requirement, project URLs, package README support boundaries, docs index, and release instructions. The package-local auth guide remains the PyPI README; the root README was not changed. +- **Stage 2 — CI:** Authored wheel build/install tests for all five target platforms across CPython 3.11–3.15, plus isolated sdist build/install tests across those minors. Locally on macOS arm64 / CPython 3.14, Rust fmt/clippy/tests, Maturin 1.16.0 wheel and sdist builds, `twine check`, clean wheel/sdist installs, imports, `pip check`, mypy, pytest (4 passed each), and `maturin develop` passed. `actionlint` and `yamllint` pass. The GitHub matrix has not run, and no Raspberry Pi device or piwheels build was tested. +- **Stage 3 — Publisher:** Added a Python-only publisher with version/tag checks, read-only build/validation jobs, artifact/tag validation, verification-only manual dispatch, and OIDC permission isolated to the publish job. `actionlint`/`yamllint` pass. PyPI Trusted Publisher and protected GitHub environment/reviewer settings are not configured. +- **Stage 4 — Candidate:** Not complete. These files have not been committed or tagged; no GitHub release or TestPyPI/PyPI upload was created. The first upload remains gated on full CI/artifact review and fresh explicit user authorization. + +## Staged implementation + +### Stage 0 — Approve policy and confirm release boundary + +- Recheck PyPI project-name availability immediately before implementation; confirm who owns/configures the project and its Trusted Publisher. PyPI supports configuring a pending Trusted Publisher that creates a new project on its first successful upload. +- Approve the Python floor, supported Python builds (GIL-enabled only versus free-threaded 3.15), initial OS/architecture matrix, and Raspberry Pi/ARMv6 expectations. Record them once and use the same policy in metadata, docs, CI, and wheel filenames. +- Confirm the Python package version to publish and the independent tag format. Confirm root and crates.io workflows ignore Python release tags. +- Inventory the exact package/workflow/docs files intended for commit and keep unrelated worktree changes untouched. + +**Exit:** Name/ownership, version policy, platform scope, tag boundary, and non-publication implementation scope are explicit. + +### Stage 1 — Align metadata, README, and distribution contents + +- Update `requires-python`, Python classifiers, and PyO3 stable-ABI floor to the approved minimum; add the Python 3.15 classifier if 3.15 is in the supported range. Do not add a free-threaded claim unless Stage 0 selected it. +- Keep `readme = "README.md"` pointing to the package-local guide. Link the Python auth guide from `docs/README.md`; keep the root README focused on the Eggpass CLI. +- Review package classifiers, project URLs, license metadata/files, and version fields for completeness and consistency. Verify the sdist contains the package README, license, Rust binding source, lockfile as required, and self-contained vendored `eggpass-auth` source. +- Remove PyO3's deprecated `extension-module` feature. Require Maturin `>=1.16.0,<2.0` and pin CI/release builds to 1.16.0; validate Rust tests, wheel builds, sdist installs, and local development against that version. +- Add no unnecessary user-facing promises: distinguish compiled wheels, sdist/source builds, generic ARM, Raspberry Pi, and free-threaded Python support. + +**Exit:** Package metadata and PyPI long description accurately describe the released API and supported targets; an isolated sdist includes everything needed to build without repository-only paths. + +### Stage 2 — Expand and execute validation CI + +- Extend the Python test matrix to every supported minor version (recommended 3.11, 3.12, 3.13, 3.14, 3.15, GIL-enabled). Build the stable-ABI wheel per OS/architecture, then install and test it on each supported Python minor version; do not create redundant per-minor wheels unless the chosen ABI requires them. +- Build/install native wheels on Linux x86_64 and aarch64, macOS x86_64 and arm64, and Windows x86_64. Use Maturin's supported manylinux build path and a maintained Maturin action where appropriate. Keep build-only cross-compilation distinct from import/tests on a target runtime; use native runners or documented emulation where feasible. +- Run the existing Rust formatting/lint/tests, Python type checks, local-stub Python tests, and clean sdist build/install. Run the workflow on GitHub and record actual results; configuration alone is not qualification. +- Add armv7l and/or armv6l testing only for the explicitly selected ARM support path. Test on actual or representative generic ARM systems, not only Raspberry Pi. Before claiming Pi support from the sdist, confirm that piwheels can build this Rust package and verify a released version's build outcome; separately test 64-bit Pi OS against the aarch64 PyPI wheel. +- Check wheel tags, linked native dependencies and platform floors. Test clean installation/import on each target, not just wheel creation. Test the minimum Python version as well as 3.15. + +**Exit:** All advertised interpreters and wheels have clean install/import and test evidence; sdist rebuild works in an isolated environment; unqualified targets remain clearly excluded from claims. + +### Stage 3 — Add an isolated PyPI publication workflow + +- Create a dedicated Python-only publishing workflow. Build and validate the sdist/wheels in a separate job with read-only permissions; transfer only the verified artifacts to a narrowly scoped publish job. +- Use PyPI Trusted Publishing via GitHub OIDC and the official `pypa/gh-action-pypi-publish@release/v1`. Grant `id-token: write` only to the publish job, not the workflow or build matrix. Use the exact repository/workflow/environment in the PyPI Trusted Publisher configuration and a protected `pypi` GitHub environment, with required reviewer approval if available. +- Validate the release tag against the Python package version and reject the Rust auth tag, root Eggpass tags, branches, pull requests, and mismatched versions. A dry-run/manual validation path must be incapable of uploading, even if an input is changed. Do not add long-lived PyPI API tokens. +- Publish only prebuilt, reviewed artifacts; keep the publish job free of checkout/build steps so code execution is minimized near OIDC credentials. Use PyPI's automatic attestations from the official publishing action and retain artifact/build provenance where practical. +- Test the workflow with a safe non-production path (for example, a separately configured TestPyPI publisher) if needed. Never assume TestPyPI metadata or package state is shared with PyPI. +- Update maintainer release guidance with the Python version/tag convention, exact workflow procedure, artifact review, OIDC configuration, and distinction from Rust/crate releases. + +**Exit:** Workflow/static checks prove the only eligible publish path is the intended protected Python release; no root or crates.io release action is triggered by its tag; no credentials are stored. + +### Stage 4 — Prepare and review the first release candidate (no upload in this plan) + +- Ensure the Python package, CI, docs links, and publisher are included in a reviewed commit. Do not tag uncommitted/untracked content or include unrelated worktree changes. +- Build the exact release commit's sdist and wheels; run `twine check` (or equivalent metadata validation), inspect the rendered long description, confirm filenames/tags, and install from the artifacts in clean environments. +- Recheck PyPI name availability and configure the exact pending/normal Trusted Publisher. Inspect the release tag, package version, files, attestation configuration, and protected environment before the publish job can run. +- Stop before the first public upload until the user gives fresh, explicit confirmation. A published file/version cannot be overwritten; fix mistakes with a new version or yank where appropriate, not by reusing the same version. + +**Exit:** Candidate artifacts and workflow are reviewed and ready; publication remains unperformed and separately gated. + +## Acceptance checklist + +- [x] Python minimum, classifiers, ABI floor, GIL/free-threaded scope, and OS/architecture promises agree. +- [x] Python examples remain in the package README; docs index links to it; root README remains the CLI guide. +- [ ] Clean sdist and every advertised wheel build, install, import, and pass the package checks on the stated target matrix. +- [ ] Linux x86_64/aarch64, macOS x86_64/arm64, and Windows x86_64 are qualified for the chosen CPython range; ARMv7/armv6/Pi coverage is separately evidenced or explicitly excluded. +- [x] Local-stub tests and type checks pass; package source is self-contained; no provider-live OAuth tests are needed for CI. +- [ ] Publisher is PyPI Trusted Publishing/OIDC, protected by an exact environment/tag/version boundary; only the publish job has OIDC permission; no long-lived token is used. +- [x] Python release tag cannot trigger root Eggpass or crates.io publication. +- [ ] First release artifact review is complete; no upload occurs without fresh explicit user confirmation. + +## Remaining scope boundaries + +- No commit, push, tag, GitHub release, TestPyPI upload, PyPI Publisher/GitHub Environment configuration, or PyPI upload was performed. The first upload needs fresh, explicit user authorization. +- Unrelated worktree changes were preserved. Review and stage only the intended package/workflow/docs changes; do not stage the whole worktree. +- Do not claim ARMv6, 32-bit ARM/Pi wheels, universal Raspberry Pi support, musllinux, Windows ARM64, PyPy, or free-threaded Python 3.15. A compatible 64-bit Pi still requires an actual device/OS check. +- Do not modify the Rust crate API or merge Python versioning into the Rust/CLI release process. + +## Research references + +Repository evidence: + +- [`python-pyo3-bindings-implementation.md`](python-pyo3-bindings-implementation.md) — current binding plan and pending platform validation. +- `python/eggpass-auth/pyproject.toml`, `python/eggpass-auth/README.md`, `python/eggpass-auth/Cargo.toml`, `.github/workflows/python-auth.yml`, `.github/workflows/publish-eggpass-auth-pypi.yml`, `.github/workflows/publish-eggpass-auth.yml`, `docs/README.md`, and `docs/releasing.md`. + +External guidance checked 2026-11-17: + +- [Python version status](https://devguide.python.org/versions/) — lifecycle of Python 3.11–3.15. +- [PyO3 0.30.1 building and distribution](https://pyo3.rs/v0.30.1/building-and-distribution) and [features](https://pyo3.rs/v0.30.1/features.html) — `abi3`, `abi3t`, minimum versions, and Maturin requirements; [FAQ](https://pyo3.rs/v0.30.1/faq) — migration away from `extension-module`. +- [Maturin platform support](https://www.maturin.rs/platform_support), [Maturin action](https://github.com/PyO3/maturin-action), and [Maturin changelog](https://www.maturin.rs/changelog) — target support, CI building, and current Python 3.15/stable-ABI fixes in 1.16.0. +- [piwheels FAQ](https://www.piwheels.org/faq.html) — Raspberry Pi build availability, 32-/64-bit OS limits, and caution about publishing Raspberry-Pi-built ARM wheels to PyPI for broader ARM audiences. +- [Adding a PyPI Trusted Publisher](https://docs.pypi.org/trusted-publishers/adding-a-publisher/), [publishing with one](https://docs.pypi.org/trusted-publishers/using-a-publisher/), [security model](https://docs.pypi.org/trusted-publishers/security-model/), and [producing attestations](https://docs.pypi.org/attestations/producing-attestations/) — OIDC, least-privilege publish jobs, protected environments, and automatic attestations. diff --git a/python/eggpass-auth/Cargo.lock b/python/eggpass-auth/Cargo.lock new file mode 100644 index 0000000..62d2203 --- /dev/null +++ b/python/eggpass-auth/Cargo.lock @@ -0,0 +1,1333 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "eggfetch-core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c22bdfc6ab683ddf5d5fcf0321b60dfc86c0ec1311284a33c31f536d12c1d2ae" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "getrandom 0.2.17", + "http", + "http-body", + "http-body-util", + "httpdate", + "hyper", + "hyper-rustls", + "hyper-util", + "pem-rfc7468", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-native-certs", + "thiserror", + "tokio", + "tokio-rustls", + "tower-service", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "eggpass-auth" +version = "0.1.0" +dependencies = [ + "base64", + "eggfetch-core", + "rand", + "serde", + "serde_json", + "sha2", + "tempfile", + "tokio", + "tokio-util", + "url", +] + +[[package]] +name = "eggpass-auth-python" +version = "0.1.0" +dependencies = [ + "eggpass-auth", + "pyo3", + "pyo3-async-runtimes", + "serde_json", +] + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "log", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "libc", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "pem-rfc7468" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "801ef81ab8a21fdd738a9de457509b5c0aef72efa93ffdfc80f3329a1588405b" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pyo3" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229ca13b8a15bb0d1487b81ab975bfcd97513416499a8312011b6036e42e0de4" +dependencies = [ + "libc", + "once_cell", + "portable-atomic", + "pyo3-build-config", + "pyo3-ffi", + "pyo3-macros", +] + +[[package]] +name = "pyo3-async-runtimes" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b877331c7817ccb6379e9d19a06993160141f1d0a386e55276128717df85e3fc" +dependencies = [ + "futures-channel", + "futures-util", + "once_cell", + "pin-project-lite", + "pyo3", + "tokio", +] + +[[package]] +name = "pyo3-build-config" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70130e2b6dd1ee589a8788026a429561ca5c40fa7a2fa7914c2282eddae24700" +dependencies = [ + "target-lexicon", +] + +[[package]] +name = "pyo3-ffi" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e7ff73c555c286d212d4ce7e5fbda845a973c4f61bd5f160f5f2c3c2a04d1c4" +dependencies = [ + "libc", + "pyo3-build-config", +] + +[[package]] +name = "pyo3-macros" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c46d2e5862c7bb8207e3b639f713dda3c499933444784154c11d013c5a691b60" +dependencies = [ + "proc-macro2", + "pyo3-macros-backend", + "quote", + "syn", +] + +[[package]] +name = "pyo3-macros-backend" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b89f066f2ae72a2aef52d1537ca2fcd104440ebfadee06e97aa90738a25b9b" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "target-lexicon" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "futures-util", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/python/eggpass-auth/Cargo.toml b/python/eggpass-auth/Cargo.toml new file mode 100644 index 0000000..89d96d4 --- /dev/null +++ b/python/eggpass-auth/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "eggpass-auth-python" +version = "0.1.0" +edition = "2024" +rust-version = "1.89" +description = "Python asyncio bindings for eggpass-auth" +license = "MIT" +repository = "https://github.com/eggstack/eggpass" +documentation = "https://github.com/eggstack/eggpass/tree/main/python/eggpass-auth" + +[workspace] +members = [".", "vendor/eggpass-auth"] +resolver = "3" + +[lib] +name = "_native" +crate-type = ["cdylib"] + +[dependencies] +eggpass-auth = { path = "vendor/eggpass-auth" } +pyo3 = { version = "=0.30.1", features = ["abi3-py311"] } +pyo3-async-runtimes = { version = "=0.30.0", features = ["tokio-runtime"] } +serde_json = "1.0" diff --git a/python/eggpass-auth/LICENSE b/python/eggpass-auth/LICENSE new file mode 100644 index 0000000..329eea1 --- /dev/null +++ b/python/eggpass-auth/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 David Bowman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python/eggpass-auth/README.md b/python/eggpass-auth/README.md new file mode 100644 index 0000000..adbf1a8 --- /dev/null +++ b/python/eggpass-auth/README.md @@ -0,0 +1,86 @@ +# `eggpass-auth` for Python + +This package exposes the Rust `eggpass-auth` OAuth client to Python `asyncio` through PyO3, `pyo3-async-runtimes`, and Tokio. The Rust protocol implementation remains a separate, Python-free crate. The Python distribution is versioned independently. + +## Build and test locally + +From this directory, use a virtual environment and install the local package: + +```sh +python3 -m venv .venv +. .venv/bin/activate +python -m pip install maturin pytest +maturin develop +pytest +``` + +A regular `pip install .` or a Maturin wheel build compiles the extension. The package uses PyO3's `abi3-py311` stable ABI for GIL-enabled CPython. The GitHub Actions matrix builds Linux x86_64/aarch64 wheels with manylinux2014 (glibc), macOS x86_64/arm64 wheels, and a Windows x86_64 wheel; it tests each wheel on CPython 3.11–3.15. The workflows do not build musllinux wheels. Treat a platform as supported for a release only after the corresponding build and wheel-install tests pass. + +The workflows do not build free-threaded CPython 3.15t or 32-bit ARM wheels (including armv6l/armv7l Raspberry Pi wheels). A compatible 64-bit Raspberry Pi OS may be able to use the Linux aarch64 wheel, but that combination is not separately qualified. Building from source requires a working Rust toolchain and the platform's native build prerequisites. + +## Authorization-code flow + +The host application owns browser launching, the callback listener/UI, and credential persistence. Pass the full callback URL to Rust so it can validate the origin, exact path, state, and OIDC nonce: + +```python +from eggpass_auth import OAuthClient, ProviderProfile + +oauth = OAuthClient(ProviderProfile.xai()) +pending = oauth.begin_authorization("http://127.0.0.1:43123/callback") +print("Open this URL in the host UI:", pending.authorization_url) + +async def complete_from_host_callback(callback_url: str): + # The host passes the full URL received by its loopback listener. + return await oauth.complete_authorization(pending, callback_url) +``` + +`PendingAuthorization` is opaque and one-use. Its `repr` never prints the authorization URL or PKCE/state/nonce values. Completion consumes it even if validation or the network request fails. Do not parse the callback into a code/state pair and bypass the full-URL validation. + +For pasted-code flows, use `complete_authorization_with_code`. The lower-level `exchange_authorization_code` method is also available when the host intentionally manages PKCE material itself. + +## Device flow and cancellation + +```python +from eggpass_auth import CancellationToken, OAuthClient, ProviderProfile + +async def device_login(): + oauth = OAuthClient(ProviderProfile.xai()) + device = await oauth.request_device_code() + print(device.user_code, device.verification_uri) + cancellation = CancellationToken() + try: + return await oauth.poll_device_authorization( + device, cancellation, timeout_seconds=600 + ) + finally: + cancellation.cancel() +``` + +Pass a `CancellationToken` when the host needs to stop the Rust polling loop explicitly. Cancelling an `asyncio.Task` should not be treated as a signal to every shared token; call `cancel()` on the token. No Python polling or networking work blocks the event loop. + +## Profiles and transport + +`ProviderProfile.xai()`, `ProviderProfile.xai_compatibility_fallback()`, and `ProviderProfile.openai()` provide the built-in profiles. Custom profiles are validated by the Rust provider builder: + +```python +profile = ProviderProfile.custom("Example", "https://auth.example", "public-client") +profile.authorization_endpoint("https://auth.example/authorize") +profile.token_endpoint("https://auth.example/token") +profile.callback_path("/callback") +profile.scopes(["offline_access"]) +profile = profile.build() +``` + +`OAuthClient` constructs and owns its Rust Eggfetch client. It accepts a finite `timeout_seconds` and a positive `max_response_body_bytes`; a Python `requests`, `httpx`, or `aiohttp` session cannot be injected. V1 does not expose custom proxy, root-certificate, or arbitrary transport configuration. OAuth requests suppress inherited default authentication, disable redirects and retries, and use bounded response bodies. + +## Credentials and errors + +Token fields are available explicitly when the host needs to persist or use them. `Credentials.to_json()` and `Credentials.from_json()` are secret-bearing storage APIs: protect their output and do not log it. `repr()` for credentials, token sets, pending authorizations, device codes, and clients redacts secrets and sensitive URLs. Exceptions expose only safe protocol facts; OAuth errors provide a recognized `code` and HTTP `status` when available. + +Python owns persistence and refresh scheduling in V1. The Rust generic async `CredentialStore` / `TokenManager` API is not exposed: an async Python storage adapter has not been proven safe or atomic. `refresh_token()` returns provider tokens; `refresh_credentials()` merges them while retaining the old refresh token if rotation was omitted. Persist the returned credentials yourself. Rust single-flight management is therefore not claimed for Python callers. + +All network operations are awaitable on the caller's running `asyncio` loop. Do not start a nested event loop or call `block_on`. Browser/UI, callback reception, and filesystem paths remain with the host application. + +## Packaging scope + +The sdist includes a self-contained snapshot of the local `eggpass-auth` crate, so it builds without a published Rust crate. In the monorepo checkout, `vendor/eggpass-auth` is generated from `../../crates/eggpass-auth`; run `python tools/sync_core.py --check` to verify it, or `python tools/sync_core.py --sync` after intentional core changes. Python releases use a separate `eggpass-auth-python-vX.Y.Z` tag and PyPI Trusted Publishing workflow; they do not publish the Rust crate or Eggpass CLI. Publishing remains gated by the protected `pypi` GitHub environment. diff --git a/python/eggpass-auth/pyproject.toml b/python/eggpass-auth/pyproject.toml new file mode 100644 index 0000000..a52c037 --- /dev/null +++ b/python/eggpass-auth/pyproject.toml @@ -0,0 +1,43 @@ +[build-system] +requires = ["maturin>=1.16.0,<2.0"] +build-backend = "maturin" + +[project] +name = "eggpass-auth" +version = "0.1.0" +description = "Async Python bindings for the eggpass-auth OAuth client" +readme = "README.md" +requires-python = ">=3.11" +license = "MIT" +license-files = ["LICENSE"] +keywords = ["oauth", "oauth2", "asyncio", "authentication", "pyo3"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Framework :: AsyncIO", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: 11", + "Programming Language :: Python :: 3 :: 12", + "Programming Language :: Python :: 3 :: 13", + "Programming Language :: Python :: 3 :: 14", + "Programming Language :: Python :: 3 :: 15", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Rust", + "Topic :: Security", +] + +[project.urls] +Homepage = "https://github.com/eggstack/eggpass" +Documentation = "https://github.com/eggstack/eggpass/tree/main/python/eggpass-auth" +Repository = "https://github.com/eggstack/eggpass" +Issues = "https://github.com/eggstack/eggpass/issues" + +[tool.maturin] +manifest-path = "Cargo.toml" +module-name = "eggpass_auth._native" +bindings = "pyo3" +python-source = "src" +strip = true + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/python/eggpass-auth/src/eggpass_auth/__init__.py b/python/eggpass-auth/src/eggpass_auth/__init__.py new file mode 100644 index 0000000..527da4b --- /dev/null +++ b/python/eggpass-auth/src/eggpass_auth/__init__.py @@ -0,0 +1,70 @@ +"""Async Python bindings for the eggpass-auth OAuth protocol client. + +This package owns a Rust Eggfetch client. It does not launch a browser, listen +for callbacks, or persist credentials; those remain responsibilities of the +Python host application. +""" + +from ._native import ( + CallbackMismatchError, + CancellationToken, + CredentialStorageError, + Credentials, + DeviceCode, + DeviceExpiredError, + DevicePoll, + EggpassAuthError, + HttpStatusError, + InvalidConfigurationError, + InvalidResponseError, + NoRefreshTokenError, + NonceMismatchError, + NotLoggedInError, + OAuthClient, + OAuthError, + OperationCancelledError, + OperationTimeoutError, + PendingAuthorization, + ProviderBuilder, + ProviderDeniedError, + ProviderProfile, + ResponseTooLargeError, + StateMismatchError, + TokenSet, + TransportError, + UntrustedVerificationUrlError, + UnsupportedOperationError, + UserInfo, +) + +__all__ = [ + "CallbackMismatchError", + "CancellationToken", + "CredentialStorageError", + "Credentials", + "DeviceCode", + "DeviceExpiredError", + "DevicePoll", + "EggpassAuthError", + "HttpStatusError", + "InvalidConfigurationError", + "InvalidResponseError", + "NoRefreshTokenError", + "NonceMismatchError", + "NotLoggedInError", + "OAuthClient", + "OAuthError", + "OperationCancelledError", + "OperationTimeoutError", + "PendingAuthorization", + "ProviderBuilder", + "ProviderDeniedError", + "ProviderProfile", + "ResponseTooLargeError", + "StateMismatchError", + "TokenSet", + "TransportError", + "UntrustedVerificationUrlError", + "UnsupportedOperationError", + "UserInfo", +] diff --git a/python/eggpass-auth/src/eggpass_auth/__init__.pyi b/python/eggpass-auth/src/eggpass_auth/__init__.pyi new file mode 100644 index 0000000..1b4368f --- /dev/null +++ b/python/eggpass-auth/src/eggpass_auth/__init__.pyi @@ -0,0 +1,151 @@ +from typing import Optional, Sequence + +class EggpassAuthError(Exception): ... +class InvalidConfigurationError(EggpassAuthError): ... +class InvalidResponseError(EggpassAuthError): ... +class HttpStatusError(EggpassAuthError): + status: int +class OAuthError(EggpassAuthError): + status: int + code: str +class ProviderDeniedError(EggpassAuthError): + code: str +class CallbackMismatchError(EggpassAuthError): ... +class StateMismatchError(EggpassAuthError): ... +class NonceMismatchError(EggpassAuthError): ... +class ResponseTooLargeError(EggpassAuthError): ... +class TransportError(EggpassAuthError): ... +class OperationTimeoutError(EggpassAuthError): ... +class UnsupportedOperationError(EggpassAuthError): ... +class DeviceExpiredError(EggpassAuthError): ... +class OperationCancelledError(EggpassAuthError): ... +class UntrustedVerificationUrlError(EggpassAuthError): ... +class NotLoggedInError(EggpassAuthError): ... +class NoRefreshTokenError(EggpassAuthError): ... +class CredentialStorageError(EggpassAuthError): ... + +class ProviderProfile: + @staticmethod + def xai() -> ProviderProfile: ... + @staticmethod + def xai_compatibility_fallback() -> ProviderProfile: ... + @staticmethod + def openai(host_id: Optional[str] = ...) -> ProviderProfile: ... + @staticmethod + def custom(display_name: str, issuer: str, client_id: str) -> ProviderBuilder: ... + @property + def display_name(self) -> str: ... + @property + def issuer(self) -> str: ... + @property + def callback_path(self) -> str: ... + @property + def scopes(self) -> list[str]: ... + @property + def client_id_policy(self) -> str: ... + +class ProviderBuilder: + def authorization_endpoint(self, value: str) -> None: ... + def token_endpoint(self, value: str) -> None: ... + def device_authorization_endpoint(self, value: str) -> None: ... + def userinfo_endpoint(self, value: str) -> None: ... + def revocation_endpoint(self, value: str) -> None: ... + def callback_path(self, value: str) -> None: ... + def scopes(self, values: Sequence[str]) -> None: ... + def client_id_policy(self, value: str) -> None: ... + def authorization_parameter(self, name: str, value: str) -> None: ... + def registration_parameter(self, name: str, value: str) -> None: ... + def token_parameter(self, name: str, value: str) -> None: ... + def device_parameter(self, name: str, value: str) -> None: ... + def trusted_device_hosts(self, hosts: Sequence[str]) -> None: ... + def build(self) -> ProviderProfile: ... + +class OAuthClient: + def __init__(self, profile: ProviderProfile, timeout_seconds: int = ..., max_response_body_bytes: int = ...) -> None: ... + @property + def provider(self) -> ProviderProfile: ... + def begin_authorization(self, redirect_uri: str, existing: Optional[Credentials] = ...) -> PendingAuthorization: ... + async def complete_authorization(self, pending: PendingAuthorization, callback_url: str) -> Credentials: ... + async def complete_authorization_with_code(self, pending: PendingAuthorization, code: str) -> Credentials: ... + async def exchange_authorization_code(self, code: str, redirect_uri: str, code_verifier: str, client_id: Optional[str] = ...) -> Credentials: ... + async def refresh_token(self, refresh_token: str, client_id: Optional[str] = ...) -> TokenSet: ... + async def refresh_credentials(self, credentials: Credentials) -> Credentials: ... + async def revoke(self, token: str, client_id: Optional[str] = ...) -> None: ... + async def userinfo(self, access_token: str) -> UserInfo: ... + async def request_device_code(self) -> DeviceCode: ... + async def poll_device_code(self, device: DeviceCode) -> DevicePoll: ... + async def poll_device_authorization(self, device: DeviceCode, cancellation: Optional[CancellationToken] = ..., timeout_seconds: int = ...) -> Credentials: ... + +class PendingAuthorization: + @property + def authorization_url(self) -> str: ... + @property + def consumed(self) -> bool: ... + +class Credentials: + @property + def access_token(self) -> str: ... + @property + def refresh_token(self) -> Optional[str]: ... + @property + def id_token(self) -> Optional[str]: ... + @property + def token_type(self) -> str: ... + @property + def scope(self) -> Optional[str]: ... + @property + def client_id(self) -> str: ... + @property + def issuer(self) -> str: ... + @property + def expires_at(self) -> Optional[int]: ... + @property + def obtained_at(self) -> int: ... + def is_fresh(self, now_unix: Optional[int] = ..., skew_seconds: int = ...) -> bool: ... + def to_json(self) -> str: ... + @staticmethod + def from_json(serialized: str) -> Credentials: ... + +class TokenSet: + @property + def access_token(self) -> str: ... + @property + def refresh_token(self) -> Optional[str]: ... + @property + def id_token(self) -> Optional[str]: ... + @property + def token_type(self) -> str: ... + @property + def scope(self) -> Optional[str]: ... + @property + def expires_at(self) -> Optional[int]: ... + +class DeviceCode: + @property + def user_code(self) -> str: ... + @property + def verification_uri(self) -> str: ... + @property + def verification_uri_complete(self) -> Optional[str]: ... + @property + def expires_in_seconds(self) -> float: ... + @property + def interval_seconds(self) -> float: ... + +class DevicePoll: + @property + def status(self) -> str: ... + @property + def tokens(self) -> Optional[TokenSet]: ... + +class UserInfo: + @property + def user_id(self) -> Optional[str]: ... + @property + def email(self) -> Optional[str]: ... + +class CancellationToken: + def __init__(self) -> None: ... + def cancel(self) -> None: ... + @property + def is_cancelled(self) -> bool: ... diff --git a/python/eggpass-auth/src/eggpass_auth/py.typed b/python/eggpass-auth/src/eggpass_auth/py.typed new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/python/eggpass-auth/src/eggpass_auth/py.typed @@ -0,0 +1 @@ + diff --git a/python/eggpass-auth/src/lib.rs b/python/eggpass-auth/src/lib.rs new file mode 100644 index 0000000..acad76b --- /dev/null +++ b/python/eggpass-auth/src/lib.rs @@ -0,0 +1,897 @@ +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use eggpass_auth::{ + CancellationToken, ClientIdPolicy, ClientOptions, Credentials, DeviceCode, DevicePoll, Error, + OAuthClient, OAuthProviderConfig, PendingAuthorization, TokenSet, UserInfo, +}; +use pyo3::create_exception; +use pyo3::exceptions::PyException; +use pyo3::prelude::*; +use pyo3::types::PyModule; +use pyo3_async_runtimes::tokio::future_into_py; + +create_exception!(_native, EggpassAuthError, PyException); +create_exception!(_native, InvalidConfigurationError, EggpassAuthError); +create_exception!(_native, InvalidResponseError, EggpassAuthError); +create_exception!(_native, HttpStatusError, EggpassAuthError); +create_exception!(_native, OAuthError, EggpassAuthError); +create_exception!(_native, ProviderDeniedError, EggpassAuthError); +create_exception!(_native, CallbackMismatchError, EggpassAuthError); +create_exception!(_native, StateMismatchError, EggpassAuthError); +create_exception!(_native, NonceMismatchError, EggpassAuthError); +create_exception!(_native, ResponseTooLargeError, EggpassAuthError); +create_exception!(_native, TransportError, EggpassAuthError); +create_exception!(_native, OperationTimeoutError, EggpassAuthError); +create_exception!(_native, UnsupportedOperationError, EggpassAuthError); +create_exception!(_native, DeviceExpiredError, EggpassAuthError); +create_exception!(_native, OperationCancelledError, EggpassAuthError); +create_exception!(_native, UntrustedVerificationUrlError, EggpassAuthError); +create_exception!(_native, NotLoggedInError, EggpassAuthError); +create_exception!(_native, NoRefreshTokenError, EggpassAuthError); +create_exception!(_native, CredentialStorageError, EggpassAuthError); + +fn map_error(error: Error) -> PyErr { + match error { + Error::InvalidResponse(message) => InvalidResponseError::new_err(message), + Error::InvalidConfiguration(message) => InvalidConfigurationError::new_err(message), + Error::HttpStatus { status } => { + let py_error = HttpStatusError::new_err(format!("HTTP {status} from OAuth endpoint")); + Python::attach(|py| { + let _ = py_error.value(py).setattr("status", status); + }); + py_error + } + Error::OAuth { status, code } => { + let py_error = + OAuthError::new_err(format!("OAuth endpoint returned HTTP {status} ({code})")); + Python::attach(|py| { + let value = py_error.value(py); + let _ = value.setattr("status", status); + let _ = value.setattr("code", code); + }); + py_error + } + Error::ProviderDenied(code) => { + let py_error = + ProviderDeniedError::new_err(format!("provider denied authorization ({code})")); + Python::attach(|py| { + let _ = py_error.value(py).setattr("code", code); + }); + py_error + } + Error::CallbackMismatch => { + CallbackMismatchError::new_err("callback did not match the pending authorization") + } + Error::StateMismatch => { + StateMismatchError::new_err("callback state did not match the pending authorization") + } + Error::NonceMismatch => { + NonceMismatchError::new_err("ID-token nonce did not match the pending authorization") + } + Error::ResponseTooLarge => { + ResponseTooLargeError::new_err("OAuth response exceeded the configured body limit") + } + Error::Transport => TransportError::new_err("OAuth HTTP request failed"), + Error::Timeout(operation) => { + OperationTimeoutError::new_err(format!("OAuth {operation} timed out")) + } + Error::Unsupported(operation) => { + UnsupportedOperationError::new_err(format!("provider does not support {operation}")) + } + Error::DeviceExpired => DeviceExpiredError::new_err("device authorization expired"), + Error::Cancelled => OperationCancelledError::new_err("device authorization was cancelled"), + Error::UntrustedVerificationUrl { .. } => UntrustedVerificationUrlError::new_err( + "device verification URL was rejected by the trusted-host policy", + ), + Error::NotLoggedIn => NotLoggedInError::new_err("no credentials are stored"), + Error::NoRefreshToken => { + NoRefreshTokenError::new_err("stored credentials contain no refresh token") + } + Error::Storage(_) => CredentialStorageError::new_err("credential storage failed"), + _ => EggpassAuthError::new_err("OAuth operation failed"), + } +} + +#[pyclass(name = "ProviderProfile", module = "eggpass_auth._native")] +struct PyProviderProfile { + inner: OAuthProviderConfig, +} + +#[pymethods] +impl PyProviderProfile { + #[staticmethod] + fn xai() -> Self { + Self { + inner: OAuthProviderConfig::xai(), + } + } + + #[staticmethod] + fn xai_compatibility_fallback() -> Self { + Self { + inner: OAuthProviderConfig::xai_compatibility_fallback(), + } + } + + #[staticmethod] + #[pyo3(signature = (host_id=None))] + fn openai(host_id: Option) -> PyResult { + let inner = match host_id { + Some(host_id) => OAuthProviderConfig::openai_with_host_id(host_id), + None => Ok(OAuthProviderConfig::openai()), + } + .map_err(map_error)?; + Ok(Self { inner }) + } + + #[staticmethod] + fn custom(display_name: String, issuer: String, client_id: String) -> PyProviderBuilder { + PyProviderBuilder { + display_name, + issuer, + client_id, + authorization_endpoint: None, + token_endpoint: None, + device_authorization_endpoint: None, + userinfo_endpoint: None, + revocation_endpoint: None, + callback_path: "/callback".to_string(), + scopes: Vec::new(), + client_id_policy: ClientIdPolicy::Fixed, + authorization_parameters: Vec::new(), + registration_parameters: Vec::new(), + token_parameters: Vec::new(), + device_parameters: Vec::new(), + trusted_device_hosts: Vec::new(), + } + } + + #[getter] + fn display_name(&self) -> String { + self.inner.display_name().to_string() + } + + #[getter] + fn issuer(&self) -> String { + self.inner.issuer().to_string() + } + + #[getter] + fn callback_path(&self) -> String { + self.inner.callback_path().to_string() + } + + #[getter] + fn scopes(&self) -> Vec { + self.inner.scopes().to_vec() + } + + #[getter] + fn client_id_policy(&self) -> &'static str { + match self.inner.client_id_policy() { + ClientIdPolicy::Fixed => "fixed", + ClientIdPolicy::IssuedOnRegistration => "issued_on_registration", + _ => "unknown", + } + } + + fn __repr__(&self) -> &'static str { + "ProviderProfile(