Skip to content

🐛 protect encoded dots in keys during decoding when decodeDotInKeys is false#36

Closed
techouse wants to merge 3 commits intomainfrom
fix/decode-dot-in-keys-minimal
Closed

🐛 protect encoded dots in keys during decoding when decodeDotInKeys is false#36
techouse wants to merge 3 commits intomainfrom
fix/decode-dot-in-keys-minimal

Conversation

@techouse
Copy link
Owner

This pull request updates the decoding logic in the extension _$Decode on QS within lib/src/extensions/decode.dart to improve how percent-encoded dots (%2E/%2e) are handled in query string keys, particularly when dot splitting is enabled but decoding of dots in keys is not desired. The main change protects encoded dots from being prematurely interpreted as key separators, ensuring more accurate parsing.

Key improvements to query string key decoding:

  • Added logic to detect %2E/%2e in keys and replace them with %252E/%252e when allowDots is true and decodeDotInKeys is false, preventing accidental dot splitting during decoding.
  • Applied this protection both for bare keys and for keys with values (i.e., before the = sign), ensuring consistent behavior in all parsing scenarios.

@techouse techouse self-assigned this Aug 20, 2025
@techouse techouse added the bug Something isn't working label Aug 20, 2025
@coderabbitai
Copy link

coderabbitai bot commented Aug 20, 2025

Important

Review skipped

Draft detected.

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.

Walkthrough

Guards percent-decoding of keys in query-string parsing so encoded dots (%2E/%2e) aren't treated as separators when dot-splitting is enabled but decodeDotInKeys is disabled; expands dot-decoding to recognise both %2E and %2e and enables dot-notation when either allowDots or decodeDotInKeys is set. No public API changes.

Changes

