From ad95a44375c7f58d9207af8b0d227e7bfa978d22 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 23 Nov 2026 19:19:45 +0000 Subject: [PATCH 01/13] feat: add installers and provenance-safe updates --- .github/workflows/ci.yml | 12 + .github/workflows/release.yml | 2 +- README.md | 51 ++- docs/releasing.md | 20 +- docs/updating.md | 83 ++-- packaging/install.ps1 | 293 ++++++++++++ packaging/install.sh | 472 ++++++++++++++++++++ packaging/tests/test-install.ps1 | 219 +++++++++ packaging/tests/test-install.sh | 229 ++++++++++ release/eggpack/github-policy.json | 3 +- release/eggpack/github-template.json | 2 +- release/eggpack/installer-presentation.json | 11 + scripts/check-installer-contract.py | 101 +++++ src/cli/commands/update.rs | 18 +- src/update.rs | 374 ++++++++++++++-- src/update_tests.rs | 449 +++++++++++++++++++ 16 files changed, 2266 insertions(+), 73 deletions(-) create mode 100644 packaging/install.ps1 create mode 100644 packaging/install.sh create mode 100644 packaging/tests/test-install.ps1 create mode 100644 packaging/tests/test-install.sh create mode 100644 release/eggpack/installer-presentation.json create mode 100644 scripts/check-installer-contract.py create mode 100644 src/update_tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a725c76..bd6b188 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,6 +16,11 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Test bootstrap installers + run: | + bash -n packaging/install.sh + bash packaging/tests/test-install.sh + - name: Install the toolchain run: | rustup toolchain install stable --profile minimal --no-self-update @@ -52,6 +57,10 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Run PowerShell installer fixtures + shell: pwsh + run: pwsh -NoProfile -File packaging/tests/test-install.ps1 + - name: Set up Rust toolchain uses: dtolnay/rust-toolchain@2c7215f132e9ebf062739d9130488b56d53c060c with: @@ -82,6 +91,9 @@ jobs: cargo install --git https://github.com/eggstack/eggpack --rev "$revision" --locked eggpack-cli eggpack --version + - name: Check installer release contract + run: python3 scripts/check-installer-contract.py + - name: Check generated release workflow run: >- eggpack ci check diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4be3dc0..100b578 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1209,7 +1209,7 @@ jobs: if-no-files-found: error - name: Prepare staging payload shell: bash - run: "'eggpack' 'ci' '_prepare-stage' '--contract' 'release/eggpack/distribution.toml' '--release-manifest' './eggpack-finalized/release-manifest.json' '--finalized-root' './eggpack-finalized/root' '--github-policy' 'eggpack-runtime/github-draft.json' '--install-policy' 'release/eggpack/install-policy.toml' '--output-dir' './eggpack-staging' '--output-payload' './eggpack-staging-payload.json'" + run: "'eggpack' 'ci' '_prepare-stage' '--contract' 'release/eggpack/distribution.toml' '--release-manifest' './eggpack-finalized/release-manifest.json' '--finalized-root' './eggpack-finalized/root' '--github-policy' 'eggpack-runtime/github-draft.json' '--install-policy' 'release/eggpack/install-policy.toml' '--output-dir' './eggpack-staging' '--output-payload' './eggpack-staging-payload.json' '--installer-presentation' 'release/eggpack/installer-presentation.json' '--source-root' '${{ github.workspace }}'" - name: Stage GitHub draft release shell: bash env: diff --git a/README.md b/README.md index a742291..7b47c9f 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,56 @@ need a separate provider API key. ## Install -Install the published CLI from crates.io: +Install the latest prebuilt release on Linux or macOS (Bash): + +```sh +curl -fsSL https://github.com/eggstack/eggpass/releases/latest/download/install.sh | bash +``` + +To pin an exact stable release, use the matching release script and version: + +```sh +curl -fsSL https://github.com/eggstack/eggpass/releases/download/vX.Y.Z/install.sh | bash -s -- --version X.Y.Z +``` + +On Windows, from PowerShell, download and run the latest installer: + +```powershell +$installer = Join-Path $env:TEMP "eggpass-install.ps1" +Invoke-WebRequest -UseBasicParsing -Uri "https://github.com/eggstack/eggpass/releases/latest/download/install.ps1" -OutFile $installer +& $installer +``` + +For a pinned Windows release, change both the script URL to +`https://github.com/eggstack/eggpass/releases/download/vX.Y.Z/install.ps1` and +pass `-Version X.Y.Z` to the script. The installers verify the published SHA-256 +sidecar and the candidate's exact `eggpass --version` identity before installing. +They default to a per-user directory (`~/.local/bin` on Unix or `%LOCALAPPDATA%\Eggpass` +on Windows); Bash can add a safe PATH block to a Bash/Zsh profile. The Bash +installer needs Bash, `curl`, and `sha256sum` or `shasum`; Windows needs +PowerShell 5.1 or later. Prebuilt installs do not require Rust. If the Windows +install directory is not already on PATH, add `%LOCALAPPDATA%\Eggpass` to PATH, +use the full executable path, or for the current PowerShell session run: + +```powershell +$env:Path = "$env:LOCALAPPDATA\Eggpass;$env:Path" +``` + +A system-wide install requires an explicitly elevated shell (`--system` on Bash +or `-System` in PowerShell); neither installer invokes elevation for you. For +example, an explicit Unix system install is: + +```sh +curl -fsSL https://github.com/eggstack/eggpass/releases/latest/download/install.sh | sudo bash -s -- --system +``` + +Unsupported targets fail rather than installing a binary without a supported +updater mapping. On a supported target, Cargo fallback is attempted only when the exact GitHub release +binary asset returns HTTP 404; it requests that same exact crate version, so a +brief crates.io publication lag requires retrying later. Other transport or +verification failures stop without fallback. + +Cargo remains a separate supported install method: ```sh cargo install eggpass diff --git a/docs/releasing.md b/docs/releasing.md index 410a73e..b95d9f1 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -25,16 +25,22 @@ publication. | Manifest file | `release-manifest.json` | The release contains these five binary assets, a matching `.sha256` sidecar -for each, and the manifest: +for each, `release-manifest.json`, and four auxiliary installer assets: - `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` +- `install.sh` and `install.ps1` (Eggpass product wrappers) +- `install-exact.sh` and `install-exact.ps1` (Eggpack-generated exact bootstraps) The Windows executable keeps its `.exe` suffix. Asset names are not -versioned so the `releases/latest/download/` URLs remain stable. +versioned, so binary URLs and the latest installer URLs use +`releases/latest/download/`. Pinned installer scripts select the exact +`vX.Y.Z` release; they do not fetch scripts from the repository's `main` branch. +The four installer files are auxiliary staging assets and are not members of +`release-manifest.json` or the five-target distribution contract. ## Prepare and stage a release @@ -84,8 +90,14 @@ versioned so the `releases/latest/download/` URLs remain stable. 5. Review the staged draft and download every asset into a clean local verification directory. Confirm that: - - all five expected binaries, all five checksum sidecars, and - `release-manifest.json` are present; + - all five expected binaries, all five checksum sidecars, + `release-manifest.json`, and all four installer assets (`install.sh`, + `install.ps1`, `install-exact.sh`, and `install-exact.ps1`) are present; + - latest installer URLs select `releases/latest/download`, pinned installs + select the exact `releases/download/vX.Y.Z` tag, and no installer fetches + mutable source from `main`; + - the four installer files are auxiliary assets and do not appear as + artifacts or targets in `release-manifest.json`; - `schema_version` is `1`, `product_id` is `eggpass`, `release_id` is the plain package version, and `source_revision` matches the full commit the tag peels to; diff --git a/docs/updating.md b/docs/updating.md index 186d516..a5c66e1 100644 --- a/docs/updating.md +++ b/docs/updating.md @@ -10,19 +10,55 @@ eggpass update --check # show the proposed update without changing anything restart a running server. Restart manually when you are ready; restarting ends active streams. -## Verification +## Installers -For the selected release, the updater: +The Bash installer supports Linux and macOS on the published targets: -1. Refuses to replace a binary managed by Cargo. Cargo must update its own - installation. -2. Fetches the release manifest and the matching binary for this system. -3. Checks the download's size and SHA-256 against the manifest. -4. Runs the candidate with `--version` and checks the reported version. -5. Replaces the binary under a lock and rolls back if the operation fails. +```sh +curl -fsSL https://github.com/eggstack/eggpass/releases/latest/download/install.sh | bash +curl -fsSL https://github.com/eggstack/eggpass/releases/download/vX.Y.Z/install.sh | bash -s -- --version X.Y.Z +``` + +On Windows, download the release script, then run it in PowerShell: -The updater replaces only the binary it can prove it owns. If ownership or a -check cannot be established, it refuses the update. +```powershell +$installer = Join-Path $env:TEMP "eggpass-install.ps1" +Invoke-WebRequest -UseBasicParsing -Uri "https://github.com/eggstack/eggpass/releases/latest/download/install.ps1" -OutFile $installer +& $installer +``` + +For a pinned Windows release, use the matching `vX.Y.Z` script URL and pass +`-Version X.Y.Z`. Bash requires `curl` and `sha256sum` or `shasum`; PowerShell +5.1 or later is supported. Prebuilt installs need no Rust; exact-version Cargo +fallback requires Cargo and retries only the selected version. The default +destinations are `~/.local/bin` and `%LOCALAPPDATA%\Eggpass`. Bash can append a +safe PATH block to a Bash/Zsh profile; PowerShell prints PATH guidance, and the +Windows directory can be added to the user PATH or invoked by its full path. +System installs require explicit elevation (`--system` or `-System`). + +## Installation-aware updates + +The updater preserves the installation method: + +- A binary installed by the Eggpass installer is self-managed. It uses Eggup's + existing release-manifest transaction, including exact size/digest checks, + candidate identity validation, lock ownership, atomic commit, and rollback. +- A Cargo-managed install is updated by Cargo only when `.crates.toml` proves + the root, installed version, package, and default crates.io source. The + updater first resolves an exact Eggpass release from GitHub, then requests + that exact version with `--locked --force --root`; it never directly replaces + a Cargo-owned binary. If the release was just published and crates.io has not + indexed that version yet, retry later; no older or floating version is used. +- On Windows, the running executable cannot be safely replaced by an in-process + Cargo update, so Eggpass prints the exact Cargo command to run after it exits. +- Path, Git, alternate-registry, malformed, or unrecognized Cargo sources are + not converted to crates.io installs. They remain manual-only, and `--check` + does not mutate any installation. + +If ownership or source cannot be established, the updater refuses mutation. +For a successful Cargo update it re-reads Cargo's record and runs the installed +`eggpass --version`; success is reported only when both identify the requested +release. ## Integrity limit @@ -30,16 +66,13 @@ The SHA-256 check detects corruption or a mismatch with the manifest. It does not prove who published the manifest or binary. Releases are not signed by this update process. -## Cargo installations - -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: +## Cargo installation sources -```sh -cargo install eggpass --locked --force -``` +Only a positively identified default crates.io install is eligible for automatic +Cargo delegation. Cargo's package record remains authoritative for its root and +source. If the install came from a local path, Git, an alternate registry, or +metadata that Eggpass cannot interpret, update it using the original Cargo +source options; Eggpass will not silently switch it to crates.io. To reinstall from the current repository checkout instead: @@ -49,11 +82,7 @@ cargo install --path . --locked --force ## Exact versions and rollback -An exact version can install an older release, so rollback uses the same -command: - -```sh -eggpass update 0.1.0 -``` - -The updater does not delete or overwrite published releases. +An exact version selects one published release, but `eggpass update` refuses +to downgrade a running build. To install an older stable release, use that +release's pinned installer URL and version instead. The updater does not delete +or overwrite published releases. diff --git a/packaging/install.ps1 b/packaging/install.ps1 new file mode 100644 index 0000000..d082092 --- /dev/null +++ b/packaging/install.ps1 @@ -0,0 +1,293 @@ +<# +Eggpass PowerShell bootstrap installer, adapted from eggstack/gregg packaging/install.ps1 +at fabcaf21bc60f719a5de5b9420490ffed52400e4. +Copyright (c) 2026 The Gregg Authors. MIT License. +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. + +.SYNOPSIS + Install Eggpass from a verified GitHub release. +.DESCRIPTION + The default is a per-user install under LOCALAPPDATA. Use -System explicitly + from an elevated PowerShell session for a system-wide install. No sudo or + elevation prompt is launched. Only the five Eggpack release targets exist. +.PARAMETER Version + Pin the exact stable GitHub CLI release X.Y.Z (optional leading v accepted). +.PARAMETER System + Install under ProgramFiles; requires an already elevated session. +.EXAMPLE + irm https://github.com/eggstack/eggpass/releases/latest/download/install.ps1 | iex +.EXAMPLE + .\install.ps1 -Version 1.2.3 +#> +[CmdletBinding()] +param( + [string]$Version, + [switch]$System +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" +$Repo = "eggstack/eggpass" +$BaseUrl = "https://github.com/$Repo/releases" +$StrippedVersion = "" +$Tag = "" +if ($PSBoundParameters.ContainsKey("Version")) { + if ([string]::IsNullOrWhiteSpace($Version)) { throw "Version must be stable X.Y.Z." } + $StrippedVersion = $Version.Trim() + if ($StrippedVersion.StartsWith("v")) { $StrippedVersion = $StrippedVersion.Substring(1) } + if ($StrippedVersion -notmatch '^[0-9]+\.[0-9]+\.[0-9]+$') { throw "Version must be stable X.Y.Z (got '$Version')" } + $Tag = "v$StrippedVersion" +} + +$Arch = $env:EGGPASS_TEST_ARCH +if (-not $Arch) { $Arch = $env:PROCESSOR_ARCHITEW6432 } +if (-not $Arch) { $Arch = $env:PROCESSOR_ARCHITECTURE } +if (-not $Arch) { $Arch = "unknown" } +$Target = $null +$SupportedBinary = $false +if (($Arch -eq "AMD64" -or $Arch -eq "x86_64") -and [Environment]::Is64BitOperatingSystem) { + $Target = "x86_64-pc-windows-msvc" + $SupportedBinary = $true +} +$Asset = if ($Target) { "eggpass-$Target.exe" } else { $null } +$InstallName = "eggpass.exe" +$IsAdmin = $false +if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { + $IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +} +Write-Host "Detected: ARCH=$Arch TARGET=$(if ($Target) { $Target } else { 'unknown' }) $(if ($Tag) { $Tag } else { 'latest' })" + +function Get-DestDir { + param([bool]$ForSystem) + if ($ForSystem) { + if (-not $script:IsAdmin) { throw "-System requires an already elevated PowerShell session; no elevation is launched." } + if ($env:EGGPASS_TEST_SYSTEM_DIR) { return $env:EGGPASS_TEST_SYSTEM_DIR } + return (Join-Path $env:ProgramFiles "Eggpass") + } + $local = $env:LOCALAPPDATA + if (-not $local) { $local = Join-Path $env:USERPROFILE "AppData\Local" } + return (Join-Path $local "Eggpass") +} + +function Test-OnPath { + param([string]$Dir) + foreach ($entry in ($env:PATH -split ';')) { + if ($entry.Trim().Trim('"').TrimEnd('\') -ieq $Dir.TrimEnd('\')) { return $true } + } + return $false +} + +function Write-PathGuidance { + param([string]$Dir) + if (Test-OnPath -Dir $Dir) { + Write-Host "$Dir is available on the current PATH." + return + } + Write-Warning "$Dir is not in PATH; add it to PATH or use the full executable path." + Write-Host 'For this PowerShell session, run:' + Write-Host ('$env:Path = "' + $Dir + ';$env:Path"') +} + +function Get-CandidateVersion { + param([string]$Candidate) + $output = @(& $Candidate --version 2>&1) + if ($LASTEXITCODE -ne 0 -or $output.Count -ne 1) { throw "Candidate failed eggpass --version validation: $output" } + $line = [string]$output[0] + if ($line -notmatch '^eggpass ([0-9]+\.[0-9]+\.[0-9]+)$') { throw "Candidate identity must be exactly 'eggpass X.Y.Z': $line" } + return $Matches[1] +} + +function Get-ExistingVersion { + param([string]$DestPath) + if (-not (Test-Path -LiteralPath $DestPath -PathType Leaf)) { return "" } + try { return "eggpass $(Get-CandidateVersion -Candidate $DestPath)" } catch { return "" } +} + +function Get-DestinationClassification { + param([string]$DestPath) + try { + $item = Get-Item -LiteralPath $DestPath -Force -ErrorAction Stop + } catch { + if ($_.CategoryInfo.Category -eq [System.Management.Automation.ErrorCategory]::ObjectNotFound) { return "absent" } + throw "Cannot safely inspect destination '$DestPath': $($_.Exception.Message)" + } + if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw "Refusing to replace a symlink/reparse point: $DestPath" } + if ($item.PSIsContainer) { return "foreign" } + $existing = Get-ExistingVersion -DestPath $DestPath + if ($existing -match '^eggpass [0-9]+\.[0-9]+\.[0-9]+$') { return "replace" } + return "foreign" +} + +function Invoke-EggpassWebRequest { + param([string]$Uri, [string]$OutFile, [int]$TimeoutSec) + Invoke-WebRequest -Uri $Uri -OutFile $OutFile -UseBasicParsing -TimeoutSec $TimeoutSec -MaximumRedirection 5 -ErrorAction Stop +} + +function Get-HttpFailure { + param($ErrorRecord) + $code = 0 + $responseUri = "" + $response = $null + try { $response = $ErrorRecord.Exception.Response } catch { } + if ($response) { + $statusProperty = $response.PSObject.Properties['StatusCode'] + if ($statusProperty -and $statusProperty.Value) { $code = [int]$statusProperty.Value } + $responseUriProperty = $response.PSObject.Properties['ResponseUri'] + if ($responseUriProperty -and $responseUriProperty.Value) { + $responseUri = [string]$responseUriProperty.Value.AbsoluteUri + } else { + $requestProperty = $response.PSObject.Properties['RequestMessage'] + if ($requestProperty -and $requestProperty.Value) { + $requestUriProperty = $requestProperty.Value.PSObject.Properties['RequestUri'] + if ($requestUriProperty -and $requestUriProperty.Value) { $responseUri = [string]$requestUriProperty.Value.AbsoluteUri } + } + } + } + return [pscustomobject]@{ StatusCode = $code; ResponseUri = $responseUri } +} + +function Resolve-ReleaseVersion { + param([string]$Uri, [string]$ExpectedAsset) + if (-not $Uri) { return "" } + try { $parsed = [Uri]$Uri } catch { return "" } + if ($parsed.Scheme -ne "https" -or $parsed.Host -ne "github.com" -or $parsed.Query -or $parsed.Fragment) { return "" } + $parts = $parsed.AbsolutePath.Trim('/').Split('/') + if ($parts.Count -ne 6 -or $parts[0] -ne "eggstack" -or $parts[1] -ne "eggpass" -or $parts[2] -ne "releases" -or $parts[3] -ne "download") { return "" } + if ($parts[4] -notmatch '^v([0-9]+\.[0-9]+\.[0-9]+)$') { return "" } + if ($parts[5] -ne $ExpectedAsset -or $parsed.AbsolutePath -ne "/eggstack/eggpass/releases/download/$($parts[4])/$ExpectedAsset") { return "" } + return $Matches[1] +} + +function Set-PrivateDirectoryAcl { + param([string]$Path) + $acl = New-Object System.Security.AccessControl.DirectorySecurity + $acl.SetAccessRuleProtection($true, $false) + $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User + $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow") + $acl.AddAccessRule($rule) + Set-Acl -LiteralPath $Path -AclObject $acl +} + +function Invoke-EggpassCargo { + param([string]$CargoPath, [string[]]$Arguments) + & $CargoPath @Arguments 2>&1 | Out-Host + return $LASTEXITCODE +} + +function Install-VerifiedCandidate { + param([string]$Candidate, [string]$DestPath, [string]$DestDir, [string]$Scope, [string]$ExistingVersion) + $dirItem = Get-Item -LiteralPath $DestDir -Force -ErrorAction SilentlyContinue + if ($dirItem -and ($dirItem.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw "Refusing to install through a symlink/reparse point: $DestDir" } + New-Item -ItemType Directory -Path $DestDir -Force | Out-Null + $dirItem = Get-Item -LiteralPath $DestDir -Force -ErrorAction Stop + if (($dirItem.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw "Refusing to install through a symlink/reparse point: $DestDir" } + $current = Get-DestinationClassification -DestPath $DestPath + if ($current -ne $Scope) { throw "Destination changed during install (expected $Scope, found $current); refusing to overwrite it." } + $stagedCopy = Join-Path $DestDir (".eggpass-install-" + [Guid]::NewGuid().ToString('N') + ".tmp") + try { + [IO.File]::Copy($Candidate, $stagedCopy, $false) + if ($Scope -eq "replace") { [IO.File]::Replace($stagedCopy, $DestPath, $null) } + else { [IO.File]::Move($stagedCopy, $DestPath) } + } finally { + if (Test-Path -LiteralPath $stagedCopy) { Remove-Item -LiteralPath $stagedCopy -Force -ErrorAction SilentlyContinue } + } + if ($Scope -eq "replace") { Write-Host "Updated Eggpass at $DestPath ($ExistingVersion -> eggpass $(Get-CandidateVersion -Candidate $DestPath))" } + else { Write-Host "Installed Eggpass to $DestPath" } +} + +function Invoke-CargoFallback { + param([string]$SelectedVersion, [string]$DestDir, [string]$DestPath, [string]$Scope, [string]$ExistingVersion) + if ($SelectedVersion -notmatch '^[0-9]+\.[0-9]+\.[0-9]+$') { throw "Cargo fallback requires the exact selected GitHub release version." } + $cargo = Get-Command cargo -CommandType Application -ErrorAction SilentlyContinue + if (-not $cargo) { throw "The exact eggpass $SelectedVersion crate is not available through Cargo. Install Rust and retry this exact version later." } + $stageRoot = Join-Path ([IO.Path]::GetTempPath()) ("eggpass-install-" + [Guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $stageRoot | Out-Null + try { + Set-PrivateDirectoryAcl -Path $stageRoot + $cargoRoot = Join-Path $stageRoot "cargo-root" + $cargoArgs = @("install", "--locked", "--version", "=$SelectedVersion", "--root", $cargoRoot, "eggpass") + Write-Host "No prebuilt asset (HTTP 404); staging exact Eggpass $SelectedVersion with Cargo." + $exitCode = Invoke-EggpassCargo -CargoPath $cargo.Source -Arguments $cargoArgs + if ($exitCode -ne 0) { throw "Cargo fallback failed for exact eggpass $SelectedVersion; retry when that crate version is available." } + $candidate = Join-Path $cargoRoot "bin\eggpass.exe" + if (-not (Test-Path -LiteralPath $candidate -PathType Leaf)) { throw "Cargo install succeeded but staged candidate is missing: $candidate" } + $candidateVersion = Get-CandidateVersion -Candidate $candidate + if ($candidateVersion -ne $SelectedVersion) { throw "Cargo candidate $candidateVersion does not match selected GitHub release $SelectedVersion" } + Install-VerifiedCandidate -Candidate $candidate -DestPath $DestPath -DestDir $DestDir -Scope $Scope -ExistingVersion $ExistingVersion + } finally { + if (Test-Path -LiteralPath $stageRoot) { Remove-Item -LiteralPath $stageRoot -Recurse -Force -ErrorAction SilentlyContinue } + } +} + +function Install-Program { + if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { throw "This PowerShell installer runs on Windows only." } + if (-not $SupportedBinary) { throw "Unsupported target $Arch; no published Eggpass asset exists and Cargo fallback is disabled for unsupported targets." } + $destDir = Get-DestDir -ForSystem:($System.IsPresent) + $destDirItem = Get-Item -LiteralPath $destDir -Force -ErrorAction SilentlyContinue + if ($destDirItem -and ($destDirItem.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw "Refusing to install through a symlink/reparse point: $destDir" } + $destPath = Join-Path $destDir $InstallName + $scope = Get-DestinationClassification -DestPath $destPath + if ($scope -eq "foreign") { throw "Refusing to overwrite unrelated file at $destPath; it is not an Eggpass executable." } + $existingVersion = "" + if ($scope -eq "replace") { $existingVersion = Get-ExistingVersion -DestPath $destPath; Write-Host "Found $existingVersion at $destPath; same-scope rerun will replace it." } + + if ($Tag) { $url = "$BaseUrl/download/$Tag/$Asset" } else { $url = "$BaseUrl/latest/download/$Asset" } + $shaUrl = "$url.sha256" + if (-not $url.StartsWith("https://github.com/$Repo/releases/", [StringComparison]::Ordinal)) { throw "Constructed URL is outside the expected Eggpass release repository." } + $tmp = Join-Path ([IO.Path]::GetTempPath()) ("eggpass-install-" + [Guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $tmp | Out-Null + try { + Set-PrivateDirectoryAcl -Path $tmp + $candidate = Join-Path $tmp $Asset + $shaFile = Join-Path $tmp "$Asset.sha256" + $download = $null + try { + $download = Invoke-EggpassWebRequest -Uri $url -OutFile $candidate -TimeoutSec 100 + } catch { + $failure = Get-HttpFailure -ErrorRecord $_ + if ($failure.StatusCode -ne 404) { throw "Failed to download $Asset (HTTP $($failure.StatusCode)): $($_.Exception.Message)" } + $selected = $StrippedVersion + if (-not $selected) { $selected = Resolve-ReleaseVersion -Uri $failure.ResponseUri -ExpectedAsset $Asset } + if (-not $selected) { throw "Binary asset returned HTTP 404 but no exact release tag could be resolved; refusing floating Cargo fallback." } + Invoke-CargoFallback -SelectedVersion $selected -DestDir $destDir -DestPath $destPath -Scope $scope -ExistingVersion $existingVersion + Write-PathGuidance -Dir $destDir + return + } + if (-not (Test-Path -LiteralPath $candidate -PathType Leaf)) { throw "Download completed without an asset file." } + $assetLength = (Get-Item -LiteralPath $candidate).Length + if ($assetLength -gt 67108864) { throw "Asset exceeds the 67108864 byte maximum." } + + try { Invoke-EggpassWebRequest -Uri $shaUrl -OutFile $shaFile -TimeoutSec 30 | Out-Null } + catch { throw "Failed to download checksum for ${Asset}: $($_.Exception.Message)" } + if (-not (Test-Path -LiteralPath $shaFile -PathType Leaf) -or (Get-Item -LiteralPath $shaFile).Length -gt 4096) { throw "Checksum sidecar is missing or exceeds 4096 bytes." } + $expected = ((Get-Content -LiteralPath $shaFile -Raw).Split())[0].ToLowerInvariant() + if ($expected -notmatch '^[0-9a-f]{64}$') { throw "Checksum sidecar is malformed." } + $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $candidate).Hash.ToLowerInvariant() + if ($expected -ne $actual) { throw "SHA-256 mismatch for $Asset." } + + $candidateVersion = Get-CandidateVersion -Candidate $candidate + if ($StrippedVersion -and $candidateVersion -ne $StrippedVersion) { throw "Candidate version $candidateVersion does not match requested $StrippedVersion." } + Install-VerifiedCandidate -Candidate $candidate -DestPath $destPath -DestDir $destDir -Scope $scope -ExistingVersion $existingVersion + Write-PathGuidance -Dir $destDir + } finally { + if (Test-Path -LiteralPath $tmp) { Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue } + } +} + +if ($env:EGGPASS_TEST_SKIP_MAIN -ne "1") { Install-Program } diff --git a/packaging/install.sh b/packaging/install.sh new file mode 100644 index 0000000..4a93fb1 --- /dev/null +++ b/packaging/install.sh @@ -0,0 +1,472 @@ +#!/usr/bin/env bash +# Eggpass bootstrap installer, adapted from eggstack/gregg packaging/install.sh +# at fabcaf21bc60f719a5de5b9420490ffed52400e4. +# Copyright (c) 2026 The Gregg Authors. MIT License. +# 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. + +if [ -z "${BASH_VERSION:-}" ]; then echo "error: install.sh requires bash; run it with bash, not sh" >&2; exit 1; fi +set -euo pipefail +REPO="eggstack/eggpass" +BASE_URL="https://github.com/$REPO/releases" +VERSION=""; STRIPPED_VERSION=""; TAG="" +SYSTEM_INSTALL=false; NO_SHELL_PROFILE=false +usage() { + cat <<'EOF' +usage: install.sh [--version X.Y.Z] [--system] [--no-shell-profile] + +Install Eggpass from a verified GitHub release. The default is $HOME/.local/bin. +--system selects /usr/local/bin and requires an already elevated shell; this +installer never invokes sudo. Only the five published Eggpack targets are supported. + + --version X.Y.Z install exact release vX.Y.Z + --system explicit system-wide install (requires root) + --no-shell-profile do not append a safe user-local PATH block + --help, -h show this help +EOF +} +die() { echo "error: $*" >&2; exit 1; } +while [[ $# -gt 0 ]]; do + case "$1" in + --version) [[ $# -ge 2 && -n "${2:-}" ]] || die "--version requires X.Y.Z"; VERSION="$2"; shift 2 ;; + --system) SYSTEM_INSTALL=true; shift ;; + --no-shell-profile) NO_SHELL_PROFILE=true; shift ;; + --help|-h) usage; exit 0 ;; + *) die "unknown argument: $1" ;; + esac +done +if [[ -n "$VERSION" ]]; then + STRIPPED_VERSION="${VERSION#v}" + [[ "$STRIPPED_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "--version must be stable X.Y.Z (got '$VERSION')" + TAG="v$STRIPPED_VERSION" +fi +# EGGPASS_TEST_OS/ARCH are test-only host overrides; production uses uname. +if [[ -n "${EGGPASS_TEST_OS:-}" ]]; then OS="$EGGPASS_TEST_OS"; else OS="$(uname -s 2>/dev/null || echo unknown)"; fi +if [[ -n "${EGGPASS_TEST_ARCH:-}" ]]; then ARCH="$EGGPASS_TEST_ARCH"; else ARCH="$(uname -m 2>/dev/null || echo unknown)"; fi +TARGET="" +case "$OS" in + Linux) case "$ARCH" in x86_64|amd64|AMD64) TARGET=x86_64-unknown-linux-gnu ;; aarch64|arm64|ARM64) TARGET=aarch64-unknown-linux-gnu ;; esac ;; + Darwin) case "$ARCH" in x86_64|amd64|AMD64) TARGET=x86_64-apple-darwin ;; arm64|aarch64|ARM64) TARGET=aarch64-apple-darwin ;; esac ;; + MINGW*|MSYS*|CYGWIN*|Windows_NT) case "$ARCH" in x86_64|amd64|AMD64) TARGET=x86_64-pc-windows-msvc ;; esac ;; +esac +SUPPORTED_BINARY=false +case "$TARGET" in x86_64-unknown-linux-gnu|aarch64-unknown-linux-gnu|x86_64-apple-darwin|aarch64-apple-darwin|x86_64-pc-windows-msvc) SUPPORTED_BINARY=true ;; esac +ASSET_SUFFIX=""; INSTALL_NAME=eggpass +if [[ "$TARGET" == x86_64-pc-windows-msvc ]]; then ASSET_SUFFIX=.exe; INSTALL_NAME=eggpass.exe; fi +echo "Detected: OS=$OS ARCH=$ARCH TARGET=${TARGET:-unknown} ${TAG:-latest}" >&2 +if [[ "$SYSTEM_INSTALL" == true ]]; then + [[ $EUID -eq 0 ]] || die "--system requires an already elevated shell; rerun as root (the installer never invokes sudo)" + DEST_DIR="${EGGPASS_TEST_SYSTEM_DIR:-/usr/local/bin}" +else + [[ -n "${HOME:-}" ]] || die "HOME is empty; cannot select a per-user destination" + DEST_DIR="$HOME/.local/bin" +fi +is_system_install() { [[ "$SYSTEM_INSTALL" == true ]]; } + +# --- user-local PATH persistence (Plan 130) ---------------------------------- +# +# Post-install user experience only, never installation identity. Destinations +# stay canonical (root -> /usr/local/bin, non-root -> $HOME/.local/bin). +# A piped child installer cannot export into its parent shell, so profile +# edits persist for future shells while the documented trailing parent-shell +# `export PATH="$HOME/.local/bin:$PATH"` activates the current shell. + +dest_on_path() { + case ":${PATH:-}:" in + *":${DEST_DIR}:"*) return 0 ;; + *) return 1 ;; + esac +} + +# Active-integration predicate (Plan 131 corrective pass): success means the +# selected startup file contains a recognizable active PATH integration for +# the canonical user-local bin directory — either Eggpass's intact managed +# block (exact marker plus an active functional PATH line) or a supported, +# non-commented user-authored PATH (or zsh tied `path` array) assignment +# containing `$HOME/.local/bin`, `${HOME}/.local/bin`, `~/.local/bin`, or the +# expanded `$HOME/.local/bin` as a discrete PATH entry. Arbitrary `.local/bin` +# text (comments, commented-out assignments, prose, echo/printf, aliases, +# functions, non-PATH variables, subpaths, or longer names) is not sufficient. +# Read-only: profile contents are never sourced, evaluated, executed, or +# command-substituted. Conservative: exotic shell metaprogramming fails closed +# (returns nonzero) so the installer appends its safe managed block rather +# than falsely claiming persistence. +line_has_canonical_bin_entry() { + local code="$1" + if [[ $code =~ \$HOME/\.local/bin([^/A-Za-z0-9_.-]|$) ]]; then + return 0 + fi + if [[ $code =~ \$\{HOME\}/\.local/bin([^/A-Za-z0-9_.-]|$) ]]; then + return 0 + fi + if [[ $code =~ \~/\.local/bin([^/A-Za-z0-9_.-]|$) ]]; then + return 0 + fi + # Expanded `$HOME/.local/bin` (deterministic, read-only): the installer + # knows `$HOME`, so an explicit absolute user-authored entry for this home + # counts when it appears as a discrete PATH entry. Boundary-checked with + # fixed-string matching to avoid regex-escaping the home path. + if [[ -n "${HOME:-}" ]]; then + local expanded="${HOME}/.local/bin" + if [[ "$code" == *"$expanded"* ]]; then + local rest="$code" + while [[ "$rest" == *"$expanded"* ]]; do + rest="${rest#*"$expanded"}" + local next="${rest:0:1}" + if [[ -z "$next" ]]; then + return 0 + fi + # shellcheck disable=SC2053 + if [[ "$next" =~ [^/A-Za-z0-9_.-] ]]; then + return 0 + fi + [[ "$rest" == *"$expanded"* ]] || break + done + fi + fi + return 1 +} + +# Intact Eggpass-managed block: the exact marker plus at least one active +# (non-commented) functional `export PATH=` line carrying the canonical entry. +# Marker text alone — including an unrelated comment that happens to match it, +# or a block whose functional line was manually commented out — is not enough. +profile_has_managed_block() { + local file="$1" + grep -Fq "added by eggpass installer" "$file" 2>/dev/null || return 1 + local line trimmed code + while IFS= read -r line || [[ -n "$line" ]]; do + trimmed="${line#"${line%%[![:space:]]*}"}" + [[ -z "$trimmed" ]] && continue + [[ "$trimmed" == \#* ]] && continue + code="$trimmed" + # The managed export lives on a case-branch line (`*) export ... ;;`); + # strip one leading branch prefix before matching the functional part. + if [[ "$code" == '*)'* ]]; then + code="${code#\*\)}" + code="${code#"${code%%[![:space:]]*}"}" + fi + if [[ "$code" == *'export PATH='* ]] && line_has_canonical_bin_entry "$code"; then + return 0 + fi + done < "$file" + return 1 +} + +# Supported user-authored integration: a non-commented line that starts (after +# leading whitespace) with `export PATH=`, `PATH=`, `export path=`, or `path=` +# (zsh tied array) and carries the canonical entry discretely. `echo`, +# `printf`, aliases, functions, non-PATH variables, and other paths that +# merely contain the substring are ignored. Full-line and leading-whitespace +# comments are skipped; inline comments after an active assignment are +# accepted because matching is prefix-anchored, not full-line. +profile_has_user_path_integration() { + local file="$1" + local line trimmed code + while IFS= read -r line || [[ -n "$line" ]]; do + trimmed="${line#"${line%%[![:space:]]*}"}" + [[ -z "$trimmed" ]] && continue + [[ "$trimmed" == \#* ]] && continue + code="$trimmed" + if [[ "$code" =~ ^export[[:space:]]+PATH= ]] || [[ "$code" =~ ^PATH= ]]; then + if line_has_canonical_bin_entry "$code"; then + return 0 + fi + elif [[ "$code" =~ ^export[[:space:]]+path= ]] || [[ "$code" =~ ^path= ]]; then + if line_has_canonical_bin_entry "$code"; then + return 0 + fi + fi + done < "$file" + return 1 +} + +profile_has_active_path_integration() { + local file="$1" + [[ -f "$file" ]] || return 1 + if profile_has_managed_block "$file"; then + return 0 + fi + if profile_has_user_path_integration "$file"; then + return 0 + fi + return 1 +} + +zsh_profile_path() { + local zdot="${ZDOTDIR:-}" + if [[ -n "$zdot" && "$zdot" == /* && "$zdot" != *$'\n'* ]]; then + printf '%s/.zshrc' "$zdot" + else + printf '%s/.zshrc' "${HOME}" + fi +} + +# Deterministic bash startup target: Linux centers on ~/.bashrc; macOS honors +# login-shell behavior (existing ~/.bash_profile, ~/.bash_login, or ~/.profile +# wins, otherwise ~/.bash_profile is created). Takes explicit inputs so tests +# can exercise macOS selection without a real interactive shell. +bash_profile_path() { + local os_name="${1:-$OS}" + local home_dir="${2:-$HOME}" + if [[ "$os_name" == "Darwin" ]]; then + if [[ -f "${home_dir}/.bash_profile" ]]; then + printf '%s/.bash_profile' "$home_dir" + elif [[ -f "${home_dir}/.bash_login" ]]; then + printf '%s/.bash_login' "$home_dir" + elif [[ -f "${home_dir}/.profile" ]]; then + printf '%s/.profile' "$home_dir" + else + printf '%s/.bash_profile' "$home_dir" + fi + else + printf '%s/.bashrc' "$home_dir" + fi +} + +# Prints the supported profile path, or returns nonzero for unsupported shells. +# Only zsh and bash are integrated; anything else falls back to manual advice. +select_shell_profile() { + local shell_name="" + if [[ -z "${SHELL:-}" ]]; then + return 1 + fi + shell_name="$(basename "${SHELL}" 2>/dev/null || true)" + case "$shell_name" in + zsh) zsh_profile_path ;; + bash) bash_profile_path "$OS" "$HOME" ;; + *) return 1 ;; + esac +} + +# Appends one bounded, idempotent PATH block. Never evaluates or sources the +# profile, never rewrites it, never touches system shell policy. Returns +# nonzero when the target is malformed, inaccessible, or outside the expected +# user home/config location; callers report that separately without rolling +# back the already successful binary install. +append_profile_entry() { + local file="$1" + local parent + # Never follow a profile symlink outside $HOME (would append to an + # attacker-chosen target); the caller reports the miss as manual guidance. + if [[ -L "$file" ]]; then + return 1 + fi + parent="$(dirname "$file")" + if [[ ! -d "$parent" ]]; then + return 1 + fi + if [[ -e "$file" && ! -f "$file" ]]; then + return 1 + fi + if [[ -e "$file" ]]; then + if [[ ! -w "$file" && $EUID -ne 0 ]]; then + return 1 + fi + else + local expected_parent_ok=false + if [[ "$parent" == "$HOME" ]]; then + expected_parent_ok=true + elif [[ -n "${ZDOTDIR:-}" && "$parent" == "${ZDOTDIR}" && "${ZDOTDIR}" == /* ]]; then + expected_parent_ok=true + fi + if [[ "$expected_parent_ok" != "true" ]]; then + return 1 + fi + if [[ ! -w "$parent" ]]; then + return 1 + fi + fi + { + echo "" + echo "# added by eggpass installer: ensure user-local binaries are on PATH" + echo "case \":\$PATH:\" in" + echo " *\":\$HOME/.local/bin:\"*) ;;" + echo " *) export PATH=\"\$HOME/.local/bin:\$PATH\" ;;" + echo "esac" + } >>"$file" 2>/dev/null || return 1 + return 0 +} + +print_manual_path_guidance() { + echo " export PATH=\"\$HOME/.local/bin:\$PATH\"" >&2 +} + +PATH_INTEGRATION_DONE=false + +# Runs at most once per installer invocation, after all verified installs. +run_path_integration_once() { + if [[ "$PATH_INTEGRATION_DONE" == "true" ]]; then + return 0 + fi + PATH_INTEGRATION_DONE=true + + # System installs never mutate user or global shell startup files. + if is_system_install; then + if dest_on_path; then + echo "${DEST_DIR} is available on the current PATH." >&2 + else + if [[ "$DEST_DIR" == "/usr/local/bin" ]]; then + echo "note: /usr/local/bin is not in PATH; add it to your shell configuration:" >&2 + echo " export PATH=\"/usr/local/bin:\$PATH\"" >&2 + else + echo "note: ${DEST_DIR} is not in PATH; add it to your shell profile:" >&2 + print_manual_path_guidance + fi + fi + return 0 + fi + + # Non-root user-local installs. + if dest_on_path; then + echo "${DEST_DIR} is available on the current PATH." >&2 + return 0 + fi + + if [[ "$NO_SHELL_PROFILE" == "true" ]]; then + echo "${DEST_DIR} is not on the current PATH." >&2 + echo "Add it to your shell configuration, or run for this shell:" >&2 + print_manual_path_guidance + return 0 + fi + + local profile="" + if ! profile="$(select_shell_profile)"; then + echo "${DEST_DIR} is not on the current PATH." >&2 + echo "Add it to your shell configuration, or run for this shell:" >&2 + print_manual_path_guidance + return 0 + fi + + if profile_has_active_path_integration "$profile"; then + echo "${DEST_DIR} is not on the current PATH." >&2 + echo "Your shell profile already integrates ${DEST_DIR}; for this shell, run:" >&2 + print_manual_path_guidance + return 0 + fi + + if append_profile_entry "$profile"; then + echo "Added ${DEST_DIR} to ${profile} for future shells." >&2 + echo "For this shell, run:" >&2 + print_manual_path_guidance + return 0 + else + echo "${DEST_DIR} is not on the current PATH." >&2 + echo "Could not update ${profile}; add it to your shell configuration, or run for this shell:" >&2 + print_manual_path_guidance + return 0 + fi +} + +# --- candidate and checksum verification ------------------------------------ +SELECTED_VERSION=""; SCOPE="" +existing_version_for() { local f="$1"; if [[ -x "$f" ]]; then "$f" --version 2>/dev/null || true; fi; } +classify_destination() { + local f="$1" output + [[ ! -e "$f" ]] && { echo absent; return 0; } + output="$(existing_version_for "$f")" + if [[ "$output" =~ ^eggpass\ [0-9]+\.[0-9]+\.[0-9]+$ ]]; then echo replace; else echo foreign; fi +} +verify_checksum() { + local file="$1" sidecar="$2" expected actual + expected="$(awk '{print $1}' "$sidecar" 2>/dev/null || true)" + expected="$(printf '%s' "$expected" | tr '[:upper:]' '[:lower:]')" + [[ "$expected" =~ ^[0-9a-f]{64}$ ]] || die "checksum sidecar is empty or malformed" + if command -v sha256sum >/dev/null 2>&1; then actual="$(sha256sum "$file" | awk '{print $1}')" + elif command -v shasum >/dev/null 2>&1; then actual="$(shasum -a 256 "$file" | awk '{print $1}')" + else die "no SHA-256 utility found (need sha256sum or shasum)"; fi + actual="$(printf '%s' "$actual" | tr '[:upper:]' '[:lower:]')" + [[ "$expected" == "$actual" ]] || die "SHA-256 mismatch for $(basename "$file")" +} +verify_candidate_version() { + local candidate="$1" output + if ! output="$("$candidate" --version 2>&1)"; then die "candidate failed eggpass --version validation: $output"; fi + [[ "$output" =~ ^eggpass\ ([0-9]+\.[0-9]+\.[0-9]+)$ ]] || die "candidate identity must be exactly 'eggpass X.Y.Z': $output" + SELECTED_VERSION="${BASH_REMATCH[1]}" + if [[ -n "$STRIPPED_VERSION" && "$SELECTED_VERSION" != "$STRIPPED_VERSION" ]]; then die "candidate version $SELECTED_VERSION does not match requested $STRIPPED_VERSION"; fi + echo "Verified candidate: $output" >&2 +} +cargo_fallback() { + local existing="$1" selected="$STRIPPED_VERSION" stage_root cargo_root candidate + [[ "$selected" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "cannot use Cargo fallback without an exact selected release version" + command -v cargo >/dev/null 2>&1 || die "Cargo is unavailable; retry exact version $selected after installing Rust" + stage_root="$(mktemp -d "${TMPDIR:-/tmp}/eggpass-install.XXXXXX")" + # shellcheck disable=SC2064 + trap "rm -rf \"$stage_root\"" EXIT + cargo_root="$stage_root/cargo-root" + local -a cargo_args=(install --locked --version "=$selected" --root "$cargo_root" eggpass) + echo "Building exact Eggpass $selected in private Cargo staging." >&2 + if ! cargo "${cargo_args[@]}"; then die "Cargo could not install exact eggpass $selected; retry when that crate version is available"; fi + candidate="$cargo_root/bin/eggpass$ASSET_SUFFIX" + [[ -x "$candidate" ]] || die "Cargo produced no staged candidate at $candidate" + verify_candidate_version "$candidate" + [[ "$SELECTED_VERSION" == "$selected" ]] || die "Cargo candidate does not match selected GitHub release $selected" + mkdir -p "$DEST_DIR" + [[ ! -L "$DEST_DIR/$INSTALL_NAME" ]] || die "$DEST_DIR/$INSTALL_NAME became a symlink; refusing to overwrite it" + if command -v install >/dev/null 2>&1; then install -m 755 "$candidate" "$DEST_DIR/$INSTALL_NAME"; else cp "$candidate" "$DEST_DIR/$INSTALL_NAME"; chmod 755 "$DEST_DIR/$INSTALL_NAME"; fi + rm -rf "$stage_root"; trap - EXIT + if [[ "$SCOPE" == replace ]]; then echo "Updated eggpass at $DEST_DIR/$INSTALL_NAME ($existing -> $("$DEST_DIR/$INSTALL_NAME" --version 2>&1))" >&2; else echo "Installed eggpass to $DEST_DIR/$INSTALL_NAME" >&2; fi +} + +install_program() { + local asset url sha_url tmpdir dest scope existing meta curl_status http_code effective_url + if [[ "$SUPPORTED_BINARY" != true ]]; then die "unsupported target $OS/$ARCH (${TARGET:-unknown})"; fi + asset="eggpass-$TARGET$ASSET_SUFFIX" + if [[ -n "$TAG" ]]; then url="$BASE_URL/download/$TAG/$asset"; else url="$BASE_URL/latest/download/$asset"; fi + sha_url="$url.sha256" + dest="$DEST_DIR/$INSTALL_NAME" + [[ ! -L "$dest" ]] || die "$dest is a symlink; refusing to overwrite it" + scope="$(classify_destination "$dest")" + [[ "$scope" != foreign ]] || die "$dest is foreign; refusing to overwrite it" + SCOPE="$scope"; existing="" + if [[ "$scope" == replace ]]; then existing="$(existing_version_for "$dest")"; echo "Found $existing at $dest; same-scope rerun will replace it." >&2; fi + tmpdir="$(mktemp -d "${TMPDIR:-/tmp}/eggpass-install.XXXXXX")" + # shellcheck disable=SC2064 + trap "rm -rf \"$tmpdir\"" EXIT + set +e + meta="$(curl --proto '=https' --tlsv1.2 -fsSL --max-time 100 --max-filesize 67108864 -H "User-Agent: eggpass/installer" -o "$tmpdir/$asset" -w "%{http_code}\n%{url_effective}" "$url" 2>/dev/null)" + curl_status=$?; set -e + http_code="${meta%%$'\n'*}"; effective_url="${meta#*$'\n'}" + [[ "$effective_url" == "$meta" ]] && effective_url="" + http_code="${http_code:-000}" +if [[ "$http_code" == 404 ]]; then + if [[ -z "$STRIPPED_VERSION" ]]; then + local release_tag + release_tag="$(printf '%s' "$effective_url" | awk -F/ '{print $(NF-1)}')" + [[ "$release_tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ && "$effective_url" == "$BASE_URL/download/$release_tag/$asset" ]] || die "latest 404 did not resolve to an exact release tag; refusing floating Cargo fallback" + TAG="$release_tag"; STRIPPED_VERSION="${release_tag#v}" + fi + echo "Binary asset missing (HTTP 404); using exact release $STRIPPED_VERSION for Cargo fallback." >&2 + rm -rf "$tmpdir"; trap - EXIT; cargo_fallback "$existing"; return 0 +fi +if [[ $curl_status -ne 0 ]]; then die "curl failed (exit $curl_status, HTTP $http_code); only a definite 404 permits Cargo fallback"; fi +[[ "$http_code" == 2* ]] || die "unexpected HTTP $http_code; refusing install and Cargo fallback" +if ! curl --proto '=https' --tlsv1.2 -fsSL --max-time 30 --max-filesize 4096 -H "User-Agent: eggpass/installer" -o "$tmpdir/$asset.sha256" "$sha_url"; then die "checksum download failed for $asset"; fi +verify_checksum "$tmpdir/$asset" "$tmpdir/$asset.sha256" +chmod +x "$tmpdir/$asset" +verify_candidate_version "$tmpdir/$asset" +mkdir -p "$DEST_DIR" +[[ ! -L "$dest" ]] || die "$dest became a symlink; refusing to overwrite it" +if command -v install >/dev/null 2>&1; then install -m 755 "$tmpdir/$asset" "$dest"; else cp "$tmpdir/$asset" "$dest"; chmod 755 "$dest"; fi +if [[ "$scope" == replace ]]; then echo "Updated eggpass at $dest ($existing -> $("$dest" --version 2>&1))" >&2; else echo "Installed eggpass to $dest" >&2; fi +rm -rf "$tmpdir"; trap - EXIT +} +install_program +run_path_integration_once +echo "Done. Installed eggpass to $DEST_DIR" >&2 +echo " $DEST_DIR/$INSTALL_NAME --version => $("$DEST_DIR/$INSTALL_NAME" --version 2>&1 || echo not-runnable)" >&2 diff --git a/packaging/tests/test-install.ps1 b/packaging/tests/test-install.ps1 new file mode 100644 index 0000000..9f89b2c --- /dev/null +++ b/packaging/tests/test-install.ps1 @@ -0,0 +1,219 @@ +$ErrorActionPreference = "Stop" +$installer = Join-Path $PSScriptRoot "../install.ps1" +$installer = (Resolve-Path $installer).Path +$env:EGGPASS_TEST_SKIP_MAIN = "1" +$env:EGGPASS_TEST_ARCH = "AMD64" +. $installer + +if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { + Write-Host "PowerShell runtime fixtures require Windows; URL/helper fixtures are ready for Windows PowerShell 7." + if ((Resolve-ReleaseVersion -Uri "https://github.com/eggstack/eggpass/releases/download/v1.2.3/eggpass-x86_64-pc-windows-msvc.exe" -ExpectedAsset "eggpass-x86_64-pc-windows-msvc.exe") -ne "1.2.3") { throw "release URL fixture failed" } + exit 0 +} + +$script:Sandbox = Join-Path ([IO.Path]::GetTempPath()) ("eggpass-installer-tests-" + [Guid]::NewGuid().ToString('N')) +$script:FakeBin = Join-Path $script:Sandbox "fakebin" +$script:FixtureBinary = Join-Path $script:Sandbox "fixture.exe" +New-Item -ItemType Directory -Path $script:Sandbox, $script:FakeBin -Force | Out-Null +[IO.File]::WriteAllText($script:FixtureBinary, "offline fixture bytes") +$env:LOCALAPPDATA = Join-Path $script:Sandbox "local" +$env:USERPROFILE = Join-Path $script:Sandbox "profile" +$env:TEMP = Join-Path $script:Sandbox "tmp" +New-Item -ItemType Directory -Path $env:LOCALAPPDATA, $env:USERPROFILE, $env:TEMP -Force | Out-Null +$oldPath = $env:PATH +$env:PATH = "$script:FakeBin;$oldPath" +[IO.File]::WriteAllText((Join-Path $script:FakeBin "cargo.cmd"), "@echo off" + [Environment]::NewLine + "exit /b 0" + [Environment]::NewLine) +$script:FixtureMode = "ok" +$script:FixtureVersion = "1.2.3" +$script:FixtureUrls = [System.Collections.Generic.List[string]]::new() +$script:CargoArgsSeen = [System.Collections.Generic.List[string]]::new() +$script:CandidateVersions = @{} +$script:CargoRootSeen = "" + +function Assert-Fixture { + param([bool]$Condition, [string]$Name) + if (-not $Condition) { throw "Fixture failed: $Name" } + Write-Host "ok - $Name" +} +function Reset-Fixture { + param([string]$Name) + $script:FixtureMode = "ok" + $script:FixtureVersion = "1.2.3" + $script:FixtureUrls.Clear() + $script:CargoArgsSeen.Clear() + $script:CandidateVersions.Clear() + $script:CargoRootSeen = "" + $script:DestRoot = Join-Path $env:LOCALAPPDATA "Eggpass" + if (Test-Path -LiteralPath $script:DestRoot) { Remove-Item -LiteralPath $script:DestRoot -Recurse -Force } + New-Item -ItemType Directory -Path $script:DestRoot -Force | Out-Null + $script:StrippedVersion = "" + $script:Tag = "" + $script:System = [System.Management.Automation.SwitchParameter]::new($false) +} +function Get-CandidateVersion { + param([string]$Candidate) + if ($script:CandidateVersions.ContainsKey($Candidate)) { return [string]$script:CandidateVersions[$Candidate] } + return [string]$script:FixtureVersion +} +function Set-PrivateDirectoryAcl { + param([string]$Path) +} +function Invoke-EggpassWebRequest { + param([string]$Uri, [string]$OutFile, [int]$TimeoutSec) + if ($script:Tag) { $expectedUrl = "https://github.com/eggstack/eggpass/releases/download/$script:Tag/$Asset" } + else { $expectedUrl = "https://github.com/eggstack/eggpass/releases/latest/download/$Asset" } + if ([string]::Equals($Uri, $expectedUrl, [StringComparison]::Ordinal)) { $isChecksum = $false } + elseif ([string]::Equals($Uri, "$expectedUrl.sha256", [StringComparison]::Ordinal)) { $isChecksum = $true } + else { throw "Offline fixture refused unexpected host/path: $Uri" } + $script:FixtureUrls.Add($Uri) + if ($isChecksum) { + if ($script:FixtureMode -eq "sha-error") { throw [Exception]::new("fixture checksum transport failure") } + if ($script:FixtureMode -eq "malformed-sha") { [IO.File]::WriteAllText($OutFile, "not-a-digest"); return } + $hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $script:FixtureBinary).Hash.ToLowerInvariant() + if ($script:FixtureMode -eq "wrong-sha") { $hash = "0" * 64 } + [IO.File]::WriteAllText($OutFile, "$hash eggpass-x86_64-pc-windows-msvc.exe") + return + } + if ($script:FixtureMode -eq "transport") { throw [Exception]::new("fixture network failure") } + if ($script:FixtureMode -eq "http500") { Throw-FixtureHttp -Status 500 -Uri $Uri } + if ($script:FixtureMode -eq "404") { + $finalUri = "https://github.com/eggstack/eggpass/releases/download/v1.2.3/eggpass-x86_64-pc-windows-msvc.exe" + Throw-FixtureHttp -Status 404 -Uri $finalUri + } + Copy-Item -LiteralPath $script:FixtureBinary -Destination $OutFile -Force + $script:CandidateVersions[$OutFile] = $script:FixtureVersion +} +function Throw-FixtureHttp { + param([int]$Status, [string]$Uri) + $ex = [Exception]::new("fixture HTTP $Status") + $response = [pscustomobject]@{ StatusCode = $Status; ResponseUri = [Uri]$Uri; RequestMessage = $null } + $ex | Add-Member -MemberType NoteProperty -Name Response -Value $response + throw $ex +} +function Invoke-EggpassCargo { + param([string]$CargoPath, [string[]]$Arguments) + $expectedVersion = if ($script:Tag) { $script:StrippedVersion } else { $script:FixtureVersion } + if ($Arguments.Count -ne 7 -or $Arguments[0] -cne "install" -or $Arguments[1] -cne "--locked" -or $Arguments[2] -cne "--version" -or $Arguments[3] -cne "=$expectedVersion" -or $Arguments[4] -cne "--root" -or $Arguments[6] -cne "eggpass") { + throw "Offline fixture refused unexpected Cargo arguments: $($Arguments -join ' ')" + } + $script:CargoRootSeen = $Arguments[5] + $tempPrefix = Join-Path ([IO.Path]::GetTempPath()) "eggpass-install-" + if (-not $script:CargoRootSeen.StartsWith($tempPrefix, [StringComparison]::OrdinalIgnoreCase) -or (Split-Path -Leaf $script:CargoRootSeen) -cne "cargo-root") { + throw "Offline fixture refused unexpected Cargo staging root: $script:CargoRootSeen" + } + foreach ($arg in $Arguments) { $script:CargoArgsSeen.Add($arg) } + $requested = $Arguments[3].TrimStart('=') + $binDir = Join-Path $script:CargoRootSeen "bin" + New-Item -ItemType Directory -Path $binDir -Force | Out-Null + $staged = Join-Path $binDir "eggpass.exe" + Copy-Item -LiteralPath $script:FixtureBinary -Destination $staged -Force + [IO.File]::WriteAllText((Join-Path $script:CargoRootSeen ".crates.toml"), "fake metadata") + $script:CandidateVersions[$staged] = $requested + return 0 +} + +try { + Assert-Fixture ($Target -eq "x86_64-pc-windows-msvc" -and $Asset -eq "eggpass-x86_64-pc-windows-msvc.exe") "Windows target maps to distribution asset" + Assert-Fixture ((Resolve-ReleaseVersion -Uri "https://github.com/eggstack/eggpass/releases/download/v1.2.3/eggpass-x86_64-pc-windows-msvc.exe" -ExpectedAsset $Asset) -eq "1.2.3") "latest 404 URL resolves exact release version" + Assert-Fixture (-not (Resolve-ReleaseVersion -Uri "https://github.com/eggstack/eggpass/releases/latest/download/$Asset" -ExpectedAsset $Asset)) "floating URL is not accepted as exact version" + + Reset-Fixture "latest" + $script:System = [System.Management.Automation.SwitchParameter]::new($false) + Install-Program + Assert-Fixture (Test-Path -LiteralPath (Join-Path $script:DestRoot "eggpass.exe")) "latest fixture installs only into isolated user directory" + Assert-Fixture ($script:FixtureUrls.Count -eq 2 -and $script:FixtureUrls[0] -ceq "https://github.com/eggstack/eggpass/releases/latest/download/$Asset" -and $script:FixtureUrls[1] -ceq "https://github.com/eggstack/eggpass/releases/latest/download/$Asset.sha256") "latest binary/checksum URLs use GitHub latest authority" + + Reset-Fixture "pinned" + $script:StrippedVersion = "2.3.4"; $script:Tag = "v2.3.4"; $script:FixtureVersion = "2.3.4" + Install-Program + Assert-Fixture ($script:FixtureUrls.Count -eq 2 -and $script:FixtureUrls[0] -ceq "https://github.com/eggstack/eggpass/releases/download/v2.3.4/$Asset" -and $script:FixtureUrls[1] -ceq "https://github.com/eggstack/eggpass/releases/download/v2.3.4/$Asset.sha256") "pin binary/checksum URLs use exact v2.3.4 tag" + + Reset-Fixture "checksum-failure" + $script:FixtureMode = "wrong-sha" + try { Install-Program; throw "checksum failure was accepted" } catch { Assert-Fixture (-not (Test-Path -LiteralPath (Join-Path $script:DestRoot "eggpass.exe"))) "checksum mismatch never installs" } + Assert-Fixture ($script:CargoArgsSeen.Count -eq 0) "checksum failure never triggers Cargo" + + Reset-Fixture "malformed-checksum" + $script:FixtureMode = "malformed-sha" + $malformedFailed = $false + try { Install-Program } catch { $malformedFailed = $true } + Assert-Fixture ($malformedFailed -and -not (Test-Path -LiteralPath (Join-Path $script:DestRoot "eggpass.exe"))) "malformed checksum never installs" + Assert-Fixture ($script:CargoArgsSeen.Count -eq 0) "malformed checksum never triggers Cargo" + + Reset-Fixture "identity-failure" + $script:StrippedVersion = "1.2.3"; $script:Tag = "v1.2.3"; $script:FixtureVersion = "9.9.9" + try { Install-Program; throw "identity mismatch was accepted" } catch { Assert-Fixture (-not (Test-Path -LiteralPath (Join-Path $script:DestRoot "eggpass.exe"))) "identity mismatch never installs" } + Assert-Fixture ($script:CargoArgsSeen.Count -eq 0) "identity failure never triggers Cargo" + + Reset-Fixture "transport-failure" + $script:FixtureMode = "transport" + $transportFailed = $false + try { Install-Program } catch { $transportFailed = $true } + Assert-Fixture ($transportFailed -and $script:CargoArgsSeen.Count -eq 0) "transport failure never triggers Cargo" + + Reset-Fixture "fallback" + $script:FixtureMode = "404" + Install-Program + Assert-Fixture ($script:CargoArgsSeen.Contains("--version") -and $script:CargoArgsSeen.Contains("=1.2.3")) "exact 404 Cargo fallback pins selected release" + $cargoStageParent = Split-Path -Parent $script:CargoRootSeen + Assert-Fixture (-not (Test-Path -LiteralPath $script:CargoRootSeen) -and -not (Test-Path -LiteralPath $cargoStageParent)) "Cargo staging root and parent are removed" + Assert-Fixture (Test-Path -LiteralPath (Join-Path $script:DestRoot "eggpass.exe")) "Cargo candidate is copied to installer-owned destination" + + Reset-Fixture "http500-failure" + $script:FixtureMode = "http500" + $serverFailed = $false + try { Install-Program } catch { $serverFailed = $true } + Assert-Fixture ($serverFailed -and $script:CargoArgsSeen.Count -eq 0) "non-404 HTTP failure never triggers Cargo" + + Reset-Fixture "same-scope-rerun" + Install-Program + $rerunPath = Join-Path $script:DestRoot "eggpass.exe" + $script:CandidateVersions[$rerunPath] = "1.2.3" + $script:FixtureVersion = "1.2.4" + Install-Program + $script:CandidateVersions[$rerunPath] = "1.2.4" + Assert-Fixture ((Get-DestinationClassification -DestPath $rerunPath) -eq "replace" -and (Get-ExistingVersion -DestPath $rerunPath) -eq "eggpass 1.2.4") "same-scope rerun replaces the verified Eggpass executable" + Assert-Fixture ($script:FixtureUrls.Count -eq 4) "same-scope rerun fetches both exact latest assets again" + + Reset-Fixture "foreign" + $foreign = Join-Path $script:DestRoot "eggpass.exe" + [IO.File]::WriteAllText($foreign, "foreign") + $script:CandidateVersions[$foreign] = "not-a-version" + try { Install-Program; throw "foreign destination was accepted" } catch { Assert-Fixture ($script:FixtureUrls.Count -eq 0) "foreign executable is refused before transport" } + + if (-not $IsAdmin) { + $systemDenied = $false + try { Get-DestDir -ForSystem:$true } catch { $systemDenied = $true } + Assert-Fixture $systemDenied "system destination requires elevation" + } else { + $env:EGGPASS_TEST_SYSTEM_DIR = Join-Path $script:Sandbox "system-destination" + Assert-Fixture ((Get-DestDir -ForSystem:$true) -eq $env:EGGPASS_TEST_SYSTEM_DIR) "explicit system destination is separately scoped" + } + + Reset-Fixture "reparse-point" + $outsideTarget = Join-Path $script:Sandbox "reparse-target" + New-Item -ItemType Directory -Path $outsideTarget -Force | Out-Null + Remove-Item -LiteralPath $script:DestRoot -Recurse -Force + New-Item -ItemType Junction -Path $script:DestRoot -Target $outsideTarget | Out-Null + $reparseRefused = $false + try { Install-Program } catch { $reparseRefused = $true } + Assert-Fixture ($reparseRefused -and $script:FixtureUrls.Count -eq 0 -and -not (Test-Path -LiteralPath (Join-Path $outsideTarget "eggpass.exe"))) "reparse-point destination is refused before transport" + Remove-Item -LiteralPath $script:DestRoot -Force + + $oldArch = $script:Arch + $oldSupported = $script:SupportedBinary + $script:Arch = "ARM64" + $script:SupportedBinary = $false + Reset-Fixture "unsupported-architecture" + $unsupportedRefused = $false + try { Install-Program } catch { $unsupportedRefused = $true } + Assert-Fixture ($unsupportedRefused -and $script:FixtureUrls.Count -eq 0 -and $script:CargoArgsSeen.Count -eq 0) "unsupported architecture refuses release and Cargo access" + $script:Arch = $oldArch + $script:SupportedBinary = $oldSupported + Write-Host "PowerShell fixture suite passed." +} finally { + $env:PATH = $oldPath + Remove-Item Env:EGGPASS_TEST_SKIP_MAIN -ErrorAction SilentlyContinue + Remove-Item Env:EGGPASS_TEST_ARCH -ErrorAction SilentlyContinue + if (Test-Path -LiteralPath $script:Sandbox) { Remove-Item -LiteralPath $script:Sandbox -Recurse -Force -ErrorAction SilentlyContinue } +} diff --git a/packaging/tests/test-install.sh b/packaging/tests/test-install.sh new file mode 100644 index 0000000..1a0c973 --- /dev/null +++ b/packaging/tests/test-install.sh @@ -0,0 +1,229 @@ +#!/usr/bin/env bash +# Offline fixtures adapted from eggstack/gregg test-install-rerun.sh at +# fabcaf21bc60f719a5de5b9420490ffed52400e4. +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +INSTALL_SH="$ROOT/packaging/install.sh" +INSTALL_PS="$ROOT/packaging/install.ps1" +CONTRACT="$ROOT/release/eggpack/distribution.toml" +PASS=0; FAIL=0 +ok() { PASS=$((PASS + 1)); echo "ok - $1"; } +fail() { FAIL=$((FAIL + 1)); echo "not ok - $1" >&2; } +contains() { [[ "$1" == *"$2"* ]]; } +SANDBOX="$(mktemp -d)" +trap 'rm -rf "$SANDBOX"' EXIT +mkdir -p "$SANDBOX/tmp" "$SANDBOX/fakebin" +export TMPDIR="$SANDBOX/tmp" +FAKEBIN="$SANDBOX/fakebin" +export CURL_LOG="$SANDBOX/curl.log" CARGO_LOG="$SANDBOX/cargo.log" CARGO_ROOT_LOG="$SANDBOX/cargo-root.log" +: > "$CURL_LOG"; : > "$CARGO_LOG"; : > "$CARGO_ROOT_LOG" +cat > "$FAKEBIN/curl" <<'CURL_FIXTURE' +#!/usr/bin/env bash +set -eu +out=""; url=""; format="" +while [[ $# -gt 0 ]]; do + case "$1" in + --proto) [[ $# -ge 2 && "$2" == '=https' ]] || exit 91; shift 2 ;; + --max-time) [[ $# -ge 2 && "$2" =~ ^[0-9]+$ ]] || exit 91; shift 2 ;; + --max-filesize) [[ $# -ge 2 && "$2" =~ ^[0-9]+$ ]] || exit 91; shift 2 ;; + -H) [[ $# -ge 2 && "$2" == 'User-Agent: eggpass/installer' ]] || exit 91; shift 2 ;; + -o) [[ $# -ge 2 && -z "$out" ]] || exit 91; out="$2"; shift 2 ;; + -w) [[ $# -ge 2 && -z "$format" ]] || exit 91; format="$2"; shift 2 ;; + --tlsv1.2|-fsSL) shift ;; + https://*) [[ -z "$url" ]] || exit 91; url="$1"; shift ;; + *) printf 'fake curl refused unexpected argument: %s\n' "$1" >&2; exit 91 ;; + esac +done +[[ -n "$out" && -n "$url" ]] || exit 90 +case "$url" in https://github.com/eggstack/eggpass/releases/*) ;; *) printf 'fake curl refused unexpected host/path: %s\n' "$url" >&2; exit 92 ;; esac +if [[ "$url" == "$FIXTURE_EXPECTED_URL" ]]; then + [[ "$format" == '%{http_code}\n%{url_effective}' ]] || exit 93 +elif [[ "$url" == "$FIXTURE_EXPECTED_URL.sha256" ]]; then + [[ -z "$format" ]] || exit 93 +else + printf 'fake curl refused unexpected URL: %s\n' "$url" >&2; exit 94 +fi +printf '%s\n' "$url" >> "$CURL_LOG" +if [[ "$url" == "$FIXTURE_EXPECTED_URL.sha256" ]]; then + case "$FIXTURE_CURL_MODE" in sha-error) exit 22 ;; malformed-sha) printf 'not-a-digest\n' > "$out"; exit 0 ;; wrong-sha) printf '%064d fixture\n' 0 > "$out"; exit 0 ;; esac + asset="$(printf '%s' "$out" | sed 's/\.sha256$//')" + if command -v sha256sum >/dev/null 2>&1; then digest="$(sha256sum "$asset" | awk '{print $1}')"; else digest="$(shasum -a 256 "$asset" | awk '{print $1}')"; fi + printf '%s %s\n' "$digest" "$(basename "$asset")" > "$out" + exit 0 +fi +latest="$FIXTURE_LATEST_VERSION" +effective="$url" +case "$url" in */latest/download/*) effective="https://github.com/eggstack/eggpass/releases/download/v$latest/$(basename "$url")" ;; esac +case "$FIXTURE_CURL_MODE" in + transport) printf '000\n%s' "$effective"; exit 7 ;; + http500) printf '500\n%s' "$effective"; exit 22 ;; + 404) if [[ "$FIXTURE_NO_EFFECTIVE_TAG" == 1 ]]; then effective="$url"; fi; printf '404\n%s' "$effective"; exit 22 ;; +esac +line="eggpass $FIXTURE_VERSION" +if [[ -n "$FIXTURE_IDENTITY" ]]; then line="$FIXTURE_IDENTITY"; fi +printf '#!/bin/sh\nif [ "$1" = "--version" ]; then printf "%%s\\n" "%s"; exit 0; fi\nexit 0\n' "$line" > "$out" +chmod +x "$out" +printf '200\n%s' "$effective" +CURL_FIXTURE +chmod +x "$FAKEBIN/curl" +cat > "$FAKEBIN/cargo" <<'CARGO_FIXTURE' +#!/usr/bin/env bash +set -eu +[[ $# -eq 7 && "$1" == install && "$2" == --locked && "$3" == --version && "$4" == "=$FIXTURE_CARGO_EXPECTED_VERSION" && "$5" == --root && "$7" == eggpass ]] || { printf 'fake cargo refused unexpected arguments\n' >&2; exit 95; } +root="$6" +case "$root" in "$TMPDIR"/eggpass-install.*/cargo-root) ;; *) printf 'fake cargo refused unexpected staging root: %s\n' "$root" >&2; exit 96 ;; esac +printf 'cargo' >> "$CARGO_LOG" +for arg in "$@"; do printf ' <%s>' "$arg" >> "$CARGO_LOG"; done +printf '\n' >> "$CARGO_LOG" +printf '%s\n' "$root" > "$CARGO_ROOT_LOG" +mkdir -p "$root/bin" +line="eggpass $FIXTURE_CARGO_EXPECTED_VERSION" +if [[ -n "$FIXTURE_CARGO_IDENTITY" ]]; then line="$FIXTURE_CARGO_IDENTITY"; fi +cargo_name=eggpass; [[ "$FIXTURE_EXPECTED_URL" == *windows-msvc.exe ]] && cargo_name=eggpass.exe +printf '#!/bin/sh\nif [ "$1" = "--version" ]; then printf "%%s\\n" "%s"; exit 0; fi\nexit 0\n' "$line" > "$root/bin/$cargo_name" +chmod +x "$root/bin/$cargo_name" +printf 'fake Cargo metadata\n' > "$root/.crates.toml" +CARGO_FIXTURE +chmod +x "$FAKEBIN/cargo" +export PATH="$FAKEBIN:/usr/bin:/bin" SHELL=/bin/zsh +OS=Linux; ARCH=x86_64; FIXTURE_CURL_MODE=ok; FIXTURE_VERSION=1.2.3 +FIXTURE_LATEST_VERSION=1.2.3; FIXTURE_IDENTITY=""; FIXTURE_CARGO_IDENTITY=""; FIXTURE_NO_EFFECTIVE_TAG=0 +export OS ARCH FIXTURE_CURL_MODE FIXTURE_VERSION FIXTURE_LATEST_VERSION FIXTURE_IDENTITY FIXTURE_CARGO_IDENTITY FIXTURE_NO_EFFECTIVE_TAG +fresh_home() { + HOME="$SANDBOX/home-$1"; mkdir -p "$HOME"; export HOME + DEST_DIR="$HOME/.local/bin"; mkdir -p "$DEST_DIR"; export DEST_DIR + PATH="$FAKEBIN:$DEST_DIR:/usr/bin:/bin"; export PATH +} +fixture_target() { + case "$OS" in + Linux) case "$ARCH" in x86_64|amd64|AMD64) printf '%s' x86_64-unknown-linux-gnu ;; aarch64|arm64|ARM64) printf '%s' aarch64-unknown-linux-gnu ;; esac ;; + Darwin) case "$ARCH" in x86_64|amd64|AMD64) printf '%s' x86_64-apple-darwin ;; arm64|aarch64|ARM64) printf '%s' aarch64-apple-darwin ;; esac ;; + MINGW*|MSYS*|CYGWIN*|Windows_NT) case "$ARCH" in x86_64|amd64|AMD64) printf '%s' x86_64-pc-windows-msvc ;; esac ;; + esac +} +run_install() { + local requested="" want_version=0 arg target asset cargo_version + for arg in "$@"; do + if [[ "$want_version" == 1 ]]; then requested="$arg"; want_version=0; continue; fi + if [[ "$arg" == --version ]]; then want_version=1; fi + done + target="$(fixture_target)" + asset="" + EXPECTED_URL="" + if [[ -n "$target" ]]; then + asset="eggpass-$target" + [[ "$target" == x86_64-pc-windows-msvc ]] && asset="$asset.exe" + if [[ -n "$requested" ]]; then EXPECTED_URL="https://github.com/eggstack/eggpass/releases/download/v$requested/$asset" + else EXPECTED_URL="https://github.com/eggstack/eggpass/releases/latest/download/$asset"; fi + fi + cargo_version="$FIXTURE_LATEST_VERSION" + [[ -n "$requested" ]] && cargo_version="$requested" + set +e + OUT="$(EGGPASS_TEST_OS="$OS" EGGPASS_TEST_ARCH="$ARCH" FIXTURE_EXPECTED_URL="$EXPECTED_URL" FIXTURE_CARGO_EXPECTED_VERSION="$cargo_version" bash "$INSTALL_SH" "$@" 2>&1)" + STATUS=$? + set -e +} +reset_logs() { : > "$CURL_LOG"; : > "$CARGO_LOG"; : > "$CARGO_ROOT_LOG"; } +assert_no_cargo() { if [[ ! -s "$CARGO_LOG" ]]; then ok "$1"; else fail "$1 (unexpected Cargo call)"; fi; } + +# Target mapping must remain in the checked-in five-triple Eggpack contract. +for triple in aarch64-apple-darwin aarch64-unknown-linux-gnu x86_64-apple-darwin x86_64-pc-windows-msvc x86_64-unknown-linux-gnu; do + if grep -Fq "triple = \"$triple\"" "$CONTRACT"; then ok "distribution contract includes $triple"; else fail "distribution contract missing $triple"; fi +done +# Cross-installer static policy checks: PowerShell uses the same release URLs, +# Windows distribution asset name, exact candidate identity, and exact Cargo pin. +# shellcheck disable=SC2016 # These literals intentionally match source text. +for policy in '$BaseUrl/latest/download/$Asset' '$BaseUrl/download/$Tag/$Asset' 'eggpass-$Target.exe' 'eggpass --version' '=$SelectedVersion' 'Set-PrivateDirectoryAcl -Path $stageRoot'; do + if grep -Fq "$policy" "$INSTALL_PS"; then ok "PowerShell policy includes $policy"; else fail "PowerShell policy missing $policy"; fi +done +if grep -Fq 'cargo install eggpass' "$INSTALL_PS"; then fail "PowerShell contains floating Cargo install"; else ok "PowerShell has no floating Cargo install"; fi +check_target() { + OS="$1"; ARCH="$2"; expected="$3"; asset="$4"; export OS ARCH + fresh_home "target-$3"; reset_logs; FIXTURE_CURL_MODE=ok; export FIXTURE_CURL_MODE + run_install + executable=eggpass; [[ "$expected" == x86_64-pc-windows-msvc ]] && executable=eggpass.exe + if [[ $STATUS -eq 0 && -x "$DEST_DIR/$executable" ]]; then ok "target maps to $expected"; else fail "target mapping $expected ($OUT)"; fi + expected_urls="$(printf '%s\n%s' "$EXPECTED_URL" "$EXPECTED_URL.sha256")" + if [[ $STATUS -eq 0 && "$(cat "$CURL_LOG")" == "$expected_urls" ]]; then ok "asset and checksum URLs are exact for $expected"; else fail "wrong release URL for $expected: $(cat "$CURL_LOG")"; fi + if ! grep -Fq "triple = \"$expected\"" "$CONTRACT"; then fail "mapping $expected drifted from distribution contract"; fi +} +check_target Linux x86_64 x86_64-unknown-linux-gnu eggpass-x86_64-unknown-linux-gnu +check_target Linux aarch64 aarch64-unknown-linux-gnu eggpass-aarch64-unknown-linux-gnu +check_target Darwin x86_64 x86_64-apple-darwin eggpass-x86_64-apple-darwin +check_target Darwin arm64 aarch64-apple-darwin eggpass-aarch64-apple-darwin +check_target MINGW64_NT x86_64 x86_64-pc-windows-msvc eggpass-x86_64-pc-windows-msvc.exe + +OS=Linux; ARCH=x86_64; export OS ARCH +fresh_home latest; reset_logs; run_install +if [[ $STATUS -eq 0 && "$(cat "$CURL_LOG")" == "$(printf '%s\n%s' "$EXPECTED_URL" "$EXPECTED_URL.sha256")" ]]; then ok "latest selects only GitHub releases/latest"; else fail "latest URL authority"; fi +fresh_home pinned; reset_logs; FIXTURE_VERSION=2.3.4; export FIXTURE_VERSION; run_install --version 2.3.4 +if [[ $STATUS -eq 0 && "$EXPECTED_URL" == 'https://github.com/eggstack/eggpass/releases/download/v2.3.4/eggpass-x86_64-unknown-linux-gnu' && "$(cat "$CURL_LOG")" == "$(printf '%s\n%s' "$EXPECTED_URL" "$EXPECTED_URL.sha256")" ]]; then ok "pinned selection uses only exact v2.3.4 authority"; else fail "pinned URL authority"; fi + +for mode in malformed-sha wrong-sha sha-error; do + fresh_home "failure-$mode"; reset_logs; FIXTURE_CURL_MODE="$mode"; export FIXTURE_CURL_MODE; run_install + if [[ $STATUS -ne 0 && ! -e "$DEST_DIR/eggpass" ]]; then ok "$mode fails before install"; else fail "$mode did not fail closed"; fi + assert_no_cargo "$mode never triggers Cargo" +done +fresh_home mismatch; reset_logs; FIXTURE_CURL_MODE=ok; FIXTURE_VERSION=9.9.8; export FIXTURE_CURL_MODE FIXTURE_VERSION; run_install --version 1.2.3 +if [[ $STATUS -ne 0 && ! -e "$DEST_DIR/eggpass" ]]; then ok "pinned candidate mismatch fails"; else fail "pinned mismatch was accepted"; fi +assert_no_cargo "identity mismatch never triggers Cargo" +fresh_home extra-identity; reset_logs; FIXTURE_VERSION=1.2.3; FIXTURE_IDENTITY='eggpass 1.2.3 extra'; export FIXTURE_VERSION FIXTURE_IDENTITY; run_install --version 1.2.3 +if [[ $STATUS -ne 0 && ! -e "$DEST_DIR/eggpass" ]]; then ok "extra candidate identity fields are rejected"; else fail "extra identity accepted"; fi +assert_no_cargo "candidate identity failure never triggers Cargo" +FIXTURE_IDENTITY=""; export FIXTURE_IDENTITY +for mode in transport http500; do + fresh_home "transport-$mode"; reset_logs; FIXTURE_CURL_MODE="$mode"; export FIXTURE_CURL_MODE; run_install --version 1.2.3 + if [[ $STATUS -ne 0 ]]; then ok "$mode fails"; else fail "$mode was accepted"; fi + assert_no_cargo "$mode does not trigger fallback" +done + +# Exact 404 is the only fallback trigger; latest must resolve to an exact tag. +OS=Linux; ARCH=x86_64; export OS ARCH; fresh_home fallback-latest; reset_logs +FIXTURE_CURL_MODE=404; FIXTURE_LATEST_VERSION=1.2.3; FIXTURE_VERSION=1.2.3; export FIXTURE_CURL_MODE FIXTURE_LATEST_VERSION FIXTURE_VERSION; run_install +if [[ $STATUS -eq 0 ]] && contains "$(cat "$CARGO_LOG")" '<--version> <=1.2.3'; then ok "latest 404 fallback pins Cargo to resolved release"; else fail "latest fallback did not pin Cargo ($OUT)"; fi +if [[ -x "$DEST_DIR/eggpass" && "$("$DEST_DIR/eggpass" --version)" == 'eggpass 1.2.3' ]]; then ok "Cargo candidate copied to per-user binary path"; else fail "Cargo result not installed"; fi +cargo_root="$(cat "$CARGO_ROOT_LOG")" +if [[ -n "$cargo_root" && ! -e "$cargo_root" && ! -e "$(dirname "$cargo_root")" ]]; then ok "private Cargo staging root and parent are removed"; else fail "Cargo staging leaked: $cargo_root"; fi +if [[ ! -e "$HOME/.cargo" && ! -e "$DEST_DIR/.crates.toml" ]]; then ok "Cargo metadata is not retained at final install"; else fail "Cargo metadata leaked"; fi +fresh_home fallback-pinned; reset_logs; FIXTURE_CURL_MODE=404; FIXTURE_VERSION=3.4.5; export FIXTURE_CURL_MODE FIXTURE_VERSION; run_install --version 3.4.5 +if contains "$(cat "$CARGO_LOG")" '<--version> <=3.4.5'; then ok "pinned fallback asks Cargo for the exact version"; else fail "pinned fallback version was not exact"; fi +fresh_home fallback-unresolved; reset_logs; FIXTURE_CURL_MODE=404; FIXTURE_NO_EFFECTIVE_TAG=1; export FIXTURE_CURL_MODE FIXTURE_NO_EFFECTIVE_TAG; run_install +if [[ $STATUS -ne 0 ]]; then ok "unresolved latest 404 is refused"; else fail "unresolved latest fallback accepted"; fi +assert_no_cargo "latest without exact tag never invokes Cargo" +FIXTURE_NO_EFFECTIVE_TAG=0; export FIXTURE_NO_EFFECTIVE_TAG + +fresh_home unsupported; reset_logs; OS=FreeBSD; ARCH=x86_64; export OS ARCH; FIXTURE_CURL_MODE=404; export FIXTURE_CURL_MODE; run_install +if [[ $STATUS -ne 0 ]]; then ok "unsupported platform is rejected"; else fail "unsupported platform accepted"; fi +assert_no_cargo "unsupported platform never falls back" +if [[ ! -s "$CURL_LOG" ]]; then ok "unsupported platform performs no HTTP request"; else fail "unsupported platform reached the downloader"; fi +OS=Linux; ARCH=x86_64; export OS ARCH; fresh_home rerun; reset_logs; FIXTURE_CURL_MODE=ok; FIXTURE_VERSION=1.0.0; export FIXTURE_CURL_MODE FIXTURE_VERSION; run_install +FIXTURE_VERSION=1.2.3; export FIXTURE_VERSION; run_install +if [[ $STATUS -eq 0 && "$("$DEST_DIR/eggpass" --version)" == 'eggpass 1.2.3' && "$OUT" == *"same-scope rerun"* ]]; then ok "same-scope rerun replaces the owned binary"; else fail "same-scope rerun failed"; fi +fresh_home foreign; printf '%s\n' '#!/bin/sh' 'echo foreign 1.0.0' > "$DEST_DIR/eggpass"; chmod +x "$DEST_DIR/eggpass"; reset_logs; FIXTURE_CURL_MODE=ok; export FIXTURE_CURL_MODE; run_install +if [[ $STATUS -ne 0 && "$("$DEST_DIR/eggpass")" == 'foreign 1.0.0' ]]; then ok "foreign executable is preserved"; else fail "foreign executable overwritten"; fi +fresh_home symlink; printf '%s\n' 'preserve me' > "$SANDBOX/target-file"; ln -s "$SANDBOX/target-file" "$DEST_DIR/eggpass"; reset_logs; run_install +if [[ $STATUS -ne 0 && -L "$DEST_DIR/eggpass" && "$(cat "$SANDBOX/target-file")" == 'preserve me' ]]; then ok "destination symlink is refused safely"; else fail "destination symlink safety failed"; fi + +# All profile paths and HOME values are inside SANDBOX. +fresh_home path; PATH="$FAKEBIN:/usr/bin:/bin"; export PATH; reset_logs; FIXTURE_CURL_MODE=ok; FIXTURE_VERSION=1.2.3; export FIXTURE_CURL_MODE FIXTURE_VERSION; run_install +if [[ $STATUS -eq 0 && -f "$HOME/.zshrc" ]] && grep -Fq 'added by eggpass installer' "$HOME/.zshrc"; then ok "zsh profile gets managed PATH block"; else fail "PATH block missing"; fi +run_install +if [[ $(grep -c 'added by eggpass installer' "$HOME/.zshrc") -eq 1 ]]; then ok "profile PATH append is idempotent"; else fail "PATH entry duplicated"; fi +fresh_home path-symlink; PATH="$FAKEBIN:/usr/bin:/bin"; export PATH; printf '%s\n' safe > "$SANDBOX/profile-target"; ln -s "$SANDBOX/profile-target" "$HOME/.zshrc"; run_install +if [[ -L "$HOME/.zshrc" && "$(cat "$SANDBOX/profile-target")" == safe ]]; then ok "profile symlink is not followed"; else fail "profile symlink was changed"; fi +fresh_home path-present; PATH="$DEST_DIR:$FAKEBIN:/usr/bin:/bin"; export PATH; reset_logs; run_install --no-shell-profile +if [[ $STATUS -eq 0 && "$OUT" == *"is available on the current PATH"* && ! -e "$HOME/.zshrc" ]]; then ok "existing PATH entry is detected without profile edits"; else fail "current PATH detection failed"; fi +fresh_home path-manual; PATH="$FAKEBIN:/usr/bin:/bin"; export PATH; reset_logs; run_install --no-shell-profile +if [[ $STATUS -eq 0 && "$OUT" == *"export PATH=\"\$HOME/.local/bin:\$PATH\""* && ! -e "$HOME/.zshrc" ]]; then ok "no-profile mode prints manual PATH guidance"; else fail "manual PATH guidance missing"; fi + +fresh_home user-scope; reset_logs; FIXTURE_CURL_MODE=ok; export FIXTURE_CURL_MODE; run_install +if [[ $STATUS -eq 0 && -x "$HOME/.local/bin/eggpass" ]]; then ok "default install is per-user"; else fail "default user scope failed"; fi +if [[ $EUID -eq 0 ]]; then + fresh_home system-scope; EGGPASS_TEST_SYSTEM_DIR="$SANDBOX/system-bin"; export EGGPASS_TEST_SYSTEM_DIR; run_install --system + if [[ $STATUS -eq 0 && -x "$SANDBOX/system-bin/eggpass" ]]; then ok "explicit system scope uses isolated system destination"; else fail "system scope failed"; fi +else + fresh_home system-denied; run_install --system + if [[ $STATUS -ne 0 && "$OUT" == *"requires an already elevated shell"* ]]; then ok "system scope requires elevation"; else fail "system elevation boundary failed"; fi +fi +printf '\npass=%s fail=%s\n' "$PASS" "$FAIL" +[[ $FAIL -eq 0 ]] diff --git a/release/eggpack/github-policy.json b/release/eggpack/github-policy.json index 5d859cc..8c15bd4 100644 --- a/release/eggpack/github-policy.json +++ b/release/eggpack/github-policy.json @@ -69,7 +69,8 @@ "inputs": { "contract": "release/eggpack/distribution.toml", "install_policy": "release/eggpack/install-policy.toml", - "github_policy": "release/eggpack/github-template.json" + "github_policy": "release/eggpack/github-template.json", + "installer_presentation": "release/eggpack/installer-presentation.json" }, "receipt_retention_days": 7 } diff --git a/release/eggpack/github-template.json b/release/eggpack/github-template.json index 8e2a6e9..438ea01 100644 --- a/release/eggpack/github-template.json +++ b/release/eggpack/github-template.json @@ -3,7 +3,7 @@ "owner": "eggstack", "repository": "eggpass", "title_prefix": "eggpass ", - "body": "Draft binary release staged by Eggpack. Review the five target binaries, release manifest, source revision, and checksum sidecars before publishing. This release remains a draft until a maintainer publishes it.", + "body": "Draft release staged by Eggpack. Review all five target binaries and checksum sidecars, release manifest, source revision, and four auxiliary installer assets (install.sh, install.ps1, install-exact.sh, install-exact.ps1). Confirm wrappers use latest/exact release URLs and are not manifest binaries. This release remains a draft until a maintainer publishes it.", "prerelease": false, "token_env": "GITHUB_TOKEN", "request_timeout_secs": 30, diff --git a/release/eggpack/installer-presentation.json b/release/eggpack/installer-presentation.json new file mode 100644 index 0000000..e68f5de --- /dev/null +++ b/release/eggpack/installer-presentation.json @@ -0,0 +1,11 @@ +{ + "schema_version": 1, + "mode": { + "product_wrappers": { + "posix_source": "packaging/install.sh", + "powershell_source": "packaging/install.ps1", + "generated_posix_name": "install-exact.sh", + "generated_powershell_name": "install-exact.ps1" + } + } +} diff --git a/scripts/check-installer-contract.py b/scripts/check-installer-contract.py new file mode 100644 index 0000000..7b1bff7 --- /dev/null +++ b/scripts/check-installer-contract.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Static release-contract checks for Eggpass's installer presentation.""" + +from __future__ import annotations + +import json +import sys +import tomllib +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +EXPECTED_TARGETS = { + "aarch64-apple-darwin", + "aarch64-unknown-linux-gnu", + "x86_64-apple-darwin", + "x86_64-pc-windows-msvc", + "x86_64-unknown-linux-gnu", +} +EXPECTED_AUXILIARY = { + "install.sh", + "install.ps1", + "install-exact.sh", + "install-exact.ps1", +} + + +def require(condition: bool, message: str) -> None: + if not condition: + raise ValueError(message) + + +def main() -> int: + distribution = tomllib.loads((ROOT / "release/eggpack/distribution.toml").read_text()) + targets = distribution["targets"] + triples = {target["triple"] for target in targets} + require(triples == EXPECTED_TARGETS, f"distribution target drift: {sorted(triples)}") + require(distribution["product"]["id"] == "eggpass", "unexpected distribution product") + + binary_assets: set[str] = set() + checksum_assets: set[str] = set() + for target in targets: + triple = target["triple"] + asset = target["asset"]["asset"].replace("{product}", "eggpass").replace("{target}", triple) + sidecar = target["checksum"]["sidecar"].replace("{asset}", asset) + require(asset not in binary_assets, f"duplicate binary asset: {asset}") + binary_assets.add(asset) + checksum_assets.add(sidecar) + + presentation = json.loads((ROOT / "release/eggpack/installer-presentation.json").read_text()) + require(presentation == { + "schema_version": 1, + "mode": { + "product_wrappers": { + "posix_source": "packaging/install.sh", + "powershell_source": "packaging/install.ps1", + "generated_posix_name": "install-exact.sh", + "generated_powershell_name": "install-exact.ps1", + } + }, + }, "installer presentation must stage the reviewed wrappers and exact bootstraps") + + auxiliary = EXPECTED_AUXILIARY + release_members = binary_assets | checksum_assets | {"release-manifest.json"} + require(not (auxiliary & release_members), "installer assets must remain outside the binary manifest contract") + + for relative in ("packaging/install.sh", "packaging/install.ps1"): + path = ROOT / relative + require(path.is_file() and not path.is_symlink(), f"installer source is missing or unsafe: {relative}") + require(path.stat().st_size <= 1_048_576, f"installer exceeds Eggpack's 1 MiB bound: {relative}") + text = path.read_text(encoding="utf-8") + require("eggstack/eggpass" in text, f"wrong repository in {relative}") + require("latest/download" in text, f"latest release URL missing from {relative}") + require("--version" in text or "Version" in text, f"pinned-version option missing from {relative}") + require(".sha256" in text, f"checksum sidecar handling missing from {relative}") + script_targets = EXPECTED_TARGETS if relative.endswith(".sh") else {"x86_64-pc-windows-msvc"} + for triple in script_targets: + require(triple in text, f"target mapping missing from {relative}: {triple}") + require("raw.githubusercontent.com" not in text, f"installer must not fetch a mutable source file: {relative}") + + readme = (ROOT / "README.md").read_text(encoding="utf-8") + for url in ( + "https://github.com/eggstack/eggpass/releases/latest/download/install.sh", + "https://github.com/eggstack/eggpass/releases/latest/download/install.ps1", + "https://github.com/eggstack/eggpass/releases/download/vX.Y.Z/install.sh", + "https://github.com/eggstack/eggpass/releases/download/vX.Y.Z/install.ps1", + ): + require(url in readme, f"install documentation is missing release URL: {url}") + + draft = json.loads((ROOT / "release/eggpack/github-template.json").read_text()) + for asset in sorted(auxiliary): + require(asset in draft["body"], f"draft review text omits auxiliary asset: {asset}") + print("Eggpass installer release contract is consistent") + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except (OSError, UnicodeError, json.JSONDecodeError, tomllib.TOMLDecodeError, KeyError, TypeError, ValueError) as exc: + print(f"installer contract check failed: {exc}", file=sys.stderr) + raise SystemExit(1) diff --git a/src/cli/commands/update.rs b/src/cli/commands/update.rs index b31a407..615a0d3 100644 --- a/src/cli/commands/update.rs +++ b/src/cli/commands/update.rs @@ -1,10 +1,9 @@ //! `eggpass update`. //! -//! The update itself is done by `eggup`, the eggstack family's verified -//! updater: it fetches the release manifest, checks the SHA-256 of what it -//! downloaded, validates it, and only then replaces the running binary. The -//! same mechanism every other eggstack tool uses, so the behaviour is the same -//! everywhere. +//! Self-managed binaries use Eggup's verified manifest-driven transaction. +//! Cargo-managed binaries are delegated to Cargo only when their recorded root +//! and default crates.io source can be proven; the Cargo-owned executable is +//! never replaced through Eggup. //! //! The SHA-256 check is an **integrity** check, not an authenticity check: it //! proves the download was not corrupted, not that it came from us. The @@ -38,6 +37,15 @@ pub fn update(context: &Context, version: Option, check: bool) -> Result ); println!(" target: {}", plan.target); println!(" asset: {}", plan.asset); + match &plan.provenance { + crate::update::Provenance::CargoManaged { .. } => { + println!(" method: Cargo-managed install") + } + crate::update::Provenance::SelfManaged { .. } => { + println!(" method: verified Eggup transaction") + } + crate::update::Provenance::Unprovable { .. } => {} + } // The daemon is deliberately not restarted: a restart cuts live streams, // and the user asked for an update, not an outage. diff --git a/src/update.rs b/src/update.rs index c9a06a2..27e87d5 100644 --- a/src/update.rs +++ b/src/update.rs @@ -76,6 +76,9 @@ const TOTAL_TIMEOUT: Duration = Duration::from_secs(120); /// installation root. const CARGO_ROOT_SEARCH_DEPTH: usize = 4; +/// Cargo's canonical source identifier for the default crates.io registry. +const CRATES_IO_SOURCE: &str = "registry+https://github.com/rust-lang/crates.io-index"; + /// The User-Agent every outbound request identifies itself with. /// /// The release host answers 403 to an anonymous or generic agent, so this is a @@ -118,14 +121,16 @@ pub fn host_target() -> Option<&'static str> { #[derive(Debug, Clone, PartialEq, Eq)] pub enum Provenance { /// The running executable is positively recorded in a Cargo installation - /// root's package metadata. Cargo owns that file and its bookkeeping; - /// replacing it here would leave `cargo install --list` and uninstall - /// lying. The correct command is printed instead. + /// root's package metadata, including its original source. Cargo owns that + /// file and its bookkeeping; the binary is never replaced through Eggup. + /// Only a default crates.io source is eligible for Cargo delegation. CargoManaged { /// The installation root Cargo owns. root: PathBuf, /// The version Cargo recorded. version: String, + /// The source string Cargo recorded for this installation. + source: String, }, /// The running executable is not Cargo-managed and is positively identified /// by its exact digest, which is revalidated under `eggup`'s mutation lock @@ -155,10 +160,19 @@ impl Provenance { /// The exact command the user should run instead, when there is one. pub fn remediation(&self) -> Option { match self { - Provenance::CargoManaged { root, .. } => Some(format!( - "cargo install {PRODUCT} --locked --force --root {}", - root.display() - )), + Provenance::CargoManaged { root, source, .. } => { + if source == CRATES_IO_SOURCE { + Some(format!( + "rerun `eggpass update` so Cargo uses the detected root {}", + root.display() + )) + } else { + Some(format!( + "update eggpass with the original Cargo source options for root {}", + root.display() + )) + } + } Provenance::Unprovable { .. } => Some(format!( "Reinstall with the published installer, then retry: \ https://github.com/eggstack/{PRODUCT}" @@ -223,6 +237,26 @@ pub enum UpdateError { /// What stopped it. provenance: Provenance, }, + /// Cargo owns this install, but its source cannot be safely automated. + CargoSource { + /// Human-readable source classification. + source: &'static str, + /// Exact Eggpass release selected by the manifest. + version: String, + /// The Cargo installation root. + root: PathBuf, + }, + /// Cargo could not update or verify a supported installation. + CargoUpdate { + /// What went wrong. + detail: String, + }, + /// The platform requires the user to run the exact Cargo command after exit. + #[cfg(windows)] + CargoHandoff { + /// Exact command to run after this process closes. + command: String, + }, /// The host has no published artifact. HostUnsupported { /// What was missing. @@ -285,6 +319,24 @@ impl std::fmt::Display for UpdateError { } Ok(()) } + UpdateError::CargoSource { + source, + version, + root, + } => write!( + f, + "Cargo owns this installation at {} and its recorded source is {source}; \ + automatic updates are limited to default crates.io and will not switch sources. \ + Update eggpass {version} with the original Cargo source options.", + root.display() + ), + UpdateError::CargoUpdate { detail } => write!(f, "{detail}"), + #[cfg(windows)] + UpdateError::CargoHandoff { command } => write!( + f, + "Cargo owns this executable and this platform cannot safely replace a running \ + executable. Close eggpass, then run:\n {command}" + ), UpdateError::HostUnsupported { detail } => write!(f, "{detail}"), UpdateError::Catalogue { detail } => write!(f, "{detail}"), UpdateError::WrongRelease { wanted, published } => write!( @@ -350,7 +402,7 @@ pub fn update( // release host anything. When local provenance alone makes the mutation // impossible, there is nothing the network can tell us that changes the // answer. - if !check_only && !matches!(provenance, Provenance::SelfManaged { .. }) { + if !check_only && matches!(provenance, Provenance::Unprovable { .. }) { return Err(UpdateError::Provenance { provenance }); } @@ -436,7 +488,166 @@ pub fn update( return Ok(plan); } - execute(settings, &plan, binary, ¤t_exe) + match &plan.provenance { + Provenance::SelfManaged { .. } => execute(settings, &plan, binary, ¤t_exe), + Provenance::CargoManaged { root, source, .. } => { + execute_cargo_managed_update(root, source, &plan.to_version, ¤t_exe) + .map(|()| plan) + } + Provenance::Unprovable { .. } => Err(UpdateError::Provenance { + provenance: plan.provenance, + }), + } +} + +/// Dispatch only when the original install is proven to come from crates.io. +fn execute_cargo_managed_update( + root: &Path, + source: &str, + version: &str, + current_exe: &Path, +) -> Result<(), UpdateError> { + execute_cargo_managed_update_with( + std::ffi::OsStr::new("cargo"), + root, + source, + version, + current_exe, + ) +} + +fn execute_cargo_managed_update_with( + cargo: &std::ffi::OsStr, + root: &Path, + source: &str, + version: &str, + current_exe: &Path, +) -> Result<(), UpdateError> { + if source != CRATES_IO_SOURCE { + return Err(UpdateError::CargoSource { + source: cargo_source_description(source), + version: version.to_string(), + root: root.to_path_buf(), + }); + } + execute_cargo_update_with(cargo, root, version, current_exe) +} + +/// Update a Cargo-managed binary without replacing it through Eggup. +/// +/// Unix permits Cargo's atomic replacement while this process continues to run. +/// Windows does not have a qualified safe replacement path for a running image, +/// so it receives an exact command handoff instead of a risky in-place attempt. +fn execute_cargo_update_with( + cargo: &std::ffi::OsStr, + root: &Path, + version: &str, + current_exe: &Path, +) -> Result<(), UpdateError> { + let manual_command = cargo_update_hint(root, version); + + #[cfg(windows)] + { + let _ = current_exe; + return Err(UpdateError::CargoHandoff { + command: manual_command, + }); + } + + #[cfg(not(windows))] + { + let status = cargo_update_command(cargo, root, version) + .status() + .map_err(|err| UpdateError::CargoUpdate { + detail: format!( + "could not start Cargo ({err}); update the detected root manually with:\n {manual_command}" + ), + })?; + if !status.success() { + return Err(UpdateError::CargoUpdate { + detail: format!( + "Cargo did not install eggpass {version} (exit status {}). If this release was just published, wait for crates.io to index the exact version and retry; no other version was selected.\nRun manually with:\n {manual_command}", + status + .code() + .map_or_else(|| "unknown".to_string(), |code| code.to_string()) + ), + }); + } + + match read_cargo_record(root) { + CargoRecord::Recorded { + version: recorded, + source, + } if recorded == version && source == CRATES_IO_SOURCE => {} + CargoRecord::Recorded { + version: recorded, .. + } => { + return Err(UpdateError::CargoUpdate { + detail: format!( + "Cargo completed, but its record at {} names eggpass {recorded} rather than the requested crates.io version {version}; refusing to report success", + root.display() + ), + }); + } + _ => { + return Err(UpdateError::CargoUpdate { + detail: format!( + "Cargo completed, but the package record at {} could not prove eggpass {version} is installed from crates.io; refusing to report success", + root.display() + ), + }); + } + } + + let output = std::process::Command::new(current_exe) + .arg("--version") + .output() + .map_err(|err| UpdateError::CargoUpdate { + detail: format!( + "Cargo recorded eggpass {version}, but the installed executable could not be checked: {err}" + ), + })?; + if !output.status.success() || output.stdout != expected_identity(version).as_bytes() { + return Err(UpdateError::CargoUpdate { + detail: format!( + "Cargo recorded eggpass {version}, but the installed executable did not print the exact expected identity; refusing to report success" + ), + }); + } + + Ok(()) + } +} + +/// Construct Cargo's invocation without a shell, preserving the detected root. +fn cargo_update_command( + cargo: &std::ffi::OsStr, + root: &Path, + version: &str, +) -> std::process::Command { + let exact_version = format!("={version}"); + let mut command = std::process::Command::new(cargo); + command + .args(["install", PRODUCT, "--version"]) + .arg(exact_version) + .args(["--locked", "--force", "--root"]) + .arg(root) + .args(["--registry", "crates-io"]); + command +} + +/// A shell-ready exact command for platforms that need a safe handoff. +fn cargo_update_hint(root: &Path, version: &str) -> String { + #[cfg(unix)] + let quoted_root = format!("'{}'", root.display().to_string().replace('\'', "'\\''")); + #[cfg(windows)] + let quoted_root = format!("\"{}\"", root.display()); + #[cfg(not(any(unix, windows)))] + let quoted_root = root.display().to_string(); + + format!( + "cargo install {PRODUCT} --version ={version} --locked --force --root {quoted_root} --registry crates-io" + ) } /// The base URL a release's assets are served from. @@ -752,8 +963,20 @@ pub fn classify_provenance(current_exe: &Path) -> Provenance { // A Cargo installation root owns the file when its own record says so. for root in cargo_roots_above(current_exe) { match read_cargo_record(&root) { - CargoRecord::Recorded { version } => { - return Provenance::CargoManaged { root, version }; + CargoRecord::Recorded { version, source } => { + if version != CURRENT_VERSION { + return Provenance::Unprovable { + detail: format!( + "Cargo records eggpass {version} in {}, but the running binary identifies as {CURRENT_VERSION}; ownership metadata and executable identity disagree", + root.display() + ), + }; + } + return Provenance::CargoManaged { + root, + version, + source, + }; } CargoRecord::Uninterpretable { detail } => { // The record is there but could not be read. That is positive @@ -782,7 +1005,7 @@ pub fn classify_provenance(current_exe: &Path) -> Provenance { #[derive(Debug, Clone, PartialEq, Eq)] enum CargoRecord { /// Cargo positively records this product in this root. - Recorded { version: String }, + Recorded { version: String, source: String }, /// The record is readable and does not claim this product. DoesNotClaim, /// No record file at this root. @@ -812,7 +1035,7 @@ fn cargo_roots_above(path: &Path) -> Vec { fn read_cargo_record(root: &Path) -> CargoRecord { let path = root.join(".crates.toml"); - let metadata = match std::fs::metadata(&path) { + let metadata = match std::fs::symlink_metadata(&path) { Err(err) if err.kind() == std::io::ErrorKind::NotFound => return CargoRecord::Absent, Err(err) => { return CargoRecord::Uninterpretable { @@ -874,33 +1097,114 @@ fn read_cargo_record(root: &Path) -> CargoRecord { }; }; + let mut matching_record = None; for (key, binaries) in table { - // The key is ` ()`. - let Some(rest) = key.split_whitespace().next() else { - continue; + let Some(list) = binaries.as_array() else { + return CargoRecord::Uninterpretable { + detail: format!( + "the Cargo record {} contains a non-array package entry", + path.display() + ), + }; }; - if rest != PRODUCT { + let mut claims = false; + for binary in list { + let Some(binary) = binary.as_str() else { + return CargoRecord::Uninterpretable { + detail: format!( + "the Cargo record {} contains a non-string binary entry", + path.display() + ), + }; + }; + claims |= binary == PRODUCT; + } + if !claims { continue; } - let version = key - .split_whitespace() - .nth(1) - .unwrap_or("unknown") - .to_string(); - let claims = binaries - .as_array() - .map(|list| { - list.iter() - .filter_map(toml::Value::as_str) - .any(|name| name == PRODUCT) - }) - .unwrap_or(false); - if claims { - return CargoRecord::Recorded { version }; + + let Some((package, version, source)) = parse_cargo_record_key(key) else { + return CargoRecord::Uninterpretable { + detail: format!( + "the Cargo record {} claims an eggpass binary with malformed package metadata", + path.display() + ), + }; + }; + if package != PRODUCT || !is_release_version(&version) { + return CargoRecord::Uninterpretable { + detail: format!( + "the Cargo record {} claims eggpass but its package identity or version is not a supported stable release", + path.display() + ), + }; + } + if matching_record.is_some() { + return CargoRecord::Uninterpretable { + detail: format!( + "the Cargo record {} contains multiple entries claiming the eggpass binary", + path.display() + ), + }; } + matching_record = Some((version, source)); } - CargoRecord::DoesNotClaim + match matching_record { + Some((version, source)) => CargoRecord::Recorded { version, source }, + None => CargoRecord::DoesNotClaim, + } +} + +/// Parse Cargo's ` ()` record key. +fn parse_cargo_record_key(key: &str) -> Option<(String, String, String)> { + let (package_version, source) = key.split_once(" (")?; + let source = source.strip_suffix(')')?; + if source.is_empty() || source.contains(['\n', '\r']) { + return None; + } + + let mut fields = package_version.split_whitespace(); + let package = fields.next()?; + let version = fields.next()?; + if fields.next().is_some() { + return None; + } + + Some((package.to_string(), version.to_string(), source.to_string())) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum CargoSourceKind { + CratesIo, + OtherRegistry, + Git, + Path, + Unrecognized, +} + +fn cargo_source_kind(source: &str) -> CargoSourceKind { + if source == CRATES_IO_SOURCE { + CargoSourceKind::CratesIo + } else if source.starts_with("registry+") || source.starts_with("sparse+") { + CargoSourceKind::OtherRegistry + } else if source.starts_with("git+") { + CargoSourceKind::Git + } else if source.starts_with("path+") { + CargoSourceKind::Path + } else { + CargoSourceKind::Unrecognized + } +} + +fn cargo_source_description(source: &str) -> &'static str { + match cargo_source_kind(source) { + CargoSourceKind::CratesIo => "the default crates.io registry", + CargoSourceKind::OtherRegistry => "an alternate registry", + CargoSourceKind::Git => "a Git source", + CargoSourceKind::Path => "a local path source", + CargoSourceKind::Unrecognized => "an unrecognized Cargo source", + } } /// Compare two plain `X.Y.Z` versions. @@ -1001,3 +1305,7 @@ mod tests { assert_eq!(host_target(), Some("x86_64-unknown-linux-gnu")); } } + +#[cfg(test)] +#[path = "update_tests.rs"] +mod extra_tests; diff --git a/src/update_tests.rs b/src/update_tests.rs new file mode 100644 index 0000000..38bbbc3 --- /dev/null +++ b/src/update_tests.rs @@ -0,0 +1,449 @@ +use super::*; + +#[test] +fn cargo_record_parser_retains_registry_source() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path(); + std::fs::write( + root.join(".crates.toml"), + format!("[v1]\n\"eggpass {CURRENT_VERSION} ({CRATES_IO_SOURCE})\" = [\"eggpass\"]\n"), + ) + .unwrap(); + + assert_eq!( + read_cargo_record(root), + CargoRecord::Recorded { + version: CURRENT_VERSION.to_string(), + source: CRATES_IO_SOURCE.to_string(), + } + ); +} + +#[test] +fn cargo_source_classification_keeps_non_default_sources_manual_only() { + assert_eq!( + cargo_source_kind(CRATES_IO_SOURCE), + CargoSourceKind::CratesIo + ); + assert_eq!( + cargo_source_kind("registry+https://registry.example.invalid/index"), + CargoSourceKind::OtherRegistry + ); + assert_eq!( + cargo_source_kind("sparse+https://registry.example.invalid/index/"), + CargoSourceKind::OtherRegistry + ); + assert_eq!( + cargo_source_kind("git+https://example.invalid/repo"), + CargoSourceKind::Git + ); + assert_eq!( + cargo_source_kind("path+file:///workspace/eggpass"), + CargoSourceKind::Path + ); + assert_eq!( + cargo_source_kind("mystery-source"), + CargoSourceKind::Unrecognized + ); +} + +#[test] +fn cargo_record_parser_preserves_other_source_ids() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path(); + for (source, expected) in [ + ( + "registry+https://registry.example.invalid/index", + CargoSourceKind::OtherRegistry, + ), + ( + "git+https://example.invalid/eggpass#commit", + CargoSourceKind::Git, + ), + ("path+file:///workspace/eggpass", CargoSourceKind::Path), + ("opaque-source", CargoSourceKind::Unrecognized), + ] { + std::fs::write( + root.join(".crates.toml"), + format!("[v1]\n\"eggpass {CURRENT_VERSION} ({source})\" = [\"eggpass\"]\n"), + ) + .unwrap(); + match read_cargo_record(root) { + CargoRecord::Recorded { + version, + source: recorded, + } => { + assert_eq!(version, CURRENT_VERSION); + assert_eq!(recorded, source); + assert_eq!(cargo_source_kind(&recorded), expected); + } + other => panic!("expected a preserved Cargo source, got {other:?}"), + } + } +} + +#[cfg(unix)] +#[test] +fn symlinked_cargo_record_is_unprovable() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().join("cargo-root"); + let binary = root.join("bin").join("eggpass"); + std::fs::create_dir_all(binary.parent().unwrap()).unwrap(); + std::fs::write(&binary, b"test binary").unwrap(); + let external = directory.path().join("external-crates.toml"); + std::fs::write( + &external, + format!("[v1]\n\"eggpass {CURRENT_VERSION} ({CRATES_IO_SOURCE})\" = [\"eggpass\"]\n"), + ) + .unwrap(); + std::os::unix::fs::symlink(&external, root.join(".crates.toml")).unwrap(); + + assert!(matches!( + classify_provenance(&binary), + Provenance::Unprovable { .. } + )); +} + +#[test] +fn malformed_or_ambiguous_cargo_claims_fail_closed() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path(); + std::fs::write( + root.join(".crates.toml"), + format!("[v1]\n\"eggpass {CURRENT_VERSION} without-source\" = [\"eggpass\"]\n"), + ) + .unwrap(); + assert!(matches!( + read_cargo_record(root), + CargoRecord::Uninterpretable { .. } + )); + + std::fs::write( + root.join(".crates.toml"), + format!( + "[v1]\n\"eggpass {CURRENT_VERSION} ({CRATES_IO_SOURCE})\" = [\"eggpass\"]\n\"eggpass 0.1.2 ({CRATES_IO_SOURCE})\" = [\"eggpass\"]\n" + ), + ) + .unwrap(); + assert!(matches!( + read_cargo_record(root), + CargoRecord::Uninterpretable { .. } + )); +} + +#[test] +fn cargo_record_must_match_the_running_binary_version() { + let directory = tempfile::tempdir().unwrap(); + let root = directory.path().join("cargo-root"); + let binary = root.join("bin").join("eggpass"); + std::fs::create_dir_all(binary.parent().unwrap()).unwrap(); + std::fs::write(&binary, b"test binary").unwrap(); + std::fs::write( + root.join(".crates.toml"), + "[v1]\n\"eggpass 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)\" = [\"eggpass\"]\n", + ) + .unwrap(); + + assert!(matches!( + classify_provenance(&binary), + Provenance::Unprovable { .. } + )); +} + +#[test] +fn cargo_update_command_pins_version_and_detected_root() { + let root = Path::new("/tmp/cargo root"); + let command = cargo_update_command(std::ffi::OsStr::new("cargo"), root, "0.2.0"); + let args: Vec<_> = command + .get_args() + .map(|argument| argument.to_string_lossy().into_owned()) + .collect(); + assert_eq!( + args, + [ + "install", + "eggpass", + "--version", + "=0.2.0", + "--locked", + "--force", + "--root", + "/tmp/cargo root", + "--registry", + "crates-io", + ] + ); +} + +#[cfg(unix)] +#[test] +fn non_default_cargo_sources_never_invoke_update_delegation() { + use std::os::unix::fs::PermissionsExt; + + let directory = tempfile::tempdir().unwrap(); + let fake_cargo = directory.path().join("fake-cargo"); + std::fs::write(&fake_cargo, "#!/bin/sh\nexit 0\n").unwrap(); + let mut permissions = std::fs::metadata(&fake_cargo).unwrap().permissions(); + permissions.set_mode(0o755); + std::fs::set_permissions(&fake_cargo, permissions).unwrap(); + + let result = execute_cargo_managed_update_with( + fake_cargo.as_os_str(), + &directory.path().join("cargo-root"), + "git+https://example.invalid/eggpass#revision", + "0.2.0", + &directory.path().join("eggpass"), + ); + assert!(matches!(result, Err(UpdateError::CargoSource { .. }))); +} + +#[cfg(unix)] +fn write_fake_cargo(path: &Path, candidate_version: &str) { + use std::os::unix::fs::PermissionsExt; + + let script = format!( + r#"#!/bin/sh +set -eu +root= +version= +while [ "$#" -gt 0 ]; do + case "$1" in + --root) shift; root="$1" ;; + --version) shift; version="$(printf '%s' "$1" | cut -c2-)" ;; + esac + shift +done +test "$version" = "0.2.0" +mkdir -p "$root/bin" +cat > "$root/.crates.toml" < "$root/bin/eggpass" < println!("eggpass {}", env!("CARGO_PKG_VERSION")), + Some("--hold") => { + println!("ready"); + io::stdout().flush().unwrap(); + thread::sleep(Duration::from_secs(30)); + } + _ => std::process::exit(2), + } +} +"#, + ) + .unwrap(); + + let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()); + let first = Command::new(&cargo) + .args(["install", "--path"]) + .arg(&project) + .args(["--root"]) + .arg(&root) + .args(["--locked"]) + .output() + .expect("start local Cargo fixture install"); + assert!( + first.status.success(), + "initial Cargo fixture install failed: {}", + String::from_utf8_lossy(&first.stderr) + ); + + let executable = root.join("bin").join(if cfg!(windows) { + "eggpass.exe" + } else { + "eggpass" + }); + let mut running = Command::new(&executable) + .arg("--hold") + .stdout(Stdio::piped()) + .spawn() + .expect("start the installed fixture binary"); + let mut ready = String::new(); + BufReader::new(running.stdout.take().unwrap()) + .read_line(&mut ready) + .expect("read fixture readiness"); + assert_eq!(ready.trim(), "ready"); + + std::fs::write( + project.join("Cargo.toml"), + "[package] +name = \"eggpass\" +version = \"0.1.1\" +edition = \"2024\" +", + ) + .unwrap(); + std::fs::write( + project.join("Cargo.lock"), + "version = 4 + +[[package]] +name = \"eggpass\" +version = \"0.1.1\" +", + ) + .unwrap(); + let replacement = Command::new(&cargo) + .args(["install", "--path"]) + .arg(&project) + .args(["--root"]) + .arg(&root) + .args(["--locked", "--force"]) + .output() + .expect("start Cargo replacement while the old image is running"); + let _ = running.kill(); + let _ = running.wait(); + assert!( + replacement.status.success(), + "Cargo could not replace the running fixture binary: {}", + String::from_utf8_lossy(&replacement.stderr) + ); + + let installed = Command::new(&executable) + .arg("--version") + .output() + .expect("run the replaced Cargo fixture binary"); + assert!(installed.status.success()); + assert_eq!(installed.stdout, b"eggpass 0.1.1\n"); + match read_cargo_record(&root) { + CargoRecord::Recorded { version, source } => { + assert_eq!(version, "0.1.1"); + assert_eq!(cargo_source_kind(&source), CargoSourceKind::Path); + } + other => panic!("expected Cargo metadata after replacement, got {other:?}"), + } +} + +#[cfg(windows)] +#[test] +fn windows_uses_an_exact_cargo_handoff_instead_of_replacing_a_running_image() { + let root = Path::new(r"C:\Users\test\.cargo"); + let error = execute_cargo_update_with( + std::ffi::OsStr::new("not-used"), + root, + "0.2.0", + Path::new(r"C:\Users\test\.cargo\bin\eggpass.exe"), + ) + .unwrap_err(); + match error { + UpdateError::CargoHandoff { command } => { + assert!(command.contains("--version =0.2.0")); + assert!(command.contains("--root")); + assert!(command.contains("--registry crates-io")); + } + other => panic!("expected a Cargo handoff, got {other:?}"), + } +} From 6724e9e832ee49552ce024c691a6fba5648e511d Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 23 Nov 2026 19:29:43 +0000 Subject: [PATCH 02/13] fix: use backup path for Windows replacement --- packaging/install.ps1 | 22 +++++++++++++++++++++- packaging/tests/test-install.ps1 | 2 ++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packaging/install.ps1 b/packaging/install.ps1 index d082092..670f496 100644 --- a/packaging/install.ps1 +++ b/packaging/install.ps1 @@ -200,12 +200,32 @@ function Install-VerifiedCandidate { $current = Get-DestinationClassification -DestPath $DestPath if ($current -ne $Scope) { throw "Destination changed during install (expected $Scope, found $current); refusing to overwrite it." } $stagedCopy = Join-Path $DestDir (".eggpass-install-" + [Guid]::NewGuid().ToString('N') + ".tmp") + $backupPath = $null + $replacementSucceeded = $false try { [IO.File]::Copy($Candidate, $stagedCopy, $false) - if ($Scope -eq "replace") { [IO.File]::Replace($stagedCopy, $DestPath, $null) } + if ($Scope -eq "replace") { + $backupPath = Join-Path $DestDir (".eggpass-backup-" + [Guid]::NewGuid().ToString('N') + ".tmp") + [IO.File]::Replace($stagedCopy, $DestPath, $backupPath) + $replacementSucceeded = $true + } else { [IO.File]::Move($stagedCopy, $DestPath) } + } catch { + $installError = $_ + if ($backupPath -and [IO.File]::Exists($backupPath) -and -not [IO.File]::Exists($DestPath)) { + try { + [IO.File]::Move($backupPath, $DestPath) + $backupPath = $null + } catch { + throw "Installation failed and the prior Eggpass executable could not be restored; its backup remains at $backupPath. Install error: $($installError.Exception.Message). Restore error: $($_.Exception.Message)" + } + } elseif ($backupPath -and [IO.File]::Exists($backupPath)) { + Write-Warning "Replacement failed; retained the prior executable backup at $backupPath for recovery." + } + throw $installError } finally { if (Test-Path -LiteralPath $stagedCopy) { Remove-Item -LiteralPath $stagedCopy -Force -ErrorAction SilentlyContinue } + if ($replacementSucceeded -and $backupPath -and [IO.File]::Exists($backupPath)) { Remove-Item -LiteralPath $backupPath -Force -ErrorAction SilentlyContinue } } if ($Scope -eq "replace") { Write-Host "Updated Eggpass at $DestPath ($ExistingVersion -> eggpass $(Get-CandidateVersion -Candidate $DestPath))" } else { Write-Host "Installed Eggpass to $DestPath" } diff --git a/packaging/tests/test-install.ps1 b/packaging/tests/test-install.ps1 index 9f89b2c..e6d6321 100644 --- a/packaging/tests/test-install.ps1 +++ b/packaging/tests/test-install.ps1 @@ -174,6 +174,8 @@ try { $script:CandidateVersions[$rerunPath] = "1.2.4" Assert-Fixture ((Get-DestinationClassification -DestPath $rerunPath) -eq "replace" -and (Get-ExistingVersion -DestPath $rerunPath) -eq "eggpass 1.2.4") "same-scope rerun replaces the verified Eggpass executable" Assert-Fixture ($script:FixtureUrls.Count -eq 4) "same-scope rerun fetches both exact latest assets again" + $replacementTemps = @(Get-ChildItem -LiteralPath $script:DestRoot -Filter ".eggpass-*.tmp" -ErrorAction SilentlyContinue) + Assert-Fixture ($replacementTemps.Count -eq 0) "same-scope replacement cleans staged and backup files" Reset-Fixture "foreign" $foreign = Join-Path $script:DestRoot "eggpass.exe" From 96aec845335d54a2aea3651f04a12f67ee48b8af Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Tue, 24 Nov 2026 13:42:31 +0000 Subject: [PATCH 03/13] chore: add eggpass-installer-update-implementation.md --- ...eggpass-installer-update-implementation.md | 168 ++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 plans/eggpass-installer-update-implementation.md diff --git a/plans/eggpass-installer-update-implementation.md b/plans/eggpass-installer-update-implementation.md new file mode 100644 index 0000000..af6607d --- /dev/null +++ b/plans/eggpass-installer-update-implementation.md @@ -0,0 +1,168 @@ +# Eggpass Installer and Installation-Aware Updates — Implementation Plan + +**Status:** Implementation authorized by a follow-up request. This document remains the design record; its plan does not authorize a public release, tag mutation, or package publication. +**Direction:** Port/adapt Gregg’s mature installer closely. Do not create a new installer design from scratch. +**Primary source snapshot:** `eggstack/gregg` commit `fabcaf21bc60f719a5de5b9420490ffed52400e4` (current `main` when researched on 2026-11-23). + +## Goal + +Provide a supported, prebuilt-binary installation path for Eggpass on the five existing release targets, then make `eggpass update` preserve the installation channel: Cargo-managed installs are updated by Cargo; installer/direct installs use Eggpass’s existing verified self-update transaction. + +Preserve the current Eggpack release contract and `eggup` ownership, integrity, locking, rollback, and candidate-validation machinery. Reuse Gregg’s installer implementation and tests for the generic bootstrap mechanics rather than duplicating those mechanics in a fresh script. + +## Pre-implementation Eggpass baseline + +- At the start of this implementation, the README documented `cargo install eggpass` and Eggpass had no `install.sh` or `install.ps1`. +- The starting Eggpack contract released five native binaries, each with a SHA-256 sidecar, plus `release-manifest.json`; the manifest carries the exact asset size and digest used by Eggpass’s updater. +- `.github/workflows/release.yml` is generated from `release/eggpack/` inputs and CI runs `eggpack ci check`; the implementation must keep using that generator and drift gate. +- At baseline, `src/update.rs` positively detected Cargo ownership and refused mutating self-updates for any provenance other than `SelfManaged`. The existing `eggup` transaction remains the direct-binary update path. +- At baseline, Cargo provenance retained only the detected root and version. The `.crates.toml` key includes ` ()`; the implementation now retains that source and delegates only the recognized default crates.io source. Path, Git, alternate-registry, malformed, and unknown-source installs remain fail-closed with source-appropriate guidance. +- At plan time, the public version identities are independent: Eggpass CLI `v0.1.3` / crate `0.1.3`, Rust `eggpass-auth` `eggpass-auth-v0.1.1` / crate `0.1.1`, and Python `eggpass-auth-python-v0.1.2` / package `0.1.2`. This work changes only CLI install/update behavior; do not bump, retag, or publish any of these packages as part of implementation. +- `docs/releasing.md` defines `vX.Y.Z` as the CLI tag and states that publishing the reviewed GitHub draft triggers crates.io publication. Therefore the public GitHub stable release is the binary installer’s version authority; crates.io publication may lag and is only used for an exact-version Cargo fallback/update after that version is available. + +## Resolved Eggpack staging seam + +The Eggpack revision already pinned in `release/eggpack/github-policy.json` (`242654ab29e59ebbd3beca0a0ff276f4df4df873`) supports the required product-wrapper path. Its `InstallerPresentationV1` `product_wrappers` mode copies two explicitly named repository files as the public `install.sh` and `install.ps1`, while staging Eggpack-generated exact-version bootstrap installers under separate configured names. The checked-in `GitHubStagingInputsV1` has an optional `installer_presentation` path; the renderer passes `--installer-presentation` and the checked-out repository root to `_prepare-stage`. This is the supported extension point: no Eggpack generator/schema change or Eggpack pin bump is presently required. + +Use a new `release/eggpack/installer-presentation.json` with this shape, then point `staging.inputs.installer_presentation` in `release/eggpack/github-policy.json` at it: + +```json +{ + "schema_version": 1, + "mode": { + "product_wrappers": { + "posix_source": "packaging/install.sh", + "powershell_source": "packaging/install.ps1", + "generated_posix_name": "install-exact.sh", + "generated_powershell_name": "install-exact.ps1" + } + } +} +``` + +Eggpack treats wrapper files as bounded, regular, non-symlink source files copied as bytes; it does not execute them. The four installer assets are auxiliary staging assets, not target binaries or members of `release-manifest.json`. Keep `release/eggpack/install-policy.toml` as the schema-v1 bootstrap policy for the existing direct targets; do not repurpose it for installer presentation. + +## Design constraints + +### 1. Port Gregg’s installer as a cohesive unit + +Use the Gregg installer family at the pinned revision as the implementation source: the release entrypoints and their helper scripts under `packaging/`, the installer rerun tests, and the release-time validation in `.github/workflows/release-binaries.yml`. First inventory the exact entrypoints, helper boundaries, test seams, and license headers at that revision; keep the source revision recorded in the implementation PR. + +Preserve the proven structure and behavior, including argument parsing, stable-version validation, host detection, staging/cleanup, checksum verification, candidate identity checks, same-scope rerun handling, foreign-file/symlink refusal, privilege boundaries, PATH guidance, and platform-specific replacement behavior. Make only the Eggpass-specific adaptations below. Retain applicable copyright/license notices when copying or adapting source. + +Primary references: [Gregg installer source](https://github.com/eggstack/gregg/tree/fabcaf21bc60f719a5de5b9420490ffed52400e4/packaging), [installer rerun test](https://github.com/eggstack/gregg/blob/fabcaf21bc60f719a5de5b9420490ffed52400e4/scripts/tests/test-install-rerun.sh), and [release workflow](https://github.com/eggstack/gregg/blob/fabcaf21bc60f719a5de5b9420490ffed52400e4/.github/workflows/release-binaries.yml). Snip-it is a secondary reference only: its docs promise method-following updates, but its current updater special-cases Homebrew and otherwise follows a binary-replacement path. Do not copy that mismatch. + +### 2. Eggpass-specific installer contract + +- Publish a Bash installer and a PowerShell installer alongside the tagged Eggpass release. Support both latest and a pinned stable `X.Y.Z` version, with direct links through the GitHub release assets (latest and exact-tag forms). Do not make the installer command fetch a mutable script from the repository’s `main` branch. +- Reuse Gregg’s latest/exact release acquisition pattern, but use Eggpass’s GitHub releases as the selector: no version means the public latest stable release (`releases/latest`); `--version X.Y.Z` means the exact `vX.Y.Z` release. Never resolve the CLI version from a floating crates.io response. A pinned install must go directly to that release tag. The Eggpass release flow publishes crates.io only after the GitHub release is made public, so a Cargo fallback/update may encounter a short registry lag; request the exact selected version and return a clear retry-later error if it is not yet available—never install an older floating version. +- Use the existing stable target set and asset names from `release/eggpack/distribution.toml`: Linux x86_64/aarch64, macOS x86_64/arm64, and Windows x86_64. Keep the script’s mapping covered by a drift test against that contract; do not silently add an unqualified target. +- Reuse Gregg’s sidecar-verification implementation for the bootstrap scripts, and keep Eggpack’s release validation proving that every sidecar matches the corresponding `release-manifest.json` asset. Avoid introducing `jq`, Python, or a custom shell JSON parser solely for installation. Do not change the manifest schema or duplicate its integrity logic in Rust. +- Verify the downloaded candidate’s exact stable version using Eggpass’s existing `eggpass --version` output contract (not Gregg’s `version` subcommand). Verify before installing or executing it. +- Fail closed on checksum, transport, malformed metadata, or candidate-identity errors. Hosts outside the five published targets are unsupported and must fail with guidance; do not use Cargo fallback there because Eggup has no release-target mapping for subsequent updates. For one of the five supported targets, an exact-version Cargo fallback may be attempted only after a definite missing binary asset (HTTP 404), never after failed verification or transient server/network errors. +- If Cargo fallback is used, request the exact selected CLI version from the standard crates.io registry under an owner-private temporary Cargo root, validate the candidate, then copy it to the installer’s chosen final directory and remove the temporary root. The installed binary must not remain Cargo-managed merely because Cargo built it. If that exact crate is not yet published, fail with retry guidance; do not fall back to an unpinned `cargo install eggpass` or choose a different version. +- Default to a per-user install. Require explicit elevation for a system install; never invoke `sudo` silently. Reuse Gregg’s tested PATH/profile behavior and no-op/refusal checks rather than creating new profile-editing logic. Eggpass has no service-registration post-install step, so omit Gregg’s daemon lifecycle actions. +- Keep same-scope reruns idempotent; refuse to overwrite a symlink or unrelated executable. Preserve separate user/system destinations so rerunning at one scope does not replace another scope’s install. + +### 3. Method-aware `eggpass update` + +Treat the bootstrap installer’s final binary as a direct/self-managed installation, regardless of whether its candidate was downloaded or built by the temporary Cargo fallback. It should update through the current `eggup` manifest-driven transaction, which already verifies artifact size/digest, candidate identity, and live-file ownership under the update lock. + +For a Cargo-managed executable, do not bypass the existing provenance refusal and replace the file directly. Add a Cargo update branch that preserves Cargo’s own package record: + +- For a positively identified default-crates.io installation, invoke Cargo with the detected root and the exact target version from the already-resolved Eggpass release (equivalent to `cargo install eggpass --version --locked --force --root `). Re-read Cargo’s record and the installed candidate after completion; report success only if Cargo metadata and executable version agree with the requested version. +- Preserve the installation source. The initial implementation does not auto-update `--path`, `--git`, alternate-registry, or unrecognized sources because the current provenance does not retain enough invocation/revision evidence. Keep those cases fail-closed with useful manual guidance; never silently convert them into crates.io installs. If crates.io has not published `` yet, fail with retry guidance rather than installing another version. +- Validate Cargo’s running-process replacement behavior on every supported OS. In particular, prove Windows behavior while the updater executable is running. If safe automatic replacement cannot be demonstrated, use a bounded helper that waits for the parent to exit or retain an explicit Cargo command handoff; do not weaken the no-in-place-Cargo-mutation invariant. +- For `SelfManaged`, use the existing Eggup transaction. For `Unprovable`, preserve fail-closed behavior and actionable guidance. Never fall back from a rejected Cargo update to direct replacement. +- Keep `--check` non-mutating and preserve current daemon restart behavior. Deciding whether an already-current check should return a nonzero exit code is a separate issue and is out of scope for this plan unless implementation proves it blocks the installer/update contract. + +## Implementation stages + +### Stage 0 — Freeze the Gregg source and resolve integration boundaries + +- Check out/read Gregg at the pinned commit; inspect its Bash/PowerShell entrypoints, platform helpers, tests, release uploads, and CI gates. Run Gregg’s installer tests at that baseline before adapting them, where a suitable checkout is available. +- Record which files and behaviors will be ported with only identity/contract changes. Keep the Gregg-specific implementation intact wherever Eggpass has no reason to differ. +- Preserve the resolved authority: latest is GitHub’s public latest stable release; pinned is the exact `vX.Y.Z` release. Add a deterministic fixture for crates.io publication lag: a valid binary release still installs from GitHub, while a required Cargo fallback for the exact not-yet-published crate fails safely with retry guidance. +- Use the already-supported Eggpack `InstallerPresentationV1` seam described above: add `release/eggpack/installer-presentation.json`, add its path as `staging.inputs.installer_presentation` in `release/eggpack/github-policy.json`, then regenerate `.github/workflows/release.yml` with the currently pinned Eggpack. Do not change the distribution contract, repurpose `install-policy.toml`, patch the generated workflow by hand, or bump Eggpack unless implementation first proves the pinned feature is absent or defective. +- Extend `.crates.toml` parsing to preserve the Cargo source string. Automatically delegate only when root, package, version, and the recognized default crates.io source are all proven. Path, git, alternate registry, and unrecognized sources remain manual-only; never rewrite them as crates.io installs. Add fixtures for each source classification before enabling the Cargo update branch. + +**Exit:** Source revision, copy/adaptation boundary, release attachment mechanism, latest-version authority, and Cargo-source policy are all explicit. No installer code is started until these are settled. + +### Stage 1 — Port and qualify the bootstrap installers + +- Create `packaging/install.sh` and `packaging/install.ps1` by closely porting Gregg’s entrypoints/helpers at the pinned commit, retaining its tested helper boundaries, safety checks, and applicable license notices. Port/adapt the relevant rerun tests into a deterministic `packaging/tests/` harness. Limit adaptations to Eggpass identity/version output, the five existing asset names/targets, destination naming, and Eggpass-specific messaging. +- Add deterministic fixtures for latest/pinned version selection, all five target mappings, valid/malformed checksum sidecars, identity mismatch, transport failure, exact 404 fallback on a supported target, unsupported-target refusal, cleanup, same-scope rerun, foreign files, symlinks, PATH handling, and privilege behavior. +- Test the Bash script under the minimum supported Bash (including macOS system Bash 3.2); run `bash -n` and ShellCheck. Parse/lint the PowerShell script and run its platform-appropriate fixture tests. No fixture may contact a live release host or require credentials. + +**Exit:** The port passes adapted Gregg installer tests and Eggpass-specific fixtures on supported test hosts; checksum/identity/transport failures never install or trigger Cargo fallback. + +### Stage 2 — Publish installer files through Eggpack + +- Add `release/eggpack/installer-presentation.json` using the resolved `product_wrappers` shape above and add `staging.inputs.installer_presentation` to `release/eggpack/github-policy.json`. Leave the five-target `distribution.toml`, binary manifest schema, and direct-target `install-policy.toml` unchanged. +- Keep `packaging/install.sh` and `packaging/install.ps1` as the public wrapper names. Stage Eggpack’s exact-version generated bootstraps as `install-exact.sh` and `install-exact.ps1`; test that names are non-colliding and wrapper bytes are copied without execution. +- Regenerate the workflow, never edit it directly. Use the same pinned tool and input shape as CI: + + ```sh + eggpack ci generate \ + --workflow-shape release/eggpack/workflow-shape.json \ + --contract release/eggpack/distribution.toml \ + --github-policy release/eggpack/github-policy.json \ + --output .github/workflows/release.yml + eggpack ci check \ + --workflow-shape release/eggpack/workflow-shape.json \ + --contract release/eggpack/distribution.toml \ + --github-policy release/eggpack/github-policy.json \ + --workflow .github/workflows/release.yml + ``` + +- Extend draft validation to require all four installer assets plus the five binaries, five sidecars, and manifest; verify latest/exact script URLs, and prove wrappers/generated installers are not binary members in `release-manifest.json`. Preserve Eggpack’s draft-first staging and the separate human publish action. No public asset is published by implementation work. + +**Exit:** The pinned Eggpack generator stages the product wrappers and exact bootstraps, `eggpack ci check` passes, the manifest remains the existing five-target contract, and the ordinary build/qualification graph is unchanged. + +### Stage 3 — Add method dispatch to the updater + +- Refactor only the updater policy boundary needed to dispatch `CargoManaged`, `SelfManaged`, and `Unprovable`. Continue using Eggup for manifest fetch/projection, bounded download, digest/size verification, candidate validation, lock ownership, atomic commit, and rollback. +- Preserve Cargo root and source evidence in provenance as needed. Invoke Cargo only for supported Cargo-managed sources; keep its metadata and installed version in sync. Provide explicit, tested guidance for cases that cannot be automated safely. +- Exercise updater behavior using fake Cargo executables and local fixture transports. Test successful/failed Cargo delegation, detected non-default roots, unsupported sources, not-installed Cargo, and Windows running-executable handling. Test direct updates through the same manifest and artifact identity contract as today. + +**Exit:** Cargo installs are never directly self-replaced; direct/bootstrap installs update through Eggup; all unsupported or uncertain ownership/source cases fail safely with useful next steps. + +### Stage 4 — User docs and end-to-end qualification + +- Update the root README install section and `docs/updating.md` with the supported shell/PowerShell commands, pinned install syntax, prerequisites, install destinations, PATH guidance, integrity limits, and method-specific update behavior. Update `docs/releasing.md` with the installer asset review/checks. Keep Cargo installation documented as a separate supported method. +- Run formatting, strict Clippy, locked workspace tests, Linux installer tests, macOS Bash 3.2 installer tests, Windows PowerShell and updater tests, the five-target release build/qualification checks, crate packaging, and `eggpack ci check`. Run `git diff --check` and review that the diff contains no generated binaries, secrets, or unrelated release changes. +- Verify a draft release locally or through a non-publishing validation path only. Any public release remains a separate operation requiring the existing fresh approval gate. + +**Exit:** All advertised targets have installation and update evidence, Cargo metadata remains accurate after Cargo updates, installer-created binaries update via Eggup, and the generated release workflow remains in sync. + +## Out of scope + +- Writing a new installer framework or replacing Gregg’s tested generic installer logic with a separate implementation. +- Homebrew, apt, winget, or other package-manager support not already part of Eggpass’s distribution contract. +- Changes to Eggpack manifest schema, Eggup transaction internals, release signing/TUF, daemon restart policy, or the current `--check` already-current exit-code policy, unless Stage 0 proves a narrowly scoped prerequisite is unavoidable. +- Running public release workflows, publishing installer assets, changing tags, or installing Eggpass on a user machine as part of the implementation-plan task. + +## Acceptance checklist + +- [ ] Gregg source commit is pinned and its current installer/test structure is ported closely, with license notices retained. +- [ ] Five Eggpass targets map to the existing Eggpack distribution contract without drift. +- [ ] Latest and pinned installers fetch exact release assets, verify checksum and Eggpass version, and fail closed on non-404 errors. +- [ ] On supported targets, Cargo fallback uses an isolated staging root and leaves the final bootstrap install outside Cargo’s managed root; unsupported targets fail rather than promising an un-updatable install. +- [ ] Reinstall-at-same-scope, PATH handling, permissions, symlink and foreign-file protections are covered by adapted Gregg tests. +- [ ] Shell and PowerShell installers are included in the reviewed release draft through Eggpack’s supported generation path; `eggpack ci check` passes. +- [ ] Cargo-managed `eggpass update` delegates to Cargo only for a positively identified default-crates.io source/root and requests the exact resolved CLI version; unsupported sources fail safely and it never self-replaces the Cargo-owned binary. +- [ ] Direct/bootstrap `eggpass update` continues to use Eggup’s manifest-driven verified transaction. +- [ ] CI covers supported OS/architecture behavior; no live credentials or provider/release network access are needed by deterministic tests. +- [ ] Latest selection follows the public GitHub stable release; exact installs/updates use the exact `vX.Y.Z` CLI release, with crate-publication lag handled by a retryable exact-version failure. +- [ ] Eggpack’s pinned product-wrapper staging feature is configured through release inputs; generated workflow is regenerated and checked, and the five-target manifest remains unchanged. +- [ ] CLI, Rust auth, and Python auth version/tag lines remain independent; no existing published tag or package version is overwritten. +- [ ] No public release, tag mutation, or package publication occurs without a separate fresh authorization. + +## References + +- Eggpass install and release contract: `README.md:19-29`, `docs/releasing.md:15-35,85-95`, `release/eggpack/distribution.toml`, and `release/eggpack/pack.toml`. +- Eggpass generated-workflow gate: `.github/workflows/ci.yml:71-91`; generated release workflow: `.github/workflows/release.yml`. +- Eggpass updater policy and provenance: `src/update.rs:116-153,330-355,750-860`; user-facing behavior: `docs/updating.md`. +- Gregg primary source pinned at `fabcaf21bc60f719a5de5b9420490ffed52400e4`: `packaging/install.sh`, `packaging/install.ps1`, platform helper scripts, `scripts/tests/test-install-rerun.sh`, and `.github/workflows/release-binaries.yml`. +- Eggpack staging support pinned at `242654ab29e59ebbd3beca0a0ff276f4df4df873`: [staging adapter](https://github.com/eggstack/eggpack/blob/242654ab29e59ebbd3beca0a0ff276f4df4df873/crates/eggpack-github/README.md), [staging policy](https://github.com/eggstack/eggpack/blob/242654ab29e59ebbd3beca0a0ff276f4df4df873/crates/eggpack-ci/src/policy.rs), [release renderer](https://github.com/eggstack/eggpack/blob/242654ab29e59ebbd3beca0a0ff276f4df4df873/crates/eggpack-ci/src/render_release.rs), and [CLI staging reference](https://github.com/eggstack/eggpack/blob/242654ab29e59ebbd3beca0a0ff276f4df4df873/crates/eggpack-cli/README.md). +- Snip-it is a secondary comparison only: `packaging/README.md`, `packaging/install.sh`, `docs/USER_GUIDE.md`, and `src/update.rs`; its documented install-method promise is not fully reflected in its current updater dispatch. From e630895b0914d60c9b4b8ab72255ac0a71e612d3 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Tue, 24 Nov 2026 16:39:12 +0000 Subject: [PATCH 04/13] feat: expose reasoning effort metadata in model catalogue --- docs/client-setup.md | 37 +- ...thinking-level-discovery-implementation.md | 108 ++++++ src/provider/mod.rs | 243 ++++++++++-- src/server/models.rs | 10 +- src/server/tests.rs | 357 +++++++++++++++--- 5 files changed, 670 insertions(+), 85 deletions(-) create mode 100644 plans/eggpass-thinking-level-discovery-implementation.md diff --git a/docs/client-setup.md b/docs/client-setup.md index b561805..8aab193 100644 --- a/docs/client-setup.md +++ b/docs/client-setup.md @@ -132,10 +132,39 @@ curl http://127.0.0.1:8484/v1/responses \ ## Thinking levels and tool calls -For Chat Completions, set `reasoning_effort` to a level listed for that model -in `/v1/models`. ChatGPT requests are translated to the Responses API. Returned -reasoning may be available in `reasoning_content`, depending on the provider -and model. +Discover per-model thinking levels with the authenticated `GET /v1/models` +request shown above. Eggpass keeps the provider's native metadata and adds a +common, additive projection when effort levels are published: + +- ChatGPT native fields: `supported_reasoning_levels[].effort` and + `default_reasoning_level`. +- Grok native fields: `capabilities.reasoning_effort` and + `capabilities.default_reasoning_effort`. +- Eggpass's common fields: `reasoning.supported_efforts` and, only when the + provider supplies a default, `reasoning.default_effort`. + +Effort labels (including new labels) and their provider order are preserved. +The common object is a sourced projection, not a claim of full OpenRouter +metadata conformance. Eggpass does not infer `default_enabled` or `mandatory`; +those behavioral properties are omitted because the supported provider +catalogue fields do not establish them. The previous +`capabilities.reasoning` alias is retained when no provider field already +occupies that location. + +For Chat Completions, send `reasoning_effort` using a level listed for that +model. For example: + +```json +{"model":"MODEL_ID_FROM_V1_MODELS","messages":[{"role":"user","content":"Think carefully about this."}],"reasoning_effort":"high"} +``` + +ChatGPT requests are translated to the Responses API's `reasoning.effort`; +Grok receives the Chat Completions effort value unchanged. Eggpass does not +validate levels locally, so the upstream remains authoritative when a value is +unsupported. Generic OpenAI-compatible clients may ignore custom model +metadata or may not show a thinking-level selector; client UI support varies. +Returned reasoning may be available in `reasoning_content`, depending on the +provider and model. Tool calls use the Chat Completions format. The client should send the assistant's tool call back with the tool result and its `tool_call_id`, as diff --git a/plans/eggpass-thinking-level-discovery-implementation.md b/plans/eggpass-thinking-level-discovery-implementation.md new file mode 100644 index 0000000..7542d51 --- /dev/null +++ b/plans/eggpass-thinking-level-discovery-implementation.md @@ -0,0 +1,108 @@ +# Eggpass Thinking-Level Discovery — Implementation Plan + +**Status:** Implemented locally and validated. Changes are limited to code and documentation; no release, tag mutation, or package publication occurred. +**Research checked:** 2026-11-24 against the current workspace and published API documentation. +**Scope:** Make model reasoning/thinking-level metadata discoverable from Eggpass’s authenticated model catalogue, align the intended OpenRouter-compatible alias with its documented shape, and verify it end to end for Grok and ChatGPT. + +## Goal + +A client that reads Eggpass’s model catalogue should be able to determine, per model, whether reasoning effort is available, the accepted effort values, and a default effort when the provider publishes one. The response must preserve provider-native metadata, avoid inventing unsupported capabilities, and remain consumable by existing Eggpass clients. + +## Findings and current behavior + +- The configured base URL is `http://127.0.0.1:8484/v1`; the route for model discovery is `GET /v1/models`, not `GET /v1`. The route is authenticated with an Eggpass client key. Upstream OAuth sign-in for Grok/ChatGPT does not waive that local client-key check. An unauthenticated request returned `401`; a subsequent authenticated, read-only request returned HTTP 200 with 23 models, 15 of which included `reasoning.supported_efforts`. The key was supplied by the user and was neither printed nor written to disk. +- `GET /v1/models` fetches signed-in provider catalogues and normalizes them in `src/server/models.rs`. ChatGPT’s model-list allowlist in `src/provider/openai.rs` retains `supported_reasoning_levels`, `default_reasoning_level`, and related capability fields. Grok’s data-array catalogue retains its model fields, including its `capabilities` block. The normalization code derives common aliases in `src/provider/mod.rs`. +- The current alias labels itself OpenRouter-style but emits top-level `reasoning: true` and puts a list at `capabilities.reasoning.effort`. OpenRouter’s documented model metadata uses a top-level `reasoning` object, with `supported_efforts` and, when known, `default_effort`. A client following that contract will not find the current levels, and the boolean at `reasoning` conflicts with the expected object type. +- OpenAI’s documented Models API does not define a standard field for model reasoning levels. Preserving extensions is useful, but generic OpenAI-compatible clients are not required to read them or display an effort selector. Documentation must distinguish Eggpass’s advertised metadata from client-specific UI support. +- Request handling is already present: Chat Completions `reasoning_effort` is translated to Responses `reasoning.effort` for ChatGPT, while Grok’s Chat Completions request is passed through. This plan preserves that routing behavior and adds no new request syntax. + +## Design decisions and constraints + +1. Keep `/v1/models` as the discovery endpoint and keep its existing client-key requirement. Do not add a directory/index route at `/v1`; document the correct endpoint and authentication instead. +2. Preserve the upstream-native fields as received. For ChatGPT, keep the supported-level objects and native default fields; for Grok, keep its native `capabilities.reasoning_effort` and `default_reasoning_effort` values. Keep the ChatGPT allowlist bounded; do not expose internal instructions or arbitrary upstream payloads. +3. Replace the erroneous boolean alias with a top-level reasoning object. Its minimum useful contract is `reasoning.supported_efforts: string[]`, using the exact ordered values from the provider, plus `reasoning.default_effort` when an upstream default is known. Map the default from ChatGPT’s `default_reasoning_level` or Grok’s `capabilities.default_reasoning_effort`. +4. Do not infer `default_enabled`, `mandatory`, or any other behavioral flags from the mere presence of effort levels. First establish provider-supported semantics; emit those fields only when supported by source metadata or authoritative behavior. Do not claim full OpenRouter schema conformance if required semantics cannot be represented without guessing. +5. Preserve unknown/new effort labels rather than hardcoding today’s enum. Omit reasoning aliases when the provider reports no levels. Do not silently coerce, sort, or drop values; keep the upstream order unless a documented contract requires otherwise. +6. Avoid losing native metadata on key collisions. Define and test deterministic precedence for the canonical top-level `reasoning` object and any pre-existing provider `reasoning` field. Do not overwrite unrelated fields under `capabilities`. +7. Do not imply that every OpenAI-compatible client will render a control. The compatibility promise is that Eggpass exposes discoverable metadata and accepts the corresponding already-supported request shape; clients must understand the extension to show it. +8. No network inference calls, account changes, token/key creation, credential reads, publishing, release, or tag operations are required. Live verification, if available, is a read-only authenticated catalogue GET; never print the client key or dump credential files. + +## Implementation stages + +### Stage 0 — Confirm the metadata contract + +- Recheck the published OpenRouter model metadata contract and both providers’ current catalogue fixtures. Determine whether the provider responses expose `default_enabled`/`mandatory` semantics; if not, leave them out and document the deliberate partial projection. +- Confirm the source-to-alias mapping: ChatGPT `supported_reasoning_levels[*].effort` and `default_reasoning_level`; Grok `capabilities.reasoning_effort[*]` and `capabilities.default_reasoning_effort`. +- Record the exact response contract in tests and client setup docs before changing normalization. + +**Exit:** Every exposed value has an authoritative provider source, and no unsupported default/mandatory behavior is guessed. + +### Stage 1 — Correct provider normalization + +- Update `effort_levels` and `add_aliases` in `src/provider/mod.rs` to build the top-level reasoning object from either provider format. +- Preserve the provider-native source fields and default values. Keep deriving display/context aliases only from observed facts, as today. +- Replace the current boolean-shape test with assertions for the typed object and exact levels/default. Cover both ChatGPT and Grok, including empty/missing levels, unknown future labels, ordering, malformed entries, and collisions with pre-existing reasoning metadata. +- Keep the allowlist in `src/provider/openai.rs` narrow and add a test that internal prompt/instruction fields remain excluded. + +**Exit:** Unit tests prove both provider formats produce the intended catalogue metadata without fabricating or dropping provider facts. + +### Stage 2 — Exercise the public catalogue route + +- Extend the server test harness with stub upstream catalogues for both provider shapes. Call authenticated `GET /v1/models` and assert the merged output contains each model’s native fields and corrected reasoning object. +- Exercise `GET /v1/models/{id}` as well, to ensure the single-model endpoint returns identical metadata. +- Assert that no-key requests remain unauthorized, disabled/unsigned providers contribute no entries, duplicate model IDs retain deterministic behavior, and catalogue failures do not create false reasoning claims. +- Keep these tests offline and deterministic; do not use the live test server as a unit-test dependency. + +**Exit:** The public response path—not only the normalizer—preserves level metadata for both providers and retains existing authentication/merge behavior. + +### Stage 3 — Protect request compatibility and document client behavior + +- Retain tests proving that an advertised ChatGPT level is mapped from Chat Completions `reasoning_effort` to Responses `reasoning.effort`, and that the value is not lost. Add a stub-forwarding test for Grok to ensure its advertised effort value reaches the upstream unchanged. +- Do not introduce server-side level validation in this change unless it can use the same live/provider metadata safely and handle catalogue refresh/failure consistently. Upstream rejection remains the error for unsupported values otherwise. +- Update `docs/client-setup.md`: show the authenticated `GET /v1/models` path, identify the provider-native fields and the canonical `reasoning.supported_efforts`/`default_effort` metadata, and show `reasoning_effort` as the Chat Completions request parameter. Clarify that client UIs vary and may ignore custom model metadata. +- Keep the documented base URL as `http://127.0.0.1:8484/v1`; no `/v1` root catalogue is added. + +**Exit:** Existing request translation stays covered, Grok values are forwarded unmodified in a stub test, and docs explain discovery and client limitations. + +### Stage 4 — Verify and review + +- Run focused catalogue/translation/server tests, then `cargo fmt --all -- --check`, `cargo clippy --all-targets --locked -- -D warnings`, and `cargo test --all-targets --locked`. +- A read-only authenticated `GET http://127.0.0.1:8484/v1/models` was completed against the local Eggpass daemon. It returned HTTP 200 with 23 models, 15 carrying `reasoning.supported_efforts`; the key was not printed or stored. The unauthenticated `401` was not treated as catalogue evidence. +- Keep the offline stub integration tests as the deterministic acceptance check; do not create or expose credentials for future runs. +- Review the final diff for scope, response compatibility, absence of guessed capability claims, and absence of secrets. No release/tag/publish operation is part of this plan. + +**Exit:** Focused and full local checks pass, the final public response shape is covered offline, and any live-check limitation is explicit. + +## Acceptance criteria + +- `GET /v1/models` remains the documented discovery endpoint and still requires an Eggpass client key. +- For each model with advertised levels, the response contains the original provider metadata and a top-level `reasoning` object whose `supported_efforts` exactly matches the upstream values and whose `default_effort` is present only when the provider supplies a default. +- Models without published effort levels do not receive fabricated reasoning support or level metadata. +- `GET /v1/models/{id}` returns the same capability fields as the list route. +- ChatGPT effort translation and Grok pass-through remain covered by offline tests. +- Catalog and request tests require no live account, credentials, or token spend; no secret is printed. +- Client setup docs explain the metadata contract and warn that generic OpenAI-compatible clients may ignore it. +- Formatting, strict Clippy, and all-target tests pass; no release or publishing work is performed. + +## Implementation outcome + +- Catalogue normalization now emits top-level `reasoning.supported_efforts` in provider order and adds `reasoning.default_effort` only from a published provider default. Provider-native fields remain available; conflicting native top-level reasoning is retained under `reasoning.provider`, and an existing `capabilities.reasoning` field is not overwritten. +- Catalogue merging now uses the stable `ProviderId::all()` order, so duplicate IDs consistently prefer x.ai before ChatGPT, independent of hash-map iteration. +- The offline tests cover both provider shapes through list/detail routes, authentication, unsigned-provider exclusion, duplicate precedence, catalogue failures, malformed/future labels, preserved metadata, ChatGPT translation, and unchanged Grok forwarding. +- Formatting, strict Clippy, and the final all-target test run passed. One earlier parallel run had transient failures in existing Codex subprocess tests; that module passed in isolation and the subsequent all-target run passed (404 tests). +- An authenticated live catalogue request returned HTTP 200 with 23 models, 15 carrying `reasoning.supported_efforts`. The user-provided key was not printed or written to disk; no credential files were read and no key was created. + +## Relevant files + +- `src/provider/mod.rs` — normalization and common reasoning aliases. +- `src/provider/openai.rs` — ChatGPT capability field allowlist. +- `src/server/models.rs` — merged list and single-model routes. +- `src/server/tests.rs` — public route integration tests. +- `src/server/translate.rs` — Chat Completions-to-Responses effort translation. +- `docs/client-setup.md` — authenticated discovery instructions and client caveats. + +## References + +- OpenAI Models list reference: https://platform.openai.com/docs/api-reference/models/list +- OpenRouter models catalog: https://www.openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties +- OpenRouter reasoning metadata guidance: https://openrouter.ai/docs/guides/best-practices/reasoning-tokens diff --git a/src/provider/mod.rs b/src/provider/mod.rs index 5ffefb6..41f3b1a 100644 --- a/src/provider/mod.rs +++ b/src/provider/mod.rs @@ -308,13 +308,10 @@ pub fn normalize_catalogue(kind: CatalogueKind, body: &[u8]) -> Vec { /// Add the alias fields a client may read, beside the upstream's own. /// -/// Clients disagree about how a model describes itself. The OpenAI shape -/// names a model and says little else; the OpenRouter shape — which most of -/// the OpenAI-compatible ecosystem has settled on — says what the model can -/// do, under `capabilities` and `limit`. -/// -/// Aliases are derived from upstream data; absent facts are omitted rather -/// than guessed. A reasoning alias may replace a colliding upstream value. +/// Reasoning metadata is a projection of provider-published effort values, +/// not a claim that every OpenAI-compatible client understands or displays it. +/// The canonical top-level object follows the useful subset of the OpenRouter +/// model metadata shape that Eggpass can source without guessing. fn add_aliases(entry: &mut serde_json::Map) { // The display name, under the OpenRouter spelling. let display_name = entry @@ -329,7 +326,7 @@ fn add_aliases(entry: &mut serde_json::Map) { // The context window, under both names. // - // ChatGPT publishes it as `context_window` and x.ai as `context_length`, + // ChatGPT publishes it as context_window and x.ai as context_length, // so the merged catalogue gives both providers the same two names for it. let context = entry .get("context_window") @@ -342,41 +339,87 @@ fn add_aliases(entry: &mut serde_json::Map) { entry.entry("context_length".to_string()).or_insert(context); } - // The default thinking level, under the name ChatGPT uses. + // Without published effort levels there is no reasoning alias. In + // particular, a default alone does not establish an effort selector. + let levels = effort_levels(entry); + if levels.is_empty() { + return; + } + + // ChatGPT publishes a top-level default; x.ai publishes the equivalent + // value inside capabilities. Neither value is inferred from the levels. let default_effort = entry - .get("capabilities") - .and_then(|capabilities| capabilities.get("default_reasoning_effort")) + .get("default_reasoning_level") .and_then(Value::as_str) + .filter(|effort| !effort.is_empty()) + .or_else(|| { + entry + .get("capabilities") + .and_then(|capabilities| capabilities.get("default_reasoning_effort")) + .and_then(Value::as_str) + .filter(|effort| !effort.is_empty()) + }) .map(str::to_string); - if let Some(default) = default_effort { + if let Some(default) = default_effort.as_ref() { entry .entry("default_reasoning_level".to_string()) - .or_insert_with(|| Value::String(default)); + .or_insert_with(|| Value::String(default.clone())); } - // The thinking levels, under the OpenRouter spelling. - let levels = effort_levels(entry); - if !levels.is_empty() { - entry.insert("reasoning".to_string(), Value::Bool(true)); - - // x.ai publishes a `capabilities` block of its own, so the alias is - // added to it rather than over it. - let capabilities = entry - .entry("capabilities".to_string()) - .or_insert_with(|| Value::Object(serde_json::Map::new())); - if let Some(capabilities) = capabilities.as_object_mut() { - capabilities.insert( - "reasoning".to_string(), - serde_json::json!({ "supported": true, "effort": levels }), - ); + // Replace a scalar/malformed pre-existing field, or preserve a collision + // with the fields owned by this projection, under reasoning.provider. + // Non-conflicting upstream reasoning properties remain at the same path. + let supported_efforts = serde_json::json!(levels.clone()); + let native_reasoning = entry.remove("reasoning"); + let has_collision = match native_reasoning.as_ref() { + Some(Value::Object(native)) => { + let supported_conflict = native + .get("supported_efforts") + .is_some_and(|value| value != &supported_efforts); + let default_conflict = match (native.get("default_effort"), default_effort.as_ref()) { + (Some(value), Some(default)) => value != &Value::String(default.clone()), + (Some(_), None) => true, + (None, _) => false, + }; + supported_conflict || default_conflict + } + Some(_) => true, + None => false, + }; + let mut reasoning = match native_reasoning { + Some(Value::Object(native)) if !has_collision => native, + Some(native) => { + let mut reasoning = serde_json::Map::new(); + reasoning.insert("provider".to_string(), native); + reasoning } + None => serde_json::Map::new(), + }; + reasoning.insert("supported_efforts".to_string(), supported_efforts); + if let Some(default) = default_effort { + reasoning.insert("default_effort".to_string(), Value::String(default)); + } + entry.insert("reasoning".to_string(), Value::Object(reasoning)); + + // Keep Eggpass's previous capability alias for existing clients. Never + // replace a provider's own capabilities.reasoning or other capability + // fields; the canonical discovery fields are the top-level object above. + let capabilities = entry + .entry("capabilities".to_string()) + .or_insert_with(|| Value::Object(serde_json::Map::new())); + if let Some(capabilities) = capabilities.as_object_mut() { + capabilities + .entry("reasoning".to_string()) + .or_insert_with(|| serde_json::json!({ "supported": true, "effort": levels })); } } /// The thinking levels a model offers, under either provider's spelling. /// -/// ChatGPT publishes them as `supported_reasoning_levels`, a list of objects; -/// x.ai publishes them as `capabilities.reasoning_effort`, a list of strings. +/// ChatGPT publishes them as supported_reasoning_levels, a list of objects; +/// x.ai publishes them as capabilities.reasoning_effort, a list of strings. +/// Malformed entries and empty labels are ignored; valid labels, including +/// future values, are returned in the provider's original order. fn effort_levels(entry: &serde_json::Map) -> Vec { let levels: Vec = entry .get("supported_reasoning_levels") @@ -385,6 +428,7 @@ fn effort_levels(entry: &serde_json::Map) -> Vec { levels .iter() .filter_map(|level| level.get("effort").and_then(Value::as_str)) + .filter(|effort| !effort.is_empty()) .map(str::to_string) .collect() }) @@ -401,6 +445,7 @@ fn effort_levels(entry: &serde_json::Map) -> Vec { levels .iter() .filter_map(Value::as_str) + .filter(|effort| !effort.is_empty()) .map(str::to_string) .collect() }) @@ -529,8 +574,15 @@ mod tests { let model = &value["data"][0]; assert_eq!(model["name"], "GPT-6.1 Sol"); - assert_eq!(model["reasoning"], true); + assert_eq!( + model["reasoning"]["supported_efforts"], + serde_json::json!(["low", "high"]) + ); + assert!(model["reasoning"].get("default_effort").is_none()); + assert!(model["reasoning"].get("default_enabled").is_none()); + assert!(model["reasoning"].get("mandatory").is_none()); assert_eq!(model["limit"]["context"], 500000); + // The old Eggpass alias remains available for existing clients. assert_eq!(model["capabilities"]["reasoning"]["supported"], true); assert_eq!(model["capabilities"]["reasoning"]["effort"][0], "low"); assert_eq!(model["capabilities"]["reasoning"]["effort"][1], "high"); @@ -589,13 +641,138 @@ mod tests { assert_eq!(model["capabilities"]["default_reasoning_effort"], "high"); assert_eq!(model["default_reasoning_level"], "high"); - // And the OpenRouter shape is answered as well. - assert_eq!(model["reasoning"], true); + // And the canonical reasoning object is answered as well. + assert_eq!( + model["reasoning"]["supported_efforts"], + serde_json::json!(["low", "medium", "high", "xhigh"]) + ); + assert_eq!(model["reasoning"]["default_effort"], "high"); + assert!(model["reasoning"].get("default_enabled").is_none()); + assert!(model["reasoning"].get("mandatory").is_none()); assert_eq!(model["capabilities"]["reasoning"]["supported"], true); assert_eq!(model["capabilities"]["reasoning"]["effort"][3], "xhigh"); assert_eq!(model["limit"]["context"], 500000); } + #[test] + fn malformed_and_future_efforts_keep_the_provider_order() { + let chatgpt_body = br#"{"models":[{ + "slug":"gpt-future", + "visibility":"list", + "supported_reasoning_levels":[ + null, + {"effort":7}, + {"label":"missing-effort"}, + {"effort":""}, + {"effort":"future-level"}, + {"effort":"low"} + ] + }]}"#; + let normalized = normalize_catalogue(CatalogueKind::SlugArray, chatgpt_body); + let value: Value = serde_json::from_slice(&normalized).unwrap(); + let model = &value["data"][0]; + assert_eq!( + model["reasoning"]["supported_efforts"], + serde_json::json!(["future-level", "low"]) + ); + assert!(model["reasoning"].get("default_effort").is_none()); + // The native field remains byte-for-byte data, including malformed + // entries; only the additive alias filters entries it cannot use. + assert_eq!(model["supported_reasoning_levels"][0], Value::Null); + + let grok_body = br#"{"data":[{ + "id":"grok-future", + "capabilities":{"reasoning_effort":["custom-future",null,4,"","minimal"]} + }]}"#; + let normalized = normalize_catalogue(CatalogueKind::DataArray, grok_body); + let value: Value = serde_json::from_slice(&normalized).unwrap(); + assert_eq!( + value["data"][0]["reasoning"]["supported_efforts"], + serde_json::json!(["custom-future", "minimal"]) + ); + assert!( + value["data"][0]["reasoning"] + .get("default_effort") + .is_none() + ); + } + + #[test] + fn reasoning_collisions_and_native_capabilities_are_preserved() { + let body = br#"{"data":[{ + "id":"grok-collision", + "reasoning":{"supported_efforts":["provider-only"],"default_effort":"provider-default","note":"native"}, + "capabilities":{ + "reasoning_effort":["low","future"], + "default_reasoning_effort":"future", + "reasoning":{"engine":"provider-engine","effort":"provider-effort"}, + "tools":true + } + },{ + "id":"grok-legacy-boolean", + "reasoning":true, + "capabilities":{"reasoning_effort":["future-level"]} + }]}"#; + let normalized = normalize_catalogue(CatalogueKind::DataArray, body); + let value: Value = serde_json::from_slice(&normalized).unwrap(); + let model = &value["data"][0]; + + assert_eq!( + model["reasoning"]["supported_efforts"], + serde_json::json!(["low", "future"]) + ); + assert_eq!(model["reasoning"]["default_effort"], "future"); + assert_eq!( + model["reasoning"]["provider"], + serde_json::json!({ + "supported_efforts":["provider-only"], + "default_effort":"provider-default", + "note":"native" + }) + ); + assert_eq!( + model["capabilities"]["reasoning_effort"], + serde_json::json!(["low", "future"]) + ); + assert_eq!(model["capabilities"]["default_reasoning_effort"], "future"); + assert_eq!( + model["capabilities"]["reasoning"]["engine"], + "provider-engine" + ); + assert_eq!( + model["capabilities"]["reasoning"]["effort"], + "provider-effort" + ); + assert_eq!(model["capabilities"]["tools"], true); + + let legacy = &value["data"][1]; + assert_eq!( + legacy["reasoning"]["supported_efforts"], + serde_json::json!(["future-level"]) + ); + assert_eq!(legacy["reasoning"]["provider"], true); + assert!(legacy["reasoning"].get("default_effort").is_none()); + } + + #[test] + fn defaults_without_published_levels_do_not_create_reasoning_aliases() { + let body = br#"{"data":[ + {"id":"grok-default-only","capabilities":{"default_reasoning_effort":"high"}}, + {"id":"grok-empty","capabilities":{"reasoning_effort":[],"default_reasoning_effort":"low"}}, + {"id":"grok-malformed","capabilities":{"reasoning_effort":[null,5,""]}} + ]}"#; + let normalized = normalize_catalogue(CatalogueKind::DataArray, body); + let value: Value = serde_json::from_slice(&normalized).unwrap(); + for model in value["data"].as_array().unwrap() { + assert!(model.get("reasoning").is_none()); + assert!(model.get("default_reasoning_level").is_none()); + } + assert_eq!( + value["data"][0]["capabilities"]["default_reasoning_effort"], + "high" + ); + } + #[test] fn the_data_catalogue_is_normalised() { let body = br#"{"data":[{"id":"grok-4.7","object":"model"}]}"#; diff --git a/src/server/models.rs b/src/server/models.rs index 6079865..3f869db 100644 --- a/src/server/models.rs +++ b/src/server/models.rs @@ -6,6 +6,7 @@ use serde_json::{Value, json}; +use crate::provider::ProviderId; use crate::upstream::{self, Method, UpstreamError}; use super::{Request, Response, ServerContext, openai_error}; @@ -62,7 +63,14 @@ fn merged_catalogue(context: &ServerContext) -> Result, String> { let mut models: Vec = Vec::new(); let mut any = false; - for handle in context.providers.values() { + // ProviderId::all is the stable public precedence order. If two + // providers advertise the same model id, the first provider in this list + // wins regardless of HashMap iteration order. + for provider in ProviderId::all() { + let Some(handle) = context.providers.get(&provider) else { + continue; + }; + // A provider we are not signed in to contributes nothing. match handle.tokens.current() { Ok(Some(_)) => {} diff --git a/src/server/tests.rs b/src/server/tests.rs index 2107824..865f375 100644 --- a/src/server/tests.rs +++ b/src/server/tests.rs @@ -324,80 +324,97 @@ fn harness_with_spec( access_token: &str, spec: ProviderSpec, ) -> Harness { + harness_with_specs(api_key, vec![(stub, spec, Some(access_token))]) +} + +/// Start a proxy with several provider fixtures. A missing access token leaves +/// that configured provider unsigned, so catalogue tests can prove it is skipped. +fn harness_with_specs( + api_key: &str, + fixtures: Vec<(&Stub, ProviderSpec, Option<&str>)>, +) -> Harness { + assert!( + !fixtures.is_empty(), + "at least one provider fixture is required" + ); let directory = tempfile::tempdir().expect("temp dir"); let paths = Paths::in_directory(directory.path()); paths.ensure_dir().expect("config dir"); - let now = timeutil::now_unix(); - let auth = StoredAuth { - access_token: access_token.to_string(), - refresh_token: Some("stored-refresh".to_string()), - id_token: None, - token_type: "Bearer".to_string(), - scope: None, - client_id: "client".to_string(), - issuer: stub.base_url(), - expires_at: Some(now + 3_600), - obtained_at: now, - user_id: Some("user-1".to_string()), - email: Some("user@example.com".to_string()), - ext_agent_host_id: None, - plan_enabled: false, - }; - crate::auth::store::save(&paths.credential_file(spec.id.as_str()), &auth) - .expect("credentials are written"); + let mut providers = HashMap::new(); + let mut provider_ids = Vec::new(); + let mut usage_sources: HashMap, String)> = HashMap::new(); + for (stub, spec, access_token) in fixtures { + if let Some(access_token) = access_token { + let now = timeutil::now_unix(); + let auth = StoredAuth { + access_token: access_token.to_string(), + refresh_token: Some("stored-refresh".to_string()), + id_token: None, + token_type: "Bearer".to_string(), + scope: None, + client_id: "client".to_string(), + issuer: stub.base_url(), + expires_at: Some(now + 3_600), + obtained_at: now, + user_id: Some("user-1".to_string()), + email: Some("user@example.com".to_string()), + ext_agent_host_id: None, + plan_enabled: false, + }; + crate::auth::store::save(&paths.credential_file(spec.id.as_str()), &auth) + .expect("credentials are written"); + } - let upstream = UpstreamClient::new(&spec); - let client = OAuthClient::for_provider(&spec, "client"); - let tokens = TokenManager::new(paths.credential_file(spec.id.as_str()), client); + let upstream = UpstreamClient::new(&spec); + let client = OAuthClient::for_provider(&spec, "client"); + let tokens = Arc::new(TokenManager::new( + paths.credential_file(spec.id.as_str()), + client, + )); + provider_ids.push(spec.id); + usage_sources.insert(spec.id, (Arc::clone(&tokens), stub.base_url())); + providers.insert( + spec.id, + ProviderHandle { + spec, + upstream, + tokens, + }, + ); + } let keys = Arc::new(crate::keys::KeyStore::open(paths.key_store_file()).expect("key store")); - - let mut providers = HashMap::new(); - providers.insert( - spec.id, - ProviderHandle { - spec: spec.clone(), - upstream, - tokens: Arc::new(tokens), - }, - ); - let server = Server::bind_with_limits("127.0.0.1", 0, crate::config::ServerLimits::default()) .expect("proxy binds"); let port = server.address().port(); - 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], + provider_ids.clone(), move |provider| { usage_calls_for_collector.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let (usage_tokens, usage_base_url) = usage_sources + .get(&provider) + .expect("usage provider is registered"); crate::provider::usage::report::collect_entry( provider, crate::config::Upstream::Api, usage_tokens.as_ref(), usage_timeouts, None, - &usage_base_url, + usage_base_url, ) }, )); + let default_provider = *provider_ids.first().expect("provider fixture"); let context = Arc::new(ServerContext { host: "127.0.0.1".to_string(), port, @@ -405,7 +422,7 @@ fn harness_with_spec( usage_key: "server-test-usage-key".to_string(), keys: Arc::clone(&keys), providers, - default_provider: spec.id, + default_provider, routing: Routing::default(), upstream_in_flight: Arc::new(AtomicUsize::new(0)), max_upstream_requests: crate::server::DEFAULT_MAX_UPSTREAM_REQUESTS, @@ -415,15 +432,13 @@ fn harness_with_spec( let running = Arc::clone(&server); std::thread::spawn(move || running.serve(context)); - - // Give the accept loop a moment to start. std::thread::sleep(Duration::from_millis(50)); Harness { port, keys, inferences, - provider: spec.id, + provider: default_provider, usage_calls, _directory: directory, } @@ -969,6 +984,254 @@ fn the_model_list_comes_from_the_upstream() { assert_eq!(ids, vec!["grok-4.7"]); } +#[test] +fn reasoning_levels_are_visible_on_merged_and_single_model_routes() { + let xai_stub = Stub::start(|request| { + if request.path == "/v1/models" { + Reply::json( + 200, + r#"{"data":[ + {"id":"grok-4.7","object":"model","owned_by":"xai","context_length":500000,"capabilities":{"reasoning_effort":["low","future-level","high"],"default_reasoning_effort":"future-level","tools":true}}, + {"id":"shared-model","object":"model","owned_by":"xai","capabilities":{"reasoning_effort":["xai-level"]}} + ]}"#, + ) + } else { + Reply::json(404, "{}") + } + }); + let chatgpt_stub = Stub::start(|request| { + if request.path == "/v1/models" { + Reply::json( + 200, + r#"{"models":[ + {"slug":"gpt-6.1-sol","display_name":"GPT-6.1 Sol","visibility":"list","supported_reasoning_levels":[{"effort":"minimal"},{"effort":"high"},{"effort":"experimental-future"}],"default_reasoning_level":"minimal","context_window":500000,"base_instructions":"private prompt"}, + {"slug":"shared-model","visibility":"list","supported_reasoning_levels":[{"effort":"openai-level"}],"default_reasoning_level":"openai-level"} + ]}"#, + ) + } else { + Reply::json(404, "{}") + } + }); + + // Deliberately insert providers in reverse precedence order. The merged + // catalogue must still use ProviderId::all's stable ordering. + let harness = harness_with_specs( + "secret-key", + vec![ + ( + &chatgpt_stub, + chatgpt_stub_spec(&chatgpt_stub), + Some("chatgpt-token"), + ), + (&xai_stub, stub_spec(&xai_stub), Some("grok-token")), + ], + ); + let http = agent(); + let response = http + .get(harness.url("/v1/models")) + .header("Authorization", "Bearer secret-key") + .call() + .expect("the proxy answers"); + assert_eq!(response.status().as_u16(), 200); + let body = read_json_body(response); + assert_eq!(body["object"], "list"); + let data = body["data"].as_array().expect("merged data array"); + let ids: Vec<&str> = data + .iter() + .map(|model| model["id"].as_str().expect("model id")) + .collect(); + assert_eq!(ids, vec!["grok-4.7", "shared-model", "gpt-6.1-sol"]); + + let grok = data.iter().find(|model| model["id"] == "grok-4.7").unwrap(); + assert_eq!( + grok["reasoning"]["supported_efforts"], + json!(["low", "future-level", "high"]) + ); + assert_eq!(grok["reasoning"]["default_effort"], "future-level"); + assert_eq!( + grok["capabilities"]["reasoning_effort"], + json!(["low", "future-level", "high"]) + ); + assert_eq!( + grok["capabilities"]["default_reasoning_effort"], + "future-level" + ); + assert_eq!(grok["capabilities"]["tools"], true); + + let chatgpt = data + .iter() + .find(|model| model["id"] == "gpt-6.1-sol") + .unwrap(); + assert_eq!( + chatgpt["reasoning"]["supported_efforts"], + json!(["minimal", "high", "experimental-future"]) + ); + assert_eq!(chatgpt["reasoning"]["default_effort"], "minimal"); + assert_eq!( + chatgpt["supported_reasoning_levels"][0]["effort"], + "minimal" + ); + assert_eq!(chatgpt["default_reasoning_level"], "minimal"); + assert!(chatgpt.get("base_instructions").is_none()); + + // XAI is the stable first provider, so its native record wins a duplicate + // ID even though the fixtures were inserted in the opposite order. + let shared = data + .iter() + .find(|model| model["id"] == "shared-model") + .unwrap(); + assert_eq!(shared["owned_by"], "xai"); + assert_eq!( + shared["reasoning"]["supported_efforts"], + json!(["xai-level"]) + ); + + let single_model = |id: &str| { + let path = format!("/v1/models/{id}"); + let response = http + .get(&harness.url(&path)) + .header("Authorization", "Bearer secret-key") + .call() + .expect("the single-model route answers"); + assert_eq!(response.status().as_u16(), 200); + read_json_body(response) + }; + assert_eq!(single_model("grok-4.7"), *grok); + assert_eq!(single_model("gpt-6.1-sol"), *chatgpt); +} + +#[test] +fn an_unauthenticated_model_catalogue_request_is_rejected_before_upstream_access() { + let stub = Stub::start(|_| Reply::json(200, r#"{"data":[]}"#)); + let harness = harness(&stub, "secret-key", "grok-token"); + + let response = agent() + .get(harness.url("/v1/models")) + .call() + .expect("the proxy answers"); + assert_eq!(response.status().as_u16(), 401); + assert!( + stub.requests().is_empty(), + "unauthenticated catalogue requests must not reach providers" + ); +} + +#[test] +fn an_unsigned_provider_contributes_no_catalogue_entries() { + let xai_stub = Stub::start(|request| { + if request.path == "/v1/models" { + Reply::json(200, r#"{"data":[{"id":"grok-signed","object":"model"}]}"#) + } else { + Reply::json(404, "{}") + } + }); + let chatgpt_stub = Stub::start(|request| { + if request.path == "/v1/models" { + Reply::json( + 200, + r#"{"models":[{"slug":"gpt-unsigned","visibility":"list"}]}"#, + ) + } else { + Reply::json(404, "{}") + } + }); + let harness = harness_with_specs( + "secret-key", + vec![ + (&xai_stub, stub_spec(&xai_stub), Some("grok-token")), + (&chatgpt_stub, chatgpt_stub_spec(&chatgpt_stub), None), + ], + ); + + let response = agent() + .get(harness.url("/v1/models")) + .header("Authorization", "Bearer secret-key") + .call() + .expect("the proxy answers"); + assert_eq!(response.status().as_u16(), 200); + let body = read_json_body(response); + assert_eq!(body["data"].as_array().unwrap().len(), 1); + assert_eq!(body["data"][0]["id"], "grok-signed"); + assert!( + chatgpt_stub.requests().is_empty(), + "unsigned providers must not be queried" + ); +} + +#[test] +fn catalogue_failures_do_not_create_reasoning_claims() { + let xai_stub = Stub::start(|_| { + Reply::json( + 503, + r#"{"data":[{"id":"unavailable-model","capabilities":{"reasoning_effort":["high"]}}]}"#, + ) + }); + let chatgpt_stub = Stub::start(|request| { + if request.path == "/v1/models" { + Reply::json( + 200, + r#"{"models":[{"slug":"gpt-no-levels","display_name":"GPT","visibility":"list"}]}"#, + ) + } else { + Reply::json(404, "{}") + } + }); + let harness = harness_with_specs( + "secret-key", + vec![ + (&xai_stub, stub_spec(&xai_stub), Some("grok-token")), + ( + &chatgpt_stub, + chatgpt_stub_spec(&chatgpt_stub), + Some("chatgpt-token"), + ), + ], + ); + + let response = agent() + .get(harness.url("/v1/models")) + .header("Authorization", "Bearer secret-key") + .call() + .expect("the proxy answers"); + assert_eq!(response.status().as_u16(), 200); + let body = read_json_body(response); + assert_eq!(body["data"].as_array().unwrap().len(), 1); + assert_eq!(body["data"][0]["id"], "gpt-no-levels"); + assert!(body["data"][0].get("reasoning").is_none()); + assert!(body["data"][0].get("capabilities").is_none()); + assert_eq!(xai_stub.requests().len(), 1); +} + +#[test] +fn grok_reasoning_effort_is_forwarded_unchanged() { + let stub = Stub::start(|request| { + if request.path == "/v1/chat/completions" { + Reply::json(200, r#"{"id":"chatcmpl-stub","choices":[]}"#) + } else { + Reply::json(404, "{}") + } + }); + let harness = harness(&stub, "secret-key", "grok-token"); + let body = json!({ + "model":"grok-4.7", + "messages":[{"role":"user","content":"hello"}], + "reasoning_effort":"future-level" + }); + + let response = agent() + .post(harness.url("/v1/chat/completions")) + .header("Authorization", "Bearer secret-key") + .header("Content-Type", "application/json") + .send(body.to_string()) + .expect("the proxy answers"); + assert_eq!(response.status().as_u16(), 200); + let requests = stub.requests(); + assert_eq!(requests.len(), 1); + let forwarded: serde_json::Value = serde_json::from_str(&requests[0].body).unwrap(); + assert_eq!(forwarded["reasoning_effort"], "future-level"); + assert!(forwarded.get("reasoning").is_none()); +} + #[test] fn a_model_the_upstream_does_not_advertise_is_a_404() { let stub = Stub::start(|request| { From c2c103b0585375cb4fe396e9363c553f94215997 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Tue, 24 Nov 2026 22:41:26 +0000 Subject: [PATCH 05/13] chore: update Cargo.lock --- Cargo.lock | 145 ++++- Cargo.toml | 5 + docs/README.md | 2 + docs/commands.md | 13 + docs/configuration.md | 6 + docs/eggpool.md | 58 ++ src/cli/args.rs | 340 ++++++++++- src/cli/commands/eggpool.rs | 113 ++++ src/cli/commands/mod.rs | 1 + src/cli/commands/run.rs | 71 ++- src/cli/commands/status.rs | 12 + src/cli/mod.rs | 1 + src/config.rs | 425 +++++++++++++- src/eggpool.rs | 1091 +++++++++++++++++++++++++++++++++++ src/main.rs | 1 + src/paths.rs | 10 + src/server/guard.rs | 10 + src/server/mod.rs | 99 +++- src/server/router.rs | 5 + src/server/tests.rs | 1 + src/server/usage.rs | 1 + 21 files changed, 2397 insertions(+), 13 deletions(-) create mode 100644 docs/eggpool.md create mode 100644 src/cli/commands/eggpool.rs create mode 100644 src/eggpool.rs diff --git a/Cargo.lock b/Cargo.lock index 26ce3ff..b276c94 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -218,6 +218,15 @@ dependencies = [ "libc", ] +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid", +] + [[package]] name = "digest" version = "0.10.7" @@ -342,6 +351,7 @@ dependencies = [ "daemonize", "dirs", "eggpass-auth", + "eggress-protocol-reverse", "eggup-acquisition", "eggup-core", "eggup-eggfetch", @@ -360,6 +370,7 @@ dependencies = [ "url", "webbrowser", "windows-sys 0.61.2", + "zeroize", ] [[package]] @@ -380,6 +391,83 @@ dependencies = [ "tokio-util", ] +[[package]] +name = "eggress-core" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd9a88a4dd93b0098db01df1bdc1119b84040b12de39d336f5207b9d951ef481" +dependencies = [ + "bytes", + "eggress-relay", + "eggress-uri", + "pin-project-lite", + "rustls", + "serde", + "socket2 0.5.10", + "thiserror", + "tokio", + "tokio-util", + "tracing", + "trait-variant", +] + +[[package]] +name = "eggress-protocol-reverse" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed062158bbc4246fbcdaf1be2571e329b6c27ee0a2b60b013281aec69bfe8186" +dependencies = [ + "bytes", + "eggress-core", + "eggress-transport-tls", + "eggress-uri", + "rustls", + "serde", + "serde_json", + "subtle", + "thiserror", + "tokio", + "tokio-util", + "tracing", + "zeroize", +] + +[[package]] +name = "eggress-relay" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb9bbfe311ba1bacd7033fa69a7caa524e0c0d807296cb577c39abee09ef6ea0" +dependencies = [ + "tokio", +] + +[[package]] +name = "eggress-transport-tls" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "096569194c7157d855b645b34c2ecab37d022a5b4b4aa086bafbc76460e1776c" +dependencies = [ + "bytes", + "eggress-core", + "pkcs8", + "rustls", + "thiserror", + "tokio", + "tokio-rustls", + "tracing", + "webpki-roots 0.26.11", +] + +[[package]] +name = "eggress-uri" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb741d298c655f7006b9aa27295e4dc7226fbcc137ade7a397ad37574158da98" +dependencies = [ + "serde", + "thiserror", +] + [[package]] name = "eggup-acquisition" version = "0.2.2" @@ -701,7 +789,7 @@ dependencies = [ "hyper", "libc", "pin-project-lite", - "socket2", + "socket2 0.6.5", "tokio", "tower-service", "tracing", @@ -1064,6 +1152,16 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -1405,6 +1503,16 @@ version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "socket2" version = "0.6.5" @@ -1415,6 +1523,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -1523,7 +1640,8 @@ dependencies = [ "libc", "mio", "pin-project-lite", - "socket2", + "signal-hook-registry", + "socket2 0.6.5", "tokio-macros", "windows-sys 0.61.2", ] @@ -1615,9 +1733,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tracing-core" version = "0.1.36" @@ -1627,6 +1757,17 @@ dependencies = [ "once_cell", ] +[[package]] +name = "trait-variant" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b19a4867a870f6edc4c283f2b455804b1879c0baf0e642f26b03ed8ee262d9d3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "try-lock" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index f59bc3f..bac4d21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ include = [ "/docs/client-setup.md", "/docs/commands.md", "/docs/configuration.md", + "/docs/eggpool.md", "/docs/how-it-works.md", "/docs/troubleshooting.md", "/docs/updating.md", @@ -34,6 +35,8 @@ include = [ [dependencies] eggpass-auth = { version = "0.1.1", path = "crates/eggpass-auth" } base64 = "0.23.1" +# Exact Eggress reverse-client wire/API line used by EggPool. +eggress-protocol-reverse = "=1.0.12" dirs = "7.0.0" # Self-update mechanics. Acquisition, transport, release-manifest projection, # digest binding, staging, locking, and rollback are owned by the published @@ -71,6 +74,8 @@ ureq = "3.5.2" # in Cargo.lock; the check is the parser, so do not bump it in passing. url = "=2.5.8" webbrowser = "1.2.7" +# Clear one-time enrollment and private-key buffers after use. +zeroize = "1.9.1" [target.'cfg(unix)'.dependencies] # Unix-only process management and raw-terminal support. diff --git a/docs/README.md b/docs/README.md index bf108e5..7f4ff4f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,6 +5,7 @@ | [commands.md](commands.md) | Command syntax, options, exit codes, and effects | | [client-setup.md](client-setup.md) | Connect OpenAI SDK, OpenCode, Cline, Continue, or curl | | [configuration.md](configuration.md) | Settings and files on disk | +| [eggpool.md](eggpool.md) | EggPool reverse-tunnel enrollment contract and security model | | [how-it-works.md](how-it-works.md) | Routing, translation, authentication, and streaming | | [updating.md](updating.md) | Update verification and rollback | | [troubleshooting.md](troubleshooting.md) | Common errors and fixes | @@ -16,6 +17,7 @@ | Install and run eggpass | The [README](../README.md) quick start | | Connect a client | [client-setup.md](client-setup.md) | | Change providers or settings | [configuration.md](configuration.md) | +| Connect EggPass to EggPool | [eggpool.md](eggpool.md) | | 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) | diff --git a/docs/commands.md b/docs/commands.md index 4f1c164..f2e5c2f 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -110,6 +110,19 @@ ssh -L 8484:127.0.0.1:8484 box **Exit codes:** `0` if the value is shown or applied, including when already serving it. `1` for an invalid or unavailable address, a write failure, or a failed restart. +## `eggpool` + +```sh +eggpass eggpool --control pool.example:18443 --server-name pool.example --ca ./eggpool-ca.pem --label workstation +eggpass eggpool --revoke +``` + +Setup writes non-secret connection settings to [eggpool], creates an EggPass API key for the agent, and prints one epagent1. enrollment ticket to stdout. Treat the ticket as a secret: it contains the one-time enrollment credential and the EggPass API key, and is shown only once. If the daemon is already running on loopback, setup restarts it to activate the tunnel; if it is stopped, setup leaves it stopped. The listener must remain loopback-only while EggPool is enabled. eggpass status reports connection state without printing credentials. + +--revoke stops a running daemon before removing local enrollment state and the EggPool API key. It restarts only if another EggPass API key remains; otherwise the daemon stays stopped. It does not contact EggPool to revoke a certificate already issued there; that server-side operation must be provided by EggPool. + +Exit code: 0 on success; 1 if settings, credentials, the CA file, or daemon restart cannot be handled. + ## `key` ```sh diff --git a/docs/configuration.md b/docs/configuration.md index 7350fa8..5ef38f2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -70,6 +70,12 @@ For a prefix match, the longest matching prefix wins. With the defaults, names b The advanced `[oauth.xai]` settings are `client_id`, `issuer`, `scopes`, and `referrer`. `[oauth.openai]` supports `issuer`, `scopes`, `agent_name_hint`, `resource`, and `ext_agent_host_id`. `scopes` can be a space-separated string or an array of strings. Leave these at their built-in values unless a provider requires a change. The ChatGPT host ID is generated and recorded on first sign-in if it is absent. +## EggPool + +eggpass eggpool --control HOST:PORT --server-name NAME --ca PATH [--label NAME] enables the optional outbound EggPool reverse tunnel. control must be a bare Eggress control host and TCP port (not a URL); server_name is the TLS name checked for the control server; ca is a path to its CA PEM bundle. EggPool mode refuses to start unless host is loopback. EggPass uses a fixed loopback forwarding target equal to its configured listener address; ticket data cannot select an arbitrary target. EggPool must rewrite forwarded HTTP Host headers to 127.0.0.1 (or localhost) to pass the loopback authority guard. + +The config stores only non-secret fields (enabled, control, server_name, ca, and optional label). Enrollment tokens, client certificates/private keys, and status state are kept in owner-only files in the data directory. The one-line ticket printed by setup is a bearer secret: give it only to the trusted EggPool enrollment flow. See [eggpool.md](eggpool.md) for the wire contract and certificate exchange. Use eggpass eggpool --revoke to remove local state and disable the tunnel. + ## Keys and network exposure 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: `. diff --git a/docs/eggpool.md b/docs/eggpool.md new file mode 100644 index 0000000..a06604d --- /dev/null +++ b/docs/eggpool.md @@ -0,0 +1,58 @@ +# EggPool reverse tunnel + +EggPool is an optional outbound reverse tunnel for an EggPass instance. EggPass binds its HTTP API only to a loopback address while EggPool is enabled. The reverse client uses a fixed target host and port taken from that loopback listener; neither the ticket nor the EggPool peer can select an arbitrary forwarding target. + +## Setup + + eggpass eggpool --control pool.example:18443 --server-name pool.example --ca ./eggpool-ca.pem --label workstation + +The command creates an EggPass API key for the agent, generates a random 256-bit enrollment token with a 10-minute lifetime, writes private state, enables the EggPool settings, and prints one single-line epagent1. ticket. If the daemon is already running, setup restarts it on the same loopback address to load the settings. If stopped, setup leaves it stopped. + +The ticket is the prefix epagent1. followed by URL-safe, unpadded Base64 of UTF-8 JSON: + +| Field | Meaning | +| --- | --- | +| v | Ticket format version (1). | +| control | Eggress control HOST:PORT. | +| server_name | TLS server name to verify. | +| ca_sha256 | URL-safe, unpadded Base64 SHA-256 pin of the first CA certificate DER bytes. The PEM bundle itself stays local. | +| enroll | One-time random bearer token, expiring at expires_at. | +| expires_at | Unix timestamp in seconds. | +| agent | Display label. | +| eggpass | EggPass package version. | +| api_key | EggPass API key for normal EggPass API calls; keys.json stores only its hash. | + +Treat the ticket as a bearer secret. Do not paste it into issue trackers, logs, chat, telemetry, or diagnostics. It is printed to stdout only once. Provider OAuth access, refresh, and ID tokens are never part of the ticket or EggPool protocol. + +## Enrollment exchange contract + +The EggPool side must support one-time username/password authentication for the initial Eggress reverse connection: username enroll and password ticket.enroll. The connection must validate the TLS server with the ticket's CA and server_name. The first forwarded request must be: + + POST /v1/eggpool/enroll HTTP/1.1 + Authorization: Bearer + Content-Type: application/json + +The JSON body must contain exactly these fields: + + { + "client_cert_pem": "-----BEGIN CERTIFICATE-----...", + "client_key_pem": "-----BEGIN PRIVATE KEY-----..." + } + +The client certificate and unencrypted private key must be a valid pair and fit within the size limits (64 KiB each). EggPass accepts only the exact callback path, compares the token in constant time, checks expiry, validates the TLS material, writes it to owner-only private state, and consumes the token only after successful validation and persistence. Repeated or expired enrollment cannot replace the certificate. The EggPass API key is not enrollment authorization. + +After the exchange, EggPass reconnects using mutual TLS with the issued client certificate and key; the one-time password is removed from the reverse-client configuration. EggPool must authorize that certificate for the enrolled agent and route forwarded HTTP requests to the EggPass listener. The api_key field is for normal EggPass API requests and should be sent as Authorization: Bearer ; it is independent of mTLS and revocable locally. + +### HTTP forwarding contract + +Eggress relays an opaque TCP stream and does not rewrite HTTP headers. The EggPass loopback authority guard rejects the public EggPool hostname with HTTP 421. Before forwarding each HTTP request through the tunnel—including the enrollment callback—EggPool must rewrite the Host header to 127.0.0.1 (localhost is also accepted). Keep the TCP destination fixed to the configured EggPass loopback listener; do not use a caller-supplied Host or target to select a destination. The proxy must preserve the request path, method, body, and Authorization header. + +Coordination requirement: this EggPass implementation defines the contract above. EggPool must implement the corresponding ticket parser, temporary initial auth, enrollment callback, client-certificate issuance, and subsequent mTLS acceptance before the full workflow can operate end to end. + +## Status and revocation + +eggpass status shows only a connection state, label, and control endpoint; it never prints ticket or certificate contents. Status states include starting, reconnecting, connected, enrollment_required, enrollment_expired, disconnected, error, and stopped. Status is local and may become stale if the daemon is killed without graceful shutdown. + + eggpass eggpool --revoke + +Revocation stops a running daemon before removing the local EggPool API key, pending or enrolled secret material, and status file. It restarts only if another EggPass API key remains; otherwise the daemon stays stopped. It cannot revoke a certificate already issued at the EggPool server; EggPool must separately revoke that certificate or agent identity. Re-setup issues a new API key and enrollment token. diff --git a/src/cli/args.rs b/src/cli/args.rs index a8b300f..5799323 100644 --- a/src/cli/args.rs +++ b/src/cli/args.rs @@ -70,6 +70,11 @@ pub enum Command { /// What to do with the keys. action: KeyAction, }, + /// Configure or revoke an EggPool client connection. + Eggpool { + /// What to do with the EggPool connection. + action: EggpoolAction, + }, } /// What `eggpass key` was asked to do. @@ -91,6 +96,33 @@ pub enum KeyAction { }, } +/// What `eggpass eggpool` was asked to do. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EggpoolAction { + /// Configure a connection to EggPool. + Setup { + /// The EggPool control endpoint. + control: EggpoolControl, + /// The TLS server name expected by EggPool. + server_name: String, + /// The CA certificate bundle to trust. + ca: PathBuf, + /// An optional display label for this connection. + label: Option, + }, + /// Revoke the configured EggPool connection. + Revoke, +} + +/// The host and port of an EggPool control endpoint. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EggpoolControl { + /// Hostname or IP address (without IPv6 brackets). + pub host: String, + /// TCP port. + pub port: u16, +} + /// A parsed command line. #[derive(Debug, Clone)] pub struct Cli { @@ -396,6 +428,15 @@ pub fn parse>(args: I) -> Result { + if provider.is_some() { + return Err(UsageError { + message: "`eggpass eggpool` discovers providers through `/v1/models` and does not accept `--provider`".to_string(), + }); + } + let action = parse_eggpool_action(&rest)?; + Command::Eggpool { action } + } other => { return Err(UsageError { message: format!("unknown command `{other}`"), @@ -504,6 +545,176 @@ fn parse_key_action(rest: &[String]) -> Result { } } +/// Parse the arguments of `eggpass eggpool`. +fn parse_eggpool_action(rest: &[String]) -> Result { + let mut revoke = false; + let mut setup_flag_seen = false; + let mut control = None; + let mut server_name = None; + let mut ca = None; + let mut label = None; + let mut index = 0usize; + + while index < rest.len() { + let arg = rest[index].as_str(); + match arg { + "--revoke" => { + if revoke { + return Err(UsageError { + message: "`--revoke` may only be specified once".to_string(), + }); + } + revoke = true; + index += 1; + } + _ if arg == "--control" || arg.starts_with("--control=") => { + setup_flag_seen = true; + if control.is_some() { + return Err(UsageError { + message: "`--control` may only be specified once".to_string(), + }); + } + let value = eggpool_option_value(rest, &mut index, "--control", arg)?; + control = Some(parse_eggpool_control(value)?); + } + _ if arg == "--server-name" || arg.starts_with("--server-name=") => { + setup_flag_seen = true; + if server_name.is_some() { + return Err(UsageError { + message: "`--server-name` may only be specified once".to_string(), + }); + } + let value = eggpool_option_value(rest, &mut index, "--server-name", arg)?; + server_name = Some(value.to_string()); + } + _ if arg == "--ca" || arg.starts_with("--ca=") => { + setup_flag_seen = true; + if ca.is_some() { + return Err(UsageError { + message: "`--ca` may only be specified once".to_string(), + }); + } + let value = eggpool_option_value(rest, &mut index, "--ca", arg)?; + ca = Some(PathBuf::from(value)); + } + _ if arg == "--label" || arg.starts_with("--label=") => { + setup_flag_seen = true; + if label.is_some() { + return Err(UsageError { + message: "`--label` may only be specified once".to_string(), + }); + } + let value = eggpool_option_value(rest, &mut index, "--label", arg)?; + label = Some(value.to_string()); + } + _ if arg.starts_with('-') => { + return Err(UsageError { + message: format!("unknown option `{arg}` for `eggpass eggpool`"), + }); + } + _ => { + return Err(UsageError { + message: format!( + "`eggpass eggpool` does not take positional arguments (got `{arg}`)" + ), + }); + } + } + } + + if revoke { + if setup_flag_seen { + return Err(UsageError { + message: "`--revoke` cannot be combined with EggPool setup options".to_string(), + }); + } + return Ok(EggpoolAction::Revoke); + } + + let mut missing = Vec::new(); + if control.is_none() { + missing.push("--control"); + } + if server_name.is_none() { + missing.push("--server-name"); + } + if ca.is_none() { + missing.push("--ca"); + } + if !missing.is_empty() { + return Err(UsageError { + message: format!("`eggpass eggpool` setup requires {}", missing.join(", ")), + }); + } + + Ok(EggpoolAction::Setup { + control: control.expect("required above"), + server_name: server_name.expect("required above"), + ca: ca.expect("required above"), + label, + }) +} + +/// Read a required EggPool option value in either `--option VALUE` or `--option=VALUE` form. +fn eggpool_option_value<'a>( + rest: &'a [String], + index: &mut usize, + option: &str, + arg: &'a str, +) -> Result<&'a str, UsageError> { + let value = if arg == option { + let value = rest.get(*index + 1).ok_or_else(|| UsageError { + message: format!("`{option}` requires a value"), + })?; + if value.starts_with("--") { + return Err(UsageError { + message: format!("`{option}` requires a value"), + }); + } + *index += 2; + value.as_str() + } else { + *index += 1; + arg.strip_prefix(&format!("{option}=")).unwrap_or_default() + }; + if value.is_empty() { + return Err(UsageError { + message: format!("`{option}` requires a non-empty value"), + }); + } + Ok(value) +} + +/// Parse and validate an EggPool `HOST:PORT` control endpoint. +fn parse_eggpool_control(value: &str) -> Result { + let invalid = || UsageError { + message: format!("invalid EggPool control address `{value}` (expected HOST:PORT)"), + }; + let (host, port) = if value.starts_with('[') { + let close = value.find(']').ok_or_else(invalid)?; + let host = &value[1..close]; + let port = value[close + 1..].strip_prefix(':').ok_or_else(invalid)?; + if host.parse::().is_err() { + return Err(invalid()); + } + (host, port) + } else { + let (host, port) = value.split_once(':').ok_or_else(invalid)?; + if host.contains(':') { + return Err(invalid()); + } + (host, port) + }; + if host.is_empty() || host.chars().any(char::is_whitespace) { + return Err(invalid()); + } + let port = parse_port(port)?; + Ok(EggpoolControl { + host: host.to_string(), + port, + }) +} + /// Parse the number of a key given on the command line. fn parse_key_number(value: &str) -> Result { let number: u32 = value.parse().map_err(|_| UsageError { @@ -538,7 +749,7 @@ pub fn global_help() -> String { edit Open the config file in your editor\n \ croncheck Start the daemon only if it is not already running\n \ update Update to the latest released version\n \ - key Issue, list and revoke the keys clients use\n\ + key Issue, list and revoke the keys clients use\n eggpool Configure or revoke an EggPool connection\n\ \n\ OPTIONS:\n \ --config Use a different config file\n \ @@ -606,6 +817,16 @@ pub fn command_help(name: &str) -> String { revoke --all Revoke every key\n" .to_string() } + "eggpool" => "eggpass eggpool [--control HOST:PORT --server-name NAME --ca PATH --label NAME]\n\n\ + eggpass eggpool --revoke\n\n\ + Configure EggPool and print a one-time enrollment ticket;\n\ + the CA bundle stays local, and the EggPass listener must remain on loopback.\n\n\ + --control HOST:PORT EggPool control endpoint\n\ + --server-name NAME TLS server name expected by EggPool\n\ + --ca PATH CA certificate bundle to trust\n\ + --label NAME Optional connection label\n\ + --revoke Revoke the configured EggPool connection\n" + .to_string(), other => format!("unknown command `{other}`\n"), } } @@ -944,4 +1165,121 @@ mod tests { }; assert!(text.contains("--json"), "{text}"); } + + #[test] + fn eggpool_setup_and_revoke_actions_are_parsed() { + let ParseOutcome::Run(cli) = parse_args(&[ + "eggpool", + "--control", + "pool.example:8443", + "--server-name", + "eggpool.internal", + "--ca", + "/etc/ssl/eggpool.pem", + "--label", + "work", + ]) + .unwrap() else { + panic!("expected a command") + }; + assert_eq!( + cli.command, + Command::Eggpool { + action: EggpoolAction::Setup { + control: EggpoolControl { + host: "pool.example".to_string(), + port: 8443, + }, + server_name: "eggpool.internal".to_string(), + ca: PathBuf::from("/etc/ssl/eggpool.pem"), + label: Some("work".to_string()), + }, + } + ); + + let ParseOutcome::Run(cli) = parse_args(&["eggpool", "--revoke"]).unwrap() else { + panic!("expected a command") + }; + assert_eq!( + cli.command, + Command::Eggpool { + action: EggpoolAction::Revoke, + } + ); + } + + #[test] + fn eggpool_setup_label_is_optional_and_equals_values_work() { + let ParseOutcome::Run(cli) = parse_args(&[ + "eggpool", + "--control=127.0.0.1:7000", + "--server-name=pool.internal", + "--ca=/tmp/ca.pem", + ]) + .unwrap() else { + panic!("expected a command") + }; + assert_eq!( + cli.command, + Command::Eggpool { + action: EggpoolAction::Setup { + control: EggpoolControl { + host: "127.0.0.1".to_string(), + port: 7000, + }, + server_name: "pool.internal".to_string(), + ca: PathBuf::from("/tmp/ca.pem"), + label: None, + }, + } + ); + } + + #[test] + fn invalid_eggpool_option_combinations_are_usage_errors() { + for args in [ + vec!["eggpool", "--revoke", "--control", "pool:443"], + vec!["eggpool", "--revoke", "--server-name", "pool"], + vec!["eggpool", "--revoke", "--ca", "ca.pem"], + vec!["eggpool", "--revoke", "--label", "pool"], + vec!["eggpool", "--control", "pool:443", "--server-name", "pool"], + vec!["eggpool", "--control", "pool:443", "--ca", "ca.pem"], + vec!["eggpool", "--server-name", "pool", "--ca", "ca.pem"], + vec![ + "eggpool", + "--control", + "pool:0", + "--server-name", + "pool", + "--ca", + "ca.pem", + ], + vec![ + "eggpool", + "--control", + "pool:443", + "--server-name", + "pool", + "--ca", + "ca.pem", + "--provider", + "xai", + ], + ] { + assert!(parse_args(&args).is_err(), "accepted {args:?}"); + } + } + + #[test] + fn eggpool_help_describes_both_actions_and_global_help_lists_it() { + assert!(global_help().contains("eggpool Configure or revoke an EggPool connection")); + let ParseOutcome::Help(text) = parse_args(&["eggpool", "--help"]).unwrap() else { + panic!("expected help") + }; + assert!(text.contains("--control HOST:PORT"), "{text}"); + assert!(text.contains("--revoke"), "{text}"); + assert!(text.contains("one-time enrollment ticket"), "{text}"); + assert!(!text.contains("/v1/models"), "{text}"); + assert!(!text.contains("--provider"), "{text}"); + } } diff --git a/src/cli/commands/eggpool.rs b/src/cli/commands/eggpool.rs new file mode 100644 index 0000000..6785fbf --- /dev/null +++ b/src/cli/commands/eggpool.rs @@ -0,0 +1,113 @@ +//! `eggpass eggpool` setup and revocation. + +use std::path::PathBuf; + +use crate::cli::args::{EggpoolAction, EggpoolControl}; +use crate::cli::{CommandError, Context}; +use crate::config::Config; +use crate::daemon::{self, DaemonState}; + +/// Configure or revoke the EggPool connection. +pub fn eggpool(context: &Context, action: EggpoolAction) -> Result<(), CommandError> { + match action { + EggpoolAction::Setup { + control, + server_name, + ca, + label, + } => setup(context, control, server_name, ca, label), + EggpoolAction::Revoke => revoke(context), + } +} + +fn setup( + context: &Context, + control: EggpoolControl, + server_name: String, + ca: PathBuf, + label: Option, +) -> Result<(), CommandError> { + let daemon_state = daemon::state( + &context.paths.pid_file(), + &context.config.host, + context.config.port, + ); + let (live_host, live_port, was_running) = match daemon_state { + DaemonState::Running { host, port, .. } => (host, port, true), + DaemonState::Stale { .. } | DaemonState::Stopped => { + (context.config.host.clone(), context.config.port, false) + } + }; + + let ca = std::fs::canonicalize(&ca).map_err(|err| { + CommandError::new(format!( + "could not resolve EggPool CA file {}: {err}", + ca.display() + )) + })?; + let control = match control.host.contains(':') { + true => format!("[{}]:{}", control.host, control.port), + false => format!("{}:{}", control.host, control.port), + }; + let label = label.unwrap_or_else(|| "eggpass".to_string()); + let ticket = crate::eggpool::create_ticket( + &context.paths, + &context.config, + crate::eggpool::TicketSetup { + control: &control, + server_name: &server_name, + ca_path: &ca, + label: &label, + live_host: &live_host, + live_port, + }, + ) + .map_err(CommandError::new)?; + + if was_running { + let refreshed = refreshed_context(context)?; + if let Err(err) = crate::cli::commands::run::restart(&refreshed) { + return Err(CommandError::new(format!( + "EggPool was configured, but the daemon could not restart; the ticket was not printed. Rerun setup to issue a fresh ticket ({err})" + ))); + } + } + + // The ticket is a bearer credential; stdout is the only place it is shown. + println!("{}", ticket.as_str()); + Ok(()) +} + +fn revoke(context: &Context) -> Result<(), CommandError> { + let was_running = matches!( + daemon::state( + &context.paths.pid_file(), + &context.config.host, + context.config.port, + ), + DaemonState::Running { .. } + ); + // Stop first so revocation cannot leave an authenticated reverse client + // alive if cleanup or the later optional restart fails. + if was_running { + crate::cli::commands::run::stop(context)?; + } + crate::eggpool::revoke(&context.paths, &context.config).map_err(CommandError::new)?; + + if was_running { + let refreshed = refreshed_context(context)?; + crate::cli::commands::run::start_after_revoke(&refreshed)?; + } + println!("EggPool connection revoked."); + Ok(()) +} + +fn refreshed_context(context: &Context) -> Result { + let config = Config::load(context.paths.config_file()) + .map_err(|err| CommandError::new(format!("could not reload the updated config: {err}")))?; + Ok(Context { + paths: context.paths.clone(), + config, + cli: context.cli.clone(), + }) +} diff --git a/src/cli/commands/mod.rs b/src/cli/commands/mod.rs index f51fd99..e970f4b 100644 --- a/src/cli/commands/mod.rs +++ b/src/cli/commands/mod.rs @@ -2,6 +2,7 @@ pub mod address; pub mod edit; +pub mod eggpool; pub mod host; pub mod key; pub mod login; diff --git a/src/cli/commands/run.rs b/src/cli/commands/run.rs index 52edab5..31cfa4d 100644 --- a/src/cli/commands/run.rs +++ b/src/cli/commands/run.rs @@ -73,6 +73,18 @@ pub fn restart(context: &Context) -> Result<(), CommandError> { run(context, false) } +/// Start after EggPool revocation only when another client key remains. +/// +/// The caller must stop the daemon before revoking its credentials. If that +/// was the only key, leave the daemon stopped instead of failing before stop. +pub fn start_after_revoke(context: &Context) -> Result<(), CommandError> { + if has_a_key(&context.config.api_key, &context.paths.key_store_file())? { + run(context, false) + } else { + Ok(()) + } +} + /// Start the daemon only if it is not already running. /// /// Nothing is printed: a crontab entry must not mail the user. Everything @@ -106,13 +118,20 @@ fn require_key(context: &Context) -> Result<(), CommandError> { /// The implementation behind [`require_key`], testable without a context. fn ensure_a_key_exists(api_key: &str, store: &std::path::Path) -> Result<(), CommandError> { + if has_a_key(api_key, store)? { + Ok(()) + } else { + Err(no_key()) + } +} + +fn has_a_key(api_key: &str, store: &std::path::Path) -> Result { if !api_key.is_empty() { - return Ok(()); + return Ok(true); } match crate::keys::KeyStore::open(store) { - Ok(keys) if !keys.is_empty() => Ok(()), - Ok(_) => Err(no_key()), + Ok(keys) => Ok(!keys.is_empty()), Err(err) => Err(CommandError::new(format!( "the key store at {} could not be read ({err}); run `eggpass key add` to issue a key", store.display() @@ -188,6 +207,12 @@ fn start_daemon(context: &Context, quiet: bool) -> Result<(), CommandError> { /// Run the server in this process. fn serve(context: &Context) -> Result<(), CommandError> { + if context.config.eggpool.enabled && !crate::config::is_loopback_host(&context.config.host) { + return Err(CommandError::new( + "EggPool requires the EggPass HTTP listener to bind only to loopback", + )); + } + let server = Server::bind_with_limits( &context.config.host, context.config.port, @@ -195,6 +220,24 @@ fn serve(context: &Context) -> Result<(), CommandError> { ) .map_err(|err| CommandError::new(err.to_string()))?; + let mut eggpool_runtime = if context.config.eggpool.enabled { + Some( + crate::eggpool::start_runtime( + &context.config.eggpool, + context.paths.eggpool_secret_file(), + context.paths.eggpool_status_file(), + context.config.host.clone(), + context.config.port, + ) + .map_err(CommandError::new)?, + ) + } else { + None + }; + let eggpool_enrollment = eggpool_runtime + .as_ref() + .map(crate::eggpool::TunnelRuntime::enrollment_store); + // Every enabled provider gets a handle. A provider we are not signed in // to is still registered: it simply answers 401 when it is used. let mut providers: HashMap = HashMap::new(); @@ -271,6 +314,7 @@ fn serve(context: &Context) -> Result<(), CommandError> { port: context.config.port, api_key: context.config.api_key.clone(), usage_key: usage_key.token().to_string(), + eggpool_enrollment, keys, providers, default_provider, @@ -299,6 +343,9 @@ fn serve(context: &Context) -> Result<(), CommandError> { server.clone().serve(server_context); + if let Some(runtime) = &mut eggpool_runtime { + runtime.shutdown(); + } daemon::clear(&context.paths.pid_file()); crate::logging::info("shut down"); Ok(()) @@ -345,6 +392,24 @@ mod tests { assert!(ensure_a_key_exists("", &path).is_ok()); } + #[test] + fn revoking_the_only_key_leaves_the_daemon_stopped() { + let directory = tempfile::tempdir().expect("temp dir"); + let context = Context { + paths: crate::paths::Paths::in_directory(directory.path()), + config: crate::config::Config::default(), + cli: crate::cli::args::Cli { + command: crate::cli::args::Command::Eggpool { + action: crate::cli::args::EggpoolAction::Revoke, + }, + config_path: None, + verbose: false, + }, + }; + + assert!(start_after_revoke(&context).is_ok()); + } + #[test] fn a_broken_store_is_reported() { let directory = tempfile::tempdir().expect("temp dir"); diff --git a/src/cli/commands/status.rs b/src/cli/commands/status.rs index c691218..f0c9cfc 100644 --- a/src/cli/commands/status.rs +++ b/src/cli/commands/status.rs @@ -97,17 +97,29 @@ fn print_server(context: &Context) { println!(" auth: {}", auth_summary(context)); println!(" upstream: {}", context.config.upstream.display_name()); println!(" models: {}", model_count(context)); + println!( + " eggpool: {}", + crate::eggpool::status_summary(&context.config.eggpool, &context.paths, true) + ); } DaemonState::Stale { pid } => { println!("Server: stopped"); println!(" pid: {pid} (stale)"); println!(" url: {}", context.config.api_base_url()); println!(" auth: {}", auth_summary(context)); + println!( + " eggpool: {}", + crate::eggpool::status_summary(&context.config.eggpool, &context.paths, false) + ); } DaemonState::Stopped => { println!("Server: stopped"); println!(" url: {}", context.config.api_base_url()); println!(" auth: {}", auth_summary(context)); + println!( + " eggpool: {}", + crate::eggpool::status_summary(&context.config.eggpool, &context.paths, false) + ); } } } diff --git a/src/cli/mod.rs b/src/cli/mod.rs index aa39893..27276bb 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -174,5 +174,6 @@ fn dispatch(context: &Context) -> Result<(), CommandError> { commands::update::update(context, version.clone(), *check) } Command::Key { action } => commands::key::key(context, action.clone()), + Command::Eggpool { action } => commands::eggpool::eggpool(context, action.clone()), } } diff --git a/src/config.rs b/src/config.rs index c802258..b85b332 100644 --- a/src/config.rs +++ b/src/config.rs @@ -313,6 +313,24 @@ impl Default for UpdateSettings { } } +/// Non-secret settings for the optional EggPool integration. +/// +/// `ca` is a filesystem path; credentials and PEM contents do not belong in +/// the configuration file. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct EggpoolSettings { + /// Whether EggPool integration is enabled. + pub enabled: bool, + /// EggPool control endpoint. + pub control: Option, + /// Server name presented to EggPool. + pub server_name: Option, + /// Path to the CA certificate file (not certificate PEM contents). + pub ca: Option, + /// Optional agent label. + pub label: Option, +} + /// The effective configuration. #[derive(Debug, Clone)] pub struct Config { @@ -341,6 +359,8 @@ pub struct Config { pub server: ServerLimits, /// Where the releases are published. pub update: UpdateSettings, + /// Optional EggPool integration settings. + pub eggpool: EggpoolSettings, } impl Default for Config { @@ -361,6 +381,7 @@ impl Default for Config { timeouts: Timeouts::default(), server: ServerLimits::default(), update: UpdateSettings::default(), + eggpool: EggpoolSettings::default(), } } } @@ -403,6 +424,14 @@ max_connections = 256 idle_timeout_seconds = 120 write_timeout_seconds = 600 +# Optional EggPool integration. `ca` is a file path, never PEM contents. +# Do not store tokens, API keys, private keys, or certificate PEM in this file. +[eggpool] +enabled = false +control = "" +server_name = "" +ca = "" + # Where `eggpass update` looks for releases. The repository publishes a # release manifest beside the binaries it names. [update] @@ -506,6 +535,7 @@ struct RawConfig { timeouts: Option, server: Option, update: Option, + eggpool: Option, } /// The raw shape of the `[update]` table. @@ -515,6 +545,19 @@ struct RawUpdate { manifest_name: Option, } +/// The raw shape of the `[eggpool]` table. Unknown non-secret fields are +/// retained by the text writer, while credential-like keys are rejected. +#[derive(Debug, Deserialize, Default)] +struct RawEggpool { + enabled: Option, + control: Option, + server_name: Option, + ca: Option, + label: Option, + #[serde(flatten)] + extra: BTreeMap, +} + /// The raw shape of the `[timeouts]` table. #[derive(Debug, Deserialize, Default)] struct RawTimeouts { @@ -717,6 +760,25 @@ impl Config { } } + if let Some(eggpool) = raw.eggpool { + validate_eggpool_extras(&eggpool.extra, path)?; + if let Some(enabled) = eggpool.enabled { + config.eggpool.enabled = enabled; + } + config.eggpool.control = eggpool.control; + config.eggpool.server_name = eggpool.server_name; + config.eggpool.ca = eggpool.ca.map(PathBuf::from); + config.eggpool.label = eggpool.label; + validate_eggpool(&config.eggpool, path)?; + if config.eggpool.enabled && !is_loopback_host(&config.host) { + return Err(ConfigError::Invalid { + path: path.to_path_buf(), + message: "EggPool requires the EggPass HTTP listener to bind only to loopback" + .to_string(), + }); + } + } + if let Some(providers) = raw.providers { if let Some(xai) = providers.xai { if let Some(enabled) = xai.enabled { @@ -888,11 +950,67 @@ pub fn set_host_id(path: &Path, host_id: &str) -> Result<(), ConfigError> { write_file(path, &updated) } +/// Update the EggPool settings while preserving unrelated TOML text. +/// +/// Only non-secret configuration is written; credentials and PEM material are +/// rejected by validation and never serialized here. +pub fn set_eggpool_settings(path: &Path, settings: &EggpoolSettings) -> Result<(), ConfigError> { + validate_eggpool(settings, path)?; + ensure_config_file(path)?; + + let original = std::fs::read_to_string(path).map_err(|source| ConfigError::Io { + path: path.to_path_buf(), + source, + })?; + let mut updated = replace_in_table_value( + &original, + "eggpool", + "enabled", + &settings.enabled.to_string(), + ); + let ca = match settings.ca.as_ref() { + Some(path) => Some(path.to_str().ok_or_else(|| ConfigError::Invalid { + path: path.to_path_buf(), + message: "[eggpool].ca path must be valid UTF-8 to write TOML".to_string(), + })?), + None => None, + }; + for (key, value) in [ + ("control", settings.control.as_deref()), + ("server_name", settings.server_name.as_deref()), + ("ca", ca), + ] { + updated = match value { + Some(value) => replace_in_table(&updated, "eggpool", key, value), + None => remove_in_table(&updated, "eggpool", key), + }; + } + updated = match &settings.label { + Some(label) => replace_in_table(&updated, "eggpool", "label", label), + None => remove_in_table(&updated, "eggpool", "label"), + }; + + // Validate the complete result before replacing the file. + Config::parse(&updated, path)?; + write_file(path, &updated) +} + +/// Serialize a TOML string value, including any required escaping. +fn toml_string(value: &str) -> String { + toml::Value::String(value.to_string()).to_string() +} + /// Replace a key inside a named table, appending it to the table if needed. /// /// The table is named by its dotted path, so `oauth.openai` means the /// `[oauth.openai]` header. fn replace_in_table(text: &str, table: &str, key: &str, value: &str) -> String { + let value = toml_string(value); + replace_in_table_value(text, table, key, &value) +} + +/// Replace a TOML value inside a named table, appending it if needed. +fn replace_in_table_value(text: &str, table: &str, key: &str, value: &str) -> String { let header = format!("[{table}]"); let mut lines: Vec = text.lines().map(str::to_owned).collect(); @@ -920,7 +1038,7 @@ fn replace_in_table(text: &str, table: &str, key: &str, value: &str) -> String { if !out.is_empty() { out.push('\n'); } - out.push_str(&format!("\n{header}\n{key} = \"{value}\"\n")); + out.push_str(&format!("\n{header}\n{key} = {value}\n")); return out; }; @@ -947,15 +1065,63 @@ fn replace_in_table(text: &str, table: &str, key: &str, value: &str) -> String { while value_end > value_start && line.as_bytes()[value_end - 1].is_ascii_whitespace() { value_end -= 1; } - lines[index].replace_range(value_start..value_end, &format!("\"{value}\"")); + lines[index].replace_range(value_start..value_end, value); return join_lines(&lines, text.ends_with('\n')); } // The key is not in the table yet: add it at the end of the table. - lines.insert(table_end, format!("{key} = \"{value}\"")); + lines.insert(table_end, format!("{key} = {value}")); join_lines(&lines, text.ends_with('\n')) } +/// Remove a key from a named table while retaining any inline comment. +fn remove_in_table(text: &str, table: &str, key: &str) -> String { + let header = format!("[{table}]"); + let mut lines: Vec = text.lines().map(str::to_owned).collect(); + let mut table_start = None; + let mut table_end = lines.len(); + let mut in_table = false; + + for (index, line) in lines.iter().enumerate() { + let trimmed = line.trim_start(); + if trimmed.starts_with('[') { + if in_table { + table_end = index; + break; + } + if trimmed.trim() == header { + table_start = Some(index); + in_table = true; + } + } + } + let Some(start) = table_start else { + return text.to_string(); + }; + + for index in (start + 1)..table_end { + let line = &lines[index]; + let trimmed = line.trim_start(); + let Some(eq) = find_assignment(trimmed) else { + continue; + }; + if trimmed[..eq].trim() != key { + continue; + } + let indentation = line.len() - trimmed.len(); + let value_start = indentation + eq + 1; + let comment = comment_start(&line[value_start..]) + .map(|offset| line[value_start + offset..].trim_start().to_string()); + if let Some(comment) = comment { + lines[index] = format!("{}{}", &line[..indentation], comment); + } else { + lines.remove(index); + } + return join_lines(&lines, text.ends_with('\n')); + } + text.to_string() +} + /// Change one top-level key in the configuration file, preserving everything else. fn set_top_level_value(path: &Path, key: &str, value: &str) -> Result<(), ConfigError> { // Start from the documented template when there is no file yet, so the @@ -1062,10 +1228,15 @@ fn join_lines(lines: &[String], trailing_newline: bool) -> String { fn find_assignment(line: &str) -> Option { let bytes = line.as_bytes(); let mut in_string = false; + let mut escaped = false; let mut quote = b'"'; for (index, byte) in bytes.iter().enumerate() { if in_string { - if *byte == quote { + if escaped { + escaped = false; + } else if quote == b'"' && *byte == b'\\' { + escaped = true; + } else if *byte == quote { in_string = false; } continue; @@ -1087,10 +1258,15 @@ fn find_assignment(line: &str) -> Option { fn comment_start(value: &str) -> Option { let bytes = value.as_bytes(); let mut in_string = false; + let mut escaped = false; let mut quote = b'"'; for (index, byte) in bytes.iter().enumerate() { if in_string { - if *byte == quote { + if escaped { + escaped = false; + } else if quote == b'"' && *byte == b'\\' { + escaped = true; + } else if *byte == quote { in_string = false; } continue; @@ -1107,6 +1283,107 @@ fn comment_start(value: &str) -> Option { None } +/// Validate the non-secret EggPool settings and their conditional requirements. +fn validate_eggpool(settings: &EggpoolSettings, path: &Path) -> Result<(), ConfigError> { + let ca = settings + .ca + .as_ref() + .map(|ca| { + ca.to_str().ok_or_else(|| ConfigError::Invalid { + path: path.to_path_buf(), + message: "[eggpool].ca path must be valid UTF-8 to write TOML".to_string(), + }) + }) + .transpose()?; + + for (name, value) in [ + ("control", settings.control.as_deref()), + ("server_name", settings.server_name.as_deref()), + ("label", settings.label.as_deref()), + ("ca", ca), + ] { + if value.is_some_and(|value| value.contains("-----BEGIN ")) { + return Err(ConfigError::Invalid { + path: path.to_path_buf(), + message: format!("[eggpool].{name} must not contain PEM material"), + }); + } + } + + if settings.enabled { + for (name, value) in [ + ("control", settings.control.as_deref()), + ("server_name", settings.server_name.as_deref()), + ("ca", ca), + ] { + if value.is_none_or(|value| value.trim().is_empty()) { + return Err(ConfigError::Invalid { + path: path.to_path_buf(), + message: format!("[eggpool].{name} must be nonempty when enabled"), + }); + } + } + if let Some(control) = settings.control.as_deref() { + crate::eggpool::validate_control(control).map_err(|message| ConfigError::Invalid { + path: path.to_path_buf(), + message: format!("[eggpool].control {message}"), + })?; + } + } + Ok(()) +} + +/// Reject credential-like keys or PEM contents in unmodelled EggPool values. +fn validate_eggpool_extras( + extra: &BTreeMap, + path: &Path, +) -> Result<(), ConfigError> { + for (key, value) in extra { + if credential_like_key(key) || contains_prohibited_eggpool_data(value) { + return Err(ConfigError::Invalid { + path: path.to_path_buf(), + message: format!("[eggpool].{key} must not contain credentials or PEM material"), + }); + } + } + Ok(()) +} + +/// Whether a key names credential material rather than a non-secret setting. +fn credential_like_key(key: &str) -> bool { + let normalized: String = key + .chars() + .filter(|character| character.is_ascii_alphanumeric()) + .map(|character| character.to_ascii_lowercase()) + .collect(); + [ + "token", + "apikey", + "privatekey", + "clientkey", + "clientcert", + "password", + "secret", + "credential", + "authorization", + "pem", + ] + .iter() + .any(|hint| normalized.contains(hint)) +} + +/// Whether a TOML value contains credential-like keys or a PEM block marker. +fn contains_prohibited_eggpool_data(value: &toml::Value) -> bool { + match value { + toml::Value::String(text) => text.contains("-----BEGIN "), + toml::Value::Array(values) => values.iter().any(contains_prohibited_eggpool_data), + toml::Value::Table(values) => values.iter().any(|(key, value)| { + credential_like_key(key) || contains_prohibited_eggpool_data(value) + }), + _ => false, + } +} + /// Validate a port number coming from the configuration file. fn validate_port(port: i64, path: &Path) -> Result { if !(1..=65535).contains(&port) { @@ -1186,6 +1463,101 @@ mod tests { assert_eq!(config.upstream, Upstream::Api); } + #[test] + fn eggpool_defaults_disabled() { + let config = Config::parse("", Path::new("config.toml")).unwrap(); + assert!(!config.eggpool.enabled); + assert_eq!(config.eggpool.control, None); + assert_eq!(config.eggpool.server_name, None); + assert_eq!(config.eggpool.ca, None); + assert_eq!(config.eggpool.label, None); + } + + #[test] + fn eggpool_settings_parse_when_valid() { + let config = Config::parse( + "[eggpool]\nenabled = true\ncontrol = \"pool.example:18443\"\nserver_name = \"agent.example\"\nca = \"/etc/eggpool/ca.pem\"\nlabel = \"build-agent\"\n", + Path::new("config.toml"), + ) + .unwrap(); + assert!(config.eggpool.enabled); + assert_eq!( + config.eggpool.control.as_deref(), + Some("pool.example:18443") + ); + assert_eq!(config.eggpool.server_name.as_deref(), Some("agent.example")); + assert_eq!( + config.eggpool.ca.as_deref(), + Some(Path::new("/etc/eggpool/ca.pem")) + ); + assert_eq!(config.eggpool.label.as_deref(), Some("build-agent")); + } + + #[test] + fn enabled_eggpool_requires_a_loopback_http_listener() { + let text = "host = \"0.0.0.0\"\n[eggpool]\nenabled = true\ncontrol = \"pool.example:18443\"\nserver_name = \"pool.example\"\nca = \"ca.pem\"\n"; + let error = Config::parse(text, Path::new("config.toml")).unwrap_err(); + assert!(error.to_string().contains("loopback"), "{error}"); + } + + #[test] + fn enabled_eggpool_requires_control_server_name_and_ca() { + for missing in ["control", "server_name", "ca"] { + let mut fields = vec!["enabled = true".to_string()]; + for (name, value) in [ + ("control", "pool.example:18443"), + ("server_name", "agent.example"), + ("ca", "/etc/eggpool/ca.pem"), + ] { + if name != missing { + fields.push(format!("{name} = \"{value}\"")); + } + } + let text = format!("[eggpool]\n{}\n", fields.join("\n")); + let error = Config::parse(&text, Path::new("config.toml")).unwrap_err(); + assert!(error.to_string().contains(missing), "{error}"); + } + } + + #[test] + fn eggpool_rejects_control_urls_and_invalid_ports() { + for control in [ + "https://pool.example/control", + "pool.example/control", + "pool.example:0", + ] { + let text = format!( + "[eggpool]\nenabled = true\ncontrol = \"{control}\"\nserver_name = \"pool.example\"\nca = \"ca.pem\"\n" + ); + let error = Config::parse(&text, Path::new("config.toml")) + .expect_err("invalid control endpoint"); + assert!(error.to_string().contains("control"), "{error}"); + } + } + + #[test] + fn eggpool_rejects_credential_keys_and_pem_contents() { + for key in [ + "token", + "api_key", + "private_key", + "password", + "secret", + "client_key", + "client_cert", + "credential", + "authorization", + ] { + let text = format!("[eggpool]\nenabled = false\n{key} = \"not allowed\"\n"); + assert!(Config::parse(&text, Path::new("config.toml")).is_err()); + } + let pem = + "[eggpool]\nca = \"-----BEGIN CERTIFICATE-----\\nabc\\n-----END CERTIFICATE-----\"\n"; + assert!(Config::parse(pem, Path::new("config.toml")).is_err()); + let nested_secret = "[eggpool.auth]\ntoken = \"not allowed\"\n"; + assert!(Config::parse(nested_secret, Path::new("config.toml")).is_err()); + } + #[test] fn malformed_file_is_a_hard_error_with_a_position() { let dir = tempfile::tempdir().unwrap(); @@ -1274,6 +1646,49 @@ mod tests { assert!(text.contains("port = 8484"), "{text}"); } + #[test] + fn set_eggpool_settings_round_trips_and_preserves_unrelated_text() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write( + &path, + "# preserve top comment\nfuture_root = 17\n\n[eggpool]\n# preserve table comment\nenabled = false\ncontrol = \"old\" # preserve control comment\nserver_name = \"old-agent\"\nca = \"old-ca.pem\"\nlabel = \"old-label\" # preserve label comment\nfuture_eggpool_setting = \"keep me\"\n\n[unrelated]\nvalue = 42\n", + ) + .unwrap(); + + let settings = EggpoolSettings { + enabled: true, + control: Some("pool.example:18443".to_string()), + server_name: Some("agent.example".to_string()), + ca: Some(PathBuf::from("/etc/eggpool/ca.pem")), + label: Some("builder \"one\"".to_string()), + }; + set_eggpool_settings(&path, &settings).unwrap(); + + let config = Config::load(&path).unwrap(); + assert_eq!(config.eggpool, settings); + let text = std::fs::read_to_string(&path).unwrap(); + for preserved in [ + "# preserve top comment", + "# preserve table comment", + "# preserve control comment", + "# preserve label comment", + "future_root = 17", + "future_eggpool_setting = \"keep me\"", + "[unrelated]", + "value = 42", + ] { + assert!(text.contains(preserved), "missing {preserved:?} in {text}"); + } + + let mut without_label = settings; + without_label.label = None; + set_eggpool_settings(&path, &without_label).unwrap(); + assert_eq!(Config::load(&path).unwrap().eggpool.label, None); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("# preserve label comment"), "{text}"); + } + #[test] fn the_default_template_parses() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/eggpool.rs b/src/eggpool.rs new file mode 100644 index 0000000..ffcbb50 --- /dev/null +++ b/src/eggpool.rs @@ -0,0 +1,1091 @@ +//! EggPool ticket, enrollment, and reverse-client support. +//! +//! The one-time enrollment token is accepted only on the TLS-protected reverse +//! connection and the private enrollment callback. EggPool provisions the +//! durable mTLS pair through that same reverse tunnel; the callback never +//! accepts arbitrary forwarding targets. + +use std::io::Write; +use std::net::ToSocketAddrs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread::{self, JoinHandle}; +use std::time::Duration; + +use base64::Engine; +use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use eggress_protocol_reverse::client::{ReverseClient, ReverseClientConfig}; +use eggress_protocol_reverse::metrics::ReverseMetrics; +use eggress_protocol_reverse::tls::ReverseClientTlsConfig; +use rand::Rng; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use tokio::sync::Notify; +use zeroize::{Zeroize, Zeroizing}; + +use crate::config::{Config, EggpoolSettings}; +use crate::keys::KeyStore; +use crate::paths::{Paths, restrict_permissions}; + +/// The reverse-proxied endpoint used only to receive the EggPool client cert. +pub const ENROLLMENT_PATH: &str = "/v1/eggpool/enroll"; +/// The one-time ticket lifetime in seconds. +pub const TICKET_TTL_SECONDS: i64 = 600; +const MAX_TICKET_BYTES: usize = 2048; +const MAX_CERT_PEM_BYTES: usize = 64 * 1024; +const MAX_KEY_PEM_BYTES: usize = 64 * 1024; +const STATUS_STALE_SECONDS: i64 = 10; + +/// Sensitive local state. The API key itself is kept only in the emitted +/// ticket and the normal key store retains only its salted hash. +#[derive(Serialize, Deserialize)] +struct EggpoolSecrets { + version: u8, + agent: String, + api_key_id: u32, + ca_sha256: String, + #[serde(default)] + enroll_token: Option, + #[serde(default)] + expires_at: Option, + #[serde(default)] + client_cert_pem: Option, + #[serde(default)] + client_key_pem: Option, +} + +impl std::fmt::Debug for EggpoolSecrets { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EggpoolSecrets") + .field("version", &self.version) + .field("agent", &self.agent) + .field("api_key_id", &self.api_key_id) + .field("ca_sha256", &self.ca_sha256) + .field( + "enroll_token", + &self.enroll_token.as_ref().map(|_| ""), + ) + .field("expires_at", &self.expires_at) + .field( + "client_cert_pem", + &self.client_cert_pem.as_ref().map(|_| ""), + ) + .field( + "client_key_pem", + &self.client_key_pem.as_ref().map(|_| ""), + ) + .finish() + } +} + +impl Drop for EggpoolSecrets { + fn drop(&mut self) { + if let Some(value) = &mut self.enroll_token { + value.zeroize(); + } + if let Some(value) = &mut self.client_key_pem { + value.zeroize(); + } + if let Some(value) = &mut self.client_cert_pem { + value.zeroize(); + } + } +} + +#[derive(Serialize)] +struct Ticket<'a> { + #[serde(rename = "v")] + version: u8, + control: &'a str, + server_name: &'a str, + ca_sha256: &'a str, + enroll: String, + expires_at: i64, + agent: &'a str, + eggpass: &'static str, + api_key: String, +} + +impl Drop for Ticket<'_> { + fn drop(&mut self) { + self.enroll.zeroize(); + self.api_key.zeroize(); + } +} + +/// Inputs that bind one enrollment ticket to an EggPool control endpoint and +/// the currently configured loopback listener. +pub struct TicketSetup<'a> { + pub control: &'a str, + pub server_name: &'a str, + pub ca_path: &'a Path, + pub label: &'a str, + pub live_host: &'a str, + pub live_port: u16, +} + +/// Generate a ticket, persist its pending enrollment secret, and update the +/// non-secret EggPool configuration. The caller restarts the daemon and prints +/// the returned line only after those operations succeed. +pub fn create_ticket( + paths: &Paths, + config: &Config, + setup: TicketSetup<'_>, +) -> Result, String> { + let TicketSetup { + control, + server_name, + ca_path, + label, + live_host, + live_port, + } = setup; + if !crate::config::is_loopback_host(live_host) { + return Err("EggPool requires EggPass to be bound to a loopback address".to_string()); + } + if !crate::config::is_loopback_host(&config.host) { + return Err( + "EggPool cannot be enabled while the configured host is not loopback".to_string(), + ); + } + if live_host != config.host || live_port != config.port { + return Err("the live EggPass listener differs from the current configuration; restart EggPass and retry".to_string()); + } + validate_control(control)?; + validate_server_name(server_name)?; + validate_label(label)?; + + let ca_pem = std::fs::read(ca_path) + .map_err(|err| format!("could not read the EggPool CA file: {err}"))?; + let ca_sha256 = ca_digest(&ca_pem)?; + let old = load_secrets(&paths.eggpool_secret_file())?; + + paths + .ensure_dir() + .map_err(|err| format!("could not secure the EggPass data directory: {err}"))?; + let key_store = KeyStore::open(paths.key_store_file()) + .map_err(|err| format!("could not open the EggPass key store: {err}"))?; + let (api_key_id, api_key) = key_store + .add(Some(format!("EggPool agent {label}"))) + .map_err(|err| format!("could not create an EggPool API key: {err}"))?; + + let mut random = [0u8; 32]; + rand::rng().fill_bytes(&mut random); + let mut enroll_token = URL_SAFE_NO_PAD.encode(random); + random.zeroize(); + let expires_at = crate::timeutil::now_unix() + TICKET_TTL_SECONDS; + + let mut state = EggpoolSecrets { + version: 1, + agent: label.to_string(), + api_key_id, + ca_sha256: ca_sha256.clone(), + enroll_token: Some(enroll_token.clone()), + expires_at: Some(expires_at), + client_cert_pem: None, + client_key_pem: None, + }; + if let Err(err) = write_secrets(&paths.eggpool_secret_file(), &state) { + let _ = key_store.revoke(api_key_id); + enroll_token.zeroize(); + return Err(err); + } + + let settings = EggpoolSettings { + enabled: true, + control: Some(control.to_string()), + server_name: Some(server_name.to_string()), + ca: Some(ca_path.to_path_buf()), + label: Some(label.to_string()), + }; + if let Err(err) = crate::config::set_eggpool_settings(paths.config_file(), &settings) { + let _ = key_store.revoke(api_key_id); + let _ = remove_file_if_present(&paths.eggpool_secret_file()); + enroll_token.zeroize(); + return Err(format!("could not update the EggPool config: {err}")); + } + + if let Some(previous) = old + && previous.api_key_id != api_key_id + && key_store + .entries() + .iter() + .any(|entry| entry.id == previous.api_key_id) + { + key_store + .revoke(previous.api_key_id) + .map_err(|err| format!("could not revoke the previous EggPool API key: {err}"))?; + } + + let ticket = Ticket { + version: 1, + control, + server_name, + ca_sha256: &ca_sha256, + enroll: std::mem::take(&mut enroll_token), + expires_at, + agent: label, + eggpass: env!("CARGO_PKG_VERSION"), + api_key, + }; + let payload = Zeroizing::new( + serde_json::to_vec(&ticket) + .map_err(|err| format!("could not encode the EggPool ticket: {err}"))?, + ); + let encoded = Zeroizing::new(URL_SAFE_NO_PAD.encode(payload.as_slice())); + let line = Zeroizing::new(format!("epagent1.{}", encoded.as_str())); + if line.len() > MAX_TICKET_BYTES || !line.is_ascii() || line.chars().any(char::is_whitespace) { + let _ = key_store.revoke(api_key_id); + let _ = remove_file_if_present(&paths.eggpool_secret_file()); + state.enroll_token = None; + return Err("the EggPool ticket exceeded the 2 KiB single-line limit".to_string()); + } + + // The live daemon address is checked by the caller and used for the fixed + // target; config remains the source of truth for the next daemon start. + let _ = (live_host, live_port, ca_pem); + enroll_token.zeroize(); + Ok(line) +} + +/// Remove the EggPool API key, pending token, mTLS credentials, and config +/// enablement. The caller stops a running daemon before this operation and may restart it afterward if another API key remains. +pub fn revoke(paths: &Paths, config: &Config) -> Result<(), String> { + let state = load_secrets(&paths.eggpool_secret_file())?; + if let Some(state) = state { + let key_store = KeyStore::open(paths.key_store_file()) + .map_err(|err| format!("could not open the EggPass key store: {err}"))?; + if key_store + .entries() + .iter() + .any(|entry| entry.id == state.api_key_id) + { + key_store + .revoke(state.api_key_id) + .map_err(|err| format!("could not revoke the EggPool API key: {err}"))?; + } + } + + let mut settings = config.eggpool.clone(); + settings.enabled = false; + crate::config::set_eggpool_settings(paths.config_file(), &settings) + .map_err(|err| format!("could not disable EggPool in the config: {err}"))?; + remove_file_if_present(&paths.eggpool_secret_file())?; + remove_file_if_present(&paths.eggpool_status_file())?; + Ok(()) +} + +/// Status text intentionally contains no credentials or certificate data. +pub fn status_summary(settings: &EggpoolSettings, paths: &Paths, daemon_running: bool) -> String { + if !settings.enabled { + return "disabled".to_string(); + } + if !daemon_running { + return "configured; EggPass daemon is stopped".to_string(); + } + + let record = match std::fs::read(paths.eggpool_status_file()) { + Ok(bytes) => serde_json::from_slice::(&bytes).ok(), + Err(_) => None, + }; + let Some(record) = record else { + return "starting or reconnecting".to_string(); + }; + let state = + if crate::timeutil::now_unix().saturating_sub(record.updated_at) > STATUS_STALE_SECONDS { + "disconnected" + } else { + record.state.as_str() + }; + format!("{state} (agent {}, {})", record.agent, record.control) +} + +/// State shared by the HTTP server and the reverse-client supervisor. +pub struct EnrollmentStore { + path: PathBuf, + ca_pem: Vec, + server_name: String, + changed: Arc, + lock: Mutex<()>, +} + +impl EnrollmentStore { + pub(crate) fn new( + path: PathBuf, + ca_pem: Vec, + server_name: String, + changed: Arc, + ) -> Self { + Self { + path, + ca_pem, + server_name, + changed, + lock: Mutex::new(()), + } + } + + /// Check whether a bearer token is the still-live one-time enrollment token. + pub fn authorizes(&self, token: &str) -> bool { + let _guard = self + .lock + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let Ok(Some(mut state)) = load_secrets(&self.path) else { + return false; + }; + let live = state + .expires_at + .is_some_and(|at| at >= crate::timeutil::now_unix()); + let accepted = state.enroll_token.as_deref().is_some_and(|expected| { + crate::keys::constant_time_eq(expected.as_bytes(), token.as_bytes()) + }); + if let Some(value) = state.enroll_token.as_mut() { + value.zeroize(); + } + live && accepted + } + + /// Validate and persist an mTLS certificate/key bundle, consuming the + /// enrollment token only after all validation succeeds. + pub fn complete(&self, token: &str, body: &[u8]) -> Result<(), String> { + if body.len() > MAX_CERT_PEM_BYTES + MAX_KEY_PEM_BYTES + 4096 { + return Err("EggPool enrollment body is too large".to_string()); + } + let mut bundle: EnrollmentBundle = serde_json::from_slice(body) + .map_err(|_| "invalid EggPool enrollment payload".to_string())?; + validate_client_material(&bundle.client_cert_pem, &bundle.client_key_pem)?; + + let tls = ReverseClientTlsConfig { + ca_pem: Some(self.ca_pem.clone()), + server_name: self.server_name.clone(), + client_cert_pem: Some(bundle.client_cert_pem.as_bytes().to_vec()), + client_key_pem: Some(bundle.client_key_pem.as_bytes().to_vec()), + }; + tls.validate() + .map_err(|_| "EggPool supplied an invalid mTLS certificate/key pair".to_string())?; + + let _guard = self + .lock + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut state = load_secrets(&self.path)? + .ok_or_else(|| "EggPool enrollment is no longer pending".to_string())?; + let live = state + .expires_at + .is_some_and(|at| at >= crate::timeutil::now_unix()); + let accepted = state.enroll_token.as_deref().is_some_and(|expected| { + crate::keys::constant_time_eq(expected.as_bytes(), token.as_bytes()) + }); + if !live || !accepted { + return Err("EggPool enrollment is expired or already consumed".to_string()); + } + + if let Some(value) = &mut state.enroll_token { + value.zeroize(); + } + state.enroll_token = None; + state.expires_at = None; + state.client_cert_pem = Some(std::mem::take(&mut bundle.client_cert_pem)); + state.client_key_pem = Some(std::mem::take(&mut bundle.client_key_pem)); + write_secrets(&self.path, &state)?; + self.changed.notify_one(); + Ok(()) + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct EnrollmentBundle { + client_cert_pem: String, + client_key_pem: String, +} + +impl Drop for EnrollmentBundle { + fn drop(&mut self) { + self.client_cert_pem.zeroize(); + self.client_key_pem.zeroize(); + } +} + +/// Extract only a Bearer token from the exact enrollment route. +pub fn enrollment_bearer(header: Option<&str>) -> Option<&str> { + let (scheme, value) = header?.split_once(' ')?; + if !scheme.eq_ignore_ascii_case("bearer") { + return None; + } + let value = value.trim(); + (!value.is_empty() && !value.chars().any(char::is_whitespace)).then_some(value) +} + +/// Handle the internal enrollment callback. Request body and bearer material +/// are zeroized before the request is dropped. +pub fn handle_enrollment( + mut request: crate::server::Request, + store: &EnrollmentStore, +) -> crate::server::Response { + let mut token = enrollment_bearer(request.header("authorization")).map(str::to_string); + let result = token + .as_deref() + .ok_or_else(|| "missing enrollment authorization".to_string()) + .and_then(|token| store.complete(token, &request.body)); + scrub_enrollment_request(&mut request); + if let Some(value) = &mut token { + value.zeroize(); + } + + match result { + Ok(()) => crate::server::Response::bytes( + 204, + vec![("Cache-Control".to_string(), "no-store".to_string())], + Vec::new(), + ), + Err(_) => crate::server::openai_error( + 400, + "invalid or expired EggPool enrollment payload", + "invalid_request_error", + ), + } +} + +/// Zero sensitive parts of an enrollment request on every response path. +pub(crate) fn scrub_enrollment_request(request: &mut crate::server::Request) { + request.body.zeroize(); + for (name, value) in &mut request.headers { + if name.eq_ignore_ascii_case("authorization") { + value.zeroize(); + } + } +} + +/// A running Eggress client and its local mTLS enrollment endpoint state. +pub struct TunnelRuntime { + stop: Arc, + changed: Arc, + join: Option>, + enrollment: Arc, +} + +impl TunnelRuntime { + pub fn enrollment_store(&self) -> Arc { + Arc::clone(&self.enrollment) + } + + pub fn shutdown(&mut self) { + self.stop.store(true, Ordering::SeqCst); + self.changed.notify_one(); + if let Some(join) = self.join.take() { + let _ = join.join(); + } + } +} + +impl Drop for TunnelRuntime { + fn drop(&mut self) { + self.shutdown(); + } +} + +/// Start a dedicated Tokio runtime for the Eggress reverse client. The client +/// always relays to the fixed loopback EggPass listener, never a ticket target. +pub fn start_runtime( + settings: &EggpoolSettings, + secret_path: PathBuf, + status_path: PathBuf, + local_host: String, + local_port: u16, +) -> Result { + let control = settings + .control + .as_ref() + .ok_or_else(|| "EggPool control endpoint is missing".to_string())? + .clone(); + validate_control(&control)?; + let server_name = settings + .server_name + .as_ref() + .ok_or_else(|| "EggPool TLS server name is missing".to_string())? + .clone(); + let ca_path = settings + .ca + .as_ref() + .ok_or_else(|| "EggPool CA path is missing".to_string())?; + let ca_pem = std::fs::read(ca_path) + .map_err(|err| format!("could not read the EggPool CA file: {err}"))?; + validate_server_name(&server_name)?; + ReverseClientTlsConfig { + ca_pem: Some(ca_pem.clone()), + server_name: server_name.clone(), + client_cert_pem: None, + client_key_pem: None, + } + .validate() + .map_err(|_| "EggPool CA or TLS server name is invalid".to_string())?; + + let changed = Arc::new(Notify::new()); + let enrollment = Arc::new(EnrollmentStore::new( + secret_path.clone(), + ca_pem, + server_name.clone(), + Arc::clone(&changed), + )); + write_status(status_path.as_path(), settings, "starting"); + let stop = Arc::new(AtomicBool::new(false)); + let thread_stop = Arc::clone(&stop); + let thread_changed = Arc::clone(&changed); + let thread_settings = settings.clone(); + let thread_status = status_path; + let join = thread::Builder::new() + .name("eggpass-eggpool-reverse".to_string()) + .spawn(move || { + let runtime = match tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(_) => { + write_status(&thread_status, &thread_settings, "error"); + return; + } + }; + runtime.block_on(supervise_client( + thread_settings, + secret_path, + thread_status, + local_host, + local_port, + thread_changed, + thread_stop, + )); + }) + .map_err(|err| format!("could not start EggPool reverse client: {err}"))?; + + Ok(TunnelRuntime { + stop, + changed, + join: Some(join), + enrollment, + }) +} + +async fn supervise_client( + settings: EggpoolSettings, + secret_path: PathBuf, + status_path: PathBuf, + local_host: String, + local_port: u16, + changed: Arc, + stop: Arc, +) { + loop { + if stop.load(Ordering::SeqCst) { + write_status(&status_path, &settings, "stopped"); + return; + } + let state = match load_secrets(&secret_path) { + Ok(Some(state)) => state, + Ok(None) => { + write_status(&status_path, &settings, "enrollment_required"); + changed.notified().await; + continue; + } + Err(_) => { + write_status(&status_path, &settings, "error"); + tokio::select! { + _ = changed.notified() => {}, + _ = tokio::time::sleep(Duration::from_secs(5)) => {}, + } + continue; + } + }; + + let has_pair = state.client_cert_pem.is_some() && state.client_key_pem.is_some(); + let pending = state.enroll_token.is_some() + && state + .expires_at + .is_some_and(|at| at >= crate::timeutil::now_unix()); + if !has_pair && !pending { + write_status(&status_path, &settings, "enrollment_expired"); + changed.notified().await; + continue; + } + + let config = match client_config(&settings, &state, &local_host, local_port) { + Ok(config) => config, + Err(_) => { + write_status(&status_path, &settings, "error"); + tokio::select! { + _ = changed.notified() => {}, + _ = tokio::time::sleep(Duration::from_secs(5)) => {}, + } + continue; + } + }; + let metrics = Arc::new(ReverseMetrics::new()); + let mut client = ReverseClient::new(config); + client.set_metrics(Arc::clone(&metrics)); + let client = Arc::new(client); + let mut running = Box::pin(client.run()); + let mut tick = tokio::time::interval(Duration::from_secs(1)); + + loop { + tokio::select! { + result = &mut running => { + let state = if result.is_err() { "error" } else { "disconnected" }; + write_status(&status_path, &settings, state); + break; + } + _ = changed.notified() => { + client.shutdown(); + break; + } + _ = tick.tick() => { + if pending + && state + .expires_at + .is_some_and(|at| at < crate::timeutil::now_unix()) + { + client.shutdown(); + write_status(&status_path, &settings, "enrollment_expired"); + break; + } + let active = metrics.control_connections_active.load(Ordering::Relaxed); + let state = if active > 0 { "connected" } else { "reconnecting" }; + write_status(&status_path, &settings, state); + } + } + if stop.load(Ordering::SeqCst) { + client.shutdown(); + write_status(&status_path, &settings, "stopped"); + return; + } + } + drop(running); + drop(state); + if stop.load(Ordering::SeqCst) { + write_status(&status_path, &settings, "stopped"); + return; + } + // A credential update or a fatal client error should not spin. + tokio::time::sleep(Duration::from_millis(250)).await; + } +} + +fn client_config( + settings: &EggpoolSettings, + state: &EggpoolSecrets, + local_host: &str, + local_port: u16, +) -> Result { + let control = settings + .control + .as_deref() + .ok_or_else(|| "missing EggPool control endpoint".to_string())?; + let address = control + .to_socket_addrs() + .map_err(|err| format!("could not resolve EggPool control endpoint: {err}"))? + .next() + .ok_or_else(|| "EggPool control endpoint resolved to no addresses".to_string())?; + + let ca_path = settings + .ca + .as_ref() + .ok_or_else(|| "missing EggPool CA path".to_string())?; + let ca_pem = std::fs::read(ca_path) + .map_err(|err| format!("could not read the EggPool CA file: {err}"))?; + let current_pin = ca_digest(&ca_pem)?; + if !crate::keys::constant_time_eq(current_pin.as_bytes(), state.ca_sha256.as_bytes()) { + return Err("EggPool CA certificate changed after ticket creation".to_string()); + } + + if !crate::config::is_loopback_host(local_host) { + return Err("EggPool reverse target must be a loopback address".to_string()); + } + let (auth_username, auth_password) = match (&state.enroll_token, state.expires_at) { + (Some(token), Some(expires_at)) if expires_at >= crate::timeutil::now_unix() => { + (Some("enroll".to_string()), Some(token.clone())) + } + (None, None) if state.client_cert_pem.is_some() && state.client_key_pem.is_some() => { + (None, None) + } + _ => return Err("EggPool enrollment credential is incomplete or expired".to_string()), + }; + let client_config = ReverseClientConfig { + server_addr: address, + default_target_host: Some(local_host.to_string()), + default_target_port: Some(local_port), + reconnect_initial_ms: 1_000, + reconnect_max_ms: 30_000, + tls: Some(ReverseClientTlsConfig { + ca_pem: Some(ca_pem), + server_name: settings + .server_name + .clone() + .ok_or_else(|| "missing EggPool TLS server name".to_string())?, + client_cert_pem: state + .client_cert_pem + .as_ref() + .map(|cert| cert.as_bytes().to_vec()), + client_key_pem: state + .client_key_pem + .as_ref() + .map(|key| key.as_bytes().to_vec()), + }), + auth_username, + auth_password, + ..ReverseClientConfig::default() + }; + client_config + .validate() + .map_err(|_| "EggPool reverse-client TLS configuration is invalid".to_string())?; + Ok(client_config) +} + +#[derive(Serialize, Deserialize)] +struct TunnelStatus { + state: String, + agent: String, + control: String, + updated_at: i64, +} + +fn write_status(path: &Path, settings: &EggpoolSettings, state: &str) { + let status = TunnelStatus { + state: state.to_string(), + agent: settings + .label + .clone() + .unwrap_or_else(|| "eggpass".to_string()), + control: settings + .control + .clone() + .unwrap_or_else(|| "unknown".to_string()), + updated_at: crate::timeutil::now_unix(), + }; + if let Ok(mut bytes) = serde_json::to_vec(&status) { + let _ = write_private(path, &bytes); + bytes.zeroize(); + } +} + +fn validate_client_material(cert: &str, key: &str) -> Result<(), String> { + if cert.is_empty() + || cert.len() > MAX_CERT_PEM_BYTES + || !cert.contains("-----BEGIN CERTIFICATE-----") + || !cert.contains("-----END CERTIFICATE-----") + { + return Err("invalid EggPool client certificate".to_string()); + } + let key_header = [ + "-----BEGIN PRIVATE KEY-----", + "-----BEGIN EC PRIVATE KEY-----", + "-----BEGIN RSA PRIVATE KEY-----", + ]; + if key.is_empty() + || key.len() > MAX_KEY_PEM_BYTES + || key.contains("ENCRYPTED PRIVATE KEY") + || !key_header.iter().any(|header| key.contains(header)) + || !key.contains("-----END ") + { + return Err("invalid EggPool client private key".to_string()); + } + Ok(()) +} + +fn load_secrets(path: &Path) -> Result, String> { + let bytes = match std::fs::read(path) { + Ok(bytes) => bytes, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(err) => return Err(format!("could not read EggPool private state: {err}")), + }; + let result = serde_json::from_slice(&bytes) + .map(Some) + .map_err(|_| "EggPool private state is invalid".to_string()); + let mut bytes = bytes; + bytes.zeroize(); + result +} + +fn write_secrets(path: &Path, state: &EggpoolSecrets) -> Result<(), String> { + let bytes = Zeroizing::new( + serde_json::to_vec_pretty(state) + .map_err(|_| "could not encode EggPool private state".to_string())?, + ); + write_private(path, bytes.as_slice()) +} + +fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> { + let parent = path.parent().unwrap_or_else(|| Path::new(".")); + std::fs::create_dir_all(parent) + .map_err(|err| format!("could not create private state directory: {err}"))?; + + let mut random = [0u8; 8]; + rand::rng().fill_bytes(&mut random); + let suffix = URL_SAFE_NO_PAD.encode(random); + random.zeroize(); + let temporary = parent.join(format!(".eggpool-{suffix}.tmp")); + + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options + .open(&temporary) + .map_err(|err| format!("could not create private state file: {err}"))?; + if let Err(err) = file.write_all(bytes).and_then(|()| file.sync_all()) { + let _ = std::fs::remove_file(&temporary); + return Err(format!("could not write private EggPool state: {err}")); + } + drop(file); + if let Err(err) = std::fs::rename(&temporary, path) { + let _ = std::fs::remove_file(&temporary); + return Err(format!("could not replace private EggPool state: {err}")); + } + restrict_permissions(path, 0o600) + .map_err(|err| format!("could not restrict EggPool state permissions: {err}")) +} + +fn remove_file_if_present(path: &Path) -> Result<(), String> { + match std::fs::remove_file(path) { + Ok(()) => Ok(()), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(err) => Err(format!("could not remove EggPool private state: {err}")), + } +} + +fn ca_digest(pem: &[u8]) -> Result { + let text = + std::str::from_utf8(pem).map_err(|_| "EggPool CA file is not UTF-8 PEM".to_string())?; + let begin = "-----BEGIN CERTIFICATE-----"; + let end = "-----END CERTIFICATE-----"; + let start = text + .find(begin) + .map(|index| index + begin.len()) + .ok_or_else(|| "EggPool CA file contains no PEM certificate".to_string())?; + let finish = text[start..] + .find(end) + .map(|index| start + index) + .ok_or_else(|| "EggPool CA PEM certificate is incomplete".to_string())?; + let compact: Vec = text[start..finish] + .bytes() + .filter(|byte| !byte.is_ascii_whitespace()) + .collect(); + let der = STANDARD + .decode(compact) + .map_err(|_| "EggPool CA PEM certificate is malformed".to_string())?; + if der.is_empty() { + return Err("EggPool CA certificate is empty".to_string()); + } + Ok(URL_SAFE_NO_PAD.encode(Sha256::digest(der))) +} + +pub(crate) fn validate_control(control: &str) -> Result<(), String> { + if control.is_empty() + || control.len() > 255 + || control.chars().any(char::is_whitespace) + || control.contains('/') + { + return Err("invalid EggPool control endpoint".to_string()); + } + let (host, port) = if control.starts_with('[') { + let end = control + .find(']') + .ok_or_else(|| "invalid bracketed EggPool control address".to_string())?; + let host = &control[1..end]; + let port = control[end + 1..] + .strip_prefix(':') + .ok_or_else(|| "EggPool control address needs a port".to_string())?; + (host, port) + } else { + control + .rsplit_once(':') + .ok_or_else(|| "EggPool control address needs a port".to_string())? + }; + let bracketed_ipv6 = control.starts_with('['); + if host.is_empty() + || (bracketed_ipv6 && host.parse::().is_err()) + || (!bracketed_ipv6 && (host.contains(':') || !valid_dns_host(host))) + { + return Err("invalid EggPool control host (IPv6 must be bracketed)".to_string()); + } + let port: u16 = port + .parse() + .map_err(|_| "invalid EggPool control port".to_string())?; + if port == 0 { + return Err("EggPool control port must be between 1 and 65535".to_string()); + } + Ok(()) +} + +fn valid_dns_host(host: &str) -> bool { + let host = host.strip_suffix('.').unwrap_or(host); + !host.is_empty() + && host.len() <= 253 + && host.split('.').all(|label| { + !label.is_empty() + && label.len() <= 63 + && label + .as_bytes() + .first() + .is_some_and(u8::is_ascii_alphanumeric) + && label + .as_bytes() + .last() + .is_some_and(u8::is_ascii_alphanumeric) + && label + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') + }) +} + +fn validate_server_name(server_name: &str) -> Result<(), String> { + if server_name.is_empty() + || server_name.len() > 253 + || server_name.chars().any(char::is_whitespace) + || server_name.contains('/') + { + return Err("invalid EggPool TLS server name".to_string()); + } + Ok(()) +} + +fn validate_label(label: &str) -> Result<(), String> { + if label.is_empty() + || label.len() > 64 + || !label + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + { + return Err("agent label must be 1-64 ASCII letters, digits, '.', '_' or '-'".to_string()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pem(bytes: &[u8]) -> Vec { + format!( + "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----\n", + STANDARD.encode(bytes) + ) + .into_bytes() + } + + #[test] + fn ca_digest_hashes_the_der_not_the_pem_text() { + let digest = ca_digest(&pem(&[1, 2, 3, 4])).expect("digest"); + assert_eq!(digest, URL_SAFE_NO_PAD.encode(Sha256::digest([1, 2, 3, 4]))); + } + + #[test] + fn control_endpoint_requires_host_and_nonzero_port() { + assert!(validate_control("eggpool.lan:18443").is_ok()); + assert!(validate_control("eggpool.lan.:18443").is_ok()); + assert!(validate_control("127.0.0.1:18443").is_ok()); + assert!(validate_control("[::1]:18443").is_ok()); + assert!(validate_control("eggpool.lan:0").is_err()); + assert!(validate_control("https://eggpool.lan:18443").is_err()); + assert!(validate_control("user@eggpool.lan:18443").is_err()); + assert!(validate_control("pool.example?token=x:18443").is_err()); + } + + #[test] + fn ticket_is_single_line_and_secrets_stay_out_of_config_and_key_store() { + let directory = tempfile::tempdir().expect("temp dir"); + let paths = Paths::in_directory(directory.path()); + crate::config::ensure_config_file(paths.config_file()).expect("default config"); + let ca_path = directory.path().join("ca.pem"); + std::fs::write(&ca_path, pem(&[1, 2, 3, 4])).expect("write CA fixture"); + + let ticket = create_ticket( + &paths, + &Config::default(), + TicketSetup { + control: "pool.example:18443", + server_name: "pool.example", + ca_path: &ca_path, + label: "test-agent", + live_host: "127.0.0.1", + live_port: 8484, + }, + ) + .expect("create ticket"); + let line = ticket.as_str(); + assert!(line.starts_with("epagent1.")); + assert!(line.is_ascii() && !line.chars().any(char::is_whitespace)); + assert!(line.len() <= MAX_TICKET_BYTES); + + let encoded = line.strip_prefix("epagent1.").expect("ticket prefix"); + let payload = URL_SAFE_NO_PAD.decode(encoded).expect("ticket base64"); + let parsed: serde_json::Value = serde_json::from_slice(&payload).expect("ticket JSON"); + assert_eq!(parsed["v"], 1); + assert_eq!(parsed["control"], "pool.example:18443"); + assert_eq!(parsed["server_name"], "pool.example"); + let enroll = parsed["enroll"].as_str().expect("enrollment token"); + let api_key = parsed["api_key"].as_str().expect("EggPass API key"); + + let secret_text = + std::fs::read_to_string(paths.eggpool_secret_file()).expect("private state"); + let key_text = std::fs::read_to_string(paths.key_store_file()).expect("key store"); + let config_text = std::fs::read_to_string(paths.config_file()).expect("config"); + assert!(secret_text.contains(enroll)); + assert!(!secret_text.contains(api_key)); + assert!(!key_text.contains(api_key)); + assert!(!config_text.contains(enroll)); + assert!(!config_text.contains(api_key)); + assert!(config_text.contains("enabled = true")); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(paths.eggpool_secret_file()) + .expect("private state metadata") + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o600); + } + } + + #[test] + fn invalid_mtls_material_does_not_consume_the_enrollment_token() { + let directory = tempfile::tempdir().expect("temp dir"); + let ca = pem(&[1, 2, 3, 4]); + let path = directory.path().join("eggpool.json"); + let mut state = EggpoolSecrets { + version: 1, + agent: "test-agent".to_string(), + api_key_id: 1, + ca_sha256: ca_digest(&ca).expect("pin"), + enroll_token: Some("one-use".to_string()), + expires_at: Some(crate::timeutil::now_unix() + 600), + client_cert_pem: None, + client_key_pem: None, + }; + write_secrets(&path, &state).expect("write state"); + state.enroll_token = None; + let store = EnrollmentStore::new( + path.clone(), + ca, + "eggpool.lan".to_string(), + Arc::new(Notify::new()), + ); + assert!(store.authorizes("one-use")); + let invalid = br#"{"client_cert_pem":"bad","client_key_pem":"bad"}"#; + assert!(store.complete("one-use", invalid).is_err()); + assert!(store.authorizes("one-use")); + } + + #[test] + fn bearer_parser_accepts_only_a_single_bearer_value() { + assert_eq!(enrollment_bearer(Some("Bearer abc123")), Some("abc123")); + assert_eq!(enrollment_bearer(Some("Basic abc123")), None); + assert_eq!(enrollment_bearer(Some("Bearer abc 123")), None); + } +} diff --git a/src/main.rs b/src/main.rs index bd6b566..f94b5ff 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ mod auth; mod cli; mod config; mod daemon; +mod eggpool; mod inference; mod keys; mod logging; diff --git a/src/paths.rs b/src/paths.rs index 74552c3..3e379a3 100644 --- a/src/paths.rs +++ b/src/paths.rs @@ -122,6 +122,16 @@ impl Paths { self.dir.join(KEY_STORE_FILE_NAME) } + /// Owner-only state for EggPool enrollment and mTLS credentials. + pub fn eggpool_secret_file(&self) -> PathBuf { + self.dir.join("eggpool.json") + } + + /// The non-secret connection state written by the EggPool client. + pub fn eggpool_status_file(&self) -> PathBuf { + self.dir.join("eggpool.status.json") + } + /// The daemon-managed usage-only credential (not moved by `--config`). pub fn usage_key_file(&self) -> PathBuf { self.dir.join(USAGE_KEY_FILE_NAME) diff --git a/src/server/guard.rs b/src/server/guard.rs index 16d5d4b..6a845f7 100644 --- a/src/server/guard.rs +++ b/src/server/guard.rs @@ -151,6 +151,16 @@ mod tests { } } + #[test] + fn eggpool_forwarding_hosts_pass_the_loopback_guard() { + for value in ["127.0.0.1", "localhost"] { + assert!( + !refused(value), + "EggPool Host rewrite {value:?} was refused" + ); + } + } + #[test] fn a_lookalike_authority_is_refused() { for value in [ diff --git a/src/server/mod.rs b/src/server/mod.rs index 079ab73..99ff0c7 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -29,6 +29,7 @@ mod keep_body_tests { assert!(!keep_body_for("/health")); assert!(!keep_body_for("/healthz")); assert!(!keep_body_for("/v1/usage")); + assert!(keep_body_for(crate::eggpool::ENROLLMENT_PATH)); assert!(keep_body_for("/v1/chat/completions")); assert!(keep_body_for("/v1/models")); } @@ -77,6 +78,8 @@ pub struct ServerContext { /// /// This is never counted as a configured client key. pub usage_key: String, + /// The one-time EggPool enrollment callback, when the integration is enabled. + pub eggpool_enrollment: Option>, /// The keys `eggpass` issued to its clients. pub keys: Arc, /// The providers that are available. @@ -266,6 +269,32 @@ fn pre_authorize(request: &Request, context: &ServerContext) -> Option return Some(refusal); } + // Enrollment is authorized by the short-lived, one-time bearer token, not + // by an ordinary EggPass API key. It is accepted only on the exact callback + // route and only while private state says enrollment is still pending. + if router::route(request.path()) == router::Route::EggpoolEnrollment { + if request.method != "POST" { + return None; + } + let Some(store) = &context.eggpool_enrollment else { + return Some(openai_error( + 404, + "unknown endpoint", + "invalid_request_error", + )); + }; + let authorized = crate::eggpool::enrollment_bearer(request.header("authorization")) + .is_some_and(|token| store.authorizes(token)); + if !authorized { + return Some(openai_error( + 401, + "invalid or expired EggPool enrollment token", + "invalid_request_error", + )); + } + return None; + } + // The health probe is never authenticated: `status` and `croncheck` use // it, and it carries nothing but a version string. // @@ -302,14 +331,18 @@ fn pre_authorize(request: &Request, context: &ServerContext) -> Option } /// Route a request and produce a response. -fn handle_request(request: Request, context: &ServerContext) -> Response { +fn handle_request(mut request: Request, context: &ServerContext) -> Response { if let Some(refusal) = pre_authorize(&request, context) { + if router::route(request.path()) == router::Route::EggpoolEnrollment { + crate::eggpool::scrub_enrollment_request(&mut request); + } return refusal; } let path = request.path().to_string(); let route = router::route(&path); - let method = request.method.as_str(); + let method_text = request.method.clone(); + let method = method_text.as_str(); // The method is matched *after* the route, so an endpoint that exists and // takes a different method answers `405` rather than claiming not to @@ -327,6 +360,19 @@ fn handle_request(request: Request, context: &ServerContext) -> Response { "GET" => usage::handle(context), _ => method_not_allowed(method, "GET"), }, + router::Route::EggpoolEnrollment => match method { + "POST" => match &context.eggpool_enrollment { + Some(store) => crate::eggpool::handle_enrollment(request, store), + None => { + crate::eggpool::scrub_enrollment_request(&mut request); + openai_error(404, "unknown endpoint", "invalid_request_error") + } + }, + _ => { + crate::eggpool::scrub_enrollment_request(&mut request); + method_not_allowed(method, "POST") + } + }, router::Route::Models => match method { "GET" => models::list(&request, context), _ => method_not_allowed(method, "GET"), @@ -525,6 +571,7 @@ mod authorisation_tests { port: 8484, api_key: key.to_string(), usage_key: "usage-only-secret".to_string(), + eggpool_enrollment: None, keys: empty_store(), providers: HashMap::new(), default_provider: ProviderId::Xai, @@ -574,6 +621,53 @@ mod authorisation_tests { } } + #[test] + fn eggpool_enrollment_uses_the_one_time_token_without_an_api_key() { + let directory = tempfile::tempdir().expect("temp dir"); + let state_path = directory.path().join("eggpool.json"); + let state = serde_json::json!({ + "version": 1, + "agent": "test-agent", + "api_key_id": 1, + "ca_sha256": "pin", + "enroll_token": "one-time-secret", + "expires_at": crate::timeutil::now_unix() + 60 + }); + std::fs::write(&state_path, state.to_string()).expect("write pending enrollment"); + let store = Arc::new(crate::eggpool::EnrollmentStore::new( + state_path, + Vec::new(), + "pool.example".to_string(), + Arc::new(tokio::sync::Notify::new()), + )); + let mut context = context_with_key(""); + context.eggpool_enrollment = Some(store); + + let invalid_token = request_at( + "POST", + crate::eggpool::ENROLLMENT_PATH, + vec![ + ("Host", "127.0.0.1:8484"), + ("Authorization", "Bearer wrong"), + ], + b"{}", + ); + assert_eq!(handle_request(invalid_token, &context).status, 401); + + let valid_token = request_at( + "POST", + crate::eggpool::ENROLLMENT_PATH, + vec![ + ("Host", "127.0.0.1:8484"), + ("Authorization", "Bearer one-time-secret"), + ], + b"{}", + ); + // The pending token passed authorization (the body is then rejected), + // even though this context has no ordinary API key. + assert_eq!(handle_request(valid_token, &context).status, 400); + } + #[test] fn the_usage_secret_is_limited_to_the_exact_bearer_usage_get() { let context = context_with_key("regular-secret"); @@ -842,6 +936,7 @@ mod authorisation_tests { port: 8484, api_key: String::new(), usage_key: String::new(), + eggpool_enrollment: None, keys: empty_store(), providers: HashMap::new(), default_provider: ProviderId::Xai, diff --git a/src/server/router.rs b/src/server/router.rs index 1bcf83f..5c64d2e 100644 --- a/src/server/router.rs +++ b/src/server/router.rs @@ -17,6 +17,8 @@ pub enum Route { LastInference, /// `GET /v1/usage` Usage, + /// `POST /v1/eggpool/enroll` + EggpoolEnrollment, /// `GET /health` Health, /// Anything else. @@ -30,6 +32,7 @@ pub enum Route { pub fn route(path: &str) -> Route { match path { "/health" | "/healthz" => return Route::Health, + crate::eggpool::ENROLLMENT_PATH => return Route::EggpoolEnrollment, _ => {} } @@ -68,6 +71,8 @@ mod tests { assert_eq!(route("/last-inference"), Route::LastInference); assert_eq!(route("/v1/usage"), Route::Usage); assert_eq!(route("/usage"), Route::Usage); + assert_eq!(route("/v1/eggpool/enroll"), Route::EggpoolEnrollment); + assert_eq!(route("/eggpool/enroll"), Route::NotFound); } #[test] diff --git a/src/server/tests.rs b/src/server/tests.rs index 865f375..a2c1a38 100644 --- a/src/server/tests.rs +++ b/src/server/tests.rs @@ -420,6 +420,7 @@ fn harness_with_specs( port, api_key: api_key.to_string(), usage_key: "server-test-usage-key".to_string(), + eggpool_enrollment: None, keys: Arc::clone(&keys), providers, default_provider, diff --git a/src/server/usage.rs b/src/server/usage.rs index 2c946eb..8cf4931 100644 --- a/src/server/usage.rs +++ b/src/server/usage.rs @@ -665,6 +665,7 @@ mod tests { port: 8484, api_key: "route-test-key".to_string(), usage_key: String::new(), + eggpool_enrollment: None, keys, providers: std::collections::HashMap::new(), default_provider: ProviderId::Xai, From 55d5f6c811a8b438da8e3e6251f413bb8a24bb79 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Wed, 25 Nov 2026 18:21:30 +0000 Subject: [PATCH 06/13] Add proactive daemon token refresh --- docs/how-it-works.md | 6 +- src/auth/client.rs | 33 ++++++++++- src/auth/refresh.rs | 102 +++++++++++++++++++++++++++++++--- src/server/mod.rs | 127 ++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 256 insertions(+), 12 deletions(-) diff --git a/docs/how-it-works.md b/docs/how-it-works.md index ca5de69..f6d3d0c 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -19,7 +19,9 @@ log request bodies. prefix in `routing.prefixes` wins. Otherwise it uses `routing.default_provider`. 3. The proxy refreshes the provider's OAuth token if needed, removes client - credentials, and forwards the request. + credentials, and forwards the request. While the daemon is running, it also + checks each enabled provider once a minute and refreshes tokens within five + minutes of expiry, even when no client traffic arrives. 4. Chat Completions requests for ChatGPT are translated to the Responses API. x.ai Chat Completions requests are forwarded in their native format. 5. The provider response is returned to the client. Streaming responses are @@ -77,7 +79,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 first requests the running daemon's usage report and reuses its in-memory snapshot when available; the daemon refreshes on demand. A stale last-successful report is shown with a stderr warning. The CLI falls back to direct provider collection when the daemon is stopped or stale, its private runtime usage credential is missing or unreadable, or an older daemon returns `404`; after a transport failure, fallback occurs only if a state recheck confirms the daemon is stopped or stale. Other daemon errors are surfaced. Both paths query only providers enabled in configuration. ChatGPT's 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 requests the running daemon's usage report and reuses its in-memory snapshot when available; the daemon refreshes on demand. A stale last-successful report is shown with a stderr warning. The CLI falls back to direct provider collection when the daemon is stopped or stale, its private runtime usage credential is missing or unreadable, or an older daemon returns `404`; after a transport failure, fallback occurs only if a state recheck confirms the daemon is stopped or stale. Other daemon errors are surfaced. Both paths query only providers enabled in configuration. ChatGPT's 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 daemon's separate proactive token checks use a four-second OAuth deadline and retry on the next minute if a refresh fails. 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/src/auth/client.rs b/src/auth/client.rs index 55dd117..c1beba6 100644 --- a/src/auth/client.rs +++ b/src/auth/client.rs @@ -251,7 +251,38 @@ impl OAuthClient { /// Refresh a token. The returned refresh token is optional; callers should /// retain the previous value if the provider omits rotation. pub fn refresh_as(&self, refresh_token: &str, client_id: &str) -> Result { - let inner = self.inner()?.clone(); + self.refresh_as_with_options(refresh_token, client_id, None) + } + + /// Refresh a token with a shorter per-request deadline. + /// + /// Used by the daemon's background check so a provider outage cannot hold + /// shutdown open for the interactive OAuth client's longer deadline. + pub fn refresh_as_with_timeout( + &self, + refresh_token: &str, + client_id: &str, + timeout: Duration, + ) -> Result { + self.refresh_as_with_options(refresh_token, client_id, Some(timeout)) + } + + fn refresh_as_with_options( + &self, + refresh_token: &str, + client_id: &str, + timeout: Option, + ) -> Result { + let mut inner = self.inner()?.clone(); + if let Some(timeout) = timeout { + let mut options = eggpass_auth::ClientOptions::default(); + options.timeout.pool = Some(timeout); + options.timeout.connect = Some(timeout); + options.timeout.write = Some(timeout); + options.timeout.read = Some(timeout); + options.timeout.total = Some(timeout); + inner = inner.with_options(options).map_err(AuthError::from)?; + } let refresh_token = refresh_token.to_string(); let client_id = client_id.to_string(); let tokens = super::bridge::block_on(async move { diff --git a/src/auth/refresh.rs b/src/auth/refresh.rs index 18f131e..9c93761 100644 --- a/src/auth/refresh.rs +++ b/src/auth/refresh.rs @@ -10,6 +10,7 @@ use std::path::PathBuf; use std::sync::{Mutex, MutexGuard}; +use std::time::Duration; use super::client::{AuthError, OAuthClient, TokenSet}; use super::store::{self, StoreError, StoredAuth}; @@ -18,6 +19,9 @@ use crate::timeutil; /// How long before expiry we refresh the access token. pub const REFRESH_SKEW_SECS: i64 = 5 * 60; +/// A daemon refresh check should not hold shutdown open during an outage. +const BACKGROUND_REFRESH_TIMEOUT: Duration = Duration::from_secs(4); + /// Errors raised while obtaining a usable access token. #[derive(Debug)] pub enum TokenError { @@ -120,22 +124,44 @@ impl TokenManager { /// /// Refreshes the token first if it is about to expire. pub fn access_token(&self) -> Result { + self.usable_auth(None)? + .map(|auth| auth.access_token) + .ok_or(TokenError::NotLoggedIn) + } + + /// Refresh the stored credentials when they are near expiry. + /// + /// A daemon can call this periodically, independently of provider traffic. + /// No credentials is not an error: the provider may not be signed in yet. + pub fn refresh_if_needed(&self) -> Result<(), TokenError> { + self.usable_auth(Some(BACKGROUND_REFRESH_TIMEOUT)) + .map(|_| ()) + } + + /// Return current credentials after refreshing them when necessary. + fn usable_auth( + &self, + refresh_timeout: Option, + ) -> Result, TokenError> { let Some(auth) = self.current()? else { - return Err(TokenError::NotLoggedIn); + return Ok(None); }; if auth.is_fresh(timeutil::now_unix(), self.skew) { - return Ok(auth.access_token); + return Ok(Some(auth)); } let guard = self.lock(); - // Another process may have refreshed while we waited for the lock. - let auth = self.current()?.ok_or(TokenError::NotLoggedIn)?; + // Re-read after acquiring the lock in case another caller refreshed. + let Some(auth) = self.current()? else { + return Ok(None); + }; if auth.is_fresh(timeutil::now_unix(), self.skew) { - return Ok(auth.access_token); + return Ok(Some(auth)); } - Ok(self.refresh_locked(&guard, &auth)?.access_token) + self.refresh_locked(&guard, &auth, refresh_timeout) + .map(Some) } /// Refresh after an upstream request was rejected with `401`. @@ -153,7 +179,7 @@ impl TokenManager { return Ok(auth.access_token); } - Ok(self.refresh_locked(&guard, &auth)?.access_token) + Ok(self.refresh_locked(&guard, &auth, None)?.access_token) } /// Perform the refresh. The caller must hold the lock. @@ -161,6 +187,7 @@ impl TokenManager { &self, _guard: &MutexGuard<'_, ()>, current: &StoredAuth, + timeout: Option, ) -> Result { let Some(refresh_token) = current.refresh_token.clone() else { return Err(TokenError::NoRefreshToken); @@ -173,7 +200,13 @@ impl TokenManager { } else { current.client_id.clone() }; - let tokens = self.client.refresh_as(&refresh_token, &client_id)?; + let tokens = match timeout { + Some(timeout) => { + self.client + .refresh_as_with_timeout(&refresh_token, &client_id, timeout)? + } + None => self.client.refresh_as(&refresh_token, &client_id)?, + }; let refreshed = merge_refreshed(current, &tokens); store::save(&self.path, &refreshed)?; @@ -288,4 +321,57 @@ mod tests { assert_eq!(merged.email.as_deref(), Some("a@b.c")); assert_eq!(merged.user_id.as_deref(), Some("user")); } + + fn local_token_manager(path: &std::path::Path) -> TokenManager { + let config = crate::config::Config::default(); + let mut spec = crate::provider::spec_for(crate::provider::ProviderId::OpenAi, &config); + // Keep any accidental refresh attempt on loopback; these tests never + // send credentials to a real provider. + spec.issuer = "http://127.0.0.1:9".to_string(); + let client = OAuthClient::for_provider(&spec, &spec.entry_client_id); + TokenManager::new(path.to_path_buf(), client) + } + + #[test] + fn periodic_refresh_is_a_noop_without_credentials() { + let directory = tempfile::tempdir().unwrap(); + let manager = local_token_manager(&directory.path().join("auth.json")); + + assert!(manager.refresh_if_needed().is_ok()); + } + + #[test] + fn periodic_refresh_leaves_fresh_credentials_alone() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("auth.json"); + let now = timeutil::now_unix(); + let mut auth = stored(); + auth.expires_at = Some(now + 3600); + auth.obtained_at = now; + store::save(&path, &auth).unwrap(); + let manager = local_token_manager(&path); + + assert!(manager.refresh_if_needed().is_ok()); + assert_eq!( + manager.current().unwrap().unwrap().access_token, + "old-access" + ); + } + + #[test] + fn periodic_refresh_attempts_due_credentials() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("auth.json"); + let now = timeutil::now_unix(); + let mut auth = stored(); + auth.expires_at = Some(now + REFRESH_SKEW_SECS - 1); + auth.obtained_at = now; + store::save(&path, &auth).unwrap(); + let manager = local_token_manager(&path); + + assert!(matches!( + manager.refresh_if_needed(), + Err(TokenError::Auth(_)) + )); + } } diff --git a/src/server/mod.rs b/src/server/mod.rs index 99ff0c7..e91a583 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -41,9 +41,11 @@ pub use http::{HttpServer, Request, Response}; use std::collections::HashMap; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc; +use std::thread::{self, JoinHandle}; use std::time::Duration; -use crate::auth::refresh::TokenManager; +use crate::auth::refresh::{TokenError, TokenManager}; use crate::config::Routing; use crate::provider::{ProviderId, ProviderSpec}; use crate::upstream::UpstreamClient; @@ -212,6 +214,10 @@ impl Server { let _ = signal_hook::flag::register(signal_hook::consts::SIGTERM, flag.clone()); let _ = signal_hook::flag::register(signal_hook::consts::SIGINT, flag.clone()); + // Keep each signed-in provider's access token fresh even when no + // clients are sending requests. A failed check is retried next tick. + let refresh_workers = spawn_token_refresh_workers(&context); + // The gate sees the request head before the body is read. A refusal // is written without retaining the body. Health stays unauthenticated // and does not retain one either: the probe does not read it. @@ -230,6 +236,90 @@ impl Server { // The server waits for the in-flight connections itself, so a stream // that is halfway out when the signal arrives still finishes. Arc::clone(&self.http).serve(self.shutdown.clone(), gate, handler); + + // Let an in-flight refresh finish, but don't leave a worker behind + // once the listener has stopped. OAuth requests have finite deadlines. + for (stop, _) in &refresh_workers { + let _ = stop.send(()); + } + for (_, worker) in refresh_workers { + if worker.join().is_err() { + crate::logging::warn("a background token refresher stopped unexpectedly"); + } + } + } +} + +const TOKEN_REFRESH_CHECK_INTERVAL: Duration = Duration::from_secs(60); + +/// Start one periodic refresh worker for each provider enabled in this server. +fn spawn_token_refresh_workers(context: &ServerContext) -> Vec<(mpsc::Sender<()>, JoinHandle<()>)> { + let mut workers = Vec::new(); + for (provider, handle) in &context.providers { + let provider = *provider; + let tokens = Arc::clone(&handle.tokens); + let (stop, receiver) = mpsc::channel(); + let worker = thread::Builder::new() + .name(format!("eggpass-{}-token-refresh", provider.as_str())) + .spawn(move || { + let mut failed = false; + run_refresh_worker(receiver, TOKEN_REFRESH_CHECK_INTERVAL, || { + match tokens.refresh_if_needed() { + Ok(()) => { + if failed { + crate::logging::info(&format!( + "{} background credential refresh recovered", + provider.display_name() + )); + failed = false; + } + } + Err(error) => { + if !failed { + let reason = match error { + TokenError::NotLoggedIn => "credentials unavailable", + TokenError::Store(_) => "credential store error", + TokenError::Auth(_) => "OAuth refresh error", + TokenError::NoRefreshToken => "no refresh token", + }; + crate::logging::warn(&format!( + "{} background credential refresh failed ({reason}); will retry", + provider.display_name() + )); + failed = true; + } + } + } + }); + }); + + match worker { + Ok(worker) => workers.push((stop, worker)), + Err(_) => crate::logging::warn(&format!( + "could not start the {} background token refresher; request-triggered refresh remains active", + provider.display_name() + )), + } + } + workers +} + +/// Run checks immediately, then on each interval, until the owner asks us to stop. +fn run_refresh_worker(stop: mpsc::Receiver<()>, interval: Duration, mut check: F) +where + F: FnMut(), +{ + loop { + match stop.try_recv() { + Ok(()) | Err(mpsc::TryRecvError::Disconnected) => break, + Err(mpsc::TryRecvError::Empty) => {} + } + + check(); + match stop.recv_timeout(interval) { + Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => break, + Err(mpsc::RecvTimeoutError::Timeout) => {} + } } } @@ -553,6 +643,41 @@ pub fn openai_error_with_code( Response::json(status, body.to_string()) } +#[cfg(test)] +mod refresh_worker_tests { + use super::*; + use std::sync::atomic::AtomicUsize; + + #[test] + fn refresh_worker_checks_immediately_and_stops_on_request() { + let (stop_tx, stop_rx) = mpsc::channel(); + let checks = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&checks); + + run_refresh_worker(stop_rx, Duration::from_secs(60), move || { + observed.fetch_add(1, Ordering::SeqCst); + stop_tx.send(()).unwrap(); + }); + + assert_eq!(checks.load(Ordering::SeqCst), 1); + } + + #[test] + fn refresh_worker_rechecks_after_the_interval() { + let (stop_tx, stop_rx) = mpsc::channel(); + let checks = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&checks); + + run_refresh_worker(stop_rx, Duration::from_millis(1), move || { + if observed.fetch_add(1, Ordering::SeqCst) + 1 == 2 { + stop_tx.send(()).unwrap(); + } + }); + + assert_eq!(checks.load(Ordering::SeqCst), 2); + } +} + #[cfg(test)] mod authorisation_tests { use super::*; From cca03a071ef1f324ccf85291ffdd5166eaff8a87 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Wed, 25 Nov 2026 21:59:33 +0000 Subject: [PATCH 07/13] Add manual provider token refresh --- README.md | 1 + docs/commands.md | 11 ++- src/auth/refresh.rs | 143 +++++++++++++++++++++++++++++++++--- src/cli/args.rs | 39 ++++++++++ src/cli/commands/mod.rs | 1 + src/cli/commands/refresh.rs | 72 ++++++++++++++++++ src/cli/mod.rs | 1 + src/server/mod.rs | 1 + 8 files changed, 259 insertions(+), 10 deletions(-) create mode 100644 src/cli/commands/refresh.rs diff --git a/README.md b/README.md index 7b47c9f..5dae63c 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,7 @@ cleared when the daemon stops. | --- | --- | | `eggpass login` | Sign in to a provider. | | `eggpass logout` | Revoke and remove a provider credential. | +| `eggpass refresh` | Force-refresh stored credentials without an inference request. | | `eggpass status` | Show provider login and server state. | | `eggpass usage` | Show subscription usage where available, preferring the running daemon's cached report. | | `eggpass run` | Start the server. Use `--foreground` to keep it in the terminal. | diff --git a/docs/commands.md b/docs/commands.md index f2e5c2f..aaa15f1 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -19,7 +19,7 @@ Point an OpenAI-compatible client at `http://127.0.0.1:8484/v1` and send the key | Option | Meaning | | --- | --- | | `--config ` | Use a different TOML config file for this command. Other eggpass files stay in the usual data directory. | -| `--provider ` | Select `xai` or `openai` for `login`, `logout`, or `usage`. | +| `--provider ` | Select `xai` or `openai` for `login`, `logout`, `refresh`, or `usage`. | | `--verbose`, `-v` | Enable debug logging. | | `--help`, `-h` | Show help. | | `--version`, `-V` | Show the version. | @@ -48,6 +48,15 @@ Without `--provider`, `login` offers enabled providers and `logout` offers provi **Exit codes:** `login` returns `0` on success or cancellation, `1` on failure, and `2` if device flow is requested for a provider that does not support it. `logout` returns `0` on success, cancellation, or failed provider-side revocation. Credential read or removal errors return `1`. +## `refresh` + +```sh +eggpass refresh # choose a signed-in provider +eggpass refresh --provider openai # select one directly +``` + +`refresh` forces an OAuth credential refresh immediately, even when the access token is not near expiry. It does not send an inference request or remove the existing credentials. Without `--provider`, the picker lists providers with stored credentials; cancelling does nothing. A successful refresh stores rotated credentials. If the provider rejects the refresh or the stored credentials have no refresh token, run `eggpass login --provider ` to sign in again. The command returns `1` when an explicitly selected provider cannot be refreshed; with no selected provider and no stored credentials, it prints `Not logged in.` and returns `0`. + ## `status` ```sh diff --git a/src/auth/refresh.rs b/src/auth/refresh.rs index 9c93761..9bedaa0 100644 --- a/src/auth/refresh.rs +++ b/src/auth/refresh.rs @@ -5,10 +5,11 @@ //! * Refresh **proactively**, a few minutes before the token expires, so a //! request never fails because the token expired mid-flight. //! * Refresh **once**, even when several requests fail at the same moment. The -//! mutex plus the re-read inside it means a burst of parallel 401s results -//! in a single refresh. +//! in-process mutex, shared credential-file lock, and re-read after locking +//! mean a burst of parallel 401s results in a single refresh. -use std::path::PathBuf; +use std::fs::{File, OpenOptions}; +use std::path::{Path, PathBuf}; use std::sync::{Mutex, MutexGuard}; use std::time::Duration; @@ -29,6 +30,8 @@ pub enum TokenError { NotLoggedIn, /// The credential store could not be read or written. Store(StoreError), + /// The shared refresh lock could not be acquired. + Lock(std::io::Error), /// The refresh request failed. Auth(AuthError), /// The stored credentials carry no refresh token. @@ -40,6 +43,9 @@ impl std::fmt::Display for TokenError { match self { TokenError::NotLoggedIn => write!(f, "not logged in — run `eggpass login`"), TokenError::Store(err) => write!(f, "{err}"), + TokenError::Lock(err) => { + write!(f, "could not acquire the credential refresh lock ({err})") + } TokenError::Auth(err) => write!( f, "the stored credentials could not be refreshed ({err}) — run `eggpass login`" @@ -70,9 +76,9 @@ impl From for TokenError { /// Hands out usable access tokens. /// -/// One manager per provider: the credential file, the OAuth client and the -/// refresh mutex are all per provider, so a refresh on one provider never -/// blocks another. +/// One manager per provider: the credential file, OAuth client, and in-process +/// refresh mutex are per provider. A sidecar file lock coordinates refreshes +/// across processes without blocking a different provider. #[derive(Debug)] pub struct TokenManager { path: PathBuf, @@ -138,6 +144,23 @@ impl TokenManager { .map(|_| ()) } + /// Refresh the stored credentials now, even when the access token is fresh. + /// + /// Unlike [`refresh_if_needed`](Self::refresh_if_needed), this operation is + /// intended for an explicit user request and does not skip a refresh based + /// on the token's expiry time. + pub fn refresh_now(&self) -> Result<(), TokenError> { + if self.current()?.is_none() { + return Err(TokenError::NotLoggedIn); + } + let guard = self.lock(); + let _process_guard = self.process_lock()?; + let Some(auth) = self.current()? else { + return Err(TokenError::NotLoggedIn); + }; + self.refresh_locked(&guard, &auth, None).map(|_| ()) + } + /// Return current credentials after refreshing them when necessary. fn usable_auth( &self, @@ -152,7 +175,8 @@ impl TokenManager { } let guard = self.lock(); - // Re-read after acquiring the lock in case another caller refreshed. + let _process_guard = self.process_lock()?; + // Re-read after acquiring the locks in case another process refreshed. let Some(auth) = self.current()? else { return Ok(None); }; @@ -169,7 +193,11 @@ impl TokenManager { /// Only refreshes when the token that failed is still the current one, so /// a burst of parallel requests cannot trigger a refresh stampede. pub fn force_refresh(&self, failed_token: &str) -> Result { + if self.current()?.is_none() { + return Err(TokenError::NotLoggedIn); + } let guard = self.lock(); + let _process_guard = self.process_lock()?; let Some(auth) = self.current()? else { return Err(TokenError::NotLoggedIn); }; @@ -213,8 +241,38 @@ impl TokenManager { Ok(refreshed) } - /// Take the lock, ignoring poisoning — a panic elsewhere must not stop the - /// proxy from refreshing its token. + /// Lock the credential file across processes so the daemon and CLI cannot + /// use the same rotating refresh token at the same time. + fn process_lock(&self) -> Result { + let Some(file_name) = self.path.file_name() else { + return Err(TokenError::Lock(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "credential path has no file name", + ))); + }; + let mut lock_name = file_name.to_os_string(); + lock_name.push(".refresh.lock"); + let parent = self + .path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + std::fs::create_dir_all(parent).map_err(TokenError::Lock)?; + let lock_path = parent.join(lock_name); + let file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(&lock_path) + .map_err(TokenError::Lock)?; + crate::paths::restrict_permissions(&lock_path, 0o600).map_err(TokenError::Lock)?; + file.lock().map_err(TokenError::Lock)?; + Ok(file) + } + + /// Take the in-process lock, ignoring poisoning — a panic elsewhere must not + /// stop the proxy from refreshing its token. fn lock(&self) -> MutexGuard<'_, ()> { self.lock.lock().unwrap_or_else(|err| err.into_inner()) } @@ -340,6 +398,17 @@ mod tests { assert!(manager.refresh_if_needed().is_ok()); } + #[test] + fn manual_refresh_without_credentials_reports_not_logged_in() { + let directory = tempfile::tempdir().unwrap(); + let manager = local_token_manager(&directory.path().join("auth.json")); + + assert!(matches!( + manager.refresh_now(), + Err(TokenError::NotLoggedIn) + )); + } + #[test] fn periodic_refresh_leaves_fresh_credentials_alone() { let directory = tempfile::tempdir().unwrap(); @@ -358,6 +427,62 @@ mod tests { ); } + #[test] + fn manual_refresh_updates_credentials_even_when_the_access_token_is_fresh() { + use std::io::{Read, Write}; + use std::net::TcpListener; + + let listener = TcpListener::bind("127.0.0.1:0").expect("local OAuth stub binds"); + let address = listener.local_addr().expect("local OAuth stub address"); + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("refresh request connects"); + let mut request = Vec::new(); + let mut chunk = [0u8; 1024]; + loop { + let read = stream.read(&mut chunk).expect("refresh request reads"); + assert_ne!(read, 0, "client closed before sending request headers"); + request.extend_from_slice(&chunk[..read]); + if request.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + + let response_body = br#"{"access_token":"fresh-access","refresh_token":"rotated-refresh","id_token":"fresh-id","token_type":"Bearer","expires_in":3600}"#; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + response_body.len() + ); + stream + .write_all(response.as_bytes()) + .expect("response headers write"); + stream + .write_all(response_body) + .expect("response body write"); + }); + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("auth.json"); + let now = timeutil::now_unix(); + let mut auth = stored(); + auth.expires_at = Some(now + 3600); + auth.obtained_at = now; + store::save(&path, &auth).unwrap(); + + let config = crate::config::Config::default(); + let mut spec = crate::provider::spec_for(crate::provider::ProviderId::OpenAi, &config); + spec.issuer = format!("http://{address}"); + let client = OAuthClient::for_provider(&spec, &spec.entry_client_id); + let manager = TokenManager::new(path, client); + + manager.refresh_now().expect("manual refresh succeeds"); + server.join().expect("OAuth stub finishes"); + + let refreshed = manager.current().unwrap().unwrap(); + assert_eq!(refreshed.access_token, "fresh-access"); + assert_eq!(refreshed.refresh_token.as_deref(), Some("rotated-refresh")); + assert_eq!(refreshed.id_token.as_deref(), Some("fresh-id")); + } + #[test] fn periodic_refresh_attempts_due_credentials() { let directory = tempfile::tempdir().unwrap(); diff --git a/src/cli/args.rs b/src/cli/args.rs index 5799323..84109c7 100644 --- a/src/cli/args.rs +++ b/src/cli/args.rs @@ -26,6 +26,11 @@ pub enum Command { /// The provider to sign out of, when it was named. provider: Option, }, + /// Force-refresh a provider's stored credentials. + Refresh { + /// The provider to refresh, when it was named. + provider: Option, + }, /// Report account and daemon state. Status, /// Report how much of the subscription allowance remains. @@ -307,6 +312,10 @@ pub fn parse>(args: I) -> Result { + expect_no_args(&name, &rest)?; + Command::Refresh { provider } + } "status" => { expect_no_args(&name, &rest)?; Command::Status @@ -739,6 +748,7 @@ pub fn global_help() -> String { COMMANDS:\n \ login Authenticate with a provider over OAuth\n \ logout Revoke and remove stored credentials\n \ + refresh Force-refresh a provider's stored credentials\n \ status Show account and daemon state\n \ usage Show how much of the subscription allowance remains\n \ run Start the server as a background daemon\n \ @@ -775,6 +785,7 @@ pub fn command_help(name: &str) -> String { Revoke and remove the stored credentials. Without --provider a picker\n\ lists the providers you are signed in to.\n" .to_string(), + "refresh" => "eggpass refresh [--provider ID]\n\nForce-refresh stored credentials without sending an inference request.\nWithout --provider, choose from signed-in providers.\n".to_string(), "status" => "eggpass status\n\nShow account state and daemon state.\n".to_string(), "usage" => { "eggpass usage [--json]\n\n\ @@ -974,6 +985,25 @@ mod tests { ); } + #[test] + fn refresh_accepts_a_provider_before_or_after_the_command() { + for args in [ + vec!["--provider", "openai", "refresh"], + vec!["refresh", "--provider=openai"], + ] { + let ParseOutcome::Run(cli) = parse_args(&args).unwrap() else { + panic!("expected a command") + }; + assert_eq!( + cli.command, + Command::Refresh { + provider: Some(ProviderId::OpenAi) + } + ); + } + assert!(parse_args(&["refresh", "extra"]).is_err()); + } + #[test] fn an_unknown_provider_is_a_usage_error() { assert!(parse_args(&["--provider", "nope", "login"]).is_err()); @@ -1026,6 +1056,15 @@ mod tests { assert!(!usage.contains("allowance is used"), "{usage}"); } + #[test] + fn refresh_has_command_help() { + let ParseOutcome::Help(text) = parse_args(&["refresh", "--help"]).unwrap() else { + panic!("expected help") + }; + assert!(text.contains("Force-refresh stored credentials"), "{text}"); + assert!(text.contains("--provider"), "{text}"); + } + #[test] fn version_is_available() { assert!(matches!( diff --git a/src/cli/commands/mod.rs b/src/cli/commands/mod.rs index e970f4b..0935532 100644 --- a/src/cli/commands/mod.rs +++ b/src/cli/commands/mod.rs @@ -7,6 +7,7 @@ pub mod host; pub mod key; pub mod login; pub mod port; +pub mod refresh; pub mod run; pub mod status; pub mod update; diff --git a/src/cli/commands/refresh.rs b/src/cli/commands/refresh.rs new file mode 100644 index 0000000..2933934 --- /dev/null +++ b/src/cli/commands/refresh.rs @@ -0,0 +1,72 @@ +//! eggpass refresh. +//! +//! This command deliberately bypasses expiry checks: it is the manual recovery +//! path when a user wants to refresh stored credentials immediately. + +use crate::auth::refresh::TokenError; +use crate::cli::prompt::{self, Choice}; +use crate::cli::{CommandError, Context}; +use crate::provider::{ProviderId, ProviderRuntime}; + +/// Force-refresh one signed-in provider's stored credentials. +pub fn refresh(context: &Context, provider: Option) -> Result<(), CommandError> { + let signed_in: Vec = ProviderId::all() + .into_iter() + .filter(|id| super::login::is_signed_in(context, *id)) + .collect(); + + if provider.is_none() && signed_in.is_empty() { + println!("Not logged in."); + return Ok(()); + } + + let provider = match provider { + Some(provider) => provider, + None => { + let choices: Vec = signed_in + .iter() + .map(|id| Choice::new(id.as_str(), id.display_name())) + .collect(); + match prompt::select("Select a provider to refresh:", &choices) + .map_err(|err| CommandError::new(err.to_string()))? + { + Some(id) => match ProviderId::parse(&id) { + Some(provider) => provider, + None => return Ok(()), + }, + // Cancelling changes nothing. + None => return Ok(()), + } + } + }; + + let runtime = ProviderRuntime::new(provider, &context.config, &context.paths); + runtime.tokens.refresh_now().map_err(|error| { + let provider_name = provider.display_name(); + let login_command = format!("eggpass login --provider {}", provider.as_str()); + let message = match error { + // Keep CLI failures free of response bodies and credential values. + TokenError::NotLoggedIn => { + format!("not logged in to {provider_name}; run {login_command}") + } + TokenError::NoRefreshToken => format!( + "the stored {provider_name} credentials have no refresh token; run {login_command}" + ), + TokenError::Store(_) => { + format!("could not read or write the stored {provider_name} credentials") + } + TokenError::Lock(_) => { + format!("could not acquire the {provider_name} credential refresh lock") + } + TokenError::Auth(_) => { + format!( + "could not refresh the stored {provider_name} credentials; run {login_command}" + ) + } + }; + CommandError::new(message) + })?; + + println!("Credentials refreshed for {}.", provider.display_name()); + Ok(()) +} diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 27276bb..ebbea76 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -161,6 +161,7 @@ fn dispatch(context: &Context) -> Result<(), CommandError> { provider, } => commands::login::login(context, *device, *oauth, *provider), Command::Logout { provider } => commands::login::logout(context, *provider), + Command::Refresh { provider } => commands::refresh::refresh(context, *provider), Command::Status => commands::status::status(context), Command::Usage { provider, json } => commands::usage::usage(context, *provider, *json), Command::Run { foreground } => commands::run::run(context, *foreground), diff --git a/src/server/mod.rs b/src/server/mod.rs index e91a583..67556cf 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -279,6 +279,7 @@ fn spawn_token_refresh_workers(context: &ServerContext) -> Vec<(mpsc::Sender<()> let reason = match error { TokenError::NotLoggedIn => "credentials unavailable", TokenError::Store(_) => "credential store error", + TokenError::Lock(_) => "credential refresh lock error", TokenError::Auth(_) => "OAuth refresh error", TokenError::NoRefreshToken => "no refresh token", }; From 78fb98d22228b52f76c5695e0c3cd93f22fcc58a Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Thu, 26 Nov 2026 05:49:20 +0000 Subject: [PATCH 08/13] Document daemon startup and token refresh --- README.md | 19 +++++++++++++++++++ docs/commands.md | 9 +++++++-- docs/how-it-works.md | 8 +++++--- 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 5dae63c..73b74bb 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,25 @@ curl http://127.0.0.1:8484/v1/chat/completions \ Use `eggpass run --foreground` to keep the server in the current terminal. +### Start at boot and keep it available on Linux + +After signing in and creating at least one client key, open the same user's +crontab with `crontab -e`. For the standard per-user install, paste: + +```cron +@reboot "$HOME/.local/bin/eggpass" croncheck >> "$HOME/.config/eggpass/cron.log" 2>&1 +*/5 * * * * "$HOME/.local/bin/eggpass" croncheck >> "$HOME/.config/eggpass/cron.log" 2>&1 +``` + +These entries assume the binary is at `~/.local/bin/eggpass` and use the +default data directory. If installed elsewhere, replace the binary path with +the absolute path from `command -v eggpass`. If you use `EGGPASS_HOME` or +`XDG_CONFIG_HOME`, set the same value in the crontab. `croncheck` starts the +daemon only when it is not already running; it requires a client key. Cron +keeps the daemon available, while the running daemon independently refreshes +enabled xAI/Grok and OpenAI/ChatGPT credentials as needed (see +[How it works](docs/how-it-works.md)). + ## Connect a client | Setting | Value | diff --git a/docs/commands.md b/docs/commands.md index aaa15f1..81fd2e8 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -159,16 +159,21 @@ Opens the config in `$EDITOR`, then `$VISUAL`, then `helix`, `vim`, or `nano`, f ## `croncheck` -Start the daemon only if it is not already running. It is intended for a crontab, but it still requires a client key and can fail. Ordinary success is quiet. +Start the daemon only if it is not already running. It is intended for a user crontab, requires a client key, and does not refresh provider tokens itself. Ordinary success is quiet. ```sh eggpass croncheck ``` +For the standard per-user install at `~/.local/bin/eggpass`, add both lines to the same user's crontab (`crontab -e`) to start at boot and check every five minutes: + ```cron -*/5 * * * * /usr/local/bin/eggpass croncheck >> ~/.config/eggpass/cron.log 2>&1 +@reboot "$HOME/.local/bin/eggpass" croncheck >> "$HOME/.config/eggpass/cron.log" 2>&1 +*/5 * * * * "$HOME/.local/bin/eggpass" croncheck >> "$HOME/.config/eggpass/cron.log" 2>&1 ``` +If the binary is elsewhere, replace its path with the absolute path from `command -v eggpass`. These entries assume the default data directory; if you use `EGGPASS_HOME` or `XDG_CONFIG_HOME`, set the same value in the crontab. The running daemon, not `croncheck`, checks enabled xAI/Grok and OpenAI/ChatGPT credentials once a minute and refreshes tokens within five minutes of expiry; see [How it works](how-it-works.md). + **Exit codes:** `0` if already running or started, `1` on failure. ## `update` diff --git a/docs/how-it-works.md b/docs/how-it-works.md index f6d3d0c..f5751ea 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -19,9 +19,11 @@ log request bodies. prefix in `routing.prefixes` wins. Otherwise it uses `routing.default_provider`. 3. The proxy refreshes the provider's OAuth token if needed, removes client - credentials, and forwards the request. While the daemon is running, it also - checks each enabled provider once a minute and refreshes tokens within five - minutes of expiry, even when no client traffic arrives. + credentials, and forwards the request. While the daemon is running, it starts + an independent background worker for each enabled provider (xAI/Grok and + OpenAI/ChatGPT). Each worker checks stored credentials immediately and then + once a minute, refreshing an access token when it is within five minutes of + expiry—even when no client traffic arrives. 4. Chat Completions requests for ChatGPT are translated to the Responses API. x.ai Chat Completions requests are forwarded in their native format. 5. The provider response is returned to the client. Streaming responses are From 37950890b8113d5a66f1fccf7ebcfc7f02f622a1 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Thu, 26 Nov 2026 15:44:40 +0000 Subject: [PATCH 09/13] feat: add EggPool agent interoperability --- plans/eggpool-agent-interop-implementation.md | 107 ++++++++++++++++++ scripts/test-eggpool-interop.sh | 24 ++++ src/eggpool.rs | 17 ++- 3 files changed, 147 insertions(+), 1 deletion(-) create mode 100644 plans/eggpool-agent-interop-implementation.md create mode 100644 scripts/test-eggpool-interop.sh diff --git a/plans/eggpool-agent-interop-implementation.md b/plans/eggpool-agent-interop-implementation.md new file mode 100644 index 0000000..65becba --- /dev/null +++ b/plans/eggpool-agent-interop-implementation.md @@ -0,0 +1,107 @@ +# EggPass–EggPool Agent Ticket Interoperability — Implementation Plan + +**Status:** Implementation complete. The owner of both EggPass and EggPool confirmed the producer v1 contract and authorized changes on the existing EggPool consumer branch. Validation passed. Commit and push are authorized; no merge or release was performed. + +**Basis:** EggPass Issue #11, current EggPass producer code and documentation, and the EggPool provider-agent feature branch inspected during the research review. + +## Confirmed implementation decisions + +- Use EggPass's documented version-1 producer contract without producer-side format changes. +- Apply EggPool consumer changes on feat/provider-oauth-user-accounts in the existing sibling worktree. +- Persist a one-way digest of successfully consumed enrollment tickets so a restart cannot reopen replay; never persist the raw ticket/enrollment credential. + +## Goal + +Make EggPass-generated EggPool enrollment tickets usable by EggPool, complete the one-time enrollment-to-mTLS flow, and keep enrollment, transport, and inference credentials separate. Preserve existing account ownership, authorization, revocation, and secret-redaction protections. + +This plan is stored in the EggPass repository because that is the current workspace. Most compatibility changes belong in the EggPool consumer repository; those edits were separately authorized on the existing consumer branch before implementation. + +## Baseline and review findings + +- EggPass currently emits a version-1 ticket in the epagent1. envelope. Its JSON contains v, control, server_name, ca_sha256, enroll, expires_at, agent, eggpass, and api_key. The ticket lifetime is 600 seconds. The CA pin is SHA-256 over the first CA certificate's DER, encoded as URL-safe unpadded Base64. See src/eggpool.rs:32-35,97-108,177,220-230,860-883 and docs/eggpool.md:9-50. +- The relevant consumer is the sibling worktree /Users/davidbowman/projects/gorouter/.worktrees/feat-provider-oauth-user-accounts, branch feat/provider-oauth-user-accounts, inspected at commit ce027903. Its ticket decoder expects version and ca_pin, denies unknown fields, caps lifetime at 120 seconds, and hashes the full configured PEM as hex. Its reverse server uses the account name as the initial authentication username. See the consumer worktree's rust/src/agents/ticket.rs:21-24,77-90,154-162,249-259 and rust/src/agents/tunnel.rs:572-635. +- The consumer currently assigns one environment-variable name to both api_key_env and transport_secret_env, and persists the ticket enrollment credential as the account secret. See rust/src/server/agents.rs:302-318,422-428 in the consumer worktree. +- EggPass documents a certificate/key callback, subsequent mTLS reconnect, removal of the one-time password, and Host rewriting for loopback forwarding. I did not find this complete flow in the inspected consumer branch. See docs/eggpool.md:29-50; the consumer enrollment handler rejects configurations requiring client certificates at rust/src/server/agents.rs:167-174. +- The consumer fixture is synthetic and matches the consumer schema; it uses a short lifetime and hashes PEM text, so it does not establish interoperability with the current EggPass producer. See rust/tests/common/agent_ticket.rs:99-107 in the consumer worktree. No tests were run during this review. +- The consumer's historical closure record predates the current producer and reports that no live producer existed then; it also documents adopting the enrollment value as a single transport credential. This is historical evidence, not evidence of current interoperability. See plans/closure/provider-agents/002-status.md:23-37,117-120 in the consumer worktree. + +## Contract decisions required before implementation + +Use the current EggPass producer and its documented enrollment exchange as the recommended compatibility target, unless both project owners explicitly agree to a new versioned contract. Record the decision in a shared, versioned contract before coding. + +1. Envelope and fields: Confirm version-1 prefix/encoding and exact JSON field names, including how the consumer handles producer metadata and the API key. Keep strict parsing, but recognize all fields the producer emits. +2. Lifetime: Agree that a 600-second producer ticket is valid and define the maximum accepted lifetime and clock-boundary behavior. Align every decoder and replay reservation limit; the consumer registry currently caps reservations at 120 seconds (rust/src/agents/enrollment.rs:16-17,59-116). +3. CA pin: Agree on SHA-256 of the first PEM certificate's DER, encoded URL-safe without padding. +4. Initial authentication: Agree on the fixed initial username and the one-time credential's permitted use. EggPass currently specifies username enroll and the ticket's enrollment credential as password (docs/eggpool.md:29-36). +5. Credential roles: Keep the enrollment credential separate from the inference API key. The API key is used for ordinary EggPass API calls; the enrollment credential is one-time bootstrap authorization (docs/eggpool.md:18-23,39-44). +6. Enrollment lifecycle: Confirm certificate issuance, callback authorization/body, persistence and consumption rules, mTLS reconnect, revocation, and loopback Host rewriting (docs/eggpool.md:29-50). +7. Replay after restart: Choose whether consumed-ticket state must survive a consumer restart. The current registry is in-memory, so restart can reopen a replay window (plans/closure/provider-agents/002-status.md:336-339 in the consumer worktree). + +**Gate:** Do not start implementation until the field contract, authentication sequence, credential ownership, and certificate bootstrap/reconnect behavior are agreed by both sides. + +## Staged implementation + +### Stage 1 — Consumer ticket compatibility + +- Update EggPool's decoder to accept the agreed producer field names and all required version-1 fields while retaining bounded input, strict validation, secret redaction, and safe error behavior. +- Enforce the agreed lifetime policy, including expiry boundary tests. Align the replay-registry reservation limit with the accepted ticket lifetime. +- Parse the configured CA bundle and verify the agreed first-certificate DER digest and encoding; do not hash the PEM text as a substitute. +- Add a producer-shaped fixture generated from the same contract and ensure it includes the producer's extra fields. Keep malformed, unknown-version, unknown-field, and oversized-input tests. + +**Exit:** An unmodified current EggPass ticket passes consumer decoding and validation; deliberately malformed or out-of-policy tickets fail without exposing credentials. + +### Stage 2 — Bootstrap authentication and one-time callback + +- Implement the agreed initial reverse-auth username and one-time credential handling; it must not depend on the selected account display name. +- Generate or obtain the per-agent client certificate/key, then send the documented callback request through the reverse tunnel with the required path, bearer authorization, and JSON body. +- Validate certificate/key pairing and size limits. Consume the enrollment credential only after successful validation and persistence; ensure failed attempts do not create a partially enrolled account. +- Keep the forwarding destination fixed to the configured EggPass loopback listener. Implement the documented Host rewrite while preserving method, path, body, and authorization header. + +**Exit:** A successful callback enrolls a certificate with EggPass; invalid, expired, replayed, or incomplete bootstrap attempts fail safely. + +### Stage 3 — mTLS, secrets, and account lifecycle + +- Reconnect the agent using mTLS after successful enrollment and remove the one-time password from active reverse-client configuration. +- Store the inference API key separately from any bootstrap/transport credential. Use the inference key for ordinary EggPass API requests; do not substitute the enrollment credential. +- Preserve owner binding, authorization, revocation, atomic publication, and secret-redaction protections already present in the consumer branch. +- Implement persistent consumed-ticket tracking if that is the agreed restart policy; otherwise document and test the explicitly accepted restart behavior. + +**Exit:** The normal API path operates independently of bootstrap credentials, mTLS is required after enrollment, and revocation/cleanup removes the correct per-agent state. + +### Stage 4 — Cross-project interoperability and security validation + +- Add an integration test that uses a ticket produced by EggPass's actual ticket-generation path and exercises EggPool enrollment, callback delivery, mTLS reconnect, and a normal authenticated API request. +- Avoid relying solely on a hand-authored consumer-schema fixture. Keep a versioned shared fixture or test harness so producer and consumer changes detect drift. +- Run relevant test suites in both repositories, formatting/lint checks, and the focused end-to-end test. Review logs and failure paths for ticket, enrollment, API-key, private-key, and OAuth-token disclosure. + +**Exit:** The producer-generated ticket completes the full workflow; all negative tests fail closed; results are recorded separately from historical closure evidence. + +## Acceptance checklist + +- [x] Contract is agreed and versioned by EggPass and EggPool maintainers before implementation. +- [x] Current producer ticket fields and envelope decode without producer-side changes, or a jointly approved contract migration is completed. +- [x] Exactly the agreed ticket lifetime is accepted; expired and excessive lifetimes are rejected; replay reservation TTL is consistent. +- [x] CA-pin verification uses the agreed certificate input and encoding, including a multi-certificate bundle test. +- [x] Initial reverse authentication uses the agreed fixed protocol identity and one-time credential, independent of account display name. +- [x] Enrollment callback validates the exact path, authorization, payload, certificate/key pair, and size boundaries; failed persistence does not consume the ticket. +- [x] Successful enrollment stores the issued certificate/key and reconnects with mTLS; the one-time password is no longer used after bootstrap. +- [x] The API key is stored and used independently from enrollment/transport secrets. +- [x] Host rewriting and fixed-loopback routing preserve request semantics and cannot be redirected by caller-supplied Host/target values. +- [x] Replay behavior is tested for concurrent enrollment, repeated use, expiry, and the agreed restart policy. +- [x] Existing ownership, authorization, revocation, cleanup, and secret-redaction tests continue to pass. +- [x] A cross-project test uses a ticket from the real EggPass producer path and proves the complete enrollment-to-mTLS-to-API flow. +- [x] No credentials or private key material appear in logs, diagnostics, test output, or fixtures. + +**Validation evidence:** EggPass producer tests: 5 passed. EggPool full serial workspace suite passed, as did the focused routing, upstream, enrollment, migration, and producer-backed interoperability tests. Formatting, strict Clippy, locked release build, no-default-feature check/Clippy, and `git diff --check` passed. The interoperability runner exercised the real EggPass CLI ticket through callback, mTLS reconnect, and an authenticated API request. + +## Out of scope + +- Changing provider OAuth custody/login plans; those are separate from Issue #11's reverse-agent enrollment contract. +- Public release, publishing, deployment, or merge. +- Treating the historical consumer closure or its synthetic fixture as proof of current producer interoperability. + +## References + +- Issue: https://github.com/eggstack/eggpass/issues/11 +- EggPass producer: src/eggpool.rs:32-35,97-108,177,220-230,705-736,860-883; contract: docs/eggpool.md:9-50. +- EggPool consumer branch feat/provider-oauth-user-accounts at ce027903: rust/src/agents/ticket.rs; rust/src/agents/enrollment.rs; rust/src/agents/tunnel.rs; rust/src/server/agents.rs; rust/tests/common/agent_ticket.rs; historical evidence: plans/closure/provider-agents/002-status.md. diff --git a/scripts/test-eggpool-interop.sh b/scripts/test-eggpool-interop.sh new file mode 100644 index 0000000..1feb92e --- /dev/null +++ b/scripts/test-eggpool-interop.sh @@ -0,0 +1,24 @@ +#!/bin/sh +set -eu + +if [ "$#" -ne 1 ]; then + echo "usage: sh scripts/test-eggpool-interop.sh /path/to/eggpool/rust/Cargo.toml" >&2 + exit 2 +fi + +SCRIPT_DIR=$(CDPATH= cd "$(dirname "$0")" && pwd) +EGGPASS_ROOT=$(CDPATH= cd "$SCRIPT_DIR/.." && pwd) +EGGPOOL_MANIFEST=$1 +case "$EGGPOOL_MANIFEST" in + /*) ;; + *) EGGPOOL_MANIFEST=$(pwd)/$EGGPOOL_MANIFEST ;; +esac +if [ ! -f "$EGGPOOL_MANIFEST" ]; then + echo "EggPool manifest not found: $EGGPOOL_MANIFEST" >&2 + exit 2 +fi + +# The consumer integration test invokes this binary with a fresh EGGPASS_HOME +# and captures the one-time ticket in memory; it never prints ticket contents. +CARGO_TARGET_DIR="$EGGPASS_ROOT/target" cargo build --manifest-path "$EGGPASS_ROOT/Cargo.toml" --bin eggpass +EGGPASS_BIN="$EGGPASS_ROOT/target/debug/eggpass" cargo test --manifest-path "$EGGPOOL_MANIFEST" --test agent_enrollment real_eggpass_cli_ticket_completes_callback_mtls_and_authenticated_api_request -- --ignored diff --git a/src/eggpool.rs b/src/eggpool.rs index ffcbb50..3fc4728 100644 --- a/src/eggpool.rs +++ b/src/eggpool.rs @@ -978,9 +978,12 @@ mod tests { } #[test] - fn ca_digest_hashes_the_der_not_the_pem_text() { + fn ca_digest_hashes_the_first_certificate_der_not_the_pem_text() { let digest = ca_digest(&pem(&[1, 2, 3, 4])).expect("digest"); assert_eq!(digest, URL_SAFE_NO_PAD.encode(Sha256::digest([1, 2, 3, 4]))); + + let bundle = [pem(&[1, 2, 3, 4]), pem(&[9, 8, 7])].concat(); + assert_eq!(ca_digest(&bundle).expect("bundle digest"), digest); } #[test] @@ -1024,11 +1027,23 @@ mod tests { let encoded = line.strip_prefix("epagent1.").expect("ticket prefix"); let payload = URL_SAFE_NO_PAD.decode(encoded).expect("ticket base64"); let parsed: serde_json::Value = serde_json::from_slice(&payload).expect("ticket JSON"); + assert_eq!(parsed.as_object().map(serde_json::Map::len), Some(9)); assert_eq!(parsed["v"], 1); assert_eq!(parsed["control"], "pool.example:18443"); assert_eq!(parsed["server_name"], "pool.example"); + assert_eq!(parsed["agent"], "test-agent"); + assert_eq!(parsed["eggpass"], env!("CARGO_PKG_VERSION")); + let expected_pin = URL_SAFE_NO_PAD.encode(Sha256::digest([1, 2, 3, 4])); + assert_eq!(parsed["ca_sha256"].as_str(), Some(expected_pin.as_str())); + let expiry = parsed["expires_at"].as_i64().expect("expiry"); + let remaining = expiry - crate::timeutil::now_unix(); + assert!((599..=600).contains(&remaining)); let enroll = parsed["enroll"].as_str().expect("enrollment token"); let api_key = parsed["api_key"].as_str().expect("EggPass API key"); + assert_ne!( + enroll, api_key, + "bootstrap and inference credentials are distinct" + ); let secret_text = std::fs::read_to_string(paths.eggpool_secret_file()).expect("private state"); From 3cf9fddd084d9b103a3a885e7236aa89443c6b65 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Fri, 27 Nov 2026 05:01:44 +0000 Subject: [PATCH 10/13] chore: update CHANGELOG.md --- CHANGELOG.md | 28 + docs/configuration.md | 2 + docs/how-it-works.md | 25 + docs/troubleshooting.md | 31 + ...on-text-content-proxying-implementation.md | 233 +++++ scripts/probe-media-endpoints.sh | 71 ++ src/config.rs | 61 ++ src/eggpool.rs | 81 +- src/provider/mod.rs | 22 + src/provider/openai.rs | 4 + src/provider/xai.rs | 4 + src/server/chat.rs | 69 +- src/server/http.rs | 122 ++- src/server/media.rs | 236 +++++ src/server/mod.rs | 18 +- src/server/parts.rs | 271 ++++++ src/server/tests.rs | 320 ++++++- src/server/translate.rs | 868 ++++++++++++++---- tests/fixtures/media/README.md | 3 + .../media/chat-completions-image.json | 14 + tests/fixtures/media/chatgpt-models.json | 5 + .../media/responses-image-generation.json | 13 + tests/fixtures/media/responses-refusal.json | 15 + .../media/responses-stream-refusal.txt | 6 + 24 files changed, 2280 insertions(+), 242 deletions(-) create mode 100644 plans/non-text-content-proxying-implementation.md create mode 100644 scripts/probe-media-endpoints.sh create mode 100644 src/server/media.rs create mode 100644 src/server/parts.rs create mode 100644 tests/fixtures/media/README.md create mode 100644 tests/fixtures/media/chat-completions-image.json create mode 100644 tests/fixtures/media/chatgpt-models.json create mode 100644 tests/fixtures/media/responses-image-generation.json create mode 100644 tests/fixtures/media/responses-refusal.json create mode 100644 tests/fixtures/media/responses-stream-refusal.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 81277f6..bc0595f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,34 @@ Notable changes to eggpass are listed here. The format follows ## [Unreleased] +### Added + +- Carry non-text content through ChatGPT's Chat Completions translation: + `image_url` becomes `input_image` with `detail` preserved, and `input_audio` + and file parts are mapped to their Responses equivalents. An image-only + message no longer disappears. +- Return a refusal as a non-text `content` part, in both non-streaming and + streaming answers, instead of an empty answer. +- Carry request fields with a mechanical Responses equivalent, including + `response_format` to `text.format`, and pass Responses-native tools through. +- Add an optional `server.max_body_bytes` setting, defaulting to 32 MiB. +- Add probe-gated routing for native media endpoints. A route is enabled only + after `scripts/probe-media-endpoints.sh` confirms it, so an unprobed path + still answers `404`. + +### Changed + +- Refuse a part, field, or tool the translated path cannot carry with a named + `400` before the upstream runs, rather than dropping it silently. +- Answer a chat or Responses request without a readable `model` with + `400 missing_model` instead of routing it to the default provider. + +### Fixed + +- Fail an answer or stream whose content cannot be expressed in the Chat + Completions shape with `unmappable_output_item` instead of empty content. +- Name the limit and the inline-media cause in the `413` response. + ## [0.1.3] - 2026-11-22 ### Added diff --git a/docs/configuration.md b/docs/configuration.md index 5ef38f2..4eb40ea 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -28,6 +28,7 @@ body_seconds = 1800 [server] max_connections = 256 +max_body_bytes = 33554432 idle_timeout_seconds = 120 write_timeout_seconds = 600 @@ -60,6 +61,7 @@ default_provider = "xai" | `allow_privileged_port` | `false` | Must be `true` to use a port below 1024. | | `timeouts.*` | See example | Upstream connection, whole-request, and response-body time limits in seconds. | | `server.*` | See example | Local connection limit and idle/write timeouts. | +| `server.max_body_bytes` | `33554432` | Largest request body in bytes, including inline base64 media. Clamped to 1–256 MiB; a larger body answers `413 body_too_large`. | | `providers.*.enabled` | `true` | Disable a provider without deleting its stored credentials. Routing to a disabled provider will not serve requests. | | `providers.xai.upstream` | `api` | `api` uses `https://api.x.ai/v1`; `build` uses `https://cli-chat-proxy.grok.com/v1`. | | `routing.default_provider` | `xai` | Provider used when no model prefix matches. | diff --git a/docs/how-it-works.md b/docs/how-it-works.md index f5751ea..6da3e70 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -31,6 +31,31 @@ log request bodies. The Responses API is also available at `POST /v1/responses`. +## Content shapes + +What is forwarded, translated, or refused depends on the provider and the +endpoint, not only on the model. + +- **x.ai, both endpoints.** The request body is forwarded byte for byte, so + text, `image_url`, `input_audio`, and file parts reach x.ai exactly as the + client sent them. The answer is returned unchanged. +- **ChatGPT, `/v1/responses`.** The request and the answer are forwarded + verbatim. `input_image` parts and the `image_generation` tool already work + on this path. +- **ChatGPT, `/v1/chat/completions`.** The request is translated. Text, + `image_url` (including `detail`), `input_audio`, and file parts are mapped + to their Responses equivalents. A refusal and any other non-text content + part is returned in `content` as a part array; a text-only answer keeps the + string form. A part, request field, or tool with no faithful equivalent is + refused with a named `400` before the upstream is called — it is never + dropped. Image or audio generation is not expressible over Chat Completions + and must use `/v1/responses`. + +Native media endpoints, such as image generation, are declared per provider in +the provider spec. A path is routed only after a live probe confirms the +subscription serves it; until then it answers `404`, the same as any other +unknown endpoint. + ## Sign-in and credentials Sign-in uses OAuth Authorization Code with PKCE. x.ai supports a device-code diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index da869cb..f4b2e93 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -53,6 +53,37 @@ provider may omit models that are unavailable or filtered during normalization. **A reasoning level is rejected:** Use a level listed for that model. Providers can reject levels they do not support. +**`unsupported_content_part`:** The request carries a content part the +translated path cannot express. Use `text`, `image_url`, `input_audio`, or a +file part with `file_id` or `filename` and `file_data`; a non-text part in a +`system` message or a non-text `tool` output is refused by design. A part type +this proxy does not translate can still be sent to `POST /v1/responses`, which +is forwarded verbatim. + +**`unsupported_parameter`:** The named Chat Completions field has no Responses +equivalent. `stop`, `seed`, `n` greater than 1, penalty fields with a non-zero +value, `logit_bias`, and `logprobs` are examples. Remove the field, or send a +native Responses request. + +**`image_requires_responses` or `audio_requires_responses`:** An image or audio +generation tool was requested over Chat Completions, whose answer shape cannot +carry the generated media. Call `POST /v1/responses` instead. + +**`missing_model`:** The body must be a JSON object with a `model` string. A +non-JSON or model-less body is no longer forwarded to the default provider. + +**`body_too_large` (HTTP 413):** The body exceeds `server.max_body_bytes` +(32 MiB by default). Inline base64 media counts toward the limit. Raise the +setting within its documented range if the request is legitimate. + +**`unexpected_media_content_type`:** A native media endpoint answered with a +content type its provider spec does not list. The response is refused rather +than labelled wrongly; check that the endpoint and the probe result match. + +**`unmappable_output_item`:** The upstream returned an item, such as a +generated image or audio, that the Chat Completions shape cannot express. Retry +the request against `POST /v1/responses`. + **An agent does not run a tool:** Check that the response contains `message.tool_calls` and that the client handles OpenAI Chat Completions tool calls. For the tool result, the client must send the assistant's tool call and diff --git a/plans/non-text-content-proxying-implementation.md b/plans/non-text-content-proxying-implementation.md new file mode 100644 index 0000000..4faa05e --- /dev/null +++ b/plans/non-text-content-proxying-implementation.md @@ -0,0 +1,233 @@ +# Non-Text Content Proxying — Implementation Plan + +**Status:** Implemented and verified offline. Stages 1–5 and 7–9 are implemented; Stage 6's forwarding machinery is implemented with every candidate left disabled. Stage 0 live capture and the Stage 6 live probe have not run, so the documented wire shapes and each candidate's subscription access remain unverified. No commit, push, merge, or release was performed. + +**Basis:** Read-only audit of the current `fix/pypi-classifiers-0.1.1` tree at `3795089`, covering routing, the chat handler, the two translation directions, stream aggregation, the upstream client, and both provider specs. + +## Goal + +Make EggPass carry non-text content — image, audio, and file parts — correctly to the upstream provider and back to the client, or fail with a specific error that names what could not be carried. + +Two invariants define "done": + +1. **No silent drop.** Every content part and every request field either reaches the upstream, or produces a `400`/`502` that names it and gives a reason. An answer is never an empty `content` because everything in it was discarded. +2. **Truthful capabilities.** A model is advertised as accepting a modality only when the configured request path can actually deliver that modality. + +## Baseline findings + +| # | Gap | Evidence | Effect today | +| --- | --- | --- | --- | +| G1 | Chat Completions input is reduced to text before translation | `translate.rs:168` `content_text()` keeps a part only when it has a `text` field | `image_url`, `input_audio`, and `file` parts vanish for ChatGPT | +| G2 | An image-only message disappears entirely | the same function returns `None`; the `user` arm then inserts nothing | the upstream answers an empty conversation | +| G3 | Request fields outside four names are dropped | `translate.rs:18` `PASSTHROUGH = ["model","tool_choice","parallel_tool_calls","reasoning"]` | `response_format`, `stream_options`, `n`, `stop`, `seed`, penalties, `modalities`, `audio` are lost without a word | +| G4 | Non-`function` tools are discarded | `translate.rs:192` `convert_tool()` returns `None` for any other `type` | image generation, web search, and file search cannot be requested | +| G5 | Output projection is text-only | `translate.rs:340` `response_text()`; `content` is emitted as a string | refusal parts and any image/audio output item are dropped; a non-text-only answer becomes `""` | +| G6 | Streaming translation drops non-text events | the catch-all `_ => Vec::new()` at `translate.rs:809` inside `translate_event` (`translate.rs:612`) | refusals and non-text deltas never reach a streaming client | +| G7 | The catalogue advertises what the translation cannot deliver | `provider/openai.rs:103` keeps `input_modalities`; the test at `provider/mod.rs` asserts `["text","image"]` survives | a client is told images work, then they are silently discarded | +| G8 | No media endpoint is routed | `router.rs:29-46`; anything else is `404 unknown endpoint` (`mod.rs:479-482`) | image generation, audio, files, and embeddings are unreachable | +| G9 | Inline media is bounded by a buffered 32 MiB body | `http.rs:22` `MAX_BODY_BYTES`; enforced at `http.rs:626` | large media fails with a generic `413` that names no limit and no remedy | +| G10 | There is no media test coverage | no `image_url`, `input_image`, or `input_audio` occurrence anywhere under `src/`, tests included | this whole area can regress undetected | + +## What already works and must not regress + +- **xAI, both endpoints.** `src/provider/xai.rs` sets `NativePaths::Both` and `RequestPolicy::default()`. `chat.rs:53` takes the native branch, the body is cloned byte for byte, and `apply_policy` (`chat.rs:325`) short-circuits when the policy is empty. Body, content type, and any media part pass through unchanged. +- **ChatGPT on `/v1/responses`.** The same native branch forwards `input_image` parts and `image_generation` tools verbatim, and returns the provider's response object verbatim. Image generation is already reachable on this path and only this path. +- **Transport.** Request bodies are read as raw bytes with chunked decoding, and only hop-by-hop and credential headers are stripped (`upstream.rs` `STRIPPED_HEADERS`). Nothing in the HTTP layer is text-specific. +- **The EggPool tunnel** preserves method, path, body, and Authorization (`docs/eggpool.md`), so it inherits whatever the router supports and needs no change here. + +## Design principles + +1. **Translate or fail; never drop.** A part or field with a known mechanical equivalent is mapped. One without a faithful equivalent produces a named error. Silence is a defect. +2. **Verbatim by default.** When the provider speaks the client's shape, bytes are forwarded untouched. Translation is the exception, applied only where shapes differ. +3. **One projection.** Streaming and non-streaming output share a single mapping implementation so the two cannot drift. +4. **Facts, not hopes.** A capability is advertised, and a route enabled, only after it is confirmed against a live provider. +5. **Fail before the model runs.** An unserviceable request (for example an image tool over Chat Completions) is rejected at request validation, not after tokens have been spent and the answer cannot be expressed. + +## Target shapes + +Stage 0 confirms every row against a captured payload. Input parts: + +| Chat Completions | Responses | Transformation | +| --- | --- | --- | +| `{"type":"text","text":…}` | `{"type":"input_text","text":…}` | rename; already produced | +| `{"type":"image_url","image_url":{"url":…,"detail":…}}` | `{"type":"input_image","image_url":…,"detail":…}` | nested object flattened to a string, `detail` lifted alongside | +| `{"type":"input_audio","input_audio":{"data":…,"format":…}}` | `{"type":"input_audio","input_audio":{…}}` | shape-equivalent; model support is the upstream's call | +| `{"type":"file","file":{…}}` | `{"type":"input_file", …}` | type renamed; `file_id`, or `filename` with `file_data`, carried across | +| bare string `content` | one `input_text` part | unchanged | + +Output items: + +| Responses item | Chat Completions | Rule | +| --- | --- | --- | +| `message` → `output_text` | `content: "…"` | a text-only answer keeps the string form, for client compatibility | +| `message` → `refusal` | `content: [{"type":"refusal",…}]` | the array form is used only when a non-text part exists | +| `function_call` | `message.tool_calls` | existing behaviour | +| `reasoning` | `message.reasoning_content` | existing behaviour | +| `image_generation_call`, audio items | none | rejected at request time for a Chat client; `502` with a named code if one arrives unexpectedly | + +## Staged implementation + +### Stage 0 — Capture and freeze the wire shapes (gate) + +- With a signed-in account, capture one request/response pair per row above: an xAI `image_url` request, a ChatGPT `/v1/responses` `input_image` request, a refusal, and an image-generation call. +- Record them under `tests/fixtures/media/` with media replaced by a 1×1 PNG data URL and every identifier removed. No token, prompt, or user data is stored. +- Correct the target tables before any mapping code is written. A row that cannot be confirmed is implemented as an explicit rejection, not a guess. + +**Exit:** redacted fixtures exist, and every row is either confirmed or deliberately dropped from the tables. + +### Stage 1 — Input content parts + +- Add `parse_chat_content` and `to_responses_parts` in a new `src/server/parts.rs`. They accept `content` as a string or an array, and are the only place part shapes are understood. +- `chat_request_to_responses` builds part arrays for `user`, `developer`, and `assistant` messages. An image-only message now yields a message item instead of vanishing (G2). +- `system` messages still flatten into `instructions`; a non-text part in a system message is `400 unsupported_content_part`, because `instructions` is a string. +- A `tool` message stays a string `function_call_output`; non-text tool output is `400 unsupported_content_part`. +- An unknown part `type` is `400 unsupported_content_part` naming the type. It is never skipped. +- `content_text` is reduced to the `instructions` adapter and is no longer used on user content. + +**Exit:** the existing translation tests pass unchanged for text-only bodies; new tests cover each part type and the image-only message. + +### Stage 2 — Request fields and tools + +- Replace `PASSTHROUGH` with three exhaustive tables: `CARRIED` (same shape), `RENAMED` (`reasoning_effort`, `max_tokens`/`max_completion_tokens`), and `UNSUPPORTED` (a reason per field). Anything not in a table is `400 unsupported_parameter` naming the field, mirroring the upstream's own behaviour (G3). +- Carry `response_format`, `stream_options`, `n`, `stop`, `seed`, the penalties, and `modalities`/`audio` where the shape is already Responses-valid, and list the rest with a reason. +- `convert_tool` keeps converting `function` tools and passes every other Responses-native tool `type` through unchanged. An unrecognised `type` is carried so the upstream can judge it (G4). +- A Chat Completions request naming an image or audio generation tool is `400 image_requires_responses` / `400 audio_requires_responses`, before any upstream call. + +**Exit:** a table-driven test iterates every field and tool type in all three tables and proves each one either appears upstream or returns its named error. + +### Stage 3 — Non-streaming output projection + +- `responses_to_chat_completion` emits `content` as a string when the answer is text-only, and as a part array when it carries a refusal or another mapped part (G5). +- Map `refusal` to `{"type":"refusal","refusal":…}`. Reasoning and tool calls keep their current handling. +- An `image_generation_call` or audio item with no Chat equivalent returns `502` with a named code and the Responses id, so a client can retry natively. +- The Stage 2 request-time rejection means this branch should be unreachable for well-formed traffic; it exists so that the impossible case fails loudly rather than as `""`. + +**Exit:** a text-only answer is byte-shape identical to today; a refusal survives; unmappable output is an error and never an empty string. + +### Stage 4 — Streaming translation + +- Reuse the Stage 3 mapping inside `ResponsesToChatStream`; there is no second implementation (principle 3). +- Map `response.refusal.delta` and `response.refusal.done` into `delta.refusal` (G6). +- Track unmapped non-text events. On the terminal event, if nothing was emitted and unmapped non-text events were seen, emit a `finish_reason: "error"` chunk carrying the named error, then `[DONE]`. An empty stream is never the answer. + +**Exit:** refusals stream correctly; an unmappable stream fails loudly; existing stream tests are unchanged. + +### Stage 5 — Capability truthfulness + +- After Stage 1 the translated path can deliver images, so `input_modalities` stays in the catalogue. The invariant is enforced instead of assumed. +- Add a test that walks every provider spec and every model advertised with `image` and asserts the translator accepts an `image_url` part for that provider's shape (G7). A future regression that re-narrows the translator breaks the catalogue test rather than the user. +- Do not invent `output_modalities` fields the upstream does not publish. + +**Exit:** catalogue and translator cannot drift without a failing test. + +### Stage 6 — Native media routes (probe-gated) + +- Add `media_paths: &'static [MediaPath]` to `ProviderSpec` (`provider/mod.rs`), empty by default. A `MediaPath` is `{ method, path, response_types }` (G8). +- The router matches an enabled path exactly and dispatches to a new `src/server/media.rs`. It forwards verbatim through `send_with_auth`, holds an upstream slot for the life of the response, applies the configured timeouts, and returns the upstream body with its own `Content-Type`. It must not use `sse::stream`, which forces `text/event-stream` (`sse.rs`). +- Non-2xx answers reuse `upstream_error` so status, type, and code are preserved. +- Candidate entries, each enabled only after a probe: xAI `POST /v1/images/generations`, OpenAI `POST /v1/images/generations`. Audio, files, embeddings, and moderation stay out of scope until separately probed. +- Add `scripts/probe-media-endpoints.sh`: it runs the smallest valid request per candidate against a temporary `EGGPASS_HOME`, and records status and content type without printing any credential. A candidate that is not 2xx stays disabled, and the route remains a `404`. + +**Exit:** enabled routes forward byte-exactly and stream binary bodies with the right content type; disabled candidates still answer `404`; probe results are recorded in this plan. + +### Stage 7 — Limits and diagnostics + +- The `413` body names the limit and states that inline media counts toward it (G9). +- Add an optional `server.max_body_bytes`, clamped to a documented ceiling, defaulting to today's 32 MiB so behaviour does not change unless asked. +- A chat or Responses request with no readable `model` answers `400 missing_model` instead of falling through to the default provider (`config.rs:238`). Today a non-JSON body is forwarded to whichever provider is default, which hides the client's mistake. + +**Exit:** all three diagnostics are covered by tests and are actionable from the message alone. + +### Stage 8 — Tests and fixtures + +- Unit: each mapping row, the image-only message, an unknown part, a refusal, an unmappable output item, and an unmapped stream event with empty text. +- HTTP-level: an in-process stub upstream built with `UpstreamClient::for_endpoint` asserts the forwarded bytes for both provider shapes — transformed for ChatGPT, byte-identical for xAI. +- Fixtures: load the Stage 0 captures with `include_str!` so a provider shape change breaks a test rather than production (G10). +- Invariant: the Stage 5 catalogue/translator test. +- No fixture contains a real credential, prompt, or user image. + +**Exit:** `cargo test --workspace -- --test-threads=1` passes. + +### Stage 9 — Documentation + +- `docs/how-it-works.md`: what is translated, what is forwarded, and what is refused, stated per provider. +- `docs/troubleshooting.md`: `unsupported_content_part`, `unsupported_parameter`, `image_requires_responses`, `missing_model`. +- `CHANGELOG.md`: entries under Unreleased. + +## Implementation outcome + +| Gap | What changed | Where | +| --- | --- | --- | +| G1, G2 | A single parts module accepts a string or an array and maps text, image, audio, file, and refusal parts. An image-only message now yields a message item. | `src/server/parts.rs`; `translate.rs` message arms | +| G3 | Request fields are carried, renamed, mapped, stripped by provider policy, or refused by name. `response_format` becomes `text.format`; `n: 1` and `stream_options.include_usage` are no-ops; `stop`, `seed`, `n > 1`, logprobs, penalties, and unknown fields answer `unsupported_parameter`. | `translate.rs` field dispatch | +| G4 | Function tools still flatten; every other Responses-native tool is carried unchanged. Image and audio generation tools are refused over Chat Completions with `image_requires_responses` / `audio_requires_responses`. | `translate.rs` `convert_tool` | +| G5 | A text-only answer keeps the string `content`; a refusal produces an ordered part array. An image or audio output item answers `502 unmappable_output_item` instead of an empty answer. | `translate.rs` output projection | +| G6 | Refusal deltas stream as `delta.refusal`; the done copy is suppressed when deltas were seen. An unmappable stream with no chat content ends with a named error chunk and `[DONE]`. | `translate.rs` `ResponsesToChatStream` | +| G7 | A catalogue/translator invariant test accepts an `image_url` part for every advertised image model on every provider spec. | `translate.rs` tests | +| G8 | `MediaPath` is declared per provider; an enabled path is forwarded verbatim with the upstream's status, headers, and body, and its content type is checked against the spec. Dispatch runs only in the `NotFound` arm, so an undeclared path keeps the unchanged `404`. | `provider/mod.rs`; `server/media.rs`; `server/mod.rs` | +| G9 | `server.max_body_bytes` defaults to 32 MiB and clamps to 1–256 MiB. The `413` names the limit and the inline-media cause. | `config.rs`; `server/http.rs` | +| G10 | 473 tests pass, including documented-shape fixtures, HTTP-level byte-identity checks for both provider shapes, refusal projection, and the media route cases. | `server/tests.rs`; `tests/fixtures/media/` | + +Deviations from the letter of the plan: + +- **Stage 0 was not run.** No authorized live account was available. The fixtures are documented-shape, not captures, and `tests/fixtures/media/README.md` says so. The mapping is therefore tested at the proxy boundary, not against a live ChatGPT response. +- **Provider-rejected fields stay stripped, not refused.** `temperature`, `top_p`, `user`, `metadata`, and the rest of `openai::REJECTED_FIELDS` are provider policy: the live route rejects them, so passing them through fails the whole request. Refusing them would break every client that sends a default tuning value, contradicting the plan's own byte-compatibility requirement. The strip is commented in `translate.rs`; no other field is dropped. +- **No media route is enabled.** Both providers ship `media_paths: &[]`. The probe script is the manual step that would enable a candidate. +- **Media forwarding is POST-only.** A declared non-POST method answers `405` rather than being sent as POST. + +## Acceptance checklist + +Offline-verified with `cargo test --workspace -- --test-threads=1` (473 tests). Items that require a live account are left unchecked. + +- [x] A Chat Completions request carrying `image_url` reaches ChatGPT as `input_image`, with URL and `detail` preserved. +- [x] An image-only message survives translation; no message is dropped for lacking text. +- [x] `input_audio` and `file` parts are translated when a mechanical mapping exists, and rejected by name when one does not. +- [x] No request field or tool type is dropped silently; each is carried or refused with a named error. +- [x] A refusal reaches a non-streaming Chat client as a content part, not as an empty answer. +- [x] A refusal reaches a streaming Chat client as `delta.refusal`. +- [x] An unmappable answer or stream fails with a named error and is never empty content. +- [x] Text-only requests and responses are byte-compatible with the current behaviour. +- [x] xAI forwarding remains byte-identical for both endpoints. +- [x] Every model advertised with `image` is accepted by the translator for that provider. +- [ ] Each enabled media route is probe-confirmed; unconfirmed routes answer `404` and no route forces `text/event-stream` on a binary body. No route is enabled yet, and no live probe has run. +- [x] The `413` and `missing_model` diagnostics are specific and tested. +- [x] No credential, token, prompt, or real user media appears in fixtures, logs, or test output. + +## Validation + +```sh +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace -- --test-threads=1 +cargo build --locked --release +git diff --check +sh scripts/probe-media-endpoints.sh # Stage 6 only; requires a signed-in account +``` + +The probe script is the only step that needs live credentials. Every other check runs offline against fixtures and a stub upstream. + +## Risks and rollback + +- **Upstream shape drift.** Provider shapes change. Stage 0 captures plus `include_str!` fixtures turn drift into a test failure; the fail-loud rules keep an unmodelled change visible to the client instead of silent. +- **Client compatibility.** Emitting an array `content` where a string was returned would break naive clients. The text-only path keeps the string form; the array is used only when a non-text part exists. +- **Memory on large inline media.** Base64 bodies are fully buffered under the 32 MiB cap. The cap is documented and configurable, not raised by default. +- **A route that cannot serve the subscription.** A media route enabled without a probe ships a 403 to users. The probe gate is what prevents this; disabling a candidate is a one-line spec change. +- **Binary response mis-typing.** A media body returned through `sse::stream` would be labelled `text/event-stream` and mangled. Stage 6 uses `Response::stream` with the upstream's own headers, and a test asserts the type. +- **Rollback.** Stages 1–5 are local to translation and revert together. Stage 6 is disabled by setting `media_paths` to empty. Stage 7's body limit defaults to the current value, so it can ship independently. + +## Out of scope + +- Audio generation, transcription, and translation endpoints; file upload and lifecycle endpoints; embeddings; moderation. These are not probed here and stay unrouted. +- Changing provider OAuth custody or login, and the EggPool ticket/tunnel contract. +- Any real-credential integration test in CI. The probe is a manual, documented step. +- Commit, push, merge, release, or publication. + +## References + +- Translation: `src/server/translate.rs:18,168,192,340,612,809`; evaluation order: `src/server/chat.rs:53,325`. +- Aggregation: `src/server/aggregator.rs` (`aggregate_responses`). +- Routing and dispatch: `src/server/router.rs:29-46`; `src/server/mod.rs:429-482`. +- Transport: `src/server/http.rs:22,626`; `src/server/sse.rs`; `src/upstream.rs` (`send_with_auth`, `STRIPPED_HEADERS`, `normalize_target`). +- Providers: `src/provider/mod.rs` (`ProviderSpec`, `RequestPolicy`, `NativePaths`); `src/provider/xai.rs`; `src/provider/openai.rs:84-103`. +- Routing fallback: `src/config.rs:238` (`Routing::provider_for`). +- Tunnel contract: `docs/eggpool.md`. diff --git a/scripts/probe-media-endpoints.sh b/scripts/probe-media-endpoints.sh new file mode 100644 index 0000000..23e7dce --- /dev/null +++ b/scripts/probe-media-endpoints.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# +# Manually probe candidate image-generation routes through a running EggPass. +# +# Usage: +# EGGPASS_API_KEY=... scripts/probe-media-endpoints.sh +# EGGPASS_BASE_URL=http://127.0.0.1:8787 EGGPASS_API_KEY=... scripts/probe-media-endpoints.sh +# EGGPASS_XAI_MODEL=grok-2-image EGGPASS_OPENAI_MODEL=gpt-image-1 scripts/probe-media-endpoints.sh +# +# The server must be running with a signed-in account for each candidate. +# Optional model overrides: EGGPASS_XAI_MODEL and EGGPASS_OPENAI_MODEL. +# The script prints only each HTTP status and Content-Type, never the response +# body, response headers, or API key. A non-2xx result is not enabled. + +set -euo pipefail + +BASE_URL="${EGGPASS_BASE_URL:-http://127.0.0.1:8787}" +API_KEY="${EGGPASS_API_KEY:-}" +XAI_MODEL="${EGGPASS_XAI_MODEL:-grok-2-image}" +OPENAI_MODEL="${EGGPASS_OPENAI_MODEL:-gpt-image-1}" + +if [ -z "$API_KEY" ]; then + echo "EGGPASS_API_KEY is required" >&2 + exit 2 +fi + +if ! printf '%sX' "$API_KEY" | awk 'index($0, "\r") || NR > 1 { bad = 1 } END { exit bad }'; then + echo "EGGPASS_API_KEY must be a single-line value" >&2 + exit 2 +fi + +for model in "$XAI_MODEL" "$OPENAI_MODEL"; do + case "$model" in + ''|*[!A-Za-z0-9._-]*) echo "model overrides may contain only letters, digits, dot, underscore, and hyphen" >&2; exit 2 ;; + esac +done + +BASE_URL="${BASE_URL%/}" + +probe() { + candidate="$1" + model="$2" + url="$BASE_URL/v1/images/generations" + body="{\"model\":\"$model\",\"prompt\":\"a white 1x1 square\",\"n\":1,\"size\":\"1024x1024\"}" + + if result=$(printf '%s' "$API_KEY" \ + | sed 's/\\/\\\\/g; s/"/\\"/g' \ + | sed 's/^/header = "Authorization: Bearer /; s/$/"/' \ + | curl --config - --silent --output /dev/null --write-out '%{http_code}|%{content_type}' \ + --connect-timeout 5 --max-time 600 \ + --request POST --header 'Content-Type: application/json' \ + --data-binary "$body" "$url" 2>/dev/null); then + status="${result%%|*}" + content_type="${result#*|}" + else + status=000 + content_type= + fi + + case "$status" in + 2[0-9][0-9]) enabled=yes ;; + *) enabled=no ;; + esac + [ -n "$content_type" ] || content_type=- + printf '%-12s %-8s %-28s %s\n' "$candidate" "$status" "$content_type" "$enabled" +} + +printf '%-12s %-8s %-28s %s\n' CANDIDATE STATUS CONTENT_TYPE ENABLED +probe 'x.ai' "$XAI_MODEL" +probe 'OpenAI' "$OPENAI_MODEL" +printf '\nNon-2xx candidates stay disabled (media_paths: &[]).\n' diff --git a/src/config.rs b/src/config.rs index b85b332..cfede7c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -279,6 +279,8 @@ impl Default for Timeouts { pub struct ServerLimits { /// The largest number of simultaneous connections. pub max_connections: usize, + /// The largest request body, including inline media. + pub max_body_bytes: usize, /// How long a kept-alive connection may sit idle, in seconds. pub idle_timeout_seconds: u64, /// How long a single write may stall, in seconds. @@ -289,6 +291,7 @@ impl Default for ServerLimits { fn default() -> ServerLimits { ServerLimits { max_connections: crate::server::http::DEFAULT_MAX_CONNECTIONS, + max_body_bytes: crate::server::http::DEFAULT_MAX_BODY_BYTES, idle_timeout_seconds: crate::server::http::DEFAULT_IDLE_TIMEOUT.as_secs(), write_timeout_seconds: crate::server::http::DEFAULT_WRITE_TIMEOUT.as_secs(), } @@ -421,6 +424,8 @@ body_seconds = 1800 # The local server's limits. [server] max_connections = 256 +# Inline media counts toward this cap; the server clamps it to 1–256 MiB. +max_body_bytes = 33554432 idle_timeout_seconds = 120 write_timeout_seconds = 600 @@ -570,6 +575,7 @@ struct RawTimeouts { #[derive(Debug, Deserialize, Default)] struct RawServer { max_connections: Option, + max_body_bytes: Option, idle_timeout_seconds: Option, write_timeout_seconds: Option, } @@ -737,6 +743,13 @@ impl Config { if let Some(max) = server.max_connections { config.server.max_connections = max.max(1); } + if let Some(bytes) = server.max_body_bytes { + // A bad value must not disable the body bound or permit unbounded buffering. + config.server.max_body_bytes = bytes.clamp( + crate::server::http::MIN_BODY_LIMIT_BYTES as i64, + crate::server::http::MAX_BODY_CEILING_BYTES as i64, + ) as usize; + } if let Some(seconds) = server.idle_timeout_seconds { config.server.idle_timeout_seconds = seconds; } @@ -1463,6 +1476,54 @@ mod tests { assert_eq!(config.upstream, Upstream::Api); } + #[test] + fn the_body_limit_defaults_to_32_mib() { + let config = Config::parse("", Path::new("config.toml")).unwrap(); + assert_eq!(config.server.max_body_bytes, 32 * 1024 * 1024); + } + + #[test] + fn the_body_limit_is_configurable_and_clamped() { + let inside = Config::parse( + "[server]\nmax_body_bytes = 67108864\n", + Path::new("config.toml"), + ) + .unwrap(); + assert_eq!(inside.server.max_body_bytes, 64 * 1024 * 1024); + + for value in ["0", "-1"] { + let below = Config::parse( + &format!("[server]\nmax_body_bytes = {value}\n"), + Path::new("config.toml"), + ) + .unwrap(); + assert_eq!( + below.server.max_body_bytes, + crate::server::http::MIN_BODY_LIMIT_BYTES + ); + } + + let above = Config::parse( + "[server]\nmax_body_bytes = 268435457\n", + Path::new("config.toml"), + ) + .unwrap(); + assert_eq!( + above.server.max_body_bytes, + crate::server::http::MAX_BODY_CEILING_BYTES + ); + } + + #[test] + fn the_template_uses_the_default_body_limit_when_the_key_is_absent() { + let template_without_key = DEFAULT_CONFIG_TOML.replace("max_body_bytes = 33554432\n", ""); + let config = Config::parse(&template_without_key, Path::new("config.toml")).unwrap(); + assert_eq!( + config.server.max_body_bytes, + crate::server::http::DEFAULT_MAX_BODY_BYTES + ); + } + #[test] fn eggpool_defaults_disabled() { let config = Config::parse("", Path::new("config.toml")).unwrap(); diff --git a/src/eggpool.rs b/src/eggpool.rs index 3fc4728..5e65095 100644 --- a/src/eggpool.rs +++ b/src/eggpool.rs @@ -306,22 +306,15 @@ pub struct EnrollmentStore { path: PathBuf, ca_pem: Vec, server_name: String, - changed: Arc, lock: Mutex<()>, } impl EnrollmentStore { - pub(crate) fn new( - path: PathBuf, - ca_pem: Vec, - server_name: String, - changed: Arc, - ) -> Self { + pub(crate) fn new(path: PathBuf, ca_pem: Vec, server_name: String) -> Self { Self { path, ca_pem, server_name, - changed, lock: Mutex::new(()), } } @@ -390,7 +383,11 @@ impl EnrollmentStore { state.client_cert_pem = Some(std::mem::take(&mut bundle.client_cert_pem)); state.client_key_pem = Some(std::mem::take(&mut bundle.client_key_pem)); write_secrets(&self.path, &state)?; - self.changed.notify_one(); + // The supervisor is deliberately not woken here. Switching from the + // bootstrap tunnel to the mTLS one tears that tunnel down, and this + // callback's response still has to travel back through it. The + // supervisor observes the new pair on its next status tick instead, + // after the response has been written. Ok(()) } } @@ -528,7 +525,6 @@ pub fn start_runtime( secret_path.clone(), ca_pem, server_name.clone(), - Arc::clone(&changed), )); write_status(status_path.as_path(), settings, "starting"); let stop = Arc::new(AtomicBool::new(false)); @@ -641,6 +637,13 @@ async fn supervise_client( break; } _ = tick.tick() => { + // Enrollment completion is observed here, never from the + // callback handler: that response is travelling back + // through the tunnel this branch replaces. + if !has_pair && enrollment_pair_present(&secret_path) { + client.shutdown(); + break; + } if pending && state .expires_at @@ -942,6 +945,16 @@ fn valid_dns_host(host: &str) -> bool { }) } +/// Whether the private state has moved on from a pending enrollment to a +/// complete mTLS pair. The callback response is still in flight while the +/// handler runs, so the supervisor polls for this rather than being woken. +fn enrollment_pair_present(path: &Path) -> bool { + load_secrets(path) + .ok() + .flatten() + .is_some_and(|state| state.client_cert_pem.is_some() && state.client_key_pem.is_some()) +} + fn validate_server_name(server_name: &str) -> Result<(), String> { if server_name.is_empty() || server_name.len() > 253 @@ -1085,18 +1098,54 @@ mod tests { }; write_secrets(&path, &state).expect("write state"); state.enroll_token = None; - let store = EnrollmentStore::new( - path.clone(), - ca, - "eggpool.lan".to_string(), - Arc::new(Notify::new()), - ); + let store = EnrollmentStore::new(path.clone(), ca, "eggpool.lan".to_string()); assert!(store.authorizes("one-use")); let invalid = br#"{"client_cert_pem":"bad","client_key_pem":"bad"}"#; assert!(store.complete("one-use", invalid).is_err()); assert!(store.authorizes("one-use")); } + #[test] + fn the_mtls_switch_waits_for_a_complete_pair_on_disk() { + let directory = tempfile::tempdir().expect("temp dir"); + let path = directory.path().join("eggpool.json"); + assert!( + !enrollment_pair_present(&path), + "missing state must not switch the tunnel" + ); + + let mut state = EggpoolSecrets { + version: 1, + agent: "test-agent".to_string(), + api_key_id: 1, + ca_sha256: ca_digest(&pem(&[1, 2, 3, 4])).expect("pin"), + enroll_token: Some("one-use".to_string()), + expires_at: Some(crate::timeutil::now_unix() + 600), + client_cert_pem: None, + client_key_pem: None, + }; + write_secrets(&path, &state).expect("write pending state"); + assert!( + !enrollment_pair_present(&path), + "a pending enrollment stays on the bootstrap tunnel" + ); + + state.client_cert_pem = Some(String::from_utf8(pem(&[1, 2, 3, 4])).expect("pem text")); + write_secrets(&path, &state).expect("write half pair"); + assert!( + !enrollment_pair_present(&path), + "a half-written pair must not switch the tunnel" + ); + + state.client_key_pem = + Some("-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----\n".to_string()); + write_secrets(&path, &state).expect("write complete pair"); + assert!( + enrollment_pair_present(&path), + "the completed pair switches the tunnel" + ); + } + #[test] fn bearer_parser_accepts_only_a_single_bearer_value() { assert_eq!(enrollment_bearer(Some("Bearer abc123")), Some("abc123")); diff --git a/src/provider/mod.rs b/src/provider/mod.rs index 41f3b1a..a81c5fe 100644 --- a/src/provider/mod.rs +++ b/src/provider/mod.rs @@ -92,6 +92,26 @@ pub enum NativePaths { ResponsesOnly, } +/// An endpoint a provider serves outside the two inference paths. +/// +/// Media endpoints are declared by the provider because whether a subscription +/// may call one is the provider's call, not ours. The list is empty until the +/// endpoint has been confirmed against a live account; an entry that has not +/// been probed would ship a route that answers `403` to users. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MediaPath { + /// The HTTP method the endpoint takes. + pub method: &'static str, + /// The path, including the `/v1` prefix. + pub path: &'static str, + /// The content types the endpoint answers with. + /// + /// A response outside this list is a shape the proxy does not understand, + /// so it is refused rather than streamed to the client under a wrong + /// `Content-Type`. + pub response_types: &'static [&'static str], +} + /// What a provider demands of a request body. #[derive(Debug, Clone, Copy, Default)] pub struct RequestPolicy { @@ -167,6 +187,8 @@ pub struct ProviderSpec { pub catalogue: CatalogueKind, /// Which inference paths the provider serves natively. pub native_paths: NativePaths, + /// Native media endpoints, empty until each one is probe-confirmed. + pub media_paths: &'static [MediaPath], } impl ProviderSpec { diff --git a/src/provider/openai.rs b/src/provider/openai.rs index 8fe6a4f..149df96 100644 --- a/src/provider/openai.rs +++ b/src/provider/openai.rs @@ -195,6 +195,10 @@ pub fn spec(config: &crate::config::Config) -> ProviderSpec { trusted_device_hosts: &[], catalogue: CatalogueKind::SlugArray, native_paths: NativePaths::ResponsesOnly, + // Candidate: `POST /v1/images/generations`. It is enabled only after + // `scripts/probe-media-endpoints.sh` confirms the subscription serves + // it; until then the route stays a `404`. + media_paths: &[], } } diff --git a/src/provider/xai.rs b/src/provider/xai.rs index 134d48d..9f7b1a9 100644 --- a/src/provider/xai.rs +++ b/src/provider/xai.rs @@ -98,6 +98,10 @@ pub fn spec(config: &crate::config::Config) -> ProviderSpec { trusted_device_hosts: &["accounts.x.ai", "auth.x.ai", "x.ai"], catalogue: CatalogueKind::DataArray, native_paths: NativePaths::Both, + // Candidate: `POST /v1/images/generations`. It is enabled only after + // `scripts/probe-media-endpoints.sh` confirms the subscription serves + // it; until then the route stays a `404`. + media_paths: &[], } } diff --git a/src/server/chat.rs b/src/server/chat.rs index f25001d..6e65e91 100644 --- a/src/server/chat.rs +++ b/src/server/chat.rs @@ -30,6 +30,9 @@ use super::{ /// Handle `POST /v1/chat/completions` and `POST /v1/responses`. pub fn complete(request: &Request, context: &ServerContext) -> Response { let model = extract_model(&request.body); + if model.is_empty() { + return missing_model_error(); + } // Which provider serves this model? let provider_id = context.provider_for(&model); @@ -70,7 +73,12 @@ pub fn complete(request: &Request, context: &ServerContext) -> Response { match translate::chat_request_to_responses(&request.body) { Ok(body) => body, Err(err) => { - return openai_error(400, &err, "invalid_request_error"); + return openai_error_with_code( + 400, + err.message(), + "invalid_request_error", + Some(err.code()), + ); } } }; @@ -200,7 +208,12 @@ pub fn complete(request: &Request, context: &ServerContext) -> Response { Ok(bytes) => bytes, Err(err) => { context.record_inference(provider_id, 502); - return openai_error(502, &err, "server_error"); + return openai_error_with_code( + 502, + err.message(), + "server_error", + Some(err.code()), + ); } } }; @@ -254,7 +267,12 @@ pub fn complete(request: &Request, context: &ServerContext) -> Response { Ok(bytes) => bytes, Err(err) => { context.record_inference(provider_id, 502); - return openai_error(502, &err, "server_error"); + return openai_error_with_code( + 502, + err.message(), + "server_error", + Some(err.code()), + ); } } }; @@ -271,7 +289,7 @@ pub fn complete(request: &Request, context: &ServerContext) -> Response { /// model the provider does not serve has to be told exactly that — a blanket /// "server error" hides both the reason and the status, and turns a request /// that cannot succeed into something that looks worth retrying. -fn upstream_error(status: u16, body: &[u8]) -> Response { +pub(crate) fn upstream_error(status: u16, body: &[u8]) -> Response { let parsed: Option = serde_json::from_slice(body).ok(); let error = parsed.as_ref().and_then(|value| value.get("error")); @@ -362,6 +380,16 @@ fn apply_policy(body: &[u8], policy: &crate::provider::RequestPolicy) -> Vec serde_json::to_vec(&value).unwrap_or_else(|_| body.to_vec()) } +/// Answer before provider routing when the caller omitted a usable model. +fn missing_model_error() -> Response { + openai_error_with_code( + 400, + "the request body must be a JSON object with a model string", + "invalid_request_error", + Some("missing_model"), + ) +} + /// The model a request names. fn extract_model(body: &[u8]) -> String { serde_json::from_slice::(body) @@ -409,13 +437,16 @@ pub fn forwarded_headers(headers: &[(String, String)]) -> Vec<(String, String)> /// /// The slot has to be held for as long as the stream is running: a request /// that is still streaming is still in flight. -struct ReleasingStream { +pub(crate) struct ReleasingStream { inner: Box, counter: Option>, } impl ReleasingStream { - fn new(inner: Box, counter: Arc) -> ReleasingStream { + pub(crate) fn new( + inner: Box, + counter: Arc, + ) -> ReleasingStream { ReleasingStream { inner, counter: Some(counter), @@ -565,4 +596,30 @@ mod tests { let body = br#"{"model":"grok-4.7","temperature":0.7}"#; assert_eq!(apply_policy(body, &policy), body); } + #[test] + fn an_unmappable_output_is_a_502_with_its_translation_code() { + let fixture = include_str!("../../tests/fixtures/media/responses-image-generation.json"); + let error = translate::responses_to_chat_completion(fixture.as_bytes()).unwrap_err(); + let response = + openai_error_with_code(502, error.message(), "server_error", Some(error.code())); + assert_eq!(response.status, 502); + let value: Value = serde_json::from_slice(body_bytes(&response)).unwrap(); + assert_eq!(value["error"]["type"], "server_error"); + assert_eq!(value["error"]["code"], "unmappable_output_item"); + } + + #[test] + fn a_missing_model_is_a_named_bad_request() { + let response = missing_model_error(); + assert_eq!(response.status, 400); + let value: Value = serde_json::from_slice(body_bytes(&response)).unwrap(); + assert_eq!(value["error"]["type"], "invalid_request_error"); + assert_eq!(value["error"]["code"], "missing_model"); + assert!( + value["error"]["message"] + .as_str() + .unwrap() + .contains("JSON object with a model string") + ); + } } diff --git a/src/server/http.rs b/src/server/http.rs index 1212207..5aa5bda 100644 --- a/src/server/http.rs +++ b/src/server/http.rs @@ -18,8 +18,14 @@ use std::time::{Duration, Instant}; /// The largest request head we accept. const MAX_HEAD_BYTES: usize = 64 * 1024; -/// The largest request body we accept. -const MAX_BODY_BYTES: usize = 32 * 1024 * 1024; +/// The request-body cap used by default, including inline media. +pub const DEFAULT_MAX_BODY_BYTES: usize = 32 * 1024 * 1024; + +/// The smallest useful request-body cap, so a bad value cannot disable the bound. +pub const MIN_BODY_LIMIT_BYTES: usize = 1024 * 1024; + +/// The ceiling keeps a configured cap from permitting unbounded buffering. +pub const MAX_BODY_CEILING_BYTES: usize = 256 * 1024 * 1024; /// The largest chunk-size, trailer, or chunk-ending line we retain. /// @@ -157,6 +163,8 @@ pub struct HttpServer { active: Arc, /// The largest number of simultaneous connections. max_connections: usize, + /// The largest request body, including inline media. + max_body_bytes: usize, /// How long a kept-alive connection may sit idle. idle_timeout: Duration, /// How long a single write may stall. @@ -171,6 +179,7 @@ impl HttpServer { listener, active: Arc::new(AtomicUsize::new(0)), max_connections: DEFAULT_MAX_CONNECTIONS, + max_body_bytes: DEFAULT_MAX_BODY_BYTES, idle_timeout: DEFAULT_IDLE_TIMEOUT, write_timeout: DEFAULT_WRITE_TIMEOUT, }) @@ -189,6 +198,12 @@ impl HttpServer { self } + /// Set the body cap without permitting a low or unbounded value. + pub fn with_max_body_bytes(mut self, max_body_bytes: usize) -> HttpServer { + self.max_body_bytes = max_body_bytes.clamp(MIN_BODY_LIMIT_BYTES, MAX_BODY_CEILING_BYTES); + self + } + /// The address the server listens on. pub fn local_addr(&self) -> std::io::Result { self.listener.local_addr() @@ -236,8 +251,16 @@ impl HttpServer { let active = Arc::clone(&self.active); let idle_timeout = self.idle_timeout; let write_timeout = self.write_timeout; + let max_body_bytes = self.max_body_bytes; std::thread::spawn(move || { - let _ = handle_connection(stream, gate, handler, idle_timeout, write_timeout); + let _ = handle_connection( + stream, + gate, + handler, + idle_timeout, + write_timeout, + max_body_bytes, + ); // The count drops only now: the response body has been // written, so a stream that was cut short by a shutdown was // still counted as in flight. @@ -278,6 +301,7 @@ fn handle_connection( handler: Handler, idle_timeout: Duration, write_timeout: Duration, + max_body_bytes: usize, ) -> std::io::Result<()> { // Small responses should go out immediately. let _ = stream.set_nodelay(true); @@ -291,7 +315,7 @@ fn handle_connection( // is closed rather than holding a thread forever. let _ = writer.set_read_timeout(Some(idle_timeout)); - let request = match read_request(&mut reader, &mut writer, gate.as_ref()) { + let request = match read_request(&mut reader, &mut writer, gate.as_ref(), max_body_bytes) { Ok(Some(request)) => request, Ok(None) => return Ok(()), Err(err) if is_idle_timeout(&err) => return Ok(()), @@ -434,7 +458,7 @@ impl Read for SocketReader { enum BodyError { /// The connection ended or the framing was malformed. Io(std::io::Error), - /// The body is larger than [`MAX_BODY_BYTES`]. + /// The body is larger than the configured cap. TooLarge, /// A chunked line exceeded [`MAX_LINE_BYTES`]. Malformed, @@ -459,6 +483,7 @@ fn read_request( reader: &mut SocketReader, writer: &mut TcpStream, gate: &dyn Fn(&Request) -> GateDecision, + max_body_bytes: usize, ) -> std::io::Result> { let Some(head) = read_head(reader)? else { return Ok(None); @@ -470,17 +495,17 @@ fn read_request( GateDecision::Refuse(refusal) => { write_response(writer, refusal, false)?; if !expects_continue(&request.headers) { - let _ = read_body(reader, writer, &request.headers, false); + let _ = read_body(reader, writer, &request.headers, false, max_body_bytes); } return Ok(None); } GateDecision::Proceed { keep_body } => keep_body, }; - match read_body(reader, writer, &request.headers, keep_body) { + match read_body(reader, writer, &request.headers, keep_body, max_body_bytes) { Ok(body) => Ok(Some(Request { body, ..request })), Err(BodyError::TooLarge) => { - write_response(writer, payload_too_large(), false)?; + write_response(writer, payload_too_large(max_body_bytes), false)?; Ok(None) } Err(BodyError::Malformed) => { @@ -537,12 +562,12 @@ fn malformed_body() -> Response { } /// The `413` body for a request that is too large. -fn payload_too_large() -> Response { - let limit = MAX_BODY_BYTES / (1024 * 1024); +fn payload_too_large(limit: usize) -> Response { + let mib = limit / (1024 * 1024); Response::json( 413, format!( - r#"{{"error":{{"message":"the request body is larger than {limit} MiB","type":"invalid_request_error","code":"body_too_large"}}}}"# + r#"{{"error":{{"message":"the request body is larger than {limit} bytes ({mib} MiB); inline media such as base64 images, audio, and files counts toward this limit. Raise `server.max_body_bytes` in the configuration to allow more.","type":"invalid_request_error","code":"body_too_large"}}}}"# ), ) } @@ -599,6 +624,7 @@ fn read_body( writer: &mut TcpStream, headers: &[(String, String)], keep: bool, + max_body_bytes: usize, ) -> Result, BodyError> { let lookup = |name: &str| { headers @@ -615,7 +641,7 @@ fn read_body( if let Some(encoding) = lookup("transfer-encoding") && encoding.to_ascii_lowercase().contains("chunked") { - return read_chunked_body(reader, keep); + return read_chunked_body(reader, keep, max_body_bytes); } let Some(length) = lookup("content-length").and_then(|value| value.parse::().ok()) @@ -623,7 +649,7 @@ fn read_body( return Ok(Vec::new()); }; - if length > MAX_BODY_BYTES { + if length > max_body_bytes { return Err(BodyError::TooLarge); } @@ -650,7 +676,11 @@ fn discard(reader: &mut SocketReader, length: usize) -> std::io::Result<()> { } /// Read a chunked request body. -fn read_chunked_body(reader: &mut SocketReader, keep: bool) -> Result, BodyError> { +fn read_chunked_body( + reader: &mut SocketReader, + keep: bool, + max_body_bytes: usize, +) -> Result, BodyError> { let mut body = Vec::new(); loop { @@ -674,11 +704,9 @@ fn read_chunked_body(reader: &mut SocketReader, keep: bool) -> Result, B return Ok(body); } - // Bound the size before using it. `MAX_BODY_BYTES - size` cannot - // underflow once `size` is known to fit, so a chunk header of - // `ffffffffffffffff` is refused instead of wrapping the sum into a - // huge allocation. - if size > MAX_BODY_BYTES || body.len() > MAX_BODY_BYTES - size { + // Bound the size before using it. Subtraction follows the first + // check, so a huge chunk header cannot wrap into an allocation. + if size > max_body_bytes || body.len() > max_body_bytes - size { return Err(BodyError::TooLarge); } @@ -827,6 +855,62 @@ fn http_date() -> String { mod tests { use super::*; + fn tcp_pair() -> (TcpStream, TcpStream) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let server = listener.accept().unwrap().0; + (client, server) + } + + #[test] + fn an_oversized_body_error_names_the_configured_inline_media_limit() { + let response = payload_too_large(64 * 1024 * 1024); + assert_eq!(response.status, 413); + let Body::Bytes(body) = response.body else { + panic!("the 413 diagnostic is a complete response"); + }; + let body = String::from_utf8(body).unwrap(); + assert!( + body.contains("the request body is larger than 67108864 bytes (64 MiB)"), + "{body}" + ); + assert!( + body.contains( + "inline media such as base64 images, audio, and files counts toward this limit" + ), + "{body}" + ); + assert!( + body.contains("Raise `server.max_body_bytes` in the configuration to allow more."), + "{body}" + ); + assert!(body.contains("body_too_large"), "{body}"); + } + + #[test] + fn content_length_checks_use_the_configured_limit() { + let (mut writer, server) = tcp_pair(); + let mut reader = SocketReader::new(server); + let error = read_body( + &mut reader, + &mut writer, + &[("content-length".to_string(), "9".to_string())], + true, + 8, + ) + .unwrap_err(); + assert!(matches!(error, BodyError::TooLarge)); + } + + #[test] + fn chunked_checks_use_the_configured_limit() { + let (mut client, server) = tcp_pair(); + client.write_all(b"9\r\n").unwrap(); + let mut reader = SocketReader::new(server); + let error = read_chunked_body(&mut reader, true, 8).unwrap_err(); + assert!(matches!(error, BodyError::TooLarge)); + } + #[test] fn reason_phrases_cover_the_codes_we_use() { assert_eq!(reason_phrase(200), "OK"); diff --git a/src/server/media.rs b/src/server/media.rs new file mode 100644 index 0000000..7ed0b9a --- /dev/null +++ b/src/server/media.rs @@ -0,0 +1,236 @@ +//! Native media endpoints that are not inference. +//! +//! A provider declares the media paths it serves in its spec. A path is +//! forwarded verbatim, with the upstream's own status, headers, and body, and +//! is enabled only after a live probe has confirmed it. + +use serde_json::Value; + +use crate::provider::MediaPath; +use crate::upstream::{self, Method, UpstreamError}; + +use super::{ + Request, Response, ServerContext, chat::ReleasingStream, openai_error, openai_error_with_code, +}; + +/// Handle a native media path, or leave an unrelated path to the normal 404. +/// +/// Only POST candidates are currently supported; another declared method is +/// refused with 405 rather than being forwarded as POST. +pub fn handle(request: &Request, context: &ServerContext) -> Option { + let path = upstream::normalize_path(request.path()); + let declared_anywhere = context.providers.values().any(|handle| { + handle + .spec + .media_paths + .iter() + .any(|route| upstream::normalize_path(route.path) == path) + }); + if !declared_anywhere { + return None; + } + + let model = serde_json::from_slice::(&request.body) + .ok() + .and_then(|value| { + value + .get("model") + .and_then(Value::as_str) + .map(str::to_string) + }); + let Some(model) = model else { + return Some(openai_error_with_code( + 400, + "the body must be a JSON object with a model string", + "invalid_request_error", + Some("missing_model"), + )); + }; + + let provider_id = context.provider_for(&model); + let Some(handle) = context.providers.get(&provider_id) else { + return Some(openai_error( + 404, + &format!("no provider is signed in for model {model}"), + "invalid_request_error", + )); + }; + + let route = match match_media_path(handle.spec.media_paths, &path, &request.method) { + MediaRoute::NotFound => return None, + MediaRoute::MethodNotAllowed(allowed) => { + return Some(super::method_not_allowed(&request.method, &allowed)); + } + MediaRoute::Found(route) if route.method == "POST" => route, + MediaRoute::Found(_route) => { + // Only POST candidates are currently supported by send_with_auth's + // request-body forwarding path. Do not accidentally forward another + // declared method as POST. + return Some(super::method_not_allowed(&request.method, "POST")); + } + }; + + let (_, query) = upstream::normalize_target(&request.target); + let target = upstream::build_path(&path, &query); + if !context.take_upstream_slot() { + return Some(openai_error( + 503, + "too many requests are in flight; try again in a moment", + "server_error", + )); + } + + let mut response = match upstream::send_with_auth( + &handle.upstream, + handle.tokens.as_ref(), + Method::Post, + &target, + &upstream::sanitize_headers(&request.headers), + Some(&request.body), + ) { + Ok(response) => response, + Err(UpstreamError::Token(err)) => { + context.release_upstream_slot(); + context.record_inference(provider_id, 401); + return Some(openai_error( + 401, + &format!("{}: {err}", handle.spec.display_name), + "invalid_request_error", + )); + } + Err(err) => { + context.release_upstream_slot(); + context.record_inference(provider_id, 502); + return Some(openai_error(502, &err.to_string(), "server_error")); + } + }; + + let status = response.status; + if !(200..300).contains(&status) { + let bytes = match response.read_to_vec() { + Ok(bytes) => bytes, + Err(err) => { + context.release_upstream_slot(); + context.record_inference(provider_id, 502); + return Some(openai_error( + 502, + &format!("could not read the upstream response: {err}"), + "server_error", + )); + } + }; + context.release_upstream_slot(); + let response = super::chat::upstream_error(status, &bytes); + context.record_inference(provider_id, response.status); + return Some(response); + } + + let content_type = response.header("Content-Type").map(str::to_string); + if !valid_content_type(route.response_types, content_type.as_deref()) { + context.release_upstream_slot(); + context.record_inference(provider_id, 502); + let arrived = content_type.as_deref().unwrap_or("missing"); + let expected = if route.response_types.is_empty() { + "a Content-Type header (no type allowlist configured)".to_string() + } else { + route.response_types.join(", ") + }; + return Some(openai_error_with_code( + 502, + &format!("unexpected upstream Content-Type {arrived}; expected one of: {expected}"), + "server_error", + Some("unexpected_media_content_type"), + )); + } + + let headers = super::forwarded_headers(&response.headers); + let body = ReleasingStream::new(response.body, context.upstream_in_flight.clone()); + context.record_inference(provider_id, status); + Some(Response::stream(status, headers, Box::new(body))) +} + +#[derive(Debug, PartialEq, Eq)] +enum MediaRoute<'a> { + NotFound, + MethodNotAllowed(String), + Found(&'a MediaPath), +} + +/// Match a normalized path and the exact method declared by the provider. +fn match_media_path<'a>(media_paths: &'a [MediaPath], path: &str, method: &str) -> MediaRoute<'a> { + let mut allowed = Vec::new(); + for route in media_paths + .iter() + .filter(|route| upstream::normalize_path(route.path) == path) + { + if route.method == method { + return MediaRoute::Found(route); + } + if !allowed.contains(&route.method) { + allowed.push(route.method); + } + } + + if allowed.is_empty() { + MediaRoute::NotFound + } else { + MediaRoute::MethodNotAllowed(allowed.join(", ")) + } +} + +/// Check the upstream's media type, ignoring optional parameters such as charset. +fn valid_content_type(response_types: &[&str], content_type: Option<&str>) -> bool { + let Some(content_type) = content_type else { + return false; + }; + if response_types.is_empty() { + return true; + } + + let media_type = content_type.split(';').next().unwrap_or_default().trim(); + response_types + .iter() + .any(|expected| media_type.eq_ignore_ascii_case(expected)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const MEDIA_PATHS: &[MediaPath] = &[MediaPath { + method: "POST", + path: "/v1/images/generations", + response_types: &["application/json"], + }]; + + #[test] + fn matching_normalizes_paths_and_requires_the_exact_method() { + assert_eq!( + match_media_path(MEDIA_PATHS, "/v1/images/generations", "POST"), + MediaRoute::Found(&MEDIA_PATHS[0]), + ); + assert_eq!( + match_media_path(MEDIA_PATHS, "/v1/images/generations", "GET"), + MediaRoute::MethodNotAllowed("POST".to_string()), + ); + assert_eq!( + match_media_path(MEDIA_PATHS, "/v1/images/edits", "POST"), + MediaRoute::NotFound, + ); + } + + #[test] + fn content_type_allowlist_checks_the_type_before_parameters() { + assert!(valid_content_type( + &["application/json"], + Some("application/json; charset=utf-8"), + )); + assert!(!valid_content_type( + &["application/json"], + Some("image/png"), + )); + assert!(!valid_content_type(&["application/json"], None)); + assert!(valid_content_type(&[], Some("image/png"))); + assert!(!valid_content_type(&[], None)); + } +} diff --git a/src/server/mod.rs b/src/server/mod.rs index 67556cf..d87eea2 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -11,7 +11,9 @@ pub mod guard; pub mod health; pub mod http; pub mod inference; +pub mod media; pub mod models; +pub mod parts; pub mod router; pub mod sse; pub mod translate; @@ -191,7 +193,8 @@ impl Server { limits.max_connections, Duration::from_secs(limits.idle_timeout_seconds), Duration::from_secs(limits.write_timeout_seconds), - ); + ) + .with_max_body_bytes(limits.max_body_bytes); Ok(Arc::new(Server { http: Arc::new(http), @@ -476,11 +479,13 @@ fn handle_request(mut request: Request, context: &ServerContext) -> Response { "POST" => chat::complete(&request, context), _ => method_not_allowed(method, "POST"), }, - router::Route::NotFound => openai_error( - 404, - &format!("unknown endpoint `{path}`"), - "invalid_request_error", - ), + router::Route::NotFound => media::handle(&request, context).unwrap_or_else(|| { + openai_error( + 404, + &format!("unknown endpoint `{path}`"), + "invalid_request_error", + ) + }), } } @@ -764,7 +769,6 @@ mod authorisation_tests { state_path, Vec::new(), "pool.example".to_string(), - Arc::new(tokio::sync::Notify::new()), )); let mut context = context_with_key(""); context.eggpool_enrollment = Some(store); diff --git a/src/server/parts.rs b/src/server/parts.rs new file mode 100644 index 0000000..e782400 --- /dev/null +++ b/src/server/parts.rs @@ -0,0 +1,271 @@ +//! Chat Completions content parts, in the Responses shape. +//! +//! This module is the only place a content part's shape is understood. + +use super::translate::TranslateError; +use serde_json::{Value, json}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Role { + User, + Developer, + Assistant, + System, +} + +/// Accept a string or part array so content is not flattened before routing. +/// Unsupported content shapes return `unsupported_content_part`. +pub fn parse_chat_content(content: Option<&Value>) -> Result, TranslateError> { + let Some(content) = content else { + return Ok(Vec::new()); + }; + match content { + Value::Null => Ok(Vec::new()), + Value::String(text) => Ok(vec![json!({"type":"text", "text":text})]), + Value::Array(parts) => parts.iter().map(parse_part).collect(), + other => Err(TranslateError::new( + "unsupported_content_part", + format!( + "content must be a string or array, got {}", + value_kind(other) + ), + )), + } +} + +fn parse_part(part: &Value) -> Result { + if let Some(text) = part.as_str() { + return Ok(json!({"type":"text", "text":text})); + } + let Some(object) = part.as_object() else { + return Err(unsupported_part("typeless")); + }; + if object.get("type").and_then(Value::as_str).is_none() { + return Err(unsupported_part("typeless")); + } + Ok(part.clone()) +} + +/// Preserve each supported part in the role-specific Responses shape. +/// Parts without a faithful mapping return `unsupported_content_part`. +pub fn to_responses_parts( + role: Role, + content: Option<&Value>, +) -> Result, TranslateError> { + let text_type = if role == Role::Assistant { + "output_text" + } else { + "input_text" + }; + parse_chat_content(content)? + .iter() + .map(|part| { + let kind = part + .get("type") + .and_then(Value::as_str) + .unwrap_or("typeless"); + match kind { + "text" => { + let text = part + .get("text") + .and_then(Value::as_str) + .ok_or_else(|| unsupported_part("text (missing string text)"))?; + Ok(json!({"type":text_type,"text":text})) + } + "image_url" => { + let image = part + .get("image_url") + .ok_or_else(|| unsupported_part("image_url (missing image_url)"))?; + let (url, detail) = match image { + Value::String(url) => (url.clone(), part.get("detail").cloned()), + Value::Object(image) => { + let url = image + .get("url") + .and_then(Value::as_str) + .ok_or_else(|| unsupported_part("image_url (missing string url)"))? + .to_string(); + let detail = + part.get("detail").or_else(|| image.get("detail")).cloned(); + (url, detail) + } + _ => return Err(unsupported_part("image_url (invalid shape)")), + }; + let mut converted = json!({"type":"input_image", "image_url":url}); + if let Some(detail) = detail { + converted["detail"] = detail; + } + Ok(converted) + } + "input_image" | "input_audio" | "input_file" => Ok(part.clone()), + "file" => { + let file = part + .get("file") + .and_then(Value::as_object) + .ok_or_else(|| unsupported_part("file (missing file object)"))?; + let mut converted = json!({"type":"input_file"}); + if let Some(file_id) = file.get("file_id") { + converted["file_id"] = file_id.clone(); + } else if let (Some(filename), Some(file_data)) = + (file.get("filename"), file.get("file_data")) + { + converted["filename"] = filename.clone(); + converted["file_data"] = file_data.clone(); + } else { + return Err(unsupported_part( + "file (requires file_id or filename and file_data)", + )); + } + Ok(converted) + } + "refusal" if role == Role::Assistant => { + let refusal = part + .get("refusal") + .and_then(Value::as_str) + .ok_or_else(|| unsupported_part("refusal (missing string refusal)"))?; + Ok(json!({"type":"refusal", "refusal":refusal})) + } + other => Err(unsupported_part(other)), + } + }) + .collect() +} + +/// Flatten text-only system or tool content where Responses needs a string. +/// Any non-text part returns `unsupported_content_part`. +pub fn content_text(content: Option<&Value>) -> Result, TranslateError> { + let parts = to_responses_parts(Role::System, content)?; + let mut text = Vec::with_capacity(parts.len()); + for part in parts { + if part.get("type").and_then(Value::as_str) != Some("input_text") { + let kind = part + .get("type") + .and_then(Value::as_str) + .unwrap_or("typeless"); + return Err(unsupported_part(kind)); + } + text.push( + part.get("text") + .and_then(Value::as_str) + .ok_or_else(|| unsupported_part("text (missing string text)"))? + .to_string(), + ); + } + if text.is_empty() { + Ok(None) + } else { + Ok(Some(text.join("\n"))) + } +} + +fn unsupported_part(kind: &str) -> TranslateError { + TranslateError::new( + "unsupported_content_part", + format!("unsupported content part type {kind}"), + ) +} + +fn value_kind(value: &Value) -> &'static str { + match value { + Value::Bool(_) => "boolean", + Value::Number(_) => "number", + Value::Object(_) => "object", + Value::Array(_) => "array", + Value::Null => "null", + Value::String(_) => "string", + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn string_content_becomes_a_text_part() { + assert_eq!( + to_responses_parts(Role::User, Some(&json!("hello"))).unwrap(), + vec![json!({"type":"input_text","text":"hello"})] + ); + } + #[test] + fn image_only_content_is_preserved() { + let content = json!([{"type":"image_url","image_url":{"url":"https://example.invalid/image.png","detail":"high"}}]); + assert_eq!( + to_responses_parts(Role::User, Some(&content)).unwrap(), + vec![ + json!({"type":"input_image","image_url":"https://example.invalid/image.png","detail":"high"}) + ] + ); + } + #[test] + fn file_and_audio_parts_are_preserved() { + let file = json!([{"type":"file","file":{"filename":"doc.pdf","file_data":"data:application/pdf;base64,AA=="}}]); + assert_eq!( + to_responses_parts(Role::User, Some(&file)).unwrap()[0], + json!({"type":"input_file","filename":"doc.pdf","file_data":"data:application/pdf;base64,AA=="}) + ); + let audio = json!([{"type":"input_audio","input_audio":{"data":"AA==","format":"wav"}}]); + assert_eq!( + to_responses_parts(Role::User, Some(&audio)).unwrap()[0], + audio[0] + ); + } + #[test] + fn unknown_types_are_named() { + let error = to_responses_parts(Role::User, Some(&json!([{"type":"video"}]))).unwrap_err(); + assert_eq!(error.code(), "unsupported_content_part"); + assert!(error.message().contains("video")); + } + #[test] + fn image_string_detail_and_responses_image_are_carried() { + let from_chat = json!([{"type":"image_url","image_url":"https://example.invalid/img.png","detail":"low"}]); + assert_eq!( + to_responses_parts(Role::User, Some(&from_chat)).unwrap()[0], + json!({"type":"input_image","image_url":"https://example.invalid/img.png","detail":"low"}) + ); + let native = json!([{"type":"input_image","image_url":"https://example.invalid/native.png","detail":"auto"}]); + assert_eq!( + to_responses_parts(Role::User, Some(&native)).unwrap(), + native.as_array().unwrap().clone() + ); + } + + #[test] + fn file_id_assistant_refusal_and_responses_file_are_mapped() { + let file = json!([{"type":"file","file":{"file_id":"file_fixture"}}]); + assert_eq!( + to_responses_parts(Role::User, Some(&file)).unwrap()[0], + json!({"type":"input_file","file_id":"file_fixture"}) + ); + let input_file = json!([{"type":"input_file","file_id":"file_fixture"}]); + assert_eq!( + to_responses_parts(Role::User, Some(&input_file)).unwrap(), + input_file.as_array().unwrap().clone() + ); + let refusal = json!([{"type":"refusal","refusal":"No."}]); + assert_eq!( + to_responses_parts(Role::Assistant, Some(&refusal)).unwrap()[0], + refusal[0] + ); + assert_eq!( + to_responses_parts(Role::Developer, Some(&json!("directive"))).unwrap()[0]["type"], + "input_text" + ); + assert_eq!( + to_responses_parts(Role::Assistant, Some(&json!("reply"))).unwrap()[0]["type"], + "output_text" + ); + } + + #[test] + fn text_content_can_be_flattened_but_images_cannot() { + let text = json!(["first", {"type":"text","text":"second"}]); + assert_eq!( + content_text(Some(&text)).unwrap().as_deref(), + Some("first\nsecond") + ); + let image = json!([{"type":"input_image"}]); + assert_eq!( + content_text(Some(&image)).unwrap_err().code(), + "unsupported_content_part" + ); + } +} diff --git a/src/server/tests.rs b/src/server/tests.rs index a2c1a38..9c4ac55 100644 --- a/src/server/tests.rs +++ b/src/server/tests.rs @@ -21,7 +21,9 @@ use crate::auth::refresh::TokenManager; use crate::auth::store::StoredAuth; use crate::config::Routing; use crate::paths::Paths; -use crate::provider::{CatalogueKind, NativePaths, ProviderId, ProviderSpec, RequestPolicy}; +use crate::provider::{ + CatalogueKind, MediaPath, NativePaths, ProviderId, ProviderSpec, RequestPolicy, +}; use crate::server::{ProviderHandle, Server, ServerContext}; use crate::timeutil; use crate::upstream::UpstreamClient; @@ -266,6 +268,7 @@ fn stub_spec(stub: &Stub) -> ProviderSpec { trusted_device_hosts: &["auth.x.ai"], catalogue: CatalogueKind::DataArray, native_paths: NativePaths::Both, + media_paths: &[], } } @@ -303,6 +306,7 @@ fn chatgpt_stub_spec(stub: &Stub) -> ProviderSpec { trusted_device_hosts: &["auth.openai.com"], catalogue: CatalogueKind::SlugArray, native_paths: NativePaths::ResponsesOnly, + media_paths: &[], } } @@ -1722,3 +1726,317 @@ fn a_native_responses_request_is_forwarded_untouched() { "{answer}" ); } + +fn media_stub_spec(stub: &Stub) -> ProviderSpec { + let mut spec = stub_spec(stub); + spec.media_paths = &[MediaPath { + method: "POST", + path: "/v1/images/generations", + response_types: &["application/json"], + }]; + spec +} + +#[test] +fn media_route_forwards_the_exact_body_and_preserves_content_type() { + let upstream_body = r#"{"created":1,"data":[{"url":"https://example.invalid/synthetic.png"}]}"#; + let expected_response_body = upstream_body.to_string(); + let stub = Stub::start(move |_| Reply::json(200, upstream_body)); + let harness = harness_with_spec(&stub, "test-key", "test-token", media_stub_spec(&stub)); + let request_body = br#"{ "model" : "grok-4.7", "prompt" : "synthetic test payload", "n" : 1 }"#; + + let response = agent() + .post(harness.url("/images/generations?quality=low")) + .header("Authorization", "Bearer test-key") + .header("Content-Type", "application/json") + .send(request_body.as_slice()) + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 200); + assert_eq!( + response + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()), + Some("application/json") + ); + let body = response + .into_body() + .read_to_string() + .expect("response body"); + assert_eq!(body, expected_response_body); + + let requests = stub.requests(); + let forwarded = requests.first().expect("the upstream saw the request"); + assert_eq!(forwarded.method, "POST"); + assert_eq!(forwarded.path, "/v1/images/generations?quality=low"); + assert_eq!(forwarded.body.as_bytes(), request_body); +} + +#[test] +fn media_path_not_enabled_by_the_spec_keeps_the_unknown_endpoint_404() { + let stub = Stub::start(|_| Reply::json(200, "{}")); + let harness = harness(&stub, "test-key", "test-token"); + let response = agent() + .post(harness.url("/v1/images/generations")) + .header("Authorization", "Bearer test-key") + .header("Content-Type", "application/json") + .send(r#"{"model":"grok-4.7"}"#) + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 404); + let body = response.into_body().read_to_string().expect("error body"); + assert!(body.contains("unknown endpoint")); + assert!(stub.requests().is_empty()); +} + +#[test] +fn media_unrelated_unknown_paths_keep_the_404_without_a_model() { + let stub = Stub::start(|_| Reply::json(200, "{}")); + let harness = harness_with_spec(&stub, "test-key", "test-token", media_stub_spec(&stub)); + + let post = agent() + .post(harness.url("/v1/does-not-exist")) + .header("Authorization", "Bearer test-key") + .send("") + .expect("the proxy answers"); + assert_eq!(post.status().as_u16(), 404); + + let get = agent() + .get(harness.url("/v1/does-not-exist")) + .header("Authorization", "Bearer test-key") + .call() + .expect("the proxy answers"); + assert_eq!(get.status().as_u16(), 404); + assert!(stub.requests().is_empty()); +} + +#[test] +fn media_declared_path_without_a_model_answers_missing_model() { + let stub = Stub::start(|_| Reply::json(200, "{}")); + let harness = harness_with_spec(&stub, "test-key", "test-token", media_stub_spec(&stub)); + let response = agent() + .post(harness.url("/v1/images/generations")) + .header("Authorization", "Bearer test-key") + .send("{}") + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 400); + let body = response.into_body().read_to_string().expect("error body"); + let value: serde_json::Value = serde_json::from_str(&body).expect("json error"); + assert_eq!(value["error"]["code"], "missing_model"); + assert!(stub.requests().is_empty()); +} + +#[test] +fn media_path_with_the_wrong_method_answers_405_and_allow() { + let stub = Stub::start(|_| Reply::json(200, "{}")); + let harness = harness_with_spec(&stub, "test-key", "test-token", media_stub_spec(&stub)); + let body = r#"{"model":"grok-4.7"}"#; + let mut stream = std::net::TcpStream::connect(("127.0.0.1", harness.port)) + .expect("the proxy accepts a connection"); + write!( + stream, + "GET /v1/images/generations HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nAuthorization: Bearer test-key\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + harness.port, + body.len(), + body, + ) + .expect("the GET body is sent"); + let mut response = String::new(); + stream + .read_to_string(&mut response) + .expect("the response is read"); + + assert!(response.starts_with("HTTP/1.1 405"), "{response}"); + assert!(response.contains("\r\nAllow: POST\r\n"), "{response}"); + assert!(stub.requests().is_empty()); +} + +#[test] +fn media_response_with_an_unexpected_content_type_answers_502() { + let stub = Stub::start(|_| Reply::Body { + status: 200, + content_type: "image/png", + body: "synthetic image bytes".to_string(), + }); + let harness = harness_with_spec(&stub, "test-key", "test-token", media_stub_spec(&stub)); + let response = agent() + .post(harness.url("/v1/images/generations")) + .header("Authorization", "Bearer test-key") + .header("Content-Type", "application/json") + .send(r#"{"model":"grok-4.7","prompt":"synthetic"}"#) + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 502); + let body = response.into_body().read_to_string().expect("error body"); + let value: serde_json::Value = serde_json::from_str(&body).expect("json error"); + assert_eq!(value["error"]["code"], "unexpected_media_content_type"); + assert!( + value["error"]["message"] + .as_str() + .unwrap_or_default() + .contains("image/png") + ); +} + +#[test] +fn a_chatgpt_chat_request_carries_the_image_part_upstream() { + // The translated path must deliver what the catalogue advertises: an + // image-only message becomes an `input_image` part, with the URL and + // `detail` the client sent, and the message item survives translation. + let stub = Stub::start(|request| { + if request.path.starts_with("/v1/responses") { + Reply::json( + 200, + r#"{"id":"resp_image","status":"completed","model":"gpt-5.6-sol","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"seen"}]}]}"#, + ) + } else { + Reply::json(404, "{}") + } + }); + let harness = harness_with_spec( + &stub, + "secret-key", + "chatgpt-token", + chatgpt_stub_spec(&stub), + ); + + let request = json!({ + "model": "gpt-5.6-sol", + "messages": [{ + "role": "user", + "content": [{ + "type": "image_url", + "image_url": { + "url": "https://example.invalid/fixture.png", + "detail": "high" + } + }] + }] + }); + let response = agent() + .post(harness.url("/v1/chat/completions")) + .header("Authorization", "Bearer secret-key") + .header("Content-Type", "application/json") + .send(request.to_string()) + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 200); + let body = read_json_body(response); + assert_eq!(body["choices"][0]["message"]["content"], "seen", "{body}"); + + let requests = stub.requests(); + let forwarded = requests.first().expect("the upstream saw the request"); + let sent: serde_json::Value = serde_json::from_str(&forwarded.body).expect("forwarded json"); + + // The Chat shape is gone; the image is a Responses part. + assert!(sent.get("messages").is_none(), "{sent}"); + assert_eq!( + sent["input"][0]["content"][0]["type"], "input_image", + "{sent}" + ); + assert_eq!( + sent["input"][0]["content"][0]["image_url"], "https://example.invalid/fixture.png", + "{sent}" + ); + assert_eq!(sent["input"][0]["content"][0]["detail"], "high", "{sent}"); +} + +#[test] +fn an_xai_chat_request_is_forwarded_byte_for_byte_with_media_parts() { + // x.ai speaks both shapes, so its body must reach the upstream exactly as + // the client sent it — including an image part Chat Completions defines. + let stub = Stub::start(|_| { + Reply::json( + 200, + r#"{"id":"chatcmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}"#, + ) + }); + let harness = harness(&stub, "secret-key", "grok-token"); + + let raw = json!({ + "model": "grok-4.7", + "messages": [{ + "role": "user", + "content": [{ + "type": "image_url", + "image_url": { + "url": "https://example.invalid/fixture.png", + "detail": "high" + } + }] + }] + }) + .to_string(); + + let response = agent() + .post(harness.url("/v1/chat/completions")) + .header("Authorization", "Bearer secret-key") + .header("Content-Type", "application/json") + .send(raw.clone()) + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 200); + let requests = stub.requests(); + let forwarded = requests.first().expect("the upstream saw the request"); + assert_eq!(forwarded.body, raw, "the body was rewritten"); +} + +#[test] +fn a_refusal_reaches_a_chat_client_as_a_content_part() { + // The non-streaming path returns a refusal as a part array. A refusal-only + // answer must not be an empty string. + let stub = Stub::start(|request| { + if request.path.starts_with("/v1/responses") { + Reply::json( + 200, + r#"{"id":"resp_refusal","status":"completed","model":"gpt-5.6-sol","output":[{"type":"message","role":"assistant","content":[{"type":"refusal","refusal":"The request is not supported."}]}]}"#, + ) + } else { + Reply::json(404, "{}") + } + }); + let harness = harness_with_spec( + &stub, + "secret-key", + "chatgpt-token", + chatgpt_stub_spec(&stub), + ); + + let response = agent() + .post(harness.url("/v1/chat/completions")) + .header("Authorization", "Bearer secret-key") + .header("Content-Type", "application/json") + .send( + json!({"model": "gpt-5.6-sol", "messages": [{"role": "user", "content": "hello"}]}) + .to_string(), + ) + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 200); + let body = read_json_body(response); + assert_eq!( + body["choices"][0]["message"]["content"][0], + json!({"type": "refusal", "refusal": "The request is not supported."}), + "{body}" + ); +} + +#[test] +fn a_request_without_a_model_answers_missing_model() { + let stub = Stub::start(|_| Reply::json(200, "{}")); + let harness = harness(&stub, "secret-key", "grok-token"); + + let response = agent() + .post(harness.url("/v1/chat/completions")) + .header("Authorization", "Bearer secret-key") + .header("Content-Type", "application/json") + .send(r#"{"messages":[]}"#) + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 400); + let body = read_json_body(response); + assert_eq!(body["error"]["code"], "missing_model", "{body}"); + assert!(stub.requests().is_empty(), "the body was forwarded anyway"); +} diff --git a/src/server/translate.rs b/src/server/translate.rs index 42c8df4..99ddb13 100644 --- a/src/server/translate.rs +++ b/src/server/translate.rs @@ -7,295 +7,489 @@ //! //! x.ai speaks both natively, so nothing is translated for it. -use std::io::{Read, Result as IoResult}; - +use super::parts::{self, Role}; use serde_json::{Value, json}; +use std::fmt; +use std::io::{Read, Result as IoResult}; -/// The request fields that carry over from a Chat Completions request. -/// -/// Everything else either does not exist in the Responses API or is rejected -/// outright by the Sign in with ChatGPT route. -const PASSTHROUGH: &[&str] = &["model", "tool_choice", "parallel_tool_calls", "reasoning"]; +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TranslateError { + message: String, + code: &'static str, +} +impl TranslateError { + pub fn new(code: &'static str, message: impl Into) -> Self { + Self { + message: message.into(), + code, + } + } + pub fn code(&self) -> &'static str { + self.code + } + pub fn message(&self) -> &str { + &self.message + } +} +impl fmt::Display for TranslateError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} -/// Convert a Chat Completions request into a Responses request. -/// -/// System messages become `instructions`, because the Sign in with ChatGPT -/// route rejects an explicit `{type: "message", role: "system"}` item. -pub fn chat_request_to_responses(body: &[u8]) -> Result, String> { - let value: Value = - serde_json::from_slice(body).map_err(|err| format!("the request is not JSON: {err}"))?; +const CARRIED: &[&str] = &[ + "model", + "tool_choice", + "parallel_tool_calls", + "reasoning", + "max_output_tokens", + "stream", + "store", + "service_tier", + "modalities", + "audio", +]; + +pub fn chat_request_to_responses(body: &[u8]) -> Result, TranslateError> { + let value: Value = serde_json::from_slice(body).map_err(|err| { + TranslateError::new( + "unsupported_parameter", + format!("the request is not JSON: {err}"), + ) + })?; let Some(object) = value.as_object() else { - return Err("the request body is not a JSON object".to_string()); + return Err(TranslateError::new( + "unsupported_parameter", + "the request body is not a JSON object", + )); }; - let mut output = serde_json::Map::new(); - - for field in PASSTHROUGH { - if let Some(value) = object.get(*field) { - output.insert((*field).to_string(), value.clone()); + for (field, value) in object { + if crate::provider::openai::REJECTED_FIELDS.contains(&field.as_str()) { + // This is provider policy from the live route, not an omission; passing these through makes the upstream reject the whole request. + continue; + } + if CARRIED.contains(&field.as_str()) { + output.insert( + field.clone(), + if field == "tool_choice" { + flatten_tool_choice(value) + } else { + value.clone() + }, + ); + continue; + } + if !matches!( + field.as_str(), + "messages" + | "tools" + | "reasoning_effort" + | "max_tokens" + | "max_completion_tokens" + | "response_format" + | "n" + | "stream_options" + | "stop" + | "seed" + | "logit_bias" + | "prediction" + | "web_search_options" + | "function_call" + | "functions" + | "logprobs" + | "presence_penalty" + | "frequency_penalty" + ) { + return Err(unsupported_parameter( + field, + "has no known Responses API mapping", + )); + } + } + if let Some(format) = object.get("response_format") { + output.insert( + "text".into(), + json!({"format":map_response_format(format)?}), + ); + } + if let Some(n) = object.get("n").filter(|value| !value.is_null()) + && n.as_u64() != Some(1) + { + return Err(unsupported_parameter( + "n", + "Responses returns one choice per request", + )); + } + if let Some(options) = object + .get("stream_options") + .filter(|value| !value.is_null()) + { + let Some(options) = options.as_object() else { + return Err(unsupported_parameter( + "stream_options", + "must be an object containing only include_usage", + )); + }; + for key in options.keys() { + if key != "include_usage" { + return Err(unsupported_parameter( + key, + "is not supported in stream_options", + )); + } + } + } + for field in [ + "stop", + "seed", + "logit_bias", + "prediction", + "web_search_options", + "function_call", + "functions", + ] { + if object.contains_key(field) { + let reason = match field { + "stop" => "Responses has no stop-sequence equivalent", + "seed" => "Responses does not accept a deterministic seed", + "logit_bias" => "Responses has no token-bias equivalent", + "prediction" => "Responses has no prediction parameter equivalent", + "web_search_options" => "Responses web-search options are not Chat parameters", + _ => "use the tools and tool_choice parameters instead", + }; + return Err(unsupported_parameter(field, reason)); + } + } + if let Some(value) = object.get("logprobs").filter(|value| !value.is_null()) { + match value.as_bool() { + Some(false) => {} + Some(true) => { + return Err(unsupported_parameter( + "logprobs", + "Responses has no logprobs equivalent", + )); + } + None => return Err(unsupported_parameter("logprobs", "must be a boolean")), + } + } + for field in ["presence_penalty", "frequency_penalty"] { + if let Some(value) = object.get(field).filter(|value| !value.is_null()) { + let Some(value) = value.as_f64() else { + return Err(unsupported_parameter( + field, + "must be zero because Responses has no penalty equivalent", + )); + }; + if value != 0.0 { + return Err(unsupported_parameter( + field, + "Responses has no non-zero penalty equivalent", + )); + } } } - - // A Chat Completions client names a thinking level with `reasoning_effort` - // and a token limit with `max_tokens`. The Responses API names them - // `reasoning.effort` and `max_output_tokens`, and rejects the Chat - // Completions spellings outright — "Unsupported parameter: reasoning_effort" - // — so they are renamed here rather than dropped. - // - // A client that already speaks the Responses shape sends `reasoning` and - // `max_output_tokens`, and those are carried over untouched above. if !output.contains_key("reasoning") - && let Some(effort) = object.get("reasoning_effort").and_then(Value::as_str) + && let Some(effort) = object.get("reasoning_effort") { + let Some(effort) = effort.as_str() else { + return Err(unsupported_parameter( + "reasoning_effort", + "must be a string", + )); + }; output.insert( - "reasoning".to_string(), - // The summary is asked for as well, because the Chat Completions - // shape has nowhere else to carry the thinking: the upstream only - // returns the reasoning text when it is asked for. x.ai's Chat - // Completions answer always carries it in `reasoning_content`, so - // this is what makes the two providers behave the same way. - json!({ "effort": effort, "summary": "auto" }), + "reasoning".into(), + json!({"effort":effort,"summary":"auto"}), ); } - if !output.contains_key("max_output_tokens") && let Some(limit) = object .get("max_completion_tokens") .or_else(|| object.get("max_tokens")) - .and_then(Value::as_u64) { - output.insert("max_output_tokens".to_string(), json!(limit)); + let Some(limit) = limit.as_u64() else { + return Err(unsupported_parameter( + "max_tokens", + "must be a non-negative integer", + )); + }; + output.insert("max_output_tokens".into(), json!(limit)); } - - // The instructions come from the system messages. - let mut instructions: Vec = Vec::new(); - let mut input: Vec = Vec::new(); - - if let Some(messages) = object.get("messages").and_then(Value::as_array) { + let mut instructions = Vec::new(); + let mut input = Vec::new(); + if let Some(messages_value) = object.get("messages") { + let Some(messages) = messages_value.as_array() else { + return Err(unsupported_parameter("messages", "must be an array")); + }; for message in messages { + if !message.is_object() { + return Err(unsupported_parameter( + "messages", + "each message must be an object", + )); + } let role = message .get("role") .and_then(Value::as_str) .unwrap_or("user"); let content = message.get("content"); - match role { "system" => { - if let Some(text) = content_text(content) { + if let Some(text) = parts::content_text(content)? { instructions.push(text); } } "developer" => { - if let Some(text) = content_text(content) { - input.push(json!({ - "role": "developer", - "content": [{"type": "input_text", "text": text}], - })); + let content = parts::to_responses_parts(Role::Developer, content)?; + if !content.is_empty() { + input.push(json!({"role":"developer","content":content})); } } "tool" => { - // A tool result is a function-call output in the Responses - // shape. let call_id = message .get("tool_call_id") .and_then(Value::as_str) .unwrap_or_default(); - let output = content_text(content).unwrap_or_default(); - input.push(json!({ - "type": "function_call_output", - "call_id": call_id, - "output": output, - })); + let output_text = parts::content_text(content)?.unwrap_or_default(); + input.push(json!({"type":"function_call_output","call_id":call_id,"output":output_text})); } "assistant" => { - // An assistant message with no text carries nothing, and a - // message with empty text is not a message the Responses - // API wants. A tool call is carried on its own below. - if let Some(text) = content_text(content) - && !text.is_empty() - { - input.push(json!({ - "role": "assistant", - "content": [{"type": "output_text", "text": text}], - })); + let content = parts::to_responses_parts(Role::Assistant, content)?; + let only_empty_text = !content.is_empty() + && content.iter().all(|part| { + part.get("type").and_then(Value::as_str) == Some("output_text") + && part.get("text").and_then(Value::as_str) == Some("") + }); + if !content.is_empty() && !only_empty_text { + input.push(json!({"role":"assistant","content":content})); } - // The model's own tool call. - // - // The Responses API expects the call to be in the - // conversation before the tool's answer, and it matches the - // two by their `call_id`. Leaving the call out leaves the - // upstream with a tool answer it cannot place. - for call in message - .get("tool_calls") - .and_then(Value::as_array) - .into_iter() - .flatten() - { - if let Some(item) = convert_tool_call(call) { - input.push(item); + if let Some(calls) = message.get("tool_calls") { + let Some(calls) = calls.as_array() else { + return Err(unsupported_parameter("tool_calls", "must be an array")); + }; + for call in calls { + input.push(convert_tool_call(call)?); } } } _ => { - if let Some(text) = content_text(content) { - input.push(json!({ - "role": "user", - "content": [{"type": "input_text", "text": text}], - })); + let content = parts::to_responses_parts(Role::User, content)?; + if !content.is_empty() { + input.push(json!({"role":"user","content":content})); } } } } } - if !instructions.is_empty() { - output.insert("instructions".to_string(), json!(instructions.join("\n\n"))); + output.insert("instructions".into(), json!(instructions.join("\n\n"))); } - output.insert("input".to_string(), Value::Array(input)); - - // The tools have a flatter shape in the Responses API. - if let Some(tools) = object.get("tools").and_then(Value::as_array) { - let converted: Vec = tools.iter().filter_map(convert_tool).collect(); + output.insert("input".into(), Value::Array(input)); + if let Some(tools) = object.get("tools") { + let Some(tools) = tools.as_array() else { + return Err(unsupported_parameter("tools", "must be an array")); + }; + let converted = tools + .iter() + .map(convert_tool) + .collect::, _>>()?; if !converted.is_empty() { - output.insert("tools".to_string(), Value::Array(converted)); + output.insert("tools".into(), Value::Array(converted)); } } - - serde_json::to_vec(&Value::Object(output)).map_err(|err| err.to_string()) + serde_json::to_vec(&Value::Object(output)) + .map_err(|err| TranslateError::new("unsupported_parameter", err.to_string())) } -/// The text of a message's content, whatever shape it arrives in. -fn content_text(content: Option<&Value>) -> Option { - match content { - Some(Value::String(text)) => Some(text.clone()), - Some(Value::Array(parts)) => { - let text: Vec = parts - .iter() - .filter_map(|part| { - part.get("text") - .and_then(Value::as_str) - .map(str::to_string) - .or_else(|| part.as_str().map(str::to_string)) - }) - .collect(); - if text.is_empty() { - None - } else { - Some(text.join("\n")) +fn unsupported_parameter(field: &str, reason: &str) -> TranslateError { + TranslateError::new( + "unsupported_parameter", + format!("unsupported parameter {field}: {reason}"), + ) +} +fn map_response_format(value: &Value) -> Result { + let Some(kind) = value.get("type").and_then(Value::as_str) else { + return Err(unsupported_parameter( + "response_format", + "requires a string type", + )); + }; + match kind { + "json_object" | "text" => Ok(json!({"type":kind})), + "json_schema" => { + let Some(schema) = value.get("json_schema").and_then(Value::as_object) else { + return Err(unsupported_parameter( + "response_format.json_schema", + "must be an object", + )); + }; + let mut mapped = json!({"type":"json_schema"}); + for key in ["name", "schema", "strict", "description"] { + if let Some(value) = schema.get(key) { + mapped[key] = value.clone(); + } } + Ok(mapped) } - _ => None, + other => Err(unsupported_parameter( + "response_format.type", + &format!("unknown type {other}"), + )), } } - -/// Convert one Chat Completions tool definition into the Responses shape. -fn convert_tool(tool: &Value) -> Option { - let kind = tool.get("type").and_then(Value::as_str)?; +fn flatten_tool_choice(value: &Value) -> Value { + if value.get("type").and_then(Value::as_str) == Some("function") + && let Some(name) = value + .get("function") + .and_then(|function| function.get("name")) + { + return json!({"type":"function","name":name}); + } + value.clone() +} +fn convert_tool(tool: &Value) -> Result { + let Some(kind) = tool.get("type").and_then(Value::as_str) else { + return Ok(tool.clone()); + }; + if kind == "image_generation" { + return Err(TranslateError::new( + "image_requires_responses", + "image_generation tools require the native Responses API", + )); + } + if kind.starts_with("audio") { + return Err(TranslateError::new( + "audio_requires_responses", + format!("{kind} tools require the native Responses API"), + )); + } if kind != "function" { - // Only function tools have a mechanical translation. - return None; + return Ok(tool.clone()); } - let function = tool.get("function")?; - let name = function.get("name").and_then(Value::as_str)?; - - let mut converted = json!({ "type": "function", "name": name }); - if let Some(description) = function.get("description").and_then(Value::as_str) { - converted["description"] = json!(description); + let Some(function) = tool.get("function") else { + return Err(unsupported_parameter( + "tools.function", + "function definition is missing", + )); + }; + let Some(name) = function.get("name").and_then(Value::as_str) else { + return Err(unsupported_parameter( + "tools.function.name", + "function name is required", + )); + }; + let mut converted = json!({"type":"function","name":name}); + if let Some(description) = function.get("description") { + converted["description"] = description.clone(); } if let Some(parameters) = function.get("parameters") { converted["parameters"] = parameters.clone(); } - Some(converted) + if let Some(strict) = function.get("strict") { + converted["strict"] = strict.clone(); + } + Ok(converted) } /// Convert one Chat Completions tool call into the Responses shape. -/// -/// The Chat Completions shape nests the call under `function`; the Responses -/// shape puts it on the item itself. The `call_id` is what ties the call to -/// the tool's answer later in the conversation, so it is carried over. -fn convert_tool_call(call: &Value) -> Option { - let function = call.get("function")?; - let name = function.get("name").and_then(Value::as_str)?; +/// The Responses API uses call_id to match a tool result to this call. +fn convert_tool_call(call: &Value) -> Result { + let Some(function) = call.get("function") else { + return Err(unsupported_parameter( + "tool_calls.function", + "function call data is missing", + )); + }; + let Some(name) = function.get("name").and_then(Value::as_str) else { + return Err(unsupported_parameter( + "tool_calls.function.name", + "function name is required", + )); + }; let arguments = function .get("arguments") .and_then(Value::as_str) .unwrap_or("{}"); let call_id = call.get("id").and_then(Value::as_str).unwrap_or_default(); - - Some(json!({ - "type": "function_call", - "call_id": call_id, - "name": name, - "arguments": arguments, - })) + Ok(json!({"type":"function_call","call_id":call_id,"name":name,"arguments":arguments})) } /// Convert a Responses response into a Chat Completions response. -pub fn responses_to_chat_completion(body: &[u8]) -> Result, String> { - let value: Value = - serde_json::from_slice(body).map_err(|err| format!("the response is not JSON: {err}"))?; - +pub fn responses_to_chat_completion(body: &[u8]) -> Result, TranslateError> { + let value: Value = serde_json::from_slice(body).map_err(|err| { + TranslateError::new( + "unmappable_output_item", + format!("the response is not JSON: {err}"), + ) + })?; let text = response_text(&value); + let mut content = Value::String(text); + let mut parts = Vec::new(); + if let Some(output) = value.get("output").and_then(Value::as_array) { + for item in output { + let kind = item + .get("type") + .and_then(Value::as_str) + .unwrap_or("unknown"); + let id = item.get("id").and_then(Value::as_str).unwrap_or("unknown"); + if kind == "image_generation_call" || kind.starts_with("audio") { + return Err(TranslateError::new( + "unmappable_output_item", + format!( + "Responses output item {kind} (id {id}) has no Chat Completions equivalent" + ), + )); + } + if kind != "message" { + continue; + } + for part in item + .get("content") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + match part.get("type").and_then(Value::as_str).unwrap_or("unknown") { + "output_text" => parts.push(json!({"type":"text","text":part.get("text").and_then(Value::as_str).unwrap_or("")})), + "refusal" => parts.push(json!({"type":"refusal","refusal":part.get("refusal").and_then(Value::as_str).unwrap_or("")})), + other => return Err(TranslateError::new("unmappable_output_item", format!("Responses output content part {other} in item {id} has no Chat Completions equivalent"))), + } + } + } + } + if parts + .iter() + .any(|part| part.get("type").and_then(Value::as_str) == Some("refusal")) + { + content = Value::Array(parts); + } let tool_calls = response_tool_calls(&value); let mut reason = finish_reason(&value); if !tool_calls.is_empty() { - // The model asked for a tool rather than for an answer, and that is - // what the finish reason says. reason = "tool_calls"; } - - let mut choices = vec![json!({ - "index": 0, - "message": { "role": "assistant", "content": text }, - "finish_reason": reason, - })]; - - // The tool calls, when the model asked for one. - // - // The Responses API carries a tool call as an output item; the Chat - // Completions shape carries it in `message.tool_calls`. Without this the - // client sees an empty answer where the model asked for a tool, and a - // client that drives tools has nothing to run. + let mut choices = vec![ + json!({"index":0,"message":{"role":"assistant","content":content},"finish_reason":reason}), + ]; if !tool_calls.is_empty() { choices[0]["message"]["tool_calls"] = Value::Array(tool_calls); } - - // The thinking text, when the upstream sent any. - // - // x.ai's Chat Completions answer carries it in `reasoning_content`, so the - // same field is used here: a client that shows the thinking for one - // provider shows it for both. let reasoning = response_reasoning(&value); if !reasoning.is_empty() { choices[0]["message"]["reasoning_content"] = json!(reasoning); } - - // A failed response carries an error rather than an answer. - // - // The Responses object always carries an `error` key, and it is `null` on - // success. A key that is merely *present* is not a failure. if let Some(error) = value.get("error").filter(|error| !error.is_null()) { - choices[0]["message"] = json!({ - "role": "assistant", - "content": Value::Null, - }); + choices[0]["message"] = json!({"role":"assistant","content":Value::Null}); choices[0]["finish_reason"] = json!("error"); let _ = error; } - - let mut output = json!({ - "id": chat_id(value.get("id").and_then(Value::as_str)), - "object": "chat.completion", - "created": now_unix(), - "model": value.get("model").and_then(Value::as_str).unwrap_or(""), - "choices": choices, - }); - + let mut output = json!({"id":chat_id(value.get("id").and_then(Value::as_str)),"object":"chat.completion","created":now_unix(),"model":value.get("model").and_then(Value::as_str).unwrap_or(""),"choices":choices}); if let Some(usage) = responses_usage_to_chat(value.get("usage")) { output["usage"] = usage; } - - serde_json::to_vec(&output).map_err(|err| err.to_string()) + serde_json::to_vec(&output) + .map_err(|err| TranslateError::new("unmappable_output_item", err.to_string())) } /// The tool calls in a Responses object. @@ -478,6 +672,9 @@ pub struct ResponsesToChatStream { created: i64, usage: Option, tool_calls: Vec, + emitted_answer: bool, + unmappable_item: Option, + refusal_deltas: Vec, } impl ResponsesToChatStream { @@ -493,6 +690,9 @@ impl ResponsesToChatStream { created: now_unix(), usage: None, tool_calls: Vec::new(), + emitted_answer: false, + unmappable_item: None, + refusal_deltas: Vec::new(), } } @@ -560,6 +760,7 @@ impl ResponsesToChatStream { if let Some(call) = self.tool_calls.get_mut(index) { call.announced = true; } + self.emitted_answer = true; self.chunk(delta, Value::Null) } @@ -605,6 +806,7 @@ impl ResponsesToChatStream { "function": { "arguments": missing }, }], }); + self.emitted_answer = true; self.chunk(delta, Value::Null) } @@ -622,6 +824,30 @@ impl ResponsesToChatStream { } } + if kind.starts_with("response.image_generation_call.") { + let id = event + .get("item_id") + .and_then(Value::as_str) + .unwrap_or("unknown"); + self.unmappable_item = Some(format!( + "Responses output item image_generation_call (id {id}) has no Chat Completions equivalent" + )); + return Vec::new(); + } + if matches!( + kind, + "response.output_item.added" | "response.output_item.done" + ) && let Some(item) = event.get("item") + { + let item_type = item.get("type").and_then(Value::as_str).unwrap_or(""); + if item_type == "image_generation_call" || item_type.starts_with("audio") { + let id = item.get("id").and_then(Value::as_str).unwrap_or("unknown"); + self.unmappable_item = Some(format!( + "Responses output item {item_type} (id {id}) has no Chat Completions equivalent" + )); + return Vec::new(); + } + } match kind { "response.output_item.added" => { // A tool call starts. The name and the id come with it; the @@ -662,6 +888,7 @@ impl ResponsesToChatStream { "function": { "arguments": delta }, }], }); + self.emitted_answer = true; self.chunk(chunk, Value::Null) } "response.function_call_arguments.done" => { @@ -717,8 +944,44 @@ impl ResponsesToChatStream { "finish_reason": Value::Null, }], }); + self.emitted_answer = true; encode_event(&chunk) } + "response.refusal.delta" => { + let delta = event.get("delta").and_then(Value::as_str).unwrap_or(""); + if delta.is_empty() { + return Vec::new(); + } + let item_id = event + .get("item_id") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + if !self.refusal_deltas.contains(&item_id) { + self.refusal_deltas.push(item_id); + } + self.emitted_answer = true; + self.chunk(json!({"refusal":delta}), Value::Null) + } + "response.refusal.done" => { + let item_id = event + .get("item_id") + .and_then(Value::as_str) + .unwrap_or_default(); + if self.refusal_deltas.iter().any(|id| id == item_id) { + return Vec::new(); + } + let refusal = event + .get("refusal") + .or_else(|| event.get("text")) + .and_then(Value::as_str) + .unwrap_or(""); + if refusal.is_empty() { + return Vec::new(); + } + self.emitted_answer = true; + self.chunk(json!({"refusal":refusal}), Value::Null) + } "response.reasoning_summary_text.delta" | "response.reasoning_text.delta" => { // The thinking text arrives as its own events, ahead of the // answer. It goes out in `reasoning_content`, the field x.ai's @@ -751,12 +1014,26 @@ impl ResponsesToChatStream { } self.usage = responses_usage_to_chat(response.get("usage")); } + if !self.emitted_answer + && let Some(message) = self.unmappable_item.take() + { + let chunk = json!({ + "id": self.id, + "object": "chat.completion.chunk", + "created": self.created, + "model": self.model, + "choices": [{"index":0,"delta":{},"finish_reason":"error"}], + "error": {"message":message,"type":"server_error","code":"unmappable_output_item"}, + }); + let mut out = encode_event(&chunk); + out.extend_from_slice(b"data: [DONE]\n\n"); + return out; + } let finish = if kind == "response.incomplete" { "length" } else if self.tool_calls.is_empty() { "stop" } else { - // The model asked for a tool rather than for an answer. "tool_calls" }; let mut chunk = json!({ @@ -1083,6 +1360,22 @@ mod tests { assert_eq!(value["max_output_tokens"], 250); } + #[test] + fn a_responses_shaped_token_limit_is_carried() { + // A client that already uses the Responses spelling must keep its + // limit; the field is Responses-valid, so there is nothing to rename. + let body = br#"{ + "model": "gpt-6.1-sol", + "messages": [{"role": "user", "content": "hello"}], + "max_output_tokens": 300 + }"#; + + let converted = chat_request_to_responses(body).unwrap(); + let value: Value = serde_json::from_slice(&converted).unwrap(); + + assert_eq!(value["max_output_tokens"], 300); + } + #[test] fn the_thinking_text_is_carried_in_the_chat_completions_answer() { // x.ai's Chat Completions answer carries the thinking in @@ -1168,12 +1461,13 @@ mod tests { let body = br#"{ "model": "gpt-5", "messages": [], - "tools": [{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object"}}}] + "tools": [{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object"}, "strict": true}}] }"#; let converted = chat_request_to_responses(body).unwrap(); let value: Value = serde_json::from_slice(&converted).unwrap(); assert_eq!(value["tools"][0]["type"], "function"); assert_eq!(value["tools"][0]["name"], "get_weather"); + assert_eq!(value["tools"][0]["strict"], true); } #[test] @@ -1436,4 +1730,192 @@ mod tests { "{value}" ); } + + #[test] + fn documented_fixture_image_is_preserved_and_image_only_messages_survive() { + let body = include_str!("../../tests/fixtures/media/chat-completions-image.json"); + let converted = chat_request_to_responses(body.as_bytes()).unwrap(); + let value: Value = serde_json::from_slice(&converted).unwrap(); + assert_eq!(value["input"][0]["content"][0]["type"], "input_image"); + assert_eq!(value["input"][0]["content"][0]["detail"], "high"); + assert_eq!( + value["input"][0]["content"][0]["image_url"], + "https://example.invalid/fixture.png" + ); + } + + #[test] + fn response_format_is_mapped_to_text_format() { + for (input, expected) in [ + (json!({"type":"json_object"}), json!({"type":"json_object"})), + (json!({"type":"text"}), json!({"type":"text"})), + ( + json!({"type":"json_schema","json_schema":{"name":"answer","schema":{"type":"object"},"strict":true,"description":"fixture"}}), + json!({"type":"json_schema","name":"answer","schema":{"type":"object"},"strict":true,"description":"fixture"}), + ), + ] { + let request = json!({"model":"fixture","messages":[],"response_format":input}); + let bytes = chat_request_to_responses(&serde_json::to_vec(&request).unwrap()).unwrap(); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["text"]["format"], expected); + } + } + + #[test] + fn an_unknown_response_format_type_is_named() { + let request = br#"{"model":"fixture","messages":[],"response_format":{"type":"yaml"}}"#; + let error = chat_request_to_responses(request).unwrap_err(); + assert_eq!(error.code(), "unsupported_parameter"); + assert!(error.message().contains("yaml")); + } + + #[test] + fn unsupported_fields_are_named_and_provider_rejected_fields_stay_stripped() { + for (field, value) in [("n", json!(2)), ("stop", json!(["x"])), ("seed", json!(1))] { + let request = json!({"model":"fixture","messages":[],(field):value}); + let error = + chat_request_to_responses(&serde_json::to_vec(&request).unwrap()).unwrap_err(); + assert_eq!(error.code(), "unsupported_parameter"); + assert!(error.message().contains(field), "{}", error.message()); + } + let request = br#"{"model":"fixture","messages":[],"temperature":0.2,"logprobs":false,"presence_penalty":0}"#; + let value: Value = + serde_json::from_slice(&chat_request_to_responses(request).unwrap()).unwrap(); + assert!(value.get("temperature").is_none()); + assert!(value.get("logprobs").is_none()); + for value in [json!(true), json!("yes")] { + let request = json!({"model":"fixture","messages":[],"logprobs":value}); + let error = + chat_request_to_responses(&serde_json::to_vec(&request).unwrap()).unwrap_err(); + assert_eq!(error.code(), "unsupported_parameter"); + } + } + + #[test] + fn generation_tools_require_the_native_responses_path() { + for (kind, code) in [ + ("image_generation", "image_requires_responses"), + ("audio_generation", "audio_requires_responses"), + ] { + let request = json!({"model":"fixture","messages":[],"tools":[{"type":kind}]}); + let error = + chat_request_to_responses(&serde_json::to_vec(&request).unwrap()).unwrap_err(); + assert_eq!(error.code(), code); + } + } + + #[test] + fn non_function_tools_are_carried_unchanged() { + let request = br#"{"model":"fixture","messages":[],"tools":[{"type":"web_search","search_context_size":"low"}]}"#; + let value: Value = + serde_json::from_slice(&chat_request_to_responses(request).unwrap()).unwrap(); + assert_eq!( + value["tools"][0], + json!({"type":"web_search","search_context_size":"low"}) + ); + } + + #[test] + fn refusal_fixture_is_projected_as_ordered_content_parts() { + let fixture = include_str!("../../tests/fixtures/media/responses-refusal.json"); + let value: Value = + serde_json::from_slice(&responses_to_chat_completion(fixture.as_bytes()).unwrap()) + .unwrap(); + assert_eq!( + value["choices"][0]["message"]["content"][0], + json!({"type":"text","text":"I cannot help with that request."}) + ); + assert_eq!( + value["choices"][0]["message"]["content"][1], + json!({"type":"refusal","refusal":"The request is not supported."}) + ); + } + + #[test] + fn image_generation_output_returns_a_named_translation_error() { + let fixture = include_str!("../../tests/fixtures/media/responses-image-generation.json"); + let error = responses_to_chat_completion(fixture.as_bytes()).unwrap_err(); + assert_eq!(error.code(), "unmappable_output_item"); + assert!(error.message().contains("image_generation_call")); + assert!(error.message().contains("ig_fixture_1")); + } + + #[test] + fn text_only_output_remains_a_string() { + let bytes = responses_to_chat_completion(br#"{"id":"resp_1","status":"completed","output":[{"type":"message","content":[{"type":"output_text","text":"hello"}]}]}"#).unwrap(); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["choices"][0]["message"]["content"], "hello"); + } + + #[test] + fn refusal_stream_fixture_emits_refusal_deltas_once() { + let fixture = include_str!("../../tests/fixtures/media/responses-stream-refusal.txt"); + let output = translate(fixture, 3); + assert_eq!( + output.matches(r#""refusal":"I cannot help""#).count(), + 1, + "{output}" + ); + assert_eq!( + output.matches("I cannot help with that request.").count(), + 0, + "{output}" + ); + assert!(output.contains("data: [DONE]"), "{output}"); + } + + #[test] + fn refusal_done_is_emitted_when_no_delta_was_seen() { + let stream = concat!( + "data: {\"type\":\"response.refusal.done\",\"item_id\":\"m1\",\"refusal\":\"No.\"}\n\n", + "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\"}}\n\n" + ); + let output = translate(stream, 4096); + assert!(output.contains(r#""refusal":"No.""#), "{output}"); + } + + #[test] + fn unmappable_stream_with_no_chat_content_emits_named_error() { + let stream = concat!( + "data: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"audio\",\"id\":\"audio_1\"}}\n\n", + "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\"}}\n\n" + ); + let output = translate(stream, 4096); + assert!(output.contains(r#""finish_reason":"error""#), "{output}"); + assert!( + output.contains(r#""code":"unmappable_output_item""#), + "{output}" + ); + assert!(output.contains("audio_1"), "{output}"); + assert!(output.contains("data: [DONE]"), "{output}"); + } + + #[test] + fn every_advertised_image_model_is_accepted_for_every_provider_spec() { + let catalogue: Value = serde_json::from_str(include_str!( + "../../tests/fixtures/media/chatgpt-models.json" + )) + .unwrap(); + let models = catalogue["models"] + .as_array() + .unwrap() + .iter() + .filter(|model| { + model["input_modalities"] + .as_array() + .is_some_and(|modalities| modalities.iter().any(|value| value == "image")) + }); + for provider in crate::provider::ProviderId::all() { + let _spec = crate::provider::spec_for(provider, &crate::config::Config::default()); + for model in models.clone() { + let slug = model["slug"].as_str().unwrap(); + let request = json!({"model":slug,"messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"https://example.invalid/image.png"}}]}]}); + assert!( + chat_request_to_responses(&serde_json::to_vec(&request).unwrap()).is_ok(), + "provider {} model {slug}", + provider.as_str() + ); + } + } + } } diff --git a/tests/fixtures/media/README.md b/tests/fixtures/media/README.md new file mode 100644 index 0000000..3768445 --- /dev/null +++ b/tests/fixtures/media/README.md @@ -0,0 +1,3 @@ +# Media translation fixtures + +These are documented-shape fixtures for offline translation tests, not live captures. Stage 0 live capture is still pending. No credential, prompt, or real user media is present. Any image URL and identifier below is synthetic. diff --git a/tests/fixtures/media/chat-completions-image.json b/tests/fixtures/media/chat-completions-image.json new file mode 100644 index 0000000..a014f85 --- /dev/null +++ b/tests/fixtures/media/chat-completions-image.json @@ -0,0 +1,14 @@ +{ + "model": "gpt-5", + "messages": [ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": { "url": "https://example.invalid/fixture.png", "detail": "high" } + } + ] + } + ] +} diff --git a/tests/fixtures/media/chatgpt-models.json b/tests/fixtures/media/chatgpt-models.json new file mode 100644 index 0000000..29c8c65 --- /dev/null +++ b/tests/fixtures/media/chatgpt-models.json @@ -0,0 +1,5 @@ +{ + "models": [ + { "slug": "fixture-image-model", "input_modalities": ["text", "image"] } + ] +} diff --git a/tests/fixtures/media/responses-image-generation.json b/tests/fixtures/media/responses-image-generation.json new file mode 100644 index 0000000..a4744a4 --- /dev/null +++ b/tests/fixtures/media/responses-image-generation.json @@ -0,0 +1,13 @@ +{ + "id": "resp_fixture_image", + "status": "completed", + "model": "fixture-model", + "output": [ + { + "type": "image_generation_call", + "id": "ig_fixture_1", + "status": "completed", + "result": "" + } + ] +} diff --git a/tests/fixtures/media/responses-refusal.json b/tests/fixtures/media/responses-refusal.json new file mode 100644 index 0000000..7152c99 --- /dev/null +++ b/tests/fixtures/media/responses-refusal.json @@ -0,0 +1,15 @@ +{ + "id": "resp_fixture_refusal", + "status": "completed", + "model": "fixture-model", + "output": [ + { + "type": "message", + "role": "assistant", + "content": [ + { "type": "output_text", "text": "I cannot help with that request." }, + { "type": "refusal", "refusal": "The request is not supported." } + ] + } + ] +} diff --git a/tests/fixtures/media/responses-stream-refusal.txt b/tests/fixtures/media/responses-stream-refusal.txt new file mode 100644 index 0000000..c4ead04 --- /dev/null +++ b/tests/fixtures/media/responses-stream-refusal.txt @@ -0,0 +1,6 @@ +data: {"type":"response.refusal.delta","item_id":"msg_fixture_1","delta":"I cannot help"} + +data: {"type":"response.refusal.done","item_id":"msg_fixture_1","refusal":"I cannot help with that request."} + +data: {"type":"response.completed","response":{"id":"resp_fixture_refusal","model":"fixture-model","status":"completed"}} + From a32078ae82c299398c1d1c0270ee1b0729612993 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Fri, 27 Nov 2026 20:10:53 +0000 Subject: [PATCH 11/13] Pin media fixture line endings to LF Windows checkouts apply autocrlf, so include_str! embedded CRLF for the media fixtures while the SSE reader splits events on a bare \n\n. The refusal stream fixture then parsed to zero deltas and failed only on Windows. Pin the fixture tree to LF so the embedded bytes match the parser contract. --- .gitattributes | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..b2ff099 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +tests/fixtures/** text eol=lf From b98731b1464aa4e31ed8845221a07ba8a076b85d Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Sat, 28 Nov 2026 17:17:02 +0000 Subject: [PATCH 12/13] Close out non-text content proxying - Add `eggpass probe media`, which measures a provider's own media endpoint from outside the proxy: a request through the proxy cannot answer that question, because an undeclared path is refused before any upstream call is made. The report carries the status, origin, content type, byte count, and any `error.type` and `error.code`; the response body is never printed, stored, or forwarded. - Enable `POST /v1/images/generations` for x.ai after the probe recorded a `200 application/json` answer from `https://api.x.ai` for `grok-imagine-image-2.0`. ChatGPT's candidate stays disabled: its subscription token is refused at the OAuth boundary with `401`, so that endpoint was never exercised and its support is unmeasured. - Name every request part, field, and tool the translated ChatGPT path cannot carry, and refuse image or audio output by name instead of dropping it. - Answer with `unmappable_output_item` when a Responses answer has no Chat Completions expression. - Document the 14 provider-policy fields stripped before forwarding, which is not the same set as the inputs the translator rejects. --- CHANGELOG.md | 24 +- docs/commands.md | 19 + docs/how-it-works.md | 48 +- docs/troubleshooting.md | 56 +- ...-proxying-audit-followup-implementation.md | 118 +++ ...tent-proxying-corrective-implementation.md | 153 +++ ...roxying-deferred-closure-implementation.md | 235 +++++ ...on-text-content-proxying-implementation.md | 25 +- scripts/probe-media-endpoints.sh | 15 +- src/cli/args.rs | 242 ++++- src/cli/commands/mod.rs | 1 + src/cli/commands/probe.rs | 129 +++ src/cli/mod.rs | 1 + src/provider/media_probe.rs | 821 ++++++++++++++++ src/provider/mod.rs | 20 + src/provider/openai.rs | 10 +- src/provider/xai.rs | 37 +- src/server/aggregator.rs | 19 +- src/server/chat.rs | 46 +- src/server/media.rs | 32 +- src/server/tests.rs | 161 ++++ src/server/translate.rs | 905 ++++++++++++++++-- src/upstream.rs | 8 + tests/fixtures/media/README.md | 8 +- tests/fixtures/media/chatgpt-models.json | 4 +- .../media/l1-live-probe-metadata.json | 158 +++ 26 files changed, 3138 insertions(+), 157 deletions(-) create mode 100644 plans/non-text-content-proxying-audit-followup-implementation.md create mode 100644 plans/non-text-content-proxying-corrective-implementation.md create mode 100644 plans/non-text-content-proxying-deferred-closure-implementation.md create mode 100644 src/cli/commands/probe.rs create mode 100644 src/provider/media_probe.rs create mode 100644 tests/fixtures/media/l1-live-probe-metadata.json diff --git a/CHANGELOG.md b/CHANGELOG.md index bc0595f..b72777d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,13 +18,29 @@ Notable changes to eggpass are listed here. The format follows `response_format` to `text.format`, and pass Responses-native tools through. - Add an optional `server.max_body_bytes` setting, defaulting to 32 MiB. - Add probe-gated routing for native media endpoints. A route is enabled only - after `scripts/probe-media-endpoints.sh` confirms it, so an unprobed path - still answers `404`. + after `eggpass probe media` records a provider-side success for it, so an + unprobed path still answers `404`. +- Add `eggpass probe media`, which asks a provider directly whether its + subscription serves a media endpoint and reports the status, origin, content + type, byte count, and any `error.type` and `error.code`, without printing, + storing, or forwarding the response body. +- Enable `POST /v1/images/generations` for the x.ai provider, after + `eggpass probe media` recorded a `200 application/json` answer from + `https://api.x.ai` on 2026-11-28. ChatGPT's candidate stays disabled: its + subscription token is refused at the OAuth boundary with `401`, so that + endpoint was never exercised and its support is unmeasured. Send `model`, + `prompt`, and `n` to the x.ai route; an OpenAI-shaped `size` is refused + with `400`. ### Changed -- Refuse a part, field, or tool the translated path cannot carry with a named - `400` before the upstream runs, rather than dropping it silently. +- Clarify that translated inputs the ChatGPT translator cannot represent + (including unsupported content parts and image/audio generation tools) get + named `400` errors, while provider policy separately strips exactly these + 14 fields before forwarding: `background`, `conversation`, `max_tool_calls`, + `metadata`, `moderation`, `multi_agent`, `prompt`, `prompt_cache_retention`, + `safety_identifier`, `temperature`, `top_logprobs`, `top_p`, `truncation`, + `user`. - Answer a chat or Responses request without a readable `model` with `400 missing_model` instead of routing it to the default provider. diff --git a/docs/commands.md b/docs/commands.md index 81fd2e8..8eb9646 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -87,6 +87,25 @@ A complete report is retained only in daemon memory for 600 seconds from complet 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. +## `probe` + +```sh +eggpass probe media --provider xai --model grok-imagine-image-2.0 +eggpass probe media --provider openai --model gpt-image-2.5-sunburst --json +``` + +`eggpass probe media` asks a provider directly whether its subscription serves a native media endpoint, without going through the proxy. That distance is the point: a media route that is not declared is refused with the proxy's own `404` before any upstream request, so a request through the daemon measures enablement rather than the provider. The probe sends one request on the candidate path (`POST /v1/images/generations` for both providers) using the token already stored for that provider. No client key is involved, and no response body is printed, stored, or written to a fixture. + +`--model` is required and has no default, because a vendor's current slug changes faster than this document; take it from the provider's own guide and record it with the result. A slug is accepted only when it is letters, digits, dots, underscores, and hyphens. `--path` is optional and must match the provider's candidate path. `--body` reads a JSON request object from a file instead of the provider's documented minimal body, and sets its `model` to `--model`, so the two cannot disagree. The default bodies differ because the two documents do: x.ai's image guide shows `model` and `prompt` and answers `400` to an OpenAI-shaped `size`. + +The report names the provider, the candidate path, the method the measurement came from, the request model, the xAI auth mode (`api` or `build`, and `null` for OpenAI), the origin actually contacted, the HTTP status, the content type, the response byte count, whether a `2xx` carried a content type the provider spec accepts, the response's `error.type` and `error.code` when the body is JSON, the UTC date it ran, and the source and scope of the signal. `--json` prints the same fields as one object. + +Read a result literally. A `2xx` with an accepted content type is provider support for that model on that origin. A `401` or `403` answers a question about credential custody, not about the path. A `404` names either the model or the path, and the record has to say which was sent. A `2xx` with an unaccepted content type is a mismatch, not a success. + +Stop the daemon with `eggpass stop` first. The probe shares the credential store with the daemon, and two processes refreshing one token can invalidate each other's copy. A running daemon produces a warning on stderr, not a refusal. + +**Exit codes:** `0` when a report was produced, whatever status the provider returned. `1` when the provider is disabled or not signed in, the model, path, or body is unusable, or the request could not be sent. + ## `run`, `stop`, and `restart` ```sh diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 6da3e70..0dda506 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -39,22 +39,46 @@ endpoint, not only on the model. - **x.ai, both endpoints.** The request body is forwarded byte for byte, so text, `image_url`, `input_audio`, and file parts reach x.ai exactly as the client sent them. The answer is returned unchanged. -- **ChatGPT, `/v1/responses`.** The request and the answer are forwarded - verbatim. `input_image` parts and the `image_generation` tool already work - on this path. +- **ChatGPT, `/v1/responses`.** This uses the native Responses shape without + Chat Completions translation. The provider request policy still applies + (see the exact stripped-field list below). `input_image` parts and the + `image_generation` tool already work on this path. - **ChatGPT, `/v1/chat/completions`.** The request is translated. Text, `image_url` (including `detail`), `input_audio`, and file parts are mapped - to their Responses equivalents. A refusal and any other non-text content - part is returned in `content` as a part array; a text-only answer keeps the - string form. A part, request field, or tool with no faithful equivalent is - refused with a named `400` before the upstream is called — it is never - dropped. Image or audio generation is not expressible over Chat Completions - and must use `/v1/responses`. + to their Responses equivalents. A refusal is returned in `content` as a + part array; a text-only answer keeps the string form. If the translator + cannot represent a request part, field, or tool, it returns a named `400` + before the upstream is called. A Responses output item or part that cannot + be represented is returned as `unmappable_output_item`, not silently + dropped. `modalities:["text"]` is omitted as a default no-op. Image/audio + output requested through `modalities`, Chat `audio` configuration, or + generation tools is refused by name with `image_requires_responses` or + `audio_requires_responses` as applicable; use `/v1/responses` instead. + +ChatGPT's provider policy removes exactly these top-level request fields +before forwarding, because the live route rejects them if present. The source +comment describes this as 'provider policy from the live route, not an +omission; passing these through makes the upstream reject the whole request.' +This is not a general rule for unsupported inputs: other parameters are +mapped where supported, and fields with no known mapping are rejected by +name rather than silently stripped. The list is defined in +[the provider spec](../src/provider/openai.rs) and covered by +[the `unsupported_fields_are_named_and_provider_rejected_fields_stay_stripped` regression test](../src/server/translate.rs). + + +`background`, `conversation`, `max_tool_calls`, `metadata`, `moderation`, `multi_agent`, `prompt`, `prompt_cache_retention`, `safety_identifier`, `temperature`, `top_logprobs`, `top_p`, `truncation`, `user` + Native media endpoints, such as image generation, are declared per provider in -the provider spec. A path is routed only after a live probe confirms the -subscription serves it; until then it answers `404`, the same as any other -unknown endpoint. +the provider spec. A path is routed only after `eggpass probe media` records a +`2xx` answer with an accepted content type from that provider. x.ai's +`POST /v1/images/generations` meets that bar: `https://api.x.ai` answered +`200 application/json` for `grok-imagine-image-2.0` on 2026-11-28. ChatGPT's +candidate does not, because a ChatGPT subscription token is refused with `401` +at the OAuth boundary, so that endpoint was never exercised and its route stays +`404`, the same as any other unknown endpoint. A request through the proxy +cannot make that measurement, because an undeclared path is refused before any +upstream call is made. ## Sign-in and credentials diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f4b2e93..3c46f85 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -53,21 +53,33 @@ provider may omit models that are unavailable or filtered during normalization. **A reasoning level is rejected:** Use a level listed for that model. Providers can reject levels they do not support. -**`unsupported_content_part`:** The request carries a content part the -translated path cannot express. Use `text`, `image_url`, `input_audio`, or a -file part with `file_id` or `filename` and `file_data`; a non-text part in a -`system` message or a non-text `tool` output is refused by design. A part type -this proxy does not translate can still be sent to `POST /v1/responses`, which -is forwarded verbatim. - -**`unsupported_parameter`:** The named Chat Completions field has no Responses -equivalent. `stop`, `seed`, `n` greater than 1, penalty fields with a non-zero -value, `logit_bias`, and `logprobs` are examples. Remove the field, or send a -native Responses request. - -**`image_requires_responses` or `audio_requires_responses`:** An image or audio -generation tool was requested over Chat Completions, whose answer shape cannot -carry the generated media. Call `POST /v1/responses` instead. +**`unsupported_content_part`:** A content part or its position cannot be +carried by the ChatGPT Chat Completions translator. Use `text`, `image_url`, +`input_audio`, or a file part with `file_id` or `filename` and `file_data`; a +non-text part in a `system` message or a non-text `tool` output is refused +with a named `400`. This is separate from the ChatGPT provider-policy fields +that are stripped before forwarding (listed in +[how it works](how-it-works.md#content-shapes)). A native `POST /v1/responses` +avoids Chat Completions projection, but the provider request policy still +applies. + +**`unsupported_parameter`:** On translated ChatGPT Chat Completions requests, +the named field has no supported Responses mapping or has an unsupported +value. Examples include `stop`, `seed`, `logit_bias`, `prediction`, +`web_search_options`, `function_call`, `functions`, `n` other than 1, +`logprobs: true`, non-zero penalty fields, and `stream_options` keys other +than `include_usage`; unknown fields with no mapping are also refused by +name. Remove or correct the field, or use native Responses where appropriate. +The provider-policy list is different: those fields are stripped, not refused +(see [how it works](how-it-works.md#content-shapes)). + +**`image_requires_responses` or `audio_requires_responses`:** These named +translation refusals cover output modalities and tools, not only generation +tools. An image modality or image-generation tool gets +`image_requires_responses`; an audio modality, Chat `audio` output config, or +audio tool gets `audio_requires_responses`. Chat Completions cannot carry these +outputs, so use `POST /v1/responses`. `modalities:["text"]` is omitted as a +default no-op. These are not provider-policy strips. **`missing_model`:** The body must be a JSON object with a `model` string. A non-JSON or model-less body is no longer forwarded to the default provider. @@ -78,11 +90,15 @@ setting within its documented range if the request is legitimate. **`unexpected_media_content_type`:** A native media endpoint answered with a content type its provider spec does not list. The response is refused rather -than labelled wrongly; check that the endpoint and the probe result match. - -**`unmappable_output_item`:** The upstream returned an item, such as a -generated image or audio, that the Chat Completions shape cannot express. Retry -the request against `POST /v1/responses`. +than labelled wrongly; check that the endpoint and the recorded `eggpass probe media` result agree on the model, the origin, and the content type. + +**`unmappable_output_item`:** The upstream Responses answer contains an output +item, content part, or annotation that Chat Completions cannot express (for +example, generated media). A non-streaming call returns HTTP 502 with this +code. In a stream, the named terminal error chunk is emitted only if no answer +content has yet been emitted. Once content, a tool call, or a refusal has been +emitted, existing suppression semantics preserve the stream's normal terminal +chunk instead. Retry the request against `POST /v1/responses`. **An agent does not run a tool:** Check that the response contains `message.tool_calls` and that the client handles OpenAI Chat Completions tool diff --git a/plans/non-text-content-proxying-audit-followup-implementation.md b/plans/non-text-content-proxying-audit-followup-implementation.md new file mode 100644 index 0000000..bbdb91f --- /dev/null +++ b/plans/non-text-content-proxying-audit-followup-implementation.md @@ -0,0 +1,118 @@ +# Non-Text Content Proxying — Audit Follow-up Corrective Plan + +**Status:** Implemented on the uncommitted corrective tree (branch `fix/pypi-classifiers-0.1.1`, HEAD `3cf9fdd` plus working-tree changes) and validated: formatting, warning-free Clippy, 535 workspace tests, locked release build, and `git diff --check` all pass. The A1 record correction is in `plans/non-text-content-proxying-corrective-implementation.md`; A2-A5 and R1 are implemented in `src/server/translate.rs` and `src/server/tests.rs`. No commit, live probe, provider login, or media-route enablement was performed, and media routes remain empty. + +**Basis:** Read-only audit of the uncommitted corrective tree described in `plans/non-text-content-proxying-corrective-implementation.md`. The audit accepted C1-C7, D1, and L1, and left five accuracy or coverage findings (A1-A5). While researching this plan, one residual silent-drop was also found outside the audit's scope (R1). Line numbers below refer to the current working tree and may move. + +## Goal + +Close the audit's accuracy and coverage gaps without changing any behavior that passed, and close one residual silent-drop of the same class the corrective work was meant to eliminate. Every measure is offline: docs, comments, tests, and one narrow projection fix. No live probe, no provider login, no media-route enablement, and no commit. + +## Findings addressed + +| # | Severity | Finding | Evidence | Effect | +| --- | --- | --- | --- | --- | +| A1 | Minor (accuracy) | The C2 plain-body intercept is latent, but the corrective plan calls it reachable | `src/server/chat.rs:208-209` treats `force_stream` as an event stream; `src/provider/openai.rs:187` sets `force_stream: true`; `src/server/aggregator.rs:97-104` already classifies a plain JSON body | The plan records a live-path fix where a non-streaming ChatGPT client already went through the aggregator. Behavior is correct; the record is not. | +| A2 | Minor (test robustness) | The C4 catalogue invariant can pass vacuously | `src/server/translate.rs:2396-2400` filters image models into an iterator with no non-empty guard | Removing `image` from every fixture model makes both provider loops assert nothing. | +| A3 | Minor (coverage) | The C5 table omits malformed-value arms | Validations at `src/server/translate.rs:70-118`, `182-200`, `221-247`, `368-395` have no table case | A regression in those named errors is not caught by the table that claims to pin every refusal. | +| A4 | Nit (coverage) | The recorded C3 probe combination is not the tested one | The table uses `["image"]` and `["audio"]` (`translate.rs:2110-2145`); the L1 record captured `["text","image"]` | The exact probed request is not pinned, though both take the same arm. | +| A5 | Nit (test robustness) | L1 sanitization checks only four key names | `src/server/translate.rs:2353-2381` asserts `request_body`, `response_body`, `prompt`, `response_text` are absent | A body or credential carried under any other key would pass. | +| R1 | Minor (pre-existing, invariant) | A `function_call` item without a `name` is silently dropped non-stream | `src/server/translate.rs:581-608` uses `filter_map` with `let name = ...?;`; `translate.rs:534-540` then yields empty content and `finish_reason: stop` | The response loses the tool call with no named error, violating the never-drop invariant. In a stream the name becomes `""` (`translate.rs:993-997`, `1048-1052`), which is unusable rather than dropped. | + +## Stages + +### Stage A1 — Make the C2 reachability record truthful and pin the native gate + +- In `plans/non-text-content-proxying-corrective-implementation.md`, replace the C2 gap-row sentence "Reachable when a 200 body carries non-null error (plain-body path calls translator directly, chat.rs:263-274)" with: "Latent in the shipped configuration: the ChatGPT spec forces streaming (`src/provider/openai.rs:187`), so a non-streaming client's 200 body reaches `aggregate_responses`, whose JSON fallback already classifies an error object (`src/server/aggregator.rs:97-104`). The plain-body intercept is defensive parity for a non-forced-stream, non-native provider and is exercised by a test that sets `force_stream = false`." +- Replace the risk bullet's claim that the path "was a bug (empty success hid failure)" with the same distinction: a non-streaming ChatGPT client already surfaced the error through the aggregator; the intercept closes the latent path for any future non-forced-stream non-native provider. +- Add a comment above the intercept at `src/server/chat.rs:256-265` stating the gate and the reachability, so a later reader does not remove `!native` as redundant. +- Add one HTTP test in `src/server/tests.rs`, `a_native_provider_error_body_is_forwarded_byte_for_byte`: + - Use `stub_spec` (xAI shape: `NativePaths::Both`, `RequestPolicy::default()`, so `force_stream: false`) via `harness`, not `chatgpt_stub_spec`. + - Stub with `Reply::json(200, ...)`, which sends `application/json`. + - POST a Chat Completions request for a model the xAI stub serves; assert the client status is 200 and the response body bytes equal the upstream body exactly. + - This test fails if the `!native` gate is removed, because the body would then be classified and rewritten. +- **Exit:** no plan sentence claims the plain-body path is a live production path; the native forwarding test fails if `!native` is dropped. Do not change `chatgpt_stub_spec` or the production policy. + +### Stage A2 — Make the C4 catalogue invariant non-vacuous + +- In `every_advertised_image_model_is_accepted_for_every_provider_spec` (`src/server/translate.rs:2396-2425`), collect the filtered models into a `Vec` once, then assert `models.len() >= 2` with a message naming the fixture. Iterate `&models` inside the provider loop instead of cloning the iterator. +- **Exit:** a fixture with no image model, or with only one, fails the test. Translator image refusal and spec drift still fail as before. + +### Stage A3 — Complete the C5 malformed-value table + +Add cases to `refusal_arms_are_named_and_mappings_are_pinned_table_driven` (`src/server/translate.rs:2091`). Each case asserts the error code and a reason fragment, not merely the field name: + +| Field | Input | Code | Asserts | +| --- | --- | --- | --- | +| `modalities` | `"text"` | `unsupported_parameter` | "must be an array containing only text" | +| `modalities` | `[]` | `unsupported_parameter` | "must contain text" | +| `modalities` | `["video"]` | `unsupported_parameter` | "no translated Chat Completions mapping" | +| `modalities` | `[1]` | `unsupported_parameter` | "no translated Chat Completions mapping" | +| `stream_options` | `"include_usage"` | `unsupported_parameter` | "must be an object containing only include_usage" | +| `reasoning_effort` | `1` | `unsupported_parameter` | "must be a string" | +| `max_tokens` | `"40"` | `unsupported_parameter` | "must be a non-negative integer" | +| `presence_penalty` | `"x"` | `unsupported_parameter` | "must be zero" | +| `logprobs` | `"yes"` | `unsupported_parameter` | "must be a boolean" | +| `response_format` | `{}` | `unsupported_parameter` | "requires a string type" | +| `response_format` | `{"type":"json_schema"}` | `unsupported_parameter` | "must be an object" | +| `response_format` | `{"type":"bogus"}` | `unsupported_parameter` | "unknown type" | + +- Do not add no-op cases (`logprobs: false`, penalty `0`, `n: 1`/`1.0`, `modalities: ["text"]`); those are already pinned as accepted or omitted. +- For `max_tokens` and `reasoning_effort`, omit `max_output_tokens` and `reasoning` so the validation arm actually runs. +- **Exit:** every branch in the request-field validation has a table case that fails on its specific reason text; no new `#[test]` function is added. + +### Stage A4 — Pin the recorded modalities combinations + +- Add `("modalities", ["text","image"], "image_requires_responses")` and `("modalities", ["text","audio"], "audio_requires_responses")` to the same table. +- **Exit:** the exact combination in `tests/fixtures/media/l1-live-probe-metadata.json` (`chat_modalities_text_and_image`) is the combination the table pins. + +### Stage A5 — Replace the L1 four-key check with a recursive allowlist + +- In `l1_probe_fixture_contains_only_sanitized_metadata` (`src/server/translate.rs:2353`), add a local helper (not a `#[test]`) that walks every object in the fixture and asserts each key is in a closed allowlist. Keep the four explicit absent-key assertions. +- Allowed keys, from the current fixture: `record_type`, `captured_on`, `retained_material`, `probes`, `case`, `request_shape`, `http_status`, `content_type`, `response_bytes`, `error_type`, `error_code`, `classification`, `response_content_shape`, `finish_reason`, `content_part_type`, `text_part_count`, `field`, `values`, `value_shape`, `candidates`, `provider`, `enabled`. +- **Exit:** adding `body`, `messages`, `text`, `token`, `authorization`, or any other unlisted key anywhere in the fixture fails the test; the current fixture passes unchanged. Adding a legitimate metadata field requires extending the list deliberately. + +### Stage R1 — Fail loud on a nameless function_call (extra residual, outside the audit) + +Evidence: non-stream, `response_tool_calls` drops a `function_call` item whose `name` is absent or not a string (`src/server/translate.rs:581-608`); if it is the only item, the projection returns empty content with `finish_reason: stop` and no `tool_calls` (`translate.rs:534-540`). This is the never-drop class C1 closed for other item kinds. In a stream, both function-call arms default the name to `""` and announce a call (`translate.rs:993-997`, `1048-1052`), which is an unusable call rather than a silent drop. + +- Non-stream: change `response_tool_calls` to return `Result, TranslateError>`. On a `function_call` item without a string `name`, return `unmappable_output_item` naming the item (`call_id`, else `id`, else "unknown"). Propagate with `?` at the call site (`translate.rs:534`). +- Stream: in both `response.output_item.added` and `response.output_item.done` function-call arms, before `register_tool_call`, if the name is missing or not a string, set `self.unmappable_item` with the item id and return `Vec::new()`. The existing terminal rule then emits the named terminal error only when nothing has been emitted, and preserves the normal terminal chunk otherwise. +- Tests: `a_nameless_function_call_is_named_not_dropped` (non-stream: code, message contains the item id, and the result is not an empty success) and `a_nameless_function_call_fails_loud_before_content` (stream: terminal `unmappable_output_item` chunk plus `[DONE]`, no empty-name tool call). +- **Exit:** no nameless `function_call` can produce empty content plus `stop`, or an empty-name tool call. The error is named and carries the item id. + +## Validation + +```sh +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace -- --test-threads=1 +cargo build --locked --release +git diff --check +``` + +A1 and R1 add three `#[test]` functions, so the expected total is **532 + 3 = 535** (root 489 + 3 = 492, auth library 32, integration 10, doctest 1). A2-A5 add cases to existing tests and one non-test helper, so they add no test functions. Record the measured total rather than assuming it; update the corrective plan's recorded 532 only after the new tests exist and pass. + +Measured on the implemented tree: **535 passed, 0 failed** (root 492 + auth library 32 + integration 10 + doctest 1). The A1 test was mutation-checked: with the `!native` gate removed it fails on `503` versus `200`, and the gate was restored before the final run. The corrective plan's recorded count is now 535. + +## Risks and rollback + +- **A3/A4 over-pinning.** Assert the error code plus a reason fragment, never byte order or full messages. If a message is reworded, update the fragment deliberately. +- **A5 allowlist maintenance.** The closed list is the point: a new metadata field fails until reviewed. Keep it beside the test. +- **R1 over-refusal.** It applies only to a malformed upstream item, names the item, and is revertible independently. It does not change well-formed tool calls. +- **A1 test fragility.** Use the xAI-shaped `stub_spec` with `RequestPolicy::default()`; do not reuse `chatgpt_stub_spec`. Assert status and body bytes only. +- **Rollback.** Each stage is independent: A1 is plan text plus a comment and one test, A2-A5 are test-only, R1 is local to the output projection. + +## Out of scope + +- Live probes, provider logins, genuine-refusal capture, and media-route enablement; media routes stay empty. +- Any change to C1-C7's accepted behavior other than R1's nameless-item path. +- OAuth custody, EggPool contract, commit, push, merge, release, or publication. + +## References + +- C2: `src/server/chat.rs:57-58` (native), `:208-209` (`is_event_stream`), `:256-265` (intercept), `:295-297` (`upstream_failure`); `src/server/aggregator.rs:97-104` (JSON fallback), `:115-143` (`status_for_code`, `classify_plain`); `src/provider/openai.rs:187` (`force_stream`). +- Tests: `src/server/tests.rs:64-70` (`Reply::json` content type), `:258-273` (`stub_spec`), `:280-311` (`chatgpt_stub_spec`), `:1799` (native forwarding); `src/server/translate.rs:2034`, `:2091`, `:2353`, `:2396`. +- Projection: `src/server/translate.rs:534-540`, `:581-608`, `:993-997`, `:1048-1052`. +- Fixture: `tests/fixtures/media/l1-live-probe-metadata.json`; `tests/fixtures/media/README.md`. +- Corrective record: `plans/non-text-content-proxying-corrective-implementation.md` (C2 row and risk bullet, test count 535). diff --git a/plans/non-text-content-proxying-corrective-implementation.md b/plans/non-text-content-proxying-corrective-implementation.md new file mode 100644 index 0000000..9509f9f --- /dev/null +++ b/plans/non-text-content-proxying-corrective-implementation.md @@ -0,0 +1,153 @@ +# Non-Text Content Proxying — Corrective Follow-up Implementation Plan + +**Status:** Corrective implementation complete; offline validation passed (formatting, warning-free Clippy, 535 workspace tests, locked release build, and whitespace checks). The refusal item is closed by a documented-schema waiver (`tests/fixtures/media/responses-refusal.json`, `responses-stream-refusal.txt`), and this corrective work enabled no media route; a later direct probe measured both providers and enabled x.ai's `POST /v1/images/generations`, recorded in `plans/non-text-content-proxying-deferred-closure-implementation.md`. No commit, push, merge, release, or publication was performed. Temporary key #22 was revoked and `target/probe-tmp/` removed; no probe credentials or raw live bodies remain in the workspace. + +**Basis:** The original read-only review examined HEAD `3cf9fdd` (on top of audited baseline `3795089`); the corrective changes described here are uncommitted working-tree changes. The earlier review verdict was **PARTIAL** — 474/474 tests passed then, G1-G2/G4/G8-G10 were implemented and tested, G3/G5 partial, and G6/G7 pass-with-caveats. The L1 record below contains status, error-code, content-shape, and endpoint-enablement metadata only; it contains no credentials, prompts, request or response bodies, response text, user data, or secrets. This follow-up closes the identified gaps without regressing existing behavior. + +## Goal + +Restore both invariants of the parent plan without breaking the 474 passing tests or the live-verified paths: + +1. **No silent drop.** Every content part, output item (including non-message items and annotations), request field, and upstream 'error' object either reaches the other side or produces a named 400/502. +2. **Truthful capabilities and docs.** What the catalogue and user docs claim matches what the translator, policies, and disabled routes actually do. + +## Corrective gaps identified in the original review + +| # | Gap at the reviewed baseline | Evidence | Effect before correction | +| --- | --- | --- | --- | +| C1 | Non-message output items (and annotations) are dropped silently; can yield empty content | 'src/server/translate.rs:444' (if kind is not message, continue); grep for web_search_call, file_search_call, code_interpreter, mcp_call, annotation across src/ returns no matches | G4 now forwards non-function tools upstream, so web_search_call / file_search_call items arrive and vanish; an only-those response becomes empty-string content, contradicting invariant 1. Only image/audio items error (translate.rs:428-437) | +| C2 | Upstream error object is discarded on the plain-body path | 'src/server/translate.rs:485' (let _ = error) replaces message with content-null plus finish_reason error, throwing away message and code | Same condition is surfaced on the aggregated path via aggregator classify_plain (aggregator.rs:109-125) mapped to statuses (chat.rs:220-236). Two paths treat one condition differently. Latent in the shipped configuration: the ChatGPT spec forces streaming (`src/provider/openai.rs:187`), so a non-streaming client's 200 body reaches `aggregate_responses`, whose JSON fallback already classifies an error object (`src/server/aggregator.rs:97-104`). The plain-body intercept is defensive parity for a non-forced-stream, non-native provider and is exercised by a test that sets `force_stream = false`. | +| C3 | Chat `modalities` and `audio` fields lacked a supported translated-path policy | Original code carried these fields; the sanitized probes below show HTTP 400 `invalid_request_error` with no code for `modalities:["text"]`, `modalities:["text","image"]`, and Chat `audio` output configuration. The selected policy is to omit text-only modalities as a no-op and refuse image/audio modalities and Chat audio configuration by name | These upstream errors are metadata evidence, not support for passing through media output; no standalone `modalities:["audio"]` probe was recorded | +| C4 | Catalogue/translator invariant test does not consult provider specs | 'src/server/translate.rs:1894-1917'; 'let _spec = crate::provider::spec_for(...)' at line 1909 is unused | Test cannot catch a spec regression (e.g. narrowed translator support vs advertised ResponsesOnly). Fixture tests/fixtures/media/chatgpt-models.json has exactly one entry | +| C5 | Stage 2 table-driven field test is missing | No test iterates CARRIED / refusal arms | modalities, audio, stream_options, service_tier, parallel_tool_calls can regress undetected. Stage 2 exit criterion unmet | +| C6 | Multi-part text is no longer byte-identical to pre-implementation | Old content_text joined text parts with newline into one input_text (verified via git show 3795089:src/server/translate.rs); new path emits one part per element (parts.rs:80-96, translate.rs:238-250) | String content and single-part arrays are byte-identical (same key set, serde_json default sorted keys, Cargo.toml:67 no preserve_order); two-text-part arrays now send two parts. No test pins either behaviour; byte-compat claim overreaches | +| C7 | 'n: 1.0' (float one) is refused | 'src/server/translate.rs:110-117' uses as_u64(), which returns None for floats | A float 1.0 for n yields unsupported_parameter instead of the intended n-equals-1 no-op | +| D1 | User docs falsely claim refuse-rather-than-dropping-silently for all fields | Code strip is correct and commented (translate.rs:68-70 before the refuse catch-all translate.rs:104-107; mirrored openai.rs:50-69, 14 fields, plus apply_policy chat.rs:359-361; xAI unaffected via empty-policy short-circuit chat.rs:343-350, test chat.rs:595-597). But docs/how-it-works.md:49-51 plus CHANGELOG line claim refusal for temperature, top_p, user, metadata plus 10 others | Users cannot learn from docs which fields are stripped by provider policy vs refused by name. Parent plan discloses the deviation; user docs do not | +| L1 | Live gaps still open | The sanitized fixture `tests/fixtures/media/l1-live-probe-metadata.json` records translated `input_audio` 400 (`audio_input_unavailable`, 117 bytes), two-text 200 (string/stop, 299 bytes), the three C3 400s (100/100/95 bytes, no error code), and xAI/OpenAI media candidates 404/disabled | Genuine refusal remains deferred for safety; no standalone `modalities:["audio"]` probe is recorded; this corrective work left both media routes disabled (x.ai's was measured and enabled later) | + +## What already works and must not regress + +- Input parts (G1/G2): parts.rs:14-46, parts.rs:56-155; image-only survives via translate.rs:277-281; tests parts.rs:211-247, translate.rs:1735. +- Tools (G4): convert_tool translate.rs:351-395; tests translate.rs:1795,1808. +- Streaming refusal plus terminal named error (G6): translate.rs:975-1010, translate.rs:1017-1034; tests translate.rs:1851,1868,1878. Emit a named terminal error chunk for an unmappable item only if no answer content has been emitted; after content, a tool call, or a refusal has been emitted, preserve the stream's normal terminal chunk under the inherited suppression semantics. +- Media routing (G8): media_paths empty on both providers (xai.rs:104, openai.rs:201); dispatch only in NotFound arm (mod.rs:482-488); verbatim forward plus Content-Type check plus ReleasingStream (media.rs:85-190); Response::stream (media.rs:186), never sse::stream (sse.rs:14-20 forces text/event-stream). Tests tests.rs:1741,1777,1794,1815,1832,1857. +- Limits/diagnostics (G9): 32 MiB default, 1-256 MiB clamp (http.rs:22-28,202-205; config.rs:746-751); 413 names bytes/MiB/cause/remedy (http.rs:565-573, test http.rs:866-887); missing_model before routing (chat.rs:32-35,384-391; media.rs:41-47), tests tests.rs:2027, chat.rs:612. +- The original review recorded 474/474 tests; the corrective tree now passes 535/535 workspace tests. Fixtures are synthetic-only (`example.invalid`, `fixture-model`), and the sanitized live-probe fixture contains metadata only. + +## Design principles (inherited plus one addition) + +1. Translate or fail; never drop. Parent principle 1, now extended to output items and the upstream error object. +2. Verbatim by default; translation only where shapes differ. +3. One projection — streaming and non-streaming share the C1/C2 mapping. +4. Facts, not hopes — C3 records the sanitized probe metadata and a chosen translated-path policy; the upstream 400s do not justify passing image/audio output through. +5. Fail before the model runs. +6. Docs are claims with tests. Any user-facing carried/stripped/refused statement names the exact field list and points at the code plus test that pins it (new for D1). + +## Staged corrective implementation + +### Stage C1 — Fail loud on non-message output items (invariant fix) + +- In responses_to_chat_completion (translate.rs:420-493), replace the silent continue at translate.rs:444 for non-message items (except already-handled function_call / reasoning) with unmappable_output_item naming kind plus id, mirroring the image/audio arm (translate.rs:436-443). +- In ResponsesToChatStream translate_event (translate.rs:814-1080), mirror the same rule: record unmappable_item for the same kinds. Emit the named terminal error chunk only when no answer content has been emitted; once content, a tool call, or a refusal has been emitted, preserve the stream's normal terminal chunk under the inherited suppression semantics. +- Annotation policy: non-empty `output_text.annotations` cannot be represented by the Chat shape, so fail with `unmappable_output_item` naming the item; absent or empty annotation lists remain compatible. Synthetic tests cover non-stream projection and annotations nested in output-text, output-item, and terminal-response stream events; no live annotation body is retained. +- **Exit:** a web_search_call / file_search_call / mcp_call upstream item yields 502 `unmappable_output_item` (non-stream); a stream emits the named terminal error chunk plus `[DONE]` only before any answer content, tool call, or refusal has been emitted. After such output is emitted, keep the normal terminal chunk plus `[DONE]` rather than replacing it with an error chunk. New unit plus HTTP stub tests use synthetic fixtures (no live bodies). + +### Stage C2 — Surface the upstream error object (parity fix) + +- Shared HTTP error path: before translation, the plain-body handler classifies a non-null upstream error with `classify_plain` and maps it through `upstream_failure`; the aggregated path uses the same status/code mapping. Both preserve the upstream message and code. +- Selected shape: return the shared OpenAI-shaped HTTP error rather than the originally proposed 200 Chat-completion envelope with `finish_reason:error` and null content. The implementation prioritizes identical status/message/code behavior across plain and aggregated paths. The translator's envelope projection remains unit-tested for direct use, but the HTTP handler intercepts top-level provider errors first. +- **Exit:** a 200 body with non-null error surfaces the upstream message plus code on both plain and aggregated paths; status mapping matches classify_plain. Tests for both paths with a synthetic error-body fixture. + +### Stage C3 — Resolve modalities / audio (plan-deviation fix) + +- Prior sanitized C3 probes, recorded in `tests/fixtures/media/l1-live-probe-metadata.json`: `modalities:["text"]` returned HTTP 400 `invalid_request_error` with no code (100-byte response body); `modalities:["text","image"]` returned the same status/type without a code (100 bytes); Chat `audio` output configuration returned the same status/type without a code (95 bytes). No response text or raw body is retained. +- Chosen translated-path policy: omit a `modalities` list containing only `text` as a no-op; treat null `modalities` and `audio` values as unset and omit them; refuse image/audio modalities with named `image_requires_responses` / `audio_requires_responses` errors, and refuse non-null Chat `audio` output configuration with named `audio_requires_responses`, before calling upstream. No standalone `modalities:["audio"]` probe is recorded; the policy is explicit, not an inferred probe result. +- These live 400 responses describe observed upstream behavior; they do not justify passing generated media through Chat Completions. Use native Responses for image/audio output. +- **Exit:** text-only modalities are omitted; image/audio modalities and Chat audio configuration are refused by name; table-driven tests cover the policy (Stage C5). + +### Stage C4 — Harden the catalogue/translator invariant test + +- Make translate.rs:1894-1917 actually use spec_for per provider (remove the _spec dead binding at line 1909): iterate every provider spec and every catalogue model advertised with image, assert the translator accepts an image_url part for that provider's shape. +- Expand tests/fixtures/media/chatgpt-models.json beyond its single entry (synthetic slugs only) so the test exercises more than one model. +- **Exit:** narrowing translator image support or mislabelling a spec fails the test. + +### Stage C5 — Add the missing Stage 2 table-driven field test + +- One test iterates every entry of CARRIED (translate.rs:40-51), every refusal arm (stop, seed, logit_bias, prediction, web_search_options, function_call-into-tools guidance, functions, logprobs, penalties, n, stream_options), the response_format / reasoning_effort / token-limit mappings, and the unknown-field catch-all (translate.rs:104-107), proving each either appears in the stub-upstream bytes or returns its named error. +- Explicitly covers modalities, audio, stream_options (incl. non-include_usage key refusal), service_tier, parallel_tool_calls, tool_choice flattening. +- **Exit:** Stage 2 exit criterion met; C3 cannot regress. + +### Stage C6 — Pin multi-part text behaviour (byte-compat narrowing) + +- Decide and document: keep per-part emission (more faithful) and narrow the byte-compat claim to string content plus single-part arrays, OR restore the newline join for full compat. Recommended: keep per-part (correctness over bytes) plus amend the parent plan's byte-compatible line and add a test pinning two-text-parts into two input_text parts. +- **Exit:** a test pins the chosen behaviour; parent-plan byte-compat wording corrected if per-part is kept. + +### Stage C7 — Accept n 1.0 float-one no-op + +- In the n arm (translate.rs:110-117), accept any JSON number equal to 1 (u64 one or f64 1.0) as the no-op; keep refusing n greater than 1 / non-1 values with unsupported_parameter. +- **Exit:** unit test for n 1, n 1.0, n 2, n string-1. + +### Stage D1 — Make docs truthful about strip-vs-refuse + +- Update docs/how-it-works.md, docs/troubleshooting.md (including the `unsupported_content_part`, `unsupported_parameter`, `image_requires_responses`, `missing_model`, and `unmappable_output_item` entries), and CHANGELOG to separate provider-policy stripping from named translation refusals. List exactly the source-ordered 14 `REJECTED_FIELDS`: `background`, `conversation`, `max_tool_calls`, `metadata`, `moderation`, `multi_agent`, `prompt`, `prompt_cache_retention`, `safety_identifier`, `temperature`, `top_logprobs`, `top_p`, `truncation`, `user`. The how-it-works list is enclosed by stable `REJECTED_FIELDS` markers. Quote the code comment at `src/server/translate.rs:68-70` and link the `unsupported_fields_are_named_and_provider_rejected_fields_stay_stripped` regression test. +- A sync guard is implemented as a unit test that reads the stable marker region in `docs/how-it-works.md` and compares its ordered field names with OpenAI `REJECTED_FIELDS`. +- **Exit:** no user-facing sentence claims refusal for a stripped field; docs name the exact lists and the sync guard validates them. + +### Stage L1 — Close the remaining live captures (gate for C3 plus fixtures) + +- Sanitized metadata is recorded in `tests/fixtures/media/l1-live-probe-metadata.json`; it contains status/error/content-shape metadata and byte counts only, with no request or response bodies. +- Translated Chat `input_audio` returned HTTP 400 with `invalid_request_error` / `audio_input_unavailable` (117-byte response body), indicating upstream gating rather than local `unsupported_content_part`. A two-text-part Chat request returned HTTP 200 with string-shaped content and `finish_reason=stop` (299-byte response body). +- The prior C3 probes were run and are detailed under Stage C3: three HTTP 400 `invalid_request_error` outcomes without an error code (response bodies 100, 100, and 95 bytes). No standalone `modalities:["audio"]` probe is recorded. +- `scripts/probe-media-endpoints.sh` returned HTTP 404 with `ENABLED=no` for both x.ai and OpenAI candidate routes, so media routing was left disabled at that point. That is proxy-enablement metadata, not evidence about either provider: a candidate that no spec declares is refused before any upstream call. +- Genuine refusal is closed by a documented-schema waiver rather than a live capture: the wire shape is confirmed against the published Responses schema and pinned by `tests/fixtures/media/responses-refusal.json` and `responses-stream-refusal.txt`, while live provider behaviour is not captured. The original plan's Stage 0 capture set is therefore incomplete for images and image generation only. Stage 6 media candidates were left disabled by this corrective work: both proxy candidate paths returned HTTP 404 with `ENABLED=no`, which records proxy enablement and says nothing about either provider, so no provider-side result existed at that time. That was closed afterwards by `eggpass probe media`, specified in `plans/non-text-content-proxying-deferred-closure-implementation.md`: on 2026-11-28 x.ai answered `200 application/json` for `grok-imagine-image-2.0` on `https://api.x.ai` and `POST /v1/images/generations` is enabled there, while ChatGPT's candidate stays disabled because its `401` answers a credential-custody question, not a path question. The temporary probe key was uniquely rematched and key #22 revoked; `target/probe-tmp/` was removed. No raw live request/response bodies or probe credentials remain in the workspace. +- **Exit:** the sanitized fixture records confirmed probe metadata and C3's policy is covered by tests. Parent-plan Stage 0 genuine-refusal capture and Stage 6 route enablement were left deferred by this corrective work for the reasons above. Both were closed afterwards, and the closure is recorded in `plans/non-text-content-proxying-deferred-closure-implementation.md`: the refusal item by the documented-schema waiver, and one route by a direct provider probe. + +## Acceptance checklist + +- [x] C1: non-message upstream items (web/file-search, MCP, image/audio) never become empty string; non-stream calls return named `unmappable_output_item`, and streams emit its named terminal error only before answer content/tool/refusal output, otherwise preserving the normal terminal chunk. +- [x] C2: upstream error message plus code survive on both plain and aggregated paths with identical status mapping. +- [x] C3: text-only modalities are omitted as a no-op; null modality/audio values are treated as unset; image/audio modalities and non-null Chat audio configuration are refused by name; table-driven tests cover the policy. +- [x] C4: invariant test consults provider specs and fails on translator/spec drift; fixture has more than one model. +- [x] C5: table-driven field test covers every CARRIED entry and refusal arm. +- [x] C6: multi-part text behaviour pinned by test; byte-compat claim matches code. +- [x] C7: float 1.0 for n accepted as no-op; non-1 refused. +- [x] D1: docs plus CHANGELOG distinguish stripped (14 fields, named) from refused; sync guard in place. +- [x] L1: redacted live fixtures added where confirmed; probe results recorded; no credentials/prompts/user media in repo; remaining Stage 0 refusal and Stage 6 media-route captures are explicitly deferred. +- [x] Full validation green (see below); no commit/push/merge/release performed. + +## Validation + +The following offline checks passed on the uncommitted corrective tree: + + cargo fmt --all -- --check + cargo clippy --workspace --all-targets -- -D warnings + cargo test --workspace -- --test-threads=1 # 535 passed for this stage + cargo build --locked --release + git diff --check + +The L1 probes were performed separately against the local daemon and are summarized above; final validation was offline. Probe command output was metadata-only. Any transient request/response artifacts and the temporary key were confined to gitignored `target/probe-tmp/`; key #22 was revoked after a unique rematch, then that directory was removed. No live probe, OAuth flow, or daemon restart was part of final validation. + +## Risks and rollback + +- C1 over-refusal. Refusing non-message items could break clients that tolerated their absence. Mitigation: the error names kind plus id so callers can retry natively; the output-projection change can be reverted if compatibility evidence warrants it. +- C2 status-mapping change. Surfacing upstream errors changes what clients see on a previously empty-success path. In the shipped configuration a non-streaming ChatGPT client already surfaced the error through the aggregator's JSON fallback; the plain-body intercept closes the latent path for any future non-forced-stream, non-native provider. Mapping reuses `classify_plain` so behaviour converges rather than invents. +- C3 compatibility. The three sampled upstream requests returned HTTP 400 `invalid_request_error` without codes; those outcomes do not establish behavior for every modality combination. The translated path omits text-only modalities and refuses image/audio output by name; use native Responses for generated media. A standalone `modalities:["audio"]` probe was not recorded. +- C4/C5 brittleness. Table-driven tests can over-pin. Keep assertions on (carried-appears-upstream) XOR (named error), not on byte order. +- Rollback. Each stage is local to translation/tests/docs except L1 fixtures (additive). Revert per-stage; media routes stay empty throughout. + +## Out of scope + +- Enabling any media route (still probe-gated empty); audio generation/transcription, file lifecycle, embeddings, moderation. +- Provider OAuth custody/login, EggPool contract, real-credential CI. +- Commit, push, merge, release, publication. + +## References + +Line numbers in the original-review evidence below refer to the reviewed baseline and may have moved in the corrective working tree. + +- Parent plan: plans/non-text-content-proxying-implementation.md (goal, invariants G1-G10, Stages 0-9, deviations). +- Translation: src/server/translate.rs:40-51 (CARRIED), :68-70 (strip plus comment), :104-107 (catch-all), :110-117 (n), :190-207 (reasoning_effort), :238-250,277-281 (message arms), :311-338 (response_format), :351-395 (convert_tool), :420-493 (output projection; :444 continue, :482-486 error discard), :658-1080 (ResponsesToChatStream; :975-1010 refusal, :1017-1034 terminal error), :1894-1917 (invariant test). +- Parts: src/server/parts.rs:14-46, :56-155, :211-247. +- Routing/policy: src/server/chat.rs:32-35 (missing_model), :220-236 (status mapping), :263-274 (plain path), :343-361 (apply_policy), :384-391 (missing_model helper); src/server/mod.rs:482-488 (NotFound-only media dispatch); src/server/media.rs:41-47, :85-190; src/server/aggregator.rs:109-125; src/server/http.rs:22-28,202-205,565-573; src/config.rs:746-751. +- Providers: src/provider/mod.rs:301-304; src/provider/openai.rs:50-69 (REJECTED_FIELDS), :103 (input_modalities), :201 (media_paths); src/provider/xai.rs:104 (media_paths). +- Tests/fixtures/docs: src/server/tests.rs:1741,1777,1794,1815,1832,1857,2027; tests/fixtures/media/ (plus README); scripts/probe-media-endpoints.sh; docs/how-it-works.md:49-51; docs/troubleshooting.md; CHANGELOG.md. diff --git a/plans/non-text-content-proxying-deferred-closure-implementation.md b/plans/non-text-content-proxying-deferred-closure-implementation.md new file mode 100644 index 0000000..59f4ef6 --- /dev/null +++ b/plans/non-text-content-proxying-deferred-closure-implementation.md @@ -0,0 +1,235 @@ +# Non-Text Content Proxying — Deferred Closure Implementation Plan + +**Status:** Implemented. D1, D2, D3, the default D6 waiver, and D7 are done. D4 ran on 2026-11-28 with explicit approval: `https://api.x.ai` answered `200 application/json` for `grok-imagine-image-2.0`, and the ChatGPT subscription token was refused with `401` at the OAuth boundary before that endpoint was exercised. D5 therefore enabled exactly one route — x.ai's `POST /v1/images/generations` — and left ChatGPT's candidate at `404`, because a `401` answers a question about credential custody, not about the path. The Stage 6 acceptance item in `plans/non-text-content-proxying-implementation.md:192` is now backed by a provider-side result, recorded in `tests/fixtures/media/l1-live-probe-metadata.json`. No credential, prompt, response body, or real user media was written to the repository, and nothing was committed. + +**Basis:** Read-only research of the working tree on branch `fix/pypi-classifiers-0.1.1`, HEAD `3cf9fdd` plus the uncommitted corrective and audit-follow-up changes. Provider facts were fetched from the vendor documentation on 2026-11-27 and are cited under "Evidence from provider documentation". Line numbers refer to the current working tree and may move. + +## Goal + +Close the two deferred items with the smallest honest change set: + +1. Replace the circular Stage 6 probe with an instrument that measures the provider, record what it measured, and enable a media route only where a real provider-side signal supports it. +2. Close the Stage 0 genuine-refusal item by recording an explicit documented-schema waiver, or by capturing one benign refusal if that is wanted, and stop describing the fixture set as merely "incomplete". + +The load-bearing constraint is that no route is enabled without a provider-side result. Everything else here is in service of making such a result obtainable and interpretable. + +## Findings + +| # | Severity | Finding | Evidence | Effect | +| --- | --- | --- | --- | --- | +| D1 | Blocker | The Stage 6 gate is circular: the probe measures the proxy's own enablement, not the provider | `scripts/probe-media-endpoints.sh:17,43` posts to `http://127.0.0.1:8787/v1/images/generations`; `src/server/mod.rs:482-488` reaches `media::handle` only in the `NotFound` arm; `src/server/media.rs:20-31` returns `None` when no spec declares the path; both specs ship `media_paths: &[]` (`src/provider/xai.rs:104`, `src/provider/openai.rs:201`) | The proxy answers its generic `404 unknown endpoint` without contacting any upstream, so `ENABLED=no` is guaranteed by construction. The recorded rows in `tests/fixtures/media/l1-live-probe-metadata.json:50-55` carry no provider signal, and the acceptance item at `:192` cannot be closed by running this script. | +| D2 | Blocker | The probe's default models are retired or superseded | `scripts/probe-media-endpoints.sh:19-20` defaults to `grok-2-image` and `gpt-image-1`; OpenAI's deprecations page lists `gpt-image-1` with a 2026-10-23 shutdown; both current guides use other slugs | A model-level rejection would be misread as "the provider does not serve this endpoint". | +| D3 | Major | Auth mode and upstream origin are not recorded, so a non-2xx is unattributable | `src/provider/xai.rs:90` sets `base_url: upstream.origin()`; `src/config.rs:41-45` maps `Api` to `https://api.x.ai` and `Build` to `https://cli-chat-proxy.grok.com` | A Build-mode result describes the Grok CLI proxy, not xAI's public API. The fixture has no field that would reveal which origin was probed. | +| D4 | Major | A provider success can be recorded as `ENABLED=no`, and the discriminating field is discarded | `src/server/media.rs:129-144` turns a 2xx with an unlisted `Content-Type` into `502 unexpected_media_content_type`; the script prints only status and content type and writes the body to `/dev/null` | A proxy-side `502` and a provider-side `401`/`403` are indistinguishable in the recorded output, and the `error.code` that separates them is thrown away. | +| D5 | Major | The documented isolation, "a temporary `EGGPASS_HOME`", cannot authenticate | `plans/non-text-content-proxying-implementation.md:129`; `src/paths.rs:3-7` relocates every file including credentials; `src/paths.rs:150-162` deliberately refuses to import the Grok CLI credential into a relocated installation; the script takes only `EGGPASS_BASE_URL` and `EGGPASS_API_KEY` | A fresh home starts signed out, and signing in there is the provider OAuth flow that is out of scope. The L1 run therefore probed the live daemon with a temporary client key, which is not what the plan describes. | +| D6 | Minor | The genuine-refusal deferral defers a shape that is already documented and pinned | `tests/fixtures/media/responses-refusal.json`, `responses-stream-refusal.txt`; the refusal fields on the Responses streaming-events reference | A live capture would confirm provider behaviour, not an unknown wire shape, so a recorded waiver is a defensible close, and one benign capture closes it more strongly. | +| D7 | Nit | The fixture's `disabled_media_routes` entry reads like a provider result | `tests/fixtures/media/l1-live-probe-metadata.json:50-54` records `provider`, `http_status`, `enabled` | A later reader can cite it as evidence about the provider. It needs a field that says what was measured. | + +## Design decision: separate the two questions + +Stage 6's exit criterion has always mixed two independent claims: + +- **Does our forwarder work?** Already answered offline. Exact-body and content-type forwarding, the `404` for an undeclared path, `405` with `Allow: POST`, `missing_model`, and `unexpected_media_content_type` are pinned at `src/server/tests.rs:1891-2042` and `src/server/media.rs:196-235`. +- **Does the subscription serve the endpoint?** This is the only open question, and it needs a provider-side answer. + +The instrument therefore should not travel through the router. A probe that runs in-process against the provider measures the subscription and nothing else, leaves no route reachable, and needs no daemon restart. + +Three instruments were considered: + +| Option | Cost | Outcome | +| --- | --- | --- | +| Add the candidate to `media_paths` in a throwaway build, restart the daemon, run the current script, revert | Two restarts; the route is live on loopback for the duration; still needs `error.code` to interpret the result | Fallback only. It does exercise the shipped route, but it exposes a route and mixes the two questions again. | +| Copy the credential store into a temporary home and run a second daemon there | A credential copy to a second location, since `EGGPASS_HOME` is the only way a relocated home can authenticate | Rejected: custody exposure for a one-off measurement. | +| **An in-process `eggpass probe media` subcommand** | New additive CLI surface, one module; no route, no restart, no credential copy | **Chosen.** The repository already makes authenticated upstream calls from the CLI outside the daemon (`src/provider/usage/xai.rs:70-76,198-204`), so both the pattern and the token reuse exist. | + +## Stages + +### Stage D1 — Correct the record before adding machinery + +No behavior change. Every item is a claim a reader could otherwise act on incorrectly. + +- In `plans/non-text-content-proxying-implementation.md`: + - `:3` — replace the sentence that says local proxy checks returned `404` with `ENABLED=no` for both media candidates with one stating that the check measured proxy enablement and could not measure provider support, because a disabled candidate is refused before any upstream call. + - `:129` — replace the `temporary EGGPASS_HOME` claim with the credential source actually used, and state that a relocated home holds no credentials (`src/paths.rs:3-7,150-162`). + - `:131` — keep the exit criterion and add that a probe result records which origin answered. + - `:192` — reword the unchecked item to state what is measured: an enabled route must be backed by a provider-side result naming status, origin, and content type, and until then the route stays `404`. + - `:204` — point the validation block at the instrument from Stage D2, and keep the script's line only as a post-enablement smoke test. +- In `plans/non-text-content-proxying-corrective-implementation.md:101-103`, state that the L1 `404`/`ENABLED=no` rows are proxy-enablement metadata, not evidence about either provider. +- In `tests/fixtures/media/l1-live-probe-metadata.json`, add `"measured": "proxy_route_enablement"`, `"provider_signal": false`, and `"upstream_contacted": false` to the `disabled_media_routes` entry. +- In `tests/fixtures/media/README.md`, say that no recorded probe has yet measured a provider media endpoint. +- In `scripts/probe-media-endpoints.sh`, change the header comment from a pre-enablement probe to a post-enablement smoke test whose pre-enablement output is proxy state only. Change no logic. +- **Exit:** no plan, fixture, README, or script sentence presents the recorded `404` as a provider result. `grep -rn "ENABLED=no" plans docs tests scripts` returns only statements that qualify it. + +### Stage D2 — Add an in-process provider probe + +New module `src/provider/media_probe.rs`, wired to an `eggpass probe media` subcommand. It uses the existing runtime rather than the router: + +- Build the runtime with `ProviderRuntime::new(id, &context.config, &context.paths)` and `UpstreamClient::with_timeouts(&runtime.spec, context.config.timeouts)`, exactly as `src/cli/commands/run.rs:248-250` does. +- Send with `upstream::send_with_auth(&client, &runtime.tokens, Method::Post, path, headers, Some(body))` (`src/upstream.rs:209`). The token never leaves the process and no client key is involved. +- Candidates live in a local table in this module keyed by `ProviderId`, not in `media_paths`, so shipping the subcommand cannot enable a route: `Xai` to `POST /v1/images/generations`, `OpenAi` to `POST /v1/images/generations`. +- Inputs: `--provider` (required), `--model` (required, no default), `--path` (optional; must match that provider's candidate), `--body` (optional path to a JSON request body), and `--json`. A model slug is validated against `[A-Za-z0-9._-]+` before it is placed in a body, mirroring `scripts/probe-media-endpoints.sh:32-36`. +- Report fields: `provider`, `candidate_path`, `request_model`, `auth_mode` (the xAI `Upstream`, from `context.config.providers.xai.upstream`), `upstream_origin` (the spec's `base_url`), `http_status`, `content_type`, `response_bytes`, `upstream_error_type`, `upstream_error_code`, and `signal_source`, which is always `provider` because nothing is proxied. +- Body handling: read the response bytes, parse only `error.type` and `error.code` when the body is JSON, then drop the body. Never print it, store it, or include it under `--json`. +- Output: a small table by default, and one JSON object with `--json`, so a recorded fixture entry is produced by the tool rather than transcribed by hand. +- Errors: a provider that is not signed in produces a named error and a nonzero exit, not a zeroed report. A transport failure reports the `UpstreamError` variant, never a body. +- Tests, all offline against `UpstreamClient::for_endpoint` (`src/upstream.rs:138`) with a loopback stub: + - a `200 application/json` reply yields `signal_source: provider` and the byte count, with no body text in either output form; + - a `401` carrying `{"error":{"type":"invalid_request_error","code":"invalid_api_key"}}` yields the type and the code, and still no body text; + - a `404` yields status and code without concluding that the provider lacks the endpoint; + - a `200` with `text/html` is reported as a content-type mismatch rather than a success; + - a missing token yields the named not-signed-in error; + - `--model` rejects a slug containing a quote or a space. +- CLI wiring: the `Command` variant (`src/cli/args.rs:14`), a parse arm beside `:319-341`, a help entry beside `:788-791`, a dispatch arm in `src/cli/mod.rs:161-170`, and one parse test beside `:1134`. +- **Exit:** the subcommand reports a provider-side status, content type, byte count, error type, error code, auth mode, and origin for a signed-in provider; a grep of its sources for `media_paths` returns nothing; no test performs live network I/O. + +### Stage D3 — Extend the fixture schema and the closed key allowlist + +- Add the Stage D2 report keys to `ALLOWED` in `assert_only_allowlisted_metadata_keys` (`src/server/translate.rs:2507`): `candidate_path`, `request_model`, `auth_mode`, `upstream_origin`, `upstream_error_type`, `upstream_error_code`, `signal_source`, `measured`, `provider_signal`, `upstream_contacted`, `probe_method`. +- Add `probe_method` to each record, so a reader knows whether a row came from `cli_direct` or from a proxied route. +- Keep the allowlist closed. Adding a legitimate field stays a deliberate edit, which is the point of Stage A5 in `plans/non-text-content-proxying-audit-followup-implementation.md`. +- **Exit:** the fixture parses, `l1_probe_fixture_contains_only_sanitized_metadata` (`:2551`) passes, and a body, prompt, token, or header key still fails the test. + +### Stage D4 — Run the probes (approval-gated, live) + +This is the only stage that touches a real credential, and it is a manual step. It is recorded as declined, not faked, if approval is not given. + +- Preconditions: the target provider is signed in; the daemon is stopped (`eggpass stop`) so two processes never refresh one token concurrently; the model slug is taken from the vendor's current guide rather than from the script default. +- Commands, one per candidate: + - `eggpass probe media --provider xai --model grok-imagine-image-2.0 --json` + - `eggpass probe media --provider openai --model gpt-image-2.5-sunburst --json` +- Record each result in `tests/fixtures/media/l1-live-probe-metadata.json` under a new `provider_media_probes` array with `probe_method: "cli_direct"` and every Stage D2 field except any body. +- Interpret, do not infer. A `2xx` with `application/json` is provider support for that model on that origin. A `401` or `403` is an auth-custody answer, not a path answer. A `404` names either the model or the path, and the record must say which was sent. A model-level rejection is recorded as such and never becomes "endpoint unsupported". +- **Exit:** either the fixture holds one provider-side result per candidate, or the plan records that the stage was declined and no route is enabled. + +### Stage D5 — Enable only what the probe confirmed + +Per provider, only when Stage D4 recorded a `2xx application/json` for that provider's origin: + +- Replace `media_paths: &[]` with `MediaPath { method: "POST", path: "/v1/images/generations", response_types: &["application/json"] }` in that provider's spec, and replace the "Candidate:" comment with the probe date, the model, and the origin that answered. +- Add a spec test per enabled provider asserting the declared method, path, and content type, so a later narrowing is a visible test change rather than a silent regression. +- Leave the other provider's `media_paths` empty, and keep the disabled-path `404` assertion in place. +- If a `2xx` arrives with a content type outside `response_types`, decide the list from the observed value and record the decision. Do not widen it to `&[]`. +- **Exit:** exactly the probe-confirmed routes are declared; every unconfirmed candidate still answers `404`; the offline suite is green. + +### Stage D6 — Close the genuine-refusal deferral + +Default, offline: record a documented-schema waiver. + +- In `plans/non-text-content-proxying-implementation.md:173`, replace the sentence deferring genuine-refusal confirmation with a statement that the refusal wire shape is confirmed against the published Responses schema and pinned by `tests/fixtures/media/responses-refusal.json` and `responses-stream-refusal.txt`, while live provider behaviour is not captured. +- In `tests/fixtures/media/README.md`, say the same in one sentence and name the two fixtures. +- This closes the item as "confirmed by documented schema" without claiming a live observation. + +Optional, only with explicit approval: one benign live refusal capture. + +- One request through the running daemon to a model that refuses benignly. A request for a photorealistic image of a named living person is the intended case. No harmful, degrading, or otherwise unsafe material is used, and no prompt is stored. +- Record the status, whether the output carried a `refusal` part or a `response.refusal.delta`, the content shape, and byte counts. Keep any request or response artifact under `target/probe-tmp/` and delete it afterwards, as L1 did. +- **Exit:** exactly one of the two paths is recorded. Neither path leaves a prompt, body, or identifier in the repository. + +### Stage D7 — Validation and records + +- Run the offline suite and record the measured total. Do not assume a count. +- Update the two parent plans' status lines to point at this plan and at the outcome reached in D4 and D5. +- Add a CHANGELOG entry for the probe subcommand, which is user-visible, and for a route only if one is enabled. +- **Exit:** this plan's count matches the measured run, any other plan's count is labelled as the measurement for its own stage, and no plan claims a completed stage that this plan records as not run. + +## Implementation record + +Measured on branch `fix/pypi-classifiers-0.1.1` over HEAD `3cf9fdd` plus the working tree. + +| Stage | Outcome | What changed | +| --- | --- | --- | +| D1 | Done | Corrected in both parent plans, the fixture, its README, the script header, and the two provider-spec candidate comments. No behavior change. | +| D2 | Done | `src/provider/media_probe.rs` (candidates, request body, report, render), `src/cli/commands/probe.rs`, `UpstreamClient::base_url()`, and the `probe media` CLI surface with its help and parse tests. Every test is offline. | +| D3 | Done | `ALLOWED_METADATA_KEYS` extended by thirteen keys; `every_reported_probe_field_is_an_allowlisted_metadata_field` and a `#[should_panic]` rejection test added. | +| D4 | Done, 2026-11-28 | Two direct probes with approval, daemon stopped. x.ai: `200 application/json`, 179 bytes, `content_type_accepted: true`, `api` mode on `https://api.x.ai`. OpenAI: `401`, `text/plain`, 239 bytes, `rejected_by_hardened_oauth_boundary` / `hardened_oauth_rule_missing`, identical on a repeat. | +| D5 | Done, one route | x.ai declares `POST /v1/images/generations` with `response_types: &["application/json"]`, plus a spec test. ChatGPT keeps `media_paths: &[]`. | +| D6 | Done, default path | Documented-schema waiver recorded in the parent plan and the fixture README. No live refusal was captured. | +| D7 | Done | This record, the checklist, `docs/commands.md`, `docs/how-it-works.md`, and the CHANGELOG. The offline suite measures 555 passing. | + +Deviations from the letter of the plan: + +- **`content_type_accepted` was added to the report**, beyond the D2 field list. Without it a `200 text/html` reads as a success in a recorded row, which is the confusion finding D4 is about. The field is `null` for a non-2xx and `true`/`false` for a 2xx, so "the provider answered, and the answer was the wrong type" stays distinguishable from "the provider refused". +- **The content-type predicate is shared with the route.** `provider::content_type_matches` now serves both `src/server/media.rs` and the probe, replacing the route's private `valid_content_type`; its test moved with it. A probe verdict therefore predicts what an enabled route will accept, instead of being a second opinion that can drift. +- **`auth_mode` is `Option`.** It names x.ai's `api` or `build`. OpenAI reports `null` because its origin is derived from the OAuth resource rather than from `providers.openai.upstream`, so naming a mode there would be a guess; the origin that was actually contacted is recorded from `UpstreamClient::base_url()`, never from config. +- **A running daemon warns instead of refusing.** The plan makes "daemon stopped" a manual precondition, so the probe restates it on stderr and proceeds rather than letting a stale PID file block a measurement. +- **`--body` cannot disagree with `--model`.** The named model is forced into the supplied JSON object and a non-object body is refused. The plan only described `--body` as a path to a body. +- **Two smaller changes came with the CLI wiring.** `eggpool_option_value` became `option_value`, because it now serves two commands, and the pre-existing 13-space indent on the `key` and `eggpool` help lines was normalised to the four spaces the other lines use. +- **The script's stale default slugs are flagged, not changed.** D1 said to change no logic in `scripts/probe-media-endpoints.sh`, and D4's precondition already says to take a slug from the vendor's guide. The header now states that the bundled defaults are historical and that a stale slug answers a model-level `404` which is not a route failure. The instrument itself has no model default at all. +- **The error parser gained a top-level fallback after the first live probe.** x.ai answers a refusal with a top-level `code` beside a string `error`, so the nested-only read the plan specified reported nothing for a `400` that did name its reason. `error_fields` now reads both shapes and `a_top_level_code_is_read_when_the_error_is_a_string` pins it. It still extracts exactly two fields, and no body text is kept. +- **The default request body became per provider.** The shared default carried an OpenAI-shaped `size`, which x.ai refuses with `400`. A later re-probe would have reproduced a rejection that says nothing about support, so `default_body` now sends each provider's documented shape and a test asserts x.ai's has no `size`. + +### What the probes measured + +Both ran with the daemon stopped, using the credential already stored for that provider. No client key, prompt, request body, or response body was retained. + +- **x.ai measured support.** `POST /v1/images/generations` on `https://api.x.ai`, model `grok-imagine-image-2.0`, `api` upstream, answered `200` with `application/json` and 179 bytes. `content_type_accepted` was `true`, so the enabled route's content-type list accepts exactly what was measured. +- **ChatGPT measured custody.** The same candidate on `https://api.openai.com`, model `gpt-image-2.5-sunburst`, answered `401` with a JSON body served as `text/plain` naming `rejected_by_hardened_oauth_boundary` / `hardened_oauth_rule_missing`; a repeat returned byte-identical metadata. A direct `curl` to the same origin without a token received OpenAI's ordinary `application/json` 401 of 160 bytes, so the difference concerns the subscription token, not the path. The endpoint was never exercised, so support is unmeasured and the route stays off. +- **The first x.ai attempt was a shape rejection, not a verdict.** The shared default body carried an OpenAI-shaped `size`; x.ai answered `400` with 53 bytes and top-level code `400`, and an unknown model produced identical metadata. That control is why the 400 was not recorded as "the model is unavailable", and why the confirmed row comes from the documented two-field shape. The shipped default is now that shape plus `n: 1`, which the same guide documents, and a unit test pins it. +- **What is not claimed.** Two probes do not establish that either provider serves any other media endpoint, model, or origin. Every recorded row names its model, origin, date, and content type for that reason. + +## Acceptance checklist + +Every item is checked. The two that needed approval were run on 2026-11-28, and D5 enabled exactly what the probe supported. + +- [x] D1: no plan, fixture, README, or script sentence presents the recorded `404` as a provider result. `grep -rn "ENABLED=no" plans docs tests scripts` returns only statements that qualify it. +- [x] D2: `eggpass probe media` reports status, content type, byte count, error type, error code, auth mode, and origin without printing or storing a body. +- [x] D2: the subcommand's sources do not read `media_paths`, and no test performs live network I/O. +- [x] D3: the fixture and the closed key allowlist agree in both directions, asserted by `every_reported_probe_field_is_an_allowlisted_metadata_field`. +- [x] D4: a provider-side result is recorded per candidate, or the stage is recorded as declined. **x.ai `200 application/json`; OpenAI `401` at the OAuth boundary, recorded as custody rather than as a path answer.** +- [x] D5: only probe-confirmed routes are declared, and every other candidate still answers `404`. **x.ai enabled and pinned by a spec test; ChatGPT keeps `media_paths: &[]`.** +- [x] D6: the refusal item is closed by a recorded waiver, with no prompt or body retained. No live refusal was captured. +- [x] D7: offline validation is green, this plan's count matches the measured run, and the parent plans' counts are labelled as the measurements for their own stages. +- [x] No credential, token, prompt, body, or real user media was written to the repository. + +## Validation + +```sh +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace -- --test-threads=1 +cargo build --locked --release +git diff --check +``` + +Record the measured total rather than predicting it. The final run measures 555 passing, up from 535: twelve `provider::media_probe` tests, five `probe` parser tests, two allowlist guard tests, and one x.ai spec test. All five commands above completed with exit `0`. + +A stage that is declined must be recorded as declined. A green suite does not stand in for Stage D4. + +## Risks and rollback + +- **Token refresh race.** An in-process probe shares the credential store with the daemon. Two processes refreshing one refresh token can invalidate the other's copy, so Stage D4 runs with the daemon stopped. This is the main reason the probe is not a background or scheduled step. +- **New CLI surface.** `eggpass probe media` is additive and cannot enable a route, but it is user-visible and needs a help entry and a CHANGELOG line. It reverts as one module, one enum variant, and one dispatch arm. +- **A probe result read as a permanent fact.** Model churn is fast: `gpt-image-1` went from current to shut down inside the recorded window. Every written result names its model, origin, and date, and Stage D5 repeats all three in the spec comment. +- **Waiver over-read.** "Confirmed against the published schema" is not "observed live". The D6 wording must keep those apart everywhere it is repeated. +- **Enabling on a stale probe.** A route enabled from a result older than the model's current lifetime ships a 403. Re-probe before enabling, and keep the spec comment dated. +- **Rollback.** D1, D3, and D6 are text and fixture edits. D2 is additive. D5 is the only behavior change, and it reverts to `media_paths: &[]` per provider. + +## Out of scope + +- Audio generation, transcription, and translation endpoints; file upload and lifecycle; embeddings; moderation. +- Any enablement of a route without a provider-side result, and any probe that uses harmful or degrading material. +- Provider OAuth custody or login changes; the EggPool ticket and tunnel contract. +- Copying the credential store, or running a second daemon against a temporary home. +- Commit, push, merge, release, or publication. + +## Evidence from provider documentation + +Fetched on 2026-11-27. These are inputs to Stage D4, not constants, and each is re-checked before a probe runs. + +- xAI image generation: `POST /v1/images/generations` on `https://api.x.ai/v1`, `Authorization: Bearer $XAI_API_KEY`, current example model `grok-imagine-image-2.0`, URLs returned by default, `n` accepted. That page documents API-key auth only. `https://docs.x.ai/developers/model-capabilities/images/generation` +- OpenAI image generation: `POST /v1/images/generations` on `https://api.openai.com/v1`, `Authorization: Bearer $OPENAI_API_KEY`, current example models `gpt-image-2.5-sunburst` and the `gpt-image-2.6-*` family, plus a note that GPT Image models may require API Organization Verification. That page documents API-key auth only. `https://developers.openai.com/api/docs/guides/image-generation` +- OpenAI deprecations: `gpt-image-1` shutdown 2026-10-23 with `gpt-image-2.5-sunburst` or `gpt-image-2.5-flare` as the replacement; `gpt-image-1-mini`, `gpt-image-1.5`, and `chatgpt-image-latest` deprecated with 2026-12-01 shutdowns. `https://developers.openai.com/api/docs/deprecations` +- Refusal wire shape: `ResponseOutputRefusal { refusal, type: "refusal" }`, `response.refusal.delta` with `delta`, `item_id`, `content_index`, `output_index`, and `sequence_number`, and `response.refusal.done`. `https://developers.openai.com/api/reference/resources/responses/streaming-events` +- The fact that matters and is documented neither way: whether a Sign-in-with-ChatGPT subscription token is accepted by `POST /v1/images/generations`. The guides show API-key auth. That is what Stage D4 measures for the OpenAI candidate. + +## References + +- Deferred items: `plans/non-text-content-proxying-implementation.md:3,129,131,173,192,204`; `plans/non-text-content-proxying-corrective-implementation.md:96-103`. +- Probe: `scripts/probe-media-endpoints.sh:17-20,32-36,40-66`; `tests/fixtures/media/l1-live-probe-metadata.json:49-55`; `tests/fixtures/media/README.md`. +- Gate: `src/server/media.rs:20-31,59-71,129-144,196-235`; `src/server/mod.rs:482-488`; `src/provider/mod.rs:95-113,190-192`; `src/provider/xai.rs:90,101-104`; `src/provider/openai.rs:198-201`; `src/config.rs:41-45`. +- Forwarding tests: `src/server/tests.rs:1891-2042` (`media_stub_spec`, exact-body forwarding, disabled `404`, `405`, `missing_model`, `unexpected_media_content_type`). +- Probe precedent: `src/provider/usage/xai.rs:70-76,198-204`; `src/cli/commands/run.rs:243-259`; `src/upstream.rs:138-142,209-215`. +- CLI wiring: `src/cli/args.rs:14,319-341,788-791,1134`; `src/cli/mod.rs:161-170`. +- Fixture guard: `src/server/translate.rs:2506-2548,2551`. +- Credential layout: `src/paths.rs:3-7,73-77,150-162`. +- Refusal fixtures: `tests/fixtures/media/responses-refusal.json`, `tests/fixtures/media/responses-stream-refusal.txt`. diff --git a/plans/non-text-content-proxying-implementation.md b/plans/non-text-content-proxying-implementation.md index 4faa05e..2359ebb 100644 --- a/plans/non-text-content-proxying-implementation.md +++ b/plans/non-text-content-proxying-implementation.md @@ -1,6 +1,6 @@ # Non-Text Content Proxying — Implementation Plan -**Status:** Implemented and verified offline. Stages 1–5 and 7–9 are implemented; Stage 6's forwarding machinery is implemented with every candidate left disabled. Stage 0 live capture and the Stage 6 live probe have not run, so the documented wire shapes and each candidate's subscription access remain unverified. No commit, push, merge, or release was performed. +**Status:** Implemented and verified. Stages 1–5 and 7–9 are implemented; Stage 6 forwarding machinery exists and one media route is enabled. The full Stage 0 capture set is incomplete: the refusal item is closed by a documented-schema waiver, with the wire shape pinned by `tests/fixtures/media/responses-refusal.json` and `responses-stream-refusal.txt` and live provider behaviour not captured. Later corrective L1 probes covered Chat `input_audio`/multipart text and C3 modalities/audio. A local proxy check returned 404 with `ENABLED=no` for both media candidates, which measures proxy enablement only: a candidate that no spec declares is refused before any upstream call, so the check cannot report provider support. That check was superseded on 2026-11-28 by `eggpass probe media`, which contacts each provider directly: x.ai answered `200 application/json` for `grok-imagine-image-2.0` on `https://api.x.ai`, so `POST /v1/images/generations` is enabled there; ChatGPT answered `401` at the OAuth boundary, so its candidate remains disabled and its support unmeasured. `plans/non-text-content-proxying-deferred-closure-implementation.md` records both probes. No commit, push, merge, or release was performed. **Basis:** Read-only audit of the current `fix/pypi-classifiers-0.1.1` tree at `3795089`, covering routing, the chat handler, the two translation directions, stream aggregation, the upstream client, and both provider specs. @@ -102,7 +102,7 @@ Output items: - An `image_generation_call` or audio item with no Chat equivalent returns `502` with a named code and the Responses id, so a client can retry natively. - The Stage 2 request-time rejection means this branch should be unreachable for well-formed traffic; it exists so that the impossible case fails loudly rather than as `""`. -**Exit:** a text-only answer is byte-shape identical to today; a refusal survives; unmappable output is an error and never an empty string. +**Exit:** string content and single-part text arrays remain byte-shape identical to today; multi-part text arrays emit one Responses text part per input part to preserve structure. A refusal survives; unmappable output is an error and never an empty string. ### Stage 4 — Streaming translation @@ -126,9 +126,9 @@ Output items: - The router matches an enabled path exactly and dispatches to a new `src/server/media.rs`. It forwards verbatim through `send_with_auth`, holds an upstream slot for the life of the response, applies the configured timeouts, and returns the upstream body with its own `Content-Type`. It must not use `sse::stream`, which forces `text/event-stream` (`sse.rs`). - Non-2xx answers reuse `upstream_error` so status, type, and code are preserved. - Candidate entries, each enabled only after a probe: xAI `POST /v1/images/generations`, OpenAI `POST /v1/images/generations`. Audio, files, embeddings, and moderation stay out of scope until separately probed. -- Add `scripts/probe-media-endpoints.sh`: it runs the smallest valid request per candidate against a temporary `EGGPASS_HOME`, and records status and content type without printing any credential. A candidate that is not 2xx stays disabled, and the route remains a `404`. +- Add `scripts/probe-media-endpoints.sh`: it sends the smallest valid request per candidate through a running daemon with a temporary EggPass client key, and records status and content type without printing any credential. It is a post-enablement smoke test, not the enablement gate: a candidate that no spec declares is refused with the proxy's `404` before any upstream call, so its output is proxy state. A temporary `EGGPASS_HOME` is not an alternative, because a relocated home holds no credentials and `src/paths.rs:150-162` deliberately refuses to import the Grok CLI credential there. A candidate that is not 2xx stays disabled, and the route remains a `404`. -**Exit:** enabled routes forward byte-exactly and stream binary bodies with the right content type; disabled candidates still answer `404`; probe results are recorded in this plan. +**Exit:** enabled routes forward byte-exactly and stream binary bodies with the right content type; disabled candidates still answer `404`; probe results are recorded in this plan, and each recorded result names the status, the origin that answered, the model that was sent, and the content type. ### Stage 7 — Limits and diagnostics @@ -166,18 +166,18 @@ Output items: | G7 | A catalogue/translator invariant test accepts an `image_url` part for every advertised image model on every provider spec. | `translate.rs` tests | | G8 | `MediaPath` is declared per provider; an enabled path is forwarded verbatim with the upstream's status, headers, and body, and its content type is checked against the spec. Dispatch runs only in the `NotFound` arm, so an undeclared path keeps the unchanged `404`. | `provider/mod.rs`; `server/media.rs`; `server/mod.rs` | | G9 | `server.max_body_bytes` defaults to 32 MiB and clamps to 1–256 MiB. The `413` names the limit and the inline-media cause. | `config.rs`; `server/http.rs` | -| G10 | 473 tests pass, including documented-shape fixtures, HTTP-level byte-identity checks for both provider shapes, refusal projection, and the media route cases. | `server/tests.rs`; `tests/fixtures/media/` | +| G10 | 473 tests passed when this stage was measured, including documented-shape fixtures, HTTP-level byte-identity checks for both provider shapes, refusal projection, and the media route cases. That number is a historical stage measurement; `plans/non-text-content-proxying-deferred-closure-implementation.md` records the current total. | `server/tests.rs`; `tests/fixtures/media/` | Deviations from the letter of the plan: -- **Stage 0 was not run.** No authorized live account was available. The fixtures are documented-shape, not captures, and `tests/fixtures/media/README.md` says so. The mapping is therefore tested at the proxy boundary, not against a live ChatGPT response. +- **The full Stage 0 capture set remains incomplete, with the refusal item closed by a documented-schema waiver.** Corrective L1 probes covered translated Chat `input_audio`, multipart text, and C3 field behavior, but did not supply Stage 0's complete verified image/image-generation capture set. The refusal wire shape is confirmed against the published Responses schema — `ResponseOutputRefusal { refusal, type: "refusal" }` and `response.refusal.delta` — and pinned by `tests/fixtures/media/responses-refusal.json` and `responses-stream-refusal.txt`; live provider behaviour is not captured, and no recorded fixture is a live refusal. Media fixtures remain synthetic/documented-shape, and no raw live request or response bodies are retained. - **Provider-rejected fields stay stripped, not refused.** `temperature`, `top_p`, `user`, `metadata`, and the rest of `openai::REJECTED_FIELDS` are provider policy: the live route rejects them, so passing them through fails the whole request. Refusing them would break every client that sends a default tuning value, contradicting the plan's own byte-compatibility requirement. The strip is commented in `translate.rs`; no other field is dropped. -- **No media route is enabled.** Both providers ship `media_paths: &[]`. The probe script is the manual step that would enable a candidate. +- **One media route is enabled, and only after a direct probe.** x.ai declares `POST /v1/images/generations` on the strength of a `200 application/json` answer from `https://api.x.ai` for `grok-imagine-image-2.0` on 2026-11-28. ChatGPT's candidate still ships `media_paths: &[]`, because its probe answered `401` at the OAuth boundary and the endpoint was never exercised. `eggpass probe media` is that instrument and `plans/non-text-content-proxying-deferred-closure-implementation.md` owns it; `scripts/probe-media-endpoints.sh` measures proxy enablement only and is a post-enablement smoke test. - **Media forwarding is POST-only.** A declared non-POST method answers `405` rather than being sent as POST. ## Acceptance checklist -Offline-verified with `cargo test --workspace -- --test-threads=1` (473 tests). Items that require a live account are left unchecked. +Offline-verified with `cargo test --workspace -- --test-threads=1` (473 tests at the time of this stage; `plans/non-text-content-proxying-deferred-closure-implementation.md` records the later total). Items that require a live account are left unchecked. - [x] A Chat Completions request carrying `image_url` reaches ChatGPT as `input_image`, with URL and `detail` preserved. - [x] An image-only message survives translation; no message is dropped for lacking text. @@ -186,10 +186,10 @@ Offline-verified with `cargo test --workspace -- --test-threads=1` (473 tests). - [x] A refusal reaches a non-streaming Chat client as a content part, not as an empty answer. - [x] A refusal reaches a streaming Chat client as `delta.refusal`. - [x] An unmappable answer or stream fails with a named error and is never empty content. -- [x] Text-only requests and responses are byte-compatible with the current behaviour. +- [x] String content and single-part text arrays are byte-compatible with the current behaviour. Multi-part text arrays are deliberately emitted as distinct Responses text parts (C6), not joined with a newline. - [x] xAI forwarding remains byte-identical for both endpoints. - [x] Every model advertised with `image` is accepted by the translator for that provider. -- [ ] Each enabled media route is probe-confirmed; unconfirmed routes answer `404` and no route forces `text/event-stream` on a binary body. No route is enabled yet, and no live probe has run. +- [x] Each enabled media route is backed by a provider-side probe result naming the HTTP status, the origin that answered, the model and date sent, and the content type; until such a result exists the candidate stays `404`. No route forces `text/event-stream` on a binary body. One route is enabled: x.ai's `POST /v1/images/generations`, on a `200 application/json` answer from `https://api.x.ai` for `grok-imagine-image-2.0` on 2026-11-28. The earlier L1 `404`/`ENABLED=no` rows are proxy-enablement metadata, not evidence about either provider, and ChatGPT's candidate is still a `404` because its `401` answers a custody question. - [x] The `413` and `missing_model` diagnostics are specific and tested. - [x] No credential, token, prompt, or real user media appears in fixtures, logs, or test output. @@ -201,10 +201,11 @@ cargo clippy --workspace --all-targets -- -D warnings cargo test --workspace -- --test-threads=1 cargo build --locked --release git diff --check -sh scripts/probe-media-endpoints.sh # Stage 6 only; requires a signed-in account +eggpass probe media --provider xai --model --json # Stage 6: measures the provider; signed-in account, daemon stopped +sh scripts/probe-media-endpoints.sh # post-enablement smoke test; before enablement its output is proxy state only ``` -The probe script is the only step that needs live credentials. Every other check runs offline against fixtures and a stub upstream. +`eggpass probe media` is the only step that needs a live credential. The smoke test needs a running daemon and a client key, and it cannot answer the Stage 6 question while the candidate is disabled. Every other check runs offline against fixtures and a stub upstream. ## Risks and rollback diff --git a/scripts/probe-media-endpoints.sh b/scripts/probe-media-endpoints.sh index 23e7dce..f2c015b 100644 --- a/scripts/probe-media-endpoints.sh +++ b/scripts/probe-media-endpoints.sh @@ -1,14 +1,25 @@ #!/usr/bin/env bash # -# Manually probe candidate image-generation routes through a running EggPass. +# Post-enablement smoke test for candidate image-generation routes, through a +# running EggPass. +# +# Before a route is enabled this script measures proxy state only: a candidate +# that no provider spec declares is answered with EggPass's own 404 before any +# upstream request is made, so ENABLED=no says nothing about the provider. Use +# `eggpass probe media` to measure the provider, and run this script afterwards +# to confirm the proxy still forwards an enabled route. # # Usage: # EGGPASS_API_KEY=... scripts/probe-media-endpoints.sh # EGGPASS_BASE_URL=http://127.0.0.1:8787 EGGPASS_API_KEY=... scripts/probe-media-endpoints.sh # EGGPASS_XAI_MODEL=grok-2-image EGGPASS_OPENAI_MODEL=gpt-image-1 scripts/probe-media-endpoints.sh # -# The server must be running with a signed-in account for each candidate. +# After enablement the server must be running with a signed-in account for each +# candidate. # Optional model overrides: EGGPASS_XAI_MODEL and EGGPASS_OPENAI_MODEL. +# The bundled defaults are historical. After enablement, set each override to +# the model that route was probed with, because a stale slug answers a +# model-level 404 that is not a route failure. # The script prints only each HTTP status and Content-Type, never the response # body, response headers, or API key. A non-2xx result is not enabled. diff --git a/src/cli/args.rs b/src/cli/args.rs index 84109c7..4a4f2af 100644 --- a/src/cli/args.rs +++ b/src/cli/args.rs @@ -7,7 +7,7 @@ use std::path::PathBuf; -use crate::provider::ProviderId; +use crate::provider::{ProviderId, media_probe}; /// The subcommand the user asked for. #[derive(Debug, Clone, PartialEq, Eq)] @@ -40,6 +40,11 @@ pub enum Command { /// Print the report as JSON. json: bool, }, + /// Measure a provider endpoint outside the proxy. + Probe { + /// What to measure. + action: ProbeAction, + }, /// Start the server as a background daemon. Run { /// Stay in the foreground instead of detaching. @@ -82,6 +87,24 @@ pub enum Command { }, } +/// What `eggpass probe` was asked to measure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProbeAction { + /// Ask a provider directly whether it serves a media endpoint. + Media { + /// The provider to ask. + provider: ProviderId, + /// The model slug to send. + model: String, + /// An explicit candidate path, when one was given. + path: Option, + /// A file holding the JSON request body, when one was given. + body: Option, + /// Print the report as JSON. + json: bool, + }, +} + /// What `eggpass key` was asked to do. #[derive(Debug, Clone, PartialEq, Eq)] pub enum KeyAction { @@ -338,6 +361,10 @@ pub fn parse>(args: I) -> Result { + let action = parse_probe_action(&rest, provider)?; + Command::Probe { action } + } "run" => { let mut foreground = false; for arg in &rest { @@ -554,6 +581,93 @@ fn parse_key_action(rest: &[String]) -> Result { } } +/// Parse the arguments of `eggpass probe`. +fn parse_probe_action( + rest: &[String], + provider: Option, +) -> Result { + let Some(first) = rest.first() else { + return Err(UsageError { + message: "`eggpass probe` needs an action (expected \"media\")".to_string(), + }); + }; + + match first.as_str() { + "media" => { + let mut model: Option = None; + let mut path: Option = None; + let mut body: Option = None; + let mut json = false; + let mut index = 1usize; + + while index < rest.len() { + let arg = rest[index].as_str(); + match arg { + "--json" => { + json = true; + index += 1; + } + _ if arg == "--model" || arg.starts_with("--model=") => { + let value = option_value(rest, &mut index, "--model", arg)?; + model = Some(value.to_string()); + } + _ if arg == "--path" || arg.starts_with("--path=") => { + let value = option_value(rest, &mut index, "--path", arg)?; + path = Some(value.to_string()); + } + _ if arg == "--body" || arg.starts_with("--body=") => { + let value = option_value(rest, &mut index, "--body", arg)?; + body = Some(PathBuf::from(value)); + } + other => { + return Err(UsageError { + message: format!("unknown option `{other}` for `eggpass probe media`"), + }); + } + } + } + + // Without a provider there is no origin to measure and no + // credential to measure it with, so this is a usage error rather + // than a guess at a default. + let Some(provider) = provider else { + return Err(UsageError { + message: "`eggpass probe media` requires `--provider` (xai or openai); \ + the origin and the credential differ per provider" + .to_string(), + }); + }; + let Some(model) = model else { + return Err(UsageError { + message: "`eggpass probe media` requires `--model`; there is no default, \ + because a retired slug measures the wrong model — take it from \ + the provider's current documentation" + .to_string(), + }); + }; + if !media_probe::valid_model_slug(&model) { + return Err(UsageError { + message: format!( + "the model slug `{model}` may contain only letters, digits, dot, \ + underscore, and hyphen" + ), + }); + } + + Ok(ProbeAction::Media { + provider, + model, + path, + body, + json, + }) + } + other => Err(UsageError { + message: format!("unknown action `{other}` for `eggpass probe` (expected \"media\")"), + }), + } +} + /// Parse the arguments of `eggpass eggpool`. fn parse_eggpool_action(rest: &[String]) -> Result { let mut revoke = false; @@ -583,7 +697,7 @@ fn parse_eggpool_action(rest: &[String]) -> Result { message: "`--control` may only be specified once".to_string(), }); } - let value = eggpool_option_value(rest, &mut index, "--control", arg)?; + let value = option_value(rest, &mut index, "--control", arg)?; control = Some(parse_eggpool_control(value)?); } _ if arg == "--server-name" || arg.starts_with("--server-name=") => { @@ -593,7 +707,7 @@ fn parse_eggpool_action(rest: &[String]) -> Result { message: "`--server-name` may only be specified once".to_string(), }); } - let value = eggpool_option_value(rest, &mut index, "--server-name", arg)?; + let value = option_value(rest, &mut index, "--server-name", arg)?; server_name = Some(value.to_string()); } _ if arg == "--ca" || arg.starts_with("--ca=") => { @@ -603,7 +717,7 @@ fn parse_eggpool_action(rest: &[String]) -> Result { message: "`--ca` may only be specified once".to_string(), }); } - let value = eggpool_option_value(rest, &mut index, "--ca", arg)?; + let value = option_value(rest, &mut index, "--ca", arg)?; ca = Some(PathBuf::from(value)); } _ if arg == "--label" || arg.starts_with("--label=") => { @@ -613,7 +727,7 @@ fn parse_eggpool_action(rest: &[String]) -> Result { message: "`--label` may only be specified once".to_string(), }); } - let value = eggpool_option_value(rest, &mut index, "--label", arg)?; + let value = option_value(rest, &mut index, "--label", arg)?; label = Some(value.to_string()); } _ if arg.starts_with('-') => { @@ -664,8 +778,8 @@ fn parse_eggpool_action(rest: &[String]) -> Result { }) } -/// Read a required EggPool option value in either `--option VALUE` or `--option=VALUE` form. -fn eggpool_option_value<'a>( +/// Read a required option value in either `--option VALUE` or `--option=VALUE` form. +fn option_value<'a>( rest: &'a [String], index: &mut usize, option: &str, @@ -759,7 +873,9 @@ pub fn global_help() -> String { edit Open the config file in your editor\n \ croncheck Start the daemon only if it is not already running\n \ update Update to the latest released version\n \ - key Issue, list and revoke the keys clients use\n eggpool Configure or revoke an EggPool connection\n\ + key Issue, list and revoke the keys clients use\n \ + eggpool Configure or revoke an EggPool connection\n \ + probe Measure a provider media endpoint directly\n\ \n\ OPTIONS:\n \ --config Use a different config file\n \ @@ -838,6 +954,18 @@ pub fn command_help(name: &str) -> String { --label NAME Optional connection label\n\ --revoke Revoke the configured EggPool connection\n" .to_string(), + "probe" => "eggpass probe media --provider ID --model SLUG [--path PATH] [--body FILE] [--json]\n\n\ + Ask a provider directly whether it serves a media candidate, outside\n\ + the proxy. The report records the status, content type, byte count,\n\ + and any error type and code; the response body is never printed or\n\ + stored. Run it with the daemon stopped, so two processes never\n\ + refresh one token.\n\n\ + --provider ID xai or openai\n\ + --model SLUG the model to send; there is no default\n\ + --path PATH an explicit candidate path, which must match\n\ + --body FILE a JSON request body instead of the default\n\ + --json print the report as JSON\n" + .to_string(), other => format!("unknown command `{other}`\n"), } } @@ -1205,6 +1333,104 @@ mod tests { assert!(text.contains("--json"), "{text}"); } + #[test] + fn probe_media_is_parsed() { + let ParseOutcome::Run(cli) = parse_args(&[ + "probe", + "media", + "--provider", + "xai", + "--model", + "grok-imagine-image-2.0", + "--json", + ]) + .unwrap() else { + panic!("expected a command") + }; + assert_eq!( + cli.command, + Command::Probe { + action: ProbeAction::Media { + provider: ProviderId::Xai, + model: "grok-imagine-image-2.0".to_string(), + path: None, + body: None, + json: true, + }, + } + ); + } + + #[test] + fn probe_media_takes_a_path_and_a_body() { + let ParseOutcome::Run(cli) = parse_args(&[ + "probe", + "media", + "--provider=openai", + "--model=gpt-image-2.5-sunburst", + "--path", + "/v1/images/generations", + "--body", + "/tmp/body.json", + ]) + .unwrap() else { + panic!("expected a command") + }; + assert_eq!( + cli.command, + Command::Probe { + action: ProbeAction::Media { + provider: ProviderId::OpenAi, + model: "gpt-image-2.5-sunburst".to_string(), + path: Some("/v1/images/generations".to_string()), + body: Some(PathBuf::from("/tmp/body.json")), + json: false, + }, + } + ); + } + + #[test] + fn probe_media_requires_a_provider_and_a_model() { + assert!(parse_args(&["probe", "media", "--model", "a-model"]).is_err()); + assert!(parse_args(&["probe", "media", "--provider", "xai"]).is_err()); + assert!(parse_args(&["probe"]).is_err()); + assert!( + parse_args(&["probe", "audio", "--provider", "xai", "--model", "a-model"]).is_err() + ); + assert!( + parse_args(&[ + "probe", + "media", + "--provider", + "xai", + "--model", + "m", + "--nope" + ]) + .is_err() + ); + } + + #[test] + fn probe_media_rejects_a_model_slug_that_is_not_a_slug() { + for model in ["grok 2", "grok\"2", "grok;2", ""] { + assert!( + parse_args(&["probe", "media", "--provider", "xai", "--model", model]).is_err(), + "accepted {model:?}" + ); + } + } + + #[test] + fn the_probe_command_has_its_own_help() { + assert!(global_help().contains("probe Measure a provider media endpoint directly")); + let ParseOutcome::Help(text) = parse_args(&["probe", "--help"]).unwrap() else { + panic!("expected help") + }; + assert!(text.contains("--model SLUG"), "{text}"); + assert!(text.contains("--json"), "{text}"); + } #[test] fn eggpool_setup_and_revoke_actions_are_parsed() { let ParseOutcome::Run(cli) = parse_args(&[ diff --git a/src/cli/commands/mod.rs b/src/cli/commands/mod.rs index 0935532..3b7cd45 100644 --- a/src/cli/commands/mod.rs +++ b/src/cli/commands/mod.rs @@ -7,6 +7,7 @@ pub mod host; pub mod key; pub mod login; pub mod port; +pub mod probe; pub mod refresh; pub mod run; pub mod status; diff --git a/src/cli/commands/probe.rs b/src/cli/commands/probe.rs new file mode 100644 index 0000000..c20c50a --- /dev/null +++ b/src/cli/commands/probe.rs @@ -0,0 +1,129 @@ +//! `eggpass probe`. +//! +//! The subcommand measures a provider endpoint outside the proxy. It exists +//! because the proxy cannot answer the question: a path that no provider spec +//! declares is refused with the proxy's own `404` before any upstream request +//! is made, so probing through the daemon would only ever measure the daemon. + +use std::path::Path; + +use crate::cli::args::ProbeAction; +use crate::cli::{CommandError, Context}; +use crate::daemon::{self, DaemonState}; +use crate::provider::{ProviderId, ProviderRuntime, media_probe}; +use crate::upstream::UpstreamClient; + +/// Run `eggpass probe`. +pub fn probe(context: &Context, action: &ProbeAction) -> Result<(), CommandError> { + match action { + ProbeAction::Media { + provider, + model, + path, + body, + json, + } => media( + context, + *provider, + model, + path.as_deref(), + body.as_deref(), + *json, + ), + } +} + +/// Measure one provider's media candidate and print what it answered. +fn media( + context: &Context, + provider: ProviderId, + model: &str, + path: Option<&str>, + body: Option<&Path>, + json: bool, +) -> Result<(), CommandError> { + if !context.config.providers.get(provider).enabled { + return Err(CommandError::new(format!( + "provider {} is disabled in configuration", + provider.as_str() + ))); + } + + let candidate = media_probe::candidate(provider); + if let Some(path) = path + && !media_probe::matches_path(candidate, path) + { + return Err(CommandError::new(format!( + "`{path}` is not the {} media candidate; the candidate path is `{}`", + provider.display_name(), + candidate.path + ))); + } + + let supplied = match body { + Some(path) => Some(std::fs::read(path).map_err(|err| { + CommandError::new(format!( + "could not read the request body from {} ({err})", + path.display() + )) + })?), + None => None, + }; + + // Two processes must not refresh one refresh token at the same moment, so + // a running daemon is named rather than silently ignored. + if matches!( + daemon::state( + &context.paths.pid_file(), + &context.config.host, + context.config.port + ), + DaemonState::Running { .. } + ) { + eprintln!( + "warning: the eggpass daemon is running and shares these credentials; \ + stop it with `eggpass stop` so two processes never refresh one token" + ); + } + + let runtime = ProviderRuntime::new(provider, &context.config, &context.paths); + let client = UpstreamClient::with_timeouts(&runtime.spec, context.config.timeouts); + + let report = media_probe::probe( + &client, + &runtime.tokens, + candidate, + model, + auth_mode(context, provider).as_deref(), + supplied.as_deref(), + ) + .map_err(|err| CommandError::new(err.to_string()))?; + + if json { + let text = serde_json::to_string_pretty(&report) + .unwrap_or_else(|err| format!("{{\"error\":\"{err}\"}}")); + println!("{text}"); + } else { + print!("{}", media_probe::render(&report)); + } + + Ok(()) +} + +/// The configured upstream, for the provider that has one. +/// +/// x.ai has two origins and a result means something different on each. Sign +/// in with ChatGPT derives its origin from the OAuth resource, so there is no +/// upstream mode to name; the report records the origin that answered. +fn auth_mode(context: &Context, provider: ProviderId) -> Option { + match provider { + ProviderId::Xai => Some( + match context.config.providers.xai.upstream { + crate::config::Upstream::Api => "api", + crate::config::Upstream::Build => "build", + } + .to_string(), + ), + ProviderId::OpenAi => None, + } +} diff --git a/src/cli/mod.rs b/src/cli/mod.rs index ebbea76..515afab 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -164,6 +164,7 @@ fn dispatch(context: &Context) -> Result<(), CommandError> { Command::Refresh { provider } => commands::refresh::refresh(context, *provider), Command::Status => commands::status::status(context), Command::Usage { provider, json } => commands::usage::usage(context, *provider, *json), + Command::Probe { action } => commands::probe::probe(context, action), Command::Run { foreground } => commands::run::run(context, *foreground), Command::Stop => commands::run::stop(context), Command::Restart => commands::run::restart(context), diff --git a/src/provider/media_probe.rs b/src/provider/media_probe.rs new file mode 100644 index 0000000..c26175c --- /dev/null +++ b/src/provider/media_probe.rs @@ -0,0 +1,821 @@ +//! Measuring a provider media endpoint directly, outside the proxy. +//! +//! `scripts/probe-media-endpoints.sh` asks the running daemon, so it measures +//! the proxy's own enablement: a path that no provider spec declares is +//! answered with the proxy's `404` before any upstream request is made. That +//! answers "is the route on?" and never "will the provider serve it". +//! +//! This module asks the provider. It sends one request through the same +//! UpstreamClient and the same token manager the daemon uses, then records the +//! status, the content type, the byte count, and — from a JSON body — only +//! `error.type` and `error.code`. The body itself is dropped and scrubbed: a +//! successful image answer carries the generated image, and an error body can +//! carry account detail, so neither is printed, stored, or serialized. +//! +//! The candidates live here rather than in a provider spec's declared route +//! list, so building this subcommand cannot enable a route. + +use serde::Serialize; +use zeroize::Zeroize; + +use crate::provider::{ProviderId, content_type_matches}; +use crate::upstream::{Method, TokenProvider, UpstreamClient, UpstreamError, send_with_auth}; + +/// A provider endpoint that may be enabled once a probe confirms it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Candidate { + /// The provider that serves the endpoint. + pub provider: ProviderId, + /// The HTTP method the endpoint takes. + pub method: Method, + /// The path, including the `/v1` prefix. + pub path: &'static str, + /// The content types a usable answer is expected to carry. + pub response_types: &'static [&'static str], +} + +impl Candidate { + /// The smallest request the endpoint accepts. + /// + /// The model is the only field that varies, and it has already been + /// checked against valid_model_slug, so it needs no escaping. The shape is + /// per provider because the two documents differ: x.ai's image guide shows + /// `model` and `prompt` and answers `400` to an OpenAI-shaped `size`, which is + /// how the first live probe of that endpoint was misread. + fn default_body(&self, model: &str) -> Vec { + let body = match self.provider { + ProviderId::Xai => serde_json::json!({ + "model": model, + "prompt": "a white 1x1 square", + "n": 1, + }), + ProviderId::OpenAi => serde_json::json!({ + "model": model, + "prompt": "a white 1x1 square", + "n": 1, + "size": "1024x1024", + }), + }; + body.to_string().into_bytes() + } +} + +/// The media candidate for a provider. +/// +/// One candidate per provider. A candidate that a probe does not confirm stays +/// here; it never reaches a provider spec. +pub fn candidate(provider: ProviderId) -> Candidate { + Candidate { + provider, + method: Method::Post, + path: "/v1/images/generations", + response_types: &["application/json"], + } +} + +/// Whether an explicit path flag names the provider's candidate. +pub fn matches_path(candidate: Candidate, path: &str) -> bool { + crate::upstream::normalize_path(path) == crate::upstream::normalize_path(candidate.path) +} + +/// Whether a model slug is safe to place in a request body. +/// +/// The rule the probe script applies: letters, digits, dot, underscore, and +/// hyphen. The slug is interpolated into a JSON document, so a quote, a space, +/// or a brace is refused rather than escaped. +pub fn valid_model_slug(model: &str) -> bool { + !model.is_empty() + && model.chars().all(|character| { + character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | '-') + }) +} + +/// The request body to send: the caller's, with the named model enforced, or +/// the candidate's smallest valid request. +pub fn request_body( + candidate: Candidate, + model: &str, + supplied: Option<&[u8]>, +) -> Result, ProbeError> { + if !valid_model_slug(model) { + return Err(ProbeError::InvalidModel(model.to_string())); + } + + let Some(supplied) = supplied else { + return Ok(candidate.default_body(model)); + }; + + let value: serde_json::Value = serde_json::from_slice(supplied) + .map_err(|err| ProbeError::InvalidBody(format!("the request body is not JSON ({err})")))?; + let serde_json::Value::Object(mut object) = value else { + return Err(ProbeError::InvalidBody( + "the request body must be a JSON object".to_string(), + )); + }; + + // One source of truth for the model: the report names what was sent, so + // the body cannot disagree with it. + object.insert( + "model".to_string(), + serde_json::Value::String(model.to_string()), + ); + serde_json::to_vec(&serde_json::Value::Object(object)) + .map_err(|err| ProbeError::InvalidBody(err.to_string())) +} + +/// Why a probe could not produce a report. +#[derive(Debug)] +pub enum ProbeError { + /// No usable credential for this provider on this machine. + NotSignedIn(String), + /// The request did not complete. + Transport { + /// Which upstream error variant this was. + variant: &'static str, + /// The error's own description, with no body and no token. + detail: String, + }, + /// The connection completed but the response body could not be read. + UnreadableBody(String), + /// The model slug is not a slug, so it was not placed in a body. + InvalidModel(String), + /// A supplied request body is not a JSON object. + InvalidBody(String), +} + +impl std::fmt::Display for ProbeError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ProbeError::NotSignedIn(detail) => { + write!(f, "no credential is available for this provider ({detail})") + } + ProbeError::Transport { variant, detail } => { + write!(f, "the provider request failed ({variant}): {detail}") + } + ProbeError::UnreadableBody(detail) => { + write!(f, "the provider response body could not be read ({detail})") + } + ProbeError::InvalidModel(model) => write!( + f, + "the model slug {model:?} may contain only letters, digits, dot, underscore, and hyphen" + ), + ProbeError::InvalidBody(detail) => write!(f, "{detail}"), + } + } +} + +impl std::error::Error for ProbeError {} + +impl From for ProbeError { + fn from(err: UpstreamError) -> ProbeError { + match err { + UpstreamError::Token(err) => ProbeError::NotSignedIn(err.to_string()), + UpstreamError::Network(detail) => ProbeError::Transport { + variant: "network", + detail, + }, + UpstreamError::Protocol(detail) => ProbeError::Transport { + variant: "protocol", + detail, + }, + } + } +} + +/// What a probe measured. +/// +/// Every field is metadata. There is no request body, response body, prompt, +/// token, or header here, and there is no field that would hold one. +#[derive(Debug, Clone, Serialize)] +pub struct Report { + /// The provider the request was sent to. + pub provider: ProviderId, + /// The path that was sent. + pub candidate_path: &'static str, + /// How the measurement was obtained. + pub probe_method: &'static str, + /// The model slug that was sent. + pub request_model: String, + /// The configured upstream, for a provider that has one. + pub auth_mode: Option, + /// The origin the request went to, as the client holds it. + pub upstream_origin: String, + /// The HTTP status the provider answered with. + pub http_status: u16, + /// The provider's content type, when it sent one. + pub content_type: Option, + /// How many bytes the provider answered with. + pub response_bytes: u64, + /// Whether a 2xx answer carried a content type the route would accept. + pub content_type_accepted: Option, + /// `error.type` from a JSON body, when there was one. + pub upstream_error_type: Option, + /// `error.code` from a JSON body, when there was one. + pub upstream_error_code: Option, + /// Where the result came from. Always the provider: nothing is proxied. + pub signal_source: &'static str, + /// What the result measures. + pub measured: &'static str, + /// Whether the result is a provider-side signal. + pub provider_signal: bool, + /// Whether an upstream was contacted at all. + pub upstream_contacted: bool, + /// The UTC date the probe ran. + pub captured_on: String, +} + +/// The JSON keys a Report produces. +/// +/// The fixture's closed key allowlist is checked against this list, so a new +/// report field cannot reach the record without a reviewed schema edit. +pub const REPORT_KEYS: &[&str] = &[ + "provider", + "candidate_path", + "probe_method", + "request_model", + "auth_mode", + "upstream_origin", + "http_status", + "content_type", + "response_bytes", + "content_type_accepted", + "upstream_error_type", + "upstream_error_code", + "signal_source", + "measured", + "provider_signal", + "upstream_contacted", + "captured_on", +]; + +/// Send one probe request and report what came back. +pub fn probe( + client: &UpstreamClient, + tokens: &dyn TokenProvider, + candidate: Candidate, + model: &str, + auth_mode: Option<&str>, + supplied_body: Option<&[u8]>, +) -> Result { + let payload = request_body(candidate, model, supplied_body)?; + let headers = [("Content-Type".to_string(), "application/json".to_string())]; + + let mut response = send_with_auth( + client, + tokens, + candidate.method, + candidate.path, + &headers, + Some(&payload), + ) + .map_err(ProbeError::from)?; + + let http_status = response.status; + let content_type = response.header("Content-Type").map(str::to_string); + let mut body = response + .read_to_vec() + .map_err(|err| ProbeError::UnreadableBody(err.to_string()))?; + + let (upstream_error_type, upstream_error_code) = error_fields(&body); + let response_bytes = body.len() as u64; + // Only the two error fields survive. Nothing else in the body is kept, + // printed, or serialized, and the bytes are scrubbed before the buffer is + // released. + body.zeroize(); + + let content_type_accepted = (200..300) + .contains(&http_status) + .then(|| content_type_matches(candidate.response_types, content_type.as_deref())); + + Ok(Report { + provider: candidate.provider, + candidate_path: candidate.path, + probe_method: "cli_direct", + request_model: model.to_string(), + auth_mode: auth_mode.map(str::to_string), + upstream_origin: client.base_url().to_string(), + http_status, + content_type, + response_bytes, + content_type_accepted, + upstream_error_type, + upstream_error_code, + signal_source: "provider", + measured: "provider_media_endpoint", + provider_signal: true, + upstream_contacted: true, + captured_on: today(), + }) +} + +/// The two error fields a JSON body may carry. +/// +/// Two shapes are read. OpenAI nests them under an `error` object. The x.ai API +/// puts a `code` at the top level beside a string `error`, which the first live +/// probe showed: reading only the nested shape reported nothing for a refusal +/// that did name its reason. A null now means neither shape carried the field, +/// not that the body was unread. +fn error_fields(body: &[u8]) -> (Option, Option) { + let Ok(value) = serde_json::from_slice::(body) else { + return (None, None); + }; + let text = |node: Option<&serde_json::Value>, name: &str| { + node.and_then(|node| node.get(name)) + .and_then(serde_json::Value::as_str) + .map(str::to_string) + }; + let error = value.get("error"); + ( + text(error, "type").or_else(|| text(Some(&value), "type")), + text(error, "code").or_else(|| text(Some(&value), "code")), + ) +} + +/// How a content-type verdict reads in the table. +fn accepted_text(accepted: Option) -> &'static str { + match accepted { + Some(true) => "yes", + Some(false) => "no (content type mismatch)", + None => "-", + } +} + +/// Render a report as an aligned label/value table. +pub fn render(report: &Report) -> String { + let text = |value: &Option| value.clone().unwrap_or_else(|| "-".to_string()); + let rows: [(&str, String); 17] = [ + ("provider", report.provider.as_str().to_string()), + ("candidate_path", report.candidate_path.to_string()), + ("probe_method", report.probe_method.to_string()), + ("request_model", report.request_model.clone()), + ("auth_mode", text(&report.auth_mode)), + ("upstream_origin", report.upstream_origin.clone()), + ("http_status", report.http_status.to_string()), + ("content_type", text(&report.content_type)), + ("response_bytes", report.response_bytes.to_string()), + ( + "content_type_accepted", + accepted_text(report.content_type_accepted).to_string(), + ), + ("upstream_error_type", text(&report.upstream_error_type)), + ("upstream_error_code", text(&report.upstream_error_code)), + ("signal_source", report.signal_source.to_string()), + ("measured", report.measured.to_string()), + ("provider_signal", report.provider_signal.to_string()), + ("upstream_contacted", report.upstream_contacted.to_string()), + ("captured_on", report.captured_on.clone()), + ]; + + // The table and the JSON must name the same fields, or a reader of one + // form would learn less than a reader of the other. + debug_assert_eq!( + rows.iter().map(|(label, _)| *label).collect::>(), + REPORT_KEYS.to_vec(), + "every report field needs a table row" + ); + + let mut out = format!("{:<22}{}\n", "FIELD", "VALUE"); + for (label, value) in rows { + out.push_str(&format!("{label:<22}{value}\n")); + } + out +} + +/// The UTC date, for the record. +fn today() -> String { + crate::timeutil::format_rfc3339(crate::timeutil::now_unix())[..10].to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::io::{BufRead, BufReader, Read, Write}; + use std::sync::{Arc, Mutex}; + + use crate::auth::refresh::TokenError; + use crate::config::Timeouts; + + /// A request the stub provider received. + #[derive(Debug, Clone)] + struct Seen { + method: String, + path: String, + headers: Vec<(String, String)>, + body: String, + } + + impl Seen { + fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.as_str()) + } + } + + /// A stub provider listening on loopback. + /// + /// Every probe here points at this stub, so no test touches a real + /// provider, a real credential, or the network. + struct Stub { + port: u16, + seen: Arc>>, + } + + impl Stub { + fn start(status: u16, content_type: Option<&'static str>, body: &'static str) -> Stub { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("the stub binds"); + let port = listener.local_addr().expect("the stub address").port(); + let seen: Arc>> = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&seen); + + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { continue }; + let sink = Arc::clone(&sink); + std::thread::spawn(move || { + let _ = serve(stream, sink, status, content_type, body); + }); + } + }); + + Stub { port, seen } + } + + fn base_url(&self) -> String { + format!("http://127.0.0.1:{}", self.port) + } + + fn client(&self) -> UpstreamClient { + UpstreamClient::for_endpoint(&self.base_url(), &[], Timeouts::default()) + } + + fn seen(&self) -> Vec { + self.seen.lock().expect("the stub sink").clone() + } + } + + /// Serve one request and answer with the fixed reply. + fn serve( + mut stream: std::net::TcpStream, + sink: Arc>>, + status: u16, + content_type: Option<&'static str>, + body: &'static str, + ) -> std::io::Result<()> { + let mut reader = BufReader::new(stream.try_clone()?); + let mut request_line = String::new(); + reader.read_line(&mut request_line)?; + let mut parts = request_line.split_whitespace(); + let method = parts.next().unwrap_or_default().to_string(); + let path = parts.next().unwrap_or_default().to_string(); + + let mut headers: Vec<(String, String)> = Vec::new(); + let mut length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line)? == 0 || line == "\r\n" || line == "\n" { + break; + } + if let Some((name, value)) = line.split_once(':') { + let name = name.trim().to_string(); + let value = value.trim().to_string(); + if name.eq_ignore_ascii_case("content-length") { + length = value.parse().unwrap_or(0); + } + headers.push((name, value)); + } + } + + let mut request_body = vec![0u8; length]; + if length > 0 { + reader.read_exact(&mut request_body)?; + } + sink.lock().expect("the stub sink").push(Seen { + method, + path, + headers, + body: String::from_utf8_lossy(&request_body).to_string(), + }); + + let mut reply = format!( + "HTTP/1.1 {status} STATUS\r\nContent-Length: {}\r\nConnection: close\r\n", + body.len() + ); + if let Some(content_type) = content_type { + reply.push_str(&format!("Content-Type: {content_type}\r\n")); + } + reply.push_str("\r\n"); + reply.push_str(body); + stream.write_all(reply.as_bytes())?; + stream.flush() + } + + /// A token provider that always hands out a token. + struct FixedToken(&'static str); + + impl TokenProvider for FixedToken { + fn token(&self) -> Result { + Ok(self.0.to_string()) + } + + fn refresh(&self, _failed: &str) -> Result { + Ok(self.0.to_string()) + } + } + + /// A token provider for a machine with no credential. + struct NoToken; + + impl TokenProvider for NoToken { + fn token(&self) -> Result { + Err(TokenError::NotLoggedIn) + } + + fn refresh(&self, _failed: &str) -> Result { + Err(TokenError::NotLoggedIn) + } + } + + fn probe_xai(stub: &Stub, model: &str) -> Result { + probe( + &stub.client(), + &FixedToken("test-token"), + candidate(ProviderId::Xai), + model, + Some("api"), + None, + ) + } + + #[test] + fn a_200_json_answer_is_a_provider_signal_with_no_body_text() { + let body = r#"{"created":1,"data":[{"url":"https://example.invalid/synthetic.png"}],"marker":"BODYTEXTMARKER"}"#; + let stub = Stub::start(200, Some("application/json"), body); + let report = probe_xai(&stub, "grok-imagine-image-2.0").expect("the probe reports"); + + assert_eq!(report.signal_source, "provider"); + assert!(report.provider_signal); + assert!(report.upstream_contacted); + assert_eq!(report.probe_method, "cli_direct"); + assert_eq!(report.measured, "provider_media_endpoint"); + assert_eq!(report.http_status, 200); + assert_eq!(report.response_bytes, body.len() as u64); + assert_eq!(report.content_type.as_deref(), Some("application/json")); + assert_eq!(report.content_type_accepted, Some(true)); + assert_eq!(report.upstream_origin, stub.base_url()); + assert_eq!(report.request_model, "grok-imagine-image-2.0"); + assert_eq!(report.candidate_path, "/v1/images/generations"); + assert_eq!(report.auth_mode.as_deref(), Some("api")); + + let table = render(&report); + let json = serde_json::to_string(&report).expect("the report serializes"); + for text in [&table, &json] { + assert!( + !text.contains("BODYTEXTMARKER"), + "the body text reached the output: {text}" + ); + assert!( + !text.contains("synthetic.png"), + "the body text reached the output: {text}" + ); + } + + let seen = stub.seen(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].method, "POST"); + assert_eq!(seen[0].path, "/v1/images/generations"); + assert_eq!(seen[0].header("authorization"), Some("Bearer test-token")); + assert_eq!( + seen[0].header("content-type"), + Some("application/json"), + "the probe must send the content type the endpoint expects" + ); + let sent: serde_json::Value = + serde_json::from_str(&seen[0].body).expect("the request body is JSON"); + assert_eq!(sent["model"], "grok-imagine-image-2.0"); + } + + #[test] + fn a_401_keeps_the_error_type_and_code_without_the_body() { + let body = r#"{"error":{"type":"invalid_request_error","code":"invalid_api_key","message":"SECRETMESSAGE"}}"#; + let stub = Stub::start(401, Some("application/json"), body); + let report = probe_xai(&stub, "grok-imagine-image-2.0").expect("the probe reports"); + + assert_eq!(report.http_status, 401); + assert_eq!( + report.upstream_error_type.as_deref(), + Some("invalid_request_error") + ); + assert_eq!( + report.upstream_error_code.as_deref(), + Some("invalid_api_key") + ); + assert_eq!( + report.content_type_accepted, None, + "a non-2xx answer has no content-type verdict" + ); + + let table = render(&report); + let json = serde_json::to_string(&report).expect("the report serializes"); + for text in [&table, &json] { + assert!( + !text.contains("SECRETMESSAGE"), + "the error message reached the output: {text}" + ); + } + + // The auth helper refreshes once after a 401 and sends again. + assert_eq!(stub.seen().len(), 2); + } + + #[test] + fn a_top_level_code_is_read_when_the_error_is_a_string() { + // x.ai answers with a top-level `code` beside a string `error`. Reading + // only a nested `error.type`/`error.code` left a live 400 unattributable. + let body = r#"{"code":"invalid_request_error","error":"SECRETMESSAGE"}"#; + let stub = Stub::start(400, Some("application/json"), body); + let report = probe_xai(&stub, "grok-imagine-image-2.0").expect("the probe reports"); + + assert_eq!(report.http_status, 400); + assert_eq!( + report.upstream_error_code.as_deref(), + Some("invalid_request_error") + ); + assert_eq!(report.upstream_error_type, None); + + let table = render(&report); + let json = serde_json::to_string(&report).expect("the report serializes"); + for text in [&table, &json] { + assert!(!text.contains("SECRETMESSAGE"), "{text}"); + } + } + + #[test] + fn a_404_records_the_status_and_the_code_without_concluding_anything() { + let body = r#"{"error":{"type":"invalid_request_error","code":"model_not_found"}}"#; + let stub = Stub::start(404, Some("application/json"), body); + let report = probe_xai(&stub, "not-a-model").expect("the probe reports"); + + assert_eq!(report.http_status, 404); + assert_eq!( + report.upstream_error_code.as_deref(), + Some("model_not_found") + ); + assert_eq!(report.content_type_accepted, None); + + // A 404 names either the model or the path. The report says which + // model was sent and stops there; it does not turn the status into a + // claim about the endpoint. + assert_eq!(report.request_model, "not-a-model"); + let table = render(&report).to_ascii_lowercase(); + assert!(!table.contains("unsupported"), "{table}"); + assert!(!table.contains("not available"), "{table}"); + } + + #[test] + fn a_200_with_the_wrong_content_type_is_a_mismatch_not_a_success() { + let stub = Stub::start(200, Some("text/html"), "BODYTEXTMARKER"); + let report = probe_xai(&stub, "grok-imagine-image-2.0").expect("the probe reports"); + + assert_eq!(report.http_status, 200); + assert_eq!(report.content_type.as_deref(), Some("text/html")); + assert_eq!(report.content_type_accepted, Some(false)); + + let table = render(&report); + assert!(table.contains("content type mismatch"), "{table}"); + assert!(!table.contains("BODYTEXTMARKER"), "{table}"); + } + + #[test] + fn a_missing_token_is_a_named_error_rather_than_a_zeroed_report() { + let stub = Stub::start(200, Some("application/json"), "{}"); + let err = probe( + &stub.client(), + &NoToken, + candidate(ProviderId::OpenAi), + "gpt-image-2.5-sunburst", + None, + None, + ) + .expect_err("a probe with no credential fails"); + + assert!(matches!(err, ProbeError::NotSignedIn(_)), "{err:?}"); + assert!(err.to_string().contains("not logged in"), "{err}"); + assert!( + stub.seen().is_empty(), + "no request may reach the provider without a credential" + ); + } + + #[test] + fn the_default_body_is_the_shape_each_provider_documents() { + let payload = request_body(candidate(ProviderId::Xai), "grok-imagine-image-2.0", None) + .expect("a body"); + let value: serde_json::Value = serde_json::from_slice(&payload).expect("the body is JSON"); + assert_eq!(value["model"], "grok-imagine-image-2.0"); + assert_eq!(value["n"], 1); + assert!(value["prompt"].is_string()); + assert!( + value.get("size").is_none(), + "x.ai answers 400 to an OpenAI-shaped `size`, which is not a verdict on the model" + ); + + let payload = request_body( + candidate(ProviderId::OpenAi), + "gpt-image-2.5-sunburst", + None, + ) + .expect("a body"); + let value: serde_json::Value = serde_json::from_slice(&payload).expect("the body is JSON"); + assert_eq!(value["model"], "gpt-image-2.5-sunburst"); + assert_eq!(value["size"], "1024x1024"); + } + + #[test] + fn a_supplied_body_keeps_its_fields_and_takes_the_named_model() { + let supplied = br#"{"prompt":"a synthetic request","model":"stale-model","n":2}"#; + let payload = request_body( + candidate(ProviderId::OpenAi), + "gpt-image-2.5-sunburst", + Some(supplied), + ) + .expect("a body"); + let value: serde_json::Value = serde_json::from_slice(&payload).expect("the body is JSON"); + assert_eq!(value["model"], "gpt-image-2.5-sunburst"); + assert_eq!(value["prompt"], "a synthetic request"); + assert_eq!(value["n"], 2); + } + + #[test] + fn a_supplied_body_that_is_not_an_object_is_refused() { + for supplied in [&b"[1,2]"[..], &b"not json"[..]] { + let err = request_body( + candidate(ProviderId::Xai), + "grok-imagine-image-2.0", + Some(supplied), + ) + .expect_err("a non-object body is refused"); + assert!(matches!(err, ProbeError::InvalidBody(_)), "{err:?}"); + } + } + + #[test] + fn a_model_slug_with_a_quote_or_a_space_never_reaches_a_body() { + for model in ["grok 2", "grok\"2", "grok;2", "grok{2}", ""] { + let err = request_body(candidate(ProviderId::Xai), model, None) + .expect_err("the slug is refused"); + assert!( + matches!(err, ProbeError::InvalidModel(_)), + "{model}: {err:?}" + ); + } + } + + #[test] + fn an_explicit_path_must_name_the_candidate() { + let route = candidate(ProviderId::Xai); + assert!(matches_path(route, "/v1/images/generations")); + assert!(matches_path(route, "/images/generations")); + assert!(!matches_path(route, "/v1/images/edits")); + } + + #[test] + fn the_report_produces_exactly_the_declared_keys() { + let report = Report { + provider: ProviderId::Xai, + candidate_path: "/v1/images/generations", + probe_method: "cli_direct", + request_model: "fixture-model".to_string(), + auth_mode: Some("api".to_string()), + upstream_origin: "https://example.invalid".to_string(), + http_status: 200, + content_type: Some("application/json".to_string()), + response_bytes: 2, + content_type_accepted: Some(true), + upstream_error_type: None, + upstream_error_code: None, + signal_source: "provider", + measured: "provider_media_endpoint", + provider_signal: true, + upstream_contacted: true, + captured_on: "2026-11-27".to_string(), + }; + + let value = serde_json::to_value(&report).expect("the report serializes"); + let mut reported: Vec<&str> = value + .as_object() + .expect("the report is an object") + .keys() + .map(String::as_str) + .collect(); + let mut declared: Vec<&str> = REPORT_KEYS.to_vec(); + reported.sort_unstable(); + declared.sort_unstable(); + assert_eq!( + reported, declared, + "REPORT_KEYS must name every field the report serializes" + ); + } +} diff --git a/src/provider/mod.rs b/src/provider/mod.rs index a81c5fe..a3375b0 100644 --- a/src/provider/mod.rs +++ b/src/provider/mod.rs @@ -7,6 +7,7 @@ //! against the spec rather than against a particular provider, so adding a //! third provider is a matter of writing one more spec. +pub mod media_probe; pub mod openai; pub mod usage; pub mod xai; @@ -112,6 +113,25 @@ pub struct MediaPath { pub response_types: &'static [&'static str], } +/// Whether a response content type is one a media route declared. +/// +/// A media route and the out-of-band probe have to judge an answer by the same +/// rule, or a probe result would not predict what the route does with the same +/// answer. Optional parameters such as `charset` are ignored. +pub fn content_type_matches(response_types: &[&str], content_type: Option<&str>) -> bool { + let Some(content_type) = content_type else { + return false; + }; + if response_types.is_empty() { + return true; + } + + let media_type = content_type.split(';').next().unwrap_or_default().trim(); + response_types + .iter() + .any(|expected| media_type.eq_ignore_ascii_case(expected)) +} + /// What a provider demands of a request body. #[derive(Debug, Clone, Copy, Default)] pub struct RequestPolicy { diff --git a/src/provider/openai.rs b/src/provider/openai.rs index 149df96..28760e3 100644 --- a/src/provider/openai.rs +++ b/src/provider/openai.rs @@ -195,9 +195,13 @@ pub fn spec(config: &crate::config::Config) -> ProviderSpec { trusted_device_hosts: &[], catalogue: CatalogueKind::SlugArray, native_paths: NativePaths::ResponsesOnly, - // Candidate: `POST /v1/images/generations`. It is enabled only after - // `scripts/probe-media-endpoints.sh` confirms the subscription serves - // it; until then the route stays a `404`. + // Candidate: `POST /v1/images/generations` on `https://api.openai.com` + // with `gpt-image-2.5-sunburst`, probed on 2026-11-28 and left + // disabled: the ChatGPT subscription token was refused with `401` + // `rejected_by_hardened_oauth_boundary` / `hardened_oauth_rule_missing`, + // which answers a question about credential custody, not about the + // path. The endpoint was never exercised, so support is unmeasured. + // Re-probe with a credential the Platform API accepts before enabling. media_paths: &[], } } diff --git a/src/provider/xai.rs b/src/provider/xai.rs index 9f7b1a9..1395fdb 100644 --- a/src/provider/xai.rs +++ b/src/provider/xai.rs @@ -4,7 +4,7 @@ //! the public Grok CLI client id. Nothing has to be rewritten on the way //! through: the request body is forwarded as it arrived. -use super::{CatalogueKind, NativePaths, ProviderId, ProviderSpec, RequestPolicy}; +use super::{CatalogueKind, MediaPath, NativePaths, ProviderId, ProviderSpec, RequestPolicy}; /// The public Grok CLI client id. /// @@ -98,10 +98,18 @@ pub fn spec(config: &crate::config::Config) -> ProviderSpec { trusted_device_hosts: &["accounts.x.ai", "auth.x.ai", "x.ai"], catalogue: CatalogueKind::DataArray, native_paths: NativePaths::Both, - // Candidate: `POST /v1/images/generations`. It is enabled only after - // `scripts/probe-media-endpoints.sh` confirms the subscription serves - // it; until then the route stays a `404`. - media_paths: &[], + // `POST /v1/images/generations` was probed on 2026-11-28 with + // `eggpass probe media`: `https://api.x.ai` answered `200` with + // `application/json` for `grok-imagine-image-2.0`. That provider-side + // result is the only evidence this list accepts, and it is dated + // because a stale entry ships a `403`; re-probe before trusting it. + // The endpoint refuses an OpenAI-shaped `size` parameter with `400`, so + // callers send `model`, `prompt`, and `n`. + media_paths: &[MediaPath { + method: "POST", + path: "/v1/images/generations", + response_types: &["application/json"], + }], } } @@ -124,4 +132,23 @@ mod tests { "https://api.x.ai/v1/models" ); } + + #[test] + fn the_probed_media_route_is_declared_exactly() { + // `eggpass probe media` recorded `200 application/json` from + // `https://api.x.ai` for `grok-imagine-image-2.0` on 2026-11-28. The + // declaration repeats exactly what was measured, so narrowing it later + // is a visible test change rather than a silent regression. + let config = crate::config::Config::default(); + let spec = spec(&config); + + assert_eq!( + spec.media_paths, + &[MediaPath { + method: "POST", + path: "/v1/images/generations", + response_types: &["application/json"], + }] + ); + } } diff --git a/src/server/aggregator.rs b/src/server/aggregator.rs index 97ed9c9..5f65cb0 100644 --- a/src/server/aggregator.rs +++ b/src/server/aggregator.rs @@ -105,8 +105,25 @@ pub fn aggregate_responses(body: impl Read) -> Result { Ok(outcome) } +/// The status and kind a non-null upstream error object maps to. +/// +/// Shared by the aggregated-stream and plain-body paths in `chat.rs` so the +/// two paths cannot drift: one condition, one mapping. +/// +/// The mapping mirrors the subscription-sharing codes the aggregated path +/// already used; anything else is a 502 server error. +pub(crate) fn status_for_code(code: Option<&str>) -> (u16, &'static str) { + match code { + Some("subscription_sharing_usage_limit_exceeded") => (429, "rate_limit_error"), + Some("subscription_sharing_user_not_eligible") => (403, "permission_error"), + Some("subscription_sharing_usage_unavailable") => (503, "server_error"), + Some("subscription_sharing_invalid_user") => (401, "invalid_request_error"), + _ => (502, "server_error"), + } +} + /// Classify a body that arrived as one JSON object rather than as a stream. -fn classify_plain(value: &Value) -> Aggregated { +pub(crate) fn classify_plain(value: &Value) -> Aggregated { // The Responses object always carries an `error` key, and it is `null` on // success. A key that is merely *present* is not a failure. let Some(error) = value.get("error").filter(|error| !error.is_null()) else { diff --git a/src/server/chat.rs b/src/server/chat.rs index 6e65e91..3c3f0cc 100644 --- a/src/server/chat.rs +++ b/src/server/chat.rs @@ -221,18 +221,11 @@ pub fn complete(request: &Request, context: &ServerContext) -> Response { Response::bytes(200, headers, bytes) } Aggregated::Failed { code, message } => { - let (status, kind) = match code.as_deref() { - Some("subscription_sharing_usage_limit_exceeded") => (429, "rate_limit_error"), - Some("subscription_sharing_user_not_eligible") => (403, "permission_error"), - Some("subscription_sharing_usage_unavailable") => (503, "server_error"), - Some("subscription_sharing_invalid_user") => (401, "invalid_request_error"), - _ => (502, "server_error"), - }; // The upstream answered 200 and reported the failure in the - // stream. The proxy answers the client with the status the - // code stands for, and that is the code that is remembered. - context.record_inference(provider_id, status); - openai_error(status, &message, kind) + // stream. The plain-body path uses the same mapper below. + let failure = upstream_failure(code.as_deref(), &message); + context.record_inference(provider_id, failure.status); + failure } Aggregated::Incomplete => { context.record_inference(provider_id, 502); @@ -260,6 +253,28 @@ pub fn complete(request: &Request, context: &ServerContext) -> Response { }; context.release_upstream_slot(); + // A successful HTTP status can still carry a Responses error object. + // Classify it before translation so the plain-body path preserves the + // same message, code, and status mapping as the aggregated stream path. + // + // `!native` is load-bearing: a native provider speaks the client's shape, + // so its 200 body is forwarded byte for byte and reclassifying it would + // rewrite a body the client's provider understands. In the shipped + // configuration this intercept is latent for ChatGPT, whose spec forces + // streaming (`src/provider/openai.rs`): a non-streaming client's 200 body + // is collapsed by `aggregate_responses`, whose JSON fallback already + // classifies an error object. The intercept is defensive parity for any + // future non-forced-stream, non-native provider; the gate is pinned by + // `a_native_provider_error_body_is_forwarded_byte_for_byte`. + if !native + && let Ok(value) = serde_json::from_slice::(&bytes) + && let Aggregated::Failed { code, message } = aggregator::classify_plain(&value) + { + let failure = upstream_failure(code.as_deref(), &message); + context.record_inference(provider_id, failure.status); + return failure; + } + let bytes = if native { bytes } else { @@ -283,6 +298,15 @@ pub fn complete(request: &Request, context: &ServerContext) -> Response { Response::bytes(status, headers, bytes) } +/// Map an upstream Responses error code to a client error response. +/// +/// This is shared by the plain-body and aggregated-stream paths so message, +/// code, and status cannot drift between them. +fn upstream_failure(code: Option<&str>, message: &str) -> Response { + let (status, kind) = aggregator::status_for_code(code); + openai_error_with_code(status, message, kind, code) +} + /// The upstream's error, in the OpenAI error shape. /// /// The upstream's status, type and code are kept. A client that asked for a diff --git a/src/server/media.rs b/src/server/media.rs index 7ed0b9a..e6218d1 100644 --- a/src/server/media.rs +++ b/src/server/media.rs @@ -6,7 +6,7 @@ use serde_json::Value; -use crate::provider::MediaPath; +use crate::provider::{MediaPath, content_type_matches}; use crate::upstream::{self, Method, UpstreamError}; use super::{ @@ -126,7 +126,7 @@ pub fn handle(request: &Request, context: &ServerContext) -> Option { } let content_type = response.header("Content-Type").map(str::to_string); - if !valid_content_type(route.response_types, content_type.as_deref()) { + if !content_type_matches(route.response_types, content_type.as_deref()) { context.release_upstream_slot(); context.record_inference(provider_id, 502); let arrived = content_type.as_deref().unwrap_or("missing"); @@ -178,21 +178,6 @@ fn match_media_path<'a>(media_paths: &'a [MediaPath], path: &str, method: &str) } } -/// Check the upstream's media type, ignoring optional parameters such as charset. -fn valid_content_type(response_types: &[&str], content_type: Option<&str>) -> bool { - let Some(content_type) = content_type else { - return false; - }; - if response_types.is_empty() { - return true; - } - - let media_type = content_type.split(';').next().unwrap_or_default().trim(); - response_types - .iter() - .any(|expected| media_type.eq_ignore_ascii_case(expected)) -} - #[cfg(test)] mod tests { use super::*; @@ -221,16 +206,19 @@ mod tests { #[test] fn content_type_allowlist_checks_the_type_before_parameters() { - assert!(valid_content_type( + // The route and the out-of-band probe share this rule; a route that + // accepted a type the probe called a mismatch would make a recorded + // result meaningless. + assert!(content_type_matches( &["application/json"], Some("application/json; charset=utf-8"), )); - assert!(!valid_content_type( + assert!(!content_type_matches( &["application/json"], Some("image/png"), )); - assert!(!valid_content_type(&["application/json"], None)); - assert!(valid_content_type(&[], Some("image/png"))); - assert!(!valid_content_type(&[], None)); + assert!(!content_type_matches(&["application/json"], None)); + assert!(content_type_matches(&[], Some("image/png"))); + assert!(!content_type_matches(&[], None)); } } diff --git a/src/server/tests.rs b/src/server/tests.rs index 9c4ac55..b07d09b 100644 --- a/src/server/tests.rs +++ b/src/server/tests.rs @@ -1491,6 +1491,141 @@ fn a_streamed_response_without_a_content_type_reaches_a_streaming_client() { assert!(text.contains("[DONE]"), "{text}"); } +#[test] +fn plain_responses_error_keeps_message_code_and_status() { + let upstream_body = r#"{"error":{"code":"subscription_sharing_usage_limit_exceeded","message":"synthetic quota limit"}}"#; + let stub = Stub::start(move |_| Reply::json(200, upstream_body)); + let mut spec = chatgpt_stub_spec(&stub); + spec.policy.force_stream = false; + let harness = harness_with_spec(&stub, "secret-key", "chatgpt-token", spec); + + let response = agent() + .post(harness.url("/v1/chat/completions")) + .header("Authorization", "Bearer secret-key") + .header("Content-Type", "application/json") + .send(json!({"model":"gpt-5.6-sol","messages":[]}).to_string()) + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 429); + let body = read_json_body(response); + assert_eq!(body["error"]["message"], "synthetic quota limit"); + assert_eq!( + body["error"]["code"], + "subscription_sharing_usage_limit_exceeded" + ); + assert_eq!(body["error"]["type"], "rate_limit_error"); +} + +#[test] +fn aggregated_responses_error_keeps_message_code_and_status() { + let upstream_body = r#"{"error":{"code":"subscription_sharing_usage_limit_exceeded","message":"synthetic quota limit"}}"#; + let stub = Stub::start(move |_| Reply::json(200, upstream_body)); + let harness = harness_with_spec( + &stub, + "secret-key", + "chatgpt-token", + chatgpt_stub_spec(&stub), + ); + + let response = agent() + .post(harness.url("/v1/chat/completions")) + .header("Authorization", "Bearer secret-key") + .header("Content-Type", "application/json") + .send(json!({"model":"gpt-5.6-sol","messages":[]}).to_string()) + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 429); + let body = read_json_body(response); + assert_eq!(body["error"]["message"], "synthetic quota limit"); + assert_eq!( + body["error"]["code"], + "subscription_sharing_usage_limit_exceeded" + ); + assert_eq!(body["error"]["type"], "rate_limit_error"); +} + +#[test] +fn an_unmappable_non_message_response_is_a_named_http_error() { + let upstream_body = r#"{"id":"resp_fixture","status":"completed","output":[{"type":"file_search_call","id":"fs_fixture"}]}"#; + let stub = Stub::start(move |_| Reply::json(200, upstream_body)); + let harness = harness_with_spec( + &stub, + "secret-key", + "chatgpt-token", + chatgpt_stub_spec(&stub), + ); + + let response = agent() + .post(harness.url("/v1/chat/completions")) + .header("Authorization", "Bearer secret-key") + .header("Content-Type", "application/json") + .send(json!({"model":"gpt-5.6-sol","messages":[]}).to_string()) + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 502); + let body = read_json_body(response); + assert_eq!(body["error"]["code"], "unmappable_output_item"); + assert!( + body["error"]["message"] + .as_str() + .unwrap() + .contains("file_search_call") + ); + assert!( + body["error"]["message"] + .as_str() + .unwrap() + .contains("fs_fixture") + ); +} + +#[test] +fn an_unmappable_stream_item_emits_a_terminal_named_error() { + let stub = Stub::start(|request| { + if request.path.starts_with("/v1/responses") { + Reply::Stream { + status: 200, + content_type: "text/event-stream", + chunks: vec![ + ( + Duration::from_millis(0), + "data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"file_search_call\",\"id\":\"fs_fixture\"}}\n\n".to_string(), + ), + ( + Duration::from_millis(0), + "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\"}}\n\n".to_string(), + ), + ], + } + } else { + Reply::json(404, "{}") + } + }); + let harness = harness_with_spec( + &stub, + "secret-key", + "chatgpt-token", + chatgpt_stub_spec(&stub), + ); + + let response = agent() + .post(harness.url("/v1/chat/completions")) + .header("Authorization", "Bearer secret-key") + .header("Content-Type", "application/json") + .send(json!({"model":"gpt-5.6-sol","messages":[],"stream":true}).to_string()) + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 200); + let body = response.into_body().read_to_string().expect("stream body"); + assert!(body.contains(r#""finish_reason":"error""#), "{body}"); + assert!( + body.contains(r#""code":"unmappable_output_item""#), + "{body}" + ); + assert!(body.contains("fs_fixture"), "{body}"); + assert!(body.contains("data: [DONE]"), "{body}"); +} + #[test] fn usage_route_is_authenticated_cached_and_attaches_fresh_inference_state() { let stub = Stub::start(|request| { @@ -1727,6 +1862,32 @@ fn a_native_responses_request_is_forwarded_untouched() { ); } +#[test] +fn a_native_provider_error_body_is_forwarded_byte_for_byte() { + // A native provider speaks the client's shape, so a 200 body is the + // client's to interpret — even when it carries an error object. The + // `!native` gate on the plain-body classifier is what keeps this body + // untouched; without it the proxy would rewrite it into its own error + // shape and change the status. + let upstream_body = r#"{"error":{"type":"server_error","code":"subscription_sharing_usage_unavailable","message":"the shared allowance is unavailable"}}"#; + let stub = Stub::start(move |_| Reply::json(200, upstream_body)); + let harness = harness(&stub, "secret-key", "grok-token"); + + let response = agent() + .post(harness.url("/v1/chat/completions")) + .header("Authorization", "Bearer secret-key") + .header("Content-Type", "application/json") + .send(chat_body().to_string()) + .expect("the proxy answers"); + + assert_eq!(response.status().as_u16(), 200); + let body = response.into_body().read_to_string().expect("body text"); + assert_eq!( + body, upstream_body, + "a native provider's body must not be reclassified or rewritten" + ); +} + fn media_stub_spec(stub: &Stub) -> ProviderSpec { let mut spec = stub_spec(stub); spec.media_paths = &[MediaPath { diff --git a/src/server/translate.rs b/src/server/translate.rs index 99ddb13..3d175b0 100644 --- a/src/server/translate.rs +++ b/src/server/translate.rs @@ -46,8 +46,6 @@ const CARRIED: &[&str] = &[ "stream", "store", "service_tier", - "modalities", - "audio", ]; pub fn chat_request_to_responses(body: &[u8]) -> Result, TranslateError> { @@ -65,6 +63,61 @@ pub fn chat_request_to_responses(body: &[u8]) -> Result, TranslateError> }; let mut output = serde_json::Map::new(); for (field, value) in object { + if matches!(field.as_str(), "modalities" | "audio") && value.is_null() { + // Optional output configuration serialized as null is unset. + continue; + } + if field == "modalities" { + let Some(modalities) = value.as_array() else { + return Err(unsupported_parameter( + "modalities", + "must be an array containing only text for the translated path", + )); + }; + if modalities.is_empty() { + return Err(unsupported_parameter( + "modalities", + "must contain text or use the native Responses API for other modalities", + )); + } + if modalities + .iter() + .all(|modality| modality.as_str() == Some("text")) + { + // Text is the translated path's only output modality. It is + // the default, so omit the Chat-only field rather than pass + // it through to the Responses endpoint. + continue; + } + if modalities + .iter() + .any(|modality| modality.as_str() == Some("audio")) + { + return Err(TranslateError::new( + "audio_requires_responses", + "audio output modalities require the native Responses API", + )); + } + if modalities + .iter() + .any(|modality| modality.as_str() == Some("image")) + { + return Err(TranslateError::new( + "image_requires_responses", + "image output modalities require the native Responses API", + )); + } + return Err(unsupported_parameter( + "modalities", + "contains a modality with no translated Chat Completions mapping", + )); + } + if field == "audio" { + return Err(TranslateError::new( + "audio_requires_responses", + "Chat audio output configuration requires the native Responses API", + )); + } if crate::provider::openai::REJECTED_FIELDS.contains(&field.as_str()) { // This is provider policy from the live route, not an omission; passing these through makes the upstream reject the whole request. continue; @@ -113,8 +166,12 @@ pub fn chat_request_to_responses(body: &[u8]) -> Result, TranslateError> json!({"format":map_response_format(format)?}), ); } + // A float 1.0 names the same single choice as the integer 1; anything + // else has no Responses equivalent. `as_u64` returns `None` for floats, + // so both spellings are checked. if let Some(n) = object.get("n").filter(|value| !value.is_null()) && n.as_u64() != Some(1) + && n.as_f64() != Some(1.0) { return Err(unsupported_parameter( "n", @@ -433,7 +490,12 @@ pub fn responses_to_chat_completion(body: &[u8]) -> Result, TranslateErr .and_then(Value::as_str) .unwrap_or("unknown"); let id = item.get("id").and_then(Value::as_str).unwrap_or("unknown"); - if kind == "image_generation_call" || kind.starts_with("audio") { + if kind == "function_call" || kind == "reasoning" { + // Tool calls and thinking are projected separately via + // response_tool_calls / response_reasoning below. + continue; + } + if kind != "message" { return Err(TranslateError::new( "unmappable_output_item", format!( @@ -441,9 +503,6 @@ pub fn responses_to_chat_completion(body: &[u8]) -> Result, TranslateErr ), )); } - if kind != "message" { - continue; - } for part in item .get("content") .and_then(Value::as_array) @@ -451,7 +510,15 @@ pub fn responses_to_chat_completion(body: &[u8]) -> Result, TranslateErr .flatten() { match part.get("type").and_then(Value::as_str).unwrap_or("unknown") { - "output_text" => parts.push(json!({"type":"text","text":part.get("text").and_then(Value::as_str).unwrap_or("")})), + "output_text" => { + // Web-search citations arrive as `annotations` on the text part. The Chat + // Completions string shape has nowhere to carry them, so a populated + // list is named rather than stripped. + if part.get("annotations").and_then(Value::as_array).is_some_and(|list| !list.is_empty()) { + return Err(TranslateError::new("unmappable_output_item", format!("Responses output content part output_text in item {id} carries annotations with no Chat Completions equivalent"))); + } + parts.push(json!({"type":"text","text":part.get("text").and_then(Value::as_str).unwrap_or("")})); + } "refusal" => parts.push(json!({"type":"refusal","refusal":part.get("refusal").and_then(Value::as_str).unwrap_or("")})), other => return Err(TranslateError::new("unmappable_output_item", format!("Responses output content part {other} in item {id} has no Chat Completions equivalent"))), } @@ -464,7 +531,7 @@ pub fn responses_to_chat_completion(body: &[u8]) -> Result, TranslateErr { content = Value::Array(parts); } - let tool_calls = response_tool_calls(&value); + let tool_calls = response_tool_calls(&value)?; let mut reason = finish_reason(&value); if !tool_calls.is_empty() { reason = "tool_calls"; @@ -479,12 +546,22 @@ pub fn responses_to_chat_completion(body: &[u8]) -> Result, TranslateErr if !reasoning.is_empty() { choices[0]["message"]["reasoning_content"] = json!(reasoning); } - if let Some(error) = value.get("error").filter(|error| !error.is_null()) { + let upstream_error = value.get("error").filter(|error| !error.is_null()); + if upstream_error.is_some() { choices[0]["message"] = json!({"role":"assistant","content":Value::Null}); choices[0]["finish_reason"] = json!("error"); - let _ = error; } let mut output = json!({"id":chat_id(value.get("id").and_then(Value::as_str)),"object":"chat.completion","created":now_unix(),"model":value.get("model").and_then(Value::as_str).unwrap_or(""),"choices":choices}); + if let Some(error) = upstream_error { + let mut mapped = json!({ + "message": error.get("message").and_then(Value::as_str).unwrap_or("the request failed"), + "type": error.get("type").and_then(Value::as_str).unwrap_or("server_error"), + }); + if let Some(code) = error.get("code").and_then(Value::as_str) { + mapped["code"] = json!(code); + } + output["error"] = mapped; + } if let Some(usage) = responses_usage_to_chat(value.get("usage")) { output["usage"] = usage; } @@ -501,33 +578,55 @@ pub fn responses_to_chat_completion(body: &[u8]) -> Result, TranslateErr /// /// The `call_id` is the client's handle on the call, so it is preferred over /// the item's own id. -fn response_tool_calls(value: &Value) -> Vec { +/// +/// A call without a name is a named error, not a drop: an empty function name +/// is not a call a client can make, and omitting the item would turn a failed +/// answer into an empty success. +fn response_tool_calls(value: &Value) -> Result, TranslateError> { let Some(output) = value.get("output").and_then(Value::as_array) else { - return Vec::new(); + return Ok(Vec::new()); }; - output - .iter() - .filter(|item| item.get("type").and_then(Value::as_str) == Some("function_call")) - .filter_map(|item| { - let name = item.get("name").and_then(Value::as_str)?; - let arguments = item - .get("arguments") - .and_then(Value::as_str) - .unwrap_or("{}"); - let id = item - .get("call_id") - .and_then(Value::as_str) - .or_else(|| item.get("id").and_then(Value::as_str)) - .unwrap_or_default(); + let mut calls = Vec::new(); + for item in output { + if item.get("type").and_then(Value::as_str) != Some("function_call") { + continue; + } + let Some(name) = item.get("name").and_then(Value::as_str) else { + return Err(nameless_function_call_error(item)); + }; + let arguments = item + .get("arguments") + .and_then(Value::as_str) + .unwrap_or("{}"); + let id = item + .get("call_id") + .and_then(Value::as_str) + .or_else(|| item.get("id").and_then(Value::as_str)) + .unwrap_or_default(); - Some(json!({ - "id": id, - "type": "function", - "function": { "name": name, "arguments": arguments }, - })) - }) - .collect() + calls.push(json!({ + "id": id, + "type": "function", + "function": { "name": name, "arguments": arguments }, + })); + } + Ok(calls) +} + +/// The named error for a `function_call` with no usable name. +fn nameless_function_call_error(item: &Value) -> TranslateError { + let id = item + .get("call_id") + .and_then(Value::as_str) + .or_else(|| item.get("id").and_then(Value::as_str)) + .unwrap_or("unknown"); + TranslateError::new( + "unmappable_output_item", + format!( + "Responses output item function_call (id {id}) has no function name and cannot be mapped to a Chat Completions tool call" + ), + ) } /// The assistant text in a Responses object. @@ -677,6 +776,23 @@ pub struct ResponsesToChatStream { refusal_deltas: Vec, } +/// Detect annotations anywhere in a final/done stream event. Provider versions +/// may expose them on the annotation event, a completed content part, an item, +/// or the terminal response object. +fn has_populated_annotations(value: &Value) -> bool { + match value { + Value::Object(object) => object.iter().any(|(key, nested)| { + (key == "annotations" + && nested + .as_array() + .is_some_and(|annotations| !annotations.is_empty())) + || has_populated_annotations(nested) + }), + Value::Array(values) => values.iter().any(has_populated_annotations), + _ => false, + } +} + impl ResponsesToChatStream { /// Wrap an upstream event stream. pub fn new(source: R) -> ResponsesToChatStream { @@ -824,6 +940,24 @@ impl ResponsesToChatStream { } } + if has_populated_annotations(event) { + let item_id = event + .get("item_id") + .or_else(|| event.pointer("/item/id")) + .and_then(Value::as_str); + self.unmappable_item = Some(match item_id { + Some(id) => format!( + "Responses stream event {kind} for item {id} carries annotations with no Chat Completions equivalent" + ), + None => format!( + "Responses stream event {kind} carries annotations with no Chat Completions equivalent" + ), + }); + // Let terminal events reach the terminal-error/suppression logic. + if !matches!(kind, "response.completed" | "response.incomplete") { + return Vec::new(); + } + } if kind.starts_with("response.image_generation_call.") { let id = event .get("item_id") @@ -834,13 +968,29 @@ impl ResponsesToChatStream { )); return Vec::new(); } + // Annotation events have nowhere to go in the Chat shape: a populated + // annotation list is named rather than stripped. + if kind == "response.output_text.annotation.added" { + let id = event + .get("item_id") + .and_then(Value::as_str) + .unwrap_or("unknown"); + self.unmappable_item = Some(format!( + "Responses output content part output_text in item {id} carries annotations with no Chat Completions equivalent" + )); + return Vec::new(); + } if matches!( kind, "response.output_item.added" | "response.output_item.done" ) && let Some(item) = event.get("item") { let item_type = item.get("type").and_then(Value::as_str).unwrap_or(""); - if item_type == "image_generation_call" || item_type.starts_with("audio") { + // Function calls are announced by the arms below, reasoning arrives + // as summary deltas, and message text arrives as output deltas. + // Anything else has no Chat Completions equivalent and must fail + // loud rather than vanish. + if item_type != "function_call" && item_type != "reasoning" && item_type != "message" { let id = item.get("id").and_then(Value::as_str).unwrap_or("unknown"); self.unmappable_item = Some(format!( "Responses output item {item_type} (id {id}) has no Chat Completions equivalent" @@ -863,7 +1013,11 @@ impl ResponsesToChatStream { .get("call_id") .and_then(Value::as_str) .unwrap_or_default(); - let name = item.get("name").and_then(Value::as_str).unwrap_or_default(); + let Some(name) = item.get("name").and_then(Value::as_str) else { + self.unmappable_item = + Some(nameless_function_call_error(item).message().to_string()); + return Vec::new(); + }; let index = self.register_tool_call(item_id, call_id, name); self.announce_tool_call(index) } @@ -918,7 +1072,11 @@ impl ResponsesToChatStream { .get("call_id") .and_then(Value::as_str) .unwrap_or_default(); - let name = item.get("name").and_then(Value::as_str).unwrap_or_default(); + let Some(name) = item.get("name").and_then(Value::as_str) else { + self.unmappable_item = + Some(nameless_function_call_error(item).message().to_string()); + return Vec::new(); + }; let index = self.register_tool_call(item_id, call_id, name); let mut out = self.announce_tool_call(index); let arguments = item @@ -1055,18 +1213,25 @@ impl ResponsesToChatStream { out } "response.failed" => { - let message = event + let upstream_error = event .get("response") - .and_then(|response| response.get("error")) - .map(|error| { - error - .get("message") - .and_then(Value::as_str) - .unwrap_or("the request failed") - .to_string() - }) - .unwrap_or_else(|| "the request failed".to_string()); - let chunk = json!({ + .and_then(|response| response.get("error")); + let message = upstream_error + .and_then(|error| error.get("message")) + .and_then(Value::as_str) + .unwrap_or("the request failed"); + let error_type = upstream_error + .and_then(|error| error.get("type")) + .and_then(Value::as_str) + .unwrap_or("server_error"); + let mut error = json!({"message":message,"type":error_type}); + if let Some(code) = upstream_error + .and_then(|error| error.get("code")) + .and_then(Value::as_str) + { + error["code"] = json!(code); + } + let mut chunk = json!({ "id": self.id, "object": "chat.completion.chunk", "created": self.created, @@ -1076,8 +1241,8 @@ impl ResponsesToChatStream { "delta": {}, "finish_reason": "error", }], - "error": { "message": message, "type": "server_error" }, }); + chunk["error"] = error; let mut out = encode_event(&chunk); out.extend_from_slice(b"data: [DONE]\n\n"); out @@ -1675,7 +1840,7 @@ mod tests { fn a_failed_event_becomes_an_error_chunk() { let events = concat!( "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_1\",\"model\":\"gpt-5\"}}\n\n", - "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"message\":\"nope\"}}}\n\n", + "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"type\":\"rate_limit_error\",\"code\":\"quota_fixture\",\"message\":\"nope\"}}}\n\n", ); let mut translator = ResponsesToChatStream::new(events.as_bytes()); @@ -1683,6 +1848,8 @@ mod tests { translator.read_to_string(&mut out).unwrap(); assert!(out.contains("\"finish_reason\":\"error\""), "{out}"); + assert!(out.contains("\"type\":\"rate_limit_error\""), "{out}"); + assert!(out.contains("\"code\":\"quota_fixture\""), "{out}"); assert!(out.contains("nope"), "{out}"); } @@ -1729,6 +1896,9 @@ mod tests { Value::Null, "{value}" ); + assert_eq!(value["error"]["message"], "it broke", "{value}"); + assert_eq!(value["error"]["code"], "server_error", "{value}"); + assert_eq!(value["error"]["type"], "server_error", "{value}"); } #[test] @@ -1890,13 +2060,616 @@ mod tests { assert!(output.contains("data: [DONE]"), "{output}"); } + #[test] + fn a_nameless_function_call_fails_loud_before_content() { + let stream = concat!( + "data: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"function_call\",\"id\":\"call_fixture\",\"arguments\":\"\"}}\n\n", + "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\"}}\n\n" + ); + let output = translate(stream, 4096); + assert!(output.contains(r#""finish_reason":"error""#), "{output}"); + assert!( + output.contains(r#""code":"unmappable_output_item""#), + "{output}" + ); + assert!(output.contains("call_fixture"), "{output}"); + assert!(!output.contains("\"tool_calls\""), "{output}"); + assert!(output.contains("data: [DONE]"), "{output}"); + } + + #[test] + fn carried_request_field_decisions_are_pinned_table_driven() { + let cases = [ + ("model", json!("fixture"), "model", json!("fixture")), + ( + "tool_choice", + json!({"type":"function","function":{"name":"lookup"}}), + "tool_choice", + json!({"type":"function","name":"lookup"}), + ), + ( + "parallel_tool_calls", + json!(true), + "parallel_tool_calls", + json!(true), + ), + ( + "reasoning", + json!({"effort":"low"}), + "reasoning", + json!({"effort":"low"}), + ), + ( + "max_output_tokens", + json!(40), + "max_output_tokens", + json!(40), + ), + ("stream", json!(false), "stream", json!(false)), + ("store", json!(false), "store", json!(false)), + ( + "service_tier", + json!("priority"), + "service_tier", + json!("priority"), + ), + ]; + assert_eq!( + cases.len(), + CARRIED.len(), + "every carried field needs a case" + ); + for field in CARRIED { + let (_, input, output_field, expected) = cases + .iter() + .find(|(candidate, _, _, _)| candidate == field) + .unwrap_or_else(|| panic!("missing carried-field case for {field}")); + let mut request = json!({"model":"fixture","messages":[]}); + request[*field] = input.clone(); + let output: Value = serde_json::from_slice( + &chat_request_to_responses(&serde_json::to_vec(&request).unwrap()).unwrap(), + ) + .unwrap(); + assert_eq!(output.get(*output_field), Some(expected), "field {field}"); + } + } + + #[test] + fn refusal_arms_are_named_and_mappings_are_pinned_table_driven() { + let refused = [ + ("stop", json!(["stop"]), "unsupported_parameter", "stop"), + ("seed", json!(7), "unsupported_parameter", "seed"), + ( + "logit_bias", + json!({"1":1}), + "unsupported_parameter", + "logit_bias", + ), + ( + "prediction", + json!({"type":"content"}), + "unsupported_parameter", + "prediction", + ), + ( + "web_search_options", + json!({}), + "unsupported_parameter", + "web_search_options", + ), + ( + "function_call", + json!("auto"), + "unsupported_parameter", + "function_call", + ), + ("functions", json!([]), "unsupported_parameter", "functions"), + ("logprobs", json!(true), "unsupported_parameter", "logprobs"), + ( + "presence_penalty", + json!(0.5), + "unsupported_parameter", + "presence_penalty", + ), + ( + "frequency_penalty", + json!(-0.5), + "unsupported_parameter", + "frequency_penalty", + ), + ("n", json!(2), "unsupported_parameter", "n"), + ("n", json!("1"), "unsupported_parameter", "n"), + ( + "stream_options", + json!({"unsupported_key":true}), + "unsupported_parameter", + "unsupported_key", + ), + ( + "modalities", + json!(["image"]), + "image_requires_responses", + "modalities", + ), + ( + "modalities", + json!(["audio"]), + "audio_requires_responses", + "modalities", + ), + ( + "audio", + json!({"voice":"alloy"}), + "audio_requires_responses", + "audio", + ), + ( + "modalities", + json!(["text", "image"]), + "image_requires_responses", + "modalities", + ), + ( + "modalities", + json!(["text", "audio"]), + "audio_requires_responses", + "modalities", + ), + ( + "modalities", + json!("text"), + "unsupported_parameter", + "must be an array containing only text", + ), + ( + "modalities", + json!([]), + "unsupported_parameter", + "must contain text", + ), + ( + "modalities", + json!(["video"]), + "unsupported_parameter", + "no translated Chat Completions mapping", + ), + ( + "modalities", + json!([1]), + "unsupported_parameter", + "no translated Chat Completions mapping", + ), + ( + "stream_options", + json!("include_usage"), + "unsupported_parameter", + "must be an object containing only include_usage", + ), + ( + "reasoning_effort", + json!(1), + "unsupported_parameter", + "must be a string", + ), + ( + "max_tokens", + json!("40"), + "unsupported_parameter", + "must be a non-negative integer", + ), + ( + "presence_penalty", + json!("x"), + "unsupported_parameter", + "must be zero", + ), + ( + "logprobs", + json!("yes"), + "unsupported_parameter", + "must be a boolean", + ), + ( + "response_format", + json!({}), + "unsupported_parameter", + "requires a string type", + ), + ( + "response_format", + json!({"type":"json_schema"}), + "unsupported_parameter", + "must be an object", + ), + ( + "response_format", + json!({"type":"bogus"}), + "unsupported_parameter", + "unknown type", + ), + ( + "unlisted_option", + json!(true), + "unsupported_parameter", + "unlisted_option", + ), + ]; + for (field, input, code, named) in refused { + let mut request = json!({"model":"fixture","messages":[]}); + request[field] = input; + let error = chat_request_to_responses(&serde_json::to_vec(&request).unwrap()) + .expect_err("field must be refused by name"); + assert_eq!(error.code(), code, "field {field}: {}", error.message()); + assert!( + error.message().contains(named), + "field {field}: {}", + error.message() + ); + } + + // Text-only modalities are the default and therefore an intentional + // no-op; stream_options.include_usage is also validated then omitted. + let request = br#"{"model":"fixture","messages":[],"modalities":["text"],"stream_options":{"include_usage":true}}"#; + let output: Value = + serde_json::from_slice(&chat_request_to_responses(request).unwrap()).unwrap(); + assert!(output.get("modalities").is_none()); + assert!(output.get("stream_options").is_none()); + + for field in ["modalities", "audio"] { + let request = json!({"model":"fixture","messages":[],(field):Value::Null}); + let output: Value = serde_json::from_slice( + &chat_request_to_responses(&serde_json::to_vec(&request).unwrap()).unwrap(), + ) + .unwrap(); + assert!( + output.get(field).is_none(), + "null {field} should be treated as unset" + ); + } + + let request = json!({ + "model":"fixture", + "messages":[], + "response_format":{"type":"json_object"}, + "reasoning_effort":"high", + "max_completion_tokens":31 + }); + let output: Value = serde_json::from_slice( + &chat_request_to_responses(&serde_json::to_vec(&request).unwrap()).unwrap(), + ) + .unwrap(); + assert_eq!(output["text"]["format"]["type"], "json_object"); + assert_eq!(output["reasoning"]["effort"], "high"); + assert_eq!(output["max_output_tokens"], 31); + assert!(output.get("max_completion_tokens").is_none()); + } + + #[test] + fn n_integer_one_and_float_one_are_no_ops() { + for n in [json!(1), json!(1.0)] { + let request = json!({"model":"fixture","messages":[],"n":n}); + let output: Value = serde_json::from_slice( + &chat_request_to_responses(&serde_json::to_vec(&request).unwrap()).unwrap(), + ) + .unwrap(); + assert!(output.get("n").is_none()); + } + } + + #[test] + fn multiple_text_parts_remain_separate_responses_parts() { + let request = br#"{"model":"fixture","messages":[{"role":"user","content":[{"type":"text","text":"first"},{"type":"text","text":"second"}]}]}"#; + let output: Value = + serde_json::from_slice(&chat_request_to_responses(request).unwrap()).unwrap(); + assert_eq!(output["input"][0]["content"].as_array().unwrap().len(), 2); + assert_eq!( + output["input"][0]["content"][0], + json!({"type":"input_text","text":"first"}) + ); + assert_eq!( + output["input"][0]["content"][1], + json!({"type":"input_text","text":"second"}) + ); + } + + #[test] + fn non_message_output_items_fail_loud_with_their_kind_and_id() { + for kind in ["web_search_call", "file_search_call", "mcp_call", "audio"] { + let response = json!({ + "id":"resp_fixture", + "status":"completed", + "output":[{"type":kind,"id":"item_fixture"}] + }); + let error = responses_to_chat_completion(&serde_json::to_vec(&response).unwrap()) + .expect_err("unmappable output must not become empty content"); + assert_eq!(error.code(), "unmappable_output_item"); + assert!(error.message().contains(kind), "{}", error.message()); + assert!( + error.message().contains("item_fixture"), + "{}", + error.message() + ); + } + } + + #[test] + fn a_nameless_function_call_is_named_not_dropped() { + let response = json!({ + "id":"resp_fixture", + "status":"completed", + "output":[{"type":"function_call","id":"item_fixture","call_id":"call_fixture","arguments":"{}"}] + }); + let error = responses_to_chat_completion(&serde_json::to_vec(&response).unwrap()) + .expect_err("a nameless function call must not become an empty success"); + assert_eq!(error.code(), "unmappable_output_item"); + assert!( + error.message().contains("call_fixture"), + "{}", + error.message() + ); + } + + #[test] + fn populated_output_text_annotations_fail_loud() { + let response = br#"{"id":"resp_fixture","status":"completed","output":[{"type":"message","id":"msg_fixture","content":[{"type":"output_text","text":"cited","annotations":[{"type":"url_citation"}]}]}]}"#; + let error = + responses_to_chat_completion(response).expect_err("annotations cannot be dropped"); + assert_eq!(error.code(), "unmappable_output_item"); + assert!(error.message().contains("annotations")); + assert!(error.message().contains("msg_fixture")); + } + + #[test] + fn a_late_unmappable_item_keeps_the_existing_stream_terminal_semantics() { + let stream = concat!( + "data: {\"type\":\"response.output_text.delta\",\"delta\":\"already sent\"}\n\n", + "data: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"file_search_call\",\"id\":\"late_item\"}}\n\n", + "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\"}}\n\n" + ); + let output = translate(stream, 4096); + assert!(output.contains("already sent"), "{output}"); + assert!(!output.contains("unmappable_output_item"), "{output}"); + assert!(output.contains(r#""finish_reason":"stop""#), "{output}"); + assert!(output.contains("data: [DONE]"), "{output}"); + } + + #[test] + fn an_annotation_stream_event_fails_loud_when_no_chat_text_was_emitted() { + let stream = concat!( + "data: {\"type\":\"response.output_text.annotation.added\",\"item_id\":\"msg_fixture\",\"annotation\":{\"type\":\"url_citation\"}}\n\n", + "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\"}}\n\n" + ); + let output = translate(stream, 4096); + assert!(output.contains(r#""finish_reason":"error""#), "{output}"); + assert!( + output.contains(r#""code":"unmappable_output_item""#), + "{output}" + ); + assert!(output.contains("msg_fixture"), "{output}"); + assert!(output.contains("data: [DONE]"), "{output}"); + } + + #[test] + fn final_stream_events_with_annotations_fail_loud_before_chat_text() { + let annotated_content = json!({ + "type":"output_text", + "text":"cited", + "annotations":[{"type":"url_citation"}] + }); + let cases = [ + json!({ + "type":"response.output_text.done", + "item_id":"msg_fixture", + "text":"cited", + "annotations":[{"type":"url_citation"}] + }), + json!({ + "type":"response.output_item.done", + "item":{"type":"message","id":"msg_fixture","content":[annotated_content.clone()]} + }), + json!({ + "type":"response.completed", + "response":{ + "id":"resp_fixture", + "status":"completed", + "output":[{"type":"message","id":"msg_fixture","content":[annotated_content]}] + } + }), + ]; + + for event in cases { + let kind = event["type"].as_str().unwrap(); + let mut stream = format!("data: {}\n\n", serde_json::to_string(&event).unwrap()); + if kind != "response.completed" { + stream.push_str("data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\"}}\n\n"); + } + let output = translate(&stream, 4096); + assert!( + output.contains(r#""finish_reason":"error""#), + "{kind}: {output}" + ); + assert!( + output.contains(r#""code":"unmappable_output_item""#), + "{kind}: {output}" + ); + assert!(output.contains("annotations"), "{kind}: {output}"); + assert!(output.contains("data: [DONE]"), "{kind}: {output}"); + } + } + + /// Every key a recorded probe may carry. + /// + /// A closed list is the point: a field that is not here cannot reach the + /// fixture by accident, so a body, a prompt, or a credential cannot slip + /// in under a new name. A legitimate new metadata field extends this list + /// deliberately. + const ALLOWED_METADATA_KEYS: &[&str] = &[ + "record_type", + "captured_on", + "retained_material", + "probes", + "provider_media_probes", + "case", + "request_shape", + "http_status", + "content_type", + "response_bytes", + "error_type", + "error_code", + "classification", + "response_content_shape", + "finish_reason", + "content_part_type", + "text_part_count", + "field", + "values", + "value_shape", + "candidates", + "provider", + "enabled", + // What a direct provider probe reports. These come from + // `eggpass probe media`, so a recorded row is produced by the tool + // rather than transcribed by hand. + "candidate_path", + "probe_method", + "request_model", + "auth_mode", + "upstream_origin", + "content_type_accepted", + "upstream_error_type", + "upstream_error_code", + "signal_source", + "measured", + "provider_signal", + "upstream_contacted", + ]; + + /// Reject any key that is not in the reviewed list, at any depth. + fn assert_only_allowlisted_metadata_keys(value: &Value, path: &str) { + match value { + Value::Object(object) => { + for (key, nested) in object { + assert!( + ALLOWED_METADATA_KEYS.contains(&key.as_str()), + "{path}.{key} is not a reviewed metadata field" + ); + assert_only_allowlisted_metadata_keys(nested, &format!("{path}.{key}")); + } + } + Value::Array(values) => { + for (index, nested) in values.iter().enumerate() { + assert_only_allowlisted_metadata_keys(nested, &format!("{path}[{index}]")); + } + } + _ => {} + } + } + + #[test] + fn l1_probe_fixture_contains_only_sanitized_metadata() { + let fixture: Value = serde_json::from_str(include_str!( + "../../tests/fixtures/media/l1-live-probe-metadata.json" + )) + .unwrap(); + assert_eq!(fixture["record_type"], "sanitized_live_probe_metadata"); + assert_only_allowlisted_metadata_keys(&fixture, "l1"); + let probes = fixture["probes"].as_array().expect("probe list"); + for probe in probes { + assert!(probe.get("request_body").is_none()); + assert!(probe.get("response_body").is_none()); + assert!(probe.get("prompt").is_none()); + assert!(probe.get("response_text").is_none()); + assert!( + probe["probe_method"].is_string(), + "{}: every record says how it was measured", + probe["case"] + ); + } + assert!( + probes + .iter() + .any(|probe| probe["case"] == "translated_chat_input_audio") + ); + assert!( + probes + .iter() + .any(|probe| probe["case"] == "chat_modalities_text_only") + ); + let disabled = probes + .iter() + .find(|probe| probe["case"] == "disabled_media_routes") + .expect("the disabled-route record"); + assert_eq!(disabled["measured"], "proxy_route_enablement"); + assert_eq!(disabled["provider_signal"], serde_json::json!(false)); + assert_eq!(disabled["upstream_contacted"], serde_json::json!(false)); + assert_eq!( + disabled["classification"], "historical_proxy_state_not_a_provider_measurement", + "a proxy-state row must say it is not a provider measurement" + ); + + // A direct provider measurement is the only recorded row that may + // claim a provider signal, and it may never have travelled through the + // proxy or kept a body. + let provider_probes = fixture["provider_media_probes"] + .as_array() + .expect("the direct provider probe list"); + assert!(!provider_probes.is_empty()); + for probe in provider_probes { + assert_eq!( + probe["probe_method"], "cli_direct", + "a direct provider probe never travels through the proxy" + ); + assert_eq!(probe["signal_source"], "provider"); + assert_eq!(probe["upstream_contacted"], serde_json::json!(true)); + assert!(probe.get("response_body").is_none()); + } + let confirmed = provider_probes + .iter() + .find(|probe| probe["http_status"] == 200) + .expect("the confirmed x.ai probe"); + assert_eq!(confirmed["provider"], "xai"); + assert_eq!(confirmed["content_type"], "application/json"); + assert_eq!(confirmed["content_type_accepted"], serde_json::json!(true)); + } + + #[test] + fn every_reported_probe_field_is_an_allowlisted_metadata_field() { + for key in crate::provider::media_probe::REPORT_KEYS { + assert!( + ALLOWED_METADATA_KEYS.contains(key), + "{key} is reported by the provider probe but is not an allowlisted metadata field" + ); + } + } + + #[test] + #[should_panic(expected = "reviewed metadata field")] + fn a_metadata_key_outside_the_allowlist_is_rejected() { + let value = serde_json::json!({ + "probes": [{ "case": "fixture", "response_body": "not reviewed" }], + }); + assert_only_allowlisted_metadata_keys(&value, "l1"); + } + + #[test] + fn documented_stripped_fields_match_the_provider_policy() { + let docs = include_str!("../../docs/how-it-works.md"); + let section = docs + .split_once("") + .and_then(|(_, rest)| rest.split_once("")) + .map(|(section, _)| section) + .expect("the stripped-field list has sync-guard markers"); + let documented: Vec<&str> = section.split(char::from(96)).skip(1).step_by(2).collect(); + assert_eq!(documented, crate::provider::openai::REJECTED_FIELDS); + } + #[test] fn every_advertised_image_model_is_accepted_for_every_provider_spec() { let catalogue: Value = serde_json::from_str(include_str!( "../../tests/fixtures/media/chatgpt-models.json" )) .unwrap(); - let models = catalogue["models"] + let models: Vec = catalogue["models"] .as_array() .unwrap() .iter() @@ -1904,14 +2677,36 @@ mod tests { model["input_modalities"] .as_array() .is_some_and(|modalities| modalities.iter().any(|value| value == "image")) - }); + }) + .cloned() + .collect(); + assert!( + models.len() >= 2, + "tests/fixtures/media/chatgpt-models.json must advertise at least two image models; otherwise this invariant is vacuous" + ); for provider in crate::provider::ProviderId::all() { - let _spec = crate::provider::spec_for(provider, &crate::config::Config::default()); - for model in models.clone() { + let spec = crate::provider::spec_for(provider, &crate::config::Config::default()); + let expected_paths = match provider { + crate::provider::ProviderId::Xai => crate::provider::NativePaths::Both, + crate::provider::ProviderId::OpenAi => crate::provider::NativePaths::ResponsesOnly, + }; + assert_eq!( + spec.native_paths, + expected_paths, + "provider spec drift for {}", + provider.as_str() + ); + for model in &models { let slug = model["slug"].as_str().unwrap(); let request = json!({"model":slug,"messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"https://example.invalid/image.png"}}]}]}); - assert!( - chat_request_to_responses(&serde_json::to_vec(&request).unwrap()).is_ok(), + let translated = chat_request_to_responses(&serde_json::to_vec(&request).unwrap()) + .unwrap_or_else(|err| { + panic!("provider {} model {slug}: {err}", provider.as_str()) + }); + let translated: Value = serde_json::from_slice(&translated).unwrap(); + assert_eq!( + translated["input"][0]["content"][0]["type"], + "input_image", "provider {} model {slug}", provider.as_str() ); diff --git a/src/upstream.rs b/src/upstream.rs index 48e8972..6377f26 100644 --- a/src/upstream.rs +++ b/src/upstream.rs @@ -155,6 +155,14 @@ impl UpstreamClient { } } + /// The origin requests are actually sent to. + /// + /// A report names this rather than the configured value, so a recorded + /// result says which origin answered. + pub fn base_url(&self) -> &str { + &self.base_url + } + /// Send a request to the upstream. pub fn send( &self, diff --git a/tests/fixtures/media/README.md b/tests/fixtures/media/README.md index 3768445..390f7b3 100644 --- a/tests/fixtures/media/README.md +++ b/tests/fixtures/media/README.md @@ -1,3 +1,9 @@ # Media translation fixtures -These are documented-shape fixtures for offline translation tests, not live captures. Stage 0 live capture is still pending. No credential, prompt, or real user media is present. Any image URL and identifier below is synthetic. +These include documented-shape fixtures for offline translation tests and a sanitized live-probe metadata record; no raw live request or response body is retained. The refusal wire shape is confirmed against the published Responses schema and pinned by `responses-refusal.json` and `responses-stream-refusal.txt`; live provider behaviour is not captured. + +`provider_media_probes` holds direct provider measurements taken with `eggpass probe media`: metadata only, never a request or response body. On 2026-11-28 `https://api.x.ai` answered `200 application/json` for `grok-imagine-image-2.0` on `POST /v1/images/generations`, which is why that route is declared. Two x.ai control rows record that an OpenAI-shaped body and an unknown model answer the same `400`, so neither is a model verdict. ChatGPT's subscription token was refused with `401` at the OAuth boundary, so that candidate stays disabled and its endpoint support is unmeasured. + +The `disabled_media_routes` row inside `probes` is older and narrower: it records proxy route enablement on 2026-11-27 only, because a candidate that no provider spec declares is refused before any upstream call. It does not describe the current build. + +No credential, prompt, response text, or real user media is present. Any image URL and identifier below is synthetic. diff --git a/tests/fixtures/media/chatgpt-models.json b/tests/fixtures/media/chatgpt-models.json index 29c8c65..0608f50 100644 --- a/tests/fixtures/media/chatgpt-models.json +++ b/tests/fixtures/media/chatgpt-models.json @@ -1,5 +1,7 @@ { "models": [ - { "slug": "fixture-image-model", "input_modalities": ["text", "image"] } + { "slug": "fixture-image-model", "input_modalities": ["text", "image"] }, + { "slug": "fixture-image-model-plus", "input_modalities": ["text", "image"] }, + { "slug": "fixture-vision-model", "input_modalities": ["text", "image"] } ] } diff --git a/tests/fixtures/media/l1-live-probe-metadata.json b/tests/fixtures/media/l1-live-probe-metadata.json new file mode 100644 index 0000000..0ba97eb --- /dev/null +++ b/tests/fixtures/media/l1-live-probe-metadata.json @@ -0,0 +1,158 @@ +{ + "record_type": "sanitized_live_probe_metadata", + "captured_on": "2026-11-27", + "retained_material": "status, content shape, and byte counts only; no request or response bodies", + "probes": [ + { + "case": "translated_chat_input_audio", + "probe_method": "proxied_route", + "request_shape": { "content_part_type": "input_audio" }, + "http_status": 400, + "content_type": "application/json", + "response_bytes": 117, + "error_type": "invalid_request_error", + "error_code": "audio_input_unavailable", + "classification": "upstream_gating_not_local_content_rejection" + }, + { + "case": "translated_chat_multiple_text_parts", + "probe_method": "proxied_route", + "request_shape": { "text_part_count": 2 }, + "http_status": 200, + "content_type": null, + "response_bytes": 299, + "response_content_shape": "string", + "finish_reason": "stop" + }, + { + "case": "chat_modalities_text_only", + "probe_method": "proxied_route", + "request_shape": { "field": "modalities", "values": ["text"] }, + "http_status": 400, + "response_bytes": 100, + "error_type": "invalid_request_error", + "error_code": null + }, + { + "case": "chat_modalities_text_and_image", + "probe_method": "proxied_route", + "request_shape": { "field": "modalities", "values": ["text", "image"] }, + "http_status": 400, + "response_bytes": 100, + "error_type": "invalid_request_error", + "error_code": null + }, + { + "case": "chat_audio_output_configuration", + "probe_method": "proxied_route", + "request_shape": { "field": "audio", "value_shape": "object" }, + "http_status": 400, + "response_bytes": 95, + "error_type": "invalid_request_error", + "error_code": null + }, + { + "case": "disabled_media_routes", + "probe_method": "proxied_route", + "measured": "proxy_route_enablement", + "provider_signal": false, + "upstream_contacted": false, + "classification": "historical_proxy_state_not_a_provider_measurement", + "candidates": [ + { "provider": "xai", "http_status": 404, "enabled": false }, + { "provider": "openai", "http_status": 404, "enabled": false } + ] + } + ], + "provider_media_probes": [ + { + "provider": "xai", + "candidate_path": "/v1/images/generations", + "probe_method": "cli_direct", + "request_model": "grok-imagine-image-2.0", + "auth_mode": "api", + "upstream_origin": "https://api.x.ai", + "http_status": 200, + "content_type": "application/json", + "response_bytes": 179, + "content_type_accepted": true, + "upstream_error_type": null, + "upstream_error_code": null, + "signal_source": "provider", + "measured": "provider_media_endpoint", + "provider_signal": true, + "upstream_contacted": true, + "captured_on": "2026-11-28", + "request_shape": { + "value_shape": "documented_model_and_prompt" + }, + "classification": "provider_support_confirmed_for_this_model_on_this_origin" + }, + { + "provider": "xai", + "candidate_path": "/v1/images/generations", + "probe_method": "cli_direct", + "request_model": "grok-imagine-image-2.0", + "auth_mode": "api", + "upstream_origin": "https://api.x.ai", + "http_status": 400, + "content_type": "application/json", + "response_bytes": 53, + "content_type_accepted": null, + "upstream_error_type": null, + "upstream_error_code": "400", + "signal_source": "provider", + "measured": "provider_media_endpoint", + "provider_signal": true, + "upstream_contacted": true, + "captured_on": "2026-11-28", + "request_shape": { + "value_shape": "default_probe_body_with_size" + }, + "classification": "request_shape_rejection_not_a_model_verdict" + }, + { + "provider": "xai", + "candidate_path": "/v1/images/generations", + "probe_method": "cli_direct", + "request_model": "not-a-real-model-xyz", + "auth_mode": "api", + "upstream_origin": "https://api.x.ai", + "http_status": 400, + "content_type": "application/json", + "response_bytes": 53, + "content_type_accepted": null, + "upstream_error_type": null, + "upstream_error_code": "400", + "signal_source": "provider", + "measured": "provider_media_endpoint", + "provider_signal": true, + "upstream_contacted": true, + "captured_on": "2026-11-28", + "request_shape": { + "value_shape": "default_probe_body_with_size" + }, + "classification": "control_same_metadata_as_a_valid_model_so_not_model_specific" + }, + { + "provider": "openai", + "candidate_path": "/v1/images/generations", + "probe_method": "cli_direct", + "request_model": "gpt-image-2.5-sunburst", + "auth_mode": null, + "upstream_origin": "https://api.openai.com", + "http_status": 401, + "content_type": "text/plain", + "response_bytes": 239, + "content_type_accepted": null, + "upstream_error_type": "rejected_by_hardened_oauth_boundary", + "upstream_error_code": "hardened_oauth_rule_missing", + "signal_source": "provider", + "measured": "provider_media_endpoint", + "provider_signal": true, + "upstream_contacted": true, + "captured_on": "2026-11-28", + "classification": "auth_custody_refusal_endpoint_support_unmeasured" + } + ] +} From 2c87b855916dbc534b794639b2a3fbbba055cdc8 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Sat, 28 Nov 2026 17:17:07 +0000 Subject: [PATCH 13/13] Show x.ai product usage as shares of one pool The breakdown printed a bar and a `% left` per product, so `Api 91% left` beside `GrokChat 99% left` read as two allowances with two remainders. There is one pool: the provider reports each product's share of the same weekly allowance. Print those shares as plain rows under one meter, under a heading that names the pool the rows divide, with no per-product bar and no per-product remainder. The reported JSON is unchanged. --- CHANGELOG.md | 2 + docs/commands.md | 2 +- docs/how-it-works.md | 2 +- src/cli/commands/usage.rs | 97 ++++++++++++++++++++++++++++++++------- src/provider/usage/mod.rs | 8 +++- 5 files changed, 91 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b72777d..244ec2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,8 @@ Notable changes to eggpass are listed here. The format follows ### Fixed +- Show x.ai product usage as shares of the same weekly pool under one meter, + not as separate `% left` bars that read as independent allowances. - Fail an answer or stream whose content cannot be expressed in the Chat Completions shape with `unmappable_output_item` instead of empty content. - Name the limit and the inline-media cause in the `413` response. diff --git a/docs/commands.md b/docs/commands.md index 8eb9646..04f2393 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -75,7 +75,7 @@ eggpass usage --provider xai # query one provider eggpass usage --json # machine-readable report ``` -`eggpass usage` first requests the running daemon's usage report, reusing its in-memory cached snapshot when available. A stale last-successful snapshot is shown with a warning on stderr. The CLI falls back to direct provider collection when the daemon is stopped or stale, the private runtime usage credential is missing or unreadable, or an older daemon returns `404`; after a connection failure it falls back only if a state recheck confirms the daemon is stopped or stale. Other daemon errors, rejected credentials, and malformed reports are surfaced rather than bypassed. 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 requests the running daemon's usage report, reusing its in-memory cached snapshot when available. A stale last-successful snapshot is shown with a warning on stderr. The CLI falls back to direct provider collection when the daemon is stopped or stale, the private runtime usage credential is missing or unreadable, or an older daemon returns `404`; after a connection failure it falls back only if a state recheck confirms the daemon is stopped or stale. Other daemon errors, rejected credentials, and malformed reports are surfaced rather than bypassed. 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. For x.ai, the per-product breakdown is printed as plain rows under a heading that names the pool it divides, such as `Usage breakdown (share of the weekly pool)`: each row is that product's percentage of the same pool, not a separate allowance with a remainder of its own. 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/how-it-works.md b/docs/how-it-works.md index 0dda506..7f926d1 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -130,7 +130,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 first requests the running daemon's usage report and reuses its in-memory snapshot when available; the daemon refreshes on demand. A stale last-successful report is shown with a stderr warning. The CLI falls back to direct provider collection when the daemon is stopped or stale, its private runtime usage credential is missing or unreadable, or an older daemon returns `404`; after a transport failure, fallback occurs only if a state recheck confirms the daemon is stopped or stale. Other daemon errors are surfaced. Both paths query only providers enabled in configuration. ChatGPT's 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 daemon's separate proactive token checks use a four-second OAuth deadline and retry on the next minute if a refresh fails. +The `eggpass usage` command first requests the running daemon's usage report and reuses its in-memory snapshot when available; the daemon refreshes on demand. A stale last-successful report is shown with a stderr warning. The CLI falls back to direct provider collection when the daemon is stopped or stale, its private runtime usage credential is missing or unreadable, or an older daemon returns `404`; after a transport failure, fallback occurs only if a state recheck confirms the daemon is stopped or stale. Other daemon errors are surfaced. Both paths query only providers enabled in configuration. ChatGPT's 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. x.ai's product rows are shares of the same reported pool, printed without bars of their own. The daemon's separate proactive token checks use a four-second OAuth deadline and retry on the next minute if a refresh fails. 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/src/cli/commands/usage.rs b/src/cli/commands/usage.rs index 7d04c39..2817ba7 100644 --- a/src/cli/commands/usage.rs +++ b/src/cli/commands/usage.rs @@ -15,6 +15,11 @@ //! is metered against the xAI API tier and does **not** draw from the //! consumer subscription the billing endpoint reports. //! +//! A product row is not a second allowance. It is that product's share of the +//! same pool the window above reports, on the provider's own reporting +//! terms. That is why the rows are printed without bars and without a +//! percentage left: a share of a pool has no remainder of its own. +//! //! # What is never printed //! //! No token, no `Authorization` header, no raw upstream body. The billing @@ -777,28 +782,30 @@ fn render_reported( // An explicit state is the provider's answer, and it replaces every // percentage in the block: a breakdown of products with percentages // beside it would say something the state has already answered. - if report.state.is_none() { + if report.state.is_none() && !report.breakdown.is_empty() { + out.push_str(&format!(" {}\n", breakdown_heading(report))); for product in &report.breakdown { match product.used_percent { + // The product percentages are shares of the same allowance + // the window above reports, not separate quotas. They are + // plain rows for that reason: a bar per product would suggest + // an allowance of its own. Some(percent) => { - let left = left_percent(percent); out.push_str(&format!( - " {: { out.push_str(&format!( - " {: String { + let pool = match report.windows.as_slice() { + [window] => match &window.label { + WindowLabel::Weekly => "the weekly pool", + WindowLabel::Monthly => "the monthly pool", + WindowLabel::Daily => "the daily pool", + _ => "the same pool", + }, + _ => "the same pool", + }; + format!("Usage breakdown (share of {pool})") +} + /// A labelled line. fn field(label: &str, value: &str) -> String { let separator = if label.chars().count() >= LABEL_WIDTH { @@ -1127,6 +1152,7 @@ mod tests { assert!(text.contains("not eligible for this plan"), "{text}"); assert!(!text.contains("50%"), "{text}"); assert!(!text.contains("GrokBuild"), "{text}"); + assert!(!text.contains("Usage breakdown"), "{text}"); } #[test] @@ -1399,24 +1425,63 @@ mod tests { } #[test] - fn the_products_are_shown_under_the_window() { - let mut report = reported_report(Some(40.0)); + fn the_products_are_shares_of_the_same_window() { + let mut report = reported_report(Some(12.0)); report.breakdown = vec![ ProductUsage { - product: "GrokBuild".to_string(), - used_percent: Some(50.0), + product: "Api".to_string(), + used_percent: Some(11.0), }, ProductUsage { product: "GrokChat".to_string(), - used_percent: Some(20.0), + used_percent: Some(1.0), }, ]; let text = render(&[entry(ProviderUsage::Reported { report })]); - assert!(text.contains("GrokBuild"), "{text}"); - assert!(text.contains("50% left"), "{text}"); - assert!(text.contains("GrokChat"), "{text}"); - assert!(text.contains("80% left"), "{text}"); + assert!( + text.contains("Usage breakdown (share of the weekly pool)"), + "{text}" + ); + + let api = text + .lines() + .find(|line| line.trim_start().starts_with("Api ")) + .unwrap_or_else(|| panic!("no Api row in {text}")); + assert!(api.trim_end().ends_with("11%"), "{api:?}"); + assert!(!api.contains(FILLED), "{api:?}"); + assert!(!api.contains("left"), "{api:?}"); + + let chat = text + .lines() + .find(|line| line.trim_start().starts_with("GrokChat ")) + .unwrap_or_else(|| panic!("no GrokChat row in {text}")); + assert!(chat.trim_end().ends_with("1%"), "{chat:?}"); + assert!(!chat.contains(FILLED), "{chat:?}"); + assert!(!chat.contains("left"), "{chat:?}"); + + // The window keeps its bar; the product rows add none. + assert_eq!( + text.matches(FILLED).count(), + bar(88.0).matches(FILLED).count(), + "{text}" + ); + } + + #[test] + fn the_breakdown_heading_names_the_window_it_divides() { + let mut report = reported_report(Some(40.0)); + report.windows[0].label = WindowLabel::Monthly; + report.breakdown = vec![ProductUsage { + product: "Api".to_string(), + used_percent: Some(10.0), + }]; + + let text = render(&[entry(ProviderUsage::Reported { report })]); + assert!( + text.contains("Usage breakdown (share of the monthly pool)"), + "{text}" + ); } #[test] diff --git a/src/provider/usage/mod.rs b/src/provider/usage/mod.rs index 2b36c92..f876223 100644 --- a/src/provider/usage/mod.rs +++ b/src/provider/usage/mod.rs @@ -50,6 +50,10 @@ pub struct UsageReport { /// The quota windows, in the order they are printed. pub windows: Vec, /// A per-product breakdown of the same allowance. + /// + /// Each entry is that product's share of the one allowance, not a + /// separate quota with a remainder of its own. The provider reports the + /// shares on its own terms; they are not renormalised here. pub breakdown: Vec, /// Purchased credit, when the provider reports any. pub credits: Option, @@ -118,12 +122,12 @@ impl WindowLabel { } } -/// A product's share of the same allowance. +/// A product's contribution to the same allowance. #[derive(Debug, Clone, Deserialize, Serialize)] pub struct ProductUsage { /// The product id, as the provider spells it. pub product: String, - /// How much of the product's share is used, 0–100. + /// How much of the same allowance the product accounts for, 0–100. /// /// `None` means the provider did not say. It never means zero. pub used_percent: Option,