HIGH missing tlsfastapidynamodb

Missing Tls in Fastapi with Dynamodb

Missing Tls in Fastapi with Dynamodb — how this specific combination creates or exposes the vulnerability

When a Fastapi service communicates with DynamoDB without enforcing Transport Layer Security (TLS), credentials, tokens, and potentially sensitive data can be exposed in transit. This scenario commonly arises in development or misconfigured staging environments where clients connect to DynamoDB using unencrypted HTTP endpoints. Because DynamoDB supports both HTTP and HTTPS, omitting TLS means requests and responses traverse the network unencrypted, making them susceptible to interception by passive observers on the same network path.

The risk is compounded in Fastapi applications that construct AWS SDK clients dynamically. If the endpoint is derived from configuration that defaults to HTTP, or if environment variables like AWS_ENDPOINT_URL are set to an unencrypted address, all DynamoDB operations—reads, writes, and queries—occur without encryption. An attacker who can observe or tamper with network traffic may capture database keys, IAM tokens embedded in headers, or sensitive application data. This violates multiple security controls in the OWASP API Top 10, particularly regarding data exposure and insufficient transport layer protections, and can map to compliance gaps in PCI-DSS and GDPR requirements for data confidentiality.

middleBrick scans detect Missing TLS by validating that all outbound connections to DynamoDB use HTTPS and by flagging unencrypted endpoint configurations during the Encryption and Data Exposure checks. The scanner cross-references the OpenAPI specification against runtime behavior, confirming whether TLS is enforced at the client level. Even when authentication is otherwise correctly implemented, a missing TLS configuration weakens the entire security posture, because the confidentiality and integrity guarantees of AWS signed requests are undermined.

Dynamodb-Specific Remediation in Fastapi — concrete code fixes

To remediate Missing TLS, configure the AWS SDK client to use HTTPS explicitly and ensure the endpoint URL begins with https://. Below is a secure Fastapi example that creates a DynamoDB resource using TLS and demonstrates a safe dependency pattern.

import os
from fastapi import Depends, Fastapi, HTTPException
import boto3
from botocore.exceptions import ClientError

app = Fastapi()

# Enforce HTTPS endpoint; avoid HTTP or protocol-relative URLs
def get_dynamodb_resource():
    endpoint = os.getenv("AWS_DYNAMODB_ENDPOINT", "https://dynamodb.us-east-1.amazonaws.com")
    if not endpoint.startswith("https://"):
        raise ValueError("DynamoDB endpoint must use TLS (https://)")
    try:
        return boto3.resource(
            "dynamodb",
            endpoint_url=endpoint,
            region_name=os.getenv("AWS_REGION", "us-east-1"),
        )
    except ClientError as e:
        raise RuntimeError(f"Failed to initialize DynamoDB client: {e}")

@app.get("/items/{item_id}")
def read_item(item_id: str, db=Depends(get_dynamodb_resource)):
    try:
        response = db.Table(os.getenv("DYNAMODB_TABLE")).get_item(Key={"id": item_id})
        item = response.get("Item")
        if item is None:
            raise HTTPException(status_code=404, detail="Item not found")
        return item
    except ClientError as e:
        raise HTTPException(status_code=500, detail=f"Database error: {e.response["Error"]["Code"]}")

In this example, the endpoint is validated to start with https://, preventing accidental HTTP usage. Additionally, avoid relying on instance metadata service defaults that may serve HTTP; prefer explicit HTTPS configuration. For local testing, use a mock endpoint only for development, and ensure it also supports TLS if exposed externally.

Integrate these checks into your CI/CD pipeline using the middleBrick GitHub Action to automatically fail builds when insecure configurations are detected. The dashboard can track encryption compliance over time, and the CLI allows on-demand verification with middlebrick scan <url>. For AI-assisted development, the MCP Server enables scanning directly from your coding assistant, surfacing TLS issues before deployment.

Related CWEs: encryption

CWE IDNameSeverity
CWE-319Cleartext Transmission of Sensitive Information HIGH
CWE-295Improper Certificate Validation HIGH
CWE-326Inadequate Encryption Strength HIGH
CWE-327Use of a Broken or Risky Cryptographic Algorithm HIGH
CWE-328Use of Weak Hash HIGH
CWE-330Use of Insufficiently Random Values HIGH
CWE-338Use of Cryptographically Weak PRNG MEDIUM
CWE-693Protection Mechanism Failure MEDIUM
CWE-757Selection of Less-Secure Algorithm During Negotiation HIGH
CWE-261Weak Encoding for Password HIGH

Frequently Asked Questions

What should I do if my DynamoDB endpoint is configured via AWS SDK defaults and I'm unsure whether TLS is enforced?
Explicitly set the endpoint URL to an HTTPS address in your client initialization and avoid relying on SDK defaults. Inspect environment variables and configuration files for entries like AWS_ENDPOINT_URL or endpoint_url, and ensure they begin with https://. Use tools like middleBrick to validate that runtime calls are made over TLS.
Can using HTTP for DynamoDB in a private VPC be considered safe?
No. Even within a private VPC, traffic can be intercepted through compromised instances or misconfigured routing. Encryption in transit protects against internal threats and ensures defense-in-depth. Always enforce HTTPS regardless of network placement to align with security best practices and compliance requirements.