Add support for aiohttp (#3409)

This commit is contained in:
daniel-teuchert-sonarsource 2025-02-03 12:04:32 +01:00 committed by GitHub
parent c1a6b0f5f5
commit fc7ed69d88
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,50 @@
== How to fix it in aiohttp
=== Code examples
include::../../common/fix/code-rationale.adoc[]
==== Noncompliant code example
[source,python,diff-id=31,diff-type=noncompliant]
----
from fastapi import FastAPI
import aiohttp
app = FastAPI()
@app.get('/example')
async def example(url: str):
async with aiohttp.request('GET', url) as response: # Noncompliant
return {"response": await response.text()}
----
==== Compliant solution
[source,python,diff-id=31,diff-type=compliant]
----
from fastapi import FastAPI
from fastapi.responses import JSONResponse
import aiohttp
from urllib.parse import urlparse
DOMAINS_ALLOWLIST = ['trusted1.example.com', 'trusted2.example.com'];
app = FastAPI()
@app.get('/example')
async def example(url: str):
if urlparse(url).hostname not in DOMAINS_ALLOWLIST:
return JSONResponse({"error": f"URL {url} is not whitelisted."}, 400)
async with aiohttp.request('GET', url.unicode_string()) as response:
return {"response": await response.text()}
----
=== How does this work?
include::../../common/fix/pre-approved-list.adoc[]
The compliant code example uses such an approach.
=== Pitfalls
include::../../common/pitfalls/starts-with.adoc[]

View File

@ -10,6 +10,8 @@ include::how-to-fix-it/python.adoc[]
include::how-to-fix-it/requests.adoc[]
include::how-to-fix-it/aiohttp.adoc[]
include::how-to-fix-it/httpx.adoc[]
== Resources