HIGH api key exposurefibermssql

Api Key Exposure in Fiber with Mssql

Api Key Exposure in Fiber with Mssql

Api key exposure occurs when API keys are inadvertently accessible through application endpoints, logs, or responses. In a Fiber application using Microsoft SQL Server (Mssql), this risk arises when route handlers or middleware expose sensitive keys through debug endpoints, verbose error messages, or improper data handling. For example, a route that echoes request parameters in SQL queries can leak keys embedded in query strings or headers.

Consider a Fiber endpoint that dynamically builds queries using string concatenation:

const sql = require('mssql');
const express = require('fastify')();

express.get('/user/:id', async (req, res) => {
  const pool = await sql.connect('server=localhost;database=test;user=sa;password=Pass@123;');
  const result = await pool.request().query(`SELECT * FROM users WHERE id = ${req.params.id}`);
  res.send(result.recordset);
});

If the connection string containing the database password is logged or returned in error responses, an attacker can harvest the key. Additionally, misconfigured CORS or missing security headers in Fiber can allow browser-based leakage of keys via cross-origin requests.

The LLM/AI Security checks in middleBrick specifically detect system prompt leakage patterns that could expose keys in AI-generated responses, while the Data Exposure check flags endpoints that return sensitive configuration data. For instance, an unauthenticated scan might reveal a debug route like /debug/config that returns full Mssql connection details, including the API key used for authentication.

Insecure deserialization or improper input validation can further enable key extraction. If a Fiber route accepts JSON payloads and passes them directly to Mssql stored procedures without sanitization, an attacker might inject payloads that return key material through error messages or secondary queries.

middleBrick’s OpenAPI/Swagger analysis correlates spec definitions with runtime behavior to identify such exposures. For example, if an endpoint definition lacks security schemes but returns database credentials, the scanner flags it as high risk. The Inventory Management check ensures that all external secrets are accounted for, reducing the chance of forgotten keys in code.

Mssql-Specific Remediation in Fiber

Remediation focuses on preventing key exposure through secure coding practices and proper configuration. Always use parameterized queries to avoid injection and accidental key leakage in error messages.

Replace dynamic SQL with prepared statements:

const sql = require('mssql');
const fastify = require('fastify')();

fastify.get('/user/:id', async (request, reply) => {
  const pool = await sql.connect('server=localhost;database=mydb;user=sa;password=encryptedPass;');
  const result = await pool.request()
    .input('id', sql.Int, request.params.id)
    .query('SELECT * FROM users WHERE id = @id');
  reply.send(result.recordset);
});

This ensures that user input never concatenates into the query string, reducing the risk of key exposure through injection attacks.

Secure connection management is critical. Store Mssql credentials in environment variables and avoid hardcoding them:

const poolConfig = {
  server: process.env.DB_SERVER,
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  options: {
    encrypt: true,
    trustServerCertificate: false
  }
};
const pool = await sql.connect(poolConfig);

Enable encryption for all Mssql connections in Fiber to prevent eavesdropping. The Encryption check in middleBrick verifies that TLS is enforced and that certificates are validated properly.

Implement robust error handling to prevent verbose messages from leaking keys:

fastify.setErrorHandler((error, request, reply) => {
  if (error instanceof sql.errors.SqlError) {
    console.error('Database error occurred');
    reply.code(500).send({ error: 'Internal server error' });
  } else {
    reply.code(500).send({ error: 'Unexpected error' });
  }
});

Use middleware to strip sensitive headers and disable debugging routes in production. The Data Exposure check ensures that endpoints do not return connection strings or keys in JSON responses.

middleBrick’s Continuous Monitoring in the Pro plan can schedule regular scans to detect regressions. If a new endpoint accidentally logs Mssql credentials, the system alerts you before keys are exposed publicly.

Frequently Asked Questions

How does middleBrick detect Api Key Exposure in Fiber applications using Mssql?
middleBrick performs unauthenticated black-box scans, checking for endpoints that expose connection strings or keys in responses, logs, or error messages. It cross-references OpenAPI specs with runtime behavior and applies Data Exposure and LLM/AI Security checks to identify leakage patterns.
Can the GitHub Action prevent Api Key Exposure in CI/CD for Fiber with Mssql?
Yes, the GitHub Action can be configured to fail builds if a scan detects high-risk findings related to key exposure. This ensures that insecure code does not reach production.