Skip to content

fix(pairing): reject malformed base64 padding - #12027

Closed
hsusul wants to merge 3 commits into
stablyai:mainfrom
hsusul:fix/pairing-code-padding-validation
Closed

hsusul wants to merge 3 commits into
stablyai:mainfrom
hsusul:fix/pairing-code-padding-validation

Conversation

@hsusul

@hsusul hsusul commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Summary

Problem

Orca's shared pairing parser accepted malformed Base64 padding in Node while rejecting the same pairing code in browser runtimes. A code formed by adding a single = to an unpadded payload that requires == was decoded by Node's permissive Buffer.from(..., 'base64'), while atob rejected it.

Before this fix, the regression test observed a decoded pairing offer from the Node path and null from the browser path for the identical malformed code.

Root cause

decodePairingBase64 validated the character set and allowed up to two trailing padding characters, but did not validate Base64 length and padding structure before dispatching to the runtime-specific decoder.

Solution

Reject:

  • unpadded inputs whose length has the impossible Base64 remainder of 1
  • padded inputs whose total length is not divisible by 4

Canonical padded and existing unpadded pairing codes remain accepted.

Screenshots

Not applicable; this is shared pairing-code validation with no visual change.

Testing checklist

  • Added a deterministic regression covering the Node Buffer and browser atob paths with the same malformed input.
  • Confirmed the regression failed before the production change: Node returned the offer while the browser path returned null.
  • Added a boundary test confirming canonical == padding remains accepted.
  • pnpm exec vitest run --config config/vitest.config.ts src/shared/pairing.test.ts — 1 file, 20 tests passed.
  • Related runtime-environment suite — 4 files, 78 tests passed.
  • pnpm run typecheck — passed for node, CLI, and web projects.
  • pnpm run lint — passed, including native, type-aware, reliability, max-lines, skill-manifest, and localization checks.
  • pnpm run build — passed, including desktop and macOS native targets. The build reported the existing non-fatal /usr/local/bin/orca-dev permission warning.
  • pnpm test — 4,052 files and 43,141 tests passed; 13 files and 81 tests skipped. One unrelated root-directory guard fixture file had 3 failures because macOS system Bash 3.2 does not support its declare -A associative array, causing the script to exit 2 before its assertions.
  • git diff --check upstream/main...HEAD — passed.

Compatibility and non-goals

The change is platform-neutral and makes shared parsing consistent across Node and browser runtimes. It does not alter pairing payloads, public APIs, authentication flows, shell invocation, filesystem paths, SSH/folder workspaces, Git behavior, providers, or IPC.

AI Review Report

Reviewed every changed line against upstream/main. The diff is limited to shared pairing validation and focused tests. Existing unpadded behavior and canonical padding are covered alongside the malformed-padding regression.

Security Audit

No new input source, command execution, interpolation, authentication flow, secret handling, IPC surface, or dependency is introduced. The parser now rejects malformed credential-bearing pairing payloads before runtime-specific decoding, eliminating a Node/browser validation discrepancy.

Notes

  • Bounded searches across open and closed issues and PRs for pairing Base64 padding, parsePairingCode, invalid pairing codes, and Node/browser decoder parity found no same-root-cause report.
  • Closed issue [Bug]: Mobile companion rejects QR / pairing code as invalid #4391 concerned mobile query-versus-fragment parsing. Open PR feat(mobile): tell Android users when their build is out of date #11825 concerns outdated mobile-version diagnostics and parser parity tests; neither changes shared Base64 padding validation.
  • Additional exact GitHub searches were limited by the search API rate limit; repository history, blame, and the successful issue/PR searches found no duplicate.
  • No issue was created because this focused fix has a deterministic regression and the contribution policy does not require a preceding issue.
  • X handle: not provided.

@coderabbitai

coderabbitai Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The pairing decoder now rejects Base64URL inputs with invalid padding length or a remainder of one modulo four. Mobile pairing parsing now applies the shared input-size limit to raw codes, URLs, and decoded URLs. Mobile decoding now uses the shared Base64 normalization helper. Tests cover malformed and canonical padding across runtimes.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: rejecting malformed Base64 padding in pairing codes.
Description check ✅ Passed The description covers the problem, root cause, solution, testing, compatibility, review, security, and notes with sufficient detail.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

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.

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

🧹 Nitpick comments (1)
src/shared/pairing.test.ts (1)

