ARCHIVED from builddistributedsystem.com on 2026-04-28 — URL: https://builddistributedsystem.com/tracks/securitor/tasks/task-24-1-5-api-security
TASK

Implementation

API security is a set of layers: rate limiting prevents abuse, input validation rejects malformed data before it reaches business logic, parameterised queries prevent SQL injection, and security headers protect browsers from common attacks.

Implement a node that enforces all four security layers:

// Rate limiting: 100 requests per minute per IP
{ "type": "rate_limit_test", "msg_id": 1,
  "requests": 105, "window": "1m" }
-> { "type": "rate_limit_exceeded", "in_reply_to": 1,
    "allowed_requests": 100, "blocked_requests": 5 }

// Input validation: report all errors at once
{ "type": "create_user", "msg_id": 2,
  "email": "invalid-email", "password": "weak" }
-> { "type": "validation_error", "in_reply_to": 2,
    "errors": [{"field":"email","message":"Invalid email format"},
                {"field":"password","message":"Password must be at least 8 characters"}] }

// SQL injection attempt -> safe empty result (parameterised query)
{ "type": "search_users", "msg_id": 3,
  "email": "' OR '1'='1" }
-> { "type": "search_results", "in_reply_to": 3, "users": [] }

// Security headers on every response
{ "type": "get_options", "msg_id": 4 }
-> { "type": "options", "in_reply_to": 4,
    "headers": {"X-Frame-Options":"DENY",
                 "X-Content-Type-Options":"nosniff",
                 "Strict-Transport-Security":"max-age=31536000"} }

Sample Test Cases

Rate limitingTimeout: 5000ms
Input
{
  "src": "attacker",
  "dest": "api",
  "body": {
    "type": "rate_limit_test",
    "msg_id": 1,
    "requests": 105,
    "window": "1m"
  }
}
Expected Output
{"type": "rate_limit_exceeded", "in_reply_to": 1, "allowed_requests": 100, "blocked_requests": 5}
Input validationTimeout: 5000ms
Input
{
  "src": "client",
  "dest": "api",
  "body": {
    "type": "create_user",
    "msg_id": 1,
    "email": "invalid-email",
    "password": "weak"
  }
}
Expected Output
{"type": "validation_error", "in_reply_to": 1, "errors": [{"field": "email", "message": "Invalid email format"}, {"field": "password", "message": "Password must be at least 8 characters"}]}

Hints

Hint 1
Rate limiting: track request count per IP per window; block once count > limit
Hint 2
Input validation: check field types and formats before processing (email regex, min password length)
Hint 3
SQL injection: use parameterised queries — never interpolate user input into SQL strings
Hint 4
Security headers: X-Frame-Options, X-Content-Type-Options, Strict-Transport-Security
Hint 5
Return all validation errors together in the errors array, not just the first one
OVERVIEW

Theoretical Hub

Concept overview coming soon

Key Concepts

rate limitinginput validationSQL injection preventionsecurity headersOWASP
main.py
python
Implement API Security Best Practices - The Securitor | Build Distributed Systems