HIGH api key exposurehapimysql

Api Key Exposure in Hapi with Mysql

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

When an API built with Hapi interacts with a Mysql database, mishandled API keys can lead to direct data compromise. Hapi servers often store service credentials (for example, a payment processor key) in configuration or environment variables and may inadvertently include those keys in logs, error messages, or response payloads. If the application also exposes a Mysql endpoint or uses an ORM that logs queries, a key that appears only as a string in JavaScript code can be concatenated into debug output or stack traces that reach the client.

A common pattern is to pass the API key as a header or query parameter to a downstream service, while the Hapi server uses a Mysql connection pool to store or audit those transactions. If the developer accidentally logs the key with something like this.log(['info', 'payment'], { key: paymentKey }) or includes request parameters in Mysql query construction without proper sanitization, the key can be reflected back in HTTP responses or written to database audit tables accessible via an injection path.

Mysql itself does not store or process the Hapi API key directly, but the application layer does when it forms queries such as INSERT INTO transactions (gateway, key_ref, amount) VALUES ('stripe', ? , 100). If user-controlled input is used to build that query—such as an object ID or a callback URL that contains the key—and passed to the query without validation, the key can be exfiltrated through error-based SQL injection or through verbose error messages returned by the database driver. The exposure becomes critical when the same database contains sensitive tables (for example, a table storing outbound webhook configurations or secrets) and the Hapi route does not enforce strict parameterization and output encoding.

Another vector specific to this combination is unauthenticated endpoint exposure. If a development or debugging route in Hapi provides a dump of recent requests including headers and Mysql metadata, and that route is accidentally left open, an attacker can enumerate stored key references or infer connection patterns. The scanner categories relevant here include Authentication (whether the key is required for the endpoint), Data Exposure (whether the key appears in responses), and Unsafe Consumption (whether external input is safely handled before being used in Mysql queries). These checks highlight routes where API keys are reflected, logged, or constructed into queries without adequate safeguards.

Because middleBrick tests unauthenticated attack surfaces and runs checks in parallel, it can surface these issues without requiring credentials. The tool examines OpenAPI specs and runtime behavior to detect whether API keys appear in error outputs, whether input validation is missing before Mysql interactions, and whether rate limiting or data exposure controls are insufficient. While middleBrick reports findings and provides remediation guidance, the operator must apply secure coding practices to resolve the underlying issues.

Mysql-Specific Remediation in Hapi

Remediation focuses on preventing the API key from reaching the client and ensuring that all Mysql interactions are parameterized and validated. The following examples assume you are using the @hapi/hapi server and the mysql2 package with promises in Node.js.

First, never concatenate user input into SQL strings. Use prepared statements for every query that references sensitive values. For example, if you need to store a transaction that involves an API key reference, bind the key as a parameter:

const mysql = require('mysql2/promise');

async function storeTransaction(server, transaction) {
  const connection = await mysql.createConnection({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_NAME,
  });

  // Safe: key is passed as a parameter, not interpolated
  const [results] = await connection.execute(
    'INSERT INTO transactions (gateway, key_ref, amount, created_at) VALUES (?, ?, ?, NOW())',
    [transaction.gateway, transaction.keyRef, transaction.amount]
  );

  await connection.end();
  return results.insertId;
}

Second, sanitize and validate all inputs before using them in queries. Use Joi or another schema validator in your Hapi routes to ensure that only expected formats reach the database:

const Joi = require('joi');

const transactionSchema = Joi.object({
  gateway: Joi.string().valid('stripe', 'paypal').required(),
  keyRef: Joi.string().pattern(/^[a-zA-Z0-9_-]{1,64}$/).required(),
  amount: Joi.number().positive().required(),
});

server.route({
  method: 'POST',
  path: '/transaction',
  options: {
    validate: {
      payload: transactionSchema,
    },
    handler: async (request, h) => {
      const { gateway, keyRef, amount } = request.payload;
      const id = await storeTransaction(server, { gateway, keyRef, amount });
      return h.response({ id }).code(201);
    },
  },
});

Third, ensure that API keys are never included in logs or error responses. Configure your logging strategy to redact sensitive fields, and avoid dumping headers or query objects directly:

// Instead of logging the full request payload
// this approach logs only safe metadata
server.ext('onRequest', (server, extNext) => {
  server.log(['debug'], { event: 'request_start', path: extNext.request.path });
  extNext.continue;
});

Fourth, restrict database permissions for the application user to the minimum required operations. For example, if the service only inserts transactions and reads public configuration, do not grant it DROP or administrative rights:

-- Example MySQL user setup
CREATE USER 'hapi_app'@'%' IDENTIFIED BY 'StrongPassword!';
GRANT INSERT, SELECT ON appdb.transactions TO 'hapi_app'@'%';
GRANT SELECT ON appdb.config TO 'hapi_app'@'%';
FLUSH PRIVILEGES;

Finally, use environment variables for secrets and rotate keys regularly. With middleBrick’s continuous monitoring (available in the Pro plan), you can detect when a key appears unexpectedly in outputs and tighten validation before an exposure escalates.

Frequently Asked Questions

How can I verify that my API keys are not leaking through Mysql error messages?
Review server logs and HTTP responses for raw key strings, and use parameterized queries consistently. middleBrick can scan unauthenticated endpoints and flag reflections of sensitive values in outputs.
Does middleBrick test for API key exposure in authenticated flows only?
No. middleBrick tests the unauthenticated attack surface by default, but you can also provide authentication so it can exercise protected routes that interact with Mysql.