Skip to content

fix: verify CID hash before decoding in Block.create#340

Merged
rvagg merged 1 commit into
multiformats:masterfrom
tabcat:fix/verify-cid-hash-before-decode
Jun 24, 2026
Merged

fix: verify CID hash before decoding in Block.create#340
rvagg merged 1 commit into
multiformats:masterfrom
tabcat:fix/verify-cid-hash-before-decode

Conversation

@tabcat

@tabcat tabcat commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Block.create is the verifying block constructor, but it decoded bytes before checking they matched the CID, so the codec parser ran on unverified, potentially untrusted input.

This hashes and compares first, then delegates decoding to createUnsafe. Valid blocks are unchanged; bytes that don't match the CID are now rejected without ever being decoded, and such input always throws the hash-mismatch error rather than possibly a codec error first.

Adds a test asserting mismatched, codec-invalid bytes reject with the hash error (i.e. decode never runs).

Closes #339

Block.create is the verifying block constructor, but it decoded bytes
before checking they matched the CID, so the codec parser ran on
unverified, potentially untrusted input.

Hash and compare first, then delegate decoding to createUnsafe. Valid
blocks are unchanged; bytes that do not match the CID are now rejected
without ever being decoded, and such input always throws the hash
mismatch error rather than possibly a codec error first.

Adds a test asserting mismatched, codec-invalid bytes reject with the
hash error.

Closes multiformats#339

Signed-off-by: tabcat <tabcat00@proton.me>
Comment thread src/block.ts
@tabcat tabcat marked this pull request as ready for review June 23, 2026 11:06
Comment thread test/test-block.spec.ts
await assert.isRejected(main.create({ bytes: block.bytes, cid: block2.cid, codec, hasher }), 'CID hash does not match bytes')
})

it('create verifies the cid hash before decoding the bytes', async () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nice 👌

@rvagg rvagg merged commit 6784d3e into multiformats:master Jun 24, 2026
23 checks passed
github-actions Bot pushed a commit that referenced this pull request Jun 24, 2026
## [14.0.2](v14.0.1...v14.0.2) (2026-06-24)

### Bug Fixes

* verify CID hash before decoding in Block.create ([#340](#340)) ([6784d3e](6784d3e)), closes [#339](#339)
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 14.0.2 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Verify CID hash before decoding in Block.create

2 participants