Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
120 changes: 120 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our
community include:

- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
- Focusing on what is best not just for us as individuals, but for the
community as a whole

Examples of unacceptable behavior include:

- The use of sexualized language or imagery, and sexual attention or advances
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address,
without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for
moderation decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official email address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
jacksonsr451@gmail.com. All complaints will be reviewed and investigated
promptly and fairly.

All community leaders are obligated to respect the privacy and security of the
reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series of
actions.

**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or permanent
ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within the
community.

## Attribution

This Code of Conduct is adapted from the Contributor Covenant, version 2.1,
available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html

Community Impact Guidelines were inspired by
https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Jackson Severino da Rocha

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
119 changes: 117 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,131 @@
# API Gateway (FastAPI)

Starter structure for a FastAPI service managed with Poetry.
API gateway service built with FastAPI and Poetry. It provides CORS, versioned
routes, JWT validation via an external auth service, rate limiting, and a
YAML-backed proxy router with regex matching and rewrites.

## Features

- Versioned API prefix (`/api/v1`).
- CORS configurable via environment variables.
- JWT validation + authorization delegated to `auth_service`.
- Rate limiting with `X-RateLimit-*` headers.
- Dynamic proxy routes stored in `routes.yaml`.
- Admin CRUD endpoints to manage routes.

## Requirements

- Python 3.11+
- Poetry

## Quick start

```bash
poetry install
poetry run uvicorn app.main:app --reload
cp env.example .env
poetry run fastapi run
```

The `fastapi` command is wrapped to load `.env` and use `APP_HOST`/`APP_PORT`
automatically. You can also run Uvicorn directly:

```bash
set -a; source .env; set +a
poetry run uvicorn app.main:app --reload --host $APP_HOST --port $APP_PORT
```

## Health

```
GET /api/v1/health
```

## Route management (admin)

All route management endpoints require the permission configured in
`ROUTES_ADMIN_PERMISSION` (default: `gateway:routes:manage`).

- `GET /api/v1/routes`
- `GET /api/v1/routes/{route_id}`
- `POST /api/v1/routes`
- `PUT /api/v1/routes/{route_id}`
- `DELETE /api/v1/routes/{route_id}`

## Proxy routing (YAML)

Routes are stored in the YAML file configured by `ROUTES_CONFIG_PATH`
(default: `routes.yaml`).

Example:

```yaml
routes:
- id: users
name: users-service
methods: ["GET"]
regex: "^/users/(\\d+)$"
upstream_base_url: "http://users:8000"
rewrite:
regex_uri: ["^/users/(\\d+)$", "/members/\\1"]
auth:
required: true
permission: "users:read"
roles: ["admin"]
priority: 10
enabled: true
```

Notes:
- Matching uses regex against the request path.
- Routes are sorted by `priority` (higher wins).
- `rewrite.regex_uri` uses Python `re.sub` replacement syntax.
- If any of `auth.required`, `auth.permission`, or `auth.roles` is set,
the request must have a valid `Authorization: Bearer <token>` header.

## Auth service integration

The gateway delegates token validation and permission checks to `auth_service`.
Configure the endpoints with:

- `AUTH_SERVICE_BASE_URL`
- `AUTH_SERVICE_VALIDATE_PATH`
- `AUTH_SERVICE_AUTHORIZE_PATH`
- `AUTH_SERVICE_TIMEOUT_SECONDS`

The `roles` check expects a `roles` claim (string or list) in the validation
response.

## Rate limiting

Rate limiting is in-memory per process. Configure with:

- `RATE_LIMIT_ENABLED`
- `RATE_LIMIT_REQUESTS`
- `RATE_LIMIT_WINDOW_SECONDS`
- `RATE_LIMIT_EXEMPT_PATHS`
- `RATE_LIMIT_KEY_HEADER` (defaults to `X-Forwarded-For`)

## Configuration

Key settings are read from `.env` (see `env.example`):

