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

feat: checksum extension #347

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
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
18 changes: 8 additions & 10 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
{
"presets": [
[
"@babel/preset-env",
{
"modules": false,
"corejs": false,
"forceAllTransforms": true
}
]
]
"presets": [
[ "@babel/preset-env", {
"modules": false,
"corejs": false,
"forceAllTransforms": true
} ]
],
"plugins": ["@babel/transform-runtime"]
Copy link
Member

Choose a reason for hiding this comment

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

Could you explain why this plugin is necessary?

}
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"editor.formatOnSaveMode": "modifications"
}
1 change: 1 addition & 0 deletions demos/browser/demo.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ function startUpload() {
endpoint,
chunkSize,
retryDelays: [0, 1000, 3000, 5000],
checksumAlgo: "SHA-256",
Copy link
Member

Choose a reason for hiding this comment

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

The tus protocol itself uses a naming conventional like sha1, so I would prefer if we could also use sha256 here.

parallelUploads,
metadata: {
filename: file.name,
Expand Down
37 changes: 37 additions & 0 deletions lib/browser/extensions/checksum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Checksum {
static supportedAlgorithms = ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512'];

constructor (algo = 'SHA-256') {
Copy link
Member

Choose a reason for hiding this comment

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

I don't think we need a default value here. If no algorithm or an unsupported one is supplied, we can just error out.

// Checking support for crypto on the browser
if (!crypto) {
throw new Error(`tus: this browser does not support checksum`)
} else if (!Checksum.supportedAlgorithms.includes(algo)) {
throw new Error(
`tus: unsupported checksumAlgo provided. Supported values are : ${Checksum.supportedAlgorithms.join(
',',
)}`,
)
} else {
this.algo = algo
}
}

/**
* Gets Hexadecimal digest using the algorithm set in this.algo
* @param {ArrayBuffer} data contains the chunk of data to be hashed
*/

getHexDigest = async (data) => {
try {
const hashBuffer = await crypto.subtle.digest(this.algo, data)
manohar27 marked this conversation as resolved.
Show resolved Hide resolved
const hashArray = Array.from(new Uint8Array(hashBuffer)) // convert buffer to byte array
const hashHex = hashArray
.map((b) => b.toString(16).padStart(2, '0'))
.join('') // convert bytes to hex string
return hashHex
} catch (err) {
throw new Error('tus: could not compute checksum for integrity check', err)
}
};
}
export default Checksum
3 changes: 3 additions & 0 deletions lib/browser/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import { canStoreURLs, WebStorageUrlStorage } from './urlStorage.js'
import DefaultHttpStack from './httpStack.js'
import FileReader from './fileReader.js'
import fingerprint from './fileSignature.js'
import Checksum from './extensions/checksum.js'

const defaultOptions = {
...BaseUpload.defaultOptions,
httpStack: new DefaultHttpStack(),
fileReader: new FileReader(),
urlStorage: canStoreURLs ? new WebStorageUrlStorage() : new NoopUrlStorage(),
fingerprint,
Checksum,
}

class Upload extends BaseUpload {
Expand All @@ -40,4 +42,5 @@ export {
enableDebugLog,
DefaultHttpStack,
DetailedError,
Checksum,
}
6 changes: 6 additions & 0 deletions lib/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,12 @@ interface UploadOptions {
removeFingerprintOnSuccess?: boolean
uploadLengthDeferred?: boolean
uploadDataDuringCreation?: boolean
checksumAlgo?: string

urlStorage?: UrlStorage
fileReader?: FileReader
httpStack?: HttpStack
checksum?: Checksum;
Copy link
Member

Choose a reason for hiding this comment

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

I would prefer a name that aligns with fileReader for the checksum as well. Maybe we can call this option checksumProvider and the classes also ChecksumGenerator.

"Digest" would also likely be a better fit than checksum, although the protocol specification does not use that term, unfortunately.

}

interface UrlStorage {
Expand Down Expand Up @@ -129,3 +131,7 @@ export class DetailedError extends Error {
originalResponse: HttpResponse
causingError: Error
}

export interface Checksum {
Copy link
Member

Choose a reason for hiding this comment

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

Once we have finalized the interface and options, we should also add documentation. But that can wait for now.

getHexDigest(): string;
Copy link
Member

Choose a reason for hiding this comment

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

The Upload-Checksum encodes the checksum in base64, instead of hexadecimal. So we need to adjust the interface itself as well as the implementations. I am also wondering if the checksum provider should just return a byte array and let the main tus-js-client logic take care of encoding it into the right format.

Copy link
Member

Choose a reason for hiding this comment

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

The inferface definition is also missing the data argument.

}
36 changes: 36 additions & 0 deletions lib/node/extensions/checksum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import crypto from 'crypto'

class Checksum {
static supportedAlgorithms = ['sha1', 'sha256', 'sha384', 'sha512', 'md5'];

constructor (algo = 'sha256') {
if (!Checksum.supportedAlgorithms.includes(algo)) {
throw new Error(
`Checksum: unsupported checksumAlgo provided. Supported values are ${Checksum.supportedAlgorithms.join(
',',
)}`,
)
} else {
this.algo = algo
}
}

/**
* Gets Hexadecimal digest using the algorithm set in this.algo
* @param {ArrayBuffer} data contains the chunk of data to be hashed
*/
getHexDigest = async (data) => {
try {
const hashHex = await crypto
.createHash(this.algo)
.update(data)
.digest('hex')

return hashHex
} catch (err) {
throw new Error('tus: could not compute checksum for integrity check')
}
};
}

export default Checksum
3 changes: 3 additions & 0 deletions lib/node/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ import DefaultHttpStack from './httpStack.js'
import FileReader from './fileReader.js'
import fingerprint from './fileSignature.js'
import StreamSource from './sources/StreamSource.js'
import Checksum from './extensions/checksum.js'

const defaultOptions = {
...BaseUpload.defaultOptions,
httpStack: new DefaultHttpStack(),
fileReader: new FileReader(),
urlStorage: new NoopUrlStorage(),
fingerprint,
Checksum,
}

class Upload extends BaseUpload {
Expand Down Expand Up @@ -47,4 +49,5 @@ export {
DefaultHttpStack,
DetailedError,
StreamSource,
Checksum,
}
36 changes: 31 additions & 5 deletions lib/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@ const defaultOptions = {
uploadLengthDeferred: false,
uploadDataDuringCreation: false,

urlStorage: null,
fileReader: null,
httpStack: null,
urlStorage : null,
fileReader : null,
httpStack : null,
checksumAlgo: null,
}

class BaseUpload {
Expand Down Expand Up @@ -102,6 +103,9 @@ class BaseUpload {
// An array of upload URLs which are used for uploading the different
// parts, if the parallelUploads option is used.
this._parallelUploadUrls = null

// A platform dependent checksum generator, this is instantiated if options.checksumAlgo is provided
this._checksum = null
}

/**
Expand Down Expand Up @@ -565,6 +569,9 @@ class BaseUpload {
return
}

if (this.options.checksumAlgo) {
this._checksum = new this.options.Checksum(this.options.checksumAlgo)
}
const req = this._openRequest('POST', this.options.endpoint)

if (this.options.uploadLengthDeferred) {
Expand Down Expand Up @@ -793,8 +800,27 @@ class BaseUpload {
if (value === null) {
return this._sendRequest(req)
}
this._emitProgress(this._offset, this._size)
return this._sendRequest(req, value)

if (this.options.checksumAlgo) {
if (this._checksum) {
value.arrayBuffer().then((chunkBuffer) => {
this._checksum
.getHexDigest(chunkBuffer)
.then((hash) => {
req.setHeader('Upload-Checksum', `${this._checksum.algo} ${hash}`)
this._emitProgress(this._offset, this._size)
return this._sendRequest(req, value)
})
.catch((err) => {
log(err)
throw err
Copy link
Member

Choose a reason for hiding this comment

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

For error handling, please use _emitError.

})
})
}
} else {
this._emitProgress(this._offset, this._size)
return this._sendRequest(req, value)
}
})
}

Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@
"@babel/helper-get-function-arity": "^7.16.7",
"@babel/plugin-syntax-jsx": "^7.12.13",
"@babel/plugin-transform-modules-commonjs": "^7.9.6",
"@babel/plugin-transform-runtime": "^7.17.0",
"@babel/preset-env": "^7.0.0",
"@babel/runtime": "^7.17.9",
"axios": "^0.27.2",
"babelify": "^10.0.0",
"browserify": "^17.0.0",
Expand Down
20 changes: 20 additions & 0 deletions test/spec/test-browser-specific.js
Original file line number Diff line number Diff line change
Expand Up @@ -787,4 +787,24 @@ describe('tus', () => {
await assertUrlStorage(tus.defaultOptions.urlStorage)
})
})

describe('#Checksum', () => {
Copy link
Member

Choose a reason for hiding this comment

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

We would also need a full test to ensure the checksum header is added to the actual requests. Such a test should be placed in test-common, which includes tests shared between browsers and Node.js.

Let me know if you need help with getting this running :)

it('should generate hex digest for a given chunk of file', async () => {
const checksum = new tus.Checksum()
const hexDigest = await checksum.getHexDigest(
new TextEncoder().encode('hello'),
)
expect(hexDigest).toBe(
'2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824',
)
})

it('should throw an error when an unsupported algo is provided', () => {
try {
const checksum = new tus.Checksum('md5')
} catch (err) {
expect(err.message).toContain('unsupported checksumAlgo')
}
})
})
})
16 changes: 16 additions & 0 deletions test/spec/test-node-specific.js
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,22 @@ describe('tus', () => {
})
})

describe('#Checksum', () => {
it('should generate hex digest for a given chunk of file', async () => {
const checksum = new tus.Checksum()
const hexDigest = await checksum.getHexDigest(Buffer.from('hello', 'utf8'))
expect(hexDigest).toBe('2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824')
})

it('should throw an error when an unsupported algo is provided', () => {
try {
const checksum = new tus.Checksum('new-algo')
} catch (err) {
expect(err.message).toContain('unsupported checksumAlgo')
}
})
})

describe('#StreamSource', () => {
it('should slice at different ranges', async () => {
const input = stream.Readable.from(Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), {
Expand Down