diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 24c4c07..a725c76 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,13 +28,21 @@ jobs: run: cargo fmt --all -- --check - name: Run clippy - run: cargo clippy --all-targets -- -D warnings + run: cargo clippy --all-targets --locked -- -D warnings - name: Run the tests - run: cargo test --all-targets + run: cargo test --all-targets --locked + + - name: Package eggpass-auth + run: cargo package --locked --allow-dirty -p eggpass-auth + + - name: Package eggpass + run: >- + cargo package --locked --allow-dirty -p eggpass + --config 'patch.crates-io.eggpass-auth.path="crates/eggpass-auth"' - name: Build the release binary - run: cargo build --release + run: cargo build --release --locked windows-msvc: name: Windows MSVC tests and release build diff --git a/.github/workflows/publish-crates.yml b/.github/workflows/publish-crates.yml index acc9b7b..166aa78 100644 --- a/.github/workflows/publish-crates.yml +++ b/.github/workflows/publish-crates.yml @@ -23,6 +23,10 @@ permissions: jobs: publish: + if: >- + github.event_name == 'workflow_dispatch' || + (github.event_name == 'release' && + startsWith(github.event.release.tag_name, 'v')) name: publish runs-on: ubuntu-latest steps: @@ -52,10 +56,10 @@ jobs: fi - name: Verify the package - run: cargo package --locked --allow-dirty + run: cargo package --locked --allow-dirty -p eggpass - name: Publish the crate - if: ${{ github.event_name == 'release' && !(inputs.dry_run == true) }} - run: cargo publish --locked + if: ${{ github.event_name == 'release' && startsWith(github.event.release.tag_name, 'v') && !(inputs.dry_run == true) }} + run: cargo publish --locked -p eggpass env: CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} diff --git a/.github/workflows/publish-eggpass-auth-pypi.yml b/.github/workflows/publish-eggpass-auth-pypi.yml new file mode 100644 index 0000000..2910e06 --- /dev/null +++ b/.github/workflows/publish-eggpass-auth-pypi.yml @@ -0,0 +1,326 @@ +name: Publish eggpass-auth to PyPI + +# Python releases use eggpass-auth-python-vX.Y.Z and are independent of the +# Rust auth crate (eggpass-auth-vX.Y.Z) and the Eggpass CLI (vX.Y.Z). +on: + release: + types: [published] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pypi-${{ github.event.release.tag_name || github.ref }} + cancel-in-progress: false + +jobs: + verify-source: + name: Verify Python release tag and version + if: >- + github.event_name == 'workflow_dispatch' || + (github.event_name == 'release' && + github.event.action == 'published' && + startsWith(github.event.release.tag_name, 'eggpass-auth-python-v')) + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.version.outputs.value }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.release.tag_name || github.ref }} + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Verify package versions and release tag + id: version + env: + EVENT_NAME: ${{ github.event_name }} + RELEASE_TAG: ${{ github.event.release.tag_name || '' }} + working-directory: python/eggpass-auth + run: | + python - <<'PY' + import os + import re + import tomllib + from pathlib import Path + + with Path("pyproject.toml").open("rb") as manifest: + python_version = tomllib.load(manifest)["project"]["version"] + with Path("Cargo.toml").open("rb") as manifest: + rust_version = tomllib.load(manifest)["package"]["version"] + + if python_version != rust_version: + raise SystemExit( + f"pyproject.toml version {python_version} does not match " + f"Cargo.toml {rust_version}" + ) + + if os.environ["EVENT_NAME"] == "release": + tag = os.environ["RELEASE_TAG"] + tag_pattern = r"eggpass-auth-python-v\d+\.\d+\.\d+" + if not re.fullmatch(tag_pattern, tag): + raise SystemExit(f"invalid Python release tag: {tag}") + if tag != f"eggpass-auth-python-v{python_version}": + raise SystemExit( + f"tag {tag} does not match package version " + f"{python_version}" + ) + + output_path = Path(os.environ["GITHUB_OUTPUT"]) + with output_path.open("a", encoding="utf-8") as output: + output.write(f"value={python_version}\n") + print(f"Verified eggpass-auth Python version {python_version}") + PY + + build-wheels: + name: Build ${{ matrix.platform.name }} wheel + needs: verify-source + runs-on: ${{ matrix.platform.runner }} + strategy: + fail-fast: false + matrix: + platform: + - name: linux-x86_64 + runner: ubuntu-24.04 + manylinux: "2014" + interpreter: python3.11 + - name: linux-aarch64 + runner: ubuntu-24.04-arm + manylinux: "2014" + interpreter: python3.11 + - name: macos-x86_64 + runner: macos-15-intel + manylinux: "off" + interpreter: python + - name: macos-arm64 + runner: macos-15 + manylinux: "off" + interpreter: python + - name: windows-x86_64 + runner: windows-2025 + manylinux: "off" + interpreter: python + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.release.tag_name || github.ref }} + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Check the vendored Rust source snapshot + run: python tools/sync_core.py --check + working-directory: python/eggpass-auth + + - name: Build stable-ABI wheel + uses: PyO3/maturin-action@v1 + with: + maturin-version: v1.16.0 + manylinux: ${{ matrix.platform.manylinux }} + args: >- + --release --locked --interpreter ${{ matrix.platform.interpreter }} + --out dist + working-directory: python/eggpass-auth + + - uses: actions/upload-artifact@v4 + with: + name: python-dist-${{ matrix.platform.name }} + path: python/eggpass-auth/dist/*.whl + if-no-files-found: error + retention-days: 14 + + build-sdist: + name: Build source distribution + needs: verify-source + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.release.tag_name || github.ref }} + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal --no-self-update + rustup default stable + + - name: Install Maturin + run: python -m pip install "maturin==1.16.0" + + - name: Check the vendored Rust source snapshot + run: python tools/sync_core.py --check + working-directory: python/eggpass-auth + + - name: Build source distribution + run: maturin sdist --out dist + working-directory: python/eggpass-auth + + - uses: actions/upload-artifact@v4 + with: + name: python-dist-sdist + path: python/eggpass-auth/dist/*.tar.gz + if-no-files-found: error + retention-days: 14 + + validate-artifacts: + name: Validate release distributions + needs: [verify-source, build-wheels, build-sdist] + runs-on: ubuntu-24.04 + steps: + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - uses: actions/download-artifact@v4 + with: + pattern: python-dist-* + path: dist + merge-multiple: true + + - name: Install distribution checker + run: python -m pip install twine packaging + + - name: Validate metadata and target coverage + env: + PACKAGE_VERSION: ${{ needs.verify-source.outputs.version }} + run: | + python -m twine check dist/* + python - <<'PY' + import os + import tarfile + from pathlib import Path + from packaging.utils import ( + canonicalize_name, + parse_sdist_filename, + parse_wheel_filename, + ) + + version = os.environ["PACKAGE_VERSION"] + files = sorted(Path("dist").iterdir()) + wheels = [path for path in files if path.suffix == ".whl"] + sdists = [path for path in files if path.name.endswith(".tar.gz")] + if len(wheels) != 5 or len(sdists) != 1 or len(files) != 6: + names = [path.name for path in files] + raise SystemExit( + f"expected five wheels and one sdist; found {names}" + ) + + wheel_platforms = [] + for wheel in wheels: + _name, wheel_version, _build, tags = parse_wheel_filename( + wheel.name + ) + if canonicalize_name(_name) != canonicalize_name("eggpass-auth"): + raise SystemExit(f"unexpected distribution in {wheel.name}") + if str(wheel_version) != version: + raise SystemExit(f"unexpected wheel version in {wheel.name}") + abi3 = any( + tag.interpreter == "cp311" and tag.abi == "abi3" + for tag in tags + ) + if not abi3: + raise SystemExit( + f"wheel is not tagged cp311-abi3: {wheel.name}" + ) + wheel_platforms.append({tag.platform for tag in tags}) + + def has_platform(platforms, prefix, suffix): + return any( + platform.startswith(prefix) and platform.endswith(suffix) + for platform in platforms + ) + + expected = { + "Linux x86_64": ("manylinux", "_x86_64"), + "Linux aarch64": ("manylinux", "_aarch64"), + "macOS x86_64": ("macosx_", "_x86_64"), + "macOS arm64": ("macosx_", "_arm64"), + "Windows x86_64": ("win_amd64", ""), + } + unmatched = list(wheel_platforms) + for label, (prefix, suffix) in expected.items(): + if label == "Windows x86_64": + matches = lambda platforms: prefix in platforms + else: + matches = lambda platforms: has_platform( + platforms, prefix, suffix + ) + index = next( + ( + i + for i, platforms in enumerate(unmatched) + if matches(platforms) + ), + None, + ) + if index is None: + raise SystemExit( + f"missing {label} wheel; wheel tags were " + f"{wheel_platforms}" + ) + unmatched.pop(index) + + sdist = sdists[0] + distribution, sdist_version = parse_sdist_filename(sdist.name) + expected_name = canonicalize_name("eggpass-auth") + if canonicalize_name(distribution) != expected_name: + raise SystemExit(f"unexpected distribution in {sdist.name}") + if str(sdist_version) != version: + raise SystemExit(f"unexpected sdist version in {sdist.name}") + with tarfile.open(sdist) as archive: + members = archive.getnames() + required = ( + "/README.md", + "/LICENSE", + "/Cargo.toml", + "/Cargo.lock", + "/src/lib.rs", + "/vendor/eggpass-auth/Cargo.toml", + "/vendor/eggpass-auth/src/lib.rs", + ) + missing = [ + suffix + for suffix in required + if not any(name.endswith(suffix) for name in members) + ] + if missing: + raise SystemExit(f"sdist is missing required files: {missing}") + print(f"Validated {len(wheels)} wheels and {sdist.name}") + PY + + - uses: actions/upload-artifact@v4 + with: + name: verified-distributions + path: dist/* + if-no-files-found: error + retention-days: 14 + + publish: + name: Publish verified files to PyPI + needs: validate-artifacts + if: >- + github.event_name == 'release' && + github.event.action == 'published' && + startsWith(github.event.release.tag_name, 'eggpass-auth-python-v') + runs-on: ubuntu-24.04 + environment: + name: pypi + permissions: + id-token: write + steps: + - uses: actions/download-artifact@v4 + with: + name: verified-distributions + path: dist + + - name: Publish with PyPI Trusted Publishing + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: dist diff --git a/.github/workflows/publish-eggpass-auth.yml b/.github/workflows/publish-eggpass-auth.yml new file mode 100644 index 0000000..c027fdd --- /dev/null +++ b/.github/workflows/publish-eggpass-auth.yml @@ -0,0 +1,66 @@ +name: Publish eggpass-auth to crates.io + +# Auth crate versions and releases are independent of the Eggpass binary. +# Publishing only follows a human-published eggpass-auth-vX.Y.Z release. + +on: + release: + types: [published] + workflow_dispatch: + inputs: + dry_run: + description: "Verify the package without publishing it" + required: false + type: boolean + default: true + +permissions: + contents: read + +jobs: + publish: + if: >- + (github.event_name == 'release' && + startsWith(github.event.release.tag_name, 'eggpass-auth-v')) || + (github.event_name == 'workflow_dispatch' && + startsWith(github.ref, 'refs/tags/eggpass-auth-v')) + name: publish + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + # Build the exact source associated with a published auth release. + ref: ${{ github.event.release.tag_name || github.ref }} + + - name: Install the toolchain + run: | + rustup toolchain install stable --profile minimal --no-self-update + rustup default stable + + - uses: Swatinem/rust-cache@v2 + + - name: Check the version matches the release tag + env: + TAG: ${{ github.event.release.tag_name || github.ref_name }} + shell: bash + run: | + set -euo pipefail + if [[ ! "$TAG" =~ ^eggpass-auth-v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "::error::Expected an eggpass-auth-vX.Y.Z tag, got $TAG" + exit 1 + fi + version="$(sed -n 's/^version = \"\(.*\)\"$/\1/p' crates/eggpass-auth/Cargo.toml | head -1)" + tag_version="${TAG#eggpass-auth-v}" + if [[ "$version" != "$tag_version" ]]; then + echo "::error::crates/eggpass-auth/Cargo.toml says $version but the release tag says $tag_version" + exit 1 + fi + + - name: Verify the package + run: cargo package --locked -p eggpass-auth + + - name: Publish the crate + if: ${{ github.event_name == 'release' && startsWith(github.event.release.tag_name, 'eggpass-auth-v') && !(inputs.dry_run == true) }} + run: cargo publish --locked -p eggpass-auth + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} diff --git a/.github/workflows/python-auth.yml b/.github/workflows/python-auth.yml new file mode 100644 index 0000000..3c5d3ce --- /dev/null +++ b/.github/workflows/python-auth.yml @@ -0,0 +1,269 @@ +name: Python eggpass-auth + +on: + push: + branches: [main] + paths: + - "python/eggpass-auth/**" + - "crates/eggpass-auth/**" + - ".github/workflows/python-auth.yml" + - ".github/workflows/publish-eggpass-auth-pypi.yml" + pull_request: + branches: [main] + paths: + - "python/eggpass-auth/**" + - "crates/eggpass-auth/**" + - ".github/workflows/python-auth.yml" + - ".github/workflows/publish-eggpass-auth-pypi.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: python-auth-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + CARGO_TERM_COLOR: always + +jobs: + rust-and-local-tests: + name: Rust checks and local Python tests + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: python/eggpass-auth + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Create Python virtual environment + run: | + python -m venv .venv + echo "VIRTUAL_ENV=$PWD/.venv" >> "$GITHUB_ENV" + echo "$PWD/.venv/bin" >> "$GITHUB_PATH" + + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal --no-self-update + rustup default stable + + - name: Install Python build and test tools + run: python -m pip install "maturin==1.16.0" pytest mypy + + - name: Check the vendored Rust source snapshot + run: python tools/sync_core.py --check + + - name: Check Rust formatting, lint, and tests + run: | + cargo fmt --all -- --check + cargo clippy --workspace --all-targets --locked -- -D warnings + cargo test --workspace --all-targets --locked + + - name: Build and install the local extension + run: maturin develop --release --locked + + - name: Check stubs and run local-stub tests + run: | + mypy --strict tests/typecheck_api.py + pytest -q + + build-wheels: + name: Build ${{ matrix.platform.name }} wheel + runs-on: ${{ matrix.platform.runner }} + strategy: + fail-fast: false + matrix: + platform: + - name: linux-x86_64 + runner: ubuntu-24.04 + manylinux: "2014" + interpreter: python3.11 + - name: linux-aarch64 + runner: ubuntu-24.04-arm + manylinux: "2014" + interpreter: python3.11 + - name: macos-x86_64 + runner: macos-15-intel + manylinux: "off" + interpreter: python + - name: macos-arm64 + runner: macos-15 + manylinux: "off" + interpreter: python + - name: windows-x86_64 + runner: windows-2025 + manylinux: "off" + interpreter: python + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Check the vendored Rust source snapshot + run: python tools/sync_core.py --check + working-directory: python/eggpass-auth + + - name: Build stable-ABI wheel + uses: PyO3/maturin-action@v1 + with: + maturin-version: v1.16.0 + manylinux: ${{ matrix.platform.manylinux }} + args: >- + --release --locked --interpreter ${{ matrix.platform.interpreter }} + --out dist + working-directory: python/eggpass-auth + + - uses: actions/upload-artifact@v4 + with: + name: wheel-${{ matrix.platform.name }} + path: python/eggpass-auth/dist/*.whl + if-no-files-found: error + retention-days: 14 + + test-wheels: + name: Test ${{ matrix.platform.name }} on Python ${{ matrix.python }} + needs: build-wheels + runs-on: ${{ matrix.platform.runner }} + strategy: + fail-fast: false + matrix: + platform: + - name: linux-x86_64 + runner: ubuntu-24.04 + - name: linux-aarch64 + runner: ubuntu-24.04-arm + - name: macos-x86_64 + runner: macos-15-intel + - name: macos-arm64 + runner: macos-15 + - name: windows-x86_64 + runner: windows-2025 + python: ["3.11", "3.12", "3.13", "3.14", "3.15"] + defaults: + run: + working-directory: python/eggpass-auth + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + + - uses: actions/download-artifact@v4 + with: + name: wheel-${{ matrix.platform.name }} + path: python/eggpass-auth/dist + + - name: Install wheel and test the installed package + shell: bash + run: | + python -m pip install --upgrade pip pytest mypy + python -m pip install --no-deps dist/*.whl + python -m pip check + python -c "import eggpass_auth; print(eggpass_auth.__all__)" + mypy --strict tests/typecheck_api.py + pytest -q + + build-sdist: + name: Build and inspect source distribution + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: python/eggpass-auth + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal --no-self-update + rustup default stable + + - name: Install Maturin and metadata checker + run: python -m pip install "maturin==1.16.0" twine + + - name: Check the vendored Rust source snapshot + run: python tools/sync_core.py --check + + - name: Build and validate source distribution metadata + run: | + maturin sdist --out dist + python -m twine check dist/*.tar.gz + python - <<'PY' + from pathlib import Path + import tarfile + + archives = list(Path("dist").glob("*.tar.gz")) + assert len(archives) == 1, f"expected one sdist, found {archives}" + with tarfile.open(archives[0]) as archive: + members = archive.getnames() + required = ( + "/README.md", + "/LICENSE", + "/Cargo.toml", + "/Cargo.lock", + "/src/lib.rs", + "/vendor/eggpass-auth/Cargo.toml", + "/vendor/eggpass-auth/src/lib.rs", + ) + missing = [ + suffix + for suffix in required + if not any(name.endswith(suffix) for name in members) + ] + assert not missing, f"sdist is missing required files: {missing}" + PY + + - uses: actions/upload-artifact@v4 + with: + name: python-sdist + path: python/eggpass-auth/dist/*.tar.gz + if-no-files-found: error + retention-days: 14 + + test-sdist: + name: Build and test sdist on Python ${{ matrix.python }} + needs: build-sdist + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + python: ["3.11", "3.12", "3.13", "3.14", "3.15"] + defaults: + run: + working-directory: python/eggpass-auth + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal --no-self-update + rustup default stable + + - uses: actions/download-artifact@v4 + with: + name: python-sdist + path: python/eggpass-auth/dist + + - name: Install source distribution and run package checks + run: | + python -m pip install --upgrade pip pytest mypy + python -m pip install --no-deps dist/*.tar.gz + python -m pip check + python -c "import eggpass_auth; print(eggpass_auth.__all__)" + mypy --strict tests/typecheck_api.py + pytest -q diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 13619a4..4be3dc0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,17 +16,40 @@ jobs: runs-on: "ubuntu-latest" permissions: contents: read + outputs: + source_sha: ${{ steps.resolve_tag.outputs.source_sha }} timeout-minutes: 90 steps: + - name: Resolve and validate immutable release source + id: resolve_tag + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ \"${#tag}\" -gt 255 ] || [ -z \"$tag\" ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\naskpass=\"$RUNNER_TEMP/eggpack-tag-askpass\"\nverify_repo=\"$RUNNER_TEMP/eggpack-tag-verify.git\"\ntrap 'rm -f -- \"$askpass\"' EXIT\ncat >\"$askpass\" <<'ASKPASS'\n#!/bin/sh\ncase \"$1\" in\n *Username*) printf '%s\\n' x-access-token ;;\n *Password*) printf '%s\\n' \"$EGGPACK_GIT_TOKEN\" ;;\n *) exit 1 ;;\nesac\nASKPASS\nchmod 700 \"$askpass\"\nremote=\"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git\"\nrefs=\"$(GIT_ASKPASS=\"$askpass\" GIT_TERMINAL_PROMPT=0 EGGPACK_GIT_TOKEN=\"$GITHUB_TOKEN\" git ls-remote --exit-code \"$remote\" \"$ref\" \"$ref^{}\")\"\ndirect=\npeeled=\nwhile IFS=\"$(printf '\\t')\" read -r oid name; do\n case \"$name\" in\n \"$ref\") [ -z \"$direct\" ] || { echo 'duplicate tag ref result' >&2; exit 1; }; direct=\"$oid\" ;;\n \"$ref^{}\") [ -z \"$peeled\" ] || { echo 'duplicate peeled ref result' >&2; exit 1; }; peeled=\"$oid\" ;;\n *) echo 'unexpected tag resolution result' >&2; exit 1 ;;\n esac\ndone <<< \"$refs\"\nsource_sha=\"${peeled:-$direct}\"\nif [[ ! \"$source_sha\" =~ ^[0-9a-f]{40}$ ]]; then\n echo 'tag did not resolve to one full object OID' >&2\n exit 1\nfi\ngit init --bare \"$verify_repo\" >/dev/null\nGIT_ASKPASS=\"$askpass\" GIT_TERMINAL_PROMPT=0 EGGPACK_GIT_TOKEN=\"$GITHUB_TOKEN\" git --git-dir=\"$verify_repo\" fetch --no-tags --depth=1 \"$remote\" \"$ref\" >/dev/null\nfetched_commit=\"$(git --git-dir=\"$verify_repo\" rev-parse --verify 'FETCH_HEAD^{commit}')\"\nif [ \"$fetched_commit\" != \"$source_sha\" ]; then\n echo 'tag did not resolve to the advertised commit object' >&2\n exit 1\nfi\nprintf 'source_sha=%s\\n' \"$source_sha\" >> \"$GITHUB_OUTPUT\"\n" - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ steps.resolve_tag.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ steps.resolve_tag.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ steps.resolve_tag.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Check Cargo availability shell: bash run: cargo --version resolve: needs: preflight + outputs: + source_sha: ${{ needs.preflight.outputs.source_sha }} runs-on: "ubuntu-latest" permissions: contents: read @@ -35,24 +58,35 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" - - name: Validate exact-tag source + ref: "${{ needs.preflight.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.preflight.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification shell: bash - run: "test -n \"${{ inputs.release_tag }}\"" + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.preflight.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Install pinned Eggpack tool shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Create runtime identity directory shell: bash run: "mkdir -p './eggpack-runtime'" - name: Resolve runtime release identity shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" run: | head_sha="$(git rev-parse --verify HEAD^{commit})" - 'eggpack' 'ci' '_resolve-release' '--contract' 'release/eggpack/distribution.toml' '--pack-config' 'release/eggpack/pack.toml' '--build-bindings' 'release/eggpack/build-bindings.toml' '--qualification-bindings' 'release/eggpack/qualification-bindings.toml' '--consumer-validators' 'release/eggpack/consumer-validators.json' '--selected' 'linux-x64,linux-arm64,macos-x64,macos-arm64,windows-x64' '--tag' '${{ inputs.release_tag }}' '--source-revision' "$head_sha" '--template' 'release/eggpack/github-template.json' '--source-root' '${{ github.workspace }}' '--output-plan' './eggpack-runtime/release-plan.json' '--output-ci-plan' './eggpack-runtime/release-ci-plan.json' '--output-github-policy' './eggpack-runtime/github-draft.json' + 'eggpack' 'ci' '_resolve-release' '--contract' 'release/eggpack/distribution.toml' '--pack-config' 'release/eggpack/pack.toml' '--build-bindings' 'release/eggpack/build-bindings.toml' '--qualification-bindings' 'release/eggpack/qualification-bindings.toml' '--consumer-validators' 'release/eggpack/consumer-validators.json' '--selected' 'linux-x64,linux-arm64,macos-x64,macos-arm64,windows-x64' '--tag' "$EGGPACK_RELEASE_TAG" '--source-revision' "$head_sha" '--template' 'release/eggpack/github-template.json' '--source-root' '${{ github.workspace }}' '--output-plan' './eggpack-runtime/release-plan.json' '--output-ci-plan' './eggpack-runtime/release-ci-plan.json' '--output-github-policy' './eggpack-runtime/github-draft.json' - name: Upload runtime release identity uses: "actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02" with: @@ -71,7 +105,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -90,7 +136,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -121,7 +167,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -140,7 +198,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -171,7 +229,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -190,7 +260,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -221,7 +291,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -240,7 +322,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -271,7 +353,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -290,7 +384,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -311,7 +405,7 @@ jobs: if-no-files-found: error retention-days: 7 qualify_build_aarch64_apple_darwin: - needs: build_aarch64_apple_darwin + needs: [ build_aarch64_apple_darwin, resolve ] runs-on: "macos-15" permissions: contents: read @@ -321,7 +415,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -332,7 +438,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -353,7 +459,7 @@ jobs: if-no-files-found: error retention-days: 7 qualify_build_aarch64_unknown_linux_gnu: - needs: build_aarch64_unknown_linux_gnu + needs: [ build_aarch64_unknown_linux_gnu, resolve ] runs-on: "ubuntu-24.04-arm" permissions: contents: read @@ -363,7 +469,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -374,7 +492,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -395,7 +513,7 @@ jobs: if-no-files-found: error retention-days: 7 qualify_build_x86_64_apple_darwin: - needs: build_x86_64_apple_darwin + needs: [ build_x86_64_apple_darwin, resolve ] runs-on: "macos-15-intel" permissions: contents: read @@ -405,7 +523,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -416,7 +546,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -437,7 +567,7 @@ jobs: if-no-files-found: error retention-days: 7 qualify_build_x86_64_pc_windows_msvc: - needs: build_x86_64_pc_windows_msvc + needs: [ build_x86_64_pc_windows_msvc, resolve ] runs-on: "windows-latest" permissions: contents: read @@ -447,7 +577,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -458,7 +600,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -479,7 +621,7 @@ jobs: if-no-files-found: error retention-days: 7 qualify_build_x86_64_unknown_linux_gnu: - needs: build_x86_64_unknown_linux_gnu + needs: [ build_x86_64_unknown_linux_gnu, resolve ] runs-on: "ubuntu-latest" permissions: contents: read @@ -489,7 +631,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -500,7 +654,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -521,7 +675,7 @@ jobs: if-no-files-found: error retention-days: 7 validate_build_aarch64_apple_darwin: - needs: qualify_build_aarch64_apple_darwin + needs: [ qualify_build_aarch64_apple_darwin, resolve ] runs-on: "macos-15" permissions: contents: read @@ -531,7 +685,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -542,7 +708,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -566,7 +732,7 @@ jobs: if-no-files-found: error retention-days: 7 validate_build_aarch64_unknown_linux_gnu: - needs: qualify_build_aarch64_unknown_linux_gnu + needs: [ qualify_build_aarch64_unknown_linux_gnu, resolve ] runs-on: "ubuntu-24.04-arm" permissions: contents: read @@ -576,7 +742,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -587,7 +765,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -611,7 +789,7 @@ jobs: if-no-files-found: error retention-days: 7 validate_build_x86_64_apple_darwin: - needs: qualify_build_x86_64_apple_darwin + needs: [ qualify_build_x86_64_apple_darwin, resolve ] runs-on: "macos-15-intel" permissions: contents: read @@ -621,7 +799,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -632,7 +822,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -656,7 +846,7 @@ jobs: if-no-files-found: error retention-days: 7 validate_build_x86_64_pc_windows_msvc: - needs: qualify_build_x86_64_pc_windows_msvc + needs: [ qualify_build_x86_64_pc_windows_msvc, resolve ] runs-on: "windows-latest" permissions: contents: read @@ -666,7 +856,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -677,7 +879,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -701,7 +903,7 @@ jobs: if-no-files-found: error retention-days: 7 validate_build_x86_64_unknown_linux_gnu: - needs: qualify_build_x86_64_unknown_linux_gnu + needs: [ qualify_build_x86_64_unknown_linux_gnu, resolve ] runs-on: "ubuntu-latest" permissions: contents: read @@ -711,7 +913,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -722,7 +936,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -746,7 +960,7 @@ jobs: if-no-files-found: error retention-days: 7 required_gate: - needs: [validate_build_aarch64_apple_darwin, validate_build_aarch64_unknown_linux_gnu, validate_build_x86_64_apple_darwin, validate_build_x86_64_pc_windows_msvc, validate_build_x86_64_unknown_linux_gnu] + needs: [ validate_build_aarch64_apple_darwin, validate_build_aarch64_unknown_linux_gnu, validate_build_x86_64_apple_darwin, validate_build_x86_64_pc_windows_msvc, validate_build_x86_64_unknown_linux_gnu, resolve ] runs-on: "ubuntu-latest" permissions: contents: read @@ -755,7 +969,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -766,7 +992,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -828,7 +1054,7 @@ jobs: shell: bash run: "'eggpack' 'ci' '_evaluate-gate' '--ci-plan' 'eggpack-runtime/release-ci-plan.json' '--inputs-dir' './eggpack-inputs' '--output' './eggpack-gate/gate-outcome.json'" aggregate: - needs: required_gate + needs: [ required_gate, resolve ] runs-on: "ubuntu-latest" permissions: contents: read @@ -837,7 +1063,19 @@ jobs: - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ github.event_name == 'workflow_dispatch' && inputs.release_tag || github.ref }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: @@ -848,7 +1086,7 @@ jobs: shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash @@ -917,31 +1155,48 @@ jobs: if-no-files-found: error retention-days: 7 stage: - needs: aggregate + needs: [ aggregate, resolve ] if: github.event_name == 'workflow_dispatch' runs-on: "ubuntu-latest" permissions: contents: write timeout-minutes: 90 steps: + - name: Resolve and validate immutable release source + id: confirm_tag_source + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ \"${#tag}\" -gt 255 ] || [ -z \"$tag\" ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\naskpass=\"$RUNNER_TEMP/eggpack-tag-askpass\"\nverify_repo=\"$RUNNER_TEMP/eggpack-tag-verify.git\"\ntrap 'rm -f -- \"$askpass\"' EXIT\ncat >\"$askpass\" <<'ASKPASS'\n#!/bin/sh\ncase \"$1\" in\n *Username*) printf '%s\\n' x-access-token ;;\n *Password*) printf '%s\\n' \"$EGGPACK_GIT_TOKEN\" ;;\n *) exit 1 ;;\nesac\nASKPASS\nchmod 700 \"$askpass\"\nremote=\"$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git\"\nrefs=\"$(GIT_ASKPASS=\"$askpass\" GIT_TERMINAL_PROMPT=0 EGGPACK_GIT_TOKEN=\"$GITHUB_TOKEN\" git ls-remote --exit-code \"$remote\" \"$ref\" \"$ref^{}\")\"\ndirect=\npeeled=\nwhile IFS=\"$(printf '\\t')\" read -r oid name; do\n case \"$name\" in\n \"$ref\") [ -z \"$direct\" ] || { echo 'duplicate tag ref result' >&2; exit 1; }; direct=\"$oid\" ;;\n \"$ref^{}\") [ -z \"$peeled\" ] || { echo 'duplicate peeled ref result' >&2; exit 1; }; peeled=\"$oid\" ;;\n *) echo 'unexpected tag resolution result' >&2; exit 1 ;;\n esac\ndone <<< \"$refs\"\nsource_sha=\"${peeled:-$direct}\"\nif [[ ! \"$source_sha\" =~ ^[0-9a-f]{40}$ ]]; then\n echo 'tag did not resolve to one full object OID' >&2\n exit 1\nfi\ngit init --bare \"$verify_repo\" >/dev/null\nGIT_ASKPASS=\"$askpass\" GIT_TERMINAL_PROMPT=0 EGGPACK_GIT_TOKEN=\"$GITHUB_TOKEN\" git --git-dir=\"$verify_repo\" fetch --no-tags --depth=1 \"$remote\" \"$ref\" >/dev/null\nfetched_commit=\"$(git --git-dir=\"$verify_repo\" rev-parse --verify 'FETCH_HEAD^{commit}')\"\nif [ \"$fetched_commit\" != \"$source_sha\" ]; then\n echo 'tag did not resolve to the advertised commit object' >&2\n exit 1\nfi\nif [ \"$source_sha\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag moved after preflight resolution' >&2\n exit 1\nfi\n" - name: Check out source uses: "actions/checkout@11d5960a326750d5838078e36cf38b85af677262" with: - ref: "${{ inputs.release_tag }}" + ref: "${{ needs.resolve.outputs.source_sha }}" + - name: Verify frozen source checkout + shell: bash + env: + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: test "$(git rev-parse --verify HEAD^{commit})" = "$EGGPACK_EXPECTED_SOURCE_SHA" + - name: Fetch release tag for local verification + shell: bash + env: + EGGPACK_RELEASE_TAG: "${{ inputs.release_tag }}" + EGGPACK_EXPECTED_SOURCE_SHA: "${{ needs.resolve.outputs.source_sha }}" + run: "set -euo pipefail\ntag=\"$EGGPACK_RELEASE_TAG\"\nif [ -z \"$tag\" ] || [ \"${#tag}\" -gt 128 ]; then\n echo 'release tag is empty or oversized' >&2\n exit 1\nfi\nref=\"refs/tags/$tag\"\ngit check-ref-format \"$ref\"\ngit fetch --no-tags --depth=1 origin \"$ref:$ref\"\npeeled=\"$(git rev-parse --verify \"$ref^{commit}\")\"\nif [ \"$peeled\" != \"$EGGPACK_EXPECTED_SOURCE_SHA\" ]; then\n echo 'release tag does not peel to the frozen source revision' >&2\n exit 1\nfi\n" + - name: Download runtime release identity uses: "actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093" with: name: "eggpack-runtime-identity" path: "./eggpack-runtime" if-no-files-found: error - - name: Validate exact-tag source - shell: bash - run: "test -n \"${{ inputs.release_tag }}\"" - name: Install pinned Eggpack tool shell: bash timeout-minutes: 30 run: | - cargo install --git https://github.com/eggstack/eggpack --rev 32a0903936fcc283863e0bfb86151b13b4d75ce9 --locked eggpack-cli + cargo install --git https://github.com/eggstack/eggpack --rev 242654ab29e59ebbd3beca0a0ff276f4df4df873 --locked eggpack-cli eggpack --version - name: Verify checked-out release source shell: bash diff --git a/.gitignore b/.gitignore index 65306e1..6a1756a 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,9 @@ out/ # Dependencies node_modules/ vendor/ +!python/eggpass-auth/vendor/ +!python/eggpass-auth/vendor/eggpass-auth/ +!python/eggpass-auth/vendor/eggpass-auth/** __pycache__/ *.py[cod] .venv/ diff --git a/.minimax/skills/eggpass-eggpack-release/SKILL.md b/.minimax/skills/eggpass-eggpack-release/SKILL.md new file mode 100644 index 0000000..21c99bc --- /dev/null +++ b/.minimax/skills/eggpass-eggpack-release/SKILL.md @@ -0,0 +1,71 @@ +--- +name: eggpass-eggpack-release +description: | + Prepare, validate, and publish releases of `eggstack/eggpass` with the checked-in + Eggpack workflow. Trigger when asked to cut an Eggpass release, run Eggpack, + inspect its GitHub draft, or publish the release to GitHub/crates.io. Do not use + for ordinary code changes or another repository's release process. +--- + +# Eggpass Eggpack Release + +## Inputs to collect + +- The intended `X.Y.Z` release version and source branch/commit, if not clear from context. +- Whether the request is to prepare a draft or to publish it. Publishing is a separate, public action that also triggers crates.io publication. + +## Procedure + +1. Read `docs/releasing.md`, the release workflow, `Cargo.toml`, and the changelog. Check the working tree, current version, tag, and existing GitHub release. Releases are immutable: use a new version/tag; do not move or overwrite a published tag or release. For the v0.1.1 release lineage, preserve the v0.1.0 tag at `21e14c93d1b4292b410ce6c0707c064e63c98dc0`. +2. Confirm the release commit has the intended Cargo version (`X.Y.Z`, no `v`) and accurate release notes. Run the repository's CI/release checks before tagging, including formatting, all-target tests, Clippy with warnings denied, and package validation. Fix failures before continuing. +3. Push the release commit, then create and push the annotated tag `vX.Y.Z` pointing at that exact commit. Eggpack does not create or push tags; do not run it against an unpushed or ambiguous tag. +4. Dispatch the checked-in release workflow for the exact tag: + + ```sh + gh workflow run release.yml --repo eggstack/eggpass --field release_tag=vX.Y.Z + ``` + + Watch the resulting run to completion. The workflow should build and qualify all five targets, produce the manifest and checksum sidecars, and stage a **draft** GitHub release. A successful aggregate/gate alone is insufficient; inspect all matrix jobs and artifacts. +5. Inspect the draft's release notes and download every asset. Verify the manifest independently of CI: + - `schema_version` is `1`, `product_id` is `eggpass`, and `release_id` is plain `X.Y.Z` (no leading `v`). + - `source_revision` is the exact 40-character commit the tag peels to. + - The manifest names exactly the five expected target assets below; each recorded size and lowercase SHA-256 matches the downloaded binary. + - Each `.sha256` sidecar also validates against its corresponding binary. + - The release notes agree with the changelog and link to the actual downloads/checksums. + + Expected assets (the Windows executable keeps its `.exe` suffix): + - `eggpass-aarch64-apple-darwin` + - `eggpass-aarch64-unknown-linux-gnu` + - `eggpass-x86_64-apple-darwin` + - `eggpass-x86_64-pc-windows-msvc.exe` + - `eggpass-x86_64-unknown-linux-gnu` + + Do not treat CI's binary `--version` validation as proof that the manifest `release_id` is correct; `scripts/validate-release-version.py` validates the executable against Cargo metadata, not the manifest field. +6. If only the current draft's manifest is wrong and the binaries/sidecars are otherwise verified, correct that draft asset alone with `gh release upload vX.Y.Z --repo eggstack/eggpass --clobber`, then download it again and repeat the manifest/artifact checks. Do not edit the release generator or pipeline as an incidental part of a release; propose that as a separate code change if future runs need a permanent fix. Keep the release a draft until every check passes. +7. Immediately before making it public, obtain explicit user confirmation for this exact tag and its crates.io consequence. A broad initial request to “release” is not the final confirmation. After confirmation, publish the draft: + + ```sh + gh release edit vX.Y.Z --repo eggstack/eggpass --draft=false + ``` + + This public action fires `.github/workflows/publish-crates.yml`, which publishes the crate. Do not expose or print credentials; rely on the configured GitHub CLI session and repository secret. +8. Watch the release-triggered crates.io workflow through its publish step. Confirm the GitHub release is public and the exact `eggpass` version is present on crates.io. If available, run `eggpass update --check` as a final consumer-side check and report its result separately. + +## Output contract + +Report the source commit and tag; workflow run and matrix outcome; draft/public status; five-target manifest and checksum result; GitHub release URL; crates.io workflow and version result; and any checks skipped or still unverified. Never call a draft “published.” + +## Failure handling + +- Any failed workflow job, missing target, mismatched checksum/size/revision/version, or inaccurate release notes blocks publication. Leave the release as a draft and report the evidence. +- If an API request is rate-limited, inspect the relevant run/release state and rate limit before retrying; do not repeat an unchanged failing request in a tight loop. +- If the published version/tag already exists, stop rather than overwrite it. A correction must use the documented recovery path or a new release, never silently retarget history. +- Do not request, read, or paste registry tokens or other credentials into chat or logs. + +## Windows (win32) platform notes + +The Cargo and `gh` commands above also work in PowerShell. Use PowerShell paths and `Get-FileHash -Algorithm SHA256` to compute a local digest; compare its lowercase `Hash` value with the manifest and `.sha256` sidecar. Do not assume `shasum` or `sha256sum` exists. + +## Example + +For v0.1.1, keep the existing v0.1.0 tag unchanged, stage v0.1.1 as a draft, and verify `release_id` is `0.1.1` (not `v0.1.1`) before publication. The v0.1.1 draft's verified `source_revision` was `578a1eb7f3703cdf76861607d2c8a9bbc9807fe5`; the manifest was corrected and re-downloaded before the user authorized publication. diff --git a/CHANGELOG.md b/CHANGELOG.md index ef3513f..667a052 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ Notable changes to eggpass are listed here. The format follows ## [Unreleased] +### Added + +- Add the independently versioned async `eggpass-auth` Rust library and its + Python `asyncio` bindings. + ## [0.1.2] - 2026-11-20 ### Added diff --git a/Cargo.lock b/Cargo.lock index d3be48f..5586b6f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -313,6 +313,37 @@ dependencies = [ "webpki-roots 0.26.11", ] +[[package]] +name = "eggfetch-core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c22bdfc6ab683ddf5d5fcf0321b60dfc86c0ec1311284a33c31f536d12c1d2ae" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "getrandom 0.2.17", + "http", + "http-body", + "http-body-util", + "httpdate", + "hyper", + "hyper-rustls", + "hyper-util", + "pem-rfc7468", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-native-certs", + "thiserror", + "tokio", + "tokio-rustls", + "tower-service", + "url", + "webpki-roots 0.26.11", +] + [[package]] name = "eggfetch-http-connect" version = "0.2.2" @@ -341,6 +372,7 @@ dependencies = [ "base64", "daemonize", "dirs", + "eggpass-auth", "eggup-acquisition", "eggup-core", "eggup-eggfetch", @@ -353,6 +385,7 @@ dependencies = [ "sha2 0.11.1", "signal-hook", "tempfile", + "tokio", "toml", "ureq", "url", @@ -360,6 +393,22 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "eggpass-auth" +version = "0.1.0" +dependencies = [ + "base64", + "eggfetch-core 0.3.0", + "rand", + "serde", + "serde_json", + "sha2 0.11.1", + "tempfile", + "tokio", + "tokio-util", + "url", +] + [[package]] name = "eggup-acquisition" version = "0.2.1" @@ -395,7 +444,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fc8f6480cd6717ed854ac764d0cfc18c6325b7367940149ea2f45f2d5658721" dependencies = [ - "eggfetch-core", + "eggfetch-core 0.2.2", "eggup-acquisition", "futures-util", "tokio", @@ -500,6 +549,23 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" version = "0.3.34" @@ -513,6 +579,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-macro", "futures-task", "pin-project-lite", "slab", @@ -1511,6 +1578,20 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "futures-util", + "pin-project-lite", + "tokio", +] + [[package]] name = "toml" version = "1.2.1+spec-1.1.0" diff --git a/Cargo.toml b/Cargo.toml index 278a96c..8b44e3f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,7 @@ +[workspace] +members = ["crates/eggpass-auth"] +resolver = "3" + [package] name = "eggpass" version = "0.1.2" @@ -9,7 +13,7 @@ readme = "README.md" repository = "https://github.com/eggstack/eggpass" documentation = "https://docs.rs/eggpass" keywords = ["grok", "chatgpt", "openai", "proxy", "oauth"] -categories = ["command-line-utilities", "api-bindings"] +categories = ["command-line-utilities"] # The published crate carries the source and the documentation, and nothing # else: no CI definitions, no live-verification script, no build output. @@ -28,6 +32,7 @@ include = [ ] [dependencies] +eggpass-auth = { version = "0.1.0", path = "crates/eggpass-auth" } base64 = "0.23.1" dirs = "7.0.0" # Self-update mechanics. Acquisition, transport, release-manifest projection, @@ -60,6 +65,7 @@ serde_json = "1.0.154" sha2 = "0.11.1" signal-hook = "0.4.6" toml = "1.2.1" +tokio = { version = "1.54.1", features = ["io-util", "macros", "net", "rt-multi-thread", "sync", "time"] } ureq = "3.5.2" # WHATWG parser for the device-flow URL check. Pinned to the copy already # in Cargo.lock; the check is the parser, so do not bump it in passing. diff --git a/README.md b/README.md index 225f22a..a742291 100644 --- a/README.md +++ b/README.md @@ -18,16 +18,18 @@ need a separate provider API key. ## Install +Install the published CLI from crates.io: + ```sh -cargo install eggpass --git https://github.com/eggstack/eggpass +cargo install eggpass ``` -Or install from a local checkout: +To build the current repository checkout instead: ```sh git clone https://github.com/eggstack/eggpass cd eggpass -cargo install --path . +cargo install --path . --locked --force ``` ## Quick start @@ -126,7 +128,7 @@ cleared when the daemon stops. | `eggpass usage` | Show subscription usage where available, preferring the running daemon's cached report. | | `eggpass run` | Start the server. Use `--foreground` to keep it in the terminal. | | `eggpass stop` / `restart` | Stop or restart the server. | -| `eggpass port` / `host` | Show or change the listen address. Changes restart the server. | +| `eggpass port` / `host` | Show or change the listen address. Changes restart a running server; when stopped, they take effect at the next start. | | `eggpass key` | Add, list, or revoke client keys. | | `eggpass edit` | Edit the config file. | | `eggpass croncheck` | Start the server if it is not running. | diff --git a/async-auth-library-requirements.md b/async-auth-library-requirements.md new file mode 100644 index 0000000..b723aec --- /dev/null +++ b/async-auth-library-requirements.md @@ -0,0 +1,57 @@ +# Requirements for a public async Eggpass auth library + +## Recommendation and boundary + +The deliverable should be a separate, small Rust library crate—provisionally `eggpass-auth`—rather than making the whole Eggpass application async. Eggpass currently has only a binary target: `src/main.rs` declares `mod auth`, and the OAuth types are not exported to downstream crates (`src/main.rs:8-21`). Its server deliberately uses blocking sockets, one thread per connection, and synchronous SSE writes (`src/server/http.rs:166-253, 748-772`). None of that needs to change for async downstream consumers to call reusable auth functions. + +The library should expose an async OAuth core that accepts or can be built around an `eggfetch_core::Client`, but should not create a Tokio runtime, print to the terminal, open a browser, or assume that credentials live in Eggpass’s home-directory files. Keep CLI conveniences and the current synchronous `TokenProvider` integration in Eggpass as host-side adapters. That preserves the existing proxy architecture while letting async consumers call the library inside their own runtime. + +At the time of this research, crates.io’s API returned “crate does not exist” for `eggpass-auth`; the name appears available but must be checked again before publishing. Eggfetch 0.3.0 is the current documented async API. Eggpass’s updater currently brings in Eggfetch 0.2.2 through `eggup-eggfetch` 0.2.0, which depends on the 0.2 line. A new direct 0.3 dependency will therefore coexist with 0.2.x until the updater adapter moves forward or the duplicate is accepted. + +## Public API requirements + +**Provider configuration must be auth-specific.** Do not export Eggpass’s full `ProviderSpec`: it mixes OAuth endpoints and scopes with inference URLs, request policies, headers, and catalogue formats (`src/provider/mod.rs:65-160`). Define a focused `OAuthProviderConfig` containing issuer/endpoints, client ID policy, scopes, callback path, and the provider-specific parameters the OAuth requests need. Include the current x.ai and OpenAI profiles, while allowing callers to construct a compatible profile without importing Eggpass server/config modules. Preserve OpenAI’s issued-client-ID behavior and registration-only parameters, and x.ai’s client ID, `referrer` fallback, and device-flow support (`src/provider/xai.rs:75-100`; `src/provider/openai.rs:149-198`). + +**Separate protocol from user interaction.** The core should offer async operations for authorization-code exchange, refresh, revocation, user-info, device-code creation, and polling. For browser authorization, provide a session/transaction API that returns the authorization URL and later accepts a validated callback; keep the verifier, state, and nonce inside an opaque pending-session value. An optional loopback helper can bind a random loopback port, but terminal prompts, browser launching, and stdin handling belong in an optional adapter or in the downstream application. For device authorization, return the verification URI and user code as data; let the caller decide how to present them, then poll asynchronously with cancellation support. + +**Make credentials caller-owned by default.** Provide token parsing and refresh operations independently of the current `~/.config/eggpass/auth.json` path and Grok CLI import. A downstream service may want to store credentials in its own database or secret store. A generic storage seam or an explicit-token API should enable that; Eggpass’s restrictive, atomic file store and `~/.grok/auth.json` import can remain optional adapters (`src/auth/store.rs:1-18, 130-195`). Document the concurrency guarantee: the current manager’s mutex coalesces refreshes within a process but is not a cross-process lock (`src/auth/refresh.rs:67-187`). Either make the store contract support cross-process coordination or state that boundary clearly. + +**Make Eggfetch ergonomic without hiding its ownership.** Accept a caller-supplied, cloneable `eggfetch_core::Client` so downstream code can reuse its connection pool and configuration. Offer a builder/default convenience only if it does not create a runtime or hide timeout policy. Keep Eggfetch response internals out of public return types; translate them to the library’s own status, OAuth, parsing, timeout, and network errors. The library’s async methods should simply be awaited in the caller’s runtime. Eggfetch’s [0.3.0 Client API](https://docs.rs/eggfetch-core/0.3.0/eggfetch_core/client/struct.Client.html) is async-first; its [Timeout API](https://docs.rs/eggfetch-core/0.3.0/eggfetch_core/timeout/struct.Timeout.html) supports separate pool/connect/write/read/total budgets. + +**Keep public types semver-manageable.** Use builders for provider/client configuration, avoid exposing internal module paths, mark extensible error enums non-exhaustive, document ownership and `Send`/`Sync` guarantees, and include compiling Tokio/Eggfetch examples. If the public constructor accepts the Eggfetch `Client` type, the library is coupled to that Eggfetch version line; downstream consumers must align to a compatible line to pass their client directly. Avoid a generic async transport trait in the first version unless transport substitution is a real requirement—it adds API and implementation complexity without helping the stated Eggfetch-first consumers. + +## Security and protocol acceptance criteria + +The library must retain the safeguards already present in the current auth code and make them part of its public contract: + +- Authorization-code flows use PKCE S256, high-entropy state, and nonce; callback state and the exact redirect path are validated. For native apps, [RFC 8252](https://www.rfc-editor.org/rfc/rfc8252.html) requires PKCE for public clients and recommends an external user-agent. Loopback listeners must bind only to loopback, use a short-lived random port, and close after completion. Do not introduce embedded-login pages. +- Device verification URIs are checked against the provider’s trusted-host policy before the library opens or presents them. Device-code values are not shown to users or placed in logs. +- Async cancellation, request deadlines, and response-size bounds are explicit. Preserve current OAuth timeouts intentionally rather than inheriting Eggfetch defaults accidentally. Do not blindly retry token exchanges or refreshes; document the retry policy, especially around refresh-token rotation. +- The manager preserves the current proactive refresh skew, 401 compare-and-refresh behavior, one-refresh-under-concurrency guarantee, atomic persistence, and rule that a missing rotated refresh token does not erase the existing one (`src/auth/refresh.rs:119-179, 190-225`). +- Public errors may expose status and OAuth error codes, but should not automatically include arbitrary response bodies. Token-bearing values need redacted `Debug` implementations and should never be logged by the library. + +Two concrete porting issues need resolution before declaring parity. First, `TokenSet`, `DeviceCode`, and `StoredAuth` currently derive `Debug` while containing access/refresh tokens or device codes (`src/auth/client.rs:51-67, 130-145`; `src/auth/store.rs:44-87`). A public crate should redact those fields (or use secret wrappers) before downstream users can accidentally log them. Second, the current device-flow loop increments the polling interval by **one** second after `slow_down` (`src/auth/flow.rs:277-279`), but [RFC 8628 §3.5](https://www.rfc-editor.org/rfc/rfc8628.html#section-3.5) requires increasing it by five seconds for that and subsequent polls. The loop also clamps `expires_in` to at least 60 seconds (`src/auth/flow.rs:259-264`); review that against the server-provided expiry rather than copying it unquestioned. Async cancellation and timeout retries should also follow RFC 8628’s polling guidance. + +## Package, dependency, tests, and release work + +A separate `eggpass-auth` workspace package is the cleaner boundary than adding a library target to the existing binary package. The current `Cargo.toml` has a broad CLI/server dependency list and an explicit root-package include list (`Cargo.toml:1-28, 30-77`). A dedicated package can keep its dependency surface focused on Eggfetch, serde/JSON, time/PKCE utilities, and optional storage/loopback adapters. Keep the existing MSRV at Rust 1.89 if using Eggfetch 0.3.0, which also declares Rust 1.89. + +The current `.github/workflows/publish-crates.yml` checks and publishes only the root `eggpass` package (`.github/workflows/publish-crates.yml:41-61`). A public auth crate therefore needs its own package verification and publish path, or a deliberate workspace-aware release workflow. Decide whether the auth crate is versioned independently or must ship in lockstep with the CLI; test the exact crate with `cargo package --locked` before publication. Do not assume the existing Eggpack release job or crates.io workflow will automatically publish a second package. + +Minimum acceptance tests should cover request form encoding and provider-specific parameters; success, OAuth error, non-JSON error, timeout, and oversized-body handling; PKCE/state/nonce and callback validation; device `authorization_pending`, `slow_down`, denial, expiry, and cancellation; OpenAI issued-client-ID reuse; refresh-token rotation; concurrent access-token refresh; and atomic credential persistence. Run tests against a local stub endpoint using the real Eggfetch client, then compile a small downstream-style consumer that supplies its Eggfetch client and awaits login/refresh without Eggpass CLI or server modules. Keep network-dependent live provider checks separate from deterministic CI. + +## Decisions to settle before implementation + +1. **MVP flow scope:** async OAuth/token operations only, or also complete browser loopback and device-login orchestration? Recommended: core transaction/polling APIs in the first release; UI and loopback conveniences as optional adapters. +2. **Storage contract:** caller-owned token storage only, or include a default file store? Recommended: caller-owned storage in core; optional Eggpass-compatible file adapter. +3. **Crate/release boundary:** separate `eggpass-auth` package with independent versioning, or couple its release to `eggpass`? Recommended: separate package and explicit publication workflow. +4. **Eggfetch alignment:** accept the current dual 0.2/0.3 dependency graph temporarily, or first update/release the Eggup adapter against Eggfetch 0.3.0? This affects dependency duplication, not the downstream API design. +5. **Provider extensibility:** only the built-in x.ai/OpenAI profiles, or a documented generic OAuth provider configuration as well? Recommended: support the two built-ins and a minimal custom OAuth profile, but keep provider-specific registration semantics explicit. + +## Sources + +- Eggpass source: `src/main.rs:8-21`; `src/auth/client.rs:51-67, 130-145, 162-220, 298-545`; `src/auth/flow.rs:127-289`; `src/auth/refresh.rs:67-225`; `src/auth/store.rs:1-18, 44-87, 130-195`; `src/provider/xai.rs:75-100`; `src/provider/openai.rs:149-198`; `src/server/http.rs:166-253, 748-772`; `.github/workflows/publish-crates.yml:41-61`. +- [RFC 8252 — OAuth 2.0 for Native Apps](https://www.rfc-editor.org/rfc/rfc8252.html). +- [RFC 8628 — OAuth 2.0 Device Authorization Grant](https://www.rfc-editor.org/rfc/rfc8628.html). +- [Eggfetch `eggfetch-core` 0.3.0](https://docs.rs/eggfetch-core/0.3.0/eggfetch_core/) and [Eggup Eggfetch adapter 0.2.0](https://docs.rs/eggup-eggfetch/0.2.0/eggup_eggfetch/). +- [crates.io `eggpass-auth` lookup](https://crates.io/api/v1/crates/eggpass-auth) (not found at research time; availability can change). diff --git a/async-auth-migration-cost.md b/async-auth-migration-cost.md new file mode 100644 index 0000000..5e247d5 --- /dev/null +++ b/async-auth-migration-cost.md @@ -0,0 +1,39 @@ +# Cost of an async Eggpass auth library + +## Recommendation + +For downstream Rust repositories that already run async code and use Eggfetch, the useful migration target is a **public async authentication library**, not an async rewrite of Eggpass’s proxy server. The auth module is currently private to the `eggpass` binary (`src/main.rs:8-21`), so changing ureq calls to Eggfetch alone would not make the code consumable downstream. A focused `eggpass-auth` library—async OAuth/token methods and, if required, login flows—addresses the stated goal while leaving the custom blocking server and its SSE path intact. + +My rough estimate for that full reusable auth surface, including keeping Eggpass’s current CLI and server operational, is **8–15 engineer-days (about 2–3 working weeks for one experienced Rust engineer)**. A narrower async OAuth client plus a small public API and consumer example, without porting the token manager or interactive login flows, is approximately **3–5 engineer-days**. A full Eggpass server conversion is a separate, substantially larger project; I would not undertake it for this downstream-reuse goal. These are code-review estimates, not measured implementation times; they assume provider behavior stays unchanged and carry roughly ±50% uncertainty until downstream API requirements are known. + +## Where the work is + +`OAuthClient` owns a ureq agent and synchronous exchange, device-code, refresh, revocation, and user-info calls (`src/auth/client.rs:167-220, 298-545`). Replacing those calls with Eggfetch is mechanically bounded: Eggfetch’s `Client` has async request methods, and request builders send with `.await`; response bodies can be collected or streamed asynchronously. The work is principally translating request construction, status/body/error mapping, user-agent and timeout policy, and the existing local-server tests—not reimplementing OAuth. + +The larger change is state and flow behavior. `TokenManager::access_token` and `force_refresh` are synchronous, use `std::sync::Mutex`, and deliberately re-check credentials after taking the lock to collapse concurrent refreshes (`src/auth/refresh.rs:67-187`). Its async version must preserve that single-refresh property across `await`, preserve refresh-token rotation, and save credentials atomically. The current store uses synchronous filesystem operations and restrictive permissions (`src/auth/store.rs:1-18, 130-195`); it can remain a small synchronous boundary initially, but should not be accidentally weakened during extraction. + +Login flows add another layer: device login polls with `std::thread::sleep`, while browser login uses a blocking loopback `TcpListener` and an optional stdin thread (`src/auth/flow.rs:127-289, 370-517`). A complete async login API needs to make polling cancellable and awaitable, and decide how to host the callback listener and terminal input. Separately, auth types depend on Eggpass’s combined provider description and credential paths, while the synchronous `TokenProvider` trait is declared in `src/upstream.rs:54-70` and consumed by request handling (`src/upstream.rs:207-229`). A downstream package should have a smaller OAuth-only provider configuration and storage boundary rather than importing server/config internals. + +Eggpass’s server is intentionally blocking: it uses a standard `TcpListener`, spawns one OS thread per connection, and writes and flushes SSE chunks synchronously (`src/server/http.rs:166-253, 748-772`). That creates an integration boundary, but not a reason to make the HTTP server async. Eggpass can keep a small host-owned compatibility adapter for the current CLI/server while downstream crates call the auth library’s async API directly. Keep runtime bridging at that host boundary; do not hide runtime construction inside a reusable library. Tokio’s own guidance discusses explicit sync/async bridging and using blocking work at appropriate boundaries ([Tokio bridging](https://tokio.rs/tokio/topics/bridging), [Tokio `spawn_blocking`](https://docs.rs/tokio/latest/tokio/task/fn.spawn_blocking.html)). + +## Effort by scope + +| Scope | Estimate | Included work | +|---|---:|---| +| Async OAuth transport only | 3–5 engineer-days | Convert `OAuthClient` endpoint calls to Eggfetch; preserve timeouts, user-agent, status/error semantics; update HTTP tests; add a minimal consumer example. This does not make the current private module reusable unless a public library surface is added. | +| Recommended reusable auth package | 8–15 engineer-days | Add a public crate/API; isolate OAuth provider configuration from inference/config types; async OAuth and token refresh; preserve refresh serialization and credential-store guarantees; port device and loopback login as required; add a synchronous host adapter for Eggpass; test a downstream-style Eggfetch consumer. | +| Entire Eggpass application async | Several additional weeks; separate estimate | Replace or adapt the custom server, upstream request path, connection management, and synchronous streaming writer. This is outside the stated purpose and would increase risk without improving downstream auth ergonomics proportionally. | + +The full package estimate assumes both browser and device login should remain supported. If downstream callers only need to exchange/refresh tokens after handling user interaction themselves, omitting the login-flow port should reduce the estimate by several days. Publishing a new crate also adds ongoing compatibility, documentation, and semver obligations beyond the initial implementation. + +## Eggfetch version and integration cost + +Eggfetch’s current published `eggfetch-core` is 0.3.0 (released 31 October 2026); its documentation describes it as async-first and demonstrates `.send().await` and async body reads ([0.3.0 docs](https://docs.rs/eggfetch-core/0.3.0/eggfetch_core/), [Client API](https://docs.rs/eggfetch-core/0.3.0/eggfetch_core/client/struct.Client.html)). Eggpass’s lockfile currently resolves `eggfetch-core` 0.2.2 through `eggup-eggfetch` 0.2.0, as confirmed by `cargo tree --locked --offline`. The published updater adapter remains at 0.2.0 and depends on `eggfetch-core ^0.2.0` ([adapter docs](https://docs.rs/eggup-eggfetch/0.2.0/eggup_eggfetch/); [crates.io version metadata](https://crates.io/api/v1/crates/eggup-eggfetch)). Therefore, adding a direct 0.3.x dependency for the new auth library will currently leave both 0.2.x and 0.3.x in Eggpass’s dependency graph. That is manageable, but has compile/binary-size and maintenance cost; it can be avoided later if the updater adapter is released against 0.3.x. Downstream consumers on 0.3.x should use the same major/minor line if the library accepts an Eggfetch `Client` from the caller. + +Eggfetch’s `Timeout` supports separate pool, connect, write, read, and total deadlines ([timeout API](https://docs.rs/eggfetch-core/0.3.0/eggfetch_core/timeout/struct.Timeout.html)). The port still needs to deliberately map Eggpass’s existing OAuth agent policy (60-second global and 180-second body receive timeouts in `src/auth/client.rs:189-194`); phase-aware defaults should not silently change login behavior. ureq is explicitly a blocking-I/O client ([ureq 3.5.2 docs](https://docs.rs/ureq/3.5.2/ureq/)). + +## Suggested implementation boundary + +Create a small library crate with an OAuth-specific provider config, `OAuthClient` constructed with or accepting a clone of `eggfetch_core::Client`, and async token/refresh methods. Keep provider policy and token parsing in the crate; make credential persistence configurable or portable. Port the device and browser flow only if downstream callers need Eggpass to own those interactions. In the binary, adapt its current synchronous token-provider contract at the boundary, so the proxy’s ureq inference path and SSE implementation need not move in the same change. + +Do not count this as a complete removal of ureq: it remains used by upstream inference, daemon health probes, and usage queries (`src/upstream.rs:91-204`, `src/daemon.rs:210-223`, `src/cli/commands/usage.rs:291-309`). Removing ureq from the dependency graph would require a broader, separately justified migration. diff --git a/crates/eggpass-auth/Cargo.toml b/crates/eggpass-auth/Cargo.toml new file mode 100644 index 0000000..f39d24f --- /dev/null +++ b/crates/eggpass-auth/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "eggpass-auth" +version = "0.1.0" +edition = "2024" +rust-version = "1.89" +description = "Async OAuth authentication flows for applications using Eggfetch" +license = "MIT" +readme = "README.md" +repository = "https://github.com/eggstack/eggpass" +documentation = "https://docs.rs/eggpass-auth" +keywords = ["oauth", "authentication", "async"] +categories = ["asynchronous", "authentication"] +include = ["/src", "/README.md", "/LICENSE", "/examples"] + +[dependencies] +base64 = "0.23.1" +eggfetch-core = { version = "0.3.0", default-features = false, features = ["http1", "logical-retry", "redirects", "tls-rustls", "tls-native-roots"] } +rand = "0.10.3" +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +sha2 = "0.11.1" +tokio = { version = "1.54.1", features = ["macros", "rt", "sync", "time"] } +tokio-util = { version = "0.7", features = ["rt"] } +url = "2.5.8" + +[dev-dependencies] +tempfile = "3.27.0" +tokio = { version = "1.54.1", features = ["io-util", "macros", "net", "rt-multi-thread", "test-util", "time"] } + +[package.metadata.docs.rs] +all-features = true diff --git a/crates/eggpass-auth/LICENSE b/crates/eggpass-auth/LICENSE new file mode 100644 index 0000000..329eea1 --- /dev/null +++ b/crates/eggpass-auth/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 David Bowman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/eggpass-auth/README.md b/crates/eggpass-auth/README.md new file mode 100644 index 0000000..a208ad1 --- /dev/null +++ b/crates/eggpass-auth/README.md @@ -0,0 +1,63 @@ +# eggpass-auth + +Async OAuth authentication primitives for applications using Eggfetch. The crate is independently versioned from the Eggpass CLI and accepts an Eggfetch 0.3 `Client` owned by the caller. + +## Boundary + +The library does not create a Tokio runtime, launch a browser, print to a terminal, bind a callback listener, read stdin, or assume a credential file path. The host application owns the runtime, user interface, callback transport, and persistence. The async methods are awaited on the application's runtime. + +## Browser authorization + +```rust,no_run +use eggfetch_core::Client; +use eggpass_auth::{OAuthClient, OAuthProviderConfig}; + +# async fn example() -> Result<(), Box> { +let auth = OAuthClient::new(Client::new(), OAuthProviderConfig::xai()); +let pending = auth.begin_authorization("http://127.0.0.1:43123/callback", None)?; +let url_for_external_browser = pending.authorization_url(); +// Present the URL, receive the callback in the host application, then pass its +// full URL to complete_authorization. The crate does not create the listener. +let _ = url_for_external_browser; +# Ok(()) +# } +``` + +`begin_authorization` creates PKCE S256, state, nonce, and the authorization URL. `complete_authorization` consumes the opaque pending transaction and rejects callback origin/path mismatches, missing or mismatched state, and an ID-token nonce mismatch. The ID-token nonce claim is checked; this crate does not validate ID-token signatures. Use the provider's user-info endpoint or a separate OIDC verifier when signature/issuer/audience validation is required. + +## Device authorization + +`request_device_code().await` returns a `DeviceCode` containing a verification URI and user code. Before returning it, the library requires HTTPS and an exact provider-configured host match for both regular and pre-filled URIs. The caller presents these values. `poll_device_authorization(&device, &cancel, timeout).await` sleeps before the first poll, honors server expiry (including short lifetimes), applies the RFC 8628 five-second increment after each `slow_down`, and supports cancellation and a caller timeout. + +## Profiles + +- `OAuthProviderConfig::xai()` uses the public x.ai client ID, full scopes, `referrer=eggpass`, device authorization, and the exact x.ai verification-host allowlist. +- `OAuthProviderConfig::xai_compatibility_fallback()` returns the `grok-build` referrer and the reference client's shorter scope set for a new user authorization after a client-configuration refusal. Token exchange and refresh are never retried automatically. +- `OAuthProviderConfig::openai()` uses the `dynamic_agent_client` registration entrypoint, OpenAI resource parameters, and registration-only `agent_name_hint=eggpass`. OpenAI's issued ID is returned in `Credentials::client_id()` and should be persisted/reused. `openai_with_host_id(...)` adds a caller-owned stable `ext_agent_host_id`. +- `OAuthProviderConfig::custom(...)` starts a builder for custom endpoints and scopes. Endpoints require HTTPS, except localhost/loopback HTTP for local tests. Add verification hosts before using device flow. + +Custom parameters should contain OAuth protocol parameters, not secrets. `Debug` output redacts client IDs and custom parameter values. `PendingAuthorization` also redacts its authorization URL, verifier, state, and nonce; provider issuer/endpoint URLs, configured scopes, callback paths, and the pending redirect URI are printed. + +## Explicit token operations + +The low-level operations `exchange_authorization_code`, `refresh_token`, `revoke`, and `userinfo` are async and accept explicit caller-owned token values. `refresh_token` returns the provider's token set without retrying. When an issued refresh response omits a new refresh token, preserve the previous one when saving credentials. Prefer `refresh_credentials` or `TokenManager` for this merge behavior. + +## Storage and refresh manager + +Implement `CredentialStore` for the application's database or secret store. Its `save` operation should atomically replace a credential set. `TokenManager` performs proactive refresh with a five-minute default skew, compares the failed 401 token before refreshing, coalesces refreshes in one manager/process, and retains an old refresh token when rotation is omitted. It does not provide a cross-process lock. The crate has no built-in filesystem adapter. + +## HTTP safety defaults + +Each request explicitly sets finite Eggfetch phase and total timeouts (pool/connect/write 10–15 seconds, read 30 seconds, total 60 seconds by default) and caps decoded response bodies at 1 MiB. Tune them with `ClientOptions`. Requests disable redirects, automatic retries, and caller-configured default authentication; the user-info call sets its own bearer token. OAuth errors expose status and a sanitized error code, not arbitrary response bodies. Timeout and transport diagnostics are deliberately generic to avoid leaking request details. + +## Validation + +Run the downstream-style example and deterministic local OAuth stub tests with: + +```sh +cargo test -p eggpass-auth --locked +cargo check -p eggpass-auth --example downstream --locked +cargo package -p eggpass-auth --locked --allow-dirty +``` + +Provider-live requests are not part of deterministic CI. diff --git a/crates/eggpass-auth/examples/downstream.rs b/crates/eggpass-auth/examples/downstream.rs new file mode 100644 index 0000000..4063e5a --- /dev/null +++ b/crates/eggpass-auth/examples/downstream.rs @@ -0,0 +1,21 @@ +use std::error::Error; + +use eggfetch_core::Client; +use eggpass_auth::{OAuthClient, OAuthProviderConfig}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // The application owns this runtime and HTTP client. eggpass-auth creates + // neither and simply returns futures for the application to await. + let oauth = OAuthClient::new(Client::new(), OAuthProviderConfig::xai()); + let _pending = oauth.begin_authorization("http://127.0.0.1:43123/callback", None)?; + + // Optional opt-in demonstration of an async refresh using a caller-supplied + // token. The token itself is never printed. This example does not launch a + // browser or start a callback listener. + if let Ok(refresh_token) = std::env::var("EGGPASS_AUTH_REFRESH_TOKEN") { + let refreshed = oauth.refresh_token(&refresh_token, None).await?; + println!("Refresh succeeded; expiry: {:?}", refreshed.expires_at()); + } + Ok(()) +} diff --git a/crates/eggpass-auth/src/authorization.rs b/crates/eggpass-auth/src/authorization.rs new file mode 100644 index 0000000..1c9a4c2 --- /dev/null +++ b/crates/eggpass-auth/src/authorization.rs @@ -0,0 +1,390 @@ +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use rand::Rng; +use serde_json::Value; +use sha2::{Digest, Sha256}; + +use crate::client::{OAuthClient, PendingAuthorization, validate_redirect_uri}; +use crate::provider::ClientIdPolicy; +use crate::token::{Credentials, TokenSet}; +use crate::{Error, Result}; + +pub(crate) fn begin_authorization( + client: &OAuthClient, + redirect_uri: &str, + existing: Option<&Credentials>, +) -> Result { + let redirect = validate_redirect_uri(redirect_uri, &client.provider.callback_path)?; + if let Some(credentials) = existing + && !credentials.issuer().is_empty() + && credentials.issuer() != client.provider.issuer + { + return Err(Error::InvalidConfiguration( + "existing credentials belong to a different issuer", + )); + } + + let existing_client_id = existing + .map(Credentials::client_id) + .filter(|client_id| !client_id.is_empty()); + let registration = client.provider.client_id_policy == ClientIdPolicy::IssuedOnRegistration + && existing_client_id.is_none(); + let client_id = if client.provider.client_id_policy == ClientIdPolicy::IssuedOnRegistration { + existing_client_id + .unwrap_or(&client.provider.client_id) + .to_string() + } else { + client.provider.client_id.clone() + }; + let code_verifier = random_urlsafe(32); + let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(code_verifier.as_bytes())); + let state = random_urlsafe(32); + let nonce = random_urlsafe(32); + + let scope = client.provider.scopes.join(" "); + let mut authorization_url = url::Url::parse(&client.provider.authorization_endpoint) + .map_err(|_| Error::InvalidConfiguration("authorization endpoint URL is invalid"))?; + { + let mut query = authorization_url.query_pairs_mut(); + query.append_pair("response_type", "code"); + query.append_pair("client_id", &client_id); + query.append_pair("redirect_uri", redirect_uri); + query.append_pair("scope", &scope); + query.append_pair("code_challenge", &challenge); + query.append_pair("code_challenge_method", "S256"); + query.append_pair("state", &state); + query.append_pair("nonce", &nonce); + for (name, value) in &client.provider.authorization_parameters { + query.append_pair(name, value); + } + if registration { + for (name, value) in &client.provider.registration_parameters { + query.append_pair(name, value); + } + } + if !registration && let Some(id_token) = existing.and_then(Credentials::id_token) { + query.append_pair("id_token_hint", id_token); + } + } + + Ok(PendingAuthorization { + authorization_url: authorization_url.into(), + redirect_uri: redirect.to_string(), + code_verifier, + state, + nonce, + client_id, + registration, + }) +} + +pub(crate) async fn complete_authorization( + client: &OAuthClient, + pending: PendingAuthorization, + callback_url: &str, +) -> Result { + let callback = url::Url::parse(callback_url).map_err(|_| Error::CallbackMismatch)?; + let redirect = url::Url::parse(&pending.redirect_uri).map_err(|_| Error::CallbackMismatch)?; + if callback.path() != client.provider.callback_path + || !same_origin(&callback, &redirect) + || callback.path() != redirect.path() + || !callback.username().is_empty() + || callback.password().is_some() + || callback.fragment().is_some() + { + return Err(Error::CallbackMismatch); + } + + let state = unique_query_value(&callback, "state")?.ok_or(Error::StateMismatch)?; + if state != pending.state { + return Err(Error::StateMismatch); + } + if let Some(error) = unique_query_value(&callback, "error")? { + return Err(Error::ProviderDenied(sanitize_oauth_code(&error))); + } + let code = unique_query_value(&callback, "code")? + .ok_or(Error::InvalidResponse("authorization callback has no code"))?; + if code.is_empty() || code.chars().any(char::is_control) { + return Err(Error::InvalidResponse( + "authorization callback code is invalid", + )); + } + + let callback_client_id = unique_query_value(&callback, "client_id")?; + let client_id = match client.provider.client_id_policy { + ClientIdPolicy::Fixed => pending.client_id.clone(), + ClientIdPolicy::IssuedOnRegistration if pending.registration => callback_client_id + .filter(|issued| !issued.trim().is_empty()) + .ok_or(Error::InvalidResponse( + "provider callback has no issued client ID", + ))?, + ClientIdPolicy::IssuedOnRegistration => { + if callback_client_id + .as_ref() + .is_some_and(|issued| issued != &pending.client_id) + { + return Err(Error::CallbackMismatch); + } + pending.client_id.clone() + } + }; + let callback_scope = unique_query_value(&callback, "scope")?; + + complete_pending_authorization(client, pending, code, client_id, callback_scope).await +} + +pub(crate) async fn complete_authorization_with_code( + client: &OAuthClient, + pending: PendingAuthorization, + code: &str, +) -> Result { + if client.provider.client_id_policy == ClientIdPolicy::IssuedOnRegistration { + return Err(Error::Unsupported( + "pasted authorization codes for issued-client-ID providers", + )); + } + if code.is_empty() || code.chars().any(char::is_control) { + return Err(Error::InvalidResponse( + "pasted authorization code is invalid", + )); + } + let client_id = pending.client_id.clone(); + complete_pending_authorization(client, pending, code.to_string(), client_id, None).await +} + +async fn complete_pending_authorization( + client: &OAuthClient, + pending: PendingAuthorization, + code: String, + client_id: String, + callback_scope: Option, +) -> Result { + let mut parameters = vec![ + ("grant_type".to_string(), "authorization_code".to_string()), + ("code".to_string(), code), + ("redirect_uri".to_string(), pending.redirect_uri), + ("client_id".to_string(), client_id.clone()), + ("code_verifier".to_string(), pending.code_verifier), + ]; + parameters.extend(client.provider.token_parameters.clone()); + let value = client + .post_form_json(&client.provider.token_endpoint, ¶meters) + .await?; + let tokens = TokenSet::from_json(&value, Credentials::now_unix())?; + if client.provider.scopes.iter().any(|scope| scope == "openid") { + validate_nonce(tokens.id_token(), &pending.nonce)?; + } else if let Some(id_token) = tokens.id_token() { + validate_nonce(Some(id_token), &pending.nonce)?; + } + let mut credentials = Credentials::from_tokens( + tokens, + client_id, + client.provider.issuer.clone(), + Credentials::now_unix(), + ); + if credentials.scope.is_none() { + credentials.scope = callback_scope; + } + Ok(credentials) +} + +fn unique_query_value(url: &url::Url, name: &str) -> Result> { + let mut values = url.query_pairs().filter(|(key, _)| key == name); + let value = values.next().map(|(_, value)| value.into_owned()); + if values.next().is_some() { + return Err(Error::CallbackMismatch); + } + Ok(value) +} + +fn same_origin(left: &url::Url, right: &url::Url) -> bool { + left.scheme() == right.scheme() + && left.host_str().is_some_and(|host| { + right + .host_str() + .is_some_and(|other| host.eq_ignore_ascii_case(other)) + }) + && left.port_or_known_default() == right.port_or_known_default() +} + +fn validate_nonce(id_token: Option<&str>, expected_nonce: &str) -> Result<()> { + let Some(id_token) = id_token else { + return Err(Error::NonceMismatch); + }; + let Some(payload) = id_token.split('.').nth(1) else { + return Err(Error::NonceMismatch); + }; + let decoded = URL_SAFE_NO_PAD + .decode(payload) + .map_err(|_| Error::NonceMismatch)?; + let claims: Value = serde_json::from_slice(&decoded).map_err(|_| Error::NonceMismatch)?; + if claims.get("nonce").and_then(Value::as_str) == Some(expected_nonce) { + Ok(()) + } else { + Err(Error::NonceMismatch) + } +} + +fn sanitize_oauth_code(value: &str) -> String { + crate::error::safe_oauth_error_code(value) + .unwrap_or("unknown_error") + .to_string() +} + +fn random_urlsafe(bytes: usize) -> String { + let mut value = vec![0; bytes]; + rand::rng().fill_bytes(&mut value); + URL_SAFE_NO_PAD.encode(value) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::client::OAuthClient; + use crate::provider::OAuthProviderConfig; + use eggfetch_core::Client; + + fn client() -> OAuthClient { + OAuthClient::new(Client::new(), OAuthProviderConfig::xai()) + } + + #[test] + fn authorization_transaction_uses_pkce_state_nonce_and_callback_path() { + let pending = client() + .begin_authorization("http://127.0.0.1:34567/callback", None) + .unwrap(); + let url = url::Url::parse(pending.authorization_url()).unwrap(); + let values: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect(); + assert_eq!( + values.get("code_challenge_method").map(String::as_str), + Some("S256") + ); + assert_eq!( + values.get("redirect_uri").map(String::as_str), + Some("http://127.0.0.1:34567/callback") + ); + assert_eq!( + values.get("state").map(String::as_str), + Some(pending.state.as_str()) + ); + assert_eq!( + values.get("nonce").map(String::as_str), + Some(pending.nonce.as_str()) + ); + assert!(values.contains_key("code_challenge")); + assert!(pending.authorization_url().contains("referrer=eggpass")); + let debug = format!("{pending:?}"); + assert!(!debug.contains(&pending.state)); + assert!(!debug.contains(&pending.code_verifier)); + assert!(!debug.contains(&pending.nonce)); + } + + #[test] + fn openai_registration_hint_is_only_sent_for_first_authorization() { + let client = OAuthClient::new(Client::new(), OAuthProviderConfig::openai()); + let first = client + .begin_authorization("http://127.0.0.1:45678/auth/callback", None) + .unwrap(); + let first_url = url::Url::parse(first.authorization_url()).unwrap(); + let first_values: std::collections::HashMap<_, _> = + first_url.query_pairs().into_owned().collect(); + assert_eq!( + first_values.get("client_id").map(String::as_str), + Some("dynamic_agent_client") + ); + assert_eq!( + first_values.get("agent_name_hint").map(String::as_str), + Some("eggpass") + ); + assert!(first.registration); + assert!(first_values.contains_key("resource")); + + let existing = Credentials { + client_id: "issued-client-id".into(), + issuer: crate::provider::OPENAI_ISSUER.into(), + ..Credentials::default() + }; + let next = client + .begin_authorization("http://127.0.0.1:45678/auth/callback", Some(&existing)) + .unwrap(); + let next_url = url::Url::parse(next.authorization_url()).unwrap(); + let next_values: std::collections::HashMap<_, _> = + next_url.query_pairs().into_owned().collect(); + assert_eq!( + next_values.get("client_id").map(String::as_str), + Some("issued-client-id") + ); + assert!(!next.registration); + assert!(!next_values.contains_key("agent_name_hint")); + } + + #[tokio::test] + async fn callback_completion_rejects_wrong_origin_path_state_and_duplicates() { + let client = client(); + for case in ["origin", "path", "state", "duplicate-state", "missing-code"] { + let pending = client + .begin_authorization("http://127.0.0.1:34567/callback", None) + .unwrap(); + let state = pending.state.clone(); + let (callback, expected_callback_error) = match case { + "origin" => ( + format!("http://127.0.0.2:34567/callback?code=c&state={state}"), + true, + ), + "path" => ( + format!("http://127.0.0.1:34567/other?code=c&state={state}"), + true, + ), + "state" => ( + "http://127.0.0.1:34567/callback?code=c&state=wrong".to_string(), + false, + ), + "duplicate-state" => ( + format!("http://127.0.0.1:34567/callback?code=c&state={state}&state={state}"), + true, + ), + _ => ( + format!("http://127.0.0.1:34567/callback?state={state}"), + false, + ), + }; + let error = client + .complete_authorization(pending, &callback) + .await + .unwrap_err(); + if expected_callback_error { + assert!( + matches!(error, Error::CallbackMismatch), + "{case}: {error:?}" + ); + } else if case == "state" { + assert!(matches!(error, Error::StateMismatch)); + } else { + assert!(matches!(error, Error::InvalidResponse(_))); + } + } + } + + #[test] + fn callback_error_codes_never_reflect_arbitrary_provider_values() { + assert_eq!(sanitize_oauth_code("access_denied"), "access_denied"); + assert_eq!(sanitize_oauth_code("refresh-secret-123"), "unknown_error"); + } + + #[test] + fn nonce_claim_must_match_exactly() { + let nonce = "expected-nonce"; + let payload = URL_SAFE_NO_PAD + .encode(serde_json::to_vec(&serde_json::json!({ "nonce": nonce })).unwrap()); + let token = format!("header.{payload}.signature"); + assert!(validate_nonce(Some(&token), nonce).is_ok()); + assert!(matches!( + validate_nonce(Some(&token), "wrong"), + Err(Error::NonceMismatch) + )); + assert!(matches!( + validate_nonce(None, nonce), + Err(Error::NonceMismatch) + )); + } +} diff --git a/crates/eggpass-auth/src/client.rs b/crates/eggpass-auth/src/client.rs new file mode 100644 index 0000000..486c217 --- /dev/null +++ b/crates/eggpass-auth/src/client.rs @@ -0,0 +1,966 @@ +use std::future::Future; +use std::time::Duration; + +use eggfetch_core::timeout::Timeout; +use eggfetch_core::{Client as HttpClient, redirect::RedirectPolicy}; +use serde_json::Value; +use tokio_util::sync::CancellationToken; + +use crate::provider::{ClientIdPolicy, OAuthProviderConfig}; +use crate::token::{Credentials, DeviceCode, DevicePoll, TokenSet, UserInfo}; +use crate::{Error, Result}; + +/// Per-request timeout and response-size policy for OAuth HTTP exchanges. +/// +/// Every OAuth request explicitly overrides the supplied Eggfetch client's +/// timeout, redirect, retry, and default-auth settings. This avoids inheriting +/// accidental unbounded waits, redirects carrying credentials, or automatic +/// retries of one-shot code/refresh exchanges. +#[derive(Clone, Copy, Debug)] +pub struct ClientOptions { + /// Eggfetch phase timeouts, including an absolute request-wide deadline. + pub timeout: Timeout, + /// Maximum decoded response body size in bytes. + pub max_response_body_bytes: usize, +} + +impl Default for ClientOptions { + fn default() -> Self { + Self { + timeout: Timeout { + pool: Some(Duration::from_secs(10)), + connect: Some(Duration::from_secs(15)), + write: Some(Duration::from_secs(15)), + read: Some(Duration::from_secs(30)), + total: Some(Duration::from_secs(60)), + }, + max_response_body_bytes: 1024 * 1024, + } + } +} + +/// Async OAuth protocol client for one provider. +/// +/// The caller supplies and owns the cloneable Eggfetch client. This type never +/// creates a Tokio runtime. Methods are awaited on the caller's runtime. +pub struct OAuthClient { + pub(crate) http: HttpClient, + pub(crate) provider: OAuthProviderConfig, + pub(crate) options: ClientOptions, +} + +impl std::fmt::Debug for OAuthClient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("OAuthClient") + .field("provider", &self.provider) + .field("options", &self.options) + .field("http", &"") + .finish() + } +} + +impl Clone for OAuthClient { + fn clone(&self) -> Self { + Self { + http: self.http.clone(), + provider: self.provider.clone(), + options: self.options, + } + } +} + +impl OAuthClient { + /// Construct a client around a caller-owned Eggfetch client and validated + /// provider profile. No runtime is created or retained by this library. + pub fn new(http: HttpClient, provider: OAuthProviderConfig) -> Self { + Self { + http, + provider, + options: ClientOptions::default(), + } + } + + /// Set the explicit request timeout and response body cap. + pub fn with_options(mut self, options: ClientOptions) -> Result { + if options.max_response_body_bytes == 0 { + return Err(Error::InvalidConfiguration( + "response body limit must be greater than zero", + )); + } + self.options = options; + Ok(self) + } + + /// Provider profile used by this client. + pub fn provider(&self) -> &OAuthProviderConfig { + &self.provider + } + + /// Start an authorization-code transaction. The returned value contains + /// the authorization URL and private PKCE/state/nonce material; pass it to + /// [`Self::complete_authorization`] after the caller receives the callback. + pub fn begin_authorization( + &self, + redirect_uri: &str, + existing: Option<&Credentials>, + ) -> Result { + crate::authorization::begin_authorization(self, redirect_uri, existing) + } + + /// Complete a pending transaction from a full callback URL. This validates + /// callback origin and exact path, state, and (when OpenID Connect is + /// requested) ID-token nonce before returning credentials. + pub async fn complete_authorization( + &self, + pending: PendingAuthorization, + callback_url: &str, + ) -> Result { + crate::authorization::complete_authorization(self, pending, callback_url).await + } + + /// Complete an authorization when the provider displayed a code for the + /// user to copy instead of redirecting to the registered callback. + /// + /// The pending PKCE verifier and nonce are still used and the ID-token + /// nonce is still validated. This is available only for fixed-client-ID + /// profiles; providers that issue a client ID need the callback metadata. + pub async fn complete_authorization_with_code( + &self, + pending: PendingAuthorization, + code: &str, + ) -> Result { + crate::authorization::complete_authorization_with_code(self, pending, code).await + } + + /// Exchange an authorization code using caller-supplied PKCE material. + /// + /// Prefer [`Self::begin_authorization`] and [`Self::complete_authorization`] + /// for browser flows; the lower-level form is for callers that manage the + /// transaction themselves. `client_id` is an issued ID for providers that + /// have [`ClientIdPolicy::IssuedOnRegistration`], or `None` to use the + /// configured entry ID. + pub async fn exchange_authorization_code( + &self, + code: &str, + redirect_uri: &str, + code_verifier: &str, + client_id: Option<&str>, + ) -> Result { + validate_nonempty(code, "authorization code")?; + validate_nonempty(code_verifier, "PKCE verifier")?; + validate_redirect_uri(redirect_uri, &self.provider.callback_path)?; + let client_id = self.client_id(client_id)?; + let mut parameters = vec![ + ("grant_type".to_string(), "authorization_code".to_string()), + ("code".to_string(), code.to_string()), + ("redirect_uri".to_string(), redirect_uri.to_string()), + ("client_id".to_string(), client_id.clone()), + ("code_verifier".to_string(), code_verifier.to_string()), + ]; + parameters.extend(self.provider.token_parameters.clone()); + let value = self + .post_form_json(&self.provider.token_endpoint, ¶meters) + .await?; + let tokens = TokenSet::from_json(&value, Credentials::now_unix())?; + Ok(Credentials::from_tokens( + tokens, + client_id, + self.provider.issuer.clone(), + Credentials::now_unix(), + )) + } + + /// Exchange a refresh token and return only the provider response tokens. + /// + /// This operation is not automatically retried. A successful response may + /// rotate the refresh token; callers using explicit tokens must persist the + /// returned token when present and retain their previous refresh token when + /// the provider omits rotation. + pub async fn refresh_token( + &self, + refresh_token: &str, + client_id: Option<&str>, + ) -> Result { + validate_nonempty(refresh_token, "refresh token")?; + let client_id = self.client_id(client_id)?; + let mut parameters = vec![ + ("grant_type".to_string(), "refresh_token".to_string()), + ("refresh_token".to_string(), refresh_token.to_string()), + ("client_id".to_string(), client_id), + ]; + parameters.extend(self.provider.token_parameters.clone()); + let value = self + .post_form_json(&self.provider.token_endpoint, ¶meters) + .await?; + TokenSet::from_json(&value, Credentials::now_unix()) + } + + /// Refresh a stored credential set and merge it safely. The existing + /// refresh token is retained if the provider omits a rotated token. + pub async fn refresh_credentials(&self, current: &Credentials) -> Result { + self.validate_credentials(current)?; + let refresh_token = current.refresh_token().ok_or(Error::NoRefreshToken)?; + let tokens = self + .refresh_token(refresh_token, Some(current.client_id())) + .await?; + Ok(current.merged_refresh(tokens, Credentials::now_unix())) + } + + /// Revoke a token when the provider publishes a revocation endpoint. + pub async fn revoke(&self, token: &str, client_id: Option<&str>) -> Result<()> { + validate_nonempty(token, "token")?; + let endpoint = self + .provider + .revocation_endpoint + .as_deref() + .ok_or(Error::Unsupported("token revocation"))?; + let client_id = self.client_id(client_id)?; + let parameters = vec![ + ("token".to_string(), token.to_string()), + ("token_type_hint".to_string(), "refresh_token".to_string()), + ("client_id".to_string(), client_id), + ]; + let response = self.post_form_raw(endpoint, ¶meters).await?; + if (200..300).contains(&response.status) { + Ok(()) + } else { + Err(oauth_error(response.status, &response.body)) + } + } + + /// Fetch non-secret user details using an explicit access token. + pub async fn userinfo(&self, access_token: &str) -> Result { + validate_nonempty(access_token, "access token")?; + let endpoint = self + .provider + .userinfo_endpoint + .as_deref() + .ok_or(Error::Unsupported("user-info lookup"))?; + let builder = self + .http + .get(endpoint) + .map_err(map_eggfetch_error)? + .without_auth() + .header("Authorization", &format!("Bearer {access_token}")) + .timeout(self.options.timeout) + .max_decoded_body_size(self.options.max_response_body_bytes) + .without_retry() + .redirect_policy(RedirectPolicy::new(false, 0)); + let mut response = builder.send().await.map_err(map_eggfetch_error)?; + let status = response.status().as_u16(); + let body = read_limited_body(&mut response, self.options.max_response_body_bytes).await?; + if !(200..300).contains(&status) { + return Err(oauth_error(status, &body)); + } + let value: Value = serde_json::from_slice(&body) + .map_err(|_| Error::InvalidResponse("user-info response is not valid JSON"))?; + Ok(UserInfo { + user_id: first_string( + &value, + &["sub", "user_id", "userId", "preferred_username", "username"], + ), + email: first_string(&value, &["email", "email_address", "emailAddress"]), + }) + } + + /// Request a device authorization. The verification URI and any completed + /// verification URI are checked against the provider's exact HTTPS host + /// allowlist before being returned to the caller. + pub async fn request_device_code(&self) -> Result { + let endpoint = self + .provider + .device_authorization_endpoint + .as_deref() + .ok_or(Error::Unsupported("device authorization"))?; + let scope = self.provider.scopes.join(" "); + let mut parameters = vec![ + ("client_id".to_string(), self.provider.client_id.clone()), + ("scope".to_string(), scope), + ]; + parameters.extend(self.provider.device_parameters.clone()); + let value = self.post_form_json(endpoint, ¶meters).await?; + + let device_code = value + .get("device_code") + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .ok_or(Error::InvalidResponse("device response has no device_code"))? + .to_string(); + let user_code = value + .get("user_code") + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .ok_or(Error::InvalidResponse("device response has no user_code"))? + .to_string(); + let verification_uri = value + .get("verification_uri") + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .ok_or(Error::InvalidResponse( + "device response has no verification_uri", + ))? + .to_string(); + let verification_uri_complete = value + .get("verification_uri_complete") + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .map(str::to_owned); + let expires_in = value + .get("expires_in") + .and_then(Value::as_u64) + .filter(|seconds| *seconds > 0) + .ok_or(Error::InvalidResponse( + "device response expires_in must be positive", + ))?; + let interval = value + .get("interval") + .and_then(Value::as_u64) + .unwrap_or(5) + .max(1); + + require_trusted_verification_url(&verification_uri, &self.provider.trusted_device_hosts)?; + if let Some(complete) = &verification_uri_complete { + require_trusted_verification_url(complete, &self.provider.trusted_device_hosts)?; + } + + let expires_in = Duration::from_secs(expires_in); + let expires_at = + tokio::time::Instant::now() + .checked_add(expires_in) + .ok_or(Error::InvalidResponse( + "device response expiry is out of range", + ))?; + + Ok(DeviceCode { + device_code, + user_code, + verification_uri, + verification_uri_complete, + expires_in, + expires_at, + interval: Duration::from_secs(interval), + }) + } + + /// Perform one device poll. For a cancellable polling loop, use + /// [`Self::poll_device_authorization`]. + pub async fn poll_device_code(&self, device_code: &str) -> Result { + validate_nonempty(device_code, "device code")?; + let client_id = self.client_id(None)?; + let parameters = vec![ + ( + "grant_type".to_string(), + "urn:ietf:params:oauth:grant-type:device_code".to_string(), + ), + ("device_code".to_string(), device_code.to_string()), + ("client_id".to_string(), client_id), + ]; + let response = self + .post_form_raw(&self.provider.token_endpoint, ¶meters) + .await?; + if (200..300).contains(&response.status) { + let value: Value = serde_json::from_slice(&response.body) + .map_err(|_| Error::InvalidResponse("device token response is not valid JSON"))?; + return Ok(DevicePoll::Complete(TokenSet::from_json( + &value, + Credentials::now_unix(), + )?)); + } + let code = oauth_error_code(&response.body); + match code.as_deref() { + Some("authorization_pending") => Ok(DevicePoll::Pending), + Some("slow_down") => Ok(DevicePoll::SlowDown), + Some("access_denied" | "authorization_denied") => Ok(DevicePoll::Denied), + Some("expired_token") => Ok(DevicePoll::Expired), + _ => Err(oauth_error(response.status, &response.body)), + } + } + + /// Poll a device authorization until success, denial, server expiry, + /// caller deadline, or cancellation. The loop sleeps before its first poll; + /// each `slow_down` adds five seconds to all subsequent intervals. + pub async fn poll_device_authorization( + &self, + device: &DeviceCode, + cancellation: &CancellationToken, + caller_timeout: Duration, + ) -> Result { + let client_id = self.client_id(None)?; + poll_device_until( + device, + cancellation, + caller_timeout, + client_id, + self.provider.issuer.clone(), + |device_code| async move { self.poll_device_code(&device_code).await }, + ) + .await + } + + pub(crate) fn validate_credentials(&self, credentials: &Credentials) -> Result<()> { + credentials.validate()?; + if !credentials.issuer().is_empty() && credentials.issuer() != self.provider.issuer { + return Err(Error::InvalidConfiguration( + "stored credentials belong to a different issuer", + )); + } + Ok(()) + } + + pub(crate) fn client_id(&self, override_id: Option<&str>) -> Result { + match (self.provider.client_id_policy, override_id) { + (ClientIdPolicy::IssuedOnRegistration, Some(value)) if !value.trim().is_empty() => { + Ok(value.to_string()) + } + (ClientIdPolicy::IssuedOnRegistration, _) => Ok(self.provider.client_id.clone()), + (ClientIdPolicy::Fixed, Some(value)) if !value.trim().is_empty() => { + Ok(value.to_string()) + } + (ClientIdPolicy::Fixed, _) => Ok(self.provider.client_id.clone()), + } + } + + pub(crate) async fn post_form_json( + &self, + endpoint: &str, + parameters: &[(String, String)], + ) -> Result { + let response = self.post_form_raw(endpoint, parameters).await?; + if !(200..300).contains(&response.status) { + return Err(oauth_error(response.status, &response.body)); + } + serde_json::from_slice(&response.body) + .map_err(|_| Error::InvalidResponse("OAuth response is not valid JSON")) + } + + pub(crate) async fn post_form_raw( + &self, + endpoint: &str, + parameters: &[(String, String)], + ) -> Result { + let body = { + let mut encoded = url::form_urlencoded::Serializer::new(String::new()); + encoded.extend_pairs( + parameters + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())), + ); + encoded.finish() + }; + let builder = self + .http + .post(endpoint) + .map_err(map_eggfetch_error)? + .without_auth() + .header("Content-Type", "application/x-www-form-urlencoded") + .body(body) + .timeout(self.options.timeout) + .max_decoded_body_size(self.options.max_response_body_bytes) + .without_retry() + .redirect_policy(RedirectPolicy::new(false, 0)); + let mut response = builder.send().await.map_err(map_eggfetch_error)?; + let status = response.status().as_u16(); + let body = read_limited_body(&mut response, self.options.max_response_body_bytes).await?; + Ok(RawResponse { status, body }) + } +} + +async fn poll_device_until( + device: &DeviceCode, + cancellation: &CancellationToken, + caller_timeout: Duration, + client_id: String, + issuer: String, + mut poll: F, +) -> Result +where + F: FnMut(String) -> Fut, + Fut: Future>, +{ + if device.expires_in.is_zero() { + return Err(Error::DeviceExpired); + } + let start = tokio::time::Instant::now(); + let caller_deadline = start + .checked_add(caller_timeout) + .ok_or(Error::InvalidResponse( + "device authorization deadline is out of range", + ))?; + let server_is_deadline = device.expires_at <= caller_deadline; + let deadline = device.expires_at.min(caller_deadline); + let mut interval = device.interval; + + loop { + let now = tokio::time::Instant::now(); + if now >= deadline { + return if server_is_deadline { + Err(Error::DeviceExpired) + } else { + Err(Error::Timeout("device authorization")) + }; + } + let remaining = deadline.saturating_duration_since(now); + let wake = now + interval.min(remaining); + tokio::select! { + _ = cancellation.cancelled() => return Err(Error::Cancelled), + _ = tokio::time::sleep_until(wake) => {} + } + if tokio::time::Instant::now() >= deadline { + return if server_is_deadline { + Err(Error::DeviceExpired) + } else { + Err(Error::Timeout("device authorization")) + }; + } + let poll_future = poll(device.device_code.clone()); + let result = tokio::select! { + _ = cancellation.cancelled() => return Err(Error::Cancelled), + result = tokio::time::timeout_at(deadline, poll_future) => match result { + Ok(result) => result?, + Err(_) => return if server_is_deadline { + Err(Error::DeviceExpired) + } else { + Err(Error::Timeout("device authorization")) + }, + } + }; + match result { + DevicePoll::Pending => {} + DevicePoll::SlowDown => interval = interval.saturating_add(Duration::from_secs(5)), + DevicePoll::Denied => return Err(Error::ProviderDenied("access_denied".to_string())), + DevicePoll::Expired => return Err(Error::DeviceExpired), + DevicePoll::Complete(tokens) => { + return Ok(Credentials::from_tokens( + tokens, + client_id, + issuer, + Credentials::now_unix(), + )); + } + } + } +} + +/// Opaque, one-use authorization transaction. Sensitive fields are private and +/// redacted from `Debug`; it is consumed by callback completion. +pub struct PendingAuthorization { + pub(crate) authorization_url: String, + pub(crate) redirect_uri: String, + pub(crate) code_verifier: String, + pub(crate) state: String, + pub(crate) nonce: String, + pub(crate) client_id: String, + pub(crate) registration: bool, +} + +impl PendingAuthorization { + /// URL to present to the user in an external browser or another UI. + pub fn authorization_url(&self) -> &str { + &self.authorization_url + } +} + +impl std::fmt::Debug for PendingAuthorization { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PendingAuthorization") + .field("authorization_url", &"") + .field("redirect_uri", &self.redirect_uri) + .field("code_verifier", &"") + .field("state", &"") + .field("nonce", &"") + .field("client_id", &"") + .field("registration", &self.registration) + .finish() + } +} + +pub(crate) struct RawResponse { + pub status: u16, + pub body: Vec, +} + +async fn read_limited_body( + response: &mut eggfetch_core::Response, + maximum: usize, +) -> Result> { + if response + .content_length() + .is_some_and(|size| size > maximum as u64) + { + return Err(Error::ResponseTooLarge); + } + let bytes = response.bytes().await.map_err(map_eggfetch_error)?; + if bytes.len() > maximum { + return Err(Error::ResponseTooLarge); + } + Ok(bytes.to_vec()) +} + +pub(crate) fn oauth_error(status: u16, body: &[u8]) -> Error { + if let Some(code) = oauth_error_code(body) { + Error::OAuth { status, code } + } else { + Error::HttpStatus { status } + } +} + +fn oauth_error_code(body: &[u8]) -> Option { + let value: Value = serde_json::from_slice(body).ok()?; + let code = value.get("error")?.as_str()?; + crate::error::safe_oauth_error_code(code).map(str::to_string) +} + +fn map_eggfetch_error(error: eggfetch_core::error::Error) -> Error { + use eggfetch_core::error::Error as FetchError; + match error { + FetchError::DecodedBodyTooLarge => Error::ResponseTooLarge, + FetchError::Timeout { .. } | FetchError::TransportIoTimeout { .. } => { + Error::Timeout("HTTP request") + } + _ => Error::Transport, + } +} + +fn validate_nonempty(value: &str, label: &'static str) -> Result<()> { + if value.is_empty() || value.chars().any(char::is_control) { + return Err(Error::InvalidConfiguration(match label { + "authorization code" => { + "authorization code must not be empty or contain control characters" + } + "PKCE verifier" => "PKCE verifier must not be empty or contain control characters", + "refresh token" => "refresh token must not be empty or contain control characters", + "access token" => "access token must not be empty or contain control characters", + "device code" => "device code must not be empty or contain control characters", + _ => "token value must not be empty or contain control characters", + })); + } + Ok(()) +} + +pub(crate) fn validate_redirect_uri(redirect_uri: &str, expected_path: &str) -> Result { + let redirect = url::Url::parse(redirect_uri) + .map_err(|_| Error::InvalidConfiguration("redirect URI is invalid"))?; + let loopback_http = match redirect.host() { + Some(url::Host::Ipv4(address)) => address.is_loopback(), + Some(url::Host::Ipv6(address)) => address.is_loopback(), + Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"), + None => false, + }; + if !matches!(redirect.scheme(), "https" | "http") + || (redirect.scheme() == "http" && !loopback_http) + || !redirect.username().is_empty() + || redirect.password().is_some() + || redirect.query().is_some() + || redirect.fragment().is_some() + || redirect.path() != expected_path + { + return Err(Error::InvalidConfiguration( + "redirect URI must use HTTPS or loopback HTTP and the exact configured callback path", + )); + } + Ok(redirect) +} + +fn first_string(value: &Value, names: &[&str]) -> Option { + names + .iter() + .find_map(|name| value.get(*name).and_then(Value::as_str).map(str::to_owned)) +} + +pub(crate) fn require_trusted_verification_url(url: &str, trusted_hosts: &[String]) -> Result<()> { + if trusted_hosts.is_empty() + || url + .bytes() + .any(|byte| byte == b'\\' || byte.is_ascii_whitespace() || byte < 0x20) + { + return Err(Error::UntrustedVerificationUrl { host: None }); + } + let parsed = match url::Url::parse(url) { + Ok(parsed) => parsed, + Err(_) => return Err(Error::UntrustedVerificationUrl { host: None }), + }; + let host = parsed + .host_str() + .map(|host| host.strip_suffix('.').unwrap_or(host).to_ascii_lowercase()); + let trusted = parsed.scheme() == "https" + && parsed.username().is_empty() + && parsed.password().is_none() + && host.as_ref().is_some_and(|host| { + trusted_hosts + .iter() + .any(|candidate| candidate.eq_ignore_ascii_case(host)) + }); + if trusted { + Ok(()) + } else { + let host = host.filter(|host| host.len() <= 253 && host.is_ascii()); + Err(Error::UntrustedVerificationUrl { host }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_timeouts_are_finite_and_response_limit_is_bounded() { + let options = ClientOptions::default(); + assert!(options.timeout.connect.is_some()); + assert!(options.timeout.read.is_some()); + assert!(options.timeout.total.is_some()); + assert!(options.max_response_body_bytes > 0); + } + + #[test] + fn redirect_uri_path_is_exact_and_http_requires_loopback() { + assert!(validate_redirect_uri("http://127.0.0.1:1234/callback", "/callback").is_ok()); + assert!(validate_redirect_uri("https://example.test/callback", "/callback").is_ok()); + assert!(validate_redirect_uri("http://example.test/callback", "/callback").is_err()); + assert!(validate_redirect_uri("http://127.0.0.1:1234/other", "/callback").is_err()); + } + + #[test] + fn oauth_errors_keep_codes_but_never_descriptions_or_body() { + let error = oauth_error( + 400, + br#"{"error":"invalid_scope","error_description":"secret detail"}"#, + ); + assert_eq!(error.oauth_code(), Some("invalid_scope")); + let display = error.to_string(); + assert!(!display.contains("secret detail")); + assert!(!format!("{error:?}").contains("secret detail")); + + let echoed_secret = oauth_error(400, br#"{"error":"refresh-secret-123"}"#); + assert!(matches!(echoed_secret, Error::HttpStatus { status: 400 })); + assert!(!echoed_secret.to_string().contains("refresh-secret-123")); + assert!(!format!("{echoed_secret:?}").contains("refresh-secret-123")); + } + + #[tokio::test] + async fn refresh_credentials_rejects_a_different_issuer_before_network_access() { + let client = OAuthClient::new( + eggfetch_core::Client::new(), + crate::provider::OAuthProviderConfig::xai(), + ); + let credentials = Credentials { + access_token: "access-secret".into(), + refresh_token: Some("refresh-secret".into()), + client_id: crate::provider::XAI_CLIENT_ID.into(), + issuer: crate::provider::OPENAI_ISSUER.into(), + ..Credentials::default() + }; + + assert!(matches!( + client.refresh_credentials(&credentials).await, + Err(Error::InvalidConfiguration(_)) + )); + } + + #[test] + fn trusted_verification_url_requires_exact_https_host_and_rejects_parser_delimiters() { + let hosts = vec!["accounts.x.ai".to_string(), "auth.x.ai".to_string()]; + assert!( + require_trusted_verification_url("https://accounts.x.ai/verify?user_code=ABCD", &hosts) + .is_ok() + ); + assert!( + require_trusted_verification_url("https://accounts.x.ai.evil.test/", &hosts).is_err() + ); + assert!( + require_trusted_verification_url("https://accounts.x.ai\\@evil.test/", &hosts).is_err() + ); + assert!(require_trusted_verification_url("http://accounts.x.ai/", &hosts).is_err()); + } + + fn test_device(expires: u64, interval: u64) -> DeviceCode { + let expires_in = Duration::from_secs(expires); + DeviceCode { + device_code: "device-secret".into(), + user_code: "user-secret".into(), + verification_uri: "https://accounts.x.ai/device".into(), + verification_uri_complete: None, + expires_in, + expires_at: tokio::time::Instant::now() + expires_in, + interval: Duration::from_secs(interval), + } + } + + #[test] + fn device_code_debug_redacts_device_codes_and_verification_urls() { + let mut device = test_device(30, 5); + device.verification_uri = "https://accounts.x.ai/device?verification-secret=hidden".into(); + device.verification_uri_complete = + Some("https://accounts.x.ai/device?user_code=hidden-code".into()); + + let debug = format!("{device:?}"); + for secret in [ + "device-secret", + "user-secret", + "verification-secret", + "hidden-code", + ] { + assert!(!debug.contains(secret)); + } + } + + fn test_tokens() -> TokenSet { + TokenSet { + access_token: "access".into(), + refresh_token: Some("refresh".into()), + id_token: None, + token_type: "Bearer".into(), + scope: None, + expires_at: Some(10_000), + } + } + + #[tokio::test(start_paused = true)] + async fn device_slow_down_increases_all_later_intervals_by_five_seconds() { + use std::sync::{Arc, Mutex}; + + let observations = Arc::new(Mutex::new(Vec::new())); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let observed = observations.clone(); + let counter = calls.clone(); + let result = poll_device_until( + &test_device(30, 1), + &CancellationToken::new(), + Duration::from_secs(30), + "client".into(), + "https://auth.x.ai".into(), + move |_| { + let observed = observed.clone(); + let index = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + async move { + observed.lock().unwrap().push(tokio::time::Instant::now()); + Ok(match index { + 0 => DevicePoll::SlowDown, + 1 => DevicePoll::Pending, + _ => DevicePoll::Complete(test_tokens()), + }) + } + }, + ) + .await + .unwrap(); + assert_eq!(result.access_token(), "access"); + let observations = observations.lock().unwrap(); + assert_eq!(observations.len(), 3); + assert_eq!( + observations[1].duration_since(observations[0]), + Duration::from_secs(6) + ); + assert_eq!( + observations[2].duration_since(observations[1]), + Duration::from_secs(6) + ); + } + + #[tokio::test(start_paused = true)] + async fn device_expiry_is_measured_from_code_issuance_not_polling_start() { + let device = test_device(2, 1); + tokio::time::advance(Duration::from_secs(3)).await; + let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = calls.clone(); + let error = poll_device_until( + &device, + &CancellationToken::new(), + Duration::from_secs(10), + "client".into(), + "https://auth.x.ai".into(), + move |_| { + let count = count.clone(); + async move { + count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(DevicePoll::Pending) + } + }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::DeviceExpired)); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0); + } + + #[tokio::test(start_paused = true)] + async fn device_flow_honors_short_expiry_and_caller_deadline() { + let cancellation = CancellationToken::new(); + let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = calls.clone(); + let error = poll_device_until( + &test_device(2, 5), + &cancellation, + Duration::from_secs(20), + "client".into(), + "https://auth.x.ai".into(), + move |_| { + let count = count.clone(); + async move { + count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(DevicePoll::Pending) + } + }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::DeviceExpired)); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0); + + let error = poll_device_until( + &test_device(30, 5), + &cancellation, + Duration::from_secs(2), + "client".into(), + "https://auth.x.ai".into(), + |_| async { Ok(DevicePoll::Pending) }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout("device authorization"))); + } + + #[tokio::test(start_paused = true)] + async fn device_flow_supports_cancellation_denial_and_server_expiry() { + let cancellation = CancellationToken::new(); + let cancel_signal = cancellation.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(100)).await; + cancel_signal.cancel(); + }); + let error = poll_device_until( + &test_device(30, 10), + &cancellation, + Duration::from_secs(20), + "client".into(), + "https://auth.x.ai".into(), + |_| async { Ok(DevicePoll::Pending) }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::Cancelled)); + + let error = poll_device_until( + &test_device(30, 1), + &CancellationToken::new(), + Duration::from_secs(20), + "client".into(), + "https://auth.x.ai".into(), + |_| async { Ok(DevicePoll::Denied) }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::ProviderDenied(_))); + + let error = poll_device_until( + &test_device(30, 1), + &CancellationToken::new(), + Duration::from_secs(20), + "client".into(), + "https://auth.x.ai".into(), + |_| async { Ok(DevicePoll::Expired) }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::DeviceExpired)); + } +} diff --git a/crates/eggpass-auth/src/error.rs b/crates/eggpass-auth/src/error.rs new file mode 100644 index 0000000..629d134 --- /dev/null +++ b/crates/eggpass-auth/src/error.rs @@ -0,0 +1,210 @@ +use std::fmt; + +/// Result type returned by the library. +pub type Result = std::result::Result; + +/// Return only recognized protocol error codes; never reflect arbitrary provider text. +pub(crate) fn safe_oauth_error_code(value: &str) -> Option<&'static str> { + const SAFE_CODES: &[&str] = &[ + "invalid_request", + "unauthorized_client", + "access_denied", + "unsupported_response_type", + "invalid_scope", + "server_error", + "temporarily_unavailable", + "invalid_client", + "invalid_grant", + "unsupported_grant_type", + "invalid_token", + "insufficient_scope", + "authorization_pending", + "slow_down", + "expired_token", + "authorization_denied", + "login_required", + "interaction_required", + "account_selection_required", + "consent_required", + "invalid_request_uri", + "invalid_request_object", + "request_not_supported", + "request_uri_not_supported", + "registration_not_supported", + ]; + SAFE_CODES.iter().copied().find(|code| *code == value) +} + +/// Errors returned by the OAuth client and credential manager. +/// +/// Response bodies, authorization codes, URLs, access tokens, refresh tokens, +/// device codes, and request URLs are deliberately not included in errors. +#[non_exhaustive] +pub enum Error { + /// Configuration or a response contained an invalid or missing value. + InvalidResponse(&'static str), + /// Provider or request configuration failed validation. + InvalidConfiguration(&'static str), + /// The HTTP server returned an unexpected status. + HttpStatus { status: u16 }, + /// The server returned a standard OAuth error code. + OAuth { status: u16, code: String }, + /// The provider denied an authorization callback. + ProviderDenied(String), + /// Callback origin or exact path did not match the pending transaction. + CallbackMismatch, + /// Callback state did not match the issued state. + StateMismatch, + /// The ID-token nonce did not match the pending authorization. + NonceMismatch, + /// The response body exceeded the configured limit. + ResponseTooLarge, + /// The HTTP exchange failed. Eggfetch error details are not exposed because + /// they can contain request URLs or caller configuration. + Transport, + /// A configured request or authorization deadline elapsed. + Timeout(&'static str), + /// The provider has no endpoint for the requested operation. + Unsupported(&'static str), + /// The device authorization expired before approval. + DeviceExpired, + /// Device polling was cancelled by the caller. + Cancelled, + /// The verification URL did not match the exact configured host allowlist. + UntrustedVerificationUrl { host: Option }, + /// No credentials were returned by the caller-owned store. + NotLoggedIn, + /// Stored credentials have no refresh token. + NoRefreshToken, + /// Caller-owned credential storage failed. + Storage(StorageError), +} + +impl Error { + /// HTTP status associated with an HTTP or OAuth error, when available. + pub fn status(&self) -> Option { + match self { + Self::HttpStatus { status } | Self::OAuth { status, .. } => Some(*status), + _ => None, + } + } + + /// OAuth error code associated with a provider response, when available. + pub fn oauth_code(&self) -> Option<&str> { + match self { + Self::OAuth { code, .. } | Self::ProviderDenied(code) => Some(code), + _ => None, + } + } +} + +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidResponse(reason) => { + f.debug_tuple("InvalidResponse").field(reason).finish() + } + Self::InvalidConfiguration(reason) => { + f.debug_tuple("InvalidConfiguration").field(reason).finish() + } + Self::HttpStatus { status } => f + .debug_struct("HttpStatus") + .field("status", status) + .finish(), + Self::OAuth { status, code } => f + .debug_struct("OAuth") + .field("status", status) + .field("code", code) + .finish(), + Self::ProviderDenied(code) => f.debug_tuple("ProviderDenied").field(code).finish(), + Self::CallbackMismatch => f.write_str("CallbackMismatch"), + Self::StateMismatch => f.write_str("StateMismatch"), + Self::NonceMismatch => f.write_str("NonceMismatch"), + Self::ResponseTooLarge => f.write_str("ResponseTooLarge"), + Self::Transport => f.write_str("Transport"), + Self::Timeout(operation) => f.debug_tuple("Timeout").field(operation).finish(), + Self::Unsupported(operation) => f.debug_tuple("Unsupported").field(operation).finish(), + Self::DeviceExpired => f.write_str("DeviceExpired"), + Self::Cancelled => f.write_str("Cancelled"), + Self::UntrustedVerificationUrl { host } => f + .debug_struct("UntrustedVerificationUrl") + .field("host", host) + .finish(), + Self::NotLoggedIn => f.write_str("NotLoggedIn"), + Self::NoRefreshToken => f.write_str("NoRefreshToken"), + Self::Storage(_) => f.write_str("Storage()"), + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidResponse(reason) => write!(f, "invalid OAuth response: {reason}"), + Self::InvalidConfiguration(reason) => { + write!(f, "invalid OAuth configuration: {reason}") + } + Self::HttpStatus { status } => write!(f, "HTTP {status} from OAuth endpoint"), + Self::OAuth { status, code } => { + write!(f, "OAuth endpoint returned HTTP {status} ({code})") + } + Self::ProviderDenied(code) => write!(f, "provider denied authorization ({code})"), + Self::CallbackMismatch => { + f.write_str("callback did not match the pending authorization") + } + Self::StateMismatch => { + f.write_str("callback state did not match the pending authorization") + } + Self::NonceMismatch => { + f.write_str("ID-token nonce did not match the pending authorization") + } + Self::ResponseTooLarge => { + f.write_str("OAuth response exceeded the configured body limit") + } + Self::Transport => f.write_str("OAuth HTTP request failed"), + Self::Timeout(operation) => write!(f, "OAuth {operation} timed out"), + Self::Unsupported(operation) => write!(f, "provider does not support {operation}"), + Self::DeviceExpired => f.write_str("device authorization expired"), + Self::Cancelled => f.write_str("device authorization was cancelled"), + Self::UntrustedVerificationUrl { host: Some(host) } => { + write!(f, "untrusted device verification host: {host}") + } + Self::UntrustedVerificationUrl { host: None } => { + f.write_str("device verification URL could not be parsed safely") + } + Self::NotLoggedIn => f.write_str("no credentials are stored"), + Self::NoRefreshToken => f.write_str("stored credentials contain no refresh token"), + Self::Storage(_) => f.write_str("credential storage failed"), + } + } +} + +impl std::error::Error for Error {} + +/// A safe, caller-provided description of a credential-storage failure. +/// +/// Do not put credentials or other secrets in this message. `Debug` always +/// redacts it; `Display` returns it so an application may decide whether to +/// present its own storage diagnostics. +pub struct StorageError(String); + +impl StorageError { + /// Construct a storage error using a message that contains no secrets. + pub fn new(message: impl Into) -> Self { + Self(message.into()) + } +} + +impl fmt::Debug for StorageError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("StorageError()") + } +} + +impl fmt::Display for StorageError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for StorageError {} diff --git a/crates/eggpass-auth/src/lib.rs b/crates/eggpass-auth/src/lib.rs new file mode 100644 index 0000000..d61d663 --- /dev/null +++ b/crates/eggpass-auth/src/lib.rs @@ -0,0 +1,77 @@ +//! Async OAuth authentication building blocks for Eggfetch applications. +//! +//! This crate accepts a caller-owned [`EggfetchClient`], never creates a Tokio +//! runtime, and does not launch a browser, print to a terminal, open a listener, +//! or read/write credential files. Applications own their runtime, user +//! interaction, callback receiver, and credential storage. Owned API values +//! such as [`OAuthClient`], [`PendingAuthorization`], [`Credentials`], +//! [`TokenSet`], and [`DeviceCode`] are `Send + Sync`. [`CredentialStore`] +//! implementations are also `Send + Sync` and return `Send` futures. +//! +//! # Authorization-code flow +//! +//! ```no_run +//! use eggfetch_core::Client; +//! use eggpass_auth::{OAuthClient, OAuthProviderConfig}; +//! +//! # async fn login() -> Result<(), Box> { +//! let oauth = OAuthClient::new(Client::new(), OAuthProviderConfig::xai()); +//! // The redirect URI must use the provider profile's exact callback path. +//! let pending = oauth.begin_authorization("http://127.0.0.1:43123/callback", None)?; +//! let browser_url = pending.authorization_url(); +//! // Present browser_url using the caller's UI, then receive the redirect URL +//! // in a caller-owned loopback listener or another registered callback. +//! let _ = browser_url; +//! # Ok(()) +//! # } +//! ``` +//! +//! The [`PendingAuthorization`] value keeps the PKCE verifier, state, and nonce +//! private and redacts them in `Debug`. Call [`OAuthClient::complete_authorization`] +//! with the full callback URL to validate origin, exact path, state, and the +//! returned ID-token nonce before credentials are released. +//! +//! # Device authorization +//! +//! [`OAuthClient::request_device_code`] returns a host-checked verification URI +//! and user code as data. The caller decides how to present them. Polling accepts +//! a [`CancellationToken`] and a caller timeout; the server expiry is honored, +//! and each `slow_down` response adds five seconds to subsequent intervals. +//! +//! # Credential storage and refresh +//! +//! [`Credentials`] is serializable for caller-owned storage and redacts secrets +//! from `Debug`. [`CredentialStore`] and [`TokenManager`] provide an optional +//! async refresh manager. Its single-flight guarantee applies to one manager in +//! one process only. Store implementations should atomically replace credential +//! sets and add cross-process coordination when needed. +//! +//! # Security and transport behavior +//! +//! OAuth requests use explicit finite timeouts and a bounded decoded response +//! size. Redirects and automatic retries are disabled for each request, and +//! caller-configured Eggfetch default authentication is suppressed before the +//! library sets any explicit bearer header. Errors expose status and sanitized +//! OAuth codes but not response bodies, URLs, authorization codes, or tokens. +//! Custom OAuth endpoints must use HTTPS, except for loopback HTTP endpoints +//! used by local tests. + +mod authorization; +mod client; +mod error; +mod manager; +mod pkce; +mod provider; +mod token; + +pub use client::{ClientOptions, OAuthClient, PendingAuthorization}; +pub use eggfetch_core::Client as EggfetchClient; +pub use error::{Error, Result, StorageError}; +pub use manager::{CredentialStore, TokenManager}; +pub use pkce::{challenge_for, random_verifier}; +pub use provider::{ + ClientIdPolicy, OAuthProviderConfig, OAuthProviderConfigBuilder, OPENAI_ENTRY_CLIENT_ID, + OPENAI_ISSUER, OPENAI_RESOURCE, XAI_CLIENT_ID, XAI_ISSUER, +}; +pub use token::{Credentials, DeviceCode, DevicePoll, TokenSet, UserInfo}; +pub use tokio_util::sync::CancellationToken; diff --git a/crates/eggpass-auth/src/manager.rs b/crates/eggpass-auth/src/manager.rs new file mode 100644 index 0000000..e26f163 --- /dev/null +++ b/crates/eggpass-auth/src/manager.rs @@ -0,0 +1,273 @@ +use std::future::Future; + +use tokio::sync::Mutex; + +use crate::client::OAuthClient; +use crate::error::StorageError; +use crate::token::Credentials; +use crate::{Error, Result}; + +/// Caller-owned asynchronous credential storage. +/// +/// Implementations should make `save` an atomic replacement of one credential +/// set. This contract does not itself coordinate separate processes; an +/// application needing cross-process refresh coordination must implement it in +/// its storage layer. The trait is generic/RPITIT-based and is not a `dyn` +/// trait; this keeps store errors and futures allocation-free. +pub trait CredentialStore: Send + Sync { + /// Load the current credentials, or `None` when the user is not logged in. + fn load( + &self, + ) -> impl Future, StorageError>> + Send; + + /// Atomically replace the stored credentials. + fn save( + &self, + credentials: Credentials, + ) -> impl Future> + Send; + + /// Remove credentials. Removing an absent entry should succeed. + fn clear(&self) -> impl Future> + Send; +} + +/// Async token manager over caller-owned credential storage. +/// +/// One manager coalesces proactive and compare-and-refresh requests within this +/// process. It is not a cross-process lock; storage implementations must add +/// coordination if multiple processes can refresh the same account. +pub struct TokenManager { + client: OAuthClient, + store: S, + refresh_lock: Mutex<()>, + refresh_skew_seconds: i64, +} + +impl std::fmt::Debug for TokenManager { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TokenManager") + .field("client", &self.client) + .field("refresh_skew_seconds", &self.refresh_skew_seconds) + .field("store", &"") + .finish() + } +} + +impl TokenManager { + /// Create a manager using the standard five-minute proactive refresh skew. + pub fn new(client: OAuthClient, store: S) -> Self { + Self { + client, + store, + refresh_lock: Mutex::new(()), + refresh_skew_seconds: 5 * 60, + } + } + + /// Configure how long before expiry a token should be refreshed. + pub fn with_refresh_skew(mut self, seconds: i64) -> Self { + self.refresh_skew_seconds = seconds.max(0); + self + } + + /// Read credentials without refreshing. + pub async fn current(&self) -> Result> { + let credentials = self.store.load().await.map_err(Error::Storage)?; + if let Some(credentials) = &credentials { + self.client.validate_credentials(credentials)?; + } + Ok(credentials) + } + + /// Store credentials obtained from an authorization or device flow. + pub async fn save(&self, credentials: Credentials) -> Result<()> { + credentials.validate()?; + self.store.save(credentials).await.map_err(Error::Storage) + } + + /// Remove credentials from the caller-owned store. + pub async fn clear(&self) -> Result<()> { + self.store.clear().await.map_err(Error::Storage) + } + + /// Get a usable access token, refreshing proactively when it is near expiry. + pub async fn access_token(&self) -> Result { + let current = self.current().await?.ok_or(Error::NotLoggedIn)?; + if current.is_fresh(Credentials::now_unix(), self.refresh_skew_seconds) { + return Ok(current.access_token().to_string()); + } + + let _guard = self.refresh_lock.lock().await; + let current = self.current().await?.ok_or(Error::NotLoggedIn)?; + if current.is_fresh(Credentials::now_unix(), self.refresh_skew_seconds) { + return Ok(current.access_token().to_string()); + } + self.refresh_current(¤t).await + } + + /// Refresh after an upstream request was rejected with HTTP 401. + /// + /// The refresh is performed only if `failed_access_token` is still current; + /// if another task already replaced it, that newer token is returned. + pub async fn force_refresh(&self, failed_access_token: &str) -> Result { + let _guard = self.refresh_lock.lock().await; + let current = self.current().await?.ok_or(Error::NotLoggedIn)?; + if current.access_token() != failed_access_token { + return Ok(current.access_token().to_string()); + } + self.refresh_current(¤t).await + } + + async fn refresh_current(&self, current: &Credentials) -> Result { + let refreshed = self.client.refresh_credentials(current).await?; + let access_token = refreshed.access_token().to_string(); + self.store.save(refreshed).await.map_err(Error::Storage)?; + Ok(access_token) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + use crate::token::TokenSet; + + #[derive(Clone, Default)] + struct MemoryStore(Arc>>); + + impl CredentialStore for MemoryStore { + fn load( + &self, + ) -> impl Future, StorageError>> + Send + { + let inner = self.0.clone(); + async move { Ok(inner.lock().await.clone()) } + } + + fn save( + &self, + credentials: Credentials, + ) -> impl Future> + Send { + let inner = self.0.clone(); + async move { + *inner.lock().await = Some(credentials); + Ok(()) + } + } + + fn clear(&self) -> impl Future> + Send { + let inner = self.0.clone(); + async move { + *inner.lock().await = None; + Ok(()) + } + } + } + + fn credentials() -> Credentials { + Credentials { + access_token: "access-secret".into(), + refresh_token: Some("refresh-secret".into()), + id_token: Some("id-secret".into()), + token_type: "Bearer".into(), + scope: Some("openid offline_access".into()), + client_id: "client".into(), + issuer: "https://auth.x.ai".into(), + expires_at: Some(1), + obtained_at: 0, + } + } + + #[test] + fn secret_bearing_credentials_have_redacted_debug() { + let credentials = credentials(); + let debug = format!("{credentials:?}"); + for secret in ["access-secret", "refresh-secret", "id-secret"] { + assert!(!debug.contains(secret)); + } + } + + #[test] + fn refresh_merge_retains_refresh_token_when_rotation_is_omitted() { + let current = credentials(); + let tokens = TokenSet { + access_token: "new-access".into(), + refresh_token: None, + id_token: None, + token_type: "Bearer".into(), + scope: None, + expires_at: Some(10_000), + }; + let merged = current.merged_refresh(tokens, 500); + assert_eq!(merged.access_token(), "new-access"); + assert_eq!(merged.refresh_token(), Some("refresh-secret")); + assert_eq!(merged.id_token(), Some("id-secret")); + assert_eq!(merged.client_id(), "client"); + } + + #[tokio::test] + async fn manager_rejects_missing_credentials_and_supports_clear() { + let store = MemoryStore::default(); + let client = OAuthClient::new( + eggfetch_core::Client::new(), + crate::provider::OAuthProviderConfig::xai(), + ); + let manager = TokenManager::new(client, store.clone()); + assert!(matches!( + manager.access_token().await, + Err(Error::NotLoggedIn) + )); + manager.save(credentials()).await.unwrap(); + assert!(manager.current().await.unwrap().is_some()); + manager.clear().await.unwrap(); + assert!(manager.current().await.unwrap().is_none()); + } + + #[tokio::test] + async fn manager_rejects_credentials_for_a_different_issuer() { + let store = MemoryStore::default(); + let client = OAuthClient::new( + eggfetch_core::Client::new(), + crate::provider::OAuthProviderConfig::xai(), + ); + let manager = TokenManager::new(client, store.clone()); + let mut wrong_issuer = credentials(); + wrong_issuer.issuer = crate::provider::OPENAI_ISSUER.into(); + store.save(wrong_issuer).await.unwrap(); + + assert!(matches!( + manager.current().await, + Err(Error::InvalidConfiguration(_)) + )); + } + + #[tokio::test] + async fn force_refresh_uses_a_newer_token_without_another_refresh() { + let store = MemoryStore::default(); + let client = OAuthClient::new( + eggfetch_core::Client::new(), + crate::provider::OAuthProviderConfig::xai(), + ); + let manager = TokenManager::new(client, store.clone()); + let mut current = credentials(); + current.access_token = "newer-access".into(); + store.save(current).await.unwrap(); + + assert_eq!( + manager.force_refresh("failed-old-access").await.unwrap(), + "newer-access" + ); + } + + #[test] + fn public_owned_api_types_are_send_and_sync() { + fn assert_send_sync() {} + + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::>(); + } +} diff --git a/crates/eggpass-auth/src/pkce.rs b/crates/eggpass-auth/src/pkce.rs new file mode 100644 index 0000000..02f5dd2 --- /dev/null +++ b/crates/eggpass-auth/src/pkce.rs @@ -0,0 +1,43 @@ +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use rand::Rng; +use sha2::{Digest, Sha256}; + +/// Generate a cryptographically random PKCE verifier (RFC 7636, 32 random bytes). +pub fn random_verifier() -> String { + random_urlsafe(32) +} + +/// Return the RFC 7636 S256 code challenge for an ASCII verifier. +pub fn challenge_for(verifier: &str) -> String { + URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) +} + +fn random_urlsafe(bytes: usize) -> String { + let mut value = vec![0; bytes]; + rand::rng().fill_bytes(&mut value); + URL_SAFE_NO_PAD.encode(value) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_the_rfc_7636_s256_test_vector() { + assert_eq!( + challenge_for("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + ); + } + + #[test] + fn verifier_is_base64url_without_padding_and_has_256_bits_of_entropy() { + let verifier = random_verifier(); + assert_eq!(verifier.len(), 43); + assert!(!verifier.contains('=')); + assert!(!verifier.contains('+')); + assert!(!verifier.contains('/')); + assert_ne!(verifier, random_verifier()); + } +} diff --git a/crates/eggpass-auth/src/provider.rs b/crates/eggpass-auth/src/provider.rs new file mode 100644 index 0000000..3877223 --- /dev/null +++ b/crates/eggpass-auth/src/provider.rs @@ -0,0 +1,669 @@ +use std::fmt; + +use crate::{Error, Result}; + +/// The x.ai OAuth issuer. +pub const XAI_ISSUER: &str = "https://auth.x.ai"; +/// The public x.ai / Grok CLI client identifier. +pub const XAI_CLIENT_ID: &str = "b1a00492-073a-47ea-816f-4c329264a828"; +/// The OpenAI OAuth issuer. +pub const OPENAI_ISSUER: &str = "https://auth.openai.com"; +/// The temporary client identifier used to register an OpenAI agent. +pub const OPENAI_ENTRY_CLIENT_ID: &str = "dynamic_agent_client"; +/// The OpenAI resource sent during authorization and token requests. +pub const OPENAI_RESOURCE: &str = "https://api.openai.com/v1"; + +const XAI_SCOPES: &[&str] = &[ + "openid", + "profile", + "email", + "offline_access", + "grok-cli:access", + "api:access", + "conversations:read", + "conversations:write", + "workspaces:read", + "workspaces:write", +]; +const XAI_FALLBACK_SCOPES: &[&str] = &[ + "openid", + "profile", + "email", + "offline_access", + "grok-cli:access", + "api:access", +]; +const OPENAI_SCOPES: &[&str] = &[ + "openid", + "profile", + "email", + "offline_access", + "resource.invoke", + "chatgpt.tokens.use.direct", +]; + +/// Whether a provider uses a fixed client ID or issues one during registration. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ClientIdPolicy { + /// The configured public client ID is used for every operation. + Fixed, + /// The provider returns a client ID during the first authorization; callers + /// must persist it and pass it back for later login and refresh operations. + IssuedOnRegistration, +} + +/// Auth-specific OAuth endpoints and parameters for one provider. +/// +/// This type intentionally excludes inference URLs, request policies, and other +/// application-specific provider metadata. Use [`OAuthProviderConfig::xai`], +/// [`OAuthProviderConfig::openai`], or [`OAuthProviderConfig::custom`] to +/// construct a validated profile. +#[derive(Clone)] +pub struct OAuthProviderConfig { + pub(crate) display_name: String, + pub(crate) issuer: String, + pub(crate) authorization_endpoint: String, + pub(crate) token_endpoint: String, + pub(crate) device_authorization_endpoint: Option, + pub(crate) userinfo_endpoint: Option, + pub(crate) revocation_endpoint: Option, + pub(crate) callback_path: String, + pub(crate) client_id: String, + pub(crate) client_id_policy: ClientIdPolicy, + pub(crate) scopes: Vec, + pub(crate) authorization_parameters: Vec<(String, String)>, + pub(crate) registration_parameters: Vec<(String, String)>, + pub(crate) token_parameters: Vec<(String, String)>, + pub(crate) device_parameters: Vec<(String, String)>, + pub(crate) trusted_device_hosts: Vec, + pub(crate) xai_referrer_fallback: Option, +} + +impl fmt::Debug for OAuthProviderConfig { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("OAuthProviderConfig") + .field("display_name", &self.display_name) + .field("issuer", &self.issuer) + .field("authorization_endpoint", &self.authorization_endpoint) + .field("token_endpoint", &self.token_endpoint) + .field( + "device_authorization_endpoint", + &self.device_authorization_endpoint, + ) + .field("userinfo_endpoint", &self.userinfo_endpoint) + .field("revocation_endpoint", &self.revocation_endpoint) + .field("callback_path", &self.callback_path) + .field("client_id", &"") + .field("client_id_policy", &self.client_id_policy) + .field("scopes", &self.scopes) + .field( + "authorization_parameter_names", + ¶meter_names(&self.authorization_parameters), + ) + .field( + "registration_parameter_names", + ¶meter_names(&self.registration_parameters), + ) + .field( + "token_parameter_names", + ¶meter_names(&self.token_parameters), + ) + .field( + "device_parameter_names", + ¶meter_names(&self.device_parameters), + ) + .field("trusted_device_hosts", &self.trusted_device_hosts) + .finish() + } +} + +fn parameter_names(parameters: &[(String, String)]) -> Vec<&str> { + parameters.iter().map(|(name, _)| name.as_str()).collect() +} + +impl OAuthProviderConfig { + /// The built-in x.ai OAuth profile with the full Grok CLI scope set. + /// + /// The profile sends `referrer=eggpass`, as Eggpass does. If x.ai returns a + /// client-configuration OAuth error, applications may start a new + /// authorization transaction with [`Self::xai_compatibility_fallback`]; + /// token exchanges and refreshes are never automatically retried. + pub fn xai() -> Self { + Self::xai_builder(false) + .build() + .expect("built-in x.ai profile is valid") + } + + /// The x.ai fallback profile used when a provider rejects the primary + /// referrer or full scope set. It uses `referrer=grok-build` and the shorter + /// reference-client scope set. Start a new user authorization with it; do + /// not retry an authorization-code exchange or refresh request. + pub fn xai_compatibility_fallback() -> Self { + Self::xai_builder(true) + .build() + .expect("built-in x.ai fallback profile is valid") + } + + fn xai_builder(fallback: bool) -> OAuthProviderConfigBuilder { + let scopes = if fallback { + XAI_FALLBACK_SCOPES + } else { + XAI_SCOPES + }; + let referrer = if fallback { "grok-build" } else { "eggpass" }; + OAuthProviderConfigBuilder::new("x.ai", XAI_ISSUER, XAI_CLIENT_ID) + .authorization_endpoint(format!("{XAI_ISSUER}/oauth2/authorize")) + .token_endpoint(format!("{XAI_ISSUER}/oauth2/token")) + .device_authorization_endpoint(format!("{XAI_ISSUER}/oauth2/device/code")) + .userinfo_endpoint(format!("{XAI_ISSUER}/oauth2/userinfo")) + .revocation_endpoint(format!("{XAI_ISSUER}/oauth2/revoke")) + .callback_path("/callback") + .scopes(scopes.iter().copied()) + .authorization_parameter("referrer", referrer) + .device_parameter("referrer", referrer) + .trusted_device_host("accounts.x.ai") + .trusted_device_host("auth.x.ai") + .trusted_device_host("x.ai") + .xai_referrer_fallback(if fallback { "eggpass" } else { "grok-build" }) + } + + /// The built-in Sign in with ChatGPT for Open Source profile. + /// + /// OpenAI issues a client ID during the first registration. Save the + /// callback's issued ID in the returned [`Credentials`] and pass it to the + /// next authorization/refresh call. The built-in registration hint is + /// `eggpass`; callers may build a custom profile to use another hint. + pub fn openai() -> Self { + Self::openai_builder(None) + .build() + .expect("built-in OpenAI profile is valid") + } + + /// OpenAI's profile with a caller-owned, stable host identifier. + pub fn openai_with_host_id(host_id: impl Into) -> Result { + Self::openai_builder(Some(host_id.into())).build() + } + + fn openai_builder(host_id: Option) -> OAuthProviderConfigBuilder { + let mut builder = + OAuthProviderConfigBuilder::new("OpenAI", OPENAI_ISSUER, OPENAI_ENTRY_CLIENT_ID) + .authorization_endpoint(format!("{OPENAI_ISSUER}/api/accounts/authorize")) + .token_endpoint(format!("{OPENAI_ISSUER}/api/accounts/oauth/token")) + .userinfo_endpoint(format!("{OPENAI_ISSUER}/api/accounts/oauth/userinfo")) + .revocation_endpoint(format!("{OPENAI_ISSUER}/api/accounts/oauth/revoke")) + .callback_path("/auth/callback") + .client_id_policy(ClientIdPolicy::IssuedOnRegistration) + .scopes(OPENAI_SCOPES.iter().copied()) + .authorization_parameter("resource", OPENAI_RESOURCE) + .registration_parameter("agent_name_hint", "eggpass") + .token_parameter("resource", OPENAI_RESOURCE); + if let Some(host_id) = host_id { + builder = builder.authorization_parameter("ext_agent_host_id", host_id); + } + builder + } + + /// Start a custom OAuth profile. Set the absolute authorization and token + /// endpoint URLs and add only the optional endpoints/parameters the + /// provider supports, then call [`OAuthProviderConfigBuilder::build`]. + pub fn custom( + display_name: impl Into, + issuer: impl Into, + client_id: impl Into, + ) -> OAuthProviderConfigBuilder { + OAuthProviderConfigBuilder::new(display_name, issuer, client_id) + } + + /// Provider display name, safe to show in UI. + pub fn display_name(&self) -> &str { + &self.display_name + } + + /// The issuer associated with credentials from this profile. + pub fn issuer(&self) -> &str { + &self.issuer + } + + /// The configured callback path. + pub fn callback_path(&self) -> &str { + &self.callback_path + } + + /// The configured client ID to use before a provider-issued ID is stored. + pub fn entry_client_id(&self) -> &str { + &self.client_id + } + + /// How this provider assigns client IDs. + pub fn client_id_policy(&self) -> ClientIdPolicy { + self.client_id_policy + } + + /// The scopes requested by this profile. + pub fn scopes(&self) -> &[String] { + &self.scopes + } + + /// Return a profile with a different client ID, useful for a caller-owned + /// provider registration or a changed public client ID. + pub fn with_client_id(mut self, client_id: impl Into) -> Result { + let client_id = client_id.into(); + if client_id.trim().is_empty() { + return Err(Error::InvalidConfiguration("client ID must not be empty")); + } + self.client_id = client_id; + Ok(self) + } + + /// Add or replace a non-secret authorization parameter. Existing values + /// with the same name are replaced. + pub fn with_authorization_parameter( + mut self, + name: impl Into, + value: impl Into, + ) -> Result { + insert_parameter( + &mut self.authorization_parameters, + name.into(), + value.into(), + )?; + Ok(self) + } + + /// Add or replace a non-secret registration-only authorization parameter. + pub fn with_registration_parameter( + mut self, + name: impl Into, + value: impl Into, + ) -> Result { + insert_parameter(&mut self.registration_parameters, name.into(), value.into())?; + Ok(self) + } + + /// Add or replace a non-secret parameter sent with every token request. + pub fn with_token_parameter( + mut self, + name: impl Into, + value: impl Into, + ) -> Result { + insert_parameter(&mut self.token_parameters, name.into(), value.into())?; + Ok(self) + } +} + +/// Builder for an [`OAuthProviderConfig`]. +/// +/// Endpoint URLs must be HTTPS, except for loopback HTTP endpoints used by +/// deterministic local tests. Callback paths are compared exactly when a +/// callback is completed. +pub struct OAuthProviderConfigBuilder { + config: OAuthProviderConfig, +} + +impl OAuthProviderConfigBuilder { + fn new( + display_name: impl Into, + issuer: impl Into, + client_id: impl Into, + ) -> Self { + Self { + config: OAuthProviderConfig { + display_name: display_name.into(), + issuer: issuer.into(), + authorization_endpoint: String::new(), + token_endpoint: String::new(), + device_authorization_endpoint: None, + userinfo_endpoint: None, + revocation_endpoint: None, + callback_path: "/callback".to_string(), + client_id: client_id.into(), + client_id_policy: ClientIdPolicy::Fixed, + scopes: Vec::new(), + authorization_parameters: Vec::new(), + registration_parameters: Vec::new(), + token_parameters: Vec::new(), + device_parameters: Vec::new(), + trusted_device_hosts: Vec::new(), + xai_referrer_fallback: None, + }, + } + } + + pub fn authorization_endpoint(mut self, endpoint: impl Into) -> Self { + self.config.authorization_endpoint = endpoint.into(); + self + } + + pub fn token_endpoint(mut self, endpoint: impl Into) -> Self { + self.config.token_endpoint = endpoint.into(); + self + } + + pub fn device_authorization_endpoint(mut self, endpoint: impl Into) -> Self { + self.config.device_authorization_endpoint = Some(endpoint.into()); + self + } + + pub fn userinfo_endpoint(mut self, endpoint: impl Into) -> Self { + self.config.userinfo_endpoint = Some(endpoint.into()); + self + } + + pub fn revocation_endpoint(mut self, endpoint: impl Into) -> Self { + self.config.revocation_endpoint = Some(endpoint.into()); + self + } + + pub fn callback_path(mut self, path: impl Into) -> Self { + self.config.callback_path = path.into(); + self + } + + pub fn client_id_policy(mut self, policy: ClientIdPolicy) -> Self { + self.config.client_id_policy = policy; + self + } + + pub fn scopes(mut self, scopes: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.config.scopes = scopes.into_iter().map(Into::into).collect(); + self + } + + pub fn authorization_parameter( + mut self, + name: impl Into, + value: impl Into, + ) -> Self { + let _ = insert_parameter( + &mut self.config.authorization_parameters, + name.into(), + value.into(), + ); + self + } + + pub fn registration_parameter( + mut self, + name: impl Into, + value: impl Into, + ) -> Self { + let _ = insert_parameter( + &mut self.config.registration_parameters, + name.into(), + value.into(), + ); + self + } + + pub fn token_parameter(mut self, name: impl Into, value: impl Into) -> Self { + let _ = insert_parameter(&mut self.config.token_parameters, name.into(), value.into()); + self + } + + pub fn device_parameter(mut self, name: impl Into, value: impl Into) -> Self { + let _ = insert_parameter( + &mut self.config.device_parameters, + name.into(), + value.into(), + ); + self + } + + pub fn trusted_device_host(mut self, host: impl Into) -> Self { + self.config + .trusted_device_hosts + .push(host.into().to_ascii_lowercase()); + self + } + + fn xai_referrer_fallback(mut self, value: impl Into) -> Self { + self.config.xai_referrer_fallback = Some(value.into()); + self + } + + /// Validate endpoint URLs, callback path, client ID, and OAuth parameters. + pub fn build(mut self) -> Result { + if self.config.display_name.trim().is_empty() { + return Err(Error::InvalidConfiguration( + "provider display name must not be empty", + )); + } + if self.config.client_id.trim().is_empty() { + return Err(Error::InvalidConfiguration("client ID must not be empty")); + } + validate_endpoint(&self.config.issuer, "issuer")?; + validate_endpoint( + &self.config.authorization_endpoint, + "authorization endpoint", + )?; + validate_endpoint(&self.config.token_endpoint, "token endpoint")?; + for (endpoint, name) in [ + ( + self.config.device_authorization_endpoint.as_deref(), + "device endpoint", + ), + ( + self.config.userinfo_endpoint.as_deref(), + "userinfo endpoint", + ), + ( + self.config.revocation_endpoint.as_deref(), + "revocation endpoint", + ), + ] { + if let Some(endpoint) = endpoint { + validate_endpoint(endpoint, name)?; + } + } + validate_callback_path(&self.config.callback_path)?; + if self + .config + .scopes + .iter() + .any(|scope| scope.is_empty() || scope.chars().any(char::is_whitespace)) + { + return Err(Error::InvalidConfiguration( + "each OAuth scope must be a non-empty token", + )); + } + validate_parameters(&self.config.authorization_parameters)?; + validate_parameters(&self.config.registration_parameters)?; + validate_parameters(&self.config.token_parameters)?; + validate_parameters(&self.config.device_parameters)?; + for host in &self.config.trusted_device_hosts { + if host.is_empty() + || host.starts_with('.') + || host.ends_with('.') + || host.contains('/') + || host.contains(':') + || !host.is_ascii() + { + return Err(Error::InvalidConfiguration( + "trusted device hosts must be plain DNS hostnames", + )); + } + } + self.config.trusted_device_hosts.sort(); + self.config.trusted_device_hosts.dedup(); + Ok(self.config) + } +} + +fn validate_endpoint(value: &str, label: &'static str) -> Result<()> { + let url = url::Url::parse(value) + .map_err(|_| Error::InvalidConfiguration("OAuth endpoint URL is invalid"))?; + if !matches!(url.scheme(), "https" | "http") + || url.host_str().is_none() + || !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + { + return Err(Error::InvalidConfiguration(match label { + "issuer" => "issuer must be an HTTP(S) origin without credentials, query, or fragment", + _ => "OAuth endpoints must be HTTP(S) URLs without credentials, query, or fragment", + })); + } + if url.scheme() != "https" && !is_loopback_url(&url) { + return Err(Error::InvalidConfiguration( + "plain HTTP is permitted only for loopback OAuth endpoints", + )); + } + Ok(()) +} + +fn is_loopback_url(url: &url::Url) -> bool { + match url.host() { + Some(url::Host::Ipv4(address)) => address.is_loopback(), + Some(url::Host::Ipv6(address)) => address.is_loopback(), + Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"), + None => false, + } +} + +fn validate_callback_path(path: &str) -> Result<()> { + if !path.starts_with('/') + || path.starts_with("//") + || path.contains('?') + || path.contains('#') + || path.contains('\r') + || path.contains('\n') + { + return Err(Error::InvalidConfiguration( + "callback path must be an absolute path without query or fragment", + )); + } + Ok(()) +} + +fn validate_parameters(parameters: &[(String, String)]) -> Result<()> { + for (name, value) in parameters { + if name.is_empty() + || name.chars().any(|c| c.is_control()) + || value.chars().any(|c| c.is_control()) + { + return Err(Error::InvalidConfiguration( + "OAuth parameter names and values must not contain control characters", + )); + } + } + Ok(()) +} + +fn insert_parameter( + parameters: &mut Vec<(String, String)>, + name: String, + value: String, +) -> Result<()> { + if name.is_empty() + || name.chars().any(|c| c.is_control()) + || value.chars().any(|c| c.is_control()) + { + return Err(Error::InvalidConfiguration( + "OAuth parameter names and values must not contain control characters", + )); + } + if let Some((_, previous)) = parameters + .iter_mut() + .find(|(existing, _)| existing == &name) + { + *previous = value; + } else { + parameters.push((name, value)); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn xai_has_referrer_device_flow_and_trusted_hosts() { + let config = OAuthProviderConfig::xai(); + assert_eq!(config.client_id, XAI_CLIENT_ID); + assert_eq!( + config.device_authorization_endpoint.as_deref(), + Some("https://auth.x.ai/oauth2/device/code") + ); + assert!( + config + .trusted_device_hosts + .iter() + .any(|host| host == "accounts.x.ai") + ); + assert!( + config + .authorization_parameters + .contains(&("referrer".into(), "eggpass".into())) + ); + let fallback = OAuthProviderConfig::xai_compatibility_fallback(); + assert!( + fallback + .authorization_parameters + .contains(&("referrer".into(), "grok-build".into())) + ); + assert_eq!(fallback.scopes.len(), 6); + } + + #[test] + fn openai_registration_parameters_and_issued_id_policy_are_explicit() { + let config = OAuthProviderConfig::openai(); + assert_eq!( + config.client_id_policy, + ClientIdPolicy::IssuedOnRegistration + ); + assert!( + config + .authorization_parameters + .contains(&("resource".into(), OPENAI_RESOURCE.into())) + ); + assert!( + config + .token_parameters + .contains(&("resource".into(), OPENAI_RESOURCE.into())) + ); + assert!( + config + .registration_parameters + .contains(&("agent_name_hint".into(), "eggpass".into())) + ); + let with_host = OAuthProviderConfig::openai_with_host_id("urn:uuid:test").unwrap(); + assert!( + with_host + .authorization_parameters + .contains(&("ext_agent_host_id".into(), "urn:uuid:test".into())) + ); + } + + #[test] + fn custom_profiles_reject_plain_http_outside_loopback_and_invalid_callback_paths() { + let insecure = OAuthProviderConfig::custom("example", "https://issuer.example", "client") + .authorization_endpoint("http://issuer.example/authorize") + .token_endpoint("https://issuer.example/token") + .build(); + assert!(matches!(insecure, Err(Error::InvalidConfiguration(_)))); + + let invalid_path = + OAuthProviderConfig::custom("example", "https://issuer.example", "client") + .authorization_endpoint("https://issuer.example/authorize") + .token_endpoint("https://issuer.example/token") + .callback_path("/callback?wrong=1") + .build(); + assert!(matches!(invalid_path, Err(Error::InvalidConfiguration(_)))); + } + + #[test] + fn configuration_debug_redacts_client_and_parameter_values() { + let config = OAuthProviderConfig::xai(); + let debug = format!("{config:?}"); + assert!(!debug.contains(XAI_CLIENT_ID)); + assert!(!debug.contains("eggpass")); + assert!(debug.contains("referrer")); + } +} diff --git a/crates/eggpass-auth/src/token.rs b/crates/eggpass-auth/src/token.rs new file mode 100644 index 0000000..c13aaa9 --- /dev/null +++ b/crates/eggpass-auth/src/token.rs @@ -0,0 +1,538 @@ +use std::fmt; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::{Error, Result}; + +/// OAuth tokens returned by an authorization-code, device, or refresh grant. +/// +/// Secret fields are private and `Debug` redacts their values. Use the accessors +/// to pass tokens to the caller's storage or authenticated API client. +#[derive(Clone, Default)] +pub struct TokenSet { + pub(crate) access_token: String, + pub(crate) refresh_token: Option, + pub(crate) id_token: Option, + pub(crate) token_type: String, + pub(crate) scope: Option, + pub(crate) expires_at: Option, +} + +impl TokenSet { + pub(crate) fn from_json(value: &Value, now: i64) -> Result { + let access_token = value + .get("access_token") + .and_then(Value::as_str) + .filter(|token| !token.is_empty()) + .ok_or(Error::InvalidResponse("token response has no access_token"))? + .to_string(); + let refresh_token = optional_string(value, "refresh_token"); + let id_token = optional_string(value, "id_token"); + let token_type = value + .get("token_type") + .and_then(Value::as_str) + .filter(|token_type| !token_type.is_empty()) + .unwrap_or("Bearer") + .to_string(); + let scope = optional_string(value, "scope"); + + let expires_at = if let Some(expiry) = value.get("expires_in") { + let seconds = expiry.as_i64().ok_or(Error::InvalidResponse( + "token response expires_in is not an integer", + ))?; + if seconds < 0 { + return Err(Error::InvalidResponse( + "token response expires_in is negative", + )); + } + Some(now.checked_add(seconds).ok_or(Error::InvalidResponse( + "token response expiry is out of range", + ))?) + } else { + match value.get("expires_at") { + Some(Value::Number(number)) => number.as_i64(), + Some(Value::String(timestamp)) => parse_rfc3339_to_unix(timestamp), + _ => None, + } + }; + + Ok(Self { + access_token, + refresh_token, + id_token, + token_type, + scope, + expires_at, + }) + } + + /// Bearer access token. + pub fn access_token(&self) -> &str { + &self.access_token + } + + /// Refresh token, when the provider returned one. + pub fn refresh_token(&self) -> Option<&str> { + self.refresh_token.as_deref() + } + + /// OpenID Connect ID token, when the provider returned one. + pub fn id_token(&self) -> Option<&str> { + self.id_token.as_deref() + } + + /// Token type, normally `Bearer`. + pub fn token_type(&self) -> &str { + &self.token_type + } + + /// Granted scope string, when returned by the provider. + pub fn scope(&self) -> Option<&str> { + self.scope.as_deref() + } + + /// Absolute expiry in Unix seconds, when returned or derived from + /// `expires_in`. + pub fn expires_at(&self) -> Option { + self.expires_at + } +} + +impl fmt::Debug for TokenSet { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TokenSet") + .field("access_token", &"") + .field( + "refresh_token", + &self.refresh_token.as_ref().map(|_| ""), + ) + .field("id_token", &self.id_token.as_ref().map(|_| "")) + .field("token_type", &self.token_type) + .field("scope", &self.scope) + .field("expires_at", &self.expires_at) + .finish() + } +} + +/// Credentials to keep in caller-owned storage. +/// +/// The type is serializable for storage adapters, but its `Debug` output always +/// redacts token values. The library does not write it to disk or assume a +/// filesystem location. +#[derive(Clone, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Credentials { + #[serde(default)] + pub(crate) access_token: String, + #[serde(default)] + pub(crate) refresh_token: Option, + #[serde(default)] + pub(crate) id_token: Option, + #[serde(default = "default_token_type")] + pub(crate) token_type: String, + #[serde(default)] + pub(crate) scope: Option, + #[serde(default)] + pub(crate) client_id: String, + #[serde(default)] + pub(crate) issuer: String, + #[serde(default)] + pub(crate) expires_at: Option, + #[serde(default)] + pub(crate) obtained_at: i64, +} + +fn default_token_type() -> String { + "Bearer".to_string() +} + +impl Credentials { + pub(crate) fn from_tokens( + tokens: TokenSet, + client_id: String, + issuer: String, + obtained_at: i64, + ) -> Self { + Self { + access_token: tokens.access_token, + refresh_token: tokens.refresh_token, + id_token: tokens.id_token, + token_type: if tokens.token_type.is_empty() { + default_token_type() + } else { + tokens.token_type + }, + scope: tokens.scope, + client_id, + issuer, + expires_at: tokens.expires_at, + obtained_at, + } + } + + pub(crate) fn validate(&self) -> Result<()> { + if self.access_token.is_empty() { + return Err(Error::InvalidResponse( + "stored credentials have no access token", + )); + } + if self.client_id.is_empty() { + return Err(Error::InvalidResponse( + "stored credentials have no client ID", + )); + } + Ok(()) + } + + pub(crate) fn merged_refresh(&self, tokens: TokenSet, now: i64) -> Self { + Self { + access_token: tokens.access_token, + refresh_token: tokens.refresh_token.or_else(|| self.refresh_token.clone()), + id_token: tokens.id_token.or_else(|| self.id_token.clone()), + token_type: if tokens.token_type.is_empty() { + self.token_type.clone() + } else { + tokens.token_type + }, + scope: tokens.scope.or_else(|| self.scope.clone()), + client_id: self.client_id.clone(), + issuer: if self.issuer.is_empty() { + String::new() + } else { + self.issuer.clone() + }, + expires_at: tokens.expires_at, + obtained_at: now, + } + } + + /// Access token for authenticated requests. + pub fn access_token(&self) -> &str { + &self.access_token + } + + /// Refresh token, when available. + pub fn refresh_token(&self) -> Option<&str> { + self.refresh_token.as_deref() + } + + /// ID token, when available. + pub fn id_token(&self) -> Option<&str> { + self.id_token.as_deref() + } + + /// Token type, normally `Bearer`. + pub fn token_type(&self) -> &str { + &self.token_type + } + + /// Granted scopes. + pub fn scope(&self) -> Option<&str> { + self.scope.as_deref() + } + + /// The client ID to reuse for refresh and future authorizations. + pub fn client_id(&self) -> &str { + &self.client_id + } + + /// Issuer associated with these credentials. + pub fn issuer(&self) -> &str { + &self.issuer + } + + /// Absolute expiry in Unix seconds, when known. + pub fn expires_at(&self) -> Option { + self.expires_at + } + + /// Unix time when these credentials were obtained. + pub fn obtained_at(&self) -> i64 { + self.obtained_at + } + + /// Whether the access token remains fresh after the requested refresh skew. + pub fn is_fresh(&self, now: i64, skew_seconds: i64) -> bool { + let fallback_expiry = self.obtained_at.saturating_add(30 * 86_400); + now.saturating_add(skew_seconds.max(0)) < self.expires_at.unwrap_or(fallback_expiry) + } + + /// Unix seconds since the system epoch. Returns zero if the system clock is + /// before the Unix epoch. + pub fn now_unix() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_secs().min(i64::MAX as u64) as i64) + .unwrap_or_default() + } +} + +impl fmt::Debug for Credentials { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Credentials") + .field("access_token", &"") + .field( + "refresh_token", + &self.refresh_token.as_ref().map(|_| ""), + ) + .field("id_token", &self.id_token.as_ref().map(|_| "")) + .field("token_type", &self.token_type) + .field("scope", &self.scope) + .field("client_id", &"") + .field("issuer", &self.issuer) + .field("expires_at", &self.expires_at) + .field("obtained_at", &self.obtained_at) + .finish() + } +} + +fn parse_rfc3339_to_unix(value: &str) -> Option { + let (local, offset_seconds) = + if let Some(local) = value.strip_suffix('Z').or_else(|| value.strip_suffix('z')) { + (local, 0) + } else { + let offset_index = value + .char_indices() + .skip(10) + .find_map(|(index, character)| matches!(character, '+' | '-').then_some(index))?; + let (local, offset) = value.split_at(offset_index); + (local, parse_timezone_offset(offset)?) + }; + let (date, time) = local.split_once('T').or_else(|| local.split_once('t'))?; + if date.len() != 10 { + return None; + } + let mut date_parts = date.split('-'); + let year = parse_decimal(date_parts.next()?, 4)?; + let month = parse_decimal(date_parts.next()?, 2)?; + let day = parse_decimal(date_parts.next()?, 2)?; + if date_parts.next().is_some() || !(1..=12).contains(&month) { + return None; + } + let leap_year = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + let days_in_month = match month { + 2 if leap_year => 29, + 2 => 28, + 4 | 6 | 9 | 11 => 30, + _ => 31, + }; + if !(1..=days_in_month).contains(&day) { + return None; + } + + let (time, fraction) = match time.split_once('.') { + Some((time, fraction)) => { + if fraction.is_empty() || !fraction.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + (time, Some(fraction)) + } + None => (time, None), + }; + let _ = fraction; + if time.len() != 8 + || time.as_bytes().get(2) != Some(&b':') + || time.as_bytes().get(5) != Some(&b':') + { + return None; + } + let hour = parse_decimal(&time[0..2], 2)?; + let minute = parse_decimal(&time[3..5], 2)?; + let second = parse_decimal(&time[6..8], 2)?; + if hour > 23 || minute > 59 || second > 60 { + return None; + } + + let adjusted_year = year - i64::from(month <= 2); + let era = adjusted_year.div_euclid(400); + let year_of_era = adjusted_year - era * 400; + let month_prime = month + if month > 2 { -3 } else { 9 }; + let day_of_year = (153 * month_prime + 2) / 5 + day - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + let days = era * 146_097 + day_of_era - 719_468; + days.checked_mul(86_400)? + .checked_add(hour * 3_600 + minute * 60 + second)? + .checked_sub(offset_seconds) +} + +fn parse_timezone_offset(value: &str) -> Option { + let (sign, offset) = match value.as_bytes().first()? { + b'+' => (1, &value[1..]), + b'-' => (-1, &value[1..]), + _ => return None, + }; + if offset.len() != 5 || offset.as_bytes().get(2) != Some(&b':') { + return None; + } + let hours = parse_decimal(&offset[0..2], 2)?; + let minutes = parse_decimal(&offset[3..5], 2)?; + if hours > 23 || minutes > 59 { + return None; + } + Some(sign * (hours * 3_600 + minutes * 60)) +} + +fn parse_decimal(value: &str, digits: usize) -> Option { + if value.len() != digits || !value.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + value.parse().ok() +} + +fn optional_string(value: &Value, key: &str) -> Option { + value + .get(key) + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .map(str::to_owned) +} + +/// Non-secret account details returned by an OpenID user-info endpoint. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct UserInfo { + /// Provider account identifier, when available. + pub user_id: Option, + /// Account email, when available. + pub email: Option, +} + +/// Data returned by a device authorization endpoint. +#[derive(Clone)] +pub struct DeviceCode { + pub(crate) device_code: String, + pub(crate) user_code: String, + pub(crate) verification_uri: String, + pub(crate) verification_uri_complete: Option, + pub(crate) expires_in: std::time::Duration, + pub(crate) expires_at: tokio::time::Instant, + pub(crate) interval: std::time::Duration, +} + +impl DeviceCode { + /// Secret device code used only for token polling. + pub fn device_code(&self) -> &str { + &self.device_code + } + + /// Short code the user enters at the verification page. + pub fn user_code(&self) -> &str { + &self.user_code + } + + /// Verification page URL. + pub fn verification_uri(&self) -> &str { + &self.verification_uri + } + + /// Verification page URL with the user code pre-filled, when provided. + pub fn verification_uri_complete(&self) -> Option<&str> { + self.verification_uri_complete.as_deref() + } + + /// Server-provided authorization lifetime. The library does not increase + /// short values to a local minimum. + pub fn expires_in(&self) -> std::time::Duration { + self.expires_in + } + + /// Initial server-provided polling interval. + pub fn interval(&self) -> std::time::Duration { + self.interval + } +} + +impl fmt::Debug for DeviceCode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DeviceCode") + .field("device_code", &"") + .field("user_code", &"") + .field("verification_uri", &"") + .field( + "verification_uri_complete", + &self + .verification_uri_complete + .as_ref() + .map(|_| ""), + ) + .field("expires_in", &self.expires_in) + .field("interval", &self.interval) + .finish() + } +} + +/// Result of one device-code poll. +#[derive(Debug)] +#[non_exhaustive] +pub enum DevicePoll { + /// The user has not approved the request yet. + Pending, + /// The server asked the client to increase its interval by five seconds. + SlowDown, + /// The user denied the request. + Denied, + /// The device grant expired. + Expired, + /// Authorization succeeded. + Complete(TokenSet), +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn token_response_parses_rfc3339_expiry_and_numeric_expiry() { + let rfc3339 = TokenSet::from_json( + &serde_json::json!({ + "access_token": "access", + "expires_at": "2026-12-13T05:12:18Z" + }), + 0, + ) + .unwrap(); + assert_eq!(rfc3339.expires_at(), Some(1_797_138_738)); + + let offset = TokenSet::from_json( + &serde_json::json!({ + "access_token": "access", + "expires_at": "1970-01-01T01:00:00+01:00" + }), + 0, + ) + .unwrap(); + assert_eq!(offset.expires_at(), Some(0)); + + let numeric = TokenSet::from_json( + &serde_json::json!({"access_token": "access", "expires_at": 1234}), + 0, + ) + .unwrap(); + assert_eq!(numeric.expires_at(), Some(1234)); + } + + #[test] + fn credential_freshness_respects_the_requested_refresh_skew() { + let credentials = Credentials { + expires_at: Some(1_000), + obtained_at: 0, + ..Credentials::default() + }; + assert!(credentials.is_fresh(699, 300)); + assert!(!credentials.is_fresh(700, 300)); + } + + #[test] + fn malformed_rfc3339_expiry_is_ignored_without_panicking() { + let tokens = TokenSet::from_json( + &serde_json::json!({ + "access_token": "access", + "expires_at": "2026-99-99T25:61:61Z" + }), + 0, + ) + .unwrap(); + assert_eq!(tokens.expires_at(), None); + } +} diff --git a/crates/eggpass-auth/tests/oauth_stub.rs b/crates/eggpass-auth/tests/oauth_stub.rs new file mode 100644 index 0000000..67bc3e3 --- /dev/null +++ b/crates/eggpass-auth/tests/oauth_stub.rs @@ -0,0 +1,513 @@ +use std::future::Future; +use std::sync::Arc; +use std::time::Duration; + +use eggfetch_core::Client; +use eggfetch_core::timeout::Timeout; +use eggpass_auth::{ + ClientIdPolicy, ClientOptions, CredentialStore, Credentials, Error, OAuthClient, + OAuthProviderConfig, StorageError, TokenManager, +}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::task::JoinHandle; + +async fn stub_once(status: u16, body: &'static [u8]) -> (String, JoinHandle>) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let task = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let request = read_request(&mut stream).await; + write_response(&mut stream, status, body).await; + request + }); + (format!("http://{address}"), task) +} + +async fn read_request(stream: &mut TcpStream) -> Vec { + let mut request = Vec::new(); + let mut chunk = [0u8; 1024]; + let header_end; + loop { + let read = stream.read(&mut chunk).await.unwrap(); + assert!(read > 0, "connection closed before request headers"); + request.extend_from_slice(&chunk[..read]); + if let Some(index) = request.windows(4).position(|window| window == b"\r\n\r\n") { + header_end = index + 4; + break; + } + } + let headers = String::from_utf8_lossy(&request[..header_end]); + let content_length = headers + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().unwrap()) + }) + .unwrap_or(0); + while request.len() < header_end + content_length { + let read = stream.read(&mut chunk).await.unwrap(); + assert!(read > 0, "connection closed before request body"); + request.extend_from_slice(&chunk[..read]); + } + request +} + +async fn write_response(stream: &mut TcpStream, status: u16, body: &[u8]) { + let reason = match status { + 200 => "OK", + 302 => "Found", + 400 => "Bad Request", + 503 => "Service Unavailable", + _ => "Test Response", + }; + let response = format!( + "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + stream.write_all(response.as_bytes()).await.unwrap(); + stream.write_all(body).await.unwrap(); + stream.flush().await.unwrap(); +} + +fn oauth(base: &str, client: Client) -> OAuthClient { + let config = OAuthProviderConfig::custom("stub", base, "public-client") + .authorization_endpoint(format!("{base}/authorize")) + .token_endpoint(format!("{base}/token")) + .device_authorization_endpoint(format!("{base}/device")) + .userinfo_endpoint(format!("{base}/userinfo")) + .revocation_endpoint(format!("{base}/revoke")) + .callback_path("/callback") + .scopes(["offline_access"]) + .trusted_device_host("accounts.test") + .build() + .unwrap(); + OAuthClient::new(client, config) +} + +fn options(total: Duration, body_limit: usize) -> ClientOptions { + ClientOptions { + timeout: Timeout { + pool: Some(Duration::from_secs(1)), + connect: Some(Duration::from_secs(1)), + write: Some(Duration::from_secs(1)), + read: Some(Duration::from_secs(1)), + total: Some(total), + }, + max_response_body_bytes: body_limit, + } +} + +#[tokio::test] +async fn real_eggfetch_posts_encoded_authorization_code_without_leaking_bearer_auth() { + let (base, server) = stub_once( + 200, + br#"{"access_token":"access-secret","refresh_token":"refresh-secret","token_type":"Bearer","expires_in":3600}"#, + ) + .await; + let oauth = oauth(&base, Client::new()) + .with_options(options(Duration::from_secs(2), 4096)) + .unwrap(); + let credentials = oauth + .exchange_authorization_code( + "code /+&", + "http://127.0.0.1:43123/callback", + "verifier-123456789", + None, + ) + .await + .unwrap(); + let request = String::from_utf8(server.await.unwrap()).unwrap(); + assert!(request.starts_with("POST /token HTTP/1.1"), "{request}"); + assert!( + request + .to_ascii_lowercase() + .contains("content-type: application/x-www-form-urlencoded") + ); + assert!(!request.to_ascii_lowercase().contains("authorization:")); + let body = request.split("\r\n\r\n").nth(1).unwrap(); + let parameters: std::collections::HashMap<_, _> = url::form_urlencoded::parse(body.as_bytes()) + .into_owned() + .collect(); + assert_eq!(parameters.get("code").map(String::as_str), Some("code /+&")); + assert_eq!( + parameters.get("code_verifier").map(String::as_str), + Some("verifier-123456789") + ); + assert_eq!( + parameters.get("grant_type").map(String::as_str), + Some("authorization_code") + ); + assert_eq!(credentials.access_token(), "access-secret"); + assert_eq!(credentials.refresh_token(), Some("refresh-secret")); + assert!(!format!("{credentials:?}").contains("access-secret")); +} + +#[tokio::test] +async fn revocation_and_userinfo_use_their_configured_endpoints() { + let (base, server) = stub_once(200, b"{}").await; + let revoker = oauth(&base, Client::new()); + revoker.revoke("refresh-secret", None).await.unwrap(); + let request = String::from_utf8(server.await.unwrap()).unwrap(); + assert!(request.starts_with("POST /revoke HTTP/1.1")); + assert!(!request.to_ascii_lowercase().contains("authorization:")); + let body = request.split("\r\n\r\n").nth(1).unwrap(); + let form: std::collections::HashMap<_, _> = url::form_urlencoded::parse(body.as_bytes()) + .into_owned() + .collect(); + assert_eq!( + form.get("token").map(String::as_str), + Some("refresh-secret") + ); + assert_eq!( + form.get("token_type_hint").map(String::as_str), + Some("refresh_token") + ); + + let (base, server) = stub_once(200, br#"{"sub":"account-7","email":"a@example.test"}"#).await; + let oauth = oauth(&base, Client::new()); + let info = oauth.userinfo("access-secret").await.unwrap(); + let request = String::from_utf8(server.await.unwrap()).unwrap(); + assert!(request.starts_with("GET /userinfo HTTP/1.1")); + assert!( + request + .to_ascii_lowercase() + .contains("authorization: bearer access-secret") + ); + assert_eq!(info.user_id.as_deref(), Some("account-7")); + assert_eq!(info.email.as_deref(), Some("a@example.test")); +} + +#[tokio::test] +async fn device_code_request_and_poll_use_real_eggfetch_requests() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut first, _) = listener.accept().await.unwrap(); + let first_request = read_request(&mut first).await; + write_response( + &mut first, + 200, + br#"{"device_code":"device-secret","user_code":"human-code","verification_uri":"https://accounts.test/activate","verification_uri_complete":"https://accounts.test/activate?user_code=human-code","expires_in":15,"interval":1}"#, + ) + .await; + drop(first); + + let (mut second, _) = listener.accept().await.unwrap(); + let second_request = read_request(&mut second).await; + write_response( + &mut second, + 200, + br#"{"access_token":"device-access","expires_in":3600}"#, + ) + .await; + (first_request, second_request) + }); + + let base = format!("http://{address}"); + let oauth = oauth(&base, Client::new()); + let device = oauth.request_device_code().await.unwrap(); + assert_eq!(device.user_code(), "human-code"); + assert_eq!(device.verification_uri(), "https://accounts.test/activate"); + let debug = format!("{device:?}"); + assert!(!debug.contains("device-secret")); + assert!(!debug.contains("human-code")); + let credentials = oauth + .poll_device_authorization( + &device, + &tokio_util::sync::CancellationToken::new(), + Duration::from_secs(3), + ) + .await + .unwrap(); + assert_eq!(credentials.access_token(), "device-access"); + + let (first, second) = server.await.unwrap(); + let first = String::from_utf8(first).unwrap(); + assert!(first.starts_with("POST /device HTTP/1.1")); + let first_body = first.split("\r\n\r\n").nth(1).unwrap(); + let first_form: std::collections::HashMap<_, _> = + url::form_urlencoded::parse(first_body.as_bytes()) + .into_owned() + .collect(); + assert_eq!( + first_form.get("client_id").map(String::as_str), + Some("public-client") + ); + + let second = String::from_utf8(second).unwrap(); + assert!(second.starts_with("POST /token HTTP/1.1")); + let second_body = second.split("\r\n\r\n").nth(1).unwrap(); + let second_form: std::collections::HashMap<_, _> = + url::form_urlencoded::parse(second_body.as_bytes()) + .into_owned() + .collect(); + assert_eq!( + second_form.get("device_code").map(String::as_str), + Some("device-secret") + ); + assert_eq!( + second_form.get("grant_type").map(String::as_str), + Some("urn:ietf:params:oauth:grant-type:device_code") + ); +} + +#[tokio::test] +async fn issued_client_id_is_exchanged_and_reused_after_registration() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let request = read_request(&mut stream).await; + write_response( + &mut stream, + 200, + br#"{"access_token":"registered-access","expires_in":3600}"#, + ) + .await; + request + }); + + let base = format!("http://{address}"); + let profile = OAuthProviderConfig::custom("registered", &base, "entry-client") + .authorization_endpoint(format!("{base}/authorize")) + .token_endpoint(format!("{base}/token")) + .callback_path("/callback") + .client_id_policy(ClientIdPolicy::IssuedOnRegistration) + .registration_parameter("agent_name_hint", "consumer") + .build() + .unwrap(); + let oauth = OAuthClient::new(Client::new(), profile); + let redirect = format!("{base}/callback"); + let pending = oauth.begin_authorization(&redirect, None).unwrap(); + let authorization_url = url::Url::parse(pending.authorization_url()).unwrap(); + let state = authorization_url + .query_pairs() + .find(|(key, _)| key == "state") + .map(|(_, value)| value.into_owned()) + .unwrap(); + let callback = + format!("{redirect}?code=registration-code&state={state}&client_id=issued-client"); + let credentials = oauth + .complete_authorization(pending, &callback) + .await + .unwrap(); + assert_eq!(credentials.client_id(), "issued-client"); + + let request = String::from_utf8(server.await.unwrap()).unwrap(); + assert!(request.starts_with("POST /token HTTP/1.1")); + let body = request.split("\r\n\r\n").nth(1).unwrap(); + let form: std::collections::HashMap<_, _> = url::form_urlencoded::parse(body.as_bytes()) + .into_owned() + .collect(); + assert_eq!( + form.get("client_id").map(String::as_str), + Some("issued-client") + ); + + let next = oauth + .begin_authorization(&redirect, Some(&credentials)) + .unwrap(); + let next_url = url::Url::parse(next.authorization_url()).unwrap(); + let next_values: std::collections::HashMap<_, _> = + next_url.query_pairs().into_owned().collect(); + assert_eq!( + next_values.get("client_id").map(String::as_str), + Some("issued-client") + ); + assert!(!next_values.contains_key("agent_name_hint")); +} + +#[tokio::test] +async fn non_json_error_does_not_escape_response_body() { + let (base, server) = stub_once(503, b"proxy diagnostic contains hidden-secret").await; + let oauth = oauth(&base, Client::new()); + let error = oauth + .refresh_token("refresh-secret", None) + .await + .unwrap_err(); + let request = server.await.unwrap(); + assert!(!request.is_empty()); + assert!(matches!(error, Error::HttpStatus { status: 503 })); + assert!(!error.to_string().contains("hidden-secret")); + assert!(!format!("{error:?}").contains("hidden-secret")); +} + +#[tokio::test] +async fn oauth_error_code_is_returned_without_description_or_body() { + let (base, server) = stub_once( + 400, + br#"{"error":"invalid_client","error_description":"hidden-secret details"}"#, + ) + .await; + let oauth = oauth(&base, Client::new()); + let error = oauth + .refresh_token("refresh-secret", None) + .await + .unwrap_err(); + let _ = server.await.unwrap(); + assert!(matches!(error, Error::OAuth { status: 400, .. })); + assert_eq!(error.oauth_code(), Some("invalid_client")); + assert!(!error.to_string().contains("hidden-secret")); + assert!(!format!("{error:?}").contains("hidden-secret")); +} + +#[tokio::test] +async fn decoded_body_limit_is_enforced_with_the_real_eggfetch_client() { + let (base, server) = stub_once( + 200, + b"{\"access_token\":\"this-response-is-over-the-limit\"}", + ) + .await; + let oauth = oauth(&base, Client::new()) + .with_options(options(Duration::from_secs(2), 16)) + .unwrap(); + let error = oauth + .refresh_token("refresh-secret", None) + .await + .unwrap_err(); + let _ = server.await.unwrap(); + assert!(matches!(error, Error::ResponseTooLarge)); +} + +#[tokio::test] +async fn request_deadline_is_normalized_without_transport_details() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let _ = read_request(&mut stream).await; + tokio::time::sleep(Duration::from_millis(250)).await; + let _ = write_response(&mut stream, 200, br#"{"access_token":"late"}"#).await; + }); + let oauth = oauth(&format!("http://{address}"), Client::new()) + .with_options(options(Duration::from_millis(50), 4096)) + .unwrap(); + let error = oauth + .refresh_token("refresh-secret", None) + .await + .unwrap_err(); + assert!(matches!(error, Error::Timeout("HTTP request"))); + server.await.unwrap(); +} + +#[tokio::test] +async fn redirects_are_not_followed_even_for_a_caller_owned_client() { + let (base, server) = stub_once(302, br#"{"next":"/redirected"}"#).await; + let oauth = oauth(&base, Client::new()); + let error = oauth + .refresh_token("refresh-secret", None) + .await + .unwrap_err(); + let request = String::from_utf8(server.await.unwrap()).unwrap(); + assert!(request.starts_with("POST /token HTTP/1.1")); + assert!(matches!(error, Error::HttpStatus { status: 302 })); +} + +#[derive(Clone, Default)] +struct MemoryStore(Arc>>); + +impl CredentialStore for MemoryStore { + fn load(&self) -> impl Future, StorageError>> + Send { + let inner = self.0.clone(); + async move { Ok(inner.lock().await.clone()) } + } + + fn save( + &self, + credentials: Credentials, + ) -> impl Future> + Send { + let inner = self.0.clone(); + async move { + *inner.lock().await = Some(credentials); + Ok(()) + } + } + + fn clear(&self) -> impl Future> + Send { + let inner = self.0.clone(); + async move { + *inner.lock().await = None; + Ok(()) + } + } +} + +#[tokio::test] +async fn manager_coalesces_concurrent_refresh_and_retains_rotated_refresh_token() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let first = read_request(&mut stream).await; + write_response( + &mut stream, + 200, + br#"{"access_token":"fresh-access","expires_in":3600}"#, + ) + .await; + let second = tokio::time::timeout(Duration::from_millis(100), listener.accept()).await; + (first, second.is_ok()) + }); + + let base = format!("http://{address}"); + let mut profile = OAuthProviderConfig::custom("stub", &base, "public-client") + .authorization_endpoint(format!("{base}/authorize")) + .token_endpoint(format!("{base}/token")) + .callback_path("/callback") + .scopes(["offline_access"]) + .build() + .unwrap(); + profile = profile.with_client_id("public-client").unwrap(); + let client = OAuthClient::new(Client::new(), profile); + let store = MemoryStore::default(); + let stale: Credentials = serde_json::from_str( + r#"{ + "access_token":"stale-access", + "refresh_token":"preserved-refresh", + "id_token":null, + "token_type":"Bearer", + "scope":"offline_access", + "client_id":"public-client", + "issuer":"PLACEHOLDER_ISSUER", + "expires_at":0, + "obtained_at":0 + }"# + .replace("PLACEHOLDER_ISSUER", &base) + .as_str(), + ) + .unwrap(); + store.save(stale).await.unwrap(); + let manager = Arc::new(TokenManager::new(client, store.clone())); + + let mut tasks = tokio::task::JoinSet::new(); + for _ in 0..12 { + let manager = manager.clone(); + tasks.spawn(async move { manager.access_token().await }); + } + while let Some(result) = tasks.join_next().await { + assert_eq!(result.unwrap().unwrap(), "fresh-access"); + } + + let (request, saw_second_refresh) = server.await.unwrap(); + assert!(request.starts_with(b"POST /token HTTP/1.1")); + assert!( + !saw_second_refresh, + "manager issued more than one refresh request" + ); + let header_end = request + .windows(4) + .position(|window| window == b"\r\n\r\n") + .expect("request contains the end of headers"); + let body = &request[header_end + 4..]; + let form: std::collections::HashMap<_, _> = + url::form_urlencoded::parse(body).into_owned().collect(); + assert_eq!( + form.get("refresh_token").map(String::as_str), + Some("preserved-refresh") + ); + let stored = store.load().await.unwrap().unwrap(); + assert_eq!(stored.access_token(), "fresh-access"); + assert_eq!(stored.refresh_token(), Some("preserved-refresh")); +} diff --git a/docs/README.md b/docs/README.md index b45cbe2..dcfc532 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,3 +19,4 @@ | Understand routing and security | [how-it-works.md](how-it-works.md) | | Fix an error | [troubleshooting.md](troubleshooting.md) | | Update eggpass | [updating.md](updating.md) | +| Use the Python `eggpass-auth` library | [Python auth guide](https://github.com/eggstack/eggpass/blob/main/python/eggpass-auth/README.md) | diff --git a/docs/commands.md b/docs/commands.md index 10c6f1e..213bb9e 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -153,7 +153,7 @@ eggpass croncheck ```sh eggpass update # install the latest release -eggpass update 0.2.0 # install an exact version +eggpass update 0.1.0 # install an exact version eggpass update --check # report the plan without changing files ``` diff --git a/docs/configuration.md b/docs/configuration.md index 03a14aa..7350fa8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -92,7 +92,7 @@ Use `eggpass host` and `eggpass port` to change a live server's address. These c | `eggpass.pid` | Daemon process ID and the address and port it serves. | | `eggpass.log` | Daemon log. | -The data directory and `credentials` directory are restricted to mode `0700`; credential and key files use `0600` on Unix-like systems. Keep any custom config file containing `api_key` private too. +The data directory and `credentials` directory are restricted to mode `0700`; credential and key files use `0600` on Unix-like systems. On Windows, daemon startup applies protected current-user-only ACLs to the data directory and `usage.key`, and fails closed if that protection cannot be established. A crash or forced termination may leave a stale `usage.key`; the next daemon start replaces it before serving. Keep any custom config file containing `api_key` private too. With the default data directory, xAI credentials may be read from `~/.grok/auth.json` when `credentials/xai.json` is absent. If an imported refresh token is rotated, eggpass stores its replacement in its own credential file; the Grok CLI's original file is not updated. Setting `EGGPASS_HOME` disables this import to keep the relocated installation isolated. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 2cca737..ca5de69 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -37,7 +37,11 @@ clients. Client keys are separate from provider credentials. `eggpass key add` shows a key once and stores only a salted hash. The key is checked locally on each -request. Add or revoke issued keys without restarting the server. +request. Add or revoke issued keys without restarting the server. The CLI's +usage request uses a separate private runtime Bearer credential, generated for +each daemon start and accepted only for a bodyless `GET /v1/usage`. It is not +stored in config or the regular key store, cannot authorize inference or other +routes, and cannot satisfy the regular-key startup requirement. ## Model routing and discovery diff --git a/docs/releasing.md b/docs/releasing.md index 5934180..410a73e 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -8,7 +8,9 @@ publication. ## Prerequisites - Push access to `eggstack/eggpass` and permission to run GitHub Actions. -- The repository secret `CARGO_REGISTRY_TOKEN` must contain a crates.io API token with the `publish` scope for `eggpass`. Do not put the token in a file, command line, or log. +- The repository secret `CARGO_REGISTRY_TOKEN` must authorize publishing the + crates.io package being released (`eggpass` or `eggpass-auth`). Do not put + the token in a file, command line, or log. - The release workflow is generated from `release/eggpack/`. Its pinned Eggpack revision is in `release/eggpack/github-policy.json`; CI checks the generated workflow for drift. ## Release identity and assets @@ -134,3 +136,25 @@ sign the manifest or binaries. manifest checks. - Never move or overwrite an existing published tag or release. A published crate version cannot be replaced; fixes require a new version. + +## Independently versioned auth releases + +### Rust crate + +`eggpass-auth` in `crates/eggpass-auth/Cargo.toml` is versioned separately from +the Eggpass CLI. Its release tag is `eggpass-auth-vX.Y.Z`. The +`publish-eggpass-auth.yml` workflow checks the tag against the crate version +and runs `cargo package`. A manual dispatch on an auth tag is verification-only; +crates.io publication runs only after a human publishes a GitHub release for +that exact tag. Publish the crate before the next Eggpass crates.io release +that depends on it, so Cargo can resolve the dependency. + +### Python distribution + +The Python package in `python/eggpass-auth` has its own version and uses the +`eggpass-auth-python-vX.Y.Z` tag. Keep `pyproject.toml` and its `Cargo.toml` +versions equal. The PyPI workflow validates five stable-ABI wheels (Linux +x86_64/aarch64, macOS x86_64/arm64, Windows x86_64) and an sdist; CI tests +them on CPython 3.11–3.15. Configure the PyPI Trusted Publisher and protected +GitHub `pypi` environment before first publication. A published matching GitHub +release triggers the verified-files publish job using PyPI Trusted Publishing. diff --git a/docs/updating.md b/docs/updating.md index 7d465f1..186d516 100644 --- a/docs/updating.md +++ b/docs/updating.md @@ -2,7 +2,7 @@ ```sh eggpass update # install the latest published release -eggpass update 0.2.0 # install an exact version +eggpass update 0.1.0 # install an exact version eggpass update --check # show the proposed update without changing anything ``` @@ -32,17 +32,19 @@ update process. ## Cargo installations -If you installed with Cargo, update with Cargo instead. The updater prints the -appropriate command. For a local checkout: +If you installed with Cargo, the updater refuses to replace that binary and +prints a command with `--locked --force --root` set to the detected Cargo +installation. Run that command unchanged so Cargo updates the correct +installation. For a default crates.io installation, the equivalent is: ```sh -cargo install --path . +cargo install eggpass --locked --force ``` -For the Git repository: +To reinstall from the current repository checkout instead: ```sh -cargo install eggpass --git https://github.com/eggstack/eggpass +cargo install --path . --locked --force ``` ## Exact versions and rollback diff --git a/plans/async-auth-library-implementation.md b/plans/async-auth-library-implementation.md new file mode 100644 index 0000000..d747527 --- /dev/null +++ b/plans/async-auth-library-implementation.md @@ -0,0 +1,143 @@ +# Async Auth Library Implementation Plan + +**Status:** Local implementation and validation complete. No public release or publication occurred or is authorized. + +**Basis:** [`async-auth-library-requirements.md`](../async-auth-library-requirements.md) and the existing Eggpass auth, provider, and release code cited below. + +## Goal + +Create a small, independently versioned public Rust crate—provisionally `eggpass-auth`—that lets downstream async applications reuse Eggpass’s OAuth behavior with their own `eggfetch_core::Client`, runtime, UI, and credential storage. Preserve Eggpass as a synchronous CLI/proxy; do not make its server or request path async as part of this work. + +## Proposed defaults to approve before implementation + +1. **Package boundary:** Add `crates/eggpass-auth` as a separate workspace package, not a library target inside the existing `eggpass` binary package. Give it its own version and crate metadata. Keep the root binary’s version and release identity independent. +2. **Dependency:** Target the researched Eggfetch 0.3 line directly and accept the temporary Eggfetch 0.2/0.3 dependency duplication from the updater unless updating `eggup-eggfetch` is independently justified. Recheck current versions and package availability before coding and again before publication. +3. **Core scope:** Include async authorization-code exchange, refresh, revocation, user-info, browser-authorization transaction creation/completion, device-code creation, and cancellable device polling. Return URLs and device instructions as data. Do not print, launch a browser, read stdin, bind loopback sockets, or create a runtime in the core crate. Consider loopback/browser conveniences only as a later optional adapter. +4. **Providers:** Ship focused built-in x.ai and OpenAI profiles plus a minimal documented custom OAuth profile. Preserve x.ai’s `referrer` behavior and device-flow support, and OpenAI’s registration-only parameters and issued-client-ID reuse. Do not expose the inference-oriented `ProviderSpec`. +5. **Credentials:** Make explicit-token operations and caller-owned storage the default. Add a generic storage seam for a manager only if it can preserve the existing refresh behavior; an Eggpass-compatible file adapter is optional and must not make the core assume `~/.config/eggpass/auth.json` or import Grok CLI paths. Document that in-process refresh coalescing is not a cross-process lock unless the storage contract provides coordination. +6. **Sync Eggpass adapter:** Before extracting or replacing the current sync auth path, prove a narrow host-owned async-to-sync bridge that does not create a runtime in the library or change the proxy/server architecture. If the bridge is unsafe or causes behavior regressions, pause that integration rather than rewrite the server or silently maintain two divergent OAuth implementations. +7. **Release boundary:** Version and publish the auth crate independently. Use an auth-specific release tag/workflow and ensure the existing root `publish-crates.yml` cannot treat an auth release as an Eggpass release. The current root publisher listens to all published releases, so this isolation is a required release-workflow change, not an assumption. + +These are recommended planning defaults, not decisions already made by the user. The scope, sync bridge, storage contract, Eggfetch alignment, and versioning choice are go/no-go decisions before implementation begins. + +## Stage 0 decisions and execution record + +The user asked to work through the plan in full. I am proceeding with the proposed defaults below; this authorizes local implementation and dry-run validation only, not a public release or crates.io publication. + +- Package: separate `crates/eggpass-auth` workspace member, independently versioned from the `eggpass` binary. Initial library version: `0.1.0`; auth release tags: `eggpass-auth-v0.1.0` and the same prefix for later versions. +- Eggfetch: use the `eggfetch-core` 0.3 line and accept temporary 0.2/0.3 duplication. Checked 2026-11-17: crates.io lists 0.3.0 as latest; it declares Rust 1.89. `eggup-eggfetch` 0.2.0 still requires `eggfetch-core ^0.2.0`. +- Scope: async token operations, auth-code transaction/callback completion, device flow, both built-in profiles, and custom OAuth configuration. Core creates no runtime and owns no UI, listener, filesystem path, or terminal interaction. +- Storage: caller-owned credentials by default, with a generic async credential-store seam and a manager whose single-flight guarantee is scoped to one manager instance/process. Eggpass’s filesystem adapter stays host-owned. +- Sync bridge: host-owned Tokio runtime calls the async library only at Eggpass’s synchronous auth boundary. The proxy/server remains synchronous. A local-stub bridge test is required before replacing the existing auth path. +- Provider profile parameters: preserve x.ai `referrer`/device flow and OpenAI registration-only `agent_name_hint`, resource parameters, and issued-client-ID reuse; support custom profiles. +- Release boundary: auth-specific tag/workflow; root publishing is limited to root `vX.Y.Z` tags. Validate package workflows dry-run only; do not create or publish a GitHub release. + +## Out of scope + +- Making Eggpass’s blocking HTTP server, upstream calls, daemon, or SSE path async. +- Replacing unrelated `ureq` uses in `src/upstream.rs`, `src/daemon.rs`, or usage reporting. +- Introducing embedded login pages, UI, browser launching, or terminal interaction into the public core. +- Live OAuth checks as a CI requirement. +- Publishing a crate, creating or publishing a GitHub release, or changing existing release artifacts/tags without a separate, fresh confirmation. + +## Staged work + +### Stage 0 — Resolve the implementation gates + +- Recheck `eggpass-auth` name availability, the current Eggfetch API/MSRV, and whether Eggup’s adapter has moved beyond Eggfetch 0.2.x. +- Choose the five defaults above or record alternatives. In particular, settle the manager/storage API and how synchronous Eggpass calls will drive the async library. +- Prototype only the sync bridge needed to establish feasibility; do not start extracting auth flows until it is demonstrated on the existing CLI path. +- Record the first crate version and tag convention separately from the Eggpass binary version. + +**Exit:** Decisions are explicit, the package name is available, dependency/MSRV compatibility is checked, and the sync bridge has a safe direction or is explicitly deferred. + +### Stage 1 — Establish the crate and public type boundary + +- Add the crate under `crates/eggpass-auth`, with a narrow dependency set, Rust 1.89 MSRV unless dependency revalidation changes it, a crate-local README/examples, and an explicit package include list. +- Add it to the Cargo workspace while preserving the existing root `eggpass` package, binary target, root package version, package include rules, and Eggpack identity. +- Define stable public modules and builders for `OAuthProviderConfig` and the client. Accept/clone a caller-supplied Eggfetch client; expose no Eggfetch response internals or Eggpass server/config modules. +- Define non-exhaustive public errors that carry useful status/OAuth codes but not arbitrary response bodies. Document ownership and `Send`/`Sync` guarantees. +- Ensure token-bearing values, device codes, pending authorization secrets, and stored credentials have redacted `Debug`; do not log secrets. + +**Exit:** The crate compiles independently and as a workspace member; a minimal consumer can construct a provider/client without importing Eggpass’s private modules. + +### Stage 2 — Port the async OAuth protocol client + +- Implement form/query encoding and provider-specific request parameters for authorization, token exchange, refresh, revocation, user-info, device-code creation, and polling. +- Make connect/read/total timeout policy explicit in configuration; do not accidentally inherit Eggfetch defaults. Bound response bodies and avoid blind retries for exchanges or refreshes, especially where refresh-token rotation may occur. +- Normalize status, OAuth, malformed-response, timeout, and network failures into the crate’s own errors. Avoid returning or displaying arbitrary response bodies. +- Preserve the current OAuth request semantics and the special OpenAI issued-client-ID lifecycle. + +**Exit:** Deterministic local-stub tests cover encoded parameters, success/error/non-JSON responses, timeout and oversized-body handling, and client-ID/registration behavior. + +### Stage 3 — Implement authorization and device-flow transactions + +- Implement an authorization transaction that returns an authorization URL and opaque pending state containing PKCE verifier, high-entropy state, nonce, redirect URI, and expected callback path. Completion validates state and the exact callback path before exchanging the code. Keep sensitive transaction fields private and redacted. +- Require PKCE S256; preserve nonce/state validation. A loopback listener, if added later, must bind only to loopback, use a short-lived random port, and close after completion; no embedded user-agent. +- Implement device-code start and async polling with caller-controlled cancellation/deadline. Return the verification URI and user code as values; validate verification hosts before presenting/opening them, and never log device codes. +- Follow RFC 8628 polling semantics: honor the server’s expiry rather than clamping short values to 60 seconds; after `slow_down`, add five seconds to the interval for subsequent polls. Cover `authorization_pending`, denial, expiry, and cancellation. + +**Exit:** Local deterministic tests verify PKCE/state/nonce, callback rejection cases, trusted-host checks, polling interval/deadline behavior, and cancellation. + +### Stage 4 — Add token lifecycle, storage seam, and Eggpass adapter + +- Provide token parsing/refresh independently from filesystem paths. If a manager is included, preserve proactive refresh skew, 401 compare-and-refresh, one refresh per process under concurrency, and merge behavior that retains the existing refresh token when rotation is omitted. +- Define whether storage operations are atomic and whether they coordinate across processes. A file adapter, if selected, must retain restrictive permissions and atomic replacement; do not imply that an in-process mutex is a cross-process lock. +- Complete the host-side Eggpass adapter only after the Stage 0 bridge is proven. Keep CLI prompts, browser launching, stdin handling, path resolution, Grok CLI import, and the synchronous `TokenProvider` interface in Eggpass host modules. Do not change the proxy server’s execution model. +- Resolve the current parity defects before calling the port complete: redact secret-bearing `Debug`, correct `slow_down` to the RFC-required five-second increase, and handle short server expiry values without the current 60-second minimum. + +**Exit:** Refresh rotation, concurrent refresh, storage guarantees, and the existing sync CLI integration pass focused regression tests without requiring downstream users to adopt Eggpass paths or UI. + +### Stage 5 — Downstream contract, CI, and package validation + +- Add a compiling downstream-style example that supplies an Eggfetch client and awaits authorization/refresh using the consumer’s runtime; it must not depend on Eggpass CLI/server modules. +- Run the library against a local OAuth stub using the real Eggfetch client. Keep provider-live tests opt-in and outside deterministic CI. +- Extend CI to format, lint, test, and package the workspace/library. Keep root binary tests and builds. Validate the library on supported platforms, including Windows if the selected storage adapter is cross-platform. +- Check dependency resolution explicitly for both Eggfetch lines and confirm `--locked` works. Run `cargo package --locked` for `eggpass-auth` and the existing root package; inspect the packaged file list for omissions or accidental inclusion. +- Verify all five existing Eggpass release targets before any later Eggpass binary release; library validation does not replace that release gate. + +**Exit:** Required protocol/security tests pass, the downstream example compiles, both packages pass locked packaging checks, and existing Eggpass CI/build/release behavior remains intact. + +### Stage 6 — Prepare a separate publication path (no publication in this plan) + +- Add an auth-specific, dry-run-first verification/publish path with independent version/tag validation and explicit package selection. +- Scope the existing root crates.io workflow to Eggpass release tags, and test that an auth-tagged release neither builds nor publishes the root `eggpass` crate. Keep the existing Eggpack binary release process and its draft-review-before-publish gate intact. +- Update maintainer release documentation with package-specific versioning, tag convention, package verification, and publication effects. Recheck crate-name availability and exact dependency versions before a first publish. +- Stop at a verified dry run. Any public GitHub release publication (which can trigger crates.io publication) requires separate, fresh user confirmation immediately before that action. + +**Exit:** Local package dry runs passed and workflow lint/source checks confirm the release boundary. A GitHub workflow dispatch was not run; no public release has been created or published. + +### Completion record + +- Passed on the local macOS host: `cargo fmt --all -- --check`, strict workspace Clippy, locked workspace tests (329 Eggpass, 30 auth unit, 10 local-stub tests), downstream example check, and locked Rust 1.89 workspace tests. +- Passed local package/build checks: `cargo package --locked --allow-dirty -p eggpass-auth`; root `eggpass` package verification with a local Cargo patch to `crates/eggpass-auth` (the auth crate is intentionally not yet on crates.io); and `cargo build --release --locked`. +- Passed `actionlint` on CI and both publisher workflows, ShellCheck on publisher shell snippets, and `git diff --check`. +- Not run: remote GitHub Actions dispatch, Windows MSVC job, or the five-target Eggpass release build. CI defines Windows 1.89 checks; all five targets remain mandatory before any future Eggpass binary release. +- No crate was published and no GitHub release was created. Publish `eggpass-auth` before any future Eggpass crates.io package release; the publisher workflows remain separately gated. + +## Acceptance checklist + +- [x] Public crate API accepts a caller-owned Eggfetch client, creates no runtime, owns no UI, and has no Eggpass home-directory assumption. +- [x] Built-in x.ai/OpenAI profiles and custom-provider configuration preserve required provider-specific parameters and issued-client-ID behavior. +- [x] PKCE S256, entropy, state/nonce and exact callback validation are tested; device verification URIs are host-checked. +- [x] Device polling handles pending, `slow_down` (+5 seconds), denial, actual expiry, timeout, and cancellation. +- [x] Timeouts, response-size bounds, error sanitization, retry rules, and secret-safe debug/log behavior are tested/documented. +- [x] Refresh preserves proactive skew, compare-and-refresh, one-process single-flight, and refresh-token rotation semantics; storage atomicity/cross-process guarantees are explicit. +- [x] Local OAuth stub tests use the real Eggfetch client; a downstream-style async consumer compiles without Eggpass application modules. +- [x] Root Eggpass sync behavior and server architecture are unchanged; the sync adapter bridge is proven or deferred explicitly. +- [x] Both packages pass formatting, lint, tests, and locked packaging; CI covers the selected platform/storage support. +- [x] Existing five-target Eggpass release gates remain intact; auth release tags cannot invoke root Eggpass publication; no public publication occurs without fresh confirmation. + +## Current code and research references + +- Requirements and dependency/version findings: [`async-auth-library-requirements.md`](../async-auth-library-requirements.md), especially sections “Recommendation and boundary,” “Security and protocol acceptance criteria,” and “Package, dependency, tests, and release work.” +- Private binary-only boundary: `src/main.rs:8-21`. +- Current synchronous OAuth client and secret-bearing token/device types: `src/auth/client.rs:51-67,130-180`. +- Browser/device flows, trusted verification URLs, expiry clamp, and current `slow_down` increment: `src/auth/flow.rs:127-289`. +- Refresh coalescing and rotated-token merge behavior: `src/auth/refresh.rs:67-225`. +- Current credential format, restrictive atomic file persistence, and Grok CLI import: `src/auth/store.rs:1-18,44-87,130-210`. +- Provider-specific profile behaviors: `src/provider/xai.rs:75-100`; `src/provider/openai.rs:149-198`. +- Existing root package metadata and explicit package include list: `Cargo.toml:1-28,30-77`. +- Existing root publisher trigger and root-only package/version checks: `.github/workflows/publish-crates.yml:10-19,41-61`. +- Eggpass binary release shape and human publication gate: `docs/releasing.md:22-115`; five-target candidate builds are in `.github/workflows/release.yml`. +- OAuth protocol references and Eggfetch API links are collected in the requirements memo. diff --git a/plans/python-pyo3-bindings-implementation.md b/plans/python-pyo3-bindings-implementation.md new file mode 100644 index 0000000..ae18ade --- /dev/null +++ b/plans/python-pyo3-bindings-implementation.md @@ -0,0 +1,124 @@ +# Python Bindings for `eggpass-auth` — Implementation Plan + +**Status:** Implemented locally. The macOS arm64 CPython 3.14 wheel and a clean sdist install pass; the separate Linux CI matrix is configured but not yet run. PyPI/crates.io publication remains out of scope. + +**Basis:** Current `eggpass-auth` API and the completed PyO3/UniFFI research. Preserve the existing Rust crate and its independent release boundary. + +## Implementation outcome + +- The separate package lives at `python/eggpass-auth`, imports as `eggpass_auth`, and builds the private `eggpass_auth._native` extension. It uses PyO3 0.30.1, `pyo3-async-runtimes` 0.30.0 with Tokio, Maturin 1.9.5, Rust 1.89, and the `abi3-py39` stable ABI. +- The Python Cargo crate is its own nested workspace. Because the canonical core crate is a member of the repository’s Cargo workspace, the Python package includes a source snapshot at `vendor/eggpass-auth`; `tools/sync_core.py --check` verifies it against `crates/eggpass-auth`. A narrow `.gitignore` exception ensures the snapshot is included in checkout/CI. The sdist packages it and installs without depending on the repository checkout. +- Python `TokenManager` and async storage callbacks are deferred. This implementation did not establish a robust atomic Python-store adapter; V1 exposes explicit credential and refresh operations only. +- Python task cancellation was tested to stop the polling future; it does not set a shared `CancellationToken`. Calling `CancellationToken.cancel()` explicitly produces the Rust cancellation result. +- Local wheel, sdist, integration tests, and type stubs were validated on macOS arm64 / CPython 3.14. The separate workflow configures Ubuntu x86_64 jobs for CPython 3.9 and 3.14, but those GitHub jobs have not run in this implementation session. Windows and other architectures are not qualified. + +## Goal + +Provide a supported Python package that reuses `eggpass-auth` OAuth protocol behavior from Python applications. Python callers should be able to await authorization, device-flow, token-refresh, and related operations from `asyncio`, while retaining ownership of UI, callback reception, and credential persistence. + +## Recommendation and proposed defaults + +1. **Binding technology:** Use PyO3 for the Python-native extension, `pyo3-async-runtimes` with its Tokio integration for Rust-future/Python-`asyncio` conversion, and Maturin for the Python package and wheels. The PyO3 v0.30.1 guide still marks its built-in `async fn` bindings as actively developing; use the dedicated runtime bridge unless a later review establishes a stable replacement. +2. **Package boundary:** Keep `crates/eggpass-auth` independent of Python and PyO3. Add a separate Python binding/package project under `python/eggpass-auth`, with a public `eggpass_auth` Python package and private `_native` module. The binding uses its own nested Cargo workspace and remains outside the root Cargo workspace. +3. **Async contract:** Export awaitable Python methods backed by Tokio. Never call `block_on` from Python methods and never create a fresh Tokio runtime per operation. Clone or move owned Rust values into `Send + 'static` futures; do not hold Python/GIL-bound borrows across Rust `.await` points. The Python caller’s event loop remains the public async interface. +4. **HTTP client ownership:** Python cannot pass an arbitrary Python HTTP session to `OAuthClient::new`, which requires a Rust `EggfetchClient`. The binding constructs and owns a Rust Eggfetch client and exposes the finite request timeout and decoded-body cap. V1 does not expose proxy, custom-root, or arbitrary transport settings; it does not imply that Python requests/aiohttp clients can be injected directly. +5. **V1 API:** Expose provider presets, validated custom profiles, `OAuthClient`, opaque pending authorization, credentials/token values, authorization-code operations, device-code operations, refresh/revoke/userinfo, and typed/sanitized errors. Leave browser launching, callback listeners, terminal/UI behavior, and filesystem paths to the Python host. Pass the full callback URL into Rust completion so existing origin/path/state/nonce checks remain authoritative. +6. **Credential storage:** Do not expose the generic Rust `CredentialStore` trait as though a Python class could implement it directly: it is generic/RPITIT-based and not object-safe (`crates/eggpass-auth/src/manager.rs:10-30`). Prototype a concrete binding-side Python-store adapter before promising Python `TokenManager` support. The adapter must safely bridge Python async `load`/`save`/`clear` callbacks into Tokio and preserve atomic whole-credential replacement. If that prototype is not robust, V1 should expose explicit refresh operations and credentials, leaving persistence and refresh orchestration to Python; record `TokenManager` support as a follow-up rather than changing the core trait solely for bindings. +7. **Versioning and release:** Version the Python distribution separately from the Rust crate. The package is `eggpass-auth` version `0.1.0`, targets CPython 3.9+ via `abi3-py39`, and uses PyO3 0.30.1 / `pyo3-async-runtimes` 0.30.0 with Maturin 1.9.5. Registry lookups found no existing `eggpass-auth` package on PyPI or crates.io; no publication workflow or release was added. + +## Current API constraints to preserve + +- `eggpass-auth` accepts a caller-owned Rust Eggfetch client and creates no runtime; the binding is the host adapter (`crates/eggpass-auth/src/lib.rs:1-9`; `crates/eggpass-auth/src/client.rs:72-80`). +- `PendingAuthorization` holds private PKCE verifier, state, nonce, client ID, and redirect information; it is one-use and its Rust `Debug` redacts sensitive fields (`crates/eggpass-auth/src/client.rs:99-118,544-575`). The Python wrapper must retain it as an opaque object, redact `repr`, and prevent reuse after completion. +- Device polling accepts a `CancellationToken` and caller timeout (`crates/eggpass-auth/src/client.rs:379-397`). Specify and test how Python cancellation signals that token; do not silently claim that cancelling an `asyncio.Task` has the same semantics until verified. +- `Credentials` is serializable for caller-owned storage but contains access, refresh, and ID tokens (`crates/eggpass-auth/src/token.rs:119-145`). Any Python serialization API is secret-bearing; document that callers must protect it. Python `repr`, logs, and exception messages must redact secrets. +- Rust errors intentionally omit response bodies, request URLs, authorization codes, and tokens (`crates/eggpass-auth/src/error.rs:38-42`). Map them to Python exception classes without adding those values back. +- `TokenManager` provides only per-manager/process single-flight, not cross-process coordination (`crates/eggpass-auth/src/manager.rs:33-43`). A Python store/manager adapter must not overstate that guarantee. + +## Staged work + +### Stage 0 — Prove the binding and resolve package gates + +- Recheck current PyO3, `pyo3-async-runtimes`, Maturin, Python, and Rust MSRV compatibility. The current core crate declares Rust 1.89 (`crates/eggpass-auth/Cargo.toml:1-5`); lock compatible versions rather than assuming the latest versions work together. +- Build a minimal extension prototype with one Rust async function returned through `pyo3_async_runtimes::tokio::future_into_py`; verify it is awaited inside a running `asyncio` event loop. Test event-loop reuse and the documented calling pattern; do not drive the returned awaitable with a second/nested event loop. +- Prototype cancellation for device polling, including normal completion, Python task cancellation, and explicit cancellation-token signaling. +- A Python async storage adapter was not proven safe and atomic in this implementation. V1 therefore defers `TokenManager` and exposes explicit credential and refresh operations without changing the core storage trait. +- The wheel uses `abi3-py39`. The sdist uses a self-contained `vendor/eggpass-auth` snapshot checked by `tools/sync_core.py`; a maintainer-only path outside the package is not required. Local macOS arm64 wheel/sdist installs passed; Ubuntu x86_64 CPython 3.9/3.14 checks are configured in CI but remain unrun, and Windows/other architectures remain unqualified. + +**Exit:** A minimal importable wheel calls an async Rust stub under `asyncio`; cancellation and event-loop behavior are understood; the store-adapter and sdist-source strategy are explicit. + +### Stage 1 — Establish the independent Python package + +- Add a separate binding crate and Maturin `pyproject.toml`; configure a mixed package such as `eggpass_auth._native` plus a small Python facade. +- Keep PyO3 and binding-only dependencies out of `crates/eggpass-auth/Cargo.toml` and the normal Rust workspace test path unless Stage 0 demonstrates a safe alternative. +- Add package metadata, license/readme inclusion, a `py.typed` marker and Python stubs or inline typing. Verify Cargo formatting, lint, and existing Rust CI remain unchanged. +- Ensure clean-checkout wheel and sdist builds work in isolation, including the selected source strategy for `eggpass-auth`. + +**Exit:** `import eggpass_auth` works after installing the built wheel in a clean environment; the sdist can rebuild without relying on files outside its declared contents. + +### Stage 2 — Bind the OAuth API and map lifecycle values + +- Wrap the Rust client and provider configuration in Python-facing types. Provide xAI and OpenAI profile constructors, the xAI compatibility profile, and a validated custom-profile builder that exposes only supported non-secret protocol parameters. +- Construct the Rust Eggfetch client inside the wrapper from explicit configuration; expose `ClientOptions`-equivalent request timeout and decoded-body cap. Document any transport settings that are not available in V1. +- Implement each network operation as an awaitable using the Tokio bridge. Keep `begin_authorization` synchronous if it remains purely local; make completion, exchange, refresh, revocation, userinfo, device-code request, and polling awaitable. +- Wrap `PendingAuthorization` as opaque, one-use state; completion consumes it and receives the full callback URL. Do not expose verifier/state/nonce or accept a callback code/state pair that bypasses Rust validation. +- Map `Credentials`, `TokenSet`, `DeviceCode`, `DevicePoll`, and `UserInfo` to typed Python values. Keep secret access explicit and `repr` redacted. Map `eggpass_auth::Error` variants into a Python exception hierarchy preserving only safe status/code facts. +- If Stage 0 approves the store adapter, expose a typed Python async store protocol through a concrete Rust adapter and then expose the core token manager. Otherwise limit V1 to explicit credential and refresh operations. + +**Exit:** Python API coverage matches the approved V1 scope; callback validation, refresh-token merge, cancellation, and error redaction match the Rust library’s behavior. + +### Stage 3 — Add Python integration and security tests + +- Add `pytest` tests that import the built extension and run under `asyncio`; use a local deterministic OAuth stub, not provider-live CI. +- Cover successful and rejected authorization callbacks (wrong origin/path/state, duplicate or missing query values, nonce mismatch), client-ID registration behavior, refresh-token rotation/omission, device pending/slow-down/denial/expiry/cancellation, and sanitized errors. +- Test one-use pending transactions, Python cancellation mapping, multiple operations on the same event loop, event-loop shutdown/recreation, and concurrent refresh behavior within the documented guarantee. +- Assert `repr`, exceptions, and captured logs do not contain access/refresh/ID tokens, authorization codes, device codes, PKCE verifier, state, nonce, or full authorization URLs. +- If storage callbacks are included, test atomic replacement and callback failures, and verify no cross-process guarantee is claimed. + +**Exit:** Rust local-stub tests and Python integration tests pass without provider access; existing Rust tests and sync Eggpass paths remain unchanged. + +### Stage 4 — Validate wheel/sdist and maintainer workflow + +- Build and install wheels for every declared OS/architecture/interpreter target. Use Maturin’s manylinux-compatible Linux build path; test the selected `abi3` or version-specific wheel strategy rather than assuming it eliminates platform-specific wheels. +- Build an sdist and install it in a clean environment; verify the Rust crate source and all build metadata are present or fetched from the selected immutable version source. +- Add a separate Python-package CI job for formatting/linting, Rust checks for the binding crate, Python typing, pytest, wheel build, sdist build, and clean installation. Do not make Python tooling a prerequisite for the existing Rust-only CI unless approved. +- Document API lifecycle, callback ownership, event-loop usage, transport limitations, secure persistence, Python cancellation, supported platforms/Python versions, and the difference between Rust crate and Python package versions. +- Stop at local/CI packaging validation. Do not add or run a PyPI publication workflow in this plan. + +**Exit:** The declared wheels and sdist build/install in clean environments; the current Rust workspace and release workflows remain unaffected; no public package is uploaded. + +## Out of scope + +- Adding PyO3 or Python runtime dependencies to the core `eggpass-auth` crate. +- Making Eggpass’s synchronous CLI, proxy server, or SSE path async. +- Python-owned browser launching, callback listener, UI, terminal prompts, or credential file paths. +- Accepting an arbitrary Python HTTP client as the Rust Eggfetch client. +- Publishing to PyPI, publishing a Rust crate, or changing the existing crates.io release workflows. +- UniFFI, CFFI, or raw C ABI support unless a future multi-language or non-CPython requirement justifies it. + +## Acceptance checklist + +- [x] The Python binding is a separate package; core `eggpass-auth` remains Python-free. +- [x] Awaitable Rust operations integrate with `asyncio` via the Tokio bridge; no nested `block_on` or per-call runtime is used. +- [x] The Python API owns/configures its Rust Eggfetch client explicitly and documents transport limitations. +- [x] Pending authorization stays opaque and one-use; callback validation remains inside Rust. +- [x] Device-flow cancellation, credentials, errors, and debug/repr behavior preserve the Rust security contract. +- [x] Python storage/`TokenManager` support is explicitly deferred; no object-safe Python trait is implied. +- [x] Local-stub Python tests cover authorization, refresh, device polling/cancellation, security, and event-loop behavior; provider-live calls are absent from CI. +- [ ] Full wheel/sdist platform-matrix validation remains pending: local macOS arm64 passes; Ubuntu x86_64 CPython 3.9/3.14 is configured but unrun; Windows and other architectures are unqualified. +- [x] Existing root Rust workspace checks pass; no PyPI or crates.io publication occurred. + +## Research references + +Local implementation and conventions: + +- Existing Rust API contract and example: `crates/eggpass-auth/README.md`, `crates/eggpass-auth/src/lib.rs`, `crates/eggpass-auth/src/client.rs`, `crates/eggpass-auth/src/token.rs`, `crates/eggpass-auth/src/manager.rs`, `crates/eggpass-auth/src/error.rs`, `crates/eggpass-auth/examples/downstream.rs`. +- Existing implementation plan and crate/workspace release context: `plans/async-auth-library-implementation.md`, `Cargo.toml`, `.github/workflows/ci.yml`. + +Current official binding and packaging guidance reviewed 2026-11-17: + +- [PyO3 async/await guide](https://pyo3.rs/v0.30.1/async-await) — native async binding status, future bounds, cancellation, interpreter attachment. +- [PyO3 ecosystem async guide](https://pyo3.rs/v0.30.1/ecosystem/async-await) — recommends `pyo3-async-runtimes` for Python/Rust async interoperability. +- [pyo3-async-runtimes](https://github.com/PyO3/pyo3-async-runtimes) — Tokio runtime integration and `future_into_py` pattern. +- [Maturin project layout](https://www.maturin.rs/project_layout), [bindings](https://www.maturin.rs/bindings), and [distribution](https://www.maturin.rs/distribution) — mixed packages, PyO3/UniFFI/CFFI modes, wheels, source distributions, and platform portability. +- [UniFFI async support](https://mozilla.github.io/uniffi-rs/0.32/futures.html) — async Python bindings and cancellation/runtime tradeoffs; retained as an alternative, not the proposed route. diff --git a/plans/python-pypi-release-implementation.md b/plans/python-pypi-release-implementation.md new file mode 100644 index 0000000..e0e33a5 --- /dev/null +++ b/plans/python-pypi-release-implementation.md @@ -0,0 +1,130 @@ +# Python `eggpass-auth` — PyPI Release Implementation Plan + +**Status:** Implementation prepared; local checks passed on macOS arm64 / CPython 3.14. The full GitHub target matrix, GitHub/PyPI publisher configuration, reviewed commit/tag/release, Raspberry Pi device check, and first public upload remain outstanding. This document and the implementation do not authorize publication. + +**Research checked:** 2026-11-17. + +**Scope:** Prepare the independent `python/eggpass-auth` distribution for a first PyPI release, with documented Python support, reviewed wheel coverage, and a secure, separate publish path. This extends the packaging/validation work in [`python-pyo3-bindings-implementation.md`](python-pyo3-bindings-implementation.md); it does not redo the binding implementation. + +## Goal + +Publish a reviewed `eggpass-auth` Python release with accurate package metadata and user documentation, tested distributions for a clearly defined set of CPython/platform targets, and an isolated PyPI Trusted Publishing workflow. Keep the Rust crate and Eggpass CLI release identities and workflows independent. + +This implementation prepares release-readiness files in the worktree. It does not authorize a public PyPI upload; the first upload requires fresh, explicit confirmation immediately before publication. + +## Pre-implementation baseline and known gaps + +The following records the state found during research, before the implementation described below. + +- `python/eggpass-auth/pyproject.toml` declares package `eggpass-auth` version `0.1.0`, `requires-python = ">=3.9"`, `readme = "README.md"`, and Python classifiers through 3.14. The README reference is correctly relative to the package root; keep it pointed at the package's auth-library guide rather than the root CLI README. +- The package README already has Python authorization-code, device-flow, and profile examples. `docs/README.md` does not currently link to that guide. Link the guide; do not duplicate or replace the root CLI README. +- `.github/workflows/python-auth.yml` tests Ubuntu x86_64 on Python 3.9 and 3.14 and separately builds/installs an sdist. The package README reports a local macOS arm64 / CPython 3.14 wheel and sdist install, but the GitHub workflow has not run; Windows and other architectures remain unqualified. +- The current binding enables PyO3 `abi3-py39` and `extension-module`, and CI pins Maturin 1.9.5. The stable ABI can reduce the number of per-Python-version wheels for GIL-enabled CPython, but each OS/architecture still needs its own wheel. PyO3's current guide recommends migrating away from `extension-module`; review this alongside the CI/build changes. +- The existing auth Rust publisher is crates.io-only and follows `eggpass-auth-vX.Y.Z`. There is no separate PyPI publisher in the checked workflow set. Do not reuse the Rust auth tag for Python releases. +- The observed worktree contains numerous modified and untracked files, including the Python package and workflows. Review and commit the intended release inputs explicitly; never stage the entire worktree as part of this plan. +- The live `https://pypi.org/pypi/eggpass-auth/json` endpoint returned `Not Found` on 2026-11-17. Treat this only as a point-in-time availability check, not a reservation or guarantee. + +## Approved first-release policy + +The user selected these support boundaries on 2026-11-17; metadata, docs, and CI should stay aligned with them. + +1. **Python policy:** Declare and test GIL-enabled CPython 3.11–3.15. Set `requires-python = ">=3.11"` and PyO3's stable ABI floor to `abi3-py311`; test the same `cp311-abi3` wheels on each supported CPython minor. Require Maturin `>=1.16.0,<2.0` and pin CI/release builds to 1.16.0. +2. **Free-threaded CPython 3.15:** Exclude 3.15t from the first-release claim. Reconsider only after separately building/testing the required `abi3t` wheels and auditing native thread-safety. +3. **Baseline PyPI wheels:** Target Linux x86_64 and aarch64, macOS x86_64 and arm64, and Windows x86_64, plus an sdist. Use the manylinux2014 compatibility target for Linux wheels. Musllinux and Windows arm64 are not included. +4. **32-bit ARM / Raspberry Pi:** The selected initial path is a Linux aarch64 wheel plus an sdist. Do not claim armv7l/armv6l or universal Raspberry Pi support; a compatible 64-bit Pi OS must still be checked on-device before claiming it as qualified. sdist and piwheels builds for Pi are not guaranteed until tested. Maturin supports additional targets, but PyPI ARM wheels must demonstrate portability beyond Raspberry Pi hardware. +5. **Release identity:** Keep the current Python package version `0.1.0` aligned between `pyproject.toml` and the binding crate manifest. Use `eggpass-auth-python-vX.Y.Z`, separate from `eggpass-auth-vX.Y.Z` and the root `vX.Y.Z` CLI tag, with a protected GitHub `pypi` environment. +6. **README/docs:** Keep `python/eggpass-auth/README.md` as the PyPI long-description source, preserve its Python auth-library examples, and link it from the docs index. Keep the root README focused on the CLI. + +The PyPI JSON endpoint returned `Not Found` when rechecked on 2026-11-17. This is not a name reservation or proof that the project will remain available. No PyPI Publisher or GitHub Environment configuration, tag, commit, GitHub release, TestPyPI upload, or PyPI upload has been performed by this implementation. + +## Implementation progress + +- **Stage 0 — Policy:** The user approved CPython 3.11–3.15 (GIL-enabled), the five-platform wheel matrix, a Linux aarch64 wheel plus sdist, and no 32-bit ARM/Pi or free-threaded claim. The PyPI name endpoint was rechecked; ownership and account settings still need maintainer action. +- **Stage 1 — Metadata/docs:** Updated Python minimum/classifiers, `abi3-py311`, Maturin build requirement, project URLs, package README support boundaries, docs index, and release instructions. The package-local auth guide remains the PyPI README; the root README was not changed. +- **Stage 2 — CI:** Authored wheel build/install tests for all five target platforms across CPython 3.11–3.15, plus isolated sdist build/install tests across those minors. Locally on macOS arm64 / CPython 3.14, Rust fmt/clippy/tests, Maturin 1.16.0 wheel and sdist builds, `twine check`, clean wheel/sdist installs, imports, `pip check`, mypy, pytest (4 passed each), and `maturin develop` passed. `actionlint` and `yamllint` pass. The GitHub matrix has not run, and no Raspberry Pi device or piwheels build was tested. +- **Stage 3 — Publisher:** Added a Python-only publisher with version/tag checks, read-only build/validation jobs, artifact/tag validation, verification-only manual dispatch, and OIDC permission isolated to the publish job. `actionlint`/`yamllint` pass. PyPI Trusted Publisher and protected GitHub environment/reviewer settings are not configured. +- **Stage 4 — Candidate:** Not complete. These files have not been committed or tagged; no GitHub release or TestPyPI/PyPI upload was created. The first upload remains gated on full CI/artifact review and fresh explicit user authorization. + +## Staged implementation + +### Stage 0 — Approve policy and confirm release boundary + +- Recheck PyPI project-name availability immediately before implementation; confirm who owns/configures the project and its Trusted Publisher. PyPI supports configuring a pending Trusted Publisher that creates a new project on its first successful upload. +- Approve the Python floor, supported Python builds (GIL-enabled only versus free-threaded 3.15), initial OS/architecture matrix, and Raspberry Pi/ARMv6 expectations. Record them once and use the same policy in metadata, docs, CI, and wheel filenames. +- Confirm the Python package version to publish and the independent tag format. Confirm root and crates.io workflows ignore Python release tags. +- Inventory the exact package/workflow/docs files intended for commit and keep unrelated worktree changes untouched. + +**Exit:** Name/ownership, version policy, platform scope, tag boundary, and non-publication implementation scope are explicit. + +### Stage 1 — Align metadata, README, and distribution contents + +- Update `requires-python`, Python classifiers, and PyO3 stable-ABI floor to the approved minimum; add the Python 3.15 classifier if 3.15 is in the supported range. Do not add a free-threaded claim unless Stage 0 selected it. +- Keep `readme = "README.md"` pointing to the package-local guide. Link the Python auth guide from `docs/README.md`; keep the root README focused on the Eggpass CLI. +- Review package classifiers, project URLs, license metadata/files, and version fields for completeness and consistency. Verify the sdist contains the package README, license, Rust binding source, lockfile as required, and self-contained vendored `eggpass-auth` source. +- Remove PyO3's deprecated `extension-module` feature. Require Maturin `>=1.16.0,<2.0` and pin CI/release builds to 1.16.0; validate Rust tests, wheel builds, sdist installs, and local development against that version. +- Add no unnecessary user-facing promises: distinguish compiled wheels, sdist/source builds, generic ARM, Raspberry Pi, and free-threaded Python support. + +**Exit:** Package metadata and PyPI long description accurately describe the released API and supported targets; an isolated sdist includes everything needed to build without repository-only paths. + +### Stage 2 — Expand and execute validation CI + +- Extend the Python test matrix to every supported minor version (recommended 3.11, 3.12, 3.13, 3.14, 3.15, GIL-enabled). Build the stable-ABI wheel per OS/architecture, then install and test it on each supported Python minor version; do not create redundant per-minor wheels unless the chosen ABI requires them. +- Build/install native wheels on Linux x86_64 and aarch64, macOS x86_64 and arm64, and Windows x86_64. Use Maturin's supported manylinux build path and a maintained Maturin action where appropriate. Keep build-only cross-compilation distinct from import/tests on a target runtime; use native runners or documented emulation where feasible. +- Run the existing Rust formatting/lint/tests, Python type checks, local-stub Python tests, and clean sdist build/install. Run the workflow on GitHub and record actual results; configuration alone is not qualification. +- Add armv7l and/or armv6l testing only for the explicitly selected ARM support path. Test on actual or representative generic ARM systems, not only Raspberry Pi. Before claiming Pi support from the sdist, confirm that piwheels can build this Rust package and verify a released version's build outcome; separately test 64-bit Pi OS against the aarch64 PyPI wheel. +- Check wheel tags, linked native dependencies and platform floors. Test clean installation/import on each target, not just wheel creation. Test the minimum Python version as well as 3.15. + +**Exit:** All advertised interpreters and wheels have clean install/import and test evidence; sdist rebuild works in an isolated environment; unqualified targets remain clearly excluded from claims. + +### Stage 3 — Add an isolated PyPI publication workflow + +- Create a dedicated Python-only publishing workflow. Build and validate the sdist/wheels in a separate job with read-only permissions; transfer only the verified artifacts to a narrowly scoped publish job. +- Use PyPI Trusted Publishing via GitHub OIDC and the official `pypa/gh-action-pypi-publish@release/v1`. Grant `id-token: write` only to the publish job, not the workflow or build matrix. Use the exact repository/workflow/environment in the PyPI Trusted Publisher configuration and a protected `pypi` GitHub environment, with required reviewer approval if available. +- Validate the release tag against the Python package version and reject the Rust auth tag, root Eggpass tags, branches, pull requests, and mismatched versions. A dry-run/manual validation path must be incapable of uploading, even if an input is changed. Do not add long-lived PyPI API tokens. +- Publish only prebuilt, reviewed artifacts; keep the publish job free of checkout/build steps so code execution is minimized near OIDC credentials. Use PyPI's automatic attestations from the official publishing action and retain artifact/build provenance where practical. +- Test the workflow with a safe non-production path (for example, a separately configured TestPyPI publisher) if needed. Never assume TestPyPI metadata or package state is shared with PyPI. +- Update maintainer release guidance with the Python version/tag convention, exact workflow procedure, artifact review, OIDC configuration, and distinction from Rust/crate releases. + +**Exit:** Workflow/static checks prove the only eligible publish path is the intended protected Python release; no root or crates.io release action is triggered by its tag; no credentials are stored. + +### Stage 4 — Prepare and review the first release candidate (no upload in this plan) + +- Ensure the Python package, CI, docs links, and publisher are included in a reviewed commit. Do not tag uncommitted/untracked content or include unrelated worktree changes. +- Build the exact release commit's sdist and wheels; run `twine check` (or equivalent metadata validation), inspect the rendered long description, confirm filenames/tags, and install from the artifacts in clean environments. +- Recheck PyPI name availability and configure the exact pending/normal Trusted Publisher. Inspect the release tag, package version, files, attestation configuration, and protected environment before the publish job can run. +- Stop before the first public upload until the user gives fresh, explicit confirmation. A published file/version cannot be overwritten; fix mistakes with a new version or yank where appropriate, not by reusing the same version. + +**Exit:** Candidate artifacts and workflow are reviewed and ready; publication remains unperformed and separately gated. + +## Acceptance checklist + +- [x] Python minimum, classifiers, ABI floor, GIL/free-threaded scope, and OS/architecture promises agree. +- [x] Python examples remain in the package README; docs index links to it; root README remains the CLI guide. +- [ ] Clean sdist and every advertised wheel build, install, import, and pass the package checks on the stated target matrix. +- [ ] Linux x86_64/aarch64, macOS x86_64/arm64, and Windows x86_64 are qualified for the chosen CPython range; ARMv7/armv6/Pi coverage is separately evidenced or explicitly excluded. +- [x] Local-stub tests and type checks pass; package source is self-contained; no provider-live OAuth tests are needed for CI. +- [ ] Publisher is PyPI Trusted Publishing/OIDC, protected by an exact environment/tag/version boundary; only the publish job has OIDC permission; no long-lived token is used. +- [x] Python release tag cannot trigger root Eggpass or crates.io publication. +- [ ] First release artifact review is complete; no upload occurs without fresh explicit user confirmation. + +## Remaining scope boundaries + +- No commit, push, tag, GitHub release, TestPyPI upload, PyPI Publisher/GitHub Environment configuration, or PyPI upload was performed. The first upload needs fresh, explicit user authorization. +- Unrelated worktree changes were preserved. Review and stage only the intended package/workflow/docs changes; do not stage the whole worktree. +- Do not claim ARMv6, 32-bit ARM/Pi wheels, universal Raspberry Pi support, musllinux, Windows ARM64, PyPy, or free-threaded Python 3.15. A compatible 64-bit Pi still requires an actual device/OS check. +- Do not modify the Rust crate API or merge Python versioning into the Rust/CLI release process. + +## Research references + +Repository evidence: + +- [`python-pyo3-bindings-implementation.md`](python-pyo3-bindings-implementation.md) — current binding plan and pending platform validation. +- `python/eggpass-auth/pyproject.toml`, `python/eggpass-auth/README.md`, `python/eggpass-auth/Cargo.toml`, `.github/workflows/python-auth.yml`, `.github/workflows/publish-eggpass-auth-pypi.yml`, `.github/workflows/publish-eggpass-auth.yml`, `docs/README.md`, and `docs/releasing.md`. + +External guidance checked 2026-11-17: + +- [Python version status](https://devguide.python.org/versions/) — lifecycle of Python 3.11–3.15. +- [PyO3 0.30.1 building and distribution](https://pyo3.rs/v0.30.1/building-and-distribution) and [features](https://pyo3.rs/v0.30.1/features.html) — `abi3`, `abi3t`, minimum versions, and Maturin requirements; [FAQ](https://pyo3.rs/v0.30.1/faq) — migration away from `extension-module`. +- [Maturin platform support](https://www.maturin.rs/platform_support), [Maturin action](https://github.com/PyO3/maturin-action), and [Maturin changelog](https://www.maturin.rs/changelog) — target support, CI building, and current Python 3.15/stable-ABI fixes in 1.16.0. +- [piwheels FAQ](https://www.piwheels.org/faq.html) — Raspberry Pi build availability, 32-/64-bit OS limits, and caution about publishing Raspberry-Pi-built ARM wheels to PyPI for broader ARM audiences. +- [Adding a PyPI Trusted Publisher](https://docs.pypi.org/trusted-publishers/adding-a-publisher/), [publishing with one](https://docs.pypi.org/trusted-publishers/using-a-publisher/), [security model](https://docs.pypi.org/trusted-publishers/security-model/), and [producing attestations](https://docs.pypi.org/attestations/producing-attestations/) — OIDC, least-privilege publish jobs, protected environments, and automatic attestations. diff --git a/python/eggpass-auth/Cargo.lock b/python/eggpass-auth/Cargo.lock new file mode 100644 index 0000000..62d2203 --- /dev/null +++ b/python/eggpass-auth/Cargo.lock @@ -0,0 +1,1333 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "eggfetch-core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c22bdfc6ab683ddf5d5fcf0321b60dfc86c0ec1311284a33c31f536d12c1d2ae" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "getrandom 0.2.17", + "http", + "http-body", + "http-body-util", + "httpdate", + "hyper", + "hyper-rustls", + "hyper-util", + "pem-rfc7468", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-native-certs", + "thiserror", + "tokio", + "tokio-rustls", + "tower-service", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "eggpass-auth" +version = "0.1.0" +dependencies = [ + "base64", + "eggfetch-core", + "rand", + "serde", + "serde_json", + "sha2", + "tempfile", + "tokio", + "tokio-util", + "url", +] + +[[package]] +name = "eggpass-auth-python" +version = "0.1.0" +dependencies = [ + "eggpass-auth", + "pyo3", + "pyo3-async-runtimes", + "serde_json", +] + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "log", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "libc", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "pem-rfc7468" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "801ef81ab8a21fdd738a9de457509b5c0aef72efa93ffdfc80f3329a1588405b" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pyo3" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229ca13b8a15bb0d1487b81ab975bfcd97513416499a8312011b6036e42e0de4" +dependencies = [ + "libc", + "once_cell", + "portable-atomic", + "pyo3-build-config", + "pyo3-ffi", + "pyo3-macros", +] + +[[package]] +name = "pyo3-async-runtimes" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b877331c7817ccb6379e9d19a06993160141f1d0a386e55276128717df85e3fc" +dependencies = [ + "futures-channel", + "futures-util", + "once_cell", + "pin-project-lite", + "pyo3", + "tokio", +] + +[[package]] +name = "pyo3-build-config" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70130e2b6dd1ee589a8788026a429561ca5c40fa7a2fa7914c2282eddae24700" +dependencies = [ + "target-lexicon", +] + +[[package]] +name = "pyo3-ffi" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e7ff73c555c286d212d4ce7e5fbda845a973c4f61bd5f160f5f2c3c2a04d1c4" +dependencies = [ + "libc", + "pyo3-build-config", +] + +[[package]] +name = "pyo3-macros" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c46d2e5862c7bb8207e3b639f713dda3c499933444784154c11d013c5a691b60" +dependencies = [ + "proc-macro2", + "pyo3-macros-backend", + "quote", + "syn", +] + +[[package]] +name = "pyo3-macros-backend" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b89f066f2ae72a2aef52d1537ca2fcd104440ebfadee06e97aa90738a25b9b" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "target-lexicon" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "futures-util", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/python/eggpass-auth/Cargo.toml b/python/eggpass-auth/Cargo.toml new file mode 100644 index 0000000..89d96d4 --- /dev/null +++ b/python/eggpass-auth/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "eggpass-auth-python" +version = "0.1.0" +edition = "2024" +rust-version = "1.89" +description = "Python asyncio bindings for eggpass-auth" +license = "MIT" +repository = "https://github.com/eggstack/eggpass" +documentation = "https://github.com/eggstack/eggpass/tree/main/python/eggpass-auth" + +[workspace] +members = [".", "vendor/eggpass-auth"] +resolver = "3" + +[lib] +name = "_native" +crate-type = ["cdylib"] + +[dependencies] +eggpass-auth = { path = "vendor/eggpass-auth" } +pyo3 = { version = "=0.30.1", features = ["abi3-py311"] } +pyo3-async-runtimes = { version = "=0.30.0", features = ["tokio-runtime"] } +serde_json = "1.0" diff --git a/python/eggpass-auth/LICENSE b/python/eggpass-auth/LICENSE new file mode 100644 index 0000000..329eea1 --- /dev/null +++ b/python/eggpass-auth/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 David Bowman + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python/eggpass-auth/README.md b/python/eggpass-auth/README.md new file mode 100644 index 0000000..adbf1a8 --- /dev/null +++ b/python/eggpass-auth/README.md @@ -0,0 +1,86 @@ +# `eggpass-auth` for Python + +This package exposes the Rust `eggpass-auth` OAuth client to Python `asyncio` through PyO3, `pyo3-async-runtimes`, and Tokio. The Rust protocol implementation remains a separate, Python-free crate. The Python distribution is versioned independently. + +## Build and test locally + +From this directory, use a virtual environment and install the local package: + +```sh +python3 -m venv .venv +. .venv/bin/activate +python -m pip install maturin pytest +maturin develop +pytest +``` + +A regular `pip install .` or a Maturin wheel build compiles the extension. The package uses PyO3's `abi3-py311` stable ABI for GIL-enabled CPython. The GitHub Actions matrix builds Linux x86_64/aarch64 wheels with manylinux2014 (glibc), macOS x86_64/arm64 wheels, and a Windows x86_64 wheel; it tests each wheel on CPython 3.11–3.15. The workflows do not build musllinux wheels. Treat a platform as supported for a release only after the corresponding build and wheel-install tests pass. + +The workflows do not build free-threaded CPython 3.15t or 32-bit ARM wheels (including armv6l/armv7l Raspberry Pi wheels). A compatible 64-bit Raspberry Pi OS may be able to use the Linux aarch64 wheel, but that combination is not separately qualified. Building from source requires a working Rust toolchain and the platform's native build prerequisites. + +## Authorization-code flow + +The host application owns browser launching, the callback listener/UI, and credential persistence. Pass the full callback URL to Rust so it can validate the origin, exact path, state, and OIDC nonce: + +```python +from eggpass_auth import OAuthClient, ProviderProfile + +oauth = OAuthClient(ProviderProfile.xai()) +pending = oauth.begin_authorization("http://127.0.0.1:43123/callback") +print("Open this URL in the host UI:", pending.authorization_url) + +async def complete_from_host_callback(callback_url: str): + # The host passes the full URL received by its loopback listener. + return await oauth.complete_authorization(pending, callback_url) +``` + +`PendingAuthorization` is opaque and one-use. Its `repr` never prints the authorization URL or PKCE/state/nonce values. Completion consumes it even if validation or the network request fails. Do not parse the callback into a code/state pair and bypass the full-URL validation. + +For pasted-code flows, use `complete_authorization_with_code`. The lower-level `exchange_authorization_code` method is also available when the host intentionally manages PKCE material itself. + +## Device flow and cancellation + +```python +from eggpass_auth import CancellationToken, OAuthClient, ProviderProfile + +async def device_login(): + oauth = OAuthClient(ProviderProfile.xai()) + device = await oauth.request_device_code() + print(device.user_code, device.verification_uri) + cancellation = CancellationToken() + try: + return await oauth.poll_device_authorization( + device, cancellation, timeout_seconds=600 + ) + finally: + cancellation.cancel() +``` + +Pass a `CancellationToken` when the host needs to stop the Rust polling loop explicitly. Cancelling an `asyncio.Task` should not be treated as a signal to every shared token; call `cancel()` on the token. No Python polling or networking work blocks the event loop. + +## Profiles and transport + +`ProviderProfile.xai()`, `ProviderProfile.xai_compatibility_fallback()`, and `ProviderProfile.openai()` provide the built-in profiles. Custom profiles are validated by the Rust provider builder: + +```python +profile = ProviderProfile.custom("Example", "https://auth.example", "public-client") +profile.authorization_endpoint("https://auth.example/authorize") +profile.token_endpoint("https://auth.example/token") +profile.callback_path("/callback") +profile.scopes(["offline_access"]) +profile = profile.build() +``` + +`OAuthClient` constructs and owns its Rust Eggfetch client. It accepts a finite `timeout_seconds` and a positive `max_response_body_bytes`; a Python `requests`, `httpx`, or `aiohttp` session cannot be injected. V1 does not expose custom proxy, root-certificate, or arbitrary transport configuration. OAuth requests suppress inherited default authentication, disable redirects and retries, and use bounded response bodies. + +## Credentials and errors + +Token fields are available explicitly when the host needs to persist or use them. `Credentials.to_json()` and `Credentials.from_json()` are secret-bearing storage APIs: protect their output and do not log it. `repr()` for credentials, token sets, pending authorizations, device codes, and clients redacts secrets and sensitive URLs. Exceptions expose only safe protocol facts; OAuth errors provide a recognized `code` and HTTP `status` when available. + +Python owns persistence and refresh scheduling in V1. The Rust generic async `CredentialStore` / `TokenManager` API is not exposed: an async Python storage adapter has not been proven safe or atomic. `refresh_token()` returns provider tokens; `refresh_credentials()` merges them while retaining the old refresh token if rotation was omitted. Persist the returned credentials yourself. Rust single-flight management is therefore not claimed for Python callers. + +All network operations are awaitable on the caller's running `asyncio` loop. Do not start a nested event loop or call `block_on`. Browser/UI, callback reception, and filesystem paths remain with the host application. + +## Packaging scope + +The sdist includes a self-contained snapshot of the local `eggpass-auth` crate, so it builds without a published Rust crate. In the monorepo checkout, `vendor/eggpass-auth` is generated from `../../crates/eggpass-auth`; run `python tools/sync_core.py --check` to verify it, or `python tools/sync_core.py --sync` after intentional core changes. Python releases use a separate `eggpass-auth-python-vX.Y.Z` tag and PyPI Trusted Publishing workflow; they do not publish the Rust crate or Eggpass CLI. Publishing remains gated by the protected `pypi` GitHub environment. diff --git a/python/eggpass-auth/pyproject.toml b/python/eggpass-auth/pyproject.toml new file mode 100644 index 0000000..a52c037 --- /dev/null +++ b/python/eggpass-auth/pyproject.toml @@ -0,0 +1,43 @@ +[build-system] +requires = ["maturin>=1.16.0,<2.0"] +build-backend = "maturin" + +[project] +name = "eggpass-auth" +version = "0.1.0" +description = "Async Python bindings for the eggpass-auth OAuth client" +readme = "README.md" +requires-python = ">=3.11" +license = "MIT" +license-files = ["LICENSE"] +keywords = ["oauth", "oauth2", "asyncio", "authentication", "pyo3"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Framework :: AsyncIO", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: 11", + "Programming Language :: Python :: 3 :: 12", + "Programming Language :: Python :: 3 :: 13", + "Programming Language :: Python :: 3 :: 14", + "Programming Language :: Python :: 3 :: 15", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Rust", + "Topic :: Security", +] + +[project.urls] +Homepage = "https://github.com/eggstack/eggpass" +Documentation = "https://github.com/eggstack/eggpass/tree/main/python/eggpass-auth" +Repository = "https://github.com/eggstack/eggpass" +Issues = "https://github.com/eggstack/eggpass/issues" + +[tool.maturin] +manifest-path = "Cargo.toml" +module-name = "eggpass_auth._native" +bindings = "pyo3" +python-source = "src" +strip = true + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/python/eggpass-auth/src/eggpass_auth/__init__.py b/python/eggpass-auth/src/eggpass_auth/__init__.py new file mode 100644 index 0000000..527da4b --- /dev/null +++ b/python/eggpass-auth/src/eggpass_auth/__init__.py @@ -0,0 +1,70 @@ +"""Async Python bindings for the eggpass-auth OAuth protocol client. + +This package owns a Rust Eggfetch client. It does not launch a browser, listen +for callbacks, or persist credentials; those remain responsibilities of the +Python host application. +""" + +from ._native import ( + CallbackMismatchError, + CancellationToken, + CredentialStorageError, + Credentials, + DeviceCode, + DeviceExpiredError, + DevicePoll, + EggpassAuthError, + HttpStatusError, + InvalidConfigurationError, + InvalidResponseError, + NoRefreshTokenError, + NonceMismatchError, + NotLoggedInError, + OAuthClient, + OAuthError, + OperationCancelledError, + OperationTimeoutError, + PendingAuthorization, + ProviderBuilder, + ProviderDeniedError, + ProviderProfile, + ResponseTooLargeError, + StateMismatchError, + TokenSet, + TransportError, + UntrustedVerificationUrlError, + UnsupportedOperationError, + UserInfo, +) + +__all__ = [ + "CallbackMismatchError", + "CancellationToken", + "CredentialStorageError", + "Credentials", + "DeviceCode", + "DeviceExpiredError", + "DevicePoll", + "EggpassAuthError", + "HttpStatusError", + "InvalidConfigurationError", + "InvalidResponseError", + "NoRefreshTokenError", + "NonceMismatchError", + "NotLoggedInError", + "OAuthClient", + "OAuthError", + "OperationCancelledError", + "OperationTimeoutError", + "PendingAuthorization", + "ProviderBuilder", + "ProviderDeniedError", + "ProviderProfile", + "ResponseTooLargeError", + "StateMismatchError", + "TokenSet", + "TransportError", + "UntrustedVerificationUrlError", + "UnsupportedOperationError", + "UserInfo", +] diff --git a/python/eggpass-auth/src/eggpass_auth/__init__.pyi b/python/eggpass-auth/src/eggpass_auth/__init__.pyi new file mode 100644 index 0000000..1b4368f --- /dev/null +++ b/python/eggpass-auth/src/eggpass_auth/__init__.pyi @@ -0,0 +1,151 @@ +from typing import Optional, Sequence + +class EggpassAuthError(Exception): ... +class InvalidConfigurationError(EggpassAuthError): ... +class InvalidResponseError(EggpassAuthError): ... +class HttpStatusError(EggpassAuthError): + status: int +class OAuthError(EggpassAuthError): + status: int + code: str +class ProviderDeniedError(EggpassAuthError): + code: str +class CallbackMismatchError(EggpassAuthError): ... +class StateMismatchError(EggpassAuthError): ... +class NonceMismatchError(EggpassAuthError): ... +class ResponseTooLargeError(EggpassAuthError): ... +class TransportError(EggpassAuthError): ... +class OperationTimeoutError(EggpassAuthError): ... +class UnsupportedOperationError(EggpassAuthError): ... +class DeviceExpiredError(EggpassAuthError): ... +class OperationCancelledError(EggpassAuthError): ... +class UntrustedVerificationUrlError(EggpassAuthError): ... +class NotLoggedInError(EggpassAuthError): ... +class NoRefreshTokenError(EggpassAuthError): ... +class CredentialStorageError(EggpassAuthError): ... + +class ProviderProfile: + @staticmethod + def xai() -> ProviderProfile: ... + @staticmethod + def xai_compatibility_fallback() -> ProviderProfile: ... + @staticmethod + def openai(host_id: Optional[str] = ...) -> ProviderProfile: ... + @staticmethod + def custom(display_name: str, issuer: str, client_id: str) -> ProviderBuilder: ... + @property + def display_name(self) -> str: ... + @property + def issuer(self) -> str: ... + @property + def callback_path(self) -> str: ... + @property + def scopes(self) -> list[str]: ... + @property + def client_id_policy(self) -> str: ... + +class ProviderBuilder: + def authorization_endpoint(self, value: str) -> None: ... + def token_endpoint(self, value: str) -> None: ... + def device_authorization_endpoint(self, value: str) -> None: ... + def userinfo_endpoint(self, value: str) -> None: ... + def revocation_endpoint(self, value: str) -> None: ... + def callback_path(self, value: str) -> None: ... + def scopes(self, values: Sequence[str]) -> None: ... + def client_id_policy(self, value: str) -> None: ... + def authorization_parameter(self, name: str, value: str) -> None: ... + def registration_parameter(self, name: str, value: str) -> None: ... + def token_parameter(self, name: str, value: str) -> None: ... + def device_parameter(self, name: str, value: str) -> None: ... + def trusted_device_hosts(self, hosts: Sequence[str]) -> None: ... + def build(self) -> ProviderProfile: ... + +class OAuthClient: + def __init__(self, profile: ProviderProfile, timeout_seconds: int = ..., max_response_body_bytes: int = ...) -> None: ... + @property + def provider(self) -> ProviderProfile: ... + def begin_authorization(self, redirect_uri: str, existing: Optional[Credentials] = ...) -> PendingAuthorization: ... + async def complete_authorization(self, pending: PendingAuthorization, callback_url: str) -> Credentials: ... + async def complete_authorization_with_code(self, pending: PendingAuthorization, code: str) -> Credentials: ... + async def exchange_authorization_code(self, code: str, redirect_uri: str, code_verifier: str, client_id: Optional[str] = ...) -> Credentials: ... + async def refresh_token(self, refresh_token: str, client_id: Optional[str] = ...) -> TokenSet: ... + async def refresh_credentials(self, credentials: Credentials) -> Credentials: ... + async def revoke(self, token: str, client_id: Optional[str] = ...) -> None: ... + async def userinfo(self, access_token: str) -> UserInfo: ... + async def request_device_code(self) -> DeviceCode: ... + async def poll_device_code(self, device: DeviceCode) -> DevicePoll: ... + async def poll_device_authorization(self, device: DeviceCode, cancellation: Optional[CancellationToken] = ..., timeout_seconds: int = ...) -> Credentials: ... + +class PendingAuthorization: + @property + def authorization_url(self) -> str: ... + @property + def consumed(self) -> bool: ... + +class Credentials: + @property + def access_token(self) -> str: ... + @property + def refresh_token(self) -> Optional[str]: ... + @property + def id_token(self) -> Optional[str]: ... + @property + def token_type(self) -> str: ... + @property + def scope(self) -> Optional[str]: ... + @property + def client_id(self) -> str: ... + @property + def issuer(self) -> str: ... + @property + def expires_at(self) -> Optional[int]: ... + @property + def obtained_at(self) -> int: ... + def is_fresh(self, now_unix: Optional[int] = ..., skew_seconds: int = ...) -> bool: ... + def to_json(self) -> str: ... + @staticmethod + def from_json(serialized: str) -> Credentials: ... + +class TokenSet: + @property + def access_token(self) -> str: ... + @property + def refresh_token(self) -> Optional[str]: ... + @property + def id_token(self) -> Optional[str]: ... + @property + def token_type(self) -> str: ... + @property + def scope(self) -> Optional[str]: ... + @property + def expires_at(self) -> Optional[int]: ... + +class DeviceCode: + @property + def user_code(self) -> str: ... + @property + def verification_uri(self) -> str: ... + @property + def verification_uri_complete(self) -> Optional[str]: ... + @property + def expires_in_seconds(self) -> float: ... + @property + def interval_seconds(self) -> float: ... + +class DevicePoll: + @property + def status(self) -> str: ... + @property + def tokens(self) -> Optional[TokenSet]: ... + +class UserInfo: + @property + def user_id(self) -> Optional[str]: ... + @property + def email(self) -> Optional[str]: ... + +class CancellationToken: + def __init__(self) -> None: ... + def cancel(self) -> None: ... + @property + def is_cancelled(self) -> bool: ... diff --git a/python/eggpass-auth/src/eggpass_auth/py.typed b/python/eggpass-auth/src/eggpass_auth/py.typed new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/python/eggpass-auth/src/eggpass_auth/py.typed @@ -0,0 +1 @@ + diff --git a/python/eggpass-auth/src/lib.rs b/python/eggpass-auth/src/lib.rs new file mode 100644 index 0000000..acad76b --- /dev/null +++ b/python/eggpass-auth/src/lib.rs @@ -0,0 +1,897 @@ +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use eggpass_auth::{ + CancellationToken, ClientIdPolicy, ClientOptions, Credentials, DeviceCode, DevicePoll, Error, + OAuthClient, OAuthProviderConfig, PendingAuthorization, TokenSet, UserInfo, +}; +use pyo3::create_exception; +use pyo3::exceptions::PyException; +use pyo3::prelude::*; +use pyo3::types::PyModule; +use pyo3_async_runtimes::tokio::future_into_py; + +create_exception!(_native, EggpassAuthError, PyException); +create_exception!(_native, InvalidConfigurationError, EggpassAuthError); +create_exception!(_native, InvalidResponseError, EggpassAuthError); +create_exception!(_native, HttpStatusError, EggpassAuthError); +create_exception!(_native, OAuthError, EggpassAuthError); +create_exception!(_native, ProviderDeniedError, EggpassAuthError); +create_exception!(_native, CallbackMismatchError, EggpassAuthError); +create_exception!(_native, StateMismatchError, EggpassAuthError); +create_exception!(_native, NonceMismatchError, EggpassAuthError); +create_exception!(_native, ResponseTooLargeError, EggpassAuthError); +create_exception!(_native, TransportError, EggpassAuthError); +create_exception!(_native, OperationTimeoutError, EggpassAuthError); +create_exception!(_native, UnsupportedOperationError, EggpassAuthError); +create_exception!(_native, DeviceExpiredError, EggpassAuthError); +create_exception!(_native, OperationCancelledError, EggpassAuthError); +create_exception!(_native, UntrustedVerificationUrlError, EggpassAuthError); +create_exception!(_native, NotLoggedInError, EggpassAuthError); +create_exception!(_native, NoRefreshTokenError, EggpassAuthError); +create_exception!(_native, CredentialStorageError, EggpassAuthError); + +fn map_error(error: Error) -> PyErr { + match error { + Error::InvalidResponse(message) => InvalidResponseError::new_err(message), + Error::InvalidConfiguration(message) => InvalidConfigurationError::new_err(message), + Error::HttpStatus { status } => { + let py_error = HttpStatusError::new_err(format!("HTTP {status} from OAuth endpoint")); + Python::attach(|py| { + let _ = py_error.value(py).setattr("status", status); + }); + py_error + } + Error::OAuth { status, code } => { + let py_error = + OAuthError::new_err(format!("OAuth endpoint returned HTTP {status} ({code})")); + Python::attach(|py| { + let value = py_error.value(py); + let _ = value.setattr("status", status); + let _ = value.setattr("code", code); + }); + py_error + } + Error::ProviderDenied(code) => { + let py_error = + ProviderDeniedError::new_err(format!("provider denied authorization ({code})")); + Python::attach(|py| { + let _ = py_error.value(py).setattr("code", code); + }); + py_error + } + Error::CallbackMismatch => { + CallbackMismatchError::new_err("callback did not match the pending authorization") + } + Error::StateMismatch => { + StateMismatchError::new_err("callback state did not match the pending authorization") + } + Error::NonceMismatch => { + NonceMismatchError::new_err("ID-token nonce did not match the pending authorization") + } + Error::ResponseTooLarge => { + ResponseTooLargeError::new_err("OAuth response exceeded the configured body limit") + } + Error::Transport => TransportError::new_err("OAuth HTTP request failed"), + Error::Timeout(operation) => { + OperationTimeoutError::new_err(format!("OAuth {operation} timed out")) + } + Error::Unsupported(operation) => { + UnsupportedOperationError::new_err(format!("provider does not support {operation}")) + } + Error::DeviceExpired => DeviceExpiredError::new_err("device authorization expired"), + Error::Cancelled => OperationCancelledError::new_err("device authorization was cancelled"), + Error::UntrustedVerificationUrl { .. } => UntrustedVerificationUrlError::new_err( + "device verification URL was rejected by the trusted-host policy", + ), + Error::NotLoggedIn => NotLoggedInError::new_err("no credentials are stored"), + Error::NoRefreshToken => { + NoRefreshTokenError::new_err("stored credentials contain no refresh token") + } + Error::Storage(_) => CredentialStorageError::new_err("credential storage failed"), + _ => EggpassAuthError::new_err("OAuth operation failed"), + } +} + +#[pyclass(name = "ProviderProfile", module = "eggpass_auth._native")] +struct PyProviderProfile { + inner: OAuthProviderConfig, +} + +#[pymethods] +impl PyProviderProfile { + #[staticmethod] + fn xai() -> Self { + Self { + inner: OAuthProviderConfig::xai(), + } + } + + #[staticmethod] + fn xai_compatibility_fallback() -> Self { + Self { + inner: OAuthProviderConfig::xai_compatibility_fallback(), + } + } + + #[staticmethod] + #[pyo3(signature = (host_id=None))] + fn openai(host_id: Option) -> PyResult { + let inner = match host_id { + Some(host_id) => OAuthProviderConfig::openai_with_host_id(host_id), + None => Ok(OAuthProviderConfig::openai()), + } + .map_err(map_error)?; + Ok(Self { inner }) + } + + #[staticmethod] + fn custom(display_name: String, issuer: String, client_id: String) -> PyProviderBuilder { + PyProviderBuilder { + display_name, + issuer, + client_id, + authorization_endpoint: None, + token_endpoint: None, + device_authorization_endpoint: None, + userinfo_endpoint: None, + revocation_endpoint: None, + callback_path: "/callback".to_string(), + scopes: Vec::new(), + client_id_policy: ClientIdPolicy::Fixed, + authorization_parameters: Vec::new(), + registration_parameters: Vec::new(), + token_parameters: Vec::new(), + device_parameters: Vec::new(), + trusted_device_hosts: Vec::new(), + } + } + + #[getter] + fn display_name(&self) -> String { + self.inner.display_name().to_string() + } + + #[getter] + fn issuer(&self) -> String { + self.inner.issuer().to_string() + } + + #[getter] + fn callback_path(&self) -> String { + self.inner.callback_path().to_string() + } + + #[getter] + fn scopes(&self) -> Vec { + self.inner.scopes().to_vec() + } + + #[getter] + fn client_id_policy(&self) -> &'static str { + match self.inner.client_id_policy() { + ClientIdPolicy::Fixed => "fixed", + ClientIdPolicy::IssuedOnRegistration => "issued_on_registration", + _ => "unknown", + } + } + + fn __repr__(&self) -> &'static str { + "ProviderProfile(