{}DSA Atlas

API Security — OWASP & Common Vulnerabilities

The OWASP API Security Top 10 (2023) explained with fixes, plus SQL injection, XSS, CSRF, SSRF, mass assignment, insecure deserialization, secrets management, security headers, supply-chain risk, and security logging.

Intermediate → Advanced7 interview questions

The OWASP API Security Top 10 (2023)

#RiskExampleFix
API1Broken Object Level AuthorizationGET /invoices/1044 returns someone else's invoiceper-object authorization on every access; tenant-scoped queries
API2Broken Authenticationno rate limit on login; weak JWT validationMFA, rate limits, proper token validation, short-lived tokens
API3Broken Object Property Level AuthorizationPATCH /me {"role":"admin"}; responses leak password_hashexplicit input/output schemas, field-level authz
API4Unrestricted Resource Consumption?limit=1000000, huge uploads, expensive searchrate limits, quotas, size/page caps, timeouts, cost limits
API5Broken Function Level Authorizationnormal user calls DELETE /admin/users/7role checks per function; deny by default
API6Unrestricted Access to Sensitive Business Flowsscalper bots buy all ticketsbot detection, device fingerprinting, per-account limits, CAPTCHA
API7SSRF"import from URL" fetches cloud metadataallow-lists, block internal ranges, isolated egress
API8Security Misconfigurationstack traces, Access-Control-Allow-Origin: * with credentialshardened defaults, config scanning, security headers
API9Improper Inventory Managementforgotten /v1 without auth fixesAPI inventory, gateway as the only entry, retire old versions
API10Unsafe Consumption of APIstrusting a partner API's redirects/datavalidate and sanitise third-party data, TLS, timeouts

Injection

# ✅ parameterised
cur.execute("SELECT id, name FROM product WHERE category = %s ORDER BY price LIMIT %s", (cat, limit))

# ✅ identifiers from an allow-list
SORTABLE = {"price": "price", "newest": "created_at"}
order_col = SORTABLE.get(sort, "created_at")
cur.execute(f"SELECT id, name FROM product ORDER BY {order_col} DESC LIMIT %s", (limit,))
// ✅ parameterised (node-postgres)
await pool.query("SELECT * FROM users WHERE email = $1", [email]);

// ❌ command injection
exec(`convert ${userFileName} out.png`);
// ✅ pass arguments as an array, no shell
execFile("convert", [userFileName, "out.png"]);

XSS and security headers

HTTP
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Cross-Origin-Opener-Policy: same-origin
HeaderProtects against
Content-Security-PolicyXSS impact, clickjacking (frame-ancestors), data injection
Strict-Transport-SecuritySSL stripping
X-Content-Type-Options: nosniffMIME-sniffing attacks
Referrer-Policyleaking URLs (tokens) to third parties
Cross-Origin-*-Policycross-origin data leaks (Spectre-class)

CSRF

Victim's browserlogged in to bank.com evil.comauto-submitting form bank.comPOST /transfer visits browser sends the form + bank.com cookies fixes: SameSite=Lax/Strict cookies · CSRF tokens · Origin/Sec-Fetch-Site checks · no state changes on GET
The browser's automatic cookie attachment is what CSRF abuses.

SSRF-safe URL fetching

Python
import ipaddress, socket
from urllib.parse import urlparse

BLOCKED = [ipaddress.ip_network(n) for n in (
    "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8",
    "169.254.0.0/16", "100.64.0.0/10", "::1/128", "fc00::/7", "fe80::/10")]

def safe_target(url: str) -> str:
    u = urlparse(url)
    if u.scheme not in ("http", "https"):
        raise ValueError("scheme not allowed")
    ip = ipaddress.ip_address(socket.gethostbyname(u.hostname))
    if any(ip in net for net in BLOCKED) or ip.is_reserved or ip.is_multicast:
        raise ValueError("destination not allowed")
    return str(ip)   # connect to THIS ip (pin it) with Host/SNI set to u.hostname; disable redirects

Mass assignment

Python
class UpdateProfile(BaseModel):
    model_config = {"extra": "forbid"}        # unknown fields → 422
    display_name: str | None = None
    bio: str | None = Field(default=None, max_length=500)
    # is_admin, balance, email_verified are NOT accepted here

class PublicUser(BaseModel):                  # explicit response shape
    id: str
    display_name: str

Secrets management

Serviceworkload identity Secrets managerVault · AWS SM · GCP SM KMS / HSMencrypts secrets auth by identityshort-lived secret no secrets in Git, images or logs · automatic rotation · audit trail
Fetch secrets at runtime using the workload's identity; prefer dynamic, short-lived credentials.

Other risks to know

RiskMitigation
Insecure deserialization (Java serialization, Python pickle, YAML load)never deserialize untrusted data with object-instantiating formats; use JSON + schemas; yaml.safe_load
Path traversal (../../etc/passwd)normalise and confine paths; use IDs, not filenames
File upload abusecheck type by content, size limits, store outside web root/in object storage, scan, serve from another domain
Open redirectsallow-list redirect targets
Timing attacks on secretsconstant-time comparison (hmac.compare_digest)
Dependency / supply-chain attackslockfiles, pinned versions, SCA scanning (Dependabot, Snyk), SBOMs, signed artifacts (Sigstore), minimal base images
Verbose errorsgeneric messages to clients, details in logs only
Log injection / sensitive data in logsstructured logging, redact PII/tokens
Clickjackingframe-ancestors 'none'

Security in the development lifecycle

  • Threat modelling for new features (STRIDE: spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege).
  • SAST/DAST/SCA in CI; secret scanning; container image scanning.
  • Security-focused code review checklists (authz on every endpoint!).
  • Pen tests and bug bounties for public APIs.
  • Audit logs for security-relevant events (logins, permission changes, data exports) shipped to tamper-resistant storage.
  • Incident response runbooks: revoke tokens, rotate secrets, notify.

Interview questions

0 / 7 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.