Skip to content

fix(auth): keep the full length difference in ApiKey::matches - #6

Merged
renshao merged 1 commit into
mainfrom
fix/auth-apikey-length-truncation
Sep 13, 2026
Merged

renshao merged 1 commit into
mainfrom
fix/auth-apikey-length-truncation

Conversation

@renshao

@renshao renshao commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator

Fixes #4.

The bug

ApiKey::matches narrowed the length difference to u8, so it became zero whenever the lengths differed by a multiple of 256. Because the loop indexes both inputs modulo their lengths, the key repeated that many times then matched on every byte. A generated 64-byte key sent five or nine times over authenticated.

The existing test only tried one repeat (abcdefabcdef). A length difference of 6 does not fold to zero, so the test passed.

The fix

  • The difference stays a full usize, and each byte's XOR is widened into it with usize::from.
  • The loop still reads every byte of the longer input, so the comparison takes the same time whether the key is right or wrong.

Tests

  • New test a_repeated_key_does_not_match_at_any_length: a generated key repeated 2 to 9 times, and "ab" repeated 129 times (258 bytes).
  • Checked against the old code: the test fails there with key x5 matched, and passes with the fix.
  • cargo test --workspace, cargo clippy --workspace --all-targets and cargo fmt are all clean.

🤖 Generated with Claude Code

https://claude.ai/code/session_01VhxjRgZo4zeCeNA8rZXp7v

The length difference was narrowed to u8, so it folded to zero whenever the
two lengths differed by a multiple of 256. The modulo indexing then let the
key repeated that many times match on every byte: a generated 64-byte key
presented five or nine times over authenticated.

Keep the difference as a usize and widen each byte's XOR into it. The loop
still reads every byte of the longer input, so the timing is unchanged.

Fixes #4

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VhxjRgZo4zeCeNA8rZXp7v
@renshao
renshao merged commit b53b0d2 into main Sep 13, 2026
1 check passed
@renshao
renshao deleted the fix/auth-apikey-length-truncation branch September 13, 2026 09:15
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.

ApiKey::matches accepts the key repeated (length difference truncated to u8)

1 participant