Skip to content

[NEW QUERY] Python: py/cors-csp-security-headers for permissive CORS and weak CSP (CWE-942, CWE-693) - #332

Draft
felickz with Copilot wants to merge 4 commits into
mainfrom
copilot/query-create-cors-csp-security-headers
Draft

felickz with Copilot wants to merge 4 commits into
mainfrom
copilot/query-create-cors-csp-security-headers

Conversation

Copilot AI commented Oct 31, 2026 •

Copy link
Copy Markdown

📝 Query Information

  • Language: python
  • Query ID: py/cors-csp-security-headers
  • Category: security
  • Severity: warning (@security-severity 5.3, @precision medium, so it targets Community Packs)
  • CWE/CVE (if applicable): CWE-942, CWE-693

🎯 Description

What This Query Detects

The default CodeQL setup missed four AI Scan findings in public synthetic Python apps. The cause was a combination of a missing query and missing library modeling:

  • No query checks CORS or CSP header values. Http::Server::ResponseHeaderWrite already models header writes, but nothing inspects the values.
  • The Flask after_request / after_app_request response parameter is not modeled in python-all 7.2.8. Writes such as response.headers[...] = v inside these hooks are not ResponseHeaderWrites, so even a header-value query would miss both Flask findings.
  • The experimental py/cors-misconfiguration-with-credentials query is narrow. It only checks allow_origins containing *, ignores allow_origin_regex, and is not in the default suite.

This PR adds languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql. It reports the following.

Access-Control-Allow-Origin header writes

  • Reports * or null values.
  • Each value gets its own message.

Content-Security-Policy header writes that allow inline scripts

  • Reports 'unsafe-inline' in script-src, script-src-elem or script-src-attr.
  • Also reports 'unsafe-inline' in default-src when no script-src directive is present.
  • Does not report when the directive also has a well-formed 'nonce-…' or 'sha256|384|512-…' source, because browsers then ignore 'unsafe-inline'.
  • Evaluates only the first occurrence of each directive.
  • For comma-separated policy lists, reports only when every policy allows inline scripts.

Starlette/FastAPI CORSMiddleware with allow_credentials=True

Starlette matches origins with re.fullmatch. The query reports when either of the following holds:

  • allow_origin_regex is permissive. That means one of:

    • a catch-all top-level alternative, such as .*, https://.*, ^https?://[^/]+$ or …|.*;
    • an unescaped domain dot, such as restaurant.com;
    • an unbounded wildcard directly before the domain, such as .*example\.com;
    • an unbounded wildcard directly after the domain, such as example\.com.*.

    The checks ignore the contents of character classes.

  • allow_origins contains "*".

Library gap fix (local to the query)

  • The new FlaskAfterRequestResponseHeaders class extends Werkzeug::Headers::InstanceSource to cover <param0>.headers in functions decorated with @<Flask app or Blueprint>.after_request / .after_app_request.
  • This also works when the app comes from a create_app() factory in another module, which is the pattern in the affected repos.

Example Vulnerable Code

@app.after_request
def add_csp_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'                                # flagged
    response.headers['Content-Security-Policy'] = "script-src 'self' 'unsafe-inline'"    # flagged
    return response

app.add_middleware(
    CORSMiddleware,
    allow_origin_regex=".*.(restaurant.com|deliveryservice.com)",  # flagged: matches https://evilrestaurant.com
    allow_credentials=True,
)

Example Safe Code

response.headers['Access-Control-Allow-Origin'] = 'https://trusted.example.com'
response.headers['Content-Security-Policy'] = "script-src 'self' 'nonce-r4nd0m' 'unsafe-inline'"
response.headers['Content-Security-Policy'] = "default-src 'self'; style-src 'self' 'unsafe-inline'"
response.headers['Content-Security-Policy'] = "script-src 'self'; script-src 'unsafe-inline'"  # first directive wins

