HIGH api key exposurehapimssql

Api Key Exposure in Hapi with Mssql

Api Key Exposure in Hapi with Mssql — how this specific combination creates or exposes the vulnerability

When an API built with Hapi interacts with Microsoft SQL Server (Mssql), improper handling of secrets and dynamic SQL can lead to Api Key Exposure. This typically occurs when API keys or database credentials are embedded in code, passed in query strings, or logged inadvertently. In Hapi, route handlers often construct Mssql queries using request parameters or headers, and if those values are not properly validated or parameterized, keys may be exposed through error messages, logs, or response payloads.

Consider a scenario where an Hapi route accepts an Authorization header containing an API key and uses it to query Mssql without sanitization:

const Hapi = require('@hapi/hapi');
const sql = require('mssql');

const init = async () => {
  const server = Hapi.server({ port: 3000, host: 'localhost' });

  server.route({
    method: 'GET',
    path: '/data',
    options: {
      validate: {
        headers: Joi.object({
          'api-key': Joi.string().required()
        }).unknown()
      }
    },
    handler: async (request, h) => {
      const pool = await sql.connect('Server=localhost;Database=Test;User ID=sa;Password=Pass@word1;');
      const result = await pool.request()
        .input('key', sql.VarChar, request.headers['api-key'])
        .query('SELECT * FROM secrets WHERE api_key = @key');
      return result.recordset;
    }
  });

  await server.start();
};
init();

In this pattern, if the connection string or API key is mishandled—such as being logged in debug mode or exposed through verbose error responses—attackers can harvest valid keys. Mssql error messages, when not suppressed, may reveal internal queries or connection details. Additionally, if the API key is reflected in responses or stored insecurely in client-side JavaScript, it becomes susceptible to extraction via browser dev tools or network inspection. This combination is risky because Hapi’s flexibility in routing and Mssql’s rich feature set can inadvertently expose sensitive values through misconfigured logging, improper error handling, or dynamic SQL construction.

Another vector involves OpenAPI spec analysis: if the API specification inadvertently documents the API key as a query parameter rather than a header, scanners may flag it as exposed. MiddleBrick’s OpenAPI/Swagger analysis (2.0, 3.0, 3.1) with full $ref resolution can detect such mismatches by cross-referencing spec definitions with runtime behavior, helping identify where keys might leak through documentation or implementation drift.

Moreover, unchecked request inputs can lead to SSRF or injection issues that expose internal endpoints where keys are cached. For example, an attacker could manipulate a parameter to trigger internal Mssql connections that reveal metadata or configuration. MiddleBrick’s 12 security checks—particularly Authentication, Data Exposure, and Unsafe Consumption—run in parallel to uncover these weaknesses. Findings include severity levels and remediation guidance, ensuring teams understand how to harden Hapi routes and Mssql interactions without relying on manual review.

Mssql-Specific Remediation in Hapi — concrete code fixes

To mitigate Api Key Exposure in Hapi when using Mssql, apply strict input validation, parameterized queries, and secure logging practices. The following code demonstrates a hardened implementation that avoids string concatenation and ensures secrets remain protected:

const Hapi = require('@hapi/hapi');
const sql = require('mssql');
const Joi = require('joi');

const init = async () => {
  const server = Hapi.server({ port: 3000, host: 'localhost' });

  // Secure route with header validation and parameterized query
  server.route({
    method: 'GET',
    path: '/secure-data',
    options: {
      validate: {
        headers: Joi.object({
          'x-api-key': Joi.string().pattern(/^[a-f0-9]{32}$/i).required()
        }).unknown(false) // reject unknown headers
      }
    },
    handler: async (request, h) => {
      const config = {
        user: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        server: process.env.DB_HOST,
        database: process.env.DB_NAME,
        options: {
          encrypt: true,
          trustServerCertificate: false
        }
      };

      try {
        const pool = await sql.connect(config);
        const result = await pool.request()
          .input('apiKey', sql.VarChar(64), request.headers['x-api-key'])
          .query('SELECT id, data FROM secure_table WHERE api_key = @apiKey AND revoked = 0');

        if (result.recordset.length === 0) {
          return h.response({ error: 'Not found' }).code(404);
        }

        // Avoid logging sensitive values
        console.log('Query executed successfully, records returned:', result.recordset.length);
        return result.recordset;
      } catch (err) {
        // Generic error to prevent leakage
        console.error('Database operation failed');
        return h.response({ error: 'Internal server error' }).code(500);
      }
    }
  });

  await server.start();
  console.log('Server running on %s', server.info.uri);
};
init();

Key remediation steps include:

  • Use environment variables for connection strings and never hardcode credentials.
  • Apply strict header validation with Joi to enforce expected formats and reject unknown inputs.
  • Always use parameterized queries (.input()) to prevent SQL injection and avoid embedding keys in SQL strings.
  • Suppress detailed Mssql error messages in production to avoid exposing stack traces or query structure.
  • Ensure TLS encryption for database connections and disable trustServerCertificate in production.
  • Audit logs to ensure API keys or sensitive data are not inadvertently recorded.

For continuous protection, the Pro plan’s continuous monitoring can be configured to scan Hapi endpoints on a schedule, alerting teams if risk scores drop below defined thresholds. The GitHub Action can enforce security gates in CI/CD, preventing deployments that introduce exposed keys. These capabilities complement manual fixes by providing ongoing visibility without requiring deep expertise in Mssql or Hapi internals.

Frequently Asked Questions

How can I verify that my Hapi API does not leak API keys in error messages?
Test endpoints with malformed requests and inspect responses. Ensure errors are generic and do not include stack traces or query details. Use tools like MiddleBrick to scan for Data Exposure findings.
Is it safe to log API keys for debugging purposes in Hapi applications using Mssql?
No. Logging API keys, even temporarily, can lead to exposure through log files or monitoring systems. Use masked logging and environment variables instead.