Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PTFE-672: api authentication #322

Merged
merged 19 commits into from
Aug 11, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
42 changes: 40 additions & 2 deletions runner_manager/main.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,39 @@
import logging

from fastapi import Depends, FastAPI, HTTPException, Response, Security, status
from fastapi.security import APIKeyHeader, APIKeyQuery
from fastapi import FastAPI, Response

from runner_manager.dependencies import get_queue
from runner_manager.dependencies import get_queue, get_settings
Abubakarr99 marked this conversation as resolved.
Show resolved Hide resolved
from runner_manager.jobs.startup import startup

log = logging.getLogger(__name__)

app = FastAPI()
api_key_query = APIKeyQuery(name="api-key", auto_error=False)
api_key_header = APIKeyHeader(name="x-api-key", auto_error=False)

Abubakarr99 marked this conversation as resolved.
Show resolved Hide resolved
def get_api_key(
api_key_query: str = Security(api_key_query),
api_key_header: str = Security(api_key_header),
) -> str:
settings = get_settings()
Abubakarr99 marked this conversation as resolved.
Show resolved Hide resolved
if not settings.api_key:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="API Key not configured in settings",
)
Abubakarr99 marked this conversation as resolved.
Show resolved Hide resolved
api_key = api_key_query or api_key_header
if not api_key:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="API Key required for this endpoint",
)
if api_key != settings.api_key.get_secret_value():
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid API Key",
)
return api_key
Abubakarr99 marked this conversation as resolved.
Show resolved Hide resolved


@app.on_event("startup")
Expand All @@ -21,3 +47,15 @@ def startup_event():
@app.get("/_health")
def health():
return Response(status_code=200)


@app.get("/public")
def public():
"""A public endpoint that does not require any authentication."""
return "Public Endpoint"


@app.get("/private")
def private(api_key: str = Depends(get_api_key)):
"""A private endpoint that requires a valid API key to be provided."""
return f"Private Endpoint. API Key: {api_key}"
3 changes: 2 additions & 1 deletion runner_manager/models/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from typing import Any, Dict, Optional

import yaml
from pydantic import AnyHttpUrl, BaseSettings, RedisDsn
from pydantic import AnyHttpUrl, BaseSettings, RedisDsn, SecretStr


def yaml_config_settings_source(settings: BaseSettings) -> Dict[str, Any]:
Expand All @@ -24,6 +24,7 @@ class Settings(BaseSettings):
name: str = "runner-manager"
redis_om_url: Optional[RedisDsn] = None
github_base_url: Optional[AnyHttpUrl] = None
api_key: Optional[SecretStr] = None

class Config:
config: ConfigFile = ConfigFile()
Expand Down
19 changes: 19 additions & 0 deletions tests/api/auth_tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import os


def test_public_endpoint(client):
response = client.get("/public")

assert response.status_code == 200


def test_private_endpoint_without_api_key(client):
response = client.get("/private")
assert response.status_code == 401


def test_private_endpoint_with_valid_api_key(client):
os.environ["API_KEY"] = "secret"
headers = {"x-api-key": "secret"}
response = client.get("/private", headers=headers)
assert response.status_code == 200
Loading