HIGH api key exposurehapicockroachdb

Api Key Exposure in Hapi with Cockroachdb

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

Api key exposure becomes more likely when Hapi services interact with Cockroachdb in common patterns that mishandle secrets. A typical misconfiguration is storing database credentials or service-level API keys in environment variables that Hapi reads into process.env, then accidentally logging or echoing them during request handling. For example, if your Hapi server logs connection details on startup or includes them in error responses returned to the client, an attacker who can trigger or observe those responses can harvest the keys.

Another exposure vector comes from how Cockroachdb connection strings are constructed. If the connection URI includes an embedded password or API key and that string is passed through server-side code to logging, debugging, or telemetry hooks, the key can leak into logs or crash reports. This is especially risky when Hapi plugins or route handlers dynamically build connection strings using user-controlled inputs without strict validation, enabling injection or concatenation mistakes that expose the full credential string.

Cockroachdb’s wire protocol and SQL behavior also play a role. If your Hapi routes execute dynamic SQL using string concatenation rather than parameterized queries, an attacker may leverage injection to extract metadata or results that include sensitive connection attributes or keys stored in user tables. Even when using an ORM, if the configuration object containing sensitive keys is serialized into logs or error traces, the keys are effectively exposed to anyone who can trigger or observe those outputs.

Cockroachdb-Specific Remediation in Hapi — concrete code fixes

Secure Hapi integrations with Cockroachdb by keeping credentials out of logs and out of dynamic SQL. Use environment variables for secrets at runtime but ensure they are never included in response bodies or debug output. Below are concrete, realistic code examples that demonstrate safe patterns for Hapi with Cockroachdb.

Secure Hapi server setup with Cockroachdb credentials

// server.js — safe Hapi setup with Cockroachdb
'use strict';
const Hapi = require('@hapi/hapi');
const { Pool } = require('pg'); // Use the Postgres-compatible driver for Cockroachdb

// Load from environment; do not log these values
const dbHost = process.env.COCKROACHDB_HOST || 'localhost';
const dbPort = process.env.COCKROACHDB_PORT || 26257;
const dbUser = process.env.COCKROACHDB_USER || 'maxroach';
const dbPassword = process.env.COCKROACHDB_PASSWORD; // must be set in deployment
const dbName = process.env.COCKROACHDB_DB_NAME || 'mydb';

if (!dbPassword) {
  console.error('FATAL: COCKROACHDB_PASSWORD environment variable is required.');
  process.exit(1);
}

const pool = new Pool({
  host: dbHost,
  port: dbPort,
  user: dbUser,
  password: dbPassword,
  database: dbName,
  ssl: {
    rejectUnauthorized: false // Use proper CA in production
  }
});

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

  // Register a route that safely queries Cockroachdb
  server.route({
    method: 'GET',
    path: '/users/{id}',
    handler: async (request, h) => {
      const { id } = request.params;
      // Use parameterized query to prevent injection and avoid exposing credentials in SQL strings
      const result = await pool.query('SELECT id, name, email FROM users WHERE id = $1', [id]);
      if (result.rows.length === 0) {
        return h.response({ error: 'User not found' }).code(404);
      }
      return result.rows[0];
    }
  });

  // Graceful error handler that does not leak stack or config details
  server.ext('onPreResponse', (request, h) => {
    const response = request.response;
    if (response.isBoom) {
      // Log full details server-side; return generic message to client
      console.error('Request error:', response.originalError && response.originalError.message ? response.originalError.message : response.message);
      return h.response({ error: 'Internal server error' }).code(response.output.statusCode);
    }
    return h.continue;
  });

  await server.start();
  console.log('Server running on port', server.info.port);
};

process.on('unhandledRejection', (err) => {
  console.error('Unhandled rejection:', err && err.message ? err.message : err);
  process.exit(1);
});

init();

Key remediation practices

  • Keep API keys and database passwords in environment variables and ensure they are not concatenated into logs or responses.
  • Always use parameterized queries with Cockroachdb to avoid SQL injection and prevent attackers from manipulating SQL to expose configuration or metadata.
  • Scrub server-side logs and error responses to remove any sensitive values; return generic error messages to clients.
  • Use TLS for Cockroachdb connections and validate certificates to protect credentials in transit.

Frequently Asked Questions

Can Cockroachdb connection strings safely include passwords if they are logged for debugging?
No. Including passwords in connection strings that are logged or exposed in error responses can lead to credential leakage. Store secrets in environment variables and ensure they are never written to logs or returned to clients.
Is it safe to construct Cockroachdb queries by concatenating user input if I validate the input on the server?
No. Validation alone is not sufficient against injection. Always use parameterized queries with placeholders to prevent SQL injection and avoid constructing SQL strings from user-controlled data.