Hapi API Security

Hapi Security Posture

Hapi provides a solid security foundation out of the box, but like any framework, its defaults require careful attention. The framework includes built-in protections such as XSS prevention through output escaping, CSRF token generation, and input validation via joi schemas. However, Hapi's security posture is notably conservative—many critical protections are opt-in rather than enabled by default.

The framework's plugin architecture, while powerful, can introduce security gaps if plugins aren't properly vetted. Common authentication plugins like hapi-auth-jwt2 and hapi-auth-basic require explicit configuration, and misconfiguration is a frequent source of vulnerabilities. Hapi's validation system, though robust when used correctly, doesn't enforce validation globally—developers must remember to validate every input.

Environment-specific configuration is another area where Hapi can trip developers up. Production deployments often inherit development settings, leaving debug endpoints exposed or authentication bypassed. The framework's flexibility means security is only as strong as your implementation choices, making regular security audits essential for production APIs.

Top 5 Security Pitfalls in Hapi

Developers frequently encounter these security misconfigurations when building Hapi APIs. Understanding these pitfalls can prevent common vulnerabilities that plague production systems.

1. Missing Input Validation: Hapi's validation is optional by default. Developers often forget to add joi schemas to route handlers, leaving endpoints vulnerable to injection attacks, malformed requests, and data integrity issues. Without validation, attackers can send arbitrary data that breaks application logic or exposes sensitive information.

2. Insecure Default CORS Configuration: Hapi's CORS plugin defaults to allowing all origins, methods, and headers when first configured. This overly permissive setup enables cross-origin attacks and data exposure to malicious websites. Production APIs should restrict origins to trusted domains and limit allowed HTTP methods.

3. Debug Mode in Production: Hapi's debug mode provides detailed error messages and stack traces that are invaluable during development but catastrophic in production. These verbose error responses can reveal server paths, database schemas, and implementation details that attackers use to craft targeted exploits.

4. Insufficient Authentication Scope Checks: Hapi's authentication system allows fine-grained scope control, but developers often implement overly broad scopes or fail to check permissions on individual routes. This leads to privilege escalation where authenticated users access resources they shouldn't see.

5. Unprotected Plugin Endpoints: Hapi's plugin system can register routes without proper authentication or authorization. Plugin developers may assume their endpoints are internal-only, but without explicit security controls, these become attack vectors for unauthenticated access to administrative functions.

Security Hardening Checklist

Implementing these security measures will significantly strengthen your Hapi API's security posture. Each recommendation addresses common vulnerabilities and establishes defense-in-depth principles.

Input Validation: Always use joi schemas for route validation. Define schemas for query parameters, path parameters, headers, and payload. Example:

const schema = Joi.object({
  userId: Joi.string().uuid().required(),
  email: Joi.string().email().required(),
  age: Joi.number().integer().min(0).max(150)
});

server.route({
  method: 'POST',
  path: '/users',
  options: {
    validate: {
      payload: schema
    }
  },
  handler: createUser
});

CORS Configuration: Restrict origins to your production domains and limit methods. Never use wildcard origins in production:

const corsOptions = {
  origins: ['https://yourdomain.com', 'https://app.yourdomain.com'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  headers: ['Authorization', 'Content-Type', 'Accept']
};

await server.register({ plugin: require('@hapi/cors'), options: corsOptions });

Production Security Headers: Use the hapip-inert plugin or middleware to set security headers:

server.ext('onPreResponse', (request, h) => {
  const response = request.response;
  if (!response.headers['x-content-type-options']) {
    response.headers['x-content-type-options'] = 'nosniff';
  }
  if (!response.headers['x-frame-options']) {
    response.headers['x-frame-options'] = 'DENY';
  }
  return h.continue;
});

Authentication & Authorization: Implement role-based access control with proper scope checking. Use the hapi-auth-jwt2 plugin with RSA signing and validate scopes on each route:

server.route({
  method: 'GET',
  path: '/admin/users',
  options: {
    auth: {
      strategy: 'jwt',
      scope: ['admin', 'user-manager']
    }
  },
  handler: listUsers
});

Rate Limiting: Protect against brute force and DoS attacks using the hapi-rate-limitor plugin:

await server.register(require('hapi-rate-limitor'));
server.route({
  method: 'POST',
  path: '/login',
  options: {
    plugins: {
      rateLimitor: {
        max: 5,
        window: 900,
        whitelist: ['127.0.0.1']
      }
    }
  },
  handler: login
});

Logging & Monitoring: Implement comprehensive logging for security events. Log authentication failures, authorization errors, and unusual access patterns. Use structured logging with correlation IDs for tracing attacks.

Frequently Asked Questions

How can I scan my Hapi API for security vulnerabilities?
middleBrick provides instant security scanning for Hapi APIs without requiring any credentials or configuration. Simply submit your API endpoint URL to middleBrick's web dashboard or use the CLI tool with middlebrick scan https://yourapi.com. The scanner tests your unauthenticated attack surface across 12 security categories including authentication bypass, IDOR vulnerabilities, input validation issues, and rate limiting weaknesses. For Hapi-specific concerns, middleBrick checks for common misconfigurations like missing input validation, insecure CORS settings, and debug mode exposure. The scan takes 5-15 seconds and provides a letter grade security score with prioritized findings and remediation guidance.
Does middleBrick support Hapi's plugin architecture security analysis?
Yes, middleBrick's black-box scanning methodology effectively tests Hapi APIs regardless of their internal plugin architecture. Since middleBrick doesn't require access to your source code or server configuration, it can scan APIs built with any combination of Hapi plugins. The scanner tests the actual runtime behavior of your endpoints, identifying vulnerabilities that might arise from plugin interactions or misconfigurations. Whether you're using authentication plugins, CORS middleware, or custom business logic plugins, middleBrick will detect security issues in the exposed API surface without needing to understand your specific plugin stack.
Can I integrate Hapi API security testing into my CI/CD pipeline?
Absolutely. The middleBrick GitHub Action allows you to add automated security testing to your CI/CD pipeline for Hapi APIs. You can configure the action to scan your staging or production API endpoints on every pull request or deployment. The action can be set to fail builds if security scores drop below your defined threshold, ensuring that security regressions are caught before they reach production. This is particularly valuable for Hapi APIs where security misconfigurations can easily be introduced through plugin updates or configuration changes. The GitHub Action integrates seamlessly with your existing workflow, providing security gates that protect your API throughout the development lifecycle.