Skip to content

Commit

Permalink
Add Middleware to Handle Duplicate Slashes in URLs (microsoft#51)
Browse files Browse the repository at this point in the history
This PR adds some FastAPI middleware to fix URLs that have duplicate
forward slashes.

For example, if the user puts the following in their .env file....

```dotenv
TEST_OPENAI_ENDPOINT=http://localhost:8000/
```

... then the tests will generate urls such as
`http://localhost:8000//openai/foo/bar/baz`. Notice the double forward
slash. This causes the simulator to generate errors.

This is an easy config mistake to make, so this middleware helps address
this problem by removing these duplicates.
  • Loading branch information
stuartleeks authored Sep 16, 2024
2 parents da8704e + a0f0d76 commit 9937f25
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/aoai-api-simulator/src/aoai_api_simulator/app_builder.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
import re
import traceback
from typing import Annotated
from fastapi import Depends, FastAPI, Request, Response, HTTPException

from aoai_api_simulator.auth import validate_api_key_header
from aoai_api_simulator.config_loader import get_config, set_config
Expand All @@ -11,12 +11,13 @@
from aoai_api_simulator.models import RequestContext
from aoai_api_simulator.record_replay.handler import RecordReplayHandler
from aoai_api_simulator.record_replay.persistence import YamlRecordingPersister

from fastapi import Depends, FastAPI, HTTPException, Request, Response

logger = logging.getLogger(__name__)

app = FastAPI()

repeated_quotes = re.compile(r"//+")

# pylint: disable-next=invalid-name
record_replay_handler = None
Expand Down Expand Up @@ -53,6 +54,17 @@ def _default_validate_api_key_header(request: Request):
validate_api_key_header(request=request, header_name="api-key", allowed_key_value=get_config().simulator_api_key)


# This middleware replaces double slashes in paths with a single slash
@app.middleware("http")
async def fix_double_slash_urls(request: Request, call_next):
if repeated_quotes.search(request.url.path):
new_url = request.url.replace(path=repeated_quotes.sub("/", request.url.path))
request.scope["path"] = new_url.path

response = await call_next(request)
return response


@app.get("/")
async def root():
return {"message": "👋 aoai-api-simulator is running"}
Expand Down

0 comments on commit 9937f25

Please sign in to comment.