Skip to content

fix: limit incoming hamt width #433

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/ipfs-unixfs/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,14 @@ export class InvalidTypeError extends Error {
super(message)
}
}

export class InvalidUnixFSMessageError extends Error {
static name = 'InvalidUnixFSMessageError'
static code = 'ERR_INVALID_MESSAGE'
name = InvalidUnixFSMessageError.name
code = InvalidUnixFSMessageError.code

constructor (message = 'Invalid message') {
super(message)
}
}
9 changes: 8 additions & 1 deletion packages/ipfs-unixfs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@
* ```
*/

import { InvalidTypeError } from './errors.js'
import { InvalidTypeError, InvalidUnixFSMessageError } from './errors.js'
import { Data as PBData } from './unixfs.js'

export interface Mtime {
Expand All @@ -117,6 +117,9 @@ const dirTypes = [
const DEFAULT_FILE_MODE = parseInt('0644', 8)
const DEFAULT_DIRECTORY_MODE = parseInt('0755', 8)

// https://github.com/ipfs/boxo/blob/364c5040ec91ec8e2a61446e9921e9225704c34d/ipld/unixfs/hamt/hamt.go#L778
const MAX_FANOUT = BigInt(1 << 10)

export interface UnixFSOptions {
type?: string
data?: Uint8Array
Expand All @@ -134,6 +137,10 @@ class UnixFS {
static unmarshal (marshaled: Uint8Array): UnixFS {
const message = PBData.decode(marshaled)

if (message.fanout != null && message.fanout > MAX_FANOUT) {
throw new InvalidUnixFSMessageError(`Fanout size was too large - ${message.fanout} > ${MAX_FANOUT}`)
}

const data = new UnixFS({
type: types[message.Type != null ? message.Type.toString() : 'File'],
data: message.Data,
Expand Down
13 changes: 13 additions & 0 deletions packages/ipfs-unixfs/test/unixfs-format.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,4 +431,17 @@ describe('unixfs-format', () => {

expect(marshaled).to.deep.equal(Uint8Array.from([0x08, 0x02, 0x18, 0x00]))
})

it('should limit maximum fanout size', () => {
const data = new UnixFS({
type: 'hamt-sharded-directory',
fanout: 1025n
})
const marshaled = data.marshal()

expect(() => {
UnixFS.unmarshal(marshaled)
}).to.throw()
.with.property('name', 'InvalidUnixFSMessageError')
})
})