mirror of
https://github.com/step-security/harden-runner
synced 2026-08-09 13:11:02 +00:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1188420976 | ||
|
|
162cfeac17 | ||
|
|
eb9e1f4943 | ||
|
|
1a10b01783 | ||
|
|
8b4a105ef5 | ||
|
|
3626e03277 | ||
|
|
100e08b39c | ||
|
|
774f75f2c6 | ||
|
|
f312657a64 | ||
|
|
0c7c518e1e | ||
|
|
49e6c282a3 | ||
|
|
9af89fc715 | ||
|
|
485dce8cb5 | ||
|
|
ab7a9404c0 | ||
|
|
ec41b783c2 | ||
|
|
9ca718d3bf | ||
|
|
1dee3df8d2 | ||
|
|
a5ad31d6a1 | ||
|
|
6e928567d7 | ||
|
|
4e0504ee08 | ||
|
|
8d3c67de8e | ||
|
|
376d25a97f |
Vendored
+30
-17
@@ -31913,6 +31913,21 @@ function isAgentInstalled(platform) {
|
||||
function shouldDeployAgentOnSelfHosted(deployOnSelfHostedVm, isContainer, agentAlreadyInstalled) {
|
||||
return deployOnSelfHostedVm && !isContainer && !agentAlreadyInstalled;
|
||||
}
|
||||
function detectThirdPartyRunnerProvider() {
|
||||
var _a;
|
||||
if (process.env["DEPOT_RUNNER"] === "1")
|
||||
return "depot";
|
||||
if (process.env["NAMESPACE_GITHUB_RUNTIME"])
|
||||
return "namespace";
|
||||
if (process.env["BITRISE_IO"])
|
||||
return "bitrise";
|
||||
const runnerName = (_a = process.env["RUNNER_NAME"]) !== null && _a !== void 0 ? _a : "";
|
||||
if (runnerName.startsWith("warp-"))
|
||||
return "warp";
|
||||
if (runnerName.startsWith("blacksmith-"))
|
||||
return "blacksmith";
|
||||
return null;
|
||||
}
|
||||
function utils_getAnnotationLogs(platform) {
|
||||
switch (platform) {
|
||||
case "linux":
|
||||
@@ -31967,8 +31982,8 @@ const processLogLine = (line, tableEntries) => {
|
||||
}
|
||||
};
|
||||
function addSummary() {
|
||||
var _a;
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
var _a;
|
||||
if (process.env.STATE_addSummary !== "true") {
|
||||
return;
|
||||
}
|
||||
@@ -32009,7 +32024,9 @@ function addSummary() {
|
||||
// Fetch job summary from API
|
||||
const apiUrl = `${STEPSECURITY_API_URL}/github/${owner}/${repo}/actions/runs/${run_id}/correlation/${correlation_id}/job-markdown-summary`;
|
||||
try {
|
||||
const response = yield fetch(apiUrl);
|
||||
const response = yield fetch(apiUrl, {
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
console.error(`Failed to fetch job summary: ${response.status} ${response.statusText}`);
|
||||
return;
|
||||
@@ -32033,6 +32050,7 @@ const HARDEN_RUNNER_UNAVAILABLE_MESSAGE = "Sorry, we are currently experiencing
|
||||
const ARC_RUNNER_MESSAGE = "Workflow is currently being executed in ARC based runner.";
|
||||
const ARM64_RUNNER_MESSAGE = "ARM runners are not supported in the Harden-Runner community tier.";
|
||||
const ARM64_WINDOWS_RUNNER_MESSAGE = "Windows ARM runners are not yet supported by Harden-Runner.";
|
||||
const UBUNTU_SLIM_MESSAGE = "This job is running on an ubuntu-slim runner. Harden Runner is not supported on ubuntu-slim runners. This job will not be monitored.";
|
||||
|
||||
;// CONCATENATED MODULE: external "node:fs"
|
||||
const external_node_fs_namespaceObject = require("node:fs");
|
||||
@@ -32073,8 +32091,6 @@ const configs_STEPSECURITY_API_URL = (/* unused pure expression or super */ null
|
||||
const STEPSECURITY_TELEMETRY_URL = "https://prod.app-api.stepsecurity.io/v1";
|
||||
const STEPSECURITY_WEB_URL = "https://app.stepsecurity.io";
|
||||
|
||||
// EXTERNAL MODULE: ./node_modules/@actions/http-client/lib/index.js
|
||||
var lib = __nccwpck_require__(4844);
|
||||
;// CONCATENATED MODULE: ./src/tls-inspect.ts
|
||||
var tls_inspect_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
@@ -32087,28 +32103,25 @@ var tls_inspect_awaiter = (undefined && undefined.__awaiter) || function (thisAr
|
||||
};
|
||||
|
||||
|
||||
|
||||
function isTLSEnabled(owner) {
|
||||
return tls_inspect_awaiter(this, void 0, void 0, function* () {
|
||||
let tlsStatusEndpoint = `${STEPSECURITY_API_URL}/github/${owner}/actions/tls-inspection-status`;
|
||||
let httpClient = new HttpClient();
|
||||
httpClient.requestOptions = { socketTimeout: 3 * 1000 };
|
||||
const tlsStatusEndpoint = `${STEPSECURITY_API_URL}/github/${owner}/actions/tls-inspection-status`;
|
||||
core.info(`[!] Checking TLS_STATUS: ${owner}`);
|
||||
let isEnabled = false;
|
||||
try {
|
||||
let resp = yield httpClient.get(tlsStatusEndpoint);
|
||||
if (resp.message.statusCode === 200) {
|
||||
isEnabled = true;
|
||||
const resp = yield fetch(tlsStatusEndpoint, {
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
if (resp.status === 200) {
|
||||
core.info(`[!] TLS_ENABLED: ${owner}`);
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
core.info(`[!] TLS_NOT_ENABLED: ${owner}`);
|
||||
}
|
||||
core.info(`[!] TLS_NOT_ENABLED: ${owner}`);
|
||||
return false;
|
||||
}
|
||||
catch (e) {
|
||||
core.info(`[!] Unable to check TLS_STATUS`);
|
||||
core.info(`[!] Unable to check TLS_STATUS. Defaulting to TLS enabled.`);
|
||||
return true;
|
||||
}
|
||||
return isEnabled;
|
||||
});
|
||||
}
|
||||
function isGithubHosted() {
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+100
-21
@@ -31874,10 +31874,10 @@ var __webpack_exports__ = {};
|
||||
(() => {
|
||||
"use strict";
|
||||
|
||||
// EXTERNAL MODULE: external "fs"
|
||||
var external_fs_ = __nccwpck_require__(9896);
|
||||
// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js
|
||||
var lib_core = __nccwpck_require__(7484);
|
||||
// EXTERNAL MODULE: external "fs"
|
||||
var external_fs_ = __nccwpck_require__(9896);
|
||||
;// CONCATENATED MODULE: ./src/configs.ts
|
||||
const STEPSECURITY_ENV = "agent"; // agent or int
|
||||
const configs_STEPSECURITY_API_URL = `https://${STEPSECURITY_ENV}.api.stepsecurity.io/v1`;
|
||||
@@ -31919,6 +31919,21 @@ function isAgentInstalled(platform) {
|
||||
function shouldDeployAgentOnSelfHosted(deployOnSelfHostedVm, isContainer, agentAlreadyInstalled) {
|
||||
return deployOnSelfHostedVm && !isContainer && !agentAlreadyInstalled;
|
||||
}
|
||||
function detectThirdPartyRunnerProvider() {
|
||||
var _a;
|
||||
if (process.env["DEPOT_RUNNER"] === "1")
|
||||
return "depot";
|
||||
if (process.env["NAMESPACE_GITHUB_RUNTIME"])
|
||||
return "namespace";
|
||||
if (process.env["BITRISE_IO"])
|
||||
return "bitrise";
|
||||
const runnerName = (_a = process.env["RUNNER_NAME"]) !== null && _a !== void 0 ? _a : "";
|
||||
if (runnerName.startsWith("warp-"))
|
||||
return "warp";
|
||||
if (runnerName.startsWith("blacksmith-"))
|
||||
return "blacksmith";
|
||||
return null;
|
||||
}
|
||||
function getAnnotationLogs(platform) {
|
||||
switch (platform) {
|
||||
case "linux":
|
||||
@@ -31973,8 +31988,8 @@ const processLogLine = (line, tableEntries) => {
|
||||
}
|
||||
};
|
||||
function addSummary() {
|
||||
var _a;
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
var _a;
|
||||
if (process.env.STATE_addSummary !== "true") {
|
||||
return;
|
||||
}
|
||||
@@ -32015,7 +32030,9 @@ function addSummary() {
|
||||
// Fetch job summary from API
|
||||
const apiUrl = `${configs_STEPSECURITY_API_URL}/github/${owner}/${repo}/actions/runs/${run_id}/correlation/${correlation_id}/job-markdown-summary`;
|
||||
try {
|
||||
const response = yield fetch(apiUrl);
|
||||
const response = yield fetch(apiUrl, {
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
console.error(`Failed to fetch job summary: ${response.status} ${response.statusText}`);
|
||||
return;
|
||||
@@ -32039,6 +32056,7 @@ const HARDEN_RUNNER_UNAVAILABLE_MESSAGE = "Sorry, we are currently experiencing
|
||||
const ARC_RUNNER_MESSAGE = "Workflow is currently being executed in ARC based runner.";
|
||||
const ARM64_RUNNER_MESSAGE = "ARM runners are not supported in the Harden-Runner community tier.";
|
||||
const ARM64_WINDOWS_RUNNER_MESSAGE = "Windows ARM runners are not yet supported by Harden-Runner.";
|
||||
const UBUNTU_SLIM_MESSAGE = "This job is running on an ubuntu-slim runner. Harden Runner is not supported on ubuntu-slim runners. This job will not be monitored.";
|
||||
|
||||
// EXTERNAL MODULE: external "path"
|
||||
var external_path_ = __nccwpck_require__(6928);
|
||||
@@ -32121,8 +32139,6 @@ function echo(content) {
|
||||
cp.execFileSync("echo", [content]);
|
||||
}
|
||||
|
||||
// EXTERNAL MODULE: ./node_modules/@actions/http-client/lib/index.js
|
||||
var lib = __nccwpck_require__(4844);
|
||||
;// CONCATENATED MODULE: ./src/tls-inspect.ts
|
||||
var tls_inspect_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
@@ -32135,28 +32151,25 @@ var tls_inspect_awaiter = (undefined && undefined.__awaiter) || function (thisAr
|
||||
};
|
||||
|
||||
|
||||
|
||||
function isTLSEnabled(owner) {
|
||||
return tls_inspect_awaiter(this, void 0, void 0, function* () {
|
||||
let tlsStatusEndpoint = `${STEPSECURITY_API_URL}/github/${owner}/actions/tls-inspection-status`;
|
||||
let httpClient = new HttpClient();
|
||||
httpClient.requestOptions = { socketTimeout: 3 * 1000 };
|
||||
const tlsStatusEndpoint = `${STEPSECURITY_API_URL}/github/${owner}/actions/tls-inspection-status`;
|
||||
core.info(`[!] Checking TLS_STATUS: ${owner}`);
|
||||
let isEnabled = false;
|
||||
try {
|
||||
let resp = yield httpClient.get(tlsStatusEndpoint);
|
||||
if (resp.message.statusCode === 200) {
|
||||
isEnabled = true;
|
||||
const resp = yield fetch(tlsStatusEndpoint, {
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
if (resp.status === 200) {
|
||||
core.info(`[!] TLS_ENABLED: ${owner}`);
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
core.info(`[!] TLS_NOT_ENABLED: ${owner}`);
|
||||
}
|
||||
core.info(`[!] TLS_NOT_ENABLED: ${owner}`);
|
||||
return false;
|
||||
}
|
||||
catch (e) {
|
||||
core.info(`[!] Unable to check TLS_STATUS`);
|
||||
core.info(`[!] Unable to check TLS_STATUS. Defaulting to TLS enabled.`);
|
||||
return true;
|
||||
}
|
||||
return isEnabled;
|
||||
});
|
||||
}
|
||||
function isGithubHosted() {
|
||||
@@ -32185,6 +32198,13 @@ var cleanup_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _
|
||||
|
||||
|
||||
|
||||
|
||||
// See setup.ts for rationale — Node 22+ kills the process on unhandled rejections.
|
||||
process.on("unhandledRejection", (reason) => {
|
||||
var _a;
|
||||
const detail = reason instanceof Error ? ((_a = reason.stack) !== null && _a !== void 0 ? _a : reason.message) : String(reason);
|
||||
lib_core.warning(`Unhandled promise rejection during Post-step: ${detail}`);
|
||||
});
|
||||
(() => cleanup_awaiter(void 0, void 0, void 0, function* () {
|
||||
var _a, _b;
|
||||
console.log("[harden-runner] post-step");
|
||||
@@ -32201,10 +32221,15 @@ var cleanup_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _
|
||||
console.log(CONTAINER_MESSAGE);
|
||||
return;
|
||||
}
|
||||
if (isGithubHosted() && process.platform === "linux" && !process.env.USER) {
|
||||
console.log(UBUNTU_SLIM_MESSAGE);
|
||||
return;
|
||||
}
|
||||
if (isARCRunner()) {
|
||||
console.log(`[!] ${ARC_RUNNER_MESSAGE}`);
|
||||
return;
|
||||
}
|
||||
const thirdPartyProvider = detectThirdPartyRunnerProvider();
|
||||
if (process.env.STATE_selfHosted === "true") {
|
||||
return;
|
||||
}
|
||||
@@ -32218,7 +32243,12 @@ var cleanup_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _
|
||||
}
|
||||
switch (process.platform) {
|
||||
case "linux":
|
||||
yield handleLinuxCleanup();
|
||||
if (thirdPartyProvider) {
|
||||
yield handleAgentBravoCleanup();
|
||||
}
|
||||
else {
|
||||
yield handleLinuxCleanup();
|
||||
}
|
||||
break;
|
||||
case "win32":
|
||||
yield handleWindowsCleanup();
|
||||
@@ -32234,11 +32264,48 @@ var cleanup_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _
|
||||
console.log(exception);
|
||||
}
|
||||
}))();
|
||||
function handleAgentBravoCleanup() {
|
||||
return cleanup_awaiter(this, void 0, void 0, function* () {
|
||||
external_child_process_.execFileSync("/usr/bin/echo", ["step_policy_jobend"]);
|
||||
const doneFile = "/home/agent/done.json";
|
||||
let counter = 0;
|
||||
while (true) {
|
||||
if (!external_fs_.existsSync(doneFile)) {
|
||||
counter++;
|
||||
if (counter > 10) {
|
||||
console.log("timed out");
|
||||
break;
|
||||
}
|
||||
yield sleep(1000);
|
||||
}
|
||||
else {
|
||||
console.log(external_fs_.readFileSync(doneFile, "utf-8"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
const log = "/home/agent/agent.log";
|
||||
if (external_fs_.existsSync(log)) {
|
||||
console.log("log:");
|
||||
console.log(external_fs_.readFileSync(log, "utf-8"));
|
||||
}
|
||||
const status = "/home/agent/agent.status";
|
||||
if (external_fs_.existsSync(status)) {
|
||||
console.log("status:");
|
||||
console.log(external_fs_.readFileSync(status, "utf-8"));
|
||||
}
|
||||
});
|
||||
}
|
||||
function handleLinuxCleanup() {
|
||||
return cleanup_awaiter(this, void 0, void 0, function* () {
|
||||
if (process.env.STATE_isTLS === "false" && process.arch === "arm64") {
|
||||
return;
|
||||
}
|
||||
// If Pre-step crashed before installing the agent, /home/agent doesn't exist;
|
||||
// bail out instead of throwing ENOENT on the writeFileSync below.
|
||||
if (!external_fs_.existsSync("/home/agent")) {
|
||||
console.log("Linux cleanup: /home/agent not found; agent was not installed (Pre-step likely failed). Skipping.");
|
||||
return;
|
||||
}
|
||||
if (isGithubHosted() && external_fs_.existsSync("/home/agent/post_event.json")) {
|
||||
console.log("Post step already executed, skipping");
|
||||
return;
|
||||
@@ -32298,6 +32365,12 @@ function handleLinuxCleanup() {
|
||||
function handleMacosCleanup() {
|
||||
return cleanup_awaiter(this, void 0, void 0, function* () {
|
||||
const post_event = "/opt/step-security/post_event.json";
|
||||
// If Pre-step crashed before installing the agent, /opt/step-security doesn't
|
||||
// exist; bail out instead of throwing ENOENT on the writeFileSync below.
|
||||
if (!external_fs_.existsSync("/opt/step-security")) {
|
||||
console.log("macOS cleanup: /opt/step-security not found; agent was not installed (Pre-step likely failed). Skipping.");
|
||||
return;
|
||||
}
|
||||
if (isGithubHosted() && external_fs_.existsSync(post_event)) {
|
||||
console.log("Post step already executed, skipping");
|
||||
return;
|
||||
@@ -32336,7 +32409,7 @@ function handleMacosCleanup() {
|
||||
console.log("\nSystem log stream for io.stepsecurity.harden-runner:");
|
||||
const logStreamOutput = external_child_process_.execSync("log show --predicate 'subsystem == \"io.stepsecurity.harden-runner\"' --info --last 10m", {
|
||||
encoding: "utf8",
|
||||
maxBuffer: 1024 * 1024 * 10,
|
||||
maxBuffer: 1024 * 1024 * 10, // 10MB buffer
|
||||
timeout: 5000, // 5 seconds timeout
|
||||
});
|
||||
console.log(logStreamOutput);
|
||||
@@ -32351,6 +32424,12 @@ function handleWindowsCleanup() {
|
||||
// windows cleanup
|
||||
const agentDir = process.env.STATE_agentDir || "C:\\agent";
|
||||
const postEventFile = external_path_.join(agentDir, "post_event.json");
|
||||
// If Pre-step crashed before installing the agent, agentDir doesn't exist;
|
||||
// bail out instead of throwing ENOENT on the writeFileSync below.
|
||||
if (!external_fs_.existsSync(agentDir)) {
|
||||
console.log(`Windows cleanup: ${agentDir} not found; agent was not installed (Pre-step likely failed). Skipping.`);
|
||||
return;
|
||||
}
|
||||
if (isGithubHosted() && external_fs_.existsSync(postEventFile)) {
|
||||
console.log("Windows post step already executed, skipping");
|
||||
return;
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+372
-100
File diff suppressed because one or more lines are too long
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Generated
+864
-810
File diff suppressed because it is too large
Load Diff
+3
-3
@@ -37,7 +37,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^27.5.2",
|
||||
"@types/node": "^16.9.0",
|
||||
"@types/node": "^24.13.1",
|
||||
"@typescript-eslint/eslint-plugin": "^6.1.0",
|
||||
"@typescript-eslint/parser": "^6.1.0",
|
||||
"@vercel/ncc": "^0.38.3",
|
||||
@@ -46,8 +46,8 @@
|
||||
"jest": "^29.3.1",
|
||||
"jest-junit": ">=13.0.0",
|
||||
"nock": "^13.3.0",
|
||||
"ts-jest": "^29.0.3",
|
||||
"ts-jest": "^29.4.11",
|
||||
"ts-node": "^10.9.1",
|
||||
"typescript": "^4.3.5"
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { buildBravoConfig } from "./bravo-config";
|
||||
import { Configuration } from "./interfaces";
|
||||
|
||||
const base: Configuration = {
|
||||
repo: "org/repo",
|
||||
run_id: "123",
|
||||
correlation_id: "depot-abc",
|
||||
working_directory: "/w",
|
||||
api_url: "https://int.api.stepsecurity.io/v1",
|
||||
telemetry_url: "https://int.app-api.stepsecurity.io/v1",
|
||||
allowed_endpoints: "github.com:443",
|
||||
egress_policy: "audit",
|
||||
disable_telemetry: false,
|
||||
disable_sudo: false,
|
||||
disable_sudo_and_containers: false,
|
||||
disable_file_monitoring: false,
|
||||
is_github_hosted: false,
|
||||
private: "true" as unknown as string,
|
||||
is_debug: false,
|
||||
one_time_key: "otk-xyz",
|
||||
api_key: "tenant-key",
|
||||
use_policy_store: false,
|
||||
deploy_on_self_hosted_vm: false,
|
||||
};
|
||||
|
||||
describe("buildBravoConfig", () => {
|
||||
test("forces is_github_hosted=true so agent honors passed correlation_id", () => {
|
||||
expect(buildBravoConfig(base).is_github_hosted).toBe(true);
|
||||
});
|
||||
|
||||
test("omits api_key (agent authenticates via one_time_key, not vm-api-key)", () => {
|
||||
expect(buildBravoConfig(base)).not.toHaveProperty("api_key");
|
||||
});
|
||||
|
||||
test("omits customer (server infers tenant from repo)", () => {
|
||||
expect(buildBravoConfig(base)).not.toHaveProperty("customer");
|
||||
});
|
||||
|
||||
test("omits use_policy_store (action-side concern, not agent)", () => {
|
||||
expect(buildBravoConfig(base)).not.toHaveProperty("use_policy_store");
|
||||
});
|
||||
|
||||
test("forwards telemetry_url so network events hit configured env", () => {
|
||||
expect(buildBravoConfig(base).telemetry_url).toBe(base.telemetry_url);
|
||||
});
|
||||
|
||||
test("forwards one_time_key so agent can auth to presigned URL endpoint", () => {
|
||||
expect(buildBravoConfig(base).one_time_key).toBe("otk-xyz");
|
||||
});
|
||||
|
||||
test("forwards repo, run_id, correlation_id so server can attribute events", () => {
|
||||
const cfg = buildBravoConfig(base);
|
||||
expect(cfg.repo).toBe("org/repo");
|
||||
expect(cfg.run_id).toBe("123");
|
||||
expect(cfg.correlation_id).toBe("depot-abc");
|
||||
});
|
||||
|
||||
test("forwards private flag", () => {
|
||||
expect(buildBravoConfig(base).private).toBe(base.private);
|
||||
});
|
||||
|
||||
test("forwards egress_policy and allowed_endpoints", () => {
|
||||
const cfg = buildBravoConfig(base);
|
||||
expect(cfg.egress_policy).toBe("audit");
|
||||
expect(cfg.allowed_endpoints).toBe("github.com:443");
|
||||
});
|
||||
|
||||
test("forwards disable_* flags", () => {
|
||||
const cfg = buildBravoConfig({
|
||||
...base,
|
||||
disable_telemetry: true,
|
||||
disable_sudo: true,
|
||||
disable_sudo_and_containers: true,
|
||||
disable_file_monitoring: true,
|
||||
});
|
||||
expect(cfg.disable_telemetry).toBe(true);
|
||||
expect(cfg.disable_sudo).toBe(true);
|
||||
expect(cfg.disable_sudo_and_containers).toBe(true);
|
||||
expect(cfg.disable_file_monitoring).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Configuration } from "./interfaces";
|
||||
|
||||
export function buildBravoConfig(confg: Configuration) {
|
||||
return {
|
||||
repo: confg.repo,
|
||||
run_id: confg.run_id,
|
||||
correlation_id: confg.correlation_id,
|
||||
working_directory: confg.working_directory,
|
||||
api_url: confg.api_url,
|
||||
telemetry_url: confg.telemetry_url,
|
||||
one_time_key: confg.one_time_key,
|
||||
allowed_endpoints: confg.allowed_endpoints,
|
||||
egress_policy: confg.egress_policy,
|
||||
disable_telemetry: confg.disable_telemetry,
|
||||
disable_sudo: confg.disable_sudo,
|
||||
disable_sudo_and_containers: confg.disable_sudo_and_containers,
|
||||
disable_file_monitoring: confg.disable_file_monitoring,
|
||||
private: confg.private,
|
||||
is_github_hosted: true,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import * as fs from "fs";
|
||||
import * as crypto from "crypto";
|
||||
import * as core from "@actions/core";
|
||||
import { verifyChecksum, CHECKSUMS } from "./checksum";
|
||||
|
||||
jest.mock("fs", () => ({
|
||||
...jest.requireActual("fs"),
|
||||
readFileSync: jest.fn(),
|
||||
}));
|
||||
jest.mock("crypto", () => ({
|
||||
...jest.requireActual("crypto"),
|
||||
createHash: jest.fn(),
|
||||
}));
|
||||
jest.mock("@actions/core");
|
||||
|
||||
const mockReadFile = fs.readFileSync as jest.MockedFunction<typeof fs.readFileSync>;
|
||||
const mockSetFailed = core.setFailed as jest.MockedFunction<typeof core.setFailed>;
|
||||
const mockCreateHash = crypto.createHash as jest.MockedFunction<typeof crypto.createHash>;
|
||||
|
||||
function stubHash(hash: string) {
|
||||
mockCreateHash.mockReturnValue({
|
||||
update: jest.fn().mockReturnThis(),
|
||||
digest: jest.fn().mockReturnValue(hash),
|
||||
} as unknown as crypto.Hash);
|
||||
}
|
||||
|
||||
const WRONG_HASH = "0".repeat(64);
|
||||
|
||||
describe("verifyChecksum", () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockReadFile.mockReturnValue(Buffer.from("test-payload"));
|
||||
});
|
||||
|
||||
describe("agentType=bravo", () => {
|
||||
test("passes with matching bravo amd64 checksum", () => {
|
||||
stubHash(CHECKSUMS.bravo.amd64);
|
||||
expect(verifyChecksum("/tmp/f", true, "amd64", "linux", "bravo")).toBe(true);
|
||||
expect(mockSetFailed).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("passes with matching bravo arm64 checksum", () => {
|
||||
stubHash(CHECKSUMS.bravo.arm64);
|
||||
expect(verifyChecksum("/tmp/f", true, "arm64", "linux", "bravo")).toBe(true);
|
||||
});
|
||||
|
||||
test("uses bravo checksum even when isTLS=false", () => {
|
||||
stubHash(CHECKSUMS.bravo.amd64);
|
||||
expect(verifyChecksum("/tmp/f", false, "amd64", "linux", "bravo")).toBe(true);
|
||||
});
|
||||
|
||||
test("fails on mismatched bravo checksum", () => {
|
||||
stubHash(WRONG_HASH);
|
||||
expect(verifyChecksum("/tmp/f", true, "amd64", "linux", "bravo")).toBe(false);
|
||||
expect(mockSetFailed).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("agentType default (omitted)", () => {
|
||||
test("uses TLS checksum when isTLS=true", () => {
|
||||
stubHash(CHECKSUMS.tls.amd64);
|
||||
expect(verifyChecksum("/tmp/f", true, "amd64", "linux")).toBe(true);
|
||||
});
|
||||
|
||||
test("uses non_tls checksum when isTLS=false", () => {
|
||||
stubHash(CHECKSUMS.non_tls.amd64);
|
||||
expect(verifyChecksum("/tmp/f", false, "amd64", "linux")).toBe(true);
|
||||
});
|
||||
|
||||
test("TLS mismatch fails", () => {
|
||||
stubHash(CHECKSUMS.bravo.amd64);
|
||||
expect(verifyChecksum("/tmp/f", true, "amd64", "linux")).toBe(false);
|
||||
expect(mockSetFailed).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("darwin", () => {
|
||||
test("passes with matching darwin checksum", () => {
|
||||
stubHash(CHECKSUMS.darwin);
|
||||
expect(verifyChecksum("/tmp/f", false, "", "darwin")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("win32", () => {
|
||||
test("passes with matching windows amd64 checksum", () => {
|
||||
stubHash(CHECKSUMS.windows.amd64);
|
||||
expect(verifyChecksum("/tmp/f", false, "amd64", "win32")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("unsupported platform", () => {
|
||||
test("returns false without calling setFailed", () => {
|
||||
stubHash(CHECKSUMS.bravo.amd64);
|
||||
expect(verifyChecksum("/tmp/f", true, "amd64", "freebsd")).toBe(false);
|
||||
expect(mockSetFailed).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
+19
-10
@@ -2,17 +2,21 @@ import * as core from "@actions/core";
|
||||
import * as crypto from "crypto";
|
||||
import * as fs from "fs";
|
||||
|
||||
const CHECKSUMS = {
|
||||
export const CHECKSUMS = {
|
||||
tls: {
|
||||
amd64: "86d042adcdc03eb1ea50d35d265da47622a6d0aedef9657f84ce1eb7f04d6057", // v1.8.0
|
||||
arm64: "ea1074a2358d50db9a9fe18ae3971b87305cda63f262c494a5f43b25f4e524ce",
|
||||
amd64: "a54c4305b5665ba54bfdc46eb32aee1758699b994550ca3658d698367cc96a3f", // v1.8.12
|
||||
arm64: "3f401d508e1427b9ba205681d5abecde3b4a0f0a18542d198b6dc14cadd93ab5", // v1.8.12
|
||||
},
|
||||
non_tls: {
|
||||
amd64: "4aaaeebbe10e619d8ce13e8cc4a1acbafc8f891e8cdd319984480b9ec08407b8", // v0.15.0
|
||||
amd64: "4b14d8a3a5fbcef95af55e0c54d3bee6f44da802878c10289a4ca0b79b6d0237", // v0.16.2
|
||||
},
|
||||
darwin: "797399a3a3f6f9c4c000a02e0d8c7b16499129c9bdc2ad9cf2a10072c10654fb", // v0.0.4
|
||||
bravo: {
|
||||
amd64: "c986d0a19637325c9a8d4a331a6c4ed047e4cddb798f56b641d0e66f8bf9b1b2", // v1.8.12
|
||||
arm64: "5c3df17f82e317c8b288dfbbcee449c2a24a80deeeb3416dccabd0a61982c676", // v1.8.12
|
||||
},
|
||||
darwin: "2990f0390d2760fa6262a3830060b6db1233f16a1410ffe1ed2bf13dfda80c38", // v0.0.6
|
||||
windows: {
|
||||
amd64: "e98f8b9cf9ecf6566f1e16a470fbe4aef01610a644fd8203a1bab3ff142186c8", // v1.0.0
|
||||
amd64: "5e3604d08aba65d7bdd1d0684826d5894ffb0c6f56b914c6ecb35c3271e04483", // v1.0.7
|
||||
},
|
||||
};
|
||||
|
||||
@@ -21,7 +25,8 @@ export function verifyChecksum(
|
||||
downloadPath: string,
|
||||
isTLS: boolean,
|
||||
variant: string,
|
||||
platform: string
|
||||
platform: string,
|
||||
agentType: "default" | "bravo" = "default"
|
||||
) {
|
||||
const fileBuffer: Buffer = fs.readFileSync(downloadPath);
|
||||
const checksum: string = crypto
|
||||
@@ -33,9 +38,13 @@ export function verifyChecksum(
|
||||
|
||||
switch (platform) {
|
||||
case "linux":
|
||||
expectedChecksum = isTLS
|
||||
? CHECKSUMS["tls"][variant]
|
||||
: CHECKSUMS["non_tls"][variant];
|
||||
if (agentType === "bravo") {
|
||||
expectedChecksum = CHECKSUMS["bravo"][variant];
|
||||
} else {
|
||||
expectedChecksum = isTLS
|
||||
? CHECKSUMS["tls"][variant]
|
||||
: CHECKSUMS["non_tls"][variant];
|
||||
}
|
||||
break;
|
||||
case "darwin":
|
||||
expectedChecksum = CHECKSUMS["darwin"];
|
||||
|
||||
+80
-2
@@ -1,3 +1,4 @@
|
||||
import * as core from "@actions/core";
|
||||
import * as fs from "fs";
|
||||
import * as common from "./common";
|
||||
import * as cp from "child_process";
|
||||
@@ -6,7 +7,14 @@ import isDocker from "is-docker";
|
||||
import { isARCRunner } from "./arc-runner";
|
||||
import { isGithubHosted } from "./tls-inspect";
|
||||
import { context } from "@actions/github";
|
||||
import { isPlatformSupported, isAgentInstalled } from "./utils";
|
||||
import { isPlatformSupported, isAgentInstalled, detectThirdPartyRunnerProvider } from "./utils";
|
||||
|
||||
// See setup.ts for rationale — Node 22+ kills the process on unhandled rejections.
|
||||
process.on("unhandledRejection", (reason) => {
|
||||
const detail =
|
||||
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason);
|
||||
core.warning(`Unhandled promise rejection during Post-step: ${detail}`);
|
||||
});
|
||||
|
||||
(async () => {
|
||||
console.log("[harden-runner] post-step");
|
||||
@@ -26,11 +34,18 @@ import { isPlatformSupported, isAgentInstalled } from "./utils";
|
||||
return;
|
||||
}
|
||||
|
||||
if (isGithubHosted() && process.platform === "linux" && !process.env.USER) {
|
||||
console.log(common.UBUNTU_SLIM_MESSAGE);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isARCRunner()) {
|
||||
console.log(`[!] ${common.ARC_RUNNER_MESSAGE}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const thirdPartyProvider = detectThirdPartyRunnerProvider();
|
||||
|
||||
if (process.env.STATE_selfHosted === "true") {
|
||||
return;
|
||||
}
|
||||
@@ -49,7 +64,11 @@ import { isPlatformSupported, isAgentInstalled } from "./utils";
|
||||
|
||||
switch (process.platform) {
|
||||
case "linux":
|
||||
await handleLinuxCleanup();
|
||||
if (thirdPartyProvider) {
|
||||
await handleAgentBravoCleanup();
|
||||
} else {
|
||||
await handleLinuxCleanup();
|
||||
}
|
||||
break;
|
||||
case "win32":
|
||||
await handleWindowsCleanup();
|
||||
@@ -66,11 +85,52 @@ import { isPlatformSupported, isAgentInstalled } from "./utils";
|
||||
}
|
||||
})();
|
||||
|
||||
async function handleAgentBravoCleanup() {
|
||||
cp.execFileSync("/usr/bin/echo", ["step_policy_jobend"]);
|
||||
|
||||
const doneFile = "/home/agent/done.json";
|
||||
let counter = 0;
|
||||
while (true) {
|
||||
if (!fs.existsSync(doneFile)) {
|
||||
counter++;
|
||||
if (counter > 10) {
|
||||
console.log("timed out");
|
||||
break;
|
||||
}
|
||||
await sleep(1000);
|
||||
} else {
|
||||
console.log(fs.readFileSync(doneFile, "utf-8"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const log = "/home/agent/agent.log";
|
||||
if (fs.existsSync(log)) {
|
||||
console.log("log:");
|
||||
console.log(fs.readFileSync(log, "utf-8"));
|
||||
}
|
||||
|
||||
const status = "/home/agent/agent.status";
|
||||
if (fs.existsSync(status)) {
|
||||
console.log("status:");
|
||||
console.log(fs.readFileSync(status, "utf-8"));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLinuxCleanup() {
|
||||
if (process.env.STATE_isTLS === "false" && process.arch === "arm64") {
|
||||
return;
|
||||
}
|
||||
|
||||
// If Pre-step crashed before installing the agent, /home/agent doesn't exist;
|
||||
// bail out instead of throwing ENOENT on the writeFileSync below.
|
||||
if (!fs.existsSync("/home/agent")) {
|
||||
console.log(
|
||||
"Linux cleanup: /home/agent not found; agent was not installed (Pre-step likely failed). Skipping."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isGithubHosted() && fs.existsSync("/home/agent/post_event.json")) {
|
||||
console.log("Post step already executed, skipping");
|
||||
return;
|
||||
@@ -142,6 +202,15 @@ async function handleLinuxCleanup() {
|
||||
async function handleMacosCleanup() {
|
||||
const post_event = "/opt/step-security/post_event.json";
|
||||
|
||||
// If Pre-step crashed before installing the agent, /opt/step-security doesn't
|
||||
// exist; bail out instead of throwing ENOENT on the writeFileSync below.
|
||||
if (!fs.existsSync("/opt/step-security")) {
|
||||
console.log(
|
||||
"macOS cleanup: /opt/step-security not found; agent was not installed (Pre-step likely failed). Skipping."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isGithubHosted() && fs.existsSync(post_event)) {
|
||||
console.log("Post step already executed, skipping");
|
||||
return;
|
||||
@@ -199,6 +268,15 @@ async function handleWindowsCleanup() {
|
||||
const agentDir = process.env.STATE_agentDir || "C:\\agent";
|
||||
const postEventFile = path.join(agentDir, "post_event.json");
|
||||
|
||||
// If Pre-step crashed before installing the agent, agentDir doesn't exist;
|
||||
// bail out instead of throwing ENOENT on the writeFileSync below.
|
||||
if (!fs.existsSync(agentDir)) {
|
||||
console.log(
|
||||
`Windows cleanup: ${agentDir} not found; agent was not installed (Pre-step likely failed). Skipping.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isGithubHosted() && fs.existsSync(postEventFile)) {
|
||||
console.log("Windows post step already executed, skipping");
|
||||
return;
|
||||
|
||||
+6
-1
@@ -109,7 +109,9 @@ export async function addSummary() {
|
||||
const apiUrl = `${STEPSECURITY_API_URL}/github/${owner}/${repo}/actions/runs/${run_id}/correlation/${correlation_id}/job-markdown-summary`;
|
||||
|
||||
try {
|
||||
const response = await fetch(apiUrl);
|
||||
const response = await fetch(apiUrl, {
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
console.error(`Failed to fetch job summary: ${response.status} ${response.statusText}`);
|
||||
return;
|
||||
@@ -148,3 +150,6 @@ export const ARM64_RUNNER_MESSAGE =
|
||||
|
||||
export const ARM64_WINDOWS_RUNNER_MESSAGE =
|
||||
"Windows ARM runners are not yet supported by Harden-Runner.";
|
||||
|
||||
export const UBUNTU_SLIM_MESSAGE =
|
||||
"This job is running on an ubuntu-slim runner. Harden Runner is not supported on ubuntu-slim runners. This job will not be monitored.";
|
||||
|
||||
+58
-4
@@ -26,7 +26,7 @@ export async function installAgent(
|
||||
|
||||
if (isTLS) {
|
||||
downloadPath = await tc.downloadTool(
|
||||
`https://github.com/step-security/agent-ebpf/releases/download/v1.8.0/harden-runner_1.8.0_linux_${variant}.tar.gz`,
|
||||
`https://github.com/step-security/agent-ebpf/releases/download/v1.8.12/harden-runner_1.8.12_linux_${variant}.tar.gz`,
|
||||
undefined,
|
||||
auth
|
||||
);
|
||||
@@ -36,7 +36,7 @@ export async function installAgent(
|
||||
return false;
|
||||
}
|
||||
downloadPath = await tc.downloadTool(
|
||||
"https://github.com/step-security/agent/releases/download/v0.15.0/agent_0.15.0_linux_amd64.tar.gz",
|
||||
"https://github.com/step-security/agent/releases/download/v0.16.2/agent_0.16.2_linux_amd64.tar.gz",
|
||||
undefined,
|
||||
auth
|
||||
);
|
||||
@@ -69,6 +69,60 @@ export async function installAgent(
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function installAgentBravo(configStr: string): Promise<boolean> {
|
||||
// Note: to avoid github rate limiting
|
||||
const token = core.getInput("token", { required: true });
|
||||
const auth = `token ${token}`;
|
||||
|
||||
const variant = process.arch === "x64" ? "amd64" : "arm64";
|
||||
const downloadPath = await tc.downloadTool(
|
||||
`https://github.com/step-security/agent-ebpf/releases/download/v1.8.12/harden-runner-bravo_1.8.12_linux_${variant}.tar.gz`,
|
||||
undefined,
|
||||
auth
|
||||
);
|
||||
|
||||
if (!verifyChecksum(downloadPath, true, variant, "linux", "bravo")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const extractPath = await tc.extractTar(downloadPath);
|
||||
cp.execFileSync("cp", [path.join(extractPath, "agent"), "/home/agent/agent"]);
|
||||
|
||||
cp.execSync("chmod +x /home/agent/agent");
|
||||
|
||||
fs.writeFileSync("/home/agent/agent.json", configStr);
|
||||
|
||||
const logStream = fs.openSync("/home/agent/agent.stdout", "a");
|
||||
const agentProcess = cp.spawn("sudo", ["/home/agent/agent"], {
|
||||
cwd: "/home/agent",
|
||||
detached: true,
|
||||
stdio: ["ignore", logStream, logStream],
|
||||
});
|
||||
agentProcess.unref();
|
||||
|
||||
const agentStatus = "/home/agent/agent.status";
|
||||
const deadline = Date.now() + 10000;
|
||||
while (true) {
|
||||
if (!fs.existsSync(agentStatus)) {
|
||||
if (Date.now() >= deadline) {
|
||||
console.log("timed out waiting for bravo agent");
|
||||
if (fs.existsSync("/home/agent/agent.stdout")) {
|
||||
console.log(fs.readFileSync("/home/agent/agent.stdout", "utf-8"));
|
||||
}
|
||||
if (fs.existsSync("/home/agent/agent.log")) {
|
||||
console.log(fs.readFileSync("/home/agent/agent.log", "utf-8"));
|
||||
}
|
||||
break;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
} else {
|
||||
console.log(fs.readFileSync(agentStatus, "utf-8"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function installMacosAgent(configStr: string): Promise<boolean> {
|
||||
const token = core.getInput("token", { required: true });
|
||||
const auth = `token ${token}`;
|
||||
@@ -89,7 +143,7 @@ export async function installMacosAgent(configStr: string): Promise<boolean> {
|
||||
|
||||
// Download installer package
|
||||
const downloadUrl =
|
||||
"https://github.com/step-security/agent-releases/releases/download/v0.0.4-mac/macos-installer-0.0.4.tar.gz";
|
||||
"https://github.com/step-security/agent-releases/releases/download/v0.0.6-mac/macos-installer-0.0.6.tar.gz";
|
||||
core.info(`Downloading macOS installer.. : ${downloadUrl}`);
|
||||
const downloadPath = await tc.downloadTool(downloadUrl, undefined, auth);
|
||||
core.info(`✓ Successfully downloaded installer to: ${downloadPath}`);
|
||||
@@ -172,7 +226,7 @@ export async function installWindowsAgent(configStr: string): Promise<boolean> {
|
||||
const agentExePath = path.join(agentDir, "agent.exe");
|
||||
|
||||
const downloadPath = await tc.downloadTool(
|
||||
`https://github.com/step-security/agent-releases/releases/download/v1.0.0-win/harden-runner-agent-windows_1.0.0_windows_amd64.tar.gz`,
|
||||
`https://github.com/step-security/agent-releases/releases/download/v1.0.7-win/harden-runner-agent-windows_1.0.7_windows_amd64.tar.gz`,
|
||||
undefined,
|
||||
auth
|
||||
);
|
||||
|
||||
+231
-231
@@ -1,12 +1,46 @@
|
||||
import nock from "nock";
|
||||
import { fetchPolicy, mergeConfigs } from "./policy-utils";
|
||||
import { fetchPolicy, fetchPolicyFromStore, mergeConfigs } from "./policy-utils";
|
||||
import { Configuration, PolicyResponse } from "./interfaces";
|
||||
import { STEPSECURITY_API_URL } from "./configs";
|
||||
|
||||
const ORIGINAL_FETCH = globalThis.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = ORIGINAL_FETCH;
|
||||
});
|
||||
|
||||
type FetchImpl = (
|
||||
input: RequestInfo | URL,
|
||||
init?: RequestInit
|
||||
) => Promise<Response>;
|
||||
|
||||
function mockFetch(impl: FetchImpl) {
|
||||
globalThis.fetch = impl as typeof fetch;
|
||||
}
|
||||
|
||||
function jsonResponse(status: number, body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
// Mock fetch with a sequence of responses or errors. Each call consumes one entry.
|
||||
function mockFetchSequence(entries: Array<Response | Error>) {
|
||||
let i = 0;
|
||||
mockFetch(async () => {
|
||||
const entry = entries[i++];
|
||||
if (!entry) throw new Error("fetch called more times than expected");
|
||||
if (entry instanceof Error) throw entry;
|
||||
return entry;
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== fetchPolicy ====================
|
||||
|
||||
test("success: fetching policy", async () => {
|
||||
let owner = "h0x0er";
|
||||
let policyName = "policy1";
|
||||
let response = {
|
||||
const owner = "h0x0er";
|
||||
const policyName = "policy1";
|
||||
const response = {
|
||||
owner: "h0x0er",
|
||||
policyName: "policy1",
|
||||
allowed_endpoints: ["github.com:443"],
|
||||
@@ -15,16 +49,196 @@ test("success: fetching policy", async () => {
|
||||
disable_sudo: false,
|
||||
disable_file_monitoring: false,
|
||||
};
|
||||
const policyScope = nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/actions/policies/${policyName}`)
|
||||
.reply(200, response);
|
||||
|
||||
let idToken = "xyz";
|
||||
let policy = await fetchPolicy(owner, policyName, idToken);
|
||||
console.log(policy);
|
||||
expect(policy).toStrictEqual(response);
|
||||
const expectedUrl = `${STEPSECURITY_API_URL}/github/${owner}/actions/policies/${policyName}`;
|
||||
mockFetch(async (url, init) => {
|
||||
expect(String(url)).toBe(expectedUrl);
|
||||
expect((init?.headers as Record<string, string>)["Authorization"]).toBe("Bearer xyz");
|
||||
expect((init?.headers as Record<string, string>)["Source"]).toBe("github-actions");
|
||||
return jsonResponse(200, response);
|
||||
});
|
||||
|
||||
const policy = await fetchPolicy(owner, policyName, "xyz");
|
||||
expect(policy).toEqual(response);
|
||||
});
|
||||
|
||||
test("fetchPolicy throws when idToken is empty", async () => {
|
||||
await expect(fetchPolicy("owner", "policy1", "")).rejects.toThrow(
|
||||
"[PolicyFetch]: id-token in empty"
|
||||
);
|
||||
});
|
||||
|
||||
test("fetchPolicy retries on failure and succeeds", async () => {
|
||||
const response = {
|
||||
allowed_endpoints: ["example.com:443"],
|
||||
egress_policy: "block",
|
||||
};
|
||||
|
||||
mockFetchSequence([
|
||||
new TypeError("fetch failed"),
|
||||
jsonResponse(200, response),
|
||||
]);
|
||||
|
||||
const policy = await fetchPolicy("test-owner", "test-policy", "token123");
|
||||
expect(policy).toEqual(response);
|
||||
});
|
||||
|
||||
test("fetchPolicy throws after all retries exhausted", async () => {
|
||||
mockFetchSequence([
|
||||
new TypeError("fetch failed"),
|
||||
new TypeError("fetch failed"),
|
||||
new TypeError("fetch failed"),
|
||||
]);
|
||||
|
||||
await expect(
|
||||
fetchPolicy("test-owner", "test-policy", "token123")
|
||||
).rejects.toThrow("[Policy Fetch]");
|
||||
});
|
||||
|
||||
test("fetchPolicy preserves statusCode from error", async () => {
|
||||
// server returns 404 on every retry; the HttpStatusError raised internally
|
||||
// carries statusCode=404 which the outer error should expose.
|
||||
mockFetchSequence([
|
||||
jsonResponse(404, { message: "not found" }),
|
||||
jsonResponse(404, { message: "not found" }),
|
||||
jsonResponse(404, { message: "not found" }),
|
||||
]);
|
||||
|
||||
try {
|
||||
await fetchPolicy("test-owner", "test-policy", "token123");
|
||||
fail("should have thrown");
|
||||
} catch (err: any) {
|
||||
expect(err.message).toContain("[Policy Fetch]");
|
||||
expect(err.statusCode).toBe(404);
|
||||
}
|
||||
});
|
||||
|
||||
// ==================== fetchPolicyFromStore ====================
|
||||
|
||||
test("success: fetches policy from store", async () => {
|
||||
const owner = "test-owner";
|
||||
const repo = "test-repo";
|
||||
const workflow = "ci.yml";
|
||||
const runId = "12345";
|
||||
const correlationId = "abc-def";
|
||||
const response = {
|
||||
allowed_endpoints: ["registry.npmjs.org:443", "github.com:443"],
|
||||
egress_policy: "block",
|
||||
disable_sudo: true,
|
||||
disable_file_monitoring: false,
|
||||
};
|
||||
|
||||
mockFetch(async () => jsonResponse(200, response));
|
||||
|
||||
const result = await fetchPolicyFromStore(owner, repo, "my-api-key", workflow, runId, correlationId);
|
||||
expect(result).toEqual(response);
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore throws when apiKey is empty", async () => {
|
||||
await expect(
|
||||
fetchPolicyFromStore("owner", "repo", "", "ci.yml", "123", "abc")
|
||||
).rejects.toThrow("[PolicyStoreFetch]: api-key is empty");
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore returns null when policy not found (404)", async () => {
|
||||
mockFetch(async () => jsonResponse(404, { message: "not found" }));
|
||||
|
||||
const result = await fetchPolicyFromStore("test-owner", "test-repo", "my-api-key", "ci.yml", "12345", "abc-def");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore returns null when API returns empty policy", async () => {
|
||||
mockFetch(async () => jsonResponse(200, { allowed_endpoints: [], egress_policy: "", policy_name: "" }));
|
||||
|
||||
const result = await fetchPolicyFromStore("test-owner", "nonexistent-repo", "my-api-key", "ci.yml", "12345", "abc-def");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore retries on failure and succeeds", async () => {
|
||||
const response = {
|
||||
allowed_endpoints: ["example.com:443"],
|
||||
egress_policy: "audit",
|
||||
};
|
||||
|
||||
mockFetchSequence([
|
||||
new TypeError("fetch failed"),
|
||||
jsonResponse(200, response),
|
||||
]);
|
||||
|
||||
const result = await fetchPolicyFromStore("test-owner", "test-repo", "my-api-key", "ci.yml", "12345", "abc-def");
|
||||
expect(result).toEqual(response);
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore throws after all retries exhausted", async () => {
|
||||
mockFetchSequence([
|
||||
new TypeError("fetch failed"),
|
||||
new TypeError("fetch failed"),
|
||||
new TypeError("fetch failed"),
|
||||
]);
|
||||
|
||||
await expect(
|
||||
fetchPolicyFromStore("test-owner", "test-repo", "my-api-key", "ci.yml", "12345", "abc-def")
|
||||
).rejects.toThrow("[Policy Store Fetch]");
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore preserves statusCode from error", async () => {
|
||||
mockFetchSequence([
|
||||
jsonResponse(401, { message: "Unauthorized" }),
|
||||
jsonResponse(401, { message: "Unauthorized" }),
|
||||
jsonResponse(401, { message: "Unauthorized" }),
|
||||
]);
|
||||
|
||||
try {
|
||||
await fetchPolicyFromStore("test-owner", "test-repo", "my-api-key", "ci.yml", "12345", "abc-def");
|
||||
fail("should have thrown");
|
||||
} catch (err: any) {
|
||||
expect(err.message).toContain("[Policy Store Fetch]");
|
||||
expect(err.statusCode).toBe(401);
|
||||
}
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore sends correct authorization header", async () => {
|
||||
const apiKey = "secret-key-123";
|
||||
|
||||
mockFetch(async (_url, init) => {
|
||||
const headers = init?.headers as Record<string, string>;
|
||||
expect(headers["Authorization"]).toBe(`vm-api-key ${apiKey}`);
|
||||
expect(headers["Source"]).toBe("github-actions");
|
||||
return jsonResponse(200, { allowed_endpoints: [], egress_policy: "audit" });
|
||||
});
|
||||
|
||||
const result = await fetchPolicyFromStore("test-owner", "test-repo", apiKey, "ci.yml", "12345", "abc-def");
|
||||
expect(result).toEqual({ allowed_endpoints: [], egress_policy: "audit" });
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore returns within ~3s when server is slow (regression test for AggregateError)", async () => {
|
||||
mockFetch((_url, init) => {
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
const signal = init?.signal;
|
||||
if (signal) {
|
||||
if (signal.aborted) {
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
return;
|
||||
}
|
||||
signal.addEventListener("abort", () =>
|
||||
reject(new DOMException("Aborted", "AbortError"))
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const start = Date.now();
|
||||
await expect(
|
||||
fetchPolicyFromStore("test-owner", "test-repo", "my-api-key", "ci.yml", "12345", "abc-def")
|
||||
).rejects.toThrow("[Policy Store Fetch]");
|
||||
const elapsed = Date.now() - start;
|
||||
// 3 retries × (3s timeout + 1s sleep), but last sleep is unnecessary.
|
||||
// Bounded by 3 * 3s + 2 * 1s = 11s. Test passes if it doesn't hang for minutes.
|
||||
expect(elapsed).toBeLessThan(13_000);
|
||||
}, 20_000);
|
||||
|
||||
// ==================== mergeConfigs ====================
|
||||
|
||||
test("merge configs", async () => {
|
||||
let localConfig: Configuration = {
|
||||
repo: "test/repo",
|
||||
@@ -47,7 +261,7 @@ test("merge configs", async () => {
|
||||
use_policy_store: false,
|
||||
deploy_on_self_hosted_vm: false,
|
||||
};
|
||||
let policyResponse: PolicyResponse = {
|
||||
const policyResponse: PolicyResponse = {
|
||||
owner: "h0x0er",
|
||||
policyName: "policy1",
|
||||
allowed_endpoints: ["github.com:443", "google.com:443"],
|
||||
@@ -56,8 +270,7 @@ test("merge configs", async () => {
|
||||
disable_sudo: false,
|
||||
disable_file_monitoring: false,
|
||||
};
|
||||
|
||||
let expectedConfiguration: Configuration = {
|
||||
const expectedConfiguration: Configuration = {
|
||||
repo: "test/repo",
|
||||
run_id: "xyx",
|
||||
correlation_id: "aaaaa",
|
||||
@@ -83,219 +296,6 @@ test("merge configs", async () => {
|
||||
expect(localConfig).toStrictEqual(expectedConfiguration);
|
||||
});
|
||||
|
||||
// ==================== additional fetchPolicy tests ====================
|
||||
|
||||
test("fetchPolicy throws when idToken is empty", async () => {
|
||||
await expect(fetchPolicy("owner", "policy1", "")).rejects.toThrow(
|
||||
"[PolicyFetch]: id-token in empty"
|
||||
);
|
||||
});
|
||||
|
||||
test("fetchPolicy retries on failure and succeeds", async () => {
|
||||
const owner = "test-owner";
|
||||
const policyName = "test-policy";
|
||||
const response = {
|
||||
allowed_endpoints: ["example.com:443"],
|
||||
egress_policy: "block",
|
||||
};
|
||||
|
||||
nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/actions/policies/${policyName}`)
|
||||
.replyWithError("connection timeout");
|
||||
nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/actions/policies/${policyName}`)
|
||||
.reply(200, response);
|
||||
|
||||
const policy = await fetchPolicy(owner, policyName, "token123");
|
||||
expect(policy).toStrictEqual(response);
|
||||
});
|
||||
|
||||
test("fetchPolicy throws after all retries exhausted", async () => {
|
||||
const owner = "test-owner";
|
||||
const policyName = "test-policy";
|
||||
|
||||
nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/actions/policies/${policyName}`)
|
||||
.times(3)
|
||||
.replyWithError("connection timeout");
|
||||
|
||||
await expect(
|
||||
fetchPolicy(owner, policyName, "token123")
|
||||
).rejects.toThrow("[Policy Fetch]");
|
||||
});
|
||||
|
||||
test("fetchPolicy preserves statusCode from error", async () => {
|
||||
const owner = "test-owner";
|
||||
const policyName = "test-policy";
|
||||
|
||||
const errorWithStatus = new Error("Not Found");
|
||||
(errorWithStatus as any).statusCode = 404;
|
||||
|
||||
nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/actions/policies/${policyName}`)
|
||||
.times(3)
|
||||
.replyWithError(errorWithStatus);
|
||||
|
||||
try {
|
||||
await fetchPolicy(owner, policyName, "token123");
|
||||
fail("should have thrown");
|
||||
} catch (err) {
|
||||
expect(err.message).toContain("[Policy Fetch]");
|
||||
}
|
||||
});
|
||||
|
||||
// ==================== fetchPolicyFromStore ====================
|
||||
|
||||
import { fetchPolicyFromStore } from "./policy-utils";
|
||||
|
||||
const policyStoreQueryString = (workflow: string, runId: string, correlationId: string) =>
|
||||
`workflow=${encodeURIComponent(workflow)}&run_id=${encodeURIComponent(runId)}&correlationId=${encodeURIComponent(correlationId)}`;
|
||||
|
||||
test("success: fetches policy from store", async () => {
|
||||
const owner = "test-owner";
|
||||
const repo = "test-repo";
|
||||
const workflow = "ci.yml";
|
||||
const runId = "12345";
|
||||
const correlationId = "abc-def";
|
||||
const response = {
|
||||
allowed_endpoints: ["registry.npmjs.org:443", "github.com:443"],
|
||||
egress_policy: "block",
|
||||
disable_sudo: true,
|
||||
disable_file_monitoring: false,
|
||||
};
|
||||
|
||||
nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/${repo}/actions/policies/workflow-policy?${policyStoreQueryString(workflow, runId, correlationId)}`)
|
||||
.reply(200, response);
|
||||
|
||||
const result = await fetchPolicyFromStore(owner, repo, "my-api-key", workflow, runId, correlationId);
|
||||
expect(result).toStrictEqual(response);
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore throws when apiKey is empty", async () => {
|
||||
await expect(
|
||||
fetchPolicyFromStore("owner", "repo", "", "ci.yml", "123", "abc")
|
||||
).rejects.toThrow("[PolicyStoreFetch]: api-key is empty");
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore returns null when policy not found (404)", async () => {
|
||||
const owner = "test-owner";
|
||||
const repo = "test-repo";
|
||||
const workflow = "ci.yml";
|
||||
const runId = "12345";
|
||||
const correlationId = "abc-def";
|
||||
|
||||
nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/${repo}/actions/policies/workflow-policy?${policyStoreQueryString(workflow, runId, correlationId)}`)
|
||||
.reply(404, { message: "not found" });
|
||||
|
||||
const result = await fetchPolicyFromStore(owner, repo, "my-api-key", workflow, runId, correlationId);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore returns null when API returns empty policy", async () => {
|
||||
const owner = "test-owner";
|
||||
const repo = "nonexistent-repo";
|
||||
const workflow = "ci.yml";
|
||||
const runId = "12345";
|
||||
const correlationId = "abc-def";
|
||||
|
||||
nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/${repo}/actions/policies/workflow-policy?${policyStoreQueryString(workflow, runId, correlationId)}`)
|
||||
.reply(200, { allowed_endpoints: [], egress_policy: "", policy_name: "" });
|
||||
|
||||
const result = await fetchPolicyFromStore(owner, repo, "my-api-key", workflow, runId, correlationId);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore retries on failure and succeeds", async () => {
|
||||
const owner = "test-owner";
|
||||
const repo = "test-repo";
|
||||
const workflow = "ci.yml";
|
||||
const runId = "12345";
|
||||
const correlationId = "abc-def";
|
||||
const response = {
|
||||
allowed_endpoints: ["example.com:443"],
|
||||
egress_policy: "audit",
|
||||
};
|
||||
|
||||
nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/${repo}/actions/policies/workflow-policy?${policyStoreQueryString(workflow, runId, correlationId)}`)
|
||||
.replyWithError("timeout");
|
||||
nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/${repo}/actions/policies/workflow-policy?${policyStoreQueryString(workflow, runId, correlationId)}`)
|
||||
.reply(200, response);
|
||||
|
||||
const result = await fetchPolicyFromStore(owner, repo, "my-api-key", workflow, runId, correlationId);
|
||||
expect(result).toStrictEqual(response);
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore throws after all retries exhausted", async () => {
|
||||
const owner = "test-owner";
|
||||
const repo = "test-repo";
|
||||
const workflow = "ci.yml";
|
||||
const runId = "12345";
|
||||
const correlationId = "abc-def";
|
||||
|
||||
nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/${repo}/actions/policies/workflow-policy?${policyStoreQueryString(workflow, runId, correlationId)}`)
|
||||
.times(3)
|
||||
.replyWithError("connection refused");
|
||||
|
||||
await expect(
|
||||
fetchPolicyFromStore(owner, repo, "my-api-key", workflow, runId, correlationId)
|
||||
).rejects.toThrow("[Policy Store Fetch]");
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore preserves statusCode from error", async () => {
|
||||
const owner = "test-owner";
|
||||
const repo = "test-repo";
|
||||
const workflow = "ci.yml";
|
||||
const runId = "12345";
|
||||
const correlationId = "abc-def";
|
||||
|
||||
const errorWithStatus = new Error("Unauthorized");
|
||||
(errorWithStatus as any).statusCode = 401;
|
||||
|
||||
nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/${repo}/actions/policies/workflow-policy?${policyStoreQueryString(workflow, runId, correlationId)}`)
|
||||
.times(3)
|
||||
.replyWithError(errorWithStatus);
|
||||
|
||||
try {
|
||||
await fetchPolicyFromStore(owner, repo, "my-api-key", workflow, runId, correlationId);
|
||||
fail("should have thrown");
|
||||
} catch (err) {
|
||||
expect(err.message).toContain("[Policy Store Fetch]");
|
||||
}
|
||||
});
|
||||
|
||||
test("fetchPolicyFromStore sends correct authorization header", async () => {
|
||||
const owner = "test-owner";
|
||||
const repo = "test-repo";
|
||||
const apiKey = "secret-key-123";
|
||||
const workflow = "ci.yml";
|
||||
const runId = "12345";
|
||||
const correlationId = "abc-def";
|
||||
|
||||
nock(`${STEPSECURITY_API_URL}`, {
|
||||
reqheaders: {
|
||||
Authorization: `vm-api-key ${apiKey}`,
|
||||
Source: "github-actions",
|
||||
},
|
||||
})
|
||||
.get(`/github/${owner}/${repo}/actions/policies/workflow-policy?${policyStoreQueryString(workflow, runId, correlationId)}`)
|
||||
.reply(200, { allowed_endpoints: [], egress_policy: "audit" });
|
||||
|
||||
const result = await fetchPolicyFromStore(owner, repo, apiKey, workflow, runId, correlationId);
|
||||
expect(result).toStrictEqual({
|
||||
allowed_endpoints: [],
|
||||
egress_policy: "audit",
|
||||
});
|
||||
});
|
||||
|
||||
// ==================== additional mergeConfigs tests ====================
|
||||
|
||||
test("mergeConfigs does not override local allowed_endpoints if not empty", () => {
|
||||
let localConfig: Configuration = {
|
||||
repo: "test/repo",
|
||||
@@ -318,7 +318,7 @@ test("mergeConfigs does not override local allowed_endpoints if not empty", () =
|
||||
use_policy_store: false,
|
||||
deploy_on_self_hosted_vm: false,
|
||||
};
|
||||
let policyResponse: PolicyResponse = {
|
||||
const policyResponse: PolicyResponse = {
|
||||
allowed_endpoints: ["remote.endpoint:443"],
|
||||
egress_policy: "block",
|
||||
};
|
||||
@@ -350,7 +350,7 @@ test("mergeConfigs overrides disable_sudo_and_containers from remote", () => {
|
||||
use_policy_store: false,
|
||||
deploy_on_self_hosted_vm: false,
|
||||
};
|
||||
let policyResponse: PolicyResponse = {
|
||||
const policyResponse: PolicyResponse = {
|
||||
allowed_endpoints: [],
|
||||
disable_sudo_and_containers: true,
|
||||
};
|
||||
@@ -381,7 +381,7 @@ test("mergeConfigs does not override fields when remote values are undefined", (
|
||||
use_policy_store: false,
|
||||
deploy_on_self_hosted_vm: false,
|
||||
};
|
||||
let policyResponse: PolicyResponse = {
|
||||
const policyResponse: PolicyResponse = {
|
||||
allowed_endpoints: [],
|
||||
};
|
||||
|
||||
|
||||
+54
-47
@@ -1,7 +1,14 @@
|
||||
import { HttpClient } from "@actions/http-client";
|
||||
import { PolicyResponse, Configuration } from "./interfaces";
|
||||
import { STEPSECURITY_API_URL } from "./configs";
|
||||
|
||||
class HttpStatusError extends Error {
|
||||
statusCode: number;
|
||||
constructor(statusCode: number, message: string) {
|
||||
super(message);
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchPolicy(
|
||||
owner: string,
|
||||
policyName: string,
|
||||
@@ -11,43 +18,35 @@ export async function fetchPolicy(
|
||||
throw new Error("[PolicyFetch]: id-token in empty");
|
||||
}
|
||||
|
||||
let policyEndpoint = `${STEPSECURITY_API_URL}/github/${owner}/actions/policies/${policyName}`;
|
||||
const policyEndpoint = `${STEPSECURITY_API_URL}/github/${owner}/actions/policies/${policyName}`;
|
||||
|
||||
let httpClient = new HttpClient();
|
||||
const headers = {
|
||||
Authorization: `Bearer ${idToken}`,
|
||||
Source: "github-actions",
|
||||
};
|
||||
|
||||
let headers = {};
|
||||
headers["Authorization"] = `Bearer ${idToken}`;
|
||||
headers["Source"] = "github-actions";
|
||||
let result: PolicyResponse | undefined;
|
||||
let err: unknown;
|
||||
|
||||
let response = undefined;
|
||||
let err = undefined;
|
||||
|
||||
let retry = 0;
|
||||
while (retry < 3) {
|
||||
for (let retry = 0; retry < 3; retry++) {
|
||||
try {
|
||||
console.log(`Attempt: ${retry + 1}`);
|
||||
response = await httpClient.getJson<PolicyResponse>(
|
||||
policyEndpoint,
|
||||
headers
|
||||
);
|
||||
result = await getJsonWithTimeout<PolicyResponse>(policyEndpoint, headers);
|
||||
break;
|
||||
} catch (e) {
|
||||
err = e;
|
||||
if (retry < 2) await sleep(1000);
|
||||
}
|
||||
retry += 1;
|
||||
await sleep(1000);
|
||||
}
|
||||
|
||||
if (response === undefined && err !== undefined) {
|
||||
// Preserve the original error's statusCode if it exists
|
||||
if (result === undefined) {
|
||||
const error = new Error(`[Policy Fetch] ${err}`);
|
||||
if (err.statusCode !== undefined) {
|
||||
(error as any).statusCode = err.statusCode;
|
||||
if (err && typeof err === "object" && "statusCode" in err) {
|
||||
(error as any).statusCode = (err as { statusCode: unknown }).statusCode;
|
||||
}
|
||||
throw error;
|
||||
} else {
|
||||
return response.result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function fetchPolicyFromStore(
|
||||
@@ -62,46 +61,39 @@ export async function fetchPolicyFromStore(
|
||||
throw new Error("[PolicyStoreFetch]: api-key is empty");
|
||||
}
|
||||
|
||||
let policyEndpoint = `${STEPSECURITY_API_URL}/github/${owner}/${repo}/actions/policies/workflow-policy?workflow=${encodeURIComponent(workflow)}&run_id=${encodeURIComponent(runId)}&correlationId=${encodeURIComponent(correlationId)}`;
|
||||
const policyEndpoint = `${STEPSECURITY_API_URL}/github/${owner}/${repo}/actions/policies/workflow-policy?workflow=${encodeURIComponent(workflow)}&run_id=${encodeURIComponent(runId)}&correlationId=${encodeURIComponent(correlationId)}`;
|
||||
|
||||
let httpClient = new HttpClient();
|
||||
const headers = {
|
||||
Authorization: `vm-api-key ${apiKey}`,
|
||||
Source: "github-actions",
|
||||
};
|
||||
|
||||
let headers = {};
|
||||
headers["Authorization"] = `vm-api-key ${apiKey}`;
|
||||
headers["Source"] = "github-actions";
|
||||
let result: PolicyResponse | undefined;
|
||||
let err: unknown;
|
||||
|
||||
let response = undefined;
|
||||
let err = undefined;
|
||||
|
||||
let retry = 0;
|
||||
while (retry < 3) {
|
||||
for (let retry = 0; retry < 3; retry++) {
|
||||
try {
|
||||
console.log(`Attempt: ${retry + 1}`);
|
||||
response = await httpClient.getJson<PolicyResponse>(
|
||||
policyEndpoint,
|
||||
headers
|
||||
);
|
||||
result = await getJsonWithTimeout<PolicyResponse>(policyEndpoint, headers);
|
||||
break;
|
||||
} catch (e) {
|
||||
// 404 means policy not found — don't retry, return null
|
||||
if (e instanceof HttpStatusError && e.statusCode === 404) {
|
||||
return null;
|
||||
}
|
||||
err = e;
|
||||
if (retry < 2) await sleep(1000);
|
||||
}
|
||||
retry += 1;
|
||||
await sleep(1000);
|
||||
}
|
||||
|
||||
if (response === undefined && err !== undefined) {
|
||||
if (result === undefined) {
|
||||
const error = new Error(`[Policy Store Fetch] ${err}`);
|
||||
if (err.statusCode !== undefined) {
|
||||
(error as any).statusCode = err.statusCode;
|
||||
if (err && typeof err === "object" && "statusCode" in err) {
|
||||
(error as any).statusCode = (err as { statusCode: unknown }).statusCode;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (response.statusCode === 404) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const result = response.result;
|
||||
if (!result || (!result.egress_policy && (!result.allowed_endpoints || result.allowed_endpoints.length === 0))) {
|
||||
return null;
|
||||
}
|
||||
@@ -109,6 +101,21 @@ export async function fetchPolicyFromStore(
|
||||
return result;
|
||||
}
|
||||
|
||||
async function getJsonWithTimeout<T>(
|
||||
url: string,
|
||||
headers: Record<string, string>
|
||||
): Promise<T> {
|
||||
const resp = await fetch(url, {
|
||||
method: "GET",
|
||||
headers,
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
throw new HttpStatusError(resp.status, `HTTP ${resp.status}`);
|
||||
}
|
||||
return (await resp.json()) as T;
|
||||
}
|
||||
|
||||
export function mergeConfigs(
|
||||
localConfig: Configuration,
|
||||
remoteConfig: PolicyResponse
|
||||
|
||||
+109
-11
@@ -1,7 +1,6 @@
|
||||
import * as core from "@actions/core";
|
||||
import * as cp from "child_process";
|
||||
import * as fs from "fs";
|
||||
import * as httpm from "@actions/http-client";
|
||||
import * as path from "path";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import * as common from "./common";
|
||||
@@ -33,11 +32,13 @@ import {
|
||||
import { isGithubHosted, isTLSEnabled } from "./tls-inspect";
|
||||
import {
|
||||
installAgent,
|
||||
installAgentBravo,
|
||||
installMacosAgent,
|
||||
installWindowsAgent,
|
||||
} from "./install-agent";
|
||||
|
||||
import { chownForFolder, isAgentInstalled, isPlatformSupported, shouldDeployAgentOnSelfHosted } from "./utils";
|
||||
import { chownForFolder, detectThirdPartyRunnerProvider, isAgentInstalled, isPlatformSupported, shouldDeployAgentOnSelfHosted } from "./utils";
|
||||
import { buildBravoConfig } from "./bravo-config";
|
||||
|
||||
interface MonitorResponse {
|
||||
runner_ip_address?: string;
|
||||
@@ -45,6 +46,17 @@ interface MonitorResponse {
|
||||
monitoring_started?: boolean;
|
||||
}
|
||||
|
||||
// Node 22+ terminates the process on unhandled promise rejections by default.
|
||||
// Third-party libraries used during Pre-step (notably @actions/cache's tar +
|
||||
// upload streams under concurrent matrix runs) can emit background rejections
|
||||
// that escape our try/catch, killing Pre-step silently and leaving the runner
|
||||
// without an agent installed. Log and continue instead.
|
||||
process.on("unhandledRejection", (reason) => {
|
||||
const detail =
|
||||
reason instanceof Error ? (reason.stack ?? reason.message) : String(reason);
|
||||
core.warning(`Unhandled promise rejection during Pre-step: ${detail}`);
|
||||
});
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
console.log("[harden-runner] pre-step");
|
||||
@@ -64,6 +76,11 @@ interface MonitorResponse {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isGithubHosted() && process.platform === "linux" && !process.env.USER) {
|
||||
console.log(common.UBUNTU_SLIM_MESSAGE);
|
||||
return;
|
||||
}
|
||||
|
||||
var correlation_id = uuidv4();
|
||||
var api_url = STEPSECURITY_API_URL;
|
||||
var web_url = STEPSECURITY_WEB_URL;
|
||||
@@ -100,7 +117,10 @@ interface MonitorResponse {
|
||||
if (confg.use_policy_store) {
|
||||
console.log(`Fetching policy from policy store`);
|
||||
if (confg.api_key === "") {
|
||||
core.setFailed("api-key is required when use-policy-store is set to true");
|
||||
core.warning(
|
||||
"api-key is not set while use-policy-store is true. Defaulting to audit mode."
|
||||
);
|
||||
confg.egress_policy = "audit";
|
||||
} else {
|
||||
try {
|
||||
const repoName = (process.env["GITHUB_REPOSITORY"] || "").split("/")[1] || "";
|
||||
@@ -289,6 +309,31 @@ interface MonitorResponse {
|
||||
const runnerName = process.env.RUNNER_NAME || "";
|
||||
core.info(`RUNNER_NAME: ${runnerName}`);
|
||||
if (!isGithubHosted()) {
|
||||
const thirdPartyProvider = detectThirdPartyRunnerProvider();
|
||||
if (thirdPartyProvider) {
|
||||
const providerLabel = thirdPartyProvider.charAt(0).toUpperCase() + thirdPartyProvider.slice(1);
|
||||
if (process.platform !== "linux" && process.platform !== "darwin") {
|
||||
core.info(`Detected ${providerLabel} runner on ${process.platform}. HardenRunner is not supported on this third-party provider, skipping install.`);
|
||||
return;
|
||||
}
|
||||
core.info(`Detected ${providerLabel} runner environment. Installing agent-bravo.`);
|
||||
confg.correlation_id = runnerName || confg.correlation_id;
|
||||
await callMonitorEndpoint(api_url, confg);
|
||||
const bravoConfigStr = JSON.stringify(buildBravoConfig(confg));
|
||||
switch (process.platform) {
|
||||
case "darwin": {
|
||||
const installed = await installMacosAgent(bravoConfigStr);
|
||||
if (!installed) {
|
||||
core.warning("macos bravo agent installation failed");
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "linux":
|
||||
await installAgentForBravo(context.repo.owner, bravoConfigStr);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
fs.appendFileSync(process.env.GITHUB_STATE, `selfHosted=true${EOL}`, {
|
||||
encoding: "utf8",
|
||||
});
|
||||
@@ -340,22 +385,25 @@ interface MonitorResponse {
|
||||
return;
|
||||
}
|
||||
|
||||
let _http = new httpm.HttpClient();
|
||||
let statusCode: number | undefined;
|
||||
_http.requestOptions = { socketTimeout: 3 * 1000 };
|
||||
let addSummary = "false";
|
||||
try {
|
||||
const monitorRequestData = {
|
||||
correlation_id: correlation_id,
|
||||
job: process.env["GITHUB_JOB"],
|
||||
};
|
||||
const resp = await _http.postJson<MonitorResponse>(
|
||||
`${api_url}/github/${process.env["GITHUB_REPOSITORY"]}/actions/runs/${process.env["GITHUB_RUN_ID"]}/monitor`,
|
||||
monitorRequestData
|
||||
);
|
||||
const url = `${api_url}/github/${process.env["GITHUB_REPOSITORY"]}/actions/runs/${process.env["GITHUB_RUN_ID"]}/monitor`;
|
||||
const resp = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(monitorRequestData),
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
|
||||
const responseData = resp.result;
|
||||
statusCode = resp.statusCode; // adding error code to check whether agent is getting installed or not.
|
||||
statusCode = resp.status;
|
||||
const responseData = resp.ok
|
||||
? ((await resp.json()) as MonitorResponse)
|
||||
: undefined;
|
||||
fs.appendFileSync(
|
||||
process.env.GITHUB_STATE,
|
||||
`monitorStatusCode=${statusCode}${EOL}`,
|
||||
@@ -470,6 +518,36 @@ export function sleep(ms: number) {
|
||||
});
|
||||
}
|
||||
|
||||
async function callMonitorEndpoint(api_url: string, confg: Configuration) {
|
||||
let statusCode: number | undefined;
|
||||
let addSummary = "false";
|
||||
try {
|
||||
const monitorRequestData = {
|
||||
correlation_id: confg.correlation_id,
|
||||
job: process.env["GITHUB_JOB"],
|
||||
};
|
||||
const url = `${api_url}/github/${process.env["GITHUB_REPOSITORY"]}/actions/runs/${process.env["GITHUB_RUN_ID"]}/monitor`;
|
||||
const resp = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(monitorRequestData),
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
statusCode = resp.status;
|
||||
if (resp.ok) {
|
||||
const result = (await resp.json()) as MonitorResponse;
|
||||
console.log(`Runner IP Address: ${result.runner_ip_address}`);
|
||||
confg.one_time_key = result.one_time_key;
|
||||
addSummary = result.monitoring_started ? "true" : "false";
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(`error in connecting to ${api_url}: ${e}`);
|
||||
}
|
||||
fs.appendFileSync(process.env.GITHUB_STATE, `monitorStatusCode=${statusCode}${EOL}`, { encoding: "utf8" });
|
||||
fs.appendFileSync(process.env.GITHUB_STATE, `addSummary=${addSummary}${EOL}`, { encoding: "utf8" });
|
||||
fs.appendFileSync(process.env.GITHUB_STATE, `correlation_id=${confg.correlation_id}${EOL}`, { encoding: "utf8" });
|
||||
}
|
||||
|
||||
export async function installAgentForSelfHosted(owner: string, confg: Configuration) {
|
||||
try {
|
||||
console.log("Installing Harden Runner agent for self-hosted runner");
|
||||
@@ -528,3 +606,23 @@ export async function installAgentForSelfHosted(owner: string, confg: Configurat
|
||||
console.log(`Failed to install agent for self-hosted runner: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function installAgentForBravo(owner: string, bravoConfigStr: string) {
|
||||
try {
|
||||
console.log("Installing Harden Runner bravo agent for third-party runner");
|
||||
|
||||
let isTLS = await isTLSEnabled(owner);
|
||||
|
||||
if (!isTLS) {
|
||||
console.log("TLS is not enabled for this organization. Bravo agent installation skipped.");
|
||||
return;
|
||||
}
|
||||
|
||||
cp.execSync("sudo mkdir -p /home/agent");
|
||||
chownForFolder(process.env.USER, "/home/agent");
|
||||
|
||||
await installAgentBravo(bravoConfigStr);
|
||||
} catch (error) {
|
||||
console.log(`Failed to install bravo agent: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
+64
-16
@@ -1,29 +1,77 @@
|
||||
import nock from "nock";
|
||||
import { STEPSECURITY_API_URL } from "./configs";
|
||||
import { isTLSEnabled } from "./tls-inspect";
|
||||
|
||||
const ORIGINAL_FETCH = globalThis.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = ORIGINAL_FETCH;
|
||||
});
|
||||
|
||||
function mockFetch(impl: typeof fetch) {
|
||||
globalThis.fetch = impl as typeof fetch;
|
||||
}
|
||||
|
||||
test("tls-inspect enabled", async () => {
|
||||
let owner = "h0x0er";
|
||||
let expected = true;
|
||||
const owner = "h0x0er";
|
||||
const expectedUrl = `${STEPSECURITY_API_URL}/github/${owner}/actions/tls-inspection-status`;
|
||||
|
||||
const resp = nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/actions/tls-inspection-status`)
|
||||
.reply(200, "");
|
||||
mockFetch(async (url, _init) => {
|
||||
expect(String(url)).toBe(expectedUrl);
|
||||
return new Response("", { status: 200 });
|
||||
});
|
||||
|
||||
let got = await isTLSEnabled(owner);
|
||||
|
||||
expect(got).toEqual(expected);
|
||||
const got = await isTLSEnabled(owner);
|
||||
expect(got).toBe(true);
|
||||
});
|
||||
|
||||
test("tls-inspect not enabled", async () => {
|
||||
let owner = "step-security";
|
||||
let expected = false;
|
||||
const owner = "step-security";
|
||||
|
||||
const resp = nock(`${STEPSECURITY_API_URL}`)
|
||||
.get(`/github/${owner}/actions/tls-inspection-status`)
|
||||
.reply(401, "");
|
||||
mockFetch(async () => new Response("unauthorized", { status: 401 }));
|
||||
|
||||
let got = await isTLSEnabled(owner);
|
||||
const got = await isTLSEnabled(owner);
|
||||
expect(got).toBe(false);
|
||||
});
|
||||
|
||||
expect(got).toEqual(expected);
|
||||
test("isTLSEnabled returns true within ~3s when server is slow (regression test for AggregateError)", async () => {
|
||||
const owner = "slow-org";
|
||||
|
||||
mockFetch((_url, init) => {
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
const signal = init?.signal;
|
||||
if (signal) {
|
||||
if (signal.aborted) {
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
return;
|
||||
}
|
||||
signal.addEventListener("abort", () => {
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const start = Date.now();
|
||||
const result = await isTLSEnabled(owner);
|
||||
const elapsed = Date.now() - start;
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(elapsed).toBeLessThan(3500);
|
||||
}, 10_000);
|
||||
|
||||
test("isTLSEnabled returns true on connection error without hanging", async () => {
|
||||
const owner = "broken-org";
|
||||
|
||||
mockFetch(async () => {
|
||||
const err = new TypeError("fetch failed");
|
||||
(err as Error & { cause?: unknown }).cause = Object.assign(new Error("ECONNREFUSED"), { code: "ECONNREFUSED" });
|
||||
throw err;
|
||||
});
|
||||
|
||||
const start = Date.now();
|
||||
const result = await isTLSEnabled(owner);
|
||||
const elapsed = Date.now() - start;
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(elapsed).toBeLessThan(3500);
|
||||
});
|
||||
|
||||
+10
-13
@@ -1,26 +1,23 @@
|
||||
import { HttpClient } from "@actions/http-client";
|
||||
import { STEPSECURITY_API_URL } from "./configs";
|
||||
import * as core from "@actions/core";
|
||||
|
||||
export async function isTLSEnabled(owner: string): Promise<boolean> {
|
||||
let tlsStatusEndpoint = `${STEPSECURITY_API_URL}/github/${owner}/actions/tls-inspection-status`;
|
||||
let httpClient = new HttpClient();
|
||||
httpClient.requestOptions = { socketTimeout: 3 * 1000 };
|
||||
const tlsStatusEndpoint = `${STEPSECURITY_API_URL}/github/${owner}/actions/tls-inspection-status`;
|
||||
core.info(`[!] Checking TLS_STATUS: ${owner}`);
|
||||
let isEnabled = false;
|
||||
try {
|
||||
let resp = await httpClient.get(tlsStatusEndpoint);
|
||||
if (resp.message.statusCode === 200) {
|
||||
isEnabled = true;
|
||||
const resp = await fetch(tlsStatusEndpoint, {
|
||||
signal: AbortSignal.timeout(3000),
|
||||
});
|
||||
if (resp.status === 200) {
|
||||
core.info(`[!] TLS_ENABLED: ${owner}`);
|
||||
} else {
|
||||
core.info(`[!] TLS_NOT_ENABLED: ${owner}`);
|
||||
return true;
|
||||
}
|
||||
core.info(`[!] TLS_NOT_ENABLED: ${owner}`);
|
||||
return false;
|
||||
} catch (e) {
|
||||
core.info(`[!] Unable to check TLS_STATUS`);
|
||||
core.info(`[!] Unable to check TLS_STATUS. Defaulting to TLS enabled.`);
|
||||
return true;
|
||||
}
|
||||
|
||||
return isEnabled;
|
||||
}
|
||||
|
||||
export function isGithubHosted() {
|
||||
|
||||
+73
-1
@@ -1,4 +1,4 @@
|
||||
import { shouldDeployAgentOnSelfHosted, isAgentInstalled, isPlatformSupported, getAnnotationLogs } from "./utils";
|
||||
import { shouldDeployAgentOnSelfHosted, isAgentInstalled, isPlatformSupported, getAnnotationLogs, detectThirdPartyRunnerProvider } from "./utils";
|
||||
import * as fs from "fs";
|
||||
|
||||
jest.mock("fs", () => ({
|
||||
@@ -90,3 +90,75 @@ describe("getAnnotationLogs", () => {
|
||||
expect(() => getAnnotationLogs("freebsd" as NodeJS.Platform)).toThrow("platform not supported");
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectThirdPartyRunnerProvider", () => {
|
||||
const originalEnv = process.env;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
delete process.env.DEPOT_RUNNER;
|
||||
delete process.env.NAMESPACE_GITHUB_RUNTIME;
|
||||
delete process.env.BITRISE_IO;
|
||||
delete process.env.RUNNER_NAME;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
process.env = originalEnv;
|
||||
});
|
||||
|
||||
test("returns depot when DEPOT_RUNNER=1", () => {
|
||||
process.env.DEPOT_RUNNER = "1";
|
||||
expect(detectThirdPartyRunnerProvider()).toBe("depot");
|
||||
});
|
||||
|
||||
test("returns null when DEPOT_RUNNER=0", () => {
|
||||
process.env.DEPOT_RUNNER = "0";
|
||||
expect(detectThirdPartyRunnerProvider()).toBeNull();
|
||||
});
|
||||
|
||||
test("returns namespace when NAMESPACE_GITHUB_RUNTIME is set", () => {
|
||||
process.env.NAMESPACE_GITHUB_RUNTIME = "something";
|
||||
expect(detectThirdPartyRunnerProvider()).toBe("namespace");
|
||||
});
|
||||
|
||||
test("returns bitrise when BITRISE_IO is set", () => {
|
||||
process.env.BITRISE_IO = "true";
|
||||
expect(detectThirdPartyRunnerProvider()).toBe("bitrise");
|
||||
});
|
||||
|
||||
test("returns warp for RUNNER_NAME prefix warp-", () => {
|
||||
process.env.RUNNER_NAME = "warp-4x-x64-abc";
|
||||
expect(detectThirdPartyRunnerProvider()).toBe("warp");
|
||||
});
|
||||
|
||||
test("returns blacksmith for RUNNER_NAME prefix blacksmith-", () => {
|
||||
process.env.RUNNER_NAME = "blacksmith-01kpj-4vcpu";
|
||||
expect(detectThirdPartyRunnerProvider()).toBe("blacksmith");
|
||||
});
|
||||
|
||||
test("returns null when no env vars match", () => {
|
||||
expect(detectThirdPartyRunnerProvider()).toBeNull();
|
||||
});
|
||||
|
||||
test("returns null for a non-matching RUNNER_NAME", () => {
|
||||
process.env.RUNNER_NAME = "GitHub Actions 1";
|
||||
expect(detectThirdPartyRunnerProvider()).toBeNull();
|
||||
});
|
||||
|
||||
test("depot takes precedence over namespace", () => {
|
||||
process.env.DEPOT_RUNNER = "1";
|
||||
process.env.NAMESPACE_GITHUB_RUNTIME = "something";
|
||||
expect(detectThirdPartyRunnerProvider()).toBe("depot");
|
||||
});
|
||||
|
||||
test("namespace takes precedence over warp runner name prefix", () => {
|
||||
process.env.NAMESPACE_GITHUB_RUNTIME = "something";
|
||||
process.env.RUNNER_NAME = "warp-x";
|
||||
expect(detectThirdPartyRunnerProvider()).toBe("namespace");
|
||||
});
|
||||
|
||||
test("warp takes precedence over blacksmith when both prefixes seen (warp wins on name check order)", () => {
|
||||
process.env.RUNNER_NAME = "warp-x";
|
||||
expect(detectThirdPartyRunnerProvider()).toBe("warp");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -40,6 +40,18 @@ export function shouldDeployAgentOnSelfHosted(
|
||||
return deployOnSelfHostedVm && !isContainer && !agentAlreadyInstalled;
|
||||
}
|
||||
|
||||
export type ThirdPartyRunnerProvider = "depot" | "namespace" | "warp" | "blacksmith" | "bitrise";
|
||||
|
||||
export function detectThirdPartyRunnerProvider(): ThirdPartyRunnerProvider | null {
|
||||
if (process.env["DEPOT_RUNNER"] === "1") return "depot";
|
||||
if (process.env["NAMESPACE_GITHUB_RUNTIME"]) return "namespace";
|
||||
if (process.env["BITRISE_IO"]) return "bitrise";
|
||||
const runnerName = process.env["RUNNER_NAME"] ?? "";
|
||||
if (runnerName.startsWith("warp-")) return "warp";
|
||||
if (runnerName.startsWith("blacksmith-")) return "blacksmith";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function getAnnotationLogs(platform: NodeJS.Platform) {
|
||||
switch (platform) {
|
||||
case "linux":
|
||||
|
||||
Reference in New Issue
Block a user