diff --git a/F02_GITHUB_AUTH_DESIGN.md b/F02_GITHUB_AUTH_DESIGN.md new file mode 100644 index 0000000..75baa1f --- /dev/null +++ b/F02_GITHUB_AUTH_DESIGN.md @@ -0,0 +1,609 @@ +# F02 — GitHub App User Authorization Design + +Date: 2026-10-07. Status: approved architecture; implementation NOT started. +Source checkout: `.audit-worktree`, `security/final-security-audit`, baseline +`f57dcd81ecf44956a3a97f22a20a4fea28867cff` plus the uncommitted Phase 6 fixes. + +This document distinguishes verified current behavior from proposed behavior. +Every new table, field, route, service and environment-variable name below is a +design proposal, not something already implemented. No production configuration, +GitHub App registration or live token permissions have been verified. No existing +Phase 6 files are to be changed by this documentation task. + +## 1. Current shared-token architecture + +Verified source: `apps/api/app/core/config.py`, `api/routes/repositories.py`, +`services/github.py`, `services/branch_fixer.py`, `services/pr_commenter.py`, +`services/pr_reviewer.py`, `services/ingestion.py`, `models/user.py`, +`models/repository.py`, and `apps/web/lib/api.ts`. + +`GITHUB_TOKEN` populates `settings.github_token`. `github.py` attaches that +server-wide credential to metadata, tree and source-content GET requests. +`branch_fixer.py` and `pr_commenter.py` accept an optional service-level token but +fall back to `settings.github_token`; the HTTP routes supply no caller-specific +credential. `pr_reviewer.py` currently makes unauthenticated GitHub reads. + +The three GitHub mutation endpoints are: + +| Existing CodeLens POST route | Remote side effects | +| --- | --- | +| `/repositories/{repository_id}/findings/{finding_id}/apply-fix` | Create a Git ref/branch, then commit file contents | +| `/repositories/{repository_id}/findings/{finding_id}/create-pr` | Create a pull request from a supplied existing branch | +| `/repositories/{repository_id}/pull-requests/{pull_request_number}/comment` | Post an issue-style PR timeline comment | + +There is no GitHub merge endpoint. Repository deletion deletes CodeLens data, +not the GitHub repository. A user can create/connect a local repository record +with their CodeLens `user_id` without proving GitHub permission. Checks against +that row prevent CodeLens IDOR but do not authorize use of the shared token. +The actual shared token's permissions determine whether GitHub accepts a call. + +Current users have password/Google identity fields, not GitHub connections. +`Repository.github_id` is a string populated with `full_name`, not a reliable +immutable numeric GitHub repository ID. Uniqueness is per CodeLens user. +The background scan currently receives only `repository_id` and opens a fresh +`SessionLocal`. Source files/findings/PR reviews/snapshots are stored locally. + +## 2. Target GitHub App architecture + +Keep password/Google login, CodeLens JWT cookies and existing `Repository.user_id` +ownership. GitHub connection is an additional authorization, not a new login or +email-based account merge. Initial scope is individual CodeLens accounts; team +tenancy is not implemented in the current repository and is not assumed here. + +The authorization conjunction for every protected repository action is: + +`CodeLens row ownership AND active caller connection AND verified repository/ +installation binding AND current GitHub user access AND required operation +permission AND CodeLens operation policy`. + +All user-triggered content reads, scans and mutations use that user's GitHub App +user access token. Version 1 has NO installation-token fallback for these paths. +App JWTs may authenticate installation-metadata reconciliation only; they are +not user credentials. Future autonomous installation-token automation requires +a separate explicit tenant/grant design and approval. + +GitHub user tokens constrain operations to both the user's and App's authority; +installation and user authorization are distinct prerequisites. Installation +alone is not permission for every CodeLens user to operate on its repositories. +[GitHub authorization semantics](https://docs.github.com/en/apps/using-github-apps/authorizing-github-apps). + +Proposed components: GitHub connection routes, single authorization resolver, +credential/refresh manager, constrained HTTP client, installation/webhook +reconciliation, and sanitized audit events. Services receive an authorized +context bound to actor, connection generation, installation, numeric repository +ID and operation—not an arbitrary token or caller-selected installation ID. +Token material stays out of repr, serialization, logs and error context. + +## 3. User authorization flow + +1. An already authenticated user requests GitHub connection through a CSRF-checked + POST. Reconnection/account replacement requires recent CodeLens authentication. +2. Backend creates a random, single-use, server-expiring transaction (proposed + ten-minute TTL), bound to CodeLens user, current session jti hash, browser + transaction cookie and fixed callback/return destination. Store only the + state's hash; store the PKCE verifier encrypted. Do not reuse Google state. +3. Navigate to GitHub's authorization endpoint with the App client ID, state, + exact registered callback and S256 PKCE challenge. Request no classic OAuth + `repo` scope. User authorization is a GitHub App flow. +4. GET callback requires the same logged-in CodeLens user/session and browser + binding; atomically consume the transaction before exchanging the code. + Reject missing, expired, replayed or mismatched state, including account swaps. +5. Exchange server-side using the verifier and App client authentication; validate + token type/expiry response, then obtain the stable GitHub numeric user ID + through authenticated `/user`. Never link by email or a submitted username. +6. Enforce connection uniqueness, encrypt credentials, discover accessible + installations/repositories and return a fixed frontend success/status URL. + Never put token material in redirects, JSON responses or frontend state. + +Clear transaction cookies on every terminal path. Callback responses are +no-store; redact callback query parameters in application/proxy/access logs. +Scrub token-exchange HTTP tracing and APM capture. Interrupted flow requires a +new transaction; it must not attach credentials to a later logged-in user. +GitHub supports S256 PKCE for this flow. +[User-token generation](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-user-access-token-for-a-github-app). + +## 4. GitHub App installation flow + +After connecting, list installations visible to the user using their token, then +repositories within the chosen installation. If none is suitable, provide a +server-constructed installation URL for the registered App. Prefer selected +repositories rather than all repositories. Organization installation requests +may need owner approval; show pending status, not a successful connection. + +Enable a fixed setup callback with a separate browser-bound transaction. Treat +callback installation IDs and setup actions as hints, never proof of authority. +Re-fetch installation/repository membership with the caller token and match the +configured App ID before binding. A webhook announcing installation also cannot +link arbitrary CodeLens users to it. Authorization and installation may happen +in either order; enable repository actions only after both checks succeed. +[Installation behavior](https://docs.github.com/en/apps/using-github-apps/installing-a-github-app-from-a-third-party). + +## 5. User access token lifecycle + +Require expiring GitHub App user tokens. Store server-derived access/refresh +expiry timestamps and refresh before access expiry with a small clock-skew +margin. Do not rely on parsing token strings. The current documented defaults +are eight hours for access and six months for refresh; use returned lifetime +fields rather than hard-coded validity assumptions. Refresh replaces both tokens +and invalidates the previous pair. Expired refresh requires reauthorization. +[Refresh lifecycle](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/refreshing-user-access-tokens). + +Connection states: active, reauthorization-required, disconnected and revoked. +Installation suspension/removal is tracked separately. A valid access token +does not imply permission to every repository/action. On upstream rejection, +classify credentials versus repository permission versus rate-limit/network +errors; do not refresh every 403 or mark a whole account revoked for one 404. + +## 6. Token encryption/storage strategy + +Proposed production policy: authenticated envelope encryption with AES-256-GCM +and a managed KMS wrapping key outside PostgreSQL. Use independent random nonces; +associated data binds connection ID, CodeLens user ID, GitHub user ID, field type +and encryption version. Persist ciphertext, authentication data/nonce, wrapped +data key and key/version identifiers—never plaintext credentials. + +Only the backend credential manager may unwrap/decrypt, immediately before use. +No tokens in ORM repr, public schemas, exception causes exposed to callers, task +arguments, URLs, frontend bundles or telemetry. Use provider-supported secret +storage for App client credentials, signing private key and webhook secret. +Do not reuse AUTH_SECRET_KEY as an encryption key. Database encryption at rest +alone does not protect a database export. Do not claim protection from a fully +compromised authorized backend process or guaranteed Python memory zeroization. + +Key rotation rewraps data keys or reencrypts through a bounded audited job; reads +can support a controlled previous-key window. KMS failure denies credentialed +actions. Protect backups and restore procedures; restored records must undergo +revocation/installation reconciliation before being used. The KMS provider and +runtime identity mechanism must be selected before implementation/deployment; +no particular live infrastructure is assumed. + +## 7. Refresh-token handling + +Use database-coordinated refresh across replicas, not process-local locks. +Serialize one refresh per connection with an expiring lease and generation/CAS +check; do not hold a database transaction across an unbounded HTTP request. +Only the winning refresh commits the newly encrypted pair atomically. Other +requests wait briefly and reload; they never reuse the consumed refresh token. + +Disconnect/revoke increments authorization generation. A stale refresh response +cannot reactivate or overwrite that generation. Bound requests by timeout and +retry budget. If GitHub consumed the refresh token but a network/DB failure lost +the replacement pair, fail closed and require reauthorization rather than trying +alternate identities. Never retry an unknown-outcome mutation just because a +credential refresh succeeded. Test crash, lease expiry and cross-worker races. + +## 8. Revocation/disconnect handling + +Process signed `github_app_authorization` revocation events by stable GitHub +user ID. Also process installation deletion/suspension and repository selection +changes. Verify HMAC over raw bounded bytes, configured App identity/event shape, +and deduplicate delivery IDs. Reconcile out-of-order events against GitHub; +never reactivate access solely from an old webhook. User revocation produces +this authorization webhook; invalid credentials also fail at GitHub. +[Token/revocation behavior](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-with-a-github-app-on-behalf-of-a-user), +[webhook reference](https://docs.github.com/en/webhooks/webhook-events-and-payloads#github_app_authorization). + +Disconnect first atomically disables the local connection, invalidates grants/ +caches/leases and stops jobs, then attempts GitHub-side authorization revocation. +Use the documented App authorization revocation endpoint with server-side App +client authentication, not an installation token. If remote revocation fails, +retain only encrypted revocation material in a restricted expiring retry record, +never available to the ordinary credential resolver; notify the user to revoke +through GitHub settings. Purge ordinary credential ciphertext immediately. +[Authorization deletion](https://docs.github.com/en/rest/apps/oauth-applications#delete-an-app-authorization). + +## 9. Repository-to-user authorization model + +Preserve CodeLens ownership and per-user duplicate repository records. Add +immutable numeric GitHub repository ID, installation ID and the owner's +connection binding through verified association rows. Full name/URL are display +and routing metadata; refresh them on rename/transfer only after verifying the +numeric ID. Never automatically substitute a different repository at an old URL. + +One active GitHub account per CodeLens account; a GitHub numeric account ID is +unique across active CodeLens connections in version 1. A collision requires an +explicit account-recovery/support flow, never auto-merge by email. Changing the +GitHub identity invalidates existing bindings and requires reconnection. + +A grant records a verified access observation, not permanent GitHub authority. +For each remote operation, resolve live repository access with the user token; +write operations always perform a fresh check. GitHub remains the final action +permission authority (including comment permissions, not inferred just from +repository push rights). Check connection generation again before side effects. + +For locally cached private content, revalidate user access before returning it or +submitting it to AI. Version 1 permits no positive authorization cache across +requests for these sensitive paths; deployment must measure GitHub quota/latency +and coalesce concurrent checks only within one request/job. A future cache TTL +requires an explicit, documented revocation-delay policy. Webhooks accelerate +invalidation but do not guarantee instantaneous knowledge of every membership +change. In-flight responses/mutations already authorized cannot be recalled. + +## 10. Private repository read authorization + +Connection discovery and metadata must use the caller credential, not global +credentials. Verify membership in `/user/installations/{installation_id}/repositories` +with bounded pagination, then verify the exact repository with the user token. +Require active installation selection and readable contents before ingesting. +Unauthorized discovery must not disclose private repository existence. + +Use the same context for tree, file and PR reads; remove the current +unauthenticated PR-client inconsistency. Protect cached source, findings, AI +explanations/fixes/tests/Ask context, PR review detail/history and historical +dashboard data derived from private repositories. Filter lists by authorized +repositories; failures never return sensitive cached items. CodeLens repository +deletion and connection-management status may remain accessible to their local +owner without GitHub access so users can disconnect/delete their data. + +Even a repository made public later is not automatically reclassified from an +untrusted request. Optional anonymous public browsing would be a separate, +read-only explicit path; it cannot enable shared-token private reads or writes. + +## 11. Apply-fix authorization + +Retain repository/finding ownership, nested-ID checks, source lookup, AI quotas +and unchanged-content rejection. Resolve caller connection and live repository +write capability BEFORE source retrieval/AI generation, then recheck immediately +before GitHub side effects. Use the same caller identity throughout. + +Resolve current default-branch commit and file SHA; reject stale source/fix +preconditions rather than overwriting changed code. Allow only new validated +CodeLens fix branches, never updating the default branch or workflow files. +Use bounded generated content, path/ref validation and an idempotent operation +record. Record created branch/commit numeric repository identity and connection +generation. Partial branch-created/commit-failed outcomes are visible and audited; +do not delete remote branches automatically or repeat unknown-outcome writes. +Explicit user invocation remains required; no AI instruction grants authority. + +## 12. Create-PR authorization + +Retain the existing route and response fields. Check local owner/nested finding, +active caller connection, exact repository installation membership and current +operation permission. Require a recorded successful CodeLens fix operation for +this owner/repository/finding/head branch, not any supplied existing branch. +Verify current head commit and base/default branch with the caller token. + +Use the caller token to create the PR; bound/sanitize title/body, deny unexpected +cross-repository heads in version 1, and reconcile duplicates/unknown outcomes +before retrying. Record PR number/result under the originating operation. +Never merge a PR or bypass branch protections. Stale/missing legacy branch +provenance requires a new verified fix flow, not automatic trust. + +## 13. PR-comment authorization + +Check local repository ownership, verified binding, live user access and +App permission to comment. Fetch the exact PR with the same context before +generating or posting; this avoids commenting on an unrelated issue number. +Comment authorization is operation-specific: lack of push access alone does +not prove the user cannot comment. GitHub's endpoint remains authoritative. + +Post only on explicit caller request. Bound Markdown and prevent accidental +secret/source oversharing; enforce deduplication/idempotency for retries. +Existing static-analysis fallback may still produce a comment, but only inside +the same authorized context; fallback cannot bypass permission or quota errors. + +## 14. Background scan authorization + +Extend the existing `run_background_scan(repository_id)` contract to an immutable +job identity: initiating CodeLens user, repository/binding IDs, connection +generation and requested read-only operation. Persist these IDs/status in a job +record; put no credential material in task arguments. Existing BackgroundTasks +can initially dispatch it, but durable execution is a separate operational +upgrade, not an assumed current capability. + +Re-resolve ownership, connection, installation and user access at execution, +before each remote batch and before committing/displaying results. Refresh through +the same coordinated manager. Disconnect, removal or changed generation cancels +remaining work; staged source is not promoted after access loss. Failed checks +release scan state and report a neutral actionable status. No installation-token +or other user's token fallback. Jobs initiated before logout may finish while +their explicit GitHub connection remains active; disconnect cancels them. + +## 15. Organization/SAML considerations + +An organization owner installing the App does not authorize every member's +CodeLens account. Each member must authorize the App; installation selection, +membership, role changes, organization restrictions and suspension are honored. +New App permissions may need installation-owner approval; an old installation +must not be assumed to have the new permissions. + +SSO-protected organizations may need an active SAML session during authorization +or installation. If organization resources are missing, guide the user through +SSO and appropriate reauthorization rather than escalating to a service token. +Do not implement PAT-style SSO handling as if it were GitHub App authorization. +Enterprise-managed users and actual organization policies need sandbox validation +before support is claimed. Initial host scope is GitHub.com; GitHub Enterprise +Server/custom API hosts require a separately validated deployment design. +[SAML and GitHub Apps](https://docs.github.com/en/enterprise-cloud%40latest/apps/using-github-apps/saml-and-github-apps). + +## 16. Required GitHub App permissions + +| Permission | Proposed level | Reason | +| --- | --- | --- | +| Repository Metadata | Read | Identify repositories/installation association | +| Repository Contents | Read/write | Read tree/source; create fix refs and commit files | +| Repository Pull requests | Read/write | Read PR diff/source metadata; create PRs; post PR timeline comments | +| Repository Issues | Not requested initially | PR comment endpoint accepts Pull requests write as an alternative | +| Repository Workflows | Not requested | Workflow-file changes explicitly denied | +| Administration, organization Members, user Emails | Not requested initially | Not needed for the current feature set; no email identity linking | + +Use least privilege and selected repositories. Subscription proposal: +`github_app_authorization`, `installation`, `installation_repositories` and +repository rename/transfer/delete events supported by the selected permissions; +verify event availability when registering. No automatic PR-review automation +is introduced solely by subscribing to events. +Endpoint requirements: [Git refs](https://docs.github.com/en/rest/git/refs#create-a-reference), +[file commits](https://docs.github.com/en/rest/repos/contents#create-or-update-file-contents), +[PR creation](https://docs.github.com/en/rest/pulls/pulls#create-a-pull-request), +[PR timeline comments](https://docs.github.com/en/rest/issues/comments#create-an-issue-comment). +Permission changes require reviewing existing installation approvals. +[App permissions](https://docs.github.com/en/apps/creating-github-apps/registering-a-github-app/choosing-permissions-for-a-github-app). + +## 17. Required backend models/tables + +All names below are proposed. Use BIGINT for GitHub numeric IDs, independent of +CodeLens integer primary keys; UTC timestamps, FK constraints and explicit indexes. + +| Proposed table | Essential fields/invariants | +| --- | --- | +| `github_connections` | CodeLens user FK, GitHub user ID, display login, status, authorization generation, encrypted credential pair/envelope metadata, expiry, refresh lease/version; partial unique constraints prevent multiple active connections per CodeLens user or reuse of one GitHub identity across active CodeLens accounts; disconnected historical rows may remain credential-free | +| `github_oauth_transactions` | Hashed state, user/session/browser binding, encrypted PKCE verifier, purpose, expiry and consumed timestamp; atomic one-use | +| `github_installations` | Unique installation ID, App ID, stable account ID/type, status, granted permissions, repository selection and reconciliation timestamps; contains no user credential | +| `github_repository_bindings` | Unique local repository FK, owner connection FK, installation FK, numeric GitHub repository ID, status and last verified metadata; check owner consistency in resolver/transactions | +| `github_operations` | Actor, repository/binding, connection generation, operation/idempotency key, expected head SHA, fix branch/commit/PR/comment results and sanitized status; branch provenance and audit | +| `github_scan_jobs` | Actor/binding/generation, bounded parameters, lifecycle/cancellation status; no token fields | +| `github_webhook_deliveries` | Unique delivery ID, event type, validated subject IDs, processing/reconciliation status and bounded retention; do not retain raw sensitive payloads by default | +| `github_revocation_tasks` | Restricted encrypted remote-revocation material only when necessary, expiry/retry status; unavailable to data-operation resolver | + +Use existing `Repository`, source/finding/review/snapshot relationships unchanged. +Local bindings preserve per-user duplicate GitHub repo records. Owner/connection +FK consistency and account collisions must be verified transactionally, not just +by frontend filtering. Use bounded retention for transactions/delivery/job logs. + +## 18. Required migrations + +Design only—no migration files are created here. Existing migration head is +`0207cb567c11`; confirm actual head again before a future migration is authored. + +An additive migration series would create connection/transaction/installation/ +binding tables, then operation/job/delivery/revocation tables and indexes. +Do not change `users.google_sub`, password nullability, repository ownership or +existing per-user uniqueness. Legacy repository rows start unverified; do not +backfill GitHub numeric IDs or access grants by trusting `github_id`/full_name. +Only authenticated GitHub verification may populate bindings. Preserve existing +source/history during schema rollout, but gate access until verified (section 24). + +Test fresh/reused databases, constraints, transaction races, upgrade and safe +downgrade/rollback. A downgrade must not restore shared-token runtime behavior; +encrypted credentials must be purged safely rather than left orphaned. Obtain +separate implementation/migration authorization before writing any migration. + +## 19. Required routes + +Proposed additional routes (names subject to implementation review): + +| Method / path | Purpose/security | +| --- | --- | +| `GET /github/connection` | Caller connection status/display identity only; no credentials | +| `POST /github/authorize` | Authenticated, recent-auth/Origin-checked transaction start; return fixed authorization navigation URL | +| `GET /github/callback` | Browser-bound one-use state + logged-in user verification; backend exchange, fixed redirect | +| `GET /github/installations` | Caller-visible verified installation list, bounded pagination | +| `GET /github/installations/{installation_id}/repositories` | Caller-visible App-selected repositories; never trust the requested installation ID alone | +| `POST /github/installations/start` | Create a bound installation-navigation transaction | +| `GET /github/installations/callback` | Treat setup parameters as untrusted; verify through GitHub | +| `DELETE /github/connection` | CSRF-checked disable/cancel/purge and remote-revocation attempt | +| `POST /github/webhooks` | No CodeLens session required; strict webhook signature/body/delivery validation | + +Existing connection/metadata, scan/ingest, PR reads/AI and three mutation routes +keep their paths and successful response shapes but require the resolver. +Protect cached-data paths in `ask.py`, `code_retriever.py`, `pr_reviews.py` and +`dashboard.py` as well. Apply Phase 6 limits/headers to new routes; define separate +bounded webhook abuse controls without relying on session-based limiting. +Use neutral codes such as `GITHUB_CONNECTION_REQUIRED`, +`GITHUB_REAUTHORIZATION_REQUIRED`, `GITHUB_INSTALLATION_REQUIRED`, +`GITHUB_ACCESS_DENIED`, and `GITHUB_UNAVAILABLE`; retain 401 for missing CodeLens +authentication, avoid private-resource enumeration, and preserve quota semantics. + +## 20. Required frontend changes + +Extend `apps/web/lib/api.ts` with status, authorization, installation discovery +and disconnect methods/types. Update `apps/web/app/dashboard/page.tsx` with a +GitHub connection panel, verified repository chooser, pending installation/ +SSO/reconnection states and operation-capability controls. A proposed dedicated +GitHub settings page can keep that large existing dashboard from growing further. + +Use backend-generated navigation URLs; callback returns fixed status, not +credentials. No GitHub tokens in React context, localStorage, sessionStorage, +NEXT_PUBLIC variables or URL fragments. Preserve `lib/auth-context.tsx` and +password/Google login semantics. Disabled buttons improve UX but are not policy +enforcement. Handle neutral new error codes without infinite retries. Explicit +disconnect confirmation explains cached-data locking and scan cancellation. + +## 21. Required service-layer changes + +| Existing file/area | Proposed change | +| --- | --- | +| `app/core/config.py` | App/KMS secret-reference configuration and startup validation; remove runtime shared token | +| `app/main.py`, `app/core/rate_limit.py` | Register new routes and specific bounded limits; preserve Phase 6 middleware | +| `app/api/routes/repositories.py` | Resolve actor/repository operation context; capture background actor; provenance checks | +| `app/services/github.py` | Explicit authorized context for metadata/tree/source; bounded pagination and constrained HTTP requests | +| `app/services/ingestion.py` | Carry the same context for every fetch and guarded result promotion | +| `app/services/pr_reviewer.py` | Caller-authenticated PR metadata/files/content reads, retaining host validation | +| `app/services/branch_fixer.py` | Remove global fallback; enforce authorized context, branch provenance/preconditions and idempotency | +| `app/services/pr_commenter.py` | Remove global fallback; authorization before analysis/comment; same-context fallback | +| `app/services/scan_progress.py` | Integrate guarded job cancellation/status; retain atomic Phase 6 claim behavior | +| `app/api/routes/ask.py`, `services/code_retriever.py`, `api/routes/pr_reviews.py`, `api/routes/dashboard.py` | Gate/filter cached private content before reads/AI dispatch | +| `app/schemas/repository.py`, relevant schemas/model registration | Public connection/capability statuses, never credentials | + +Proposed new modules: GitHub App flow client, credential/encryption/refresh +manager, repository authorization resolver, installation/webhook service and +sanitized operation recorder. Centralize GitHub HTTP calls with fixed allowed +hosts, safe redirect policy, bounded body sizes, encoding and timeouts. +App identity/JWT operations are segregated from user-content operations. +AI providers/analyzers need no credential awareness; preserve existing quotas. +No current Phase 6 fix depends on implementing F02. + +## 22. Required tests + +Tests must use synthetic credentials/mocked GitHub and a disposable database; +never log token responses or use production repositories. Required regressions: + +- OAuth state/session/browser binding, TTL, denial/cleanup, callback replay, + PKCE, account collision and malicious redirect/install-ID substitution. +- Encryption integrity, wrong associated data/key/version, repr/serialization/ + validation/log secrecy, KMS outage and rotation/backup restoration. +- Expiring token refresh, single-use rotation, simultaneous replicas, timeout + after remote consumption, stale lease and disconnect-versus-refresh races. +- Two CodeLens users; token belongs to correct actor; private reads and writes + denied when only the other user or installation can access the repository. +- All three mutation routes; operation-specific rights, stale SHA, unrelated + branch, workflow paths, branch protection, duplicate/unknown-outcome handling. +- Private source/findings/Ask/explanations/fixes/tests/review history/trend do + not leak after disconnect or permission loss; metadata/list enumeration checks. +- Scan actor/generation persistence, permission removal mid-job, cancellation + and no result promotion or fallback after access loss. +- Signed webhook validation, bad signatures, replay/deduplication, wrong App, + out-of-order removal/suspension/reinstatement and bounded body/retention. +- Organization selected repositories, changed permissions, SSO required, + revoked membership and transfer/rename with immutable IDs. +- Every missing/expired/revoked user-credential path fails closed even when + legacy GITHUB_TOKEN or an installation credential is configured. +- Migration constraints/backfill safety, old repository response compatibility, + frontend connection/error/disconnect UX and all Phase 1–6 regressions. + +Future release validation: complete backend pytest on CI's supported runtime, +TypeScript validation, frontend build, dependency/secret/diff checks and a +separately approved sandbox GitHub App end-to-end test. Documentation creation +does not rerun or certify the previously recorded Phase 6 test result. + +## 23. Removing existing GITHUB_TOKEN fallback + +Replace every `settings.github_token` read and `token or settings.github_token` +path with required authorized user context. Replace unauthenticated PR reads; +reject missing context before network access. Low-level clients must not accept +caller-controlled tokens from request JSON or silently substitute credentials. + +Remove shared-token guards in apply-fix/create-PR and global setting/config +references in API Compose/CI/development documentation when future cutover is +authorized. Treat a still-present runtime GITHUB_TOKEN as a deprecated unused +variable with a value-free warning; never read it for SaaS operations. Removal +of a deployed legacy credential is a separately approved operator action, not +something this design task does. GitHub Actions' platform token is unrelated; +do not break CI by indiscriminately removing platform-provided token usage. + +## 24. Backward compatibility/migration strategy + +1. Implement/test additive schema and App flows in a future approved branch. +2. Register/test an App and secret/KMS setup in an approved sandbox; no live + deployment or secret change is authorized by this document. +3. Disable legacy privileged GitHub operations at cutover BEFORE enabling public + SaaS onboarding; there must be no period of dual unsafe fallback behavior. +4. Existing rows remain owned by their existing CodeLens users but are marked + unverified. Reconnect through GitHub, then bind only after numeric-ID and + permission verification. Rows whose legacy target cannot be verified remain + locked; no blanket conversion of local ownership into GitHub authority. +5. Keep source/history physically retained during an explicitly approved + migration/retention window, hidden from retrieval/AI until authorization is + verified; allow owner deletion and neutral reconnection/status information. + Restrict metadata that itself reveals formerly private repository identity. +6. Preserve successful route response shapes and frontend auth. New neutral + connection-required failures are intentional compatibility changes. Old + branches have no trusted fix provenance; do not automatically authorize PRs + for them. Deploy backend/frontend compatibility together or gate safely. +7. Rollback fails closed/temporarily disables GitHub integration; NEVER restore + shared-token delegation. Operator rotates/removes the legacy credential only + after confirming all runtime consumers were intentionally migrated. + +No existing data is automatically deleted or migrated by this document. Any +retention/purge/backfill job needs explicit approved scope and recovery review. + +## 25. Security failure cases + +| Failure | Required outcome | +| --- | --- | +| Caller owns local row but lacks GitHub access | Deny before private read/AI/write; no service-token substitution | +| Wrong connection/installation/repository or renamed URL now identifies another repo | Deny numeric-ID mismatch; require verified binding | +| Expired/revoked token, refresh unavailable | Bounded refresh or reauthorization; no stale cache success | +| KMS/DB/GitHub outage | Neutral temporary failure, no private cached fallback; bounded retries | +| Organization suspension, repository deselection, member removal | Invalidate known grants/jobs, live checks deny further use | +| Callback tampering/replay/session swap | Reject and clear transaction; no account merge or credential overwrite | +| Invalid/replayed webhook | Reject/deduplicate; no authorization changes from unverified payload | +| Refresh overlaps disconnect | Generation fence prevents reactivation | +| Write accepted remotely but response lost | Reconcile operation; no automatic duplicate mutation | +| Access changes during a job/mutation | Stop at next check; report partial outcome; never claim retroactive rollback | +| User supplies workflow/default-branch/traversal/unknown head | Deny explicit branch/path/provenance policy | +| Prompt injection requests different repository/identity/action | AI never selects credentials or expands authorization | + +Keep rate/resource/AI/body/CSRF protections independent of GitHub grants. Redact +secrets in provider responses/errors/telemetry and sanitize external diagnostics. +The App does not itself fix all other remaining Phase 6 deployment/resource risks. + +## 26. Logout, disconnect and revocation behavior + +CodeLens logout clears the CodeLens session only; it is NOT GitHub disconnect or +GitHub App uninstall. Explicit authorized queued scans may complete after logout, +but no new action is permitted without CodeLens authentication. Current stateless +CodeLens JWT revocation limitations remain; this design does not rebuild sessions. + +GitHub disconnect disables local use immediately, cancels jobs, locks cached +private-derived views and initiates remote authorization revocation. It does +not uninstall an organization-wide App or affect other users' independent +connections. Reconnection revalidates identities/repositories; it does not revive +stale queued operations. GitHub-side user revocation disables that connection; +App uninstall/suspension or repository removal affects relevant bindings across +users. Locally known events take effect immediately; remote discovery delays +and in-flight work cannot be represented as instantaneous revocation guarantees. + +Account deletion must first disconnect/revoke safely, then apply the approved +CodeLens data-retention/deletion policy. Removing the local repository row does +not delete remote branches/PRs/comments. Do not uninstall an App just because a +single CodeLens user logs out, disconnects or deletes their account. + +## 27. Deployment environment variables — names only + +Existing names relevant to this design: + +```text +DATABASE_URL +AUTH_SECRET_KEY +AUTH_COOKIE_NAME +AUTH_COOKIE_SECURE +AUTH_COOKIE_SAMESITE +AUTH_TOKEN_EXPIRE_MINUTES +FRONTEND_URL +NEXT_PUBLIC_API_URL +GITHUB_TOKEN +``` + +Proposed GitHub App names (not currently implemented): + +```text +GITHUB_APP_ID +GITHUB_APP_SLUG +GITHUB_APP_CLIENT_ID +GITHUB_APP_CLIENT_SECRET +GITHUB_APP_PRIVATE_KEY_SECRET_REF +GITHUB_APP_WEBHOOK_SECRET +GITHUB_APP_REDIRECT_URI +GITHUB_APP_SETUP_REDIRECT_URI +GITHUB_API_VERSION +GITHUB_TOKEN_KMS_KEY_ID +GITHUB_TOKEN_ENCRYPTION_VERSION +``` + +GITHUB_TOKEN is listed for removal, not target SaaS authorization. Only +NEXT_PUBLIC_API_URL is intended for client exposure. App secret/private-key +material and encryption credentials must remain server-side. Cloud-specific KMS +identity variable names depend on the provider selected; do not invent a current +provider configuration. Prefer workload identity to stored cloud access keys. +No values, token examples, connection strings or credential material are included. + +## Design review / implementation gate + +This is documentation only. F02 remains unimplemented and the Phase 6 release +blocker remains open. Implementation requires a separate user instruction. +Before coding, confirm KMS/runtime identity, App registration/permission settings, +retention window, sandbox organization coverage and authorization-check quota +budget. These are deployment/product decisions, not verified live facts. +No migrations, credentials, production code, Phase 6 fixes, commits, pushes, +merges or deployments are created/changed by this document. diff --git a/SECURITY_AUDIT_PHASE6.md b/SECURITY_AUDIT_PHASE6.md new file mode 100644 index 0000000..a36d426 --- /dev/null +++ b/SECURITY_AUDIT_PHASE6.md @@ -0,0 +1,464 @@ +# Phase 6 Security Audit + +Date: 2026-10-07. Baseline: f57dcd81ecf44956a3a97f22a20a4fea28867cff. + +## Executive Summary + +Authentication, OAuth, repository ownership, resource limits, AI provider controls, +rate limiting and HTTP hardening exist. Their presence does not establish that all +guarantees in CODEX_CONTEXT.md hold. Concrete defects were found in rate-limit +identity and scope, OAuth linking/cleanup, JWT requirements, error handling and +cookie-authentication CSRF protection. The shared server GitHub token is also an +unresolved authorization boundary for a public multi-user deployment. + +This report was created before production code changes. Audit sections describe +the baseline; the remediation/validation section records the final fixed state. +No live Render, Supabase, Vercel or Google configuration was inspected. + +## Repository State + +- Remote: origin, yashvatsdev/codelens on GitHub; fresh fetch completed. +- Execution workspace main: 1f669cd04eac8531663cd16eba49df6d9d9c0aac, 30 commits behind. +- That workspace has an existing app/core/config.py edit and untracked context file. +- IDE checkout C:/Users/yashv/codelens: main at f57dcd8. +- Audit worktree: .audit-worktree on security/final-security-audit at f57dcd8, + matching origin/main, initially clean. All audit changes are confined there. +- CODEX_CONTEXT.md was read completely from the parent workspace. Its assertions + about synchronized/clean local main, complete enumeration protection, universal + OAuth cleanup and complete Phase 5 coverage are not evidence of those properties. +- Existing migrations were applied to a disposable local test database; no new + migrations were created. The application database was not used by tests. + +## Authentication + +HS256 is explicitly selected when verifying sessions; Argon2 hashes passwords. +Auth responses use UserResponse, excluding password_hash and Google/provider tokens. +OAuth-only accounts are rejected by password login. Missing cookies, bad signatures +and expired tokens are rejected. However exp is not required, subject parsing is +not strictly positive/canonical, and token creation contains no random transaction +identifier. Login short-circuits hashing for unknown/OAuth-only users. Signup +reveals existing email addresses and has no backend password-length constraint. +Logout removes the browser cookie; stateless JWTs copied beforehand remain valid +until expiration. No session database/revocation redesign is proposed. + +## Authorization / Tenant Isolation + +Repository routes check current_user and repository.user_id before data/AI/GitHub +operations. Nested finding routes also compare finding.repository_id. Repository +listing, dashboard snapshots and PR review history are user-scoped. Ask checks +ownership in code_retriever before retrieving SourceFile rows. There is no separate +public finding router and no repository update route. No database-row IDOR was +identified by inspection; a two-user HTTP matrix is required to validate it. + +CodeLens ownership is not proof of GitHub permission: any authenticated account +can connect a URL, and GitHub requests use one application-wide token (F02). + +### Endpoint inventory + +All application routes are listed below; FastAPI also supplies public /docs, +/docs/oauth2-redirect, /redoc and /openapi.json. The body middleware applies globally. +DB = SQLAlchemy; GH = GitHub HTTP; AI = cloud/local provider HTTP. Repository paths +use r = repository_id, f = finding_id, p = pull_request_number. + +| Method / path | Auth/authorization | Main access / response | Baseline limit | +| --- | --- | --- | --- | +| POST /auth/signup | public | DB insert, Argon2, user/session | 5/min | +| POST /auth/login | public | DB lookup, Argon2, user/session | 10/min | +| POST /auth/logout | public | cookie removal | default | +| GET /auth/me | session user | DB user, public user fields | default | +| GET /auth/google/login | public | Google discovery/redirect, transaction cookies | 10/min | +| GET /auth/google/callback | state/nonce transaction | Google token/JWKS, DB link/create, redirect/session | default | +| GET /health | public | lightweight status | 120/min | +| GET /db/health | public | DB SELECT 1/status | 30/min | +| GET, POST /repositories/github/metadata | session | URL input; GH metadata | 30/min | +| POST /repositories/github | session | URL/ref input; GH metadata, DB insert | 10/min | +| POST /repositories | session | explicit metadata or URL; DB insert | default | +| GET /repositories | session, user filter | DB metadata list | default | +| GET /repositories/{r} | repository owner | DB metadata | default | +| DELETE /repositories/{r} | repository owner | DB cascade deletion | default | +| GET /repositories/{r}/files | repository owner | DB file metadata, no contents | default | +| POST /repositories/{r}/ingest | repository owner | GH tree/contents, DB source replacement | default | +| POST /repositories/{r}/analyze | repository owner | DB source/findings/snapshot | default | +| POST /repositories/{r}/scan | repository owner | background GH + DB analysis | 5/hour | +| GET /repositories/{r}/scan-status | repository owner | process-local progress | default | +| GET /repositories/{r}/findings | repository owner | DB finding data | default | +| POST /repositories/{r}/findings/{f}/explain | repository owner, nested finding | DB source, AI explanation | 20/hour | +| POST /repositories/{r}/findings/{f}/fix | repository owner, nested finding | DB source, AI suggested code/diff | 10/hour | +| POST /repositories/{r}/findings/{f}/test | repository owner, nested finding | DB source, AI test text | 10/hour | +| POST /repositories/{r}/findings/{f}/apply-fix | repository owner, nested finding | optional ref/message; AI + GH branch/commit | default | +| POST /repositories/{r}/findings/{f}/create-pr | repository owner, nested finding | branch/title/body; GH PR mutation | default | +| POST /repositories/{r}/pull-requests/{p}/review | repository owner | GH changed source/static findings | default | +| POST /repositories/{r}/pull-requests/{p}/ai-review | repository owner | GH + AI + DB PR history | 5/hour | +| POST /repositories/{r}/pull-requests/{p}/findings/fix | repository owner, file/line membership | GH + AI fix text | default | +| POST /repositories/{r}/pull-requests/{p}/comment | repository owner | summary input; GH + AI + GH comment | default | +| POST /repositories/{r}/ask | repository owner | question input; DB context + AI answer/citations | 20/hour | +| GET /pr-reviews | session, review.user_id filter | DB history, caller-controlled limit | default | +| GET /pr-reviews/{review_id} | session, review.user_id filter | DB review/detail | default | +| GET /dashboard/findings-trend | session, repository owner filter | DB snapshots | default | + +No application endpoint extracts archives, writes repository files to disk or +executes the returned code. Responses containing source snippets/findings are +sensitive even when they contain no authentication credentials. + +## Google OAuth + +Random state and nonce, browser cookie equality, Google discovery, signed ID-token +decode, issuer/audience/expiration/nonce comparisons and verified email checks exist. +Redirect destinations come from server FRONTEND_URL, not callback inputs. Token +exchange occurs on the backend. The temporary cookies are plain random strings, +not signed cookies as a module comment claims. Browser max-age alone does not +provide server-enforced transaction expiry/replay tracking. Google authorization +codes are single-use, limiting replay; no live provider replay was attempted. +The baseline can overwrite a previously linked different google_sub, treats any +truthy email_verified as verified, and leaves transaction cookies on failure. +JWKS is cached for the process lifetime without refresh after key rotation. + +## Rate Limiting + +The limits package, MemoryStorage, FixedWindowRateLimiter, per-route limits, +neutral 429 and Retry-After exist. X-Forwarded-For is ignored by this middleware. +Unverified JWT sub is trusted for identity (F01). Counters are keyed by raw path, +so resource IDs, trailing slashes and alternate routes multiply budgets (F03). +The default is a per-path 60/min limit, not a total client-wide global budget. +Apply-fix, PR-fix and PR-comment are expensive but only receive the default limit. +Counters are process-local; replicas multiply effective limits. Actual Render +proxy client-IP behavior is not verified and uvicorn proxy handling is separate +from the application ignoring forwarded headers. + +## Resource Exhaustion + +10,000 tree entries, 200 ingestion files, 100,000 bytes/file, 20,000,000 aggregate +source bytes, 1,000,000 request bytes, 120,000 AI prompt characters and 4,096 output +tokens are configured. Ask retrieves at most five excerpts of 200 lines each, +1,000 lines total, and questions are at most 2,000 characters. PR review paginates +to 300 files; oversize source is checked after download. GitHub JSON responses +are read in full before tree-count checks. Ingestion does not independently reject +an actual oversized individual file when tree metadata underestimates it. +Scan progress is process-local. Checking active state then setting queued state +uses separate locks, allowing a concurrent-start race; direct ingest/analyze +routes also bypass the background scan guard. Repository lists, trend history, +caller-supplied PR history limit, snapshots and in-memory scan entries can grow. + +## AI Security + +Centralized provider controls enforce prompt size, output limits, cloud timeout +and one cloud-to-Ollama fallback. No tool execution, arbitrary DB query or backend +secret is supplied to the model. Repository content is untrusted prompt data; +it can affect suggestions but cannot itself execute server commands. Generated +tests are returned as text. GitHub changes require explicit endpoints and never +merge automatically. Generated changes still require human review. +Provider error logs interpolate raw exceptions, and sanitize_ai_error preserves +unrecognized raw text. Ask catches AIQuotaExceededError and changes 429 to 503. +Several AI services require a Gemini key even when Ollama-only is configured. + +## GitHub Security + +Token use is server-side Authorization headers; response schemas do not serialize +it. The same token serves all CodeLens users; no GitHub user connection/permission +binding exists. Manual repository creation accepts owner/name/full_name/URL +without validating them when all are supplied. Branch and ref parameters are +interpolated in URLs without consistently encoding them. The branch client +returns upstream response bodies and reasons through GitHubAPIError. + +## SSRF + +Normal GitHub URL parsing constructs https://api.github.com requests rather than +fetching the supplied URL. Direct localhost, private-IP, file and FTP repository +URLs are rejected by that parser. OAuth discovery starts from a fixed Google URL; +Ollama URL is server configuration, not a user request field. PR contents_url is +used without host/scheme validation and urllib follows redirects. A compromised +or unexpected upstream response could therefore request internal targets. An +attacker-controlled redirect from the real GitHub API was not demonstrated. +Do not label this as a verified internet-exploitable internal-network SSRF. + +## Path Traversal + +Repository paths are stored as DB strings; analyzers process strings. No local +repository checkout/extraction/write path exists. Remote GitHub identifier and +path/ref validation needs tightening (F07), but arbitrary local filesystem writes +were not identified. Suggested test_file names are not executed or written. + +## Command Execution + +No dangerous command execution path identified in the application. Python AST +parsing and JavaScript pattern matching do not run repository code. Occurrences +of eval in the JS analyzer are detection rules, not calls. CI/Docker shell commands +are static, with no untrusted GitHub issue/PR text interpolation. + +## SQL Injection / Database Security + +Application SQLAlchemy queries use expression parameters. The raw health SQL is +constant SELECT 1. Test sequence SQL is constant. No dynamic user-derived SQL or +dynamic table names were identified. Repository user_id is nullable for legacy +rows; owner checks deny these rows to ordinary authenticated users. Repository +deletion cascades source/findings/snapshots; PR FK has database cascade. Unique +email/google_sub and per-user github_id constraints exist. OAuth/signup concurrent +inserts can raise IntegrityError; safe rollback/redirect needs coverage. +Tests mutate rows and synchronize sequences, so they must use a disposable DB. + +## Error Handling + +/db/health exposes str(e). Provider/branch errors can expose internal diagnostics +and upstream bodies; AI logs also include exception strings. Unhandled errors +are generic framework 500 responses with debug disabled, but explicit raw-error +responses bypass that protection. Validation responses can include submitted +password input; error schemas must avoid returning it. + +## CORS / CSRF / Cookies + +CORS trusts the configured FRONTEND_URL and uses credentials. Actual production +value is unverified. Wildcard/invalid origin configuration is not rejected at +startup. Session cookies are HttpOnly, path=/, host-only; Secure and SameSite are +configurable and default to development values. Lax prevents most cross-site +authenticated POSTs, but default Vercel/Render hostnames require cross-site cookie +configuration for credentialed fetch. SameSite=None enables simple cross-site +logout POSTs; CORS does not prevent side effects. No server Origin validation +exists in the baseline. Browser third-party-cookie restrictions remain a deployment +compatibility issue independent of backend correctness. + +## Security Headers + +Security middleware supplies nosniff, DENY, referrer/permissions policies, HSTS +for an HTTPS scope and no-store on auth. 413 bypasses parts of this header path. +CORS is registered inside rate/body middleware, so their direct 429/413 responses +do not receive CORS headers. Swagger remains enabled and no backend CSP is added. +Streaming overflow can be converted by FastAPI to a body-parse 400 instead of 413. + +## Secret Leakage + +Safe detection scanned 388 reachable history blobs for private keys, GitHub token +formats, Google API-key formats and AWS access-key IDs: no matches. No .env file +was found in reachable history. This is bounded pattern detection, not proof that +arbitrary opaque credentials have never been committed. Tracked config/Compose/CI +and seed files contain identifiable development/test credentials; values are not +reproduced here. No verified production credential exposure was established. +.dockerignore excludes .env variants, git metadata and tests; Docker COPY is +explicit. Root .gitignore does not cover every .env.* name. Backend configuration +has a public default signing secret; deployment must not accept it silently. + +## Dependency Security + +Python requirements pin many packages but leave authentication/provider packages +open-ended; no complete Python lock exists. Both psycopg and psycopg2 drivers are +declared. npm lockfile exists; Next.js is 16.3.4, React 19.2.8. Maintainer advisories +were checked, not inferred from package age. Next.js September release recommends +16.3.8, but listed production issues require features not configured here (remote +image patterns, Pages Router/catch-all/cache components or metadata image routes). +The next/og RCE advisory also requires ImageResponse usage, not found here. No +CodeLens exploit of those advisories was established. Dependency scanning and +resolved-version results are recorded under validation; no broad upgrade. + +Sources: [Next.js September release](https://nextjs.org/blog/september-2026-security-release), +[next/og advisory](https://github.com/vercel/next.js/security/advisories/GHSA-vcvr-r3jv-pc5j), +[joserfc claim validation advisory](https://github.com/authlib/joserfc/security/advisories/GHSA-r74j-q665-7rpj). + +## Docker Security + +Python 3.13 slim image, explicit copies, uvicorn 0.0.0.0:8000; no privileged mode +or Docker socket mounts. Image has no USER directive and runs as root. Compose +is development-oriented: database port exposure, development credentials, insecure +cookies and fallback signing key. Do not deploy this Compose configuration as a +production security configuration. No production image was built in this audit. + +## CI/CD Security + +Backend push/PR workflow uses Python 3.13 and PostgreSQL 16, applies migrations, +then pytest. It does not use production repository secrets or interpolate PR text +into shell scripts. Action versions are tags, permissions are not explicitly +restricted, and dependency/security scanning is absent. pull_request_target is +not used. Real repository token permissions and branch protection are unverified. + +## Frontend Security + +Credentialed fetch, in-memory user context and backend OAuth navigation exist. +No localStorage/sessionStorage authentication token or dangerouslySetInnerHTML +was found. React displays code/AI output as text. NEXT_PUBLIC_API_URL is the public +backend address; no backend secret environment variable is referenced by browser +code. Repository href is server-stored data, including arbitrary manual-create +URL in the baseline. No verified cross-user XSS was established. Logout clears +UI state even if the API logout fails; that does not revoke a surviving cookie. + +## Phase 1–5 Regression Check + +| Protection | Baseline result | +| --- | --- | +| Password + JWT authentication | Present; claim/password validation gaps | +| Google OAuth | Present; linking/cleanup/claim-type gaps | +| Repository/finding ownership | Present; HTTP matrix to be added | +| Rate limiting | Present; identity/path bypasses | +| Resource limits | Present; concurrency/response-size limitations | +| AI quotas/provider limits | Present; Ask quota HTTP mapping regression | +| Request-body limit | Present; streaming behavior needs regression test | +| Security headers | Present; direct middleware responses incomplete | +| FRONTEND_URL CORS | Present; live value unknown, middleware ordering defect | +| Signup enumeration protection | Not present despite context claim | + +## Findings + +Every entry refers to the inspected baseline, not an invented live incident. + +| ID / severity | Location | Vulnerability and impact | Recommended fix | Exploit verification | +| --- | --- | --- | --- | --- | +| F01 High | core/rate_limit.py _get_client_key | Unverified sub lets forged cookies rotate login/signup budgets or consume another user's counters | Verify signature/claims; use IP for public auth flows | Verified locally: forged cookie selected a user budget; regression now passes | +| F02 High | GitHub services; repository connection/apply-fix/create-pr/comment | Shared server token authority is available to arbitrary CodeLens accounts that connect a repository; CodeLens ownership does not prove GitHub permission | Explicit per-user GitHub authorization or restricted operator-approved access policy before public signup | Authority flow confirmed; no live private data read or GH write attempted | +| F03 Medium | core/rate_limit.py dispatch/ROUTE_LIMITS | Raw path namespaces and alternate routes multiply expensive-operation budgets; no client-wide global bucket | Canonical route buckets, auth IP bucket, default global bucket and missing expensive-route rules | Verified locally: rotating resource IDs/trailing slashes avoided the operation budget; aggregate/alternate/header tests now pass | +| F04 Medium | main.py db_health; services/branch_fixer.py; AI service logging | Raw DB/upstream/provider exceptions can disclose internals or credentials if embedded by upstream | Generic responses and no raw provider exception logs | Verified with synthetic diagnostics: DB/GH responses and AI logging; neutral errors and secret-safe Settings representations now tested | +| F05 Medium | routes/auth.py _resolve_user/_fail_redirect; core/oauth.py | Existing linked Google identity can be replaced; failure cookies persist; truthy nonboolean verification accepted | Reject conflicting linked sub, strict verified flag/claims, always clear failure cookies | Verified with mocked resolution/callback: linked sub replacement, truthy flag and retained failure cookies; regressions now pass | +| F06 Medium | api/deps.py; core/security.py; schemas/user.py | Missing exp accepted, subjects loosely parsed, deterministic sessions within a second, empty/huge passwords accepted | Require claims, canonical positive ID, random token ID, bounded signup/login fields | Verified locally: signed sessions without exp/noncanonical IDs accepted, duplicate token issuance, corrupt hash failure and password bounds; regressions now pass | +| F07 Medium | routes/repositories.py create_repository; services/github.py | Manual route skips URL/identifier validation; path/query-bearing names reach remote API URLs and arbitrary URL reaches browser | Canonical URL/metadata consistency and identifier validation | Verified locally: explicit metadata bypassed parser and dot identifiers accepted; invalid cases now rejected before DB/network | +| F08 Medium (deployment-dependent) | core/middleware.py; auth/logout | SameSite=None cookie sent on simple cross-site logout POST; CORS is not a CSRF gate | Validate Origin for unsafe browser requests, reject cross-site requests missing Origin | Verified locally: cross-site-header logout mutated cookies; now 403 before mutation; live cookie behavior not exercised | +| F09 Medium | core/config.py auth_secret_key | Known default signing key silently enables token forgery when operator omits configuration | Require explicit signing key; validate production cookie/origin configuration | Verified default acceptance by inspection/config tests; omission/unsafe origins/cookies now rejected; live omission not verified | +| F10 Medium | api/routes/ask.py exception handling | Quota/context exhaustion becomes 503 instead of neutral 429 | Propagate AIQuotaExceededError to existing handler | Verified mocked quota returned 503; regression now receives existing 429 quota schema | +| F11 Medium | routes/auth.py signup; schemas/user.py | Duplicate signup discloses email existence; API accepts weaker password than advertised frontend | Deliberate signup UX decision; enforce existing advertised length on backend | Distinct signup 409 confirmed; password bounds fixed/tested, enumeration deliberately remains pending UX decision | +| F12 Medium | scan route/progress; unbounded list/history reads | Concurrent scan-start check/set race, direct ingest/analyze overlap, unbounded retained histories/response reads | Atomic scan claim and durable/shared limits/pagination where necessary | Separate locking confirmed by inspection, concurrency stress/active direct-route tests now pass; negative/unbounded PR limit reproduced and bounded; upstream/history growth remains | +| F13 Low | core/middleware.py; main.py middleware order | 429/413 lack CORS; 413 omits some security headers; chunk overflow may return 400 | Reorder CORS; consistent security headers; pre-parse streaming limit | Verified local HTTP/ASGI: missing early CORS/headers and swallowed streaming overflow; regressions now pass | +| F14 Low | Dockerfile, .gitignore, CI | Root container, incomplete env ignores, unpinned auth dependencies/actions and implicit CI permissions | Least privilege, env ignore coverage, planned dependency/action locking | Configuration verified; no remote compromise demonstrated | +| F15 Low | core/oauth.py JWKS cache; urllib HTTP clients | Lifetime JWKS cache can fail after rotation; unexpected contents URLs/redirects lack explicit policy | Expiring/refreshed JWKS and constrained outbound URLs/redirect policy | Code confirmed; malicious real GitHub redirect not verified | +| F16 Informational | core/security.py logout architecture; deployment | Stateless logout does not revoke copies; process-local rate/scan state; browser cross-site-cookie compatibility | Document constraints and validate deployment topology | Architecture verified, live topology unknown | + +## Final Risk Assessment + +High after remediation because F02 remains unresolved. A public multi-user +deployment must resolve that authority boundary rather than assuming a CodeLens +repository row establishes GitHub permission. The audit, scoped fixes and local +validation are complete; Phase 6 cannot be signed off for production release. +Live production configuration cannot be certified from repository files. + +Baseline application findings: 0 Critical, 2 High, 10 Medium, 3 Low and 1 +Informational. Dependency-advisory severities below are separate from these +application findings and do not establish CodeLens exploitability. + +## Remediation and Validation + +- Baseline full backend run: 439 passed, 24 warnings, 13.76 seconds, Python 3.14 + and local PostgreSQL 18. This is an actual run, not the historical claim. +- CI targets Python 3.13/PostgreSQL 16; the local result does not replace CI. +- New focused regressions: 103 passed, 3 warnings, 1.84 seconds. +- Final complete backend suite: 542 passed, 25 warnings, 11.51 seconds. +- Frontend: `npx tsc --noEmit` passed (no typecheck script exists). +- Frontend: `npm run build` passed; all five listed routes prerendered. + The first build failed fetching Google fonts in the restricted network; the + retry with network access passed. No frontend source/lockfile was changed. +- `pip-audit -r requirements.txt --format json`: resolved requirements contain + no known advisories at audit time. Resolution of unpinned requirements is not + a lockfile or proof that every deployed environment uses those versions. +- `npm audit --json --package-lock-only`: exit 1, nine affected package entries, + one Critical and eight High. Next 16.3.4 is flagged for next/og ImageResponse; + that API is not used here. sharp 0.35.4 is flagged for librsvg SVG decoding; + no user-upload/SVG-processing feature was found. Developer/build dependencies + include brace-expansion 1.1.18, braces/micromatch/fast-glob/ESLint dependency + chains and source-map-js 1.2.1. No advisory exploit was run or demonstrated. + Review targeted patch updates separately; no automatic audit fix/downgrade. +- `git diff --check`: passed. Changed-file credential-format detection: no hits. + No .env, migrations, frontend source or dependency manifests changed. +- Test environment: local Windows PostgreSQL 18/Python 3.14, not Compose's + PostgreSQL 16/Python 3.13. Docker was unavailable on PATH. The requested local + codelens_test database was absent on the available local instance and was + created/applied with existing migrations using existing local credentials. + codelens_test is retained. Only the additional audit-created temporary database + codelens_phase6_audit_20261007 was dropped; it held disposable test data and is + not recoverable without rebuilding fixtures. Application data was untouched. +- Warnings include dependency deprecations and existing OAuth AsyncMock + unawaited-coroutine warnings. They are recorded, not claimed resolved. +- Test-output incident: an early pytest assertion expanded Settings and displayed + the local database URL. Values are not repeated or persisted in this report. + Secret settings now use repr=False and configuration error input is hidden; + later runs used restricted tracebacks. Rotate the exposed local DB credential. +- No production code, frontend, migrations, secrets or deployment settings changed + before this initial report was written. + +### Final remediation status + +| Finding | Status after this audit | +| --- | --- | +| F01 | Fixed: verified session identity; public auth IP identity | +| F02 | OPEN High release blocker: GitHub-token authority requires a deliberate access policy or per-user authorization; no architecture redesign performed | +| F03 | Fixed: canonical operation buckets, client-wide 60/min default (health separate), shared connect/metadata alternatives, costly-operation limits | +| F04 | Fixed targeted leaks: health/GH upstream diagnostics, AI provider/service logs and unknown error strings, validation inputs, Settings repr/config error inputs; no universal infrastructure-log certification | +| F05 | Fixed conflicting Google linkage, strict boolean verification/sub types, failure cookie cleanup and neutral IntegrityError rollback/redirect; existing OIDC architecture retained | +| F06 | Fixed required exp/sub, bounded canonical positive DB ID, fresh random jti, corrupt-hash handling and signup/login password bounds | +| F07 | Partial: manual URL/metadata and dot identifiers fixed; consistent ref/path encoding remains a hardening task, no filesystem-write exploit found | +| F08 | Fixed unsafe-method browser Origin check and missing-Origin cross-site Fetch Metadata rejection; non-browser clients without Origin remain compatible | +| F09 | Fixed implicit signing key; explicit 32-character-minimum key required, origin/cookie validation, Compose app/test require AUTH_SECRET_KEY; live values unknown | +| F10 | Fixed Ask quota propagation, preserving existing global neutral 429 response | +| F11 | Partial: backend signup 8–1024, login 1–1024 characters; existing duplicate-signup 409 remains to preserve the current API/UX pending a product decision | +| F12 | Partial: atomic scan claim across scan/ingest/analyze, actual individual-source-size recheck and PR history 1–100 bounds; process-local stores, other history/list growth and upstream full-body reads remain | +| F13 | Fixed tested 429/413 CORS/header paths and bounded pre-parse streaming checks; preflight/framework-generated catastrophic 500 header coverage is not certified | +| F14 | Mostly OPEN Low: root image, incomplete env ignore coverage, dependency/action locks and CI permissions; Compose signing-key fallback removed | +| F15 | Partial: PR content URLs restricted to HTTPS api.github.com/repos; urllib redirect policy and lifetime JWKS cache remain | +| F16 | Documented architecture/deployment constraints; logout revocation and multi-replica/shared state not redesigned | + +### Regression coverage and compatibility + +New tests cover forged/valid/public-auth identities; required/malformed session +claims; fresh sessions; malformed Argon2 hashes; password bounds; OAuth account +collision/failure cookies/truthy verification; neutral DB/GH/AI errors and logs; +CSRF trusted/untrusted origins; early CORS/security headers; ASGI streaming +overflow; manual URL/metadata and remote traversal; unexpected PR content URLs; +scan concurrency/entrypoint overlap; bounded PR history; configuration secrecy; +global/alternate/forwarded-header/expensive-operation budgets. The actual-DB HTTP +matrix exercises 19 cross-user operations, 19 unauthenticated operations and five +mixed repository/finding operations. Foreign source/finding markers never appear +in their responses. No real GitHub mutation or Google login was attempted. + +Existing tests that expected raw provider/scan error strings were updated to +expect neutral messages; concurrency mocks now target the atomic claim operation. +Existing response structures, routes, JWT/cookie/OAuth architecture and ownership +schema remain. Deliberate security behavior changes: weak signup passwords, +untrusted browser origins, inconsistent manual metadata, overlapping processing, +invalid PR history limits and unsafe startup settings are rejected. Authenticated +CLI clients without browser Origin headers still work. A stricter aggregate rate +budget may require frontend polling/backoff tuning under sustained use; health +probes keep independent budgets. Operators must explicitly supply AUTH_SECRET_KEY, +use an exact FRONTEND_URL origin, secure cookies for non-local deployments and +secure cookies for SameSite=None. No live or .env values were changed by the audit. + +Sharp advisory source: [maintainer librsvg advisory](https://github.com/lovell/sharp/security/advisories/GHSA-wq5f-xc86-pv6w). + +### Git handoff and exact files changed + +All changes below are uncommitted in `.audit-worktree`, branch +`security/final-security-audit`, still based on f57dcd8 matching origin/main. +The parent checkout remains on stale main with its pre-existing config edit and +context file preserved. Do not stage the nested worktree from the parent main; +review with `git -C .audit-worktree diff` and `git -C .audit-worktree status`. +No commit, push, PR, migration creation, merge or deployment was performed. +Review and then commit the tested scoped fixes on the audit branch; request PR +creation explicitly. Resolve F02 before any public multi-user production release. + +```text +SECURITY_AUDIT_PHASE6.md +apps/api/app/api/deps.py +apps/api/app/api/routes/ask.py +apps/api/app/api/routes/auth.py +apps/api/app/api/routes/pr_reviews.py +apps/api/app/api/routes/repositories.py +apps/api/app/core/ai_errors.py +apps/api/app/core/config.py +apps/api/app/core/middleware.py +apps/api/app/core/rate_limit.py +apps/api/app/core/security.py +apps/api/app/main.py +apps/api/app/schemas/user.py +apps/api/app/services/ai_pr_fixer.py +apps/api/app/services/ai_pr_reviewer.py +apps/api/app/services/ai_provider.py +apps/api/app/services/branch_fixer.py +apps/api/app/services/explainer.py +apps/api/app/services/fixer.py +apps/api/app/services/github.py +apps/api/app/services/ingestion.py +apps/api/app/services/pr_commenter.py +apps/api/app/services/pr_reviewer.py +apps/api/app/services/scan_progress.py +apps/api/app/services/test_generator.py +apps/api/tests/test_ai_error_handling.py +apps/api/tests/test_ai_pr_fixer.py +apps/api/tests/test_ai_pr_reviewer.py +apps/api/tests/test_ask.py +apps/api/tests/test_phase6_security.py +apps/api/tests/test_rate_limiting.py +apps/api/tests/test_resource_limits.py +apps/api/tests/test_scan_progress.py +docker-compose.yml +``` diff --git a/apps/api/app/api/deps.py b/apps/api/app/api/deps.py index 8199d6c..af2d717 100644 --- a/apps/api/app/api/deps.py +++ b/apps/api/app/api/deps.py @@ -6,6 +6,7 @@ from app.core.config import settings from app.db.database import get_db from app.models.user import User +from app.core.security import decode_session_user_id def get_token_from_cookie(request: Request) -> str | None: return request.cookies.get(settings.auth_cookie_name) @@ -22,17 +23,8 @@ def get_current_user( ) try: - payload = jwt.decode( - token, settings.auth_secret_key, algorithms=["HS256"] - ) - user_id_str: str = payload.get("sub") - if user_id_str is None: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid authentication credentials", - ) - user_id = int(user_id_str) - except (jwt.InvalidTokenError, ValueError): + user_id = decode_session_user_id(token) + except (jwt.InvalidTokenError, ValueError, TypeError): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", diff --git a/apps/api/app/api/routes/ask.py b/apps/api/app/api/routes/ask.py index c3091ac..27429ff 100644 --- a/apps/api/app/api/routes/ask.py +++ b/apps/api/app/api/routes/ask.py @@ -133,9 +133,11 @@ def ask_repository( response.answer = "I couldn't find enough relevant code in this repository to answer that confidently." return response - except (AIUnavailableError, AIQuotaExceededError) as e: - logger.error(f"AI error in ask: {e}") + except AIQuotaExceededError: + raise + except AIUnavailableError as e: + logger.error("AI service unavailable during Ask") raise HTTPException(status_code=503, detail=sanitize_ai_error(e)) except Exception as e: - logger.error(f"Unexpected error in ask: {e}") + logger.error("Unexpected generation failure during Ask") raise HTTPException(status_code=500, detail="An internal error occurred during generation.") diff --git a/apps/api/app/api/routes/auth.py b/apps/api/app/api/routes/auth.py index e1a404b..a29d6c1 100644 --- a/apps/api/app/api/routes/auth.py +++ b/apps/api/app/api/routes/auth.py @@ -2,6 +2,7 @@ from fastapi.responses import RedirectResponse from sqlalchemy.orm import Session from sqlalchemy import select +from sqlalchemy.exc import IntegrityError from pydantic import ValidationError from app.api.deps import get_current_user @@ -220,17 +221,21 @@ async def google_callback( # --- 4. Extract and validate required claims --- google_sub: str | None = claims.get("sub") email: str | None = claims.get("email") - email_verified: bool = bool(claims.get("email_verified", False)) + email_verified: bool = claims.get("email_verified") is True name: str | None = claims.get("name") - if not google_sub: + if not isinstance(google_sub, str) or not google_sub or len(google_sub) > 255: return _fail_redirect(reason="missing_sub") - if not email or not email_verified: + if not isinstance(email, str) or not email or not email_verified: return _fail_redirect(reason="unverified_email") # --- 5. User resolution (Cases A/B/C/D) --- - user = _resolve_user(db, google_sub=google_sub, email=email, name=name) + try: + user = _resolve_user(db, google_sub=google_sub, email=email, name=name) + except IntegrityError: + db.rollback() + return _fail_redirect(reason="identity_conflict") if user is None: # Conflict: google_sub belongs to one user, email to another — refuse silently return _fail_redirect(reason="identity_conflict") @@ -277,6 +282,8 @@ def _resolve_user( if user_by_email is not None: # CASE B: existing CodeLens account — link Google identity. + if user_by_email.google_sub is not None: + return None # Never replace an already linked different identity. user_by_email.google_sub = google_sub if not user_by_email.name and name: user_by_email.name = name @@ -302,10 +309,12 @@ def _fail_redirect(reason: str) -> RedirectResponse: Redirect to the frontend login page with a provider-neutral error code. Never exposes tokens, secrets, or internal details. """ - return RedirectResponse( + response = RedirectResponse( url=f"{settings.frontend_url}/login?error={reason}", status_code=status.HTTP_302_FOUND, ) + _clear_oauth_state_cookies(response) + return response def _constant_time_compare(val1: str, val2: str) -> bool: diff --git a/apps/api/app/api/routes/pr_reviews.py b/apps/api/app/api/routes/pr_reviews.py index e28a373..da92151 100644 --- a/apps/api/app/api/routes/pr_reviews.py +++ b/apps/api/app/api/routes/pr_reviews.py @@ -1,4 +1,4 @@ -from fastapi import APIRouter, Depends, HTTPException, status +from fastapi import APIRouter, Depends, HTTPException, Query, status from sqlalchemy import select from sqlalchemy.orm import Session @@ -16,7 +16,7 @@ def get_pr_review_history( db: Session = Depends(get_db), current_user: User = Depends(get_current_user), - limit: int = 50, + limit: int = Query(default=50, ge=1, le=100), ): """Get the current user's PR review history.""" reviews = ( diff --git a/apps/api/app/api/routes/repositories.py b/apps/api/app/api/routes/repositories.py index 3252088..82c5d98 100644 --- a/apps/api/app/api/routes/repositories.py +++ b/apps/api/app/api/routes/repositories.py @@ -40,7 +40,7 @@ from app.services.analyzer import analyze_repository from app.services.scan_progress import ( get_scan_progress, - is_scan_active, + claim_scan, set_scan_progress, update_scan_progress, ) @@ -230,26 +230,19 @@ def create_repository( db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): - # If explicit details are missing, attempt to parse them from the provided URL - if not (repository_in.name and repository_in.owner and repository_in.full_name): - try: - parsed = parse_github_url(repository_in.url) - name = repository_in.name or parsed.name - owner = repository_in.owner or parsed.owner - full_name = repository_in.full_name or parsed.full_name - canonical_url = parsed.url - github_id = repository_in.github_id or full_name - except ValueError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=str(e), - ) - else: - name = repository_in.name - owner = repository_in.owner - full_name = repository_in.full_name - canonical_url = repository_in.url - github_id = repository_in.github_id or full_name + # Explicit metadata must not bypass the URL trust boundary. + try: + parsed = parse_github_url(repository_in.url) + for supplied, expected in ((repository_in.name, parsed.name), + (repository_in.owner, parsed.owner), + (repository_in.full_name, parsed.full_name)): + if supplied is not None and supplied != expected: + raise ValueError("Repository metadata must match the GitHub URL") + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + name, owner, full_name = parsed.name, parsed.owner, parsed.full_name + canonical_url = parsed.url + github_id = repository_in.github_id or full_name existing = db.execute( select(Repository).where( @@ -404,7 +397,7 @@ def analyze_cb(processed: int, total: int, msg: str) -> None: ) except Exception as exc: - clean_error = sanitize_ai_error(exc) if hasattr(exc, "__str__") else "Scan failed unexpectedly" + clean_error = "Scan failed. Please try again later." set_scan_progress( repository_id=repository_id, status="failed", @@ -454,20 +447,9 @@ def start_repository_scan( detail=f"Repository with id {repository_id} not found", ) - if is_scan_active(repository_id): - # Scan is already running: return existing status without starting duplicate - return get_scan_progress(repository_id) - - # Initialize queued state - initial_state = set_scan_progress( - repository_id=repository_id, - status="queued", - stage="preparing", - progress=0, - files_processed=0, - files_total=0, - message="Scan queued...", - ) + claimed, initial_state = claim_scan(repository_id) + if not claimed: + return initial_state background_tasks.add_task(run_background_scan, repository_id) return initial_state @@ -491,6 +473,8 @@ def ingest_repository_endpoint( detail=f"Repository with id {repository_id} not found", ) + if not claim_scan(repository_id)[0]: + raise HTTPException(status_code=409, detail="A repository scan is already active") set_scan_progress( repository_id=repository_id, status="running", @@ -627,6 +611,8 @@ def analyze_repository_endpoint( detail=f"Repository with id {repository_id} not found", ) + if not claim_scan(repository_id)[0]: + raise HTTPException(status_code=409, detail="A repository scan is already active") set_scan_progress( repository_id=repository_id, status="running", diff --git a/apps/api/app/core/ai_errors.py b/apps/api/app/core/ai_errors.py index 6f3f710..43c08c1 100644 --- a/apps/api/app/core/ai_errors.py +++ b/apps/api/app/core/ai_errors.py @@ -140,12 +140,13 @@ def is_transient_cloud_error(exc: Exception | str) -> bool: def sanitize_ai_error(exc: Exception | str) -> str: """Sanitize any AI provider error to avoid leaking provider details or internal metrics. - If the error message contains provider-specific details (Gemini, Google, Ollama, quotaId, URLs), - returns a friendly generic AI unavailable message. Otherwise preserves clean messages. + Unknown exception strings are never safe merely because a pattern did not + match: they may include credentials or source code. Always return the stable + provider-neutral unavailable message; quota errors have a separate handler. """ raw = str(exc).strip() for pattern in _PROVIDER_PATTERNS: if pattern.search(raw): return AI_UNAVAILABLE_MESSAGE - return raw or AI_UNAVAILABLE_MESSAGE + return AI_UNAVAILABLE_MESSAGE diff --git a/apps/api/app/core/config.py b/apps/api/app/core/config.py index 4979b2f..1728dbb 100644 --- a/apps/api/app/core/config.py +++ b/apps/api/app/core/config.py @@ -1,4 +1,6 @@ from pathlib import Path +from urllib.parse import urlparse +from pydantic import Field, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict @@ -8,16 +10,16 @@ class Settings(BaseSettings): - database_url: str - gemini_api_key: str | None = None + database_url: str = Field(repr=False) + gemini_api_key: str | None = Field(default=None, repr=False) gemini_model: str = "gemini-3.6-flash" - github_token: str | None = None + github_token: str | None = Field(default=None, repr=False) ai_provider_mode: str = "hybrid" # hybrid | cloud_only | ollama_only ollama_base_url: str = "http://localhost:11434" ollama_model: str = "qwen2.5-coder:7b" ollama_timeout: int = 60 - auth_secret_key: str = "dev_secret_key_change_in_production" + auth_secret_key: str = Field(min_length=32, repr=False) auth_cookie_name: str = "codelens_session" auth_cookie_secure: bool = False auth_cookie_samesite: str = "lax" @@ -26,7 +28,7 @@ class Settings(BaseSettings): # Google OAuth 2.0 / OpenID Connect # Set these via environment variables: GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URI google_client_id: str | None = None - google_client_secret: str | None = None + google_client_secret: str | None = Field(default=None, repr=False) google_redirect_uri: str | None = None # Frontend origin – used for post-OAuth redirects. @@ -36,8 +38,25 @@ class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=str(_ENV_FILE), extra="ignore", + hide_input_in_errors=True, ) + @model_validator(mode="after") + def validate_browser_security(self): + origin = urlparse(self.frontend_url) + if (origin.scheme not in ("http", "https") or not origin.hostname + or origin.username or origin.password or origin.query or origin.fragment + or origin.path or "*" in self.frontend_url): + raise ValueError("FRONTEND_URL must be an exact HTTP(S) origin without a path") + if self.auth_cookie_samesite not in ("lax", "strict", "none"): + raise ValueError("AUTH_COOKIE_SAMESITE must be lax, strict or none") + if self.auth_cookie_samesite == "none" and not self.auth_cookie_secure: + raise ValueError("SameSite=None requires AUTH_COOKIE_SECURE") + if origin.hostname not in ("localhost", "127.0.0.1", "::1"): + if origin.scheme != "https" or not self.auth_cookie_secure: + raise ValueError("Non-local browser deployments require HTTPS and secure cookies") + return self + @property def google_oauth_configured(self) -> bool: """True only when all three Google OAuth values are present.""" @@ -48,4 +67,4 @@ def google_oauth_configured(self) -> bool: ) -settings = Settings() \ No newline at end of file +settings = Settings() diff --git a/apps/api/app/core/middleware.py b/apps/api/app/core/middleware.py index 66e07ce..741045a 100644 --- a/apps/api/app/core/middleware.py +++ b/apps/api/app/core/middleware.py @@ -1,6 +1,8 @@ import typing +from starlette.responses import JSONResponse from starlette.types import ASGIApp, Receive, Scope, Send, Message +from app.core.config import settings MAX_REQUEST_BODY_BYTES = 1_000_000 # 1 MB @@ -21,31 +23,6 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: await self.app(scope, receive, send) return - # 1. Check Content-Length upfront - content_length_header = next( - (v for k, v in scope["headers"] if k.lower() == b"content-length"), None - ) - if content_length_header is not None: - try: - if int(content_length_header) > self.max_body_size: - await self._send_413(send) - return - except ValueError: - pass # Ignore malformed Content-Length and let it fail downstream - - # 2. Track chunked or unspecified body size - total_bytes = 0 - - async def receive_wrapper() -> Message: - nonlocal total_bytes - message = await receive() - if message["type"] == "http.request": - body = message.get("body", b"") - total_bytes += len(body) - if total_bytes > self.max_body_size: - raise RequestBodyTooLargeError("REQUEST_BODY_TOO_LARGE") - return message - is_secure = scope.get("scheme") == "https" path = scope.get("path", "") @@ -69,19 +46,52 @@ async def send_wrapper(message: Message) -> None: await send(message) - try: - await self.app(scope, receive_wrapper, send_wrapper) - except RequestBodyTooLargeError: - await self._send_413(send) + headers = {k.lower(): v for k, v in scope["headers"]} + if scope.get("method") not in ("GET", "HEAD", "OPTIONS"): + origin = headers.get(b"origin") + if ((origin is not None and origin.decode("latin-1") != settings.frontend_url) + or (origin is None and headers.get(b"sec-fetch-site") == b"cross-site")): + await JSONResponse(status_code=403, content={"detail": "Untrusted request origin"})(scope, receive, send_wrapper) + return + + # Reject before parsing: parsers can catch exceptions from receive and + # turn an overflow into 400, or start a response before the body is read. + length = headers.get(b"content-length") + if length is not None: + try: + if int(length) > self.max_body_size: + await self._send_413(send_wrapper) + return + except ValueError: + pass + body = bytearray() + while True: + message = await receive() + if message["type"] == "http.disconnect": + return + chunk = message.get("body", b"") + if len(body) + len(chunk) > self.max_body_size: + await self._send_413(send_wrapper) + return + body.extend(chunk) + if not message.get("more_body", False): + break + delivered = False + + async def receive_wrapper() -> Message: + nonlocal delivered + if not delivered: + delivered = True + return {"type": "http.request", "body": bytes(body), "more_body": False} + return await receive() + + await self.app(scope, receive_wrapper, send_wrapper) async def _send_413(self, send: Send) -> None: response_body = b'{"detail": "Request body too large.", "code": "REQUEST_BODY_TOO_LARGE"}' headers = [ (b"content-type", b"application/json"), (b"content-length", str(len(response_body)).encode("ascii")), - (b"x-content-type-options", b"nosniff"), - (b"x-frame-options", b"DENY"), - (b"referrer-policy", b"strict-origin-when-cross-origin"), ] await send({"type": "http.response.start", "status": 413, "headers": headers}) await send({"type": "http.response.body", "body": response_body}) diff --git a/apps/api/app/core/rate_limit.py b/apps/api/app/core/rate_limit.py index 4db6902..81b5f0d 100644 --- a/apps/api/app/core/rate_limit.py +++ b/apps/api/app/core/rate_limit.py @@ -25,17 +25,17 @@ ---------------------- ``ROUTE_LIMITS`` is a list of ``(HTTP_method, path_glob, limit_string)`` tuples evaluated top-to-bottom. The first matching rule wins. If no rule -matches the global ``DEFAULT_LIMIT`` is used. +matches the global ``DEFAULT_LIMIT`` is used. Specific rules additionally share +that client-wide budget, except health probes with their own limits. Counters +use canonical operation patterns, not individual resource IDs or raw paths. Path globs use ``fnmatch`` syntax. ``*`` matches any characters within a single path segment (or across segments -- fnmatch treats the whole string). Client identification --------------------- -Authenticated requests: the CodeLens JWT session cookie is decoded (without -signature/expiry verification -- the normal auth dependency handles that) to -extract ``sub`` (user ID). This prevents a single user from bypassing limits -by rotating IPs. +Authenticated requests: the session signature, expiry and subject are verified +before identity is used. Public auth flows always use the remote IP. Unauthenticated requests: ``request.client.host`` (remote IP) is used. @@ -75,6 +75,7 @@ from starlette.responses import JSONResponse, Response from app.core.config import settings +from app.core.security import decode_session_user_id logger = logging.getLogger(__name__) @@ -129,9 +130,12 @@ def reset_limiter() -> None: ("POST", "/repositories/github/metadata", "30/minute"), ("GET", "/repositories/github/metadata", "30/minute"), ("POST", "/repositories/github", "10/minute"), + ("POST", "/repositories", "10/minute"), # Scan (expensive background job) ("POST", "/repositories/*/scan", "5/hour"), + ("POST", "/repositories/*/ingest", "5/hour"), + ("POST", "/repositories/*/analyze", "5/hour"), # AI endpoints ("POST", "/repositories/*/ask", "20/hour"), @@ -139,6 +143,10 @@ def reset_limiter() -> None: ("POST", "/repositories/*/findings/*/fix", "10/hour"), ("POST", "/repositories/*/findings/*/test", "10/hour"), ("POST", "/repositories/*/pull-requests/*/ai-review", "5/hour"), + ("POST", "/repositories/*/findings/*/apply-fix", "10/hour"), + ("POST", "/repositories/*/findings/*/create-pr", "10/hour"), + ("POST", "/repositories/*/pull-requests/*/findings/fix", "10/hour"), + ("POST", "/repositories/*/pull-requests/*/comment", "5/hour"), # Health (raised limit so Render probes are never blocked) ("GET", "/health", "120/minute"), @@ -148,12 +156,23 @@ def reset_limiter() -> None: def _match_path(method: str, path: str) -> str: """Return the limit string for the first matching rule, or DEFAULT_LIMIT.""" + return _match_rule(method, path)[1] + + +def _canonical_path(path: str) -> str: + return "/" + "/".join(segment for segment in path.split("/") if segment) + + +def _match_rule(method: str, path: str) -> tuple[str, str]: + path = _canonical_path(path) for rule_method, rule_pattern, limit_str in ROUTE_LIMITS: if rule_method not in ("*", method): continue - if fnmatch.fnmatch(path, rule_pattern): - return limit_str - return DEFAULT_LIMIT + if fnmatch.fnmatchcase(path, rule_pattern): + # Alternate repository-connection routes share one budget. + bucket = "/repositories/connect" if rule_pattern in ("/repositories", "/repositories/github") and method == "POST" else rule_pattern + return bucket, limit_str + return "default", DEFAULT_LIMIT def _get_client_key(request: Request) -> str: @@ -165,17 +184,10 @@ def _get_client_key(request: Request) -> str: Falls back to ``request.client.host`` for unauthenticated requests. """ cookie = request.cookies.get(settings.auth_cookie_name) - if cookie: + if cookie and not _canonical_path(request.url.path).startswith("/auth/"): try: - payload = jwt.decode( - cookie, - options={"verify_signature": False}, - algorithms=["HS256"], - ) - sub = payload.get("sub") - if sub: - return f"user:{sub}" - except Exception: + return f"user:{decode_session_user_id(cookie)}" + except (jwt.InvalidTokenError, ValueError, TypeError): pass # malformed token -- fall back to IP host = (request.client.host if request.client else None) or "unknown" return f"ip:{host}" @@ -189,17 +201,22 @@ class RateLimitMiddleware(BaseHTTPMiddleware): """ async def dispatch(self, request: Request, call_next: Callable) -> Response: - path = request.url.path + path = _canonical_path(request.url.path) method = request.method - limit_str = _match_path(method, path) + bucket, limit_str = _match_rule(method, path) item = parse_limit(limit_str) key = _get_client_key(request) - # Namespace by method+path so limits are independent per endpoint. - namespace = f"rl:{method}:{path}" + # A rule is one operation budget across all resource IDs and methods. + namespace = f"rl:{bucket}" # Access via module global so reset_limiter() is respected. allowed = _state.limiter.hit(item, namespace, key) + if allowed and bucket != "default" and path not in ("/health", "/db/health"): + global_item = parse_limit(DEFAULT_LIMIT) + allowed = _state.limiter.hit(global_item, "rl:default", key) + if not allowed: + item, namespace = global_item, "rl:default" if not allowed: try: diff --git a/apps/api/app/core/security.py b/apps/api/app/core/security.py index 5e9953a..47271a8 100644 --- a/apps/api/app/core/security.py +++ b/apps/api/app/core/security.py @@ -1,8 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Any import jwt +import re +import secrets from argon2 import PasswordHasher -from argon2.exceptions import VerifyMismatchError +from argon2.exceptions import VerificationError, InvalidHashError from app.core.config import settings @@ -11,7 +13,7 @@ def verify_password(plain_password: str, hashed_password: str) -> bool: try: return ph.verify(hashed_password, plain_password) - except VerifyMismatchError: + except (VerificationError, InvalidHashError): return False def get_password_hash(password: str) -> str: @@ -24,6 +26,19 @@ def create_access_token(subject: str | int, expires_delta: timedelta | None = No expire = datetime.now(timezone.utc) + timedelta( minutes=settings.auth_token_expire_minutes ) - to_encode = {"exp": expire, "sub": str(subject)} + to_encode = {"exp": expire, "sub": str(subject), "jti": secrets.token_urlsafe(24)} encoded_jwt = jwt.encode(to_encode, settings.auth_secret_key, algorithm="HS256") return encoded_jwt + + +def decode_session_user_id(token: str) -> int: + """Verify the session before trusting identity, including in middleware.""" + payload = jwt.decode(token, settings.auth_secret_key, algorithms=["HS256"], + options={"require": ["exp", "sub"]}) + sub = payload["sub"] + if not isinstance(sub, str) or not re.fullmatch(r"[1-9][0-9]{0,9}", sub): + raise jwt.InvalidTokenError("Invalid subject") + user_id = int(sub) + if user_id > 2_147_483_647: + raise jwt.InvalidTokenError("Invalid subject") + return user_id diff --git a/apps/api/app/main.py b/apps/api/app/main.py index be08203..6bb9c04 100644 --- a/apps/api/app/main.py +++ b/apps/api/app/main.py @@ -1,6 +1,7 @@ from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from fastapi.middleware.cors import CORSMiddleware +from fastapi.exceptions import RequestValidationError from sqlalchemy import text from app.core.config import settings @@ -33,6 +34,18 @@ def ai_quota_exception_handler(request: Request, exc: AIQuotaExceededError): ) +@app.exception_handler(RequestValidationError) +def validation_exception_handler(request: Request, exc: RequestValidationError): + # Never echo submitted credentials, source code or arbitrary error context. + return JSONResponse(status_code=422, content={"detail": [ + {"loc": error["loc"], "type": error["type"], "msg": "Invalid request value"} + for error in exc.errors() + ]}) + + +# Last registered middleware is outermost. CORS must wrap direct 429/413. +app.add_middleware(RateLimitMiddleware) +app.add_middleware(SecurityAndBodyLimitMiddleware) app.add_middleware( CORSMiddleware, allow_origins=[settings.frontend_url], @@ -41,12 +54,6 @@ def ai_quota_exception_handler(request: Request, exc: AIQuotaExceededError): allow_headers=["*"], ) -# Rate limiting — added after CORS so 429 responses still carry CORS headers -# for browser clients. -app.add_middleware(RateLimitMiddleware) -app.add_middleware(SecurityAndBodyLimitMiddleware) - - app.include_router(auth.router) app.include_router(repositories.router) app.include_router(pr_reviews.router) @@ -74,12 +81,12 @@ def db_health(): "database": "connected", } - except Exception as e: + except Exception: return JSONResponse( status_code=503, content={ "status": "error", "database": "disconnected", - "detail": str(e), + "detail": "Database unavailable", }, ) diff --git a/apps/api/app/schemas/user.py b/apps/api/app/schemas/user.py index 09cc56d..6c8fe8e 100644 --- a/apps/api/app/schemas/user.py +++ b/apps/api/app/schemas/user.py @@ -1,15 +1,15 @@ -from pydantic import BaseModel, EmailStr +from pydantic import BaseModel, EmailStr, Field class UserBase(BaseModel): email: EmailStr name: str | None = None class UserCreate(UserBase): - password: str + password: str = Field(min_length=8, max_length=1024, repr=False) class UserLogin(BaseModel): email: EmailStr - password: str + password: str = Field(min_length=1, max_length=1024, repr=False) class UserResponse(UserBase): id: int diff --git a/apps/api/app/services/ai_pr_fixer.py b/apps/api/app/services/ai_pr_fixer.py index 6927462..1aa7798 100644 --- a/apps/api/app/services/ai_pr_fixer.py +++ b/apps/api/app/services/ai_pr_fixer.py @@ -165,7 +165,7 @@ def generate_pr_finding_fix( except AIQuotaExceededError: raise except Exception as exc: - logger.error(f"AI API call for PR fix generation failed: {exc}") + logger.error("AI API call for PR fix generation failed") if is_ai_quota_error(exc): raise AIQuotaExceededError() from exc raise AIPRFixerError(sanitize_ai_error(exc)) from exc diff --git a/apps/api/app/services/ai_pr_reviewer.py b/apps/api/app/services/ai_pr_reviewer.py index f70cd9e..74d067a 100644 --- a/apps/api/app/services/ai_pr_reviewer.py +++ b/apps/api/app/services/ai_pr_reviewer.py @@ -272,7 +272,7 @@ def generate_ai_pr_review( except AIQuotaExceededError: raise except Exception as exc: - logger.error(f"AI PR review generation failed: {exc}") + logger.error("AI PR review generation failed") if is_ai_quota_error(exc): raise AIQuotaExceededError() from exc raise AIPRReviewerError(sanitize_ai_error(exc)) from exc diff --git a/apps/api/app/services/ai_provider.py b/apps/api/app/services/ai_provider.py index b0ece78..de05379 100644 --- a/apps/api/app/services/ai_provider.py +++ b/apps/api/app/services/ai_provider.py @@ -200,7 +200,7 @@ def generate_ai_response( raw_text = call_ollama(prompt, schema=schema, temperature=temperature) return raw_text, "ollama" except Exception as exc: - logger.error(f"Ollama execution failed: {exc}") + logger.error("Local AI execution failed") raise AIUnavailableError(sanitize_ai_error(exc)) from exc # Mode 2: Hybrid (default) or Cloud-only @@ -212,7 +212,7 @@ def generate_ai_response( return raw_text, "cloud" except Exception as exc: cloud_error = exc - logger.warning(f"Cloud AI call failed: {exc}") + logger.warning("Cloud AI call failed") # If not hybrid, or if error is not transient, do not fall back if mode != "hybrid" or not is_transient_cloud_error(exc): if is_ai_quota_error(exc): @@ -231,7 +231,7 @@ def generate_ai_response( raw_text = call_ollama(prompt, schema=schema, temperature=temperature) return raw_text, "ollama" except Exception as ollama_exc: - logger.error(f"Ollama fallback failed: {ollama_exc}") + logger.error("Local AI fallback failed") # Both failed: return provider-neutral error if cloud_error and is_ai_quota_error(cloud_error): raise AIQuotaExceededError() from cloud_error diff --git a/apps/api/app/services/branch_fixer.py b/apps/api/app/services/branch_fixer.py index 4953a75..5f58a64 100644 --- a/apps/api/app/services/branch_fixer.py +++ b/apps/api/app/services/branch_fixer.py @@ -127,7 +127,7 @@ def _authenticated_github_request( "GitHub API rate limit exceeded. Please try again later." ) from err raise GitHubCredentialsUnavailableError( - f"GitHub permission denied: {err.reason}" + "GitHub permission denied." ) from err if err.code == 404: raise GitHubRepoNotFoundError( @@ -142,14 +142,12 @@ def _authenticated_github_request( raise PullRequestAlreadyExistsError( "A pull request already exists for this branch." ) from err - detail_msg = f"{err.reason} {err_body}".strip() if err_body else str(err.reason) raise GitHubAPIError( - f"GitHub API returned error {err.code}: {err.reason}" - f"GitHub API returned error {err.code}: {detail_msg}" + f"GitHub API returned error {err.code}." ) from err except urllib.error.URLError as err: raise GitHubAPIError( - f"Failed to reach GitHub API: {err.reason}" + "Failed to reach GitHub API." ) from err except TimeoutError as err: raise GitHubAPIError( diff --git a/apps/api/app/services/explainer.py b/apps/api/app/services/explainer.py index c3e8525..6f23376 100644 --- a/apps/api/app/services/explainer.py +++ b/apps/api/app/services/explainer.py @@ -166,7 +166,7 @@ def explain_finding( except AIQuotaExceededError: raise except Exception as exc: - logger.error(f"AI explainer generation failed: {exc}") + logger.error("AI explainer generation failed") if is_ai_quota_error(exc): raise AIQuotaExceededError() from exc raise ExplainerError(sanitize_ai_error(exc)) from exc diff --git a/apps/api/app/services/fixer.py b/apps/api/app/services/fixer.py index 7ae323c..e535270 100644 --- a/apps/api/app/services/fixer.py +++ b/apps/api/app/services/fixer.py @@ -255,7 +255,7 @@ def generate_fix( except AIQuotaExceededError: raise except Exception as exc: - logger.error(f"AI fix generation failed: {exc}") + logger.error("AI fix generation failed") if is_ai_quota_error(exc): raise AIQuotaExceededError() from exc raise FixerError(sanitize_ai_error(exc)) from exc diff --git a/apps/api/app/services/github.py b/apps/api/app/services/github.py index d7db364..af29d6e 100644 --- a/apps/api/app/services/github.py +++ b/apps/api/app/services/github.py @@ -161,11 +161,11 @@ def _github_api_request(url: str, timeout: int = 10) -> dict | list: raise GitHubRateLimitError("GitHub API rate limit exceeded. Please try again later.") from err raise GitHubAPIError("CodeLens does not have permission to access this repository.") from err raise GitHubAPIError( - f"GitHub API returned error {err.code}: {err.reason}" + f"GitHub API returned error {err.code}." ) from err except urllib.error.URLError as err: raise GitHubAPIError( - f"Failed to reach GitHub API: {err.reason}" + "Failed to reach GitHub API." ) from err except TimeoutError as err: raise GitHubAPIError( @@ -199,6 +199,8 @@ def parse_github_url(raw_url: str) -> ParsedGitHubRepo: if ssh_match: owner = ssh_match.group("owner") repo = ssh_match.group("repo") + if owner in (".", "..") or repo in (".", ".."): + raise ValueError("Invalid GitHub repository identifier") full_name = f"{owner}/{repo}" return ParsedGitHubRepo( owner=owner, @@ -231,7 +233,7 @@ def parse_github_url(raw_url: str) -> ParsedGitHubRepo: if repo.endswith(".git"): repo = repo[:-4] - if not repo: + if not repo or owner in (".", "..") or repo in (".", ".."): raise ValueError("Invalid GitHub repository URL: repository name is missing") name_pattern = r"^[a-zA-Z0-9._-]+$" diff --git a/apps/api/app/services/ingestion.py b/apps/api/app/services/ingestion.py index 0d57e02..f08a931 100644 --- a/apps/api/app/services/ingestion.py +++ b/apps/api/app/services/ingestion.py @@ -18,6 +18,7 @@ GitHubFileContent, GitHubServiceError, GitHubTreeEntry, + MAX_FILE_SIZE_BYTES, fetch_file_content, fetch_repo_tree, is_supported_file, @@ -130,6 +131,8 @@ def ingest_repository( try: file_content = fetch_file_content(owner, repo, entry.path) + if len(file_content.content.encode("utf-8")) > MAX_FILE_SIZE_BYTES: + raise RepositorySourceTooLargeError("Source file exceeds the maximum allowed size") # Additional safety check against actual content size if actual_bytes_fetched + len(file_content.content.encode('utf-8')) > MAX_TOTAL_SOURCE_BYTES: diff --git a/apps/api/app/services/pr_commenter.py b/apps/api/app/services/pr_commenter.py index ddb659f..3e98ca9 100644 --- a/apps/api/app/services/pr_commenter.py +++ b/apps/api/app/services/pr_commenter.py @@ -217,14 +217,14 @@ def post_github_pr_comment( "GitHub API rate limit exceeded. Please try again later." ) from err raise GitHubCredentialsUnavailableError( - f"GitHub permission denied: {err.reason}" + "GitHub permission denied." ) from err raise GitHubAPIError( - f"GitHub API returned error {err.code}: {err.reason}" + f"GitHub API returned error {err.code}." ) from err except urllib.error.URLError as err: raise GitHubAPIError( - f"Failed to reach GitHub API: {err.reason}" + "Failed to reach GitHub API." ) from err except TimeoutError as err: raise GitHubAPIError( @@ -288,8 +288,7 @@ def create_pr_review_comment( ai_review_succeeded = True except Exception as exc: logger.warning( - "Gemini AI PR review generation failed, falling back to static analysis findings: %s", - exc, + "AI PR review generation failed, falling back to static analysis findings", ) if not ai_review_succeeded: diff --git a/apps/api/app/services/pr_reviewer.py b/apps/api/app/services/pr_reviewer.py index 0b7015d..f0a3404 100644 --- a/apps/api/app/services/pr_reviewer.py +++ b/apps/api/app/services/pr_reviewer.py @@ -14,6 +14,7 @@ import re import urllib.error import urllib.request +from urllib.parse import urlparse from dataclasses import dataclass, field from app.services.analyzer import analyze_source_file, ANALYZABLE_EXTENSIONS, get_file_extension @@ -80,6 +81,10 @@ def _github_api_request(url: str, timeout: int = 15) -> dict | list: Reuses the same User-Agent and Accept headers as the existing GitHub service, and maps HTTP errors to the same exception hierarchy. """ + parsed = urlparse(url) + if (parsed.scheme != "https" or parsed.netloc != "api.github.com" + or not parsed.path.startswith("/repos/") or parsed.fragment): + raise GitHubAPIError("Unexpected GitHub content URL") req = urllib.request.Request( url, headers={ @@ -101,11 +106,11 @@ def _github_api_request(url: str, timeout: int = 15) -> dict | list: "GitHub API rate limit exceeded. Please try again later." ) from err raise GitHubAPIError( - f"GitHub API returned error {err.code}: {err.reason}" + f"GitHub API returned error {err.code}." ) from err except urllib.error.URLError as err: raise GitHubAPIError( - f"Failed to reach GitHub API: {err.reason}" + "Failed to reach GitHub API." ) from err except TimeoutError as err: raise GitHubAPIError( diff --git a/apps/api/app/services/scan_progress.py b/apps/api/app/services/scan_progress.py index 3c6b6d8..bf4dc0b 100644 --- a/apps/api/app/services/scan_progress.py +++ b/apps/api/app/services/scan_progress.py @@ -98,3 +98,15 @@ def clear_scan_progress(repository_id: int | None = None) -> None: else: _scan_store.clear() + +def claim_scan(repository_id: int) -> tuple[bool, dict[str, Any]]: + """Check and claim a scan in one critical section, across all entrypoints.""" + with _lock: + current = _scan_store.get(repository_id) + if current and current.get("status") in ("queued", "running"): + return False, dict(current) + current = _default_idle_state(repository_id) + current.update(status="queued", stage="preparing", message="Scan queued...") + _scan_store[repository_id] = current + return True, dict(current) + diff --git a/apps/api/app/services/test_generator.py b/apps/api/app/services/test_generator.py index 9413a46..c9f4ecc 100644 --- a/apps/api/app/services/test_generator.py +++ b/apps/api/app/services/test_generator.py @@ -136,7 +136,7 @@ def generate_test( except AIQuotaExceededError: raise except Exception as exc: - logger.error(f"AI test generation failed: {exc}") + logger.error("AI test generation failed") if is_ai_quota_error(exc): raise AIQuotaExceededError() from exc raise TestGeneratorError(sanitize_ai_error(exc)) from exc diff --git a/apps/api/tests/test_ai_error_handling.py b/apps/api/tests/test_ai_error_handling.py index d26cb9a..6848ceb 100644 --- a/apps/api/tests/test_ai_error_handling.py +++ b/apps/api/tests/test_ai_error_handling.py @@ -16,6 +16,7 @@ from app.core.ai_errors import ( AI_QUOTA_CODE, AI_QUOTA_MESSAGE, + AI_UNAVAILABLE_MESSAGE, AIQuotaExceededError, is_ai_quota_error, sanitize_ai_error, @@ -59,9 +60,9 @@ def test_sanitize_ai_error_removes_provider_terms(self): self.assertNotIn("googleapis", sanitized.lower()) self.assertNotIn("api_key", sanitized.lower()) - def test_sanitize_ai_error_preserves_safe_messages(self): + def test_sanitize_ai_error_does_not_trust_unknown_messages(self): safe_msg = "Model timeout during AST parse" - self.assertEqual(sanitize_ai_error(safe_msg), safe_msg) + self.assertEqual(sanitize_ai_error(safe_msg), AI_UNAVAILABLE_MESSAGE) class TestAIErrorEndpoints(unittest.TestCase): diff --git a/apps/api/tests/test_ai_pr_fixer.py b/apps/api/tests/test_ai_pr_fixer.py index 92d800a..c04bcce 100644 --- a/apps/api/tests/test_ai_pr_fixer.py +++ b/apps/api/tests/test_ai_pr_fixer.py @@ -548,7 +548,7 @@ def test_gemini_service_error_returns_502(self): ) self.assertEqual(response.status_code, 502) - self.assertIn("Model timeout", response.json()["detail"]) + self.assertIn("AI service is temporarily unavailable", response.json()["detail"]) def test_github_rate_limit_returns_429(self): """Returns 429 when GitHub rate limit is exceeded.""" diff --git a/apps/api/tests/test_ai_pr_reviewer.py b/apps/api/tests/test_ai_pr_reviewer.py index 3ac909a..fd3dd80 100644 --- a/apps/api/tests/test_ai_pr_reviewer.py +++ b/apps/api/tests/test_ai_pr_reviewer.py @@ -564,7 +564,7 @@ def test_gemini_failure_returns_502(self, mock_review, mock_ai_review): response = self.client.post(f"/repositories/{repo.id}/pull-requests/1/ai-review") self.assertEqual(response.status_code, 502) data = response.json() - self.assertIn("Service connection failed", data["detail"]) + self.assertIn("AI service is temporarily unavailable", data["detail"]) @patch("app.api.routes.repositories.generate_ai_pr_review") @patch("app.api.routes.repositories.review_pull_request") diff --git a/apps/api/tests/test_ask.py b/apps/api/tests/test_ask.py index 01c299d..8d63419 100644 --- a/apps/api/tests/test_ask.py +++ b/apps/api/tests/test_ask.py @@ -204,7 +204,7 @@ def test_ai_failure(self, mock_generate): json={"question": "login"} ) self.assertEqual(response.status_code, 503) - self.assertIn("Model offline", response.json()["detail"]) + self.assertIn("AI service is temporarily unavailable", response.json()["detail"]) if __name__ == "__main__": unittest.main() diff --git a/apps/api/tests/test_phase6_security.py b/apps/api/tests/test_phase6_security.py new file mode 100644 index 0000000..f379539 --- /dev/null +++ b/apps/api/tests/test_phase6_security.py @@ -0,0 +1,453 @@ +"""Regression reproductions for the Phase 6 audit; no real external services.""" +import asyncio +import time +from types import SimpleNamespace +from unittest.mock import Mock, patch + +import jwt +import pytest +from fastapi.testclient import TestClient +from pydantic import ValidationError +from starlette.requests import Request + +from app.api.deps import get_current_user +from app.api.routes.auth import _resolve_user +from app.core.ai_errors import AIQuotaExceededError, AI_UNAVAILABLE_MESSAGE, sanitize_ai_error +from app.core.config import settings +from app.core.middleware import SecurityAndBodyLimitMiddleware +from app.core.rate_limit import _get_client_key, reset_limiter +from app.core.security import create_access_token, verify_password +from app.db.database import get_db +from app.main import app +from app.schemas.user import UserCreate, UserLogin + + +@pytest.fixture +def client(): + with TestClient(app) as value: + yield value + app.dependency_overrides.clear() + + +def request_with_cookie(token, path="/repositories/1"): + return Request({"type": "http", "method": "GET", "path": path, + "headers": [(b"cookie", f"{settings.auth_cookie_name}={token}".encode())], + "client": ("192.0.2.1", 1234)}) + + +def test_forged_cookie_cannot_select_rate_identity(): + token = jwt.encode({"sub": "345", "exp": int(time.time()) + 60}, "synthetic-untrusted-key-for-regression", algorithm="HS256") + assert _get_client_key(request_with_cookie(token)).startswith("ip:") + + +def test_valid_cookie_still_uses_user_identity(): + assert _get_client_key(request_with_cookie(create_access_token(345))) == "user:345" + + +def test_public_auth_budget_cannot_rotate_signed_users(): + req = request_with_cookie(create_access_token(345), "/auth/login") + assert _get_client_key(req).startswith("ip:") + + +def test_resource_ids_and_slashes_share_ai_budget(client): + # These requests are unauthorized, but must consume the same operation budget. + results = [client.post(f"/repositories/{i}/ask" + ("/" if i % 2 else ""), + json={"question": "What is this?"}, follow_redirects=False).status_code + for i in range(1, 22)] + assert results[-1] == 429 + + +@pytest.mark.parametrize("payload", [ + {"sub": "1"}, {"sub": "01", "exp": 4102444800}, + {"sub": "-1", "exp": 4102444800}, {"sub": "0", "exp": 4102444800}, + {"sub": " 1", "exp": 4102444800}, {"sub": [], "exp": 4102444800}, +]) +def test_session_claims_rejected_before_database_access(payload): + token = jwt.encode(payload, settings.auth_secret_key, algorithm="HS256") + db = Mock() + from fastapi import HTTPException + with pytest.raises(HTTPException) as caught: + get_current_user(request_with_cookie(token), db) + assert caught.value.status_code == 401 + db.get.assert_not_called() + + +def test_sessions_are_fresh_even_in_same_second(): + assert create_access_token(1) != create_access_token(1) + + +def test_corrupt_password_hash_fails_closed(): + assert verify_password("synthetic-password", "invalid-hash") is False + + +@pytest.mark.parametrize("length", [0, 7, 1025]) +def test_signup_password_bounds(length): + with pytest.raises(ValidationError): + UserCreate(email="someone@example.com", password="x" * length) + + +def test_login_preserves_existing_short_password_accounts(): + assert UserLogin(email="someone@example.com", password="short").password == "short" + + +def test_linked_google_identity_cannot_be_replaced(): + existing = SimpleNamespace(id=4, google_sub="original-identity", name="Someone") + db = Mock() + db.scalar.side_effect = [None, existing] + assert _resolve_user(db, google_sub="replacement", email="someone@example.com", name=None) is None + assert existing.google_sub == "original-identity" + db.commit.assert_not_called() + + +def test_failed_oauth_clears_transaction_cookies(client): + response = client.get("/auth/google/callback?error=access_denied", follow_redirects=False) + cookies = response.headers.get_list("set-cookie") + assert any("codelens_oauth_state=" in c and "Max-Age=0" in c for c in cookies) + assert any("codelens_oauth_nonce=" in c and "Max-Age=0" in c for c in cookies) + + +def test_database_failure_is_neutral(client): + with patch("app.main.engine.connect", side_effect=RuntimeError("synthetic-private-diagnostic")): + response = client.get("/db/health") + assert response.status_code == 503 + assert "synthetic-private-diagnostic" not in response.text + + +def test_unknown_ai_error_is_neutral(): + assert sanitize_ai_error(RuntimeError("synthetic-private-diagnostic")) == AI_UNAVAILABLE_MESSAGE + + +def test_ask_quota_remains_429_without_raw_logs(client, caplog): + app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(id=1) + app.dependency_overrides[get_db] = lambda: Mock() + with patch("app.api.routes.ask.retrieve_code_context", return_value=[]), patch( + "app.api.routes.ask.generate_structured", side_effect=AIQuotaExceededError() + ): + response = client.post("/repositories/1/ask", json={"question": "Explain"}) + assert response.status_code == 429 + assert response.json()["code"] == "AI_QUOTA_EXCEEDED" + + +def test_cross_site_logout_rejected_before_cookie_mutation(client): + response = client.post("/auth/logout", headers={"Origin": "https://attacker.example", "Sec-Fetch-Site": "cross-site"}) + assert response.status_code == 403 + assert "set-cookie" not in response.headers + + +def test_trusted_frontend_logout_allowed(client): + assert client.post("/auth/logout", headers={"Origin": settings.frontend_url}).status_code == 200 + + +@pytest.mark.parametrize("kind", ["rate", "body"]) +def test_early_responses_have_cors_and_security_headers(client, kind): + headers = {"Origin": settings.frontend_url} + if kind == "rate": + for _ in range(10): + client.post("/auth/login", json={}, headers=headers) + response = client.post("/auth/login", json={}, headers=headers) + assert response.status_code == 429 + else: + response = client.post("/auth/login", content=b"x" * 1_000_001, headers=headers) + assert response.status_code == 413 + assert response.headers.get("access-control-allow-origin") == settings.frontend_url + assert response.headers.get("permissions-policy") + assert response.headers.get("cache-control") == "no-store" + + +def test_streaming_overflow_rejected_before_downstream_parser(): + downstream = Mock() + async def endpoint(scope, receive, send): + downstream() + # A parser may swallow receive errors; the guard must run before it. + try: + await receive() + except Exception: + pass + await send({"type": "http.response.start", "status": 400, "headers": []}) + await send({"type": "http.response.body", "body": b""}) + messages = iter([{"type": "http.request", "body": b"1234", "more_body": True}, + {"type": "http.request", "body": b"5678", "more_body": False}]) + sent = [] + async def receive(): + return next(messages) + async def send(message): + sent.append(message) + asyncio.run(SecurityAndBodyLimitMiddleware(endpoint, max_body_size=5)( + {"type": "http", "method": "POST", "scheme": "https", "path": "/auth/login", "headers": []}, receive, send)) + assert sent[0]["status"] == 413 + downstream.assert_not_called() + + +def test_validation_does_not_echo_password(client): + response = client.post("/auth/signup", json={"email": "someone@example.com", "password": "synthetic-private-password" * 100}) + assert response.status_code == 422 + assert "synthetic-private-password" not in response.text + + +@pytest.mark.parametrize("fields", [ + {"auth_secret_key": None}, {"frontend_url": "*"}, + {"frontend_url": "https://frontend.example/path"}, + {"auth_cookie_samesite": "none", "auth_cookie_secure": False}, +]) +def test_unsafe_security_configuration_rejected(fields, monkeypatch): + from app.core.config import Settings + if fields.get("auth_secret_key", "present") is None: + monkeypatch.delenv("AUTH_SECRET_KEY", raising=False) + fields = {} + with pytest.raises(ValidationError): + Settings(_env_file=None, **fields) + + +@pytest.mark.parametrize("url,owner", [ + ("http://127.0.0.1/private", "o"), ("javascript:alert(1)", "o"), + ("https://github.com/o/r", "../other"), +]) +def test_manual_metadata_cannot_bypass_repository_validation(url, owner): + from fastapi import HTTPException + from app.api.routes.repositories import create_repository + from app.schemas.repository import RepositoryCreate + db = Mock() + with pytest.raises(HTTPException) as caught: + create_repository(RepositoryCreate(url=url, owner=owner, name="r", full_name=f"{owner}/r"), db, SimpleNamespace(id=1)) + assert caught.value.status_code == 400 + db.execute.assert_not_called() + + +@pytest.mark.parametrize("url", ["https://github.com/../r", "git@github.com:o/..", "https://github.com/o/%2e%2e", "https://github.com/o/..\\r"]) +def test_remote_repository_traversal_rejected(url): + from app.services.github import parse_github_url + with pytest.raises(ValueError): + parse_github_url(url) + + +def test_github_upstream_error_cannot_expose_body_or_reason(): + import io + from urllib.error import HTTPError + from app.services.branch_fixer import _authenticated_github_request + from app.services.github import GitHubAPIError + error = HTTPError("https://api.github.com/repos/o/r", 500, "synthetic-private-diagnostic", {}, io.BytesIO(b"synthetic-private-body")) + with patch("urllib.request.urlopen", side_effect=error), pytest.raises(GitHubAPIError) as caught: + _authenticated_github_request("https://api.github.com/repos/o/r") + assert "synthetic-private" not in str(caught.value) + + +@pytest.mark.parametrize("url", ["http://127.0.0.1/private", "https://evil.example/source", "file:///etc/passwd"]) +def test_unexpected_pr_contents_url_rejected_before_network(url): + from app.services.pr_reviewer import _fetch_file_content_from_url + from app.services.github import GitHubServiceError + with patch("urllib.request.urlopen") as network, pytest.raises(GitHubServiceError): + _fetch_file_content_from_url(url) + network.assert_not_called() + + +def test_scan_claim_is_atomic_under_concurrent_starts(): + from concurrent.futures import ThreadPoolExecutor + from fastapi import BackgroundTasks + from app.api.routes.repositories import start_repository_scan + from app.services.scan_progress import clear_scan_progress + clear_scan_progress(987654) + db = Mock() + db.get.return_value = SimpleNamespace(user_id=1) + tasks = [BackgroundTasks() for _ in range(20)] + try: + with ThreadPoolExecutor(max_workers=8) as pool: + list(pool.map(lambda task: start_repository_scan(987654, task, db, SimpleNamespace(id=1)), tasks)) + assert sum(len(task.tasks) for task in tasks) == 1 + finally: + clear_scan_progress(987654) + + +def test_ingestion_rechecks_actual_individual_size(): + from app.services.github import GitHubTreeEntry, GitHubFileContent, MAX_FILE_SIZE_BYTES + from app.services.ingestion import ingest_repository, RepositorySourceTooLargeError + entry = GitHubTreeEntry(path="large.py", sha="x", type="blob", size=1) + content = GitHubFileContent(path="large.py", sha="x", size=1, content="x" * (MAX_FILE_SIZE_BYTES + 1)) + with patch("app.services.ingestion.fetch_repo_tree", return_value=[entry]), patch( + "app.services.ingestion.fetch_file_content", return_value=content + ), pytest.raises(RepositorySourceTooLargeError): + ingest_repository("owner", "repo") + + +def test_ai_provider_logs_do_not_include_raw_exception(caplog): + from app.services.ai_provider import generate_ai_response + with patch.object(settings, "ai_provider_mode", "ollama_only"), patch( + "app.services.ai_provider.call_ollama", side_effect=RuntimeError("synthetic-private-diagnostic") + ), pytest.raises(Exception): + generate_ai_response("Explain code") + assert "synthetic-private-diagnostic" not in caplog.text + + +def test_oauth_truthy_unverified_flag_is_rejected(client): + from unittest.mock import AsyncMock + client.cookies.set("codelens_oauth_state", "transaction") + client.cookies.set("codelens_oauth_nonce", "nonce") + with patch.object(settings, "google_client_id", "synthetic-client"), patch.object( + settings, "google_client_secret", "synthetic-only" + ), patch.object(settings, "google_redirect_uri", "https://backend.example/auth/google/callback"), patch( + "app.api.routes.auth.exchange_code_and_validate", new=AsyncMock(return_value={ + "sub": "identity", "email": "someone@example.com", "email_verified": "false" + }) + ), patch("app.api.routes.auth._resolve_user") as resolve: + response = client.get("/auth/google/callback?code=synthetic&state=transaction", follow_redirects=False) + assert "unverified_email" in response.headers["location"] + resolve.assert_not_called() + + +@pytest.fixture +def tenants(): + import uuid + from app.db.database import SessionLocal + from app.models.user import User + from app.models.repository import Repository + from app.models.finding import Finding + from app.models.source_file import SourceFile + from app.models.pr_review import PRReview + suffix = uuid.uuid4().hex + with SessionLocal() as db: + a = User(email=f"audit-a-{suffix}@example.com", password_hash=None) + b = User(email=f"audit-b-{suffix}@example.com", password_hash=None) + db.add_all([a, b]) + db.flush() + repo = Repository(user_id=b.id, github_id=suffix, owner="owner", name="repo", full_name="owner/repo", url="https://github.com/owner/repo") + own_repo = Repository(user_id=a.id, github_id=suffix, owner="owner", name="repo", full_name="owner/repo", url="https://github.com/owner/repo") + db.add_all([repo, own_repo]) + db.flush() + finding = Finding(repository_id=repo.id, file_path="private.py", line_number=1, severity="info", category="style", message="foreign-private-marker", rule_id="TODO") + source = SourceFile(repository_id=repo.id, path="private.py", sha="x", content="foreign-private-marker", size=22) + review = PRReview(user_id=b.id, repository_id=repo.id, pull_request_number=1, summary="foreign-private-marker", risk_level="low", overall_assessment="private") + db.add_all([finding, source, review]) + db.commit() + values = dict(token=create_access_token(a.id), repo=repo.id, own_repo=own_repo.id, finding=finding.id, review=review.id) + try: + yield values + finally: + db.rollback() + db.delete(repo) + db.delete(own_repo) + db.flush() + db.delete(a) + db.delete(b) + db.commit() + + +PROTECTED_OPERATIONS = [ + ("GET", "/repositories/{repo}", None), + ("GET", "/repositories/{repo}/files", None), + ("GET", "/repositories/{repo}/findings", None), + ("GET", "/repositories/{repo}/scan-status", None), + ("POST", "/repositories/{repo}/scan", None), + ("POST", "/repositories/{repo}/ingest", None), + ("POST", "/repositories/{repo}/analyze", None), + ("POST", "/repositories/{repo}/ask", {"question": "Explain private.py"}), + ("POST", "/repositories/{repo}/findings/{finding}/explain", None), + ("POST", "/repositories/{repo}/findings/{finding}/fix", None), + ("POST", "/repositories/{repo}/findings/{finding}/test", None), + ("POST", "/repositories/{repo}/findings/{finding}/apply-fix", {}), + ("POST", "/repositories/{repo}/findings/{finding}/create-pr", {"branch_name": "fix"}), + ("POST", "/repositories/{repo}/pull-requests/1/review", None), + ("POST", "/repositories/{repo}/pull-requests/1/ai-review", None), + ("POST", "/repositories/{repo}/pull-requests/1/findings/fix", {"file_path": "private.py", "line_number": 1, "issue": "TODO", "severity": "info", "category": "style", "message": "Issue"}), + ("POST", "/repositories/{repo}/pull-requests/1/comment", {}), + ("GET", "/pr-reviews/{review}", None), + ("DELETE", "/repositories/{repo}", None), +] + + +@pytest.mark.parametrize("method,path,payload", PROTECTED_OPERATIONS) +def test_two_user_http_isolation(client, tenants, method, path, payload, monkeypatch): + import app.api.routes.repositories as routes + def forbidden_side_effect(*args, **kwargs): + pytest.fail("Foreign resource reached an external operation") + for name in ("ingest_repository", "analyze_repository", "run_background_scan", "review_pull_request", + "generate_ai_pr_review", "generate_pr_finding_fix", "post_pr_review_comment"): + if hasattr(routes, name): + monkeypatch.setattr(routes, name, forbidden_side_effect) + client.cookies.set(settings.auth_cookie_name, tenants["token"]) + response = client.request(method, path.format(**tenants), json=payload) + assert response.status_code in (403, 404) + assert "foreign-private-marker" not in response.text + + +@pytest.mark.parametrize("method,path,payload", PROTECTED_OPERATIONS) +def test_protected_operations_require_authentication(client, method, path, payload): + response = client.request(method, path.format(repo=1, finding=1, review=1), json=payload) + assert response.status_code == 401 + + +@pytest.mark.parametrize("operation", ["explain", "fix", "test", "apply-fix", "create-pr"]) +def test_finding_cannot_be_mixed_into_owned_repository(client, tenants, operation): + client.cookies.set(settings.auth_cookie_name, tenants["token"]) + payload = {"branch_name": "fix"} if operation == "create-pr" else {} + response = client.post(f"/repositories/{tenants['own_repo']}/findings/{tenants['finding']}/{operation}", json=payload) + assert response.status_code == 404 + + +@pytest.mark.parametrize("endpoint", ["ingest", "analyze"]) +def test_direct_processing_cannot_overlap_active_scan(client, tenants, endpoint): + from app.services.scan_progress import set_scan_progress, clear_scan_progress + client.cookies.set(settings.auth_cookie_name, tenants["token"]) + set_scan_progress(tenants["own_repo"], "running", "fetching_files", 10) + try: + response = client.post(f"/repositories/{tenants['own_repo']}/{endpoint}") + assert response.status_code == 409 + finally: + clear_scan_progress(tenants["own_repo"]) + + +@pytest.mark.parametrize("limit", [-1, 0, 101, 2147483648]) +def test_pr_history_limit_is_bounded(client, limit): + app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(id=1) + db = Mock() + db.query.return_value.join.return_value.filter.return_value.order_by.return_value.limit.return_value.all.return_value = [] + app.dependency_overrides[get_db] = lambda: db + response = client.get(f"/pr-reviews?limit={limit}") + assert response.status_code == 422 + + +def test_compose_requires_explicit_session_secret_for_app_and_tests(): + from pathlib import Path + text = (Path(__file__).resolve().parents[3] / "docker-compose.yml").read_text() + for service in ("api", "test"): + section = text.split(f"\n {service}:\n", 1)[1].split("\n postgres:", 1)[0].split("\n test:", 1)[0] + assert "AUTH_SECRET_KEY=${AUTH_SECRET_KEY:?" in section + + +def test_settings_validation_and_repr_do_not_echo_sensitive_values(): + from app.core.config import Settings + values = dict(database_url="synthetic-private-diagnostic", auth_secret_key="synthetic-private-diagnostic" * 2, + google_client_secret="synthetic-private-diagnostic", github_token="synthetic-private-diagnostic") + assert "synthetic-private-diagnostic" not in repr(Settings(_env_file=None, **values)) + with pytest.raises(ValidationError) as caught: + Settings(_env_file=None, frontend_url="*", **values) + assert "synthetic-private-diagnostic" not in str(caught.value) + assert "input_value" not in str(caught.value) + + +def test_aggregate_budget_spans_different_default_paths(client): + for i in range(60): + assert client.get(f"/unknown-audit-route/{i}").status_code == 404 + assert client.get("/another-unknown-route").status_code == 429 + + +def test_alternate_repository_creation_routes_share_budget(client): + for i in range(10): + path = "/repositories/github" if i % 2 else "/repositories" + assert client.post(path, json={}).status_code != 429 + assert client.post("/repositories", json={}).status_code == 429 + + +def test_forwarded_headers_cannot_rotate_login_budget(client): + for i in range(10): + client.post("/auth/login", json={}, headers={"X-Forwarded-For": f"192.0.2.{i}"}) + assert client.post("/auth/login", json={}, headers={"X-Forwarded-For": "198.51.100.9"}).status_code == 429 + + +@pytest.mark.parametrize("path,budget", [ + ("/repositories/{i}/findings/1/apply-fix", 10), + ("/repositories/{i}/pull-requests/1/findings/fix", 10), + ("/repositories/{i}/pull-requests/1/comment", 5), +]) +def test_expensive_alternate_operations_have_resource_independent_budgets(client, path, budget): + for i in range(budget): + assert client.post(path.format(i=i + 1), json={}).status_code != 429 + assert client.post(path.format(i=999), json={}).status_code == 429 diff --git a/apps/api/tests/test_rate_limiting.py b/apps/api/tests/test_rate_limiting.py index e5e752a..03a823c 100644 --- a/apps/api/tests/test_rate_limiting.py +++ b/apps/api/tests/test_rate_limiting.py @@ -323,7 +323,7 @@ class TestScanRateLimit(RateLimitTestBase): """ def test_above_limit_is_429(self): - with patch("app.api.routes.repositories.is_scan_active", return_value=False), patch("app.api.routes.repositories.run_background_scan"): + with patch("app.api.routes.repositories.run_background_scan"): for _ in range(5): self.client.post("/repositories/99999/scan") resp = self.client.post("/repositories/99999/scan") diff --git a/apps/api/tests/test_resource_limits.py b/apps/api/tests/test_resource_limits.py index 61ef1fc..0a7b93d 100644 --- a/apps/api/tests/test_resource_limits.py +++ b/apps/api/tests/test_resource_limits.py @@ -134,8 +134,7 @@ def test_scan_concurrency_protection(): } with patch("app.api.routes.repositories.Session.get", return_value=MagicMock(user_id=FAKE_USER.id)), \ - patch("app.api.routes.repositories.is_scan_active", return_value=True), \ - patch("app.api.routes.repositories.get_scan_progress", return_value=mock_running_state), \ + patch("app.api.routes.repositories.claim_scan", return_value=(False, mock_running_state)), \ patch("app.api.routes.repositories.BackgroundTasks.add_task") as mock_add_task: response = client.post("/repositories/1/scan") diff --git a/apps/api/tests/test_scan_progress.py b/apps/api/tests/test_scan_progress.py index 7fb5a84..c3583ca 100644 --- a/apps/api/tests/test_scan_progress.py +++ b/apps/api/tests/test_scan_progress.py @@ -286,4 +286,4 @@ def test_run_background_scan_failure_flow(self): self.assertEqual(status["stage"], "failed") self.assertEqual(status["progress"], 0) self.assertNotIn("Traceback", status["message"]) - self.assertIn("rate limit", status["message"].lower()) + self.assertEqual("Scan failed. Please try again later.", status["message"]) diff --git a/docker-compose.yml b/docker-compose.yml index 10a8f0b..9f4f5d2 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -32,7 +32,7 @@ services: - AI_PROVIDER_MODE=${AI_PROVIDER_MODE:-hybrid} - OLLAMA_BASE_URL=${OLLAMA_BASE_URL:-http://localhost:11434} - OLLAMA_MODEL=${OLLAMA_MODEL:-qwen2.5-coder:7b} - - AUTH_SECRET_KEY=${AUTH_SECRET_KEY:-local_dev_secret_key_change_me} + - AUTH_SECRET_KEY=${AUTH_SECRET_KEY:?Set an explicit signing key of at least 32 characters} - AUTH_COOKIE_SECURE=false - GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID:-} - GOOGLE_CLIENT_SECRET=${GOOGLE_CLIENT_SECRET:-} @@ -49,6 +49,7 @@ services: condition: service_healthy environment: - DATABASE_URL=postgresql://codelens:codelens_dev_password@postgres:5432/codelens_test + - AUTH_SECRET_KEY=${AUTH_SECRET_KEY:?Set an explicit signing key of at least 32 characters} volumes: - ./apps/api:/app command: sh -c "pip install --no-cache-dir -r requirements-dev.txt && pytest -q"