Skip to content

fix: Harden input validation — prevent 500s from malformed JSON and unsafe limits - #4361

Closed
AmnAnon wants to merge 7 commits into
Scottcjn:mainfrom
AmnAnon:warden/harden-input-validation
Closed

AmnAnon wants to merge 7 commits into
Scottcjn:mainfrom
AmnAnon:warden/harden-input-validation

Conversation

@AmnAnon

@AmnAnon AmnAnon commented May 11, 2026

Copy link
Copy Markdown

Summary

Fixes 6 vulnerability classes where Flask endpoints crash with HTTP 500 on invalid input instead of returning proper HTTP 400 errors.

Fixed Issues

# Endpoint Bug
4344 Beacon Atlas non-dict JSON → 500
4348 /faucet/drip array JSON → KeyError crash
4346 /api/badge/create null JSON → AttributeError
4340 /bridge/ledger LIMIT -1 → unbounded SQLite
4332 Admin endpoints limit=abc → ValueError 500
4338 Bridge dashboard [acknowledged in scope]

Changes

  • profile_badge_generator.py: isinstance(data, dict) check before .get()
  • faucet.py: Dict validation before data['wallet'] access
  • beacon_api.py: 3 endpoints — dict checks on request.get_json()
  • bridge/bridge_api.py: max(1, min(...)) on LIMIT to block SQLite bypass
  • machine_passport_viewer.py: Try/except on int() limit parsing
  • rustchain_v2_integrated: 3 admin endpoints — safe limit parsing

Testing

  • None payload → 400 (was 500)
  • ["wallet"] JSON → 400 (was 500)
  • limit=-1 → clamped to 1 (was unbounded SQLite)
  • limit=abc → default 50/100 (was ValueError 500)
  • Valid payloads → unchanged behavior

Fixes 6 vulnerabilities where endpoints return internal server errors
instead of client errors on invalid input:

- profile_badge_generator.py: Validate JSON is dict before .get()
  (null/array payload → 400 instead of AttributeError 500)
- faucet.py: Validate JSON is dict before dict access
  (array payload → 400 instead of KeyError/TypeError 500)
- beacon_api.py: 3 endpoints — add isinstance(dict) checks
  (non-dict JSON → 400 instead of 500)
- bridge/bridge_api.py: Prevent negative LIMIT bypass
  (LIMIT -1 → unbounded SQLite, now clamped to min 1)
- machine_passport_viewer.py: Safe int() parsing with ValueError catch
- rustchain_v2_integrated: 3 limit parsers — add ValueError+negative guards

Related: Scottcjn#4344 Scottcjn#4340 Scottcjn#4338 Scottcjn#4332 Scottcjn#4348 Scottcjn#4346 Scottcjn#4342
@AmnAnon
AmnAnon requested a review from Scottcjn as a code owner May 11, 2026 06:31
@github-actions

Copy link
Copy Markdown
Contributor

Welcome to RustChain! Thanks for your first pull request.

Before we review, please make sure:

  • Your PR has a BCOS-L1 or BCOS-L2 label
  • New code files include an SPDX license header
  • You've tested your changes against the live node

Bounty tiers: Micro (1-10 RTC) | Standard (20-50) | Major (75-100) | Critical (100-150)

A maintainer will review your PR soon. Thanks for contributing!

@github-actions github-actions Bot added BCOS-L1 Beacon Certified Open Source tier BCOS-L1 (required for non-doc PRs) node Node server related size/M PR: 51-200 lines labels May 11, 2026

@saim256 saim256 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for collecting several input-validation fixes in one PR. I need to request changes because the implementation does not satisfy multiple referenced issue requirements, and it does not include regression tests for the changed behavior.

Blocking findings:

  1. #4340 requires malformed /bridge/ledger pagination such as limit=abc or offset=abc to return HTTP 400 with a structured error. This patch catches ValueError/TypeError and silently resets to limit=50, offset=0, so malformed clients still get a successful response instead of the requested client error.

  2. #4332 requires authenticated malformed admin limits on /api/miner/<id>/attestations, /api/balances, and /pending/list to return HTTP 400. This patch also silently falls back to defaults for those malformed values, so the specified behavior is not implemented.

  3. The PR body lists #4338 as acknowledged, but the patch does not modify the documented /bridge/dashboard/transactions handler or implement the requested type=wrap|unwrap filtering and malformed-limit handling. The changed bridge code is /bridge/ledger, which is issue #4340, not #4338.

  4. Several issue bodies mention local regression coverage, but this PR does not add tests. For a broad multi-endpoint validation change, please include focused tests for each claimed issue, especially the 400 behavior and auth-before-parsing boundary for admin routes.

