Jenkins - HTML Publisher Plugin - No CSS is displayed when report is viewed in Jenkins Server
Asked Answered
W

21

134

I have a strange problem with the Jenkins HTML Publisher plugin, wherein all the fancy CSS I have added to the report is stripped out when viewed in Jenkins. If I download the report to local, I am able to see the CSS formatting. Is there a setting in Jenkins which allows CSS to be viewed?

My HTML Publisher Settings in Jenkins:

enter image description here

My Report Page when displayed in Jenkins :

enter image description here

My Report Page when displayed in Local :

enter image description here

Woodrum answered 3/3, 2016 at 22:3 Comment(2)
Possible duplicate of Jenkins HTML Publisher Plugin: No external links with Jenkins 1.643Tuba
Everyone is saying you "fix" it by disabling the Content Security Policy, without any thought as to why it's there in the first place. Anyone who can affect the changes to be built will be able to hijack the admin credentials and gain access to the whole Jenkins cluster. While inline css is mostly safe if you're careful, allowing scripts is a disaster.Garnet
W
240

Figured out the issue. Sharing it here for other users.

CSS is stripped out because of the Content Security Policy in Jenkins. (https://wiki.jenkins-ci.org/display/JENKINS/Configuring+Content+Security+Policy)

The default rule is set to:

sandbox; default-src 'none'; img-src 'self'; style-src 'self';

This rule set results in the following:

  • No JavaScript allowed at all
  • No plugins (object/embed) allowed
  • No inline CSS, or CSS from other sites allowed
  • No images from other sites allowed
  • No frames allowed
  • No web fonts allowed
  • No XHR/AJAX allowed, etc.

To relax this rule, go to

  1. Manage Jenkins->
  2. Manage Nodes->
  3. Click settings(gear icon)->
  4. click Script console on left and type in the following command:

    System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "")

and Press Run. If you see the output as 'Result:' below "Result" header then the protection disabled. Re-Run your build and you can see that the new HTML files archived will have the CSS enabled.

Woodrum answered 4/3, 2016 at 0:25 Comment(9)
@Steerpike I wondered what you meant and then found out that the css was blocked upon restarting Jenkins. So I created a Jenkins job that runs the command every 12 hours. Seems to do the trick.Neve
@Neve thank you - I am a Jenkins novice - how do I setup that job? Setup a general job with a Build Step of Execute Windows Batch Command?Resinoid
@Resinoid That's right except it is a groovy command, so you need to execute it in an "Execute system Groovy Script" build step. And then under the "Build Triggers" section I selected "Build Periodically" with this value: H 12 * * *Neve
Actually , you don't even need to rerun your build. Simply reload the generated HTML from Jenkins and it would take the effect of the policy change.Hangman
Setting this property to an empty string seems to solve the problem for CSS, but inline JS is still not executed (console log shows Content Security Policy: The page’s settings blocked the loading of a resource at self (“script-src”)...). Any ideas how to explicitly allow inline JS as well?Scrubland
Disabling CSP entirely isn't very safe.Garnet
This answer needs to specify which node to run this command on. It should run on the jenkins' master node. Or as some comments and answers have specified, just go to Manage Jenkins->Script Console rather than picking your master node from the node list.Undergrowth
that does not help for generated cypress gherkin reports - neither for 'cucumber-html-reporter' , nor for 'multiple-cucumber-html-reporter'. the only difference after running script in this post, or setting JENKINS_JAVA_OPTIONS (post below) is it shows funny green 'cucumber-report' label and adds scrollbarsVespine
Also note that in Manage Jenkins page (e.g. localhost:8080/manage) you will be able to see a warning similar to this one: The default Content-Security-Policy is currently overridden using the hudson.model.DirectoryBrowserSupport.CSP system property, which is a potential security issue when browsing untrusted files. As an alternative, you can set up a Resource Root URL that Jenkins will use to serve some static files without adding Content-Security-Policy headers. if the solution has been applied okSolothurn
S
36

In CentOs, to enable images in html report

  • sudo vi /etc/sysconfig/jenkins
  • set following in JENKINS_JAVA_OPTION

JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true -Dhudson.model.DirectoryBrowserSupport.CSP=\"default-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' 'unsafe-inline' data:;\""

This will work even after restarting jenkins' server.


Directive

default-src: The default-src is the default policy for loading content such as JavaScript, Images, CSS, Fonts, AJAX requests, Frames, HTML5 Media

img-src: Defines valid sources of images.

Source Value

' self ' - Allows loading resources from the same origin (same scheme, host and port).

Usage : default-src 'self'