Cohort / File(s) Summary
Decode key guarding & dot-handling
lib/src/extensions/decode.dart
Adds guarded keyInput used before percent-decoding to rewrite %2E/%2e%252E/%252e when allowDots && !decodeDotInKeys, applied to bare keys and pre-'=' slices. _splitKeyIntoSegments now treats `allowDots = options.allowDots

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client as Input (query string)
  participant Parser as _parseQueryStringValues
  participant Guard as KeyGuard (escape %2E/%2e → %252E/%252e)
  participant Decoder as Percent Decoder
  participant Splitter as _splitKeyIntoSegments
  participant Builder as _parseObject / Result Map

  Client->>Parser: part ("a.b=value" / "a%2E b=value" / "bareKey")
  alt key is bare
    Parser->>Guard: keyInput = entire part
  else contains '='
    Parser->>Guard: keyInput = part.slice(0,pos)
  end
  alt allowDots && !decodeDotInKeys && keyInput contains "%2"
    Guard->>Decoder: guarded keyInput (escaped %2E/%2e)
  else
    Guard->>Decoder: keyInput
  end
  Decoder-->>Parser: decodedKey
  Parser->>Splitter: split using (allowDots || decodeDotInKeys)
  Splitter-->>Builder: segments (dots/brackets)
  Parser->>Builder: assign value into result map
  Builder-->>Client: final params map
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

A rabbit in code with a carrot and key,
I guard tiny dots from decoding spree.
Upper or lower — %2E I see,
Wrapped and safe, then split with glee.
Hop on the map — neat params for tea 🥕🐇

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/decode-dot-in-keys-minimal

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codacy-production
Copy link

codacy-production bot commented Aug 20, 2025

Coverage summary from Codacy

See diff coverage on Codacy

Coverage variation Diff coverage
-0.09% (target: -1.00%) 87.50%
Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (fb620c5) 815 777 95.34%
Head commit (e2b734d) 820 (+5) 781 (+4) 95.24% (-0.09%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#36) 8 7 87.50%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

See your quality gate settings    Change summary preferences

@codecov
Copy link

codecov bot commented Aug 20, 2025

Codecov Report

❌ Patch coverage is 87.50000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 95.24%. Comparing base (fb620c5) to head (e2b734d).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
lib/src/extensions/decode.dart 87.50% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #36      +/-   ##
==========================================
- Coverage   95.33%   95.24%   -0.10%     
==========================================
  Files          14       14              
  Lines         815      820       +5     
==========================================
+ Hits          777      781       +4     
- Misses         38       39       +1     

☔ 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@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: 0

🧹 Nitpick comments (2)
lib/src/extensions/decode.dart (2)

150-158: Correctly preserves encoded dots in bare keys; consider extracting a small helper to deduplicate

The guarding logic is sound and matches the stated intent: by double-encoding %2E/%2e in the key before decoding, the dot never appears as a literal and won’t be dot-split. This is exactly what we want when allowDots && !decodeDotInKeys.

To reduce duplication and make the intent reusable, consider extracting the guard into a tiny helper and calling it from both key paths.

Apply this diff within this block:

-        String keyInput = part;
-        if (options.allowDots &&
-            !options.decodeDotInKeys &&
-            keyInput.contains('%2')) {
-          keyInput =
-              keyInput.replaceAll('%2E', '%252E').replaceAll('%2e', '%252e');
-        }
-        key = options.decoder(keyInput, charset: charset);
+        final String keyInput = _guardEncodedDotsInKey(part, options);
+        key = options.decoder(keyInput, charset: charset);

And add this helper (inside the same extension is fine):

static String _guardEncodedDotsInKey(String s, DecodeOptions options) {
  if (options.allowDots && !options.decodeDotInKeys && s.contains('%2')) {
    // Case-insensitive replace: %2E / %2e → %252E (so a single decode yields %2E)
    return s.replaceAll(RegExp(r'%2e', caseSensitive: false), '%252E');
  }
  return s;
}

Also, tiny nit: the top-of-file implementation note still claims “No behavioural changes are introduced here; comments only.” That line is now outdated; consider amending it.


161-170: Same protection for key= pairs; unify via the helper for consistency

This mirrors the bare-key case and is correct: values remain unaffected, only the key slice is guarded. For consistency and readability, reuse the same helper here.

Apply this diff within this block:

-        String keyInput = part.slice(0, pos);
-        if (options.allowDots &&
-            !options.decodeDotInKeys &&
-            keyInput.contains('%2')) {
-          keyInput =
-              keyInput.replaceAll('%2E', '%252E').replaceAll('%2e', '%252e');
-        }
-        key = options.decoder(keyInput, charset: charset);
+        final String keyInput = _guardEncodedDotsInKey(part.slice(0, pos), options);
+        key = options.decoder(keyInput, charset: charset);

If a custom options.decoder is ever supplied that repeatedly decodes until no percent-escapes remain (nonstandard), this guard would be bypassed. The default single-pass behaviour is expected; if you support custom decoders, it’s worth documenting that they should only perform a single decode pass.

Would you like me to add unit tests for:

  • bare key: a%2Eb with allowDots=true, decodeDotInKeys=false → key remains a%2Eb
  • key=value: a%2Eb=c with the same options
  • control cases where decodeDotInKeys=true (encoded dot should participate in dot splitting)
  • mixed-case %2E/%2e?
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between fb620c5 and 4bb15d3.

📒 Files selected for processing (1)
  • lib/src/extensions/decode.dart (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis

Copy link

@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: 0

🧹 Nitpick comments (3)
lib/src/extensions/decode.dart (3)

150-159: Good, targeted protection of encoded dots before decoding; consider deduping into a helper.

The approach of re-encoding %2E/%2e to %252E/%252e when allowDots is true and decodeDotInKeys is false correctly prevents premature dot-splitting. The same logic appears again below for the key=value path — factoring it into a small helper will reduce duplication and keep the behaviour consistent.

Apply this diff locally to reuse a helper:

-        // Protect %2E/%2e in keys so dot-splitting doesn’t see them unless decodeDotInKeys is true.
-        String keyInput = part;
-        if (options.allowDots &&
-            !options.decodeDotInKeys &&
-            keyInput.contains('%2')) {
-          keyInput =
-              keyInput.replaceAll('%2E', '%252E').replaceAll('%2e', '%252e');
-        }
-        key = options.decoder(keyInput, charset: charset);
+        // Protect %2E/%2e in keys so dot-splitting doesn’t see them unless decodeDotInKeys is true.
+        final String keyInput = _protectEncodedDotsInKey(part, options);
+        key = options.decoder(keyInput, charset: charset);

And add this helper inside the same extension (for example, near the bottom of the file):

static String _protectEncodedDotsInKey(String input, DecodeOptions options) {
  if (options.allowDots && !options.decodeDotInKeys && input.contains('%2')) {
    // Re-encode '%' of '%2E' -> '%25', so the decoder yields '%2E' (not '.').
    return input.replaceAll('%2E', '%252E').replaceAll('%2e', '%252e');
  }
  return input;
}

Also consider adding tests that cover:

  • allowDots=true, decodeDotInKeys=false with keys: a%2Eb, a%2eb (should not split on '.').
  • allowDots=true, decodeDotInKeys=true with the same keys (should decode to dots and then split).
  • Keys that already contain %252E to ensure no double protection occurs.

161-170: Mirror the same protection via a shared helper to avoid drift between branches.

This duplicates the protection logic from the bare-key path. Using a shared helper keeps behaviour identical and easier to maintain.

Apply this diff:

-        // Protect %2E/%2e in the key slice only; values decode normally.
-        String keyInput = part.slice(0, pos);
-        if (options.allowDots &&
-            !options.decodeDotInKeys &&
-            keyInput.contains('%2')) {
-          keyInput =
-              keyInput.replaceAll('%2E', '%252E').replaceAll('%2e', '%252e');
-        }
-        key = options.decoder(keyInput, charset: charset);
+        // Protect %2E/%2e in the key slice only; values decode normally.
+        final String keyInput = _protectEncodedDotsInKey(part.slice(0, pos), options);
+        key = options.decoder(keyInput, charset: charset);

If you adopt the helper, ensure the corresponding tests also cover key=value pairs, not just bare keys (e.g., a%2Eb=1).


319-319: Potential behaviour change: dot-notation now enabled when decodeDotInKeys is true — confirm intent.

Using allowDots: options.allowDots || options.decodeDotInKeys means that plain dots (e.g., a.b) will now be treated as separators even when allowDots is false, as long as decodeDotInKeys is true. This broadens the scope of dot-splitting and may break existing callers that wanted only percent-encoded dots to be treated specially, but not plain dots.

  • If this is intentional, please:

    • Document that decodeDotInKeys also enables dot-notation splitting.
    • Add tests that assert:
      • allowDots=false, decodeDotInKeys=true: a.b=1{'a': {'b': '1'}}.
      • allowDots=false, decodeDotInKeys=true: a%2Eb=1{'a': {'b': '1'}}.
      • allowDots=false, decodeDotInKeys=false: a.b=1 remains a single key a.b.
  • If this is not desired, consider reverting to the previous behaviour:

-      allowDots: options.allowDots || options.decodeDotInKeys,
+      allowDots: options.allowDots,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4bb15d3 and f674ad7.

📒 Files selected for processing (1)
  • lib/src/extensions/decode.dart (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (1)
lib/src/extensions/decode.dart (1)

275-277: Case-insensitive %2E decoding is a nice improvement.

Decoding both %2E and %2e when decodeDotInKeys is enabled removes a subtle edge case and aligns expectations.

@techouse techouse marked this pull request as draft August 20, 2025 06:25
@techouse techouse closed this Aug 20, 2025
@techouse techouse deleted the fix/decode-dot-in-keys-minimal branch August 20, 2025 06:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant