Problem/Motivation

In twig and its drupal integration, an important feature was the sandboxing security feature. Read: Using twig, you can not access information apart from the provided variables. (Admittedly there are still issues with this, but people work hard to fix it.)

Use case: Think you run a site and want to give some users twig permissions to do some theme templating, or email templating, or whatever. You do not want them to be able to query arbitrary entities or config and phone that out.

The problem with the current state of this project is, if i want some really useful safe functions, i also have to enable some unsafe functions.

Proposed resolution

* split out (sub)module(s) with unsafe functions
* add an update function that enables the new modules for legacy sites

I'd be willing to do the code work and help comaintain if this is wanted.

Proposal how to split

Twig tweaks (safe)

This module contains functions and filters that stay in the sandbox of provided variables.

drupal_image
drupal_token
drupal_dump / dd
drupal_url
drupal_breakpoint
|token_replace
|preg_replace
|image_style
|transliterate
|check_markup
|truncate
|view
|with
|children

Twig Tweaks Convenience

This module adds twig functions and filters to do some limited queries outside the sandbox.

drupal_title
drupal_messages
drupal_breadcrumb
contextual_links

Twig Tweaks Unsafe

This module adds twig functions and filters to do arbitrary queries, effecively breaking the sandbox.

drupal_view
drupal_view_result
drupal_block
drupal_region
drupal_entity
drupal_entity_form
drupal_field
drupal_menu
drupal_form
drupal_config

Comments

chi’s picture

I think this won't make the site more secure as there are so many ways to bypass the policy. Drupal core and contributed modules offer many render elements and theme functions that execute arbitrary queries.
For instance instead of drupal_view() users can simply type {{ {'#type': 'view', '#name': 'view_name'} }}.

See how many render elements are provided by Webform module.
https://git.drupalcode.org/project/webform/tree/8.x-5.4/src/Element

chi’s picture

Version: 8.x-2.x-dev » 3.x-dev
Status: Active » Fixed

Since version 3.x Twig Tweak offers alter hooks than can be used to remove "unsafe" Twig functions, filters and tests.

Example:

/**
 * Implements hook_twig_tweak_functions_alter().
 */
function HOOK_twig_tweak_functions_alter(array &$functions): void {
  $allowed_functions = [
    'drupal_view',
    'drupal_entity',
    'drupal_menu',
  ];
  foreach ($functions as $index => $function) {
    if (!in_array($function->getName(), $allowed_functions)) {
      unset($functions[$index]);
    }
  }
}

Thanks for the report.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.