Skip to content

Commit

Permalink
fix: error when calculating sha256 on big files (#1094)
Browse files Browse the repository at this point in the history
Signed-off-by: lstocchi <lstocchi@redhat.com>
  • Loading branch information
lstocchi committed May 16, 2024
1 parent 22928e0 commit fe447d6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
16 changes: 13 additions & 3 deletions packages/backend/src/utils/sha.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,22 @@
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/
import { beforeEach, expect, test, vi } from 'vitest';
import { promises } from 'node:fs';
import * as fs from 'node:fs';
import { hasValidSha } from './sha';
import { Readable } from 'node:stream';

beforeEach(() => {
vi.resetAllMocks();
});

test('return true if file has same hash of the expected one', () => {
vi.mock('node:fs');
vi.spyOn(promises, 'readFile').mockImplementation(() => Promise.resolve(Buffer.from('test')));

const readable = Readable.from('test');

vi.spyOn(fs, 'createReadStream').mockImplementation(() => {
return readable as fs.ReadStream;
});

// sha of test => 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
const isValid = hasValidSha('file', '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08');
Expand All @@ -34,7 +40,11 @@ test('return true if file has same hash of the expected one', () => {

test('return false if file has different hash of the expected one', () => {
vi.mock('node:fs');
vi.spyOn(promises, 'readFile').mockImplementation(() => Promise.resolve(Buffer.from('test')));
const readable = Readable.from('test');

vi.spyOn(fs, 'createReadStream').mockImplementation(() => {
return readable as fs.ReadStream;
});

// sha of test => 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
const isValid = hasValidSha('file', 'fakeSha');
Expand Down
7 changes: 4 additions & 3 deletions packages/backend/src/utils/sha.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/
import crypto from 'node:crypto';
import { promises } from 'node:fs';
import * as fs from 'node:fs';
import { promises } from 'node:stream';

export async function hasValidSha(filePath: string, expectedSha: string): Promise<boolean> {
const checkSum = crypto.createHash('sha256');
const readStream = await promises.readFile(filePath);
const input = fs.createReadStream(filePath);
await promises.pipeline(input, checkSum);

checkSum.update(readStream);
const actualSha = checkSum.digest('hex');
return actualSha === expectedSha;
}

0 comments on commit fe447d6

Please sign in to comment.