Skip to content

Commit e131ba9

Browse files
committed
Add nonceStyleSrcElem() to complete nonce support on element directives
A nonce is valid on the four element directives (script-src, script-src-elem, style-src, style-src-elem) per CSP3. Added the style-src-elem counterpart of nonceScriptSrcElem(). No nonce helper for the -attr directives: a nonce matches elements, not inline event handlers or style attributes, so it could never apply there. No sha helpers for the granular directives - the generic add() attaches precomputed hashes and the -attr hashes need 'unsafe-hashes' to apply.
1 parent 938bf13 commit e131ba9

2 files changed

Lines changed: 21 additions & 0 deletions

File tree

modules/web/web-api/src/main/java/com/enonic/xp/web/csp/ContentSecurityPolicy.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ public final class ContentSecurityPolicy
8787

8888
private static final String STYLE_SRC = "style-src";
8989

90+
private static final String STYLE_SRC_ELEM = "style-src-elem";
91+
9092
private static final String NONE = "'none'";
9193

9294
private static final String NONCE_SOURCE_PREFIX = "'nonce-";
@@ -641,6 +643,16 @@ public String nonceStyleSrc()
641643
return nonceFor( STYLE_SRC );
642644
}
643645

646+
/**
647+
* Wires the request nonce into {@code style-src-elem} and returns its value (for stamping on a
648+
* {@code <style nonce="...">} element that must satisfy a page whose {@code style-src-elem} uses
649+
* {@code 'strict-dynamic'}). A nonce is valid on {@code style-src-elem} per CSP Level 3.
650+
*/
651+
public String nonceStyleSrcElem()
652+
{
653+
return nonceFor( STYLE_SRC_ELEM );
654+
}
655+
644656
/**
645657
* The nonce is a cryptographically random, base64-encoded value (≥ 128 bits of entropy). Every
646658
* {@code nonce*} call returns the same value for the life of this policy instance (= life of

modules/web/web-api/src/test/java/com/enonic/xp/web/csp/ContentSecurityPolicyTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -843,6 +843,15 @@ void nonceScriptSrcElem_wires_the_request_nonce_into_script_src_elem()
843843
assertThat( csp.nonceScriptSrc() ).isEqualTo( nonce );
844844
}
845845

846+
@Test
847+
void nonceStyleSrcElem_wires_the_request_nonce_into_style_src_elem()
848+
{
849+
final ContentSecurityPolicy csp = new ContentSecurityPolicy();
850+
final String nonce = csp.nonceStyleSrcElem();
851+
assertThat( csp.serialize() ).isEqualTo( "style-src-elem 'nonce-" + nonce + "'" );
852+
assertThat( csp.nonceStyleSrc() ).isEqualTo( nonce );
853+
}
854+
846855
@Test
847856
void resetTo_parses_comma_separated_policies_and_round_trips()
848857
{

0 commit comments

Comments
 (0)