title: Bypass Script Security Plugin within Code
body: <p>I have written a few groovy utility methods for use in Jenkins Pipelines. A simple example is:</p>
  
  <pre><code>// src/org/package/utils.groovy
  def remove_file(String file) {
    new File(file).delete()
  }
  </code></pre>
  
  <p>However, as expected this throws the following exception in Jenkins Pipeline:</p>
  
  <blockquote>
    <p>org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new java.io.File java.lang.String</p>
  </blockquote>
  
  <p>According to the <a href="https://wiki.jenkins.io/display/JENKINS/Script+Security+Plugin" rel="nofollow noreferrer">Script Security Plugin documentation</a>, I can bypass this with the <code>@Whitelisted</code> method annotation:</p>
  
  <pre><code>@Whitelisted
  def remove_file(String file) {
    new File(file).delete()
  }
  </code></pre>
  
  <p>According to this <a href="https://stackoverflow.com/questions/42295921/what-is-the-effect-on-noncps-in-a-jenkins-pipeline-script">question</a>, I can bypass this with the <code>@NonCPS</code> annotation (and the code in this method is of course not necessary to be serializable anyway):</p>
  
  <pre><code>@NonCPS
  def remove_file(String file) {
    new File(file).delete()
  }
  </code></pre>
  
  <p>The shared library is being used in a global var like the following:</p>
  
  <pre><code>// vars/var.groovy
  import org.package.utils
  
  def method(body) {
    ...
    new utils().remove_file('file')
    ...
  }
  </code></pre>
  
  <p>The library/var is being imported and used in a Jenkinsfile like the following:</p>
  
  <pre><code>library identifier: 'lib@master', retriever: modernSCM(
    [$class: 'GitSCMSource',
     remote: 'https://github.com/org/repo.git'])
  
  pipeline {
    ...
    script {
      var.method {
        // body
      }
    }
    ...
  }
  </code></pre>
  
  <p>Of the listed code-based approaches to importing a Pipeline shared library, the approach I utilized above seemed to be the only one that actually works with the standard Jenkins Pipeline plugin set, so that was the approach I took.</p>
  
  <p>Both of these have failed at bypassing the security exception that Jenkins Pipeline is throwing. What is the best solution to bypass the script security plugin using code and avoiding manual/human-error solutions such as modifying the whitelist in the GUI?</p>