38-56: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the remainder-one branch.

This test covers the invalid padded-length branch at src/shared/pairing.ts Line 88. It does not directly exercise the new unpadded length check at src/shared/pairing.ts Line 87. Add a valid payload with an unpadded length divisible by four, append one Base64 character, and assert that parsePairingCode returns null.

Suggested boundary test
+  it('rejects unpadded Base64URL with length remainder one', () => {
+    const alignedOffer: PairingOffer = { ...offer, scope: 'mobile' }
+    const alignedUrl = encodePairingOffer(alignedOffer)
+    const alignedCode = new URLSearchParams(
+      alignedUrl.slice(alignedUrl.indexOf('?') + 1)
+    ).get('code')!
+    expect(alignedCode.length % 4).toBe(0)
+    expect(parsePairingCode(`${alignedCode}A`)).toBeNull()
+  })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8682d3d0-6ecf-49bc-ba53-dc20f28b0880

📥 Commits

Reviewing files that changed from the base of the PR and between 8fc892d and ce33961a6dfd61d74971e23ab7442d557d1393c4.

📒 Files selected for processing (2)
  • src/shared/pairing.test.ts
  • src/shared/pairing.ts

@greptile-apps

greptile-apps Bot commented Aug 2, 2026

Copy link
Copy Markdown

Greptile Summary

This PR fixes a Node/browser split in base64 padding validation: Node's Buffer.from(..., 'base64') silently decoded malformed padding that atob rejected, making the same pairing code succeed on one runtime and fail on the other. Two new length-based guards are added to decodePairingBase64 before any runtime-specific decoding occurs.

  • Adds length % 4 === 1 rejection — this remainder is structurally impossible in any valid base64 string (padded or unpadded).
  • Adds includes('=') && length % 4 !== 0 rejection — any padded base64 block must be divisible by 4 in total length; this catches e.g. an unpadded code that needs == but received only one =.
  • Adds two tests: a cross-runtime regression that stubs Buffer to force the browser code-path, and a boundary test confirming canonical == padding still decodes correctly.

Confidence Score: 4/5

Safe to merge; the production change is a targeted two-line guard that makes validation stricter and consistent across runtimes, with no API surface changes.

The two new guards in decodePairingBase64 are logically correct and close a real cross-runtime inconsistency. The only concern is in the tests: both new cases implicitly depend on the specific offer fixture producing a base64url code whose length mod 4 equals 2, without asserting that invariant. If the offer structure changes, both tests could fail with misleading messages, or the malformed-padding test could silently assert valid input should be rejected.

Files Needing Attention: src/shared/pairing.test.ts — the two new tests rely on an unstated length-modulo property of the offer fixture.

Important Files Changed

Filename Overview
src/shared/pairing.ts Adds two structurally sound pre-validation guards to decodePairingBase64: rejects length % 4 == 1 (impossible in any valid base64) and rejects padded inputs (contains '=') whose total length isn't divisible by 4. Both conditions are checked before the existing regex, consistently closing the Node-permissive/browser-strict gap.
src/shared/pairing.test.ts Adds a cross-runtime malformed-padding regression and a canonical-padding acceptance test. Both tests silently depend on the specific offer fixture serializing to a JSON length whose mod-3 remainder is 1, producing code.length % 4 == 2; this invariant is not explicitly asserted, making future offer-structure changes potentially produce misleading test failures.

Reviews (1): Last reviewed commit: "fix(pairing): reject malformed base64 pa..." | Re-trigger Greptile

Comment on lines +38 to +63
it('rejects malformed padding consistently across Node and browser runtimes', () => {
const url = encodePairingOffer(offer)
const code = new URLSearchParams(url.slice(url.indexOf('?') + 1)).get('code')!
const malformedCode = `${code}=`
const nodeDecoded = parsePairingCode(malformedCode)
const nodeBuffer = Buffer
let browserDecoded: PairingOffer | null = null
try {
vi.stubGlobal('Buffer', undefined)
browserDecoded = parsePairingCode(malformedCode)
} finally {
vi.stubGlobal('Buffer', nodeBuffer)
}

expect({ nodeDecoded, browserDecoded }).toEqual({
nodeDecoded: null,
browserDecoded: null
})
})

