// Runs inside the Jenkins controller JVM at startup (operator-standard init.groovy.d hook).
// Creates the inbound-agent node used by the reproduction, prints the agent secret, and
// prints the identity of the JEP-200 class filter that Jenkins core installs as the
// remoting default (jenkins.model.Jenkins -> ClassFilterImpl.register() ->
// ClassFilter.setDefault(new ClassFilterImpl()); ChannelBuilder defaults to ClassFilter.DEFAULT).
import jenkins.model.Jenkins
import hudson.model.Node
import hudson.slaves.DumbSlave
import hudson.slaves.JNLPLauncher
import hudson.slaves.RetentionStrategy

def j = Jenkins.get()

if (j.getNode("agent1") == null) {
    def node = new DumbSlave("agent1", "/tmp/agent", new JNLPLauncher())
    node.setNodeDescription("SECURITY-3911 reproduction agent")
    node.setNumExecutors(1)
    node.setRetentionStrategy(RetentionStrategy.INSTANCE)
    j.addNode(node)
}

def computer = null
for (int i = 0; i < 60 && computer == null; i++) {
    computer = j.getComputer("agent1")
    if (computer == null) {
        Thread.sleep(1000)
    }
}
if (computer != null) {
    println("SECURITY3911_AGENT_SECRET=" + computer.getJnlpMac())
} else {
    println("SECURITY3911_AGENT_SECRET=UNAVAILABLE")
}

// Prove the production filter identity and that it blocks the payload class at class level.
try {
    def f = hudson.remoting.ClassFilter.getDeclaredField("CURRENT_DEFAULT")
    f.accessible = true
    def filter = f.get(null)
    println("SECURITY3911_CHANNEL_DEFAULT_FILTER=" + filter.getClass().getName())
    try {
        filter.check(Class.forName("hudson.security3911.Payload", false, hudson.remoting.Channel.class.getClassLoader()))
        println("SECURITY3911_FILTER_PROBE=NOT_REJECTED (unexpected on a JEP-200-enforcing controller)")
    } catch (ClassNotFoundException cnfe) {
        println("SECURITY3911_FILTER_PROBE=PAYLOAD_CLASS_NOT_ON_CLASSPATH")
    } catch (SecurityException ex) {
        println("SECURITY3911_FILTER_PROBE=REJECTED: " + ex.message)
    }
} catch (Throwable t) {
    println("SECURITY3911_CHANNEL_DEFAULT_FILTER=ERROR " + t)
}
