Skip to content

Commit

Permalink
Implement matchRequestIntegrity
Browse files Browse the repository at this point in the history
  • Loading branch information
jelmervdl committed Aug 10, 2022
1 parent 741edf7 commit 1d66bc7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
26 changes: 24 additions & 2 deletions lib/fetch/index.js
Expand Up @@ -721,7 +721,9 @@ async function mainFetch (fetchParams, recursive = false) {
}

// 3. Let processBody given bytes be these steps:
const processBody = (bytes) => {
const processBody = async (response) => {
const bytes = await readBodyToArrayBuffer(response)

// 1. If bytes do not match request’s integrity metadata,
// then run processBodyError and abort these steps. [SRI]
if (!matchRequestIntegrity(request, bytes)) {
Expand All @@ -739,7 +741,7 @@ async function mainFetch (fetchParams, recursive = false) {

// 4. Fully read response’s body given processBody and processBodyError.
try {
processBody(await response.arrayBuffer())
processBody(response)
} catch (err) {
processBodyError(err)
}
Expand All @@ -749,6 +751,26 @@ async function mainFetch (fetchParams, recursive = false) {
}
}

async function readBodyToArrayBuffer (response) {
const size = parseInt(response.headersList.get('content-length'))
const bytes = new Uint8Array(size)

const reader = response.body.stream.getReader()
let offset = 0

while (true) {
const { done, value } = await reader.read()
if (done) {
break
} else {
bytes.set(value, offset)
offset += value.length
}
}

return bytes
}

// https://fetch.spec.whatwg.org/#concept-scheme-fetch
// given a fetch params fetchParams
async function schemeFetch (fetchParams) {
Expand Down
4 changes: 3 additions & 1 deletion lib/fetch/util.js
Expand Up @@ -4,6 +4,7 @@ const { redirectStatus } = require('./constants')
const { performance } = require('perf_hooks')
const { isBlobLike, toUSVString, ReadableStreamFrom } = require('../core/util')
const assert = require('assert')
const { createHash } = require('crypto')

let File

Expand Down Expand Up @@ -340,7 +341,8 @@ function determineRequestsReferrer (request) {
}

function matchRequestIntegrity (request, bytes) {
return false
const [algo, expectedHashValue] = request.integrity.split('-', 2)
return createHash(algo).update(bytes).digest('hex') === expectedHashValue
}

// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
Expand Down

0 comments on commit 1d66bc7

Please sign in to comment.