Skip to content

Fix ArgumentOutOfRangeException when validating Basic Authorization h…#492

Open
benyuz wants to merge 5 commits into
nanoframework:mainfrom
benyuz:main
Open

Fix ArgumentOutOfRangeException when validating Basic Authorization h…#492
benyuz wants to merge 5 commits into
nanoframework:mainfrom
benyuz:main

Conversation

@benyuz
Copy link
Copy Markdown
Contributor

@benyuz benyuz commented May 10, 2026

Fix crash when Authorization validation for Basic format

Description

  • Fixed an ArgumentOutOfRangeException crash in HttpListenerRequest.ParseHTTPRequest when the Authorization header value does not contain a space (e.g., Authorization: a111111 or malformed Basic authentication).
  • Added a safety check if (sepSpace > 0) before parsing the Authorization header value.
  • If the value does not contain a space, the header is silently ignored.

Motivation and Context

  • Currently, when a malformed Authorization header without space is received (e.g., Authorization: a111111), the ParseHTTPRequest method crashes with ArgumentOutOfRangeException because sepSpace is -1 and Substring(0, sepSpace) is called.
  • This issue was discovered during development of PicoServer.Nano when testing edge cases with malformed Authorization headers.

How Has This Been Tested?

  • Manually tested on ESP32 device using curl -H "Authorization: a111111" http://<device-ip>/hello
  • Verified that no exception is thrown and the request is handled gracefully
  • Added unit test Add_Authorization_NoSpaceMultipleChars_ShouldNotThrow in HttpListenerRequestTests.cs

Screenshots

Types of changes

  • Bug fix (non-breaking change which fixes an issue with code or algorithm)
  • Unit Tests (add new Unit Test(s) or improved existing one(s), has no impact on code or features)

Checklist:

  • My code follows the code style of this project (only if there are changes in source code).
  • My changes require an update to the documentation (there are changes that require the docs website to be updated).
  • I have updated the documentation accordingly (the changes require an update on the docs in this repo).
  • I have read the CONTRIBUTING document.
  • I have tested everything locally and all new and existing tests passed (only if there are changes in source code).
  • I have added new tests to cover my changes.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 10, 2026

Review Change Stack

Warning

Rate limit exceeded

@benyuz has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 32 minutes and 37 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: nanoframework/coderabbit/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6389fb35-68f5-4670-9785-a14c123b2de6

📥 Commits

Reviewing files that changed from the base of the PR and between 39b3e14 and 1caf226.

📒 Files selected for processing (2)
  • Tests/HttpUnitTests/HttpListenerRequestTests.cs
  • Tests/HttpUnitTests/HttpUnitTests.nfproj
📝 Walkthrough

Walkthrough

The PR adds defensive validation to HttpListenerRequest.ParseHTTPRequest to check for a space delimiter in Authorization headers before parsing, preventing exceptions on malformed values. It includes two unit tests verifying both malformed (no space) and valid (Basic auth) header handling, plus a project file update to compile the new test file.

Changes

Authorization Header Validation and Testing

Layer / File(s) Summary
Authorization Header Validation
nanoFramework.System.Net.Http/Http/System.Net.HttpListenerRequest.cs
ParseHTTPRequest checks for space delimiter in Authorization header before extracting auth type and base64 credentials, preventing substring exceptions on malformed headers.
Unit Tests
Tests/HttpUnitTests/HttpListenerRequest.cs
HttpListenerRequestTests adds two tests: one verifies malformed Authorization header without space does not throw, the other verifies valid Basic auth header is stored and read correctly.
Project Configuration
Tests/HttpUnitTests/HttpUnitTests.nfproj
New test file HttpListenerRequest.cs is added to the project's <Compile> item group.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main issue being fixed: an ArgumentOutOfRangeException in Basic Authorization validation, which aligns with the primary change in the PR.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, detailing the bug, the fix, testing approach, and motivation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@nanoFramework.System.Net.Http/Http/System.Net.HttpListenerRequest.cs`:
- Around line 215-219: The Basic auth parsing in HttpListenerRequest currently
calls Convert.FromBase64String(authInfo) and builds strAuthInfo without guarding
FormatException; wrap the Base64 decode and subsequent UTF8 char
conversion/credential split (the authInfo, authInfoDecoded, authInfoDecChar and
strAuthInfo logic) in a try-catch that catches FormatException (and optionally
ArgumentException) and simply ignores the malformed Authorization header (i.e.,
do not throw, continue processing other headers), mirroring the graceful
behavior used in the Content-Length parsing; ensure you reference and protect
the Convert.FromBase64String call and the UTF8 decoding and string construction
so malformed Base64 does not propagate an exception to callers.

