feat(secureHeader): add CSP Report-Only mode support (#3413)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Hiroki Isogai · committed by GitHub · parent fe0a82a · Browse files · 2 files·+258 added−235 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+258 added−235 removed
- tests:+244 added−234 removed
- other:+14 added−1 removed
Provenance
- Commit
8130a67- Tree
7e0d3a3- Author
Hiroki Isogai <prog@d2deck.com>- Committer
GitHub <noreply@github.com>- Parent
fe0a82a
2 files changed+258 added−235 removed
modified:src/middleware/secure-headers/index.test.ts+244 added-234 removed
36 unmodified lines37 expect(res.headers.get('Cross-Origin-Opener-Policy')).toEqual('same-origin')38 expect(res.headers.get('Origin-Agent-Cluster')).toEqual('?1')39 expect(res.headers.get('Permissions-Policy')).toBeNull()40 expect(res.headers.get('Content-Security-Policy')).toBeFalsy()41+ expect(res.headers.get('Content-Security-Policy-ReportOnly')).toBeFalsy()42 })43 44 it('all headers enabled', async () => {45 const app = new Hono()2 unmodified lines48 secureHeaders({49 contentSecurityPolicy: {50 defaultSrc: ["'self'"],51 },52+ contentSecurityPolicyReportOnly: {53+ defaultSrc: ["'self'"],54+ },55 crossOriginEmbedderPolicy: true,56 permissionsPolicy: {57 camera: [],58 },22 unmodified lines81 expect(res.headers.get('Origin-Agent-Cluster')).toEqual('?1')82 expect(res.headers.get('Cross-Origin-Embedder-Policy')).toEqual('require-corp')83 expect(res.headers.get('Permissions-Policy')).toEqual('camera=()')84 expect(res.headers.get('Content-Security-Policy')).toEqual("default-src 'self'")85+ expect(res.headers.get('Content-Security-Policy-Report-Only')).toEqual("default-src 'self'")86 })87 88 it('specific headers disabled', async () => {89 const app = new Hono()103 unmodified lines193 'accelerometer=("https://*.example.com"), gyroscope=(src), ' +194 'magnetometer=("https://a.example.com" "https://b.example.com")'195 )196 })192- it('CSP Setting', async () => {197+198+ it('Remove X-Powered-By', async () => {199 const app = new Hono()194- app.use(195- '/test',196- secureHeaders({197- contentSecurityPolicy: {198- defaultSrc: ["'self'"],199- baseUri: ["'self'"],200- fontSrc: ["'self'", 'https:', 'data:'],201- frameAncestors: ["'self'"],202- imgSrc: ["'self'", 'data:'],203- objectSrc: ["'none'"],204- scriptSrc: ["'self'"],205- scriptSrcAttr: ["'none'"],206- styleSrc: ["'self'", 'https:', "'unsafe-inline'"],207- },208- })209- )200 211- app.all('*', async (c) => {212- c.res.headers.set('Strict-Transport-Security', 'Hono')213- return c.text('header updated')201+ app.get('/test', secureHeaders(), poweredBy(), async (c) => {202+ return c.text('Hono is cool')203 })204 216- const res = await app.request('/test')217- expect(res.headers.get('Content-Security-Policy')).toEqual(218- "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'"219- )220- })221-222- it('CSP Setting one only', async () => {223- const app = new Hono()224- app.use(225- '/test',205+ app.get(206+ '/test2',207 secureHeaders({227- contentSecurityPolicy: {228- defaultSrc: ["'self'"],229- },230- })208+ removePoweredBy: false,209+ }),210+ poweredBy(),211+ async (c) => {212+ return c.text('Hono is cool')213+ }214 )215 233- app.all('*', async (c) => {234- return c.text('header updated')235- })236-216 const res = await app.request('/test')238- expect(res.headers.get('Content-Security-Policy')).toEqual("default-src 'self'")239- })217+ const poweredby = res.headers.get('X-Powered-By')218+ expect(poweredby).toEqual(null)219+ expect(await res.text()).toEqual('Hono is cool')220 241- it('No CSP Setting', async () => {242- const app = new Hono()243- app.use('/test', secureHeaders({ contentSecurityPolicy: {} }))244-245- app.all('*', async (c) => {246- return c.text('header updated')247- })248-249- const res = await app.request('/test')250- expect(res.headers.get('Content-Security-Policy')).toEqual('')221+ const res2 = await app.request('/test2')222+ const poweredby2 = res2.headers.get('X-Powered-By')223+ expect(poweredby2).toEqual('Hono')224+ expect(await res2.text()).toEqual('Hono is cool')225 })226 227+ describe.each([228+ { cspSettingName: 'contentSecurityPolicy', cspHeaderName: 'Content-Security-Policy' },229+ {230+ cspSettingName: 'contentSecurityPolicyReportOnly',231+ cspHeaderName: 'Content-Security-Policy-Report-Only',232+ },233+ ])('CSP Setting ($cspSettingName)', ({ cspSettingName, cspHeaderName }) => {253- it('CSP with reportTo', async () => {254- const app = new Hono()255- app.use(256- '/test1',257- secureHeaders({258- reportingEndpoints: [259- {260- name: 'endpoint-1',261- url: 'https://example.com/reports',234+ it('CSP Setting', async () => {235+ const app = new Hono()236+ app.use(237+ '/test',238+ secureHeaders({239+ [cspSettingName]: {240+ defaultSrc: ["'self'"],241+ baseUri: ["'self'"],242+ fontSrc: ["'self'", 'https:', 'data:'],243+ frameAncestors: ["'self'"],244+ imgSrc: ["'self'", 'data:'],245+ objectSrc: ["'none'"],246+ scriptSrc: ["'self'"],247+ scriptSrcAttr: ["'none'"],248+ styleSrc: ["'self'", 'https:', "'unsafe-inline'"],249 },263- ],264- contentSecurityPolicy: {265- defaultSrc: ["'self'"],266- reportTo: 'endpoint-1',267- },268- })269- )250+ })251+ )252 271- app.use(272- '/test2',273- secureHeaders({274- reportTo: [275- {276- group: 'endpoint-1',277- max_age: 10886400,278- endpoints: [{ url: 'https://example.com/reports' }],279- },280- ],281- contentSecurityPolicy: {282- defaultSrc: ["'self'"],283- reportTo: 'endpoint-1',284- },253+ app.all('*', async (c) => {254+ c.res.headers.set('Strict-Transport-Security', 'Hono')255+ return c.text('header updated')256 })286- )257 288- app.use(289- '/test3',290- secureHeaders({291- reportTo: [292- {293- group: 'g1',294- max_age: 10886400,295- endpoints: [296- { url: 'https://a.example.com/reports' },297- { url: 'https://b.example.com/reports' },298- ],258+ const res = await app.request('/test')259+ expect(res.headers.get(cspHeaderName)).toEqual(260+ "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'"261+ )262+ })263+264+ it('CSP Setting one only', async () => {265+ const app = new Hono()266+ app.use(267+ '/test',268+ secureHeaders({269+ [cspSettingName]: {270+ defaultSrc: ["'self'"],271 },300- {301- group: 'g2',302- max_age: 10886400,303- endpoints: [304- { url: 'https://c.example.com/reports' },305- { url: 'https://d.example.com/reports' },306- ],307- },308- ],309- contentSecurityPolicy: {310- defaultSrc: ["'self'"],311- reportTo: 'g2',312- },272+ })273+ )274+275+ app.all('*', async (c) => {276+ return c.text('header updated')277 })314- )278 316- app.use(317- '/test4',318- secureHeaders({319- reportingEndpoints: [320- {321- name: 'e1',322- url: 'https://a.example.com/reports',323- },324- {325- name: 'e2',326- url: 'https://b.example.com/reports',327- },328- ],329- contentSecurityPolicy: {330- defaultSrc: ["'self'"],331- reportTo: 'e1',332- },279+ const res = await app.request('/test')280+ expect(res.headers.get(cspHeaderName)).toEqual("default-src 'self'")281+ })282+283+ it('No CSP Setting', async () => {284+ const app = new Hono()285+ app.use('/test', secureHeaders({ [cspSettingName]: {} }))286+287+ app.all('*', async (c) => {288+ return c.text('header updated')289 })334- )290 336- app.all('*', async (c) => {337- return c.text('header updated')291+ const res = await app.request('/test')292+ expect(res.headers.get(cspHeaderName)).toEqual('')293 })294 340- const res1 = await app.request('/test1')341- expect(res1.headers.get('Reporting-Endpoints')).toEqual(342- 'endpoint-1="https://example.com/reports"'343- )344- expect(res1.headers.get('Content-Security-Policy')).toEqual(345- "default-src 'self'; report-to endpoint-1"346- )295+ it('CSP with reportTo', async () => {296+ const app = new Hono()297+ app.use(298+ '/test1',299+ secureHeaders({300+ reportingEndpoints: [301+ {302+ name: 'endpoint-1',303+ url: 'https://example.com/reports',304+ },305+ ],306+ [cspSettingName]: {307+ defaultSrc: ["'self'"],308+ reportTo: 'endpoint-1',309+ },310+ })311+ )312 348- const res2 = await app.request('/test2')349- expect(res2.headers.get('Report-To')).toEqual(350- '{"group":"endpoint-1","max_age":10886400,"endpoints":[{"url":"https://example.com/reports"}]}'351- )352- expect(res2.headers.get('Content-Security-Policy')).toEqual(353- "default-src 'self'; report-to endpoint-1"354- )313+ app.use(314+ '/test2',315+ secureHeaders({316+ reportTo: [317+ {318+ group: 'endpoint-1',319+ max_age: 10886400,320+ endpoints: [{ url: 'https://example.com/reports' }],321+ },322+ ],323+ [cspSettingName]: {324+ defaultSrc: ["'self'"],325+ reportTo: 'endpoint-1',326+ },327+ })328+ )329 356- const res3 = await app.request('/test3')357- expect(res3.headers.get('Report-To')).toEqual(358- '{"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"}]}'359- )360- expect(res3.headers.get('Content-Security-Policy')).toEqual("default-src 'self'; report-to g2")330+ app.use(331+ '/test3',332+ secureHeaders({333+ reportTo: [334+ {335+ group: 'g1',336+ max_age: 10886400,337+ endpoints: [338+ { url: 'https://a.example.com/reports' },339+ { url: 'https://b.example.com/reports' },340+ ],341+ },342+ {343+ group: 'g2',344+ max_age: 10886400,345+ endpoints: [346+ { url: 'https://c.example.com/reports' },347+ { url: 'https://d.example.com/reports' },348+ ],349+ },350+ ],351+ [cspSettingName]: {352+ defaultSrc: ["'self'"],353+ reportTo: 'g2',354+ },355+ })356+ )357 362- const res4 = await app.request('/test4')363- expect(res4.headers.get('Reporting-Endpoints')).toEqual(364- 'e1="https://a.example.com/reports", e2="https://b.example.com/reports"'365- )366- expect(res4.headers.get('Content-Security-Policy')).toEqual("default-src 'self'; report-to e1")367- })358+ app.use(359+ '/test4',360+ secureHeaders({361+ reportingEndpoints: [362+ {363+ name: 'e1',364+ url: 'https://a.example.com/reports',365+ },366+ {367+ name: 'e2',368+ url: 'https://b.example.com/reports',369+ },370+ ],371+ [cspSettingName]: {372+ defaultSrc: ["'self'"],373+ reportTo: 'e1',374+ },375+ })376+ )377 369- it('CSP nonce for script-src', async () => {370- const app = new Hono()371- app.use(372- '/test',373- secureHeaders({374- contentSecurityPolicy: {375- scriptSrc: ["'self'", NONCE],376- },378+ app.all('*', async (c) => {379+ return c.text('header updated')380 })378- )381 380- app.all('*', async (c) => {381- return c.text(`nonce: ${c.get('secureHeadersNonce')}`)382- })382+ const res1 = await app.request('/test1')383+ expect(res1.headers.get('Reporting-Endpoints')).toEqual(384+ 'endpoint-1="https://example.com/reports"'385+ )386+ expect(res1.headers.get(cspHeaderName)).toEqual("default-src 'self'; report-to endpoint-1")387 384- const res = await app.request('/test')385- const csp = res.headers.get('Content-Security-Policy')386- const nonce = csp?.match(/script-src 'self' 'nonce-([a-zA-Z0-9+/]+=*)'/)?.[1] || ''387- expect(csp).toMatch(`script-src 'self' 'nonce-${nonce}'`)388- expect(await res.text()).toEqual(`nonce: ${nonce}`)389- })388+ const res2 = await app.request('/test2')389+ expect(res2.headers.get('Report-To')).toEqual(390+ '{"group":"endpoint-1","max_age":10886400,"endpoints":[{"url":"https://example.com/reports"}]}'391+ )392+ expect(res2.headers.get(cspHeaderName)).toEqual("default-src 'self'; report-to endpoint-1")393 391- it('CSP nonce for script-src and style-src', async () => {392- const app = new Hono()393- app.use(394- '/test',395- secureHeaders({396- contentSecurityPolicy: {397- scriptSrc: ["'self'", NONCE],398- styleSrc: ["'self'", NONCE],399- },400- })401- )394+ const res3 = await app.request('/test3')395+ expect(res3.headers.get('Report-To')).toEqual(396+ '{"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"}]}'397+ )398+ expect(res3.headers.get(cspHeaderName)).toEqual("default-src 'self'; report-to g2")399 403- app.all('*', async (c) => {404- return c.text(`nonce: ${c.get('secureHeadersNonce')}`)400+ const res4 = await app.request('/test4')401+ expect(res4.headers.get('Reporting-Endpoints')).toEqual(402+ 'e1="https://a.example.com/reports", e2="https://b.example.com/reports"'403+ )404+ expect(res4.headers.get(cspHeaderName)).toEqual("default-src 'self'; report-to e1")405 })406 407- const res = await app.request('/test')408- const csp = res.headers.get('Content-Security-Policy')409- const nonce = csp?.match(/script-src 'self' 'nonce-([a-zA-Z0-9+/]+=*)'/)?.[1] || ''410- expect(csp).toMatch(`script-src 'self' 'nonce-${nonce}'`)411- expect(csp).toMatch(`style-src 'self' 'nonce-${nonce}'`)412- expect(await res.text()).toEqual(`nonce: ${nonce}`)413- })407+ it('CSP nonce for script-src', async () => {408+ const app = new Hono()409+ app.use(410+ '/test',411+ secureHeaders({412+ [cspSettingName]: {413+ scriptSrc: ["'self'", NONCE],414+ },415+ })416+ )417 415- it('CSP nonce by app own function', async () => {416- const app = new Hono()417- const setNonce: ContentSecurityPolicyOptionHandler = (ctx, directive) => {418- ctx.set(`test-${directive}-nonce`, directive)419- return `'nonce-${directive}'`420- }421- app.use(422- '/test',423- secureHeaders({424- contentSecurityPolicy: {425- scriptSrc: ["'self'", setNonce],426- styleSrc: ["'self'", setNonce],427- },418+ app.all('*', async (c) => {419+ return c.text(`nonce: ${c.get('secureHeadersNonce')}`)420 })429- )421 431- app.all('*', async (c) => {432- return c.text(433- `script: ${c.get('test-scriptSrc-nonce')}, style: ${c.get('test-styleSrc-nonce')}`434- )422+ const res = await app.request('/test')423+ const csp = res.headers.get(cspHeaderName)424+ const nonce = csp?.match(/script-src 'self' 'nonce-([a-zA-Z0-9+/]+=*)'/)?.[1] || ''425+ expect(csp).toMatch(`script-src 'self' 'nonce-${nonce}'`)426+ expect(await res.text()).toEqual(`nonce: ${nonce}`)427 })428 437- const res = await app.request('/test')438- const csp = res.headers.get('Content-Security-Policy')439- expect(csp).toMatch(`script-src 'self' 'nonce-scriptSrc'`)440- expect(csp).toMatch(`style-src 'self' 'nonce-styleSrc'`)441- expect(await res.text()).toEqual('script: scriptSrc, style: styleSrc')442- })429+ it('CSP nonce for script-src and style-src', async () => {430+ const app = new Hono()431+ app.use(432+ '/test',433+ secureHeaders({434+ [cspSettingName]: {435+ scriptSrc: ["'self'", NONCE],436+ styleSrc: ["'self'", NONCE],437+ },438+ })439+ )440 444- it('Remove X-Powered-By', async () => {445- const app = new Hono()441+ app.all('*', async (c) => {442+ return c.text(`nonce: ${c.get('secureHeadersNonce')}`)443+ })444 447- app.get('/test', secureHeaders(), poweredBy(), async (c) => {448- return c.text('Hono is cool')445+ const res = await app.request('/test')446+ const csp = res.headers.get(cspHeaderName)447+ const nonce = csp?.match(/script-src 'self' 'nonce-([a-zA-Z0-9+/]+=*)'/)?.[1] || ''448+ expect(csp).toMatch(`script-src 'self' 'nonce-${nonce}'`)449+ expect(csp).toMatch(`style-src 'self' 'nonce-${nonce}'`)450+ expect(await res.text()).toEqual(`nonce: ${nonce}`)451 })452 451- app.get(452- '/test2',453- secureHeaders({454- removePoweredBy: false,455- }),456- poweredBy(),457- async (c) => {458- return c.text('Hono is cool')453+ it('CSP nonce by app own function', async () => {454+ const app = new Hono()455+ const setNonce: ContentSecurityPolicyOptionHandler = (ctx, directive) => {456+ ctx.set(`test-${directive}-nonce`, directive)457+ return `'nonce-${directive}'`458 }459+ app.use(460+ '/test',461+ secureHeaders({462+ [cspSettingName]: {463+ scriptSrc: ["'self'", setNonce],464+ styleSrc: ["'self'", setNonce],465+ },466+ })460- )467+ )468 462- const res = await app.request('/test')463- const poweredby = res.headers.get('X-Powered-By')464- expect(poweredby).toEqual(null)465- expect(await res.text()).toEqual('Hono is cool')469+ app.all('*', async (c) => {470+ return c.text(471+ `script: ${c.get('test-scriptSrc-nonce')}, style: ${c.get('test-styleSrc-nonce')}`472+ )473+ })474 467- const res2 = await app.request('/test2')468- const poweredby2 = res2.headers.get('X-Powered-By')469- expect(poweredby2).toEqual('Hono')470- expect(await res2.text()).toEqual('Hono is cool')475+ const res = await app.request('/test')476+ const csp = res.headers.get(cspHeaderName)477+ expect(csp).toMatch(`script-src 'self' 'nonce-scriptSrc'`)478+ expect(csp).toMatch(`style-src 'self' 'nonce-styleSrc'`)479+ expect(await res.text()).toEqual('script: scriptSrc, style: styleSrc')480+ })481 })482 })modified:src/middleware/secure-headers/secure-headers.ts+14 added-1 removed
63 unmodified lines64 type overridableHeader = boolean | string65 66 interface SecureHeadersOptions {67 contentSecurityPolicy?: ContentSecurityPolicyOptions68+ contentSecurityPolicyReportOnly?: ContentSecurityPolicyOptions69 crossOriginEmbedderPolicy?: overridableHeader70 crossOriginResourcePolicy?: overridableHeader71 crossOriginOpenerPolicy?: overridableHeader72 originAgentCluster?: overridableHeader75 unmodified lines148 * @see {@link https://hono.dev/docs/middleware/builtin/secure-headers}149 *150 * @param {Partial<SecureHeadersOptions>} [customOptions] - The options for the secure headers middleware.151 * @param {ContentSecurityPolicyOptions} [customOptions.contentSecurityPolicy] - Settings for the Content-Security-Policy header.152+ * @param {ContentSecurityPolicyOptions} [customOptions.contentSecurityPolicyReportOnly] - Settings for the Content-Security-Policy-Report-Only header.153 * @param {overridableHeader} [customOptions.crossOriginEmbedderPolicy=false] - Settings for the Cross-Origin-Embedder-Policy header.154 * @param {overridableHeader} [customOptions.crossOriginResourcePolicy=true] - Settings for the Cross-Origin-Resource-Policy header.155 * @param {overridableHeader} [customOptions.crossOriginOpenerPolicy=true] - Settings for the Cross-Origin-Opener-Policy header.156 * @param {overridableHeader} [customOptions.originAgentCluster=true] - Settings for the Origin-Agent-Cluster header.29 unmodified lines186 }187 headersToSet.push(['Content-Security-Policy', value as string])188 }189 190+ if (options.contentSecurityPolicyReportOnly) {191+ const [callback, value] = getCSPDirectives(options.contentSecurityPolicyReportOnly)192+ if (callback) {193+ callbacks.push(callback)194+ }195+ headersToSet.push(['Content-Security-Policy-Report-Only', value as string])196+ }197+198 if (options.permissionsPolicy && Object.keys(options.permissionsPolicy).length > 0) {199 headersToSet.push([200 'Permissions-Policy',201 getPermissionsPolicyDirectives(options.permissionsPolicy),65 unmodified lines267 ? [undefined, resultValues.join('')]268 : [269 (ctx, headersToSet) =>270 headersToSet.map((values) => {261- if (values[0] === 'Content-Security-Policy') {271+ if (272+ values[0] === 'Content-Security-Policy' ||273+ values[0] === 'Content-Security-Policy-Report-Only'274+ ) {275 const clone = values[1].slice() as unknown as string[]276 callbacks.forEach((cb) => {277 cb(ctx, clone)278 })54 unmodified lines