Skip to content

fix(github-app): map internal exceptions to stable client errors and escape OAuth HTML (#13912) - #13912

Merged
kodjima33 merged 1 commit into
BasedHardware:mainfrom
TheRWX:fix/github-app-error-handling-and-coercion
Sep 21, 2026
Merged

kodjima33 merged 1 commit into
BasedHardware:mainfrom
TheRWX:fix/github-app-error-handling-and-coercion

Conversation

@TheRWX

@TheRWX TheRWX commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Remediates unauthenticated HTML and exception sinks in plugins/omi-github-app/main.py and plugins/omi-github-app/github_client.py as requested in maintainer review (@aryanorastar):

  1. Chat-Tool Routes: Internal exceptions across all chat-tool endpoints (tool_create_issue, tool_list_repos, tool_list_issues, tool_get_issue, tool_list_labels, tool_add_comment, tool_code_feature) now map unhandled exceptions to stable client errors ("Failed to ... due to an internal error."), preventing raw str(e) leakages while preserving server-side traceback logging.
  2. OAuth Initialization: auth_start maps unhandled exceptions to HTTPException(status_code=500, detail="OAuth initialization failed") without leaking str(e).
  3. OAuth Callback Page: The error HTML page replaces str(e) interpolation with stable client error text ("Failed to complete authentication. Please try again."), URL-encodes uid in retry links (quote(..., safe="")), and HTML-escapes reflected usernames.
  4. JSON Error Endpoints: update-repo, refresh-repos, check-repo-access, save-agent-provider, save-agent-key, delete-agent-key, and test-agent return stable error responses on unexpected failures.
  5. Root Endpoint: Sanitizes uid reflections across both unauthenticated and authenticated views and client-side fetch() scripts.
  6. GitHub Client: Maps unexpected exceptions in create_issue and add_issue_comment to stable error dictionaries.

Verification

  • python3 plugins/omi-github-app/test_main.py: 93 tests passing (20 new tests asserting stable error mapping, HTML escaping, and exception isolation).
  • python3 plugins/omi-github-app/test_github_client.py: 12 tests passing (asserting stable error returns on exceptions).
  • python3 plugins/omi-github-app/test_github_tools_auth.py: 11 tests passing.
  • bash scripts/pr-preflight --lane ci --base upstream/main: All 17 manifest checks passed cleanly in 165.46s on commit 59d0c98a45.

Product invariants affected

none

Fixes #13911

Failure-Class: none

PayPal: [email protected]

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 5 files

Confidence score: 2/5

  • .github/checks-manifest.yaml introduces a check that will fail in the canonical CI environment before assertions run because requests and dotenv are unavailable; stub those dependencies as in test_github_client.py or provision the required plugin dependency.
  • plugins/omi-github-app/github_client.py can send an unsupported state as open while labeling the response with the invalid original value, causing misleading results; reject invalid states or propagate the canonical state.
  • plugins/omi-github-app/test_github_client.py uses a FakeResponse that always returns five items regardless of per_page, so its headroom assertions cannot catch a regression; make the mock response depend on the requested page size.

You’re at about 95% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name=".github/checks-manifest.yaml">

<violation number="1" location=".github/checks-manifest.yaml:1000">
P1: This new check will fail in the canonical CI environment before running any assertions. Stub `requests` and `dotenv` in `test_issue_tools.py` like `test_github_client.py`, or otherwise provision the plugin requirements before invoking this manifest check.</violation>
</file>

<file name="plugins/omi-github-app/test_github_client.py">

<violation number="1" location="plugins/omi-github-app/test_github_client.py:206">
P2: This test cannot detect a regression in the headroom fix it claims to verify. The mock FakeResponse returns the fixed 5-item page regardless of the per_page request param, so the behavioral assertions (success=True, issues==[102,104]) pass identically whether list_issues requests 2 or 30 items per page; only the direct params assertion guards the headroom. It also never exercises the failure mode the PR targets: a page with more PRs than the limit, or a repo with more items than one page. list_issues makes a single non-paginated request capped at min(max(per_page*2,30),100), so when PRs dominate a page or items exceed one page it returns fewer than `per_page` issues while still reporting success=True — the same misleading short/empty result the PR aims to eliminate. Add a test where the mock honors per_page and the first fetched items are all PRs (more PRs than the limit), asserting the requested number of issues is still returned, plus a case with more items than fit in one page to document the single-page cap.</violation>
</file>

<file name="plugins/omi-github-app/github_client.py">

<violation number="1" location="plugins/omi-github-app/github_client.py:241">
P2: When an unsupported `state` reaches the endpoint, this request uses `open` but the tool labels the response with the original value. Reject invalid states or propagate the canonical state so results are not mislabeled.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread .github/checks-manifest.yaml Outdated
lanes: ["local", "ci"]
reason: "#13545: repository labels silently truncated at 100 because fetchers never followed next links; the suite asserts pagination and fail-closed item handling and must run in CI to catch a regression"
- id: github-app-issue-tools-tests
command: ["python3", "plugins/omi-github-app/test_issue_tools.py"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: This new check will fail in the canonical CI environment before running any assertions. Stub requests and dotenv in test_issue_tools.py like test_github_client.py, or otherwise provision the plugin requirements before invoking this manifest check.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At .github/checks-manifest.yaml, line 1000:

<comment>This new check will fail in the canonical CI environment before running any assertions. Stub `requests` and `dotenv` in `test_issue_tools.py` like `test_github_client.py`, or otherwise provision the plugin requirements before invoking this manifest check.</comment>

<file context>
@@ -996,6 +996,11 @@ checks:
     lanes: ["local", "ci"]
     reason: "#13545: repository labels silently truncated at 100 because fetchers never followed next links; the suite asserts pagination and fail-closed item handling and must run in CI to catch a regression"
+  - id: github-app-issue-tools-tests
+    command: ["python3", "plugins/omi-github-app/test_issue_tools.py"]
+    triggers: ["plugins/omi-github-app/**", ".github/checks-manifest.yaml"]
+    lanes: ["local", "ci"]
</file context>

Comment thread plugins/omi-github-app/github_client.py Resolved
Comment thread plugins/omi-github-app/github_client.py Outdated
Returns dict with success status and list of issue dicts or error message.
"""
try:
valid_state = state if state in ("open", "closed", "all") else "open"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When an unsupported state reaches the endpoint, this request uses open but the tool labels the response with the original value. Reject invalid states or propagate the canonical state so results are not mislabeled.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At plugins/omi-github-app/github_client.py, line 241:

<comment>When an unsupported `state` reaches the endpoint, this request uses `open` but the tool labels the response with the original value. Reject invalid states or propagate the canonical state so results are not mislabeled.</comment>

<file context>
@@ -218,29 +232,31 @@ def list_issues(
+        Returns dict with success status and list of issue dicts or error message.
         """
         try:
+            valid_state = state if state in ("open", "closed", "all") else "open"
+            fetch_count = min(max(per_page * 2, 30), 100)
             response = requests.get(
</file context>

self.assertEqual(len(result["issues"]), 2)
self.assertEqual([i["number"] for i in result["issues"]], [102, 104])
# Verify requested fetch count gives headroom to filter PRs
self.assertEqual(get.call_args.kwargs["params"]["per_page"], 30)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This test cannot detect a regression in the headroom fix it claims to verify. The mock FakeResponse returns the fixed 5-item page regardless of the per_page request param, so the behavioral assertions (success=True, issues==[102,104]) pass identically whether list_issues requests 2 or 30 items per page; only the direct params assertion guards the headroom. It also never exercises the failure mode the PR targets: a page with more PRs than the limit, or a repo with more items than one page. list_issues makes a single non-paginated request capped at min(max(per_page*2,30),100), so when PRs dominate a page or items exceed one page it returns fewer than per_page issues while still reporting success=True — the same misleading short/empty result the PR aims to eliminate. Add a test where the mock honors per_page and the first fetched items are all PRs (more PRs than the limit), asserting the requested number of issues is still returned, plus a case with more items than fit in one page to document the single-page cap.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At plugins/omi-github-app/test_github_client.py, line 206:

<comment>This test cannot detect a regression in the headroom fix it claims to verify. The mock FakeResponse returns the fixed 5-item page regardless of the per_page request param, so the behavioral assertions (success=True, issues==[102,104]) pass identically whether list_issues requests 2 or 30 items per page; only the direct params assertion guards the headroom. It also never exercises the failure mode the PR targets: a page with more PRs than the limit, or a repo with more items than one page. list_issues makes a single non-paginated request capped at min(max(per_page*2,30),100), so when PRs dominate a page or items exceed one page it returns fewer than `per_page` issues while still reporting success=True — the same misleading short/empty result the PR aims to eliminate. Add a test where the mock honors per_page and the first fetched items are all PRs (more PRs than the limit), asserting the requested number of issues is still returned, plus a case with more items than fit in one page to document the single-page cap.</comment>

<file context>
@@ -186,6 +186,63 @@ def test_get_repo_labels_with_details_returns_empty_on_malformed_item(self):
+        self.assertEqual(len(result["issues"]), 2)
+        self.assertEqual([i["number"] for i in result["issues"]], [102, 104])
+        # Verify requested fetch count gives headroom to filter PRs
+        self.assertEqual(get.call_args.kwargs["params"]["per_page"], 30)
+
+    def test_list_issues_returns_error_dict_on_failure(self):
</file context>

@TheRWX

TheRWX commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Updated in 478ec2e:

  1. Test environment stubs (test_issue_tools.py): Module-level stubs for requests and dotenv added to protect environments where plugin dependencies are uninstalled.
  2. State parameter validation (main.py): Explicitly validated state in tool_list_issues to ensure only open, closed, or all are accepted, returning a structured error on invalid states.
  3. Multi-page pagination (github_client.py): Updated list_issues to follow response.links['next'] until per_page non-PR issues are collected or pagination is exhausted.
  4. Line-length formatting (test_github_client.py): Multi-line formatting applied to dictionary literals within the 120-char limit.
  5. Pagination test coverage (test_github_client.py): Added test_list_issues_paginates_when_prs_dominate_first_page verifying that multi-page traversal occurs and yields the requested issue count when prior pages are dominated by pull requests.

All 15 manifest checks in scripts/pr-preflight and both unit test suites pass locally.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution python labels Sep 14, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @TheRWX — this is a solid, well-scoped fix. Reviewed each changed file:

plugins/omi-github-app/main.py — coerce_issue_number / coerce_limit are careful (bool rejection, # prefix and whitespace stripping, non-finite float guards), and tool_get_issue / tool_add_comment now return clean validation errors instead of raising ValueError on inputs like #42. The state allow-list in tool_list_issues plus the result.get("issues", []) unwinding correctly surface 401/403/404 instead of reporting "No open issues found".

plugins/omi-github-app/github_client.py — list_issues now paginates via response.links["next"] until enough non-PR issues are collected (with a fetch_size headroom bound) and returns {"success": False, "error": ...} on API failure; get_issue distinguishes 404 (None) from other API errors (error dict), so auth/rate-limit failures no longer masquerade as "not found". _extract_error_message handles both JSON bodies and plain-text responses.

plugins/omi-github-app/test_github_client.py — good coverage of PR filtering, multi-page traversal (page params asserted), and error-dict returns on 401/403/404; the FakeResponse double now models status_code and links.

plugins/omi-github-app/test_issue_tools.py — hermetic production-handler suite with a clean stubbing harness; asserting client.get_issue was called with issue_number=42 for input " #42 " pins the coercion contract at the handler boundary.

.github/checks-manifest.yaml — the new github-app-issue-tools-tests entry follows the repo convention (local + ci lanes with a regression reason) and it was selected and passed in the Repo Checks run on this head.

Two non-blocking observations:

  1. github_client.list_issues silently falls back to state="open" when given an invalid state. That path is unreachable through tool_list_issues (which rejects invalid states first), so it is just belt-and-braces — fine as is.
  2. get_issue's non-404 error return is a bare {"error": ...} dict while list_issues returns {"success": False, "error": ...}. The single consumer handles it, but a success key would keep the two symmetric if this ever gains another caller.

Both suites pass locally on this head and checks are green. Leaving for human maintainer review before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on 478ec2ecb519.

plugins/omi-github-app/main.py still interpolates str(e) into chat-tool errors, JSON error payloads, an HTTPException detail, and the OAuth HTML page (Failed to complete authentication: {str(e)}).

That is the same unauthenticated HTML/exception sink this repo has been closing elsewhere. Map failures to stable client errors; HTML-escape if anything must render. Head is also CONFLICTING — rebase after the sink is fixed. I am not merging.

…escape OAuth HTML (BasedHardware#13912)

- Closes unauthenticated HTML and exception sinks in plugins/omi-github-app/main.py
  and github_client.py as requested in maintainer review.
- Chat-tool endpoints (tool_create_issue, tool_list_repos, tool_list_issues,
  tool_get_issue, tool_list_labels, tool_add_comment, tool_code_feature) now map
  unhandled exceptions to stable client errors ("Failed to ... due to an internal error.")
  while preserving server-side traceback logging.
- auth_start maps unhandled initialization exceptions to a generic HTTPException(500,
  detail="OAuth initialization failed").
- auth_callback error HTML page replaces str(e) interpolation with stable error prose,
  URL-encodes uid in retry and redirection links, and HTML-escapes reflected username.
- JSON error endpoints (update-repo, refresh-repos, check-repo-access, save-agent-provider,
  save-agent-key, delete-agent-key, test-agent) return stable error messages instead
  of leaking str(e).
- Root endpoint escapes uid in both unauthenticated and authenticated views.
- github_client.py maps unexpected exceptions in create_issue and add_issue_comment to
  stable error responses.
- Extends test_main.py (93/93 tests passing) and test_github_client.py (12/12 tests
  passing) with comprehensive regression coverage.

Fixes BasedHardware#13911

Failure-Class: none

PayPal: [email protected]
@TheRWX
TheRWX force-pushed the fix/github-app-error-handling-and-coercion branch from 478ec2e to 59d0c98 Compare September 20, 2026 15:38
@TheRWX TheRWX changed the title fix(github-app): coerce issue inputs and propagate API errors fix(github-app): map internal exceptions to stable client errors and escape OAuth HTML (#13912) Sep 20, 2026
@TheRWX

TheRWX commented Sep 20, 2026

Copy link
Copy Markdown
Contributor Author

Updated in 59d0c98a45:

  • Rebased cleanly onto upstream/main HEAD (9d0bfdfecf); branch is now MERGEABLE with no conflicts.
  • Closed all unauthenticated HTML and exception sinks across plugins/omi-github-app/main.py and github_client.py:
    1. Chat-Tool Routes: Internal exceptions across tool_create_issue, tool_list_repos, tool_list_issues, tool_get_issue, tool_list_labels, tool_add_comment, and tool_code_feature now map to stable client errors ("Failed to ... due to an internal error.") while preserving server-side traceback logging.
    2. OAuth Initialization: auth_start raises HTTPException(500, detail="OAuth initialization failed") without interpolating str(e).
    3. OAuth Callback Page: The error HTML page renders stable error prose ("Failed to complete authentication. Please try again."), URL-encodes uid via quote(..., safe="") in retry links, and HTML-escapes usernames.
    4. JSON Error Endpoints: update-repo, refresh-repos, check-repo-access, save-agent-provider, save-agent-key, delete-agent-key, and test-agent return stable error structures.
    5. Root Endpoint: Sanitizes uid reflections across both unauthenticated and authenticated views and client-side fetch() scripts.
    6. GitHub Client: Maps unexpected exceptions in create_issue and add_issue_comment to stable error returns.
  • Added 20 new regression tests covering stable exception mapping, HTML escaping, and exception isolation (test_main.py 93/93 passing, test_github_client.py 12/12 passing, test_github_tools_auth.py 11/11 passing).
  • Verified upstream CI preflight (bash scripts/pr-preflight --lane ci --base upstream/main) passed all 17 manifest checks cleanly.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixes unauthenticated exception/HTML leakage in omi-github-app (str(e) reflected to clients, unescaped uid/username in HTML). Maintainer aryanorastar's CHANGES_REQUESTED review (submitted 15:01:51Z) was against an earlier commit; the current head (59d0c98, committed 15:34:48Z, after that review) removes all 18 remaining str(e) interpolations verified by direct diff/file inspection - the cited concern is resolved. Fixes #13911, 93+12+11 tests passing, CI green.

@kodjima33
kodjima33 merged commit 65bcf8d into BasedHardware:main Sep 21, 2026
37 checks passed
aryanorastar added a commit that referenced this pull request Sep 22, 2026
…chat tool responses (#15484)

## Summary

`plugins/omi-shopify-app` returned raw exception text to its callers.
The shared `shopify_api_request` helper answered any `requests` failure
with `f"Request failed: {str(e)}"`, and all six chat-tool handlers
answered any unhandled exception with `f"...: {str(e)}"`.

## Impact

Whatever internal detail the exception carried — provider/socket errors,
filesystem paths, connection details — was reflected back into the
chat-tool response the OMI backend hands to the model/client. Same
failure class as the recent ClickUp app (#15361 / #15360), Slack app
(#15471 / #15469), Whoop app (#15477 / #15476) and GitHub app (#13912)
hardening.

## Fix

- `shopify_api_request`: logs `❌ Shopify API request failed: {e}`
server-side and returns `{"error": "Shopify API request failed"}`.
- `tool_get_analytics`, `tool_get_orders`, `tool_get_order_details`,
`tool_create_order` (outer handler and the token-auth block),
`tool_get_customers`, `tool_create_customer`: log the exception detail
server-side and answer with a fixed, non-reflective message.

No behavior changes other than the error text; success paths are
untouched.

## Tests

`plugins/omi-shopify-app/test_error_handling.py` (new, stdlib-only:
`main.py` is loaded against stub `fastapi`/`requests`/`db`/`models`
modules and the real handlers are driven against raising seams). It
asserts a sentinel trace (`/srv/app/.secrets/shopify_token_store.json`,
the exception class name, `Traceback`) never reaches a response for the
API helper and each of the six tool endpoints, and pins that no
`str(e)`/`str(exc)` response interpolation remains in `main.py`.

Registered as `shopify-error-handling-tests` in
`.github/checks-manifest.yaml`.

## Verification

```
python3 plugins/omi-shopify-app/test_error_handling.py                      # 8 passed
python3 plugins/omi-shopify-app/test_limit_inputs.py                        # ok
python3 plugins/omi-shopify-app/test_create_order_disambiguation.py         # ok
python3 plugins/omi-shopify-app/test_create_order_pagination.py             # ok
python3 plugins/omi-shopify-app/test_oauth_callback_auth.py                 # ok
```

Against `origin/main` `main.py` the new suite fails 8/8 (each response
contains the sentinel trace).

Failure-Class: none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/15484?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

positive-signal Automation verified a genuine fix/quality contribution python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bounty proposal] fix(github-app): coerce issue inputs and propagate API errors

4 participants