Skip to content
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

fix: Do not blow up if the opts object is mutated #4

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 40 additions & 0 deletions README.md
Expand Up @@ -19,6 +19,7 @@ Integrity](https://w3c.github.io/webappsec/specs/subresourceintegrity/) hashes.
* [`parse`](#parse)
* [`stringify`](#stringify)
* [`Integrity#concat`](#integrity-concat)
* [`Integrity#merge`](#integrity-merge)
* [`Integrity#toString`](#integrity-to-string)
* [`Integrity#toJSON`](#integrity-to-json)
* [`Integrity#match`](#integrity-match)
Expand Down Expand Up @@ -184,6 +185,45 @@ const mobileIntegrity = ssri.fromData(fs.readFileSync('./index.mobile.js'))
desktopIntegrity.concat(mobileIntegrity)
```

#### <a name="integrity-merge"></a> `> Integrity#merge(otherIntegrity, [opts])`

Safely merges another IntegrityLike or integrity string into an `Integrity`
object.

If the other integrity value has any algorithms in common with the current
object, then the hash digests must match, or an error is thrown.

Any new hashes will be added to the current object's set.

This is useful when an integrity value may be upgraded with a stronger
algorithm, you wish to prevent accidentally supressing integrity errors by
overwriting the expected integrity value.

##### Example

```javascript
const data = fs.readFileSync('data.txt')

// integrity.txt contains 'sha1-X1UT+IIv2+UUWvM7ZNjZcNz5XG4='
// because we were young, and didn't realize sha1 would not last
const expectedIntegrity = ssri.parse(fs.readFileSync('integrity.txt', 'utf8'))
const match = ssri.checkData(data, expectedIntegrity, {
algorithms: ['sha512', 'sha1']
})
if (!match) {
throw new Error('data corrupted or something!')
}

// get a stronger algo!
if (match && match.algorithm !== 'sha512') {
const updatedIntegrity = ssri.fromData(data, { algorithms: ['sha512'] })
expectedIntegrity.merge(updatedIntegrity)
fs.writeFileSync('integrity.txt', expectedIntegrity.toString())
// file now contains
// 'sha1-X1UT+IIv2+UUWvM7ZNjZcNz5XG4= sha512-yzd8ELD1piyANiWnmdnpCL5F52f10UfUdEkHywVZeqTt0ymgrxR63Qz0GB7TKPoeeZQmWCaz7T1+9vBnypkYWg=='
}
```

#### <a name="integrity-to-string"></a> `> Integrity#toString([opts]) -> String`

Returns the string representation of an `Integrity` object. All hash entries
Expand Down
78 changes: 52 additions & 26 deletions index.js
Expand Up @@ -23,26 +23,40 @@ const SsriOpts = figgyPudding({
strict: { default: false }
})

const getOptString = options => !options || !options.length ? ''
: `?${options.join('?')}`

const _onEnd = Symbol('_onEnd')
const _getOptions = Symbol('_getOptions')
class IntegrityStream extends MiniPass {
constructor (opts) {
super()
this.size = 0
this.opts = opts
mikemimik marked this conversation as resolved.
Show resolved Hide resolved
// For verification
this.sri = opts.integrity && parse(opts.integrity, opts)
this.goodSri = this.sri && Object.keys(this.sri).length
this.algorithm = this.goodSri && this.sri.pickAlgorithm(opts)
this.digests = this.goodSri && this.sri[this.algorithm]
// Calculating stream

// may be overridden later, but set now for class consistency
this[_getOptions]()

// options used for calculating stream. can't be changed.
this.algorithms = Array.from(
new Set(opts.algorithms.concat(this.algorithm ? [this.algorithm] : []))
)
this.hashes = this.algorithms.map(crypto.createHash)
this.onEnd = this.onEnd.bind(this)
}

[_getOptions] () {
const opts = this.opts
// For verification
this.sri = opts.integrity && parse(opts.integrity, opts)
mikemimik marked this conversation as resolved.
Show resolved Hide resolved
this.expectedSize = opts.size
this.goodSri = this.sri ? Object.keys(this.sri).length || null : null
mikemimik marked this conversation as resolved.
Show resolved Hide resolved
this.algorithm = this.goodSri ? this.sri.pickAlgorithm(opts) : null
this.digests = this.goodSri ? this.sri[this.algorithm] : null
this.optString = getOptString(opts.options)
}

emit (ev, data) {
if (ev === 'end') this.onEnd()
if (ev === 'end') this[_onEnd]()
return super.emit(ev, data)
}

Expand All @@ -52,23 +66,23 @@ class IntegrityStream extends MiniPass {
return super.write(data)
}

onEnd () {
const optString = (this.opts.options && this.opts.options.length)
? `?${this.opts.options.join('?')}`
: ''
[_onEnd] () {
if (!this.goodSri) {
this[_getOptions]()
}
const newSri = parse(this.hashes.map((h, i) => {
return `${this.algorithms[i]}-${h.digest('base64')}${optString}`
return `${this.algorithms[i]}-${h.digest('base64')}${this.optString}`
}).join(' '), this.opts)
// Integrity verification mode
const match = this.goodSri && newSri.match(this.sri, this.opts)
if (typeof this.opts.size === 'number' && this.size !== this.opts.size) {
const err = new Error(`stream size mismatch when checking ${this.sri}.\n Wanted: ${this.opts.size}\n Found: ${this.size}`)
if (typeof this.expectedSize === 'number' && this.size !== this.expectedSize) {
const err = new Error(`stream size mismatch when checking ${this.sri}.\n Wanted: ${this.expectedSize}\n Found: ${this.size}`)
err.code = 'EBADSIZE'
err.found = this.size
err.expected = this.opts.size
err.expected = this.expectedSize
err.sri = this.sri
this.emit('error', err)
} else if (this.opts.integrity && !match) {
} else if (this.sri && !match) {
const err = new Error(`${this.sri} integrity checksum failed when using ${this.algorithm}: wanted ${this.digests} but got ${newSri}. (${this.size} bytes)`)
err.code = 'EINTEGRITY'
err.found = newSri
Expand Down Expand Up @@ -184,6 +198,24 @@ class Integrity {
return parse(this, { single: true }).hexDigest()
}

// add additional hashes to an integrity value, but prevent
// *changing* an existing integrity hash.
merge (integrity, opts) {
opts = SsriOpts(opts)
const other = parse(integrity, opts)
for (const algo in other) {
if (this[algo]) {
if (!this[algo].find(hash =>
other[algo].find(otherhash =>
hash.digest === otherhash.digest))) {
throw new Error('hashes do not match, cannot update integrity')
}
} else {
this[algo] = other[algo]
}
}
}

match (integrity, opts) {
opts = SsriOpts(opts)
const other = parse(integrity, opts)
Expand Down Expand Up @@ -260,9 +292,7 @@ function stringify (obj, opts) {
module.exports.fromHex = fromHex
function fromHex (hexDigest, algorithm, opts) {
opts = SsriOpts(opts)
const optString = opts.options && opts.options.length
? `?${opts.options.join('?')}`
: ''
const optString = getOptString(opts.options)
return parse(
`${algorithm}-${
Buffer.from(hexDigest, 'hex').toString('base64')
Expand All @@ -274,9 +304,7 @@ module.exports.fromData = fromData
function fromData (data, opts) {
opts = SsriOpts(opts)
const algorithms = opts.algorithms
const optString = opts.options && opts.options.length
? `?${opts.options.join('?')}`
: ''
const optString = getOptString(opts.options)
return algorithms.reduce((acc, algo) => {
const digest = crypto.createHash(algo).update(data).digest('base64')
const hash = new Hash(
Expand Down Expand Up @@ -375,9 +403,7 @@ module.exports.create = createIntegrity
function createIntegrity (opts) {
opts = SsriOpts(opts)
const algorithms = opts.algorithms
const optString = opts.options.length
? `?${opts.options.join('?')}`
: ''
const optString = getOptString(opts.options)

const hashes = algorithms.map(crypto.createHash)

Expand Down