- App: `APP_NAME`, `APP_ENV`, `APP_HOST`, `APP_PORT`, `LOG_LEVEL`
- API: `API_PREFIX`
- CORS: `CORS_ALLOW_ORIGINS`, `CORS_ALLOW_METHODS`, `CORS_ALLOW_HEADERS`,
`CORS_ALLOW_CREDENTIALS`
- Auth: `AUTH_SERVICE_*`
- Rate limit: `RATE_LIMIT_*`
- Proxy: `ROUTES_CONFIG_PATH`, `PROXY_TIMEOUT_SECONDS`,
`ROUTES_ADMIN_PERMISSION`

## Tests

```bash
poetry run pytest
```

With coverage:

```bash
poetry run pytest --cov=app --cov-report=term-missing --cov-fail-under=85
```
29 changes: 29 additions & 0 deletions TASKS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Roadmap - API Gateway

Marque as etapas conforme for concluindo. Use este arquivo como checklist.

- [x] Etapa 1: health/config/logging/testes basicos
- [x] Etapa 2: CORS e versionamento de rotas + testes
- [x] Etapa 3: Autenticacao JWT + testes
- [x] Etapa 4: Rate limiting + testes
- [x] Etapa 5: Roteamento/proxy para microservicos + testes
- [ ] Etapa 6: Padronizacao de respostas/erros + testes
- [ ] Etapa 7: OpenAPI centralizado/ajustes de docs + testes

Detalhamento (opcional):
- [x] Etapa 1.1: Health check (/health)
- [x] Etapa 1.2: Configuracao e logging base
- [x] Etapa 1.3: Testes basicos do health check
- [x] Etapa 2.1: Configurar CORS
- [x] Etapa 2.2: Versionamento de rotas (ex: /api/v1)
- [x] Etapa 2.3: Testes de CORS/versionamento
- [x] Etapa 3.1: Middleware/dependency de JWT
- [x] Etapa 3.2: Testes de autenticacao
- [x] Etapa 4.1: Rate limiting
- [x] Etapa 4.2: Testes de rate limiting
- [x] Etapa 5.1: Proxy/roteamento para servicos
- [x] Etapa 5.2: Testes de roteamento
- [ ] Etapa 6.1: Normalizacao de respostas/erros
- [ ] Etapa 6.2: Testes de erro padronizado
- [ ] Etapa 7.1: Ajustes de OpenAPI centralizado
- [ ] Etapa 7.2: Testes/validacao de docs
72 changes: 72 additions & 0 deletions app/api/deps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from __future__ import annotations

from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

from app.services.auth_service import (
AuthContext,
AuthServiceClient,
AuthServiceError,
get_auth_service_client,
)

_bearer_scheme = HTTPBearer(auto_error=False)


def get_bearer_token(
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer_scheme),
) -> str:
if (
credentials is None
or credentials.scheme.lower() != "bearer"
or not credentials.credentials
):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="not_authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
return credentials.credentials


def require_authentication(
token: str = Depends(get_bearer_token),
client: AuthServiceClient = Depends(get_auth_service_client),
) -> AuthContext:
try:
claims = client.validate_token(token)
except AuthServiceError as exc:
headers = (
{"WWW-Authenticate": "Bearer"}
if exc.status_code == status.HTTP_401_UNAUTHORIZED
else None
)
raise HTTPException(
status_code=exc.status_code,
detail=exc.detail,
headers=headers,
) from exc
return AuthContext(token=token, claims=claims)


def require_authorization(permission: str):
def dependency(
context: AuthContext = Depends(require_authentication),
client: AuthServiceClient = Depends(get_auth_service_client),
) -> AuthContext:
try:
client.authorize(context.token, permission)
except AuthServiceError as exc:
headers = (
{"WWW-Authenticate": "Bearer"}
if exc.status_code == status.HTTP_401_UNAUTHORIZED
else None
)
raise HTTPException(
status_code=exc.status_code,
detail=exc.detail,
headers=headers,
) from exc
return context

return dependency
4 changes: 3 additions & 1 deletion app/api/router.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from fastapi import APIRouter

from app.api.routes import health
from app.api.routes import gateway, health, proxy

api_router = APIRouter()
api_router.include_router(health.router, tags=["health"])
api_router.include_router(gateway.router, tags=["gateway"])
api_router.include_router(proxy.router, tags=["proxy"], include_in_schema=False)
Loading