resume/tests/headers.spec.js

61 lines
2.6 KiB
JavaScript

const { test, expect } = require('@playwright/test');
test.describe('Security Headers Tests', () => {
test('should have all required security headers', async ({ page }) => {
// Navigate to the page
await page.goto('http://localhost:8080');
// Get response headers
const response = await page.waitForResponse('http://localhost:8080');
const headers = response.headers();
// Define required headers and their expected values
const requiredHeaders = {
'Content-Security-Policy': expect.stringContaining("default-src 'self'"),
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': expect.stringContaining('geolocation=()'),
'Strict-Transport-Security': expect.stringContaining('max-age=31536000'),
};
// Check each required header
for (const [header, expectedValue] of Object.entries(requiredHeaders)) {
const headerValue = headers[header.toLowerCase()];
expect(headerValue).toBeDefined();
if (typeof expectedValue === 'string') {
expect(headerValue).toBe(expectedValue);
} else {
expect(headerValue).toMatch(expectedValue);
}
}
});
test('should have correct CSP directives with nonce and hash', async ({ page }) => {
await page.goto('http://localhost:8080');
const response = await page.waitForResponse('http://localhost:8080');
const headers = response.headers();
const csp = headers['content-security-policy'];
// Check for essential CSP directives
expect(csp).toContain("default-src 'self'");
expect(csp).toContain("script-src 'self' 'nonce-");
expect(csp).toContain("'sha256-ryQsJ+aghKKD/CeXgx8jtsnZT3Epp3EjIw8RyHIq544='");
expect(csp).toContain("style-src 'self' 'unsafe-inline'");
expect(csp).toContain("img-src 'self' data: https: http:");
expect(csp).toContain("font-src 'self'");
expect(csp).toContain("connect-src 'self'");
});
test('should have nonce attributes on script tags', async ({ page }) => {
await page.goto('http://localhost:8080');
// Check that all script tags have nonce attributes
const scripts = await page.$$('script');
for (const script of scripts) {
const hasNonce = await script.evaluate(el => el.hasAttribute('nonce'));
expect(hasNonce).toBeTruthy();
}
});
});