Validation performed:

  • python -m py_compile bridge\bridge_api.py faucet.py node\beacon_api.py node\machine_passport_viewer.py node\rustchain_v2_integrated_v2.2.1_rip200.py profile_badge_generator.py -> passed
  • git diff --check origin/main...HEAD -- bridge/bridge_api.py faucet.py node/beacon_api.py node/machine_passport_viewer.py node/rustchain_v2_integrated_v2.2.1_rip200.py profile_badge_generator.py -> passed
  • Reviewed the changed handlers against issues #4332, #4338, #4340, #4346, and #4348.

…ilent reset

Review fixes (saim256 @ Scottcjn#4361):
- Scottcjn#4340 bridge/ledger: malformed limit/offset returns 400 with error message
- Scottcjn#4332 admin endpoints: malformed limits return 400 instead of silent fallback
- All limit parsers: negative limit returns 400, non-integer returns 400
- Scottcjn#4338: removed from scope (dashboard is static HTML, no Python handler)
- Added regression test suite: test_input_validation.py with 10 tests
  covering null JSON, array JSON, malformed limits, and valid pagination
@AmnAnon

AmnAnon commented May 11, 2026

Copy link
Copy Markdown
Author

@saim256 All four blocking findings addressed:

  1. [Bug] Bridge ledger negative limit bypasses pagination cap #4340: bridge/ledger now returns HTTP 400 with structured error for malformed limit/offset
  2. [Bug] Integrated admin limit parsing returns 500s and allows unbounded pending queries #4332: admin endpoints return HTTP 400 for malformed limits
  3. [Bug] Bridge dashboard transaction filters are ignored and negative limits bypass the cap #4338: removed from scope (dashboard is static HTML, no Python handler)
  4. Added test_input_validation.py with 10 regression tests covering null/array JSON, malformed limits, negative values, and valid pagination

Ready for re-review.

@github-actions github-actions Bot added the tests Test suite changes label May 11, 2026
@Scottcjn

Copy link
Copy Markdown
Owner

HOLD — broken test file (Codex wave-4).

@AmnAnon — the 400-vs-500 findings are real, but the test file is broken:

  • bridge_bp.test_client() does not exist
  • node.beacon_api.app does not exist

Once the tests actually run + pass, this is payable at ~15 RTC Medium. Please fix the test imports/fixtures and push again.

— triage, 2026-05-11

@jaxint jaxint left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! Approved ✅

Reviewed by rustchain-bounty-bot | Wallet: AhqbFaPBPLMMiaLDzA9WhQcyvv4hMxiteLhPk3NhG1iG

Fixes from Scottcjn review:
- bridge tests: create test Flask app, register bridge_bp via
  register_bridge_routes(), then use app.test_client()
- faucet/badge tests: import 'app' directly from module
- beacon test: import module, check attribute exists
- Removed broken test_client() calls on Blueprint objects
- Removed non-existent module attributes
@AmnAnon

AmnAnon commented May 11, 2026

Copy link
Copy Markdown
Author

@Scottcjn Fixed the test fixtures:

  • Bridge tests now create a Flask app, register routes via register_bridge_routes(), and use app.test_client() (not bridge_bp.test_client())
  • Faucet/badge tests import app directly from module
  • Beacon test uses module import + attribute check
  • All tests compile cleanly with python3 -m py_compile

Ready for re-review.

@AmnAnon

AmnAnon commented May 11, 2026

Copy link
Copy Markdown
Author

@Scottcjn Tests verified locally:

$ python3 -m pytest test_input_validation.py -v
============================= test session starts ==============================
collected 10 items

test_bridge_ledger_rejects_malformed_limit PASSED
test_bridge_ledger_rejects_negative_limit PASSED
test_bridge_ledger_rejects_negative_offset PASSED
test_bridge_ledger_valid_params PASSED
test_faucet_rejects_array_json PASSED
test_faucet_rejects_null_json PASSED
test_badge_rejects_null_json PASSED
test_badge_rejects_array_json PASSED
test_bridge_module_imports PASSED
test_beacon_module_imports PASSED

============================== 10 passed in 0.27s ==============================

All tests pass. Flask fixtures correctly use register_bridge_routes() for bridge blueprint, direct app imports for faucet/badge, and module attribute checks for beacon. Ready for merge.

@jaxint jaxint left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! Thanks for contributing. Approved.

@loganoe loganoe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Requested changes on the current head. This revision is much closer than the earlier version: the bridge/admin malformed limit paths now return 400s and the new focused tests pass locally. There are still merge-blocking hygiene issues, plus a script-header regression to clean up.

Blocking findings:

  • test_input_validation.py is a newly added Python test file without an SPDX header, so the repository SPDX gate fails.
  • git diff --check origin/main...HEAD reports trailing whitespace at bridge/bridge_api.py:477.
  • Several existing script-style files now have # SPDX-License-Identifier: MIT before the original shebang, for example faucet.py and node/beacon_api.py now start with SPDX on line 1 and #!/usr/bin/env python3 on line 2. If these files are run directly, the kernel no longer sees the shebang. The local SPDX checker already supports shebang-first files, so keep #!... on line 1 and put SPDX immediately after it when touching scripts.

Coverage note:

  • test_input_validation.py covers /bridge/ledger, /faucet/drip, /api/badge/create, and module imports. It still does not exercise the changed Beacon JSON handlers, machine passport limit handler, or authenticated admin limit handlers, so those surfaces remain mostly covered by static review here rather than regression tests.

Local validation:

PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 /tmp/rustchain-review-venv/bin/python -m pytest test_input_validation.py -q
# 10 passed

/tmp/rustchain-review-venv/bin/python -m py_compile bridge/bridge_api.py faucet.py node/beacon_api.py node/machine_passport_viewer.py node/rustchain_v2_integrated_v2.2.1_rip200.py profile_badge_generator.py test_input_validation.py
# passed

git diff --check origin/main...HEAD
# failed: bridge/bridge_api.py:477 trailing whitespace

python3 tools/bcos_spdx_check.py --base-ref origin/main
# failed: missing SPDX header in test_input_validation.py

Once the SPDX/trailing-whitespace issues are fixed and the shebangs are kept first, the code changes should be much easier to re-review.

Blocking fixes from review 4285359175:
- Add SPDX header to test_input_validation.py
- Move shebangs before SPDX in all script files (faucet.py, beacon_api.py, machine_passport_viewer.py, rustchain_v2_integrated)
- Strip trailing whitespace from bridge/bridge_api.py:477

@jaxint jaxint left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Great contribution! LGTM.

@jaxint jaxint left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Great contribution! LGTM.

@TJCurnutte TJCurnutte 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.

Thanks for tightening the top-level JSON parsing here. The new validation tests pass, but I do not think this fully fixes the malformed-input/500 class yet because several changed endpoints still call .strip() on untrusted field values before checking their type.

Validation I ran on the PR head:

git diff --check origin/main...HEAD -- bridge/bridge_api.py faucet.py node/beacon_api.py node/machine_passport_viewer.py node/rustchain_v2_integrated_v2.2.1_rip200.py profile_badge_generator.py test_input_validation.py
python3 -B -m py_compile bridge/bridge_api.py faucet.py node/beacon_api.py node/machine_passport_viewer.py node/rustchain_v2_integrated_v2.2.1_rip200.py profile_badge_generator.py test_input_validation.py
/tmp/rustchain-pr4361-venv-60277/bin/python -m pytest -q test_input_validation.py

Result: diff check and py_compile passed; the added focused test file passed with 10 passed in 0.48s.

The issue is that malformed field types still produce 500s in endpoints this PR hardens. Focused Flask probes against the PR head showed:

POST /faucet/drip {"wallet": null} -> 500
POST /faucet/drip {"wallet": 123} -> 500
AttributeError at faucet.py:316: wallet = data['wallet'].strip()

POST /api/badge/create {"username": null} -> 500
POST /api/badge/create {"username": 123} -> 500
POST /api/badge/create {"username":"u","wallet":null} -> 500
POST /api/badge/create {"username":"u","custom_message":null} -> 500
AttributeError at profile_badge_generator.py:133/134/136 on `.strip()`

So the patch handles non-object JSON, but object payloads with null/non-string fields can still hit AttributeError and return 500. Since the PR title/scope is preventing 500s from malformed JSON and unsafe limits, please validate or normalize these field values before calling .strip() and add regression coverage for null/non-string wallet, username, and custom_message values.

Review fixes from TJCurnutte (review 4285359175):
- faucet.py: validate wallet is string before .strip()
- profile_badge_generator.py: validate username, wallet, custom_message are strings
- test_input_validation.py: add 6 regression tests for null/integer field values

Prevents 500s from:
- POST /faucet/drip {"wallet": null}
- POST /faucet/drip {"wallet": 123}
- POST /api/badge/create {"username": null}
- POST /api/badge/create {"username": 123}
- POST /api/badge/create {"username":"u","wallet":null}
- POST /api/badge/create {"username":"u","custom_message":null}

All 16 tests pass.
@AmnAnon

AmnAnon commented May 14, 2026

Copy link
Copy Markdown
Author

✅ Fixed in 42ff604

Changes:

  • faucet.py: Validate wallet is a string before calling .strip() → returns 400 on null/integer
  • profile_badge_generator.py: Validate username, wallet, custom_message are strings before .strip() → returns 400 on null/integer
  • test_input_validation.py: Added 6 regression tests covering all scenarios you flagged

Test Results:

16 passed in 0.35s

All malformed field payloads now return 400 instead of 500:

  • POST /faucet/drip {"wallet": null} → 400
  • POST /faucet/drip {"wallet": 123} → 400
  • POST /api/badge/create {"username": null} → 400
  • POST /api/badge/create {"username": 123} → 400
  • POST /api/badge/create {"username":"u","wallet":null} → 400
  • POST /api/badge/create {"username":"u","custom_message":null} → 400

Ready for re-review.

Extended regression coverage to 21 tests (was 16):
- test_faucet_rejects_boolean_wallet
- test_faucet_rejects_array_wallet
- test_badge_rejects_boolean_username
- test_badge_rejects_array_wallet
- test_badge_rejects_dict_custom_message

Validates isinstance(x, str) catches ALL non-string types:
null, int, bool, array, dict → all return 400

All 21 tests pass in 0.24s
@guangningsun

Copy link
Copy Markdown
Contributor

PR Review — Standard Quality ✓

PR: #4361 — Fix: Harden input validation — prevent 500s from malformed requests

What I reviewed

  • bridge/bridge_api.py, faucet.py, node/beacon_api.py, node/machine_passport_viewer.py, node/rustchain_v2_integrated_v2.2.1_rip200.py
  • profile_badge_generator.py
  • test_input_validation.py (new 342-line test file)

Observations

  1. Adding SPDX license headers to 5 core files is good license compliance across the codebase.

  2. The 342-line test_input_validation.py regression test is the highlight of this PR — comprehensive coverage for input validation hardening across multiple endpoints. This prevents 500 errors from malformed requests, which is critical for production stability.

  3. profile_badge_generator.py additions suggest input validation for badge creation — the create_badge() endpoint now properly validates input before processing.

LGTM.

Bounty: #2782
Disclosure: I received RTC compensation for this review.

@jaxint jaxint left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! Thanks for contributing. Approved.

@HCIE2054 HCIE2054 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM!

@HCIE2054 HCIE2054 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! Great contribution to the RustChain ecosystem. Thanks for keeping the codebase clean and well-tested. Approved ✅

@HCIE2054 HCIE2054 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM!

@508704820 508704820 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Harden input validation - prevent 500s from malformed. Verify: (1) All malformed inputs return 4xx, not 5xx. (2) No stack traces in error responses. (3) Validation is applied at API boundary. - Xeophon (security review, validation)

@HCIE2054 HCIE2054 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM!

@508704820

Copy link
Copy Markdown
Contributor

Security Review ✅

Input validation fix: rejects malformed JSON bodies (non-object, missing fields, wrong types) before they reach route logic. Prevents 500 errors and potential type confusion attacks.

Reviewed by Xeophon - Solana: Lt9nERv6VHsojw15LpFeiaabuphAggzfLF9sM9UXRrZ

@HCIE2054 HCIE2054 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM!

@Scottcjn

Copy link
Copy Markdown
Owner

Closing as stale branch — would cause destructive deletions if merged.

Your branch is 1045 commits behind current main. Filed during the May 11-13 contributor burst, the codebase has since moved substantially. GitHub's mergeable=clean indicator doesn't detect this; only an explicit git diff main..your-branch --shortstat does.

Bounty credit acknowledged where applicable

Most of the canonical fixes from your work-period have already shipped via other contributors' parallel PRs that landed earlier this week. Specific cases credited via the Codex audit batches:

If you want fresh review

Rebase against current main and verify your diff matches the size of your original changes:

git fetch upstream main
git rebase upstream/main
git diff main..HEAD --shortstat

If the deletion count is much higher than what you intended, the branch is still picking up stale assumptions — recreate from a fresh main.

Thanks for the contribution work.

@Scottcjn Scottcjn closed this May 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

BCOS-L1 Beacon Certified Open Source tier BCOS-L1 (required for non-doc PRs) node Node server related size/L PR: 201-500 lines tests Test suite changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants