From ad95a44375c7f58d9207af8b0d227e7bfa978d22 Mon Sep 17 00:00:00 2001 From: dbowm91 Date: Mon, 23 Nov 2026 19:19:45 +0000 Subject: [PATCH 1/8] 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 2/8] 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 3/8] 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 4/8] 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 5/8] 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 6/8] 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 7/8] 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 8/8] 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