In `@Tests/HttpUnitTests/HttpListenerRequest.cs`:
- Around line 13-29: Add tests that exercise the actual parser path by invoking
HttpListenerRequest.ParseHTTPRequest with full raw HTTP request text (including
request line, headers, and CRLF terminator) so the fixed parser path is
validated; create two test cases (e.g.,
Add_Authorization_NoSpaceMultipleChars_ParseHTTPRequest_ShouldNotThrow and
Add_Authorization_ValidBasicToken_ParseHTTPRequest_ShouldSucceed) that build raw
requests containing "Authorization: a111111" and "Authorization: Basic a111111"
respectively, call HttpListenerRequest.ParseHTTPRequest (or the public factory
that uses it) to produce an HttpListenerRequest, and assert the resulting header
value for "Authorization" matches expected ("a111111" for malformed path
behavior you want to lock in, and "Basic a111111" for the valid case) to ensure
the parser change is covered.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: nanoframework/coderabbit/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 23dd44bb-dfd8-42ab-8467-677e82068cbe

📥 Commits

Reviewing files that changed from the base of the PR and between 8b0b6fe and de2844e.

📒 Files selected for processing (3)
  • Tests/HttpUnitTests/HttpListenerRequest.cs
  • Tests/HttpUnitTests/HttpUnitTests.nfproj
  • nanoFramework.System.Net.Http/Http/System.Net.HttpListenerRequest.cs

Comment thread Tests/HttpUnitTests/HttpListenerRequestTests.cs
@benyuz
Copy link
Copy Markdown
Contributor Author

benyuz commented May 10, 2026

Yes, please create a follow-up issue for the Base64 parsing exception. That would be very helpful. Thank you!

Comment thread nanoFramework.System.Net.Http/Http/System.Net.HttpListenerRequest.cs Outdated
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Fixes a server-side crash in the nanoFramework System.Net.Http implementation when parsing malformed Authorization headers in HttpListenerRequest.ParseHTTPRequest, preventing an ArgumentOutOfRangeException when the header value lacks a space separator.

Changes:

  • Added a guard (sepSpace > 0) before splitting the Authorization header into scheme/credentials.
  • Added a new unit test file and included it in the HttpUnitTests project.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 6 comments.

File Description
nanoFramework.System.Net.Http/Http/System.Net.HttpListenerRequest.cs Adds a safety check to avoid substring with a negative length when parsing Authorization.
Tests/HttpUnitTests/HttpUnitTests.nfproj Includes a new test source file in the test project build.
Tests/HttpUnitTests/HttpListenerRequest.cs Adds new tests intended to cover malformed and valid Authorization header formats.

Comment thread Tests/HttpUnitTests/HttpListenerRequest.cs Outdated
Comment thread Tests/HttpUnitTests/HttpListenerRequestTests.cs
Comment thread Tests/HttpUnitTests/HttpListenerRequestTests.cs
Comment thread Tests/HttpUnitTests/HttpListenerRequest.cs Outdated
Comment thread Tests/HttpUnitTests/HttpUnitTests.nfproj Outdated
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Comment thread Tests/HttpUnitTests/HttpListenerRequestTests.cs
Comment thread nanoFramework.System.Net.Http/Http/System.Net.HttpListenerRequest.cs Outdated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants