Skip to content

Commit

Permalink
fix csp bug
Browse files Browse the repository at this point in the history
  • Loading branch information
LeeCheneler committed Jan 4, 2025
1 parent 8f12286 commit e5d4db0
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/headers/content-security-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,18 @@ export const contentSecurityPolicy = (
];

if (typeof value === "boolean") {
return `${directive}`;
if (value) {
return `${directive}`;
}

return "";
}

const directiveValue = Array.isArray(value) ? value.join(" ") : value;

return `${directive} ${directiveValue}`;
})
.filter(Boolean)
.join(";");

context.response.headers.set("Content-Security-Policy", header);
Expand Down
54 changes: 54 additions & 0 deletions tests/headers/content-security-policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,28 @@ beforeAll(() => {
context.text(StatusCode.OK, "Hello, World!");
});

server.app.get("/upgrade-insecure-requests/true", (context) => {
contentSecurityPolicy(context, {
directives: {
defaultSrc: ["'self'"],
upgradeInsecureRequests: true,
},
});

context.text(StatusCode.OK, "Hello, World!");
});

server.app.get("/upgrade-insecure-requests/false", (context) => {
contentSecurityPolicy(context, {
directives: {
defaultSrc: ["'self'"],
upgradeInsecureRequests: false,
},
});

context.text(StatusCode.OK, "Hello, World!");
});

server.start();
});

Expand All @@ -39,4 +61,36 @@ describe("headers - content-security-policy", () => {
"default-src 'self';script-src 'self' https://example.com",
);
});

it("should set security headers with upgrade-insecure-requests", async () => {
const response = await fetch(
server.url("/upgrade-insecure-requests/true"),
{
method: "GET",
},
);

// drain response to ensure no memory leak
await response.text();

expect(response.headers.get("Content-Security-Policy")).toEqual(
"default-src 'self';upgrade-insecure-requests",
);
});

it("should not set security headers with upgrade-insecure-requests", async () => {
const response = await fetch(
server.url("/upgrade-insecure-requests/false"),
{
method: "GET",
},
);

// drain response to ensure no memory leak
await response.text();

expect(response.headers.get("Content-Security-Policy")).toEqual(
"default-src 'self'",
);
});
});

0 comments on commit e5d4db0

Please sign in to comment.