Compare commits

...

6 commits

Author SHA1 Message Date
Adam Moussa
8a9974c3c4
feat: author Slack/dashboard/schedule commits + PRs as the app by default (#57) (#60)
Some checks failed
CI / Lint (push) Waiting to run
CI / Format check (push) Waiting to run
CI / Unit tests (push) Waiting to run
CI / Playwright E2E (push) Waiting to run
Build & publish app artifacts / Publish + deploy (dev) (push) Has been cancelled
Build & publish app artifacts / Publish + deploy (prod) (push) Has been cancelled
Infra CD / Infra CI (pre-deploy) (push) Has been cancelled
Infra CD / Deploy open-swe-dev (push) Has been cancelled
Infra CD / Deploy open-swe-prod (push) Has been cancelled
* feat: default Slack/dashboard/schedule PRs + commits to the app identity (#57)

Slack/dashboard/schedule runs now author PRs and run git/gh operations as the
GitHub App seahaven-openswe[bot] by default (matching GitHub-issue runs), so the
self-review 422 is impossible by construction rather than guarded in the prompt.
A profile flag author_prs_as_user restores per-user attribution.

- open_pull_request._resolve_pr_author_token + auth.resolve_github_token: default
  to the installation token for these sources; per-user only when opted in.
- authorship: commit identity -> seahaven-openswe[bot] (numeric noreply;
  accepted Vercel-resolution risk, documented inline).
- self-trigger safety: INTERNAL_BOT_LOGINS + webapp/reviewer_reconcile/reply
  markers recognize seahaven-openswe[bot] (bot-authored events are now ours).

Supersedes the prompt-only guard in #58.

* fix: author commits as the app bot in the default path (SH-IDSPLIT-01)

Security review found the commit identity was NOT actually unified to the bot:
resolve_triggering_user_identity got a 403 from the installation token and fell
back to configurable['github_login'], so commits were still authored as the
triggering user (commit=user, push+PR=bot — a three-way split that missed the
stated goal). Now gate the triggering-user identity resolution on the same
default-bot decision as the token: slack/dashboard/schedule default to the app
bot identity unless author_prs_as_user is set.

* docs(security): record AUTHZ-SLACK-BOT-DEFAULT-001 as an accepted residual (#59)

Single-user deployment; bounded by App-on-pilot + ALLOWED_GITHUB_REPOS lock.
Revisit (add a per-user gate) before expanding users or the App installation.
2026-06-29 14:22:33 -04:00
Adam Moussa
134963647b
chore(security): suppress pre-existing history scanner false-positives (#56)
Some checks are pending
Build & publish app artifacts / Publish + deploy (dev) (push) Waiting to run
Build & publish app artifacts / Publish + deploy (prod) (push) Waiting to run
Infra CD / Infra CI (pre-deploy) (push) Waiting to run
Infra CD / Deploy open-swe-dev (push) Blocked by required conditions
Infra CD / Deploy open-swe-prod (push) Blocked by required conditions
CI / Lint (push) Waiting to run
CI / Format check (push) Waiting to run
CI / Unit tests (push) Waiting to run
CI / Playwright E2E (push) Waiting to run
Adds repo-local suppressions for 5 verified-FP gitleaks findings that block
pushes (forcing --no-verify), all in committed history / docs / CI fixtures:
- .env.ci (dev-only e2e values, intentionally committed)
- .env.example (placeholders)
- .github/ci/fake_github_app_key.pem (throwaway CI test key)
- INSTALLATION.md (example GITHUB_APP_PRIVATE_KEY .env block)
- README.md (prose mis-matched by the generic-api-key heuristic)
Repo-local (not machine-level) so they load in git worktrees too. Also drops
the now-obsolete OSWE-IAC-AUDIT-01 suppression (B-1, fixed in #55).
2026-06-29 12:54:40 -04:00
Adam Moussa
e9499e49b8
fix: isolate dev CDK deploys on their own bootstrap qualifier (B-1/OSWE-IAC-01) (#55)
* fix: isolate dev CDK deploys on their own bootstrap qualifier (B-1)

Dev synthesizes against the oswedev qualifier and the dev infra deploy role
is scoped to cdk-oswedev-* — it can no longer assume the default hnb659fds
bootstrap roles whose admin cfn-exec-role deploys prod, closing the cross-env
escalation (OSWE-IAC-01). Prod stays on the default qualifier.

* test: assert per-env bootstrap qualifier isolation + document (B-1)
2026-06-29 12:39:23 -04:00
Adam Moussa
a33aaec495
fix: resolve security-review findings (sandbox isolation, IAM list scope, webhook replay, info-leak) (#54)
* fix: enforce a replay window on Linear webhooks (AUTHZ-001)

verify_linear_signature accepted any correctly-signed body with no freshness
check, so a captured request could be replayed indefinitely. Parse the
signed webhookTimestamp (Unix ms) and reject requests outside a 60s window,
failing closed when the field is missing or malformed — mirroring the Slack
verifier.

* fix: stop leaking upstream auth-error bodies into user comments

get_github_token_for_user folded the raw upstream response text into the
error string that becomes a Slack/Linear comment (AUTH-RESP-LEAK-01). Log the
full body server-side only and return a generic "GitHub auth failed (status
<code>)". Also document the accepted shared-installation-token blast radius on
the bot-token-only path (AUTHZ-003).

* fix: bind sandbox and token caches to repo to prevent thread-id collision

A PR head-branch name is attacker-controllable and get_thread_id_from_branch
derives a thread_id from its first UUID with no repo binding (TID-COLLIDE-01).
The in-memory sandbox cache and the per-thread GitHub-token cache were keyed on
thread_id alone, and a cached sandbox was reused after only an echo-ping, so a
different repo's webhook could bind to another thread's sandbox or token.

Without changing the persistent thread-id scheme:
- Persist the bound repo (owner/name) in thread metadata on sandbox creation and
  refuse to reuse a sandbox whose bound repo does not match the current event
  (SandboxRepoMismatchError); the in-memory proxy also carries the binding.
- Bind the GitHub-token cache entries to their repo and evict on a cross-repo
  read so a colliding thread_id cannot be served another repo's token.
- Thread repo through the reviewer and the webhook token resolvers.

* fix: scope s3:ListBucket to the releases/ prefix (F-1/IAC-04)

The instance role and the GitHub deploy app role granted s3:ListBucket on the
whole assets bucket. Every caller (deploy.sh, the publish/rollback scripts)
only ever lists under releases/, so add a StringLike s3:prefix=releases/*
condition. GetBucketLocation has no s3:prefix in its request context, so it
moves to its own unconditioned statement. Also document the accepted F-2
cross-env existence-oracle residual on BatchGetSecretValue.

* chore: suppress test-fixture credential false positive; document AUTHZ-002

Add a machine-level suppression for the fake Datadog key in the
test_team_credentials encryption-roundtrip fixture (CWE-798, not a real
credential). Clarify that the within-org thread-write path is intentional by
design (AUTHZ-002) — comment only, no behavior change.

* fix: casefold repo-binding keys to avoid spurious cross-repo mismatch

GitHub owner/name are case-insensitive. Casefold the owner/name key on both the
write (binding) and read (compare) sides — repo_cache_key and the metadata
bound_repo read — so Org/Repo and org/repo resolve to one repo and a legitimate
same-repo run cannot raise a spurious SandboxRepoMismatchError (Gap 2).

* fix: stop leaking upstream auth body in unexpected-result branch

The 2xx-but-missing-token/url branch echoed the parsed upstream response body
into the user-facing error. Return a generic message and log response_data
server-side only, mirroring the existing HTTPStatusError fix (Gap 4).

* fix: fail closed for unbound-legacy sandboxes and catch repo mismatch

Gap 1: a thread with a persisted sandbox_id but no in-memory cache and no
recorded bound_repo (a pre-binding legacy thread, post-deploy) previously
reconnected-and-served the sandbox to the current repo, then rebound it. Now
fail closed: drop the stale id and recreate a fresh sandbox bound to this repo,
logging a reconnect-with-missing-binding event. A sandbox is never served to a
repo unless its binding is known and matches; new threads bind on first run
unchanged.

Gap 3: catch SandboxRepoMismatchError at the agent and reviewer run entrypoints,
log it for alarming, and surface a clean sanitized error instead of letting an
opaque deep-stack exception crash-loop the worker.

* chore: suppress test-fixture credential false positive in token-TTL tests

Add a machine-level suppression for the fake "ghp_secret" GitHub token used by
the cached-token TTL/revocation unit tests (CWE-798). Not a real credential and
not a valid PAT; scoped to the unit test only.
2026-06-29 12:21:19 -04:00
Adam Moussa
9444fd7677
docs: document live AWS prod deploy for Open SWE (#53)
Some checks are pending
Build & publish app artifacts / Publish + deploy (dev) (push) Waiting to run
Build & publish app artifacts / Publish + deploy (prod) (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Format check (push) Waiting to run
CI / Unit tests (push) Waiting to run
CI / Playwright E2E (push) Waiting to run
Prod went live 2026-06-29 on self-hosted AWS EC2 behind the shared
seahaven-com ALB, superseding the on-prem VM model the runbook described.

- Rewrite deploy/seahaven/DEPLOYMENT.md as the canonical end-to-end runbook:
  infra CD (CDK stacks + OIDC roles + prod approval gate), config seeding
  (put-config.sh, the 13 boot-required prod vars, fetch-config fail-fast),
  app artifact deploy (S3 + SSM roll + is-active gate), promotion/rollback,
  live prod facts, and a RETAIN secret-shell troubleshooting entry that
  cross-references infra/README.md.
- Correct retired *.seahavenind.com hosts to *.seahaven.com throughout and
  document the live GitHub/Slack/Linear webhook + OAuth endpoints.
- Add a concise Deployment section to README pointing at the runbook.
- Fix the stale host in the retired on-prem nginx/openswe.conf and mark it
  superseded by the AMI template.
2026-06-29 11:12:44 -04:00
Adam Moussa
f379fbdaa9
docs: document RETAIN secret-shell orphan gotcha (#52)
Some checks are pending
Infra CD / Infra CI (pre-deploy) (push) Waiting to run
Infra CD / Deploy open-swe-dev (push) Blocked by required conditions
Infra CD / Deploy open-swe-prod (push) Blocked by required conditions
CI / Lint (push) Waiting to run
CI / Format check (push) Waiting to run
CI / Unit tests (push) Waiting to run
CI / Playwright E2E (push) Waiting to run
RETAIN + a fixed secret name means a failed FIRST create leaves empty
secret shells behind when the stack rolls back. The shells keep the
global `open-swe-<env>/<VAR>` names, so every later create fails with
`AlreadyExists`, and a plain delete-secret keeps the name reserved for
the recovery window rather than freeing it.

Record the trap and the force-delete recovery (only for empty shells)
in the config-store construct and the infra README so the next
teardown/rebuild, secret logical-id change, or new-env stand-up does
not rediscover it the hard way.

Prod's first deploy hit this on 2026-06-29: 28 orphaned shells from an
earlier failed create reserved the names and had to be force-deleted
before the stack would create.
2026-06-29 10:51:49 -04:00
37 changed files with 1525 additions and 221 deletions

1
.gitignore vendored
View file

@ -72,3 +72,4 @@ __pycache__/
TODO.md
# infra/cdk-outputs.json
.idea/

View file

@ -1,24 +1,128 @@
{
"suppressions": [
{
"id": "OSWE-IAC-AUDIT-01",
"title": "Dev-branch infra OIDC role can assume the account-wide CDK cfn-exec admin role (cdk-hnb659fds-*), a path to mutating prod",
"file": "infra/lib/constructs/github-deploy-roles.ts",
"severity": "high",
"id": "AUTHZ-SLACK-BOT-DEFAULT-001",
"title": "Slack entrypoint lacks a per-user repo-access check; default-bot PR authoring removes the implicit per-user repo boundary",
"file": "agent/webapp.py",
"severity": "medium",
"status": "confirmed",
"suppression_justification": "PRE-EXISTING and NOT introduced or worsened by the T7+T19 change (the assets bucket / app-role PutObject / SSM deploy doc). This is the known single-account-wide CDK cfn-exec residual already documented in infra/lib/config.ts:31-34 and the github-deploy-roles.ts construct comment, accepted at the T4 GPT-4.1 IAM cross-review and the v5 plan-review. WHO can assume each env's infra role is exact-subject scoped (StringEquals on the dev ref / prod environment); the residual is the shared account-wide cfn-exec-role that every env's infra role can reach. The tracked fix is per-env CDK bootstrap qualifiers so each env's infra role assumes its own env-scoped cfn-exec-role. Suppressed for THIS change's gate because it is out-of-diff and unchanged; surfaced to Adam for scheduling the per-env-bootstrap remediation.",
"suppression_justification": "ACCEPTED (Adam, 2026-06-29) while Open SWE has a SINGLE user. The Slack run entrypoint does not call require_repo_access_for_user (dashboard/schedule do), so with the default App installation token a mapped Slack user could act on any repo in the App's installation regardless of their own access. Bounded by the compensating controls: the seahaven-openswe App is installed on open-swe-pilot ONLY and ALLOWED_GITHUB_REPOS is locked, so the bot token cannot reach repos outside the pilot, and the only triggering user is the owner. Tracked as open issue #59 with three remediation options. REVISIT TRIGGER: before expanding the user base OR broadening the App's installation beyond open-swe-pilot — at that point this becomes HIGH and a gate (option (c): per-user check when a token exists) must be added. Verified medium (not high) by /sh-security-review proof-or-kill verifier.",
"owner": "adam@seahavenind.com",
"added": "2026-06-29"
},
{
"id": "OSWE-IAC-SECRETS-LIST-01",
"title": "EC2 instance role grants BatchGetSecretValue on \"*\" (operation-level; secret-NAME existence enumeration account-wide)",
"file": "infra/lib/constructs/instance-role.ts",
"severity": "low",
"status": "confirmed",
"suppression_justification": "ACCEPTED LOW residual, metadata-only. secretsmanager:BatchGetSecretValue is a collection action that AWS cannot scope to a per-secret ARN, so it is granted on `*` (documented in commit 3c69dd9d and the construct comment). Secret VALUES remain strictly gated by the PREFIX-scoped GetSecretValue/DescribeSecret on secret:open-swe-<env>/* (checked per-secret even within the batch), so cross-env VALUE isolation is preserved; only a name EXISTENCE oracle remains, within Sea Haven's single-tenant account 328440206208. ListSecrets is intentionally NOT granted (so name FILTER enumeration AccessDenies). Confirmed by GPT-4.1 IAM cross-review (no BLOCK) and the iac-iam detector (one low residual, no critical/high).",
"owner": "adam@seahavenind.com",
"added": "2026-06-26"
},
{
"id": "OSWE-IAC-SECRETS-LIST-01",
"title": "EC2 instance role grants BatchGetSecretValue + ListSecrets on \"*\" (operation-level; secret-NAME enumeration account-wide)",
"file": "infra/lib/constructs/instance-role.ts",
"id": "gitleaks-generic-api-key-89",
"title": "Hardcoded credential flagged in encryption-roundtrip test fixture (CWE-798)",
"file": "tests/test_team_credentials.py",
"line": 89,
"rule": "CWE-798",
"severity": "low",
"status": "confirmed",
"suppression_justification": "ACCEPTED LOW residual, metadata-only. fetch-config.sh materializes the .env via `batch-get-secret-value --filters Key=name,Values=open-swe-<env>/`. With a name FILTER, both BatchGetSecretValue (a collection call) and ListSecrets are authorized by AWS against `*`, NOT a per-secret ARN — a prefix-scoped ARN AccessDenies the call (confirmed empirically on i-0af4e03e8bf70e6c3). So the two `*` grants are operation-level, not value-level. Secret VALUES remain strictly gated by the PREFIX-scoped GetSecretValue/DescribeSecret on secret:open-swe-<env>/* (GetSecretValue is checked per-secret even within the batch), so cross-env VALUE isolation is preserved; only NAMES/tags/descriptions are enumerable, within Sea Haven's own single-tenant account 328440206208. Confirmed by GPT-4.1 IAM cross-review (BLOCK: none) and the iac-iam detector (one low residual, no critical/high). Future hardening to eliminate BOTH `*` grants: switch fetch-config.sh to an explicit `--secret-id-list` (no filter), which lets BatchGetSecretValue be prefix-scoped and needs no ListSecrets.",
"status": "false-positive",
"justification": "Test fixture, not a real credential. The value \"secret-api-1234\" is a fake Datadog API key used by test_datadog_roundtrip_and_redaction to assert that the plaintext key is recoverable after an encrypt/decrypt round-trip (and that the stored record holds ciphertext, not the plaintext). It is never a live secret and is scoped to the unit test only.",
"suppression_justification": "Test fixture, not a real credential. The value \"secret-api-1234\" is a fake Datadog API key used by test_datadog_roundtrip_and_redaction to assert that the plaintext key is recoverable after an encrypt/decrypt round-trip. It is never a live secret and is scoped to the unit test only.",
"owner": "adam@seahavenind.com",
"added": "2026-06-26"
"added": "2026-06-29"
},
{
"id": "gitleaks-generic-api-key-79",
"title": "Hardcoded credential flagged in encryption-roundtrip test fixture (CWE-798)",
"file": "tests/test_team_credentials.py",
"line": 79,
"rule": "CWE-798",
"severity": "low",
"status": "false-positive",
"justification": "Test fixture, not a real credential. Same fake Datadog API key \"secret-api-1234\" passed into connect_datadog by test_datadog_roundtrip_and_redaction. Never a live secret; scoped to the unit test only.",
"suppression_justification": "Test fixture, not a real credential. Same fake Datadog API key \"secret-api-1234\" passed into connect_datadog by test_datadog_roundtrip_and_redaction. Never a live secret; scoped to the unit test only.",
"owner": "adam@seahavenind.com",
"added": "2026-06-29"
},
{
"id": "gitleaks-generic-api-key-23",
"title": "Hardcoded credential flagged in GitHub-token TTL test fixture (CWE-798)",
"file": "tests/test_github_token_ttl.py",
"line": 23,
"rule": "CWE-798",
"severity": "high",
"status": "false-positive",
"justification": "Test fixture, not a real credential. The literal \"ghp_secret\" is a fake GitHub token used by the cached-token TTL/revocation unit tests. Not a valid 40-char GitHub PAT, never a live secret, scoped to the unit test only.",
"suppression_justification": "Test fixture, not a real credential. The literal \"ghp_secret\" is a fake GitHub token used by the cached-token TTL/revocation unit tests. Not a valid 40-char GitHub PAT, never a live secret, scoped to the unit test only.",
"owner": "adam@seahavenind.com",
"added": "2026-06-29"
},
{
"id": "gitleaks-generic-api-key-24",
"title": "Dev-only CI env value flagged in .env.ci (history-only; file not at HEAD)",
"file": ".env.ci",
"line": 24,
"rule": "gitleaks-generic-api-key",
"severity": "high",
"status": "false-positive",
"justification": "False positive. .env.ci is the e2e CI env file (added in commit 5a52b9b2 'ci: run playwright e2e tests') holding DELIBERATELY-FAKE, dev-only values explicitly marked 'committed intentionally' (e.g. GITHUB_WEBHOOK_SECRET=dev-secret and a dev-only Fernet TOKEN_ENCRYPTION_KEY used solely by the Playwright e2e suite). No production secret: real prod values live in Secrets Manager (open-swe-prod/*). gitleaks scans committed history so it flags this even though the file is not present at HEAD.",
"suppression_justification": "Dev-only CI fixture value, intentionally committed for the e2e suite; not a production secret (prod secrets are in Secrets Manager). Flagged from git history; file not present at HEAD.",
"owner": "adam@seahavenind.com",
"added": "2026-06-29"
},
{
"id": "gitleaks-generic-api-key-3",
"title": "Placeholder flagged in .env.example (history-only; file not at HEAD)",
"file": ".env.example",
"line": 3,
"rule": "gitleaks-generic-api-key",
"severity": "high",
"status": "false-positive",
"justification": "False positive. .env.example contains placeholder/example values only, by definition not real secrets. gitleaks scans committed history so it flags the placeholder even though the file is not present at HEAD.",
"suppression_justification": "Example/placeholder value in a committed .env.example; flagged from git history. Not a real secret.",
"owner": "adam@seahavenind.com",
"added": "2026-06-29"
},
{
"id": "gitleaks-private-key-1",
"title": "Fake CI RSA key flagged in .github/ci/fake_github_app_key.pem (history-only)",
"file": ".github/ci/fake_github_app_key.pem",
"line": 1,
"rule": "gitleaks-private-key",
"severity": "high",
"status": "false-positive",
"justification": "False positive. This is a throwaway test RSA key (the filename is literally 'fake_github_app_key.pem') referenced by .env.ci for the Playwright e2e suite. It is not a production GitHub App key (the real prod key is in Secrets Manager open-swe-prod/GITHUB_APP_PRIVATE_KEY). gitleaks scans committed history; the file is not present at HEAD.",
"suppression_justification": "Deliberately-fake CI test key for the e2e suite; not a production GitHub App key. Flagged from git history; file not present at HEAD.",
"owner": "adam@seahavenind.com",
"added": "2026-06-29"
},
{
"id": "gitleaks-private-key-185",
"title": "Documentation example PEM flagged in INSTALLATION.md (CWE-798)",
"file": "INSTALLATION.md",
"line": 185,
"rule": "gitleaks-private-key",
"severity": "high",
"status": "false-positive",
"justification": "False positive. INSTALLATION.md shows the .env format with an example GITHUB_APP_PRIVATE_KEY=\"-----BEGIN RSA PRIVATE KEY-----...\" block in the setup instructions. It is illustrative documentation, not a real key.",
"suppression_justification": "Documentation example of the GITHUB_APP_PRIVATE_KEY .env format in INSTALLATION.md; not a real key.",
"owner": "adam@seahavenind.com",
"added": "2026-06-29"
},
{
"id": "gitleaks-generic-api-key-29",
"title": "README prose flagged as a generic API key (CWE-798)",
"file": "README.md",
"line": 29,
"rule": "gitleaks-generic-api-key",
"severity": "high",
"status": "false-positive",
"justification": "False positive. README.md line 29 is descriptive project prose (the 'Open SWE is the open-source version...' paragraph / blog link); gitleaks' generic-api-key entropy heuristic mis-matched a token in the text. No secret is present.",
"suppression_justification": "README descriptive prose mis-matched by the generic-api-key entropy heuristic; no secret present.",
"owner": "adam@seahavenind.com",
"added": "2026-06-29"
}
]
}

View file

@ -151,6 +151,21 @@ This is an area where you can extend Open SWE for your org: add deterministic CI
- **[Installation Guide](INSTALLATION.md)** — local dev (backend + dashboard), GitHub App creation, LangSmith, Linear/Slack/GitHub triggers, and production deployment
- **[Customization Guide](CUSTOMIZATION.md)** — swap the sandbox, model, tools, triggers, system prompt, and middleware for your org
## Deployment (Sea Haven fork)
This fork is **self-hosted on AWS** and live in production. Each env (`dev` /
`prod`) runs the stock `langgraph dev` server (all three graphs + the FastAPI
webapp) bound to loopback `127.0.0.1:2024` on a single ARM64 EC2 box, fronted by
nginx (the sole ingress) behind the shared `seahaven-com` ALB. CDK (`infra/`)
owns the per-env stacks; GitHub Actions handle CDK deploys (`cd-infra.yml`) and
app-artifact releases to S3 rolled onto the box via an SSM document
(`build-artifacts.yml`), with `dev` auto-deploying and `prod` gated behind a
manual GitHub Environment approval.
**[`deploy/seahaven/DEPLOYMENT.md`](deploy/seahaven/DEPLOYMENT.md) is the canonical
deploy runbook** — full end-to-end pipeline, config seeding, promotion/rollback,
and live prod facts. CDK specifics live in [`infra/README.md`](infra/README.md).
## License
MIT

View file

@ -92,6 +92,23 @@ def profile_create_prs(profile: dict[str, Any] | None) -> bool:
return False
def profile_author_prs_as_user(profile: dict[str, Any] | None) -> bool:
"""Return whether Slack/dashboard/schedule PRs should be authored as the
triggering user (their per-user OAuth token) instead of the App bot.
Defaults to False: by default these PRs (and the run's git/gh operations) are
authored as the GitHub App `seahaven-openswe[bot]`, matching GitHub-issue
runs and making the self-review 422 impossible. Set the profile flag
``author_prs_as_user: true`` to opt back into per-user attribution.
"""
if not isinstance(profile, dict):
return False
value = profile.get("author_prs_as_user")
if isinstance(value, bool):
return value
return False
def _normalize_profile_model_pair(
profile: dict[str, Any],
*,

View file

@ -1206,6 +1206,8 @@ async def send_dashboard_message(
raise HTTPException(404, "thread not found") from exc
metadata = thread.get("metadata") if isinstance(thread.get("metadata"), dict) else {}
# AUTHZ-002 (intentional): any org-gated member who can read a surfaced thread
# may also post into it; non-owners are attributed via _attribution_prefix.
_assert_thread_readable(metadata)
prompt = f"{_attribution_prefix(metadata, login, email)}{body.content.strip()}"

View file

@ -391,7 +391,7 @@ When you have completed your implementation, follow these steps in order:
2. **Review your changes**: Review the diff to ensure correctness. Verify no regressions or unintended modifications.
3. **Submit**: Commit locally, push with `git push origin <branch>`, then open or update the PR when a PR is requested, necessary, or required by the Always Create PRs dashboard setting.
- **Open a new PR** with the `open_pull_request` tool (pass `owner`, `repo`, `head` = your branch, `base`, `title`, `body`). This attributes the PR to the triggering user. Push the branch BEFORE calling it.
- **Open a new PR** with the `open_pull_request` tool (pass `owner`, `repo`, `head` = your branch, `base`, `title`, `body`). By default the PR is authored by the app (`seahaven-openswe[bot]`), like GitHub-issue-triggered runs (a user can opt back into per-user attribution via the `author_prs_as_user` profile setting). Push the branch BEFORE calling it.
- **Update an existing PR** (edit the body, mark ready for review, etc.) with `GH_TOKEN=dummy gh pr edit`. If a PR already exists for the branch (including one the user pasted in), do NOT open a duplicate — `open_pull_request` returns the existing PR's URL, so switch to `gh pr edit`. For follow-up changes, add a new commit on top of the existing branch history.
**PR Title** (under 70 characters): the title rule is **repo-aware** — first detect whether the target repo enforces a conventional-commit PR title, then pick the matching style. The repo is already cloned, so this check is cheap.

View file

@ -59,6 +59,7 @@ from .server import (
DEFAULT_LLM_MAX_TOKENS,
DEFAULT_RECURSION_LIMIT,
MODEL_CALL_RECURSION_LIMIT,
SandboxRepoMismatchError,
_general_purpose_subagent,
ensure_sandbox_for_thread,
graph_loaded_for_execution,
@ -839,7 +840,9 @@ async def get_reviewer_agent(config: RunnableConfig) -> Pregel:
f"GitHub App installation token unavailable for reviewer thread {thread_id}"
)
# Cache in-process so reviewer tools and the sandbox proxy can read it this run.
cache_github_token_for_thread(thread_id, github_token, expires_at=expires_at)
cache_github_token_for_thread(
thread_id, github_token, expires_at=expires_at, repo=repo_config
)
github_proxy_token = github_token
github_api_token = github_token
@ -849,12 +852,18 @@ async def get_reviewer_agent(config: RunnableConfig) -> Pregel:
if repo_config.get("owner") and repo_config.get("name")
else None
)
sandbox_backend = await ensure_sandbox_for_thread(
thread_id,
github_proxy_token=github_proxy_token,
github_proxy_repositories=[repo_name_for_scope] if repo_name_for_scope else None,
repo=repo_for_snapshot,
)
try:
sandbox_backend = await ensure_sandbox_for_thread(
thread_id,
github_proxy_token=github_proxy_token,
github_proxy_repositories=[repo_name_for_scope] if repo_name_for_scope else None,
repo=repo_for_snapshot,
)
except SandboxRepoMismatchError as exc:
# Repo-binding refusal at the run boundary: log for alarming and surface the
# sanitized terminal error rather than crash-looping the reviewer worker.
logger.error("Refusing reviewer run for thread %s: %s", thread_id, exc)
raise RuntimeError(str(exc)) from exc
work_dir = await aresolve_sandbox_work_dir(sandbox_backend)

View file

@ -16,7 +16,7 @@ ReviewThreadMatch = tuple[ReviewThread, int | None]
def _is_open_swe_bot_comment(comment: ReviewThread) -> bool:
return comment.get("author") in {"open-swe", "open-swe[bot]"}
return comment.get("author") in {"open-swe", "open-swe[bot]", "seahaven-openswe[bot]"}
def _int_list(value: Any) -> list[int]:
@ -52,7 +52,7 @@ def _human_replies_after_bot_comment(
if not seen_bot_comment:
continue
author = comment.get("author")
if author in {"open-swe", "open-swe[bot]"}:
if author in {"open-swe", "open-swe[bot]", "seahaven-openswe[bot]"}:
continue
replies.append(comment)
return replies

View file

@ -36,6 +36,7 @@ from .dashboard.agent_overrides import (
load_profile,
normalize_profile_overrides,
normalize_profile_subagent_overrides,
profile_author_prs_as_user,
profile_create_prs,
resolve_github_login,
)
@ -98,6 +99,7 @@ from .utils.github_app import (
get_github_app_installation_token_with_expiry,
)
from .utils.github_proxy import record_proxy_token_expiry
from .utils.github_token import repo_cache_key
from .utils.model import (
DEFAULT_LLM_REASONING,
ModelKwargs,
@ -117,6 +119,7 @@ SANDBOX_POLL_INTERVAL = 1.0
from .utils.sandbox_state import (
SANDBOX_BACKENDS,
get_bound_repo_from_metadata,
get_sandbox_id_from_metadata,
set_sandbox_backend,
unwrap_sandbox_backend,
@ -405,6 +408,24 @@ def graph_loaded_for_execution(config: RunnableConfig) -> bool:
)
class SandboxRepoMismatchError(RuntimeError):
"""Raised when a thread_id is presented for a repo it is not bound to.
A thread is bound to exactly one repo. A different repo presenting a
colliding thread_id (e.g. an attacker-named branch whose first UUID matches
another thread) must never reuse this thread's sandbox or token.
"""
def __init__(self, thread_id: str, bound_repo: str, current_repo: str) -> None:
self.thread_id = thread_id
self.bound_repo = bound_repo
self.current_repo = current_repo
super().__init__(
f"Thread {thread_id} is bound to repo {bound_repo}, "
f"refusing to serve sandbox for {current_repo}"
)
async def ensure_sandbox_for_thread(
thread_id: str,
*,
@ -435,6 +456,43 @@ async def ensure_sandbox_for_thread(
logger.info("Sandbox creation in progress for thread %s, waiting...", thread_id)
sandbox_id = await _resolve_creating_sentinel(thread_id)
# Repo-binding guard (TID-COLLIDE-01): a sandbox is never served to a repo
# unless its binding is known and matches.
current_repo = repo_cache_key(repo)
bound_repo = await get_bound_repo_from_metadata(thread_id)
proxy_bound = getattr(sandbox_backend, "bound_repo", None)
effective_bound = bound_repo or (proxy_bound if isinstance(proxy_bound, str) else None)
if current_repo and effective_bound and effective_bound != current_repo:
# Known binding that does not match the current repo: refuse outright so a
# colliding thread_id from a different repo cannot reuse/clobber it.
logger.error(
"Repo mismatch for thread %s: bound=%s current=%s; refusing sandbox reuse",
thread_id,
effective_bound,
current_repo,
)
raise SandboxRepoMismatchError(thread_id, effective_bound, current_repo)
if (
current_repo
and not effective_bound
and sandbox_backend is None
and isinstance(sandbox_id, str)
and sandbox_id not in (None, SANDBOX_CREATING)
):
# Fail CLOSED for unbound-legacy threads (migration window): a thread with a
# persisted sandbox_id but no in-memory cache and no recorded bound_repo
# cannot be confirmed to belong to the current repo, so never
# reconnect-and-serve it. Drop the stale id and recreate a fresh sandbox
# bound to this repo below.
logger.error(
"reconnect-with-missing-binding for thread %s: persisted sandbox %s has no "
"bound_repo; refusing reuse and recreating for repo %s",
thread_id,
sandbox_id,
current_repo,
)
sandbox_id = None
if sandbox_backend:
logger.info("Using cached sandbox backend for thread %s", thread_id)
original_sandbox_id = sandbox_backend.id
@ -493,12 +551,15 @@ async def ensure_sandbox_for_thread(
sandbox_backend, thread_id, github_proxy_token, github_proxy_repositories, repo
)
sandbox_backend = set_sandbox_backend(thread_id, sandbox_backend)
sandbox_backend = set_sandbox_backend(thread_id, sandbox_backend, repo=current_repo)
metadata_update: dict[str, Any] = {}
if sandbox_id != sandbox_backend.id:
await client.threads.update(
thread_id=thread_id, metadata={"sandbox_id": sandbox_backend.id}
)
metadata_update["sandbox_id"] = sandbox_backend.id
if current_repo and bound_repo != current_repo:
metadata_update["bound_repo"] = current_repo
if metadata_update:
await client.threads.update(thread_id=thread_id, metadata=metadata_update)
# Re-apply git identity every run: cached/reconnected sandboxes may have
# lost their `--global` config (or had it overwritten), and Vercel preview
@ -621,19 +682,51 @@ async def get_agent(config: RunnableConfig) -> Pregel:
profile_login = resolve_github_login(config)
configurable = (config or {}).get("configurable") or {}
prompt_default_repo = await _resolve_prompt_default_repo(configurable)
triggering_user_identity_task = asyncio.create_task(
asyncio.to_thread(resolve_triggering_user_identity, config, github_token)
)
# Commit identity must follow the SAME default-bot decision as the token
# (SH-IDSPLIT-01): by default slack/dashboard/schedule runs author commits as the
# app bot, so resolve the triggering USER's git identity ONLY when authoring as the
# user (the author_prs_as_user opt-in, or a non-default source). Otherwise leave it
# None so construct_system_prompt sets the bot identity (OPEN_SWE_BOT_NAME/EMAIL) and
# commits don't get mis-attributed to a human who didn't write them.
if configurable.get("source") in ("slack", "dashboard", "schedule"):
_author_as_user = bool(
isinstance(profile_login, str)
and profile_login.strip()
and profile_author_prs_as_user(await load_profile(profile_login.strip()))
)
else:
_author_as_user = True
async def _no_triggering_identity() -> Any:
return None
if _author_as_user:
triggering_user_identity_task = asyncio.create_task(
asyncio.to_thread(resolve_triggering_user_identity, config, github_token)
)
else:
triggering_user_identity_task = asyncio.create_task(_no_triggering_identity())
sandbox_task = asyncio.create_task(
ensure_sandbox_for_thread(thread_id, repo=prompt_default_repo)
)
team_defaults_task = asyncio.create_task(get_team_default_model_pair("agent"))
profile_task = asyncio.create_task(load_profile(profile_login)) if profile_login else None
triggering_user_identity, sandbox_backend, team_defaults = await asyncio.gather(
triggering_user_identity_task,
sandbox_task,
team_defaults_task,
)
try:
triggering_user_identity, sandbox_backend, team_defaults = await asyncio.gather(
triggering_user_identity_task,
sandbox_task,
team_defaults_task,
)
except SandboxRepoMismatchError as exc:
# Repo-binding refusal at the run boundary: log for alarming and surface the
# already-sanitized terminal error (no sandbox/token internals) to the caller,
# rather than letting an opaque deep-stack exception crash-loop the worker.
logger.error("Refusing agent run for thread %s: %s", thread_id, exc)
for pending in (triggering_user_identity_task, team_defaults_task, profile_task):
if pending is not None and not pending.done():
pending.cancel()
raise RuntimeError(str(exc)) from exc
profile = await profile_task if profile_task is not None else None
del github_token

View file

@ -25,11 +25,12 @@ _REFERENCES_HEADING = "## References"
async def _resolve_pr_author_token() -> tuple[str | None, str]:
"""Return ``(token, kind)`` for opening the PR.
Prefers the triggering user's OAuth token (so the PR is created *as them*)
for Slack/dashboard runs with a mapped GitHub login, resolving it by login
from the dashboard OAuth store. Falls back to the GitHub App installation
token (creator = open-swe[bot]) for GitHub-triggered runs, unmapped users,
or bot-token-only deployments — preserving today's behavior.
DEFAULT: open the PR as the GitHub App bot ``seahaven-openswe[bot]`` (the
installation token) for every source, so Slack/dashboard PRs are attributed
to the app — matching GitHub-issue runs and making the self-review 422
impossible by construction. OPT-IN: when the triggering user's profile has
``author_prs_as_user: true``, open Slack/dashboard PRs as that user (their
per-user OAuth token, resolved by login from the dashboard OAuth store).
The token is resolved by login rather than read from the shared thread
metadata: Slack thread ids are shared across a conversation, so a cached
@ -40,12 +41,19 @@ async def _resolve_pr_author_token() -> tuple[str | None, str]:
github_login = configurable.get("github_login")
if source in _USER_TOKEN_SOURCES and isinstance(github_login, str) and github_login.strip():
from ..dashboard.profiles import get_valid_access_token
login = github_login.strip()
from ..dashboard.agent_overrides import load_profile, profile_author_prs_as_user
user_token = await get_valid_access_token(github_login.strip())
if user_token:
return user_token, "user"
logger.info("No valid user token for %s; opening PR as open-swe[bot]", github_login.strip())
if profile_author_prs_as_user(await load_profile(login)):
from ..dashboard.profiles import get_valid_access_token
user_token = await get_valid_access_token(login)
if user_token:
return user_token, "user"
logger.info(
"author_prs_as_user set but no valid user token for %s; opening PR as the app bot",
login,
)
return await get_github_app_installation_token(), "bot"

View file

@ -92,7 +92,7 @@ async def _reply_to_finding_thread_async(
"kind": "bot_reply",
"github_comment_id": reply_id if isinstance(reply_id, int) else None,
"github_parent_comment_id": comment_id,
"author": "open-swe[bot]",
"author": "seahaven-openswe[bot]",
"body": body.strip(),
"created_at": "",
"needs_reassessment": False,

View file

@ -192,11 +192,18 @@ async def get_github_token_for_user(ls_user_id: str, tenant_id: str) -> dict[str
return result
if auth_url:
return {"auth_url": auth_url}
return {"error": f"Unexpected auth result: {response_data}"}
# Log the full upstream body server-side only; the returned error becomes a
# user-facing Slack/Linear comment, so never echo the raw response body.
logger.error(
"GitHub auth returned an unexpected result (no token/url): %s", response_data
)
return {"error": "GitHub auth returned an unexpected result"}
except httpx.HTTPStatusError as e:
# Log the full upstream body server-side only; the returned error becomes a
# user-facing Slack/Linear comment, so never echo the raw response text.
logger.error("GitHub auth API HTTP error: %s - %s", e.response.status_code, e.response.text)
return {"error": f"HTTP error: {e.response.status_code} - {e.response.text}"}
return {"error": f"GitHub auth failed (status {e.response.status_code})"}
except Exception as e: # noqa: BLE001
logger.error("GitHub auth API call failed: %s: %s", type(e).__name__, str(e))
return {"error": str(e)}
@ -286,10 +293,19 @@ async def leave_failure_comment(
raise ValueError(f"Unknown source: {source}")
def _current_repo() -> Any:
"""Best-effort read of the run's repo (owner/name) for cache binding."""
try:
configurable = get_config().get("configurable", {})
except Exception:
return None
return configurable.get("repo") if isinstance(configurable, dict) else None
def _cache_resolved_github_token(
thread_id: str, token: str, expires_at: str | None = None
) -> tuple[str, str | None]:
cache_github_token_for_thread(thread_id, token, expires_at=expires_at)
cache_github_token_for_thread(thread_id, token, expires_at=expires_at, repo=_current_repo())
return token, expires_at
@ -383,7 +399,13 @@ async def _resolve_dashboard_user_token(
async def _resolve_bot_installation_token(thread_id: str) -> tuple[str, str | None]:
"""Get a GitHub App installation token and cache it for the thread."""
"""Get a GitHub App installation token and cache it for the thread.
AUTHZ-003 (accepted): in bot-token-only mode every run shares one GitHub App
installation token, so its blast radius is the whole installation rather than
a single user. This is a documented, accepted prod posture for this
single-tenant deployment, not a defect.
"""
bot_token, expires_at = await get_github_app_installation_token_with_expiry()
if not bot_token:
raise RuntimeError(
@ -418,33 +440,40 @@ async def resolve_github_token(config: RunnableConfig, thread_id: str) -> tuple[
github_login = configurable.get("github_login")
# Per-user OAuth from the dashboard store wins even in bot-token-only mode,
# for sources that carry a mapped GitHub login (Slack, dashboard). This is
# what lets the agent open PRs as the triggering user.
# DEFAULT: Slack/dashboard/schedule runs use the GitHub App installation token,
# so all git/gh operations + the PR come in as the app `seahaven-openswe[bot]`
# (deterministic; matches GitHub-issue runs; eliminates the self-review 422).
# OPT-IN: a profile with `author_prs_as_user: true` restores the per-user OAuth
# token so the run is attributed to the triggering user.
if (
source in ("slack", "dashboard", "schedule")
and isinstance(github_login, str)
and github_login.strip()
):
try:
user_token = await _resolve_dashboard_user_token(thread_id, github_login)
except ValueError as exc:
logger.error("GitHub auth failed for thread %s: %s", thread_id, str(exc))
raise RuntimeError(str(exc)) from exc
if user_token is not None:
return user_token
# No valid user token. In bot-token-only mode fall back to the bot so the
# deployment stays functional; otherwise block and require auth.
if is_bot_token_only_mode():
return await _resolve_bot_installation_token(thread_id)
raise GitHubUserAuthRequired(source, github_login)
from ..dashboard.agent_overrides import load_profile, profile_author_prs_as_user
if profile_author_prs_as_user(await load_profile(github_login.strip())):
try:
user_token = await _resolve_dashboard_user_token(thread_id, github_login)
except ValueError as exc:
logger.error("GitHub auth failed for thread %s: %s", thread_id, str(exc))
raise RuntimeError(str(exc)) from exc
if user_token is not None:
return user_token
# Opt-in set but no valid user token: in bot-token-only mode fall back
# to the bot; otherwise block and require auth.
if not is_bot_token_only_mode():
raise GitHubUserAuthRequired(source, github_login)
return await _resolve_bot_installation_token(thread_id)
if is_bot_token_only_mode():
return await _resolve_bot_installation_token(thread_id)
try:
if source == "github":
cached_token, cached_expires_at = await get_github_token_from_thread(thread_id)
cached_token, cached_expires_at = await get_github_token_from_thread(
thread_id, expected_repo=configurable.get("repo")
)
if cached_token:
return cached_token, cached_expires_at
from ..dashboard.user_mappings import email_for_login

View file

@ -10,11 +10,18 @@ import httpx
logger = logging.getLogger(__name__)
OPEN_SWE_BOT_NAME = "open-swe[bot]"
# Use the open-swe user noreply address: the bot's numeric noreply
# (215916821+open-swe[bot]@...) doesn't resolve to a GitHub account Vercel
# accepts, which broke preview deploys on commits carrying this co-author.
OPEN_SWE_BOT_EMAIL = "open-swe@users.noreply.github.com"
# Sea Haven fork identity: commits AND PRs come in as our GitHub App bot
# `seahaven-openswe[bot]` (user id 296972425) so Slack/dashboard/schedule runs are
# attributed to the app, not the triggering user (deterministic; eliminates the
# self-review 422). The numeric noreply is the canonical GitHub form.
# NOTE (Adam, 2026-06-29 — ACCEPTED RISK): the `<id>+<login>@users.noreply` form
# may NOT resolve to a GitHub account Vercel preview deploys accept (the upstream
# `open-swe[bot]` hit exactly this and worked around it with a non-numeric
# address). We deliberately accept that risk here in exchange for a consistent
# bot identity across commits + PRs. If Vercel preview deploys on a target repo
# start rejecting our commits, this is the cause — revert to a resolvable address.
OPEN_SWE_BOT_NAME = "seahaven-openswe[bot]"
OPEN_SWE_BOT_EMAIL = "296972425+seahaven-openswe[bot]@users.noreply.github.com"
@dataclass(frozen=True)

View file

@ -10,7 +10,12 @@ from .github_app import get_github_app_installation_token
logger = logging.getLogger(__name__)
INTERNAL_BOT_LOGINS: frozenset[str] = frozenset({"open-swe[bot]", "openswe-dev[bot]"})
# Bot logins whose webhook events are our OWN actions — never re-process them
# (self-trigger guard). Sea Haven's App is `seahaven-openswe[bot]`; the upstream
# `open-swe[bot]` / `openswe-dev[bot]` are kept for historical/test events.
INTERNAL_BOT_LOGINS: frozenset[str] = frozenset(
{"seahaven-openswe[bot]", "open-swe[bot]", "openswe-dev[bot]"}
)
async def is_user_active_org_member(username: str, org: str) -> bool:

View file

@ -17,22 +17,42 @@ _GITHUB_TOKEN_EXPIRY_SKEW_SECONDS = 60
# Hard cap on how long an entry stays cached regardless of the token's own
# expiry, so entries for threads that are never read again don't accumulate.
_GITHUB_TOKEN_MAX_TTL = timedelta(hours=24)
# thread_id -> (token, token_expires_at, cached_at)
_GITHUB_TOKEN_CACHE: dict[str, tuple[str, str | None, datetime]] = {}
# thread_id -> (token, token_expires_at, cached_at, bound_repo). ``bound_repo``
# ("owner/name") binds the entry to the repo it was resolved for so a colliding
# thread_id originating from a different repo cannot reuse another repo's token.
_GITHUB_TOKEN_CACHE: dict[str, tuple[str, str | None, datetime, str | None]] = {}
class GitHubAuthError(Exception):
"""Raised when a GitHub call returns 401, signalling a stale/revoked token."""
def repo_cache_key(repo: Any) -> str | None:
"""Normalize a repo dict/string to a casefolded ``owner/name`` (None if unknown).
GitHub owner/name are case-insensitive, so the key is casefolded on both the
write (binding) and read (compare) sides to keep ``Org/Repo`` and ``org/repo``
a single repo and avoid spurious cross-repo mismatches.
"""
if isinstance(repo, str):
cleaned = repo.strip()
return cleaned.casefold() or None
if isinstance(repo, Mapping):
owner = repo.get("owner")
name = repo.get("name")
if isinstance(owner, str) and isinstance(name, str) and owner and name:
return f"{owner}/{name}".casefold()
return None
def cache_github_token_for_thread(
thread_id: str, token: str, expires_at: str | None = None
thread_id: str, token: str, expires_at: str | None = None, *, repo: Any = None
) -> None:
"""Cache a GitHub token in process for the current thread."""
if not thread_id or not token:
return
now = datetime.now(UTC)
_GITHUB_TOKEN_CACHE[thread_id] = (token, expires_at, now)
_GITHUB_TOKEN_CACHE[thread_id] = (token, expires_at, now, repo_cache_key(repo))
_evict_expired(now=now)
@ -78,24 +98,37 @@ def _evict_expired(*, now: datetime | None = None) -> None:
current = now or datetime.now(UTC)
stale = [
tid
for tid, (_token, expires_at, cached_at) in _GITHUB_TOKEN_CACHE.items()
for tid, (_token, expires_at, cached_at, _repo) in _GITHUB_TOKEN_CACHE.items()
if _entry_expired(expires_at, cached_at, now=current)
]
for tid in stale:
_GITHUB_TOKEN_CACHE.pop(tid, None)
def _cached_token_if_fresh(thread_id: str | None) -> tuple[str | None, str | None]:
def _cached_token_if_fresh(
thread_id: str | None, *, expected_repo: Any = None
) -> tuple[str | None, str | None]:
if not thread_id:
return None, None
cached = _GITHUB_TOKEN_CACHE.get(thread_id)
if not cached:
return None, None
token, expires_at, cached_at = cached
token, expires_at, cached_at, bound_repo = cached
if _entry_expired(expires_at, cached_at, now=datetime.now(UTC)):
_GITHUB_TOKEN_CACHE.pop(thread_id, None)
logger.info("Cached GitHub token for thread %s has expired; re-resolving", thread_id)
return None, None
expected = repo_cache_key(expected_repo)
if expected and bound_repo and expected != bound_repo:
_GITHUB_TOKEN_CACHE.pop(thread_id, None)
logger.warning(
"Cached GitHub token for thread %s is bound to repo %s, not %s; "
"refusing cross-repo reuse",
thread_id,
bound_repo,
expected,
)
return None, None
return token, expires_at
@ -107,16 +140,27 @@ def _thread_id_from_config(run_config: Mapping[str, Any]) -> str | None:
return thread_id if isinstance(thread_id, str) and thread_id else None
def _repo_from_config(run_config: Mapping[str, Any]) -> Any:
configurable = run_config.get("configurable", {})
if not isinstance(configurable, Mapping):
return None
return configurable.get("repo")
def get_github_token(run_config: Mapping[str, Any] | None = None) -> str | None:
"""Resolve the current thread's GitHub token from process memory."""
resolved = run_config if run_config is not None else get_config()
token, _expires_at = _cached_token_if_fresh(_thread_id_from_config(resolved))
token, _expires_at = _cached_token_if_fresh(
_thread_id_from_config(resolved), expected_repo=_repo_from_config(resolved)
)
return token
async def get_github_token_from_thread(thread_id: str) -> tuple[str | None, str | None]:
async def get_github_token_from_thread(
thread_id: str, *, expected_repo: Any = None
) -> tuple[str | None, str | None]:
"""Resolve the current process's cached GitHub token for a thread."""
return _cached_token_if_fresh(thread_id)
return _cached_token_if_fresh(thread_id, expected_repo=expected_repo)
async def invalidate_cached_github_token(thread_id: str) -> None:

View file

@ -19,6 +19,7 @@ from deepagents.backends.protocol import (
)
from langgraph.config import get_config
from .github_token import repo_cache_key
from .sandbox import create_sandbox
logger = logging.getLogger(__name__)
@ -29,6 +30,9 @@ class SandboxBackendProxy(SandboxBackendProtocol):
def __init__(self, backend: SandboxBackendProtocol) -> None:
self._backend = backend
# "owner/name" of the repo this sandbox is bound to, used to refuse
# reuse by a different repo presenting a colliding thread_id.
self.bound_repo: str | None = None
@property
def current(self) -> SandboxBackendProtocol:
@ -131,21 +135,44 @@ def unwrap_sandbox_backend(sandbox_backend: SandboxBackendProtocol) -> SandboxBa
def set_sandbox_backend(
thread_id: str,
sandbox_backend: SandboxBackendProtocol,
*,
repo: str | None = None,
) -> SandboxBackendProxy:
if isinstance(sandbox_backend, SandboxBackendProxy):
if repo:
sandbox_backend.bound_repo = repo
SANDBOX_BACKENDS[thread_id] = sandbox_backend
return sandbox_backend
existing = SANDBOX_BACKENDS.get(thread_id)
if isinstance(existing, SandboxBackendProxy):
existing.replace_backend(sandbox_backend)
if repo:
existing.bound_repo = repo
return existing
proxy = SandboxBackendProxy(sandbox_backend)
if repo:
proxy.bound_repo = repo
SANDBOX_BACKENDS[thread_id] = proxy
return proxy
async def get_bound_repo_from_metadata(thread_id: str) -> str | None:
"""Fetch the repo (``owner/name``) this thread's sandbox is bound to."""
try:
config = get_config()
except Exception:
return None
metadata = config.get("metadata", {})
if not isinstance(metadata, dict):
return None
bound_repo = metadata.get("bound_repo")
# Casefold on read so legacy metadata written before normalization (e.g.
# ``Org/Repo``) still compares equal to the casefolded current repo key.
return repo_cache_key(bound_repo) if isinstance(bound_repo, str) and bound_repo else None
def clear_sandbox_backend(thread_id: str) -> None:
SANDBOX_BACKENDS.pop(thread_id, None)

View file

@ -1339,8 +1339,32 @@ async def process_slack_mention(event_data: dict[str, Any], repo_config: dict[st
)
LINEAR_WEBHOOK_MAX_AGE_SECONDS = 60
def _linear_timestamp_is_fresh(body: bytes) -> bool:
"""Reject replays: the signed payload's ``webhookTimestamp`` must be recent.
Linear includes ``webhookTimestamp`` (Unix milliseconds) inside the signed
body. Fail closed when it is missing or malformed.
"""
try:
ts_ms = json.loads(body)["webhookTimestamp"]
except (json.JSONDecodeError, KeyError, TypeError):
logger.warning("Linear webhook missing/invalid webhookTimestamp — rejecting")
return False
if not isinstance(ts_ms, (int, float)) or isinstance(ts_ms, bool):
logger.warning("Linear webhook webhookTimestamp is not numeric — rejecting")
return False
now_ms = datetime.now(UTC).timestamp() * 1000
if abs(now_ms - ts_ms) > LINEAR_WEBHOOK_MAX_AGE_SECONDS * 1000:
logger.warning("Linear webhook timestamp outside freshness window — rejecting")
return False
return True
def verify_linear_signature(body: bytes, signature: str, secret: str) -> bool:
"""Verify the Linear webhook signature.
"""Verify the Linear webhook signature and replay-freshness window.
Args:
body: Raw request body bytes
@ -1348,15 +1372,17 @@ def verify_linear_signature(body: bytes, signature: str, secret: str) -> bool:
secret: The webhook signing secret
Returns:
True if signature is valid, False otherwise
True if the signature is valid AND the signed timestamp is fresh.
"""
if not secret:
logger.warning("LINEAR_WEBHOOK_SECRET is not configured — rejecting webhook request")
return False
expected = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, signature):
return False
return hmac.compare_digest(expected, signature)
return _linear_timestamp_is_fresh(body)
@app.post("/webhooks/linear")
@ -2920,31 +2946,36 @@ async def process_github_autofix_review(payload: dict[str, Any], event_type: str
)
async def _refresh_thread_github_token_after_401(thread_id: str, email: str) -> str | None:
async def _refresh_thread_github_token_after_401(
thread_id: str, email: str, *, repo: dict[str, str] | None = None
) -> str | None:
"""Invalidate the cached token after a 401 and try to resolve a fresh one."""
logger.warning(
"GitHub returned 401 for thread %s; invalidating cached token and re-resolving",
thread_id,
)
await invalidate_cached_github_token(thread_id)
return await _get_or_resolve_thread_github_token(thread_id, email)
return await _get_or_resolve_thread_github_token(thread_id, email, repo=repo)
async def _get_or_resolve_thread_github_token(thread_id: str, email: str) -> str | None:
async def _get_or_resolve_thread_github_token(
thread_id: str, email: str, *, repo: dict[str, str] | None = None
) -> str | None:
"""Resolve and cache a GitHub token for a thread when available.
In bot-token-only mode, returns a fresh GitHub App installation token
instead of resolving per-user OAuth tokens.
instead of resolving per-user OAuth tokens. ``repo`` (owner/name) binds the
cached entry so a colliding thread_id from a different repo cannot reuse it.
"""
if is_bot_token_only_mode():
bot_token, expires_at = await get_github_app_installation_token_with_expiry()
if bot_token:
cache_github_token_for_thread(thread_id, bot_token, expires_at=expires_at)
cache_github_token_for_thread(thread_id, bot_token, expires_at=expires_at, repo=repo)
return bot_token
logger.warning("Bot-token-only mode but GitHub App token unavailable")
return None
github_token, _expires_at = await get_github_token_from_thread(thread_id)
github_token, _expires_at = await get_github_token_from_thread(thread_id, expected_repo=repo)
if github_token:
return github_token
@ -2955,7 +2986,10 @@ async def _get_or_resolve_thread_github_token(thread_id: str, email: str) -> str
expires_at = auth_result.get("expires_at")
cache_github_token_for_thread(
thread_id, github_token, expires_at=expires_at if isinstance(expires_at, str) else None
thread_id,
github_token,
expires_at=expires_at if isinstance(expires_at, str) else None,
repo=repo,
)
return github_token
@ -3017,7 +3051,7 @@ async def process_github_pr_comment(payload: dict[str, Any], event_type: str) ->
email = await email_for_login(github_login) or ""
if email:
github_token = await _get_or_resolve_thread_github_token(thread_id, email)
github_token = await _get_or_resolve_thread_github_token(thread_id, email, repo=repo_config)
else:
logger.warning("No email mapping for GitHub user '%s', skipping", github_login)
return
@ -3037,7 +3071,9 @@ async def process_github_pr_comment(payload: dict[str, Any], event_type: str) ->
node_id=node_id,
)
except GitHubAuthError:
github_token = await _refresh_thread_github_token_after_401(thread_id, email)
github_token = await _refresh_thread_github_token_after_401(
thread_id, email, repo=repo_config
)
if not github_token:
logger.warning("Re-auth failed for thread %s after 401; skipping", thread_id)
return
@ -3059,7 +3095,9 @@ async def process_github_pr_comment(payload: dict[str, Any], event_type: str) ->
repo_config, pr_number, token=github_token
)
except GitHubAuthError:
github_token = await _refresh_thread_github_token_after_401(thread_id, email)
github_token = await _refresh_thread_github_token_after_401(
thread_id, email, repo=repo_config
)
if not github_token:
logger.warning("Re-auth failed for thread %s after 401; skipping", thread_id)
return
@ -3141,7 +3179,7 @@ async def process_github_review_finding_reply(payload: dict[str, Any]) -> None:
sender = payload.get("sender", {})
sender_login = sender.get("login") if isinstance(sender, dict) else None
if sender_login == "open-swe[bot]":
if sender_login in INTERNAL_BOT_LOGINS:
return
repo = payload.get("repository", {})
@ -3297,7 +3335,7 @@ async def process_github_issue(payload: dict[str, Any], event_type: str) -> None
thread_id = generate_thread_id_from_github_issue(issue_id)
existing_thread = await _thread_exists(thread_id)
github_token = await _get_or_resolve_thread_github_token(thread_id, email)
github_token = await _get_or_resolve_thread_github_token(thread_id, email, repo=repo_config)
app_token = await get_github_app_installation_token()
reaction_token = github_token or app_token
comment = payload.get("comment", {})
@ -3314,7 +3352,9 @@ async def process_github_issue(payload: dict[str, Any], event_type: str) -> None
token=reaction_token,
)
except GitHubAuthError:
github_token = await _refresh_thread_github_token_after_401(thread_id, email)
github_token = await _refresh_thread_github_token_after_401(
thread_id, email, repo=repo_config
)
reaction_token = github_token or app_token
reacted = False
if reaction_token:
@ -3348,7 +3388,9 @@ async def process_github_issue(payload: dict[str, Any], event_type: str) -> None
repo_config, issue_number, token=github_token or app_token
)
except GitHubAuthError:
github_token = await _refresh_thread_github_token_after_401(thread_id, email)
github_token = await _refresh_thread_github_token_after_401(
thread_id, email, repo=repo_config
)
comments = await fetch_issue_comments(
repo_config, issue_number, token=github_token or app_token
)

View file

@ -1,118 +1,278 @@
# Sea Haven — Open SWE self-hosted deployment
# Sea Haven — Open SWE deployment runbook
How this fork is deployed at Sea Haven. The runtime is the **stock LangGraph dev
server** (not the Aegra path — see [Aegra](#aegra-deferred)). Internal addresses,
ARNs, and account IDs are shown as `<PLACEHOLDERS>`; the real values live in the
private IT docs (Confluence "AWS Architecture Map") — **do not commit them to this
public fork.**
How this fork is deployed at Sea Haven. **PROD is LIVE as of 2026-06-29.** The
runtime is the **stock LangGraph dev server** (not the Aegra path — see
[Aegra](#aegra-deferred)), running on a self-hosted ARM64 EC2 box behind the
shared `seahaven-com` ALB.
## Topology
Account `328440206208`, region `us-east-1`. Internal addresses, ARNs, snapshot
ids, and account-scoped values that are sensitive are shown as `<PLACEHOLDERS>`;
the real values live in the private IT docs (Confluence "AWS Architecture Map",
id 1540098) and in AWS — **do not commit them to this public fork.**
```
GitHub / Slack ──▶ hooks.seahavenind.com ──┐
│ (public ALB :443, host+path rule)
Browser ─────────▶ openswe.seahavenind.com ─┤
▼
AWS ALB ──(Site-to-Site VPN)──▶ on-prem VM
├─ nginx :80 (dashboard SPA + /dashboard/api proxy)
└─ langgraph dev :2024 (3+ graphs + FastAPI webapp)
└─▶ LangSmith cloud sandbox (build/git/PR)
```
This is the canonical deploy runbook. The CDK details live in
[`infra/README.md`](../../infra/README.md); the rotation procedure in
[`ROTATION.md`](ROTATION.md).
- The VM is **internet-closed**; all inbound rides the existing ALB over the VPN.
- **Webhooks** (`hooks.seahavenind.com`) → ALB listener rule scoped to `/webhooks/*`
only → VM `:2024`. The unauthenticated LangGraph API (`/threads`, `/runs`,
`/assistants`, `/store`) is never path-forwarded.
- **Dashboard** (`openswe.seahavenind.com`) → ALB → VM `:80` (nginx). nginx is the
security boundary: it serves the static SPA and proxies **only** `/dashboard/api/`
to `:2024`; the agent API is not reachable through it.
## Live prod facts (2026-06-29)
## VM components
| Component | What |
| | |
|---|---|
| `langgraph dev` | systemd `open-swe.service` — `--host 0.0.0.0 --port 2024 --no-browser --no-reload`. In-memory runtime. |
| Store seeding | `seed_store.sh` as `ExecStartPost` (re-seeds team settings + user mappings, which the in-memory store loses on restart). |
| nginx | `nginx/openswe.conf` — SPA from `/var/www/openswe`, proxy `/dashboard/api/` → `:2024`. |
| Postgres | present (was for the Aegra path); unused by the stock in-memory runtime. |
| swap | 8 GB swapfile — **required**: the dashboard (`ui/`) Nitro build OOMs on an 8 GB box without it. |
| Dashboard | `https://openswe.seahaven.com` |
| Webhooks | `https://hooks.seahaven.com/webhooks/*` |
| Ingress | shared internet-facing ALB `app/seahaven-com` → target group `open-swe-prod-tg` → EC2 `i-08a729e50779c4b07` (`t4g.large`, ARM64) on nginx `:80` |
| Backend | `langgraph dev` bound to `127.0.0.1:2024` (loopback only); nginx is the sole ingress |
| CDK stacks | `open-swe-iam` (OIDC roles) · `open-swe-dev` · `open-swe-prod` |
### Models
Model selection is **store-driven**, not env. `LLM_MODEL_ID` is effectively dead for
runtime selection; the `team_settings/default` store doc wins (then per-user profile,
then per-thread). Defaults seeded by `seed_store.sh`:
- builder: `anthropic:claude-opus-4-8` (effort `high`)
- reviewer (cross-family): `openai:gpt-5.5` (effort `high`) — `openai:gpt-4.1` is **not**
in this fork's `SUPPORTED_MODELS` (`agent/dashboard/options.py`); a raw value is
silently rewritten to gpt-5.5. Add it to `SUPPORTED_MODELS` first if you need 4.1.
- `analyzer` graph is hardcoded to the code default and ignores team settings.
Dev mirrors prod with `-dev` hosts (`openswe-dev.seahaven.com` /
`hooks-dev.seahaven.com`), a `t4g.medium` box, and no GitHub-App/Slack/webhook
integration (it is a deployment-validation env, not a live-triggered agent).
## Build & deploy the dashboard (`ui/`)
> The retired on-prem `*.seahavenind.com` ALB routing and DNS were removed on
> 2026-06-29; prod is now live exclusively on `*.seahaven.com`.
`ui/` is a **TanStack Start + Nitro** app (build with `bun`, not plain Vite):
## Hosting model
```
GitHub / Slack ──▶ hooks.seahaven.com ──┐
│ (shared ALB :443, host+path rules)
Browser ─────────▶ openswe.seahaven.com ──┤
▼
ALB app/seahaven-com ──▶ open-swe-prod-tg ──▶ EC2 box :80 (nginx)
├─ nginx — SPA + scoped proxy
│ /dashboard/api/* and /webhooks/*
└─ langgraph dev 127.0.0.1:2024
└─▶ LangSmith cloud sandbox (build/git/PR)
```
- A **single** VPC and a **single** internet-facing ALB (`app/seahaven-com`) are
shared with the on-prem `seahaven-site` stack. open-swe **imports** the VPC,
ALB SG, `:443` listener, and `seahaven.com` zone — it never owns/mutates them;
it only adds its own instance SG, a standalone ALB-egress rule, two listener
rules, a target group, and Route53 aliases.
- The EC2 box is in a **private** subnet (us-east-1a, same AZ as the single NAT
for in-AZ egress). It is reachable **only** from the shared ALB SG on `:80`.
- **nginx is the security boundary.** It serves the static dashboard SPA and
proxies exactly two prefixes to `:2024` — `/dashboard/api/*` and `/webhooks/*`.
The unauthenticated LangGraph API (`/threads`, `/runs`, `/assistants`,
`/store`) is never proxied; those paths return the SPA shell. `:2024` is
loopback-only and never network-reachable, even inside the SG.
- **Webhooks** ride listener rules below the on-prem host-agnostic `/webhooks/*`
rule (priority 2 dev / 3 prod, host-scoped to the open-swe hosts) so they reach
the open-swe box and never steal an on-prem host's webhooks.
The box holds **no durable state of its own**: secrets/config are materialized to
a tmpfs `.env` at boot, the app artifact is pulled from S3, and the in-memory
LangGraph store is re-seeded on every start. Replacement is tolerated; there is no
RETAIN volume.
---
## Deploy pipeline (end to end)
Two independent CD lanes, both OIDC-only (no static keys), both with a manual
approval gate on prod via the GitHub **`prod` Environment** (required reviewer:
Adam). The `environment: prod` declaration both fires the approval gate and makes
the OIDC subject `…:environment:prod`, which is the only subject the prod deploy
roles trust — so a dev-branch token can never reach prod.
### (a) Infra CD — `cd-infra.yml`
Deploys the CDK stacks. Path-filtered to `infra/**`.
```
push to dev → Infra CI (tsc + jest + cdk synth) → cdk deploy OpenSweDevStack (AUTO, CI-green-gated)
push to main → Infra CI → cdk deploy OpenSweProdStack (manual approval: env "prod")
```
- Roles: `githubdeploy-open-swe-infra-{dev,prod}` (in the `open-swe-iam` stack;
set as repo variables `AWS_DEPLOY_ROLE_INFRA_{DEV,PROD}`).
- It targets **one stack explicitly per env** (`cdk deploy OpenSweDevStack` /
`OpenSweProdStack`), not `cdk deploy --all`, so a single-env push can never
deploy the other env or the shared IAM stack.
- The shared `open-swe-iam` stack (owns both envs' OIDC deploy roles) is **not**
deployed by CD — it is a privileged, human-gated apply.
**Stack order on a clean account:** `open-swe-iam` first (creates the OIDC roles;
set the repo deploy-role variables and configure the `prod` Environment reviewer
from its outputs), then `open-swe-dev`, then `open-swe-prod`.
### (b) Seed the config store — `put-config.sh <env>`
Run **after** `cdk deploy open-swe-<env>` and **before** the box first boots. CDK
creates the value-less Secrets Manager shells (`open-swe-<env>/<VAR>`) and the
IaC-managed SSM params (`/open-swe-<env>/<VAR>`); `put-config.sh` populates the
secret values plus the out-of-band SSM params that cannot live in IaC.
```bash
cd ui
export PATH="$HOME/.bun/bin:$PATH"
export NODE_OPTIONS=--max-old-space-size=6144 # + the 8 GB swapfile, or the build OOMs
bun install
bun run build # -> .output/public (static SPA, _shell.html)
sudo cp -r .output/public/. /var/www/openswe/ # served by nginx
deploy/seahaven/put-config.sh <dev|prod> # set each value inline, via OPENSWE_PUT_<VAR>, or from a vault
deploy/seahaven/fetch-config.sh <dev|prod> # (on the box) fail-fast verify before first start
```
Served as a static SPA (per `ui/vercel.json`); the Nitro `.output/server` is unused.
`put-config.sh` ships `<FILL>` placeholders only — **no real secret values are
committed**. It does not touch the IaC-managed SSM params (CDK owns those).
## Install / wire-up checklist
**13 prod boot-required vars** — `fetch-config.sh` fail-fasts (refuses to write a
partial `.env`, the unit does not start) if any are missing/empty:
1. App config in `.env` (gitignored — never commit): LLM keys, GitHub App creds,
`LANGSMITH_API_KEY*` + `DEFAULT_SANDBOX_SNAPSHOT_ID` (`SANDBOX_TYPE=langsmith` — the
only sandbox provider with working in-sandbox git/gh auth), `LANGGRAPH_URL=http://127.0.0.1:2024`,
dashboard vars (`DASHBOARD_JWT_SECRET`, `CONFIGURED_ADMINS`, `DASHBOARD_*_URL=https://openswe.seahavenind.com`).
2. `systemd/open-swe.service` → `/etc/systemd/system/`, `seed_store.sh` on the VM with
`OPENSWE_*` env exported (owner login/email, default repo, model ids).
3. `nginx/openswe.conf` → `/etc/nginx/sites-available/openswe`, symlink into
`sites-enabled`, remove the default site, `nginx -t && systemctl reload nginx`.
4. AWS (real IDs in Confluence): IP target groups → `<VM_LAN_IP>:2024` and `:80`;
ALB SG **egress** rules to those ports (the ALB SG is allow-listed — health checks
time out without them); `:443` listener rules for the two hostnames; Route53 ALIAS
records → ALB. Webhook rule must stay path-scoped to `/webhooks/*`.
5. GitHub App: webhook URL `https://hooks.seahavenind.com/webhooks/github`; subscribe to
the events the install guide lists (Issue comment, PR review×2, check_run/suite,
workflow_run, status) — add **Issues** too if you want issue-title/body triggers.
6. **GitHub App OAuth callback (manual, UI-only — not API-settable):**
`https://openswe.seahavenind.com/dashboard/api/auth/callback` — without it, dashboard
login fails with a `redirect_uri` mismatch.
- **9 secrets** (Secrets Manager `open-swe-prod/<VAR>`): `DASHBOARD_JWT_SECRET`,
`TOKEN_ENCRYPTION_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`,
`LANGSMITH_API_KEY_PROD`, `GITHUB_APP_PRIVATE_KEY`, `GITHUB_APP_CLIENT_SECRET`,
`GITHUB_WEBHOOK_SECRET`, `SLACK_SIGNING_SECRET`.
- **4 SSM params** (`/open-swe-prod/<VAR>`): `DEFAULT_SANDBOX_SNAPSHOT_ID`,
`GITHUB_APP_ID`, `GITHUB_APP_INSTALLATION_ID`, `GITHUB_APP_CLIENT_ID`.
(`ANTHROPIC_API_KEY` + `OPENAI_API_KEY` are required because that is the seeded
cross-family pair; the active set follows `REQUIRED_PROVIDER_KEYS`. The
`LANGSMITH_API_KEY_PROD` + `DEFAULT_SANDBOX_SNAPSHOT_ID` pair is required because
`SANDBOX_TYPE=langsmith`.) Dev boots without the GitHub-App / Slack / webhook
secrets — it has no such integration.
`fetch-config.sh` runs as an `ExecStartPre=+` hook (root, only long enough to
write the `openswe`-owned `0600` tmpfs `.env`), reads all `/open-swe-<env>/*` SSM
params + all `open-swe-<env>/*` secrets via the instance role, and forces
`DEFAULT_REPO_OWNER` away from the upstream `langchain-ai` org.
### (c) App artifact deploy — `build-artifacts.yml`
Builds the release and rolls the box. Path-filtered to `agent/**`, `ui/**`,
`deploy/**`, `langgraph.json`, `pyproject.toml`, `uv.lock`.
```
push to dev → build SPA + package → open-swe-dev-assets/releases/ → SSM open-swe-dev-deploy (AUTO)
push to main → build SPA + package → open-swe-prod-assets/releases/ → SSM open-swe-prod-deploy (manual approval: env "prod")
```
1. The dashboard SPA is built **on the runner** (`bun run build` → vite →
`ui/.output/public`) — the box is small, so the memory-heavy build runs in CI.
2. `package-artifacts.sh` produces two tarballs: `spa.tar.gz` (built SPA) and
`app.tar.gz` (Python source tree — no `ui/`, no `.venv`).
3. Both are uploaded to S3 `open-swe-<env>-assets` under `releases/<sha>/`
(immutable, auditable) and mirrored to `releases/latest/` (what the box pulls).
4. CI fires the `open-swe-<env>-deploy` SSM document (tag-scoped to
`project=open-swe,env=<env>`), which runs `/opt/open-swe/bin/deploy.sh` on the
box: pull the release from S3, build a native-ARM64 venv with
`uv sync --frozen --no-dev`, extract the SPA to the nginx web root,
`systemctl restart open-swe.service`, reload nginx, then gate on
`systemctl is-active --quiet open-swe.service` (a non-active unit exits the
deploy non-zero).
Roles: `githubdeploy-open-swe-app-{dev,prod}` (repo variables
`AWS_DEPLOY_ROLE_APP_{DEV,PROD}`) — tag-scoped `ssm:SendCommand` on the deploy
document only (not the generic `AWS-RunShellScript`) + write to the env's S3
bucket.
Secrets/config are **not** fetched by `deploy.sh`; the `systemctl restart`'s
`ExecStartPre=fetch-config.sh` re-materializes the `.env` on every restart, so a
bad config surfaces as a failed unit.
### (d) dev → main promotion + rollback
**Promotion — `promote-dev-to-prod.yml`** (nightly cron `0 8 * * *` + manual
dispatch): mints a GitHub App installation token (a bypass actor on the `main`
ruleset), gates on **every check-run on the dev HEAD commit being completed and
passing**, then **fast-forward-only** pushes `dev` → `main`. A diverged `main`
fails loudly rather than force-updating. The push to `main` is what triggers the
prod lanes of `cd-infra.yml` / `build-artifacts.yml` (each still behind the `prod`
Environment approval). Re-gating via a PR on `main` would be redundant since the
commit already passed every check on dev.
**Rollback — `rollback.yml`** (manual dispatch, `env` + optional `sha`): re-points
`releases/latest/` at a prior release and re-fires the `open-swe-<env>-deploy` SSM
document — same fire/wait/gate path as a forward deploy, no rebuild.
```
env=dev, sha blank → restore open-swe-dev-assets/releases/last-good/ (AUTO)
env=prod, sha blank → restore open-swe-prod-assets/releases/last-good/ (manual approval: env "prod")
sha=<commit> → restore that exact releases/<sha>/ instead
```
It reuses the existing `githubdeploy-open-swe-app-<env>` role (no new IAM).
---
## On-box layout (reference)
| Path | What |
|---|---|
| `open-swe.service` (systemd) | `langgraph dev --host 127.0.0.1 --port 2024 --no-browser --no-reload` as the unprivileged `openswe` user. In-memory runtime. |
| `fetch-config.sh` | `ExecStartPre=+` — materializes the tmpfs `.env` from Secrets Manager + SSM, fail-fast. |
| `seed_store.sh` | `ExecStartPost` — re-seeds `team_settings/default` + `user_mappings` (the in-memory store loses them on every restart). |
| nginx | SPA from `/var/www/open-swe`, proxy `/dashboard/api/` + `/webhooks/` → `127.0.0.1:2024`, `/healthz` → 200. |
| `deploy.sh` | the release procedure run on first boot (non-fatal) and by every SSM deploy. |
| CloudWatch logs | `/open-swe/<env>/{app,user-data,nginx-access,nginx-error}` at 30-day retention. |
The live systemd unit + nginx site are the **AMI templates**
(`deploy/ami/templates/open-swe.service`, `open-swe.nginx.conf`), rendered at
first boot by `deploy/ami/user-data.sh`. The AMI is the baked
`open-swe-base-arm64` image (Ubuntu 24.04 + uv/py3.12 + nginx + CW agent), pinned
by exact id in `infra/lib/constructs/ami-cache.ts`. There is intentionally **no**
on-box swapfile — the OOM-prone SPA build now runs in CI, not on the box.
> `deploy/seahaven/{nginx/openswe.conf,systemd/open-swe.service}` are the
> **retired on-prem VM** variants (run as `adam` from a home dir, bound `0.0.0.0`,
> Postgres-backed). They are kept only for on-prem-contrast reference and are not
> used by the AWS deployment.
### Models
Model selection is **store-driven**, not env. The `team_settings/default` store
doc wins (then per-user profile, then per-thread); `LLM_MODEL_ID` is only a
seed-time fallback. Defaults seeded by `seed_store.sh`:
- builder: `anthropic:claude-opus-4-8` (effort `high`)
- reviewer (cross-family): `openai:gpt-5.5` (effort `high`) — `openai:gpt-4.1` is
**not** in this fork's `SUPPORTED_MODELS` (`agent/dashboard/options.py`); add it
there first if you need 4.1.
- the `analyzer` graph is hardcoded to the code default and ignores team settings.
## Triggering
Start a task by mentioning **`@openswe`** in a GitHub issue comment (the documented
intake — the `open-swe` *label* path needs the `Issues` event subscription). The
commenter must have a `user_mappings` entry or the run is skipped.
Mention **`@openswe`** (or `@open-swe` / `@seahaven-openswe`) in a GitHub issue or
PR comment, a Linear comment, or a Slack thread. The commenter must have a
`user_mappings` entry (seeded by `seed_store.sh` from `CONFIGURED_ADMINS` /
`SEED_USER_MAPPINGS`) or the run is skipped.
## AWS variant — env-sourced config (.env from Secrets Manager + SSM)
Live integration endpoints (set in each provider's app config):
On the AWS lift-and-shift, the `.env` is **not** staged by hand. A boot hook pulls
config from AWS via the EC2 instance role and materializes a root-only `.env` on a
tmpfs before the service starts. Same stock runtime; only how `.env` is produced
changes.
| File | Role |
| Integration | URL |
|---|---|
| `fetch-config.sh <dev\|prod>` | `ExecStartPre=+` hook. Reads all SSM params `/open-swe-<env>/*` + all secrets `open-swe-<env>/*`, FAIL-FAST on any missing required var, writes `/run/open-swe/.env` (tmpfs, root:root 0600), symlinks `<APP_DIR>/.env` → it. Forces `DEFAULT_REPO_OWNER`=`Sea-Haven-Industries` (never upstream `langchain-ai`). |
| `seed_store.sh <dev\|prod>` | `ExecStartPost` hook (unchanged role). Now sources the materialized `.env`, so `default_repo`/models/user-mappings come from AWS config instead of hardcoded `OPENSWE_*`. Still re-seeds the in-memory store on **every** restart. |
| `ROTATION.md` | How to rotate any secret/param (update AWS → `systemctl restart`) + per-secret notes (`TOKEN_ENCRYPTION_KEY` overlap list, GitHub App PEM, webhook signing secrets). |
| GitHub webhook | `https://hooks.seahaven.com/webhooks/github` |
| Slack events | `https://hooks.seahaven.com/webhooks/slack` (+ `/webhooks/slack/interactivity`) |
| Linear webhook | `https://hooks.seahaven.com/webhooks/linear` |
| GitHub OAuth callback | `https://openswe.seahaven.com/dashboard/api/auth/callback` |
Because the `.env` is root-only, the AWS `open-swe.service` runs **as root** (the
on-prem unit's `User=adam` cannot read it). See the header of `fetch-config.sh` for
the exact unit snippet and the tmpfs / `RUN_DEDICATED_TMPFS` options. Naming/secret
placement follows the T9 inventory: 29 secrets → Secrets Manager `open-swe-<env>/*`,
53 config → SSM `/open-swe-<env>/*`, each keyed by the literal env-var name.
---
## Troubleshooting
**RETAIN secret-shell orphan on stack re-create.** The Secrets Manager shells use
`DeletionPolicy: Retain` + a fixed `open-swe-<env>/<VAR>` name. If a stack's first
create rolls back (or on a teardown/rebuild, a secret logical-id refactor, or
standing up a new env), the empty shells survive and keep their global names, so
every later create fails `AlreadyExists` — and a plain `delete-secret` does not
free the name (it stays reserved for the 7–30 day recovery window). Before
re-creating the stack, **force-delete the empty orphans** (only shells with no
value version — never a populated secret). Hit on prod 2026-06-29 (PR #51 deploy
failure). Full recovery command + rationale:
[`infra/README.md`](../../infra/README.md) (PR #52).
**`langgraph dev` won't start after a deploy.** `fetch-config.sh` fail-fasts on a
missing/empty required var and prints the offending variable **names** (never
values) to the unit journal. Confirm the 13 prod boot-required vars are populated
(`put-config.sh prod`), then `systemctl restart open-swe.service`.
**ALB target unhealthy.** The TG health check is `GET /healthz` on nginx `:80`
(static 200). nginx starts before the app on first boot, so an unhealthy target
usually means the box can't reach the ALB SG on `:80` (the standalone ALB-egress
rule) rather than an app fault.
---
## Aegra (deferred)
`aegra/aegra.json` + `aegra/aegra_entry.py` are the self-hosted-runtime alternative
(Apache-2.0, avoids the LangGraph-Platform Elastic license). Not active on the stock
deployment. To use: place both at the repo root, run `aegra serve` (:2026), and point
`LANGGRAPH_URL` at `:2026`. Aegra gives a Postgres-backed durable store/checkpointer,
which removes the need for `seed_store.sh` and survives restarts (paused HITL
interrupts persist).
`aegra/aegra.json` + `aegra/aegra_entry.py` are the self-hosted-runtime
alternative (Apache-2.0, avoids the LangGraph-Platform Elastic license). Not
active on the stock deployment. To use: place both at the repo root, run
`aegra serve` (:2026), and point `LANGGRAPH_URL` at `:2026`. Aegra gives a
Postgres-backed durable store/checkpointer, which removes the need for
`seed_store.sh` and survives restarts (paused HITL interrupts persist).
</content>

View file

@ -1,10 +1,14 @@
# Open SWE dashboard frontend (TanStack Start SPA) + scoped API proxy.
# RETIRED on-prem VM variant — kept for on-prem-contrast reference only. The LIVE
# AWS nginx site is the AMI template deploy/ami/templates/open-swe.nginx.conf
# (rendered from an @@SERVER_NAME@@ token at first boot). See DEPLOYMENT.md.
#
# nginx is the security boundary: ONLY /dashboard/api/* reaches the backend;
# the unauthenticated LangGraph agent API (/threads,/runs,/assistants,/store) is NOT proxied.
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name openswe.seahavenind.com;
server_name openswe.seahaven.com;
root /var/www/openswe;
index _shell.html;

View file

@ -66,6 +66,32 @@ never defaults to PascalCase; resource names follow `open-swe-<env>-*`.
The GitHub OIDC provider already exists account-wide (created for seahaven-site);
it is referenced by ARN, never re-created.
## CDK bootstrap qualifiers — per-env deploy isolation (B-1 / OSWE-IAC-01)
Each env's infra deploy role may assume **only its own bootstrap qualifier's**
roles, so a dev-branch token can never assume the bootstrap roles whose admin
`cfn-exec-role` deploys prod (closing the cross-env escalation that bypassed
prod's Environment approval gate). Mapping lives in `config.ts:bootstrapQualifier`:
| Env | Qualifier | Toolkit stack | Infra role assumes |
|---|---|---|---|
| dev | `oswedev` | `CDKToolkit-oswedev` | `cdk-oswedev-*` |
| prod | `hnb659fds` (default) | `CDKToolkit` | `cdk-hnb659fds-*` |
The dev stack synthesizes with `DefaultStackSynthesizer({ qualifier: "oswedev" })`
(`bin/app.ts`); prod uses the default. Bootstrap a new env qualifier with:
```bash
npx cdk bootstrap --qualifier <qual> --toolkit-stack-name CDKToolkit-<qual> \
--cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \
aws://328440206208/us-east-1
```
**Deploy order matters** when changing an env's qualifier: bootstrap the new
qualifier and deploy the env stack onto it **before** re-scoping that env's infra
role in `open-swe-iam` — otherwise a pipeline deploy with the re-scoped role would
fail to assume the not-yet-targeted bootstrap roles.
## Kebab-case naming Aspect
`KebabNamingAspect` (applied app-wide in `bin/app.ts`) fails synth via
@ -98,6 +124,27 @@ Three buckets:
> **Confirm** the 27-vs-29 count (code-only candidates not in the table:
> `USER_ID_API_KEY_MAP`, `JUDGE_ANTHROPIC_BASE_URL`).
> ⚠️ **`Retain` + fixed name orphans these shells on a failed FIRST create.**
> If the stack's initial create fails and rolls back, `Retain` keeps the shells
> instead of deleting them. The stack is then gone, but the secrets survive,
> still holding the global `open-swe-<env>/<VAR>` names — so every later create
> fails with `AlreadyExists`. A plain `delete-secret` does **not** clear it
> (the name stays reserved for the 7–30 day recovery window). This bites on a
> **teardown/rebuild, a secret logical-id change/refactor, or standing up a new
> env** — never on routine updates of an already-created stack. **Recovery —**
> before re-creating the stack, force-delete the *empty* orphans so the names
> free immediately:
> ```bash
> aws secretsmanager list-secrets --region us-east-1 \
> --filters Key=name,Values=open-swe-<env>/ \
> --query 'SecretList[].Name' --output text | tr '\t' '\n' | while read -r n; do
> aws secretsmanager delete-secret --secret-id "$n" \
> --region us-east-1 --force-delete-without-recovery
> done
> ```
> Force-delete only shells with **no value version** — a populated secret holds
> real operator material. (Hit on prod 2026-06-29; see PR #51's deploy failure.)
2. **IaC-managed SSM config — 8 params, real values owned in code:**
| Param | dev | prod |

View file

@ -1,7 +1,7 @@
#!/usr/bin/env node
import "source-map-support/register";
import * as cdk from "aws-cdk-lib";
import { ACCOUNT, REGION } from "../lib/config";
import { ACCOUNT, REGION, bootstrapQualifier } from "../lib/config";
import { OpenSweIamStack } from "../lib/open-swe-iam-stack";
import { OpenSweStack } from "../lib/open-swe-stack";
import { KebabNamingAspect } from "../lib/aspects/kebab-naming-aspect";
@ -17,10 +17,18 @@ new OpenSweIamStack(app, "OpenSweIamStack", {
// The two env stacks — explicit kebab-case stackName (never let CDK default to
// PascalCase), env-parameterised so resources are `open-swe-<env>-*`.
//
// B-1 / OSWE-IAC-01: dev synthesizes against its OWN bootstrap qualifier
// (`oswedev`), so it deploys via the cdk-oswedev-* roles the dev infra role is
// scoped to — and NOT the default hnb659fds bootstrap roles that deploy prod.
// Prod stays on the default qualifier (no synthesizer override).
new OpenSweStack(app, "OpenSweDevStack", {
stackName: "open-swe-dev",
env,
envName: "dev",
synthesizer: new cdk.DefaultStackSynthesizer({
qualifier: bootstrapQualifier("dev"),
}),
});
new OpenSweStack(app, "OpenSweProdStack", {

View file

@ -28,16 +28,28 @@ export const prefix = (env: EnvName): string => `open-swe-${env}`;
* Each env gets its OWN infra + app role (githubdeploy-open-swe-{infra,app}-<env>)
* so a dev token cannot reach prod. Exact subject → StringEquals (no `*`).
*
* Residual (documented): CDK's single account-wide `cfn-exec-role` means the dev
* INFRA role can still technically `cdk deploy open-swe-prod`; the workflow only
* ever targets its own env stack, and prod's environment-gated role is the
* approved path. Per-env bootstrap qualifiers would close this fully (future).
* Cross-env deploy isolation is enforced at the bootstrap layer too — see
* `bootstrapQualifier`: dev runs on its own qualifier so the dev infra role
* cannot assume the bootstrap roles that deploy prod.
*/
export const oidcSubject = (env: EnvName): string =>
env === "prod"
? `repo:${GITHUB_ORG}/${GITHUB_REPO}:environment:prod`
: `repo:${GITHUB_ORG}/${GITHUB_REPO}:ref:refs/heads/dev`;
/**
* Per-env CDK bootstrap qualifier (B-1 / OSWE-IAC-01 fix). Dev runs on its OWN
* qualifier `oswedev` (bootstrapped into the `CDKToolkit-oswedev` stack), so the
* dev infra deploy role only assumes `cdk-oswedev-*` and can NO LONGER assume the
* default `cdk-hnb659fds-*` set whose admin `cfn-exec-role` deploys prod. Prod
* stays on the default qualifier. This closes the cross-env escalation where a
* dev-branch token could `cdk deploy open-swe-prod` via the shared bootstrap
* roles, bypassing prod's Environment approval gate.
*/
export const DEFAULT_BOOTSTRAP_QUALIFIER = "hnb659fds";
export const bootstrapQualifier = (env: EnvName): string =>
env === "dev" ? "oswedev" : DEFAULT_BOOTSTRAP_QUALIFIER;
/**
* The GitHub Actions OIDC provider already exists account-wide (created for
* seahaven-site; see .github/oidc-deploy-roles.yaml `CreateOIDCProvider=false`).

View file

@ -227,6 +227,23 @@ export class ConfigStore extends Construct {
// creates an empty secret, so the out-of-band value is never clobbered.
});
// RETAIN: a stack teardown must not destroy operator-set secret material.
//
// GOTCHA — RETAIN + fixed name orphans these shells on a FAILED FIRST
// CREATE. If the stack's initial create fails and rolls back, RETAIN keeps
// the shells instead of deleting them; the stack is then gone but the
// secrets survive, still holding the global `open-swe-<env>/<VAR>` names.
// Every later create then fails with `AlreadyExists` (and a normal
// delete-secret keeps the name reserved for the 7–30 day recovery window,
// so it does NOT clear the deadlock). Recovery: before re-creating the
// stack, force-delete the orphans so the names free immediately, e.g.
// aws secretsmanager list-secrets --filters Key=name,Values=open-swe-<env>/ \
// --query 'SecretList[].Name' --output text | tr '\t' '\n' | while read n; do
// aws secretsmanager delete-secret --secret-id "$n" \
// --force-delete-without-recovery; done
// Only force-delete shells that are EMPTY (no value version) — a populated
// secret holds real operator material. This bites on teardown/rebuild, a
// secret logical-id change/refactor, or standing up a new env — NOT on
// routine updates of an already-created stack. (Hit on prod 2026-06-29.)
secret.applyRemovalPolicy(cdk.RemovalPolicy.RETAIN);
this.secrets.push(secret);
}

View file

@ -5,6 +5,7 @@ import {
EnvName,
GITHUB_OIDC_PROVIDER_ARN,
REGION,
bootstrapQualifier,
oidcSubject,
} from "../config";
@ -62,20 +63,19 @@ export class GithubDeployRoles extends Construct {
// permissions are exercised by the bootstrap `cfn-exec-role`, whose scope is
// owned by the CDKToolkit stack — NOT granted directly here.
//
// T4 BLOCK#1: GPT-4.1 flagged the `cdk-hnb659fds-*` wildcard and recommended
// enumerating the four exact ARNs. ACCEPTED EXCEPTION (Adam, 2026-06-26): kept
// as the verified org-wide convention (githubdeploy-seahaven-account-baseline
// uses the identical wildcard). Only `cdk bootstrap` creates roles with this
// prefix, so practical escalation risk is low.
// T5 residual (OSWE-IAC-02): the single account-wide cfn-exec-role means the
// dev infra role can technically deploy any stack; per-env trust gates WHO can
// assume, and the prod role requires the environment:prod approval. Per-env
// bootstrap qualifiers would close the residual fully (future hardening).
// B-1 / OSWE-IAC-01 fix: scope the assume to THIS env's bootstrap qualifier.
// Dev uses `oswedev` (its own CDKToolkit-oswedev bootstrap), prod uses the
// default `hnb659fds`. The dev infra role can therefore no longer assume the
// bootstrap roles whose admin cfn-exec-role deploys prod — closing the prior
// cross-env escalation (a dev-branch token could `cdk deploy open-swe-prod`
// via the shared account-wide bootstrap roles, bypassing prod's Environment
// approval gate). The qualifier wildcard still matches only the handful of
// roles `cdk bootstrap` creates for that qualifier.
this.infraRole.addToPolicy(
new iam.PolicyStatement({
sid: "AssumeCdkBootstrapRoles",
actions: ["sts:AssumeRole"],
resources: [`arn:aws:iam::${ACCOUNT}:role/cdk-hnb659fds-*`],
resources: [`arn:aws:iam::${ACCOUNT}:role/cdk-${bootstrapQualifier(envName)}-*`],
}),
);
@ -150,10 +150,22 @@ export class GithubDeployRoles extends Construct {
resources: [`arn:aws:s3:::open-swe-${envName}-assets/releases/*`],
}),
);
// ListBucket is constrained to the releases/ prefix (F-1/IAC-04): the
// publish/rollback scripts only ever list under releases/, so a leaked CI
// token cannot enumerate anything else in the bucket. GetBucketLocation
// carries no s3:prefix, so it stays a separate, unconditioned statement.
this.appRole.addToPolicy(
new iam.PolicyStatement({
sid: "ListArtifactBucket",
actions: ["s3:ListBucket", "s3:GetBucketLocation"],
actions: ["s3:ListBucket"],
resources: [`arn:aws:s3:::open-swe-${envName}-assets`],
conditions: { StringLike: { "s3:prefix": ["releases/*"] } },
}),
);
this.appRole.addToPolicy(
new iam.PolicyStatement({
sid: "GetArtifactBucketLocation",
actions: ["s3:GetBucketLocation"],
resources: [`arn:aws:s3:::open-swe-${envName}-assets`],
}),
);

View file

@ -43,10 +43,23 @@ export class InstanceRole extends Construct {
resources: [`arn:aws:s3:::${p}-assets/releases/*`],
}),
);
// ListBucket is constrained to the releases/ prefix (F-1/IAC-04) — the box
// only ever lists release artifacts, so a compromised box cannot enumerate
// any other object that might land in the bucket. GetBucketLocation has no
// s3:prefix in its request context, so it stays a separate, unconditioned
// statement (the condition would otherwise AccessDeny it).
this.role.addToPolicy(
new iam.PolicyStatement({
sid: "ListArtifactBucket",
actions: ["s3:ListBucket", "s3:GetBucketLocation"],
actions: ["s3:ListBucket"],
resources: [`arn:aws:s3:::${p}-assets`],
conditions: { StringLike: { "s3:prefix": ["releases/*"] } },
}),
);
this.role.addToPolicy(
new iam.PolicyStatement({
sid: "GetArtifactBucketLocation",
actions: ["s3:GetBucketLocation"],
resources: [`arn:aws:s3:::${p}-assets`],
}),
);
@ -85,6 +98,11 @@ export class InstanceRole extends Construct {
// holds. The win that DID survive: fetch-config uses `--secret-id-list` (explicit
// names, no name filter), so `secretsmanager:ListSecrets` is NOT needed and is
// intentionally omitted — the box cannot enumerate secret names account-wide.
// F-2 (accepted residual): because the grant is `*`, a caller naming a secret
// in ANOTHER env's prefix learns whether that name EXISTS (an existence oracle
// via the per-secret AccessDenied-vs-not signal) even though the VALUE stays
// gated by the prefix-scoped GetSecretValue above. Accepted within Sea Haven's
// single-tenant account 328440206208 — cross-env VALUE isolation is preserved.
this.role.addToPolicy(
new iam.PolicyStatement({
sid: "BatchGetSecretValues",

View file

@ -0,0 +1,55 @@
import * as cdk from "aws-cdk-lib";
import { Match, Template } from "aws-cdk-lib/assertions";
import { OpenSweIamStack } from "../lib/open-swe-iam-stack";
import { bootstrapQualifier } from "../lib/config";
const ENV = { account: "328440206208", region: "us-east-1" };
// B-1 / OSWE-IAC-01: each env's infra deploy role may assume ONLY its own
// bootstrap qualifier's roles. Dev runs on `oswedev`, so a dev-branch token can
// no longer assume the default `hnb659fds` bootstrap roles whose admin
// cfn-exec-role deploys prod. Prod stays on the default qualifier.
describe("Per-env CDK bootstrap qualifier isolation (B-1/OSWE-IAC-01)", () => {
it("maps dev -> oswedev and prod -> hnb659fds", () => {
expect(bootstrapQualifier("dev")).toBe("oswedev");
expect(bootstrapQualifier("prod")).toBe("hnb659fds");
});
it("dev infra deploy role assumes only cdk-oswedev-* bootstrap roles", () => {
const app = new cdk.App();
const stack = new OpenSweIamStack(app, "OpenSweIamStack", {
stackName: "open-swe-iam",
env: ENV,
});
Template.fromStack(stack).hasResourceProperties("AWS::IAM::Policy", {
PolicyDocument: Match.objectLike({
Statement: Match.arrayWith([
Match.objectLike({
Sid: "AssumeCdkBootstrapRoles",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::328440206208:role/cdk-oswedev-*",
}),
]),
}),
});
});
it("prod infra deploy role stays on the default cdk-hnb659fds-* bootstrap roles", () => {
const app = new cdk.App();
const stack = new OpenSweIamStack(app, "OpenSweIamStack", {
stackName: "open-swe-iam",
env: ENV,
});
Template.fromStack(stack).hasResourceProperties("AWS::IAM::Policy", {
PolicyDocument: Match.objectLike({
Statement: Match.arrayWith([
Match.objectLike({
Sid: "AssumeCdkBootstrapRoles",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::328440206208:role/cdk-hnb659fds-*",
}),
]),
}),
});
});
});

View file

@ -0,0 +1,71 @@
import * as cdk from "aws-cdk-lib";
import { Match, Template } from "aws-cdk-lib/assertions";
import { OpenSweIamStack } from "../lib/open-swe-iam-stack";
import { OpenSweStack } from "../lib/open-swe-stack";
const ENV = { account: "328440206208", region: "us-east-1" };
// F-1 / IAC-04: s3:ListBucket must be constrained to the releases/ prefix so a
// compromised box / leaked CI token cannot enumerate the rest of the bucket.
const RELEASES_PREFIX_CONDITION = { StringLike: { "s3:prefix": ["releases/*"] } };
describe("S3 ListBucket prefix scoping (F-1/IAC-04)", () => {
it("instance role ListBucket is constrained to releases/*", () => {
const app = new cdk.App();
const stack = new OpenSweStack(app, "OpenSweDevStack", {
stackName: "open-swe-dev",
env: ENV,
envName: "dev",
});
Template.fromStack(stack).hasResourceProperties("AWS::IAM::Policy", {
PolicyDocument: Match.objectLike({
Statement: Match.arrayWith([
Match.objectLike({
Sid: "ListArtifactBucket",
Action: "s3:ListBucket",
Condition: RELEASES_PREFIX_CONDITION,
}),
]),
}),
});
});
it("github deploy app role ListBucket is constrained to releases/*", () => {
const app = new cdk.App();
const stack = new OpenSweIamStack(app, "OpenSweIamStack", {
stackName: "open-swe-iam",
env: ENV,
});
Template.fromStack(stack).hasResourceProperties("AWS::IAM::Policy", {
PolicyDocument: Match.objectLike({
Statement: Match.arrayWith([
Match.objectLike({
Sid: "ListArtifactBucket",
Action: "s3:ListBucket",
Condition: RELEASES_PREFIX_CONDITION,
}),
]),
}),
});
});
it("GetBucketLocation stays a separate, unconditioned statement", () => {
const app = new cdk.App();
const stack = new OpenSweStack(app, "OpenSweDevStack", {
stackName: "open-swe-dev",
env: ENV,
envName: "dev",
});
Template.fromStack(stack).hasResourceProperties("AWS::IAM::Policy", {
PolicyDocument: Match.objectLike({
Statement: Match.arrayWith([
Match.objectLike({
Sid: "GetArtifactBucketLocation",
Action: "s3:GetBucketLocation",
Condition: Match.absent(),
}),
]),
}),
});
});
});

View file

@ -0,0 +1,34 @@
from __future__ import annotations
from agent.dashboard.agent_overrides import profile_author_prs_as_user
from agent.utils.authorship import OPEN_SWE_BOT_EMAIL, OPEN_SWE_BOT_NAME
from agent.utils.github_org_membership import INTERNAL_BOT_LOGINS
def test_author_prs_as_user_defaults_off() -> None:
# Default is the app bot; the per-user opt-in must be explicit.
assert profile_author_prs_as_user(None) is False
assert profile_author_prs_as_user({}) is False
assert profile_author_prs_as_user({"author_prs_as_user": "true"}) is False
assert profile_author_prs_as_user({"author_prs_as_user": True}) is True
def test_commit_identity_is_the_app_bot() -> None:
assert OPEN_SWE_BOT_NAME == "seahaven-openswe[bot]"
assert OPEN_SWE_BOT_EMAIL == "296972425+seahaven-openswe[bot]@users.noreply.github.com"
def test_self_trigger_guard_recognizes_our_app_bot() -> None:
# Bot-authored PRs/actions must be recognized as our own to avoid self-trigger loops.
assert "seahaven-openswe[bot]" in INTERNAL_BOT_LOGINS
def test_default_commit_identity_in_prompt_is_the_app_bot() -> None:
# SH-IDSPLIT-01: with no triggering-user identity (the default-bot path), the
# constructed prompt must set the git commit identity to the app bot — so
# commits, push, and PR all come in as the app (not the triggering user).
from agent.prompt import construct_system_prompt
prompt = construct_system_prompt(working_dir="/workspace", triggering_user_identity=None)
assert OPEN_SWE_BOT_NAME in prompt
assert OPEN_SWE_BOT_EMAIL in prompt

View file

@ -0,0 +1,81 @@
"""AUTH-RESP-LEAK-01: upstream auth-error bodies must not reach user-facing text."""
from __future__ import annotations
import asyncio
from typing import Any
import httpx
import pytest
from agent.utils import auth
_SECRET_BODY = "SENSITIVE-UPSTREAM-BODY-9999"
class _Resp:
def __init__(self, status_code: int, text: str) -> None:
self.status_code = status_code
self.text = text
def raise_for_status(self) -> None:
raise httpx.HTTPStatusError(
"boom",
request=httpx.Request("POST", "http://example.test"),
response=self, # type: ignore[arg-type]
)
def json(self) -> Any:
return {}
class _Client:
def __init__(self, resp: _Resp) -> None:
self._resp = resp
async def __aenter__(self) -> _Client:
return self
async def __aexit__(self, *_a: Any) -> None:
return None
async def post(self, *_a: Any, **_k: Any) -> _Resp:
return self._resp
class _OkResp:
"""A 2xx response whose JSON body lacks both a token and an auth url."""
def __init__(self, payload: Any) -> None:
self._payload = payload
def raise_for_status(self) -> None:
return None
def json(self) -> Any:
return self._payload
def test_http_error_returns_generic_message(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(auth, "GITHUB_OAUTH_PROVIDER_ID", "provider-id")
monkeypatch.setattr(auth, "X_SERVICE_AUTH_JWT_SECRET", "jwt-secret")
monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **k: _Client(_Resp(500, _SECRET_BODY)))
result = asyncio.run(auth.get_github_token_for_user("ls-user", "tenant"))
assert "error" in result
assert _SECRET_BODY not in result["error"]
assert "500" in result["error"]
def test_unexpected_result_returns_generic_message(monkeypatch: pytest.MonkeyPatch) -> None:
"""The 2xx-but-missing-token/url branch must not echo the upstream body."""
monkeypatch.setattr(auth, "GITHUB_OAUTH_PROVIDER_ID", "provider-id")
monkeypatch.setattr(auth, "X_SERVICE_AUTH_JWT_SECRET", "jwt-secret")
body = {"unexpected_field": _SECRET_BODY}
monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **k: _Client(_OkResp(body)))
result = asyncio.run(auth.get_github_token_for_user("ls-user", "tenant"))
assert result == {"error": "GitHub auth returned an unexpected result"}
assert _SECRET_BODY not in result["error"]

View file

@ -78,10 +78,42 @@ def _stub_dashboard_store(
monkeypatch.setattr(profiles, "_get_value", fake_get_value)
def test_resolve_github_token_slack_uses_dashboard_store(
def _set_profile(monkeypatch: pytest.MonkeyPatch, *, author_prs_as_user: bool) -> None:
"""Mock the per-user profile lookup that gates per-user attribution.
``author_prs_as_user=False`` → no opt-in (default: author as the app bot).
"""
from agent.dashboard import agent_overrides
profile = {"author_prs_as_user": True} if author_prs_as_user else None
async def fake_load_profile(login: str):
return profile
monkeypatch.setattr(agent_overrides, "load_profile", fake_load_profile)
def test_resolve_github_token_slack_defaults_to_bot(monkeypatch: pytest.MonkeyPatch) -> None:
# DEFAULT (no author_prs_as_user opt-in): slack runs author as the app bot,
# even when a valid per-user token exists — so PRs come in as the app.
_stub_dashboard_store(monkeypatch, token="user-tok")
_set_profile(monkeypatch, author_prs_as_user=False)
monkeypatch.setattr(auth, "is_bot_token_only_mode", lambda: False)
async def fake_bot(thread_id: str):
return ("bot-tok", None)
monkeypatch.setattr(auth, "_resolve_bot_installation_token", fake_bot)
token, _ = asyncio.run(auth.resolve_github_token(_slack_config(), "t1"))
assert token == "bot-tok"
def test_resolve_github_token_slack_optin_uses_dashboard_store(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_stub_dashboard_store(monkeypatch, token="user-tok")
_set_profile(monkeypatch, author_prs_as_user=True)
monkeypatch.setattr(auth, "is_bot_token_only_mode", lambda: False)
token, expires_at = asyncio.run(auth.resolve_github_token(_slack_config(), "t1"))
@ -90,7 +122,7 @@ def test_resolve_github_token_slack_uses_dashboard_store(
assert expires_at == "2099-01-01T00:00:00Z"
def test_resolve_github_token_slack_ignores_stale_thread_cache(
def test_resolve_github_token_slack_optin_ignores_stale_thread_cache(
monkeypatch: pytest.MonkeyPatch,
) -> None:
# Slack thread ids are shared, so a prior user's cached token must NOT be
@ -100,6 +132,7 @@ def test_resolve_github_token_slack_ignores_stale_thread_cache(
token="bob-token",
cached=("alice-token", "2099-01-01T00:00:00Z"),
)
_set_profile(monkeypatch, author_prs_as_user=True)
monkeypatch.setattr(auth, "is_bot_token_only_mode", lambda: False)
token, _ = asyncio.run(auth.resolve_github_token(_slack_config(), "t1"))
@ -107,24 +140,26 @@ def test_resolve_github_token_slack_ignores_stale_thread_cache(
assert token == "bob-token"
def test_resolve_github_token_slack_no_token_raises(
def test_resolve_github_token_slack_optin_no_token_raises(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_stub_dashboard_store(monkeypatch, token=None)
_set_profile(monkeypatch, author_prs_as_user=True)
monkeypatch.setattr(auth, "is_bot_token_only_mode", lambda: False)
with pytest.raises(auth.GitHubUserAuthRequired):
asyncio.run(auth.resolve_github_token(_slack_config(), "t1"))
def test_resolve_github_token_per_user_wins_over_bot_only_mode(
def test_resolve_github_token_optin_per_user_wins_over_bot_only_mode(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_stub_dashboard_store(monkeypatch, token="user-tok")
_set_profile(monkeypatch, author_prs_as_user=True)
monkeypatch.setattr(auth, "is_bot_token_only_mode", lambda: True)
async def fail_bot(thread_id: str):
raise AssertionError("bot token must not be used when a user token exists")
raise AssertionError("bot token must not be used when the opt-in user token exists")
monkeypatch.setattr(auth, "_resolve_bot_installation_token", fail_bot)
@ -132,10 +167,11 @@ def test_resolve_github_token_per_user_wins_over_bot_only_mode(
assert token == "user-tok"
def test_resolve_github_token_slack_no_token_falls_back_to_bot_in_bot_only_mode(
def test_resolve_github_token_slack_optin_no_token_falls_back_to_bot_in_bot_only_mode(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_stub_dashboard_store(monkeypatch, token=None)
_set_profile(monkeypatch, author_prs_as_user=True)
monkeypatch.setattr(auth, "is_bot_token_only_mode", lambda: True)
async def fake_bot(thread_id: str):

View file

@ -1127,7 +1127,9 @@ def test_process_github_pr_comment_without_email_skips(
def test_process_github_issue_uses_resolved_user_token_for_reaction(monkeypatch) -> None:
captured: dict[str, object] = {}
async def fake_get_or_resolve_thread_github_token(thread_id: str, email: str) -> str | None:
async def fake_get_or_resolve_thread_github_token(
thread_id: str, email: str, *, repo: dict[str, str] | None = None
) -> str | None:
captured["thread_id"] = thread_id
captured["email"] = email
return "user-token"
@ -1210,7 +1212,9 @@ def test_process_github_issue_uses_resolved_user_token_for_reaction(monkeypatch)
def test_process_github_issue_existing_thread_uses_followup_prompt(monkeypatch) -> None:
captured: dict[str, object] = {}
async def fake_get_or_resolve_thread_github_token(thread_id: str, email: str) -> str | None:
async def fake_get_or_resolve_thread_github_token(
thread_id: str, email: str, *, repo: dict[str, str] | None = None
) -> str | None:
return "user-token"
async def fake_get_github_app_installation_token() -> str | None:

View file

@ -69,7 +69,7 @@ def test_cached_token_expires_after_max_ttl() -> None:
"""A token with no/far expiry is still dropped once it's older than the 24h cap."""
far_future = (datetime.now(UTC) + timedelta(days=30)).isoformat()
old_cached_at = datetime.now(UTC) - timedelta(hours=25)
github_token._GITHUB_TOKEN_CACHE["tid"] = ("ghp_secret", far_future, old_cached_at)
github_token._GITHUB_TOKEN_CACHE["tid"] = ("ghp_secret", far_future, old_cached_at, None)
assert github_token.get_github_token({"configurable": {"thread_id": "tid"}}) is None
@ -210,7 +210,7 @@ def test_process_github_pr_comment_invalidates_and_reauths_on_401(
tokens = iter(["stale-token", "fresh-token"])
async def fake_get_or_resolve(thread_id: str, email: str) -> str | None:
async def fake_get_or_resolve(thread_id: str, email: str, *, repo: Any = None) -> str | None:
token = next(tokens)
resolves.append(token)
return token

View file

@ -0,0 +1,53 @@
"""Replay-window enforcement for Linear webhook signature verification (AUTHZ-001)."""
from __future__ import annotations
import hashlib
import hmac
import json
from datetime import UTC, datetime
from agent import webapp
_SECRET = "linear-signing-secret"
def _sign(body: bytes) -> str:
return hmac.new(_SECRET.encode("utf-8"), body, hashlib.sha256).hexdigest()
def _now_ms() -> int:
return int(datetime.now(UTC).timestamp() * 1000)
def test_fresh_timestamp_accepted() -> None:
body = json.dumps({"type": "Comment", "webhookTimestamp": _now_ms()}).encode()
assert webapp.verify_linear_signature(body, _sign(body), _SECRET) is True
def test_stale_timestamp_rejected() -> None:
stale = _now_ms() - 10 * 60 * 1000 # 10 minutes old
body = json.dumps({"type": "Comment", "webhookTimestamp": stale}).encode()
# Signature is valid, but the timestamp is outside the freshness window.
assert webapp.verify_linear_signature(body, _sign(body), _SECRET) is False
def test_future_timestamp_rejected() -> None:
future = _now_ms() + 10 * 60 * 1000
body = json.dumps({"type": "Comment", "webhookTimestamp": future}).encode()
assert webapp.verify_linear_signature(body, _sign(body), _SECRET) is False
def test_missing_timestamp_rejected() -> None:
body = json.dumps({"type": "Comment"}).encode()
assert webapp.verify_linear_signature(body, _sign(body), _SECRET) is False
def test_non_numeric_timestamp_rejected() -> None:
body = json.dumps({"type": "Comment", "webhookTimestamp": "not-a-number"}).encode()
assert webapp.verify_linear_signature(body, _sign(body), _SECRET) is False
def test_bad_signature_rejected_even_when_fresh() -> None:
body = json.dumps({"type": "Comment", "webhookTimestamp": _now_ms()}).encode()
assert webapp.verify_linear_signature(body, "deadbeef", _SECRET) is False

View file

@ -11,6 +11,24 @@ import agent.tools.open_pull_request # noqa: F401
opr = sys.modules["agent.tools.open_pull_request"]
def _set_profile(monkeypatch: pytest.MonkeyPatch, *, author_prs_as_user: bool) -> None:
"""Mock the per-user profile lookup that gates per-user PR attribution."""
from agent.dashboard import agent_overrides
profile = {"author_prs_as_user": True} if author_prs_as_user else None
async def fake_load_profile(login: str):
return profile
monkeypatch.setattr(agent_overrides, "load_profile", fake_load_profile)
@pytest.fixture(autouse=True)
def _default_no_optin_profile(monkeypatch: pytest.MonkeyPatch) -> None:
# Default: the author_prs_as_user opt-in is OFF, so PRs author as the app bot.
_set_profile(monkeypatch, author_prs_as_user=False)
class _FakeResponse:
def __init__(self, status_code: int, payload: Any = None, text: str = "") -> None:
self.status_code = status_code
@ -101,11 +119,46 @@ def _open() -> dict[str, Any]:
)
def test_uses_user_token_for_slack_with_login(monkeypatch: pytest.MonkeyPatch) -> None:
def test_defaults_to_bot_for_slack_without_optin(monkeypatch: pytest.MonkeyPatch) -> None:
# DEFAULT (no author_prs_as_user opt-in): slack PRs are opened as the app bot,
# even when a valid per-user token exists — so the PR is attributed to the app.
_set_config(monkeypatch, {"source": "slack", "github_login": "johannes117"})
from agent.dashboard import profiles
async def fail_user_token(login: str, **_kw: Any) -> str | None:
raise AssertionError("user token must not be used without the author_prs_as_user opt-in")
monkeypatch.setattr(profiles, "get_valid_access_token", fail_user_token)
async def fake_bot() -> str | None:
return "bot-tok"
monkeypatch.setattr(opr, "get_github_app_installation_token", fake_bot)
client = _FakeClient(
post=_FakeResponse(
201,
{
"html_url": "https://x/pull/1",
"number": 1,
"user": {"login": "seahaven-openswe[bot]"},
},
)
)
_install_client(monkeypatch, client)
result = _open()
assert result["token_kind"] == "bot"
assert client.post_calls[0]["headers"]["Authorization"] == "Bearer bot-tok"
def test_uses_user_token_for_slack_with_optin(monkeypatch: pytest.MonkeyPatch) -> None:
_set_config(monkeypatch, {"source": "slack", "github_login": "johannes117"})
_set_profile(monkeypatch, author_prs_as_user=True)
from agent.dashboard import profiles
async def fake_user_token(login: str, **_kw: Any) -> str | None:
assert login == "johannes117"
return "user-tok"

View file

@ -264,6 +264,7 @@ class TestRefreshProxyOnSandboxReuse:
mock_sandbox = MagicMock(id="sandbox-cached")
with (
patch("agent.server.client.threads.update", new_callable=AsyncMock),
patch(
"agent.server.resolve_github_token",
new_callable=AsyncMock,
@ -308,11 +309,12 @@ class TestRefreshProxyOnSandboxReuse:
@pytest.mark.asyncio
async def test_refreshes_proxy_when_reconnecting_to_existing_langsmith_sandbox(self) -> None:
"""Reconnected sandboxes should also get a fresh proxy token."""
"""A bound thread reconnecting to its sandbox should get a fresh proxy token."""
config = self._execution_config()
mock_sandbox = MagicMock(id="sandbox-existing")
with (
patch("agent.server.client.threads.update", new_callable=AsyncMock),
patch(
"agent.server.resolve_github_token",
new_callable=AsyncMock,
@ -323,6 +325,13 @@ class TestRefreshProxyOnSandboxReuse:
new_callable=AsyncMock,
return_value="sandbox-existing",
),
# Thread is bound to the current repo, so reconnect proceeds (an unbound
# legacy thread would instead fail closed and recreate).
patch(
"agent.server.get_bound_repo_from_metadata",
new_callable=AsyncMock,
return_value="langchain-ai/open-swe",
),
patch("agent.server.create_sandbox", return_value=mock_sandbox) as mock_create,
patch(
"agent.server.get_github_app_installation_token_with_expiry",

View file

@ -0,0 +1,225 @@
"""Repo-binding isolation for the sandbox and GitHub-token caches.
Covers TID-COLLIDE-01: a second repo presenting a colliding thread_id must not
reuse the first repo's in-process sandbox or cached GitHub token.
"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
import pytest
from agent import server
from agent.utils import github_token
@pytest.fixture(autouse=True)
def _clear_caches() -> None:
github_token._GITHUB_TOKEN_CACHE.clear()
server.SANDBOX_BACKENDS.clear()
# --- token cache repo binding ------------------------------------------------
def test_cached_token_not_reused_across_repos() -> None:
"""A token bound to repo A is refused for a colliding thread_id from repo B."""
future = (datetime.now(UTC) + timedelta(hours=1)).isoformat()
github_token.cache_github_token_for_thread(
"tid", "ghp_repoA", expires_at=future, repo={"owner": "acme", "name": "alpha"}
)
# Same thread_id, different repo → must NOT serve repo A's token.
cfg_b = {"configurable": {"thread_id": "tid", "repo": {"owner": "evil", "name": "beta"}}}
assert github_token.get_github_token(cfg_b) is None
# And the poisoned entry is evicted.
assert "tid" not in github_token._GITHUB_TOKEN_CACHE
def test_cached_token_reused_for_same_repo() -> None:
future = (datetime.now(UTC) + timedelta(hours=1)).isoformat()
github_token.cache_github_token_for_thread(
"tid", "ghp_repoA", expires_at=future, repo={"owner": "acme", "name": "alpha"}
)
cfg_a = {"configurable": {"thread_id": "tid", "repo": {"owner": "acme", "name": "alpha"}}}
assert github_token.get_github_token(cfg_a) == "ghp_repoA"
def test_unbound_token_served_when_repo_unknown() -> None:
"""Legacy entries with no bound repo still resolve when no repo is supplied."""
github_token.cache_github_token_for_thread("tid", "ghp_legacy")
assert github_token.get_github_token({"configurable": {"thread_id": "tid"}}) == "ghp_legacy"
def test_cached_token_reused_for_same_repo_case_insensitive() -> None:
"""``Org/Repo`` and ``org/repo`` are the same repo: no spurious refusal."""
future = (datetime.now(UTC) + timedelta(hours=1)).isoformat()
github_token.cache_github_token_for_thread(
"tid", "ghp_repoA", expires_at=future, repo={"owner": "Acme", "name": "Alpha"}
)
cfg = {"configurable": {"thread_id": "tid", "repo": {"owner": "acme", "name": "alpha"}}}
assert github_token.get_github_token(cfg) == "ghp_repoA"
def test_repo_cache_key_normalizes() -> None:
assert github_token.repo_cache_key({"owner": "o", "name": "r"}) == "o/r"
assert github_token.repo_cache_key("o/r") == "o/r"
assert github_token.repo_cache_key({"owner": "o"}) is None
assert github_token.repo_cache_key(None) is None
# Casefolded so different casing of the same repo collapses to one key.
assert github_token.repo_cache_key({"owner": "Org", "name": "Repo"}) == "org/repo"
assert github_token.repo_cache_key("Org/Repo") == "org/repo"
# --- sandbox repo binding ----------------------------------------------------
class _FakeBackend:
def __init__(self, sandbox_id: str) -> None:
self.id = sandbox_id
self.bound_repo: str | None = None
def execute(self, *_a: Any, **_k: Any) -> Any: # pragma: no cover - must not run
raise AssertionError("colliding-repo sandbox must not be pinged/reused")
@pytest.mark.asyncio
async def test_ensure_sandbox_refuses_colliding_repo(monkeypatch: pytest.MonkeyPatch) -> None:
async def fake_sandbox_id(_tid: str) -> str:
return "sb-A"
async def fake_bound_repo(_tid: str) -> str:
return "acme/alpha"
monkeypatch.setattr(server, "get_sandbox_id_from_metadata", fake_sandbox_id)
monkeypatch.setattr(server, "get_bound_repo_from_metadata", fake_bound_repo)
backend = _FakeBackend("sb-A")
backend.bound_repo = "acme/alpha"
server.SANDBOX_BACKENDS["tid"] = backend # type: ignore[assignment]
with pytest.raises(server.SandboxRepoMismatchError):
await server.ensure_sandbox_for_thread("tid", repo={"owner": "evil", "name": "beta"})
@pytest.mark.asyncio
async def test_ensure_sandbox_allows_matching_repo(monkeypatch: pytest.MonkeyPatch) -> None:
async def fake_sandbox_id(_tid: str) -> str:
return "sb-A"
async def fake_bound_repo(_tid: str) -> str:
return "acme/alpha"
calls: dict[str, int] = {"git": 0}
backend = _FakeBackend("sb-A")
backend.bound_repo = "acme/alpha"
async def fake_check(b: Any, *_a: Any, **_k: Any) -> Any:
return b
async def fake_refresh(b: Any, *_a: Any, **_k: Any) -> Any:
return b
async def fake_git(_b: Any) -> None:
calls["git"] += 1
monkeypatch.setattr(server, "get_sandbox_id_from_metadata", fake_sandbox_id)
monkeypatch.setattr(server, "get_bound_repo_from_metadata", fake_bound_repo)
monkeypatch.setattr(server, "check_or_recreate_sandbox", fake_check)
monkeypatch.setattr(server, "_refresh_github_proxy_or_recreate", fake_refresh)
monkeypatch.setattr(server, "set_sandbox_backend", lambda _tid, b, **_k: b)
monkeypatch.setattr(server, "_configure_git_identity", fake_git)
server.SANDBOX_BACKENDS["tid"] = backend # type: ignore[assignment]
result = await server.ensure_sandbox_for_thread("tid", repo={"owner": "acme", "name": "alpha"})
assert result is backend
assert calls["git"] == 1
@pytest.mark.asyncio
async def test_ensure_sandbox_reuses_same_repo_case_insensitive(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A bound sandbox is reused when the current repo differs only by casing."""
async def fake_sandbox_id(_tid: str) -> str:
return "sb-A"
async def fake_bound_repo(_tid: str) -> str:
return "acme/alpha"
backend = _FakeBackend("sb-A")
backend.bound_repo = "acme/alpha"
async def fake_check(b: Any, *_a: Any, **_k: Any) -> Any:
return b
async def fake_refresh(b: Any, *_a: Any, **_k: Any) -> Any:
return b
async def fake_git(_b: Any) -> None:
return None
monkeypatch.setattr(server, "get_sandbox_id_from_metadata", fake_sandbox_id)
monkeypatch.setattr(server, "get_bound_repo_from_metadata", fake_bound_repo)
monkeypatch.setattr(server, "check_or_recreate_sandbox", fake_check)
monkeypatch.setattr(server, "_refresh_github_proxy_or_recreate", fake_refresh)
monkeypatch.setattr(server, "set_sandbox_backend", lambda _tid, b, **_k: b)
monkeypatch.setattr(server, "_configure_git_identity", fake_git)
server.SANDBOX_BACKENDS["tid"] = backend # type: ignore[assignment]
# Different casing of the same repo must not raise and must reuse the sandbox.
result = await server.ensure_sandbox_for_thread("tid", repo={"owner": "ACME", "name": "Alpha"})
assert result is backend
@pytest.mark.asyncio
async def test_legacy_unbound_sandbox_recreated_not_reused(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A legacy thread (sandbox_id present, bound_repo absent) must fail closed.
With no recorded binding, the existing sandbox cannot be confirmed to belong
to the current repo, so it is never reconnected-and-served: a fresh sandbox is
created and bound to the requesting repo instead.
"""
async def fake_sandbox_id(_tid: str) -> str:
return "sb-legacy"
async def fake_bound_repo(_tid: str) -> None:
return None
def fake_reconnect(*_a: Any, **_k: Any) -> Any: # pragma: no cover - must not run
raise AssertionError("must not reconnect to a legacy unbound sandbox")
fresh = _FakeBackend("sb-fresh")
async def fake_create_with_proxy(*_a: Any, **_k: Any) -> Any:
return fresh
async def fake_git(_b: Any) -> None:
return None
class _Threads:
async def update(self, **_k: Any) -> None:
return None
async def get(self, *_a: Any, **_k: Any) -> dict[str, Any]:
return {}
class _Client:
threads = _Threads()
monkeypatch.setattr(server, "get_sandbox_id_from_metadata", fake_sandbox_id)
monkeypatch.setattr(server, "get_bound_repo_from_metadata", fake_bound_repo)
monkeypatch.setattr(server, "create_sandbox", fake_reconnect)
monkeypatch.setattr(server, "_create_sandbox_with_proxy", fake_create_with_proxy)
monkeypatch.setattr(server, "_configure_git_identity", fake_git)
monkeypatch.setattr(server, "client", _Client())
result = await server.ensure_sandbox_for_thread("tid", repo={"owner": "evil", "name": "beta"})
assert result.id == "sb-fresh"
assert server.SANDBOX_BACKENDS["tid"].bound_repo == "evil/beta"

View file

@ -221,7 +221,9 @@ async def test_reviewer_resolves_app_installation_token_at_run_start() -> None:
# Token is resolved in this process at run start (scoped to the repo), not read
# from a cache the webhook handler populated in a different process.
mock_app_token.assert_awaited_once_with(repositories=["repo"])
mock_cache_token.assert_called_once_with("reviewer-thread-id", "app-token", expires_at=None)
mock_cache_token.assert_called_once_with(
"reviewer-thread-id", "app-token", expires_at=None, repo={"owner": "acme", "name": "repo"}
)
middleware = create_agent.call_args.kwargs["middleware"]
assert reviewer.check_message_queue_before_model in middleware