' unsafe-inline ' - Allows use of inline source elements such as style attribute, onclick, or script tag bodies (depends on the context of the source it is applied to) and javascript: URIs.

Usage : default-src 'unsafe-inline'

' unsafe-eval ' - Allows unsafe dynamic code evaluation such as JavaScript eval()

Usage : default-src 'unsafe-eval'

data: - Allows loading resources via the data scheme (eg Base64 encoded images).

Usage : img-src 'self' data:

Please refer more about content security policy here

Standoff answered 28/9, 2017 at 7:27 Comment(5)
you should only enable inline css, and not all these other unsafe thingsGarnet
If you use some svg in object in data part like this <object type="image/svg+xml" data="imgs/lifecycle-diagram.svg"><span class="alt">lifecycleDiagram</span></object> (result of interactive asciidoctor spring-rest documentation for embedded plantuml diagram), you would need set object-src to self. Notice escaping:JENKINS_JAVA_OPTIONS='-Djava.awt.headless=true -Dhudson.security.HudsonPrivateSecurityRealm.ID_REGEX="^[a-zA-Z0-9_.-]+$" -Dhudson.model.DirectoryBrowserSupport.CSP="sandbox; default-src '\''none'\''; img-src '\''self'\''; style-src '\''self'\''; object-src '\''self'\'';"' Deckhouse
great! can be used for docker as well with --env JAVA_OPTS="..."Halves
For my ubuntu installation i used vi /etc/default/jenkins with the variable JAVA_ARGSUng
In Jenkins 2.346.1 the variable might have changed to "JAVA_OPTS" https://mcmap.net/q/168844/-jenkins-content-security-policyKelvin
D
24

Go to “Manage Jenkins” -> “Script console” and run below command:

System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "")
Decaffeinate answered 16/5, 2018 at 20:14 Comment(2)
After modifying the second param to the values mentioned by kithinkmatthew this worked for me, i.e. System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "default-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' 'unsafe-inline' data:;")Dariodariole
@AndrewMackrodt what you suggested is the only solution that has worked for me (I am running Jenkins on CentOS)Melbamelborn
M
20

On CentOS, the below solution (which was suggested in comments of another answer) is the only one which has worked for me:

  1. Go to: Manage Jenkins > Manage Nodes and Clouds
  2. Click Gear icon on the right hand side for the node (by default there will be just one Node called Master)
  3. Click 'Script Console' on the left
  4. Enter the following into the console window: System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "default-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' 'unsafe-inline' data:;")
  5. Click Run
  6. You should see some output in the Result section, similar to below screenshot:

Script Console Result

My particular issue was missing images/css in Serenity BDD reports. After performing these steps my Serenity reports had all images/css rendering properly, including reports from builds which had executed prior to this change. This solution will also work for any published html-based report.

Melbamelborn answered 6/8, 2020 at 18:18 Comment(3)
Might be a little late, but this worked on my Windows setup. But for some reason I needed to click Run twice for the result to display the expected outputHyperthermia
Thanks it worked. Will this works after Jenkins restart also?Parakeet
@Parakeet Yes, this change persists across restartsMelbamelborn
F
17

You can fix this by using the groovy command as specified in Vall's answer.

The effect is in place until Jenkins restarts and afterwards you have to do it again.

A solution to solve this problem is to configure a job that will do this for you whenever jenkins starts up.

You can do this by using the Startup Trigger plugin.

After you install it create a new job and you will have a new checkbox under the Build Triggers section that you will have to check.

Then add an Execute system Groovy script build step with the command:

System.setProperty("hudson.model.DirectoryBrowserSupport.CSP","")

Save and everything should work.

Fransen answered 9/3, 2017 at 11:57 Comment(1)
With this method, you need to install the Groovy plugin as well, if you didn't have already. Otherwise, the Execute system Groovy script build step won't show among the build options.Maxson
S
15

(The following solution is for Windows.)

A permanent fix is to change a line in [Jenkins directory]\jenkins.xml (for me it's at C:\Jenkins\jenkins.xml)

<executable>java.exe</executable>
<arguments>[arguments are here]</arguments>

Add the following argument to the whitespace-separated list of arguments:

-Dhudson.model.DirectoryBrowserSupport.CSP=

Then restart the Jenkins service to pick up the change.

Stirpiculture answered 22/2, 2017 at 3:42 Comment(1)
that is the only working answer for me, i also added -Dfile.encoding=UTF-8 to argumentsVespine
O
7

For Ubuntu 14 version helpful was special plugins:

https://wiki.jenkins-ci.org/display/JENKINS/Startup+Trigger - To start job on jenkins startup

https://wiki.jenkins-ci.org/display/JENKINS/Groovy+plugin - To run System Groovy script

And I made a job, that starts on Jenkins restart and sets parametr.

set to start build after Jenkins is ran

And added system Groovy script to set parametr. Run System Groovy script System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "sandbox; img-src 'self';")

