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

chore: test exception ci #707

Merged
merged 8 commits into from
Apr 3, 2024
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
41 changes: 40 additions & 1 deletion src/lib/helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@
// SPDX-FileCopyrightText: 2023-Present The Pepr Authors

import { Binding, CapabilityExport } from "./types";
import { createRBACMap, addVerbIfNotExists, checkOverlap, filterNoMatchReason } from "./helpers";
import {
createRBACMap,
addVerbIfNotExists,
checkOverlap,
filterNoMatchReason,
validateHash,
ValidationError,
} from "./helpers";
import { expect, describe, test, jest, beforeEach, afterEach } from "@jest/globals";
import { parseTimeout, secretOverLimit, replaceString } from "./helpers";
import { promises as fs } from "fs";
Expand Down Expand Up @@ -1107,3 +1114,35 @@ describe("filterMatcher", () => {
expect(result).toEqual("");
});
});

describe("validateHash", () => {
let originalExit: (code?: number) => never;

beforeEach(() => {
originalExit = process.exit;
process.exit = jest.fn() as unknown as (code?: number) => never;
});

afterEach(() => {
process.exit = originalExit;
});
test("should throw ValidationError for invalid hash values", () => {
// Examples of invalid hashes
const invalidHashes = [
"", // Empty string
"12345", // Too short
"zxcvbnmasdfghjklqwertyuiop1234567890zxcvbnmasdfghjklqwertyuio", // Contains invalid character 'z'
"123456789012345678901234567890123456789012345678901234567890123", // 63 characters, one short
];

invalidHashes.forEach(hash => {
expect(() => validateHash(hash)).toThrow(ValidationError);
});
});

test("should not throw ValidationError for valid SHA-256 hash", () => {
// Example of a valid SHA-256 hash
const validHash = "abc123def456abc123def456abc123def456abc123def456abc123def456abc1";
expect(() => validateHash(validHash)).not.toThrow();
});
});
11 changes: 11 additions & 0 deletions src/lib/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,17 @@ import { K8s, KubernetesObject, kind } from "kubernetes-fluent-client";
import Log from "./logger";
import { Binding, CapabilityExport } from "./types";

export class ValidationError extends Error {}

export function validateHash(expectedHash: string): void {
// Require the hash to be a valid SHA-256 hash (64 characters, hexadecimal)
const sha256Regex = /^[a-f0-9]{64}$/i;
if (!expectedHash || !sha256Regex.test(expectedHash)) {
Log.error(`Invalid hash. Expected a valid SHA-256 hash, got ${expectedHash}`);
throw new ValidationError("Invalid hash");
}
}

type RBACMap = {
[key: string]: {
verbs: string[];
Expand Down
36 changes: 16 additions & 20 deletions src/runtime/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,9 @@ import { K8s, kind } from "kubernetes-fluent-client";
import Log from "../lib/logger";
import { packageJSON } from "../templates/data.json";
import { peprStoreCRD } from "../lib/assets/store";

import { validateHash } from "../lib/helpers";
const { version } = packageJSON;

function validateHash(expectedHash: string) {
// Require the hash to be 64 characters long
if (!expectedHash || expectedHash.length !== 64) {
Log.error("Invalid hash");
process.exit(1);
}
}

function runModule(expectedHash: string) {
const gzPath = `/app/load/module-${expectedHash}.js.gz`;
const jsPath = `/app/module-${expectedHash}.js`;
Expand All @@ -31,8 +23,7 @@ function runModule(expectedHash: string) {

// Check if the path is a valid file
if (!fs.existsSync(gzPath)) {
Log.error(`File not found: ${gzPath}`);
process.exit(1);
throw new Error(`File not found: ${gzPath}`);
}

try {
Expand All @@ -46,9 +37,10 @@ function runModule(expectedHash: string) {
const actualHash = crypto.createHash("sha256").update(code).digest("hex");

// If the hash doesn't match, exit
if (expectedHash !== actualHash) {
Log.error(`File hash does not match, expected ${expectedHash} but got ${actualHash}`);
process.exit(1);
// This is a timing safe comparison to prevent timing attacks
// https://en.wikipedia.org/wiki/Timing_attack
if (!crypto.timingSafeEqual(Buffer.from(expectedHash, "hex"), Buffer.from(actualHash, "hex"))) {
throw new Error(`File hash does not match, expected ${expectedHash} but got ${actualHash}`);
}

Log.info(`File hash matches, running module`);
Expand All @@ -59,8 +51,7 @@ function runModule(expectedHash: string) {
// Run the module
fork(jsPath);
} catch (e) {
Log.error(`Failed to decompress module: ${e}`);
process.exit(1);
throw new Error(`Failed to decompress module: ${e}`);
}
}

Expand All @@ -69,11 +60,16 @@ Log.info(`Pepr Controller (v${version})`);
const hash = process.argv[2];

const startup = async () => {
Log.info("Applying the Pepr Store CRD if it doesn't exist");
await K8s(kind.CustomResourceDefinition).Apply(peprStoreCRD, { force: true });
try {
Log.info("Applying the Pepr Store CRD if it doesn't exist");
await K8s(kind.CustomResourceDefinition).Apply(peprStoreCRD, { force: true });

validateHash(hash);
runModule(hash);
validateHash(hash);
runModule(hash);
} catch (err) {
Log.error(err);
process.exit(1);
}
};

startup().catch(err => Log.error(err));
Loading