P.S. Does anyone have a feel for whether part of the sandboxing solution is generic enough to be widely applicable? Or is it quite specific to Jenkins? I can look myself I guess but thought someone might be in the know. Just wondering whether moving some kind of sandboxing solution into the Groovy project itself would make it easier for projects to upgrade Groovy versions.
At a high level, the sandboxing system is generic. The main pieces are in https://github.com/jenkinsci/groovy-sandbox (a generic Java library) and https://github.com/jenkinsci/script-security-plugin (a Jenkins plugin), but there are some parts specific to Jenkins Pipeline that live elsewhere. We received bug reports from non-Jenkins users in the groovy-sandbox repository, so there was at least some non-Jenkins interest in such a system (we eventually updated the README to explicitly discourage non-Jenkins usage because the sandbox can be trivially bypassed unless you are using related sandbox setup code in the script-security plugin).
The goal of our sandbox is runtime interception of operations like constructor invocation, method calls, field accesses, etc., so that each operation can be checked against an allowlist and then either allowed or denied. This approach allows sandboxed scripts to use most Groovy language features internally and allows them to interact with known-safe Groovy/Java standard library APIs. It also means that the sandbox needs to understand how Groovy syntax maps to low level operations (e.g. what exactly will X as Y do at runtime?), which is complicated.
The track record for our sandbox is not good (look at previous security warnings in the sidebar of https://plugins.jenkins.io/script-security/). If I was you I would not consider adding such a system to Groovy itself unless you had some specific idea of how to improve the design in a fundamental way or add defense-in-depth.
We are up to 2.5.11 -