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/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/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..670f496 --- /dev/null +++ b/packaging/install.ps1 @@ -0,0 +1,313 @@ +<# +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") + $backupPath = $null + $replacementSucceeded = $false + try { + [IO.File]::Copy($Candidate, $stagedCopy, $false) + 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" } +} + +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..e6d6321 --- /dev/null +++ b/packaging/tests/test-install.ps1 @@ -0,0 +1,221 @@ +$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" + $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" + [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/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. 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/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/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| { 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:?}"), + } +}