Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/app/main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,37 @@
import json

import yaml
from fastapi import HTTPException, Request, Response, status
from starlette.datastructures import MutableHeaders
from starlette.middleware.base import RequestResponseEndpoint

from .api import router
from .core.config import settings
from .core.setup import create_application

app = create_application(router=router, settings=settings)


@app.middleware("http")
async def convert_yaml_to_json(
request: Request, call_next: RequestResponseEndpoint
) -> Response:
"""FastAPI middleware that will change all requests with a yaml content type to json."""
body = await request.body()
if request.headers.get("content-type") == "application/yaml":
try:
json_body = json.dumps(yaml.safe_load(body.decode("utf-8"))).encode()
except Exception as e:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Unable to parse provided YAML configuration.",
) from e

request._body = json_body
updated_headers = MutableHeaders(request._headers)
updated_headers["content-length"] = str(len(json_body))
updated_headers["content-type"] = "application/json"
request._headers = updated_headers
request.scope.update(headers=request.headers.raw)

return await call_next(request)
39 changes: 37 additions & 2 deletions tests/api/v1/test_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,27 @@
"vpn": False,
}


def test_template_range_valid_payload() -> None:
valid_range_payload_yaml: str = """provider: aws
vnc: false
vpc:
cidr: 192.168.0.0/16
name: example-vpc-1
subnets:
- cidr: 192.168.1.0/24
hosts:
- hostname: example-host-1
os: debian_11
size: 1
spec: tiny
tags:
- web
- linux
name: example-subnet-1
vpn: false
"""


def test_template_range_valid_payload_json() -> None:
"""Test that we get a 200 and a valid uuid.UUID4 in response."""
response = client.post(f"{BASE_ROUTE}/templates/range", json=valid_range_payload)
assert response.status_code == status.HTTP_200_OK
Expand All @@ -52,6 +71,22 @@ def test_template_range_valid_payload() -> None:
assert str(uuid_obj) == uuid_response


def test_template_range_valid_payload_yaml() -> None:
"""Test that we get a 200 and a valid uuid.UUID4 in response."""
response = client.post(
f"{BASE_ROUTE}/templates/range?yaml=true",
content=valid_range_payload_yaml,
headers={"content-type": "application/yaml"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["id"]

# Validate UUID returned
uuid_response = response.json()["id"]
uuid_obj = uuid.UUID(uuid_response, version=4)
assert str(uuid_obj) == uuid_response


def test_template_range_invalid_vpc_cidr() -> None:
"""Test for 422 response when VPC CIDR is invalid."""
# Use deepcopy to ensure all nested dicts are copied
Expand Down
Loading