Outgoings answered 16/5, 2017 at 6:35 Comment(3)
Although running the job completes successfully, it does not enable the CSS display for my reports. I ran the exact same groovy script in the "Script Console" and that worked fine. What else can I do? This job's groovy script is not changing the actual parent Jenkin's property.Syntactics
@frakman1 at this moment my Groovy script looks like this - System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "") But that's all and everything works. Maybe you don't have admin user?Outgoings
Thank you for the response. I eventually got it to work. I had to use this script instead: System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "sandbox allow-same-origin allow-scripts; default-src 'self'; script-src * 'unsafe-eval'; img-src *; style-src * 'unsafe-inline'; font-src *")Syntactics
D
5

Go To

Manage Jenkins --> Script console

and type in the following command:

System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "")

then Press Run. if you get the output as 'Result', then rerun the build check the HTML report format

Disputatious answered 13/8, 2018 at 9:20 Comment(0)
T
3

For setting permanently create a Groovy script file $JENKINS_HOME/init.groovy, or any .groovy file in the directory $JENKINS_HOME/init.groovy.d/ with the following content:

System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "sandbox allow-scripts; default-src 'self'; img-src *; style-src 'self' 'unsafe-inline'; script-src * 'unsafe-inline';")

systemctl restart jenkins

https://wiki.jenkins.io/display/JENKINS/Post-initialization+script

Treacy answered 2/5, 2019 at 7:8 Comment(1)
ubuntu home: /var/lib/jenkinsObliteration
S
3

Although this is an old post and an answer is provided, I felt the urge to point out new material to enhance the answer. So, sorry for the dead bump, but it is the top search find for this topic after all.

All previous answers I saw proposed setting the default content security policy to a free-for-all, in one way or another. Given the fact that the content can be modified by anyone who runs a build on your Jenkins pipeline, this bears a certain risk. After all, this is a valid setting that serves to minimize the risk of cross-site scripting. This has been pointed out by several comments I've read even in this thread.

To educate further, here are some good resources I found

https://www.jenkins.io/doc/book/security/configuring-content-security-policy/

https://content-security-policy.com/

The following enabled beautiful HTML coverage reports on my managed Jenkins instance. It is pointed out in the Jenkins documentation that setting the resource URL is the somewhat preferred solution, but that was not possible in my case:

  1. In the Jenkins web frontend, navigate to the script console.
  2. Type System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';base-uri 'self';form-action 'self' ") and click 'Run'.
  3. The setting is effective immediately, so check results by reloading the 'broken' content you try to display. (e.g. your jobs published HTML coverage report)
  4. Reverting to default type System.clearProperty("hudson.model.DirectoryBrowserSupport.CSP") in the scripting console.

The provided CSP Header is the so-called starter policy from the second link given above.

This policy allows images, scripts, AJAX, form actions, and CSS from the same origin, and does not allow any other resources to load (eg object, frame, media, etc). It is a good starting point for many sites.

For the case of HTML coverage reports in an access-protected Jenkins instance, I found this acceptable and working.

Sophisticate answered 3/7, 2023 at 15:22 Comment(0)
I
2

Open jenkins.xml file and copy arguments as below. it will fix permanently. Once its done restart your machine.

<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -Dhudson.model.DirectoryBrowserSupport.CSP="sandbox allow-scripts; default-src 'self'; style-src 'self' 'unsafe-inline';" -jar "%BASE%\jenkins.war" --httpPort=8080 --webroot="%BASE%\war"</arguments
Insufficiency answered 2/12, 2019 at 20:49 Comment(0)
G
1

It's too late to respond but thought to share.

I was struggling with Jenkins deployed on Tomcat, tried execution of script, it helps but goes away if tomcat is rebooted.

Made the permanent fix by setting the property in catalina.properties in tomcat.

Properties file: tomcat_installation_dir/conf/catalina.properties Just copy paste the below line in catalina.properties at the last (you can set it anywhere just to not mess with existing properties)

-Dhudson.model.DirectoryBrowserSupport.CSP=""

Gratianna answered 19/2, 2018 at 13:38 Comment(0)
I
1

To set the system property permanently if using Jenkins-X, then create the file myvalues.yaml in the current directory, with the following content:

jenkins:
  Master:
    JavaOpts: >
      -Dhudson.model.DirectoryBrowserSupport.CSP=

