HIGH server side template injectionsailsapi keys

Server Side Template Injection in Sails with Api Keys

Server Side Template Injection in Sails with Api Keys — how this specific combination creates or exposes the vulnerability

Server Side Template Injection (SSTI) in Sails can be triggered when an API key is incorporated into server-side template logic or passed into a rendering context without validation. Sails does not enforce strict template sandboxing by default when dynamic data is merged into views, and an attacker who can influence the value associated with an API key may be able to inject template expressions that execute code on the server.

Consider a Sails controller that uses an API key to select a template or to populate a template context variable used by an engine such as EJS or Lodash. If the API key value (or data derived from it) is interpolated into the template without escaping, an attacker may supply a crafted API key containing template syntax (e.g., <% %> for EJS) that leads to arbitrary code execution. For example, an API key like "%>_= require('child_process').exec('id')<%" can break out of intended data bindings and invoke server commands when the template is rendered.

In a black-box scan, middleBrick tests unauthenticated endpoints that accept API keys as query parameters or headers. If the API key is reflected into a template, SSTI indicators such as template context pollution or unexpected code execution may appear in findings. Because Sails applications often expose REST or GraphQL endpoints that accept keys for authorization or tenant identification, the combination of dynamic template rendering and key-driven logic increases the attack surface. Successful exploitation can lead to information disclosure or remote code execution, depending on the runtime environment and template engine configuration.

middleBrick detects these patterns by correlating OpenAPI/Swagger specifications with runtime inputs, including header and query parameters named api_key or authorization. When a template engine processes user-influenced data, the scanner checks for indicators of SSTI and flags high-severity findings with remediation guidance. This approach helps teams understand how an improperly handled API key can become a vector for template injection in Sails.

Api Keys-Specific Remediation in Sails — concrete code fixes

Remediation focuses on ensuring API keys are treated as opaque credentials, never as template input, and that template engines are configured with the strictest safe options. Do not pass API key values directly into view templates or allow dynamic template selection based on keys.

First, keep API keys out of the template context. Instead of passing the key to the view, use it only for authentication or authorization checks on the server side. The following example shows a safe Sails controller that validates an API key without exposing it to the view layer:

module.exports = {
  find: async function (req, res) {
    const providedKey = req.query.api_key || req.headers['x-api-key'];
    const validKey = await ApiKey.findOne({ where: { key: providedKey } });

    if (!validKey) {
      return res.unauthorized('Invalid API key');
    }

    // Use validKey.recordId for data scoping, not the raw key in templates
    const records = await Record.find({ tenantId: validKey.recordId });
    return res.ok(records);
  }
};

Second, if you must render dynamic content, use strict autoescaping and avoid unsafe evaluation. For EJS, ensure <%=% %> is used for output and never evaluate raw user input. Prefer a strict sandbox for template engines and disable dangerous constructs like res.render('dynamicTemplateName') where the template name is derived from API key data.

Third, validate and sanitize all inputs that could influence template rendering. Even when using Swagger-generated validation, explicitly define that API key parameters must not contain characters used for template syntax. A simple regex check can prevent many injection attempts:

const safeApiKeyPattern = /^[A-Za-z0-9\-_]+$/;
if (!safeApiKeyPattern.test(providedKey)) {
  return res.badRequest('Invalid API key format');
}

Finally, use the middleBrick CLI to verify that your Sails endpoints remain secure after changes. Run middlebrick scan <url> to obtain a report that highlights any remaining SSTI risks related to API key handling. The dashboard allows you to track remediation progress and integrate scans into your CI/CD pipeline to catch regressions early.

Frequently Asked Questions

Can an API key alone trigger Server Side Template Injection in Sails?
Only if the API key value is directly interpolated into a server-side template without proper escaping. Treat API keys as credentials, not template data, to prevent injection.
Does middleBrick fix SSTI in Sails applications?
middleBrick detects and reports SSTI findings with remediation guidance. It does not automatically patch or fix vulnerabilities; developers must apply the suggested code changes.