HIGH open redirectflaskmongodb

Open Redirect in Flask with Mongodb

Open Redirect in Flask with Mongodb — how this specific combination creates or exposes the vulnerability

An open redirect in a Flask application that uses MongoDB can occur when a route accepts a user-supplied URL or location parameter and then redirects the client without strict validation. If the application stores or references redirect targets in MongoDB—such as storing allowed callback URLs for OAuth integrations or storing user-specific redirect preferences—improper validation of those stored values can lead to open redirects. For example, an attacker might register a malicious callback URL in a MongoDB document, or manipulate a redirect target parameter to point to an external site, and if the Flask route trusts the stored value, the redirect will send users to an arbitrary destination.

Consider a Flask route that retrieves a redirect URL from a MongoDB collection based on a user identifier or an application setting:

from flask import Flask, request, redirect
from pymongo import MongoClient

app = Flask(__name__)
client = MongoClient('mongodb://localhost:27017')
db = client['mydb']
collection = db['redirects']

@app.route('/go')
def go():
    key = request.args.get('key')
    doc = collection.find_one({'key': key})
    if doc and 'url' in doc:
        return redirect(doc['url'])
    return 'Not found', 404

If the url field in MongoDB contains an external address and the route does not validate it, users visiting /go?key=somekey can be redirected without warning. Even if the application intends to store only internal paths, an attacker who can write to MongoDB—via insecure direct object references (IDOR), insecure API endpoints, or compromised admin interfaces—can inject malicious URLs. The open redirect becomes a vector for phishing or for bypassing referrer policies, because users see a trusted domain in the browser while being sent to an attacker-controlled site.

Another scenario involves dynamic configuration stored in MongoDB, such as tenant-specific redirect URIs. If these values are not validated against an allowlist of known, safe domains, an attacker who can modify configuration documents can redirect all users of that tenant. Because the redirect logic lives in Flask and the data lives in MongoDB, the risk arises from treating stored data as inherently safe. This is especially dangerous when combined with features like OAuth where a registered callback URL is stored in MongoDB and later used to redirect the user back to the application.

Mongodb-Specific Remediation in Flask — concrete code fixes

To mitigate open redirects when using MongoDB with Flask, validate and constrain redirect targets both at the application logic level and at the data layer. Prefer storing only paths relative to your application and resolve them internally rather than storing full external URLs. When external URLs must be stored, enforce a strict allowlist of domains and normalize inputs before comparison.

Use a validation function that checks the parsed URL’s hostname against a set of permitted domains and rejects non‑HTTP(S) schemes. Here is a concrete example that demonstrates a safer pattern:

from flask import Flask, request, redirect, abort
from pymongo import MongoClient
from urllib.parse import urlparse

app = Flask(__name__)
client = MongoClient('mongodb://localhost:27017')
db = client['mydb']
collection = db['redirects']

ALLOWED_DOMAINS = {'app.example.com', 'dashboard.example.com'}

def is_safe_url(url):
    parsed = urlparse(url)
    if parsed.scheme not in ('http', 'https'):
        return False
    if parsed.hostname not in ALLOWED_DOMAINS:
        return False
    return True

@app.route('/go')
def go():
    key = request.args.get('key')
    doc = collection.find_one({'key': key})
    if doc and 'url' in doc:
        url = doc['url']
        if is_safe_url(url):
            return redirect(url)
        abort(400, 'Redirect target not allowed')
    return 'Not found', 404

If your application must support arbitrary external destinations—for example, a configurable integration—do not rely on data from MongoDB without explicit consent at request time. Instead, require that the intended path be supplied as a parameter that is mapped to a stored, validated destination, or present a UI where administrators explicitly approve external URLs and the approval is recorded in MongoDB with metadata. For OAuth callback flows, store only the path portion of the redirect URI in MongoDB and construct the final URL server‑side, ensuring that the user is always returned to a known location within your application.

Additionally, consider schema validation in MongoDB to restrict the format of URL fields. Using MongoDB schema validation rules can prevent accidental or malicious insertion of malformed or external URLs into documents that are used for redirects:

db.createCollection('redirects', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['key', 'url'],
      properties: {
        key: { bsonType: 'string' },
        url: {
          bsonType: 'string',
          pattern: '^(https?):\/\\/app\\.example\\.com\\/*.*$'
        }
      }
    }
  }
})

These measures—strict allowlisting, runtime validation, restricted schemas, and avoiding storage of full external redirect targets—reduce the risk that data in MongoDB can be leveraged for open redirects in Flask.

Frequently Asked Questions

Can an open redirect in Flask with MongoDB enable phishing even if the app never stores full external URLs?
Yes. If an attacker can inject malicious URLs into MongoDB via IDOR or compromised admin functions, or if the application uses unsafe inputs to construct redirect targets at runtime, users can be redirected to phishing sites even when the app intends to use only internal paths.
How does middleBrick help detect open redirect risks involving MongoDB and Flask?
middleBrick scans the unauthenticated attack surface of your API endpoints, including Flask routes that interact with MongoDB. It checks input validation, authentication and authorization controls, and response behaviors, providing findings with severity and remediation guidance mapped to frameworks such as OWASP API Top 10.