HIGH broken access controlfastapibasic auth

Broken Access Control in Fastapi with Basic Auth

Broken Access Control in Fastapi with Basic Auth — how this specific combination creates or exposes the vulnerability

Broken Access Control occurs when authorization checks are missing or incorrectly enforced, allowing authenticated users to access or modify resources that should be restricted. In Fastapi, combining Basic Auth with missing or permissive authorization logic commonly leads to BOLA (Broken Object Level Authorization) and IDOR (Insecure Direct Object References).

Fastapi’s Basic Auth implementation typically relies on HTTPBasic and a dependency that validates credentials. If the developer uses the authenticated user identity (e.g., a username or an ID from the decoded Basic Auth token) to directly look up database records without verifying ownership or permissions, the endpoint becomes vulnerable. For example, an authenticated user could simply change an item_id query parameter to access another user’s data, because the endpoint does not ensure that the requested resource belongs to the requesting identity.

Consider a Fastapi route that retrieves a document by ID using a Basic Auth user name as a tenant discriminator. If the route only checks that a user is authenticated and uses the raw user name to filter documents, an attacker can enumerate or manipulate IDs to access other tenants’ data. This becomes more likely when authorization checks are omitted or when the route uses a broad permission like "any authenticated user" without scoping to the specific resource ownership.

The 12 parallel security checks in middleBrick exercise such endpoints with unauthenticated scans and authenticated simulations (where credentials are provided) to detect whether authorization boundaries are enforced. It tests whether reading, updating, or deleting one resource automatically validates that the resource belongs to the requester. Findings often highlight missing row-level ownership checks, overly permissive role assignments, or endpoints that rely only on path parameters without cross-referencing the access context.

Additionally, when Basic Auth credentials are transmitted on every request without TLS, credentials can be intercepted. Even with TLS, storing or logging Basic Auth credentials insecurely on the server may expose them. middleBrick’s Data Exposure and Encryption checks surface such risks by verifying that sensitive headers are not reflected in logs and that endpoints enforce transport security expectations.

To illustrate, an unsafe Fastapi route might look like this, where the developer forgets to scope the query to the authenticated user:

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from typing import Dict

app = FastAPI()
security = HTTPBasic()

# In-memory store for demonstration
USERS = {"alice": "wonderland", "bob": "builder"}
ITEMS = {
    1: {"owner": "alice", "data": "Alice’s secret"},
    2: {"owner": "bob", "data": "Bob’s secret"},
}

def get_current_user(credentials: HTTPBasicCredentials = Depends(security)):
    username = credentials.username
    password = credentials.password
    if username in USERS and USERS[username] == password:
        return username
    raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")

@app.get("/items/{item_id}")
def read_item(item_id: int, user: str = Depends(get_current_user)):
    item = ITEMS.get(item_id)
    if not item:
        raise HTTPException(status_code=404, detail="Item not found")
    # Missing: ensure item["owner"] == user
    return item

In this example, any authenticated user can access any item by changing item_id. middleBrick would flag this as a BOLA/IDOR finding, noting the absence of an authorization check that ties the item to the authenticated user.

Basic Auth-Specific Remediation in Fastapi — concrete code fixes

Remediation centers on enforcing ownership or role-based checks on every request and avoiding unsafe patterns with Basic Auth. Always use TLS to protect credentials in transit. Prefer token-based authentication for new projects, but if you must use Basic Auth, ensure the authenticated identity is used consistently to scope data access.

Below is a secure version of the earlier route that includes an explicit ownership check:

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from typing import Dict

app = FastAPI()
security = HTTPBasic()

USERS = {"alice": "wonderland", "bob": "builder"}
ITEMS = {
    1: {"owner": "alice", "data": "Alice’s secret"},
    2: {"owner": "bob", "data": "Bob’s secret"},
}

def get_current_user(credentials: HTTPBasicCredentials = Depends(security)):
    username = credentials.username
    password = credentials.password
    if username in USERS and USERS[username] == password:
        return username
    raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")

@app.get("/items/{item_id}")
def read_item(item_id: int, user: str = Depends(get_current_user)):
    item = ITEMS.get(item_id)
    if not item:
        raise HTTPException(status_code=404, detail="Item not found")
    if item["owner"] != user:
        raise HTTPException(status_code=403, detail="Access denied to this item")
    return item

This pattern ensures that the authenticated user can only access items where the owner matches the identity derived from Basic Auth. For endpoints that modify or delete resources, apply the same ownership check, or use a role-based approach if your model requires it.

When designing APIs, avoid exposing internal IDs that can be easily guessed; instead use opaque identifiers and verify access on each request. middleBrick’s Authorization and BOLA/IDOR checks validate that such controls are present and effective by simulating authenticated interactions and inspecting whether the server enforces boundaries.

In addition to runtime checks, review your OpenAPI specification to ensure that security schemes are defined clearly and that paths requiring authorization are explicitly tied to the security requirement. Tools like middleBrick’s OpenAPI/Swagger analysis resolve $ref chains and cross-reference spec definitions with runtime behavior to highlight mismatches.

Frequently Asked Questions

Does using Basic Auth with HTTPS fully protect against Broken Access Control?
No. HTTPS protects credentials in transit, but it does not enforce authorization. Without explicit ownership or role checks, authenticated users can still access other users’ resources (BOLA/IDOR). Always validate that each request is authorized for the specific resource and user.
How can I test my Fastapi endpoints for Broken Access Control without a pentest vendor?
You can use unauthenticated scans and authenticated simulations that include user-specific requests to see whether endpoints enforce ownership. middleBrick runs parallel checks that test for missing authorization boundaries and produces findings with severity and remediation guidance, helping you validate controls without a pentest vendor.