app.add_middleware(
    CORSMiddleware,
    allow_origin_regex=r"https://([a-z0-9-]+\.)?(restaurant\.com|deliveryservice\.com)",
    allow_credentials=True,
)

🧪 Testing

Tests live in languages/python/custom/test/CorsCspSecurityHeaders/ and use inline expectations (# $ Alert):

File What it covers
flask_app.py after_request, Response, headers.set, bulk make_response headers, malformed nonce, multi-policy and duplicate-directive negatives
run.py + app_factory.py the create_app() factory and Blueprint.after_app_request, plus an undecorated function as a negative
django_views.py response[...] and response.headers[...]
fastapi_app.py each permissive-regex shape, a credentials=False negative, and escaped, alternation, port and character-class negatives
  • Positive test cases included
  • Negative test cases included
  • Edge cases covered
  • All tests pass

📋 Checklist

  • Query compiles without errors
  • Documentation complete (.md and .qhelp): .md only, no .qhelp
  • Metadata properly set (@name, @id, @kind, etc.)
  • Tests validate query behavior
  • No false positives in test cases

Reviewer notes

  • Possible noise: every Access-Control-Allow-Origin: * is reported, as the issue requests, but that value is legitimate for intentionally public APIs. This is why precision is set to medium.
  • Heuristic regex checks: origin-regex detection works on the regex source text and does not parse it.
  • Not covered: flask-cors (CORS(app, supports_credentials=True)) and django-cors-headers settings.

🔗 References


Note: This query was developed using Test-Driven Development methodology.

Copilot AI and others added 2 commits October 31, 2026 05:34
Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
…sp-security-headers

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Copilot AI changed the title [WIP] Add new query for CORS, CSP and security headers [NEW QUERY] Python: py/cors-csp-security-headers for permissive CORS and weak CSP (CWE-942, CWE-693) Oct 31, 2026
Copilot AI requested a review from felickz October 31, 2026 05:39
@felickz
felickz requested a balanced review from Copilot November 2, 2026 18:37

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

CSP analysis mishandles directive precedence, combined policies, and 'strict-dynamic', while CORS regex checks misinterpret grouping, causing false positives and missed insecure configurations.

5 open issues
What changed in this PR

Adds the Python security query py/cors-csp-security-headers to address the CORS and CSP detection gaps described in #282, targeting Community Packs with medium-precision findings.

Changes:

  • Detects permissive CORS response headers, credentialed middleware configurations, and CSP policies allowing unsafe inline scripts.
  • Adds query-local modeling for response headers in Flask after-request hooks.
  • Adds framework-specific fixtures, expected results, and query documentation.
File Description
languages/​python/​custom/​test/​CorsCspSecurityHeaders/​run.py Tests factory-created Flask apps and Blueprint hooks.
languages/​python/​custom/​test/​CorsCspSecurityHeaders/​flask_app.py Tests Flask header writes and CSP edge cases.
languages/​python/​custom/​test/​CorsCspSecurityHeaders/​fastapi_app.py Tests permissive and restricted CORS middleware configurations.
languages/​python/​custom/​test/​CorsCspSecurityHeaders/​django_views.py Tests Django response-header detection.
languages/​python/​custom/​test/​CorsCspSecurityHeaders/​CorsCspSecurityHeaders.qlref Connects the query to inline-expectation tests.
languages/​python/​custom/​test/​CorsCspSecurityHeaders/​CorsCspSecurityHeaders.expected Records expected query results.
languages/​python/​custom/​test/​CorsCspSecurityHeaders/​app_factory.py Supplies the cross-module Flask factory fixture.
languages/​python/​custom/​src/​CorsCspSecurityHeaders/​CorsCspSecurityHeaders.ql Implements detection logic and Flask hook modeling.
languages/​python/​custom/​src/​CorsCspSecurityHeaders/​CorsCspSecurityHeaders.md Documents coverage, remediation, and examples.

Review effort: Balanced

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Query Create]: CWE-693, CWE-942 MEDIUM - Python: new query for CORS, CSP and security headers

3 participants