HIGH integrity failuresexpressbasic auth

Integrity Failures in Express with Basic Auth

Integrity Failures in Express with Basic Auth — how this specific combination creates or exposes the vulnerability

Integrity failures occur when an attacker can alter, replay, or strip authentication information in transit or within application logic. In Express, combining HTTP Basic Auth with integrity weaknesses typically stems from transporting credentials without protection or from insufficient validation of request authenticity. Basic Auth encodes credentials with Base64, not encryption; if no transport layer protection is enforced, credentials are easily decoded by anyone on the network. Even when TLS is used, integrity failures can arise if the application treats authenticated requests as inherently trustworthy after initial validation.

For example, an endpoint that relies solely on Basic Auth headers may parse credentials once and then assume the associated identity and permissions for subsequent operations without revalidating integrity-sensitive aspects such as the request origin, resource ownership, or mutation intent. This becomes problematic in scenarios involving idempotent operations or when authorization checks are inconsistently applied. MiddleBrick’s checks for BOLA/IDOR and Property Authorization often surface these gaps by observing whether an authenticated user can modify or access another user’s resources simply by altering identifiers in the request, despite presenting valid Basic Auth credentials.

Another integrity concern involves replay attacks: captured Basic Auth requests can be replayed over the same TLS session or a new one if the application does not implement nonce or timestamp protections. Additionally, if the Express app exposes administrative or state-changing endpoints without requiring re-authentication or additional integrity checks (such as CSRF tokens or signed requests), an attacker who obtains credentials can perform unauthorized state changes. The LLM/AI Security checks may further reveal whether prompt injection or output leakage occurs when Basic Auth is used in AI-assisted endpoints, exposing how authentication context might inadvertently influence model behavior.

When scanning an Express API with middleBrick, findings related to Integrity Failures under Basic Auth often include missing or weak TLS enforcement, inadequate scope validation, and missing request integrity mechanisms. The scanner cross-references the OpenAPI specification’s security schemes with runtime behavior to confirm whether Basic Auth is properly constrained and whether authenticated sessions are treated with appropriate caution. This helps teams understand whether their current implementation truly preserves integrity or merely provides a superficial authentication layer.

Basic Auth-Specific Remediation in Express — concrete code fixes

Remediation focuses on ensuring credentials are protected in transit, validating integrity on each request, and applying authorization consistently. Always enforce HTTPS using HTTP Strict Transport Security (HSTS) and never transmit Basic Auth over plain HTTP. Use middleware to validate the Authorization header on protected routes and avoid relying on parsed credentials beyond the initial authentication step.

Here is a secure Express pattern using Basic Auth with integrity-focused checks:

const express = require('express');
const crypto = require('crypto');
const app = express();

// Basic Auth middleware with integrity checks
function basicAuth(req, res, next) {
  const authHeader = req.headers['authorization'];
  if (!authHeader || !authHeader.startsWith('Basic ')) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  const base64 = authHeader.split(' ')[1];
  const decoded = Buffer.from(base64, 'base64').toString('utf-8');
  const [username, password] = decoded.split(':');

  // Validate credentials against a secure store (example uses hardcoded for illustration)
  const validUser = validateUser(username, password);
  if (!validUser) {
    return res.status(403).json({ error: 'Forbidden' });
  }

  // Attach user with integrity metadata
  req.user = {
    username,
    roles: validUser.roles,
    nonce: crypto.randomBytes(16).toString('hex'), // prevent replay
  };
  next();
}

// Example protected route with ownership check
app.put('/api/resource/:id', basicAuth, (req, res) => {
  const resourceId = req.params.id;
  const userId = req.user.username;

  // BOLA/IDOR check: ensure user can only modify their own resources
  if (!canModifyResource(userId, resourceId)) {
    return res.status(403).json({ error: 'Insufficient permissions' });
  }

  // Apply update...
  res.json({ status: 'updated' });
});

// Enforce HTTPS in production
app.use((req, res, next) => {
  if (process.env.NODE_ENV === 'production' && !req.secure) {
    return res.status(400).json({ error: 'HTTPS required' });
  }
  next();
});

function validateUser(username, password) {
  // Replace with secure lookup and password hashing verification
  return { username, roles: ['user'] };
}

function canModifyResource(userId, resourceId) {
  // Replace with actual data ownership check
  return true;
}

app.listen(3000, () => console.log('Server running on port 3000'));

Key practices include enforcing TLS, validating the Authorization header on every request, avoiding caching of decoded credentials, and performing ownership or scope checks before any state change. For broader protection, integrate the middleBrick CLI (middlebrick scan <url>) to continuously detect integrity-related misconfigurations and use the GitHub Action to fail builds if risk scores degrade. Teams on the Pro plan can enable continuous monitoring and receive Slack or Teams alerts when integrity issues are detected, ensuring prompt remediation.

Frequently Asked Questions

Is Basic Auth safe to use in Express if I use HTTPS?
HTTPS protects credentials in transit, but Basic Auth still requires additional integrity controls such as request validation, ownership checks, and replay protections. Always combine with strong transport security and scope-aware authorization.
How can I test if my Express endpoints have integrity issues with Basic Auth?
Use the middleBrick CLI to scan your API: run middlebrick scan <your-api-url>. The scan will identify missing integrity checks, BOLA/IDOR risks, and misconfigured authentication schemes without requiring credentials or agents.