Skip to content
Myr

feat: improvements to secure headers middleware (#1395)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by jkeys089 · committed by GitHub · parent 4d8034e · Browse files · 4 files+292 added−50 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+292 added−50 removed

  • tests:+139 added−4 removed
  • other:+153 added−46 removed

4 files+292 added−50 removed

modified:deno_dist/middleware/secure-headers/index.ts+75 added-23 removed
modified:src/middleware/secure-headers/index.test.ts+139 added-4 removed
26 unmodified lines
27 expect(res.headers.get('X-Permitted-Cross-Domain-Policies')).toEqual('none')28 expect(res.headers.get('Cross-Origin-Resource-Policy')).toEqual('same-origin')29 expect(res.headers.get('Cross-Origin-Opener-Policy')).toEqual('same-origin')30 expect(res.headers.get('Origin-Agent-Cluster')).toEqual('?1')31 expect(res.headers.get('Content-Security-Policy')).toBeFalsy31 expect(res.headers.get('Content-Security-Policy')).toBeFalsy()32 })3334 it('all headers enabled', async () => {35 const app = new Hono()
27 unmodified lines
63 expect(res.headers.get('Cross-Origin-Resource-Policy')).toEqual('same-origin')64 expect(res.headers.get('Cross-Origin-Opener-Policy')).toEqual('same-origin')65 expect(res.headers.get('Origin-Agent-Cluster')).toEqual('?1')66 expect(res.headers.get('Cross-Origin-Embedder-Policy')).toEqual('require-corp')67 expect(res.headers.get('Content-Security-Policy')).toEqual("defaultSrc 'self'")67 expect(res.headers.get('Content-Security-Policy')).toEqual("default-src 'self'")68 })6970 it('specific headers disabled', async () => {71 const app = new Hono()
54 unmodified lines
126 const res2 = await app.request('/test2')127 expect(res2.headers.get('Strict-Transport-Security')).toEqual('Hono')128 })129130 it('should use custom value when overridden', async () => {131 const app = new Hono()132 app.use(133 '/test',134 secureHeaders({135 strictTransportSecurity: 'max-age=31536000; includeSubDomains; preload;',136 xFrameOptions: 'DENY',137 xXssProtection: '1',138 })139 )140141 const res = await app.request('/test')142 expect(res.headers.get('Strict-Transport-Security')).toEqual(143 'max-age=31536000; includeSubDomains; preload;'144 )145 expect(res.headers.get('X-FRAME-OPTIONS')).toEqual('DENY')146 expect(res.headers.get('X-XSS-Protection')).toEqual('1')147 })148149 it('CSP Setting', async () => {150 const app = new Hono()151 app.use(152 '/test',
18 unmodified lines
171 })172173 const res = await app.request('/test')174 expect(res.headers.get('Content-Security-Policy')).toEqual(156 "defaultSrc 'self'; baseUri 'self'; fontSrc 'self' https: data:; frameAncestors 'self'; imgSrc 'self' data:; objectSrc 'none'; scriptSrc 'self'; scriptSrcAttr 'none'; styleSrc 'self' https: 'unsafe-inline'"175 "default-src 'self'; base-uri 'self'; font-src 'self' https: data:; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src 'self'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'"176 )177 })178179 it('CSP Setting one only', async () => {
11 unmodified lines
191 return c.text('header updated')192 })193194 const res = await app.request('/test')176 expect(res.headers.get('Content-Security-Policy')).toEqual("defaultSrc 'self'")195 expect(res.headers.get('Content-Security-Policy')).toEqual("default-src 'self'")196 })197198 it('No CSP Setting', async () => {199 const app = new Hono()
5 unmodified lines
205206 const res = await app.request('/test')207 expect(res.headers.get('Content-Security-Policy')).toEqual('')208 })209210 it('CSP with reportTo', async () => {211 const app = new Hono()212 app.use(213 '/test1',214 secureHeaders({215 reportingEndpoints: [216 {217 name: 'endpoint-1',218 url: 'https://example.com/reports',219 },220 ],221 contentSecurityPolicy: {222 defaultSrc: ["'self'"],223 reportTo: 'endpoint-1',224 },225 })226 )227228 app.use(229 '/test2',230 secureHeaders({231 reportTo: [232 {233 group: 'endpoint-1',234 max_age: 10886400,235 endpoints: [{ url: 'https://example.com/reports' }],236 },237 ],238 contentSecurityPolicy: {239 defaultSrc: ["'self'"],240 reportTo: 'endpoint-1',241 },242 })243 )244245 app.use(246 '/test3',247 secureHeaders({248 reportTo: [249 {250 group: 'g1',251 max_age: 10886400,252 endpoints: [253 { url: 'https://a.example.com/reports' },254 { url: 'https://b.example.com/reports' },255 ],256 },257 {258 group: 'g2',259 max_age: 10886400,260 endpoints: [261 { url: 'https://c.example.com/reports' },262 { url: 'https://d.example.com/reports' },263 ],264 },265 ],266 contentSecurityPolicy: {267 defaultSrc: ["'self'"],268 reportTo: 'g2',269 },270 })271 )272273 app.use(274 '/test4',275 secureHeaders({276 reportingEndpoints: [277 {278 name: 'e1',279 url: 'https://a.example.com/reports',280 },281 {282 name: 'e2',283 url: 'https://b.example.com/reports',284 },285 ],286 contentSecurityPolicy: {287 defaultSrc: ["'self'"],288 reportTo: 'e1',289 },290 })291 )292293 app.all('*', async (c) => {294 return c.text('header updated')295 })296297 const res1 = await app.request('/test1')298 expect(res1.headers.get('Reporting-Endpoints')).toEqual(299 'endpoint-1="https://example.com/reports"'300 )301 expect(res1.headers.get('Content-Security-Policy')).toEqual(302 "default-src 'self'; report-to endpoint-1"303 )304305 const res2 = await app.request('/test2')306 expect(res2.headers.get('Report-To')).toEqual(307 '{"group":"endpoint-1","max_age":10886400,"endpoints":[{"url":"https://example.com/reports"}]}'308 )309 expect(res2.headers.get('Content-Security-Policy')).toEqual(310 "default-src 'self'; report-to endpoint-1"311 )312313 const res3 = await app.request('/test3')314 expect(res3.headers.get('Report-To')).toEqual(315 '{"group":"g1","max_age":10886400,"endpoints":[{"url":"https://a.example.com/reports"},{"url":"https://b.example.com/reports"}]}, {"group":"g2","max_age":10886400,"endpoints":[{"url":"https://c.example.com/reports"},{"url":"https://d.example.com/reports"}]}'316 )317 expect(res3.headers.get('Content-Security-Policy')).toEqual("default-src 'self'; report-to g2")318319 const res4 = await app.request('/test4')320 expect(res4.headers.get('Reporting-Endpoints')).toEqual(321 'e1="https://a.example.com/reports", e2="https://b.example.com/reports"'322 )323 expect(res4.headers.get('Content-Security-Policy')).toEqual("default-src 'self'; report-to e1")324 })325})
modified:src/middleware/secure-headers/index.ts+75 added-23 removed
1 unmodified line
23interface ContentSecurityPolicyOptions {4 defaultSrc?: string[]5 baseUri?: string[]6 childSrc?: string[]7 connectSrc?: string[]8 fontSrc?: string[]9 formAction?: string[]10 frameAncestors?: string[]11 frameSrc?: string[]12 imgSrc?: string[]13 manifestSrc?: string[]14 mediaSrc?: string[]15 objectSrc?: string[]16 reportTo?: string17 sandbox?: string[]18 scriptSrc?: string[]19 scriptSrcAttr?: string[]20 scriptSrcElem?: string[]21 styleSrc?: string[]22 styleSrcAttr?: string[]23 styleSrcElem?: string[]24 upgradeInsecureRequests?: string[]25 workerSrc?: string[]26}2728interface ReportToOptions {29 group: string30 max_age: number31 endpoints: ReportToEndpoint[]32}3334interface ReportToEndpoint {35 url: string36}3738interface ReportingEndpointOptions {39 name: string40 url: string41}4243type overridableHeader = boolean | string4445interface SecureHeadersOptions {46 contentSecurityPolicy?: ContentSecurityPolicyOptions18 crossOriginEmbedderPolicy?: boolean19 crossOriginResourcePolicy?: boolean20 crossOriginOpenerPolicy?: boolean21 originAgentCluster: boolean22 referrerPolicy?: boolean23 strictTransportSecurity?: boolean24 xContentTypeOptions?: boolean25 xDnsPrefetchControl?: boolean26 xDownloadOptions?: boolean27 xFrameOptions?: boolean28 xPermittedCrossDomainPolicies?: boolean29 xXssProtection?: boolean47 crossOriginEmbedderPolicy?: overridableHeader48 crossOriginResourcePolicy?: overridableHeader49 crossOriginOpenerPolicy?: overridableHeader50 originAgentCluster: overridableHeader51 referrerPolicy?: overridableHeader52 reportingEndpoints?: ReportingEndpointOptions[]53 reportTo?: ReportToOptions[]54 strictTransportSecurity?: overridableHeader55 xContentTypeOptions?: overridableHeader56 xDnsPrefetchControl?: overridableHeader57 xDownloadOptions?: overridableHeader58 xFrameOptions?: overridableHeader59 xPermittedCrossDomainPolicies?: overridableHeader60 xXssProtection?: overridableHeader61}6263type HeadersMap = {64 [key in keyof SecureHeadersOptions]: [string, string]
13 unmodified lines
78 xPermittedCrossDomainPolicies: ['X-Permitted-Cross-Domain-Policies', 'none'],79 xXssProtection: ['X-XSS-Protection', '0'],80}8151const DEFAULT_OPTIONS = {82const DEFAULT_OPTIONS: SecureHeadersOptions = {83 crossOriginEmbedderPolicy: false,84 crossOriginResourcePolicy: true,85 crossOriginOpenerPolicy: true,86 originAgentCluster: true,
10 unmodified lines
97export const secureHeaders = (customOptions?: Partial<SecureHeadersOptions>): MiddlewareHandler => {98 const options = { ...DEFAULT_OPTIONS, ...customOptions }99 const headersToSet = Object.entries(HEADERS_MAP)100 .filter(([key]) => options[key as keyof SecureHeadersOptions])70 .map(([, value]) => value)101 .map(([key, defaultValue]) => {102 const overrideValue = options[key as keyof SecureHeadersOptions]103 if (typeof overrideValue === 'string') return [defaultValue[0], overrideValue]104 return defaultValue105 })106107 if (options.contentSecurityPolicy) {108 const cspDirectives = Object.entries(options.contentSecurityPolicy)109 .map(([directive, value]) => {110 // convert camelCase to kebab-case directives (e.g. `defaultSrc` -> `default-src`)111 directive = directive.replace(112 /[A-Z]+(?![a-z])|[A-Z]/g,113 (match, offset) => (offset ? '-' : '') + match.toLowerCase()114 )115 return `${directive} ${Array.isArray(value) ? value.join(' ') : value}`116 })117 .join('; ')118 headersToSet.push(['Content-Security-Policy', cspDirectives])119 }120121 if (options.reportingEndpoints) {122 const reportingEndpoints = options.reportingEndpoints123 .map((endpoint) => `${endpoint.name}="${endpoint.url}"`)124 .join(', ')125 headersToSet.push(['Reporting-Endpoints', reportingEndpoints])126 }127128 if (options.reportTo) {129 const reportToOptions = options.reportTo.map((option) => JSON.stringify(option)).join(', ')130 headersToSet.push(['Report-To', reportToOptions])131 }132133 return async (ctx, next) => {134 await next()135 headersToSet.forEach(([header, value]) => {136 ctx.res.headers.set(header, value)137 })13878 if (options.contentSecurityPolicy) {79 const cspDirectives = Object.entries(options.contentSecurityPolicy)80 .map(([directive, sources]) => {81 return `${directive} ${sources.join(' ')}`82 })83 .join('; ')84 ctx.res.headers.set('Content-Security-Policy', cspDirectives)85 }86139 ctx.res.headers.delete('X-Powered-By')140 }141}
modified:.gitignore+3 added
131 unmodified lines
132.yarn/unplugged133.yarn/build-state.yml134.yarn/install-state.gz135.pnp.*136137# IDE-specific settings138.idea