diff --git a/.github/RELEASING.md b/.github/RELEASING.md new file mode 100644 index 0000000..582c5fb --- /dev/null +++ b/.github/RELEASING.md @@ -0,0 +1,44 @@ +# Publishing stackone-ai + +Release Please prepares the version and changelog in a release pull request. +Merging that release PR into `main` creates the GitHub release, tests and builds +its exact commit, then publishes the tested wheel and source archive to PyPI. +Normal development PRs do not publish. Changes to the release workflow run the +same build checks on the PR without access to publishing credentials. + +## Configure PyPI before merging the publishing migration + +A PyPI project owner must open **Manage → Publishing → Add a new publisher → GitHub** +for `stackone-ai` and register these values: + +| Field | Value | +| --- | --- | +| Owner | `StackOneHQ` | +| Repository | `stackone-ai-python` | +| Workflow filename | `release.yaml` | +| Environment | `pypi` | + +Use the filename alone, without `.github/workflows/`. Keep the environment set to +`pypi`, even though PyPI labels that field optional. + +In GitHub repository settings, the `pypi` environment must allow deployment from +the **main branch only**, with no tag rules. This prevents an unreviewed branch +from replacing the publishing workflow and using the project's PyPI identity. +Keep any existing reviewer requirements. + +Publishing uses GitHub's short-lived identity, called **Trusted Publishing** by +PyPI. No new PyPI API token or GitHub secret is needed. The upload job has no +source checkout and installs no package dependencies. Only that job can request +the identity needed to upload, and it downloads artifacts from its own workflow run. + +## Release and verification + +Review and merge the release PR, then check the **Release Please** workflow. +The source commit must be on `main`, and its package version must match the +GitHub release. A failed test or build prevents uploading. Confirm both files +appear on PyPI after the publish job succeeds. + +Do not merge this migration until the PyPI publisher is configured. Keep the +existing token until the first successful publish through Trusted Publishing. +Then remove the unused `PYPI_API_TOKEN` secret and revoke its PyPI token after +checking that no other workflow uses it. diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 0c2206f..fd37bb8 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -1,6 +1,9 @@ name: Release Please on: + pull_request: + branches: [main] + paths: [.github/workflows/release.yaml] push: branches: - main @@ -17,12 +20,16 @@ permissions: jobs: release-please: + if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'StackOneHQ/stackone-ai-python' + timeout-minutes: 10 runs-on: ubuntu-latest permissions: contents: write pull-requests: write outputs: release_created: ${{ steps.release.outputs.release_created }} + release_sha: ${{ steps.release.outputs.sha }} + release_version: ${{ steps.release.outputs.version }} steps: - uses: googleapis/release-please-action@45996ed1f6d02564a971a2fa1b5860e934307cf7 # v5.0.0 id: release @@ -63,33 +70,62 @@ jobs: git push fi - # Publishing lives in its own job so it can be gated. It previously ran in the - # release-please job with no dependency on CI at all: CI is a separate workflow, - # so a red main still merged the release PR and shipped to PyPI. The suite runs - # again here against the exact commit being published. - publish: + build: + name: Test and build release needs: release-please - if: ${{ needs.release-please.outputs.release_created }} + # PRs exercise packaging without running release-please or granting publish access. + if: >- + !cancelled() && + (github.event_name == 'pull_request' || needs.release-please.outputs.release_created == 'true') runs-on: ubuntu-latest - # Configure a required reviewer on this environment in the repository settings. - environment: pypi - permissions: - contents: read + timeout-minutes: 15 steps: - - name: Checkout repository + - name: Checkout release source uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: + ref: ${{ needs.release-please.outputs.release_sha || github.sha }} + fetch-depth: 0 persist-credentials: false + - name: Verify release source + if: github.event_name == 'push' + env: + RELEASE_SHA: ${{ needs.release-please.outputs.release_sha }} + run: | + test "$(git rev-parse --verify 'HEAD^{commit}')" = "$RELEASE_SHA" + git merge-base --is-ancestor HEAD "$(git rev-parse --verify 'refs/remotes/origin/main^{commit}')" + - name: Setup uv uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 with: python-version: "3.13" + enable-cache: false - - name: Setup pnpm + - name: Validate package metadata + id: package + env: + EVENT_NAME: ${{ github.event_name }} + RELEASE_VERSION: ${{ needs.release-please.outputs.release_version }} + run: | + uv --no-config run --no-project --python 3.13 python -I - <<'PYTHON' + import os + import tomllib + from pathlib import Path + + project = tomllib.loads(Path("pyproject.toml").read_text())["project"] + if project["name"] != "stackone-ai": + raise SystemExit("Unexpected package name") + version = project["version"] + if os.environ["EVENT_NAME"] == "push" and version != os.environ["RELEASE_VERSION"]: + raise SystemExit("Package version does not match the GitHub release") + with Path(os.environ["GITHUB_OUTPUT"]).open("a") as output: + output.write(f"version={version}\n") + PYTHON + + - name: Set up pnpm uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 - - name: Setup Node + - name: Set up Node uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version-file: package.json @@ -99,12 +135,66 @@ jobs: uv sync --all-extras --locked pnpm install --frozen-lockfile - - name: Test the commit being published - run: uv run pytest + - name: Lint, type check, and test release source + run: | + uv run ruff check . + uv run ty check stackone_ai + uv run pytest + + - name: Build distributions + run: uv build --no-sources - - name: Build and publish package + - name: Verify wheel and source distribution installations env: - UV_PUBLISH_TOKEN: ${{ secrets.PYPI_API_TOKEN }} + PACKAGE_VERSION: ${{ steps.package.outputs.version }} run: | - uv build - uv publish + for artifact in dist/*.whl dist/*.tar.gz; do + uv --no-config run --isolated --no-project --with "$artifact" python -I - <<'PYTHON' + import os + from importlib.metadata import version + from stackone_ai import StackOneToolSet + assert version("stackone-ai") == os.environ["PACKAGE_VERSION"] + assert callable(StackOneToolSet) + print("Installed stackone-ai", version("stackone-ai")) + PYTHON + done + + - name: Upload tested distributions + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dist + path: | + dist/*.whl + dist/*.tar.gz + if-no-files-found: error + retention-days: 7 + + publish: + name: Publish tested distributions + needs: [release-please, build] + if: >- + github.repository == 'StackOneHQ/stackone-ai-python' && + github.event_name == 'push' && github.ref == 'refs/heads/main' && + needs.release-please.outputs.release_created == 'true' + runs-on: ubuntu-latest + timeout-minutes: 5 + environment: + name: pypi + url: https://pypi.org/project/stackone-ai/ + permissions: + contents: read + id-token: write + steps: + - name: Set up uv + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + enable-cache: false + + - name: Download tested distributions + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: dist + path: dist + + - name: Publish with PyPI Trusted Publishing + run: uv publish --trusted-publishing always diff --git a/CLAUDE.md b/CLAUDE.md index 228417b..6db1104 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -201,7 +201,8 @@ version, and `feat!` signals a breaking change. `docs`, `chore` and `test` do no trigger a release. Merging the release PR updates `CHANGELOG.md`, creates the GitHub release, and -publishes to PyPI (requires the `PYPI_API_TOKEN` secret). +publishes to PyPI through Trusted Publishing. Configure the PyPI publisher and +GitHub environment as described in `.github/RELEASING.md`; no API token is needed. Publishing only ever happens there. There is no `make publish`: releases go out via release-please after a merge to main, never from a developer machine. diff --git a/stackone_ai/toolset.py b/stackone_ai/toolset.py index 1415764..2d11097 100644 --- a/stackone_ai/toolset.py +++ b/stackone_ai/toolset.py @@ -1015,7 +1015,7 @@ def _look_up_end_user(self, account_id: str, refusal: Exception) -> bool: accounts would otherwise be told only that the header does not match. """ try: - self._join_accounts_listing() + self._join_accounts_listing(account_id) except Exception as exc: # A rate limit is the key's, not the account's, and stays fatal to a fan-out. if is_rate_limited(exc): @@ -1023,16 +1023,13 @@ def _look_up_end_user(self, account_id: str, refusal: Exception) -> bool: raise refusal from exc return self._end_user_id(account_id) is not None - def _join_accounts_listing(self) -> None: - """Wait for the GET /accounts in flight, or make one: what it records is then current. - - Raises: - Exception: Whatever that GET /accounts failed with. - """ + def _join_accounts_listing(self, missing_end_user_for: str | None = None) -> None: with self._cache_lock: fetching = self._fetching_accounts sequence = 0 if fetching is None: + if missing_end_user_for is not None and missing_end_user_for in self._end_user_ids: + return self._accounts_sequence += 1 sequence = self._accounts_sequence fetching = self._fetching_accounts = concurrent.futures.Future() diff --git a/tests/test_end_user_id.py b/tests/test_end_user_id.py index 0d9afed..ff24842 100644 --- a/tests/test_end_user_id.py +++ b/tests/test_end_user_id.py @@ -11,12 +11,13 @@ import json import logging import threading +from functools import partial from typing import Any import httpx import pytest -from stackone_ai.tools import McpToolDefinition, StackOneMcpTool +from stackone_ai.tools import McpToolDefinition, RateLimitRetryingClient, StackOneMcpTool from stackone_ai.toolset import StackOneToolSet from stackone_ai.types import StackOneAPIError, ToolParameters, ToolsetConfigError @@ -725,6 +726,7 @@ def guarded(_endpoint: str, headers: dict[str, str], **_kwargs: Any) -> list[Mcp def test_requests_refused_together_share_one_accounts_listing(self, monkeypatch): joined = threading.Event() + base_url = "https://same-listing.invalid" class Listing(concurrent.futures.Future): # type: ignore[type-arg] def result(self, timeout: float | None = None) -> Any: @@ -734,10 +736,10 @@ def result(self, timeout: float | None = None) -> Any: return super().result(timeout) monkeypatch.setattr(concurrent.futures, "Future", Listing) - calls: list[int] = [] + calls: list[tuple[str, str]] = [] - def handle(_self: Any, request: httpx.Request) -> httpx.Response: - calls.append(1) + def handle(request: httpx.Request) -> httpx.Response: + calls.append((request.method, str(request.url))) assert joined.wait(timeout=5) body = [ _account("a", shared=False, origin_username="user-a"), @@ -745,12 +747,15 @@ def handle(_self: Any, request: httpx.Request) -> httpx.Response: ] return httpx.Response(200, json=body, request=request) - monkeypatch.setattr(httpx.HTTPTransport, "handle_request", handle) + monkeypatch.setattr( + "stackone_ai.toolset.RateLimitRetryingClient", + partial(RateLimitRetryingClient, mounts={base_url: httpx.MockTransport(handle)}), + ) mcp = _GuardedMcp(monkeypatch, {"a": "user-a", "b": "user-b"}) - toolset = StackOneToolSet(api_key="k") + toolset = StackOneToolSet(api_key="k", base_url=base_url) tools = toolset.fetch_tools(account_ids=["a", "b"]) assert sorted(t.name for t in tools) == ["tool_a", "tool_b"] - assert len(calls) == 1 + assert calls == [("GET", f"{base_url}/accounts")] assert sorted((h["x-account-id"], h.get("x-end-user-id", "")) for h in mcp.listed) == [ ("a", ""), ("a", "user-a"), @@ -758,6 +763,28 @@ def handle(_self: Any, request: httpx.Request) -> httpx.Response: ("b", "user-b"), ] + def test_a_delayed_refusal_reuses_the_end_user_a_sibling_just_found(self, monkeypatch): + body = [_account(account, shared=False, origin_username=f"user-{account}") for account in ("a", "b")] + calls = _accounts_response(monkeypatch, body, body) + mcp = _GuardedMcp(monkeypatch, {"a": "user-a", "b": "user-b"}) + toolset = StackOneToolSet(api_key="k") + guard = mcp._guard + + def delay_b_until_a_retries(headers: dict[str, str]) -> None: + if headers["x-account-id"] == "b" and "x-end-user-id" not in headers: + toolset.fetch_tools(account_ids=["a"]) + guard(headers) + + monkeypatch.setattr(mcp, "_guard", delay_b_until_a_retries) + assert [t.name for t in toolset.fetch_tools(account_ids=["b"])] == ["tool_b"] + assert [(h["x-account-id"], h.get("x-end-user-id")) for h in mcp.listed] == [ + ("b", None), + ("a", None), + ("a", "user-a"), + ("b", "user-b"), + ] + assert len(calls) == 1 + def test_a_lookup_joins_the_latest_accounts_listing_still_in_flight(self, monkeypatch): """An older listing finishing must not stop a lookup joining a newer one in flight.""" joined = threading.Event()