Skip to content

Commit

Permalink
[HTTP] Fix CSP config merge behaviour (elastic#177728)
Browse files Browse the repository at this point in the history
  • Loading branch information
jloleysens authored and fkanout committed Mar 4, 2024
1 parent 2c8646b commit 4ef650a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -121,5 +121,28 @@ describe('CspDirectives', () => {
`"script-src 'report-sample' 'self' 'unsafe-hashes'; worker-src 'report-sample' 'self' blob:; style-src 'report-sample' 'self' 'unsafe-inline'"`
);
});

it('merges additional CSP configs as expected', () => {
const config = cspConfig.schema.validate({
connect_src: ['*.foo.bar'], // should de-dupe these
});
const additionalConfig1 = {
connect_src: ['*.foo.bar'],
img_src: ['*.foo.bar'],
};
const additionalConfig2 = {
connect_src: [`cdn.host.test`],
font_src: [`cdn.host.test`],
frame_src: [`cdn.host.test`],
img_src: [`cdn.host.test`],
worker_src: [`cdn.host.test`],
script_src: [`cdn.host.test`],
style_src: [`cdn.host.test`],
};
const directives = CspDirectives.fromConfig(config, additionalConfig1, additionalConfig2);
expect(directives.getCspHeader()).toEqual(
`script-src 'report-sample' 'self' cdn.host.test; worker-src 'report-sample' 'self' blob: cdn.host.test; style-src 'report-sample' 'self' 'unsafe-inline' cdn.host.test; connect-src 'self' *.foo.bar cdn.host.test; font-src 'self' cdn.host.test; frame-src 'self' cdn.host.test; img-src 'self' *.foo.bar cdn.host.test`
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* Side Public License, v 1.
*/

import { merge } from 'lodash';
import deepmerge from 'deepmerge';
import { CspConfigType } from './config';

export type CspDirectiveName =
Expand Down Expand Up @@ -70,7 +70,10 @@ export class CspDirectives {
firstConfig: CspConfigType,
...otherConfigs: Array<Partial<CspConfigType>>
): CspDirectives {
const config = otherConfigs.length ? merge(firstConfig, ...otherConfigs) : firstConfig;
const config = otherConfigs.reduce<CspConfigType>(
(acc, conf) => deepmerge(acc, conf),
firstConfig
);
const cspDirectives = new CspDirectives();

// combining `default` directive configurations
Expand Down

0 comments on commit 4ef650a

Please sign in to comment.