Skip to content

fix: Mask sensitive credentials in authorization header toString() methods - #238

Merged
SandPod merged 4 commits into
mainfrom
copilot/mask-bearer-token-in-tostring
Oct 24, 2025
Merged

SandPod merged 4 commits into
mainfrom
copilot/mask-bearer-token-in-tostring

Conversation

Copilot AI commented Oct 23, 2025 •

Copy link
Copy Markdown
Contributor
  • Understand the security issue: Bearer tokens exposed in toString() methods
  • Modify BearerAuthorizationHeader.toString() to mask the token value (show only first/last few characters)
  • Add toStringInsecure() method to BearerAuthorizationHeader that prints the full token
  • Apply same changes for BasicAuthorizationHeader (mask password)
  • Apply same changes for DigestAuthorizationHeader (mask nonce, response, cnonce, opaque)
  • Add comprehensive tests for the new toString() and toStringInsecure() methods
  • Run all existing tests to ensure no regressions (3187 tests pass)
  • Run static analysis and formatting checks (both pass)
  • Manually verify the changes work as expected
  • Run CodeQL security checker (no issues detected)
  • Address PR review feedback: increase minimum token length to 16 characters

Summary

This PR addresses a security vulnerability where sensitive authentication credentials were being exposed in full when toString() was called on authorization header instances.

Changes Made:

BearerAuthorizationHeader:

  • toString() now masks the token, showing only first 4 and last 4 characters (e.g., 1234****3456)
  • For tokens <16 chars, shows only **** (ensures at least 8 characters are masked)
  • Added toStringInsecure() method for debugging that exposes the full token

BasicAuthorizationHeader:

  • toString() now masks the password as ****
  • Added toStringInsecure() method for debugging

DigestAuthorizationHeader:

  • toString() now masks sensitive fields: nonce, response, cnonce, and opaque
  • Added toStringInsecure() method for debugging

Testing:

  • Added 11 new test cases covering all masking scenarios
  • All 3187 existing tests pass
  • Manual verification confirms proper masking behavior

This prevents accidental credential leaks in logs while still providing developers with a way to debug authentication issues in secure environments using toStringInsecure().

Original prompt

This section details on the original issue you should resolve

<issue_title>Security: Bearer tokens exposed in toString() methods</issue_title>
<issue_description>Bearer token values are currently exposed in full when toString() is called on BearerAuthorizationHeader instances. This could lead to sensitive authentication tokens being leaked in logs or debug output.

The toString() method should mask or redact the token value to prevent accidental exposure of sensitive credentials.

Related Discussion:

Reporter: @coderabbitai</issue_description>

Comments on the Issue (you are @copilot in this section)

@SandPod Should obfuscate the token in `toString` but then introduce a `toStringInsecure` that prints out the full token.

Fixes #154


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Summary by CodeRabbit

  • New Features

    • Added debug methods to reveal full sensitive authentication data when needed.
  • Bug Fixes

    • Authorization header strings now mask sensitive credentials (tokens, passwords, nonces) for security, displaying only essential fields in logs and output.
  • Tests

    • Added comprehensive tests verifying masking behavior across authorization header types.

@coderabbitai

coderabbitai Bot commented Oct 23, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Authorization header classes now mask sensitive information in toString() methods. BearerAuthorizationHeader masks token values, BasicAuthorizationHeader masks passwords, and DigestAuthorizationHeader masks nonce, response, cnonce, and opaque fields. New toStringInsecure() methods expose full values for debugging purposes.

Changes

Cohort / File(s) Summary
Authorization header security masking
lib/src/headers/typed/headers/authorization_header.dart
Modified toString() in BearerAuthorizationHeader, BasicAuthorizationHeader, and DigestAuthorizationHeader to mask sensitive fields. Added toStringInsecure() public methods to each class for unmasked debugging output. Added private _maskToken() utility for Bearer token masking logic.
Authorization header test coverage
test/headers/typed/authorization_header_test.dart
Added new test group "Given authorization header toString() methods" verifying masking behavior for all three authorization header types in both toString() and toStringInsecure() variants.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR description provides comprehensive technical content with clear problem statements, solution details, and usage examples. However, it does not follow the repository's specified template structure and is missing key required sections including the Pre-Launch Checklist (with checkboxes for style guide compliance, issue referencing, documentation, test coverage) and the Breaking Changes section (with explicit checkbox declarations). While the description contains relevant information, adherence to the template is necessary for consistency and ensures all required documentation is completed.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title "fix: Mask sensitive credentials in authorization header toString() methods" is clear, specific, and directly summarizes the main change in the PR. It uses the conventional "fix:" prefix to indicate a bug fix, clearly indicates what is being fixed, and provides sufficient detail for a developer scanning the history to understand the primary change. The title is concise and avoids vague or generic terms.
Linked Issues Check ✅ Passed The PR fully addresses all coding objectives from issue #154. The implementation masks bearer tokens (showing only first 4 and last 4 characters), passwords in BasicAuthorizationHeader, and sensitive Digest fields in toString() methods. The toStringInsecure() methods provide the requested secure debugging mechanism. The 11 new test cases verify masking behavior across all three header types, and the summary confirms that 3,187 existing tests continue to pass, fulfilling the requirement to prevent credential exposure while enabling access when needed.
Out of Scope Changes Check ✅ Passed All changes are directly scoped to the objectives of linked issue #154. Modifications to authorization_header.dart focus exclusively on masking credentials in toString() methods and adding toStringInsecure() variants for BearerAuthorizationHeader, BasicAuthorizationHeader, and DigestAuthorizationHeader. The test additions in authorization_header_test.dart serve to verify the masking behavior. No extraneous changes or features unrelated to the security concern are present in the changeset.

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

