Dangling Dns in Hapi with Cockroachdb
Dangling Dns in Hapi with Cockroachdb — how this specific combination creates or exposes the vulnerability
A dangling DNS configuration in a Hapi server that uses CockroachDB can expose runtime behavior that leaks internal network information or causes inconsistent service discovery. In this combination, the Hapi application resolves a CockroachDB connection string via DNS at startup or reconnect intervals. If the DNS record points to an internal, non-routable address or an unstable internal hostname, the application may attempt connections that never succeed, leaving sockets open or creating unresolved host entries. Attackers probing the unauthenticated API surface can infer the presence of internal infrastructure through timing differences, repeated connection attempts, or observable error patterns in logs returned by the API.
The vulnerability is not in CockroachDB itself but in how Hapi resolves and caches DNS names for the database endpoint. When Hapi initializes its database plugin or connection pool, it may store the resolved IP. If the DNS record changes or points to an internal resolver, the application might continue using an outdated address, effectively dangling a name that should refer to a reachable, authenticated endpoint. This can expose that the backend relies on internal service naming conventions, revealing environment topology through error messages or connection retries visible via API responses or monitoring integrations.
During a middleBrick scan, checks related to Input Validation, Data Exposure, and Inventory Management may surface indicators such as repeated failed connections, unreachable endpoints, or metadata leakage in stack traces. Because the scan tests the unauthenticated attack surface, it can detect that DNS-based service discovery is not hardened, and the API may return information about backend attempts to resolve CockroachDB hosts. An OpenAPI/Swagger spec analysis with full $ref resolution can show that database connection details are not explicitly abstracted, allowing cross-referencing of runtime findings with spec definitions to highlight insecure configurations.
To illustrate a typical Hapi server setup with CockroachDB using raw Node.js request handling, consider this example that does not validate or sanitize connection inputs:
const Hapi = require('@hapi/hapi');
const { Pool } = require('pg');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: '0.0.0.0'
});
const pool = new Pool({
connectionString: process.env.COCKRACK_DB_URL
});
await pool.connect();
server.route({
method: 'GET',
path: '/lookup',
handler: async (request, h) => {
const { rows } = await pool.query('SELECT id, name FROM accounts WHERE id = $1', [request.query.id]);
return rows;
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
init().catch(err => {
console.error(err);
process.exit(1);
});
In this setup, COCKRACK_DB_URL might resolve via DNS to an internal hostname that is not publicly reachable. If the DNS record is stale or points to a dangling namespace, the application reveals timing behavior and connection errors that can be correlated by a scanner. MiddleBrick’s parallel checks, such as Authentication and BOLA/IDOR, can highlight that unauthenticated endpoints indirectly expose backend resolution patterns, and the OpenAPI analysis may show that database connection details are not sufficiently abstracted from the public contract.
Cockroachdb-Specific Remediation in Hapi — concrete code fixes
Remediation focuses on removing DNS dependency for database connectivity in Hapi, ensuring that connection strings use explicit network endpoints or service discovery mechanisms that do not rely on mutable DNS records. You should avoid passing raw DNS-resolved hostnames directly to the database driver and instead use stable connection parameters or environment variables that point to reachable IPs or load balancers with health checks.
For CockroachDB, prefer using a connection string that includes explicit network addresses and, if needed, leverage secure client certificates rather than relying on internal DNS names. The following example demonstrates a hardened Hapi initialization that uses a direct connection string and properly manages the pool without exposing internal naming artifacts:
const Hapi = require('@hapi/hapi');
const { Pool } = require('pg');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: '127.0.0.1'
});
// Use an explicit connection string with stable network targets
const pool = new Pool({
connectionString: 'postgresql://user:[email protected]:26257/defaultdb?sslmode=require',
ssl: {
rejectUnauthorized: true
}
});
// Validate connectivity early and fail fast
try {
const client = await pool.connect();
await client.release();
} catch (err) {
console.error('Database connection failed:', err.message);
process.exit(1);
}
server.route({
method: 'GET',
path: '/lookup',
handler: async (request, h) => {
const client = await pool.connect();
try {
const { rows } = await client.query(
'SELECT id, name FROM accounts WHERE id = $1',
[request.query.id]
);
return rows;
} finally {
client.release();
}
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
init().catch(err => {
console.error(err);
process.exit(1);
});
Additionally, you should configure your deployment environment to use static IPs or a managed service discovery mechanism that does not rely on DNS records that can become dangling. In a Kubernetes environment, for example, use a headless service with stable endpoints or an external load balancer that points to the CockroachDB cluster’s advertised addresses. MiddleBrick’s Pro plan supports continuous monitoring with configurable scanning schedules, which can alert you if runtime behavior indicates repeated DNS resolution failures or exposure of internal endpoints, helping you maintain a hardened posture without relying on unauthenticated diagnostics.
For teams using CI/CD, the middleBrick GitHub Action can integrate API security checks into your pipeline, failing builds if risk scores exceed your defined thresholds. This ensures that configurations like the Hapi CockroachDB example are validated before deployment, reducing the chance of introducing dangling DNS references into production. The MCP Server allows you to scan APIs directly from your IDE, providing immediate feedback during development while adhering to secure connection practices.