How do I add the Sandbox extension for TWIG in the Timber WordPress plugin?

Viewed 234

I'm wanting to add the Sandbox extension to evaluate untrusted code using Timber for WordPress (included using composer but I get the same result when using the plugin).

The following (simplified) code results in a fatal error.

add_filter('timber/twig', function($twig){

    $filters = array_diff(array_keys($twig->getFilters()), ['function']);

    $policy = new \Twig\Sandbox\SecurityPolicy([], $filters, [], [], []);
    $twig->addExtension(new \Twig\Extension\SandboxExtension($policy, true));
    
    return $twig;
});

The error is: "Fatal error: Uncaught Exception: Unable to register extension "sandbox" as extensions have already been initialized."

Makes no difference if the applied filter is timber/twig or twig_apply_filters.

Is this the incorrect place to add this extension? It seems to only execute when Timber::compile_string is called.

I'm using the latest versions of WordPress and Timber on PHP 7.3.x

1 Answers

$twig->getFilters() causes extensions to be initialised and so can't be used here for this purpose. There is no error and the sandbox extension is registered when this code is removed.

Related