it('accepts canonical base64 padding', () => {
const url = encodePairingOffer(offer)
const code = new URLSearchParams(url.slice(url.indexOf('?') + 1)).get('code')!

expect(parsePairingCode(`${code}==`)).toEqual(offer)
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Both new tests rely on an unasserted offer length property

Both tests work correctly for the current offer fixture (whose JSON serializes to 169 bytes, producing a base64url code of length 226, so code.length % 4 == 2). However, neither test asserts or documents this dependency:

  • In rejects malformed padding: code + "=" is only malformed when code.length % 4 ∈ {0, 2}. When code.length % 4 == 3, appending = produces valid canonical padded base64 — parsePairingCode would return the offer, not null, and the assertion would fail for the wrong reason.
  • In accepts canonical base64 padding: code + "==" only has length % 4 == 0 (and therefore passes the new guard) when code.length % 4 == 2. Any other remainder causes the new padding guard to reject it, making the test fail regardless of whether the production code is correct.

If the offer gains a new required field or the PairingOfferSchema changes the serialization, both tests could produce confusing failures. Adding a short assertion like expect(code.length % 4).toBe(2) with a clarifying comment would pin the implicit invariant and make future failures self-explanatory.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 74a1d1a and 2b17595: every padding test now asserts code.length % 4 === 2 before appending =/==, so a fixture change fails loudly at the invariant instead of at the padding assertion.

@Jinwoo-H
Jinwoo-H force-pushed the fix/pairing-code-padding-validation branch from ce33961 to 2b17595 Compare August 4, 2026 12:32

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

🧹 Nitpick comments (1)
mobile/src/transport/pairing.test.ts (1)

67-77: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover the oversized URL through parsePairingCode.

parsePairingCode has its own early length check in mobile/src/transport/pairing.ts Lines 61-63. This test covers that check only with oversizedRawCode. Add the URL assertion to protect the public entry point.

Proposed assertion
     expect(parsePairingCode(oversizedRawCode)).toBeNull()
+    expect(parsePairingCode(oversizedUrl)).toBeNull()
     expect(extractPairingCodeFromUrl(oversizedUrl)).toBeNull()

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bc9a66d0-6402-461f-9b45-65077b1e779c

📥 Commits

Reviewing files that changed from the base of the PR and between ce33961a6dfd61d74971e23ab7442d557d1393c4 and 2b17595.

📒 Files selected for processing (2)
  • mobile/src/transport/pairing.test.ts
  • mobile/src/transport/pairing.ts

@nwparker nwparker removed the P1 label Aug 19, 2026
@nwparker

Copy link
Copy Markdown
Contributor

I am working through this pairing inconsistency as part of mobile bug batch 3. I will review and adapt this contribution with co-author credit, exercise the desktop/mobile decoders and pairing UI, and link the follow-up PR here.

@nwparker

Copy link
Copy Markdown
Contributor

Follow-up implementation: #31465. Adapted and credited Henry Su and OrcaWin in the commit. Regression tests reproduce the decoder mismatch; 55 desktop/web/normalizer and 11 mobile tests pass, and real simslim iOS WKWebView before/after screenshots are attached with the fixture limitations described.

nwparker added a commit that referenced this pull request Oct 21, 2026
Adapt the community decoder normalization and input bounds from #12027 for current desktop, browser and mobile pairing paths.

Co-authored-by: Henry Su <[email protected]>
Co-authored-by: OrcaWin <[email protected]>
nwparker added a commit that referenced this pull request Oct 21, 2026
Normalize bounded Base64 input consistently across desktop, browser, and mobile pairing paths while preserving lossless legacy padding and trailing-bit spellings. Retain offer validation and authentication behavior.

Adapted from #12027. Compatibility verified across 378 spellings with no previously accepted inputs lost; full PR workflow and aggregate gate passed for a84dfae.

Co-authored-by: Henry Su <[email protected]>
Co-authored-by: OrcaWin <[email protected]>
@nwparker

Copy link
Copy Markdown
Contributor

Superseded by merged #31465. Thank you @hsusul and @OrcaWin for the original pairing normalization/input-bounds work; both contributors are credited in the replacement and its squash commit.

The merged normalizer preserves lossless historical padding and trailing-bit spellings, with 378 before/after compatibility cases across desktop, browser, mobile, and web parser paths and no previously accepted input lost in that matrix.

@nwparker nwparker closed this Oct 21, 2026
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.

4 participants