HIGH server side template injectionloopbackbearer tokens

Server Side Template Injection in Loopback with Bearer Tokens

Server Side Template Injection in Loopback with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Server Side Template Injection (SSTI) in Loopback becomes especially risky when endpoints are protected only by Bearer Tokens. A Bearer Token is typically passed in the Authorization header (e.g., Authorization: Bearer ). If an API trusts this token to identify the user but then uses unchecked user input to construct a template — for example, to generate dynamic email content or error messages — an attacker can supply a malicious template string that gets rendered with unintended logic or data access.

Consider a scenario where an endpoint accepts a template name or fragment supplied by the caller, merges it with data, and returns the rendered result. If input validation is missing, an attacker can inject Loopback-specific expressions or partial JavaScript that execute on the server. Because the request includes a valid Bearer Token, the API may treat the request as authorized, bypassing casual authentication checks. This combination of trusted token context and unsafe template rendering can lead to data exposure, server-side code execution, or information leakage through rendered output.

For example, an attacker might send a POST to an endpoint that builds an email template using user-controlled data. If the API merges the supplied template naively, expressions like {{ user.email }} or malicious constructs can be injected. When the template engine evaluates these, it might read more data than intended, including properties accessible in the current execution context. Since the request includes a Bearer Token, logging and monitoring may flag the request as legitimate, making the malicious activity harder to detect.

MiddleBrick scans this specific attack surface by running checks such as Input Validation and Data Exposure in parallel, cross-referencing any OpenAPI/Swagger spec (including securitySchemes of type http with scheme: bearer) with runtime behavior. This helps identify where authenticated endpoints accept untrusted input that flows into template rendering, highlighting paths where SSTI can occur despite the presence of Bearer Tokens.

Bearer Tokens-Specific Remediation in Loopback — concrete code fixes

To mitigate SSTI in Loopback when Bearer Tokens are used, treat all user-controlled data as untrusted, regardless of authentication. Do not directly embed user input into templates. Instead, use strict allowlists, safe rendering APIs, and avoid dynamic template selection where possible.

Example of a vulnerable pattern in a Loopback controller:

// ❌ Vulnerable: user-supplied template injected into rendering
app.get('/email/:templateName', (req, res) => {
  const templateName = req.params.templateName;
  const user = getCurrentUser(req); // auth via Bearer Token present in headers
  const template = loadTemplate(templateName); // reads from filesystem or DB
  const rendered = _.template(template)(user); // unsafe concatenation
  res.send(rendered);
});

Secure remediation using explicit allowlisting and safe rendering:

// ✅ Secure: allowlist known templates, no user-controlled template code
const ALLOWED_TEMPLINGS = {
  welcome: 'Hello {{name}}, welcome back!',
  receipt: 'Order {{orderId}} total: {{total}}'
};

app.get('/email/:templateName', (req, res) => {
  const templateName = req.params.templateName;
  const user = getCurrentUser(req); // auth via Bearer Token present in headers

  if (!ALLOWED_TEMPLINGS[templateName]) {
    return res.status(400).send({ error: 'Invalid template' });
  }

  const template = ALLOWED_TEMPLINGS[templateName];
  // Use a safe template engine or manual substitution; avoid eval-like rendering
  const rendered = template
    .replace(/{{name}}/g, escapeHtml(user.name))
    .replace(/{{orderId}}/g, escapeHtml(String(user.orderId)))
    .replace(/{{total}}/g, escapeHtml(String(user.total)));

  res.send(rendered);
});

function escapeHtml(str) {
  return str.replace(/[<>"'&]/g, (m) => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));
}

If you use Loopback’s built-in templating or email connectors, configure them with predefined templates and pass only data — never raw template strings from clients. Additionally, ensure Bearer Token validation is consistently applied via Loopback’s built-in authentication middleware, but remember that authentication alone does not prevent injection; input validation and output encoding remain essential.

MiddleBrick’s checks include Authentication, Input Validation, and Data Exposure, which help surface endpoints where Bearer Token–protected routes accept unsafe input for template rendering. The scans do not fix issues but provide prioritized findings with remediation guidance, enabling you to harden your API design.

Frequently Asked Questions

Can an attacker exploit SSTI if the endpoint requires a Bearer Token?
Yes. If the API validates the Bearer Token but then uses untrusted input in a template, SSTI can still occur. Authentication does not guarantee input safety; always validate and sanitize user-controlled data.
How does middleBrick detect SSTI risks in Loopback APIs with Bearer Token protection?
MiddleBrick runs parallel checks including Input Validation and Data Exposure, cross-referencing the OpenAPI/Swagger spec (including bearer security schemes) with runtime behavior to identify endpoints where authenticated requests include user-controlled input that may reach a template renderer.