Skip to content
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
2 changes: 1 addition & 1 deletion .github/workflows/sighthound-security-scan.lock.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

90 changes: 32 additions & 58 deletions actions/setup/js/validate_secrets.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
*/

const fs = require("fs");
const https = require("https");
const { promisify } = require("util");
const { exec } = require("child_process");
const execAsync = promisify(exec);
Expand Down Expand Up @@ -47,80 +46,55 @@ const SECRET_DOCS = {
};

/**
* Make an HTTPS request
* Make an HTTPS GET request
* @param {string} hostname
* @param {string} path
* @param {Object} headers
* @param {string} method
* @param {Record<string, string>} headers
* @returns {Promise<{statusCode: number, data: string}>}
*/
function makeRequest(hostname, path, headers, method = "GET") {
return new Promise((resolve, reject) => {
const options = {
hostname,
path,
method,
async function makeRequest(hostname, path, headers) {
try {
const res = await fetch(`https://${hostname}${path}`, {
method: "GET",
headers,
};

const req = https.request(options, res => {
let data = "";
res.on("data", chunk => {
data += chunk;
});
res.on("end", () => {
resolve({ statusCode: res.statusCode || 0, data });
});
});

req.on("error", err => {
reject(err);
signal: AbortSignal.timeout(10000),
});

req.setTimeout(10000, () => {
req.destroy();
reject(new Error("Request timeout"));
});

req.end();
});
const data = await res.text();
return { statusCode: res.status, data };
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
throw new Error("Request timeout");
}
throw err;
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[/codebase-design] makePostRequest silently injects Content-Type: application/json when none is provided. Callers who POST non-JSON bodies (e.g., form-encoded data) will receive a misleading content-type header without any warning.

💡 Suggested fix

Either require callers to always pass Content-Type explicitly, or only spread headers without a default injection:

headers: { ...headers },

If a default is genuinely desired, document it in the JSDoc so callers are aware.

@copilot please address this.


/**
* Make an HTTPS POST request
* @param {string} hostname
* @param {string} path
* @param {Object} headers
* @param {Record<string, string>} headers - If no `Content-Type` key is present (case-insensitive),
* defaults to `application/json`. Pass an explicit `Content-Type` to override.
* @param {string} body
* @returns {Promise<{statusCode: number, data: string}>}
*/
function makePostRequest(hostname, path, headers, body) {
return new Promise((resolve, reject) => {
const options = {
hostname,
path,
async function makePostRequest(hostname, path, headers, body) {
const hasContentType = Object.keys(headers).some(k => k.toLowerCase() === "content-type");
try {
const res = await fetch(`https://${hostname}${path}`, {
method: "POST",
headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
};

const req = https.request(options, res => {
let data = "";
res.on("data", chunk => {
data += chunk;
});
res.on("end", () => {
resolve({ statusCode: res.statusCode || 0, data });
});
headers: hasContentType ? headers : { ...headers, "Content-Type": "application/json" },
body,
signal: AbortSignal.timeout(10000),
});

req.on("error", reject);
req.setTimeout(10000, () => {
req.destroy();
reject(new Error("Request timeout"));
});
req.write(body);
req.end();
});
const data = await res.text();
return { statusCode: res.status, data };
} catch (err) {
if (err instanceof Error && err.name === "AbortError") {
throw new Error("Request timeout");
}
throw err;
}
}

/**
Expand Down
69 changes: 22 additions & 47 deletions actions/setup/js/validate_secrets.test.cjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// @ts-check

import { describe, it, expect, vi, afterEach } from "vitest";
import https from "https";
import { EventEmitter } from "events";
import {
makePostRequest,
testGitHubRESTAPI,
Expand Down Expand Up @@ -121,65 +119,42 @@ describe("validate_secrets", () => {
});

describe("makePostRequest", () => {
/** @type {EventEmitter & {setTimeout: any, destroy: any, write: any, end: any, timeoutCallback?: () => void}} */
let mockRequest;
/** @type {EventEmitter & {statusCode: number}} */
let mockResponse;

afterEach(() => {
vi.restoreAllMocks();
});

function setupHttpsMock(onEnd) {
mockResponse = Object.assign(new EventEmitter(), { statusCode: 200 });
mockRequest = Object.assign(new EventEmitter(), {
setTimeout: vi.fn().mockImplementation((ms, cb) => {
mockRequest.timeoutCallback = cb;
}),
destroy: vi.fn(),
write: vi.fn(),
end: vi.fn().mockImplementation(() => {
if (onEnd) onEnd();
}),
});
vi.spyOn(https, "request").mockImplementation((_options, callback) => {
process.nextTick(() => callback?.(/** @type {any} */ mockResponse));
return /** @type {any} */ mockRequest;
});
vi.unstubAllGlobals();
});

/**
* @param {number} statusCode
* @param {string} responseBody
*/
function mockFetch(statusCode, responseBody) {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({
status: statusCode,
text: () => Promise.resolve(responseBody),
})
);
}

it("resolves with statusCode and data on success", async () => {
setupHttpsMock(() => {
process.nextTick(() => {
mockResponse.emit("data", '{"ok":true}');
mockResponse.emit("end");
});
});
mockFetch(200, '{"ok":true}');

const result = await makePostRequest("api.example.com", "/v1/test", { "Content-Type": "application/json" }, '{"query":"test"}');
expect(result.statusCode).toBe(200);
expect(result.data).toBe('{"ok":true}');
});

it("rejects on request error", async () => {
setupHttpsMock(null);
const networkError = new Error("connection refused");

const promise = makePostRequest("api.example.com", "/v1/test", {}, "{}");
process.nextTick(() => mockRequest.emit("error", networkError));
it("rejects on network error", async () => {
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("connection refused")));

await expect(promise).rejects.toThrow("connection refused");
await expect(makePostRequest("api.example.com", "/v1/test", {}, "{}")).rejects.toThrow("connection refused");
});

it("rejects with timeout error after 10 s", async () => {
setupHttpsMock(null);

const promise = makePostRequest("api.example.com", "/v1/test", {}, "{}");
// Trigger the timeout callback registered via req.setTimeout
process.nextTick(() => mockRequest.timeoutCallback?.());
it("rejects with timeout error on abort", async () => {
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(Object.assign(new Error("The operation was aborted"), { name: "AbortError" })));

await expect(promise).rejects.toThrow("Request timeout");
expect(mockRequest.destroy).toHaveBeenCalled();
await expect(makePostRequest("api.example.com", "/v1/test", {}, "{}")).rejects.toThrow("Request timeout");
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,5 +168,4 @@ describe("no-core-exportvariable-non-string", () => {
],
});
});

});
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,7 @@ export const noCoreExportVariableNonStringRule = createRule({

// Property must be `exportVariable` (direct or computed string-literal access)
const prop = callee.property;
const isExportVariableProp =
(!callee.computed && prop.type === AST_NODE_TYPES.Identifier && prop.name === "exportVariable") ||
(callee.computed && prop.type === AST_NODE_TYPES.Literal && prop.value === "exportVariable");
const isExportVariableProp = (!callee.computed && prop.type === AST_NODE_TYPES.Identifier && prop.name === "exportVariable") || (callee.computed && prop.type === AST_NODE_TYPES.Literal && prop.value === "exportVariable");
if (!isExportVariableProp) return;

// core.exportVariable expects exactly two arguments: (name, value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ const cjsRuleTester = new RuleTester({

describe("require-spawnsync-error-check", () => {
it("uses the correct docs URL", () => {
expect(requireSpawnSyncErrorCheckRule.meta.docs.url).toBe(
"https://github.com/github/gh-aw/tree/main/eslint-factory#require-spawnsync-error-check",
);
expect(requireSpawnSyncErrorCheckRule.meta.docs.url).toBe("https://github.com/github/gh-aw/tree/main/eslint-factory#require-spawnsync-error-check");
});

it("valid: result.error is checked alongside result.status", () => {
Expand Down Expand Up @@ -54,10 +52,7 @@ describe("require-spawnsync-error-check", () => {

it("valid: non-spawnSync call is ignored", () => {
cjsRuleTester.run("require-spawnsync-error-check", requireSpawnSyncErrorCheckRule, {
valid: [
`const result = execSync("git status"); if (!result) throw new Error("failed");`,
`const result = spawnSync; result.toString();`,
],
valid: [`const result = execSync("git status"); if (!result) throw new Error("failed");`, `const result = spawnSync; result.toString();`],
invalid: [],
});
});
Expand Down
Loading
Loading