HIGH phishing api keysfastapidynamodb

Phishing Api Keys in Fastapi with Dynamodb

Phishing API Keys in FastAPI with DynamoDB — how this specific combination creates or exposes the vulnerability

When a FastAPI service stores or references AWS credentials and uses DynamoDB as a persistence layer, several patterns can unintentionally expose API keys to phishing. Common anti-patterns include logging raw headers, returning configuration details to the client, or exposing metadata endpoints that reveal temporary credentials. These patterns become high-risk when DynamoDB is used to store key metadata without strict authorization checks, because an attacker who can read or modify a single record may pivot to other AWS resources.

DynamoDB-specific risks arise when an API key is stored with insufficient access controls or when query logic is driven by attacker-supplied input. For example, if an endpoint accepts a user-supplied api_key_id and uses it directly in a GetItem or Query request without validating ownership, an attacker can enumerate keys or retrieve credentials belonging to other users. DynamoDB responses that include key material in plaintext—especially when combined with verbose error messages—can be harvested by phishing pages that mimic legitimate UI flows. In FastAPI, routes that return serialized items directly to the frontend increase exposure; if those items contain sensitive fields, a compromised frontend script can exfiltrate API keys via social engineering or malicious browser extensions.

LLM-related phishing surfaces differently. An endpoint that echoes back stored configuration to help developers debug may inadvertently leak system prompts or key identifiers that an LLM-based phishing tool can exploit. For instance, an unauthenticated route that returns the structure of DynamoDB-stored credentials could be probed to understand naming conventions used for keys. This information can then be used in targeted phishing lures that appear to come from internal tooling. middleBrick’s LLM/AI Security checks detect system prompt leakage and active prompt injection attempts across common formats, identifying risky endpoints before attackers can weaponize them.

Compliance mappings are relevant here: findings often align with OWASP API Top 10 (2023) — especially Broken Object Level Authorization and Security Misconfiguration — and map to controls in SOC 2 and GDPR. Because the issue spans application logic, data store configuration, and client-side handling, remediation must address all three layers. middleBrick scans test these attack surfaces in parallel, including Property Authorization and Unsafe Consumption checks, to highlight where DynamoDB access patterns and FastAPI route behavior combine to enable key exposure.

DynamoDB-Specific Remediation in FastAPI — concrete code fixes

Apply strict ownership checks and avoid returning sensitive fields. Use server-side filtering and conditional writes, and ensure DynamoDB calls are parameterized to prevent injection-driven data leaks.

from fastapi import Depends, HTTPException, status
from pydantic import BaseModel
import boto3
from botocore.exceptions import ClientError

# Models
class APIKeyRecord(BaseModel):
    user_id: str
    key_id: str
    # Do not include raw_key in responses; store only metadata
    last_used: str

def get_db():
    # In production, use dependency injection with proper credential scoping
    return boto3.resource('dynamodb', region_name='us-east-1')

# Fetch a key record by key_id only after validating ownership
def get_api_key_record(user_id: str, key_id: str) -> APIKeyRecord:
    dynamodb = get_db()
    table = dynamodb.Table('api_keys')
    try:
        response = table.get_item(
            Key={'key_id': key_id},
            ProjectionExpression='user_id, key_id, last_used'
        )
        item = response.get('Item')
        if not item:
            raise HTTPException(status_code=404, detail='Key not found')
        if item['user_id'] != user_id:
            raise HTTPException(status_code=403, detail='Access denied')
        return APIKeyRecord(**item)
    except ClientError as e:
        raise HTTPException(status_code=502, detail='Database error')

# Store without exposing raw key; store only a reference or metadata
def store_api_key_metadata(user_id: str, key_id: str, last_used: str):
    dynamodb = get_db()
    table = dynamodb.Table('api_keys')
    try:
        table.put_item(
            Item={
                'key_id': key_id,
                'user_id': user_id,
                'last_used': last_used,
                # Never store raw_key here; keep it in a secure vault or environment
            },
            ConditionExpression='attribute_not_exists(key_id)'
        )
    except ClientError as e:
        if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
            raise HTTPException(status_code=409, detail='Key already exists')
        raise HTTPException(status_code=502, detail='Database error')

# Example route that safely references a key without returning sensitive data
from fastapi import APIRouter, Header
router = APIRouter()

@router.get('/keys/verify')
def verify_key(key_id: str, user_id: str, db=Depends(get_db)):
    record = get_api_key_record(user_id=user_id, key_id=key_id)
    # Perform verification logic without returning raw_key
    return {'status': 'valid', 'last_used': record.last_used}

Operational practices matter as much as code: rotate keys regularly, use short-lived credentials where possible, and isolate DynamoDB tables with fine-grained IAM policies that enforce least privilege. middleBrick’s Pro plan supports continuous monitoring and CI/CD integration so changes to these routes and table policies can be validated before deployment. If you use the GitHub Action, you can fail builds when risk scores drop below your chosen threshold, preventing insecure patterns from reaching production.

Frequently Asked Questions

Can DynamoDB conditional writes prevent duplicate API key records in FastAPI?
Yes. Use a ConditionExpression such as attribute_not_exists(key_id) in PutItem to ensure duplicate keys are rejected, avoiding accidental overwrites that could weaken access control.
Does middleBrick check whether FastAPI responses inadvertently expose API keys stored in DynamoDB?
Yes. middleBrick scans test unauthenticated attack surfaces and include Property Authorization and Unsafe Consumption checks that can detect endpoints returning sensitive fields from DynamoDB. Findings include severity, remediation guidance, and mappings to frameworks like OWASP API Top 10.