HIGH server side template injectionrestifybearer tokens

Server Side Template Injection in Restify with Bearer Tokens

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

Server Side Template Injection (SSTI) in Restify occurs when user-controlled data is embedded into a template string that is later rendered by a vulnerable template engine. Restify is an HTTP server framework for Node.js commonly used to build APIs. When Restify endpoints accept authentication via Bearer Tokens — typically passed in the Authorization header as Bearer <token> — developers sometimes use data from decoded tokens (e.g., user roles, tenant IDs, or usernames) to construct dynamic templates or to influence template selection. If those token-derived values are inserted into templates without proper escaping or sandboxing, an attacker can control template syntax and execute arbitrary code on the server.

Consider a scenario where a Bearer Token carries a role claim, and the server uses that claim to pick a template path or to populate a template variable. A malicious actor who obtains or guesses a valid Bearer Token can modify the role claim (via token manipulation if signing is weak, or via a trusted internal source) to inject template code. For example, if the template engine supports JavaScript evaluation (such as legacy implementations or unsafe configurations), an injected payload like {{<% eval(runtime.process.mainModule.require('child_process').exec('id')) %>}} could lead to remote code execution. Even when the template engine does not directly evaluate code, attackers can leverage SSTI to leak server-side variables, bypass intended access controls, or forge privileged operations by abusing role-based logic tied to the Bearer Token context.

The risk is amplified when token introspection or validation is incomplete. If the API decodes a JWT Bearer Token without verifying the signature and then directly uses claims in template rendering, an attacker can craft tokens with elevated scopes or tenant identifiers to traverse authorization boundaries (BOLA/IDOR) and trigger SSTI in contexts where different permissions apply. Because Restify APIs often serve as backend services for web and mobile clients, an SSTI vector combined with Bearer Token misuse can expose sensitive data, enable server-side request forgery, or lead to further infrastructure compromise.

middleBrick detects this class of issue through its 12 parallel security checks, including Input Validation, Property Authorization, and SSRF. The scanner analyzes OpenAPI specifications (including $ref resolution for 2.0, 3.0, and 3.1) and correlates runtime behavior with declared authentication schemes. If your API uses Bearer Tokens and dynamic templates, running a scan with the middleBrick CLI or Web Dashboard can surface unsafe template usage and token handling patterns before attackers do.

Bearer Tokens-Specific Remediation in Restify — concrete code fixes

To mitigate SSTI when using Bearer Tokens in Restify, focus on strict input validation, avoiding dynamic template selection based on token claims, and using safe rendering contexts. Below are concrete code examples that demonstrate secure practices.

1. Avoid template selection or variable interpolation based on Bearer Token claims

Do not use decoded token data to determine which template to render or to inject into template logic. Instead, use a fixed, server-side mapping.

// Unsafe: using role from Bearer Token to select template
const token = request.authorization?.bearer;
if (token) {
  const decoded = jwt.decode(token, { complete: false });
  const role = decoded?.role || 'user';
  const templatePath = `./templates/${role}_dashboard.hbs`; // Risky
  const template = fs.readFileSync(templatePath, 'utf8');
  const result = Handlebars.compile(template)(decoded);
  reply.send(result);
}

// Safe: use a fixed mapping
const roleTemplateMap = {
  admin: './templates/admin_dashboard.hbs',
  user: './templates/user_dashboard.hbs',
};
const token = request.authorization?.bearer;
let templatePath = roleTemplateMap['user'];
if (token) {
  const decoded = jwt.verify(token, publicKey); // always verify
  const role = decoded.role;
  templatePath = roleTemplateMap[role] || roleTemplateMap['user'];
}
const template = fs.readFileSync(templatePath, 'utf8');
const result = Handlebars.compile(template)(decoded);
reply.send(result);

2. Sanitize and escape all user-influenced data before rendering

Never insert raw token claims into templates. Escape dynamic values based on the context (HTML, URL, JS) and disable evaluation features in your template engine.

const Handlebars = require('handlebars');
// Ensure Handlebars does not compile with unsafe options
Handlebars.SafeString.prototype.toString = function() {
  return this.string;
};

// Always escape output in templates
const source = '
Welcome {{this.username}}
'; // username from token const template = Handlebars.compile(source); const safeOutput = template({ username: escapedUsername(tokenUsername) }); function escapedUsername(input) { return input.replace(/&/g, '&').replace(//g, '>'); }

3. Validate and verify Bearer Tokens before use

Always verify the token signature and scope. Do not rely on client-supplied claims. Use a library and enforce strict audience and issuer checks.

const jwt = require('jsonwebtoken');
const publicKey = fs.readFileSync('public.pem');

function authenticate(req) {
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    throw new Error('Unauthorized');
  }
  const token = authHeader.substring(7);
  try {
    const decoded = jwt.verify(token, publicKey, {
      audience: 'my-api',
      issuer: 'https://auth.example.com',
    });
    return decoded;
  } catch (err) {
    throw new Error('Invalid token');
  }
}

Using the middleBrick CLI, you can validate these patterns automatically: middlebrick scan <your-api-url>. The scanner checks for unsafe template usage and insecure token handling, providing prioritized findings with remediation guidance in the Web Dashboard or via JSON output. For teams with CI/CD pipelines, the middleBrick GitHub Action can enforce security thresholds before deployment, while the MCP Server enables scanning directly from AI coding assistants in your development environment.

Frequently Asked Questions

Can SSTI occur if I validate Bearer Tokens but still use claims in templates?
Yes. Validation ensures the token is authentic, but if you embed claims into templates without escaping or safe rendering contexts, SSTI remains possible. Always treat token-derived data as untrusted input.
Does middleBrick fix SSTI or token handling issues automatically?
middleBrick detects and reports these issues with severity levels and remediation guidance. It does not automatically patch or modify code. Use the findings to update templates, verify token usage, and enforce strict input validation.