Then restart the jenkins-x platform, which can be done by upgrading it:

$ jx upgrade platform --always-upgrade
# Presumably jx.exe is used if on Windows (not tested)

To avoid actually upgrading the platform, just forcibly upgrade it to the same version:

$ version=$(jx version --no-version-check\
            | grep 'jenkins x platform' | sed -e 's/^jenkins.\+ //')
$ jx upgrade platform --version ${version} --always-upgrade
Intermediary answered 20/8, 2019 at 14:12 Comment(0)
C
1

For those who are using asciidoctor-maven-plugin plugin to produce an HTML document from the asciidoc file to further publish it to Jenkins, update the plugin configuration, add linkcss attribute:

<configuration>
    <attributes>
        <linkcss>true</linkcss>
    </attributes>
    <backend>html5</backend>
    <outputDirectory>${project.build.directory}/generated-resources</outputDirectory>
</configuration>
Capone answered 11/3, 2020 at 11:59 Comment(0)
S
1

We have a much simpler solution to the problem. Unless you really insist on having the HTML reports, you can just use the Warnings NG plugin (which is a good idea anyway):

https://github.com/jenkinsci/warnings-ng-plugin/blob/master/SUPPORTED-FORMATS.md

We use this for CodeNarc (Groovy), but also for Checkstyle, PMD, SpotBugs and Java warnings (Java).

Schnapp answered 2/6, 2021 at 9:31 Comment(0)
N
1

I know this is old, but this worked great for me, and it is what seems to be recommended in the Jenkins docs. I just set the resource root to a different url served from the same location.

"It is strongly recommended to set up the Resource Root URL instead of customizing Content-Security-Policy. Most of the documentation below was written when Content-Security-Policy was first introduced and is retained for use by administrators unable to set up Jenkins to serve user content from a different domain."

Nugget answered 21/1, 2022 at 3:17 Comment(2)
Can you share a link to that documentation you're (presumably) quoting? That would add a lot to the answer...Twicetold
@UlrichEckhardt It comes from "Configuring Content Security Policy". See also "How to set the "Resource root URL" in Jenkins"Wino
P
1
  1. In MacOS, Jenkins runs a service, that needs to create a groovy script inside $JENKINS_HOME/init.groovy.d
  2. Call startup-properties.groovy and code :
    import jenkins.model.Jenkins
    import java.util.logging.LogManager 
    /* Jenkins home directory */
    def jenkinsHome = Jenkins.instance.getRootDir().absolutePath
    def logger = LogManager.getLogManager().getLogger("")
    /* Replace the Key and value with the values you want to set.*/
    /* System.setProperty(key, value) */
    System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "")
    logger.info("Jenkins Startup Script: Successfully updated the system properties value for hudson.model.DirectoryBrowserSupport.CSP . Script location : ${jenkinsHome}/init.groovy.d")
  1. Restart the Jenkins Service: brew services restart jenkins-lts

Re-build the job and verify the HTML report into the build

https://i.stack.imgur.com/A60BN.png

enter image description here

Prelude answered 27/1, 2022 at 15:16 Comment(0)
I
0

I had the same issues after adding HTTPS to my jenkins. In case you are having the same issue, the solution is easy - set your Jenkins url to use HTTPS protocol instead of HTTP. It can be configured via jenkins configuration -> jenkins url

Indus answered 5/3, 2018 at 8:20 Comment(0)
T
0

The best solution to this problem is to add or update Resource Root URL in System of Manage Jenkins.

if you are running Jenkins on AWS simply add the Public IPv4 DNS in the Resource Root URL. For example, https://ec2-XXX-XXX-XXX-XXX.compute-1.amazonaws.com:8080 in Resource Root URL.

Note: Hostname of Jenkins URL and Resource Root URL should be different.

Trilbi answered 15/2 at 7:53 Comment(0)
G
0

Just want to update per my study following this thread especially dragosb's answer. Need first install two plugins: Startup Trigger plugin then Groovy plugin. And don't forget to restart jenkins. After that, in the test project find build steps, from there add Execute system Groovy script before any other build step. And then paste following command:

System.setProperty("hudson.model.DirectoryBrowserSupport.CSP","")

enter image description here

Now after build you are able to open report.html and log.html.

I guess by doing this they restrict this security exception to be allowed in project level.

Greatgranduncle answered 17/3 at 20:42 Comment(0)
D
0

Turning off CSP entirely isn't safe. You should only enable inline CSS and not all the other things that are vulnerable to cross-site scripting (XSS) attacks.

System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; script-src 'none';");
Danialah answered 10/4 at 1:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.