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
55 changes: 39 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,23 @@ const {
LANGUAGE_API_KEY, LANGUAGE_API_ENDPOINT, DATABASE_CONNECTION_STRING, VALIDATE_SEAT_ASSIGNMENT, APPLICATIONINSIGHTS_CONNECTION_STRING } =
process.env;

const SURVEY_COLUMNS = [
"enterprise_name",
"organization_name",
"repository_name",
"issue_id",
"issue_number",
"PR_number",
"assignee_name",
"is_copilot_used",
"saving_percentage",
"usage_frequency",
"savings_invested",
"comment",
"created_at",
"completed_at",
];

export default (app) => {
// Your code here
app.log.info("Yay, the app was loaded!");
Expand Down Expand Up @@ -279,27 +296,33 @@ export default (app) => {
app.log.info("Database has been created and issue id existence has been confirmed");

if (result.recordset.length > 0) {
// create query
let update_query = `UPDATE [SurveyResults] SET [is_copilot_used] = ${newContent.is_copilot_used}`;

for (let key in newContent) {
if (newContent.hasOwnProperty(key) && newContent[key] !== undefined && key !== "is_copilot_used") {
update_query += `, [${key}] = '${newContent[key]}'`;
}
}

update_query += ` WHERE [issue_id] = ${newContent.issue_id}`;
const updateColumns = SURVEY_COLUMNS.filter(
(column) => column !== "is_copilot_used" && newContent[column] !== undefined
);
const updateRequest = new sql.Request(conn);
updateRequest.input("is_copilot_used", newContent.is_copilot_used);
updateColumns.forEach((column, index) => {
updateRequest.input(`value${index}`, newContent[column]);
});
updateRequest.input("issue_id", newContent.issue_id);
const update_query = `UPDATE [SurveyResults] SET [is_copilot_used] = @is_copilot_used, ${updateColumns
.map((column, index) => `[${column}] = @value${index}`)
.join(", ")} WHERE [issue_id] = @issue_id`;

// update existing record
let update_result = await sql.query(update_query);
let update_result = await updateRequest.query(update_query);
app.log.info(update_result);
} else {
// insert new record if it doesn't exist
let keys = Object.keys(newContent).join(', ');
let values = Object.values(newContent).map(value => `'${value}'`).join(', ');

let insert_query = `INSERT INTO SurveyResults (${keys}) VALUES (${values})`;
let insert_result = await sql.query(insert_query);
const insertColumns = SURVEY_COLUMNS.filter((column) => newContent[column] !== undefined);
const insertRequest = new sql.Request(conn);
insertColumns.forEach((column, index) => {
insertRequest.input(`value${index}`, newContent[column]);
});
const insert_query = `INSERT INTO SurveyResults (${insertColumns
.map((column) => `[${column}]`)
.join(", ")}) VALUES (${insertColumns.map((_, index) => `@value${index}`).join(", ")})`;
let insert_result = await insertRequest.query(insert_query);
app.log.info(insert_result);
}
} catch (err) {
Expand Down
68 changes: 68 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,16 @@ jest.unstable_mockModule("mssql", () => ({
connect: jest.fn(),
query: jest.fn().mockResolvedValue({ recordset: [] }),
close: jest.fn(),
Request: jest.fn().mockImplementation(() => ({
input: jest.fn().mockReturnThis(),
query: jest.fn().mockResolvedValue({}),
})),
},
}));

// Dynamically import the app AFTER mocks are registered
const { default: myProbotApp } = await import("..");
const { default: sql } = await import("mssql");

const requireJSON = createRequire(import.meta.url);
const payload_pr_closed = requireJSON("./fixtures/pull_request.closed.json");
Expand Down Expand Up @@ -174,7 +179,70 @@ describe("My Probot app", () => {
expect(mock.pendingMocks()).toStrictEqual([]);
});

test("parameterizes survey data containing SQL syntax", async () => {
const injection = "'; DROP TABLE SurveyResults;--";
const payload = structuredClone(issue_comment_created);
payload.comment.body = injection;

const mock = nock("https://api.github.com")
.post("/app/installations/35217443/access_tokens")
.reply(200, {
token: "test",
permissions: {
issues: "write",
},
})
.patch("/repos/mageroni/TestRepo/issues/60")
.reply(200);

sql.Request.mockClear();

await probot.receive({ name: "issue_comment", payload });

const request = sql.Request.mock.results[0].value;
const query = request.query.mock.calls[0][0];
expect(query).not.toContain(injection);
const [, columns, values] = query.match(/\(([^)]*)\) VALUES \(([^)]*)\)/);
const commentParam = values.split(", ")[columns.split(", ").indexOf("[comment]")];
expect(commentParam).toMatch(/^@\w+$/);
expect(request.input).toHaveBeenCalledWith(commentParam.slice(1), injection);
expect(mock.pendingMocks()).toStrictEqual([]);
});

test("parameterizes updates to existing survey data", async () => {
const injection = "'; DROP TABLE SurveyResults;--";
const payload = structuredClone(issue_comment_created);
payload.comment.body = injection;
sql.query.mockImplementation((queryParts) => ({
recordset: queryParts.join("").includes("SELECT * FROM SurveyResults") ? [{}] : [],
}));

const mock = nock("https://api.github.com")
.post("/app/installations/35217443/access_tokens")
.reply(200, {
token: "test",
permissions: {
issues: "write",
},
})
.patch("/repos/mageroni/TestRepo/issues/60")
.reply(200);

sql.Request.mockClear();

await probot.receive({ name: "issue_comment", payload });

const request = sql.Request.mock.results[0].value;
const query = request.query.mock.calls[0][0];
expect(query).toContain("UPDATE [SurveyResults]");
expect(query).not.toContain(injection);
expect(query).toContain("[comment] = @value10");
expect(request.input).toHaveBeenCalledWith("value10", injection);
expect(mock.pendingMocks()).toStrictEqual([]);
});

afterEach(() => {
sql.query.mockReset().mockResolvedValue({ recordset: [] });
nock.cleanAll();
nock.enableNetConnect();
});
Expand Down
Loading