Skip to content

fix: return a standard error body for non-JSON error responses - #1509

Merged
jshcodes merged 1 commit into
CrowdStrike:devfrom
ManuelFCastillo:fix/non-json-error-response-1508
Sep 23, 2026
Merged

jshcodes merged 1 commit into
CrowdStrike:devfrom
ManuelFCastillo:fix/non-json-error-response-1508

Conversation

@ManuelFCastillo

Copy link
Copy Markdown
Contributor

Return a standard error body for non-JSON error responses

Error responses are not always JSON. A proxy, load balancer or WAF sitting in front of the API can answer with an HTML error page, an empty body or an unexpected content type. Those payloads reach calc_content_return() as raw bytes, and the error inspection block then calls .get() on them:

if resp.status_code >= 400:
    _message = None
    _errors = returned.get("body", {}).get("errors", [])

which raises AttributeError: 'bytes' object has no attribute 'get'. The exception is caught by the general handler in perform_request(), wrapped in an SDKError (whose code defaults to 500) and returned as a generated error, so the real status code and every response header, including X-Cs-TraceId, are discarded. That is the loss reported in #1508: the caller cannot tell a 429 from a 502 from a 503, and Support has no trace ID to research.

  • Bug fixes
  • Updated unit tests

Reproduction

Four conditions reach the failing line on main (1.6.5). All four require status_code >= 400 and a body that is not JSON or text/plain:

Response 1.6.5
502, text/html gateway page AttributeError
503, empty body, no Content-Type AttributeError
500, application/octet-stream AttributeError
429, text/html rate limit page AttributeError

End to end through the operation named in the issue, before the change:

{'status_code': 500, 'headers': {}, 'body': {'errors': [{'message': "'bytes' object has no attribute 'get'", 'code': 500}], 'resources': []}}

and after:

{'status_code': 502, 'headers': {'Content-Type': 'text/html', 'X-Cs-Traceid': 'trace-abc-123'}, 'body': {'errors': [{'code': 502, 'message': '<html>...502 Bad Gateway...</html>'}], 'resources': []}}

Both Service Classes and APIHarnessV2 reach this through the same function, so both were affected and both are fixed.

Behaviour change

A response with status_code >= 400 whose body is not JSON or text/plain previously raised, and now returns the documented status_code / headers / body dictionary with a Falcon shaped errors list.

The guard is nested inside the existing status_code >= 400 branch, so successful binary responses are untouched. RTR file get, sensor downloads and report exports still return raw bytes. There is a unit test asserting this.

Relationship to #1428

PR #1428 is open against the same function for a different issue (#1154). I checked it out and ran the reproduction against it: it resolves the two text/html cases as a side effect of adding a text/html branch, and leaves the empty body and application/octet-stream cases raising, because it does not change the .get() call. The two changes are complementary rather than competing, and I do not believe they conflict textually. Happy to rebase on it, fold this into it, or step aside if you would rather see that one land first.

Unit test coverage

tests/test_non_json_error_responses.py is new: 14 tests built on stubbed requests.Response objects, requiring no credentials.

$ coverage run --source=src --omit=src/falconpy/debug.py -m pytest tests/test_non_json_error_responses.py -q
14 passed, 1 warning in 0.14s

Name                                   Stmts   Miss  Cover
-------------------------------------------------------------
src/falconpy/_constant/__init__.py        13      0   100%
src/falconpy/_util/_functions.py         475    244    49%

Every line added by this PR is covered by this file alone. The 49% figure is this one test file in isolation; the rest of the module is exercised by the credentialed suite, which does not run on fork pull requests (the unit testing workflows are gated on head.repo.full_name == github.repository), so I could not produce a full series result. Removing the guard and rerunning the new file fails 8 of 14, each with the original AttributeError.

Bandit analysis

$ bandit -r src/falconpy
Total lines of code: 155107

Total issues (by severity):
    Undefined: 0
    Low: 0
    Medium: 0
    High: 0

flake8 src/falconpy --count reports 0. pylint on the changed module scores 9.80 against a 9.79 baseline on main.

Issues resolved

Other

  • build_error_body_from_payload() decodes with errors="replace" so an error page that is not valid UTF-8 cannot raise from inside error handling, and truncates at MAX_ERROR_PAYLOAD_LENGTH (4096) so a large HTML page is not embedded whole into an error message.
  • It is not exported from _util/__init__.py since nothing outside _functions.py uses it. Happy to export it if you would prefer.
  • No version bump included, assuming that is maintainer managed.

@jshcodes jshcodes left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thank you for your contribution!! 🙇

@jshcodes

Copy link
Copy Markdown
Member

Related to #1498 and #1510. Merging to dev for additional unit testing and confirmation.

Planned as part of the v1.6.6 released.

Error responses are not always JSON. A proxy, load balancer or WAF in
front of the API can answer with an HTML error page, an empty body or an
unexpected content type. Those payloads reach calc_content_return() as
raw bytes, and the error inspection block then calls .get() on them:

    if resp.status_code >= 400:
        _errors = returned.get("body", {}).get("errors", [])

raising AttributeError: 'bytes' object has no attribute 'get'. The
exception is caught by the general handler in perform_request(), wrapped
in an SDKError and returned as a generated 500, so the real status code
and every response header, including X-Cs-TraceId, are discarded.

Normalize a non-dictionary payload into the documented error format
before the block inspects it, so the status code and headers survive and
the returned body is always a dictionary.

The guard is nested inside the existing status_code >= 400 branch, so
successful binary responses (RTR file get, sensor downloads, report
exports) are untouched and still return bytes.

Adds tests/test_non_json_error_responses.py: 14 tests built on stubbed
requests.Response objects, no credentials required.

Fixes CrowdStrike#1508

Co-Authored-By: Claude Opus 5 <[email protected]>
@jshcodes
jshcodes force-pushed the fix/non-json-error-response-1508 branch from 0c9aca2 to 4c1d807 Compare September 23, 2026 14:51
@jshcodes
jshcodes merged commit 902bde9 into CrowdStrike:dev Sep 23, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[ BUG ] Intermittent "'bytes' object has no attribute 'get'" 500 returned from UserManagement.grant_user_role_ids / revoke_user_group_member

2 participants