Skip to content

Commit

Permalink
chore: add pre-commit github action
Browse files Browse the repository at this point in the history
  • Loading branch information
alukach committed Nov 30, 2024
1 parent 0c5cf4e commit 260b098
Show file tree
Hide file tree
Showing 11 changed files with 67 additions and 18 deletions.
28 changes: 28 additions & 0 deletions .github/workflows/cicd.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
on:
- push

jobs:
lint:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- name: Restore cached virtualenv
uses: actions/cache/restore@v4
with:
key: venv-${{ runner.os }}-${{ hashFiles('uv.lock') }}
path: .venv

- name: Install uv
uses: astral-sh/setup-uv@v4

- name: Run pre-commit
run: uv run pre-commit run --all-files

- name: Saved cached virtualenv
uses: actions/cache/save@v4
if: always()
with:
key: venv-${{ runner.os }}-${{ hashFiles('uv.lock') }}
path: .venv
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/abravalheri/validate-pyproject
rev: v0.12.1
rev: v0.23
hooks:
- id: validate-pyproject

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ known_first_party = ["stac_auth_proxy"]
profile = "black"

[tool.ruff]
ignore = ["E501"]
ignore = ["E501", "D203", "D212"]
select = ["D", "E", "F"]

[build-system]
Expand Down
3 changes: 2 additions & 1 deletion src/stac_auth_proxy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""STAC Auth Proxy package.
"""
STAC Auth Proxy package.
This package contains the components for the STAC authentication and proxying system.
It includes FastAPI routes for handling authentication, authorization, and interaction
Expand Down
3 changes: 2 additions & 1 deletion src/stac_auth_proxy/__main__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Main module for the STAC Auth Proxy."""

import uvicorn
from uvicorn.config import LOGGING_CONFIG


LOGGING_CONFIG["loggers"][__package__] = {
"level": "DEBUG",
"handlers": ["default"],
Expand Down
8 changes: 5 additions & 3 deletions src/stac_auth_proxy/app.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""STAC Auth Proxy API.
"""
STAC Auth Proxy API.
This module defines the FastAPI application for the STAC Auth Proxy, which handles
authentication, authorization, and proxying of requests to some internal STAC API.
Expand All @@ -9,13 +10,14 @@
from fastapi import Depends, FastAPI
from fastapi.security import OpenIdConnect

from .proxy import ReverseProxy
from .config import Settings
from .middleware import AddProcessTimeHeaderMiddleware
from .handlers import OpenApiSpecHandler
from .middleware import AddProcessTimeHeaderMiddleware
from .proxy import ReverseProxy


def create_app(settings: Optional[Settings] = None) -> FastAPI:
"""FastAPI Application Factory."""
settings = settings or Settings()

app = FastAPI(openapi_url=None)
Expand Down
8 changes: 7 additions & 1 deletion src/stac_auth_proxy/config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Configuration for the STAC Auth Proxy."""

from typing import Optional, TypeAlias

from pydantic.networks import HttpUrl
Expand All @@ -7,7 +9,9 @@


class Settings(BaseSettings):
upstream_url: HttpUrl = "https://earth-search.aws.element84.com/v1"
"""Configuration settings for the STAC Auth Proxy."""

upstream_url: HttpUrl = HttpUrl(url="https://earth-search.aws.element84.com/v1")
oidc_discovery_url: HttpUrl

# Endpoints
Expand All @@ -26,4 +30,6 @@ class Settings(BaseSettings):
openapi_spec_endpoint: Optional[str] = None

class Config:
"""Pydantic configuration."""

env_prefix = "STAC_AUTH_PROXY_"
11 changes: 6 additions & 5 deletions src/stac_auth_proxy/handlers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from dataclasses import dataclass
"""Custom request handlers."""

import logging
from dataclasses import dataclass

from fastapi import Request, Response
from fastapi.routing import APIRoute
Expand All @@ -12,15 +14,14 @@

@dataclass
class OpenApiSpecHandler:
"""Handler for OpenAPI spec requests."""

proxy: ReverseProxy
oidc_config_url: str
auth_scheme_name: str = "oidcAuth"

async def dispatch(self, req: Request, res: Response):
"""
Proxy the OpenAPI spec from the upstream STAC API, updating it with OIDC security
requirements.
"""
"""Proxy the OpenAPI spec from the upstream STAC API, updating it with OIDC security requirements."""
oidc_spec_response = await self.proxy.proxy_request(req)
openapi_spec = oidc_spec_response.json()

Expand Down
5 changes: 5 additions & 0 deletions src/stac_auth_proxy/middleware.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
"""Custom middleware."""

import time

from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware


class AddProcessTimeHeaderMiddleware(BaseHTTPMiddleware):
"""Middleware to add a header with the process time to the response."""

async def dispatch(self, request: Request, call_next) -> Response:
"""Add a header with the process time to the response."""
start_time = time.perf_counter()
response = await call_next(request)
process_time = time.perf_counter() - start_time
Expand Down
9 changes: 7 additions & 2 deletions src/stac_auth_proxy/proxy.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,34 @@
"""Tooling to manage the reverse proxying of requests to an upstream STAC API."""

import logging
import time
from dataclasses import dataclass

import httpx
from fastapi import Request
from starlette.background import BackgroundTask
from starlette.datastructures import MutableHeaders
from starlette.responses import StreamingResponse
from starlette.background import BackgroundTask


logger = logging.getLogger(__name__)


@dataclass
class ReverseProxy:
"""Reverse proxy functionality."""

upstream: str
client: httpx.AsyncClient = None

def __post_init__(self):
"""Initialize the HTTP client."""
self.client = self.client or httpx.AsyncClient(
base_url=self.upstream,
timeout=httpx.Timeout(timeout=15.0),
)

async def proxy_request(self, request: Request, *, stream=False) -> httpx.Response:
"""Proxy a request to the upstream STAC API."""
headers = MutableHeaders(request.headers)

# https://github.com/fastapi/fastapi/discussions/7382#discussioncomment-5136466
Expand Down
6 changes: 3 additions & 3 deletions src/stac_auth_proxy/utils.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""Utility functions."""

from httpx import Headers


def safe_headers(headers: Headers) -> dict[str, str]:
"""
Scrub headers that should not be proxied to the client.
"""
"""Scrub headers that should not be proxied to the client."""
excluded_headers = [
"content-length",
"content-encoding",
Expand Down

0 comments on commit 260b098

Please sign in to comment.