HIGH path traversalhapibasic auth

Path Traversal in Hapi with Basic Auth

Path Traversal in Hapi with Basic Auth — how this specific combination creates or exposes the vulnerability

Path Traversal occurs when an API endpoint uses user-controlled input to build file system paths without adequate validation or sanitization. In Hapi, this commonly appears in routes that serve files or access resources based on parameters such as filename or path. Even when Basic Authentication is enforced, the presence of authentication does not inherently protect against Path Traversal; it only identifies the requesting user. An authenticated attacker can still supply malicious inputs like ../../../etc/passwd to access files outside the intended directory.

Consider a Hapi route that serves user documents. If the route relies on concatenating a base directory with a user-provided filename, and does not canonicalize or validate the resulting path, an authenticated user can traverse directories. For example, a route defined as /files/{name} that maps to a filesystem path may allow an authenticated user to request /files/../../../etc/shadow. Because the request includes valid Basic Auth credentials, the server processes the request with the expected authentication context, but the handler does not prevent directory escape.

This combination is significant because Basic Auth provides identity, but not authorization boundaries. middleBrick detects such patterns by correlating authentication presence with path construction logic. The scanner checks whether user input undergoes normalization, validation, and strict allowlisting. Without these controls, authenticated access to unintended resources remains possible, and middleBrick reports this as a high-severity finding aligned with OWASP API Top 10 and relevant compliance mappings.

Basic Auth-Specific Remediation in Hapi — concrete code fixes

To mitigate Path Traversal in Hapi while using Basic Auth, ensure that user input is never directly used in filesystem operations. Use path validation, canonical resolution, and strict allowlisting. The following examples demonstrate secure patterns.

Secure route implementation with validation

const Hapi = require('@hapi/hapi');
const Path = require('path');
const Fs = require('fs');

const allowedFiles = new Set(['report.pdf', 'image.png', 'readme.txt']);

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

  server.auth.strategy('simple', 'basic', {
    validate: (request, username, password, h) => {
      // Replace with secure credential verification
      if (username === 'user' && password === 'pass') {
        return { isValid: true, credentials: { username } };
      }
      return { isValid: false };
    }
  });

  server.route({
    method: 'GET',
    path: '/files/{filename}',
    options: {
      auth: 'simple',
      handler: (request, h) => {
        const { filename } = request.params;

        // Validate against allowlist
        if (!allowedFiles.has(filename)) {
          return h.response('File not allowed').code(400);
        }

        // Resolve to absolute path safely
        const safePath = Path.resolve('/var/uploads', filename);

        // Ensure the resolved path is within the allowed directory
        if (!safePath.startsWith(Path.resolve('/var/uploads'))) {
          return h.response('Invalid path').code(400);
        }

        if (!Fs.existsSync(safePath)) {
          return h.response('File not found').code(404);
        }

        return Fs.readFileSync(safePath);
      }
    }
  });

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

init().catch(err => {
  console.error(err);
});

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Does enabling Basic Auth in Hapi prevent Path Traversal attacks?
No. Basic Auth provides identity but does not prevent malicious path inputs. Always validate, sanitize, and restrict file paths independently of authentication.
How does middleBrick assess Path Traversal in authenticated endpoints?
middleBrick scans unauthenticated attack surface and correlates findings with authentication mechanisms. It checks whether user input is properly validated and canonicalized, regardless of authentication, and reports findings with remediation guidance.