Copilot AI changed the title [WIP] Fix exposure of bearer tokens in toString() methods fix: Mask sensitive credentials in authorization header toString() methods Oct 23, 2025
Copilot AI requested a review from SandPod October 23, 2025 13:29
@SandPod

SandPod commented Oct 23, 2025

Copy link
Copy Markdown
Contributor

@coderabbitai - full review

@coderabbitai

coderabbitai Bot commented Oct 23, 2025

Copy link
Copy Markdown
Contributor

@SandPod: I'll perform a comprehensive review of all the changes in this PR, examining the implementation of credential masking in the authorization headers, the test coverage, and ensuring the security improvements are properly implemented.

✅ Actions performed

Full review triggered.

@SandPod
SandPod marked this pull request as ready for review October 23, 2025 14:20
@SandPod
SandPod requested a review from a team October 23, 2025 14:20

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f85d567 and 18ffa66.

📒 Files selected for processing (2)
  • lib/src/headers/typed/headers/authorization_header.dart (3 hunks)
  • test/headers/typed/authorization_header_test.dart (1 hunks)
🧰 Additional context used
🪛 Gitleaks (8.28.0)
test/headers/typed/authorization_header_test.dart

[high] 545-545: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (4)
lib/src/headers/typed/headers/authorization_header.dart (2)

105-127: LGTM! Token masking implementation is secure and well-designed.

The masking strategy is sound:

  • Tokens ≤ 8 characters are fully masked as ****
  • Longer tokens reveal first 4 and last 4 characters with middle masked
  • The toStringInsecure() method includes appropriate security warnings

The implementation effectively prevents accidental token exposure while maintaining debuggability.


208-218: LGTM! Password masking is correctly implemented.

The approach of masking the password while keeping the username visible is reasonable, as usernames are typically not considered sensitive. The security warning in toStringInsecure() is appropriately worded.

test/headers/typed/authorization_header_test.dart (2)

540-671: Excellent test coverage with one gap.

The test suite comprehensively validates masking behavior across all authorization header types and includes good boundary testing (8-char and 9-char tokens).

However, there's no test case for DigestAuthorizationHeader.toString() when cnonce and opaque are null. Consider adding a test to verify that null optional fields are properly represented (especially important given the issue flagged in the implementation).

Example test to add:

test(
  'when DigestAuthorizationHeader.toString() is called with null optional fields '
  'then it should show null instead of masking',
  () {
    final digest = DigestAuthorizationHeader(
      username: 'user',
      realm: 'realm',
      nonce: 'secretNonce',
      uri: '/path',
      response: 'secretResponse',
      // cnonce and opaque are null
    );
    final result = digest.toString();
    expect(result, contains('cnonce: null'));
    expect(result, contains('opaque: null'));
  },
);

545-545: Static analysis false positive - safe to ignore.

The Gitleaks warning about a "Generic API Key" is a false positive. The string 'abc123def456ghi789' is test data used specifically to verify the token masking functionality, not an actual credential.

@SandPod

SandPod commented Oct 23, 2025

Copy link
Copy Markdown
Contributor

@copilot - Please address all the PR review comments.

@codecov

codecov Bot commented Oct 23, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.23%. Comparing base (f85d567) to head (10261b8).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #238      +/-   ##
==========================================
+ Coverage   91.18%   91.23%   +0.04%     
==========================================
  Files          88       88              
  Lines        3325     3343      +18     
  Branches     1715     1720       +5     
==========================================
+ Hits         3032     3050      +18     
  Misses        293      293              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@SandPod
SandPod requested a review from nielsenko October 24, 2025 08:10
@SandPod
SandPod merged commit 7086221 into main Oct 24, 2025
@SandPod
SandPod deleted the copilot/mask-bearer-token-in-tostring branch October 24, 2025 08:42
@nielsenko nielsenko mentioned this pull request Oct 27, 2025
8 of 9 tasks
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.

Security: Bearer tokens exposed in toString() methods

3 participants