From 37bb98af78d771701947c179fd20e7e0af09866c Mon Sep 17 00:00:00 2001 From: bnbong Date: Tue, 1 Dec 2026 17:55:56 +0900 Subject: [PATCH 1/4] [CHORE] bump package version var --- src/fastapi_fastkit/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fastapi_fastkit/__init__.py b/src/fastapi_fastkit/__init__.py index 0f228f2..5197c5f 100644 --- a/src/fastapi_fastkit/__init__.py +++ b/src/fastapi_fastkit/__init__.py @@ -1 +1 @@ -__version__ = "1.5.1" +__version__ = "1.5.2" From 982d345e5bdda2151815c388183a0413efd727de Mon Sep 17 00:00:00 2001 From: bnbong Date: Wed, 2 Dec 2026 08:46:41 +0900 Subject: [PATCH 2/4] [FEAT, TEMPLATE, DOCS] add fastkit doctor, unify generated API conventions - add `fastkit doctor` with --fix, --dry-run and --format json - addroute: --dry-run/--diff/--entity, full CRUD for both layouts - one HTTP contract for all templates, init options and addroute output - pagination built in; JWT and FastAPI-Users options implemented - session invalidation, stricter SECRET_KEY rule outside development - startdemo/addroute exit 1 on failure - bump version to 2.0.0 (unreleased; base of the 2.0.0 work) Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 75 + CONTRIBUTING.md | 21 +- README.md | 31 +- .../contributing/template-creation-guide.md | 135 +- docs/en/index.md | 92 +- docs/en/reference/preset-feature-matrix.md | 108 +- .../reference/template-quality-assurance.md | 19 + docs/en/reference/translation-status.md | 11 +- docs/en/tutorial/async-crud-api.md | 340 +-- docs/en/tutorial/auth-jwt.md | 34 +- docs/en/tutorial/basic-api-server.md | 226 +- docs/en/tutorial/custom-response-handling.md | 30 +- docs/en/tutorial/database-integration.md | 56 +- docs/en/tutorial/docker-deployment.md | 23 + docs/en/tutorial/domain-starter.md | 171 +- docs/en/tutorial/first-project.md | 52 +- docs/en/tutorial/getting-started.md | 131 +- docs/en/tutorial/llm-agent.md | 37 +- docs/en/tutorial/mcp-integration.md | 30 +- docs/en/tutorial/sqlmodel.md | 88 +- docs/en/user-guide/adding-routes.md | 616 ++--- docs/en/user-guide/choosing-a-starter.md | 2 +- docs/en/user-guide/cli-reference.md | 174 +- docs/en/user-guide/creating-projects.md | 45 +- docs/en/user-guide/quick-start.md | 27 +- docs/en/user-guide/using-templates.md | 104 +- src/fastapi_fastkit/__init__.py | 2 +- .../backend/doctor/__init__.py | 49 + .../backend/doctor/checks_api.py | 296 +++ .../backend/doctor/checks_code.py | 343 +++ .../backend/doctor/checks_files.py | 575 +++++ .../backend/doctor/checks_secrets.py | 466 ++++ src/fastapi_fastkit/backend/doctor/command.py | 214 ++ src/fastapi_fastkit/backend/doctor/context.py | 612 +++++ src/fastapi_fastkit/backend/doctor/envfile.py | 279 +++ src/fastapi_fastkit/backend/doctor/known.py | 88 + src/fastapi_fastkit/backend/doctor/model.py | 162 ++ src/fastapi_fastkit/backend/doctor/pyast.py | 68 + src/fastapi_fastkit/backend/doctor/render.py | 348 +++ src/fastapi_fastkit/backend/doctor/runner.py | 366 +++ .../backend/interactive/config_builder.py | 5 +- .../backend/interactive/prompts.py | 21 +- .../backend/interactive/validators.py | 21 +- src/fastapi_fastkit/backend/main.py | 538 +++-- .../project_builder/config_generator.py | 2000 +++++++++++++++-- .../backend/project_builder/config_schema.py | 37 + .../project_builder/dependency_collector.py | 23 + .../backend/project_builder/preset_layout.py | 723 +++--- .../backend/route_generators.py | 856 ++++++- src/fastapi_fastkit/backend/route_plan.py | 309 +++ src/fastapi_fastkit/backend/route_wiring.py | 144 +- src/fastapi_fastkit/backend/scaffolder.py | 32 +- src/fastapi_fastkit/cli.py | 349 ++- src/fastapi_fastkit/core/settings.py | 44 +- .../fastapi-async-crud/.env.example-tpl | 10 + .../fastapi-async-crud/README.md-tpl | 68 +- .../fastapi-async-crud/pyproject.toml-tpl | 4 +- .../fastapi-async-crud/requirements.txt-tpl | 5 +- .../fastapi-async-crud/setup.cfg-tpl | 14 - .../fastapi-async-crud/src/api/deps.py-tpl | 16 + .../src/api/routes/items.py-tpl | 101 +- .../fastapi-async-crud/src/core/config.py-tpl | 131 +- .../src/core/pagination.py-tpl | 37 + .../src/core/responses.py-tpl | 40 + .../fastapi-async-crud/src/crud/items.py-tpl | 136 +- .../fastapi-async-crud/src/main.py-tpl | 13 +- .../src/schemas/items.py-tpl | 38 +- .../fastapi-async-crud/tests/conftest.py-tpl | 44 +- .../tests/test_config.py-tpl | 194 ++ .../tests/test_item_store.py-tpl | 85 + .../tests/test_items.py-tpl | 193 +- .../fastapi-async-crud/tests/test_main.py-tpl | 59 + .../fastapi-auth-jwt/.dockerignore-tpl | 47 + .../fastapi-auth-jwt/.env.example-tpl | 17 +- .../fastapi-auth-jwt/Dockerfile-tpl | 29 +- .../fastapi-auth-jwt/README.md-tpl | 124 +- .../fastapi-auth-jwt/alembic.ini-tpl | 2 +- .../fastapi-auth-jwt/pyproject.toml-tpl | 1 + .../src/app/alembic/env.py-tpl | 23 +- .../versions/0001_initial_auth_schema.py-tpl | 8 +- .../0002_timezone_aware_timestamps.py-tpl | 57 + .../fastapi-auth-jwt/src/app/api/deps.py-tpl | 37 +- .../src/app/api/health.py-tpl | 74 +- .../src/app/api/router.py-tpl | 9 +- .../src/app/core/config.py-tpl | 90 +- .../src/app/core/pagination.py-tpl | 37 + .../src/app/core/rate_limit.py-tpl | 113 + .../src/app/core/responses.py-tpl | 40 + .../src/app/core/security.py-tpl | 28 +- .../src/app/db/session.py-tpl | 35 +- .../fastapi-auth-jwt/src/app/db/types.py-tpl | 48 + .../src/app/domains/auth/models.py-tpl | 7 +- .../src/app/domains/auth/repository.py-tpl | 7 +- .../src/app/domains/auth/router.py-tpl | 106 +- .../src/app/domains/auth/schemas.py-tpl | 13 + .../src/app/domains/auth/service.py-tpl | 17 +- .../src/app/domains/users/models.py-tpl | 5 +- .../src/app/domains/users/repository.py-tpl | 26 +- .../src/app/domains/users/router.py-tpl | 82 +- .../src/app/domains/users/schemas.py-tpl | 16 +- .../src/app/domains/users/service.py-tpl | 42 +- .../fastapi-auth-jwt/src/app/main.py-tpl | 7 +- .../fastapi-auth-jwt/tests/conftest.py-tpl | 10 + .../fastapi-auth-jwt/tests/test_auth.py-tpl | 62 +- .../fastapi-auth-jwt/tests/test_config.py-tpl | 215 +- .../fastapi-auth-jwt/tests/test_health.py-tpl | 171 +- .../tests/test_login_hardening.py-tpl | 223 ++ .../tests/test_refresh_rotation.py-tpl | 12 +- .../tests/test_timestamps.py-tpl | 127 ++ .../fastapi-auth-jwt/tests/test_users.py-tpl | 123 +- .../fastapi-custom-response/.env.example-tpl | 10 + .../fastapi-custom-response/README.md-tpl | 102 +- .../pyproject.toml-tpl | 4 +- .../requirements.txt-tpl | 5 +- .../fastapi-custom-response/setup.cfg-tpl | 12 - .../src/api/api.py-tpl | 2 +- .../src/api/deps.py-tpl | 16 + .../src/api/routes/items.py-tpl | 236 +- .../src/core/config.py-tpl | 131 +- .../src/core/pagination.py-tpl | 37 + .../src/crud/items.py-tpl | 136 +- .../src/helper/exceptions.py-tpl | 161 +- .../src/helper/pagination.py-tpl | 72 - .../src/helper/responses.py-tpl | 22 + .../fastapi-custom-response/src/main.py-tpl | 31 +- .../src/schemas/base.py-tpl | 103 +- .../src/schemas/items.py-tpl | 51 +- .../src/utils/documents.py-tpl | 3 +- .../tests/conftest.py-tpl | 51 +- .../tests/test_config.py-tpl | 194 ++ .../tests/test_item_store.py-tpl | 85 + .../tests/test_items.py-tpl | 226 +- .../tests/test_main.py-tpl | 68 + .../fastapi-default/.env.example-tpl | 10 + .../fastapi-default/README.md-tpl | 64 +- .../fastapi-default/pyproject.toml-tpl | 8 +- .../fastapi-default/requirements.txt-tpl | 5 +- .../fastapi-default/setup.cfg-tpl | 13 - .../fastapi-default/src/api/deps.py-tpl | 16 + .../src/api/routes/items.py-tpl | 97 +- .../fastapi-default/src/core/config.py-tpl | 136 +- .../src/core/pagination.py-tpl | 37 + .../fastapi-default/src/core/responses.py-tpl | 40 + .../fastapi-default/src/crud/items.py-tpl | 127 +- .../fastapi-default/src/main.py-tpl | 13 +- .../fastapi-default/src/schemas/items.py-tpl | 38 +- .../fastapi-default/tests/conftest.py-tpl | 33 +- .../fastapi-default/tests/test_config.py-tpl | 194 ++ .../tests/test_item_store.py-tpl | 81 + .../fastapi-default/tests/test_items.py-tpl | 187 +- .../fastapi-default/tests/test_main.py-tpl | 59 + .../fastapi-dockerized/.dockerignore-tpl | 47 + .../fastapi-dockerized/.env.example-tpl | 10 + .../fastapi-dockerized/Dockerfile-tpl | 29 +- .../fastapi-dockerized/README.md-tpl | 64 +- .../fastapi-dockerized/pyproject.toml-tpl | 11 +- .../fastapi-dockerized/requirements.txt-tpl | 9 +- .../fastapi-dockerized/setup.cfg-tpl | 13 - .../fastapi-dockerized/src/api/deps.py-tpl | 16 + .../src/api/routes/items.py-tpl | 100 +- .../fastapi-dockerized/src/core/config.py-tpl | 131 +- .../src/core/pagination.py-tpl | 37 + .../src/core/responses.py-tpl | 40 + .../fastapi-dockerized/src/crud/items.py-tpl | 130 +- .../fastapi-dockerized/src/main.py-tpl | 13 +- .../src/schemas/items.py-tpl | 41 +- .../fastapi-dockerized/tests/conftest.py-tpl | 34 +- .../tests/test_config.py-tpl | 194 ++ .../tests/test_item_store.py-tpl | 81 + .../tests/test_items.py-tpl | 186 +- .../fastapi-dockerized/tests/test_main.py-tpl | 59 + .../fastapi-domain-starter/.env.example-tpl | 9 + .../fastapi-domain-starter/README.md-tpl | 64 +- .../fastapi-domain-starter/pyproject.toml-tpl | 5 + .../requirements.txt-tpl | 4 +- .../src/app/api/health.py-tpl | 3 + .../src/app/api/router.py-tpl | 10 +- .../src/app/core/config.py-tpl | 82 +- .../src/app/core/pagination.py-tpl | 37 + .../src/app/core/responses.py-tpl | 40 + .../src/app/db/memory.py-tpl | 60 +- .../src/app/domains/items/repository.py-tpl | 36 +- .../src/app/domains/items/router.py-tpl | 89 +- .../src/app/domains/items/schemas.py-tpl | 23 +- .../src/app/domains/items/service.py-tpl | 32 +- .../src/app/main.py-tpl | 5 +- .../tests/conftest.py-tpl | 7 +- .../tests/test_config.py-tpl | 197 +- .../tests/test_health.py-tpl | 8 +- .../tests/test_items.py-tpl | 179 +- .../tests/test_pagination.py-tpl | 23 + .../fastapi-empty/.env.example-tpl | 10 + .../fastapi-empty/README.md-tpl | 33 +- .../fastapi-empty/pyproject.toml-tpl | 5 + .../fastapi-empty/requirements.txt-tpl | 4 +- .../fastapi-empty/setup.cfg-tpl | 13 - .../fastapi-empty/src/core/config.py-tpl | 135 +- .../fastapi-empty/src/core/pagination.py-tpl | 37 + .../fastapi-empty/src/core/responses.py-tpl | 40 + .../fastapi-empty/src/main.py-tpl | 27 +- .../fastapi-empty/tests/test_config.py-tpl | 194 ++ .../fastapi-empty/tests/test_main.py-tpl | 59 +- .../tests/test_pagination.py-tpl | 47 + .../fastapi-llm-agent/.dockerignore-tpl | 47 + .../fastapi-llm-agent/.env.example-tpl | 18 + .../fastapi-llm-agent/Dockerfile-tpl | 21 +- .../fastapi-llm-agent/README.md-tpl | 69 +- .../fastapi-llm-agent/pyproject.toml-tpl | 1 + .../fastapi-llm-agent/scripts/chat.sh-tpl | 7 +- .../fastapi-llm-agent/src/app/api/chat.py-tpl | 145 +- .../fastapi-llm-agent/src/app/api/deps.py-tpl | 40 +- .../src/app/api/health.py-tpl | 3 + .../src/app/api/router.py-tpl | 6 +- .../src/app/core/config.py-tpl | 91 +- .../src/app/core/responses.py-tpl | 40 + .../src/app/llm/agent.py-tpl | 15 +- .../src/app/llm/tools.py-tpl | 95 +- .../fastapi-llm-agent/src/app/main.py-tpl | 5 +- .../src/app/memory/base.py-tpl | 7 +- .../src/app/memory/in_memory.py-tpl | 37 +- .../src/app/schemas/chat.py-tpl | 10 +- .../fastapi-llm-agent/tests/conftest.py-tpl | 1 + .../fastapi-llm-agent/tests/test_chat.py-tpl | 172 +- .../tests/test_config.py-tpl | 197 +- .../tests/test_health.py-tpl | 9 +- .../tests/test_memory.py-tpl | 49 + .../fastapi-llm-agent/tests/test_tools.py-tpl | 96 +- .../fastapi-mcp/.env.example-tpl | 25 +- .../fastapi-mcp/README.md-tpl | 165 +- .../fastapi-mcp/pyproject.toml-tpl | 35 +- .../fastapi-mcp/requirements.txt-tpl | 5 +- .../fastapi-mcp/setup.cfg-tpl | 89 - .../fastapi-mcp/src/__init__.py-tpl | 1 + .../fastapi-mcp/src/api/api.py-tpl | 16 +- .../fastapi-mcp/src/api/routes/auth.py-tpl | 158 +- .../fastapi-mcp/src/api/routes/items.py-tpl | 287 +-- .../src/api/routes/mcp_server.py-tpl | 27 + .../fastapi-mcp/src/api/routes/users.py-tpl | 47 + .../fastapi-mcp/src/auth/dependencies.py-tpl | 156 +- .../fastapi-mcp/src/auth/security.py-tpl | 58 + .../fastapi-mcp/src/auth/users.py-tpl | 77 + .../fastapi-mcp/src/core/config.py-tpl | 90 +- .../fastapi-mcp/src/core/pagination.py-tpl | 37 + .../fastapi-mcp/src/core/responses.py-tpl | 40 + .../fastapi-mcp/src/crud/__init__.py-tpl | 3 + .../fastapi-mcp/src/crud/items.py-tpl | 110 + .../fastapi-mcp/src/main.py-tpl | 43 +- .../fastapi-mcp/src/mcp_server/router.py-tpl | 105 +- .../fastapi-mcp/src/schemas/items.py-tpl | 68 +- .../fastapi-mcp/src/schemas/mcp_server.py-tpl | 15 + .../fastapi-mcp/src/schemas/users.py-tpl | 23 + .../fastapi-mcp/tests/conftest.py-tpl | 80 +- .../fastapi-mcp/tests/test_auth.py-tpl | 214 +- .../fastapi-mcp/tests/test_config.py-tpl | 299 ++- .../fastapi-mcp/tests/test_items.py-tpl | 282 ++- .../fastapi-mcp/tests/test_mcp.py-tpl | 139 +- .../fastapi-psql-orm/.dockerignore-tpl | 49 + .../fastapi-psql-orm/.env.example-tpl | 15 +- .../fastapi-psql-orm/Dockerfile-tpl | 27 +- .../fastapi-psql-orm/README.md-tpl | 99 +- .../fastapi-psql-orm/alembic.ini-tpl | 2 +- .../fastapi-psql-orm/docker-compose.yml-tpl | 20 +- .../fastapi-psql-orm/pyproject.toml-tpl | 13 +- .../fastapi-psql-orm/requirements.txt-tpl | 4 +- .../fastapi-psql-orm/scripts/lint.sh-tpl | 1 + .../fastapi-psql-orm/scripts/pre-start.sh-tpl | 5 +- .../fastapi-psql-orm/setup.cfg-tpl | 13 - .../fastapi-psql-orm/src/alembic/env.py-tpl | 17 +- ...5f2a9c1d7e3b_constrain_item_columns.py-tpl | 37 + .../bedcdc35b64a_first_alembic.py-tpl | 20 +- .../fastapi-psql-orm/src/api/api.py-tpl | 7 +- .../fastapi-psql-orm/src/api/deps.py-tpl | 21 +- .../src/api/routes/health.py-tpl | 77 + .../src/api/routes/items.py-tpl | 182 +- .../fastapi-psql-orm/src/core/config.py-tpl | 144 +- .../fastapi-psql-orm/src/core/db.py-tpl | 76 +- .../src/core/pagination.py-tpl | 37 + .../src/core/responses.py-tpl | 40 + .../fastapi-psql-orm/src/crud/items.py-tpl | 117 +- .../fastapi-psql-orm/src/main.py-tpl | 28 +- .../src/models}/__init__.py-tpl | 0 .../fastapi-psql-orm/src/models/items.py-tpl | 25 + .../fastapi-psql-orm/src/schemas/items.py-tpl | 64 +- .../fastapi-psql-orm/template-config.yml-tpl | 4 +- .../fastapi-psql-orm/tests/conftest.py-tpl | 142 +- .../fastapi-psql-orm/tests/test_config.py-tpl | 231 ++ .../fastapi-psql-orm/tests/test_health.py-tpl | 186 ++ .../tests/test_init_data.py-tpl | 14 + .../fastapi-psql-orm/tests/test_items.py-tpl | 176 +- .../fastapi-single-module/.env.example-tpl | 10 + .../fastapi-single-module/README.md-tpl | 18 +- .../fastapi-single-module/pyproject.toml-tpl | 1 + .../requirements.txt-tpl | 5 +- .../fastapi-single-module/setup.cfg-tpl | 4 + .../fastapi-single-module/src/main.py-tpl | 145 +- .../tests/test_config.py-tpl | 205 ++ .../tests/test_main.py-tpl | 42 +- .../fastapi-sqlmodel/.dockerignore-tpl | 47 + .../fastapi-sqlmodel/.env.example-tpl | 17 + .../fastapi-sqlmodel/Dockerfile-tpl | 29 +- .../fastapi-sqlmodel/README.md-tpl | 54 +- .../fastapi-sqlmodel/pyproject.toml-tpl | 4 + .../src/app/alembic/env.py-tpl | 19 + .../0002_timezone_aware_created_at.py-tpl | 50 + .../fastapi-sqlmodel/src/app/api/deps.py-tpl | 11 + .../src/app/api/health.py-tpl | 55 +- .../src/app/api/router.py-tpl | 9 +- .../src/app/core/config.py-tpl | 85 +- .../src/app/core/pagination.py-tpl | 37 + .../src/app/core/responses.py-tpl | 40 + .../fastapi-sqlmodel/src/app/crud/base.py-tpl | 40 +- .../src/app/crud/pagination.py-tpl | 21 - .../src/app/db/session.py-tpl | 36 +- .../fastapi-sqlmodel/src/app/db/types.py-tpl | 48 + .../src/app/domains/items/crud.py-tpl | 12 +- .../src/app/domains/items/models.py-tpl | 50 +- .../src/app/domains/items/router.py-tpl | 80 +- .../src/app/domains/items/schemas.py-tpl | 45 + .../fastapi-sqlmodel/src/app/main.py-tpl | 7 +- .../fastapi-sqlmodel/tests/conftest.py-tpl | 1 + .../fastapi-sqlmodel/tests/test_config.py-tpl | 215 +- .../tests/test_crud_base.py-tpl | 27 +- .../fastapi-sqlmodel/tests/test_health.py-tpl | 124 +- .../fastapi-sqlmodel/tests/test_items.py-tpl | 103 +- .../tests/test_timestamps.py-tpl | 52 + .../modules/api/routes/__init__.py-tpl | 0 .../modules/api/routes/new_route.py-tpl | 188 +- .../api/routes/new_route_envelope.py-tpl | 128 ++ .../modules/core/pagination.py-tpl | 37 + .../modules/core/responses.py-tpl | 40 + .../modules/crud/__init__.py-tpl | 0 .../modules/crud/new_route.py-tpl | 102 +- .../modules/domain/models.py-tpl | 6 +- .../modules/domain/repository.py-tpl | 44 +- .../modules/domain/router.py-tpl | 146 +- .../modules/domain/schemas.py-tpl | 28 +- .../modules/domain/service.py-tpl | 60 +- .../modules/schemas/__init__.py-tpl | 0 .../modules/schemas/new_route.py-tpl | 39 +- .../modules/tests/test_new_route.py-tpl | 132 ++ src/fastapi_fastkit/fragments/README.md | 80 +- .../fragments/auth/dependencies.py.j2 | 194 ++ .../fragments/auth/fastapi_users.py.j2 | 8 - .../fragments/auth/fastapi_users/models.py.j2 | 15 + .../fragments/auth/fastapi_users/router.py.j2 | 108 + .../auth/fastapi_users/schemas.py.j2 | 23 + .../fragments/auth/fastapi_users/users.py.j2 | 99 + src/fastapi_fastkit/fragments/auth/jwt.py.j2 | 40 - .../fragments/auth/middleware.py.j2 | 29 + .../fragments/auth/models.py.j2 | 46 + .../fragments/auth/oauth2.py.j2 | 115 - .../fragments/auth/oauth2_router.py.j2 | 236 ++ .../fragments/auth/package_init.py.j2 | 45 + .../fragments/auth/repository.py.j2 | 254 +++ .../fragments/auth/router.py.j2 | 249 ++ .../fragments/auth/schemas.py.j2 | 42 + .../fragments/auth/security.py.j2 | 111 + .../fragments/auth/service.py.j2 | 98 + .../fragments/auth/session.py.j2 | 71 - .../fragments/auth/settings.j2 | 61 - .../fragments/core/config.py.j2 | 142 ++ .../fragments/db/mongodb.py.j2 | 66 +- src/fastapi_fastkit/fragments/db/redis.py.j2 | 33 +- .../fragments/db/sqlalchemy.py.j2 | 72 +- .../fragments/docker/docker_compose.j2 | 86 +- .../fragments/docker/dockerfile.j2 | 41 +- .../fragments/docker/dockerignore.j2 | 16 + .../fragments/features/cache.py.j2 | 37 +- .../fragments/features/pagination.py.j2 | 31 - .../fragments/features/readiness.py.j2 | 85 + .../fragments/features/tasks_celery.py.j2 | 31 +- .../fragments/features/tasks_dramatiq.py.j2 | 103 +- .../fragments/features/websocket.py.j2 | 60 +- .../fragments/logging/loguru.py.j2 | 53 + .../fragments/logging/structured.py.j2 | 11 + src/fastapi_fastkit/fragments/main.py.j2 | 31 +- .../fragments/main/imports/auth.j2 | 1 + .../fragments/main/imports/caching.j2 | 4 - .../fragments/main/imports/cors.j2 | 1 + .../fragments/main/imports/fastapi_users.j2 | 1 - .../fragments/main/imports/jwt.j2 | 3 - .../fragments/main/imports/loguru.j2 | 2 +- .../fragments/main/imports/mongodb.j2 | 2 +- .../fragments/main/imports/oauth2.j2 | 4 - .../fragments/main/imports/opentelemetry.j2 | 7 +- .../fragments/main/imports/pagination.j2 | 3 - .../fragments/main/imports/rate_limiting.j2 | 4 +- .../fragments/main/imports/readiness.j2 | 1 + .../fragments/main/imports/redis_db.j2 | 1 + .../fragments/main/imports/session_auth.j2 | 4 - .../main/imports/session_middleware.j2 | 1 + .../fragments/main/imports/sqlalchemy.j2 | 3 +- .../main/imports/structured_logging.j2 | 2 +- .../fragments/main/imports/websocket.j2 | 2 +- .../fragments/main/lifespan/caching.j2 | 7 - .../fragments/main/lifespan/mongodb.j2 | 2 - .../fragments/main/lifespan/sqlalchemy.j2 | 2 - .../fragments/main/setup/async_tasks.j2 | 2 +- .../fragments/main/setup/auth.j2 | 2 + .../fragments/main/setup/caching.j2 | 3 +- .../fragments/main/setup/cors.j2 | 14 +- .../fragments/main/setup/loguru.j2 | 1 + .../fragments/main/setup/oauth2.j2 | 3 - .../fragments/main/setup/opentelemetry.j2 | 20 +- .../fragments/main/setup/pagination.j2 | 2 - .../fragments/main/setup/prometheus.j2 | 2 +- .../fragments/main/setup/rate_limiting.j2 | 5 +- .../fragments/main/setup/readiness.j2 | 1 + .../fragments/main/setup/session_auth.j2 | 6 - .../main/setup/session_middleware.j2 | 2 + .../main/setup/structured_logging.j2 | 3 +- .../fragments/main/setup/websocket.j2 | 4 +- .../fragments/main/shutdown/mongodb.j2 | 1 + .../fragments/main/shutdown/redis_db.j2 | 1 + .../fragments/main/shutdown/sqlalchemy.j2 | 1 + .../fragments/main/startup/mongodb.j2 | 1 + .../fragments/middleware/rate_limiting.py.j2 | 140 ++ .../fragments/migrations/alembic_ini.j2 | 4 +- .../fragments/migrations/env.py.j2 | 28 +- .../migrations/initial_revision.py.j2 | 43 + .../fragments/monitoring/telemetry.py.j2 | 34 + .../fragments/tasks/celery_worker.py.j2 | 14 +- .../fragments/tasks/dramatiq_worker.py.j2 | 28 +- .../fragments/test/_auth_settings_tests.j2 | 43 + .../fragments/test/_auth_store_fixtures.j2 | 137 ++ .../fragments/test/conftest_root.py.j2 | 42 + .../fragments/test/pytest_ini.j2 | 6 + .../test/test_auth_fastapi_users.py.j2 | 296 +++ .../fragments/test/test_auth_jwt.py.j2 | 298 +++ .../fragments/test/test_auth_oauth2.py.j2 | 232 ++ .../fragments/test/test_auth_session.py.j2 | 319 +++ .../fragments/test/test_main.py.j2 | 24 +- .../fragments/test/test_pagination.py.j2 | 57 + .../fragments/test/test_rate_limiting.py.j2 | 48 + .../fragments/test/test_readiness.py.j2 | 47 + .../fragments/test/test_tasks_dramatiq.py.j2 | 106 + .../fragments/test/test_websocket.py.j2 | 71 + .../fragments/tooling/mypy_overrides_toml.j2 | 14 + tests/conftest.py | 8 +- tests/test_backends/doctor_helpers.py | 216 ++ tests/test_backends/test_doctor_checks.py | 1324 +++++++++++ tests/test_backends/test_doctor_checks_api.py | 316 +++ tests/test_backends/test_doctor_hardening.py | 885 ++++++++ tests/test_backends/test_doctor_runner.py | 523 +++++ .../test_backends/test_fragment_hardening.py | 1059 +++++++++ .../test_generated_runtime_safety.py | 700 +++++- tests/test_backends/test_import_ordering.py | 58 +- .../test_interactive_config_builder.py | 47 +- .../test_backends/test_interactive_prompts.py | 60 + .../test_interactive_validators.py | 33 +- tests/test_backends/test_main.py | 323 +-- tests/test_backends/test_preset_layout.py | 489 +++- .../test_project_builder_config_generator.py | 790 ++++++- ...st_project_builder_dependency_collector.py | 56 +- .../test_project_builder_settings.py | 479 ++++ tests/test_backends/test_project_metadata.py | 4 +- tests/test_backends/test_route_generators.py | 346 ++- tests/test_backends/test_route_hardening.py | 678 ++++++ tests/test_backends/test_route_naming.py | 188 ++ tests/test_backends/test_route_plan.py | 606 +++++ tests/test_backends/test_scaffolder.py | 24 + .../test_backends/test_windows_portability.py | 5 +- tests/test_cli_operations/test_cli.py | 22 +- .../test_cli_addroute_exit_codes.py | 218 ++ .../test_cli_addroute_preview.py | 147 ++ .../test_cli_config_options.py | 46 +- tests/test_cli_operations/test_cli_doctor.py | 501 +++++ .../test_cli_error_paths.py | 8 + .../test_cli_operations/test_cli_extended.py | 39 +- .../test_cli_interactive_integration.py | 88 +- .../test_cli_startdemo_exit_codes.py | 163 ++ tests/test_core.py | 14 +- .../test_templates/test_domain_starter_e2e.py | 13 +- .../test_feature_route_collisions.py | 104 +- 474 files changed, 37502 insertions(+), 7132 deletions(-) create mode 100644 src/fastapi_fastkit/backend/doctor/__init__.py create mode 100644 src/fastapi_fastkit/backend/doctor/checks_api.py create mode 100644 src/fastapi_fastkit/backend/doctor/checks_code.py create mode 100644 src/fastapi_fastkit/backend/doctor/checks_files.py create mode 100644 src/fastapi_fastkit/backend/doctor/checks_secrets.py create mode 100644 src/fastapi_fastkit/backend/doctor/command.py create mode 100644 src/fastapi_fastkit/backend/doctor/context.py create mode 100644 src/fastapi_fastkit/backend/doctor/envfile.py create mode 100644 src/fastapi_fastkit/backend/doctor/known.py create mode 100644 src/fastapi_fastkit/backend/doctor/model.py create mode 100644 src/fastapi_fastkit/backend/doctor/pyast.py create mode 100644 src/fastapi_fastkit/backend/doctor/render.py create mode 100644 src/fastapi_fastkit/backend/doctor/runner.py create mode 100644 src/fastapi_fastkit/backend/route_plan.py delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/setup.cfg-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/deps.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/responses.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_config.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_item_store.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_main.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.dockerignore-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/alembic/versions/0002_timezone_aware_timestamps.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/rate_limit.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/responses.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/db/types.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_login_hardening.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_timestamps.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/setup.cfg-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/deps.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/pagination.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/responses.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_config.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_item_store.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_main.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-default/setup.cfg-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/deps.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/responses.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_config.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_item_store.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_main.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.dockerignore-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/setup.cfg-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/deps.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/responses.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_config.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_item_store.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_main.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/responses.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_pagination.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-empty/setup.cfg-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/responses.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/test_config.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/test_pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.dockerignore-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/core/responses.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/setup.cfg-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/mcp_server.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/users.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/security.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/users.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/responses.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/crud/__init__.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/crud/items.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/schemas/mcp_server.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/schemas/users.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.dockerignore-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/setup.cfg-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/versions/5f2a9c1d7e3b_constrain_item_columns.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/routes/health.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/responses.py-tpl rename src/fastapi_fastkit/fastapi_project_template/{modules/api => fastapi-psql-orm/src/models}/__init__.py-tpl (100%) create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/models/items.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_config.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_health.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_init_data.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/tests/test_config.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.dockerignore-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/alembic/versions/0002_timezone_aware_created_at.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/api/deps.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/responses.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/crud/pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/db/types.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/schemas.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_timestamps.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/modules/api/routes/__init__.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/modules/api/routes/new_route_envelope.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/modules/core/pagination.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/modules/core/responses.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/modules/crud/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/modules/schemas/__init__.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/modules/tests/test_new_route.py-tpl create mode 100644 src/fastapi_fastkit/fragments/auth/dependencies.py.j2 delete mode 100644 src/fastapi_fastkit/fragments/auth/fastapi_users.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/fastapi_users/models.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/fastapi_users/router.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/fastapi_users/schemas.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/fastapi_users/users.py.j2 delete mode 100644 src/fastapi_fastkit/fragments/auth/jwt.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/middleware.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/models.py.j2 delete mode 100644 src/fastapi_fastkit/fragments/auth/oauth2.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/oauth2_router.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/package_init.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/repository.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/router.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/schemas.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/security.py.j2 create mode 100644 src/fastapi_fastkit/fragments/auth/service.py.j2 delete mode 100644 src/fastapi_fastkit/fragments/auth/session.py.j2 delete mode 100644 src/fastapi_fastkit/fragments/auth/settings.j2 create mode 100644 src/fastapi_fastkit/fragments/core/config.py.j2 create mode 100644 src/fastapi_fastkit/fragments/docker/dockerignore.j2 delete mode 100644 src/fastapi_fastkit/fragments/features/pagination.py.j2 create mode 100644 src/fastapi_fastkit/fragments/features/readiness.py.j2 create mode 100644 src/fastapi_fastkit/fragments/logging/loguru.py.j2 create mode 100644 src/fastapi_fastkit/fragments/main/imports/auth.j2 create mode 100644 src/fastapi_fastkit/fragments/main/imports/cors.j2 delete mode 100644 src/fastapi_fastkit/fragments/main/imports/fastapi_users.j2 delete mode 100644 src/fastapi_fastkit/fragments/main/imports/jwt.j2 delete mode 100644 src/fastapi_fastkit/fragments/main/imports/oauth2.j2 delete mode 100644 src/fastapi_fastkit/fragments/main/imports/pagination.j2 create mode 100644 src/fastapi_fastkit/fragments/main/imports/readiness.j2 create mode 100644 src/fastapi_fastkit/fragments/main/imports/redis_db.j2 delete mode 100644 src/fastapi_fastkit/fragments/main/imports/session_auth.j2 create mode 100644 src/fastapi_fastkit/fragments/main/imports/session_middleware.j2 delete mode 100644 src/fastapi_fastkit/fragments/main/lifespan/caching.j2 delete mode 100644 src/fastapi_fastkit/fragments/main/lifespan/mongodb.j2 delete mode 100644 src/fastapi_fastkit/fragments/main/lifespan/sqlalchemy.j2 create mode 100644 src/fastapi_fastkit/fragments/main/setup/auth.j2 create mode 100644 src/fastapi_fastkit/fragments/main/setup/loguru.j2 delete mode 100644 src/fastapi_fastkit/fragments/main/setup/oauth2.j2 delete mode 100644 src/fastapi_fastkit/fragments/main/setup/pagination.j2 create mode 100644 src/fastapi_fastkit/fragments/main/setup/readiness.j2 delete mode 100644 src/fastapi_fastkit/fragments/main/setup/session_auth.j2 create mode 100644 src/fastapi_fastkit/fragments/main/setup/session_middleware.j2 create mode 100644 src/fastapi_fastkit/fragments/main/shutdown/mongodb.j2 create mode 100644 src/fastapi_fastkit/fragments/main/shutdown/redis_db.j2 create mode 100644 src/fastapi_fastkit/fragments/main/shutdown/sqlalchemy.j2 create mode 100644 src/fastapi_fastkit/fragments/main/startup/mongodb.j2 create mode 100644 src/fastapi_fastkit/fragments/middleware/rate_limiting.py.j2 create mode 100644 src/fastapi_fastkit/fragments/monitoring/telemetry.py.j2 create mode 100644 src/fastapi_fastkit/fragments/test/_auth_settings_tests.j2 create mode 100644 src/fastapi_fastkit/fragments/test/_auth_store_fixtures.j2 create mode 100644 src/fastapi_fastkit/fragments/test/conftest_root.py.j2 create mode 100644 src/fastapi_fastkit/fragments/test/test_auth_fastapi_users.py.j2 create mode 100644 src/fastapi_fastkit/fragments/test/test_auth_jwt.py.j2 create mode 100644 src/fastapi_fastkit/fragments/test/test_auth_oauth2.py.j2 create mode 100644 src/fastapi_fastkit/fragments/test/test_auth_session.py.j2 create mode 100644 src/fastapi_fastkit/fragments/test/test_pagination.py.j2 create mode 100644 src/fastapi_fastkit/fragments/test/test_rate_limiting.py.j2 create mode 100644 src/fastapi_fastkit/fragments/test/test_readiness.py.j2 create mode 100644 src/fastapi_fastkit/fragments/test/test_tasks_dramatiq.py.j2 create mode 100644 src/fastapi_fastkit/fragments/test/test_websocket.py.j2 create mode 100644 src/fastapi_fastkit/fragments/tooling/mypy_overrides_toml.j2 create mode 100644 tests/test_backends/doctor_helpers.py create mode 100644 tests/test_backends/test_doctor_checks.py create mode 100644 tests/test_backends/test_doctor_checks_api.py create mode 100644 tests/test_backends/test_doctor_hardening.py create mode 100644 tests/test_backends/test_doctor_runner.py create mode 100644 tests/test_backends/test_fragment_hardening.py create mode 100644 tests/test_backends/test_project_builder_settings.py create mode 100644 tests/test_backends/test_route_hardening.py create mode 100644 tests/test_backends/test_route_naming.py create mode 100644 tests/test_backends/test_route_plan.py create mode 100644 tests/test_cli_operations/test_cli_addroute_exit_codes.py create mode 100644 tests/test_cli_operations/test_cli_addroute_preview.py create mode 100644 tests/test_cli_operations/test_cli_doctor.py create mode 100644 tests/test_cli_operations/test_cli_startdemo_exit_codes.py diff --git a/CHANGELOG.md b/CHANGELOG.md index bd6fc5f..5cd0eab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,80 @@ # Changelog +## v2.0.0 + +### Breaking changes + +All 12 templates, the code `fastkit init` generates for its options, and `fastkit addroute` output now share one HTTP contract: + +| | v1.5.2 | v2.0.0 | +|---|---|---| +| Business routes | `/items` at the root in `fastapi-default`, `fastapi-async-crud`, `fastapi-dockerized`, `fastapi-psql-orm` and `fastapi-custom-response`; `init` auth routes at `/auth/...` | Under `API_V1_PREFIX` (default `/api/v1`), e.g. `/api/v1/items`, `/api/v1/auth/...` | +| Liveness | `/api/v1/health` in `fastapi-domain-starter`, `fastapi-sqlmodel`, `fastapi-auth-jwt`, `fastapi-llm-agent`; elsewhere `/health` returning `{"status": "healthy"}` | `GET /health` at the root, always `{"status": "ok"}` | +| Readiness | none | `GET /ready` where a database or cache exists: 200 `{"status": "ok"}` or 503 `{"status": "unavailable"}` | +| List endpoints | Plain JSON array (`fastapi-mcp`: `page` / `page_size`) | `limit` (1-100, default 20) and `offset`; body `{"items", "total", "limit", "offset"}` | +| Create | 201 | 201 with a `Location` header | +| Delete | 200 with a message (most templates) | 204, empty body | +| Update | PUT applied partial updates in some templates | PUT replaces the resource; PATCH updates the fields sent | +| Not found | Varies | 404 `{"detail": " not found"}` | +| Collection path | `/items/` in `fastapi-mcp` and `fastapi-custom-response` | `/items` (no trailing slash) | +| Schemas | `ItemResponse`, `ItemPublic` | `ItemCreate`, `ItemUpdate`, `ItemRead` | + +Every 401 carries `WWW-Authenticate`, and each project reads its configuration from one settings module that loads `.env`. + +- **Secrets outside development:** every template and generated settings module now refuses to start with any `ENVIRONMENT` other than `development` (`staging` or `production`) and a missing, example, or shorter than 32-byte `SECRET_KEY`. In `development` an example key only warns. +- **`fastapi-mcp`:** `API_V1_STR` is renamed `API_V1_PREFIX`, and the OpenAPI schema moves to `/openapi.json`. `POST /api/v1/auth/login` is removed (use `POST /api/v1/auth/token`), `/auth/me` becomes `GET /api/v1/users/me`, and `/auth/users` becomes `GET /api/v1/users` (superusers only). `/mcp-routes/*` is replaced by `GET /api/v1/mcp-server`. Only the six item operations are MCP tools. Send the MCP key as `X-MCP-API-Key` (`Authorization: Bearer ` still works) so `Authorization` can carry a user token and write tools work in API-key mode. +- **`fastapi-auth-jwt`:** a rejected refresh token returns 400 `{"error": "invalid_grant"}` instead of 401; token responses add `expires_in`; `GET /api/v1/users` returns the page envelope. +- **`fastapi-sqlmodel`:** `ItemPublic` is renamed `ItemRead`. +- **`fastapi-llm-agent`:** the server generates conversation ids. Send `conversation_id` only to continue a conversation; an unknown id returns 404. +- **`fastapi-custom-response`:** errors, including validation errors and unhandled exceptions, use the response envelope; 500 responses no longer contain exception text. +- **`init` Session-based / OAuth2:** `GET /auth/me` moves to `GET /api/v1/users/me`, and logout returns 204. +- **`init` FastAPI-Users** needs PostgreSQL, MySQL or SQLite; other database choices are rejected. +- **`init` WebSocket:** the connection list moves from `/api/v1/ws/connections` to `/api/v1/connections`; `/ws` is unchanged. +- **CLI:** `startdemo` exits with status 1 when it refuses to run or fails, including an in-place overwrite without a terminal or `--yes`. `addroute` exits with status 1 on errors and refuses route names that are not lower-case ASCII. + +### CLI + +- New `fastkit doctor [PATH]` checks a generated project for problems that newer templates fixed: a committed or unignored `.env`, a missing `.env.example`, example secrets, an MCP server without authentication, CORS `*` with credentials, Prometheus set up inside the lifespan, `sqlalchemy` without `greenlet`, CRLF scripts, a missing `.gitattributes`, an old `requires-python`, a pinned pre-commit Python, a commit after `yield`, `SlowAPIMiddleware`, Motor, the old pagination demo router and configuration read outside the settings module. It never prints secret values. +- `doctor --fix` shows the diff of the safe fixes and asks once (`--yes` skips the question and is required without a terminal); `--dry-run` / `--diff` only previews. `--format json` is for CI, and `--force` checks projects generated before 1.4.0. Exit status: 0 no problem left, 1 problems remain, 2 doctor could not run. +- `fastkit addroute` generates a typed CRUD resource with tests in both layouts (schemas, 201 with `Location`, 204, 404, paginated list) and adds `core/pagination.py` to older projects. The domain layout is chosen when the project has a `domains/` package. New options: `--entity` (class name), `--dry-run` (list files) and `--diff` (show changes). It refuses a route whose files already exist. +- `startdemo -y` also skips the creation prompt. `runserver` rejects an invalid `app_module` in `[tool.fastapi-fastkit]`. + +### `fastkit init` options + +- **JWT** generates an OAuth2 password flow: `POST /api/v1/auth/register`, `POST /api/v1/auth/token` and `GET /api/v1/users/me`, with users stored in the selected SQL database or MongoDB (in memory otherwise). +- **FastAPI-Users** generates working routes (`/api/v1/auth/jwt/*`, `/api/v1/auth/register`, `/api/v1/users/*`) with tests. +- **Session-based:** logout invalidates the session, sessions have an absolute lifetime (`SESSION_ABSOLUTE_MAX_AGE`), and the demo account needs `ENABLE_DEMO_USERS=true` (refused outside development). **OAuth2** requires `OAUTH_REDIRECT_BASE_URL` outside development. +- **Pagination** is built into every list endpoint, so the option does nothing and `fastapi-pagination` is no longer installed. +- **Rate-Limiting** applies `RATE_LIMIT_DEFAULT` to every route and the stricter `RATE_LIMIT_AUTH` to the auth endpoints, using `limits` instead of slowapi. +- **MongoDB** uses PyMongo's async client instead of Motor. The SQL session dependency no longer commits; services commit. +- `classic-layered` and `domain-starter` wire every selected feature into the template's `main.py`. +- Generated tests run against in-memory SQLite and do not export telemetry. +- **Docker:** the image runs as a non-root user and has a healthcheck, `.dockerignore` is generated, compose points the app at its services, and `.env` is supplied at run time instead of copied into the image. **Loguru** is now configured at startup. + +### Templates + +- `fastapi-mcp`: item reads are public; PUT and PATCH work as specified. +- `fastapi-auth-jwt`: login, register and refresh are rate limited (`AUTH_RATE_LIMIT_*`); timestamps are timezone-aware (new migration); `GET /api/v1/users/{user_id}` (superusers only) is added. +- `fastapi-sqlmodel`: timestamps are timezone-aware (new migration) and PUT is added. +- `fastapi-psql-orm`: tests use a separate database (`_test` or `TEST_DATABASE_URL`), and Alembic creates the schema (new migration adds column constraints). +- `fastapi-llm-agent`: the SSE stream is declared in OpenAPI, the calculator tool and the conversation store are bounded (`MAX_CONVERSATIONS`, `MAX_MESSAGES_PER_CONVERSATION`), and there are hook points for authentication and rate limiting. +- Templates that store items in a JSON file no longer reuse ids, write atomically, and their tests no longer overwrite the shipped data. +- Unused dependencies and `setup.cfg` files are removed. Template Dockerfiles run as a non-root user and ship a `.dockerignore`. + +### Documentation + +- The English docs cover the changes above, including a `fastkit doctor` section in the CLI reference and the conventions a new template must follow. +- The translated locales are not re-synced in this release; `reference/translation-status` lists the affected pages. + +### Upgrade notes for existing projects + +Upgrading fastkit does not change an existing project. Run `fastkit doctor` in it to see what can be checked and fixed automatically, then: + +1. **Clients of a regenerated project:** apply the contract changes above (paths under `/api/v1`, `/health`, the list envelope, 204 on delete). +2. **Docker:** new images set `ENVIRONMENT=production` and do not contain `.env`; pass `SECRET_KEY` (at least 32 bytes) and the other settings at run time, e.g. `docker run --env-file .env ...`. +3. **`fastapi-auth-jwt`, `fastapi-sqlmodel`, `fastapi-psql-orm` projects that adopt the new template code:** run `alembic upgrade head` for the new migration. +4. **Saved `--config` files** with the Pagination option still work. + ## v1.5.2 (2026-12-01) ### Security diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b7933cd..b46df96 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -238,10 +238,10 @@ When adding a new FastAPI template project, follow these guidelines: template-name/ ├── src/ │ ├── main.py-tpl -│ ├── config/ -│ ├── models/ -│ ├── routes/ -│ └── utils/ +│ ├── api/ +│ ├── core/ # config.py-tpl, pagination.py-tpl, responses.py-tpl +│ ├── crud/ +│ └── schemas/ ├── tests/ ├── scripts/ ├── pyproject.toml-tpl @@ -249,7 +249,9 @@ template-name/ ├── README.md-tpl ├── .env.example-tpl ├── .gitattributes-tpl -└── .gitignore-tpl +├── .gitignore-tpl +├── Dockerfile-tpl # optional +└── .dockerignore-tpl # required with a Dockerfile ``` 2. File Extensions: @@ -258,11 +260,16 @@ template-name/ - `.gitignore-tpl` must ignore `.env` and `.env.*` and keep `!.env.example` 3. Dependencies: - - Declare dependencies in `pyproject.toml-tpl` (`requires-python = ">=3.12"`); no `setup.py-tpl`, no `FastAPI-fastkit` dependency + - Declare dependencies and tool settings in `pyproject.toml-tpl` (`requires-python = ">=3.12"`); no `setup.py-tpl` or `setup.cfg-tpl`, no `FastAPI-fastkit` dependency - Specify version numbers in requirements.txt - Use latest stable versions of dependencies -See [Template Creation Guide](docs/en/contributing/template-creation-guide.md) for the full rules. +4. API conventions: + - Business routes under `API_V1_PREFIX` (`/api/v1`), `GET /health` returning `{"status": "ok"}` at the root, paginated lists (`limit` / `offset`, `{"items", "total", "limit", "offset"}`), 201 with `Location`, 204 on delete, `XCreate` / `XUpdate` / `XRead` schemas + - `core/pagination.py-tpl` and `core/responses.py-tpl` identical to `fastapi_project_template/modules/core/` + - Every `ENVIRONMENT` except `development` (`staging`, `production`) refuses a missing, example, or shorter than 32-byte `SECRET_KEY` + +See [Template Creation Guide](docs/en/contributing/template-creation-guide.md) for the full rules and the conventions checklist. ### Security Requirements diff --git a/README.md b/README.md index e608e81..389bde3 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ fastkit init --interactive - **Caching**: Redis, fastapi-cache2 - **Monitoring**: Loguru, OpenTelemetry, Prometheus - **Testing**: Basic (pytest), Coverage, Advanced (with faker, factory-boy) - - **Utilities**: CORS, Rate-Limiting, Pagination, WebSocket + - **Utilities**: CORS, Rate-Limiting, WebSocket (Pagination is built into every list endpoint) - **Logging**: structured JSON logging with a request-id middleware - **Migrations**: Alembic (async env, baseline revision) - **Tooling**: ruff, pre-commit, GitHub Actions, devcontainer, Makefile (multi-select) @@ -94,12 +94,12 @@ fastkit init --interactive - **Package manager**: pip, uv, pdm, poetry - **Custom packages**: Add your own dependencies - Auto-generates (varies by preset - see [the matrix](https://bnbong.github.io/FastAPI-fastkit/reference/preset-feature-matrix/) for details): - - `main.py` regenerated from selected features for `minimal` / `single-module`; preserved as-shipped for `classic-layered` / `domain-starter` - - Database and authentication configuration files at preset-specific paths + - `main.py` regenerated from selected features for `minimal` / `single-module`; for `classic-layered` / `domain-starter` the shipped `main.py` is kept and every feature is wired into it + - Database module and authentication package at preset-specific paths, with routes under `/api/v1` - Docker deployment files (`Dockerfile`, `docker-compose.yml`) with the preset's correct uvicorn entrypoint - Test configuration (pytest with coverage) - - `/health` and `/ready` endpoints on every generated project - - Real working code — not just installed packages — for background tasks, caching, WebSocket, pagination, OpenTelemetry, OAuth2 and session-based auth + - `GET /health` on every generated project, and `GET /ready` when it has a database or cache + - Real working code with tests — not just installed packages — for background tasks, caching, WebSocket, rate limiting, OpenTelemetry, and JWT, FastAPI-Users, OAuth2 and session-based auth - `--dry-run` previews the exact file tree a run would create, including logging/migrations/tooling artifacts ### Create a project from a template @@ -113,14 +113,29 @@ fastkit startdemo [TEMPLATE] [OPTIONS] - `--project-name`, `--author`, `--author-email`, `--description` - `--package-manager` [pip|uv|pdm|poetry] - `--dry-run`, `--no-venv`, `--no-install`, `--yes`/`-y` — same meaning as on `init` - - Refuses to run if the target project directory already exists (`--dry-run` excepted) + - Refuses to run if the target project directory already exists (`--dry-run` excepted), and then exits with status 1 - Tip: List available templates with `fastkit list-templates` ### Add a new route ```console -fastkit addroute +fastkit addroute [project_dir] [OPTIONS] ``` -- What it does: Adds a new API route to the specified project +- What it does: Adds a CRUD resource with tests (paginated list, create, read, replace, update, delete) under `/api/v1/` +- Key options: + - `--layout` [classic-layer|domain]: defaults to `domain` for `domain-starter` projects and projects with a `domains/` package + - `--entity`: class name for the resource (e.g. `Order`) + - `--dry-run` / `--diff`: preview the files and changes without writing anything + +### Check an existing project +```console +fastkit doctor [PATH] [OPTIONS] +``` +- What it does: Checks a generated project for problems that newer fastkit versions fixed (committed `.env`, example secrets, CORS `*` with credentials, CRLF scripts, and more); upgrading fastkit never changes an existing project +- Key options: + - `--fix`: apply the safe fixes after showing the diff and asking once (`--yes` skips the question) + - `--dry-run` / `--diff`: show what `--fix` would change + - `--format json`: machine-readable report for CI + - Exit status: 0 no problem, 1 problems remain, 2 doctor could not run ### Run the development server ```console diff --git a/docs/en/contributing/template-creation-guide.md b/docs/en/contributing/template-creation-guide.md index 3aeb691..9698573 100644 --- a/docs/en/contributing/template-creation-guide.md +++ b/docs/en/contributing/template-creation-guide.md @@ -72,13 +72,15 @@ fastapi-{template-name}/ │ ├── __init__.py-tpl │ ├── api/ # API routers │ │ ├── __init__.py-tpl -│ │ ├── api.py-tpl # Main API router +│ │ ├── api.py-tpl # Main API router (mounted under API_V1_PREFIX) │ │ └── routes/ # Individual routes │ │ ├── __init__.py-tpl │ │ └── items.py-tpl # Example route │ ├── core/ # Core configuration │ │ ├── __init__.py-tpl -│ │ └── config.py-tpl # Settings management +│ │ ├── config.py-tpl # The only settings module (reads .env) +│ │ ├── pagination.py-tpl # Page envelope (copy of modules/core/pagination.py-tpl) +│ │ └── responses.py-tpl # error_responses() (copy of modules/core/responses.py-tpl) │ ├── crud/ # CRUD logic │ │ ├── __init__.py-tpl │ │ └── items.py-tpl @@ -99,11 +101,12 @@ fastapi-{template-name}/ │ └── test.sh-tpl # Test execution ├── pyproject.toml-tpl # ✅ Primary metadata (PEP 621, required) ├── requirements.txt-tpl # 🟡 Optional when pyproject declares deps -├── setup.cfg-tpl # Development tools configuration ├── README.md-tpl # ✅ Project documentation (required) ├── .env.example-tpl # Shareable environment variables (fastkit creates .env from it) ├── .gitattributes-tpl # Line-ending policy (LF for scripts, Docker, env files) -└── .gitignore-tpl # Git ignore file (must ignore .env) +├── .gitignore-tpl # Git ignore file (must ignore .env) +├── Dockerfile-tpl # Optional: non-root user, no .env in the image +└── .dockerignore-tpl # Required with a Dockerfile (excludes .env, .git, .venv) ``` **Minimum required files.** A template must provide: @@ -137,10 +140,52 @@ generated project. `[Ss]cripts` rule hides `scripts/`). - Ship a `.gitattributes-tpl` that pins LF for shell scripts, Docker files, `Makefile` and env files; copy one from an existing template. -- If the settings read `SECRET_KEY`, refuse to start with - `ENVIRONMENT=production` and an example key (see - `KNOWN_EXAMPLE_SECRET_KEYS` in `fastapi-auth-jwt`'s - `src/app/core/config.py-tpl`). +- Every template's settings define `SECRET_KEY` and refuse to start with any + `ENVIRONMENT` other than `development` (`staging`, `production`) when it is + missing, an example value, or shorter than 32 bytes; in `development` an + example value only warns. Copy the + validator and `KNOWN_EXAMPLE_SECRET_KEYS` from `fastapi-default`'s + `src/core/config.py-tpl`. +- Development tool settings (black, isort, mypy, pytest) live in + `pyproject.toml-tpl`; templates do not ship `setup.cfg-tpl`. +- A Dockerfile runs the app as a non-root user, copies only what the app + needs (never `.env`), and comes with a `.dockerignore-tpl`. + +**API conventions.** Every template, `fastkit init` feature module and +`addroute` output follows the same HTTP contract, and the template's tests +check the parts it implements: + +- [ ] Business routers are mounted under `settings.API_V1_PREFIX` + (`/api/v1`); routers carry only their resource prefix + (`APIRouter(prefix="/items", tags=["items"])`) and no trailing slash + (collection route `""`, item route `"/{item_id}"`). +- [ ] `GET /health` at the root returns `{"status": "ok"}` without auth or + I/O; with a database or cache, `GET /ready` returns 200 + `{"status": "ok"}` or 503 `{"status": "unavailable"}`. +- [ ] List endpoints take `limit` (1-100, default 20) and `offset` and + return `Page[XRead]` (`{"items", "total", "limit", "offset"}`) from + `core/pagination.py`. +- [ ] POST returns 201 with a `Location` header; DELETE returns 204 with no + body; PUT replaces (takes `XCreate`), PATCH applies `XUpdate` with + `exclude_unset=True`. +- [ ] 404 body is `{"detail": " not found"}`, 409 for conflicts, + every 401 has `WWW-Authenticate`, and 5xx bodies never contain + exception text. Error responses are documented with + `error_responses(...)` from `core/responses.py`. +- [ ] Schemas are named `XCreate`, `XUpdate`, `XRead` (pydantic v2, + `model_config`), and dependencies use `Annotated` aliases. +- [ ] Request-scoped session dependencies never commit after `yield`; + services or repositories commit. +- [ ] CORS origins come only from `BACKEND_CORS_ORIGINS`, and `*` turns + credentials off. +- [ ] Shipped tests never modify shipped data files or the developer's + database. + +A template with list endpoints ships `core/pagination.py-tpl`, and one that +documents errors with `error_responses(...)` ships `core/responses.py-tpl`. +Both must be identical to the canonical files in +`fastapi_project_template/modules/core/`; a repository test compares every +copy. **Never declare `FastAPI-fastkit` as a runtime dependency** of a generated project. The CLI is a development tool; a template's dependency list should @@ -159,41 +204,32 @@ This file is the main application for the project created with Fa from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware -from api.api import api_router -from core.config import settings +from src.api.api import api_router +from src.core.config import settings + +# fastkit:imports # Create FastAPI app (required for inspector validation) -app = FastAPI( - title="", - description="Project created with FastAPI-fastkit", - version="1.0.0", -) - -# CORS middleware configuration -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) - -# Register API router -app.include_router(api_router, prefix="/api/v1") - -@app.get("/") -async def root(): - """Root endpoint""" - return {"message": "Hello from !"} - -@app.get("/health") -async def health_check(): - """Health check endpoint""" - return {"status": "healthy"} - -if __name__ == "__main__": - import uvicorn - uvicorn.run(app, host="0.0.0.0", port=8000) +app = FastAPI(title=settings.PROJECT_NAME) + +# CORS only for the configured origins; "*" never with credentials +if settings.all_cors_origins: + app.add_middleware( + CORSMiddleware, + allow_origins=settings.all_cors_origins, + allow_credentials="*" not in settings.all_cors_origins, + allow_methods=["*"], + allow_headers=["*"], + ) + +# fastkit:routes +app.include_router(api_router, prefix=settings.API_V1_PREFIX) + + +@app.get("/health", tags=["health"]) +async def health_check() -> dict[str, str]: + """Liveness probe: no authentication and no I/O.""" + return {"status": "ok"} ``` #### 2. Writing pyproject.toml-tpl (preferred) @@ -310,7 +346,7 @@ Items API test module """ import pytest from fastapi.testclient import TestClient -from main import app +from src.main import app client = TestClient(app) @@ -324,7 +360,7 @@ def test_health_check(): """Test health check""" response = client.get("/health") assert response.status_code == 200 - assert response.json() == {"status": "healthy"} + assert response.json() == {"status": "ok"} def test_create_item(): """Test item creation""" @@ -332,17 +368,16 @@ def test_create_item(): "name": "Test Item", "description": "Test Description" } - response = client.post("/api/v1/items/", json=item_data) - assert response.status_code == 200 - data = response.json() - assert data["name"] == item_data["name"] - assert data["description"] == item_data["description"] + response = client.post("/api/v1/items", json=item_data) + assert response.status_code == 201 + assert response.headers["location"].endswith(f"/api/v1/items/{response.json()['id']}") + assert response.json()["name"] == item_data["name"] def test_read_items(): """Test reading items list""" - response = client.get("/api/v1/items/") + response = client.get("/api/v1/items", params={"limit": 20, "offset": 0}) assert response.status_code == 200 - assert isinstance(response.json(), list) + assert set(response.json()) == {"items", "total", "limit", "offset"} ``` ## 🔍 Step 3: Local Validation diff --git a/docs/en/index.md b/docs/en/index.md index c93ae4b..55ef298 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -219,7 +219,7 @@ Select architecture preset: [4] Select database (PostgreSQL, MySQL, MongoDB, Redis, SQLite, None): 1. PostgreSQL - PostgreSQL database with SQLAlchemy 2. MySQL - MySQL database with SQLAlchemy - 3. MongoDB - MongoDB with motor async driver + 3. MongoDB - MongoDB with PyMongo's async client 4. Redis - Redis for caching and session storage 5. SQLite - SQLite database for development 6. None - No database @@ -274,7 +274,7 @@ Select testing framework: 2 Select utilities (comma-separated numbers, e.g., 1,3,4): 1. CORS - Cross-Origin Resource Sharing 2. Rate-Limiting - Request rate limiting - 3. Pagination - Pagination support + 3. Pagination - (built in: list endpoints are always paginated) 4. WebSocket - WebSocket support Select utilities: 1 @@ -356,15 +356,11 @@ Proceed with project creation? [Y/n]: y ╭─────────────────────── Success ───────────────────────╮ │ ✨ Generated Docker deployment files │ ╰───────────────────────────────────────────────────────╯ -╭────────────────────── Warning ────────────────────────╮ -│ ⚠ Preset compatibility │ -│ fastapi-domain-starter's shipped src/app/main.py is │ -│ preserved. The selections below need manual wiring │ -│ there (CORS is already wired — set │ -│ BACKEND_CORS_ORIGINS in .env to activate it). │ -│ Affected selections (packages installed, but no │ -│ dynamic main.py edits applied for the │ -│ 'domain-starter' preset): Prometheus │ +╭─────────────────────── Success ───────────────────────╮ +│ ✨ Wired generated features into src/app/main.py: │ +│ Structured logging, Prometheus, Database lifespan, │ +│ Background tasks, Caching (Redis), Readiness probe, │ +│ Authentication routes │ ╰───────────────────────────────────────────────────────╯ ╭─────────────────────── Success ───────────────────────╮ │ ✨ Generated configuration files for selected stack │ @@ -387,30 +383,30 @@ The interactive mode provides: - **Architecture preset selection** (`minimal` / `single-module` / `classic-layered` / `domain-starter`) that picks the right base template and project layout - **Guided selection** for databases, authentication, background tasks, caching, monitoring, and more -- **Auto-generated code** for selected features — varies by preset (regenerated `main.py` for `minimal` / `single-module`; preserve template-shipped `main.py` and overlay config modules for `classic-layered` / `domain-starter`) +- **Auto-generated code** for selected features — varies by preset (regenerated `main.py` for `minimal` / `single-module`; for `classic-layered` / `domain-starter` the template-shipped `main.py` is kept and every feature is wired into it) - **Preset-aware Docker generation** — the generated `Dockerfile` `CMD` targets the preset's actual entrypoint (`src.main:app` or `src.app.main:app`) - **Smart dependency management** with automatic pip compatibility -- **Feature validation** with manual-wiring warnings for selections the preset cannot auto-wire +- **Feature validation**: combinations that cannot be generated (FastAPI-Users without a SQL database) are rejected before anything is written - **Identity markers** in the generated `pyproject.toml` (description marker + `[tool.fastapi-fastkit]` table) so `is_fastkit_project()` can recognize generated projects later - **Project metadata** recorded in `[tool.fastapi-fastkit]` — template, preset, package manager, `app_module` and the selected `features` — which `fastkit runserver` and `fastkit addroute` read back - **Reproducible runs**: `--save-config ` records the answers, `--config ` replays them without a single prompt, and `--dry-run` previews the result without writing anything -Every catalog selection now generates real, working code rather than just -installing a package — background tasks (Celery/Dramatiq), Redis caching, -WebSocket, Pagination, OpenTelemetry tracing, and OAuth2 / session-based -auth all ship with a matching module and `main.py` wiring. Three new axes -round out the catalog: +Every catalog selection generates real, working code with tests rather than +just installing a package — background tasks (Celery/Dramatiq), Redis +caching, WebSocket, rate limiting, OpenTelemetry tracing, and JWT, +FastAPI-Users, OAuth2 and session-based auth all ship with a matching module +and `main.py` wiring. Pagination is built into every list endpoint. Three +more axes round out the catalog: - **Logging**: `structured` adds stdlib `logging` + `json` structured output with a request-id middleware — no new dependency - **Migrations**: `Alembic` generates a full async migration environment (`alembic.ini`, `alembic/env.py`, a baseline revision, `scripts/migrate.sh`) for any SQL database selection - **Tooling** (multi-select): `ruff`, `pre-commit`, `github-actions`, `devcontainer`, `makefile` — each generates its own config file; `ruff` also merges a `[tool.ruff]` block into `pyproject.toml` -Every generated project also gets `/health` and `/ready` endpoints, and -`--dry-run` lists the exact same file set a real run would write, including -these new artifacts. `classic-layered` and `domain-starter` preserve their -shipped `main.py`, so feature validation warns when a selection under any -of these axes needs manual wiring — see the -[preset / feature matrix](reference/preset-feature-matrix.md) for details. +Every generated project serves `GET /health` at the root and mounts its API +under `/api/v1`; with a database or cache it also serves `GET /ready`. +`--dry-run` lists the exact same file set a real run would write. See the +[preset / feature matrix](reference/preset-feature-matrix.md) for where each +feature lands per preset. ### Add a new route to the FastAPI project @@ -421,27 +417,59 @@ Add a new route endpoint to your FastAPI project with:
```console -$ fastkit addroute user my-awesome-project +$ fastkit addroute users my-awesome-project Adding New Route ┌──────────────────┬──────────────────────────────────────────┐ │ Project │ my-awesome-project │ -│ Route Name │ user │ +│ Route Name │ users │ +│ Layout │ classic-layer │ +│ Path │ /users │ +│ Entity │ User │ +│ Schemas │ UserCreate, UserUpdate, UserRead │ │ Target Directory │ ~your-project-path~ │ └──────────────────┴──────────────────────────────────────────┘ +Files to create (4): + + src/api/routes/users.py + + src/crud/users.py + + src/schemas/users.py + + tests/test_users.py +Files to modify (1): + ~ src/api/api.py -Do you want to add route 'user' to project 'my-awesome-project'? [Y/n]: y +Do you want to add route 'users' to project 'my-awesome-project'? [Y/n]: y -╭──────────────────────── Info ────────────────────────╮ -│ ℹ Updated main.py to include the API router │ -╰──────────────────────────────────────────────────────╯ ╭─────────────────────── Success ───────────────────────╮ -│ ✨ Successfully added new route 'user' to project │ +│ ✨ Successfully added new route 'users' to project │ │ `my-awesome-project` │ ╰───────────────────────────────────────────────────────╯ ```
+The route is a complete CRUD resource with tests: a paginated list, 201 with +`Location` on create, PUT, PATCH, 204 on delete and 404 for unknown ids, +under `/api/v1/users`. `--dry-run` and `--diff` preview the change, and +`--entity` sets the class name. + +### Check an existing project + +Upgrading fastkit never changes a project you already generated. `fastkit +doctor` checks a project for problems that newer templates fixed (a committed +`.env`, example secrets, CORS `*` with credentials, CRLF scripts, and more) +and applies the safe fixes after showing the diff: + +
+ +```console +$ fastkit doctor my-awesome-project +$ fastkit doctor my-awesome-project --fix +``` + +
+ +See the [CLI reference](user-guide/cli-reference.md#doctor) for every check +and option. + ### Place a structured FastAPI demo project immediately You can also start with a structured FastAPI demo project. @@ -510,7 +538,7 @@ FastAPI template project will deploy at '~your-project-path~' - `--project-name`, `--author`, `--author-email`, `--description` - `--package-manager` [pip|uv|pdm|poetry] - `--dry-run`, `--no-venv`, `--no-install`, `--yes`/`-y` — same meaning as on `init` - - Refuses to run if the target project directory already exists (`--dry-run` excepted) + - Refuses to run if the target project directory already exists (`--dry-run` excepted), and then exits with status 1 To view the list of available FastAPI demos, check with: diff --git a/docs/en/reference/preset-feature-matrix.md b/docs/en/reference/preset-feature-matrix.md index 0aa02ad..a5fd303 100644 --- a/docs/en/reference/preset-feature-matrix.md +++ b/docs/en/reference/preset-feature-matrix.md @@ -21,71 +21,61 @@ land, and which feature combinations require manual wiring. ## Generated file locations -| Preset | `main.py` overlay | Database config target | Auth config target | -|---|---|---|---| -| `minimal` | regenerated at `src/main.py` | `src/config/database.py` | `src/config/auth.py` | -| `single-module` | regenerated at `src/main.py` | `src/config/database.py` | `src/config/auth.py` | -| `classic-layered` | preserved (template-shipped) | `src/core/database.py` | `src/core/auth.py` | -| `domain-starter` | preserved (template-shipped) | `src/app/core/database.py` | `src/app/core/auth.py` | - -## Database / auth feature support per preset - -These features are supported across **every** preset — the package install -always succeeds; the difference is whether the dynamic `main.py` overlay -also wires them up automatically. - -| Feature | `minimal` / `single-module` | `classic-layered` / `domain-starter` | +| Preset | `main.py` overlay | Settings module | Database module | Auth package | +|---|---|---|---|---| +| `minimal` | regenerated at `src/main.py` | `src/core/config.py` | `src/config/database.py` | `src/auth/` | +| `single-module` | regenerated at `src/main.py` | `src/core/config.py` (written by fastkit) | `src/config/database.py` | `src/auth/` | +| `classic-layered` | preserved (template-shipped) | `src/core/config.py` | `src/core/database.py` | `src/auth/` | +| `domain-starter` | preserved (template-shipped) | `src/app/core/config.py` | `src/app/core/database.py` | `src/app/domains/auth/` | + +Every preset has `core/pagination.py` (the `Page` envelope and the +`limit` / `offset` parameters); with `single-module`, fastkit writes it. Generated feature code reads its configuration from the settings +module, which loads `.env`. + +## Feature support per preset + +Every feature is generated for every preset. `minimal` and `single-module` +regenerate `main.py` with everything wired. `classic-layered` and +`domain-starter` keep the template's `main.py` and fastkit splices each +feature into it through the `# fastkit:imports` / `# fastkit:routes` anchors: +routers are mounted under `settings.API_V1_PREFIX` (probes and `/ws` at the +root), and middleware goes above the CORS block so CORS stays outermost. The +summary line "Wired generated features into ..." lists what was added. + +| Feature | Generated | Wired into `main.py` | |---|---|---| -| **Database** (PostgreSQL, MySQL, SQLite, MongoDB) | Generates the config module **and** stubs `await init_db()` calls in the regenerated `main.py`. | Generates the config module at the preset's path. The shipped `main.py` is **preserved**, so wire `get_db()` into routers manually. | -| **Authentication** (JWT, FastAPI-Users, OAuth2, Session-based) | Generates the auth config module; JWT imports `HTTPBearer`, OAuth2 and Session-based also add their `main.py` middleware setup. JWT, OAuth2 and Session-based refuse to start with a missing or example `SECRET_KEY` when `ENVIRONMENT=production`. | Generates the auth config module at the preset's path. No imports added to `main.py` — wire dependencies manually. | -| **Background tasks** (Celery, Dramatiq) | Generates `worker.py` and `features/tasks.py`, and mounts the task router in the regenerated `main.py`. | Generates `worker.py` and `features/tasks.py` and mounts the task router through the `# fastkit:imports` / `# fastkit:routes` anchors of the shipped `main.py`. | -| **Caching** (Redis) | Generates `features/cache.py` and mounts/initializes it in the regenerated `main.py`. | Generates `features/cache.py`; mount it manually. | -| **Utilities: Pagination / WebSocket** | Generates `features/pagination.py` (a paginated demo list on `GET /api/v1/items`) / `features/websocket.py` and mounts the router in the regenerated `main.py`. | WebSocket: generates `features/websocket.py` and mounts it below the `# fastkit:routes` anchor. Pagination: no demo router, because both templates already serve an items list (`GET /items`, `GET /api/v1/items`); `add_pagination(app)` is appended to `main.py` with a comment on paginating that endpoint. | -| **Monitoring: OpenTelemetry** | No standalone file — tracing setup is added directly to the regenerated `main.py`. | No standalone file. The shipped `main.py` is preserved, so tracing is **not wired** — add the setup manually. | -| **Migrations** (Alembic) | Generates `alembic.ini`, `alembic/env.py`, a baseline revision and `scripts/migrate.sh` for any SQL database selection — independent of the `main.py` overlay. | Same — Alembic generation does not depend on whether `main.py` is preserved. | -| **Tooling** (ruff, pre-commit, github-actions, devcontainer, makefile) | Generates the matching config file(s), independent of the `main.py` overlay. | Same. | -| **Logging** (structured) | Generates `logging_config.py` and wires the request-id middleware into the regenerated `main.py`. | Generates `logging_config.py`; the shipped `main.py` is preserved, so wire the middleware manually. | -| **CORS** (utility) | `CORSMiddleware` is added only when `BACKEND_CORS_ORIGINS` lists origins (comma-separated); `*` turns credentials off. | **Already wired** in the shipped `main.py` (conditional on `settings.all_cors_origins`). Activate by setting `BACKEND_CORS_ORIGINS` in `.env` — no code edits required. | -| **Testing** (Basic / Coverage / Advanced) | `pytest.ini` is generated at the project root; Advanced also adds `tests/factories.py` and `tests/test_factories.py`. | Same. | -| **Deployment** (Docker, docker-compose) | `Dockerfile` and/or `docker-compose.yml` written at the project root. | Same. | -| **`/health` / `/ready`** | Always present in the regenerated `main.py`. | Already present in the preserved, template-shipped `main.py`. | +| **Database** (PostgreSQL, MySQL, SQLite, MongoDB) | Database module at the preset's path with a session / client dependency; the client is opened and closed with the app | Regenerated `main.py` closes it in its lifespan; a template `main.py` includes the module's `lifespan_router`. Your own routers use the dependency. With `classic-layered` / `domain-starter`, the template's example `/items` API keeps its own store; fastkit prints a note and adds it to `README.md` | +| **Readiness** (with a database or Redis cache) | `features/readiness.py`: `GET /ready`, 200 or 503 within a 2-second timeout | Included at the root | +| **Authentication** (JWT, FastAPI-Users, OAuth2, Session-based) | Auth package with routes and tests. Users (JWT, Session-based, FastAPI-Users) are stored in the selected SQL database or MongoDB, in memory otherwise; FastAPI-Users needs a SQL database | Auth routes under `/api/v1`; OAuth2 and Session-based also add the session middleware. A template router that already uses `/auth` or `/users` is reported as a conflict | +| **Background tasks** (Celery, Dramatiq) | `worker.py` and `features/tasks.py` | Task router under `/api/v1/tasks` | +| **Caching** (Redis) | `features/cache.py` (its router initialises the cache) | Cache router under `/api/v1/cache` | +| **Rate-Limiting** (utility) | `rate_limiting.py`, built on `limits`: `RATE_LIMIT_DEFAULT` for every route, `RATE_LIMIT_AUTH` for the auth endpoints | `setup_rate_limiting(app)` | +| **WebSocket** (utility) | `features/websocket.py` | `/ws` at the root, `GET /api/v1/connections` | +| **Pagination** (utility) | Nothing: list endpoints are always paginated. The option only prints an info line, so saved configs still load | - | +| **CORS** (utility) | - | Regenerated `main.py`: `CORSMiddleware` only when `BACKEND_CORS_ORIGINS` lists origins; `*` turns credentials off. Template `main.py` files already contain the same block | +| **Monitoring** | Loguru: `loguru_config.py` · OpenTelemetry: `telemetry.py` · Prometheus: none | `setup_loguru()` · `setup_telemetry(app)` · `Instrumentator().instrument(app).expose(app)` right after `app = FastAPI(...)` | +| **Logging** (structured) | `logging_config.py` | `setup_logging(app)` (request-id middleware) | +| **Migrations** (Alembic) | `alembic.ini`, `alembic/env.py`, a baseline revision and `scripts/migrate.sh` for a SQL database | - | +| **Testing** (Basic / Coverage / Advanced) | `pytest.ini`, a root `conftest.py` (in-memory SQLite, no telemetry export) and tests per feature; Advanced also adds `tests/factories.py` | - | +| **Tooling** (ruff, pre-commit, github-actions, devcontainer, makefile) | The matching config files | - | +| **Deployment** (Docker, docker-compose) | `Dockerfile` (non-root user, healthcheck on `/health`, no `.env` in the image), `.dockerignore`, `docker-compose.yml` with service URLs and healthchecks | - | +| **`/health`** | Always present: `{"status": "ok"}` at the root | - | ## When you'll see a "Preset compatibility" warning -For presets that **preserve the shipped `main.py`** (`classic-layered`, -`domain-starter`), some feature selections won't be auto-wired into the -app. The CLI surfaces a one-shot warning at the end of generation listing -which selections need manual wiring: +With `classic-layered` and `domain-starter`, fastkit warns only when it +cannot find the template's `main.py` (for example, after you moved it). The +warning lists every selection you then have to register yourself. `minimal` +and `single-module` never warn. -| Selected feature | Triggers a warning under `classic-layered` / `domain-starter`? | -|---|---| -| `CORS` (utility) | ❌ — already wired in the shipped `main.py`. Just populate `BACKEND_CORS_ORIGINS` in `.env`. | -| `Rate-Limiting` (utility) | ✅ — `slowapi` limiter setup is not added | -| `Pagination` / `WebSocket` (utility) | ❌ — WebSocket is mounted through `# fastkit:routes`; Pagination wires only `add_pagination(app)` and prints an info line. | -| `Celery` / `Dramatiq` (async_tasks) | ❌ — the `features/tasks.py` router is mounted through the `# fastkit:routes` anchor | -| `Redis` (caching) | ✅ — the generated `features/cache.py` is not mounted or initialized | -| `Prometheus` / `OpenTelemetry` (monitoring) | ✅ — instrumentation setup is not added to `main.py`. For Prometheus the warning shows the line to add after `app = FastAPI(...)`. | -| `structured` (logging) | ✅ — `logging_config.py` is generated, but the request-id middleware is not added to `main.py` | -| `OAuth2` / `Session-based` (authentication) | ✅ — the `SessionMiddleware` setup and the auth router are not added to `main.py` | -| `Alembic` (migrations), `tooling` selections | ❌ — these files are generated and usable regardless of preset; nothing depends on `main.py` | -| Any database / auth selection | ⚠️ — config files are generated, but you must `Depends()` them into your routers | +## What fastkit never changes -For `minimal` and `single-module` presets the dynamic `main.py` overlay -handles every axis above automatically; no warnings fire. - -## Unsupported combinations (stay safe) - -The strategist changes a template-shipped `main.py` only for the -background task and WebSocket routers (through the `# fastkit:imports` / -`# fastkit:routes` anchors) and `add_pagination(app)`. Middleware, lifespan -hooks and instrumentation are never spliced in, to avoid broken imports or -duplicate setup. The contract is: +fastkit edits a template-shipped `main.py` only by adding import lines and +single module-level statements at its anchors. It does not rewrite template +code or the template's lifespan; features that need startup or shutdown work +bring it in their own router. The contract is: - Selected packages are always installed (so `pip freeze` matches the user's intent). -- Generated config modules always land at the preset-appropriate path. -- For preserve-main presets, the user is told which selections still need - manual wiring instead of getting silently broken code. - -If you need full auto-wiring of every feature, pick `minimal` or -`single-module` — they regenerate `main.py` from feature flags. +- Generated modules always land at the preset-appropriate path. +- Anything that cannot be wired is reported instead of silently broken. diff --git a/docs/en/reference/template-quality-assurance.md b/docs/en/reference/template-quality-assurance.md index 671acc7..9561e20 100644 --- a/docs/en/reference/template-quality-assurance.md +++ b/docs/en/reference/template-quality-assurance.md @@ -310,6 +310,25 @@ setup.py is the legacy fallback; matching is case-insensitive). Metadata injection ensures the markers end up in generated projects even if a template forgets them. +### Conventions +These are checked by the repository's test suite and in review rather than +by the inspector: + +- Follow the API conventions checklist in the + [Template Creation Guide](../contributing/template-creation-guide.md#required-directory-structure): + business routes under `API_V1_PREFIX`, `GET /health` returning + `{"status": "ok"}`, paginated lists (`limit` / `offset`, `{"items", + "total", "limit", "offset"}`), 201 with `Location`, 204 on delete, and the + `XCreate` / `XUpdate` / `XRead` schema names. +- Every shipped `core/pagination.py-tpl` and `core/responses.py-tpl` is + identical to the canonical file in `fastapi_project_template/modules/core/`. +- Settings refuse to start with any `ENVIRONMENT` other than `development` + (`staging`, `production`) and a missing, example, or shorter than 32-byte + `SECRET_KEY`. +- No `setup.cfg-tpl`: tool settings live in `pyproject.toml-tpl`. +- A template with a `Dockerfile-tpl` also ships `.dockerignore-tpl`, and the + image runs as a non-root user without `.env`. + ### Quality Standards - All template files must be syntactically correct - Dependencies must be properly specified diff --git a/docs/en/reference/translation-status.md b/docs/en/reference/translation-status.md index 4b87787..85ea44d 100644 --- a/docs/en/reference/translation-status.md +++ b/docs/en/reference/translation-status.md @@ -41,12 +41,13 @@ next section explains). | 🇫🇷 French (`fr`) | ✅ Complete | 29 / 29 | Phases 1-3 complete. Re-synced with the v1.5.0 English sources on 2026-10-14: the three v1.4.0 tutorials (`tutorial/auth-jwt.md`, `tutorial/sqlmodel.md`, `tutorial/llm-agent.md`) are translated and pages that had drifted since their original translation were brought back in line. `docs/fr/changelog.md` intentionally reuses the canonical English `CHANGELOG.md`. | | 🇩🇪 German (`de`) | ✅ Complete | 29 / 29 | Phases 1-3 complete. Re-synced with the v1.5.0 English sources on 2026-10-14: the three v1.4.0 tutorials (`tutorial/auth-jwt.md`, `tutorial/sqlmodel.md`, `tutorial/llm-agent.md`) are translated and pages that had drifted since their original translation were brought back in line. `docs/de/changelog.md` intentionally reuses the canonical English `CHANGELOG.md`. | -**Not yet re-synced after v1.5.2.** In all six locales these pages still -describe v1.5.1; follow the English pages until they are updated: +**Not yet re-synced after v1.5.2 and v2.0.0.** In all six locales these +pages still describe v1.5.1; follow the English pages until they are updated: -- `user-guide/`: `cli-reference`, `creating-projects`, `using-templates`, `installation` -- `tutorial/`: `auth-jwt`, `domain-starter`, `llm-agent`, `sqlmodel`, `mcp-integration`, `docker-deployment` -- `contributing/template-creation-guide`, `reference/preset-feature-matrix` +- `index` +- `user-guide/`: `cli-reference`, `adding-routes`, `creating-projects`, `using-templates`, `choosing-a-starter`, `quick-start`, `installation` +- `tutorial/`: all twelve tutorials (`getting-started`, `first-project`, `basic-api-server`, `async-crud-api`, `database-integration`, `docker-deployment`, `custom-response-handling`, `mcp-integration`, `auth-jwt`, `sqlmodel`, `domain-starter`, `llm-agent`) +- `contributing/template-creation-guide`, `reference/preset-feature-matrix`, `reference/template-quality-assurance` *Snapshot verified 2026-10-14, after the v1.5.0 release. All six translated locales were brought to parity with the English sources: the three tutorials diff --git a/docs/en/tutorial/async-crud-api.md b/docs/en/tutorial/async-crud-api.md index de431bc..7fd2769 100644 --- a/docs/en/tutorial/async-crud-api.md +++ b/docs/en/tutorial/async-crud-api.md @@ -91,6 +91,8 @@ async-todo-api/ ├── src/ │ ├── main.py # Asynchronous FastAPI application │ ├── api/ +│ │ ├── api.py # Router mounted under /api/v1 +│ │ ├── deps.py # ItemStoreDep dependency │ │ └── routes/ │ │ └── items.py # Asynchronous CRUD endpoints │ ├── crud/ @@ -100,7 +102,9 @@ async-todo-api/ │ ├── mocks/ │ │ └── mock_items.json # JSON file database │ └── core/ -│ └── config.py # Configuration file +│ ├── config.py # Configuration file +│ ├── pagination.py # Page envelope, limit/offset parameters +│ └── responses.py # Documented error responses └── tests/ ├── conftest.py # Asynchronous test configuration └── test_items.py # Asynchronous test cases @@ -116,137 +120,70 @@ async-todo-api/ ### Asynchronous Data Processing (`src/crud/items.py`) -```python -import json -import asyncio -from typing import List, Optional -from aiofiles import open as aio_open -from pathlib import Path - -from src.schemas.items import Item, ItemCreate, ItemUpdate - -class AsyncItemCRUD: - def __init__(self, data_file: str = "src/mocks/mock_items.json"): - self.data_file = Path(data_file) - - async def _read_data(self) -> List[dict]: - """Asynchronously read data from JSON file""" - try: - async with aio_open(self.data_file, 'r', encoding='utf-8') as f: - content = await f.read() - return json.loads(content) - except FileNotFoundError: - return [] - - async def _write_data(self, data: List[dict]) -> None: - """Asynchronously write data to JSON file""" - async with aio_open(self.data_file, 'w', encoding='utf-8') as f: - await f.write(json.dumps(data, indent=2, ensure_ascii=False)) - - async def get_items(self) -> List[Item]: - """Retrieve all items (asynchronous)""" - data = await self._read_data() - return [Item(**item) for item in data] - - async def get_item(self, item_id: int) -> Optional[Item]: - """Retrieve specific item (asynchronous)""" - data = await self._read_data() - item_data = next((item for item in data if item["id"] == item_id), None) - return Item(**item_data) if item_data else None - - async def create_item(self, item: ItemCreate) -> Item: - """Create new item (asynchronous)""" - data = await self._read_data() - new_id = max([item["id"] for item in data], default=0) + 1 - - new_item = Item(id=new_id, **item.dict()) - data.append(new_item.dict()) - - await self._write_data(data) - return new_item - - async def update_item(self, item_id: int, item_update: ItemUpdate) -> Optional[Item]: - """Update item (asynchronous)""" - data = await self._read_data() - - for i, item in enumerate(data): - if item["id"] == item_id: - update_data = item_update.dict(exclude_unset=True) - data[i].update(update_data) - await self._write_data(data) - return Item(**data[i]) - - return None - - async def delete_item(self, item_id: int) -> bool: - """Delete item (asynchronous)""" - data = await self._read_data() - original_length = len(data) - - data = [item for item in data if item["id"] != item_id] - - if len(data) < original_length: - await self._write_data(data) - return True - - return False -``` - -### Asynchronous API Endpoints (`src/api/routes/items.py`) +`ItemStore` keeps the items in `src/mocks/mock_items.json`. It reads the file +with aiofiles, writes it atomically in a worker thread +(`asyncio.to_thread`), serialises changes with an `asyncio.Lock`, and never +reuses an id: ```python -from typing import List -from fastapi import APIRouter, HTTPException, status +class ItemStore: + def __init__(self, path: Path) -> None: ... + + async def list_page(self, offset: int, limit: int) -> tuple[list[ItemData], int]: ... + async def get(self, item_id: int) -> ItemData | None: ... + async def create(self, data: ItemData) -> ItemData: ... + async def replace(self, item_id: int, data: ItemData) -> ItemData | None: ... + async def update(self, item_id: int, changes: ItemData) -> ItemData | None: ... + async def delete(self, item_id: int) -> bool: ... +``` -from src.schemas.items import Item, ItemCreate, ItemUpdate -from src.crud.items import AsyncItemCRUD +The routes get the store through the `ItemStoreDep` dependency +(`src/api/deps.py`), so tests can replace it. -router = APIRouter() -crud = AsyncItemCRUD() +### Asynchronous API Endpoints (`src/api/routes/items.py`) -@router.get("/", response_model=List[Item]) -async def read_items(): - """Retrieve all items (asynchronous)""" - return await crud.get_items() +The router is mounted under `/api/v1` (`API_V1_PREFIX`): -@router.get("/{item_id}", response_model=Item) -async def read_item(item_id: int): - """Retrieve specific item (asynchronous)""" - item = await crud.get_item(item_id) +```python +router = APIRouter(prefix="/items", tags=["items"]) + + +@router.get("") +async def list_items( + store: ItemStoreDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> Page[ItemRead]: + items, total = await store.list_page(offset=offset, limit=limit) + return Page[ItemRead]( + items=[ItemRead.model_validate(item) for item in items], + total=total, + limit=limit, + offset=offset, + ) + + +@router.get("/{item_id}", responses=error_responses(404)) +async def get_item(item_id: int, store: ItemStoreDep) -> ItemRead: + item = await store.get(item_id) if item is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item with id {item_id} not found" - ) - return item - -@router.post("/", response_model=Item, status_code=status.HTTP_201_CREATED) -async def create_item(item: ItemCreate): - """Create new item (asynchronous)""" - return await crud.create_item(item) - -@router.put("/{item_id}", response_model=Item) -async def update_item(item_id: int, item_update: ItemUpdate): - """Update item (asynchronous)""" - updated_item = await crud.update_item(item_id, item_update) - if updated_item is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item with id {item_id} not found" - ) - return updated_item + raise item_not_found() # 404 {"detail": "Item not found"} + return ItemRead.model_validate(item) -@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT) -async def delete_item(item_id: int): - """Delete item (asynchronous)""" - deleted = await crud.delete_item(item_id) - if not deleted: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item with id {item_id} not found" - ) + +@router.post("", status_code=status.HTTP_201_CREATED) +async def create_item( + payload: ItemCreate, request: Request, response: Response, store: ItemStoreDep +) -> ItemRead: + item = await store.create(payload.model_dump()) + response.headers["Location"] = str(request.url_for("get_item", item_id=item["id"])) + return ItemRead.model_validate(item) ``` +`PUT /api/v1/items/{item_id}` replaces an item (it takes `ItemCreate`), +`PATCH` changes only the fields sent (`ItemUpdate`), and `DELETE` returns 204 +with no body. + ## Step 4: Running Server and Testing Navigate to the project directory and run the server: @@ -279,14 +216,14 @@ import aiohttp import time async def create_item(session, item_data): - async with session.post("http://127.0.0.1:8000/items/", json=item_data) as response: + async with session.post("http://127.0.0.1:8000/api/v1/items", json=item_data) as response: return await response.json() async def test_concurrent_requests(): start_time = time.time() items_to_create = [ - {"name": f"Item {i}", "description": f"Description {i}", "price": i * 10, "tax": i} + {"name": f"Item {i}", "description": f"Description {i}", "price": i * 10, "category": "demo"} for i in range(1, 11) # Create 10 items concurrently ] @@ -307,85 +244,60 @@ async def test_concurrent_requests(): ### Test Configuration (`tests/conftest.py`) ```python -import pytest -import asyncio -from httpx import AsyncClient -from src.main import app +@pytest.fixture +def store(tmp_path: Path) -> ItemStore: + """Item store on a temporary file, so tests never touch src/mocks.""" + path = tmp_path / "items.json" + path.write_text(json.dumps(SEED_ITEMS), encoding="utf-8") + return ItemStore(path) -@pytest.fixture(scope="session") -def event_loop(): - """Event loop configuration""" - loop = asyncio.get_event_loop_policy().new_event_loop() - yield loop - loop.close() @pytest.fixture -async def async_client(): - """Asynchronous test client""" - async with AsyncClient(app=app, base_url="http://test") as client: - yield client +async def client(store: ItemStore) -> AsyncGenerator[AsyncClient, None]: + app.dependency_overrides[get_item_store] = lambda: store + async with AsyncClient( + transport=ASGITransport(app=app), base_url="http://test" + ) as ac: + yield ac + app.dependency_overrides.clear() ``` +pytest-asyncio's mode and fixture loop scope are set in `pyproject.toml`, so +no `event_loop` fixture is needed. + ### Asynchronous Test Cases (`tests/test_items.py`) ```python -import pytest -from httpx import AsyncClient +ITEMS_URL = "/api/v1/items" + -@pytest.mark.asyncio -async def test_create_item_async(async_client: AsyncClient): - """Asynchronous item creation test""" - item_data = { - "name": "Test Item", - "description": "Item for asynchronous testing", - "price": 100.0, - "tax": 10.0 - } +async def test_create_item(client: AsyncClient) -> None: + item_data = {"name": "Test Item", "price": 100.0, "category": "test"} - response = await async_client.post("/items/", json=item_data) + response = await client.post(ITEMS_URL, json=item_data) assert response.status_code == 201 data = response.json() + assert response.headers["location"].endswith(f"{ITEMS_URL}/{data['id']}") assert data["name"] == item_data["name"] - assert data["price"] == item_data["price"] - assert "id" in data -@pytest.mark.asyncio -async def test_read_items_async(async_client: AsyncClient): - """Asynchronous item list retrieval test""" - response = await async_client.get("/items/") + +async def test_list_items(client: AsyncClient) -> None: + response = await client.get(ITEMS_URL, params={"limit": 1, "offset": 0}) assert response.status_code == 200 - items = response.json() - assert isinstance(items, list) + page = response.json() + assert set(page) == {"items", "total", "limit", "offset"} + assert len(page["items"]) == 1 -@pytest.mark.asyncio -async def test_concurrent_operations(async_client: AsyncClient): - """Concurrent operations test""" - import asyncio - # Create multiple items concurrently - tasks = [] - for i in range(5): - item_data = { - "name": f"ConcurrentItem{i}", - "description": f"Description{i}", - "price": i * 10, - "tax": i - } - task = async_client.post("/items/", json=item_data) - tasks.append(task) - - responses = await asyncio.gather(*tasks) - - # Verify all requests succeeded - for response in responses: - assert response.status_code == 201 - - # Verify created items - response = await async_client.get("/items/") - items = response.json() - assert len(items) >= 5 +async def test_concurrent_creates(client: AsyncClient) -> None: + payloads = [{"name": f"Item{i}", "price": i * 10, "category": "test"} for i in range(5)] + + responses = await asyncio.gather(*(client.post(ITEMS_URL, json=p) for p in payloads)) + + assert all(r.status_code == 201 for r in responses) + assert len({r.json()["id"] for r in responses}) == 5 ``` ### Running Tests @@ -393,20 +305,12 @@ async def test_concurrent_operations(async_client: AsyncClient):
```console -$ pytest tests/ -v --asyncio-mode=auto +$ pytest tests/ -v ======================== test session starts ======================== -collected 8 items - -tests/test_items.py::test_create_item_async PASSED [ 12%] -tests/test_items.py::test_read_items_async PASSED [ 25%] -tests/test_items.py::test_read_item_async PASSED [ 37%] -tests/test_items.py::test_update_item_async PASSED [ 50%] -tests/test_items.py::test_delete_item_async PASSED [ 62%] -tests/test_items.py::test_concurrent_operations PASSED [ 75%] -tests/test_items.py::test_item_not_found_async PASSED [ 87%] -tests/test_items.py::test_invalid_item_data_async PASSED [100%] - -======================== 8 passed in 0.24s ======================== +tests/test_items.py::test_list_items_returns_a_page PASSED +tests/test_items.py::test_create_item_returns_201_and_location PASSED +tests/test_items.py::test_delete_item_returns_204 PASSED +... ```
@@ -423,11 +327,7 @@ from fastapi import FastAPI, Request from src.api.api import api_router from src.core.config import settings -app = FastAPI( - title=settings.PROJECT_NAME, - version=settings.VERSION, - description=settings.DESCRIPTION, -) +app = FastAPI(title=settings.PROJECT_NAME) @app.middleware("http") async def add_process_time_header(request: Request, call_next): @@ -438,11 +338,11 @@ async def add_process_time_header(request: Request, call_next): response.headers["X-Process-Time"] = str(process_time) return response -app.include_router(api_router) +app.include_router(api_router, prefix=settings.API_V1_PREFIX) -@app.get("/") -async def read_root(): - return {"message": "Welcome to the Asynchronous Todo API!"} +@app.get("/health", tags=["health"]) +async def health_check() -> dict[str, str]: + return {"status": "ok"} ``` ### Implementing Asynchronous Batch Processing @@ -452,19 +352,19 @@ Let's add batch endpoints for processing multiple items at once: ```python # Add to src/api/routes/items.py -@router.post("/batch", response_model=List[Item]) -async def create_items_batch(items: List[ItemCreate]): +@router.post("/batch", status_code=status.HTTP_201_CREATED) +async def create_items_batch(items: list[ItemCreate], store: ItemStoreDep) -> list[ItemRead]: """Create multiple items concurrently (batch processing)""" import asyncio # Execute all item creation tasks concurrently - tasks = [crud.create_item(item) for item in items] + tasks = [store.create(item.model_dump()) for item in items] created_items = await asyncio.gather(*tasks) - return created_items + return [ItemRead.model_validate(item) for item in created_items] @router.get("/batch/{item_ids}") -async def read_items_batch(item_ids: str): +async def read_items_batch(item_ids: str, store: ItemStoreDep) -> list[ItemRead]: """Retrieve multiple items concurrently (batch processing)""" import asyncio @@ -472,11 +372,11 @@ async def read_items_batch(item_ids: str): ids = [int(id.strip()) for id in item_ids.split(",")] # Execute all item retrieval tasks concurrently - tasks = [crud.get_item(item_id) for item_id in ids] + tasks = [store.get(item_id) for item_id in ids] items = await asyncio.gather(*tasks) # Return only non-None items - return [item for item in items if item is not None] + return [ItemRead.model_validate(item) for item in items if item is not None] ``` ### Batch Processing Testing @@ -485,16 +385,16 @@ async def read_items_batch(item_ids: str): ```console # Batch creation test -$ curl -X POST "http://127.0.0.1:8000/items/batch" \ +$ curl -X POST "http://127.0.0.1:8000/api/v1/items/batch" \ -H "Content-Type: application/json" \ -d '[ - {"name": "Item1", "description": "Description1", "price": 10.0, "tax": 1.0}, - {"name": "Item2", "description": "Description2", "price": 20.0, "tax": 2.0}, - {"name": "Item3", "description": "Description3", "price": 30.0, "tax": 3.0} + {"name": "Item1", "description": "Description1", "price": 10.0, "category": "demo"}, + {"name": "Item2", "description": "Description2", "price": 20.0, "category": "demo"}, + {"name": "Item3", "description": "Description3", "price": 30.0, "category": "demo"} ]' # Batch retrieval test -$ curl -X GET "http://127.0.0.1:8000/items/batch/1,2,3" +$ curl -X GET "http://127.0.0.1:8000/api/v1/items/batch/1,2,3" ``` @@ -637,8 +537,8 @@ async def safe_async_operation(operation, *args, **kwargs) -> Union[Any, None]: # usage example @router.get("/safe/{item_id}") -async def read_item_safe(item_id: int): - return await safe_async_operation(crud.get_item, item_id) +async def read_item_safe(item_id: int, store: ItemStoreDep): + return await safe_async_operation(store.get, item_id) ``` ## Next Steps diff --git a/docs/en/tutorial/auth-jwt.md b/docs/en/tutorial/auth-jwt.md index d091fbf..035f4b0 100644 --- a/docs/en/tutorial/auth-jwt.md +++ b/docs/en/tutorial/auth-jwt.md @@ -73,8 +73,8 @@ accounts-api/ │ │ └── security.py # argon2 hashing + JWT encode/decode │ ├── db/session.py # engine + get_session dependency │ ├── api/ -│ │ ├── router.py # aggregates health + every domain router -│ │ ├── health.py # GET /health +│ │ ├── router.py # aggregates every domain router (under /api/v1) +│ │ ├── health.py # GET /health, GET /ready (root level) │ │ └── deps.py # session, current user, role/scope guards │ ├── domains/ │ │ ├── auth/ # login, refresh rotation, logout @@ -101,7 +101,7 @@ $ curl -X POST http://127.0.0.1:8000/api/v1/auth/register \ # 2. log in — note the form encoding: this is the OAuth2 password flow $ curl -X POST http://127.0.0.1:8000/api/v1/auth/login \ -d 'username=alice@example.com&password=s3cret-password' -{"access_token": "...", "refresh_token": "...", "token_type": "bearer"} +{"access_token": "...", "refresh_token": "...", "token_type": "bearer", "expires_in": 1800} # 3. call a protected route $ curl http://127.0.0.1:8000/api/v1/users/me \ @@ -115,7 +115,8 @@ The full surface: | Method | Endpoint | Auth | Description | |--------|-----------------------------|-------------|-----------------------------------| -| GET | `/api/v1/health` | — | Liveness probe | +| GET | `/health` | — | Liveness probe | +| GET | `/ready` | — | Database check, 200 or 503 | | POST | `/api/v1/auth/register` | — | Create an account | | POST | `/api/v1/auth/login` | — | OAuth2 password form → token pair | | POST | `/api/v1/auth/refresh` | refresh tok | Rotate into a fresh token pair | @@ -124,7 +125,13 @@ The full surface: | GET | `/api/v1/users/me` | access tok | Current user's profile | | PATCH | `/api/v1/users/me` | access tok | Update the current user's profile | | GET | `/api/v1/users/me/scopes` | scope `me` | Scope-gated example route | -| GET | `/api/v1/users` | superuser | Role-gated user listing | +| GET | `/api/v1/users` | superuser | Role-gated user listing, paginated (`limit`, `offset`) | +| GET | `/api/v1/users/{user_id}` | superuser | One user (the `Location` of a registration) | + +Registration returns 201 with a `Location` header. Login, register and +refresh are rate limited per client address (`AUTH_RATE_LIMIT_REQUESTS` per +`AUTH_RATE_LIMIT_WINDOW_SECONDS`, on by default with +`AUTH_RATE_LIMIT_ENABLED`); over the limit the response is 429. ## Step 4: Two tokens, and why @@ -192,7 +199,7 @@ $ curl -X POST http://127.0.0.1:8000/api/v1/auth/refresh \ $ curl -X POST http://127.0.0.1:8000/api/v1/auth/refresh \ -H 'Content-Type: application/json' \ -d "{\"refresh_token\": \"$REFRESH_TOKEN\"}" -# → 401: the token died the moment it was used +# → 400 {"error": "invalid_grant", ...}: the token died the moment it was used ``` That single property is what turns a stolen refresh token from a @@ -277,6 +284,10 @@ After a model change: $ alembic revision --autogenerate -m "add profile fields" ``` +Timestamps are stored timezone-aware (UTC). A database created by an older +version of the template needs the `0002_timezone_aware_timestamps` revision: +run `alembic upgrade head`. + ## Step 9: Before you deploy Two settings in `.env` decide whether this is a demo or a real service: @@ -284,10 +295,13 @@ Two settings in `.env` decide whether this is a demo or a real service: - **`SECRET_KEY`** signs every token. The generated `.env` already has a unique key. Leave `SECRET_KEY` unset and a random key is generated per process — which logs everyone out on every restart, - and makes multiple workers disagree about which tokens are valid. With - `ENVIRONMENT=production` the app refuses to start with an example key - such as the placeholder in `.env.example`. For a deployment, generate a - key and pin it: + and makes multiple workers disagree about which tokens are valid. With any + `ENVIRONMENT` other than `development` (`staging`, `production`) the app + refuses to start when the key is + missing, an example such as the placeholder in `.env.example`, or shorter + than 32 bytes. The Docker image sets `ENVIRONMENT=production` and does not + contain `.env`, so pass the key at run time (`docker run --env-file .env`). + For a deployment, generate a key and pin it: ```console $ python -c "import secrets; print(secrets.token_urlsafe(32))" diff --git a/docs/en/tutorial/basic-api-server.md b/docs/en/tutorial/basic-api-server.md index d81e509..16940b7 100644 --- a/docs/en/tutorial/basic-api-server.md +++ b/docs/en/tutorial/basic-api-server.md @@ -63,15 +63,19 @@ Let's examine the generated project structure: my-first-api/ ├── README.md # Project documentation ├── requirements.txt # Dependency package list -├── setup.py # Package configuration +├── pyproject.toml # Package and tool configuration +├── .env.example # Settings to share (.env is generated, git-ignored) ├── scripts/ │ └── run-server.sh # Server execution script ├── src/ # Main source code │ ├── main.py # FastAPI application entry point │ ├── core/ -│ │ └── config.py # Configuration management +│ │ ├── config.py # Configuration management +│ │ ├── pagination.py # Page envelope, limit/offset parameters +│ │ └── responses.py # Documented error responses │ ├── api/ │ │ ├── api.py # API router collection +│ │ ├── deps.py # Shared dependencies (the item store) │ │ └── routes/ │ │ └── items.py # Item-related endpoints │ ├── schemas/ @@ -83,7 +87,8 @@ my-first-api/ └── tests/ # Test code ├── __init__.py ├── conftest.py - └── test_items.py + ├── test_items.py + └── ... ``` ### Key File Descriptions @@ -91,8 +96,8 @@ my-first-api/ - **`src/main.py`**: FastAPI application entry point - **`src/api/routes/items.py`**: Item-related API endpoint definitions - **`src/schemas/items.py`**: Request/response data structure definitions -- **`src/crud/items.py`**: Database operation logic -- **`src/mocks/mock_items.json`**: Sample data for development +- **`src/crud/items.py`**: Item store backed by the JSON file +- **`src/mocks/mock_items.json`**: Sample data for development (tests use a temporary copy) ## Step 3: Running the Server @@ -117,21 +122,23 @@ INFO: Application startup complete. Once the server is successfully running, you can access the following URLs in your browser: -- **API Server**: http://127.0.0.1:8000 +- **Health check**: http://127.0.0.1:8000/health returns `{"status": "ok"}` - **Swagger UI Documentation**: http://127.0.0.1:8000/docs - **ReDoc Documentation**: http://127.0.0.1:8000/redoc ## Step 4: Exploring API Endpoints -The generated API provides the following endpoints by default: +The generated API provides the following endpoints by default, under the +`/api/v1` prefix (`API_V1_PREFIX`): | Method | Endpoint | Description | |--------|----------|-------------| -| GET | `/items/` | Retrieve all items | -| GET | `/items/{item_id}` | Retrieve specific item | -| POST | `/items/` | Create new item | -| PUT | `/items/{item_id}` | Update item | -| DELETE | `/items/{item_id}` | Delete item | +| GET | `/api/v1/items` | List items, one page at a time (`limit` 1-100, default 20; `offset`) | +| GET | `/api/v1/items/{item_id}` | Retrieve specific item (404 if missing) | +| POST | `/api/v1/items` | Create new item (201 with a `Location` header) | +| PUT | `/api/v1/items/{item_id}` | Replace an item (every field required) | +| PATCH | `/api/v1/items/{item_id}` | Change only the fields sent | +| DELETE | `/api/v1/items/{item_id}` | Delete item (204, no body) | ### Testing the API @@ -140,23 +147,21 @@ The generated API provides the following endpoints by default:
```console -$ curl -X GET "http://127.0.0.1:8000/items/" -[ - { - "id": 1, - "name": "Laptop", - "description": "High-performance laptop", - "price": 999.99, - "tax": 99.99 - }, - { - "id": 2, - "name": "Mouse", - "description": "Wireless mouse", - "price": 29.99, - "tax": 2.99 - } -] +$ curl -X GET "http://127.0.0.1:8000/api/v1/items" +{ + "items": [ + { + "id": 1, + "name": "Test Item 1", + "description": null, + "price": 20.0, + "category": "test" + } + ], + "total": 1, + "limit": 20, + "offset": 0 +} ```
@@ -166,21 +171,24 @@ $ curl -X GET "http://127.0.0.1:8000/items/"
```console -$ curl -X POST "http://127.0.0.1:8000/items/" \ +$ curl -i -X POST "http://127.0.0.1:8000/api/v1/items" \ -H "Content-Type: application/json" \ -d '{ "name": "Keyboard", "description": "Mechanical keyboard", "price": 150.00, - "tax": 15.00 + "category": "peripherals" }' +HTTP/1.1 201 Created +location: http://127.0.0.1:8000/api/v1/items/2 + { - "id": 3, + "id": 2, "name": "Keyboard", "description": "Mechanical keyboard", "price": 150.0, - "tax": 15.0 + "category": "peripherals" } ``` @@ -191,13 +199,13 @@ $ curl -X POST "http://127.0.0.1:8000/items/" \
```console -$ curl -X GET "http://127.0.0.1:8000/items/1" +$ curl -X GET "http://127.0.0.1:8000/api/v1/items/1" { "id": 1, - "name": "Laptop", - "description": "High-performance laptop", - "price": 999.99, - "tax": 99.99 + "name": "Test Item 1", + "description": null, + "price": 20.0, + "category": "test" } ``` @@ -216,7 +224,7 @@ What you can do with Swagger UI: ### How to Use Swagger UI -1. Click on the `/items/` GET endpoint +1. Click on the `/api/v1/items` GET endpoint 2. Click the "Try it out" button 3. Click the "Execute" button 4. View the server response @@ -227,71 +235,71 @@ What you can do with Swagger UI: ```python from fastapi import FastAPI +from starlette.middleware.cors import CORSMiddleware + from src.api.api import api_router from src.core.config import settings -app = FastAPI( - title=settings.PROJECT_NAME, - version=settings.VERSION, - description=settings.DESCRIPTION, -) +app = FastAPI(title=settings.PROJECT_NAME) + +# CORS only for the origins in BACKEND_CORS_ORIGINS +if settings.all_cors_origins: + app.add_middleware( + CORSMiddleware, + allow_origins=settings.all_cors_origins, + allow_credentials="*" not in settings.all_cors_origins, + allow_methods=["*"], + allow_headers=["*"], + ) + +# fastkit:routes +app.include_router(api_router, prefix=settings.API_V1_PREFIX) -app.include_router(api_router) -@app.get("/") -def read_root(): - return {"message": "Hello World"} +@app.get("/health", tags=["health"]) +async def health_check() -> dict[str, str]: + return {"status": "ok"} ``` ### Item Schema (`src/schemas/items.py`) ```python -from pydantic import BaseModel -from typing import Optional +from pydantic import BaseModel, ConfigDict, Field + class ItemBase(BaseModel): - name: str - description: Optional[str] = None - price: float - tax: Optional[float] = None + name: str = Field(min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=1000) + price: float = Field(ge=0) + category: str = Field(min_length=1, max_length=50) + class ItemCreate(ItemBase): - pass + """POST and PUT body: every required field must be sent.""" -class ItemUpdate(ItemBase): - name: Optional[str] = None - price: Optional[float] = None -class Item(ItemBase): - id: int - - class Config: - from_attributes = True -``` +class ItemUpdate(BaseModel): + """PATCH body: send only the fields to change.""" -### CRUD Logic (`src/crud/items.py`) + name: str | None = Field(default=None, min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=1000) + price: float | None = Field(default=None, ge=0) + category: str | None = Field(default=None, min_length=1, max_length=50) -```python -from typing import List, Optional -from src.schemas.items import Item, ItemCreate, ItemUpdate -class ItemCRUD: - def __init__(self): - self.items: List[Item] = [] - self.next_id = 1 +class ItemRead(ItemBase): + model_config = ConfigDict(from_attributes=True) - def create_item(self, item: ItemCreate) -> Item: - new_item = Item(id=self.next_id, **item.dict()) - self.items.append(new_item) - self.next_id += 1 - return new_item + id: int +``` - def get_items(self) -> List[Item]: - return self.items +### CRUD Logic (`src/crud/items.py`) - def get_item(self, item_id: int) -> Optional[Item]: - return next((item for item in self.items if item.id == item_id), None) -``` +`ItemStore` keeps the items in `src/mocks/mock_items.json`. It exposes +`list_page(offset, limit)`, `get`, `create`, `replace`, `update` and +`delete`, serialises access with a lock, never reuses an id, and writes the +file atomically. The routes receive it through the `ItemStoreDep` dependency +from `src/api/deps.py`, which the tests override with a temporary file. ## Step 7: Expanding the Project @@ -302,46 +310,52 @@ You can add new endpoints using the `fastkit addroute` command:
```console -$ fastkit addroute user +$ fastkit addroute users Adding New Route ┌──────────────────┬──────────────────────────────────────────┐ │ Project │ my-first-api │ -│ Route Name │ user │ -│ Target Directory │ /path/to/my-first-api │ +│ Route Name │ users │ +│ Layout │ classic-layer │ +│ Path │ /users │ +│ Entity │ User │ +│ Schemas │ UserCreate, UserUpdate, UserRead │ └──────────────────┴──────────────────────────────────────────┘ -Do you want to add route 'user' to the current project? [Y/n]: y +Do you want to add route 'users' to the current project? [Y/n]: y -✨ Successfully added new route 'user' to the current project! +✨ Successfully added new route 'users' to the current project! ```
This command creates the following files: -- `src/api/routes/user.py` - User-related endpoints -- `src/schemas/user.py` - User data models -- `src/crud/user.py` - User data processing logic +- `src/api/routes/users.py` - CRUD endpoints under `/api/v1/users` +- `src/schemas/users.py` - `UserCreate`, `UserUpdate`, `UserRead` +- `src/crud/users.py` - In-memory repository +- `tests/test_users.py` - Tests for the new endpoints ### Customizing Environment Configuration You can modify the `src/core/config.py` file to change project settings: ```python -from pydantic_settings import BaseSettings - class Settings(BaseSettings): - PROJECT_NAME: str = "My First API" - VERSION: str = "1.0.0" - DESCRIPTION: str = "My first FastAPI server" - API_V1_STR: str = "/api/v1" + model_config = SettingsConfigDict(env_file=".env", env_ignore_empty=True, extra="ignore") - class Config: - env_file = ".env" + PROJECT_NAME: str = "my-first-api" + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + SECRET_KEY: str = secrets.token_urlsafe(32) + API_V1_PREFIX: str = "/api/v1" + BACKEND_CORS_ORIGINS: CorsOrigins = [] settings = Settings() ``` +With any `ENVIRONMENT` other than `development` (`staging`, `production`), the +app refuses to start unless `SECRET_KEY` is set explicitly to a non-example +value of at least 32 bytes. + ## Step 8: Running Tests The project includes basic tests: @@ -351,18 +365,18 @@ The project includes basic tests: ```console $ pytest tests/ -v ======================== test session starts ======================== -collected 4 items - -tests/test_items.py::test_create_item PASSED [ 25%] -tests/test_items.py::test_read_items PASSED [ 50%] -tests/test_items.py::test_read_item PASSED [ 75%] -tests/test_items.py::test_update_item PASSED [100%] - -======================== 4 passed in 0.15s ======================== +tests/test_items.py::test_list_items_returns_a_page PASSED +tests/test_items.py::test_create_item_returns_201_and_location PASSED +tests/test_items.py::test_put_replaces_the_whole_item PASSED +tests/test_items.py::test_delete_item_returns_204 PASSED +... ```
+The tests run against a temporary copy of the item data, so the shipped +`mock_items.json` is never modified. + ## Next Steps You've completed building a basic API server! Next things to try: diff --git a/docs/en/tutorial/custom-response-handling.md b/docs/en/tutorial/custom-response-handling.md index 7a5e008..3b6e477 100644 --- a/docs/en/tutorial/custom-response-handling.md +++ b/docs/en/tutorial/custom-response-handling.md @@ -126,6 +126,32 @@ advanced-api-server/ └── test_responses.py # Response format tests ``` +!!! note "What the template ships" + Steps 3 to 8 build a richer response system than the template ships, as an + example. The generated project has `src/schemas/base.py` (the envelope + models), `src/helper/responses.py` (`success_response`), + `src/helper/exceptions.py` (the error handlers) and `src/core/pagination.py` + (the `Page` model); there is no `src/helper/pagination.py`. Its items API + is served at `/api/v1/items`, lists take `limit` (1-100, default 20) and + `offset`, POST returns 201 with a `Location` header, and DELETE returns + 204 with no body. Every other response, errors included, uses one + envelope: + + ```console + $ curl "http://localhost:8000/api/v1/items?limit=1" + {"timestamp": "2026-01-01T12:00:00.000Z", "status": 200, "code": "HTTP-200", + "path": "/api/v1/items", + "message": {"items": [...], "total": 3, "limit": 1, "offset": 0}} + + $ curl "http://localhost:8000/api/v1/items/999" + {"timestamp": "2026-01-01T12:00:00.000Z", "status": 404, "code": "DATA-002", + "path": "/api/v1/items/999", "message": "Item not found"} + ``` + + Validation errors (422) list the invalid fields in `message`, and a 500 + never contains exception text. `GET /health` returns `{"status": "ok"}` + without the envelope. + ## Step 3: Implementing Standardized Response Schemas ### Base Response Schema (`src/schemas/base.py`) @@ -1312,7 +1338,7 @@ $ fastkit runserver Starting FastAPI server at 127.0.0.1:8000... # Custom response format test -$ curl -X POST "http://localhost:8000/api/v1/items/" \ +$ curl -X POST "http://localhost:8000/api/v1/items" \ -H "Content-Type: application/json" \ -d '{ "name": "Advanced notebook", @@ -1338,7 +1364,7 @@ $ curl -X POST "http://localhost:8000/api/v1/items/" \ } # Pagination and filtering test -$ curl "http://localhost:8000/api/v1/items/?page=1&size=10&search=notebook&sort_by=price&sort_order=desc" +$ curl "http://localhost:8000/api/v1/items?page=1&size=10&search=notebook&sort_by=price&sort_order=desc" # Advanced search test $ curl "http://localhost:8000/api/v1/items/search/advanced?q=notebook&fields=name&fields=description&exact_match=false" diff --git a/docs/en/tutorial/database-integration.md b/docs/en/tutorial/database-integration.md index 9afb0bb..c016a49 100644 --- a/docs/en/tutorial/database-integration.md +++ b/docs/en/tutorial/database-integration.md @@ -117,6 +117,19 @@ todo-postgres-api/ 3. **asyncpg**: Asynchronous PostgreSQL driver 4. **Docker Compose**: Development environment containerization +!!! note "What the template ships" + The listings in Steps 3 to 6 and Step 11 show one way to extend the + project; the generated code differs in detail. The generated + `fastapi-psql-orm` project serves the items API at `/api/v1/items` + (`API_V1_PREFIX`), paginates the list with `limit` (1-100, default 20) and + `offset` and returns `{"items", "total", "limit", "offset"}`, answers + `GET /health` (process up) and `GET /ready` (database reachable, 503 + otherwise), keeps the SQLAlchemy model in `src/models/items.py` and the + `ItemCreate` / `ItemUpdate` / `ItemRead` schemas in `src/schemas/items.py`. + Alembic owns the schema (`alembic upgrade head` applies both shipped + revisions), and the tests use a separate database, `_test` + on the same server or `TEST_DATABASE_URL`. + ## Step 3: Understanding Database Configuration ### Database Connection Setup (`src/core/db.py`) @@ -627,7 +640,7 @@ def downgrade(): ```console # Create new item -$ curl -X POST "http://localhost:8000/items/" \ +$ curl -X POST "http://localhost:8000/api/v1/items" \ -H "Content-Type: application/json" \ -d '{ "name": "MacBook Pro", @@ -648,16 +661,16 @@ $ curl -X POST "http://localhost:8000/items/" \ } # Get item list -$ curl "http://localhost:8000/items/" +$ curl "http://localhost:8000/api/v1/items" # Get item list with pagination -$ curl "http://localhost:8000/items/?skip=0&limit=10" +$ curl "http://localhost:8000/api/v1/items?offset=0&limit=10" # Search item -$ curl "http://localhost:8000/items/search?q=MacBook" +$ curl "http://localhost:8000/api/v1/items/search?q=MacBook" # Get item count -$ curl "http://localhost:8000/items/count" +$ curl "http://localhost:8000/api/v1/items/count" {"total": 1} ``` @@ -669,10 +682,10 @@ $ curl "http://localhost:8000/items/count" ```console # Get item list with inactive items -$ curl "http://localhost:8000/items/?active_only=false" +$ curl "http://localhost:8000/api/v1/items?active_only=false" # Update item -$ curl -X PUT "http://localhost:8000/items/1" \ +$ curl -X PUT "http://localhost:8000/api/v1/items/1" \ -H "Content-Type: application/json" \ -d '{ "price": 2300000, @@ -680,10 +693,10 @@ $ curl -X PUT "http://localhost:8000/items/1" \ }' # Soft delete item -$ curl -X DELETE "http://localhost:8000/items/1" +$ curl -X DELETE "http://localhost:8000/api/v1/items/1" # Hard delete item -$ curl -X DELETE "http://localhost:8000/items/1?hard_delete=true" +$ curl -X DELETE "http://localhost:8000/api/v1/items/1?hard_delete=true" ```
@@ -852,7 +865,7 @@ async def test_create_and_read_item(client: AsyncClient): "tax": 5000 } - response = await client.post("/items/", json=item_data) + response = await client.post("/api/v1/items", json=item_data) assert response.status_code == 201 created_item = response.json() @@ -862,7 +875,7 @@ async def test_create_and_read_item(client: AsyncClient): # Get created item item_id = created_item["id"] - response = await client.get(f"/items/{item_id}") + response = await client.get(f"/api/v1/items/{item_id}") assert response.status_code == 200 retrieved_item = response.json() @@ -880,21 +893,22 @@ async def test_item_pagination(client: AsyncClient): "price": i * 1000, "tax": i * 100 } - await client.post("/items/", json=item_data) + await client.post("/api/v1/items", json=item_data) # Get first page - response = await client.get("/items/?skip=0&limit=10") + response = await client.get("/api/v1/items?offset=0&limit=10") assert response.status_code == 200 - items = response.json() - assert len(items) == 10 + page = response.json() + assert page["total"] == 15 + assert len(page["items"]) == 10 # Get second page - response = await client.get("/items/?skip=10&limit=10") + response = await client.get("/api/v1/items?offset=10&limit=10") assert response.status_code == 200 - items = response.json() - assert len(items) == 5 + page = response.json() + assert len(page["items"]) == 5 @pytest.mark.asyncio async def test_item_search(client: AsyncClient): @@ -907,10 +921,10 @@ async def test_item_search(client: AsyncClient): ] for item in items: - await client.post("/items/", json=item) + await client.post("/api/v1/items", json=item) # Search "iPhone" - response = await client.get("/items/search?q=iPhone") + response = await client.get("/api/v1/items/search?q=iPhone") assert response.status_code == 200 results = response.json() @@ -918,7 +932,7 @@ async def test_item_search(client: AsyncClient): assert results[0]["name"] == "iPhone 15" # Search "smartphone" (description) - response = await client.get("/items/search?q=smartphone") + response = await client.get("/api/v1/items/search?q=smartphone") assert response.status_code == 200 results = response.json() diff --git a/docs/en/tutorial/docker-deployment.md b/docs/en/tutorial/docker-deployment.md index 6507afe..6fb85ea 100644 --- a/docs/en/tutorial/docker-deployment.md +++ b/docs/en/tutorial/docker-deployment.md @@ -90,6 +90,29 @@ dockerized-todo-api/ └── requirements.txt # Python dependencies ``` +!!! note "What the template ships" + The generated `fastapi-dockerized` project contains a single-stage + `Dockerfile` and a `.dockerignore`; the compose files, scripts and Nginx + configuration below are an example of how to grow it. The shipped image + runs uvicorn as a non-root user, copies only `pyproject.toml` and `src/` + (never `.env`), sets `ENVIRONMENT=production`, and checks `GET /health`. + Because staging and production refuse a missing, example or short + `SECRET_KEY`, pass + the settings at run time: + + ```console + $ docker build -t dockerized-todo-api . + $ docker run -p 8000:8000 --env-file .env dockerized-todo-api + $ curl http://localhost:8000/health + {"status":"ok"} + $ curl http://localhost:8000/api/v1/items + {"items":[...],"total":1,"limit":20,"offset":0} + ``` + + fastkit's own convention keeps `GET /health` free of database checks and + uses `GET /ready` for them; the extended health endpoint in Step 4 is an + optional addition. + ### Dockerfile Analysis ```dockerfile diff --git a/docs/en/tutorial/domain-starter.md b/docs/en/tutorial/domain-starter.md index 3c49888..a6294e5 100644 --- a/docs/en/tutorial/domain-starter.md +++ b/docs/en/tutorial/domain-starter.md @@ -69,20 +69,22 @@ orders-api/ │ ├── main.py # FastAPI() + middleware + api_router include │ ├── core/ # cross-cutting configuration │ │ ├── __init__.py -│ │ └── config.py # pydantic-settings (PROJECT_NAME, CORS, ...) +│ │ ├── config.py # pydantic-settings (PROJECT_NAME, CORS, ...) +│ │ ├── pagination.py # Page[T] envelope, limit/offset parameters +│ │ └── responses.py # documented error responses │ ├── db/ # persistence abstractions │ │ ├── __init__.py │ │ └── memory.py # InMemoryStore[T] generic key-value store │ ├── api/ # transport-level routing │ │ ├── __init__.py -│ │ ├── health.py # GET /health -│ │ └── router.py # aggregates health + every domain router +│ │ ├── health.py # GET /health (root level) +│ │ └── router.py # aggregates every domain router (under /api/v1) │ └── domains/ # business concepts (one folder each) │ ├── __init__.py │ └── items/ # the example domain │ ├── __init__.py │ ├── models.py # @dataclass Item (entity) -│ ├── schemas.py # ItemCreate, ItemRead (pydantic) +│ ├── schemas.py # ItemCreate, ItemUpdate, ItemRead (pydantic) │ ├── repository.py # ItemRepository over InMemoryStore │ ├── service.py # ItemService + ItemNotFoundError │ └── router.py # APIRouter endpoints @@ -90,7 +92,8 @@ orders-api/ ├── __init__.py ├── conftest.py # TestClient fixture, store reset ├── test_health.py - └── test_items.py + ├── test_items.py + └── ... ``` The two ideas to internalize: @@ -126,8 +129,9 @@ settings = Settings() `settings.all_cors_origins` to wire the FastAPI app. The shipped code does not read `SECRET_KEY`; it is there for signing -features you add. With `ENVIRONMENT=production` the app refuses to start -while it is an example value such as `changethis`. +features you add. With any `ENVIRONMENT` other than `development` (`staging`, +`production`) the app refuses to start while it is missing, an example value +such as `changethis`, or shorter than 32 bytes. **When to add to `core/`:** anything not specific to one domain — global settings, structured logging, custom middleware, security helpers, etc. @@ -160,20 +164,21 @@ domain repositories don't have to change their internal contract. Two pieces: - `health.py` — a small `APIRouter` exposing `GET /health` returning - `{"status": "ok"}`. Side-effect-free, ideal for liveness probes. -- `router.py` — the **top-level aggregator**. It includes the health - router and every domain's router, and that single combined - `api_router` is mounted on the FastAPI app under `/api/v1`: + `{"status": "ok"}`. Side-effect-free, ideal for liveness probes. It is + mounted at the root, not under `/api/v1`. +- `router.py` — the **top-level aggregator**. It includes every domain's + router, and that single combined `api_router` is mounted on the FastAPI + app under `/api/v1`. Each domain router carries its own prefix and tag: ```python # src/app/api/router.py api_router = APIRouter() -api_router.include_router(health.router) -api_router.include_router(items_router.router, prefix="/items", tags=["items"]) +api_router.include_router(items_router.router) # APIRouter(prefix="/items", tags=["items"]) ``` ```python # src/app/main.py +app.include_router(health.router) app.include_router(api_router, prefix=settings.API_V1_PREFIX) ``` @@ -203,10 +208,10 @@ service. Mirrors the runtime layout — one test module per surface that has behavior worth pinning. The starter ships: -- `conftest.py` — autouse fixture that resets the items store and calls - `service.reset_store()` for generated domains between tests, plus a `client` - fixture wrapping `TestClient(app)`. -- `test_health.py` — verifies `GET /api/v1/health` returns 200 + +- `conftest.py` — autouse fixture that calls `service.reset_store()` of + every domain package between tests, plus a `client` fixture wrapping + `TestClient(app)`. +- `test_health.py` — verifies `GET /health` returns 200 + `{"status": "ok"}`. - `test_items.py` — full CRUD coverage of the items endpoints, including a 404 for unknown ids and a 422 for an invalid payload. @@ -236,11 +241,16 @@ add server-controlled fields (`id`) and validation (price ≥ 0): ```python # src/app/domains/items/schemas.py -class ItemCreate(BaseModel): +class ItemCreate(BaseModel): # POST and PUT body name: str = Field(min_length=1, max_length=120) price: float = Field(ge=0) in_stock: bool = True +class ItemUpdate(BaseModel): # PATCH body: every field optional, null rejected + name: str | None = Field(default=None, min_length=1, max_length=120) + price: float | None = Field(default=None, ge=0) + in_stock: bool | None = None + class ItemRead(BaseModel): id: int name: str @@ -262,7 +272,7 @@ class ItemRepository: new_id = self._store.add(item) item.id = new_id return item - # list_all / get / replace / delete / reset elided + # list_page / count / get / replace / update / delete / reset elided ``` The service layer is where business rules accumulate. Today it's a @@ -271,7 +281,7 @@ policy lives ("can't delete an item that's in an open order", etc.): ```python # src/app/domains/items/service.py -class ItemNotFoundError(Exception): ... +class ItemNotFoundError(Exception): ... # message: "Item not found" class ItemService: def __init__(self, repository: Optional[ItemRepository] = None) -> None: @@ -280,47 +290,43 @@ class ItemService: def get_item(self, item_id: int) -> Item: item = self._repository.get(item_id) if item is None: - raise ItemNotFoundError(f"Item {item_id} does not exist") + raise ItemNotFoundError(item_id) return item - # list_items / create_item / replace_item / delete_item elided + # list_page / count / create_item / replace_item / update_item / delete_item elided ``` The router is the only piece that knows about HTTP. Notice it takes the -service as a FastAPI `Depends(...)` so tests can override it, and it -maps `ItemNotFoundError` → `HTTPException(404)`: +service through a dependency (`ItemServiceDep`) so tests can override it, +and it maps `ItemNotFoundError` → `HTTPException(404)`: ```python # src/app/domains/items/router.py -router = APIRouter() +router = APIRouter(prefix="/items", tags=["items"]) def get_item_service() -> ItemService: return ItemService() -@router.get("/{item_id}", response_model=ItemRead) -def get_item(item_id: int, service: ItemService = Depends(get_item_service)) -> ItemRead: +ItemServiceDep = Annotated[ItemService, Depends(get_item_service)] + +@router.get("/{item_id}", responses=error_responses(404)) +def get_item(item_id: int, service: ItemServiceDep) -> ItemRead: try: return ItemRead.model_validate(service.get_item(item_id)) except ItemNotFoundError as exc: - raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) -``` - -The shared API router sets the domain prefix and tags: - -```python -# src/app/api/router.py -api_router.include_router(items_router.router, prefix="/items", tags=["items"]) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc ``` The full router exposes: | Method | Path | What it does | |---|---|---| -| `GET` | `/api/v1/items` | List items | +| `GET` | `/api/v1/items` | List items (`limit` 1-100, default 20; `offset`) | | `GET` | `/api/v1/items/{item_id}` | Read one | -| `POST` | `/api/v1/items` | Create (returns 201) | +| `POST` | `/api/v1/items` | Create (returns 201 with `Location`) | | `PUT` | `/api/v1/items/{item_id}` | Replace | +| `PATCH` | `/api/v1/items/{item_id}` | Update the fields sent | | `DELETE` | `/api/v1/items/{item_id}` | Delete (returns 204) | -| `GET` | `/api/v1/health` | Liveness probe | +| `GET` | `/health` | Liveness probe | Try it: @@ -331,10 +337,10 @@ $ curl -X POST http://127.0.0.1:8000/api/v1/items \ {"id":1,"name":"Mug","price":9.5,"in_stock":true} $ curl http://127.0.0.1:8000/api/v1/items -[{"id":1,"name":"Mug","price":9.5,"in_stock":true}] +{"items":[{"id":1,"name":"Mug","price":9.5,"in_stock":true}],"total":1,"limit":20,"offset":0} $ curl http://127.0.0.1:8000/api/v1/items/999 -{"detail":"Item 999 does not exist"} +{"detail":"Item not found"} ``` ## Step 5: Add your next domain @@ -357,41 +363,42 @@ $ fastkit addroute users . --layout=domain `--layout=classic-layer` generates the traditional `api/routes`, `crud`, and `schemas` structure. That is also the default for `classic-layered`, `minimal`, -`single-module`, and projects without preset or template metadata. An unknown -preset falls back to `classic-layer` with a warning. The option does not change the project's preset. +`single-module`, and projects without preset or template metadata and without +a `domains/` package. An unknown preset falls back to `classic-layer` with a +warning. The option does not change the project's preset. ### Generated domain ```text src/app/domains/users/ ├── __init__.py -├── models.py # Users with id and name -├── schemas.py # UsersCreate and UsersRead -├── repository.py # UsersRepository: typed, in-memory CRUD -├── service.py # UsersService and UsersNotFoundError -└── router.py # endpoints and get_users_service dependency +├── models.py # User with id, name and description +├── schemas.py # UserCreate, UserUpdate and UserRead +├── repository.py # UserRepository: typed, in-memory CRUD +├── service.py # UserService and UserNotFoundError +└── router.py # endpoints and get_user_service dependency +tests/test_users.py # tests for every endpoint ``` -The new domain uses PascalCase class names derived from the route name, so -there is no need to infer a singular name from `users`. Customize these files +Class names are the singular PascalCase form of the route name (`users` +becomes `User`); pass `--entity` to choose another. Customize these files to introduce the fields and behavior your business concept requires. -The router is registered automatically in `src/app/api/router.py` with -`prefix="/users"` and `tags=["users"]`. Domain routers use `APIRouter()` without -these settings. The existing application prefix is preserved, exposing these -endpoints: +The router carries `prefix="/users"` and `tags=["users"]` and is registered +automatically in `src/app/api/router.py`, which is mounted under `/api/v1`: | Method | Endpoint | Result | |--------|----------|--------| -| GET | `/api/v1/users` | List entities, 200 | -| GET | `/api/v1/users/{entity_id}` | Read entity, 200 or 404 | -| POST | `/api/v1/users` | Create entity, 201 | -| PUT | `/api/v1/users/{entity_id}` | Replace entity, 200 or 404 | -| DELETE | `/api/v1/users/{entity_id}` | Delete entity, empty 204 or 404 | +| GET | `/api/v1/users` | List entities, 200 with the page envelope | +| GET | `/api/v1/users/{user_id}` | Read entity, 200 or 404 | +| POST | `/api/v1/users` | Create entity, 201 with `Location` | +| PUT | `/api/v1/users/{user_id}` | Replace entity, 200 or 404 | +| PATCH | `/api/v1/users/{user_id}` | Update the fields sent, 200 or 404 | +| DELETE | `/api/v1/users/{user_id}` | Delete entity, empty 204 or 404 | -POST and PUT accept `{"name": "Alice"}`; `name` must have 1–120 characters. -The repository assigns an ID starting at 1. PUT preserves that ID. No PATCH -endpoint is generated. +POST and PUT accept `{"name": "Alice"}` plus an optional `description`; +`name` must have 1–120 characters. The repository assigns an ID starting at +1. PUT preserves that ID. The new repository is self-contained; it does not use the bundled items domain's `db.memory` store. Each explicit repository instance has independent @@ -400,43 +407,23 @@ and process. CRUD operations are protected by a lock. Data is lost on restart and is not shared between worker processes; replace the repository when you need durable storage. -### Add isolated tests +### Tests -The items-specific reset fixture does not reset the new domain. Override its -service dependency with a fresh repository for each test: - -```python -from src.app.domains.users.repository import UsersRepository -from src.app.domains.users.router import get_users_service -from src.app.domains.users.service import UsersService - -def test_create_user(client): - from src.app.main import app - - service = UsersService(repository=UsersRepository()) - app.dependency_overrides[get_users_service] = lambda: service - try: - response = client.post("/api/v1/users", json={"name": "Alice"}) - assert response.status_code == 201 - assert response.json() == {"id": 1, "name": "Alice"} - finally: - app.dependency_overrides.pop(get_users_service, None) -``` +`addroute` writes `tests/test_users.py`. The starter's autouse fixture calls +`service.reset_store()` of every domain, so the new domain starts empty in +each test. In older projects, add this call to the existing reset fixture, or +override `get_user_service` with a service on a fresh `UserRepository`. -Re-running `addroute` preserves existing domain files, creates missing files, -and avoids duplicate imports and registrations. Same-named classic modules -can coexist through import aliases. Generated packages re-export their modules, -and repositories expose `reset()` to clear data and restart IDs. The starter's -autouse fixture calls `service.reset_store()` for generated domains. In older -projects, add this call to the existing reset fixture or use isolated repositories -through dependency overrides. Check HTTP paths and methods yourself when -combining routers; the generator does not detect overlapping endpoints. +Running `addroute` again for a route that is already in place does nothing; +a route whose files exist but are not registered is refused. Check HTTP paths +and methods yourself when combining routers; the generator does not detect +overlapping endpoints. ## Step 6: Where to go next - The [Architecture Preset Matrix](../reference/preset-feature-matrix.md) - shows what `fastkit init --interactive` generates for each preset, - including which feature selections need manual wiring under + shows what `fastkit init --interactive` generates for each preset and how + each feature is wired into the template's `main.py` under `domain-starter`. - The [`fastapi-default` tutorial](basic-api-server.md) covers the layered alternative if you'd like to compare layouts before diff --git a/docs/en/tutorial/first-project.md b/docs/en/tutorial/first-project.md index 1a1b4ad..463cd08 100644 --- a/docs/en/tutorial/first-project.md +++ b/docs/en/tutorial/first-project.md @@ -549,14 +549,15 @@ from fastapi import APIRouter, HTTPException, status, Depends, Query from src.schemas.users import User, UserCreate, UserUpdate from src.crud.users import users_crud -router = APIRouter() +# addroute registers this router without a prefix, so it carries its own. +router = APIRouter(prefix="/users", tags=["users"]) # Helper function to get current user (simplified for tutorial) def get_current_user_id() -> int: # In a real app, this would verify JWT token and return user ID return 1 # For tutorial purposes -@router.get("/", response_model=List[User]) +@router.get("", response_model=List[User]) def read_users( skip: int = Query(0, ge=0), limit: int = Query(100, ge=1, le=100) @@ -565,7 +566,7 @@ def read_users( users = users_crud.get_all()[skip:skip + limit] return [User(**user.dict()) for user in users] -@router.post("/", response_model=User, status_code=status.HTTP_201_CREATED) +@router.post("", response_model=User, status_code=status.HTTP_201_CREATED) def create_user(user: UserCreate): """Register a new user""" try: @@ -662,12 +663,12 @@ from fastapi import APIRouter, HTTPException, status, Depends, Query from src.schemas.posts import Post, PostCreate, PostUpdate from src.crud.posts import posts_crud -router = APIRouter() +router = APIRouter(prefix="/posts", tags=["posts"]) def get_current_user_id() -> int: return 1 # Simplified for tutorial -@router.get("/", response_model=List[Post]) +@router.get("", response_model=List[Post]) def read_posts( skip: int = Query(0, ge=0), limit: int = Query(100, ge=1, le=100), @@ -680,7 +681,7 @@ def read_posts( posts = posts_crud.get_all(skip, limit) return posts -@router.post("/", response_model=Post, status_code=status.HTTP_201_CREATED) +@router.post("", response_model=Post, status_code=status.HTTP_201_CREATED) def create_post( post: PostCreate, current_user_id: int = Depends(get_current_user_id) @@ -749,12 +750,12 @@ from fastapi import APIRouter, HTTPException, status, Depends, Query from src.schemas.comments import Comment, CommentCreate, CommentUpdate from src.crud.comments import comments_crud -router = APIRouter() +router = APIRouter(prefix="/comments", tags=["comments"]) def get_current_user_id() -> int: return 1 # Simplified for tutorial -@router.get("/", response_model=List[Comment]) +@router.get("", response_model=List[Comment]) def read_comments( skip: int = Query(0, ge=0), limit: int = Query(100, ge=1, le=100) @@ -763,7 +764,7 @@ def read_comments( comments = comments_crud.get_all()[skip:skip + limit] return comments -@router.post("/", response_model=Comment, status_code=status.HTTP_201_CREATED) +@router.post("", response_model=Comment, status_code=status.HTTP_201_CREATED) def create_comment( comment: CommentCreate, current_user_id: int = Depends(get_current_user_id) @@ -856,7 +857,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000
```console -$ curl -X POST "http://127.0.0.1:8000/api/v1/users/" \ +$ curl -X POST "http://127.0.0.1:8000/api/v1/users" \ -H "Content-Type: application/json" \ -d '{ "email": "john@example.com", @@ -906,7 +907,7 @@ $ curl -X POST "http://127.0.0.1:8000/api/v1/users/login" \
```console -$ curl -X POST "http://127.0.0.1:8000/api/v1/posts/" \ +$ curl -X POST "http://127.0.0.1:8000/api/v1/posts" \ -H "Content-Type: application/json" \ -d '{ "title": "My First Blog Post", @@ -933,7 +934,7 @@ $ curl -X POST "http://127.0.0.1:8000/api/v1/posts/" \
```console -$ curl -X POST "http://127.0.0.1:8000/api/v1/comments/" \ +$ curl -X POST "http://127.0.0.1:8000/api/v1/comments" \ -H "Content-Type: application/json" \ -d '{ "content": "Great post! I learned a lot from this.", @@ -957,7 +958,7 @@ $ curl -X POST "http://127.0.0.1:8000/api/v1/comments/" \
```console -$ curl "http://127.0.0.1:8000/api/v1/posts/?search=FastAPI" +$ curl "http://127.0.0.1:8000/api/v1/posts?search=FastAPI" [ { @@ -982,7 +983,6 @@ Visit [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) to see your compl - **Users**: Registration, login, profile management - **Posts**: CRUD operations, search, author filtering - **Comments**: CRUD operations, post/author filtering -- **Items**: Original example endpoints The documentation shows: @@ -1010,7 +1010,7 @@ class TestUserAPI: "bio": "Test bio", "password": "testpassword123" } - response = client.post("/api/v1/users/", json=user_data) + response = client.post("/api/v1/users", json=user_data) assert response.status_code == 201 data = response.json() assert data["email"] == user_data["email"] @@ -1025,7 +1025,7 @@ class TestUserAPI: "username": "user1", "password": "password123" } - response1 = client.post("/api/v1/users/", json=user_data1) + response1 = client.post("/api/v1/users", json=user_data1) assert response1.status_code == 201 # Second user with same email @@ -1034,7 +1034,7 @@ class TestUserAPI: "username": "user2", "password": "password123" } - response2 = client.post("/api/v1/users/", json=user_data2) + response2 = client.post("/api/v1/users", json=user_data2) assert response2.status_code == 400 assert "Email already registered" in response2.json()["detail"] @@ -1045,7 +1045,7 @@ class TestUserAPI: "username": "loginuser", "password": "loginpassword123" } - client.post("/api/v1/users/", json=user_data) + client.post("/api/v1/users", json=user_data) # Test login login_data = { @@ -1065,7 +1065,7 @@ class TestPostAPI: "content": "This is a test post content", "published": True } - response = client.post("/api/v1/posts/", json=post_data) + response = client.post("/api/v1/posts", json=post_data) assert response.status_code == 201 data = response.json() assert data["title"] == post_data["title"] @@ -1074,7 +1074,7 @@ class TestPostAPI: assert "author_id" in data def test_read_posts(self): - response = client.get("/api/v1/posts/") + response = client.get("/api/v1/posts") assert response.status_code == 200 data = response.json() assert isinstance(data, list) @@ -1086,10 +1086,10 @@ class TestPostAPI: "content": "Learn how to build APIs with FastAPI", "published": True } - client.post("/api/v1/posts/", json=post_data) + client.post("/api/v1/posts", json=post_data) # Search for the post - response = client.get("/api/v1/posts/?search=FastAPI") + response = client.get("/api/v1/posts?search=FastAPI") assert response.status_code == 200 data = response.json() assert len(data) > 0 @@ -1103,7 +1103,7 @@ class TestCommentAPI: "content": "This post will receive comments", "published": True } - post_response = client.post("/api/v1/posts/", json=post_data) + post_response = client.post("/api/v1/posts", json=post_data) post_id = post_response.json()["id"] # Create comment @@ -1111,7 +1111,7 @@ class TestCommentAPI: "content": "This is a test comment", "post_id": post_id } - response = client.post("/api/v1/comments/", json=comment_data) + response = client.post("/api/v1/comments", json=comment_data) assert response.status_code == 201 data = response.json() assert data["content"] == comment_data["content"] @@ -1124,14 +1124,14 @@ class TestCommentAPI: "content": "This post has comments", "published": True } - post_response = client.post("/api/v1/posts/", json=post_data) + post_response = client.post("/api/v1/posts", json=post_data) post_id = post_response.json()["id"] comment_data = { "content": "Comment on post", "post_id": post_id } - client.post("/api/v1/comments/", json=comment_data) + client.post("/api/v1/comments", json=comment_data) # Get comments for the post response = client.get(f"/api/v1/comments/post/{post_id}") diff --git a/docs/en/tutorial/getting-started.md b/docs/en/tutorial/getting-started.md index 1b147dd..5165038 100644 --- a/docs/en/tutorial/getting-started.md +++ b/docs/en/tutorial/getting-started.md @@ -150,8 +150,7 @@ drwxr-xr-x 3 user user 96 Dec 7 10:30 .. drwxr-xr-x 5 user user 160 Dec 7 10:30 .venv -rw-r--r-- 1 user user 156 Dec 7 10:30 README.md -rw-r--r-- 1 user user 243 Dec 7 10:30 requirements.txt -drwxr-xr-x 3 user user 96 Dec 7 10:30 scripts --rw-r--r-- 1 user user 1245 Dec 7 10:30 setup.py +-rw-r--r-- 1 user user 1245 Dec 7 10:30 pyproject.toml drwxr-xr-x 8 user user 256 Dec 7 10:30 src drwxr-xr-x 3 user user 96 Dec 7 10:30 tests ``` @@ -204,7 +203,7 @@ Open your web browser and visit: You should see: ```json -{"message": "Hello World"} +{"message": "Welcome to my-first-api", "docs": "/docs"} ``` ### Method 2: Interactive API Documentation @@ -229,19 +228,10 @@ Open a new terminal (keep the server running) and test with curl: ```console $ curl http://127.0.0.1:8000 -{"message":"Hello World"} +{"message":"Welcome to my-first-api","docs":"/docs"} -$ curl http://127.0.0.1:8000/api/v1/items/ -[] - -$ curl -X POST "http://127.0.0.1:8000/api/v1/items/" \ - -H "Content-Type: application/json" \ - -d '{"title": "My First Item", "description": "This is a test item"}' -{ - "id": 1, - "title": "My First Item", - "description": "This is a test item" -} +$ curl http://127.0.0.1:8000/health +{"status":"ok"} ```
@@ -257,24 +247,11 @@ $ tree src src/ ├── __init__.py ├── main.py # FastAPI application entry point -├── core/ -│ ├── __init__.py -│ └── config.py # Application configuration -├── api/ -│ ├── __init__.py -│ ├── api.py # Main API router -│ └── routes/ -│ ├── __init__.py -│ └── items.py # Items API endpoints -├── crud/ -│ ├── __init__.py -│ └── items.py # Business logic for items -├── schemas/ -│ ├── __init__.py -│ └── items.py # Data validation schemas -└── mocks/ +└── core/ ├── __init__.py - └── mock_items.json # Sample data + ├── config.py # Application configuration (reads .env) + ├── pagination.py # Page envelope for list endpoints + └── responses.py # Documented error responses ```
@@ -284,57 +261,40 @@ src/ **`src/main.py`** - The heart of your application: ```python from fastapi import FastAPI -from src.api.api import api_router + from src.core.config import settings -app = FastAPI( - title=settings.PROJECT_NAME, - version=settings.VERSION, - openapi_url=f"{settings.API_V1_STR}/openapi.json" -) +app = FastAPI(title=settings.PROJECT_NAME) -app.include_router(api_router, prefix=settings.API_V1_STR) +# Mount business routers under the versioned prefix, for example: +# app.include_router(items_router, prefix=settings.API_V1_PREFIX) +# fastkit:routes -@app.get("/") -def read_root(): - return {"message": "Hello World"} + +@app.get("/", tags=["root"]) +async def root() -> dict[str, str]: + return {"message": f"Welcome to {settings.PROJECT_NAME}", "docs": "/docs"} + + +@app.get("/health", tags=["health"]) +async def health_check() -> dict[str, str]: + return {"status": "ok"} ``` **`src/core/config.py`** - Application settings: ```python -from pydantic_settings import BaseSettings - class Settings(BaseSettings): - PROJECT_NAME: str = "my-first-api" - VERSION: str = "1.0.0" - API_V1_STR: str = "/api/v1" + model_config = SettingsConfigDict(env_file=".env", env_ignore_empty=True, extra="ignore") - class Config: - env_file = ".env" + PROJECT_NAME: str = "my-first-api" + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + SECRET_KEY: str = secrets.token_urlsafe(32) + API_V1_PREFIX: str = "/api/v1" + BACKEND_CORS_ORIGINS: CorsOrigins = [] settings = Settings() ``` -**`src/api/routes/items.py`** - API endpoints: -```python -from typing import List -from fastapi import APIRouter, HTTPException -from src.schemas.items import Item, ItemCreate, ItemUpdate -from src.crud.items import items_crud - -router = APIRouter() - -@router.get("/", response_model=List[Item]) -def read_items(): - """Get all items""" - return items_crud.get_all() - -@router.post("/", response_model=Item) -def create_item(item: ItemCreate): - """Create a new item""" - return items_crud.create(item) -``` - ## Step 8: Add Your First Custom Route Let's add a new API route to practice what you've learned: @@ -359,33 +319,38 @@ Do you want to add route 'users' to project 'my-first-api'? [Y/n]: y The server will automatically restart and now you have new endpoints: -- `GET /api/v1/users/` - Get all users -- `POST /api/v1/users/` - Create a new user +- `GET /api/v1/users` - List users, one page at a time +- `POST /api/v1/users` - Create a new user (201) - `GET /api/v1/users/{user_id}` - Get a specific user -- And more... +- `PUT`, `PATCH` and `DELETE` on `/api/v1/users/{user_id}` ### Test Your New Route
```console -$ curl -X POST "http://127.0.0.1:8000/api/v1/users/" \ +$ curl -X POST "http://127.0.0.1:8000/api/v1/users" \ -H "Content-Type: application/json" \ - -d '{"title": "John Doe", "description": "Software Developer"}' + -d '{"name": "John Doe", "description": "Software Developer"}' { "id": 1, - "title": "John Doe", + "name": "John Doe", "description": "Software Developer" } -$ curl http://127.0.0.1:8000/api/v1/users/ -[ - { - "id": 1, - "title": "John Doe", - "description": "Software Developer" - } -] +$ curl http://127.0.0.1:8000/api/v1/users +{ + "items": [ + { + "id": 1, + "name": "John Doe", + "description": "Software Developer" + } + ], + "total": 1, + "limit": 20, + "offset": 0 +} ```
diff --git a/docs/en/tutorial/llm-agent.md b/docs/en/tutorial/llm-agent.md index 3b33fc1..9736a00 100644 --- a/docs/en/tutorial/llm-agent.md +++ b/docs/en/tutorial/llm-agent.md @@ -89,7 +89,7 @@ support-agent/ │ └── api/ │ ├── router.py # aggregates health + chat │ ├── deps.py # store / agent dependencies -│ ├── health.py # GET /health +│ ├── health.py # GET /health (root level) │ └── chat.py # POST /chat (SSE), conversation history └── tests/ ├── conftest.py # scripted fake Anthropic client @@ -106,14 +106,17 @@ one file). | Method | Endpoint | Description | |--------|------------------------------|-------------------------| -| GET | `/api/v1/health` | Liveness probe | -| POST | `/api/v1/chat` | Stream a reply as SSE | +| GET | `/health` | Liveness probe | +| POST | `/api/v1/chat` | Stream a reply as SSE (`text/event-stream`, declared in OpenAPI) | | GET | `/api/v1/conversations/{id}` | Read stored history | -| DELETE | `/api/v1/conversations/{id}` | Forget a conversation | +| DELETE | `/api/v1/conversations/{id}` | Forget a conversation (204) | `POST /api/v1/chat` takes `{"message": "...", "conversation_id": "..."}`. -Omit `conversation_id` to start a new conversation and read the assigned -id back from the final `done` event. +Omit `conversation_id` to start a new conversation; the server generates +the id and sends it in the final `done` event. Send that id back to continue +the conversation. An id the server did not issue (or has since evicted) +returns 404, and a conversation that reached +`MAX_MESSAGES_PER_CONVERSATION` messages returns 409. ## Step 4: The stream protocol @@ -127,7 +130,7 @@ envelope in `data:`. A client has to handle five of them plus errors: | `tool_result` | `tool_name`, `tool_output` | The tool ran | | `usage` | `input_tokens`, `output_tokens` | Per-turn token spend | | `done` | `conversation_id` | The turn finished | -| `error` | `detail` | Something failed mid-stream | +| `error` | `detail` | Something failed mid-stream (a generic message; the exception is logged) | `tool_use` and `tool_result` are not decoration — they are what lets a UI show "searching…" instead of an unexplained pause while a tool runs. @@ -179,7 +182,9 @@ misunderstands a tool result can bill you indefinitely. The `calculator` deserves a second look. It parses the expression with `ast` and walks only whitelisted node types, so a tool argument coming -from a model cannot execute arbitrary Python. Any tool that accepts +from a model cannot execute arbitrary Python. It also bounds the +expression length, nesting depth, exponents and result size, so a crafted +expression cannot exhaust CPU or memory. Any tool that accepts model-generated input needs the same discipline: **model output is untrusted input.** @@ -205,8 +210,10 @@ Two things to get right: ## Step 7: Conversation memory `ConversationStore` (`src/app/memory/base.py`) is the interface; the -bundled `in_memory.py` implements it with a dict. That is fine for a -single process and wrong for anything else — a restart forgets +bundled `in_memory.py` implements it with a dict bounded by +`MAX_CONVERSATIONS` (the least recently used conversation is evicted) and +`MAX_MESSAGES_PER_CONVERSATION`. That is fine for a single process and +wrong for anything else — a restart forgets everything, and two workers disagree about history. To make it real: implement the same interface against Redis or a @@ -239,10 +246,12 @@ suite that still cannot assert what the model will say. Testing the natural seam is `ChatAgent.stream`: fetch context before the first request and prepend it to the system prompt, or expose your index as one more tool and let the model decide when to search. -- **Auth and rate limiting** — `POST /chat` is unauthenticated as - shipped. Put a dependency on the router before exposing it publicly; - the [JWT Authentication tutorial](auth-jwt.md) has the guards you - would reuse. +- **Auth and rate limiting** — the chat endpoints are unauthenticated as + shipped. `src/app/api/deps.py` has two hook points that run before them, + `authorize_chat` and `limit_chat_rate`; both let every request through + until you implement them. Do that before exposing the API publicly; the + [JWT Authentication tutorial](auth-jwt.md) has the guards you would + reuse. ## Recap diff --git a/docs/en/tutorial/mcp-integration.md b/docs/en/tutorial/mcp-integration.md index b232efc..647d87c 100644 --- a/docs/en/tutorial/mcp-integration.md +++ b/docs/en/tutorial/mcp-integration.md @@ -86,17 +86,27 @@ Do you want to proceed with project creation? [y/N]: y The generated `fastapi-mcp` project already applies these defaults (its `README.md` has the details): - - The MCP endpoint requires `Authorization: Bearer ` when - `MCP_API_KEY` is set, and a JWT access token from - `/api/v1/auth/login` otherwise. It is never open. + - The MCP endpoint requires the key in `X-MCP-API-Key` (or + `Authorization: Bearer `) when `MCP_API_KEY` is set, and + a JWT access token from `POST /api/v1/auth/token` otherwise. It is + never open. Sending the key in `X-MCP-API-Key` keeps `Authorization` + free for a user's token, so write tools act as that user. - The demo users (`user1`, `user2`, `admin`) exist only with `ENABLE_DEMO_USERS=true`. - - With `ENVIRONMENT=production` the app refuses to start with a missing - or example `SECRET_KEY`, or with `ENABLE_DEMO_USERS=true`. + - With any `ENVIRONMENT` other than `development` (`staging`, + `production`) the app refuses to start with a missing, + example or shorter than 32-byte `SECRET_KEY`, or with + `ENABLE_DEMO_USERS=true`. - `MCP_MOUNT_PATH` (default `/mcp`) sets where the MCP server is mounted. - In `MCP_API_KEY` mode, tools that call JWT-protected endpoints return - `401`. + The REST API lives under `/api/v1` (`API_V1_PREFIX`): `POST /auth/token` + (OAuth2 password form), `GET /users/me`, `GET /users` (superusers only, + paginated), the public reads `GET /items` and `GET /items/{item_id}`, the + authenticated writes `POST`, `PUT`, `PATCH` and `DELETE` on items, and + `GET /mcp-server`, which describes the MCP server. Only the six item + operations are exposed as MCP tools. Lists take `limit` and `offset` and + return `{"items", "total", "limit", "offset"}`. `GET /health` returns + `{"status": "ok"}`, and the OpenAPI schema is at `/openapi.json`. ## Step 2: Project Structure Analysis @@ -1479,9 +1489,9 @@ $ cd ai-integrated-api $ fastkit runserver Starting FastAPI server at 127.0.0.1:8000... -# User login (in a generated fastapi-mcp project, admin/admin123 needs -# ENABLE_DEMO_USERS=true) -$ curl -X POST "http://localhost:8000/auth/login" \ +# User login (in a generated fastapi-mcp project the endpoint is +# POST /api/v1/auth/token, and admin/admin123 needs ENABLE_DEMO_USERS=true) +$ curl -X POST "http://localhost:8000/api/v1/auth/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "username=admin&password=admin123" diff --git a/docs/en/tutorial/sqlmodel.md b/docs/en/tutorial/sqlmodel.md index b04517c..00bd2ad 100644 --- a/docs/en/tutorial/sqlmodel.md +++ b/docs/en/tutorial/sqlmodel.md @@ -10,7 +10,7 @@ to add your own domain. ## What you'll learn - Generating a project with `fastkit startdemo fastapi-sqlmodel` -- How `ItemBase` → `Item` / `ItemCreate` / `ItemUpdate` / `ItemPublic` +- How `ItemBase` → `Item` / `ItemCreate` / `ItemUpdate` / `ItemRead` removes schema duplication - What `CRUDBase` gives you for free and where to extend it - The `Page[T]` list envelope and where its limits are enforced @@ -62,35 +62,39 @@ catalog-api/ ├── src/ │ └── app/ │ ├── main.py # FastAPI app + lifespan -│ ├── core/config.py # pydantic-settings +│ ├── core/ +│ │ ├── config.py # pydantic-settings +│ │ ├── pagination.py # Page[T] envelope, limit/offset parameters +│ │ └── responses.py # documented error responses │ ├── db/ │ │ ├── session.py # async engine, get_session dependency -│ │ └── base.py # metadata aggregation for Alembic +│ │ ├── base.py # metadata aggregation for Alembic +│ │ └── types.py # timezone-aware UTC datetime column type │ ├── crud/ -│ │ ├── base.py # generic CRUDBase -│ │ └── pagination.py # Page[T] envelope +│ │ └── base.py # generic CRUDBase │ ├── alembic/ │ │ ├── env.py # async migration environment -│ │ └── versions/0001_create_items_table.py +│ │ └── versions/ # 0001_create_items_table, 0002_timezone_aware_created_at │ ├── api/ -│ │ ├── router.py # aggregates health + domain routers -│ │ └── health.py # GET /health +│ │ ├── router.py # aggregates domain routers (under /api/v1) +│ │ ├── deps.py # SessionDep +│ │ └── health.py # GET /health, GET /ready (root level) │ └── domains/items/ # the example domain -│ ├── models.py # Item table + Create/Update/Public schemas +│ ├── models.py # ItemBase and the Item table +│ ├── schemas.py # ItemCreate / ItemUpdate / ItemRead │ ├── crud.py # ItemCRUD(CRUDBase) │ └── router.py # FastAPI router └── tests/ - ├── conftest.py test_health.py test_items.py test_crud_base.py + ├── conftest.py test_health.py test_items.py test_crud_base.py ... ``` -Note what a domain folder does *not* contain: no `schemas.py` separate -from `models.py`, and no per-domain repository boilerplate. Both -disappear into SQLModel and `CRUDBase` respectively. +Note what a domain folder does *not* contain: no per-domain repository +boilerplate. That disappears into `CRUDBase`. ## Step 3: One model definition per concept -Open `src/app/domains/items/models.py`. Everything derives from a single -base: +Open `src/app/domains/items/models.py` and `schemas.py`. Everything +derives from a single base: ```python class ItemBase(SQLModel): @@ -104,10 +108,11 @@ class ItemBase(SQLModel): class Item(ItemBase, table=True): # the actual table __tablename__ = "items" id: int | None = Field(default=None, primary_key=True) - created_at: datetime = Field(default_factory=_utcnow) + created_at: datetime = Field(default_factory=_utcnow, sa_type=UTCDateTime) -class ItemCreate(ItemBase): ... # POST body — no server-assigned fields +# schemas.py +class ItemCreate(ItemBase): ... # POST and PUT body — no server-assigned fields class ItemUpdate(SQLModel): # PATCH body — every field optional @@ -115,7 +120,7 @@ class ItemUpdate(SQLModel): # PATCH body — every field optional ... -class ItemPublic(ItemBase): # response — base + server-assigned +class ItemRead(ItemBase): # response — base + server-assigned id: int created_at: datetime ``` @@ -126,9 +131,9 @@ Four classes, four distinct jobs, one place where the fields live: |--------------|-------------------------------|-------------------| | `ItemBase` | shared field definitions | the single source of truth | | `Item` | the database table | adds `id`, `created_at` | -| `ItemCreate` | request body for `POST` | must not accept `id` | +| `ItemCreate` | request body for `POST` and `PUT` | must not accept `id` | | `ItemUpdate` | request body for `PATCH` | every field optional | -| `ItemPublic` | response body | exposes server-assigned fields | +| `ItemRead` | response body | exposes server-assigned fields | **The payoff:** adding a `sku` column means adding one line to `ItemBase`. The table gets the column, the create body accepts it, and @@ -144,10 +149,11 @@ model and its two input schemas: ```python class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): async def get(self, session, obj_id) -> ModelType | None: ... - async def list(self, session, *, offset=0, limit=20) -> Sequence[ModelType]: ... + async def list_page(self, session, *, offset=0, limit=20) -> Sequence[ModelType]: ... async def count(self, session) -> int: ... async def create(self, session, obj_in) -> ModelType: ... - async def update(self, session, db_obj, obj_in) -> ModelType: ... + async def replace(self, session, db_obj, obj_in) -> ModelType: ... # PUT + async def update(self, session, db_obj, obj_in) -> ModelType: ... # PATCH async def delete(self, session, db_obj) -> None: ... ``` @@ -182,30 +188,30 @@ item_crud = ItemCRUD(Item) List endpoints return a `Page[T]` envelope rather than a bare array: ```json -{"items": [...], "total": 42, "offset": 0, "limit": 20} +{"items": [...], "total": 42, "limit": 20, "offset": 0} ``` -The clamping happens in the router, not in the client: +The bounds are declared on the parameters in `src/app/core/pagination.py`: ```python -limit: int = Query(default=settings.DEFAULT_PAGE_LIMIT, ge=1) -... -limit = min(limit, settings.MAX_PAGE_LIMIT) +LimitParam = Annotated[int, Query(ge=1, le=MAX_LIMIT)] # MAX_LIMIT = 100 +OffsetParam = Annotated[int, Query(ge=0)] ``` -So `?limit=100000` cannot turn one request into a full table scan. -`Page` also exposes a `has_next` property derived from `offset`, -`len(items)` and `total`, which is usually what a front end actually -wants. +So `?limit=100000` is rejected with 422 instead of turning one request into +a full table scan. A client knows there is a next page while +`offset + len(items) < total`. The endpoints the items domain ships: | Method | Endpoint | Description | |--------|---------------------------|--------------------------------| -| GET | `/api/v1/health` | Liveness probe | +| GET | `/health` | Liveness probe | +| GET | `/ready` | Database check, 200 or 503 | | GET | `/api/v1/items` | List items (`offset`, `limit`) | | GET | `/api/v1/items/{item_id}` | Read a single item | -| POST | `/api/v1/items` | Create an item (`201`) | +| POST | `/api/v1/items` | Create an item (`201` with `Location`) | +| PUT | `/api/v1/items/{item_id}` | Replace an item | | PATCH | `/api/v1/items/{item_id}` | Partially update an item | | DELETE | `/api/v1/items/{item_id}` | Delete an item (`204`) | @@ -230,9 +236,11 @@ async def get_session() -> AsyncGenerator[AsyncSession, None]: yield session ``` -Routers depend on it (`session: AsyncSession = Depends(get_session)`), -`CRUDBase` takes it as its first argument, and every database call is -awaited. Nothing in the request path blocks the event loop on I/O. +Routers depend on it through the `SessionDep` alias +(`Annotated[AsyncSession, Depends(get_session)]`), and the session never +commits on its own: `CRUDBase` commits each change. `CRUDBase` takes the +session as its first argument, +and every database call is awaited. Nothing in the request path blocks the event loop on I/O. `create_db_and_tables()` also lives here and is called from the app's `lifespan`. It is a convenience for the SQLite default and for tests — @@ -241,7 +249,7 @@ once Alembic owns the schema, set `CREATE_TABLES_ON_STARTUP=false`. ## Step 7: Adding a domain 1. Create `src/app/domains//` mirroring `items` - (`models.py`, `crud.py`, `router.py`). + (`models.py`, `schemas.py`, `crud.py`, `router.py`). 2. **Import the table model in `src/app/db/base.py`.** This is the step that is easy to forget and confusing to debug: Alembic autogenerate and `create_db_and_tables` only see models that have been imported, @@ -264,6 +272,10 @@ $ bash scripts/migrate.sh # upgrade head $ alembic revision --autogenerate -m "add sku to items" # after a model change ``` +`created_at` is stored timezone-aware (UTC). A database created by an older +version of the template needs the `0002_timezone_aware_created_at` revision: +run `bash scripts/migrate.sh`. + Switching databases is a URL change plus a driver: ```console @@ -295,7 +307,7 @@ that your own domains inherit. from it, so a new column is declared once. - **CRUD**: `CRUDBase` supplies get / list / count / create / update / delete; domains subclass it for their own queries. -- **Lists**: `Page[T]` envelope with server-side limit clamping. +- **Lists**: `Page[T]` envelope; `limit` is bounded to 1-100. - **Schema**: async Alembic; remember to import new models in `src/app/db/base.py`. - **Database**: SQLite by default, PostgreSQL by changing diff --git a/docs/en/user-guide/adding-routes.md b/docs/en/user-guide/adding-routes.md index ab1bf66..1e9c43a 100644 --- a/docs/en/user-guide/adding-routes.md +++ b/docs/en/user-guide/adding-routes.md @@ -9,9 +9,10 @@ it reads `[tool.fastapi-fastkit].preset`: `domain-starter` selects `domain`; `classic-layered`, `minimal`, and `single-module` select `classic-layer`. If `preset` is missing, it infers the preset from `template`, so projects created with `startdemo` or interactive `init` also select `domain` for -`fastapi-domain-starter`. Without either value, it selects `classic-layer`. An unknown preset falls back to `classic-layer` with -a warning. An explicit option overrides this selection without changing the -project's metadata. +`fastapi-domain-starter`. A project with a `domains/` package also selects +`domain`; otherwise `classic-layer` is used. An unknown preset falls back to +`classic-layer` with a warning. An explicit option overrides this selection +without changing the project's metadata. ```console $ cd my-api @@ -19,314 +20,135 @@ $ fastkit addroute users . --layout=domain $ fastkit addroute products . --layout=classic-layer ``` -The selected layout is displayed before confirmation. Files are placed under -the application's actual package (`src/` or `src/app/`), using its recorded -entrypoint when available. +The route name must be lower-case ASCII (letters, digits and underscores, +starting with a letter); it names the modules and the URL segment. Class +names are singular PascalCase (`users` becomes `User`); pass `--entity` to +choose another name (`fastkit addroute people . --entity Person`). -## Generate a domain CRUD +The selected layout, path, entity and schema names are displayed before +confirmation. Files are placed under the application's actual package (`src/` +or `src/app/`), using its recorded entrypoint when available. -For a `domain-starter` project, simply run: +## Preview the change -```console -$ fastkit addroute users -``` - -This creates the following files and registers the domain router automatically: - -```text -src/app/domains/users/ -├── __init__.py -├── models.py # Users(id: int, name: str) -├── schemas.py # UsersCreate for POST/PUT, UsersRead for responses -├── repository.py # typed CRUD operations and in-memory storage -├── service.py # business logic and UsersNotFoundError -└── router.py # HTTP endpoints and overridable service dependency -``` - -The classes are named `Users`, `UsersCreate`, `UsersRead`, `UsersRepository`, -and `UsersService` within each domain; class names use PascalCase (`health_checks` becomes `HealthChecks`), without singularization. -The repository assigns IDs starting at 1. POST and PUT require a `name` between -1 and 120 characters; PUT preserves the existing ID. - -| Method | Domain path | Result | -|--------|-------------|--------| -| GET | `/users` | List entities, 200 | -| GET | `/users/{entity_id}` | Read entity, 200 or 404 | -| POST | `/users` | Create entity, 201 | -| PUT | `/users/{entity_id}` | Replace entity, 200 or 404 | -| DELETE | `/users/{entity_id}` | Delete entity, empty 204 or 404 | - -The domain prefix and tags are set in the shared API router when it calls -`include_router`, as in the classic layout. - -The application's existing API prefix remains in effect (for example, -`/api/v1/users`). Domain routes do not include PATCH. - -The generated repository is self-contained and locks its CRUD operations. Its -default instance is shared between requests **within this domain and process**. -Data is lost on restart and is not shared between worker processes. Adapt the -repository for durable persistence; it has no dependency on the starter's -`db.memory`, ORM, or database configuration. - -For isolated tests, inject a fresh `UsersRepository` into `UsersService`, -then override the router's `get_users_service` FastAPI dependency. -`UsersRepository.reset()` clears that repository and restarts IDs at 1. -`service.reset_store()` resets the default repository shared between requests. -Explicitly created repository instances have independent storage. - -## Re-running the command - -Existing module files are preserved; missing files are created. Imports and -router registrations are not duplicated. Same-named modules in different layouts -can coexist; import aliases avoid Python name collisions. HTTP method/path -conflicts are not checked by the generator. `--layout` does not migrate existing -modules. - -## Basic Route Addition - -The following examples describe the `classic-layer` layout. Pass -`--layout=classic-layer` explicitly when using a domain-starter project. - -### Using the `addroute` Command - -FastAPI-fastkit's `addroute` command makes it easy to add new routes: - -
+`--dry-run` lists the files that would be created and modified and writes +nothing. `--diff` also prints a unified diff of each modified file and the +content of each new file. ```console -$ fastkit addroute users my-awesome-api - Adding New Route -┌──────────────────┬──────────────────────────────────────────┐ -│ Project │ my-awesome-api │ -│ Route Name │ users │ -│ Target Directory │ ~/my-awesome-api │ -└──────────────────┴──────────────────────────────────────────┘ - -Do you want to add route 'users' to project 'my-awesome-api'? [Y/n]: y - -╭──────────────────────── Info ────────────────────────╮ -│ ℹ Updated main.py to include the API router │ -╰──────────────────────────────────────────────────────╯ -╭─────────────────────── Success ───────────────────────╮ -│ ✨ Successfully added new route 'users' to project │ -│ `my-awesome-api` │ -╰───────────────────────────────────────────────────────╯ +$ fastkit addroute orders . --dry-run +Files to create (4): + + src/api/routes/orders.py + + src/crud/orders.py + + src/schemas/orders.py + + tests/test_orders.py +Files to modify (1): + ~ src/api/api.py ``` -
- -## What Gets Created - -When you add a route, FastAPI-fastkit automatically creates: +## What gets created -### 1. Route File: `src/api/routes/users.py` +Both layouts generate the same CRUD resource with an in-memory repository +and tests, and register the router automatically. -```python -from typing import List -from fastapi import APIRouter, HTTPException, status -from src.schemas.users import User, UserCreate, UserUpdate -from src.crud.users import users_crud - -router = APIRouter() - -@router.get("/", response_model=List[User]) -def read_users(): - """Get all users""" - return users_crud.get_all() - -@router.post("/", response_model=User, status_code=status.HTTP_201_CREATED) -def create_user(user: UserCreate): - """Create a new user""" - return users_crud.create(user) - -@router.get("/{user_id}", response_model=User) -def read_user(user_id: int): - """Get a specific user""" - user = users_crud.get_by_id(user_id) - if user is None: - raise HTTPException(status_code=404, detail="User not found") - return user +`classic-layer`: -@router.put("/{user_id}", response_model=User) -def update_user(user_id: int, user: UserUpdate): - """Update a user""" - updated_user = users_crud.update(user_id, user) - if updated_user is None: - raise HTTPException(status_code=404, detail="User not found") - return updated_user - -@router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT) -def delete_user(user_id: int): - """Delete a user""" - success = users_crud.delete(user_id) - if not success: - raise HTTPException(status_code=404, detail="User not found") -``` - -### 2. CRUD Operations: `src/crud/users.py` - -```python -from typing import List, Optional -from src.schemas.users import User, UserCreate, UserUpdate - -class UsersCRUD: - def __init__(self): - self._users: List[User] = [] - self._next_id = 1 - - def get_all(self) -> List[User]: - """Get all users""" - return self._users - - def get_by_id(self, user_id: int) -> Optional[User]: - """Get user by ID""" - return next((user for user in self._users if user.id == user_id), None) - - def create(self, user: UserCreate) -> User: - """Create a new user""" - new_user = User( - id=self._next_id, - title=user.title, - description=user.description - ) - self._next_id += 1 - self._users.append(new_user) - return new_user - - def update(self, user_id: int, user: UserUpdate) -> Optional[User]: - """Update an existing user""" - existing_user = self.get_by_id(user_id) - if existing_user: - update_data = user.dict(exclude_unset=True) - for field, value in update_data.items(): - setattr(existing_user, field, value) - return existing_user - return None - - def delete(self, user_id: int) -> bool: - """Delete a user""" - user = self.get_by_id(user_id) - if user: - self._users.remove(user) - return True - return False - -users_crud = UsersCRUD() +```text +src/api/routes/users.py # endpoints +src/crud/users.py # User record and UserRepository (in memory) +src/schemas/users.py # UserCreate, UserUpdate, UserRead +tests/test_users.py # endpoint tests ``` -### 3. Pydantic Schemas: `src/schemas/users.py` - -```python -from typing import Optional -from pydantic import BaseModel - -class UserBase(BaseModel): - title: str - description: Optional[str] = None - -class UserCreate(UserBase): - pass - -class UserUpdate(BaseModel): - title: Optional[str] = None - description: Optional[str] = None +`domain`: -class User(UserBase): - id: int - - class Config: - from_attributes = True +```text +src/app/domains/users/ +├── __init__.py +├── models.py # User(id, name, description) +├── schemas.py # UserCreate, UserUpdate, UserRead +├── repository.py # UserRepository (in memory) +├── service.py # UserService and UserNotFoundError +└── router.py # endpoints and the get_user_service dependency +tests/test_users.py ``` -### 4. Router Registration - -The command automatically updates `src/api/api.py` to include the new router: +A project generated by an older fastkit without `core/pagination.py` also gets +that module. The router is registered below the `# fastkit:routes` anchor of +the API router (`src/api/api.py`, `src/app/api/router.py`), which is mounted +under `API_V1_PREFIX`: ```python -from fastapi import APIRouter -from src.api.routes import items, users - api_router = APIRouter() - -api_router.include_router(items.router, prefix="/items", tags=["items"]) -api_router.include_router(users.router, prefix="/users", tags=["users"]) +api_router.include_router(items.router) +# fastkit:routes +api_router.include_router(users_router) ``` -## Generated API Endpoints - -After adding the `users` route, you'll have these endpoints: +## Generated API endpoints -| Method | Endpoint | Description | -|--------|----------|-------------| -| `GET` | `/api/v1/users/` | Get all users | -| `POST` | `/api/v1/users/` | Create a new user | -| `GET` | `/api/v1/users/{user_id}` | Get a specific user | -| `PUT` | `/api/v1/users/{user_id}` | Update a user | -| `DELETE` | `/api/v1/users/{user_id}` | Delete a user | +| Method | Endpoint | Result | +|--------|----------|--------| +| `GET` | `/api/v1/users?limit=20&offset=0` | 200, one page: `{"items", "total", "limit", "offset"}`; `limit` 1-100 | +| `POST` | `/api/v1/users` | 201 with a `Location` header | +| `GET` | `/api/v1/users/{user_id}` | 200 or 404 | +| `PUT` | `/api/v1/users/{user_id}` | 200 or 404; replaces every field | +| `PATCH` | `/api/v1/users/{user_id}` | 200 or 404; changes only the fields sent | +| `DELETE` | `/api/v1/users/{user_id}` | empty 204 or 404 | -## Testing Your New Routes +`name` takes 1 to 120 characters and `description` is optional. The repository +assigns IDs starting at 1, and PUT keeps the existing ID. A 404 body is +`{"detail": "User not found"}`. -### 1. Start the Server +The repository locks its operations. Its default instance is shared between +requests **within this route and process**: data is lost on restart and is not +shared between worker processes. Replace it for durable persistence; it does +not depend on the project's ORM or database configuration. For tests, override +the router's repository or service dependency (`get_user_repository`, +`get_user_service`), or call `reset_store()`. -
- -```console -$ fastkit runserver -INFO: Uvicorn running on http://127.0.0.1:8000 -``` - -
+## Re-running the command -### 2. Check API Documentation +Running `addroute` again for a route that is already in place does nothing. +A route whose files exist but are not registered, or a name that matches an +existing module, is refused with exit status 1. HTTP method/path conflicts are +not checked by the generator. `--layout` does not migrate existing modules. -Visit [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) to see your new endpoints in the interactive documentation. +## Testing your new routes -### 3. Test with curl +Start the server with `fastkit runserver` and open +[http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), or run the generated +tests with `pytest`. **Create a user:**
```console -$ curl -X POST "http://127.0.0.1:8000/api/v1/users/" \ +$ curl -i -X POST "http://127.0.0.1:8000/api/v1/users" \ -H "Content-Type: application/json" \ - -d '{"title": "John Doe", "description": "Software Developer"}' - -{ - "id": 1, - "title": "John Doe", - "description": "Software Developer" -} -``` - -
+ -d '{"name": "John Doe", "description": "Software Developer"}' -**Get all users:** -
+HTTP/1.1 201 Created +location: http://127.0.0.1:8000/api/v1/users/1 -```console -$ curl http://127.0.0.1:8000/api/v1/users/ - -[ - { - "id": 1, - "title": "John Doe", - "description": "Software Developer" - } -] +{"id": 1, "name": "John Doe", "description": "Software Developer"} ```
-**Get a specific user:** +**List users:**
```console -$ curl http://127.0.0.1:8000/api/v1/users/1 +$ curl "http://127.0.0.1:8000/api/v1/users?limit=20&offset=0" { - "id": 1, - "title": "John Doe", - "description": "Software Developer" + "items": [ + {"id": 1, "name": "John Doe", "description": "Software Developer"} + ], + "total": 1, + "limit": 20, + "offset": 0 } ``` @@ -334,130 +156,17 @@ $ curl http://127.0.0.1:8000/api/v1/users/1 ## Customizing Generated Code -The generated code is fully customizable. Here are common modifications: - -### 1. Enhanced User Schema - -Modify `src/schemas/users.py` for more realistic user data: - -```python -from typing import Optional -from datetime import datetime -from pydantic import BaseModel, EmailStr, Field - -class UserBase(BaseModel): - email: EmailStr - username: str = Field(..., min_length=3, max_length=50) - full_name: Optional[str] = None - is_active: bool = True - -class UserCreate(UserBase): - password: str = Field(..., min_length=8) - -class UserUpdate(BaseModel): - email: Optional[EmailStr] = None - username: Optional[str] = Field(None, min_length=3, max_length=50) - full_name: Optional[str] = None - is_active: Optional[bool] = None - -class User(UserBase): - id: int - created_at: datetime - - class Config: - from_attributes = True - -class UserInDB(User): - hashed_password: str -``` - -### 2. Enhanced CRUD with Validation - -Update `src/crud/users.py` with better validation: - -```python -from typing import List, Optional -from datetime import datetime -import hashlib -from src.schemas.users import UserCreate, UserUpdate, UserInDB - -class UsersCRUD: - def __init__(self): - self._users: List[UserInDB] = [] - self._next_id = 1 - - def _hash_password(self, password: str) -> str: - """Simple password hashing (use bcrypt in production)""" - return hashlib.sha256(password.encode()).hexdigest() - - def get_by_email(self, email: str) -> Optional[UserInDB]: - """Get user by email""" - return next((user for user in self._users if user.email == email), None) - - def get_by_username(self, username: str) -> Optional[UserInDB]: - """Get user by username""" - return next((user for user in self._users if user.username == username), None) - - def create(self, user: UserCreate) -> UserInDB: - """Create a new user with validation""" - # Check for duplicates - if self.get_by_email(user.email): - raise ValueError("Email already registered") - if self.get_by_username(user.username): - raise ValueError("Username already taken") - - new_user = UserInDB( - id=self._next_id, - email=user.email, - username=user.username, - full_name=user.full_name, - is_active=user.is_active, - created_at=datetime.now(), - hashed_password=self._hash_password(user.password) - ) - self._next_id += 1 - self._users.append(new_user) - return new_user - -users_crud = UsersCRUD() -``` - -### 3. Enhanced Route with Error Handling +The generated code is a starting point. Typical changes: -Update `src/api/routes/users.py` with better error handling: - -```python -from typing import List -from fastapi import APIRouter, HTTPException, status -from src.schemas.users import User, UserCreate, UserUpdate -from src.crud.users import users_crud - -router = APIRouter() - -@router.post("/", response_model=User, status_code=status.HTTP_201_CREATED) -def create_user(user: UserCreate): - """Create a new user""" - try: - new_user = users_crud.create(user) - # Return user without password hash - return User(**new_user.dict()) - except ValueError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=str(e) - ) - -@router.get("/{user_id}", response_model=User) -def read_user(user_id: int): - """Get a specific user""" - user = users_crud.get_by_id(user_id) - if not user: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"User with id {user_id} not found" - ) - return User(**user.dict()) -``` +- Add fields to `UserCreate`, `UserUpdate` and `UserRead` in the schemas module + and to the record in the repository (or `models.py`). Keep secrets such as + password hashes out of `UserRead`. +- Replace the in-memory repository with one backed by your database; the + routes only call its methods (`list_page`, `get`, `add`, `replace`, + `update`, `delete`). +- Raise `HTTPException(status_code=409, ...) from exc` for uniqueness + conflicts, and document extra error responses with `error_responses(...)` + from `core/responses.py`. ## Adding Multiple Routes @@ -478,47 +187,23 @@ $ fastkit addroute categories my-awesome-api This creates a comprehensive API with: -- `/api/v1/users/` - User management -- `/api/v1/products/` - Product catalog -- `/api/v1/orders/` - Order processing -- `/api/v1/categories/` - Category management +- `/api/v1/users` - User management +- `/api/v1/products` - Product catalog +- `/api/v1/orders` - Order processing +- `/api/v1/categories` - Category management ## Route Organization ### Grouping Related Endpoints -You can organize routes by domain: +Each generated router carries its own prefix and tag +(`APIRouter(prefix="/products", tags=["products"])`). To group endpoints in +the docs, add tags when registering the router; do not add a second prefix: ```python # src/api/api.py -from fastapi import APIRouter -from src.api.routes import users, products, orders, categories - -api_router = APIRouter() - -# User management -api_router.include_router( - users.router, - prefix="/users", - tags=["User Management"] -) - -# E-commerce -api_router.include_router( - products.router, - prefix="/products", - tags=["E-commerce"] -) -api_router.include_router( - orders.router, - prefix="/orders", - tags=["E-commerce"] -) -api_router.include_router( - categories.router, - prefix="/categories", - tags=["E-commerce"] -) +api_router.include_router(products_router, tags=["E-commerce"]) +api_router.include_router(orders_router, tags=["E-commerce"]) ``` ### Adding Route Dependencies @@ -527,24 +212,14 @@ Add authentication or other dependencies: ```python from fastapi import APIRouter, Depends -from src.core.auth import get_current_user - -router = APIRouter() - -@router.get("/profile", response_model=User) -def get_user_profile(current_user: User = Depends(get_current_user)): - """Get current user's profile""" - return current_user - -@router.post("/", response_model=User) -def create_user( - user: UserCreate, - current_user: User = Depends(get_current_user) -): - """Create a new user (admin only)""" - if not current_user.is_admin: - raise HTTPException(status_code=403, detail="Admin access required") - return users_crud.create(user) + +from src.auth.dependencies import get_current_user # your auth dependency + +router = APIRouter( + prefix="/products", + tags=["products"], + dependencies=[Depends(get_current_user)], # every endpoint requires a user +) ``` ## Best Practices @@ -554,31 +229,32 @@ def create_user( Follow consistent naming conventions: - **Route names**: Use plural nouns (`users`, `products`, `orders`) -- **Schema names**: Use singular (`User`, `Product`, `Order`) -- **CRUD classes**: End with `CRUD` (`UsersCRUD`, `ProductsCRUD`) +- **Schema names**: Use singular (`UserCreate`, `UserUpdate`, `UserRead`) +- **Repository classes**: Singular, ending with `Repository` (`UserRepository`) ### 2. Error Handling Always handle errors gracefully: ```python -@router.post("/", response_model=User) -def create_user(user: UserCreate): +@router.post("", status_code=status.HTTP_201_CREATED, responses=error_responses(409)) +def create_user(payload: UserCreate, repository: UserRepositoryDep) -> UserRead: try: - return users_crud.create(user) - except ValueError as e: - raise HTTPException(status_code=400, detail=str(e)) - except Exception as e: - raise HTTPException(status_code=500, detail="Internal server error") + record = repository.add(payload.model_dump()) + except DuplicateEmailError as exc: + raise HTTPException(status_code=409, detail="Email already registered") from exc + return UserRead.model_validate(record) ``` +Do not put exception text in 5xx responses; log it instead. + ### 3. Documentation Add comprehensive docstrings: ```python -@router.get("/{user_id}", response_model=User) -def read_user(user_id: int): +@router.get("/{user_id}", responses=error_responses(404)) +def get_user(user_id: int, repository: UserRepositoryDep) -> UserRead: """ Get a specific user by ID. @@ -591,37 +267,17 @@ def read_user(user_id: int): Raises: HTTPException: 404 if user not found """ - user = users_crud.get_by_id(user_id) - if not user: + record = repository.get(user_id) + if record is None: raise HTTPException(status_code=404, detail="User not found") - return user + return UserRead.model_validate(record) ``` ### 4. Testing -Always test your new routes: - -```python -# tests/test_users.py -from fastapi.testclient import TestClient -from src.main import app - -client = TestClient(app) - -def test_create_user(): - user_data = { - "email": "test@example.com", - "username": "testuser", - "password": "securepassword123" - } - response = client.post("/api/v1/users/", json=user_data) - assert response.status_code == 201 - assert response.json()["email"] == user_data["email"] - -def test_get_user(): - response = client.get("/api/v1/users/1") - assert response.status_code == 200 -``` +`addroute` writes `tests/test_users.py` with tests for every endpoint (201 +and `Location`, the page envelope, `limit` bounds, PUT, PATCH, 204, 404). Run +them with `pytest` and extend them when you change the resource. ## Troubleshooting @@ -629,7 +285,7 @@ def test_get_user(): If your route doesn't appear in the API documentation: -1. **Check router registration** in `src/api/api.py` +1. **Check router registration** below `# fastkit:routes` in `src/api/api.py` (or `src/app/api/router.py`) 2. **Restart the server** after adding routes 3. **Check for import errors** in the route file @@ -661,4 +317,4 @@ Now that you know how to add routes: - Always test new routes in the interactive docs (`/docs`) - Use meaningful HTTP status codes - Implement proper error handling for all endpoints - - Keep route handlers simple and delegate business logic to CRUD classes + - Keep route handlers simple and delegate business logic to the repository or service diff --git a/docs/en/user-guide/choosing-a-starter.md b/docs/en/user-guide/choosing-a-starter.md index f527ac9..7459390 100644 --- a/docs/en/user-guide/choosing-a-starter.md +++ b/docs/en/user-guide/choosing-a-starter.md @@ -133,7 +133,7 @@ A side-by-side at a glance. | Project entry | `src/main.py` | `src/main.py` | `src/main.py` | `src/app/main.py` | | Routers location | (you add) | (inside `main.py`) | `src/api/routes/` | `src/app/domains//router.py` | | Per-domain folders | ❌ | ❌ | ❌ | ✅ | -| Built-in `/health` endpoint | ✅ | ✅ | ❌ | ✅ | +| Built-in `/health` endpoint | ✅ | ✅ | ✅ | ✅ | | `main.py` regenerated from features | ✅ | ✅ | ❌ | ❌ | | CORS pre-wired in `main.py` | added when selected | added when selected | yes (env-driven) | yes (env-driven) | | pyproject-first | optional | optional | optional | ✅ | diff --git a/docs/en/user-guide/cli-reference.md b/docs/en/user-guide/cli-reference.md index 81dea8a..b34f1fe 100644 --- a/docs/en/user-guide/cli-reference.md +++ b/docs/en/user-guide/cli-reference.md @@ -36,6 +36,7 @@ Options: Commands: addroute Add a new route to FastAPI project + doctor Check a generated project for known problems init Create a new FastAPI project list-templates List available FastAPI templates runserver Start FastAPI development server @@ -226,8 +227,7 @@ skips that confirmation and proceeds with the overwrite. It does not affect the separate "Do you want to proceed with project creation?" prompt, which is still shown. In a non-interactive environment (stdin is not a TTY, as in CI or a piped run), fastkit refuses to overwrite anything unless `--yes` -is given: `init` exits with status 1 before writing any file (`startdemo` -exits with status 0). An existing `.env` is never overwritten (see +is given: `init` and `startdemo` exit with status 1 before writing any file. An existing `.env` is never overwritten (see [Generated `.env` file](#generated-env-file)). #### Generated `.env` file @@ -292,20 +292,25 @@ warnings) differ. | Axis | Choices | Installed packages | Generated files | |---|---|---|---| -| `database` | PostgreSQL, MySQL, MongoDB, Redis, SQLite, None | PostgreSQL: `asyncpg`, `sqlalchemy[asyncio]` · MySQL: `aiomysql`, `sqlalchemy[asyncio]` · MongoDB: `motor` · Redis: `redis[hiredis]` · SQLite: `sqlalchemy[asyncio]`, `aiosqlite` | A database config module at the preset's path (e.g. `src/config/database.py`) | -| `authentication` | JWT, OAuth2, FastAPI-Users, Session-based, None | JWT: `pyjwt[crypto]`, `pwdlib[argon2]` · OAuth2: `authlib`, `itsdangerous`, `httpx` · FastAPI-Users: `fastapi-users[sqlalchemy]`, `pyjwt[crypto]`, `pwdlib[argon2]` · Session-based: `itsdangerous` | An auth config module at the preset's path; OAuth2 and Session-based also add `main.py` middleware setup | +| `database` | PostgreSQL, MySQL, MongoDB, Redis, SQLite, None | PostgreSQL: `asyncpg`, `sqlalchemy[asyncio]` · MySQL: `aiomysql`, `sqlalchemy[asyncio]` · MongoDB: `pymongo>=4.13` (its async client) · Redis: `redis[hiredis]` · SQLite: `sqlalchemy[asyncio]`, `aiosqlite` | A database module at the preset's path (e.g. `src/config/database.py`) that opens and closes the client with the app; with a database or Redis cache, `GET /ready` | +| `authentication` | JWT, OAuth2, FastAPI-Users, Session-based, None | JWT: `pyjwt[crypto]`, `pwdlib[argon2]`, `email-validator`, `python-multipart` · OAuth2: `authlib`, `itsdangerous`, `httpx2` · FastAPI-Users: `fastapi-users[sqlalchemy]` · Session-based: `itsdangerous`, `pwdlib[argon2]`, `email-validator` | An auth package (`src/auth/`, or `src/app/domains/auth/` with `domain-starter`) with routes under `/api/v1` and tests. JWT: OAuth2 password flow (`POST /auth/register`, `POST /auth/token`, `GET /users/me`), users stored in the selected SQL database or MongoDB, in memory otherwise. FastAPI-Users: SQL databases only. Session-based: login, logout (204), demo account only with `ENABLE_DEMO_USERS=true`. OAuth2: needs `OAUTH_REDIRECT_BASE_URL` outside development | | `async_tasks` | Celery, Dramatiq, None | Celery: `celery[redis]`, `redis[hiredis]` · Dramatiq: `dramatiq[redis]`, `redis[hiredis]` | `/worker.py` (background worker) + `/features/tasks.py` (task routes) | -| `testing` | Basic, Coverage, Advanced, None | Basic: `pytest`, `pytest-asyncio`, `httpx` · Coverage: + `pytest-cov` · Advanced: + `faker`, `factory-boy` | `pytest.ini`; Advanced also adds `tests/factories.py` and `tests/test_factories.py` | +| `testing` | Basic, Coverage, Advanced, None | Basic: `pytest`, `pytest-asyncio`, `httpx`, `httpx2` · Coverage: + `pytest-cov` · Advanced: + `faker`, `factory-boy` | `pytest.ini`, a root `conftest.py` that runs tests against in-memory SQLite without telemetry export, and tests for the selected features; Advanced also adds `tests/factories.py` and `tests/test_factories.py` | | `caching` | Redis, None | Redis: `redis[hiredis]`, `fastapi-cache2`, `jinja2` | `/features/cache.py` (cached endpoints) | -| `monitoring` | Loguru, OpenTelemetry, Prometheus, None | Loguru: `loguru` · OpenTelemetry: `opentelemetry-api`, `opentelemetry-sdk`, `opentelemetry-instrumentation-fastapi`, `opentelemetry-exporter-otlp-proto-http` · Prometheus: `prometheus-client`, `prometheus-fastapi-instrumentator` | No standalone file — wired directly into `main.py` (import / setup) | -| `utilities` (multi-select) | CORS, Rate-Limiting, Pagination, WebSocket, None | CORS: none (built into FastAPI) · Rate-Limiting: `slowapi` · Pagination: `fastapi-pagination` · WebSocket: `websockets` | CORS and Rate-Limiting wire into `main.py` directly (CORS stays off until `BACKEND_CORS_ORIGINS` is set); Pagination adds `/features/pagination.py` (a demo list on `GET /api/v1/items`), or only `add_pagination(app)` with `classic-layered` / `domain-starter`; WebSocket adds `/features/websocket.py` | +| `monitoring` | Loguru, OpenTelemetry, Prometheus, None | Loguru: `loguru` · OpenTelemetry: `opentelemetry-api`, `opentelemetry-sdk`, `opentelemetry-instrumentation-fastapi`, `opentelemetry-exporter-otlp-proto-http` · Prometheus: `prometheus-client`, `prometheus-fastapi-instrumentator` | Loguru: `/loguru_config.py` · OpenTelemetry: `/telemetry.py` · Prometheus: set up in `main.py` (`GET /metrics`) | +| `utilities` (multi-select) | CORS, Rate-Limiting, Pagination, WebSocket, None | CORS: none (built into FastAPI) · Rate-Limiting: `limits>=3.4` · Pagination: none · WebSocket: `websockets` | CORS wires into `main.py` (off until `BACKEND_CORS_ORIGINS` is set); Rate-Limiting adds `/rate_limiting.py`, which applies `RATE_LIMIT_DEFAULT` to every route and `RATE_LIMIT_AUTH` to the auth endpoints (429 with `Retry-After`); Pagination generates nothing, because list endpoints are always paginated (`core/pagination.py`), and is kept so saved configs still load; WebSocket adds `/features/websocket.py` (`/ws`, and `GET /api/v1/connections`) | | `migrations` | Alembic, None | Alembic: `alembic` | `alembic.ini`, `alembic/env.py`, `alembic/script.py.mako`, a baseline `alembic/versions/_initial.py`, `scripts/migrate.sh` — only when the database axis is a SQL database | | `tooling` (multi-select) | ruff, pre-commit, github-actions, devcontainer, makefile, None | ruff: `ruff` · pre-commit: `pre-commit` · github-actions / devcontainer / makefile: none | ruff merges a `[tool.ruff]` block into `pyproject.toml` (or writes `ruff.toml` for `pip` projects) that allows FastAPI's `Depends`, `Query`, ... defaults (B008); pre-commit writes `.pre-commit-config.yaml` without pinning a Python interpreter (without ruff, it also adds a missing `[tool.black]` table); github-actions writes `.github/workflows/test.yml`; devcontainer writes `.devcontainer/devcontainer.json`; makefile writes `Makefile` | | `logging` | structured, None | None (stdlib `logging` + `json` only) | `/logging_config.py` (structured JSON logging + request-id middleware), wired into `main.py` | +| `deployment` (multi-select) | Docker, docker-compose | none | `Dockerfile` (non-root user, healthcheck on `/health`, `ENVIRONMENT=production`, no `.env` in the image), `.dockerignore`; docker-compose adds `docker-compose.yml` with the database / cache services, healthchecks and service URLs, reading `.env` at run time | -Regardless of selection, every generated project gets `/health` and -`/ready` endpoints in `main.py`, and `--dry-run` prints this exact file set -before anything is written. +Regardless of selection, every generated project serves `GET /health` +(`{"status": "ok"}`) at the root and mounts feature routers under +`API_V1_PREFIX` (default `/api/v1`). With a database or a Redis cache it also +serves `GET /ready`, which returns 503 when the backend does not answer +within a short timeout. All generated code reads its settings from the +project's settings module (`core/config.py`), which loads `.env`. +`--dry-run` prints the exact file set before anything is written. #### Examples @@ -376,7 +381,7 @@ $ fastkit addroute ROUTE_NAME [PROJECT_DIR] [OPTIONS] | Argument | Description | Required | |----------|-------------|----------| -| `ROUTE_NAME` | Name of the new route (plural recommended) | Yes | +| `ROUTE_NAME` | Name of the new route (plural recommended): lower-case ASCII letters, digits and underscores, starting with a letter. It names the modules and the URL segment | Yes | | `PROJECT_DIR` | Project directory under your workspace (defaults to `.`, the current directory) | No | #### Options @@ -384,8 +389,17 @@ $ fastkit addroute ROUTE_NAME [PROJECT_DIR] [OPTIONS] | Option | Description | Default | |--------|-------------|---------| | `--layout [classic-layer\|domain]` | Structure of the generated route module; overrides preset metadata | Automatic from preset | +| `--entity TEXT` | Singular PascalCase class name for the resource (e.g. `Order`) | Derived from `ROUTE_NAME` | +| `--dry-run` | List the files that would be created or modified; write nothing | off | +| `--diff` | Like `--dry-run`, and also print a unified diff of each modified file and the content of each new file | off | | `--help` | Show command help | - | +`addroute` exits with status 1 when it refuses to run (missing project +directory, not a fastkit project, invalid route name or `--entity`, a route +whose files already exist or that is named like an existing module) or when +planning or writing fails; a failed write is rolled back. Declining the +confirmation and a preview (`--dry-run` / `--diff`) exit with status 0. + #### Examples
@@ -422,54 +436,57 @@ $ fastkit addroute users my-api With `--layout=classic-layer`, creates these files under the app package: - `src/api/routes/users.py` - Route handlers -- `src/crud/users.py` - CRUD operations -- `src/schemas/users.py` - Pydantic schemas +- `src/crud/users.py` - In-memory repository +- `src/schemas/users.py` - Pydantic schemas (`UserCreate`, `UserUpdate`, `UserRead`) +- `tests/test_users.py` - Tests for the endpoints With `--layout=domain`, creates `domains/users/` containing `__init__.py`, -`models.py`, `schemas.py`, `repository.py`, `service.py`, and `router.py`. -The entity has `id: int` and `name: str`, with a working in-memory repository. +`models.py`, `schemas.py`, `repository.py`, `service.py`, and `router.py`, +plus `tests/test_users.py`. The entity has `id: int`, `name: str` and an +optional `description`, with a working in-memory repository. A project +without `core/pagination.py` (generated by an older fastkit) gets one. Both layouts update the existing API router and connect it to the application if necessary. Paths follow the actual app package, including `src/app/`. Without the option, `[tool.fastapi-fastkit].preset = "domain-starter"` selects `domain`. When `preset` is missing, the preset is inferred from `template`; -`fastapi-domain-starter` also selects `domain`. Other presets and projects without -either metadata value select `classic-layer`. An unknown preset falls back to `classic-layer` with a -warning. Explicit selection does not change the project's preset. +`fastapi-domain-starter` also selects `domain`, and so does any project with a +`domains/` package. Other projects select `classic-layer`. An unknown preset +falls back to `classic-layer` with a warning. Explicit selection does not +change the project's preset. ```console $ fastkit addroute users . --layout=domain $ fastkit addroute products . --layout=classic-layer +$ fastkit addroute orders . --entity Order --diff ``` -The command displays its selected layout before confirmation. Re-running it -preserves existing files, restores missing files, and avoids duplicate router -registrations. Same-named modules of different layouts can coexist through -import aliases. The generator does not check HTTP method/path conflicts. -Migration is manual. +The command displays its selected layout, path, entity and schema names +before confirmation. Running it again for a route that is already in place +does nothing; a route whose files exist but are not registered is refused. +The generator does not check HTTP method/path conflicts. Migration is +manual. #### Generated Endpoints -The domain layout creates these endpoints (shown with `/api/v1` as the app's -existing prefix): +Both layouts create these endpoints (shown with `/api/v1` as the app's +`API_V1_PREFIX`): | Method | Endpoint | Description | |--------|----------|-------------| -| `GET` | `/api/v1/users` | List entities, 200 | -| `POST` | `/api/v1/users` | Create entity, 201 | -| `GET` | `/api/v1/users/{entity_id}` | Read entity, 200 or 404 | -| `PUT` | `/api/v1/users/{entity_id}` | Replace entity, 200 or 404 | -| `DELETE` | `/api/v1/users/{entity_id}` | Delete entity, empty 204 or 404 | - -POST and PUT accept a `name` of 1–120 characters. IDs are assigned by the -repository, and PUT preserves them. No PATCH endpoint is generated for domains. -Storage is process-local, lost on restart, and independent between domains; -replace the repository for durable persistence. Tests can inject a fresh -repository through the service and override `get_users_service`. - -The classic layout retains its existing GET/POST/PUT/PATCH/DELETE stubs at -`//` for you to implement. +| `GET` | `/api/v1/users?limit=20&offset=0` | List entities, 200 with `{"items", "total", "limit", "offset"}` (`limit` 1-100) | +| `POST` | `/api/v1/users` | Create entity, 201 with a `Location` header | +| `GET` | `/api/v1/users/{user_id}` | Read entity, 200 or 404 | +| `PUT` | `/api/v1/users/{user_id}` | Replace entity, 200 or 404 | +| `PATCH` | `/api/v1/users/{user_id}` | Update the fields sent, 200 or 404 | +| `DELETE` | `/api/v1/users/{user_id}` | Delete entity, empty 204 or 404 | + +`name` takes 1–120 characters. IDs are assigned by the repository, and PUT +preserves them. A 404 body is `{"detail": "User not found"}`. Storage is +process-local, lost on restart, and independent between routes; replace the +repository for durable persistence. In a `fastapi-custom-response` project +the routes return that template's response envelope. #### Where the code is inserted @@ -502,6 +519,73 @@ router registrations itself. The anchors simply make the result predictable. the entrypoint, so it works on layouts the on-disk scan alone would rank wrongly. +### `doctor` + +Check a generated project for problems that newer fastkit versions fixed in +their templates, and fix the safe ones. Upgrading fastkit never changes an +existing project; `doctor` shows what still applies to it. + +#### Syntax + +```console +$ fastkit doctor [PATH] [OPTIONS] +``` + +`PATH` is the project directory (default: the current directory). + +#### Options + +| Option | Description | Default | +|--------|-------------|---------| +| `--fix` | Apply the safe fixes: show every change as a diff first, then ask once. Advisory problems are never changed | off | +| `--dry-run`, `--diff` | Show the changes `--fix` would make without writing anything (implies `--fix`) | off | +| `--yes` / `-y` | Apply `--fix` changes without asking; required without a terminal | off | +| `--format [text\|json]` | `json` prints one JSON document on stdout, for CI | `text` | +| `--force` | Check a project without `[tool.fastapi-fastkit]` metadata (generated before fastkit 1.4.0, or not by fastkit); checks that need the metadata are skipped | off | +| `--help` | Show command help | - | + +Exit status: 0 when no problem is found (or all were fixed), 1 when problems +remain, 2 when `doctor` could not run (not a fastkit project, unreadable +project, a failed check, or `--fix` without `--yes` and without a terminal). +With `--format json`, `--fix` needs `--yes` or `--dry-run`. `doctor` never +prints secret values. + +#### Checks + +| Check | Problem | `--fix` | +|-------|---------|---------| +| `env-tracked` | `.env` is committed to git | - | +| `gitignore-env` | `.gitignore` does not keep `.env` out of git | Adds the rules | +| `env-example-missing` | `.env` exists but `.env.example` does not | Writes it from `.env` without secret values | +| `example-secret` | An example secret shipped by fastkit is still in use | - | +| `session-secret` | The session signing key has a default value or is hard-coded | - | +| `mcp-auth` | The `fastapi-mcp` server is created without authentication | - | +| `mcp-demo-users` | Hard-coded `fastapi-mcp` demo users are always enabled | - | +| `cors-credentials` | CORS allows every origin (`*`) with credentials | - | +| `app-module-missing` | The recorded `app_module` does not exist | - | +| `prometheus-lifespan` | Prometheus is set up inside the lifespan | - | +| `commit-after-yield` | A session dependency commits after `yield` | - | +| `slowapi-middleware` | The default rate limit relies on `SlowAPIMiddleware` | - | +| `pagination-demo` | The `fastapi-pagination` demo router shadows the items list | - | +| `motor-deprecated` | MongoDB is accessed through Motor | - | +| `settings-sprawl` | Generated modules read configuration outside the settings module | - | +| `sqlalchemy-asyncio` | Async SQLAlchemy is installed without `greenlet` | Depends on `sqlalchemy[asyncio]` | +| `crlf-scripts` | Shell scripts or Dockerfiles have CRLF line endings | Converts them to LF | +| `gitattributes-missing` | No `.gitattributes` pins LF line endings | Writes one | +| `requires-python` | `requires-python` allows Python versions the template does not support | - | +| `pre-commit-python` | `.pre-commit-config.yaml` pins a `python3.x` interpreter | Removes the pin | + +Each problem in the report says how to fix it by hand. + +#### Examples + +```console +$ fastkit doctor # check the current directory +$ fastkit doctor my-api --diff # preview the safe fixes +$ fastkit doctor my-api --fix # apply them after one confirmation +$ fastkit doctor . --format json # machine-readable report for CI +``` + ### `startdemo` Create a FastAPI project from a pre-built template. @@ -524,14 +608,16 @@ $ fastkit startdemo [OPTIONS] | `--dry-run` | Show the files and packages that would be created, without writing anything | off | | `--no-venv` | Skip virtual environment creation (implies `--no-install`) | off | | `--no-install` | Skip dependency installation | off | -| `--yes` / `-y` | Do not ask for confirmation before overwriting existing files when deploying the project in place | off | +| `--yes` / `-y` | Create the project without asking and, when deploying in place, overwrite existing files | off | | `--help` | Show command help | - | Like `init`, `startdemo` refuses to run when the target project directory already exists (`Error: Project '{name}' already exists.`). `--dry-run` is the exception: since it never writes to disk, it is still allowed to target -a name that already has a directory. Unlike `init`, `startdemo` still exits -with status 0 when it refuses or when generation fails. See +a name that already has a directory. `startdemo` exits with status 1 when it +refuses to run (unknown template, invalid project name, existing project +directory, in-place overwrite without a terminal or `--yes`) or generation +fails; declining a confirmation exits with status 0. See [In-place deployment and overwrite confirmation](#in-place-deployment-and-overwrite-confirmation-yes-y) above for what `--yes` does when deploying into the current workspace. @@ -638,7 +724,9 @@ INFO: Uvicorn running on http://127.0.0.1:8000 - Virtual environment should be activated If neither the recorded entrypoint nor the scan finds a module, `runserver` -reports that it could not find `main.py` and stops. +reports that it could not find `main.py` and stops. An `app_module` that is +not a valid `module:attr` value, or that points outside the project, is +rejected with an error. ### `list-templates` diff --git a/docs/en/user-guide/creating-projects.md b/docs/en/user-guide/creating-projects.md index c815192..86f5f21 100644 --- a/docs/en/user-guide/creating-projects.md +++ b/docs/en/user-guide/creating-projects.md @@ -113,10 +113,13 @@ my-awesome-api/ │ ├── main.py # Application entry point │ ├── core/ # Core configuration │ │ ├── __init__.py -│ │ └── config.py # Settings and configuration +│ │ ├── config.py # Settings (reads .env) +│ │ ├── pagination.py # Page envelope and limit/offset parameters +│ │ └── responses.py # Shared error response documentation │ ├── api/ # API layer │ │ ├── __init__.py -│ │ ├── api.py # Main API router +│ │ ├── api.py # Main API router (mounted under /api/v1) +│ │ ├── deps.py # Shared dependencies │ │ └── routes/ # Individual route modules │ │ ├── __init__.py │ │ └── items.py # Example items endpoints @@ -138,7 +141,8 @@ my-awesome-api/ │ ├── coverage.sh # Test coverage │ └── lint.sh # Code linting ├── requirements.txt # Python dependencies -├── setup.py # Package configuration +├── pyproject.toml # Package and tool configuration +├── .env.example # Settings to share; .env is generated and git-ignored └── README.md # Project documentation ``` @@ -429,33 +433,36 @@ only (see [Generated `.env` file](cli-reference.md#generated-env-file)). A `.env ```env # .env -APP_NAME=My Awesome API -APP_VERSION=1.0.0 -DEBUG=True -DATABASE_URL=sqlite:///./app.db -SECRET_KEY=your-secret-key-here +PROJECT_NAME=my-awesome-api +ENVIRONMENT=development +SECRET_KEY= +BACKEND_CORS_ORIGINS=http://localhost:3000 ``` ### Configuration in Code -The generated `src/core/config.py` automatically loads these variables: +The generated `src/core/config.py` is the project's only settings module; it +loads these variables, and generated feature code reads its configuration from +it: ```python -from pydantic_settings import BaseSettings - class Settings(BaseSettings): - APP_NAME: str = "FastAPI Application" - APP_VERSION: str = "1.0.0" - DEBUG: bool = False - DATABASE_URL: str = "sqlite:///./app.db" - SECRET_KEY: str = "dev-secret-key" + model_config = SettingsConfigDict(env_file=".env", env_ignore_empty=True, extra="ignore") - class Config: - env_file = ".env" + PROJECT_NAME: str = "my-awesome-api" + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + SECRET_KEY: str = secrets.token_urlsafe(32) + API_V1_PREFIX: str = "/api/v1" # every business router is mounted here + BACKEND_CORS_ORIGINS: CorsOrigins = [] settings = Settings() ``` +With any `ENVIRONMENT` other than `development` (`staging`, `production`) the +application refuses to start when `SECRET_KEY` is missing, is a public example +value, or is shorter than 32 bytes. In `development` an example value only +prints a warning. + ## Customization Options ### Adding Custom Dependencies @@ -477,7 +484,7 @@ While the generated structure follows best practices, you can modify it: - Add new modules in `src/` - Create additional route files in `api/routes/` -- Extend CRUD operations in `crud/` +- Extend CRUD operations in `crud/` (or add a resource with `fastkit addroute`) - Add more schemas in `schemas/` ## Best Practices diff --git a/docs/en/user-guide/quick-start.md b/docs/en/user-guide/quick-start.md index fbe882a..26814b7 100644 --- a/docs/en/user-guide/quick-start.md +++ b/docs/en/user-guide/quick-start.md @@ -127,9 +127,11 @@ Visit [http://127.0.0.1:8000](http://127.0.0.1:8000) You'll see: ```json -{"message": "Hello World"} +{"message": "Welcome to my-first-app", "docs": "/docs"} ``` +`GET /health` returns `{"status": "ok"}`. + ### Interactive API Documentation Visit [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) @@ -176,11 +178,12 @@ Do you want to add route 'users' to project 'my-first-app'? [Y/n]: y The server will automatically reload, and now you have new endpoints: -- `GET /api/v1/users/` - Get all users -- `POST /api/v1/users/` - Create a new user +- `GET /api/v1/users` - List users, one page at a time (`limit`, `offset`) +- `POST /api/v1/users` - Create a new user (201) - `GET /api/v1/users/{user_id}` - Get a specific user -- `PUT /api/v1/users/{user_id}` - Update a user -- `DELETE /api/v1/users/{user_id}` - Delete a user +- `PUT /api/v1/users/{user_id}` - Replace a user +- `PATCH /api/v1/users/{user_id}` - Update some fields of a user +- `DELETE /api/v1/users/{user_id}` - Delete a user (204) ## 6. Test the New API @@ -191,8 +194,8 @@ The server will automatically reload, and now you have new endpoints:
```console -$ curl http://127.0.0.1:8000/api/v1/users/ -[] +$ curl http://127.0.0.1:8000/api/v1/users +{"items": [], "total": 0, "limit": 20, "offset": 0} ```
@@ -202,12 +205,12 @@ $ curl http://127.0.0.1:8000/api/v1/users/
```console -$ curl -X POST "http://127.0.0.1:8000/api/v1/users/" \ +$ curl -X POST "http://127.0.0.1:8000/api/v1/users" \ -H "Content-Type: application/json" \ - -d '{"title": "John Doe", "description": "Software Developer"}' + -d '{"name": "John Doe", "description": "Software Developer"}' { "id": 1, - "title": "John Doe", + "name": "John Doe", "description": "Software Developer" } ``` @@ -218,12 +221,12 @@ $ curl -X POST "http://127.0.0.1:8000/api/v1/users/" \ 1. Visit [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) 2. Expand the **"users"** section -3. Click on **"POST /api/v1/users/"** +3. Click on **"POST /api/v1/users"** 4. Click **"Try it out"** 5. Fill in the request body: ```json { - "title": "Jane Smith", + "name": "Jane Smith", "description": "Product Manager" } ``` diff --git a/docs/en/user-guide/using-templates.md b/docs/en/user-guide/using-templates.md index 27c93b9..cadfb7c 100644 --- a/docs/en/user-guide/using-templates.md +++ b/docs/en/user-guide/using-templates.md @@ -233,6 +233,7 @@ $ alembic upgrade head INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. INFO [alembic.runtime.migration] Running upgrade -> bedcdc35b64a, first alembic +INFO [alembic.runtime.migration] Running upgrade bedcdc35b64a -> 5f2a9c1d7e3b, constrain item columns ```
@@ -248,6 +249,11 @@ INFO: Uvicorn running on http://127.0.0.1:8000
+The items API is served at `/api/v1/items`, `GET /health` checks that the +process is up, and `GET /ready` checks the database. The tests use a separate +database, `_test` on the same server (or `TEST_DATABASE_URL`), +and never touch the application database. + ### Using `fastapi-dockerized` This template provides full Docker support: @@ -270,59 +276,46 @@ Successfully tagged my-dockerized-api:latest
```console -$ docker run -p 8000:8000 my-dockerized-api +$ docker run -p 8000:8000 --env-file .env my-dockerized-api INFO: Uvicorn running on http://0.0.0.0:8000 ```
+The image runs as a non-root user with `ENVIRONMENT=production` and does not +contain `.env`, so settings such as `SECRET_KEY` must be passed at run time. + ### Using `fastapi-custom-response` This template includes advanced response handling: -1. **Custom response models:** +1. **Every response uses one envelope** (`timestamp`, `status`, `code`, + `path`, `message`). A list returns a page in `message`: ```python -from src.helper.pagination import PaginatedResponse -from src.schemas.base import StandardResponse - -@router.get("/", response_model=PaginatedResponse[Item]) -def read_items(skip: int = 0, limit: int = 10): - items = items_crud.get_multi(skip=skip, limit=limit) - total = items_crud.count() - - return PaginatedResponse( - data=items, +@router.get("", summary="List items") +async def list_items( + request: Request, + store: ItemStoreDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> ResponseSchema[Page[ItemRead]]: + items, total = await store.list_page(offset=offset, limit=limit) + page = Page[ItemRead]( + items=[ItemRead.model_validate(item) for item in items], total=total, - page=skip // limit + 1, - pages=(total + limit - 1) // limit - ) - -@router.post("/", response_model=StandardResponse[Item]) -def create_item(item: ItemCreate): - new_item = items_crud.create(item) - return StandardResponse( - data=new_item, - message="Item created successfully", - status_code=201 + limit=limit, + offset=offset, ) + return success_response(request, page) ``` -2. **Enhanced error handling:** +2. **Errors use the same envelope**, including validation errors (422) and + unhandled exceptions (500, without exception text): ```python -from src.helper.exceptions import ItemNotFoundError, ValidationError - -@router.get("/{item_id}", response_model=StandardResponse[Item]) -def read_item(item_id: int): - try: - item = items_crud.get(item_id) - return StandardResponse(data=item) - except ItemNotFoundError: - raise HTTPException( - status_code=404, - detail=f"Item with id {item_id} not found" - ) +def item_not_found() -> InternalException: + return InternalException(message="Item not found", error_code=ErrorCode.ITEM_NOT_FOUND) ``` ## Template Project Structure @@ -334,9 +327,13 @@ Each template follows a consistent but customized structure: my-project/ ├── src/ │ ├── main.py -│ ├── core/config.py +│ ├── core/ +│ │ ├── config.py +│ │ ├── pagination.py +│ │ └── responses.py │ ├── api/ │ │ ├── api.py +│ │ ├── deps.py │ │ └── routes/items.py │ ├── crud/items.py │ ├── schemas/items.py @@ -353,12 +350,17 @@ my-project/ │ ├── main.py │ ├── core/ │ │ ├── config.py -│ │ └── db.py +│ │ ├── db.py +│ │ ├── pagination.py +│ │ └── responses.py │ ├── api/ │ │ ├── api.py │ │ ├── deps.py -│ │ └── routes/items.py +│ │ └── routes/ +│ │ ├── health.py +│ │ └── items.py │ ├── crud/items.py +│ ├── models/items.py │ ├── schemas/items.py │ ├── alembic/ │ │ ├── env.py @@ -393,26 +395,24 @@ $ fastkit addroute comments my-blog-api Edit `src/core/config.py` to match your needs: ```python -from pydantic_settings import BaseSettings - class Settings(BaseSettings): - PROJECT_NAME: str = "My Blog API" - VERSION: str = "1.0.0" - API_V1_STR: str = "/api/v1" + model_config = SettingsConfigDict(env_file=".env", env_ignore_empty=True, extra="ignore") - # Database settings (for PostgreSQL templates) - DATABASE_URL: str = "postgresql://user:password@localhost/dbname" + PROJECT_NAME: str = "My Blog API" + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + API_V1_PREFIX: str = "/api/v1" - # Security settings - SECRET_KEY: str = "your-secret-key-here" + # Security settings: staging and production refuse a missing, example or + # short key + SECRET_KEY: str = secrets.token_urlsafe(32) ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 - class Config: - env_file = ".env" - settings = Settings() ``` +Keep every setting in this one module; generated code reads its configuration +from it. + ### 3. Add Environment Variables fastkit already created a git-ignored `.env` from the template's @@ -432,7 +432,7 @@ POSTGRES_PASSWORD=password POSTGRES_DB=myblogdb # Security -SECRET_KEY=your-super-secret-key-here +SECRET_KEY= ACCESS_TOKEN_EXPIRE_MINUTES=30 ``` diff --git a/src/fastapi_fastkit/__init__.py b/src/fastapi_fastkit/__init__.py index 5197c5f..8c0d5d5 100644 --- a/src/fastapi_fastkit/__init__.py +++ b/src/fastapi_fastkit/__init__.py @@ -1 +1 @@ -__version__ = "1.5.2" +__version__ = "2.0.0" diff --git a/src/fastapi_fastkit/backend/doctor/__init__.py b/src/fastapi_fastkit/backend/doctor/__init__.py new file mode 100644 index 0000000..80ef29f --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/__init__.py @@ -0,0 +1,49 @@ +# -------------------------------------------------------------------------- +# ``fastkit doctor``: checks a generated project for the problems newer +# fastkit releases fixed in their templates, and fixes the safe ones. +# +# - ``model`` : Check / Finding / PlannedEdit / Severity +# - ``context`` : read-only project access (files, AST, git) +# - ``checks_secrets`` : .env handling, example and session secrets +# - ``checks_code`` : entry point, MCP auth, CORS, Prometheus +# - ``checks_api`` : transactions, rate limiting, Motor, settings, +# pagination demo (code older releases generated) +# - ``checks_files`` : line endings, requires-python, sqlalchemy, pre-commit +# - ``runner`` : running checks, diffs, applying edits +# - ``render`` : Rich and JSON output +# - ``command`` : the command flow used by the CLI +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from .command import DoctorOptions, run_doctor +from .context import DoctorError, ProjectContext +from .model import ( + Check, + CheckResult, + CheckSkipped, + CheckStatus, + Finding, + FixRefused, + PlannedEdit, + Severity, +) +from .runner import DoctorReport, apply_edits, default_checks, run_checks + +__all__ = [ + "Check", + "CheckResult", + "CheckSkipped", + "CheckStatus", + "DoctorError", + "DoctorOptions", + "DoctorReport", + "Finding", + "FixRefused", + "PlannedEdit", + "ProjectContext", + "Severity", + "apply_edits", + "default_checks", + "run_checks", + "run_doctor", +] diff --git a/src/fastapi_fastkit/backend/doctor/checks_api.py b/src/fastapi_fastkit/backend/doctor/checks_api.py new file mode 100644 index 0000000..cf3841e --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/checks_api.py @@ -0,0 +1,296 @@ +# -------------------------------------------------------------------------- +# Doctor checks for code older ``fastkit init`` releases generated and +# v2.0.0 replaced: transactions, rate limiting, MongoDB driver, settings +# and the fastapi-pagination demo. +# +# All of them are advisory: the code may have been edited since it was +# generated, so the remediation says what to change instead of rewriting it. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +from typing import Iterator, List, Sequence, Union + +from .checks_files import _project_dependencies, _requirement_lines, _split_requirement +from .context import ProjectContext +from .model import Check, Finding, Severity +from .pyast import call_name, dotted_name, is_env_read, keyword, str_constant + +FunctionNode = Union[ast.FunctionDef, ast.AsyncFunctionDef] + +#: Header line every module rendered from a ``fastkit init`` fragment carries. +GENERATED_MARKER = "Generated by FastAPI-fastkit" + + +def _contains_yield(node: ast.AST) -> bool: + """Whether ``node`` yields, ignoring functions defined inside it.""" + if isinstance(node, (ast.Yield, ast.YieldFrom)): + return True + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): + return False + return any(_contains_yield(child) for child in ast.iter_child_nodes(node)) + + +def _commit_lines(node: ast.AST) -> List[int]: + """Lines of ``.commit()`` calls in ``node``, outside nested functions.""" + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): + return [] + lines: List[int] = [] + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "commit" + ): + lines.append(node.lineno) + for child in ast.iter_child_nodes(node): + lines += _commit_lines(child) + return lines + + +def _commits_after_yield(statements: Sequence[ast.stmt]) -> List[int]: + """Commit lines that run after a ``yield`` in one block (nested blocks too).""" + found: List[int] = [] + yielded = False + for statement in statements: + if yielded: + found += _commit_lines(statement) + continue + if isinstance(statement, ast.Try) and any( + _contains_yield(s) for s in statement.body + ): + found += _commits_after_yield(statement.body) + for block in (statement.orelse, statement.finalbody): + for s in block: + found += _commit_lines(s) + yielded = True + continue + for field in ("body", "orelse", "finalbody"): + nested = getattr(statement, field, None) + if isinstance(nested, list) and not isinstance( + statement, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef) + ): + found += _commits_after_yield(nested) + if _contains_yield(statement): + yielded = True + return found + + +def _is_context_manager(node: FunctionNode) -> bool: + """Decorated with ``(async)contextmanager``: a unit-of-work block, which + commits when the ``with`` body succeeds, not a request dependency.""" + return any( + dotted_name(d.func if isinstance(d, ast.Call) else d).endswith("contextmanager") + for d in node.decorator_list + ) + + +class CommitAfterYieldCheck(Check): + id = "commit-after-yield" + title = "A session dependency commits after yield" + severity = Severity.MEDIUM + remediation = ( + "Let the dependency only yield the session and roll back on error, and " + "call `await session.commit()` in the service or repository that " + "changes data. A commit after `yield` runs once the endpoint has " + "returned, so a failed commit is not reported to the client." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + findings: List[Finding] = [] + for relative, tree in ctx.iter_python_trees(): + for node in ast.walk(tree): + if not isinstance( + node, (ast.FunctionDef, ast.AsyncFunctionDef) + ) or _is_context_manager(node): + continue + lines = _commits_after_yield(node.body) + if lines: + findings.append( + self.finding( + f"{relative}:{min(lines)} commits after yield in " + f"{node.name}().", + relative, + ) + ) + return findings + + +class SlowapiMiddlewareCheck(Check): + id = "slowapi-middleware" + title = "Default rate limit relies on SlowAPIMiddleware" + severity = Severity.MEDIUM + remediation = ( + "SlowAPIMiddleware does not find the endpoints of routers added with " + "`include_router` on current FastAPI, so they are not limited. Apply " + "the limit in a middleware of your own (a current `fastkit init` " + "project's rate_limiting.py uses the `limits` package directly) or " + "decorate every endpoint with `@limiter.limit(...)`." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + findings: List[Finding] = [] + for relative, tree in ctx.iter_python_trees(): + for node in ast.walk(tree): + if ( + isinstance(node, ast.Call) + and call_name(node) == "add_middleware" + and node.args + and dotted_name(node.args[0]).endswith("SlowAPIMiddleware") + ): + findings.append( + self.finding( + f"{relative}:{node.lineno} adds SlowAPIMiddleware.", + relative, + ) + ) + return findings + + +class MotorDeprecatedCheck(Check): + id = "motor-deprecated" + title = "MongoDB is accessed through the deprecated Motor driver" + severity = Severity.LOW + remediation = ( + "Motor is deprecated in favour of PyMongo's asyncio client. Depend on " + "`pymongo` instead of `motor` and replace `AsyncIOMotorClient` with " + "`from pymongo import AsyncMongoClient` (the call style stays the " + "same; `close()` becomes `await client.close()`)." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + files: List[str] = [] + _, data = ctx.pyproject() + if data is not None and _declares_motor(_project_dependencies(data)): + files.append("pyproject.toml") + read = ctx.read_text("requirements.txt") + if read is not None and _declares_motor(_requirement_lines(read[0])): + files.append("requirements.txt") + for relative, tree in ctx.iter_python_trees(include_tests=True): + if any(module.split(".")[0] == "motor" for module in _imports(tree)): + files.append(relative) + if not files: + return [] + return [self.finding(f"{', '.join(files)} use motor.", *files)] + + +def _declares_motor(requirements: List[str]) -> bool: + return any( + (_split_requirement(spec) or ("",))[0] == "motor" for spec in requirements + ) + + +def _imports(tree: ast.Module) -> Iterator[str]: + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and node.module and not node.level: + yield node.module + elif isinstance(node, ast.Import): + yield from (alias.name for alias in node.names) + + +def _is_generated(ctx: ProjectContext, relative: str) -> bool: + read = ctx.read_text(relative) + return read is not None and GENERATED_MARKER in "\n".join( + read[0].split("\n", 6)[:6] + ) + + +class SettingsSprawlCheck(Check): + id = "settings-sprawl" + title = "Generated modules read configuration outside the settings module" + severity = Severity.LOW + remediation = ( + "Declare these values as fields of the project's `Settings` class and " + "read them from `settings`, so `.env` and the environment configure " + "everything in one place (current `fastkit init` modules do)." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + findings: List[Finding] = [] + for relative, tree in ctx.iter_python_trees(): + if not _is_generated(ctx, relative): + continue + found: List[str] = [] + for node in ast.walk(tree): + if ( + isinstance(node, ast.ClassDef) + and node.name != "Settings" + and any( + dotted_name(base).endswith("BaseSettings") + for base in node.bases + ) + ): + found.append(f"class {node.name}") + elif isinstance(node, ast.Call) and is_env_read(node): + name = str_constant(node.args[0]) if node.args else None + found.append(f"os.getenv({name or '...'})") + if found: + findings.append( + self.finding( + f"{relative}: {', '.join(dict.fromkeys(found))}.", relative + ) + ) + return findings + + +def _router_prefix(tree: ast.Module) -> List[str]: + prefixes: List[str] = [] + for node in ast.walk(tree): + if isinstance(node, ast.Call) and call_name(node) == "APIRouter": + prefix = keyword(node, "prefix") + value = str_constant(prefix.value) if prefix is not None else None + if value: + prefixes.append(value.rstrip("/")) + return prefixes + + +def _mentions_items(tree: ast.Module) -> bool: + return any( + (str_constant(node) or "").rstrip("/").endswith("/items") + for node in ast.walk(tree) + ) + + +class PaginationDemoCheck(Check): + id = "pagination-demo" + title = "fastapi-pagination demo router shadows the items list" + severity = Severity.MEDIUM + remediation = ( + "Delete the demo module and remove its `include_router(...)` and " + "`add_pagination(app)` from main.py. Only one of the two `GET .../items` " + "routes answers; list endpoints take `limit` / `offset` and return the " + "`Page` model of core/pagination.py instead." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + trees = dict(ctx.iter_python_trees()) + demos = [ + relative + for relative, tree in trees.items() + if any(m.startswith("fastapi_pagination") for m in _imports(tree)) + and any(p.endswith("/items") for p in _router_prefix(tree)) + ] + findings: List[Finding] = [] + for demo in demos: + others = sorted( + relative + for relative, tree in trees.items() + if relative != demo and _mentions_items(tree) + ) + if others: + findings.append( + self.finding( + f"{demo} serves GET .../items, which {others[0]} serves too.", + demo, + others[0], + ) + ) + return findings + + +__all__ = [ + "CommitAfterYieldCheck", + "MotorDeprecatedCheck", + "PaginationDemoCheck", + "SettingsSprawlCheck", + "SlowapiMiddlewareCheck", +] diff --git a/src/fastapi_fastkit/backend/doctor/checks_code.py b/src/fastapi_fastkit/backend/doctor/checks_code.py new file mode 100644 index 0000000..a721619 --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/checks_code.py @@ -0,0 +1,343 @@ +# -------------------------------------------------------------------------- +# Doctor checks that read the project's Python code. +# +# All of them are advisory: they point at code a user may have changed +# since generation, so the remediation names the lines to write instead of +# rewriting the module. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +import textwrap +from typing import List, Set, Tuple, Union + +from .context import ProjectContext +from .known import MCP_DEMO_PASSWORDS +from .model import Check, CheckSkipped, Finding, Severity +from .pyast import call_name, dotted_name, has_kwargs_unpack, keyword, str_constant + +FunctionNode = Union[ast.FunctionDef, ast.AsyncFunctionDef] + + +def _app_module_tree(ctx: ProjectContext) -> Tuple[str, ast.Module]: + """The recorded app module and its AST. + + :raises CheckSkipped: when no app module is recorded, it does not + exist or it cannot be parsed + """ + if not ctx.app_module: + raise CheckSkipped("no app_module is recorded in [tool.fastapi-fastkit]") + relative = ctx.app_module_file() + if relative is None: + raise CheckSkipped( + f"the app module {ctx.app_module} does not exist inside the project" + ) + tree = ctx.parse_python(relative) + if tree is None: + raise CheckSkipped(f"{relative} could not be parsed") + return relative, tree + + +# ---------------------------------------------------------------------- +# 5. Recorded entry point missing +# ---------------------------------------------------------------------- + + +class AppModuleMissingCheck(Check): + id = "app-module-missing" + title = "The recorded app entry point does not exist" + severity = Severity.MEDIUM + remediation = ( + "Point `app_module` in [tool.fastapi-fastkit] (pyproject.toml) at the " + "module that creates the FastAPI app, as `package.module:app`, or " + "restore that module. `fastkit runserver` and `fastkit addroute` read " + "it to find the application." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + if not ctx.has_metadata: + raise CheckSkipped("the project has no [tool.fastapi-fastkit] metadata") + if not ctx.app_module: + raise CheckSkipped("no app_module is recorded in [tool.fastapi-fastkit]") + if not ctx.app_module_is_valid or not ctx.app_module_candidates(): + return [ + self.finding( + f"app_module = {ctx.app_module} is not a dotted module path " + "inside the project (package.module:app).", + "pyproject.toml", + ) + ] + if ctx.app_module_file() is not None: + return [] + candidates = ctx.app_module_candidates() + return [ + self.finding( + f"app_module = {ctx.app_module} but {' / '.join(candidates)} " + "does not exist.", + "pyproject.toml", + ) + ] + + +# ---------------------------------------------------------------------- +# 6. fastapi-mcp: unauthenticated MCP server and demo users +# ---------------------------------------------------------------------- + + +def _is_mcp_project(ctx: ProjectContext) -> bool: + if ctx.template == "fastapi-mcp": + return True + for _, tree in ctx.iter_python_trees(): + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and (node.module or "").startswith( + "fastapi_mcp" + ): + return True + if isinstance(node, ast.Import) and any( + alias.name.startswith("fastapi_mcp") for alias in node.names + ): + return True + return False + + +class McpAuthCheck(Check): + id = "mcp-auth" + title = "The MCP server is created without authentication" + severity = Severity.HIGH + remediation = ( + "Pass an auth dependency to FastApiMCP so every MCP request is " + "authenticated (src/mcp_server/router.py in the fastapi-mcp template):\n" + " from fastapi import Depends\n" + " from fastapi_mcp import AuthConfig, FastApiMCP\n" + " from src.auth.dependencies import verify_mcp_access\n" + "\n" + " mcp = FastApiMCP(\n" + " app,\n" + " auth_config=AuthConfig(dependencies=[Depends(verify_mcp_access)]),\n" + " )\n" + "`verify_mcp_access` (src/auth/dependencies.py) accepts " + "`Authorization: Bearer ` when MCP_API_KEY is set, compared " + "with secrets.compare_digest, and a valid JWT access token otherwise. " + "A newly generated fastapi-mcp project shows the full change." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + if not _is_mcp_project(ctx): + raise CheckSkipped("not a fastapi-mcp project") + findings: List[Finding] = [] + for relative, tree in ctx.iter_python_trees(): + for node in ast.walk(tree): + if ( + isinstance(node, ast.Call) + and call_name(node) == "FastApiMCP" + and keyword(node, "auth_config") is None + and not has_kwargs_unpack(node) + ): + findings.append( + self.finding( + f"{relative}:{node.lineno} creates FastApiMCP without " + "auth_config.", + relative, + ) + ) + return findings + + +def _names_demo_flag(node: ast.AST) -> bool: + """Whether a node refers to ``ENABLE_DEMO_USERS`` (name, attribute, import).""" + if isinstance(node, ast.Name): + return node.id == "ENABLE_DEMO_USERS" + if isinstance(node, ast.Attribute): + return node.attr == "ENABLE_DEMO_USERS" + if isinstance(node, ast.alias): + return (node.asname or node.name) == "ENABLE_DEMO_USERS" + return False + + +class McpDemoUsersCheck(Check): + id = "mcp-demo-users" + title = "Hard-coded demo users are always enabled" + severity = Severity.HIGH + remediation = ( + "Remove the hard-coded users, or create them only when the " + "ENABLE_DEMO_USERS setting is true, as the current fastapi-mcp template " + "does (src/api/routes/auth.py and src/core/config.py):\n" + " def get_users_db() -> dict[str, dict]:\n" + " if settings.ENABLE_DEMO_USERS:\n" + " return _demo_users()\n" + " return {}\n" + "Declare `ENABLE_DEMO_USERS: bool = False` in the settings and refuse " + "it unless ENVIRONMENT=development." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + if not _is_mcp_project(ctx): + raise CheckSkipped("not a fastapi-mcp project") + findings: List[Finding] = [] + for relative, tree in ctx.iter_python_trees(): + gated = False + demo_lines: List[int] = [] + for node in ast.walk(tree): + if _names_demo_flag(node): + gated = True + elif str_constant(node) in MCP_DEMO_PASSWORDS: + demo_lines.append(getattr(node, "lineno", 0)) + if demo_lines and not gated: + findings.append( + self.finding( + f"{relative}:{min(demo_lines)} defines demo accounts with " + "known passwords that are not gated by ENABLE_DEMO_USERS.", + relative, + ) + ) + return findings + + +# ---------------------------------------------------------------------- +# 10. CORS: any origin together with credentials +# ---------------------------------------------------------------------- + +CORS_SNIPPET = """\ +# BACKEND_CORS_ORIGINS: comma-separated browser origins, e.g. +# "http://localhost:3000,https://app.example.com". Unset means no CORS. +cors_origins = [ + origin.strip().rstrip("/") + for origin in os.getenv("BACKEND_CORS_ORIGINS", "").split(",") + if origin.strip() +] +if cors_origins: + app.add_middleware( + CORSMiddleware, + allow_origins=cors_origins, + allow_credentials="*" not in cors_origins, + allow_methods=["*"], + allow_headers=["*"], + )""" + + +def _allows_any_origin(node: ast.AST) -> bool: + if str_constant(node) == "*": + return True + if isinstance(node, (ast.List, ast.Tuple, ast.Set)): + return any(str_constant(element) == "*" for element in node.elts) + return False + + +class CorsCredentialsCheck(Check): + id = "cors-credentials" + title = 'CORS allows every origin ("*") with credentials' + severity = Severity.HIGH + remediation = ( + 'Replace allow_origins=["*"] with your frontend origins, or set ' + "allow_credentials=False. With both, Starlette answers credentialed " + "requests from any site with that site's origin. The current `fastkit " + "init` setup reads the origins from BACKEND_CORS_ORIGINS (or use your " + "settings module if the project has one):\n" + + textwrap.indent(CORS_SNIPPET, " ") + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + relative, tree = _app_module_tree(ctx) + findings: List[Finding] = [] + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + origins = keyword(node, "allow_origins") + credentials = keyword(node, "allow_credentials") + if ( + origins is not None + and credentials is not None + and _allows_any_origin(origins.value) + and isinstance(credentials.value, ast.Constant) + and credentials.value.value is True + ): + findings.append( + self.finding( + f'{relative}:{node.lineno} combines allow_origins=["*"] ' + "with allow_credentials=True.", + relative, + ) + ) + return findings + + +# ---------------------------------------------------------------------- +# 11. Prometheus instrumentation inside the lifespan +# ---------------------------------------------------------------------- + + +def _startup_functions(tree: ast.Module) -> List[FunctionNode]: + """Functions that run once the app has started. + + The function passed as ``lifespan=``, any function decorated with + ``asynccontextmanager`` or named ``lifespan``, and ``on_event("startup")`` + handlers. + """ + lifespan_names: Set[str] = {"lifespan"} + for node in ast.walk(tree): + if isinstance(node, ast.Call): + lifespan = keyword(node, "lifespan") + if lifespan is not None and isinstance(lifespan.value, ast.Name): + lifespan_names.add(lifespan.value.id) + + functions: List[FunctionNode] = [] + for node in ast.walk(tree): + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + decorators = [ + dotted_name(d.func if isinstance(d, ast.Call) else d) + for d in node.decorator_list + ] + startup = any( + isinstance(d, ast.Call) + and dotted_name(d.func).endswith("on_event") + and d.args + and str_constant(d.args[0]) == "startup" + for d in node.decorator_list + ) + if ( + node.name in lifespan_names + or any(name.endswith("asynccontextmanager") for name in decorators) + or startup + ): + functions.append(node) + return functions + + +class PrometheusLifespanCheck(Check): + id = "prometheus-lifespan" + title = "Prometheus instrumentation runs inside the lifespan" + severity = Severity.MEDIUM + remediation = ( + "Move the instrumentation out of the lifespan function to module " + "level, right after `app = FastAPI(...)`:\n" + " app = FastAPI(..., lifespan=lifespan)\n" + " Instrumentator().instrument(app).expose(app)\n" + "It adds a middleware, and Starlette refuses to add middleware once the " + "application has started, so the app crashes at startup." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + relative, tree = _app_module_tree(ctx) + findings: List[Finding] = [] + for function in _startup_functions(tree): + for node in ast.walk(function): + if isinstance(node, ast.Call) and call_name(node) == "Instrumentator": + findings.append( + self.finding( + f"{relative}:{node.lineno} instruments the app inside " + f"{function.name}().", + relative, + ) + ) + break + return findings + + +__all__ = [ + "AppModuleMissingCheck", + "CorsCredentialsCheck", + "McpAuthCheck", + "McpDemoUsersCheck", + "PrometheusLifespanCheck", +] diff --git a/src/fastapi_fastkit/backend/doctor/checks_files.py b/src/fastapi_fastkit/backend/doctor/checks_files.py new file mode 100644 index 0000000..7fe7bec --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/checks_files.py @@ -0,0 +1,575 @@ +# -------------------------------------------------------------------------- +# Doctor checks about project files: line endings, packaging and tooling. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import re +from typing import Any, Dict, List, Optional, Tuple + +from fastapi_fastkit.backend.package_managers.pyproject import ( + PyprojectMergeError, + declared_requires_python, + replace_project_dependencies, +) +from fastapi_fastkit.core.settings import DEFAULT_PYTHON_VERSION +from fastapi_fastkit.utils.textio import CRLF, read_text_preserving_newlines + +from .context import GitUnavailable, ProjectContext +from .model import Check, CheckSkipped, Finding, FixRefused, PlannedEdit, Severity + +#: Template whose ``.gitattributes`` is used when the project's own +#: template is unknown (every template ships the same file). +FALLBACK_TEMPLATE = "fastapi-default" + +# ---------------------------------------------------------------------- +# 7a. .gitattributes missing +# ---------------------------------------------------------------------- + + +def template_gitattributes(ctx: ProjectContext) -> Optional[str]: + """The ``.gitattributes`` fastkit templates ship, read from the template.""" + if not ctx.template_root: + return None + for template in (ctx.template, FALLBACK_TEMPLATE): + if not template: + continue + path = os.path.join(ctx.template_root, template, ".gitattributes-tpl") + if os.path.isfile(path): + try: + text, _ = read_text_preserving_newlines(path) + except (OSError, UnicodeDecodeError): + continue + return text.replace(CRLF, "\n") + return None + + +class GitattributesMissingCheck(Check): + id = "gitattributes-missing" + title = "No .gitattributes pins LF line endings" + severity = Severity.LOW + fixable = True + remediation = ( + "Add the .gitattributes fastkit templates ship (the fix writes it). It " + "keeps shell scripts, Dockerfiles, compose files and .env files at LF " + "even with core.autocrlf=true, so they still run in Linux containers " + "when the project is checked out on Windows. In an existing " + "repository, run `git add --renormalize .` afterwards and commit, or " + "files already committed with CRLF show up as modified." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + if ctx.exists(".gitattributes"): + return [] + try: + # Inside a work tree a parent .gitattributes (a monorepo root) + # may already pin the line endings. + attributes = ctx.git_attributes(["Dockerfile", "scripts/x.sh"], "eol") + except GitUnavailable: + attributes = {} + if attributes and all( + values.get("eol") == "lf" for values in attributes.values() + ): + return [] + return [self.finding("The project has no .gitattributes.", ".gitattributes")] + + def plan_fix( + self, ctx: ProjectContext, findings: List[Finding] + ) -> List[PlannedEdit]: + content = template_gitattributes(ctx) + if content is None: + raise FixRefused("fastkit's template .gitattributes could not be read") + return [ + PlannedEdit( + path=".gitattributes", + content=content, + newline="\n", + original=None, + summary="create .gitattributes from the fastkit templates", + check_id=self.id, + ) + ] + + +# ---------------------------------------------------------------------- +# 7b. CRLF in shell scripts and Dockerfiles +# ---------------------------------------------------------------------- + + +def is_lf_only_file(relative_path: str) -> bool: + """Files that break with CRLF: shell scripts and Dockerfiles.""" + name = relative_path.rsplit("/", 1)[-1] + lowered = name.lower() + return ( + lowered.endswith((".sh", ".bash", ".dockerfile")) + or name.startswith("Dockerfile") + or lowered == "dockerfile" + ) + + +class CrlfScriptsCheck(Check): + id = "crlf-scripts" + title = "Shell scripts or Dockerfiles have CRLF line endings" + severity = Severity.MEDIUM + fixable = True + remediation = ( + "Convert the files to LF (the fix does) and add .gitattributes so Git " + "keeps them that way. With CRLF, `bash` fails with " + "`$'\\r': command not found` and containers with " + "`env: 'bash\\r': No such file or directory`." + ) + + def _crlf_files(self, ctx: ProjectContext) -> List[Tuple[str, str, str]]: + found = [] + for relative in ctx.walk_files(is_lf_only_file): + read = ctx.read_text(relative) + if read is None: + continue + text, newline = read + if newline == CRLF or "\r\n" in text: + found.append((relative, text, newline)) + return found + + def detect(self, ctx: ProjectContext) -> List[Finding]: + return [ + self.finding(f"{relative} has CRLF line endings.", relative) + for relative, _, _ in self._crlf_files(ctx) + ] + + def plan_fix( + self, ctx: ProjectContext, findings: List[Finding] + ) -> List[PlannedEdit]: + return [ + PlannedEdit( + path=relative, + content=text.replace(CRLF, "\n"), + newline="\n", + original=text, + original_newline=newline, + summary=f"convert {relative} from CRLF to LF line endings", + check_id=self.id, + show_diff=False, + ) + for relative, text, newline in self._crlf_files(ctx) + ] + + +# ---------------------------------------------------------------------- +# 8. requires-python below the template floor +# ---------------------------------------------------------------------- + +TEMPLATE_PYTHON_FLOOR: Tuple[int, int] = tuple( # type: ignore[assignment] + int(part) for part in DEFAULT_PYTHON_VERSION.split(".")[:2] +) + +_CLAUSE = re.compile( + r"^\s*(?P~=|===|==|!=|<=|>=|<|>|\^|~)?\s*(?P[0-9][0-9.*]*)" +) + + +def _version_tuple(text: str) -> Tuple[int, int]: + parts = [p for p in text.split(".") if p and p != "*"] + major = int(parts[0]) if parts else 0 + minor = int(parts[1]) if len(parts) > 1 else 0 + return major, minor + + +def python_floor(constraint: str) -> Optional[Tuple[int, int]]: + """The lowest ``(major, minor)`` a Python constraint allows. + + Understands PEP 440 clauses and Poetry's ``^`` / ``~`` / ``||``. Returns + None when the constraint sets no lower bound at all. + """ + floors: List[Optional[Tuple[int, int]]] = [] + for alternative in constraint.split("||"): + floor: Optional[Tuple[int, int]] = None + for clause in alternative.split(","): + match = _CLAUSE.match(clause) + if not match: + continue + op = match.group("op") or "==" + if op in ("<", "<=", "!="): + continue + version = _version_tuple(match.group("version")) + floor = version if floor is None else max(floor, version) + floors.append(floor) + if not floors or any(floor is None for floor in floors): + return None + return min(floor for floor in floors if floor is not None) + + +class RequiresPythonCheck(Check): + id = "requires-python" + title = "requires-python allows Python versions the template does not support" + severity = Severity.LOW + remediation = ( + f'Set requires-python = ">={DEFAULT_PYTHON_VERSION}" in [project] ' + "(pyproject.toml). fastkit templates use Python " + f"{DEFAULT_PYTHON_VERSION} syntax and libraries; an older floor lets " + "installers pick an interpreter the code does not run on." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + text, data = ctx.pyproject() + if text is None or data is None: + raise CheckSkipped("pyproject.toml is missing or not valid TOML") + constraint = declared_requires_python(text) + if constraint is None: + return [ + self.finding( + "pyproject.toml declares no requires-python.", "pyproject.toml" + ) + ] + floor = python_floor(constraint) + if floor is not None and floor >= TEMPLATE_PYTHON_FLOOR: + return [] + return [ + self.finding( + f'requires-python = "{constraint}" allows Python older than ' + f"{DEFAULT_PYTHON_VERSION}.", + "pyproject.toml", + ) + ] + + +# ---------------------------------------------------------------------- +# 9. plain sqlalchemy with the asyncio extension and no greenlet +# ---------------------------------------------------------------------- + +_REQUIREMENT = re.compile( + r"^(?P\s*)(?P[A-Za-z0-9][A-Za-z0-9._-]*)" + r"(?P\s*\[[^\]]*\])?(?P.*)$" +) + + +#: A requirement line the sqlalchemy fix may rewrite: a name, optional +#: extras, version clauses and an environment marker; no options +#: (``--hash``), direct URLs (``@``) or line continuations. +_SIMPLE_REQUIREMENT = re.compile( + r"^[A-Za-z0-9][A-Za-z0-9._-]*\s*(?:\[[A-Za-z0-9._,\s-]*\])?" + r"\s*(?:(?:~=|===|==|!=|<=|>=|<|>)\s*[A-Za-z0-9.*+!_-]+\s*,?\s*)*" + r"(?:;[^\\@]*)?$" +) + + +def _normalise(name: str) -> str: + return re.sub(r"[-_.]+", "-", name).lower() + + +def _split_requirement(spec: str) -> Optional[Tuple[str, List[str], str]]: + """``(normalised name, extras, rest)`` of a requirement string.""" + match = _REQUIREMENT.match(spec) + if not match: + return None + extras_text = (match.group("extras") or "").strip()[1:-1] + extras = [e.strip().lower() for e in extras_text.split(",") if e.strip()] + return _normalise(match.group("name")), extras, match.group("rest") + + +def is_plain_sqlalchemy(spec: str) -> bool: + parsed = _split_requirement(spec) + return ( + parsed is not None and parsed[0] == "sqlalchemy" and "asyncio" not in parsed[1] + ) + + +def with_asyncio_extra(spec: str) -> str: + """``SQLAlchemy>=2.0`` -> ``SQLAlchemy[asyncio]>=2.0`` (extras merged).""" + match = _REQUIREMENT.match(spec) + if not match: + return spec + extras_text = (match.group("extras") or "").strip()[1:-1] + extras = [e.strip() for e in extras_text.split(",") if e.strip()] + extras.append("asyncio") + return ( + f"{match.group('lead')}{match.group('name')}[{','.join(extras)}]" + f"{match.group('rest')}" + ) + + +def _requirement_lines(text: str) -> List[str]: + lines = [] + for line in text.split("\n"): + stripped = line.split("#", 1)[0].strip() + if stripped and not stripped.startswith("-"): + lines.append(stripped) + return lines + + +def _project_dependencies(data: Dict[str, Any]) -> List[str]: + deps: List[str] = [] + project = data.get("project") + if isinstance(project, dict) and isinstance(project.get("dependencies"), list): + deps += [d for d in project["dependencies"] if isinstance(d, str)] + poetry = data.get("tool", {}).get("poetry", {}).get("dependencies", {}) + if isinstance(poetry, dict): + for name, value in poetry.items(): + extras = value.get("extras", []) if isinstance(value, dict) else [] + deps.append(f"{name}[{','.join(extras)}]" if extras else name) + return deps + + +def _imports_async_sqlalchemy(ctx: ProjectContext) -> bool: + import ast + + for _, tree in ctx.iter_python_trees(include_tests=True): + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and (node.module or "").startswith( + "sqlalchemy.ext.asyncio" + ): + return True + if isinstance(node, ast.Import) and any( + alias.name.startswith("sqlalchemy.ext.asyncio") for alias in node.names + ): + return True + return False + + +class SqlalchemyAsyncioCheck(Check): + id = "sqlalchemy-asyncio" + title = "Async SQLAlchemy is used without greenlet" + severity = Severity.MEDIUM + fixable = True + remediation = ( + "Depend on `sqlalchemy[asyncio]` instead of `sqlalchemy` (or add " + "`greenlet`) in pyproject.toml and requirements.txt, then reinstall. " + "Plain sqlalchemy can install without greenlet, and the app or Alembic " + "then fails at import." + ) + + def _state(self, ctx: ProjectContext) -> Tuple[List[str], bool]: + """``(files declaring plain sqlalchemy, greenlet declared anywhere)``.""" + plain_in: List[str] = [] + all_deps: List[str] = [] + _, data = ctx.pyproject() + if data is not None: + deps = _project_dependencies(data) + all_deps += deps + if any(is_plain_sqlalchemy(d) for d in deps): + plain_in.append("pyproject.toml") + read = ctx.read_text("requirements.txt") + if read is not None: + deps = _requirement_lines(read[0]) + all_deps += deps + if any(is_plain_sqlalchemy(d) for d in deps): + plain_in.append("requirements.txt") + has_greenlet = any( + (_split_requirement(d) or ("",))[0] == "greenlet" for d in all_deps + ) + return plain_in, has_greenlet + + def detect(self, ctx: ProjectContext) -> List[Finding]: + plain_in, has_greenlet = self._state(ctx) + if not plain_in or has_greenlet or not _imports_async_sqlalchemy(ctx): + return [] + return [ + self.finding( + f"{' and '.join(plain_in)} depend on plain sqlalchemy, the code " + "imports sqlalchemy.ext.asyncio and nothing declares greenlet.", + *plain_in, + ) + ] + + def plan_fix( + self, ctx: ProjectContext, findings: List[Finding] + ) -> List[PlannedEdit]: + plain_in, _ = self._state(ctx) + edits: List[PlannedEdit] = [] + if "pyproject.toml" in plain_in: + edits.append(self._pyproject_edit(ctx)) + if "requirements.txt" in plain_in: + edits.append(self._requirements_edit(ctx)) + return edits + + def _pyproject_edit(self, ctx: ProjectContext) -> PlannedEdit: + read = ctx.read_text("pyproject.toml") + _, data = ctx.pyproject() + if read is None or data is None: + raise FixRefused("pyproject.toml could not be read") + text, newline = read + project = data.get("project") + deps = project.get("dependencies") if isinstance(project, dict) else None + if not isinstance(deps, list) or not any( + isinstance(d, str) and is_plain_sqlalchemy(d) for d in deps + ): + raise FixRefused( + "sqlalchemy is not declared in [project].dependencies " + "(Poetry table?); edit pyproject.toml by hand" + ) + updated_deps = [ + ( + with_asyncio_extra(d) + if isinstance(d, str) and is_plain_sqlalchemy(d) + else d + ) + for d in deps + ] + try: + updated = replace_project_dependencies(text, updated_deps) + except PyprojectMergeError as e: + raise FixRefused(f"pyproject.toml cannot be edited safely: {e}") from e + if updated is None: + raise FixRefused("[project].dependencies could not be located") + return PlannedEdit( + path="pyproject.toml", + content=updated, + newline=newline, + original=text, + original_newline=newline, + summary="depend on sqlalchemy[asyncio] in pyproject.toml", + check_id=self.id, + ) + + def _requirements_edit(self, ctx: ProjectContext) -> PlannedEdit: + read = ctx.read_text("requirements.txt") + if read is None: + raise FixRefused("requirements.txt could not be read") + text, newline = read + if "--hash" in text: + raise FixRefused( + "requirements.txt is hash-pinned (--hash); regenerate it with " + "sqlalchemy[asyncio] (and greenlet's hashes) using your lock tool" + ) + lines = text.split("\n") + for index, line in enumerate(lines): + body, sep, comment = line.partition("#") + if body.strip() and is_plain_sqlalchemy(body.strip()): + if not _SIMPLE_REQUIREMENT.match(body.strip()): + raise FixRefused( + f"requirements.txt line {index + 1} is not a plain " + "requirement (options, a URL or a line continuation); " + "edit it by hand" + ) + lines[index] = with_asyncio_extra(body) + sep + comment + return PlannedEdit( + path="requirements.txt", + content="\n".join(lines), + newline=newline, + original=text, + original_newline=newline, + summary="depend on sqlalchemy[asyncio] in requirements.txt", + check_id=self.id, + ) + + +# ---------------------------------------------------------------------- +# 12. pre-commit pinned to a python3.x interpreter +# ---------------------------------------------------------------------- + +_DEFAULT_LANGUAGE_VERSION = re.compile(r"^default_language_version:\s*(#.*)?$") +_PYTHON_PIN = re.compile(r"""^\s+python:\s*['"]?python3(\.\d+)?['"]?\s*(#.*)?$""") + + +def _pinned_python_lines(lines: List[str]) -> Tuple[Optional[int], List[int]]: + """``(header index, indices of python pins)`` in a pre-commit config.""" + for index, line in enumerate(lines): + if _DEFAULT_LANGUAGE_VERSION.match(line.rstrip("\r")): + end = _block_end(lines, index) + pins = [ + i + for i in range(index + 1, end) + if _PYTHON_PIN.match(lines[i].rstrip("\r")) + ] + return index, pins + return None, [] + + +def _block_end(lines: List[str], header: int) -> int: + """Index just past the last indented line under ``header``.""" + end = header + 1 + cursor = header + 1 + while cursor < len(lines): + current = lines[cursor].rstrip("\r") + if current.strip() and not current[:1].isspace(): + break + if current.strip(): + end = cursor + 1 + cursor += 1 + return end + + +class PreCommitPythonCheck(Check): + id = "pre-commit-python" + title = ".pre-commit-config.yaml pins a python3.x interpreter" + severity = Severity.LOW + fixable = True + remediation = ( + "Remove `python: python3.x` from default_language_version in " + ".pre-commit-config.yaml (the fix does). The pin makes every commit " + "fail where that exact interpreter is not on PATH (Git GUI clients, " + "Windows, other Python versions); hooks then run with the Python " + "pre-commit itself uses." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + read = ctx.read_text(".pre-commit-config.yaml") + if read is None: + raise CheckSkipped("the project has no .pre-commit-config.yaml") + _, pins = _pinned_python_lines(read[0].split("\n")) + if not pins: + return [] + return [ + self.finding( + ".pre-commit-config.yaml sets default_language_version.python " + "to a python3.x interpreter.", + ".pre-commit-config.yaml", + ) + ] + + def plan_fix( + self, ctx: ProjectContext, findings: List[Finding] + ) -> List[PlannedEdit]: + read = ctx.read_text(".pre-commit-config.yaml") + if read is None: + raise FixRefused(".pre-commit-config.yaml could not be read") + text, newline = read + lines = text.split("\n") + header, pins = _pinned_python_lines(lines) + if header is None or not pins: + return [] + end = _block_end(lines, header) + others = [ + i + for i in range(header + 1, end) + if i not in pins + and lines[i].strip() + and not lines[i].strip().startswith("#") + ] + if others: + kept = [line for i, line in enumerate(lines) if i not in pins] + else: + # Nothing else under the key: drop the whole block and one of the + # blank lines it leaves behind. + kept = lines[:header] + lines[end:] + at_start_or_after_blank = header == 0 or not kept[header - 1].strip() + if ( + header < len(kept) + and not kept[header].strip() + and at_start_or_after_blank + ): + del kept[header] + return [ + PlannedEdit( + path=".pre-commit-config.yaml", + content="\n".join(kept), + newline=newline, + original=text, + original_newline=newline, + summary="remove the python3.x pin from .pre-commit-config.yaml", + check_id=self.id, + ) + ] + + +__all__ = [ + "CrlfScriptsCheck", + "GitattributesMissingCheck", + "PreCommitPythonCheck", + "RequiresPythonCheck", + "SqlalchemyAsyncioCheck", + "is_lf_only_file", + "is_plain_sqlalchemy", + "python_floor", + "template_gitattributes", + "with_asyncio_extra", +] diff --git a/src/fastapi_fastkit/backend/doctor/checks_secrets.py b/src/fastapi_fastkit/backend/doctor/checks_secrets.py new file mode 100644 index 0000000..e1c32b5 --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/checks_secrets.py @@ -0,0 +1,466 @@ +# -------------------------------------------------------------------------- +# Doctor checks about secrets: .env handling and example keys. +# +# These find the problems v1.5.2 fixed in newly generated projects +# (committed .env, missing ignore rules, the shared example SECRET_KEY, +# SESSION_SECRET_KEY with a default) in projects generated before it. +# No check ever reports a value: only file and variable names. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +import fnmatch +from typing import Callable, List, Tuple + +from .context import GitUnavailable, ProjectContext +from .envfile import build_env_example, find_env_value_keys +from .known import ENV_EXAMPLE_NAMES, KNOWN_EXAMPLE_SECRETS +from .model import Check, CheckSkipped, Finding, FixRefused, PlannedEdit, Severity +from .pyast import ( + call_name, + dotted_name, + has_kwargs_unpack, + is_env_read, + keyword, + str_constant, + target_name, +) + +GENERATE_KEY_COMMAND = 'python -c "import secrets; print(secrets.token_urlsafe(32))"' + + +def _is_env_variant(name: str) -> bool: + """``.env`` or ``.env.``, excluding the committed examples.""" + return (name == ".env" or name.startswith(".env.")) and name not in ( + ENV_EXAMPLE_NAMES + ) + + +def env_files(ctx: ProjectContext) -> List[str]: + """Local env files at the project root (``.env``, ``.env.local``, ...).""" + return ctx.walk_files(lambda rel: "/" not in rel and _is_env_variant(rel)) + + +def append_lines(text: str, newline: str, lines: List[str]) -> str: + """Append ``lines`` to file text read with ``read_text_preserving_newlines``. + + Text read in CRLF mode is ``\\n``-separated and gets CRLF back on + write. Untranslated text (LF, or mixed) gets ``\\r\\n`` separators when + it already contains any, ``\\n`` otherwise. + """ + sep = "\r\n" if (newline == "" and "\r\n" in text) else "\n" + prefix = "" + if text and not text.endswith("\n"): + prefix = sep + if text.strip(): + prefix += sep # blank line between the old content and the block + return text + prefix + sep.join(lines) + sep + + +# ---------------------------------------------------------------------- +# 1. .env tracked by git +# ---------------------------------------------------------------------- + + +class EnvTrackedCheck(Check): + id = "env-tracked" + title = ".env is committed to git" + severity = Severity.HIGH + remediation = ( + "Run `git rm --cached ` for each file listed and commit; the file " + "stays on disk. Then rotate every secret it contained (SECRET_KEY, " + "database passwords, API keys such as ANTHROPIC_API_KEY / " + "LLM_AUTH_TOKEN / MCP_API_KEY, FIRST_SUPERUSER_PASSWORD, ...): " + "removing a file from the index does not remove it from Git history. " + "Rewrite history only if the old values must also disappear from the " + "repository. This is never fixed automatically." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + try: + tracked = ctx.git_tracked(".env", ".env.*") + except GitUnavailable as e: + raise CheckSkipped(str(e)) from e + leaked = [path for path in tracked if "/" not in path and _is_env_variant(path)] + if not leaked: + return [] + return [ + self.finding( + f"{', '.join(leaked)} is in the git index and is pushed with " + "every commit.", + *leaked, + ) + ] + + +# ---------------------------------------------------------------------- +# 2. .gitignore rules for .env +# ---------------------------------------------------------------------- + +GITIGNORE_BLOCK = [ + "# Local environment files hold secrets; commit .env.example instead.", + ".env", + ".env.*", + "!.env.example", +] + + +def gitignore_ignores(lines: List[str], name: str) -> bool: + """Whether a root ``.gitignore`` ignores the root-level file ``name``. + + Implements the subset of gitignore matching that applies to a file in + the repository root: comments, negation, anchoring, directory-only + patterns and ``**/``; the last matching pattern wins. + """ + ignored = False + for raw in lines: + line = raw.rstrip("\r").rstrip() + if not line or line.startswith("#"): + continue + negate = line.startswith("!") + if negate: + line = line[1:] + if line.startswith("\\"): + line = line[1:] + if line.endswith("/"): + continue # directories only; ``name`` is a file + while line.startswith("**/"): + line = line[3:] + line = line.lstrip("/") + if not line or "/" in line: + continue # a pattern for a path below the root + if fnmatch.fnmatchcase(name, line): + ignored = not negate + return ignored + + +class GitignoreEnvCheck(Check): + id = "gitignore-env" + title = ".gitignore does not keep .env out of git" + severity = Severity.MEDIUM + fixable = True + remediation = "Add these lines to .gitignore (the fix appends them):\n" + "\n".join( + GITIGNORE_BLOCK[1:] + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + try: + ignored = ctx.git_ignored([".env", ".env.local", ".env.example"]) + except GitUnavailable: + ignored = None + if ignored is not None: + # Inside a work tree git decides, so the rules of a parent + # directory (a monorepo root) count as well. + problems = self._problems(ignored.__contains__) + if not problems: + return [] + if not ctx.exists(".gitignore"): + problems.insert(0, "the project has no .gitignore") + message = "; ".join(problems) + return [self.finding(message[:1].upper() + message[1:] + ".", ".gitignore")] + read = ctx.read_text(".gitignore") + if read is None: + if ctx.exists(".gitignore"): + raise CheckSkipped(".gitignore is not readable UTF-8 text") + return [self.finding("The project has no .gitignore.", ".gitignore")] + lines = read[0].split("\n") + problems = self._problems(lambda name: gitignore_ignores(lines, name)) + if not problems: + return [] + return [self.finding("; ".join(problems) + ".", ".gitignore")] + + @staticmethod + def _problems(is_ignored: Callable[[str], bool]) -> List[str]: + problems = [] + if not is_ignored(".env"): + problems.append(".env is not ignored") + if not is_ignored(".env.local"): + problems.append(".env.* files (such as .env.local) are not ignored") + if is_ignored(".env.example"): + problems.append(".env.example is ignored and cannot be committed") + return problems + + def plan_fix( + self, ctx: ProjectContext, findings: List[Finding] + ) -> List[PlannedEdit]: + read = ctx.read_text(".gitignore") + if read is None: + return [ + PlannedEdit( + path=".gitignore", + content="\n".join(GITIGNORE_BLOCK) + "\n", + newline="\n", + original=None, + summary="create .gitignore with the .env rules", + check_id=self.id, + ) + ] + text, newline = read + return [ + PlannedEdit( + path=".gitignore", + content=append_lines(text, newline, GITIGNORE_BLOCK), + newline=newline, + original=text, + original_newline=newline, + summary="append the .env rules to .gitignore", + check_id=self.id, + ) + ] + + +# ---------------------------------------------------------------------- +# 3. .env.example missing +# ---------------------------------------------------------------------- + + +class EnvExampleMissingCheck(Check): + id = "env-example-missing" + title = ".env exists but .env.example does not" + severity = Severity.MEDIUM + fixable = True + remediation = ( + "Commit a .env.example that lists every variable without real values, " + "so others know what to set. The fix writes it from .env: comments are " + "dropped, and every value is removed except plain values of settings " + "that are never secret (ENVIRONMENT, DEBUG, HOST, PORT, token " + "lifetimes, MCP_* titles, ...); a value with user info, unusual " + "characters or anything token-like is removed even then. Review the " + "file before committing it. A committed .env.sample, .env.template or " + ".env.dist counts as well." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + if not ctx.is_file(".env"): + raise CheckSkipped("the project has no .env") + # Any committed variant (.env.sample, .env.template, ...) does the job. + if any(ctx.exists(name) for name in ENV_EXAMPLE_NAMES): + return [] + return [self.finding("There is no .env.example next to .env.", ".env")] + + def plan_fix( + self, ctx: ProjectContext, findings: List[Finding] + ) -> List[PlannedEdit]: + read = ctx.read_text(".env") + if read is None: + raise FixRefused(".env is not readable UTF-8 text") + content, kept, blanked = build_env_example(read[0]) + summary = ( + f"create .env.example from .env: {len(blanked)} value(s) removed, " + f"{len(kept)} non-secret value(s) kept" + ) + return [ + PlannedEdit( + path=".env.example", + content=content, + newline="\n", + original=None, + summary=summary, + check_id=self.id, + ) + ] + + +# ---------------------------------------------------------------------- +# 4. Example secrets still in use +# ---------------------------------------------------------------------- + + +def _secret_assignments(tree: ast.Module) -> List[Tuple[int, str]]: + """``(line, name)`` of every place a known example secret is set. + + Covers assignments and settings defaults (``SECRET_KEY: str = ...``), + keyword arguments (``secret_key=...``, ``Field(default=...)``), + function defaults and ``os.getenv("NAME", )``. Membership + tests and frozensets of known values (the templates' SECRET_KEY guard) + do not count. + """ + found: List[Tuple[int, str]] = [] + for node in ast.walk(tree): + if isinstance(node, (ast.Assign, ast.AnnAssign)): + if str_constant(node.value) in KNOWN_EXAMPLE_SECRETS: + targets = ( + node.targets if isinstance(node, ast.Assign) else [node.target] + ) + for target in targets: + found.append((node.lineno, target_name(target) or "")) + elif isinstance(node, ast.Call): + for kw in node.keywords: + if kw.arg and str_constant(kw.value) in KNOWN_EXAMPLE_SECRETS: + found.append((node.lineno, kw.arg)) + if ( + is_env_read(node) + and len(node.args) >= 2 + and str_constant(node.args[1]) in KNOWN_EXAMPLE_SECRETS + ): + name = str_constant(node.args[0]) or "" + found.append((node.lineno, name)) + elif isinstance(node, ast.arguments): + positional = node.posonlyargs + node.args + pairs = list( + zip(positional[len(positional) - len(node.defaults) :], node.defaults) + ) + pairs += [ + (arg, default) + for arg, default in zip(node.kwonlyargs, node.kw_defaults) + if default is not None + ] + for arg, default in pairs: + if str_constant(default) in KNOWN_EXAMPLE_SECRETS: + found.append((default.lineno, arg.arg)) + return sorted(set(found)) + + +class ExampleSecretCheck(Check): + id = "example-secret" + title = "An example secret shipped by fastkit is still in use" + severity = Severity.HIGH + remediation = ( + "Generate a key with\n" + f" {GENERATE_KEY_COMMAND}\n" + "and set it as SECRET_KEY in .env and in every deployment environment; " + "remove hard-coded example values from the code. Changing SECRET_KEY " + "invalidates every token and session signed with the old key, so users " + "have to log in again." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + findings: List[Finding] = [] + for relative in env_files(ctx): + read = ctx.read_text(relative) + if read is None: + continue + keys = find_env_value_keys(read[0], KNOWN_EXAMPLE_SECRETS) + if keys: + findings.append( + self.finding( + f"{relative} sets {', '.join(keys)} to an example value.", + relative, + ) + ) + for relative, tree in ctx.iter_python_trees(): + for line, name in _secret_assignments(tree): + findings.append( + self.finding( + f"{relative}:{line} sets {name} to an example value.", + relative, + ) + ) + return findings + + +# ---------------------------------------------------------------------- +# 13. Session / OAuth2 secret +# ---------------------------------------------------------------------- + + +def _has_default(value: "ast.expr | None") -> bool: + """Whether a settings field value gives the field a default. + + ``NAME: str`` and ``NAME: str = Field(...)`` (or ``Field()`` without + ``default``/``default_factory``) are required fields. + """ + if value is None: + return False + if isinstance(value, ast.Call) and call_name(value) == "Field": + if value.args: + first = value.args[0] + return not (isinstance(first, ast.Constant) and first.value is Ellipsis) + return any( + kw.arg in ("default", "default_factory") + and not (isinstance(kw.value, ast.Constant) and kw.value.value is Ellipsis) + for kw in value.keywords + ) + return True + + +def _session_secret_problems(tree: ast.Module) -> List[Tuple[int, str]]: + """Places a session signing key gets a fallback value or is hard-coded. + + A separate ``SESSION_SECRET_KEY`` that is *required* (a settings field + without default, ``os.environ["SESSION_SECRET_KEY"]``, ``os.getenv`` + without default) is a deliberate choice and is not reported. + """ + found: List[Tuple[int, str]] = [] + for node in ast.walk(tree): + if isinstance(node, ast.Call): + if ( + is_env_read(node) + and node.args + and str_constant(node.args[0]) == "SESSION_SECRET_KEY" + and (len(node.args) >= 2 or keyword(node, "default") is not None) + ): + found.append( + (node.lineno, "reads SESSION_SECRET_KEY with a default value") + ) + uses_session_middleware = call_name(node) == "SessionMiddleware" or any( + dotted_name(arg).endswith("SessionMiddleware") for arg in node.args + ) + if uses_session_middleware and not has_kwargs_unpack(node): + secret = keyword(node, "secret_key") + if secret is not None and str_constant(secret.value) is not None: + found.append( + ( + node.lineno, + "passes a hard-coded secret_key to SessionMiddleware", + ) + ) + elif isinstance(node, ast.ClassDef): + for statement in node.body: + if ( + isinstance(statement, ast.AnnAssign) + and target_name(statement.target) == "SESSION_SECRET_KEY" + and _has_default(statement.value) + ) or ( + isinstance(statement, ast.Assign) + and any( + target_name(t) == "SESSION_SECRET_KEY" + for t in statement.targets + ) + ): + found.append( + ( + statement.lineno, + "declares a SESSION_SECRET_KEY setting with a default " + "value", + ) + ) + return sorted(set(found)) + + +class SessionSecretCheck(Check): + id = "session-secret" + title = "Session signing key has a default value or is hard-coded" + severity = Severity.HIGH + remediation = ( + "Sign the session cookie with the project's SECRET_KEY:\n" + " app.add_middleware(SessionMiddleware, secret_key=settings.SECRET_KEY)\n" + "and remove SESSION_SECRET_KEY (and its default) from the code and .env. " + "If you keep a separate session key on purpose, make it required (a " + "settings field without default) so the app cannot start with a " + "fallback value. " + "Modules generated by `fastkit init` since v1.5.2 read SECRET_KEY from " + ".env and refuse a missing or example key outside development; a newly " + "generated project with Session-based or OAuth2 auth shows the full " + "module." + ) + + def detect(self, ctx: ProjectContext) -> List[Finding]: + findings: List[Finding] = [] + for relative, tree in ctx.iter_python_trees(): + for line, problem in _session_secret_problems(tree): + findings.append(self.finding(f"{relative}:{line} {problem}.", relative)) + return findings + + +__all__ = [ + "EnvExampleMissingCheck", + "EnvTrackedCheck", + "ExampleSecretCheck", + "GITIGNORE_BLOCK", + "GitignoreEnvCheck", + "SessionSecretCheck", + "append_lines", + "env_files", + "gitignore_ignores", +] diff --git a/src/fastapi_fastkit/backend/doctor/command.py b/src/fastapi_fastkit/backend/doctor/command.py new file mode 100644 index 0000000..ec0c30d --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/command.py @@ -0,0 +1,214 @@ +# -------------------------------------------------------------------------- +# The ``fastkit doctor`` command flow, kept apart from Click option parsing. +# +# check -> report -> (with --fix) plan -> show diffs -> confirm -> apply +# -> check again. Exit status: 0 no problem remains, 1 problems remain, +# 2 doctor could not run (not a fastkit project, unreadable project, a +# check crashed, or --fix refused to ask for confirmation without a +# terminal). +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import json +from dataclasses import dataclass +from typing import Any, Callable, Dict, Optional + +import click +from rich.console import Console +from rich.text import Text + +from fastapi_fastkit.utils.main import console as default_console +from fastapi_fastkit.utils.main import ( + print_error, + print_info, + print_success, + print_warning, +) +from fastapi_fastkit.utils.platform import stdin_is_interactive + +from .context import DoctorError, ProjectContext +from .render import ( + error_to_json, + render_edits, + render_findings, + render_report, + report_to_json, +) +from .runner import DoctorReport, apply_edits, run_checks + +EXIT_OK = 0 +EXIT_PROBLEMS = 1 +EXIT_CANNOT_RUN = 2 + + +@dataclass +class DoctorOptions: + """Inputs of one ``fastkit doctor`` run.""" + + path: str = "." + fix: bool = False + dry_run: bool = False + assume_yes: bool = False + output_format: str = "text" + force: bool = False + template_root: Optional[str] = None + + +def _summary(report: DoctorReport, console: Console) -> None: + if report.unreadable: + print_warning( + f"{len(report.unreadable)} file(s) could not be read or parsed: " + + ", ".join(report.unreadable) + + ". Checks that need them report status error.", + console=console, + ) + if report.problem_count == 0: + if report.errors: + print_warning( + f"{len(report.errors)} check(s) could not run; see the table above.", + console=console, + ) + else: + print_success("No problems found.", console=console) + return + counts = report.count_by_severity() + breakdown = ", ".join(f"{n} {name}" for name, n in counts.items() if n) + fixable = sum(len(r.findings) for r in report.results if r.fixable) + message = f"{report.problem_count} problem(s) found ({breakdown})." + if fixable: + message += ( + f" {fixable} can be fixed automatically: run `fastkit doctor --fix` " + "to review and apply the changes." + ) + print_warning(message, console=console) + + +def run_doctor( + options: DoctorOptions, + console: Optional[Console] = None, + echo: Callable[[str], Any] = click.echo, + confirm: Callable[..., bool] = click.confirm, +) -> int: + """ + Run ``fastkit doctor`` and return its exit status. + + :param options: Command options + :param console: Rich console for text output (the shared fastkit + console by default) + :param echo: Writes the JSON document to stdout + :param confirm: Asks the ``--fix`` confirmation question + :return: 0, 1 or 2 (see the module header) + """ + out = console or default_console + as_json = options.output_format == "json" + fix = options.fix or options.dry_run + + def emit(document: Dict[str, Any]) -> None: + echo(json.dumps(document, indent=2)) + + def fail(message: str) -> int: + if as_json: + emit(error_to_json(message)) + else: + print_error(message, console=out) + return EXIT_CANNOT_RUN + + if as_json and fix and not options.dry_run and not options.assume_yes: + return fail( + "--fix with --format json cannot ask for confirmation: add --yes to " + "apply the fixes, or --dry-run to only list them." + ) + + try: + ctx = ProjectContext.load( + options.path, template_root=options.template_root, force=options.force + ) + except DoctorError as e: + return fail(str(e)) + + report = run_checks(ctx) + edits = report.edits + + if not as_json: + render_report(report, out) + + if not fix: + if as_json: + emit(report_to_json(report)) + else: + _summary(report, out) + return report.exit_code + + if not edits: + if as_json: + emit(report_to_json(report, planned=[], dry_run=options.dry_run)) + else: + if report.problem_count: + print_info( + "None of the problems can be fixed automatically; follow " + "the 'How to fix' steps above.", + console=out, + ) + _summary(report, out) + return report.exit_code + + if not as_json: + out.print() + out.rule(Text("Planned changes", style="bold"), align="left") + render_edits(edits, out) + out.print() + + if options.dry_run: + if as_json: + emit(report_to_json(report, planned=edits, dry_run=True)) + else: + print_info( + f"Dry run: {len(edits)} file change(s) shown, nothing was written.", + console=out, + ) + return report.exit_code + + if not options.assume_yes: + if not stdin_is_interactive(): + print_error( + "Refusing to change files without confirmation: there is no " + "terminal to ask. Re-run with --yes to apply the changes shown " + "above, or with --dry-run to only show them.", + console=out, + ) + return EXIT_CANNOT_RUN + if not confirm(f"Apply these {len(edits)} file change(s)?", default=False): + print_warning("No changes were made.", console=out) + return report.exit_code + + outcome = apply_edits(ctx, edits) + after = run_checks( + ProjectContext( + ctx.root, + ctx.metadata if ctx.has_metadata else None, + ctx.template_root, + ) + ) + + if as_json: + emit(report_to_json(after, planned=edits, applied=outcome)) + return after.exit_code + + for path in outcome.applied: + out.print(Text(f"updated {path}", style="green")) + for path, reason in outcome.failed: + print_error(f"Could not update {path}: {reason}", console=out) + out.print() + out.rule(Text("After the fixes", style="bold"), align="left") + render_findings(after, out) + _summary(after, out) + return after.exit_code + + +__all__ = [ + "DoctorOptions", + "EXIT_CANNOT_RUN", + "EXIT_OK", + "EXIT_PROBLEMS", + "run_doctor", +] diff --git a/src/fastapi_fastkit/backend/doctor/context.py b/src/fastapi_fastkit/backend/doctor/context.py new file mode 100644 index 0000000..96dcd4e --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/context.py @@ -0,0 +1,612 @@ +# -------------------------------------------------------------------------- +# Read-only view of the project ``fastkit doctor`` examines. +# +# Checks reach the project only through ``ProjectContext``: file reads go +# through ``utils.textio`` (UTF-8, line endings reported, never translated), +# the file tree is walked once per run, parsed Python modules and +# ``pyproject.toml`` are cached, and git is run hardened: a scrubbed +# environment so a user's ``GIT_DIR`` or pager settings do not change the +# answer, and repository configuration that could run a command +# (``core.fsmonitor``, lazy fetches of a partial clone) switched off, so +# examining an untrusted checkout never executes anything from it. +# +# A missing file, a non-git directory or a missing ``git`` are normal +# results. A file that exists but cannot be read or parsed is recorded: +# the runner turns a check that needed it into an error instead of letting +# it pass silently. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +import contextlib +import os +import re +import shutil +import subprocess +import tomllib +from typing import ( + Any, + Callable, + Dict, + Iterator, + List, + Optional, + Sequence, + Set, + Tuple, +) + +from fastapi_fastkit.utils.main import FASTKIT_TOOL_SECTION, is_fastkit_project +from fastapi_fastkit.utils.textio import read_text_preserving_newlines + +#: Directories never walked: VCS data, virtualenvs, caches, build output. +EXCLUDED_DIRS = frozenset( + { + ".git", + ".hg", + ".svn", + ".venv", + "venv", + ".tox", + ".nox", + "node_modules", + "__pycache__", + ".mypy_cache", + ".pytest_cache", + ".ruff_cache", + "build", + "dist", + "site-packages", + ".eggs", + "htmlcov", + } +) + +#: Environment variables that would point git at another repository. +_GIT_REDIRECT_VARIABLES = ( + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_INDEX_FILE", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_NAMESPACE", + "GIT_COMMON_DIR", +) + +#: ``-c`` options passed to every git invocation. ``core.fsmonitor`` is a +#: command git runs on index reads (``ls-files``); ``protocol.allow=never`` +#: stops a partial clone from fetching missing objects (which would run +#: ``core.sshCommand`` and friends) while attributes are read. +GIT_HARDENING_OPTIONS: Tuple[str, ...] = ( + "-c", + "core.quotepath=off", + "-c", + "core.fsmonitor=false", + "-c", + "core.untrackedCache=false", + "-c", + "protocol.allow=never", +) + +#: A dotted module path as recorded in ``app_module`` (``src.main``). +_DOTTED_MODULE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$") +_IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") + + +class DoctorError(Exception): + """``fastkit doctor`` cannot examine the given path (exit status 2).""" + + +class GitUnavailable(Exception): + """git cannot answer for this project (not installed, not a repository).""" + + +def is_test_path(relative_path: str) -> bool: + """Whether a project-relative path belongs to the test suite.""" + parts = relative_path.split("/") + name = parts[-1] + if name == "conftest.py" or name.startswith("test_") or name.endswith("_test.py"): + return True + return any(part in ("tests", "test") for part in parts[:-1]) + + +def strip_bom(text: str) -> str: + """``text`` without a leading UTF-8 byte order mark.""" + return text[1:] if text.startswith("") else text + + +def valid_app_module(value: str) -> bool: + """Whether ``value`` is ``package.module`` or ``package.module:attr``.""" + module, sep, attribute = value.strip().partition(":") + if not _DOTTED_MODULE.match(module): + return False + return not sep or bool(_IDENTIFIER.match(attribute)) + + +def is_within(path: str, root: str) -> bool: + """Whether ``path`` resolves (symlinks followed) to a place inside ``root``.""" + real_path = os.path.realpath(path) + real_root = os.path.realpath(root) + try: + return os.path.commonpath([real_path, real_root]) == real_root + except ValueError: # different drives on Windows + return False + + +def git_environment() -> Dict[str, str]: + """The environment every hardened git call runs with.""" + env = dict(os.environ) + for name in _GIT_REDIRECT_VARIABLES: + env.pop(name, None) + env["GIT_TERMINAL_PROMPT"] = "0" + env["GIT_OPTIONAL_LOCKS"] = "0" + env["GIT_NO_LAZY_FETCH"] = "1" + env["GIT_PAGER"] = "cat" + env["PAGER"] = "cat" + env["LC_ALL"] = "C" + return env + + +def git_command(git: str, *args: str) -> List[str]: + """argv of a hardened git call (no pager, no optional locks, see + :data:`GIT_HARDENING_OPTIONS`).""" + return [git, "--no-pager", "--no-optional-locks", *GIT_HARDENING_OPTIONS, *args] + + +class ProjectContext: + """The project directory plus cached, read-only helpers for checks.""" + + def __init__( + self, + root: str, + metadata: Optional[Dict[str, Any]] = None, + template_root: Optional[str] = None, + ) -> None: + """ + :param root: Project directory + :param metadata: The ``[tool.fastapi-fastkit]`` table, or None when + the project has none (``--force``) + :param template_root: fastkit's template directory, used by fixes + that copy a file the templates ship + """ + self.root = os.path.abspath(root) + self.metadata: Dict[str, Any] = dict(metadata or {}) + self.has_metadata = metadata is not None + self.template_root = template_root + self._ast_cache: Dict[str, Optional[ast.Module]] = {} + self._pyproject: Optional[Tuple[Optional[str], Optional[Dict[str, Any]]]] = None + self._git_root: Optional[str] = None + self._git_checked = False + self._all_files: Optional[List[str]] = None + self._walk_errors: Dict[str, str] = {} + #: Every file that exists but could not be read or parsed, with why. + self.unreadable: Dict[str, str] = {} + self._touched: Optional[Dict[str, str]] = None + + # ------------------------------------------------------------------ + # Loading + # ------------------------------------------------------------------ + + @classmethod + def load( + cls, path: str, template_root: Optional[str] = None, force: bool = False + ) -> "ProjectContext": + """ + Open ``path`` as a fastkit project. + + :param path: Project directory + :param template_root: fastkit's template directory + :param force: Accept a project without ``[tool.fastapi-fastkit]`` + (generated before v1.4.0, or not by fastkit at all) + :raises DoctorError: when the directory cannot be examined + """ + root = os.path.abspath(path) + if not os.path.isdir(root): + raise DoctorError(f"'{path}' is not a directory.") + + pyproject_path = os.path.join(root, "pyproject.toml") + metadata: Optional[Dict[str, Any]] = None + if os.path.isfile(pyproject_path): + try: + text, _ = read_text_preserving_newlines(pyproject_path) + data = tomllib.loads(strip_bom(text)) + except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as e: + if not force: + raise DoctorError( + f"Cannot read '{pyproject_path}': {e}. Fix the file, or " + "re-run with --force to check the rest of the project." + ) from e + data = {} + tool = data.get("tool") + section = tool.get(FASTKIT_TOOL_SECTION) if isinstance(tool, dict) else None + if isinstance(section, dict): + metadata = section + + if metadata is None and not force: + if is_fastkit_project(root): + raise DoctorError( + f"'{path}' was generated by a fastkit version older than " + "1.4.0 and has no [tool.fastapi-fastkit] table in " + "pyproject.toml. Re-run with --force to check it anyway; " + "checks that need the recorded metadata are skipped." + ) + raise DoctorError( + f"'{path}' is not a FastAPI-fastkit project (no " + "[tool.fastapi-fastkit] table in pyproject.toml). Re-run with " + "--force to check it anyway." + ) + + return cls(root, metadata, template_root) + + # ------------------------------------------------------------------ + # Unreadable files + # ------------------------------------------------------------------ + + def record_unreadable(self, relative_path: str, reason: str) -> None: + """Note that an existing project file could not be read or parsed. + + Recorded for the whole run (the report lists the files) and for the + check currently running (the runner reports it as an error unless it + found real problems). + """ + self.unreadable.setdefault(relative_path, reason) + if self._touched is not None: + self._touched.setdefault(relative_path, self.unreadable[relative_path]) + + @contextlib.contextmanager + def tracking_unreadable(self) -> Iterator[Dict[str, str]]: + """Collect the unreadable files touched inside the ``with`` block.""" + previous = self._touched + touched: Dict[str, str] = {} + self._touched = touched + try: + yield touched + finally: + self._touched = previous + + # ------------------------------------------------------------------ + # Files + # ------------------------------------------------------------------ + + def path(self, relative_path: str) -> str: + """Absolute path of a ``/``-separated project-relative path.""" + return os.path.join(self.root, *relative_path.split("/")) + + def contains(self, relative_path: str) -> bool: + """Whether a project-relative path resolves to a place inside the root.""" + return is_within(self.path(relative_path), self.root) + + def exists(self, relative_path: str) -> bool: + return os.path.exists(self.path(relative_path)) + + def is_file(self, relative_path: str) -> bool: + return os.path.isfile(self.path(relative_path)) + + def unsafe_write_reason(self, relative_path: str) -> Optional[str]: + """Why ``doctor --fix`` must not write ``relative_path``, if it must not. + + A path is refused when it, or any directory between the project root + and it, is a symbolic link (the fix would replace the link with a + regular file, or write somewhere else), or when it resolves outside + the project. + """ + parts = [part for part in relative_path.split("/") if part] + if ( + not parts + or relative_path.startswith(("/", "\\")) + or os.path.isabs(relative_path) + or any(part in (".", "..") or "\\" in part or ":" in part for part in parts) + ): + return f"{relative_path} is not a plain path inside the project" + current = self.root + for index, part in enumerate(parts): + current = os.path.join(current, part) + if os.path.islink(current): + shown = "/".join(parts[: index + 1]) + return f"{shown} is a symbolic link; edit its target by hand" + if not is_within(self.path(relative_path), self.root): + return f"{relative_path} resolves outside the project" + return None + + def read_text(self, relative_path: str) -> Optional[Tuple[str, str]]: + """ + Read a project file for checking or editing. + + :return: ``(text, newline)`` as returned by + :func:`~fastapi_fastkit.utils.textio.read_text_preserving_newlines`, + or None when the file does not exist, or is not readable UTF-8 + text (recorded as unreadable) + """ + path = self.path(relative_path) + if not os.path.isfile(path): + return None + try: + return read_text_preserving_newlines(path) + except UnicodeDecodeError as e: + self.record_unreadable(relative_path, f"not UTF-8 text ({e.reason})") + except OSError as e: + self.record_unreadable(relative_path, f"cannot be read ({e.strerror or e})") + return None + + def _walk(self) -> List[str]: + """Every project file, walked once per context (cached).""" + if self._all_files is None: + found: List[str] = [] + + def unreadable_directory(error: OSError) -> None: + where = os.path.relpath(error.filename or self.root, self.root) + relative = "." if where == "." else where.replace(os.sep, "/") + self._walk_errors[relative] = ( + f"directory cannot be listed ({error.strerror or error})" + ) + + for directory, dirnames, filenames in os.walk( + self.root, onerror=unreadable_directory + ): + dirnames[:] = sorted( + name + for name in dirnames + if name not in EXCLUDED_DIRS + and not os.path.isfile(os.path.join(directory, name, "pyvenv.cfg")) + ) + relative_dir = os.path.relpath(directory, self.root) + prefix = ( + "" if relative_dir == "." else relative_dir.replace(os.sep, "/") + ) + for name in filenames: + found.append(f"{prefix}/{name}" if prefix else name) + self._all_files = sorted(found) + return self._all_files + + def walk_files(self, predicate: Callable[[str], bool]) -> List[str]: + """Project-relative paths of every file whose path matches ``predicate``. + + Virtualenvs (any directory holding ``pyvenv.cfg``), VCS data and + caches are not walked. The tree is walked once per context; the + result is sorted. Directories that cannot be listed are recorded as + unreadable for every check that walks the tree. + """ + files = self._walk() + for relative, reason in self._walk_errors.items(): + self.record_unreadable(relative, reason) + return [relative for relative in files if predicate(relative)] + + def python_files(self, include_tests: bool = False) -> List[str]: + """Project-relative paths of the project's ``.py`` files.""" + return self.walk_files( + lambda rel: rel.endswith(".py") and (include_tests or not is_test_path(rel)) + ) + + def parse_python(self, relative_path: str) -> Optional[ast.Module]: + """Parse a project module (cached). + + A UTF-8 byte order mark is ignored. Returns None when the module is + missing; an existing module that cannot be read or parsed also + returns None and is recorded as unreadable, every time it is asked + for, so each check that needed it learns about it. + """ + if relative_path in self._ast_cache: + tree = self._ast_cache[relative_path] + if tree is None and relative_path in self.unreadable: + self.record_unreadable(relative_path, self.unreadable[relative_path]) + return tree + read = self.read_text(relative_path) + tree = None + if read is not None: + try: + tree = ast.parse(strip_bom(read[0]), filename=relative_path) + except SyntaxError as e: + where = f" (line {e.lineno})" if e.lineno else "" + self.record_unreadable( + relative_path, f"cannot be parsed: {e.msg}{where}" + ) + except ValueError as e: # NUL bytes + self.record_unreadable(relative_path, f"cannot be parsed: {e}") + self._ast_cache[relative_path] = tree + return tree + + def iter_python_trees( + self, include_tests: bool = False + ) -> Iterator[Tuple[str, ast.Module]]: + """``(relative path, module AST)`` for every parseable project module. + + Modules that cannot be parsed are recorded as unreadable. + """ + for relative in self.python_files(include_tests=include_tests): + tree = self.parse_python(relative) + if tree is not None: + yield relative, tree + + # ------------------------------------------------------------------ + # pyproject.toml and metadata + # ------------------------------------------------------------------ + + def pyproject(self) -> Tuple[Optional[str], Optional[Dict[str, Any]]]: + """``(text, parsed)`` of ``pyproject.toml``. + + ``text`` is None when the file is missing or unreadable; ``parsed`` + is None when it is missing or not valid TOML (recorded as + unreadable). A UTF-8 byte order mark is ignored. + """ + if self._pyproject is None: + read = self.read_text("pyproject.toml") + if read is None: + self._pyproject = (None, None) + else: + try: + self._pyproject = (read[0], tomllib.loads(strip_bom(read[0]))) + except tomllib.TOMLDecodeError as e: + self._pyproject = (read[0], None) + self.record_unreadable("pyproject.toml", f"not valid TOML ({e})") + elif self._pyproject[1] is None and "pyproject.toml" in self.unreadable: + self.record_unreadable("pyproject.toml", self.unreadable["pyproject.toml"]) + return self._pyproject + + @property + def template(self) -> Optional[str]: + value = self.metadata.get("template") + return value if isinstance(value, str) and value else None + + @property + def app_module(self) -> Optional[str]: + value = self.metadata.get("app_module") + return value if isinstance(value, str) and value.strip() else None + + @property + def app_module_is_valid(self) -> bool: + """Whether the recorded ``app_module`` is a dotted ``module[:attr]``.""" + return self.app_module is not None and valid_app_module(self.app_module) + + def app_module_candidates(self) -> List[str]: + """Files the recorded ``app_module`` may live in (module or package). + + Empty when no app module is recorded, or when the recorded value is + not a dotted module name or would point outside the project. + """ + if not self.app_module or not valid_app_module(self.app_module): + return [] + module = self.app_module.split(":", 1)[0].strip() + base = module.replace(".", "/") + return [ + candidate + for candidate in (f"{base}.py", f"{base}/__init__.py") + if self.contains(candidate) + ] + + def app_module_file(self) -> Optional[str]: + """Project-relative path of the recorded app module, if it exists.""" + for candidate in self.app_module_candidates(): + if self.is_file(candidate): + return candidate + return None + + # ------------------------------------------------------------------ + # git + # ------------------------------------------------------------------ + + def _run_git( + self, *args: str, stdin: Optional[bytes] = None + ) -> "subprocess.CompletedProcess[bytes]": + """Run a hardened, read-only git command in the project directory. + + Output is bytes; callers decode it (paths arrive NUL-separated). + """ + git = shutil.which("git") + if git is None: + raise GitUnavailable("git is not installed") + try: + return subprocess.run( + git_command(git, *args), + cwd=self.root, + input=stdin if stdin is not None else b"", + capture_output=True, + env=git_environment(), + timeout=60, + check=False, + ) + except (OSError, subprocess.SubprocessError) as e: + raise GitUnavailable(f"git could not be run: {e}") from e + + @staticmethod + def _decode(data: Any) -> str: + if isinstance(data, bytes): + return data.decode("utf-8", errors="replace") + return str(data or "") + + def _git_error( + self, command: str, result: "subprocess.CompletedProcess[bytes]" + ) -> GitUnavailable: + return GitUnavailable( + f"git {command} failed: " + + (self._decode(result.stderr).strip() or "unknown error") + ) + + def git_root(self) -> str: + """Top level of the git work tree holding the project. + + :raises GitUnavailable: when git is missing or the project is not + inside a work tree + """ + if not self._git_checked: + result = self._run_git("rev-parse", "--show-toplevel") + self._git_checked = True + output = self._decode(result.stdout).strip() + if result.returncode == 0 and output: + self._git_root = output + if self._git_root is None: + raise GitUnavailable("the project is not inside a git repository") + return self._git_root + + def git_tracked(self, *pathspecs: str) -> List[str]: + """Project-relative paths in the git index matching ``pathspecs``. + + Pathspecs are relative to the project directory. Paths are read + NUL-separated, so unusual file names survive intact. + + :raises GitUnavailable: when git cannot answer + """ + self.git_root() + result = self._run_git("ls-files", "-z", "--", *pathspecs) + if result.returncode != 0: + raise self._git_error("ls-files", result) + return sorted(item for item in self._decode(result.stdout).split("\0") if item) + + def git_ignored(self, paths: Sequence[str]) -> Set[str]: + """Which project-relative ``paths`` the repository's ignore rules match. + + Every ``.gitignore`` from the work tree root down counts (a monorepo's + root rules included), plus ``.git/info/exclude`` and + ``core.excludesFile``. Whether a file is tracked does not matter. + + :raises GitUnavailable: when git cannot answer + """ + self.git_root() + if not paths: + return set() + data = b"".join(path.encode("utf-8") + b"\0" for path in paths) + result = self._run_git( + "check-ignore", "-z", "--stdin", "--no-index", stdin=data + ) + if result.returncode not in (0, 1): + raise self._git_error("check-ignore", result) + return {item for item in self._decode(result.stdout).split("\0") if item} + + def git_attributes( + self, paths: Sequence[str], *attributes: str + ) -> Dict[str, Dict[str, str]]: + """``{path: {attribute: value}}`` from the repository's attributes. + + Values are git's: ``set``, ``unset``, ``unspecified`` or the value + (``lf``). Every ``.gitattributes`` from the work tree root down + counts. + + :raises GitUnavailable: when git cannot answer + """ + self.git_root() + found: Dict[str, Dict[str, str]] = {path: {} for path in paths} + if not paths or not attributes: + return found + data = b"".join(path.encode("utf-8") + b"\0" for path in paths) + result = self._run_git("check-attr", "-z", "--stdin", *attributes, stdin=data) + if result.returncode != 0: + raise self._git_error("check-attr", result) + fields = self._decode(result.stdout).split("\0") + for index in range(0, len(fields) - 2, 3): + path, attribute, value = fields[index : index + 3] + found.setdefault(path, {})[attribute] = value + return found + + +__all__ = [ + "DoctorError", + "EXCLUDED_DIRS", + "GIT_HARDENING_OPTIONS", + "GitUnavailable", + "ProjectContext", + "git_command", + "git_environment", + "is_test_path", + "is_within", + "strip_bom", + "valid_app_module", +] diff --git a/src/fastapi_fastkit/backend/doctor/envfile.py b/src/fastapi_fastkit/backend/doctor/envfile.py new file mode 100644 index 0000000..2ed613f --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/envfile.py @@ -0,0 +1,279 @@ +# -------------------------------------------------------------------------- +# Minimal ``.env`` reader for ``fastkit doctor``. +# +# Enough of the dotenv format to find variable names and compare values +# (``KEY=value``, ``export KEY=value``, single and double quotes with +# backslash-escaped quote characters, values spanning several lines, +# inline comments, commented-out assignments), and to write a +# ``.env.example`` that never carries a real value. +# +# ``build_env_example`` fails closed: it drops every comment of the source +# file, keeps a value only for an allow-listed variable whose value matches +# a strict "obviously a setting" shape, and blanks everything else. Values +# are only compared, never returned for display. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import re +from dataclasses import dataclass +from typing import List, Optional, Tuple + +from .known import NON_SECRET_ENV_NAMES + +_ASSIGNMENT = re.compile( + r"^(?P[ \t]*(?:#[ \t]*)?)(?Pexport[ \t]+)?" + r"(?P[A-Za-z_][A-Za-z0-9_.]*)[ \t]*=(?P.*)$" +) + +#: A run of characters long and mixed enough to be a generated secret. +_SECRET_TOKEN = re.compile(r"[A-Za-z0-9_\-+/=.~]{20,}") + +#: Longest value ``.env.example`` may keep. +MAX_KEPT_VALUE_LENGTH = 200 + +#: Characters a kept value may contain at all (no ``@``, quotes, ``#``, +#: ``$``, ``\``, ``%``, ``!``, ...). +_SAFE_VALUE_CHARS = re.compile(r"^[A-Za-z0-9_.,:/*\[\]\" -]*$") + +#: The shapes one comma- or space-separated part of a kept value may have. +_SAFE_PARTS = ( + re.compile(r"^[A-Za-z0-9_.*-]+$"), # word, number, host name, level + re.compile(r"^[A-Za-z0-9.-]+:[0-9]{1,5}$"), # host:port + re.compile(r"^/[A-Za-z0-9._~/-]*$"), # path such as /api/v1 + # URL without user info: scheme://host[:port][/path] + re.compile( + r"^[A-Za-z][A-Za-z0-9+.-]*://[A-Za-z0-9.-]+(?::[0-9]{1,5})?" + r"(?:/[A-Za-z0-9._~/-]*)?$" + ), +) + +#: Segment separators used when looking for credential-like pieces. +_SEGMENT_SPLIT = re.compile(r"[/.:,\s\[\]\"]+") + +_HEADER = ( + "# Written by `fastkit doctor --fix` from .env. Comments and values were\n" + "# removed, except for settings that are never secret; fill in your own.\n" +) + + +@dataclass(frozen=True) +class EnvEntry: + """One ``KEY=value`` assignment of a dotenv file. + + ``closed`` is False for a quoted value whose closing quote never came + (the rest of the file was swallowed); ``multiline`` is True when the + value spans more than one line. + """ + + line: int + key: str + value: str + commented: bool + export: bool = False + multiline: bool = False + closed: bool = True + + +def _scan_quoted(text: str, start: int, quote: str) -> Tuple[str, Optional[int]]: + """Read a quoted value from ``text[start:]`` up to the closing ``quote``. + + A backslash escapes the next character (so ``\\"`` inside double quotes + and ``\\'`` inside single quotes do not close the value). + + :return: ``(value, index just past the closing quote)``; the index is + None when the text ends before the quote is closed + """ + out: List[str] = [] + index = start + while index < len(text): + char = text[index] + if char == "\\" and index + 1 < len(text): + following = text[index + 1] + out.append(following if following in (quote, "\\") else char + following) + index += 2 + continue + if char == quote: + return "".join(out), index + 1 + out.append(char) + index += 1 + return "".join(out), None + + +def _unquoted(raw: str) -> str: + """Value of an unquoted assignment: up to an inline `` #`` comment.""" + text = raw.strip() + match = re.search(r"[ \t]#", text) + if match: + text = text[: match.start()] + return text.strip() + + +def parse_env(text: str) -> List[EnvEntry]: + """Every assignment in a dotenv file, commented-out ones included. + + A small state machine: a quoted value continues until the same quote + character closes it (backslash escapes honoured), so lines inside a + multi-line value are never mistaken for assignments or comments. A + commented-out assignment never opens a multi-line value. A UTF-8 byte + order mark before the first line is ignored. + """ + if text.startswith(""): + text = text[1:] + lines = text.split("\n") + entries: List[EnvEntry] = [] + index = 0 + while index < len(lines): + number = index + 1 + line = lines[index].rstrip("\r") + index += 1 + match = _ASSIGNMENT.match(line) + if not match: + continue + commented = "#" in match.group("lead") + raw = match.group("value").lstrip(" \t") + value: str + multiline = False + closed = True + if raw[:1] in ("'", '"') and not commented: + quote = raw[0] + buffer = raw + value, end = _scan_quoted(buffer, 1, quote) + while end is None and index < len(lines): + multiline = True + buffer += "\n" + lines[index].rstrip("\r") + index += 1 + value, end = _scan_quoted(buffer, 1, quote) + closed = end is not None + elif raw[:1] in ("'", '"'): + value, end = _scan_quoted(raw, 1, raw[0]) + closed = end is not None + else: + value = _unquoted(raw) + entries.append( + EnvEntry( + line=number, + key=match.group("key"), + value=value, + commented=commented, + export=bool(match.group("export")), + multiline=multiline, + closed=closed, + ) + ) + return entries + + +def _char_classes(token: str) -> int: + return sum( + ( + any(c.islower() for c in token), + any(c.isupper() for c in token), + any(c.isdigit() for c in token), + ) + ) + + +def looks_like_secret(value: str) -> bool: + """Heuristic: does a value look like a credential rather than a setting?""" + if "@" in value: + return True # user info (``user:pass@host``), with or without scheme + for token in _SECRET_TOKEN.findall(value): + if _char_classes(token) >= 2: + return True + for segment in _SEGMENT_SPLIT.split(value): + if len(segment) >= 32 or (len(segment) >= 16 and _char_classes(segment) >= 2): + return True + return False + + +def is_safe_value(value: str) -> bool: + """Whether a value has the strict shape of a non-secret setting. + + Short, no ``@`` or other credential punctuation, every comma- or + space-separated part a plain word, ``host:port``, a path or a URL + without user info, and nothing that looks like a generated token. + """ + if len(value) > MAX_KEPT_VALUE_LENGTH or not _SAFE_VALUE_CHARS.match(value): + return False + if looks_like_secret(value): + return False + parts = [part for part in re.split(r"[,\s]+", value.strip("[]")) if part] + for part in parts: + part = part.strip('"') + if not part: + continue + if not any(shape.match(part) for shape in _SAFE_PARTS): + return False + return True + + +def keeps_value(key: str, value: str) -> bool: + """Whether ``.env.example`` may keep this variable's value.""" + return key in NON_SECRET_ENV_NAMES and is_safe_value(value) + + +def build_env_example(text: str) -> Tuple[str, List[str], List[str]]: + """ + Turn the text of ``.env`` into a ``.env.example``. + + The result is a neutral header followed by one ``KEY=`` line per active + variable, in the order of the source (blank lines between groups are + kept). Comments and commented-out assignments are dropped. A value is + kept only for a variable in + :data:`~fastapi_fastkit.backend.doctor.known.NON_SECRET_ENV_NAMES` + whose value is on one line and passes :func:`is_safe_value`. + + :param text: ``.env`` text with ``\\n`` line endings + :return: ``(example text, kept keys, blanked keys)`` + """ + out: List[str] = [] + kept: List[str] = [] + blanked: List[str] = [] + seen = set() + entries = [entry for entry in parse_env(text) if not entry.commented] + source = text[1:] if text.startswith("") else text + lines = source.split("\n") + previous_end = 0 + for entry in entries: + gap = lines[previous_end : entry.line - 1] + if out and any(not line.strip() for line in gap): + out.append("") + previous_end = entry.line + (entry.value.count("\n") if entry.multiline else 0) + if entry.key in seen: + continue + seen.add(entry.key) + prefix = f"{'export ' if entry.export else ''}{entry.key}=" + if entry.closed and not entry.multiline and keeps_value(entry.key, entry.value): + out.append(f"{prefix}{entry.value}") + kept.append(entry.key) + else: + out.append(prefix) + blanked.append(entry.key) + + while out and out[-1] == "": + out.pop() + body = "\n".join(out) + return _HEADER + (body + "\n" if body else ""), kept, blanked + + +def find_env_value_keys(text: str, values: "frozenset[str]") -> List[str]: + """Names of active (not commented) variables whose value is in ``values``.""" + seen: List[str] = [] + for entry in parse_env(text): + if entry.commented or entry.value.strip() not in values: + continue + if entry.key not in seen: + seen.append(entry.key) + return seen + + +__all__ = [ + "EnvEntry", + "MAX_KEPT_VALUE_LENGTH", + "build_env_example", + "find_env_value_keys", + "is_safe_value", + "keeps_value", + "looks_like_secret", + "parse_env", +] diff --git a/src/fastapi_fastkit/backend/doctor/known.py b/src/fastapi_fastkit/backend/doctor/known.py new file mode 100644 index 0000000..fff6406 --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/known.py @@ -0,0 +1,88 @@ +# -------------------------------------------------------------------------- +# Values fastkit itself has shipped as examples, in any version. +# +# A project that still uses one of these runs with a secret everybody can +# read in fastkit's public repository. The set is collected from the +# templates' ``KNOWN_EXAMPLE_SECRET_KEYS``, the ``.env`` / ``.env.example`` +# templates and the ``fastkit init`` fragments, including the values of +# releases before v1.5.2 (``git log -p`` on the templates and fragments). +# ``tests/test_backends/test_doctor_checks.py`` fails when a template adds a +# new example key that is missing here. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- + +#: Example secrets (SECRET_KEY, session keys, MCP API key placeholders). +KNOWN_EXAMPLE_SECRETS = frozenset( + { + # .env templates and KNOWN_EXAMPLE_SECRET_KEYS (every version) + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + # fastapi-mcp settings default and the ``fastkit init`` JWT module + # before v1.5.2 + "your-secret-key-here-change-in-production", + "your-secret-key-here", + # ``fastkit init`` Session / OAuth2 modules before v1.5.2 + # (SESSION_SECRET_KEY default) + "change-me-in-production", + # fastapi-mcp .env template (commented example of MCP_API_KEY) + "your-mcp-api-key-here", + } +) + +#: Passwords of the hard-coded demo accounts fastapi-mcp shipped before +#: v1.5.2 (``user1`` / ``user2`` / ``admin``). +MCP_DEMO_PASSWORDS = frozenset({"password123", "password456", "admin123"}) + +#: ``.env`` variants meant to be committed (no real values). +ENV_EXAMPLE_NAMES = frozenset( + {".env.example", ".env.sample", ".env.template", ".env.dist", ".env.defaults"} +) + +#: Variables whose value is never a secret in a fastkit project. Only these +#: keep their value when ``.env.example`` is written from ``.env``, and +#: only when the value itself does not look like a secret. +NON_SECRET_ENV_NAMES = frozenset( + { + "ACCESS_TOKEN_EXPIRE_MINUTES", + "ALGORITHM", + "API_V1_PREFIX", + "API_V1_STR", + "BACKEND_CORS_ORIGINS", + "DEBUG", + "ENABLE_DEMO_USERS", + "ENV", + "ENVIRONMENT", + "FRONTEND_HOST", + "HOST", + "JWT_ALGORITHM", + "LLM_MAX_TOKENS", + "LLM_MODEL", + "LLM_PROVIDER", + "LLM_TEMPERATURE", + "LOG_FORMAT", + "LOG_LEVEL", + "MCP_DESCRIPTION", + "MCP_ENABLED", + "MCP_MOUNT_PATH", + "MCP_TITLE", + "PORT", + "POSTGRES_DB", + "POSTGRES_PORT", + "POSTGRES_SERVER", + "PROJECT_NAME", + "REFRESH_TOKEN_EXPIRE_DAYS", + "SESSION_MAX_AGE", + "TZ", + "VERSION", + "WORKERS", + } +) + +__all__ = [ + "ENV_EXAMPLE_NAMES", + "KNOWN_EXAMPLE_SECRETS", + "MCP_DEMO_PASSWORDS", + "NON_SECRET_ENV_NAMES", +] diff --git a/src/fastapi_fastkit/backend/doctor/model.py b/src/fastapi_fastkit/backend/doctor/model.py new file mode 100644 index 0000000..a722d53 --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/model.py @@ -0,0 +1,162 @@ +# -------------------------------------------------------------------------- +# Data model of ``fastkit doctor``. +# +# A check is a small object with a stable id, a title, a severity, a +# ``detect`` method that returns findings and, for the safe cases, a +# ``plan_fix`` method that returns the edits it would make. Checks never +# write anything themselves: the runner plans every edit first, shows it, +# and only then applies it, so a check can be unit-tested by calling +# ``detect`` / ``plan_fix`` on a project directory. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from dataclasses import dataclass, field +from enum import Enum +from typing import List, Optional, Tuple + +from .context import ProjectContext + + +class Severity(str, Enum): + """How urgent a finding is. Ordered from most to least urgent.""" + + HIGH = "high" + MEDIUM = "medium" + LOW = "low" + + +class CheckStatus(str, Enum): + """Outcome of running one check.""" + + OK = "ok" + PROBLEM = "problem" + SKIPPED = "skipped" + ERROR = "error" + + +class CheckSkipped(Exception): + """Raised by ``detect`` when the check does not apply or cannot look. + + The message is shown to the user as the reason (a missing ``git``, a + project without the file the check reads, ...). A skipped check is not + a problem. + """ + + +class FixRefused(Exception): + """Raised by ``plan_fix`` when the safe edit cannot be made. + + The finding is then reported as advisory, with the message appended to + its remediation text. + """ + + +@dataclass(frozen=True) +class Finding: + """One problem found by a check. + + ``message`` and ``files`` must never contain a secret value: report + file and variable names only. + """ + + check_id: str + message: str + files: Tuple[str, ...] = () + + +@dataclass +class PlannedEdit: + """A whole-file edit a fixer wants to make. + + :param path: Path relative to the project root, ``/``-separated + :param content: Full new text of the file, as handed to + :func:`fastapi_fastkit.utils.textio.write_text_preserving_newlines` + :param newline: The ``newline`` mode that write uses (``"\\r\\n"`` to + restore CRLF, ``""`` to write ``content`` untranslated) + :param original: The file's text as read before planning, in the same + form as ``content`` (``None`` for a new file). Used for the diff and + to refuse the write when the file changed in the meantime. + :param summary: One line describing the edit + :param check_id: The check that planned it + :param original_newline: The ``newline`` mode the read reported for + ``original``; together they identify the file's exact bytes + :param show_diff: False for edits whose diff would be noise (a line + ending conversion touches every line); ``summary`` is shown instead + """ + + path: str + content: str + newline: str + original: Optional[str] + summary: str + check_id: str + original_newline: str = "" + show_diff: bool = True + + @property + def is_new_file(self) -> bool: + return self.original is None + + +@dataclass +class CheckResult: + """What one check reported for a project.""" + + check: "Check" + status: CheckStatus + findings: List[Finding] = field(default_factory=list) + edits: List[PlannedEdit] = field(default_factory=list) + note: Optional[str] = None + + @property + def fixable(self) -> bool: + return bool(self.edits) + + +class Check: + """Base class of a doctor check. + + Subclasses set the class attributes and implement :meth:`detect`; + fixable checks also implement :meth:`plan_fix`. + """ + + #: Stable identifier used in the output and in ``--format json``. + id: str = "" + #: Short human title. + title: str = "" + severity: Severity = Severity.MEDIUM + #: What the user should do, shown with every finding of the check. + remediation: str = "" + #: Whether :meth:`plan_fix` exists for this check. + fixable: bool = False + + def detect(self, ctx: ProjectContext) -> List[Finding]: + """Return the problems this check finds (empty when there are none). + + :raises CheckSkipped: when the check does not apply to the project + """ + raise NotImplementedError + + def plan_fix( + self, ctx: ProjectContext, findings: List[Finding] + ) -> List[PlannedEdit]: + """Return the edits that would fix ``findings`` without writing them. + + :raises FixRefused: when the edit cannot be made safely + """ + raise FixRefused("this check has no automatic fix") + + def finding(self, message: str, *files: str) -> Finding: + return Finding(check_id=self.id, message=message, files=tuple(files)) + + +__all__ = [ + "Check", + "CheckResult", + "CheckSkipped", + "CheckStatus", + "Finding", + "FixRefused", + "PlannedEdit", + "Severity", +] diff --git a/src/fastapi_fastkit/backend/doctor/pyast.py b/src/fastapi_fastkit/backend/doctor/pyast.py new file mode 100644 index 0000000..e1442d5 --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/pyast.py @@ -0,0 +1,68 @@ +# -------------------------------------------------------------------------- +# Small AST helpers shared by the doctor checks. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +from typing import Optional + + +def call_name(call: ast.Call) -> str: + """The called name: ``f`` for ``f()``, ``attr`` for ``obj.attr()``.""" + func = call.func + if isinstance(func, ast.Name): + return func.id + if isinstance(func, ast.Attribute): + return func.attr + return "" + + +def dotted_name(node: ast.AST) -> str: + """``a.b.c`` for a Name / Attribute chain, else an empty string.""" + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + base = dotted_name(node.value) + return f"{base}.{node.attr}" if base else node.attr + return "" + + +def keyword(call: ast.Call, name: str) -> Optional[ast.keyword]: + return next((kw for kw in call.keywords if kw.arg == name), None) + + +def has_kwargs_unpack(call: ast.Call) -> bool: + return any(kw.arg is None for kw in call.keywords) + + +def str_constant(node: Optional[ast.AST]) -> Optional[str]: + """The value of a string literal node, else None.""" + if isinstance(node, ast.Constant) and isinstance(node.value, str): + return node.value + return None + + +def is_env_read(call: ast.Call) -> bool: + """``os.getenv(...)``, ``getenv(...)`` or ``os.environ.get(...)``.""" + name = dotted_name(call.func) + return name in ("os.getenv", "getenv") or name.endswith("environ.get") + + +def target_name(node: ast.AST) -> str: + """Name assigned to by an assignment target (``x``, ``obj.x``).""" + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + return node.attr + return "" + + +__all__ = [ + "call_name", + "dotted_name", + "has_kwargs_unpack", + "is_env_read", + "keyword", + "str_constant", + "target_name", +] diff --git a/src/fastapi_fastkit/backend/doctor/render.py b/src/fastapi_fastkit/backend/doctor/render.py new file mode 100644 index 0000000..477713b --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/render.py @@ -0,0 +1,348 @@ +# -------------------------------------------------------------------------- +# Output of ``fastkit doctor``: Rich text for people, JSON for CI. +# +# Every user-controlled string is printed as a ``Text`` object, never as +# Rich markup, so paths and snippets such as ``[tool.fastapi-fastkit]`` or +# ``allow_origins=["*"]`` print verbatim. Check ids never wrap: on a narrow +# console the description columns wrap instead. +# +# JSON document (``schema_version`` 1):: +# +# { +# "schema_version": 1, +# "fastkit_version": "2.0.0", +# "project": {"path", "template", "preset", "generated_with", +# "app_module", "has_metadata"}, +# "summary": {"problems", "fixable", "by_severity": {"high", "medium", +# "low"}, "checks": {"ok", "problem", "skipped", "error"}}, +# "checks": [{"id", "title", "severity", "status", "fixable", "note"}], +# "findings": [{"check", "severity", "title", "message", "files", +# "fixable", "remediation"}], +# "fix": null | {"dry_run", "planned": [{"path", "check", "summary", +# "new_file", "diff"}], "applied": [path], +# "failed": [{"path", "reason"}]}, +# "unreadable": [{"path", "reason"}], +# "exit_code": 0 | 1 | 2 +# } +# +# ``unreadable`` lists project files that exist but could not be read or +# parsed; the checks that needed them have status ``error``. +# +# When doctor cannot run, the document is +# ``{"schema_version": 1, "fastkit_version": ..., "error": "...", +# "exit_code": 2}``. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from typing import Any, Dict, List, Optional, Sequence + +from rich.console import Console +from rich.padding import Padding +from rich.table import Table +from rich.text import Text + +from fastapi_fastkit import __version__ + +from .model import CheckStatus, PlannedEdit, Severity +from .runner import ApplyResult, DoctorReport, edit_diff + +JSON_SCHEMA_VERSION = 1 + +_SEVERITY_STYLE = { + Severity.HIGH: "bold red", + Severity.MEDIUM: "bold yellow", + Severity.LOW: "bold cyan", +} + +_STATUS_STYLE = { + CheckStatus.OK: "green", + CheckStatus.PROBLEM: "bold red", + CheckStatus.SKIPPED: "dim", + CheckStatus.ERROR: "bold magenta", +} + + +# ---------------------------------------------------------------------- +# Text +# ---------------------------------------------------------------------- + + +def render_header(report: DoctorReport, console: Console) -> None: + """Title, project path and what generated the project. + + The absolute path gets a line of its own and folds at the console edge + instead of being truncated or pushing the title around, so a long path + on a narrow console stays readable and complete. + """ + ctx = report.ctx + console.print(Text("fastkit doctor", style="bold")) + console.print( + Padding( + Text(ctx.root, overflow="fold", no_wrap=False), (0, 0, 0, 2), expand=False + ), + soft_wrap=False, + ) + details = [] + if ctx.template: + details.append(f"template {ctx.template}") + preset = ctx.metadata.get("preset") + if isinstance(preset, str) and preset: + details.append(f"preset {preset}") + version = ctx.metadata.get("version") + if isinstance(version, str) and version: + details.append(f"generated with fastkit {version}") + if not ctx.has_metadata: + details.append("no [tool.fastapi-fastkit] metadata (--force)") + if details: + console.print( + Padding( + Text(", ".join(details), style="dim", overflow="fold"), + (0, 0, 0, 2), + expand=False, + ) + ) + + +def render_findings(report: DoctorReport, console: Console) -> None: + """Findings grouped by severity, each with its remediation.""" + for severity in Severity: + results = [ + r for r in report.results if r.findings and r.check.severity is severity + ] + if not results: + continue + count = sum(len(r.findings) for r in results) + console.print() + console.rule( + Text( + f"{severity.value.upper()} ({count})", style=_SEVERITY_STYLE[severity] + ), + align="left", + ) + for result in results: + heading = Text() + heading.append(f"[{result.check.id}] ", style=_SEVERITY_STYLE[severity]) + heading.append(result.check.title, style="bold") + console.print() + console.print(heading) + for finding in result.findings: + console.print(Padding(Text(f"- {finding.message}"), (0, 0, 0, 2))) + console.print(Padding(Text("How to fix:", style="bold"), (0, 0, 0, 2))) + console.print(Padding(Text(result.check.remediation), (0, 0, 0, 4))) + if result.fixable: + console.print( + Padding( + Text("Fixable with `fastkit doctor --fix`.", style="green"), + (0, 0, 0, 2), + ) + ) + elif result.note: + console.print(Padding(Text(result.note, style="dim"), (0, 0, 0, 2))) + + +def build_summary_table(report: DoctorReport) -> Table: + """One row per check: status, severity, id and title / note.""" + id_width = max(len(r.check.id) for r in report.results) if report.results else 8 + table = Table( + title="Checks", title_style="bold magenta", expand=False, pad_edge=False + ) + table.add_column("Check", no_wrap=True, min_width=id_width, style="cyan") + table.add_column("Status", no_wrap=True) + table.add_column("Severity", no_wrap=True) + table.add_column("Details", overflow="fold") + for result in report.results: + if result.status is CheckStatus.OK: + details = Text(result.check.title, style="dim") + elif result.status is CheckStatus.PROBLEM: + details = Text(result.check.title) + if result.note: + details.append(f"\n{result.note}", style="dim") + else: + details = Text(result.note or "", style="dim") + table.add_row( + Text(result.check.id), + Text(result.status.value, style=_STATUS_STYLE[result.status]), + Text(result.check.severity.value), + details, + ) + return table + + +def render_unreadable(report: DoctorReport, console: Console) -> None: + """Files that exist but could not be read or parsed.""" + unreadable = report.unreadable + if not unreadable: + return + console.print() + console.rule( + Text(f"UNREADABLE FILES ({len(unreadable)})", style="bold magenta"), + align="left", + ) + console.print( + Padding( + Text( + "These files exist but could not be read or parsed, so the " + "checks that need them could not run (status error):" + ), + (0, 0, 0, 2), + ) + ) + for path, reason in unreadable.items(): + console.print(Padding(Text(f"- {path}: {reason}"), (0, 0, 0, 2))) + + +def render_report(report: DoctorReport, console: Console) -> None: + render_header(report, console) + render_findings(report, console) + render_unreadable(report, console) + console.print() + console.print(build_summary_table(report)) + + +def render_edits(edits: Sequence[PlannedEdit], console: Console) -> None: + """Planned edits as unified diffs (new files as full additions).""" + for edit in edits: + console.print() + title = Text( + f"{'create' if edit.is_new_file else 'modify'} {edit.path}", style="bold" + ) + title.append(f" ({edit.summary})", style="dim") + console.print(title) + if not edit.show_diff: + continue + for line in edit_diff(edit).splitlines(): + style = "" + if line.startswith(("+++", "---")): + style = "bold" + elif line.startswith("+"): + style = "green" + elif line.startswith("-"): + style = "red" + elif line.startswith("@@"): + style = "cyan" + console.print(Text(line, style=style), soft_wrap=True) + + +# ---------------------------------------------------------------------- +# JSON +# ---------------------------------------------------------------------- + + +def report_to_json( + report: DoctorReport, + planned: Optional[Sequence[PlannedEdit]] = None, + applied: Optional[ApplyResult] = None, + dry_run: bool = False, + exit_code: Optional[int] = None, +) -> Dict[str, Any]: + """The machine-readable document (see the module header for the schema). + + :param report: The report whose findings are listed (after fixes, when + fixes were applied) + :param planned: Edits planned by ``--fix`` (None without ``--fix``) + :param applied: Outcome of applying them (None when nothing was written) + :param dry_run: Whether the edits were only shown + :param exit_code: Exit status of the command (defaults to the report's) + """ + ctx = report.ctx + + def text_or_none(value: Any) -> Optional[str]: + return value if isinstance(value, str) and value else None + + status_counts = {status.value: 0 for status in CheckStatus} + for result in report.results: + status_counts[result.status.value] += 1 + + findings: List[Dict[str, Any]] = [] + for result, finding in report.findings: + findings.append( + { + "check": result.check.id, + "severity": result.check.severity.value, + "title": result.check.title, + "message": finding.message, + "files": list(finding.files), + "fixable": result.fixable, + "remediation": result.check.remediation, + } + ) + + fix: Optional[Dict[str, Any]] = None + if planned is not None: + fix = { + "dry_run": dry_run, + "planned": [ + { + "path": edit.path, + "check": edit.check_id, + "summary": edit.summary, + "new_file": edit.is_new_file, + "diff": edit_diff(edit) if edit.show_diff else None, + } + for edit in planned + ], + "applied": list(applied.applied) if applied else [], + "failed": [ + {"path": path, "reason": reason} + for path, reason in (applied.failed if applied else []) + ], + } + + return { + "schema_version": JSON_SCHEMA_VERSION, + "fastkit_version": __version__, + "project": { + "path": ctx.root, + "template": ctx.template, + "preset": text_or_none(ctx.metadata.get("preset")), + "generated_with": text_or_none(ctx.metadata.get("version")), + "app_module": ctx.app_module, + "has_metadata": ctx.has_metadata, + }, + "summary": { + "problems": report.problem_count, + "fixable": sum(len(r.findings) for r in report.results if r.fixable), + "by_severity": report.count_by_severity(), + "checks": status_counts, + }, + "checks": [ + { + "id": result.check.id, + "title": result.check.title, + "severity": result.check.severity.value, + "status": result.status.value, + "fixable": result.fixable, + "note": result.note, + } + for result in report.results + ], + "findings": findings, + "fix": fix, + "unreadable": [ + {"path": path, "reason": reason} + for path, reason in report.unreadable.items() + ], + "exit_code": report.exit_code if exit_code is None else exit_code, + } + + +def error_to_json(message: str) -> Dict[str, Any]: + return { + "schema_version": JSON_SCHEMA_VERSION, + "fastkit_version": __version__, + "error": message, + "exit_code": 2, + } + + +__all__ = [ + "JSON_SCHEMA_VERSION", + "build_summary_table", + "error_to_json", + "render_edits", + "render_findings", + "render_header", + "render_report", + "render_unreadable", + "report_to_json", +] diff --git a/src/fastapi_fastkit/backend/doctor/runner.py b/src/fastapi_fastkit/backend/doctor/runner.py new file mode 100644 index 0000000..cdc2187 --- /dev/null +++ b/src/fastapi_fastkit/backend/doctor/runner.py @@ -0,0 +1,366 @@ +# -------------------------------------------------------------------------- +# Running doctor checks, planning fixes and applying them. +# +# ``run_checks`` runs every check, and for each fixable one with findings +# plans its edits right away (planning is read-only), so the report always +# knows which problems ``--fix`` would resolve. ``apply_edits`` writes the +# planned edits one file at a time: each file is written to a temporary +# sibling and moved into place, and a file that changed since it was read +# is left alone. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import difflib +import os +import re +import stat +import tempfile +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence, Tuple + +from fastapi_fastkit.utils.textio import ( + CRLF, + read_text_preserving_newlines, + write_text_preserving_newlines, +) + +from .checks_api import ( + CommitAfterYieldCheck, + MotorDeprecatedCheck, + PaginationDemoCheck, + SettingsSprawlCheck, + SlowapiMiddlewareCheck, +) +from .checks_code import ( + AppModuleMissingCheck, + CorsCredentialsCheck, + McpAuthCheck, + McpDemoUsersCheck, + PrometheusLifespanCheck, +) +from .checks_files import ( + CrlfScriptsCheck, + GitattributesMissingCheck, + PreCommitPythonCheck, + RequiresPythonCheck, + SqlalchemyAsyncioCheck, +) +from .checks_secrets import ( + EnvExampleMissingCheck, + EnvTrackedCheck, + ExampleSecretCheck, + GitignoreEnvCheck, + SessionSecretCheck, +) +from .context import ProjectContext +from .model import ( + Check, + CheckResult, + CheckSkipped, + CheckStatus, + Finding, + FixRefused, + PlannedEdit, + Severity, +) + + +def default_checks() -> List[Check]: + """Every check, in report order (secrets first).""" + return [ + EnvTrackedCheck(), + GitignoreEnvCheck(), + EnvExampleMissingCheck(), + ExampleSecretCheck(), + SessionSecretCheck(), + McpAuthCheck(), + McpDemoUsersCheck(), + CorsCredentialsCheck(), + AppModuleMissingCheck(), + PrometheusLifespanCheck(), + CommitAfterYieldCheck(), + SlowapiMiddlewareCheck(), + PaginationDemoCheck(), + MotorDeprecatedCheck(), + SettingsSprawlCheck(), + SqlalchemyAsyncioCheck(), + CrlfScriptsCheck(), + GitattributesMissingCheck(), + RequiresPythonCheck(), + PreCommitPythonCheck(), + ] + + +@dataclass +class DoctorReport: + """Results of one doctor run over a project.""" + + ctx: ProjectContext + results: List[CheckResult] + + @property + def findings(self) -> List[Tuple[CheckResult, Finding]]: + return [(result, f) for result in self.results for f in result.findings] + + @property + def problem_count(self) -> int: + return len(self.findings) + + @property + def edits(self) -> List[PlannedEdit]: + return [edit for result in self.results for edit in result.edits] + + @property + def errors(self) -> List[CheckResult]: + return [r for r in self.results if r.status is CheckStatus.ERROR] + + @property + def unreadable(self) -> Dict[str, str]: + """Files that exist but could not be read or parsed, with the reason.""" + return dict(sorted(self.ctx.unreadable.items())) + + def count_by_severity(self) -> Dict[str, int]: + counts = {severity.value: 0 for severity in Severity} + for result, _ in self.findings: + counts[result.check.severity.value] += 1 + return counts + + @property + def exit_code(self) -> int: + """0: no problems; 1: problems remain; 2: a check could not run.""" + if self.problem_count: + return 1 + if self.errors: + return 2 + return 0 + + +def describe_unreadable(files: Dict[str, str]) -> str: + """``could not read a.py (reason); b.toml (reason)``.""" + return "could not read " + "; ".join( + f"{path} ({reason})" for path, reason in sorted(files.items()) + ) + + +def _run_one(check: Check, ctx: ProjectContext) -> CheckResult: + """Run one check. + + A check that touched a file which exists but could not be read or + parsed never passes silently: without findings it is an error naming + the files; with findings it stays a problem and the note names them. + """ + with ctx.tracking_unreadable() as touched: + try: + findings = check.detect(ctx) + except CheckSkipped as e: + if touched: + return CheckResult( + check, CheckStatus.ERROR, note=describe_unreadable(touched) + ) + return CheckResult(check, CheckStatus.SKIPPED, note=str(e)) + except Exception as e: # a broken check must not hide the others + return CheckResult( + check, CheckStatus.ERROR, note=f"check failed: {type(e).__name__}: {e}" + ) + if not findings: + if touched: + return CheckResult( + check, CheckStatus.ERROR, note=describe_unreadable(touched) + ) + return CheckResult(check, CheckStatus.OK) + + result = CheckResult(check, CheckStatus.PROBLEM, findings=list(findings)) + unread_note = describe_unreadable(touched) if touched else None + if check.fixable: + try: + result.edits = check.plan_fix(ctx, result.findings) + except FixRefused as e: + result.note = f"no automatic fix: {e}" + except Exception as e: + result.note = f"no automatic fix: {type(e).__name__}: {e}" + if not result.edits and result.note is None: + result.note = "no automatic fix: nothing to change" + refused = [] + for edit in list(result.edits): + reason = ctx.unsafe_write_reason(edit.path) + if reason is not None: + result.edits.remove(edit) + refused.append(reason) + if refused: + result.note = "not fixable automatically: " + "; ".join(refused) + if unread_note: + result.note = f"{result.note}; {unread_note}" if result.note else unread_note + return result + + +def run_checks( + ctx: ProjectContext, checks: Optional[Sequence[Check]] = None +) -> DoctorReport: + """Run ``checks`` (all by default) against ``ctx`` and plan their fixes. + + When two checks plan an edit of the same file, the later one is + dropped (and reported as fixable on the next run), so the edits of one + run never overwrite each other. + """ + results = [_run_one(check, ctx) for check in (checks or default_checks())] + claimed: Dict[str, str] = {} + for result in results: + kept = [] + for edit in result.edits: + if edit.path in claimed: + continue + claimed[edit.path] = result.check.id + kept.append(edit) + if result.edits and not kept: + result.note = "fixable on the next run (another fix edits the same file)" + result.edits = kept + return DoctorReport(ctx, results) + + +# ---------------------------------------------------------------------- +# Diffs +# ---------------------------------------------------------------------- + +#: A URL scheme followed by the rest of its whitespace-delimited token. +_URL_TOKEN = re.compile(r"(?P[A-Za-z][A-Za-z0-9+.-]*://)(?P\S*)") + + +def _redact_url(match: "re.Match[str]") -> str: + scheme, rest = match.group("scheme"), match.group("rest") + if "@" not in rest: + return match.group(0) + # User info ends at the *last* ``@`` before the host: passwords may + # contain ``@`` and ``/``. Keep the host only when what follows the + # last ``@`` looks like one; otherwise hide the whole value. + at = rest.rfind("@") + host = rest[at + 1 :] + if re.match(r"^[A-Za-z0-9.\-\[\]:]+(?:[/?#][^@]*)?$", host): + return f"{scheme}***@{host}" + return f"{scheme}***" + + +def redact(text: str) -> str: + """Hide credentials embedded in URLs (``https://user:token@host``). + + Everything between ``://`` and the last ``@`` of the URL is replaced, so + a password containing ``@`` or ``/`` is hidden completely; when the + part after the last ``@`` does not look like a host the whole URL after + the scheme is hidden. + """ + return _URL_TOKEN.sub(_redact_url, text) + + +def edit_diff(edit: PlannedEdit) -> str: + """Unified diff of an edit (``/dev/null`` as the old side of new files). + + Line endings are shown as ``\\n``; URL credentials are redacted. + """ + before = (edit.original or "").replace(CRLF, "\n") + after = edit.content.replace(CRLF, "\n") + diff = difflib.unified_diff( + before.splitlines(keepends=True), + after.splitlines(keepends=True), + fromfile="/dev/null" if edit.is_new_file else f"a/{edit.path}", + tofile=f"b/{edit.path}", + ) + lines = [] + for line in diff: + lines.append(line if line.endswith("\n") else line + "\n") + return redact("".join(lines)) + + +# ---------------------------------------------------------------------- +# Applying +# ---------------------------------------------------------------------- + + +@dataclass +class ApplyResult: + applied: List[str] = field(default_factory=list) + failed: List[Tuple[str, str]] = field(default_factory=list) + + +def _current_state(path: str) -> Optional[Tuple[str, str]]: + if not os.path.lexists(path): + return None + return read_text_preserving_newlines(path) + + +def _default_file_mode() -> int: + """Mode a newly created regular file gets under the current umask.""" + mask = os.umask(0o022) + os.umask(mask) + return 0o666 & ~mask + + +def _write_atomically(path: str, content: str, newline: str) -> None: + """Write through a temporary sibling so readers never see half a file. + + The temporary file is created with :func:`tempfile.mkstemp` in the same + directory (an unpredictable name, never an existing file or link). An + existing file keeps its permission bits (shell scripts stay + executable); a new one gets the usual umask-based mode. + """ + directory = os.path.dirname(path) or "." + fd, temp_path = tempfile.mkstemp( + dir=directory, prefix=f".{os.path.basename(path)}.", suffix=".fastkit-tmp" + ) + os.close(fd) + try: + write_text_preserving_newlines(temp_path, content, newline) + if os.path.exists(path): + os.chmod(temp_path, stat.S_IMODE(os.stat(path).st_mode)) + else: + os.chmod(temp_path, _default_file_mode()) + os.replace(temp_path, path) + except BaseException: + if os.path.exists(temp_path): + os.remove(temp_path) + raise + + +def apply_edits(ctx: ProjectContext, edits: Sequence[PlannedEdit]) -> ApplyResult: + """Apply planned edits file by file. + + A file is skipped (and reported in ``failed``) when it is a symbolic + link, sits below one, or resolves outside the project; when it changed + after the edit was planned; or when writing it fails. The other files + are still written. + """ + outcome = ApplyResult() + for edit in edits: + path = ctx.path(edit.path) + unsafe = ctx.unsafe_write_reason(edit.path) + if unsafe is not None: + outcome.failed.append((edit.path, unsafe)) + continue + try: + state = _current_state(path) + expected = ( + None + if edit.original is None + else (edit.original, edit.original_newline) + ) + if state != expected: + outcome.failed.append( + (edit.path, "the file changed after the fix was planned") + ) + continue + _write_atomically(path, edit.content, edit.newline) + except (OSError, UnicodeDecodeError) as e: + outcome.failed.append((edit.path, str(e))) + continue + outcome.applied.append(edit.path) + return outcome + + +__all__ = [ + "ApplyResult", + "DoctorReport", + "apply_edits", + "default_checks", + "describe_unreadable", + "edit_diff", + "redact", + "run_checks", +] diff --git a/src/fastapi_fastkit/backend/interactive/config_builder.py b/src/fastapi_fastkit/backend/interactive/config_builder.py index 686b7d7..d84bab2 100644 --- a/src/fastapi_fastkit/backend/interactive/config_builder.py +++ b/src/fastapi_fastkit/backend/interactive/config_builder.py @@ -8,7 +8,7 @@ # -------------------------------------------------------------------------- from typing import Any, Dict, List -from fastapi_fastkit.utils.main import console, print_warning +from fastapi_fastkit.utils.main import console, print_error, print_warning from ..project_builder.config_schema import normalize_project_config from ..project_builder.dependency_collector import DependencyCollector @@ -70,6 +70,9 @@ def run_interactive_flow(self) -> Dict[str, Any]: # Step 5: Validate compatibility is_valid, warning = validate_feature_compatibility(final_config) + if not is_valid: + print_error(warning or "Incompatible feature selection.") + return {} if warning: print_warning(warning, title="Feature Compatibility") diff --git a/src/fastapi_fastkit/backend/interactive/prompts.py b/src/fastapi_fastkit/backend/interactive/prompts.py index eeaf840..577eea3 100644 --- a/src/fastapi_fastkit/backend/interactive/prompts.py +++ b/src/fastapi_fastkit/backend/interactive/prompts.py @@ -17,6 +17,7 @@ import click from fastapi_fastkit.backend.project_builder.config_generator import SQL_DATABASES +from fastapi_fastkit.backend.project_builder.config_schema import combination_errors from fastapi_fastkit.core.settings import ( NONE_CHOICE, FeatureAxis, @@ -233,11 +234,11 @@ def prompt_authentication_selection(settings: Any) -> str: if name == "None": options[name] = "No authentication" elif name == "JWT": - options[name] = "JSON Web Tokens (recommended for APIs)" + options[name] = "OAuth2 password flow with JWT (recommended for APIs)" elif name == "OAuth2": options[name] = "OAuth2 with authlib" elif name == "FastAPI-Users": - options[name] = "Complete user management system (includes JWT)" + options[name] = "Complete user management (JWT; SQL databases only)" elif name == "Session-based": options[name] = "Traditional session-based authentication" else: @@ -418,9 +419,9 @@ def prompt_utilities_selection(settings: Any) -> List[str]: if name == "CORS": descriptions[name] = "(Built-in, will configure in settings)" elif name == "Rate-Limiting": - descriptions[name] = "API rate limiting with slowapi" + descriptions[name] = "Per-client API rate limits (limits)" elif name == "Pagination": - descriptions[name] = "Response pagination utilities" + descriptions[name] = "(Built-in, list endpoints are always paginated)" elif name == "WebSocket": descriptions[name] = "(Built-in, will configure routes)" else: @@ -690,8 +691,15 @@ def prompt_additional_features(settings: Any) -> Dict[str, Any]: # Database features["database"] = prompt_database_selection(settings) - # Authentication - features["authentication"] = prompt_authentication_selection(settings) + # Authentication — FastAPI-Users is generated on a SQL database only. + database_type = features["database"].get("type", NONE_CHOICE) + while True: + features["authentication"] = prompt_authentication_selection(settings) + errors = combination_errors(features) + if not errors: + break + for error in errors: + print_error(error) # Async tasks features["async_tasks"] = prompt_async_tasks_selection(settings) @@ -709,7 +717,6 @@ def prompt_additional_features(settings: Any) -> Dict[str, Any]: features["testing"] = prompt_testing_selection(settings) # Migrations — the database choice decides the recommended default. - database_type = features["database"].get("type", NONE_CHOICE) features["migrations"] = prompt_migrations_selection(settings, database_type) # Utilities diff --git a/src/fastapi_fastkit/backend/interactive/validators.py b/src/fastapi_fastkit/backend/interactive/validators.py index 015d851..1e73159 100644 --- a/src/fastapi_fastkit/backend/interactive/validators.py +++ b/src/fastapi_fastkit/backend/interactive/validators.py @@ -94,22 +94,25 @@ def validate_feature_compatibility( Check compatibility between selected features. Validates that selected features don't have conflicting requirements. + Selections that cannot be generated together (FastAPI-Users without a + SQL database) make the configuration incompatible; the message says why. Args: config: Project configuration dictionary Returns: - Tuple of (is_compatible, warning_message) + Tuple of (is_compatible, warning_or_error_message) """ - warnings = [] + # Imported lazily: the project builder package imports this module. + from fastapi_fastkit.backend.project_builder.config_schema import ( + combination_errors, + ) + + errors = combination_errors(config) + if errors: + return False, " | ".join(errors) - # Check if FastAPI-Users is selected with database - if config.get("authentication") == "FastAPI-Users": - db_type = config.get("database", {}).get("type", "None") - if db_type == "None": - warnings.append( - "FastAPI-Users requires a database. Consider selecting PostgreSQL or MySQL." - ) + warnings = [] # Check if Celery is selected with Redis if config.get("async_tasks") == "Celery" or config.get("async_tasks") == "Dramatiq": diff --git a/src/fastapi_fastkit/backend/main.py b/src/fastapi_fastkit/backend/main.py index 70b710a..0d9ecae 100644 --- a/src/fastapi_fastkit/backend/main.py +++ b/src/fastapi_fastkit/backend/main.py @@ -24,11 +24,9 @@ from fastapi_fastkit.backend.project_builder.preset_layout import ( app_module_from_main_path, ) -from fastapi_fastkit.backend.route_wiring import register_router, router_alias -from fastapi_fastkit.backend.transducer import ( - copy_and_convert_template, - copy_and_convert_template_file, -) +from fastapi_fastkit.backend.route_plan import RoutePlan +from fastapi_fastkit.backend.route_wiring import router_alias +from fastapi_fastkit.backend.transducer import copy_and_convert_template from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import settings from fastapi_fastkit.utils.config_file import format_toml_value @@ -1180,6 +1178,69 @@ def generate_dependency_file_with_manager( # ------------------------------------------------------------ +#: A dotted module path, optionally with ``:attribute`` (``src.main:app``). +_APP_MODULE_PATTERN = re.compile( + r"[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*(?::[A-Za-z_][A-Za-z0-9_]*)?" +) + + +def valid_app_module(value: str) -> bool: + """Whether ``value`` is ``package.module`` or ``package.module:attr``.""" + return bool(_APP_MODULE_PATTERN.fullmatch(value.strip())) + + +def is_within_directory(path: str, directory: str) -> bool: + """Whether ``path`` resolves (symlinks followed) to a place inside ``directory``.""" + real_path = os.path.realpath(path) + real_dir = os.path.realpath(directory) + try: + return os.path.commonpath([real_path, real_dir]) == real_dir + except ValueError: # different drives on Windows + return False + + +def recorded_app_module_path(project_dir: str, recorded: Any) -> str: + """ + The entry point file a recorded ``app_module`` names, if it is usable. + + The value comes from ``pyproject.toml`` and is therefore untrusted: it + must be a dotted module name (``src.main:app``), and the file it names + must exist and resolve inside ``project_dir``. Anything else (a leading + dot, ``..``, an absolute path, a symlink out of the project) is ignored + with a warning. + + :return: The path, or an empty string + """ + if not isinstance(recorded, str) or not recorded.strip(): + return "" + if not valid_app_module(recorded): + _warn_ignored_app_module( + recorded, "it is not a dotted module path such as 'src.main:app'" + ) + return "" + module = recorded.strip().split(":", 1)[0] + candidate = os.path.join(project_dir, *module.split(".")) + ".py" + if not os.path.isfile(candidate): + return "" + if not is_within_directory(candidate, project_dir): + _warn_ignored_app_module(recorded, "it resolves outside the project directory") + return "" + return candidate + + +_warned_app_modules: set[str] = set() + + +def _warn_ignored_app_module(recorded: str, reason: str) -> None: + """Warn once per value: layout resolution runs several times per command.""" + if recorded in _warned_app_modules: + return + _warned_app_modules.add(recorded) + print_warning( + f"Ignoring app_module = {recorded!r} in [tool.fastapi-fastkit]: {reason}." + ) + + def resolve_project_layout(project_dir: str) -> Dict[str, str]: """ Resolve where a generated project keeps its entrypoint and API router. @@ -1199,16 +1260,12 @@ def resolve_project_layout(project_dir: str) -> Dict[str, str]: """ metadata = read_fastkit_metadata(project_dir) - main_path = "" - recorded_module = metadata.get("app_module") - if isinstance(recorded_module, str) and recorded_module: - module_path = recorded_module.split(":")[0].replace(".", os.sep) - candidate = os.path.join(project_dir, f"{module_path}.py") - if os.path.exists(candidate): - main_path = candidate + main_path = recorded_app_module_path(project_dir, metadata.get("app_module")) if not main_path: main_path = find_template_core_modules(project_dir).get("main", "") + if main_path and not is_within_directory(main_path, project_dir): + main_path = "" if main_path: package_dir = os.path.dirname(main_path) @@ -1544,12 +1601,16 @@ def insert_statement_line( """ Insert a statement at the ``# fastkit:routes`` anchor, else append it. + Whether the statement is already present is decided from the code, not + the text: a commented-out copy (``# api_router.include_router(x)``) or + one inside a string does not count. + :param content: Source of the module being edited :param statement: Statement to add :param anchor: Anchor comment to look for :return: Updated source (unchanged if the statement is already present) """ - if statement in content: + if statement_present(content, statement): return content anchored = _insert_after_anchor(content, anchor, statement) @@ -1561,6 +1622,49 @@ def insert_statement_line( return f"{content}{statement}\n" +def code_without_comments(content: str) -> str: + """``content`` with every comment removed (strings are kept). + + Uses the tokenizer; a source it cannot tokenize falls back to dropping + the lines that are only a comment. + """ + try: + tokens = [ + token + for token in tokenize.generate_tokens(io.StringIO(content).readline) + if token.type != tokenize.COMMENT + ] + return tokenize.untokenize(tokens) + except (tokenize.TokenError, IndentationError, SyntaxError): + return "\n".join( + line for line in content.split("\n") if not line.lstrip().startswith("#") + ) + + +def statement_present(content: str, statement: str) -> bool: + """Whether ``statement`` is real code in ``content`` (not a comment). + + Compared as AST when both parse (formatting differences do not + matter); otherwise as text with the comments removed. + """ + try: + wanted = [ast.dump(node) for node in ast.parse(statement.strip()).body] + tree = ast.parse(content) + except SyntaxError: + return statement.strip() in code_without_comments(content) + if not wanted: + return True + for node in ast.walk(tree): + body = getattr(node, "body", None) + if not isinstance(body, list): + continue + dumped = [ast.dump(child) for child in body if isinstance(child, ast.stmt)] + for start in range(len(dumped) - len(wanted) + 1): + if dumped[start : start + len(wanted)] == wanted: + return True + return False + + def _anchor_line_numbers(content: str, anchor: str) -> List[int]: """Return the 1-based line numbers carrying ``anchor`` as a real comment. @@ -1661,184 +1765,82 @@ def _last_import_line(content: str) -> int: return prelude_line -def _ensure_project_structure(src_dir: str) -> Dict[str, str]: - """ - Ensure the project structure exists for adding a new route. - Creates necessary directories if they don't exist. - - :param src_dir: Source directory of the project - :return: Dictionary with paths to target directories - """ - if not os.path.exists(src_dir): - raise BackendExceptions(f"Source directory not found at {src_dir}") - - # Define target directories - target_dirs = { - "api": os.path.join(src_dir, "api"), - "api_routes": os.path.join(src_dir, "api", "routes"), - "crud": os.path.join(src_dir, "crud"), - "schemas": os.path.join(src_dir, "schemas"), - } - - # Create directories and __init__.py files if needed - for dir_name, dir_path in target_dirs.items(): - if not os.path.exists(dir_path): - os.makedirs(dir_path) - - # Create __init__.py if it doesn't exist - init_file = os.path.join(dir_path, "__init__.py") - if not os.path.exists(init_file): - write_generated_text(init_file, "") - - return target_dirs - - -def _create_route_files( - modules_dir: str, - target_dirs: Dict[str, str], +def _update_api_router( + api_router_file: str, route_name: str, - package_module: str = "src", + package_module: str = "", + plan: Optional[RoutePlan] = None, ) -> None: """ - Create route files from templates. + Register a classic-layout route module in the API router file. - The route template imports its crud/schemas siblings through the - ```` placeholder, so the generated imports follow the - project's real package (``src`` for the classic layout, ``src.app`` for - the domain-starter one) instead of a hardcoded ``src``. - - :param modules_dir: Path to the modules directory - :param target_dirs: Dictionary with paths to target directories - :param route_name: Name of the route to create - :param package_module: Dotted package holding ``api``/``crud``/``schemas`` - """ - replacements = { - "": route_name, - "": package_module or "src", - } - module_types = ["api/routes", "crud", "schemas"] - - for module_type in module_types: - # Source template - source = os.path.join(modules_dir, module_type, "new_route.py-tpl") - - # Target directory - if module_type == "api/routes": - target_dir = target_dirs["api_routes"] - else: - target_dir = target_dirs[module_type.split("/")[-1]] - - # Target file - target = os.path.join(target_dir, f"{route_name}.py") - - if os.path.exists(target): - print_warning(f"File {target} already exists, skipping...") - continue - - if not copy_and_convert_template_file(source, target, replacements): - print_warning(f"Failed to copy template file {source} to {target}") - - -def _handle_api_router_file( - target_dirs: Dict[str, str], - modules_dir: str, - route_name: str, - api_router_file: str = "", -) -> None: - """ - Handle API router file creation or update. - - :param target_dirs: Dictionary with paths to target directories - :param modules_dir: Path to the modules directory - :param route_name: Name of the route - :param api_router_file: Router file resolved from the project layout. - Defaults to ``/api.py`` for callers that don't resolve one. - """ - api_dir = target_dirs["api"] - if not api_router_file: - api_router_file = os.path.join(api_dir, "api.py") - - if not os.path.exists(api_router_file): - # Create the router module if it doesn't exist - api_source = os.path.join(modules_dir, "api", "__init__.py-tpl") - if os.path.exists(api_source): - copy_and_convert_template_file(api_source, api_router_file) - - # The __init__ template may be empty; initialize the API router. - if os.path.exists(api_router_file): - with open(api_router_file, "r", encoding="utf-8") as f: - content = f.read() - if not content.strip(): - write_generated_text( - api_router_file, - "from fastapi import APIRouter\n\napi_router = APIRouter()\n", - ) - - # Update API router to include new route - if os.path.exists(api_router_file): - _update_api_router(api_router_file, route_name) - - -def _update_api_router(api_router_file: str, route_name: str) -> None: - """ - Update API router file to include new route. - - Insertion points come from the ``# fastkit:imports`` / - ``# fastkit:routes`` anchors when the template declares them, and from - the module's AST otherwise. + Each route module is imported on its own line, ``from + src.api.routes.orders import router as orders_router``, so the import + block stays isort-sorted however many routes are added (separate + ``from src.api.routes import a`` / ``import b`` lines would have to be + merged). A router module that already imports the route module itself + (the templates' ``from src.api.routes import items``, or the relative + ``from .routes import items`` older fastkit versions wrote) keeps that + import and its registration. The route's ``APIRouter`` carries its own + prefix and tags, so the registration takes none. Insertion points come + from the ``# fastkit:imports`` / ``# fastkit:routes`` anchors when the + module declares them, and from the module's AST otherwise. :param api_router_file: Path to API router file :param route_name: Name of the route - """ - try: - with open(api_router_file, "r", encoding="utf-8") as f: - content = f.read() - - alias = router_alias(api_router_file, "routes", route_name, route_name) - suffix = f" as {alias}" if alias != route_name else "" - route_import = f"from .routes import {route_name}{suffix}" - route_include = ( - f"api_router.include_router({alias}.router, " - f'prefix="/{route_name}", tags=["{route_name}"])' - ) + :param package_module: Dotted package holding ``api`` (``src``, + ``src.app``); empty for imports relative to the router module + :param plan: Plan to record the change in; applied here when omitted + """ + from fastapi_fastkit.backend.route_wiring import ( + existing_router_import, + plan_router_registration, + print_plan_notes, + ) - register_router( - { - "api_dir": os.path.dirname(api_router_file), - "api_router_file": api_router_file, - }, - route_import, - route_include, + target_plan = plan if plan is not None else RoutePlan() + routes_package = f"{package_module}.api.routes" if package_module else "" + spellings = [(1, "routes")] + ([(0, routes_package)] if routes_package else []) + module_import = existing_router_import( + target_plan.read(api_router_file) or "", spellings, route_name + ) + if module_import is not None: + bound = module_import.rsplit(" ", 1)[-1] + route_import, registered = module_import, f"{bound}.router" + else: + module = ( + f"{routes_package}.{route_name}" + if routes_package + else f"routes.{route_name}" ) + alias = router_alias( + api_router_file, module, "router", f"{route_name}_router", target_plan + ) + prefix = "" if routes_package else "." + suffix = f" as {alias}" if alias != "router" else "" + route_import = f"from {prefix}{module} import router{suffix}" + registered = alias + plan_router_registration( + target_plan, + { + "api_dir": os.path.dirname(api_router_file), + "api_router_file": api_router_file, + }, + route_import, + f"api_router.include_router({registered})", + ) + if plan is None: + print_plan_notes(target_plan) + target_plan.apply() + debug_log(f"Planned API router registration for {route_name}", "info") - debug_log(f"Updated API router to include {route_name}", "info") - - except (OSError, UnicodeDecodeError) as e: - debug_log(f"Error updating API router: {e}", "error") - - -def _process_init_files( - modules_dir: str, target_dirs: Dict[str, str], module_types: List[str] -) -> None: - """ - Process __init__.py files if they don't exist. - :param modules_dir: Path to the modules directory - :param target_dirs: Dictionary with paths to target directories - :param module_types: List of module types to process - """ - for module_type in module_types: - module_base = module_type.split("/")[0] - init_source = os.path.join(modules_dir, module_base, "__init__.py-tpl") - - if os.path.exists(init_source): - init_target_dir = target_dirs.get(module_base, None) or target_dirs.get( - f"{module_base}_routes" - ) - if init_target_dir: - init_target = os.path.join(init_target_dir, "__init__.py") - if not os.path.exists(init_target): - copy_and_convert_template_file(init_source, init_target) +def _package_of_router_module(router_module: str) -> str: + """``src.app`` for ``src.app.api.router``; ``""`` for ``api.api``.""" + parts = router_module.split(".") + if len(parts) >= 2 and parts[-2] == "api": + return ".".join(parts[:-2]) + return ".".join(parts[:-1]) def _update_main_app( @@ -1846,10 +1848,14 @@ def _update_main_app( route_name: str, router_module: str = "", main_py_path: str = "", + plan: Optional[RoutePlan] = None, ) -> None: """ Update the main application file to include the API router. + When the project's settings define ``API_V1_PREFIX`` the router is + mounted under it, as the templates mount their own routers. + :param src_dir: Package directory holding ``main.py`` (``src`` or ``src/app`` depending on the template layout) :param route_name: Name of the route to add @@ -1857,85 +1863,173 @@ def _update_main_app( ``src_dir`` when omitted, preserving the classic ``src.api.api``. :param main_py_path: Explicit entrypoint path; defaults to ``/main.py``. + :param plan: Plan to record the change in; applied here when omitted """ + from fastapi_fastkit.backend.route_wiring import print_plan_notes + if not main_py_path: main_py_path = os.path.join(src_dir, "main.py") if not router_module: router_module = f"{os.path.basename(src_dir)}.api.api" - if not os.path.exists(main_py_path): - print_warning("main.py not found. Please manually add the API router.") - return - + target_plan = plan if plan is not None else RoutePlan() try: - main_content, newline = read_text_preserving_newlines(main_py_path) + main_content = target_plan.read(main_py_path) + if main_content is None: + target_plan.note( + "main.py not found. Please manually add the API router.", "warning" + ) + else: + _plan_main_app( + target_plan, src_dir, main_py_path, main_content, router_module + ) + except (OSError, UnicodeDecodeError) as e: + debug_log(f"Error updating main.py: {e}", "error") + target_plan.note(f"Failed to update main.py: {e}", "warning") - # Check if router is already imported or included - router_import = f"from {router_module} import api_router" - router_include = "app.include_router(api_router" + if plan is None: + print_plan_notes(target_plan) + target_plan.apply() + debug_log(f"Planned main.py update for {route_name}", "info") - if router_import in main_content and router_include in main_content: - # Router already fully configured, nothing to do - return - # Check if FastAPI app is defined - if "app = FastAPI" not in main_content: - print_warning( - "FastAPI app instance not found in main.py. Please manually add router." - ) - return +_PREFIXED_INCLUDE = "app.include_router(api_router, prefix=settings.API_V1_PREFIX)" + + +def _binds_settings(content: str) -> bool: + """Whether a module binds ``settings`` at the top level.""" + try: + tree = ast.parse(content) + except SyntaxError: + return False + for node in tree.body: + if isinstance(node, (ast.Import, ast.ImportFrom)): + if any((a.asname or a.name) == "settings" for a in node.names): + return True + elif isinstance(node, (ast.Assign, ast.AnnAssign)): + targets = node.targets if isinstance(node, ast.Assign) else [node.target] + if any(isinstance(t, ast.Name) and t.id == "settings" for t in targets): + return True + return False - main_content = insert_import_line(main_content, router_import) - if router_include not in main_content: - main_content = insert_statement_line( - main_content, "app.include_router(api_router)" +def _versioned_include( + plan: RoutePlan, + src_dir: str, + main_py_path: str, + main_content: str, + router_module: str, +) -> tuple[str, str]: + """ + Choose how ``main.py`` mounts the API router. + + Business routers go under ``settings.API_V1_PREFIX`` whenever the + project's settings define it: settings living in ``main.py`` itself + (``fastapi-single-module``) or in ``core/config.py`` (imported when + ``main.py`` does not bind ``settings`` yet). Projects generated before + the setting existed get the router at the root, and the plan says so. + + :return: ``(main_content, include statement)`` + """ + if "API_V1_PREFIX" in main_content and _binds_settings(main_content): + return main_content, _PREFIXED_INCLUDE + config = plan.read(os.path.join(src_dir, "core", "config.py")) or "" + if "API_V1_PREFIX" in config: + if not _binds_settings(main_content): + package = _package_of_router_module(router_module) + config_module = f"{package}.core.config" if package else "core.config" + main_content = insert_import_line( + main_content, f"from {config_module} import settings" ) + return main_content, _PREFIXED_INCLUDE + plan.note( + f"{plan.display(main_py_path)} mounts api_router at the root: the " + "project's settings define no API_V1_PREFIX. Add one and pass " + "prefix=settings.API_V1_PREFIX to app.include_router(api_router) to " + "version the API." + ) + return main_content, "app.include_router(api_router)" - write_text_preserving_newlines(main_py_path, main_content, newline) - debug_log(f"Updated main.py to include router for {route_name}", "info") +def _plan_main_app( + plan: RoutePlan, + src_dir: str, + main_py_path: str, + main_content: str, + router_module: str, +) -> None: + router_import = f"from {router_module} import api_router" + router_include = "app.include_router(api_router" + code = code_without_comments(main_content) - except (OSError, UnicodeDecodeError) as e: - debug_log(f"Error updating main.py: {e}", "error") - print_warning(f"Failed to update main.py: {e}") + if router_import in code and router_include in code: + # Router already fully configured, nothing to do + return + + if "app = FastAPI" not in code: + plan.note( + "FastAPI app instance not found in main.py. Please manually add router.", + "warning", + ) + return + + main_content = insert_import_line(main_content, router_import) + + if router_include not in code_without_comments(main_content): + main_content, include = _versioned_include( + plan, src_dir, main_py_path, main_content, router_module + ) + main_content = insert_statement_line(main_content, include) + + plan.write(main_py_path, main_content) def add_new_route( - project_dir: str, route_name: str, layout: Optional[str] = None -) -> None: + project_dir: str, + route_name: str, + layout: Optional[str] = None, + entity: Optional[str] = None, + plan: Optional[RoutePlan] = None, +) -> RoutePlan: """ Add a new API route to an existing FastAPI project. The target locations come from :func:`resolve_project_layout`, so the command works for both the classic ``src/main.py`` layout and the - domain-starter's ``src/app/main.py``. + domain-starter's ``src/app/main.py``. Every file is computed first + (:func:`~fastapi_fastkit.backend.route_generators.plan_new_route`) and + written only once the whole plan is known. :param project_dir: Path to the project directory :param route_name: Name of the new route to add - :param layout: Explicit route layout, or None to select from preset metadata + :param layout: Explicit route layout, or None to resolve it from the + project + :param entity: Explicit entity class name, or None to derive it + :param plan: A plan already computed by ``plan_new_route`` and shown to + the user (the CLI renders it before asking); computed here, and its + notes printed, when omitted + :return: The applied plan :raises BackendExceptions: If route addition fails """ try: # Import here to avoid a circular import with route_generators. - from fastapi_fastkit.backend.route_generators import ( - get_route_generator, - resolve_route_layout, - ) + from fastapi_fastkit.backend.route_generators import plan_new_route + from fastapi_fastkit.backend.route_wiring import print_plan_notes - route_layout = resolve_route_layout(project_dir, layout) - project_layout = resolve_project_layout(project_dir) - get_route_generator(route_layout).add_new_route( - project_dir, route_name, project_layout - ) + if plan is None: + plan = plan_new_route(project_dir, route_name, layout=layout, entity=entity) + print_plan_notes(plan) + plan.apply() debug_log(f"Successfully added new route: {route_name}", "info") print_success(f"Route '{route_name}' has been added successfully!") + return plan - except (OSError, PermissionError) as e: + except OSError as e: + # Reported once, as a plain message, by the caller (the CLI); the + # plan has already rolled back what it wrote. debug_log(f"File system error while adding route {route_name}: {e}", "error") - handle_exception(e, f"Error adding new route: {str(e)}") - raise BackendExceptions(f"Failed to add new route: {str(e)}") + raise BackendExceptions(f"Failed to add new route: {e}") from e except BackendExceptions: # Re-raise our own exceptions raise diff --git a/src/fastapi_fastkit/backend/project_builder/config_generator.py b/src/fastapi_fastkit/backend/project_builder/config_generator.py index a2270f7..f9c7e49 100644 --- a/src/fastapi_fastkit/backend/project_builder/config_generator.py +++ b/src/fastapi_fastkit/backend/project_builder/config_generator.py @@ -3,9 +3,10 @@ # # Turns one interactive-``init`` configuration mapping into the complete set # of files a project needs for the features the user picked: ``main.py``, -# database / auth modules, background workers and their routes, cache, -# WebSocket and pagination routers, structured logging, Alembic migrations, -# developer tooling and the Docker files. +# the settings the features read, database / auth modules, background +# workers and their routes, cache, WebSocket and readiness routers, rate +# limiting, logging and tracing setup, Alembic migrations, developer tooling +# and the Docker files. # # Every artifact is rendered from a Jinja2 fragment stored in # ``src/fastapi_fastkit/fragments``. See ``fragments/README.md`` for the @@ -17,7 +18,9 @@ # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- +import ast import hashlib +import json import re import sys from dataclasses import dataclass, field @@ -27,11 +30,13 @@ from jinja2 import Environment, PackageLoader +from fastapi_fastkit.backend.doctor.known import KNOWN_EXAMPLE_SECRETS from fastapi_fastkit.backend.package_managers.pyproject import ( PyprojectMergeError, parse_toml, split_toml_tables, ) +from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import ( NONE_CHOICE, AsyncTaskChoice, @@ -70,6 +75,22 @@ DatabaseChoice.REDIS: "redis", } +#: Connection settings of the app and worker containers per compose +#: database service (the host is the service name, not localhost). +_COMPOSE_DB_ENVIRONMENT: Dict[str, str] = { + "postgres": ( + "DATABASE_URL=${DATABASE_URL:-postgresql+asyncpg://" + "${POSTGRES_USER:-user}:${POSTGRES_PASSWORD:-password}" + "@postgres:5432/${POSTGRES_DB:-dbname}}" + ), + "mysql": ( + "DATABASE_URL=${DATABASE_URL:-mysql+aiomysql://" + "${MYSQL_USER:-user}:${MYSQL_PASSWORD:-password}" + "@mysql:3306/${MYSQL_DATABASE:-dbname}}" + ), + "mongodb": "MONGODB_URL=${MONGODB_URL:-mongodb://mongodb:27017}", +} + #: docker-compose named volume per database service. _COMPOSE_DB_VOLUMES: Dict[str, str] = { "postgres": "postgres_data", @@ -80,7 +101,16 @@ #: Default entrypoint when the caller does not describe the project layout. DEFAULT_MAIN_RELPATH = "src/main.py" DEFAULT_DB_CONFIG_RELPATH = "src/config/database.py" -DEFAULT_AUTH_CONFIG_RELPATH = "src/config/auth.py" +#: Package the authentication modules are generated in. +DEFAULT_AUTH_PACKAGE_RELPATH = "src/auth" +DEFAULT_SETTINGS_RELPATH = "src/core/config.py" + +#: Comment that marks where generated settings fields go in a template's +#: ``Settings`` class. Optional: without it they follow the last field. +SETTINGS_ANCHOR = "# fastkit:settings" + +#: Default Redis URL shared by the cache, the Redis database and the brokers. +_REDIS_URL = "redis://localhost:6379/0" #: Files written with the executable bit set. _EXECUTABLE_ARTIFACTS = frozenset({"scripts/migrate.sh"}) @@ -91,9 +121,33 @@ #: Auth choices whose module signs tokens or cookies with ``SECRET_KEY``. _SIGNING_AUTH_CHOICES = frozenset( - {AuthChoice.JWT, AuthChoice.OAUTH2, AuthChoice.SESSION} + {AuthChoice.JWT, AuthChoice.OAUTH2, AuthChoice.SESSION, AuthChoice.FASTAPI_USERS} ) +#: Auth choices whose users live in the generated user store. +_USER_STORE_AUTH_CHOICES = frozenset({AuthChoice.JWT, AuthChoice.SESSION}) + +#: Auth choices that keep their state in the signed session cookie. +_SESSION_AUTH_CHOICES = frozenset({AuthChoice.OAUTH2, AuthChoice.SESSION}) + +#: SECRET_KEY values published in fastkit templates, fragments and docs: the +#: set ``fastkit doctor`` flags and the templates' ``KNOWN_EXAMPLE_SECRET_KEYS`` +#: hold. Anyone can sign with them, so staging and production refuse them. +#: Every generated guard (the settings module fragment and the validator +#: injected into template settings) is rendered from this one tuple. +PUBLIC_EXAMPLE_SECRET_KEYS: Tuple[str, ...] = tuple(sorted(KNOWN_EXAMPLE_SECRETS)) + +#: Shortest SECRET_KEY staging and production accept: HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes (the templates' ``MIN_SECRET_KEY_BYTES``). +MIN_SECRET_KEY_BYTES = 32 + +#: Name of the guard added to the settings class with auth. It applies to +#: every environment except development; the name is kept from v1.5. +AUTH_GUARD_METHOD = "_check_auth_settings_for_production" + +#: Line length of the generated code (black / ruff default). +_LINE_LENGTH = 88 + def _env_example_declares(content: str, variable: str) -> bool: """Whether ``.env.example`` already mentions ``variable``, even commented out.""" @@ -101,6 +155,61 @@ def _env_example_declares(content: str, variable: str) -> bool: return re.search(pattern, content, re.M) is not None +def _name_sort_key(name: str) -> Tuple[int, str]: + """isort / ruff ``order-by-type``: CONSTANTS, then Classes, then the rest.""" + if name.isupper() and len(name) > 1: + return (0, name) + if name[:1].isupper(): + return (1, name) + return (2, name) + + +def _format_from_import(module: str, names: Sequence[str]) -> str: + """One ``from module import names`` statement, wrapped the way black does.""" + ordered = sorted(dict.fromkeys(names), key=_name_sort_key) + line = f"from {module} import {', '.join(ordered)}" + if len(line) <= _LINE_LENGTH: + return line + body = "".join(f" {name},\n" for name in ordered) + return f"from {module} import (\n{body})" + + +def format_imports(lines: Sequence[str]) -> str: + """Sort single-line ``from x import a, b`` statements of one isort section. + + Fragments build their first-party imports from layout-dependent module + paths (``src.auth`` or ``src.app.domains.auth``), so their order is only + known at render time. Statements for the same module are merged and long + ones are wrapped, so the block passes ``ruff check`` (I001) and + ``ruff format --check`` as generated. + + Args: + lines: ``from import `` statements + + Returns: + The sorted block, without a trailing newline + """ + modules: Dict[str, List[str]] = {} + for line in lines: + module, _, names = line.strip()[len("from ") :].partition(" import ") + modules.setdefault(module, []).extend( + name.strip() for name in names.split(",") if name.strip() + ) + statements: List[str] = [] + for module in sorted(modules): + # ``name as alias`` stays a statement of its own (isort / ruff do not + # combine aliased imports), after the plain names of the module. + plain = [name for name in modules[module] if " as " not in name] + aliased = sorted( + dict.fromkeys(name for name in modules[module] if " as " in name), + key=lambda name: _name_sort_key(name.split(" as ", 1)[0]), + ) + if plain: + statements.append(_format_from_import(module, plain)) + statements.extend(f"from {module} import {name}" for name in aliased) + return "\n".join(statements) + + @lru_cache(maxsize=1) def get_environment() -> Environment: """ @@ -109,13 +218,15 @@ def get_environment() -> Environment: Returns: Configured Jinja2 environment """ - return Environment( + environment = Environment( loader=PackageLoader("fastapi_fastkit", "fragments"), keep_trailing_newline=True, trim_blocks=True, lstrip_blocks=True, autoescape=False, ) + environment.globals["format_imports"] = format_imports + return environment def _dotted(relpath: str) -> str: @@ -162,12 +273,644 @@ class MainSections: #: Fragments contributing import statements (sorted before rendering). import_fragments: list[str] = field(default_factory=list) - #: 4-space-indented statements inside the lifespan handler. - lifespan_fragments: list[str] = field(default_factory=list) + #: 4-space-indented statements run by the lifespan before ``yield``. + startup_fragments: list[str] = field(default_factory=list) + #: 4-space-indented statements run by the lifespan after ``yield``. + shutdown_fragments: list[str] = field(default_factory=list) #: Top-level statements placed right after ``app = FastAPI(...)``. setup_fragments: list[str] = field(default_factory=list) - #: Whether any fragment reads ``os.environ``, so ``main.py`` imports ``os``. - needs_os: bool = False + + +@dataclass(frozen=True) +class SettingField: + """One configuration value a generated feature reads from ``settings``.""" + + name: str + #: Python annotation (builtin types only, so no import is needed). + annotation: str + #: Python source of the default value. + default: str + #: ``.env.example`` comment lines (without ``# ``) describing the value. + doc: Tuple[str, ...] = () + #: ``from x import y`` / ``import x`` lines the annotation or default + #: needs; added to the module when the field is injected. + imports: Tuple[str, ...] = () + + @property + def env_value(self) -> str: + """The default as it is written in a ``.env`` file.""" + if self.default.startswith('"'): # a string (``str`` or a ``Literal``) + return str(json.loads(self.default)) + return self.default.lower() + + +@dataclass(frozen=True) +class SettingGroup: + """Settings fields one feature adds, rendered under one comment.""" + + title: str + fields: Tuple[SettingField, ...] + + +def _str_field(name: str, value: str, *doc: str) -> SettingField: + return SettingField(name, "str", json.dumps(value), tuple(doc)) + + +def _settings_class(tree: ast.Module) -> Optional[ast.ClassDef]: + """The project's settings class: ``Settings``, else any ``BaseSettings``.""" + classes = [node for node in tree.body if isinstance(node, ast.ClassDef)] + for node in classes: + if node.name == "Settings": + return node + for node in classes: + if any(ast.unparse(base).endswith("BaseSettings") for base in node.bases): + return node + return None + + +def _declared_fields(cls: ast.ClassDef) -> set[str]: + """Names assigned at the top level of a class body.""" + names: set[str] = set() + for node in cls.body: + if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + names.add(node.target.id) + elif isinstance(node, ast.Assign): + names.update(t.id for t in node.targets if isinstance(t, ast.Name)) + return names + + +class SettingsInjectionError(BackendExceptions): + """Adding generated code would have broken the project's settings module. + + Raised instead of writing a module that no longer parses or that lost a + statement of the original, so generation stops (and is rolled back) with + a clear message rather than leaving a project that cannot start. + """ + + +def _source_prefix(line: str, col_offset: int) -> str: + """The text of ``line`` before an AST ``col_offset`` (a UTF-8 byte offset).""" + return line.encode("utf-8")[:col_offset].decode("utf-8", errors="replace") + + +def _line_indent(line: str) -> str: + """Leading whitespace of ``line``.""" + return line[: len(line) - len(line.lstrip(" \t"))] + + +def _indent_unit(lines: Sequence[str]) -> str: + """One indentation level as the module writes it: a tab or four spaces.""" + for line in lines: + if line.strip() and line[:1] in (" ", "\t"): + return "\t" if line.startswith("\t") else " " + return " " + + +def _body_indent(lines: Sequence[str], cls: ast.ClassDef) -> str: + """Indentation of the members of ``cls`` (its own statements' prefix).""" + for node in cls.body: + prefix = _source_prefix(lines[node.lineno - 1], node.col_offset) + if not prefix.strip(): + return prefix + return _line_indent(lines[cls.lineno - 1]) + _indent_unit(lines) + + +def _first_line(node: ast.stmt) -> int: + """First line of a statement, decorators included (1-based).""" + decorators: List[ast.expr] = getattr(node, "decorator_list", None) or [] + return min([node.lineno] + [d.lineno for d in decorators]) + + +def _settings_class_named(tree: ast.Module, name: str) -> Optional[ast.ClassDef]: + return next( + (n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == name), + None, + ) + + +def _with_body_on_own_lines(content: str) -> str: + """Move a settings class body that shares the header line onto its own line. + + ``class Settings(BaseSettings): pass`` has no line to insert members + after; ``class Settings(BaseSettings):\\n pass`` does. The statements + themselves are kept verbatim (only their line changes), so the AST is + identical. Anything else is returned unchanged. + """ + try: + tree = ast.parse(content) + except SyntaxError: + return content + cls = _settings_class(tree) + if cls is None or not cls.body: + return content + first = cls.body[0] + lines = content.split("\n") + line = lines[first.lineno - 1] + head = _source_prefix(line, first.col_offset) + if not head.strip(): + return content + body = line[len(head) :].strip() + indent = _line_indent(lines[cls.lineno - 1]) + _indent_unit(lines) + lines[first.lineno - 1 : first.lineno] = [head.rstrip(), indent + body] + return "\n".join(lines) + + +def _import_keys(nodes: Sequence[ast.stmt]) -> set[Tuple[Any, ...]]: + """One key per name bound by the top-level imports among ``nodes``.""" + keys: set[Tuple[Any, ...]] = set() + for node in nodes: + if isinstance(node, ast.Import): + keys.update(("import", a.name, a.asname) for a in node.names) + elif isinstance(node, ast.ImportFrom): + keys.update( + ("from", node.level, node.module, a.name, a.asname) for a in node.names + ) + return keys + + +def _is_subsequence(needles: Sequence[str], haystack: Sequence[str]) -> bool: + """Whether every item of ``needles`` occurs in ``haystack``, in order.""" + remaining = iter(haystack) + return all(any(needle == item for item in remaining) for needle in needles) + + +def _verify_settings_injection(original: str, updated: str, class_name: str) -> str: + """Return ``updated`` once it is proven to be ``original`` plus additions. + + The result must parse, still bind every name the original imported, keep + every other top-level statement (in order) and keep the settings class's + name, bases, keywords, decorators and every original member (in order). + Added members, statements and imported names are allowed. + + Raises: + SettingsInjectionError: the injection would have broken the module + """ + if updated == original: + return updated + try: + new_tree = ast.parse(updated) + except SyntaxError as exc: + raise SettingsInjectionError( + "Adding the generated settings would leave the settings module " + f"unparsable ({exc.msg}, line {exc.lineno}); nothing was written. " + f"Add the fields to the '{class_name}' class by hand." + ) from exc + old_tree = ast.parse(original) + + def other_statements(tree: ast.Module) -> List[str]: + return [ + ast.dump(node) + for node in tree.body + if not isinstance(node, (ast.Import, ast.ImportFrom)) + and not (isinstance(node, ast.ClassDef) and node.name == class_name) + ] + + old_cls = _settings_class_named(old_tree, class_name) + new_cls = _settings_class_named(new_tree, class_name) + problems: List[str] = [] + if not _import_keys(old_tree.body) <= _import_keys(new_tree.body): + problems.append("an import was lost") + if not _is_subsequence(other_statements(old_tree), other_statements(new_tree)): + problems.append("a top-level statement changed") + if old_cls is None or new_cls is None: + problems.append(f"the '{class_name}' class is gone") + else: + header = ("bases", "keywords", "decorator_list") + if any( + [ast.dump(n) for n in getattr(old_cls, part)] + != [ast.dump(n) for n in getattr(new_cls, part)] + for part in header + ): + problems.append(f"the '{class_name}' class header changed") + if not _is_subsequence( + [ast.dump(n) for n in old_cls.body], [ast.dump(n) for n in new_cls.body] + ): + problems.append(f"a member of '{class_name}' changed") + if problems: + raise SettingsInjectionError( + "Adding the generated settings would change the existing settings " + f"module ({'; '.join(problems)}); nothing was written. Add the " + f"fields to the '{class_name}' class by hand." + ) + return updated + + +def inject_settings_fields(content: str, groups: Sequence[SettingGroup]) -> str: + """Add the fields of ``groups`` a module's settings class does not declare. + + Fields the class already declares are left alone, so a template's own + value wins. The new fields go below a ``# fastkit:settings`` comment in + the class when there is one, otherwise right after the class's last + field (after its docstring, or above its first member, when it declares + none). They are indented like the class's members (tabs or spaces). + Content without a settings class (or that does not parse) is returned + unchanged. + + Args: + content: Source of the settings module (``\\n`` line endings) + groups: Fields to make sure the class declares + + Returns: + The updated source + + Raises: + SettingsInjectionError: the result would not parse or would lose a + statement of ``content`` + """ + original = content + try: + tree = ast.parse(content) + except SyntaxError: + return content + cls = _settings_class(tree) + if cls is None: + return content + + declared = _declared_fields(cls) + pending = [ + SettingGroup( + group.title, + tuple(f for f in group.fields if f.name not in declared), + ) + for group in groups + ] + pending = [group for group in pending if group.fields] + if not pending: + return content + + content = _with_body_on_own_lines(content) + tree = ast.parse(content) + cls = _settings_class(tree) + assert cls is not None # the same class as above, only reformatted + lines = content.split("\n") + indent = _body_indent(lines, cls) + end = cls.end_lineno or cls.lineno + + anchor = next( + ( + number + for number in range(cls.lineno, end + 1) + if lines[number - 1].strip() == SETTINGS_ANCHOR + ), + None, + ) + block: List[str] = [] + if anchor is not None: + indent = _line_indent(lines[anchor - 1]) + insert_at = anchor + else: + fields = [ + node for node in cls.body if isinstance(node, (ast.AnnAssign, ast.Assign)) + ] + first = cls.body[0] + if fields: + insert_at = fields[-1].end_lineno or fields[-1].lineno + block.append("") + elif isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant): + insert_at = first.end_lineno or first.lineno # below the docstring + block.append("") + else: + insert_at = _first_line(first) - 1 + + for index, group in enumerate(pending): + if index: + block.append("") + block.append(f"{indent}# {group.title}") + block.extend( + f"{indent}{f.name}: {f.annotation} = {f.default}" for f in group.fields + ) + if insert_at < len(lines) and lines[insert_at].strip(): + block.append("") + + lines[insert_at:insert_at] = block + updated = "\n".join(lines) + for import_line in dict.fromkeys( + line for group in pending for f in group.fields for line in f.imports + ): + updated = ensure_import(updated, import_line) + return _verify_settings_injection(original, updated, cls.name) + + +def _module_binds(tree: ast.Module, name: str) -> bool: + """Whether a top-level statement of ``tree`` binds ``name``.""" + for node in tree.body: + if isinstance(node, (ast.Import, ast.ImportFrom)): + for alias in node.names: + bound = alias.asname or alias.name.split(".", 1)[0] + if bound == name: + return True + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + if node.name == name: + return True + elif isinstance(node, ast.Assign): + if any(isinstance(t, ast.Name) and t.id == name for t in node.targets): + return True + return False + + +def ensure_import(content: str, import_line: str) -> str: + """Make ``content`` import what ``import_line`` imports, merged into place. + + A ``from x import y`` joins an existing top-level ``from x import ...`` + statement (rewritten sorted, and wrapped when too long) so the module + stays clean for isort / ruff; otherwise the line is inserted into the + import block. Names the module already binds are left alone. + + Args: + content: Module source (``\\n`` line endings) + import_line: One ``from x import y`` or ``import x`` statement + + Returns: + The updated source (unchanged when nothing was missing or the module + does not parse) + """ + try: + tree = ast.parse(content) + (new_node,) = ast.parse(import_line).body + except (SyntaxError, ValueError): + return content + if not isinstance(new_node, (ast.Import, ast.ImportFrom)): + return content + missing = [ + alias + for alias in new_node.names + if not _module_binds(tree, alias.asname or alias.name.split(".", 1)[0]) + ] + if not missing: + return content + + if isinstance(new_node, ast.ImportFrom) and new_node.level == 0: + for node in tree.body: + if ( + isinstance(node, ast.ImportFrom) + and node.module == new_node.module + and node.level == 0 + and not any(alias.asname for alias in node.names) + and not any(alias.asname for alias in missing) + ): + names = [alias.name for alias in node.names] + names += [alias.name for alias in missing] + lines = content.split("\n") + start, end = node.lineno - 1, node.end_lineno or node.lineno + lines[start:end] = _format_from_import(str(node.module), names).split( + "\n" + ) + return "\n".join(lines) + + sorted_into_block = _insert_import_by_section(content, tree, new_node, import_line) + if sorted_into_block is not None: + return sorted_into_block + + # Imported lazily: ``backend.main`` imports this package. + from fastapi_fastkit.backend.main import insert_import_line + + return insert_import_line(content, import_line) + + +def _isort_position(node: ast.stmt) -> Tuple[int, int, str, str]: + """``(section, kind, module)`` sort key of an import, as isort orders them. + + Sections: ``__future__``, standard library, third party, then relative + imports; within a section every ``import x`` precedes every ``from x + import y`` (isort / ruff ``force-sort-within-sections = false``), each + ordered by module name, case-insensitively first. + """ + if isinstance(node, ast.ImportFrom): + module = ("." * node.level) + (node.module or "") + kind = 1 + else: + assert isinstance(node, ast.Import) + module = node.names[0].name + kind = 0 + root = module.split(".", 1)[0] + if root == "__future__": + section = 0 + elif module.startswith("."): + section = 3 + elif root in sys.stdlib_module_names: + section = 1 + else: + section = 2 + return (section, kind, module.lower(), module) + + +def _insert_import_by_section( + content: str, tree: ast.Module, new_node: ast.stmt, import_line: str +) -> Optional[str]: + """Insert ``import_line`` into the leading import block at its isort place. + + None when the module has no leading import block (the caller then falls + back to the generic insertion). + """ + block: List[ast.stmt] = [] + for node in tree.body: + if isinstance(node, (ast.Import, ast.ImportFrom)): + block.append(node) + elif not block and isinstance(node, ast.Expr): + continue # module docstring + else: + break + if not block: + return None + new_key = _isort_position(new_node) + lines = content.split("\n") + same_section = [n for n in block if _isort_position(n)[0] == new_key[0]] + if same_section: + after = next((n for n in same_section if _isort_position(n) > new_key), None) + if after is not None: + lines.insert(after.lineno - 1, import_line) + else: + last = same_section[-1] + lines.insert(last.end_lineno or last.lineno, import_line) + return "\n".join(lines) + later = next((n for n in block if _isort_position(n)[0] > new_key[0]), None) + if later is not None: + lines[later.lineno - 1 : later.lineno - 1] = [import_line, ""] + else: + last = block[-1] + end = last.end_lineno or last.lineno + lines[end:end] = ["", import_line] + return "\n".join(lines) + + +def inject_settings_validator( + content: str, method_name: str, method_lines: Sequence[str] +) -> str: + """Append a method to the module's settings class unless it has one. + + The method is re-indented to the class's own indentation (tabs or + spaces), and ``from pydantic import model_validator`` is merged into the + imports at its sorted place. + + Args: + content: Source of the settings module (``\\n`` line endings) + method_name: Name of the method (used to detect it is already there) + method_lines: The method, decorators included, indented by four + spaces; ``{settings_class}`` is replaced with the class name + + Returns: + The updated source (unchanged when the class already defines the + method, or there is no settings class) + + Raises: + SettingsInjectionError: the result would not parse or would lose a + statement of ``content`` + """ + original = content + try: + tree = ast.parse(content) + except SyntaxError: + return content + cls = _settings_class(tree) + if cls is None: + return content + if any( + isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name == method_name + for node in cls.body + ): + return content + + content = _with_body_on_own_lines(content) + tree = ast.parse(content) + cls = _settings_class(tree) + assert cls is not None # the same class as above, only reformatted + lines = content.split("\n") + member_indent = _body_indent(lines, cls) + unit = member_indent[len(_line_indent(lines[cls.lineno - 1])) :] or " " + base = min( + (len(line) - len(line.lstrip(" ")) for line in method_lines if line.strip()), + default=0, + ) + + def reindent(line: str) -> str: + stripped = line.lstrip(" ") + levels = (len(line) - len(stripped) - base) // 4 + return member_indent + unit * max(levels, 0) + stripped + + end = cls.end_lineno or cls.lineno + block = [""] + [ + reindent(line.replace("{settings_class}", cls.name)) if line else "" + for line in method_lines + ] + lines[end:end] = block + updated = "\n".join(lines) + updated = ensure_import(updated, "from pydantic import model_validator") + return _verify_settings_injection(original, updated, cls.name) + + +def has_secret_key_guard(content: str) -> bool: + """Whether the settings class already guards ``SECRET_KEY`` outside development. + + A guard counts when a validator of the class exempts only + ``ENVIRONMENT == "development"`` and otherwise refuses a key that was not + set explicitly (``model_fields_set``) and a short one (``len(...)``): the + rule every fastkit template follows. A weaker template guard (one that + only checks the example values, or only applies to production) does not + count, so the generated guard is added next to it and the stricter rule + applies. + """ + try: + tree = ast.parse(content) + except SyntaxError: + return False + cls = _settings_class(tree) + if cls is None: + return False + for node in cls.body: + if ( + not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + or node.name == AUTH_GUARD_METHOD + or not any( + "validator" in ast.unparse(decorator) + for decorator in node.decorator_list + ) + ): + continue + source = ast.unparse(node) + if all( + needle in source + for needle in ( + "SECRET_KEY", + "self.ENVIRONMENT == 'development'", + "model_fields_set", + "len(", + ) + ): + return True + return False + + +def auth_guard_lines(*, demo_users: bool, secret_key: bool = True) -> List[str]: + """Source of the guard added to the settings class with auth. + + The guard applies to every environment except development (staging and + production). With ``secret_key`` it refuses a missing ``SECRET_KEY`` (the + per-process random default would sign with a key no other process + knows, and a container that forgot the variable would silently run with + it), every public example value and a key shorter than + :data:`MIN_SECRET_KEY_BYTES`; that check is left out when the template's + own validator already enforces the rule (:func:`has_secret_key_guard`). + With ``demo_users`` it also refuses ``ENABLE_DEMO_USERS``. + + Args: + demo_users: Whether the settings declare ``ENABLE_DEMO_USERS`` + secret_key: Whether the guard checks ``SECRET_KEY`` + + Returns: + Method lines indented for a class body + """ + hint = [ + ' "Generate one with "', + " '`python -c \"import secrets; print(secrets.token_urlsafe(32))\"` '", + ' "and set it in the environment or .env."', + ] + refused = [] + if secret_key: + refused.append("a missing, public or short SECRET_KEY") + if demo_users: + refused.append("demo users") + lines = [ + ' @model_validator(mode="after")', + f' def {AUTH_GUARD_METHOD}(self) -> "{{settings_class}}":', + f' """Staging and production refuse {" and ".join(refused)}."""', + ' if self.ENVIRONMENT == "development":', + " return self", + ' env = f"ENVIRONMENT={self.ENVIRONMENT}"', + ] + if secret_key: + lines += [ + ' if "SECRET_KEY" not in self.model_fields_set:', + " raise ValueError(", + ' f"SECRET_KEY must be set explicitly when {env}. "', + *hint, + " )", + " public_examples = {", + *(f' "{value}",' for value in PUBLIC_EXAMPLE_SECRET_KEYS), + " }", + " if self.SECRET_KEY.strip() in public_examples:", + " raise ValueError(", + ' "SECRET_KEY is a public example value, which must not be used "', + ' f"when {env}. "', + *hint, + " )", + f" if len(self.SECRET_KEY.encode()) < {MIN_SECRET_KEY_BYTES}:", + " raise ValueError(", + f' "SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when "', + ' f"{env}. "', + *hint, + " )", + ] + if demo_users: + lines += [ + " if self.ENABLE_DEMO_USERS:", + " raise ValueError(", + ' f"ENABLE_DEMO_USERS must be false when {env}: "', + ' "the demo account\'s password is public."', + " )", + ] + lines.append(" return self") + return lines def _declares_tool_table(pyproject_text: str, tool: str) -> bool: @@ -205,8 +948,10 @@ def __init__( app_module: str = "src.main:app", main_py_relpath: str = DEFAULT_MAIN_RELPATH, db_config_relpath: str = DEFAULT_DB_CONFIG_RELPATH, - auth_config_relpath: str = DEFAULT_AUTH_CONFIG_RELPATH, - omit_example_routers: Sequence[str] = (), + auth_package_relpath: str = DEFAULT_AUTH_PACKAGE_RELPATH, + settings_relpath: str = DEFAULT_SETTINGS_RELPATH, + shipped_paths: Sequence[str] = (), + provide_pagination: bool = False, ) -> None: """ Initialize config generator. @@ -217,21 +962,30 @@ def __init__( app_module: ``module:attr`` uvicorn entrypoint of the layout main_py_relpath: Project-relative path of the application entrypoint db_config_relpath: Project-relative path of the database module - auth_config_relpath: Project-relative path of the auth module - omit_example_routers: Labels of features (``"Pagination"``) whose - demo router is not generated because the base template - already serves that collection. Decided by - ``PresetLayoutStrategist.skipped_example_labels``, which only - names features for presets that keep the template's - ``main.py`` (the preserved file is wired separately). + auth_package_relpath: Project-relative directory of the generated + authentication package (``src/auth``) + settings_relpath: Project-relative path of the project's settings + module (exports ``settings``). Generated features read their + configuration from it; the fields they need are added to the + template's ``Settings`` class, or the module is generated + when the template ships none. + shipped_paths: Paths a preserved template ``main.py`` already + serves (``"/ready"``); the matching generated router is then + not created. Ignored when ``main.py`` is regenerated. + provide_pagination: Whether the shared ``core/pagination.py`` and + ``core/responses.py`` are written when the template does not + ship them (presets whose base template has no list endpoint + of its own). """ self.config = config self.project_dir = Path(project_dir) self.app_module = app_module self.main_py_relpath = main_py_relpath self.db_config_relpath = db_config_relpath - self.auth_config_relpath = auth_config_relpath - self.omit_example_routers = frozenset(omit_example_routers) + self.auth_package_relpath = auth_package_relpath.replace("\\", "/").strip("/") + self.settings_relpath = settings_relpath + self.shipped_paths = frozenset(shipped_paths) + self.provide_pagination = provide_pagination # ----------------------------------------------------------------- # # Layout helpers @@ -254,8 +1008,18 @@ def db_module(self) -> str: @property def auth_module(self) -> str: - """Dotted import path of the generated auth module.""" - return _dotted(self.auth_config_relpath) + """Dotted import path of the generated authentication package.""" + return _dotted(self.auth_package_relpath) + + @property + def main_module(self) -> str: + """Dotted import path of the application entrypoint.""" + return _dotted(self.main_py_relpath) + + @property + def settings_module(self) -> str: + """Dotted import path of the project's settings module.""" + return _dotted(self.settings_relpath) # ----------------------------------------------------------------- # # Rendering helpers @@ -282,7 +1046,14 @@ def _render_module(self, template_name: str, **context: Any) -> str: package_dir=self.package_dir, db_module=self.db_module, auth_module=self.auth_module, + settings_module=self.settings_module, + main_module=self.main_module, app_module=self.app_module, + auth_kind=self._auth_kind, + backend=self._user_store_backend, + id_type="str" if self._user_store_backend == "mongo" else "int", + create_tables=self._creates_user_table_on_startup, + rate_limit=self._uses_rate_limiting, project_name=self.config.get("project_name", "FastAPI App"), project_slug=_slugify(str(self.config.get("project_name", "app"))), **context, @@ -354,8 +1125,59 @@ def _database_type(self) -> str: @property def _auth_type(self) -> str: - """Selected authentication type, ``"None"`` when unset.""" - return self._choice(FeatureAxis.AUTHENTICATION) + """Generated authentication type, ``"None"`` when unset. + + FastAPI-Users is only generated on a SQL database; config validation + rejects it with any other database before generation starts. + """ + auth_type = self._choice(FeatureAxis.AUTHENTICATION) + if auth_type == AuthChoice.FASTAPI_USERS and not self._uses_sql_database: + return NONE_CHOICE + return auth_type + + @property + def _auth_kind(self) -> str: + """Short name of the auth option the fragments branch on.""" + kinds: Dict[str, str] = { + AuthChoice.JWT: "jwt", + AuthChoice.SESSION: "session", + AuthChoice.OAUTH2: "oauth2", + AuthChoice.FASTAPI_USERS: "fastapi_users", + } + return kinds.get(self._auth_type, "") + + @property + def _user_store_backend(self) -> str: + """Where accounts live: ``sql``, ``mongo`` or ``memory``.""" + if self._uses_sql_database: + return "sql" + if self._database_type == DatabaseChoice.MONGODB: + return "mongo" + return "memory" + + @property + def _has_users_table(self) -> bool: + """Whether a ``users`` table is generated (SQL user store).""" + return self._uses_sql_database and ( + self._auth_type in _USER_STORE_AUTH_CHOICES + or self._auth_type == AuthChoice.FASTAPI_USERS + ) + + @property + def _uses_alembic(self) -> bool: + return ( + self._choice(FeatureAxis.MIGRATIONS) == MigrationsChoice.ALEMBIC + and self._uses_sql_database + ) + + @property + def _creates_user_table_on_startup(self) -> bool: + """Without Alembic the auth router creates its table on startup.""" + return self._has_users_table and not self._uses_alembic + + @property + def _uses_rate_limiting(self) -> bool: + return UtilityChoice.RATE_LIMITING in self._choices(FeatureAxis.UTILITIES) @property def _uses_sql_database(self) -> bool: @@ -389,6 +1211,41 @@ def _needs_redis_service(self) -> bool: or self._database_type == DatabaseChoice.REDIS ) + @property + def _uses_redis_cache(self) -> bool: + return self._choice(FeatureAxis.CACHING) == CachingChoice.REDIS + + @property + def _uses_loguru(self) -> bool: + return self._choice(FeatureAxis.MONITORING) == MonitoringChoice.LOGURU + + @property + def _uses_structured_logging(self) -> bool: + return self._choice(FeatureAxis.LOGGING) == LoggingChoice.STRUCTURED + + def _readiness_checks(self) -> List[str]: + """Names of the checks ``GET /ready`` runs for this selection.""" + checks: List[str] = [] + db_type = self._database_type + if db_type in SQL_DATABASES: + checks.append("check_database") + elif db_type == DatabaseChoice.MONGODB: + checks.append("check_mongodb") + elif db_type == DatabaseChoice.REDIS: + checks.append("check_redis") + if self._uses_redis_cache: + checks.append("check_cache") + return checks + + @property + def generates_readiness(self) -> bool: + """Whether ``GET /ready`` is generated. + + Generated when a database or cache is selected, unless the preserved + template ``main.py`` already serves ``/ready`` itself. + """ + return bool(self._readiness_checks()) and "/ready" not in self.shipped_paths + def _worker_command(self) -> Optional[List[str]]: """docker-compose ``command`` for the background worker, if any.""" tasks = self._choice(FeatureAxis.ASYNC_TASKS) @@ -408,93 +1265,79 @@ def _main_fragments(self) -> MainSections: """ Resolve the fragments composing ``main.py`` for this configuration. + Setup statements keep a deliberate order: logging first, then auth, + rate limiting and instrumentation, then the routers, and CORS last so + its middleware wraps every other one (``add_middleware`` puts the + latest addition outermost). + Returns: The fragment paths for each section of the generated module """ imports: List[str] = [] - lifespan: List[str] = [] + startup: List[str] = [] + shutdown: List[str] = [] setup: List[str] = [] + def use(name: str, *sections: str) -> None: + """Register ``main/imports/.j2`` and ``main/
/.j2``.""" + imports.append(f"main/imports/{name}.j2") + targets = {"startup": startup, "shutdown": shutdown, "setup": setup} + for section in sections: + targets[section].append(f"main/{section}/{name}.j2") + db_type = self._database_type if db_type in SQL_DATABASES: - imports.append("main/imports/sqlalchemy.j2") - lifespan.append("main/lifespan/sqlalchemy.j2") + use("sqlalchemy", "shutdown") elif db_type == DatabaseChoice.MONGODB: - imports.append("main/imports/mongodb.j2") - lifespan.append("main/lifespan/mongodb.j2") + use("mongodb", "startup", "shutdown") + elif db_type == DatabaseChoice.REDIS: + use("redis_db", "shutdown") + + if self._uses_structured_logging: + use("structured_logging", "setup") + if self._uses_loguru: + use("loguru", "setup") auth_type = self._auth_type - if auth_type == AuthChoice.JWT: - imports.append("main/imports/jwt.j2") - elif auth_type == AuthChoice.FASTAPI_USERS: - imports.append("main/imports/fastapi_users.j2") - elif auth_type == AuthChoice.OAUTH2: - imports.append("main/imports/oauth2.j2") - setup.append("main/setup/oauth2.j2") - elif auth_type == AuthChoice.SESSION: - imports.append("main/imports/session_auth.j2") - setup.append("main/setup/session_auth.j2") - - if self._choice(FeatureAxis.LOGGING) == LoggingChoice.STRUCTURED: - imports.append("main/imports/structured_logging.j2") - setup.append("main/setup/structured_logging.j2") + if auth_type in _SESSION_AUTH_CHOICES: + use("session_middleware", "setup") utilities = self._choices(FeatureAxis.UTILITIES) - if UtilityChoice.CORS in utilities: - setup.append("main/setup/cors.j2") if UtilityChoice.RATE_LIMITING in utilities: - imports.append("main/imports/rate_limiting.j2") - setup.append("main/setup/rate_limiting.j2") - if UtilityChoice.WEBSOCKET in utilities: - imports.append("main/imports/websocket.j2") - setup.append("main/setup/websocket.j2") - if UtilityChoice.PAGINATION in utilities: - imports.append("main/imports/pagination.j2") - setup.append("main/setup/pagination.j2") - - if self._choice(FeatureAxis.ASYNC_TASKS) != NONE_CHOICE: - imports.append("main/imports/async_tasks.j2") - setup.append("main/setup/async_tasks.j2") - - if self._choice(FeatureAxis.CACHING) == CachingChoice.REDIS: - imports.append("main/imports/caching.j2") - lifespan.append("main/lifespan/caching.j2") - setup.append("main/setup/caching.j2") + use("rate_limiting", "setup") monitoring_type = self._choice(FeatureAxis.MONITORING) - if monitoring_type == MonitoringChoice.LOGURU: - imports.append("main/imports/loguru.j2") - elif monitoring_type == MonitoringChoice.PROMETHEUS: + if monitoring_type == MonitoringChoice.PROMETHEUS: # Module level, never in the lifespan: instrumenting adds # middleware, which Starlette refuses once the app has started. - imports.append("main/imports/prometheus.j2") - setup.append("main/setup/prometheus.j2") + use("prometheus", "setup") elif monitoring_type == MonitoringChoice.OPENTELEMETRY: - imports.append("main/imports/opentelemetry.j2") - setup.append("main/setup/opentelemetry.j2") - - # ``os`` is only imported when a fragment actually reads the - # environment, so the generated module stays lint-clean. - needs_os = bool( - {"main/lifespan/caching.j2"} & set(lifespan) - or { - "main/setup/cors.j2", - "main/setup/opentelemetry.j2", - "main/setup/structured_logging.j2", - } - & set(setup) - ) + use("opentelemetry", "setup") + + if self._choice(FeatureAxis.ASYNC_TASKS) != NONE_CHOICE: + use("async_tasks", "setup") + if self._uses_redis_cache: + use("caching", "setup") + if UtilityChoice.WEBSOCKET in utilities: + use("websocket", "setup") + if self.generates_readiness: + use("readiness", "setup") + if auth_type != NONE_CHOICE: + use("auth", "setup") + + # Always, like every template's main.py: the middleware is only added + # when BACKEND_CORS_ORIGINS lists an origin, so without one nothing + # changes. The CORS utility additionally documents the variable. + use("cors", "setup") return MainSections( import_fragments=imports, - lifespan_fragments=lifespan, + startup_fragments=startup, + shutdown_fragments=shutdown, setup_fragments=setup, - needs_os=needs_os, ) - def _build_import_groups( - self, import_fragments: List[str], needs_os: bool - ) -> List[List[str]]: + def _build_import_groups(self, import_fragments: List[str]) -> List[List[str]]: """ Render the import fragments into isort-ordered import blocks. @@ -505,21 +1348,16 @@ def _build_import_groups( Args: import_fragments: Fragment paths contributing import statements - needs_os: Whether any other fragment reads ``os.environ`` Returns: Standard-library / third-party / first-party blocks, in order """ - lines: List[str] = ["from collections.abc import AsyncIterator"] - if needs_os: - lines.append("import os") - lines.extend( - [ - "from contextlib import asynccontextmanager", - "from fastapi import FastAPI", - "from fastapi.middleware.cors import CORSMiddleware", - ] - ) + lines: List[str] = [ + "from collections.abc import AsyncIterator", + "from contextlib import asynccontextmanager", + "from fastapi import FastAPI", + f"from {self.settings_module} import settings", + ] for fragment in import_fragments: rendered = self._render_module(fragment) @@ -535,6 +1373,438 @@ def _build_import_groups( return [group for group in groups if group] + # ----------------------------------------------------------------- # + # Settings + # ----------------------------------------------------------------- # + def settings_groups(self) -> List[SettingGroup]: + """ + The settings fields the selected features read, grouped per feature. + + Returns: + Groups in the order they are added to the settings class + """ + groups: List[SettingGroup] = [] + slug = _slugify(str(self.config.get("project_name", "app"))) + + db_type = self._database_type + if db_type in SQL_DATABASES: + groups.append( + SettingGroup( + "Database", + ( + _str_field( + "DATABASE_URL", + SQLALCHEMY_URLS[db_type], + "Async SQLAlchemy URL of the database.", + ), + SettingField( + "DB_ECHO", + "bool", + "False", + ( + "Log every SQL statement (development only).", + "Parameter values are never logged: the engine hides", + "them from logs and error messages.", + ), + ), + ), + ) + ) + elif db_type == DatabaseChoice.MONGODB: + groups.append( + SettingGroup( + "MongoDB", + ( + _str_field( + "MONGODB_URL", + "mongodb://localhost:27017", + "MongoDB connection string.", + ), + _str_field( + "MONGODB_DB_NAME", + slug.replace("-", "_"), + "Database the app reads and writes.", + ), + SettingField( + "MONGODB_TIMEOUT_MS", + "int", + "5000", + ("How long an operation waits for a reachable server.",), + ), + ), + ) + ) + + if db_type == DatabaseChoice.REDIS or self._uses_redis_cache: + groups.append( + SettingGroup( + "Redis", + (_str_field("REDIS_URL", _REDIS_URL, "Redis server URL."),), + ) + ) + + tasks = self._choice(FeatureAxis.ASYNC_TASKS) + if tasks == AsyncTaskChoice.CELERY: + groups.append( + SettingGroup( + "Celery", + ( + _str_field( + "CELERY_BROKER_URL", _REDIS_URL, "Celery message broker." + ), + _str_field( + "CELERY_RESULT_BACKEND", + "", + "Where Celery stores task results (empty: the broker).", + ), + ), + ) + ) + elif tasks == AsyncTaskChoice.DRAMATIQ: + groups.append( + SettingGroup( + "Dramatiq", + ( + _str_field( + "DRAMATIQ_BROKER_URL", + _REDIS_URL, + "Dramatiq broker and result backend.", + ), + ), + ) + ) + + if self._uses_structured_logging or self._uses_loguru: + groups.append( + SettingGroup( + "Logging", + ( + _str_field( + "LOG_LEVEL", + "INFO", + "DEBUG, INFO, WARNING, ERROR or CRITICAL.", + ), + ), + ) + ) + + if self._choice(FeatureAxis.MONITORING) == MonitoringChoice.OPENTELEMETRY: + groups.append( + SettingGroup( + "OpenTelemetry", + ( + _str_field( + "OTEL_SERVICE_NAME", + slug, + "Service name attached to every span.", + ), + _str_field( + "OTEL_EXPORTER_OTLP_ENDPOINT", + "http://localhost:4318", + "OTLP/HTTP collector; spans go to /v1/traces.", + ), + _str_field( + "OTEL_TRACES_EXPORTER", + "otlp", + "otlp, or none to record spans without exporting them.", + ), + ), + ) + ) + + auth_group = self._auth_settings_group() + if auth_group is not None: + groups.append(auth_group) + + if UtilityChoice.RATE_LIMITING in self._choices(FeatureAxis.UTILITIES): + groups.append( + SettingGroup( + "Rate limiting", + ( + _str_field( + "RATE_LIMIT_DEFAULT", + "100/minute", + "Requests each client may make, e.g. 100/minute, 10/second.", + ), + _str_field( + "RATE_LIMIT_STORAGE_URI", + "async+memory://", + "Counter storage: async+memory:// (per process) or", + "async+redis://localhost:6379/0 (shared, needs limits[async-redis]).", + ), + ), + ) + ) + + return groups + + def _auth_settings_group(self) -> Optional[SettingGroup]: + """Settings the selected authentication option reads.""" + auth_type = self._auth_type + fields: List[SettingField] = [] + if auth_type == AuthChoice.JWT: + fields.append( + SettingField( + "JWT_ALGORITHM", + 'Literal["HS256", "HS384", "HS512"]', + '"HS256"', + ("Algorithm signing the tokens: HS256, HS384 or HS512.",), + imports=("from typing import Literal",), + ) + ) + if auth_type in (AuthChoice.JWT, AuthChoice.FASTAPI_USERS): + fields.append( + SettingField( + "ACCESS_TOKEN_EXPIRE_MINUTES", + "int", + "30", + ("Lifetime of an access token, in minutes.",), + ) + ) + if auth_type in _SESSION_AUTH_CHOICES: + fields += [ + SettingField( + "SESSION_MAX_AGE", + "int", + "1209600", + ( + "Idle timeout of the session cookie, in seconds (14 days);", + "every response renews it.", + ), + ), + SettingField( + "SESSION_ABSOLUTE_MAX_AGE", + "int", + "2592000", + ( + "Absolute session lifetime, in seconds (30 days): after it", + "the user signs in again, however active the session was.", + ), + ), + SettingField( + "SESSION_HTTPS_ONLY", + "bool", + "False", + ( + "Send the session cookie over HTTPS only (always on unless", + "ENVIRONMENT is development).", + ), + ), + ] + if auth_type == AuthChoice.SESSION: + fields.append( + SettingField( + "ENABLE_DEMO_USERS", + "bool", + "False", + ( + "Accept the demo account demo@example.com / demo-password.", + "Refused unless ENVIRONMENT is development.", + ), + ) + ) + if auth_type == AuthChoice.OAUTH2: + fields += [ + _str_field(name, "", "OAuth2 provider credentials.") + for name in ( + "GOOGLE_CLIENT_ID", + "GOOGLE_CLIENT_SECRET", + "GITHUB_CLIENT_ID", + "GITHUB_CLIENT_SECRET", + ) + ] + fields.append( + _str_field( + "OAUTH_REDIRECT_BASE_URL", + "", + "Public base URL of this API, e.g. https://api.example.com (with", + "any path prefix your proxy adds). The provider redirects back to", + "/api/v1/auth/callback/. Required unless ENVIRONMENT", + "is development, where the request URL is used instead.", + ) + ) + if ( + auth_type in (AuthChoice.JWT, AuthChoice.SESSION, AuthChoice.FASTAPI_USERS) + and self._uses_rate_limiting + ): + fields.append( + _str_field( + "RATE_LIMIT_AUTH", + "5/minute", + "Login and registration attempts each client may make per", + "endpoint, e.g. 5/minute.", + ) + ) + if not fields: + return None + return SettingGroup("Authentication", tuple(fields)) + + def _base_settings_groups(self) -> List[SettingGroup]: + """Fields every generated feature may rely on, added when missing.""" + groups = [ + SettingGroup( + "API", + ( + _str_field( + "PROJECT_NAME", str(self.config.get("project_name", "app")) + ), + _str_field("API_V1_PREFIX", "/api/v1"), + ), + ) + ] + if self._auth_type in _SIGNING_AUTH_CHOICES: + groups.append( + SettingGroup( + "Signing", + ( + SettingField( + "ENVIRONMENT", + 'Literal["development", "staging", "production"]', + '"development"', + imports=("from typing import Literal",), + ), + SettingField( + "SECRET_KEY", + "str", + "secrets.token_urlsafe(32)", + imports=("import secrets",), + ), + ), + ) + ) + return groups + + def _apply_auth_guard(self, content: str) -> str: + """Add the staging/production guard to the settings class when auth signs. + + A settings class whose own validator already enforces the + ``SECRET_KEY`` rule (every current fastkit template, and the + generated settings module) gets no second copy of it: only the + demo-user check of the Session option is added then. + """ + if self._auth_type not in _SIGNING_AUTH_CHOICES: + return content + demo_users = self._auth_type == AuthChoice.SESSION + secret_key = not has_secret_key_guard(content) + if not (demo_users or secret_key): + return content + return inject_settings_validator( + content, + AUTH_GUARD_METHOD, + auth_guard_lines(demo_users=demo_users, secret_key=secret_key), + ) + + def generate_settings_module(self) -> str: + """Render a complete settings module (for templates that ship none).""" + return self._apply_auth_guard( + self._render_module( + "core/config.py.j2", + title="Application settings", + settings_groups=self.settings_groups(), + example_secret_keys=sorted(PUBLIC_EXAMPLE_SECRET_KEYS), + min_secret_key_bytes=MIN_SECRET_KEY_BYTES, + ) + ) + + def apply_settings_module(self) -> List[str]: + """ + Make the project's settings module declare every field features read. + + A template-shipped module gets the missing fields added to its + ``Settings`` class (fields it already declares are kept); without + one, a complete module is generated. + + Returns: + Project-relative paths written (the settings module, plus the + package ``__init__.py`` when it had to be created) + """ + path = self.project_dir / self.settings_relpath + if not path.exists(): + path.parent.mkdir(parents=True, exist_ok=True) + written = self._ensure_package(path.parent) + write_generated_text(path, self.generate_settings_module()) + return written + [self.settings_relpath] + + injected = self._injected_settings(path) + if injected is None: + return [] + write_text_preserving_newlines(path, *injected) + return [self.settings_relpath] + + def _injected_settings(self, path: Path) -> Optional[Tuple[str, str]]: + """``(content, newline)`` of ``path`` with the missing fields added. + + None when the module already declares every field. + """ + content, newline = read_text_preserving_newlines(path) + updated = inject_settings_fields( + content, self._base_settings_groups() + self.settings_groups() + ) + updated = self._apply_auth_guard(updated) + return None if updated == content else (updated, newline) + + def _missing_core_modules(self) -> List[str]: + """Shared ``core/`` modules (``pagination.py``) the project lacks.""" + # Imported lazily: route_generators imports this package. + from fastapi_fastkit.backend.route_generators import SHARED_CORE_MODULES + + if self.provide_pagination: + wanted = list(SHARED_CORE_MODULES) + elif self._auth_type != NONE_CHOICE: + # The auth routers document their errors with error_responses(). + wanted = ["responses.py"] + else: + return [] + core = self.project_dir / self.package_dir / "core" + return [name for name in wanted if not (core / name).exists()] + + def apply_pagination_module(self) -> List[str]: + """ + Write the shared ``core/`` modules (``pagination.py``, ``responses.py``) + and a pagination test when the base template lacks them. + + The content is the canonical one ``fastkit addroute`` also writes, so + list endpoints added later import the same ``Page`` model. + + Returns: + Project-relative paths that were written + """ + missing = self._missing_core_modules() + if not missing: + return [] + from fastapi_fastkit.backend.route_generators import shared_core_source + + core = self.project_dir / self.package_dir / "core" + core.mkdir(parents=True, exist_ok=True) + written = self._ensure_package(core) + for name in missing: + write_generated_text(core / name, shared_core_source(name)) + written.append(f"{self.package_dir}/core/{name}") + + test_path = self.project_dir / "tests" / "test_pagination.py" + if ( + "pagination.py" in missing + and self._choice(FeatureAxis.TESTING) != NONE_CHOICE + and not test_path.exists() + ): + test_path.parent.mkdir(parents=True, exist_ok=True) + write_generated_text( + test_path, + self._render_module( + "test/test_pagination.py.j2", title="Pagination tests" + ), + ) + written.append("tests/test_pagination.py") + return written + + def _ensure_package(self, directory: Path) -> List[str]: + """Create ``__init__.py`` in a package directory that has none.""" + init = directory / "__init__.py" + if init.exists(): + return [] + write_generated_text(init, "") + return [init.relative_to(self.project_dir).as_posix()] + # ----------------------------------------------------------------- # # Public generators # ----------------------------------------------------------------- # @@ -559,9 +1829,7 @@ def build_artifacts(self, include_main: bool = True) -> Dict[str, str]: if db_config is not None: artifacts[self.db_config_relpath] = db_config - auth_config = self.generate_auth_config() - if auth_config is not None: - artifacts[self.auth_config_relpath] = auth_config + artifacts.update(self.generate_auth_files()) test_config = self.generate_test_config() if test_config is not None: @@ -576,6 +1844,8 @@ def build_artifacts(self, include_main: bool = True) -> Dict[str, str]: ) artifacts.update(self.generate_feature_modules()) + artifacts.update(self.generate_feature_tests()) + artifacts.update(self.generate_test_isolation()) artifacts.update(self.generate_migration_files()) artifacts.update(self.generate_tooling_files()) artifacts.update(self.generate_testing_files()) @@ -599,13 +1869,37 @@ def planned_files(self, include_main: bool = True) -> List[str]: planned.add("Dockerfile") if "docker-compose" in deployment: planned.add("docker-compose.yml") + if self._needs_dockerignore(): + planned.add(".dockerignore") if self._uses_ruff: planned.add("pyproject.toml") if self._needs_black_config and (self.project_dir / "pyproject.toml").exists(): planned.add("pyproject.toml") + if self._isort_needs_alembic_hint(): + planned.add("pyproject.toml") + if self._mypy_overrides(): + planned.add("pyproject.toml") if self.env_example_blocks(include_main=include_main): planned.add(ENV_EXAMPLE_RELPATH) + if self._gitignore_additions(): + planned.add(".gitignore") + + settings_path = self.project_dir / self.settings_relpath + if not settings_path.exists(): + planned.add(self.settings_relpath) + planned.add(f"{self.settings_relpath.rsplit('/', 1)[0]}/__init__.py") + elif self._injected_settings(settings_path) is not None: + planned.add(self.settings_relpath) + missing_core = self._missing_core_modules() + for name in missing_core: + planned.add(f"{self.package_dir}/core/{name}") + if missing_core: + planned.add(f"{self.package_dir}/core/__init__.py") + if "pagination.py" in missing_core and ( + self._choice(FeatureAxis.TESTING) != NONE_CHOICE + ): + planned.add("tests/test_pagination.py") return sorted(planned) @@ -633,6 +1927,8 @@ def generate_all_files(self, include_main: bool = True) -> List[str]: target.chmod(0o755) written.append(relpath) + written.extend(self.apply_settings_module()) + written.extend(self.apply_pagination_module()) written.extend(self.generate_docker_files(app_module=self.app_module)) if self._uses_ruff: @@ -641,13 +1937,58 @@ def generate_all_files(self, include_main: bool = True) -> List[str]: black_target = self.apply_black_configuration() if black_target: written.append(black_target) + isort_target = self.apply_isort_configuration() + if isort_target: + written.append(isort_target) + mypy_target = self.apply_mypy_configuration() + if mypy_target: + written.append(mypy_target) env_example = self.apply_env_example(include_main=include_main) if env_example: written.append(env_example) + gitignore = self.apply_gitignore() + if gitignore: + written.append(gitignore) return sorted(set(written)) + def _gitignore_additions(self) -> List[str]: + """Patterns the project's ``.gitignore`` lacks for generated files.""" + if self._database_type != DatabaseChoice.SQLITE: + return [] + path = self.project_dir / ".gitignore" + existing = "" + if path.exists(): + existing, _ = read_text_preserving_newlines(path) + present = {line.strip() for line in existing.splitlines()} + return [pattern for pattern in ("*.db", "*.sqlite3") if pattern not in present] + + def apply_gitignore(self) -> Optional[str]: + """ + Ignore local SQLite database files (``DATABASE_URL`` defaults to + ``./app.db``) in the project's ``.gitignore``. + + Returns: + ``".gitignore"`` when it was created or extended, else None + """ + missing = self._gitignore_additions() + if not missing: + return None + path = self.project_dir / ".gitignore" + if path.exists(): + content, newline = read_text_preserving_newlines(path) + else: + content, newline = "", "\n" + if content and not content.endswith("\n"): + content += "\n" + if content: + content += "\n" + content += "# Local SQLite databases (DATABASE_URL defaults to ./app.db).\n" + content += "".join(f"{pattern}\n" for pattern in missing) + write_text_preserving_newlines(path, content, newline) + return ".gitignore" + def env_example_blocks( self, include_main: bool = True ) -> List[Tuple[str, List[str]]]: @@ -659,10 +2000,13 @@ def env_example_blocks( are placeholders only: ``SECRET_KEY`` is replaced with a unique key when the local ``.env`` is generated from this file. + Every preset reads these through its settings module (which loads + ``.env``), so the blocks do not depend on whether ``main.py`` is + regenerated. + Args: - include_main: Whether the dynamic ``main.py`` overlay is generated - (its CORS setup reads ``BACKEND_CORS_ORIGINS``; template - entrypoints document their own settings) + include_main: Accepted for symmetry with :meth:`build_artifacts`; + the documented variables are the same either way Returns: ``(variable, lines)`` blocks, in the order they are appended @@ -685,7 +2029,8 @@ def env_example_blocks( ( "ENVIRONMENT", [ - '# "production" refuses to start without a real SECRET_KEY.', + '# "staging" and "production" refuse to start without a real', + "# SECRET_KEY.", "ENVIRONMENT=development", ], ) @@ -704,20 +2049,29 @@ def env_example_blocks( ) ) - if include_main and UtilityChoice.CORS in self._choices(FeatureAxis.UTILITIES): + if UtilityChoice.CORS in self._choices(FeatureAxis.UTILITIES): blocks.append( ( "BACKEND_CORS_ORIGINS", [ "# Comma-separated browser origins allowed to call the API.", - '# Unset: no cross-origin access. "*": any origin, no cookies.', - "# main.py reads it from the process environment: export it", - "# or start uvicorn with --env-file .env.", + '# Unset: no cross-origin access. "*": any origin, but then', + "# without credentials (no cookies or Authorization headers).", "# BACKEND_CORS_ORIGINS=http://localhost:3000", ], ) ) + for group in self.settings_groups(): + for setting in group.fields: + blocks.append( + ( + setting.name, + [f"# {line}" for line in setting.doc] + + [f"# {setting.name}={setting.env_value}"], + ) + ) + return blocks def apply_env_example(self, include_main: bool = True) -> Optional[str]: @@ -767,16 +2121,14 @@ def generate_main_py(self) -> str: Content of main.py as string """ sections = self._main_fragments() - import_groups = self._build_import_groups( - sections.import_fragments, sections.needs_os - ) return self._render_module( "main.py.j2", title="FastAPI Application Main Entry Point", description=self.config.get("description", ""), version=self.config.get("version", "0.1.0"), - import_groups=import_groups, - lifespan_fragments=sections.lifespan_fragments, + import_groups=self._build_import_groups(sections.import_fragments), + startup_fragments=sections.startup_fragments, + shutdown_fragments=sections.shutdown_fragments, setup_fragments=sections.setup_fragments, ) @@ -815,104 +2167,237 @@ def _generate_redis_config(self) -> str: """Generate the ``redis.asyncio`` client module.""" return self._render_module("db/redis.py.j2", title="Redis Configuration") - def generate_auth_config(self) -> Optional[str]: + def generate_auth_files(self) -> Dict[str, str]: """ - Generate authentication configuration. + Generate the authentication package for the selected option. + + JWT and Session-based share the account store (``models``, + ``repository``, ``service``) whose implementation follows the + selected database: SQLAlchemy, a MongoDB collection, or an in-memory + store. OAuth2 keeps the provider profile in the session cookie; + FastAPI-Users uses the library's SQLAlchemy backend. Returns: - Content of auth config file or None + Mapping of project-relative path to file content (empty without + an auth selection) """ - auth_type = self._auth_type + kind = self._auth_kind + if not kind: + return {} - if auth_type == AuthChoice.JWT: - return self._generate_jwt_config() - if auth_type == AuthChoice.FASTAPI_USERS: - return self._generate_fastapi_users_config() - if auth_type == AuthChoice.OAUTH2: - return self._render_module( - "auth/oauth2.py.j2", title="OAuth2 Authentication Configuration" + modules: Dict[str, str] + if kind in ("jwt", "session"): + modules = { + "models.py": "auth/models.py.j2", + "schemas.py": "auth/schemas.py.j2", + "security.py": "auth/security.py.j2", + "repository.py": "auth/repository.py.j2", + "service.py": "auth/service.py.j2", + "dependencies.py": "auth/dependencies.py.j2", + "router.py": "auth/router.py.j2", + } + elif kind == "oauth2": + modules = {"router.py": "auth/oauth2_router.py.j2"} + else: + modules = { + name: f"auth/fastapi_users/{name}.j2" + for name in ("models.py", "schemas.py", "users.py", "router.py") + } + if kind in ("session", "oauth2"): + modules["middleware.py"] = "auth/middleware.py.j2" + + titles = { + "jwt": "JWT authentication", + "session": "Session authentication", + "oauth2": "OAuth2 authentication", + "fastapi_users": "FastAPI-Users authentication", + } + package = self.auth_package_relpath + files = { + f"{package}/__init__.py": self._render_module( + "auth/package_init.py.j2", title=titles[kind] ) - if auth_type == AuthChoice.SESSION: - return self._render_module( - "auth/session.py.j2", title="Session Authentication Configuration" + } + for name, fragment in modules.items(): + files[f"{package}/{name}"] = self._render_module( + fragment, title=f"{titles[kind]}: {name.removesuffix('.py')}" ) - - return None - - def _generate_jwt_config(self) -> str: - """Generate JWT authentication configuration.""" - return self._render_module( - "auth/jwt.py.j2", title="JWT Authentication Configuration" - ) - - def _generate_fastapi_users_config(self) -> str: - """Generate FastAPI-Users configuration.""" - return self._render_module( - "auth/fastapi_users.py.j2", - title="FastAPI-Users Authentication Configuration", - ) + return files def generate_feature_modules(self) -> Dict[str, str]: """ Generate the standalone modules the selected features import. - These are the background worker, the task / cache / websocket / - pagination routers ``main.py`` mounts, and the structured logging - setup — everything that lives outside ``main.py`` but is referenced - from it. + These are the background worker, the task / cache / WebSocket / + readiness routers, and the logging, tracing and rate-limiting setup: + everything that lives outside ``main.py`` but is referenced from it + (or from a preserved template ``main.py`` through its anchors). Returns: Mapping of project-relative path to file content """ modules: Dict[str, str] = {} feature_dir = f"{self.package_dir}/features" + features: Dict[str, str] = {} tasks_type = self._choice(FeatureAxis.ASYNC_TASKS) if tasks_type == AsyncTaskChoice.CELERY: modules[f"{self.package_dir}/worker.py"] = self._render_module( "tasks/celery_worker.py.j2", title="Celery Worker" ) - modules[f"{feature_dir}/tasks.py"] = self._render_module( + features["tasks.py"] = self._render_module( "features/tasks_celery.py.j2", title="Background Task Routes" ) elif tasks_type == AsyncTaskChoice.DRAMATIQ: modules[f"{self.package_dir}/worker.py"] = self._render_module( "tasks/dramatiq_worker.py.j2", title="Dramatiq Worker" ) - modules[f"{feature_dir}/tasks.py"] = self._render_module( + features["tasks.py"] = self._render_module( "features/tasks_dramatiq.py.j2", title="Background Task Routes" ) - if self._choice(FeatureAxis.CACHING) == CachingChoice.REDIS: - modules[f"{feature_dir}/cache.py"] = self._render_module( + if self._uses_redis_cache: + features["cache.py"] = self._render_module( "features/cache.py.j2", title="Cached Endpoints" ) utilities = self._choices(FeatureAxis.UTILITIES) if UtilityChoice.WEBSOCKET in utilities: - modules[f"{feature_dir}/websocket.py"] = self._render_module( + features["websocket.py"] = self._render_module( "features/websocket.py.j2", title="WebSocket Routes" ) - if ( - UtilityChoice.PAGINATION in utilities - and UtilityChoice.PAGINATION not in self.omit_example_routers - ): - modules[f"{feature_dir}/pagination.py"] = self._render_module( - "features/pagination.py.j2", title="Paginated Routes" - ) - if modules: + if self.generates_readiness: + features["readiness.py"] = self._generate_readiness_module() + + for name, content in features.items(): + modules[f"{feature_dir}/{name}"] = content + if features: modules[f"{feature_dir}/__init__.py"] = self._join_lines( self._build_header("Generated feature routers") ) - if self._choice(FeatureAxis.LOGGING) == LoggingChoice.STRUCTURED: + if UtilityChoice.RATE_LIMITING in utilities: + modules[f"{self.package_dir}/rate_limiting.py"] = self._render_module( + "middleware/rate_limiting.py.j2", title="Rate Limiting" + ) + + if self._uses_structured_logging: modules[f"{self.package_dir}/logging_config.py"] = self._render_module( "logging/structured.py.j2", title="Structured Logging Configuration" ) + if self._uses_loguru: + modules[f"{self.package_dir}/loguru_config.py"] = self._render_module( + "logging/loguru.py.j2", + title="Loguru Logging Configuration", + serialize=self._uses_structured_logging, + ) + if self._choice(FeatureAxis.MONITORING) == MonitoringChoice.OPENTELEMETRY: + modules[f"{self.package_dir}/telemetry.py"] = self._render_module( + "monitoring/telemetry.py.j2", title="OpenTelemetry Tracing" + ) return modules + def _generate_readiness_module(self) -> str: + """Render ``features/readiness.py`` with one check per dependency.""" + checks = self._readiness_checks() + third_party = ["from fastapi import APIRouter, Request, Response, status"] + first_party: List[str] = [] + summary: List[str] = [] + if "check_database" in checks: + third_party.append("from sqlalchemy import text") + first_party.append(f"from {self.db_module} import engine") + summary.append("``SELECT 1`` on the database") + if "check_mongodb" in checks: + summary.append("a MongoDB ``ping``") + if "check_redis" in checks: + first_party.append(f"from {self.db_module} import redis_client") + summary.append("a Redis ``PING``") + if "check_cache" in checks: + third_party.append("from redis import asyncio as aioredis") + first_party.append(f"from {self.settings_module} import settings") + summary.append("a ``PING`` to the Redis cache") + return self._render_module( + "features/readiness.py.j2", + title="Readiness Probe", + check_names=checks, + check_sql="check_database" in checks, + check_mongo="check_mongodb" in checks, + check_redis_db="check_redis" in checks, + check_cache="check_cache" in checks, + check_summary=", ".join(summary), + third_party_imports=sorted(third_party), + first_party_imports=sorted(first_party), + ) + + def generate_feature_tests(self) -> Dict[str, str]: + """ + Generate the tests that pin the selected features' behaviour. + + They use the ``client`` fixture every base template's ``conftest.py`` + provides. Nothing is generated when testing is not selected. + + Returns: + Mapping of project-relative path to file content + """ + if self._choice(FeatureAxis.TESTING) == NONE_CHOICE: + return {} + + tests: Dict[str, str] = {} + utilities = self._choices(FeatureAxis.UTILITIES) + if self.generates_readiness: + tests["tests/test_readiness.py"] = self._render_module( + "test/test_readiness.py.j2", title="Readiness probe tests" + ) + if UtilityChoice.RATE_LIMITING in utilities: + tests["tests/test_rate_limiting.py"] = self._render_module( + "test/test_rate_limiting.py.j2", title="Rate limiting tests" + ) + if UtilityChoice.WEBSOCKET in utilities: + tests["tests/test_websocket.py"] = self._render_module( + "test/test_websocket.py.j2", title="WebSocket tests" + ) + if self._choice(FeatureAxis.ASYNC_TASKS) == AsyncTaskChoice.DRAMATIQ: + tests["tests/test_tasks.py"] = self._render_module( + "test/test_tasks_dramatiq.py.j2", title="Background task tests" + ) + if self._auth_kind: + tests["tests/test_auth.py"] = self._render_module( + f"test/test_auth_{self._auth_kind}.py.j2", title="Authentication tests" + ) + return tests + + def generate_test_isolation(self) -> Dict[str, str]: + """ + Generate the root ``conftest.py`` that isolates test runs. + + pytest loads it before ``tests/conftest.py``, so its environment + overrides are in place before the settings are read: the template's + own tests and the generated ones run on an in-memory SQLite database + (the auth router creates its table on startup), export no spans and + count rate limits in memory, reset before every test. + + Returns: + ``{"conftest.py": content}``, or nothing without testing or when + no generated feature reaches outside the process during tests + """ + if self._choice(FeatureAxis.TESTING) == NONE_CHOICE: + return {} + sql = self._uses_sql_database + otel = self._choice(FeatureAxis.MONITORING) == MonitoringChoice.OPENTELEMETRY + rate_limit = self._uses_rate_limiting + if not (sql or otel or rate_limit): + return {} + return { + "conftest.py": self._render_module( + "test/conftest_root.py.j2", + title="Test isolation", + sql=sql, + otel=otel, + ) + } + def generate_migration_files(self) -> Dict[str, str]: """ Generate the Alembic migration environment. @@ -941,17 +2426,27 @@ def generate_migration_files(self) -> Dict[str, str]: database_url=SQLALCHEMY_URLS[self._database_type], ), "alembic/env.py": self._render_module( - "migrations/env.py.j2", title="Alembic environment" + "migrations/env.py.j2", + title="Alembic environment", + model_modules=self._model_modules(), ), "alembic/script.py.mako": self._render_module( "migrations/script.py.mako.j2" ), f"alembic/versions/{revision_id}_initial.py": self._render_module( - "migrations/initial_revision.py.j2", revision_id=revision_id + "migrations/initial_revision.py.j2", + revision_id=revision_id, + users_table=self._auth_kind if self._has_users_table else "", ), "scripts/migrate.sh": self._render_module("migrations/migrate_sh.j2"), } + def _model_modules(self) -> List[str]: + """Generated modules defining ORM models (imported by Alembic).""" + if self._has_users_table: + return [f"{self.auth_module}.models"] + return [] + def generate_tooling_files(self) -> Dict[str, str]: """ Generate the developer-tooling files for the ``tooling`` selection. @@ -1027,6 +2522,107 @@ def apply_ruff_configuration(self) -> str: write_generated_text(ruff_toml, standalone.lstrip("\n")) return "ruff.toml" + def _isort_needs_alembic_hint(self) -> bool: + """Whether the template's ``[tool.isort]`` must be told about alembic.""" + pyproject = self.project_dir / "pyproject.toml" + if not (self.generate_migration_files() and pyproject.exists()): + return False + content, _ = read_text_preserving_newlines(pyproject) + try: + table = parse_toml(content).get("tool", {}).get("isort") + except PyprojectMergeError: + return False + return isinstance(table, dict) and "known_third_party" not in table + + def apply_isort_configuration(self) -> Optional[str]: + """ + Mark ``alembic`` as third party in the template's ``[tool.isort]``. + + The generated ``alembic/`` directory sits at the project root, so + isort (which looks for first-party modules there) would sort + ``from alembic import op`` with the project's own imports, while + ruff, configured with ``known-first-party``, keeps it third party. + Declaring it third party makes both agree. Templates without a + ``[tool.isort]`` table, or that already list third-party modules, + are left alone. + + Returns: + ``"pyproject.toml"`` when it was updated, else None + """ + if not self._isort_needs_alembic_hint(): + return None + pyproject = self.project_dir / "pyproject.toml" + content, newline = read_text_preserving_newlines(pyproject) + updated = re.sub( + r"^\[tool\.isort\][ \t]*$", + '[tool.isort]\nknown_third_party = ["alembic"]', + content, + count=1, + flags=re.M, + ) + if updated == content: + return None + write_text_preserving_newlines(pyproject, updated, newline) + return "pyproject.toml" + + def _mypy_overrides(self) -> Optional[str]: + """``[[tool.mypy.overrides]]`` the template's mypy needs, if any. + + Celery and Authlib ship no type information, and the Celery task + decorator and Dramatiq's broker classes are untyped, so a template + that runs ``mypy --strict`` on the package would reject the + generated worker and OAuth2 modules. None when the project has no + ``[tool.mypy]`` table, already has the overrides, or none is needed. + """ + untyped: List[str] = [] + tasks = self._choice(FeatureAxis.ASYNC_TASKS) + if tasks == AsyncTaskChoice.CELERY: + untyped += ["celery", "celery.*"] + if self._auth_type == AuthChoice.OAUTH2: + untyped.append("authlib.*") + worker = f"{self.pkg}.worker" if tasks != NONE_CHOICE else "" + if not (untyped or worker): + return None + pyproject = self.project_dir / "pyproject.toml" + if not pyproject.exists(): + return None + content, _ = read_text_preserving_newlines(pyproject) + if not _declares_tool_table(content, "mypy"): + return None + try: + overrides = parse_toml(content)["tool"]["mypy"].get("overrides", []) + except (PyprojectMergeError, KeyError, AttributeError): + return None + configured: set[str] = set() + for table in overrides: + modules = table.get("module", []) if isinstance(table, dict) else [] + configured.update([modules] if isinstance(modules, str) else modules) + if worker in configured or set(untyped) & configured: + return None + return self._render_module( + "tooling/mypy_overrides_toml.j2", + untyped_packages=untyped, + worker_module=worker, + ) + + def apply_mypy_configuration(self) -> Optional[str]: + """ + Append the mypy overrides of :meth:`_mypy_overrides` to the + template's ``pyproject.toml``. + + Returns: + ``"pyproject.toml"`` when it was updated, else None + """ + snippet = self._mypy_overrides() + if snippet is None: + return None + pyproject = self.project_dir / "pyproject.toml" + content, newline = read_text_preserving_newlines(pyproject) + if not content.endswith("\n"): + content += "\n" + write_text_preserving_newlines(pyproject, content + snippet, newline) + return "pyproject.toml" + def apply_black_configuration(self) -> Optional[str]: """ Merge a ``[tool.black]`` table into the project's ``pyproject.toml``. @@ -1100,14 +2696,69 @@ def generate_docker_files(self, app_module: str = "src.main:app") -> List[str]: write_generated_text(compose_path, self._generate_docker_compose()) written.append("docker-compose.yml") + if self._needs_dockerignore(): + write_generated_text( + self.project_dir / ".dockerignore", + self._render("docker/dockerignore.j2"), + ) + written.append(".dockerignore") + return written + def _needs_dockerignore(self) -> bool: + """Whether a ``.dockerignore`` is written (an existing one is kept). + + The generated Dockerfile copies only the package and migrations, but + the build context is still sent to Docker: the ``.dockerignore`` + keeps ``.env``, the virtualenv and caches out of it.""" + deployment = self.config.get("deployment") or [] + return ( + bool({"Docker", "docker-compose"} & set(deployment)) + and not (self.project_dir / ".dockerignore").exists() + ) + + def _dockerfile_copy_paths(self) -> List[str]: + """``COPY`` arguments: the application package and the migrations.""" + root = self.package_dir.split("/", 1)[0] + paths = [f"{root}/ {root}/"] + if self._uses_alembic: + paths += ["alembic.ini ./", "alembic/ alembic/"] + return paths + + def _dockerfile_writable_dirs(self) -> List[Dict[str, str]]: + """Directories the app user must be able to write to.""" + root = self.package_dir.split("/", 1)[0] + dirs: List[Dict[str, str]] = [] + if (self.project_dir / root / "mocks").is_dir(): + dirs.append( + { + "dir": f"/app/{root}/mocks", + "comment": f"The item store writes {root}/mocks: the app " + "user may write there.", + } + ) + if self._database_type == DatabaseChoice.SQLITE: + dirs.append( + { + "dir": "/app/data", + "comment": "The SQLite database lives in /app/data (mount a " + "volume there to keep it).", + } + ) + return dirs + def _generate_dockerfile(self, app_module: str = "src.main:app") -> str: """Generate Dockerfile content with a layout-aware uvicorn target.""" + env_lines: List[str] = [] + if self._database_type == DatabaseChoice.SQLITE: + env_lines.append("DATABASE_URL=sqlite+aiosqlite:////app/data/app.db") return self._render( "docker/dockerfile.j2", title="Dockerfile", cmd=["uvicorn", app_module, "--host", "0.0.0.0", "--port", "8000"], + copy_paths=self._dockerfile_copy_paths(), + writable_dirs=self._dockerfile_writable_dirs(), + env_lines=env_lines, ) def _generate_docker_compose(self) -> str: @@ -1132,6 +2783,17 @@ def _generate_docker_compose(self) -> str: depends_on.append("redis") volumes.append("redis_data") + environment: List[str] = [] + if db_service in _COMPOSE_DB_ENVIRONMENT: + environment.append(_COMPOSE_DB_ENVIRONMENT[db_service]) + if self._database_type == DatabaseChoice.REDIS or self._uses_redis_cache: + environment.append("REDIS_URL=redis://redis:6379/0") + tasks = self._choice(FeatureAxis.ASYNC_TASKS) + if tasks == AsyncTaskChoice.CELERY: + environment.append("CELERY_BROKER_URL=redis://redis:6379/0") + elif tasks == AsyncTaskChoice.DRAMATIQ: + environment.append("DRAMATIQ_BROKER_URL=redis://redis:6379/0") + return self._render( "docker/docker_compose.j2", title="docker-compose.yml", @@ -1140,6 +2802,7 @@ def _generate_docker_compose(self) -> str: worker_command=self._worker_command(), depends_on=depends_on, volumes=volumes, + environment=environment, ) def generate_test_config(self) -> Optional[str]: @@ -1167,11 +2830,20 @@ def generate_test_config(self) -> Optional[str]: __all__ = [ "COMPOSE_DB_SERVICES", - "DEFAULT_AUTH_CONFIG_RELPATH", + "AUTH_GUARD_METHOD", + "DEFAULT_AUTH_PACKAGE_RELPATH", "DEFAULT_DB_CONFIG_RELPATH", "DEFAULT_MAIN_RELPATH", "DynamicConfigGenerator", + "PUBLIC_EXAMPLE_SECRET_KEYS", "SQLALCHEMY_URLS", "SQL_DATABASES", + "MIN_SECRET_KEY_BYTES", + "SettingsInjectionError", + "ensure_import", + "has_secret_key_guard", + "format_imports", "get_environment", + "inject_settings_fields", + "inject_settings_validator", ] diff --git a/src/fastapi_fastkit/backend/project_builder/config_schema.py b/src/fastapi_fastkit/backend/project_builder/config_schema.py index 85752b4..f6e60b8 100644 --- a/src/fastapi_fastkit/backend/project_builder/config_schema.py +++ b/src/fastapi_fastkit/backend/project_builder/config_schema.py @@ -37,6 +37,8 @@ from fastapi_fastkit.core.settings import ( MULTI_SELECT_AXES, NONE_CHOICE, + AuthChoice, + DatabaseChoice, FastkitConfig, FeatureAxis, ) @@ -68,6 +70,40 @@ _PRESET_ALIAS = "preset" +#: Databases FastAPI-Users' SQLAlchemy backend (the generated one) supports. +FASTAPI_USERS_DATABASES: Tuple[str, ...] = ( + DatabaseChoice.POSTGRESQL, + DatabaseChoice.MYSQL, + DatabaseChoice.SQLITE, +) + + +def combination_errors(config: Dict[str, Any]) -> List[str]: + """ + Report feature selections that cannot be generated together. + + Expects the canonical shape (see :func:`normalize_project_config`), but + also accepts the interactive builder's. + + :param config: Configuration mapping + :return: Human-readable error messages, empty when every pair works + """ + errors: List[str] = [] + database = config.get(str(FeatureAxis.DATABASE)) or {} + db_type = database.get("type") if isinstance(database, dict) else database + db_type = str(db_type or NONE_CHOICE) + auth = config.get(str(FeatureAxis.AUTHENTICATION)) + if auth == AuthChoice.FASTAPI_USERS and db_type not in FASTAPI_USERS_DATABASES: + selected = "no database" if db_type == NONE_CHOICE else f"database '{db_type}'" + errors.append( + "Authentication 'FastAPI-Users' needs a SQL database " + f"({', '.join(FASTAPI_USERS_DATABASES)}), but {selected} is selected. " + "Choose one of those databases, or the 'JWT' option, which works " + "with every database." + ) + return errors + + class ConfigSchemaError(Exception): """Raised when a configuration cannot be normalised into canonical form.""" @@ -154,6 +190,7 @@ def _normalize( errors.extend(_normalize_deployment(config, normalized)) errors.extend(_normalize_string_list(config, normalized, "custom_packages")) errors.extend(_normalize_string_list(config, normalized, "all_dependencies")) + errors.extend(combination_errors(normalized)) return normalized, errors diff --git a/src/fastapi_fastkit/backend/project_builder/dependency_collector.py b/src/fastapi_fastkit/backend/project_builder/dependency_collector.py index 9415d03..de1ec9b 100644 --- a/src/fastapi_fastkit/backend/project_builder/dependency_collector.py +++ b/src/fastapi_fastkit/backend/project_builder/dependency_collector.py @@ -22,6 +22,7 @@ from fastapi_fastkit.core.settings import ( MULTI_SELECT_AXES, NONE_CHOICE, + DatabaseChoice, FeatureAxis, ) @@ -139,6 +140,8 @@ def collect_from_config(self, config: Dict[str, Any]) -> List[str]: self.add_axis_dependencies(axis, choice) # Add custom packages + self.add_combination_dependencies(config) + custom = config.get("custom_packages", []) if custom: self.dependencies.update(custom) @@ -186,6 +189,26 @@ def add_axis_dependencies(self, axis: str, choice: str) -> None: catalog = self.settings.PACKAGE_CATALOG.get(axis, {}) self.dependencies.update(catalog.get(choice, [])) + def add_combination_dependencies(self, config: Dict[str, Any]) -> None: + """ + Add packages one selection needs only together with another. + + Generated tests run against an in-memory SQLite database + (``sqlite+aiosqlite://``, set by the root ``conftest.py``), so a + project on PostgreSQL or MySQL with testing selected also gets + ``aiosqlite``. + + Args: + config: Project configuration dictionary + """ + databases = self._selected_choices(config, FeatureAxis.DATABASE) + testing = self._selected_choices(config, FeatureAxis.TESTING) + if testing and set(databases) & { + DatabaseChoice.POSTGRESQL, + DatabaseChoice.MYSQL, + }: + self.dependencies.add("aiosqlite") + def add_base_dependencies(self) -> None: """Add core FastAPI dependencies.""" self.dependencies.update( diff --git a/src/fastapi_fastkit/backend/project_builder/preset_layout.py b/src/fastapi_fastkit/backend/project_builder/preset_layout.py index 5e2a863..5f28d99 100644 --- a/src/fastapi_fastkit/backend/project_builder/preset_layout.py +++ b/src/fastapi_fastkit/backend/project_builder/preset_layout.py @@ -6,10 +6,11 @@ # # - which template ships as the base scaffold, # - whether the dynamic ``main.py`` overlay should overwrite the shipped one, -# - where database / auth config files should land so they sit next to the -# template's existing structure rather than in a parallel ``src/config``, -# - and which feature combinations need a "you must wire this up manually" -# warning because the dynamic ``main.py`` overlay isn't applied. +# - where database / auth config files and the settings module live, so +# they sit next to the template's existing structure, +# - which generated features are spliced into a preserved ``main.py`` +# through its ``# fastkit:`` anchors (a "wire this up manually" note is +# left only for a ``main.py`` that cannot be found). # # Keeping every preset's layout knowledge in one place lets the CLI flow stay # linear ("ask the strategist where to write the file") instead of growing a @@ -19,6 +20,7 @@ # -------------------------------------------------------------------------- from __future__ import annotations +import ast import os from dataclasses import dataclass, field from pathlib import Path @@ -29,8 +31,10 @@ AsyncTaskChoice, AuthChoice, CachingChoice, + DatabaseChoice, FeatureAxis, LoggingChoice, + MigrationsChoice, MonitoringChoice, UtilityChoice, ) @@ -55,116 +59,154 @@ def _axis_is(config: Dict[str, Any], axis: str, choice: str) -> bool: return config.get(axis) == choice -@dataclass(frozen=True) -class ShippedCollection: - """A list endpoint the base template already serves for one resource. - - Feature overlays that would generate a demo router for the same - resource (see ``OverlayTarget.example_collection``) skip that router - instead of shadowing the template's own endpoint. - """ - - #: Resource name, matched against ``OverlayTarget.example_collection``. - name: str - #: ``" "`` of the list endpoint as the app serves it. - endpoint: str - #: Project-relative module that defines the list endpoint. - module_relpath: str - #: Response schema of one element of the list. - schema: str - - @dataclass(frozen=True) class OverlayTarget: """One feature whose wiring normally lives in the dynamic main.py overlay. - ``label`` is what the user sees in the warning, ``applies`` decides - whether their configuration actually triggered it, and ``wiring`` (when - present) is the import / statement pair that can be spliced into a - template-shipped ``main.py`` through its ``# fastkit:`` anchors instead - of only being warned about. - - A target whose generated router is a demo collection names that - resource in ``example_collection``. When the preset's base template - already ships that collection (``PresetProfile.shipped_collections``), - the demo router is not generated and ``collection_wiring`` replaces - ``wiring``; its statements are appended to the end of ``main.py``, after - the template's own routers are included, preceded by ``collection_hint`` - as a comment. + ``label`` is what the user sees in the generation summary, ``applies`` + decides whether their configuration actually triggered it, and + ``wiring`` (when present) is the import / statement pair spliced into a + template-shipped ``main.py`` through its ``# fastkit:`` anchors. Every + statement is a single module-level line (a router include or a + ``setup_*(app)`` call into a generated module), which the routes anchor + can take without rewriting template code (lifespans included: they are + carried by routers, which FastAPI merges into the app's lifespan). + + ``middleware`` targets add middleware: their statements go right above + the template's CORS block, so CORS (added last) stays the outermost + middleware and its headers reach every response, errors included. """ label: str applies: Callable[[Dict[str, Any]], bool] - #: ``(import lines, statement lines)`` rendered with ``{pkg}``. + #: ``(import lines, statement lines)`` rendered with ``{pkg}``, + #: ``{settings_module}``, ``{auth_module}`` and ``{db_module}``. wiring: Tuple[Tuple[str, ...], Tuple[str, ...]] = ((), ()) - #: Resource the generated demo router serves as a collection, if any. - example_collection: str = "" - #: Module (relative to the application package) holding the demo router. - example_module: str = "" - #: Wiring used instead of ``wiring`` when the demo router is skipped. - collection_wiring: Tuple[Tuple[str, ...], Tuple[str, ...]] = ((), ()) - #: Comment lines for ``collection_wiring`` (without ``# ``), each rendered - #: with the fields of the matching :class:`ShippedCollection`. - collection_hint: Tuple[str, ...] = () - #: One-line how-to shown with the manual-wiring warning, rendered with - #: ``{auth_module}`` (dotted path of the generated auth module). - manual_hint: str = "" + #: Path the feature serves. When the preserved template already serves + #: it (``PresetProfile.shipped_paths``), nothing is generated or wired. + provides_path: str = "" + #: Whether the statements add middleware (placed before CORS). + middleware: bool = False @property def is_wirable(self) -> bool: return bool(self.wiring[0] or self.wiring[1]) +_SETTINGS_IMPORT = "from {settings_module} import settings" + + +def _uses_database_or_cache(config: Dict[str, Any]) -> bool: + database = config.get(FeatureAxis.DATABASE) or {} + db_type = database.get("type") if isinstance(database, dict) else database + return (db_type or NONE_CHOICE) != NONE_CHOICE or _axis_is( + config, FeatureAxis.CACHING, CachingChoice.REDIS + ) + + +def _database_type(config: Dict[str, Any]) -> str: + database = config.get(FeatureAxis.DATABASE) or {} + db_type = database.get("type") if isinstance(database, dict) else database + return str(db_type or NONE_CHOICE) + + +def _uses_database(config: Dict[str, Any]) -> bool: + return _database_type(config) != NONE_CHOICE + + +#: Databases the SQLAlchemy fragment (and FastAPI-Users) work with. +_SQL_DATABASES = ( + DatabaseChoice.POSTGRESQL, + DatabaseChoice.MYSQL, + DatabaseChoice.SQLITE, +) + + +def generated_auth(config: Dict[str, Any]) -> str: + """The authentication option that is actually generated. + + FastAPI-Users needs a SQL database; config validation rejects other + combinations, and nothing is generated for them. + """ + auth = str(config.get(FeatureAxis.AUTHENTICATION) or NONE_CHOICE) + if ( + auth == AuthChoice.FASTAPI_USERS + and _database_type(config) not in _SQL_DATABASES + ): + return NONE_CHOICE + return auth + + +def _uses_session_auth(config: Dict[str, Any]) -> bool: + return generated_auth(config) in (AuthChoice.SESSION, AuthChoice.OAUTH2) + + #: Every feature the dynamic ``main.py`` overlay is responsible for. Presets #: that preserve their template's ``main.py`` name the subset they care about #: in ``PresetProfile.extra_warning_targets``. OVERLAY_TARGETS: Tuple[OverlayTarget, ...] = ( + # Template entrypoints add CORSMiddleware from settings.all_cors_origins. OverlayTarget( label="CORS", applies=lambda c: _utility_selected(c, UtilityChoice.CORS), ), + OverlayTarget( + label="Structured logging", + applies=lambda c: _axis_is(c, FeatureAxis.LOGGING, LoggingChoice.STRUCTURED), + wiring=( + ("from {pkg}.logging_config import setup_logging",), + ("setup_logging(app)",), + ), + middleware=True, + ), + OverlayTarget( + label="Loguru", + applies=lambda c: _axis_is(c, FeatureAxis.MONITORING, MonitoringChoice.LOGURU), + wiring=(("from {pkg}.loguru_config import setup_loguru",), ("setup_loguru()",)), + ), OverlayTarget( label="Rate-Limiting", applies=lambda c: _utility_selected(c, UtilityChoice.RATE_LIMITING), + wiring=( + ("from {pkg}.rate_limiting import setup_rate_limiting",), + ("setup_rate_limiting(app)",), + ), + middleware=True, ), + # Module level, right after ``app = FastAPI``: instrumenting adds + # middleware, which Starlette refuses once the app has started. OverlayTarget( - label="WebSocket", - applies=lambda c: _utility_selected(c, UtilityChoice.WEBSOCKET), + label="Prometheus", + applies=lambda c: _axis_is( + c, FeatureAxis.MONITORING, MonitoringChoice.PROMETHEUS + ), wiring=( - ("from {pkg}.features.websocket import router as websocket_router",), - ("app.include_router(websocket_router)",), + ("from prometheus_fastapi_instrumentator import Instrumentator",), + ('Instrumentator().instrument(app).expose(app, tags=["monitoring"])',), ), + middleware=True, ), OverlayTarget( - label="Pagination", - applies=lambda c: _utility_selected(c, UtilityChoice.PAGINATION), - wiring=( - ( - "from fastapi_pagination import add_pagination", - "from {pkg}.features.pagination import router as pagination_router", - ), - ("app.include_router(pagination_router)", "add_pagination(app)"), + label="OpenTelemetry", + applies=lambda c: _axis_is( + c, FeatureAxis.MONITORING, MonitoringChoice.OPENTELEMETRY ), - # The demo router serves ``GET /api/v1/items``; a template that already - # has an items API keeps its own endpoint and only gets - # ``add_pagination(app)`` plus a how-to comment. - example_collection="items", - example_module="features/pagination.py", - collection_wiring=( - ("from fastapi_pagination import add_pagination",), - ("add_pagination(app)",), + wiring=( + ("from {pkg}.telemetry import setup_telemetry",), + ("setup_telemetry(app)",), ), - collection_hint=( - "fastapi-pagination: this template already serves {endpoint},", - "so no example pagination router was generated. To paginate that", - "endpoint, edit {module_relpath}:", - " from fastapi_pagination import Page, paginate", - " @router.get(..., response_model=Page[{schema}])", - " ...", - " return paginate(items)", - "?page= and ?size= then become query parameters, and the response", - 'body changes from a list to {{"items": [...], "total": ..., "page": ...,', - '"size": ..., "pages": ...}}, so update the template\'s list test too.', + middleware=True, + ), + # The database module's route-less ``lifespan_router`` opens (MongoDB) + # and closes the client or pool with the app. Included first, so its + # startup runs before routers that use the database on startup (the + # auth router creating its table) and its shutdown runs after theirs. + OverlayTarget( + label="Database lifespan", + applies=_uses_database, + wiring=( + ("from {db_module} import lifespan_router as database_lifespan",), + ("app.include_router(database_lifespan)",), ), ), OverlayTarget( @@ -172,60 +214,66 @@ def is_wirable(self) -> bool: applies=lambda c: c.get(FeatureAxis.ASYNC_TASKS, NONE_CHOICE) in (AsyncTaskChoice.CELERY, AsyncTaskChoice.DRAMATIQ), wiring=( - ("from {pkg}.features.tasks import router as tasks_router",), - ("app.include_router(tasks_router)",), + ( + "from {pkg}.features.tasks import router as tasks_router", + _SETTINGS_IMPORT, + ), + ("app.include_router(tasks_router, prefix=settings.API_V1_PREFIX)",), ), ), - # Caching is deliberately warn-only: mounting ``cache_router`` without the - # ``FastAPICache.init`` lifespan hook would ship endpoints that raise at - # request time, which is worse than an unmounted module plus a warning. + # The cache router carries its own lifespan (FastAPICache.init), so + # including it is enough: no lifespan edit in the template is needed. OverlayTarget( label="Caching (Redis)", applies=lambda c: _axis_is(c, FeatureAxis.CACHING, CachingChoice.REDIS), - ), - # Warn-only: the package is installed but nothing is generated, and the - # instrumentation must run at import time, right after ``app = FastAPI``. - OverlayTarget( - label="Prometheus", - applies=lambda c: _axis_is( - c, FeatureAxis.MONITORING, MonitoringChoice.PROMETHEUS - ), - manual_hint=( - "Prometheus: add `Instrumentator().instrument(app).expose(app)` " - "(from prometheus_fastapi_instrumentator) right after " - "`app = FastAPI(...)`, not inside a lifespan handler." + wiring=( + ( + "from {pkg}.features.cache import router as cache_router", + _SETTINGS_IMPORT, + ), + ("app.include_router(cache_router, prefix=settings.API_V1_PREFIX)",), ), ), OverlayTarget( - label="OpenTelemetry", - applies=lambda c: _axis_is( - c, FeatureAxis.MONITORING, MonitoringChoice.OPENTELEMETRY + label="WebSocket", + applies=lambda c: _utility_selected(c, UtilityChoice.WEBSOCKET), + wiring=( + ("from {pkg}.features import websocket", _SETTINGS_IMPORT), + ( + "app.include_router(websocket.router)", + "app.include_router(websocket.api_router, " + "prefix=settings.API_V1_PREFIX)", + ), ), ), OverlayTarget( - label="OAuth2 session middleware", - applies=lambda c: _axis_is(c, FeatureAxis.AUTHENTICATION, AuthChoice.OAUTH2), - manual_hint=( - "OAuth2: import `auth_settings` and `router` from {auth_module}, then " - "add `app.add_middleware(SessionMiddleware, " - "secret_key=auth_settings.SECRET_KEY)` and " - "`app.include_router(router)`." + label="Readiness probe", + applies=_uses_database_or_cache, + wiring=( + ("from {pkg}.features.readiness import router as readiness_router",), + ("app.include_router(readiness_router)",), ), + provides_path="/ready", ), OverlayTarget( - label="Session-based auth middleware", - applies=lambda c: _axis_is(c, FeatureAxis.AUTHENTICATION, AuthChoice.SESSION), - manual_hint=( - "Session auth: import `auth_settings` and `router` from {auth_module}, " - "then add `app.add_middleware(SessionMiddleware, " - "secret_key=auth_settings.SECRET_KEY, " - "max_age=auth_settings.SESSION_MAX_AGE)` and " - "`app.include_router(router)`." + label="Session middleware", + applies=_uses_session_auth, + wiring=( + ("from {auth_module}.middleware import add_session_middleware",), + ("add_session_middleware(app)",), ), + middleware=True, ), OverlayTarget( - label="Structured logging", - applies=lambda c: _axis_is(c, FeatureAxis.LOGGING, LoggingChoice.STRUCTURED), + label="Authentication routes", + applies=lambda c: generated_auth(c) != NONE_CHOICE, + wiring=( + ( + "from {auth_module}.router import router as auth_router", + _SETTINGS_IMPORT, + ), + ("app.include_router(auth_router, prefix=settings.API_V1_PREFIX)",), + ), ), ) @@ -239,6 +287,13 @@ def is_wirable(self) -> bool: target.label for target in OVERLAY_TARGETS if target.label != "CORS" ) +#: Shown once whenever the (former) Pagination utility is selected. +PAGINATION_NOTE = ( + "Pagination: list endpoints are paginated by default " + "(limit/offset query parameters, Page envelope from core/pagination.py); " + "the option needs no extra package and generates nothing else." +) + @dataclass(frozen=True) class PresetProfile: @@ -249,16 +304,26 @@ class PresetProfile: regenerate_main: bool main_py_relpath: str db_config_relpath: str - auth_config_relpath: str + #: Directory of the generated authentication package. + auth_package_relpath: str # Hint shown when ``regenerate_main`` is False and the user picked a # feature whose dynamic main.py overlay won't run. Empty string means # "no special note for this preset". manual_wiring_note: str = "" extra_warning_targets: Tuple[str, ...] = field(default_factory=tuple) - # List endpoints the base template ships and keeps (only meaningful when - # ``regenerate_main`` is False: a regenerated main.py does not mount the - # template's routers, so nothing generated can shadow them). - shipped_collections: Tuple[ShippedCollection, ...] = field(default_factory=tuple) + #: The project's settings module (pydantic-settings, exports ``settings``). + settings_relpath: str = "src/core/config.py" + #: Probe paths the preserved template ``main.py`` serves itself; a + #: generated router for the same path is skipped. Only meaningful when + #: ``regenerate_main`` is False (a regenerated main.py serves ``/health`` + #: and mounts the generated ``/ready`` itself). + shipped_paths: Tuple[str, ...] = field(default_factory=tuple) + #: Write ``core/pagination.py`` when the base template has none (base + #: templates without a list endpoint of their own). + provide_pagination: bool = False + #: Where the base template's example items API keeps its items, when + #: that is not the selected database ("" when the template has none). + items_store: str = "" _PRESET_PROFILES: Dict[str, PresetProfile] = { @@ -268,7 +333,9 @@ class PresetProfile: regenerate_main=True, main_py_relpath="src/main.py", db_config_relpath="src/config/database.py", - auth_config_relpath="src/config/auth.py", + auth_package_relpath="src/auth", + settings_relpath="src/core/config.py", + provide_pagination=True, ), "single-module": PresetProfile( preset_id="single-module", @@ -276,7 +343,11 @@ class PresetProfile: regenerate_main=True, main_py_relpath="src/main.py", db_config_relpath="src/config/database.py", - auth_config_relpath="src/config/auth.py", + auth_package_relpath="src/auth", + # The template is a single module: when it ships no settings module, + # the generator writes one here (next to core/pagination.py). + settings_relpath="src/core/config.py", + provide_pagination=True, ), "classic-layered": PresetProfile( preset_id="classic-layered", @@ -284,7 +355,7 @@ class PresetProfile: regenerate_main=False, main_py_relpath="src/main.py", db_config_relpath="src/core/database.py", - auth_config_relpath="src/core/auth.py", + auth_package_relpath="src/auth", # CORS is intentionally NOT in this list: fastapi-default's shipped # main.py already imports CORSMiddleware and adds it conditionally # on settings.all_cors_origins, so the user only has to populate @@ -295,14 +366,9 @@ class PresetProfile: "wired — set BACKEND_CORS_ORIGINS in .env to activate it)." ), extra_warning_targets=_NON_CORS_TARGETS, - shipped_collections=( - ShippedCollection( - name="items", - endpoint="GET /items", - module_relpath="src/api/routes/items.py", - schema="ItemResponse", - ), - ), + settings_relpath="src/core/config.py", + shipped_paths=("/health",), + items_store="in the JSON file src/mocks/mock_items.json", ), "domain-starter": PresetProfile( preset_id="domain-starter", @@ -310,21 +376,16 @@ class PresetProfile: regenerate_main=False, main_py_relpath="src/app/main.py", db_config_relpath="src/app/core/database.py", - auth_config_relpath="src/app/core/auth.py", + auth_package_relpath="src/app/domains/auth", manual_wiring_note=( "fastapi-domain-starter's shipped src/app/main.py is preserved. " "The selections below need manual wiring there (CORS is already " "wired — set BACKEND_CORS_ORIGINS in .env to activate it)." ), extra_warning_targets=_NON_CORS_TARGETS, - shipped_collections=( - ShippedCollection( - name="items", - endpoint="GET /api/v1/items", - module_relpath="src/app/domains/items/router.py", - schema="ItemRead", - ), - ), + settings_relpath="src/app/core/config.py", + shipped_paths=("/health",), + items_store="in process memory (src/app/db/memory.py)", ), } @@ -345,40 +406,6 @@ def _package_dir(main_py_relpath: str) -> str: return normalized.rsplit("/", 1)[0] if "/" in normalized else "src" -def _wire_without_example( - content: str, target: OverlayTarget, collection: ShippedCollection, pkg: str -) -> str: - """Apply ``target.collection_wiring`` to a preserved ``main.py``. - - Imports go through the usual sorted insertion. The statements are - appended to the end of the module, after the template's own - ``include_router`` calls, so that anything that inspects the mounted - routes at call time (``add_pagination``) sees the template's endpoints. - The how-to comment from ``target.collection_hint`` precedes them. - """ - # Imported lazily: ``backend.main`` imports this module at load time. - from fastapi_fastkit.backend.main import insert_import_line - - imports, statements = target.collection_wiring - for line in imports: - content = insert_import_line(content, line.format(pkg=pkg)) - - pending = [line.format(pkg=pkg) for line in statements] - pending = [line for line in pending if line not in content] - if not pending: - return content - - fields = { - "endpoint": collection.endpoint, - "module_relpath": collection.module_relpath, - "schema": collection.schema, - } - block = [f"# {line.format(**fields)}".rstrip() for line in target.collection_hint] - block.extend(pending) - # Two blank lines keep the block valid after a top-level function too. - return content.rstrip("\n") + "\n\n\n" + "\n".join(block) + "\n" - - def app_module_from_relpath(relpath: str) -> str: """Convert a project-relative ``main.py`` path into ``module:attr``. @@ -461,21 +488,16 @@ def db_config_target(self, project_dir: str) -> Path: """Absolute path for the generated database config module.""" return Path(project_dir) / self.profile.db_config_relpath - def auth_config_target(self, project_dir: str) -> Path: - """Absolute path for the generated authentication config module.""" - return Path(project_dir) / self.profile.auth_config_relpath - def compatibility_warnings( self, config: Dict[str, Any], wired: Sequence[str] = () ) -> List[str]: - """Return user-facing warnings for unsupported preset/feature mixes. + """Return user-facing warnings for selections left unwired. - The dynamic ``main.py`` overlay (middleware wiring, Prometheus - instrumentation, feature router mounting) only runs for presets that - regenerate ``main.py``. For the other presets we keep the - template-shipped ``main.py`` intact and surface a single warning - listing the affected features so users know to wire them up - themselves rather than assuming the package install was enough. + The dynamic ``main.py`` overlay wires everything for presets that + regenerate ``main.py``. Presets that keep the template-shipped + ``main.py`` get most features spliced in through its anchors + (:meth:`wire_generated_routers`). Every target is wirable, so this + lists something only when ``main.py`` could not be found. Args: config: Interactive project configuration @@ -509,13 +531,6 @@ def compatibility_warnings( + "' preset): " + ", ".join(affected) ) - auth_module = self.profile.auth_config_relpath.removesuffix(".py").replace( - "/", "." - ) - for label in affected: - hint = _TARGETS_BY_LABEL[label].manual_hint - if hint: - warnings.append(hint.format(auth_module=auth_module)) return warnings def _affected_overlay_targets(self, config: Dict[str, Any]) -> List[str]: @@ -523,65 +538,115 @@ def _affected_overlay_targets(self, config: Dict[str, Any]) -> List[str]: return [ label for label in self.profile.extra_warning_targets - if label in _TARGETS_BY_LABEL and _TARGETS_BY_LABEL[label].applies(config) + if label in _TARGETS_BY_LABEL + and _TARGETS_BY_LABEL[label].applies(config) + and _TARGETS_BY_LABEL[label].provides_path not in self.profile.shipped_paths ] - def skipped_example_routers( - self, config: Dict[str, Any] - ) -> List[Tuple[OverlayTarget, ShippedCollection]]: - """Selected features whose demo router the base template would clash with. + def items_store_note(self, config: Dict[str, Any]) -> str: + """One line saying the example items are not in the selected database. + + Empty unless a database is selected and the base template's items + API keeps its items somewhere else. + """ + if not (self.profile.items_store and _uses_database(config)): + return "" + return ( + "The example /items API keeps its items " + f"{self.profile.items_store}, not in the selected database " + f"({_database_type(config)}); replace that store to persist items." + ) - A feature that generates a demo collection router (for example the - pagination demo on ``GET /api/v1/items``) is not given that router - when the base template already serves the same collection: the demo - would shadow or duplicate the template's own endpoint. + def generation_notes(self, config: Dict[str, Any]) -> List[str]: + """Informational lines for the generation summary (any preset).""" + notes: List[str] = [] + if _utility_selected(config, UtilityChoice.PAGINATION): + notes.append(PAGINATION_NOTE) + items_note = self.items_store_note(config) + if items_note: + notes.append(items_note) + notes.extend(auth_generation_notes(config, self.profile.auth_package_relpath)) + return notes + + def append_readme_notes(self, project_dir: str, config: Dict[str, Any]) -> bool: + """Add the :meth:`items_store_note` to the project's ``README.md``. + + Returns: + Whether the README was changed (False without a note, without a + README, or when it already carries the note) + """ + note = self.items_store_note(config) + readme = Path(project_dir) / "README.md" + if not note or not readme.is_file(): + return False + content, newline = read_text_preserving_newlines(readme) + if note in content: + return False + if content and not content.endswith("\n"): + content += "\n" + content += f"\n## Notes\n\n{note}\n" + write_text_preserving_newlines(readme, content, newline) + return True + + def auth_route_conflicts( + self, project_dir: str, config: Dict[str, Any] + ) -> List[str]: + """Warn about template routers that claim the generated auth paths. + + Scans the project's Python modules (outside the generated auth + package) for ``APIRouter(prefix="/auth")`` / ``"/users"`` and + ``@...("/auth/...")`` / ``("/users/...")`` routes. Data-driven, so a + template that ships its own users or auth router is reported instead + of silently answering next to (or shadowing) the generated one. Args: + project_dir: Absolute path of the generated project config: Interactive project configuration Returns: - ``(target, shipped collection)`` pairs, empty for presets that - regenerate ``main.py`` (they do not mount the template's routers) + One warning per conflicting module (empty when there is none or + no authentication is generated) """ - if self.profile.regenerate_main: + if generated_auth(config) == NONE_CHOICE: return [] - shipped = { - collection.name: collection - for collection in self.profile.shipped_collections - } - return [ - (target, shipped[target.example_collection]) - for target in OVERLAY_TARGETS - if target.example_collection in shipped and target.applies(config) - ] - - def skipped_example_labels(self, config: Dict[str, Any]) -> List[str]: - """Labels of :meth:`skipped_example_routers`, for the config generator.""" - return [target.label for target, _ in self.skipped_example_routers(config)] - - def skipped_example_notes(self, config: Dict[str, Any]) -> List[str]: - """One user-facing line per demo router that was not generated.""" - package_dir = _package_dir(self.profile.main_py_relpath) - return [ - f"{target.label}: the base template already serves " - f"{collection.endpoint} ({collection.module_relpath}), so the example " - f"router {package_dir}/{target.example_module} was not generated. " - f"See the comment at the end of {self.profile.main_py_relpath} " - "for how to apply it to the existing endpoint." - for target, collection in self.skipped_example_routers(config) - ] + root = Path(project_dir) + package = root / _package_dir(self.profile.main_py_relpath) + auth_dir = root / self.profile.auth_package_relpath + warnings: List[str] = [] + if not package.is_dir(): + return warnings + for path in sorted(package.rglob("*.py")): + if auth_dir in path.parents: + continue + try: + content, _ = read_text_preserving_newlines(path) + tree = ast.parse(content) + except (OSError, UnicodeDecodeError, SyntaxError): + continue + claimed = sorted(_claimed_auth_paths(tree)) + if claimed: + relative = path.relative_to(root).as_posix() + warnings.append( + f"{relative} already defines {', '.join(claimed)} routes; " + "the generated authentication routes use the same paths. " + "Keep one of them (or change a prefix)." + ) + return warnings def wire_generated_routers( self, project_dir: str, config: Dict[str, Any] ) -> List[str]: - """Splice generated feature routers into a preserved ``main.py``. - - Presets that keep their template's ``main.py`` used to leave every - generated router (background tasks, WebSocket, pagination) sitting on - disk unmounted. Templates ship ``# fastkit:imports`` / - ``# fastkit:routes`` anchors precisely so generated code can be added - without rewriting the file, so we use them here and fall back to a - warning for anything not safely wirable. + """Splice generated features into a preserved ``main.py``. + + Templates ship ``# fastkit:imports`` / ``# fastkit:routes`` anchors + precisely so generated code can be added without rewriting the file. + Each wirable target contributes imports (sorted into the template's + import block) and module-level statements (placed below the routes + anchor, which sits after ``app = FastAPI(...)``): router includes, + mounted under ``settings.API_V1_PREFIX`` except root-level probes and + the WebSocket endpoint, and ``setup_*(app)`` calls into generated + modules. Anything not safely wirable is left to + :meth:`compatibility_warnings`. Args: project_dir: Absolute path of the generated project @@ -604,34 +669,40 @@ def wire_generated_routers( if not main_path.is_file(): return [] - pkg = _package_root(self.profile.main_py_relpath) + fields = { + "pkg": _package_root(self.profile.main_py_relpath), + "settings_module": _dotted_module(self.profile.settings_relpath), + "auth_module": _dotted_module(self.profile.auth_package_relpath), + "db_module": _dotted_module(self.profile.db_config_relpath), + } content, newline = read_text_preserving_newlines(main_path) original = content wired: List[str] = [] - skipped = { - target.label: collection - for target, collection in self.skipped_example_routers(config) - } - - for label in self.profile.extra_warning_targets: - target = _TARGETS_BY_LABEL.get(label) - if target is None or not target.is_wirable: - continue - if not target.applies(config): - continue - collection = skipped.get(label) - if collection is not None: - content = _wire_without_example(content, target, collection, pkg) - wired.append(label) + affected = [ + _TARGETS_BY_LABEL[label] + for label in self._affected_overlay_targets(config) + if _TARGETS_BY_LABEL[label].is_wirable + ] + # Middleware goes right above the CORS block, in declared order, so + # CORS stays outermost. Without a CORS block it joins the routes. + for target in affected: + if not target.middleware: continue - + for line in target.wiring[1]: + placed = insert_before_cors(content, line.format(**fields)) + if placed is None: + break + content = placed + # Each statement lands right below the anchor, so targets and their + # statements are inserted in reverse to keep the declared order. + for target in reversed(affected): imports, statements = target.wiring for line in imports: - content = insert_import_line(content, line.format(pkg=pkg)) - for line in statements: - content = insert_statement_line(content, line.format(pkg=pkg)) - wired.append(label) + content = insert_import_line(content, line.format(**fields)) + for line in reversed(statements): + content = insert_statement_line(content, line.format(**fields)) + wired.insert(0, target.label) if content != original: write_text_preserving_newlines(main_path, content, newline) @@ -639,12 +710,142 @@ def wire_generated_routers( return wired +#: The auth package's route prefixes; template routers using them collide. +_AUTH_PREFIXES = ("/auth", "/users") + + +def _claimed_auth_paths(tree: ast.Module) -> set[str]: + """Auth / users prefixes a module's routers or routes declare.""" + claimed: set[str] = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + name = ast.unparse(node.func) + candidates: List[ast.expr] = [] + if name.endswith("APIRouter"): + candidates = [kw.value for kw in node.keywords if kw.arg == "prefix"] + elif name.rsplit(".", 1)[-1] in ("get", "post", "put", "patch", "delete"): + candidates = node.args[:1] + for value in candidates: + if isinstance(value, ast.Constant) and isinstance(value.value, str): + for prefix in _AUTH_PREFIXES: + path = value.value.rstrip("/") + if path == prefix or path.startswith(prefix + "/"): + claimed.add(prefix) + return claimed + + +def insert_before_cors(content: str, statement: str) -> str | None: + """Insert ``statement`` above the module-level block that adds CORS. + + The block is the first top-level statement whose code calls + ``add_middleware`` with ``CORSMiddleware``; comment lines directly above + it stay attached to it. Middleware added before CORS ends up inside it + (Starlette makes the last added middleware the outermost one). + + Args: + content: Source of a ``main.py`` (``\\n`` line endings) + statement: One module-level statement + + Returns: + The updated source (unchanged when the statement is already there + as code: a commented-out copy does not count), or None when the + module has no CORS block (or does not parse) + """ + # Imported lazily: ``backend.main`` imports this module at load time. + from fastapi_fastkit.backend.main import statement_present + + if statement_present(content, statement): + return content + try: + tree = ast.parse(content) + except SyntaxError: + return None + for node in tree.body: + if any( + isinstance(call, ast.Call) + and isinstance(call.func, ast.Attribute) + and call.func.attr == "add_middleware" + and call.args + and ast.unparse(call.args[0]).endswith("CORSMiddleware") + for call in ast.walk(node) + ): + lines = content.split("\n") + index = node.lineno - 1 + while index > 0 and lines[index - 1].lstrip().startswith("#"): + index -= 1 + lines[index:index] = [statement] + return "\n".join(lines) + return None + + +def auth_generation_notes( + config: Dict[str, Any], auth_package_relpath: str +) -> List[str]: + """Summary lines describing what the selected auth option generated. + + Args: + config: Interactive project configuration + auth_package_relpath: Directory of the generated auth package + + Returns: + Informational lines (empty without an auth selection) + """ + auth = generated_auth(config) + if auth == NONE_CHOICE: + return [] + db_type = _database_type(config) + notes = [f"Authentication ({auth}): generated in {auth_package_relpath}/."] + if auth in (AuthChoice.JWT, AuthChoice.SESSION) and db_type not in _SQL_DATABASES: + if db_type == DatabaseChoice.MONGODB: + notes.append( + "Accounts are stored in the MongoDB 'users' collection " + "(unique index on email, created on first registration)." + ) + else: + notes.append( + "Accounts are kept IN MEMORY: they are lost on restart and not " + "shared between worker processes. Select a database to persist them." + ) + if auth in (AuthChoice.JWT, AuthChoice.SESSION, AuthChoice.FASTAPI_USERS) and ( + db_type in _SQL_DATABASES + ): + if config.get(FeatureAxis.MIGRATIONS) == MigrationsChoice.ALEMBIC: + notes.append( + "The users table is created by the initial Alembic revision: " + "run `alembic upgrade head`." + ) + else: + notes.append( + "The users table is created on startup when missing " + "(no migrations selected)." + ) + if auth == AuthChoice.SESSION: + notes.append( + "Demo account demo@example.com / demo-password works only with " + "ENABLE_DEMO_USERS=true (refused unless ENVIRONMENT=development)." + ) + if auth == AuthChoice.OAUTH2: + notes.append( + "Set GOOGLE_* / GITHUB_* client credentials in .env to enable a provider." + ) + return notes + + +def _dotted_module(relpath: str) -> str: + """``src/app/core/config.py`` -> ``src.app.core.config``.""" + return relpath.replace("\\", "/").removesuffix(".py").replace("/", ".") + + __all__ = [ "OVERLAY_TARGETS", "OverlayTarget", + "PAGINATION_NOTE", "PresetLayoutStrategist", "PresetProfile", - "ShippedCollection", "app_module_from_main_path", + "auth_generation_notes", + "generated_auth", + "insert_before_cors", "app_module_from_relpath", ] diff --git a/src/fastapi_fastkit/backend/route_generators.py b/src/fastapi_fastkit/backend/route_generators.py index 09a9e9d..a9fadf4 100644 --- a/src/fastapi_fastkit/backend/route_generators.py +++ b/src/fastapi_fastkit/backend/route_generators.py @@ -1,25 +1,57 @@ # -------------------------------------------------------------------------- # Route generators for fastkit addroute. +# +# Both layouts plan every file in memory (see ``route_plan``) before +# anything is written: route modules, the shared ``core/pagination.py``, a +# test module, the API router registration and the ``main.py`` wiring. # -------------------------------------------------------------------------- +import ast import keyword import os +import re +from abc import ABC, abstractmethod +from dataclasses import dataclass from pathlib import Path -from typing import Dict, Optional, Union +from typing import Dict, List, Optional, Sequence, Set, Union from fastapi_fastkit.backend import main as backend from fastapi_fastkit.backend.project_builder.preset_layout import PresetLayoutStrategist -from fastapi_fastkit.backend.route_wiring import register_router, router_alias -from fastapi_fastkit.backend.transducer import copy_and_convert_template_file +from fastapi_fastkit.backend.route_plan import RoutePlan +from fastapi_fastkit.backend.route_wiring import ( + plan_router_registration, + print_plan_notes, + router_alias, +) from fastapi_fastkit.core.exceptions import BackendExceptions from fastapi_fastkit.core.settings import settings from fastapi_fastkit.utils.main import print_warning, read_fastkit_metadata -from fastapi_fastkit.utils.textio import write_generated_text +from fastapi_fastkit.utils.textio import read_text_preserving_newlines ROUTE_LAYOUTS = ("classic-layer", "domain") +_CLASSIC_PRESETS = ("classic-layered", "minimal", "single-module") + + +# ------------------------------------------------------------ +# Layout resolution +# ------------------------------------------------------------ + + +def _has_domains_package(project_dir: str) -> bool: + package_dir = backend.resolve_project_layout(project_dir)["package_dir"] + return os.path.isdir(os.path.join(package_dir, "domains")) + def resolve_route_layout(project_dir: str, layout: Optional[str] = None) -> str: - """Resolve the route layout from the option or project metadata.""" + """ + Resolve the route layout for a project. + + Order: the explicit option; the project metadata (the ``domain-starter`` + preset or template means domain, the other known presets mean classic); + then the project itself: a ``domains/`` package next to ``main.py`` + means domain (``fastapi-sqlmodel``, ``fastapi-auth-jwt`` and projects + without metadata); everything else gets the classic layout. + """ if layout is not None: if layout not in ROUTE_LAYOUTS: raise BackendExceptions(f"Unknown route layout: {layout!r}") @@ -27,130 +59,610 @@ def resolve_route_layout(project_dir: str, layout: Optional[str] = None) -> str: metadata = read_fastkit_metadata(project_dir) preset = metadata.get("preset") + if preset == "domain-starter": + return "domain" + if preset in _CLASSIC_PRESETS: + return "classic-layer" if not preset: - template = metadata.get("template") domain_template = PresetLayoutStrategist("domain-starter").base_template - if template == domain_template: + if metadata.get("template") == domain_template: return "domain" - if preset == "domain-starter": + if _has_domains_package(project_dir): return "domain" - if preset and preset not in ("classic-layered", "minimal", "single-module"): + if preset: print_warning(f"Unknown preset {preset!r}; using classic-layer route layout.") return "classic-layer" -def _validate_route_name(route_name: str) -> None: - """Validate the route module name.""" - if not route_name.isidentifier() or keyword.iskeyword(route_name): - raise BackendExceptions(f"Route name {route_name!r} is not a Python identifier") +# ------------------------------------------------------------ +# Names +# ------------------------------------------------------------ +#: Words whose singular and plural are the same. +_UNCOUNTABLE = frozenset( + { + "data", + "equipment", + "feedback", + "fish", + "info", + "information", + "media", + "metadata", + "money", + "news", + "series", + "sheep", + "species", + "software", + } +) -class ClassicLayeredRouteGenerator: - """Generate api/routes, crud, and schemas modules.""" +#: Irregular plurals (lower case). +_IRREGULAR = { + "analyses": "analysis", + "children": "child", + "criteria": "criterion", + "feet": "foot", + "geese": "goose", + "halves": "half", + "indices": "index", + "knives": "knife", + "leaves": "leaf", + "lives": "life", + "matrices": "matrix", + "men": "man", + "mice": "mouse", + "people": "person", + "phenomena": "phenomenon", + "shelves": "shelf", + "teeth": "tooth", + "vertices": "vertex", + "wives": "wife", + "women": "woman", +} - def add_new_route( - self, project_dir: str, route_name: str, project_layout: Dict[str, str] - ) -> None: - """Create route files and register the router.""" - src_dir = project_layout["package_dir"] - _validate_route_name(route_name) - modules_dir = os.path.join(settings.FASTKIT_TEMPLATE_ROOT, "modules") - target_dirs = backend._ensure_project_structure(src_dir) - backend._create_route_files( - modules_dir, target_dirs, route_name, project_layout["package_module"] +_ENTITY_PATTERN = re.compile(r"[A-Z][A-Za-z0-9]*") + +#: Route names are module names, URL segments and identifier parts at once. +_ROUTE_NAME_PATTERN = re.compile(r"[a-z][a-z0-9_]*") + + +def singularize(word: str) -> str: + """ + Best-effort English singular of one lower- or camel-case word. + + Unknown shapes are returned unchanged, which is always a valid name. + """ + lower = word.lower() + if lower in _UNCOUNTABLE: + return word + if lower in _IRREGULAR: + singular = _IRREGULAR[lower] + return word[0] + singular[1:] if word[:1].isupper() else singular + for suffix in ("sses", "shes", "ches", "xes", "zzes"): + if lower.endswith(suffix): + return word[:-2] + if lower.endswith("ies") and len(lower) > 4: + return word[:-3] + "y" + if lower.endswith("s") and not lower.endswith(("ss", "us", "is")): + return word[:-1] if len(word) > 1 else word + return word + + +def _pascal(part: str) -> str: + return part[:1].upper() + part[1:] + + +def derive_entity_name(route_name: str) -> str: + """ + Singular PascalCase class name for a route: ``orders`` -> ``Order``, + ``health_checks`` -> ``HealthCheck``, ``news`` -> ``News``. + + The result always matches ``[A-Z][A-Za-z0-9]*`` and is never a keyword. + """ + parts = [part for part in route_name.split("_") if part] + if parts: + parts[-1] = singularize(parts[-1]) + name = "".join(_pascal(part) for part in parts) + if not name: + return "Entity" + if not name[0].isalpha(): + name = f"Entity{name}" + if keyword.iskeyword(name): + name = f"{name}Entity" + return name + + +def _snake(name: str) -> str: + """``HealthCheck`` -> ``health_check``; ``HTTPRequest`` -> ``http_request``.""" + spaced = re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", name) + return spaced.lower() + + +@dataclass(frozen=True) +class RouteNames: + """Every name a generated route uses.""" + + route: str + entity: str + + @property + def snake(self) -> str: + return _snake(self.entity) + + @property + def label(self) -> str: + """Lower-case human name: ``health check``.""" + return self.snake.replace("_", " ") + + @property + def title(self) -> str: + """Capitalised human name for messages: ``Health check``.""" + return _pascal(self.label) + + @property + def path(self) -> str: + return f"/{self.route}" + + +def _is_keyword(name: str) -> bool: + return keyword.iskeyword(name) or keyword.issoftkeyword(name) + + +def validate_route_name(route_name: str) -> None: + """Validate the route name. + + The name becomes a module name, the URL segment (``/orders``) and part + of every generated identifier, so it must be lower-case ASCII + (``[a-z][a-z0-9_]*``: no leading underscore, so no dunder names either) + and must not be a keyword or soft keyword. + """ + if not _ROUTE_NAME_PATTERN.fullmatch(route_name): + raise BackendExceptions( + f"Route name {route_name!r} is not a valid Python identifier for a " + "route: use lower-case ASCII letters, digits and underscores, " + "starting with a letter (it becomes a module name and the URL " + "segment)." ) - backend._handle_api_router_file( - target_dirs, modules_dir, route_name, project_layout["api_router_file"] + if _is_keyword(route_name): + raise BackendExceptions( + f"Route name {route_name!r} is a Python keyword and cannot be used " + "as a Python identifier." ) - backend._process_init_files( - modules_dir, target_dirs, ["api/routes", "crud", "schemas"] + + +def resolve_route_names(route_name: str, entity: Optional[str] = None) -> RouteNames: + """Validate the route name and the optional ``--entity`` override. + + The entity class name (given or derived) must be ASCII PascalCase, and + its snake_case form (used in identifiers such as ``order_id`` and in + the item URL ``/{order_id}``) must be a plain lower-case identifier. + """ + validate_route_name(route_name) + if entity is not None and ( + not _ENTITY_PATTERN.fullmatch(entity) or _is_keyword(entity) + ): + raise BackendExceptions( + f"Entity name {entity!r} must be a PascalCase class name " + "(ASCII letters and digits, starting with an upper-case letter)" + ) + names = RouteNames(route_name, entity or derive_entity_name(route_name)) + if not _ROUTE_NAME_PATTERN.fullmatch(names.snake) or _is_keyword(names.snake): + source = ( + "Entity name" if entity else f"Entity name derived from {route_name!r}," ) - backend._update_main_app( - src_dir, - route_name, - router_module=project_layout["api_router_module"], - main_py_path=project_layout["main"], + raise BackendExceptions( + f"{source} {names.entity!r} gives the identifier {names.snake!r}, " + "which cannot be used (a keyword or not a plain lower-case name); " + "pass another class name with --entity." + ) + return names + + +def _listdir_lower(directory: str) -> Dict[str, str]: + """``{lower-cased name: name}`` of a directory's entries (empty if absent).""" + try: + return {entry.lower(): entry for entry in os.listdir(directory)} + except OSError: + return {} + + +def project_top_level_names(package_dir: str) -> Dict[str, str]: + """Modules and packages directly inside the project package. + + ``{lower-cased module name: path}`` for every ``*.py`` file and every + directory (regular or namespace package) of ``package_dir``, read from + the project tree, so a route named like one of them (``main``, + ``core``, ``api``, ``auth``, ``health``, ...) can be refused. + """ + found: Dict[str, str] = {} + for lowered, entry in _listdir_lower(package_dir).items(): + if entry.startswith((".", "_")): + continue + path = os.path.join(package_dir, entry) + if os.path.isdir(path): + found[lowered] = path + elif lowered.endswith(".py"): + found[lowered[:-3]] = path + return found + + +def _existing_case_insensitive(path: str) -> Optional[str]: + """The on-disk path matching ``path`` in any letter case, if one exists. + + Compared case-insensitively on every OS, so ``Orders.py`` blocks + ``orders.py`` on Linux the same way as on macOS and Windows. + """ + parent, name = os.path.split(path) + if not parent or parent == path: + return path if os.path.exists(path) else None + if not os.path.isdir(parent): + found_parent = _existing_case_insensitive(parent) + if found_parent is None or not os.path.isdir(found_parent): + return None + parent = found_parent + entry = _listdir_lower(parent).get(name.lower()) + return os.path.join(parent, entry) if entry is not None else None + + +def route_owned_paths( + project_dir: str, project_layout: Dict[str, str], names: RouteNames, layout: str +) -> List[str]: + """Files and directories that belong to one route only. + + Classic layout: ``api/routes/.py``, ``crud/.py`` and + ``schemas/.py``; domain layout: ``domains//``. Both: the + test module ``tests/test_.py``. + """ + package_dir = project_layout["package_dir"] + if layout == "domain": + owned = [os.path.join(package_dir, "domains", names.route)] + else: + owned = [ + os.path.join(package_dir, *relative.split("/"), f"{names.route}.py") + for relative in ("api/routes", "crud", "schemas") + ] + owned.append(os.path.join(project_dir, "tests", f"test_{names.route}.py")) + return owned + + +def _check_route_name_is_free( + project_dir: str, project_layout: Dict[str, str], names: RouteNames +) -> None: + """Refuse a route named like a module or package of the project package.""" + taken = project_top_level_names(project_layout["package_dir"]) + clash = taken.get(names.route.lower()) + if clash is not None: + shown = os.path.relpath(clash, project_dir).replace(os.sep, "/") + raise BackendExceptions( + f"Route name {names.route!r} collides with {shown}, an existing " + "module or package of the project; choose another route name." + ) + + +# ------------------------------------------------------------ +# Templates +# ------------------------------------------------------------ + + +def _modules_dir() -> Path: + return Path(settings.FASTKIT_TEMPLATE_ROOT) / "modules" + + +def _render(template: Path, replacements: Dict[str, str]) -> str: + """Read a module template (any line endings) and fill its placeholders.""" + if not template.is_file(): + raise BackendExceptions( + f"Missing route template: {template.parent.name}/{template.name}" + ) + content, _ = read_text_preserving_newlines(template) + content = content.replace("\r\n", "\n") + for placeholder, value in replacements.items(): + content = content.replace(placeholder, value) + return content + + +def _module(package: str, *parts: str) -> str: + return ".".join(part for part in (package, *parts) if part) + + +def _replacements( + names: RouteNames, package_module: str, extra: Dict[str, str] +) -> Dict[str, str]: + values = { + "": package_module, + "": _module(package_module, "core", "pagination"), + "": _module(package_module, "core", "responses"), + "": names.route, + "": names.entity, + "": names.snake, + "": names.label, + "": names.title, + # Where the generated tests find the payload / error text in a body. + "": "", + "": '["detail"]', + } + values.update(extra) + return values + + +#: Project modules every generated route imports, created when a project +#: generated by an older fastkit lacks them. The templates ship the same +#: files (``core/pagination.py``, ``core/responses.py``). +SHARED_CORE_MODULES = { + "pagination.py": "the Page envelope and limit/offset parameters", + "responses.py": "the error_responses() OpenAPI helper", +} + + +def shared_core_source(filename: str) -> str: + """Canonical content of a shared ``core/`` module (``pagination.py``).""" + return _render(_modules_dir() / "core" / f"{filename}-tpl", {}) + + +def _plan_package_init(plan: RoutePlan, directory: str) -> None: + """Plan ``__init__.py`` for a package directory ``addroute`` creates.""" + if not os.path.isdir(directory): + plan.write(os.path.join(directory, "__init__.py"), "") + + +#: Modules (and what each must define) of a project that wraps every JSON +#: response in an envelope (``fastapi-custom-response``): routes added to it +#: return the same envelope and document the enveloped errors. +_ENVELOPE_MODULES = { + "": ("helper/exceptions.py", "def error_responses("), + "": ("helper/responses.py", "def success_response("), + "": ("schemas/base.py", "class ResponseSchema("), +} + + +def _envelope_replacements(package_dir: str, package_module: str) -> Dict[str, str]: + """Placeholders for an envelope project, empty for any other project.""" + replacements: Dict[str, str] = {} + for placeholder, (relative, marker) in _ENVELOPE_MODULES.items(): + path = os.path.join(package_dir, *relative.split("/")) + try: + content, _ = read_text_preserving_newlines(path) + except (OSError, UnicodeDecodeError): + return {} + if marker not in content: + return {} + replacements[placeholder] = _module( + package_module, *relative.removesuffix(".py").split("/") ) + # The generated tests read the payload and the error text from it. + replacements[""] = '["message"]' + replacements[""] = '["message"]' + return replacements + + +def _plan_shared_core( + plan: RoutePlan, package_dir: str, skip: Sequence[str] = () +) -> None: + core = os.path.join(package_dir, "core") + for filename, purpose in SHARED_CORE_MODULES.items(): + target = os.path.join(core, filename) + if filename in skip or plan.exists(target): + continue + content = shared_core_source(filename) + _plan_package_init(plan, core) + plan.write(target, content) + plan.note(f"Added {plan.display(target)}: {purpose} the routes use.") + + +def _plan_tests( + plan: RoutePlan, + project_dir: str, + project_layout: Dict[str, str], + names: RouteNames, + store_module: str, + extra: Optional[Dict[str, str]] = None, +) -> None: + """Plan ``tests/test_.py`` when the project has a ``tests`` folder.""" + tests_dir = os.path.join(project_dir, "tests") + if not os.path.isdir(tests_dir): + return + recorded = read_fastkit_metadata(project_dir).get("app_module") + app_module = ( + recorded.strip() + if isinstance(recorded, str) and backend.valid_app_module(recorded) + else project_layout.get("app_module") or "src.main:app" + ) + module, _, attribute = app_module.partition(":") + attribute = attribute or "app" + app_import = f"from {module} import {attribute}" + if attribute != "app": + app_import += " as app" + imports = sorted( + [app_import, f"from {store_module} import reset_store"], + key=lambda line: line.split()[1].lower(), + ) + content = _render( + _modules_dir() / "tests" / "test_new_route.py-tpl", + _replacements( + names, + project_layout["package_module"], + {**(extra or {}), "": "\n".join(imports)}, + ), + ) + plan.create(os.path.join(tests_dir, f"test_{names.route}.py"), content) + + +def _plan_main( + plan: RoutePlan, project_layout: Dict[str, str], names: RouteNames +) -> None: + backend._update_main_app( + project_layout["package_dir"], + names.route, + router_module=project_layout["api_router_module"], + main_py_path=project_layout["main"], + plan=plan, + ) + +# ------------------------------------------------------------ +# Generators +# ------------------------------------------------------------ -class DomainRouteGenerator: - """Generate a domain module.""" + +class _RouteGenerator(ABC): + """Shared plan-then-apply entry point.""" + + layout = "" + + @abstractmethod + def plan( + self, + plan: RoutePlan, + project_dir: str, + names: RouteNames, + project_layout: Dict[str, str], + ) -> None: + """Record every file the route needs in ``plan``.""" def add_new_route( - self, project_dir: str, route_name: str, project_layout: Dict[str, str] + self, + project_dir: str, + route_name: str, + project_layout: Dict[str, str], + entity: Optional[str] = None, + ) -> RoutePlan: + """Plan the route and write it.""" + plan = RoutePlan(project_dir) + self.plan( + plan, project_dir, resolve_route_names(route_name, entity), project_layout + ) + print_plan_notes(plan) + plan.apply() + return plan + + +class ClassicLayeredRouteGenerator(_RouteGenerator): + """Generate ``api/routes``, ``crud`` and ``schemas`` modules.""" + + layout = "classic-layer" + + def plan( + self, + plan: RoutePlan, + project_dir: str, + names: RouteNames, + project_layout: Dict[str, str], ) -> None: - """Create domain files and register the router.""" - package = Path(project_layout["package_dir"]) - _validate_route_name(route_name) - if not package.is_dir(): + package_dir = project_layout["package_dir"] + if not os.path.isdir(package_dir): + raise BackendExceptions(f"Source directory not found at {package_dir}") + package_module = project_layout["package_module"] + modules = _modules_dir() + envelope = _envelope_replacements(package_dir, package_module) + replacements = _replacements(names, package_module, envelope) + templates = { + "api/routes": ( + "new_route_envelope.py-tpl" if envelope else "new_route.py-tpl" + ), + "crud": "new_route.py-tpl", + "schemas": "new_route.py-tpl", + } + contents = { + relative: _render(modules / relative / template, replacements) + for relative, template in templates.items() + } + + for relative in ("api", "api/routes", "crud", "schemas"): + _plan_package_init(plan, os.path.join(package_dir, *relative.split("/"))) + for relative, content in contents.items(): + target = os.path.join( + package_dir, *relative.split("/"), f"{names.route}.py" + ) + plan.create(target, content) + + # An envelope project documents errors with its own error_responses(). + _plan_shared_core(plan, package_dir, skip=["responses.py"] if envelope else []) + _plan_tests( + plan, + project_dir, + project_layout, + names, + _module(package_module, "crud", names.route), + envelope, + ) + backend._update_api_router( + project_layout["api_router_file"], + names.route, + package_module=package_module, + plan=plan, + ) + _plan_main(plan, project_layout, names) + + +_DOMAIN_FILES = ( + "__init__.py", + "models.py", + "schemas.py", + "repository.py", + "service.py", + "router.py", +) + + +class DomainRouteGenerator(_RouteGenerator): + """Generate a ``domains/`` module.""" + + layout = "domain" + + def plan( + self, + plan: RoutePlan, + project_dir: str, + names: RouteNames, + project_layout: Dict[str, str], + ) -> None: + package = project_layout["package_dir"] + if not os.path.isdir(package): raise BackendExceptions(f"Source directory not found at {package}") + templates = _modules_dir() / "domain" + for filename in _DOMAIN_FILES: + if not (templates / f"{filename}-tpl").is_file(): + raise BackendExceptions(f"Missing domain template: {filename}-tpl") - domain_module = _create_domain_files(package, route_name, project_layout) + package_module = project_layout["package_module"] + domain_module = _module(package_module, "domains", names.route) + replacements = _replacements( + names, package_module, {"": domain_module} + ) + domains_dir = os.path.join(package, "domains") + domains_init = os.path.join(domains_dir, "__init__.py") + if not plan.exists(domains_init): + plan.write(domains_init, "") + domain_dir = os.path.join(domains_dir, names.route) + for filename in _DOMAIN_FILES: + content = _render(templates / f"{filename}-tpl", replacements) + plan.create(os.path.join(domain_dir, filename), content) + + _plan_shared_core(plan, package) + _plan_tests( + plan, + project_dir, + project_layout, + names, + _module(domain_module, "service"), + ) alias = router_alias( project_layout["api_router_file"], domain_module, "router", - f"{route_name}_router", + f"{names.route}_router", + plan=plan, ) - register_router( + suffix = f" as {alias}" if alias != "router" else "" + plan_router_registration( + plan, project_layout, - f"from {domain_module} import router as {alias}", - f'api_router.include_router({alias}.router, prefix="/{route_name}", tags=["{route_name}"])', - ) - backend._update_main_app( - str(package), - route_name, - router_module=project_layout["api_router_module"], - main_py_path=project_layout["main"], - ) - - -def _create_domain_files( - package: Path, route_name: str, project_layout: Dict[str, str] -) -> str: - templates = Path(settings.FASTKIT_TEMPLATE_ROOT) / "modules" / "domain" - filenames = ( - "__init__.py", - "models.py", - "schemas.py", - "repository.py", - "service.py", - "router.py", - ) - for filename in filenames: - if not (templates / f"{filename}-tpl").is_file(): - raise BackendExceptions(f"Missing domain template: {filename}-tpl") - - domain_dir = package / "domains" / route_name - domain_dir.mkdir(parents=True, exist_ok=True) - domains_init = domain_dir.parent / "__init__.py" - if not domains_init.exists(): - write_generated_text(domains_init, "") - prefix = project_layout["package_module"] - domain_module = ( - f"{prefix}.domains.{route_name}" if prefix else f"domains.{route_name}" - ) - entity_class = ( - "".join(part[:1].upper() + part[1:] for part in route_name.split("_")) or "_" - ) - if keyword.iskeyword(entity_class): - entity_class += "Entity" - replacements = { - "": route_name, - "": domain_module, - "": entity_class, - } - for filename in filenames: - target = domain_dir / filename - if target.exists(): - print_warning(f"File {target} already exists, skipping...") - continue - if not copy_and_convert_template_file( - str(templates / f"{filename}-tpl"), str(target), replacements - ): - raise BackendExceptions(f"Failed to create domain file: {target}") - - return domain_module + f"from {domain_module} import router{suffix}", + f"api_router.include_router({alias}.router)", + ) + _plan_main(plan, project_layout, names) def get_route_generator( @@ -162,3 +674,145 @@ def get_route_generator( if route_layout == "domain": return DomainRouteGenerator() raise BackendExceptions(f"Unknown route layout: {route_layout!r}") + + +def plan_new_route( + project_dir: str, + route_name: str, + layout: Optional[str] = None, + entity: Optional[str] = None, +) -> RoutePlan: + """ + Compute every file ``addroute`` would create or modify, writing nothing. + + :param project_dir: Project root + :param route_name: Route module name (``orders``) + :param layout: Explicit layout, or None to resolve it from the project + :param entity: Explicit entity class name, or None to derive it + :return: The plan, with ``details`` holding the resolved names + """ + names = resolve_route_names(route_name, entity) + route_layout = resolve_route_layout(project_dir, layout) + project_layout = backend.resolve_project_layout(project_dir) + _check_route_name_is_free(project_dir, project_layout, names) + plan = RoutePlan(project_dir) + plan.details.update(route_details(names, route_layout)) + get_route_generator(route_layout).plan(plan, project_dir, names, project_layout) + _check_existing_route(plan, project_dir, project_layout, names, route_layout) + _check_generated_modules(plan, names) + return plan + + +def _check_existing_route( + plan: RoutePlan, + project_dir: str, + project_layout: Dict[str, str], + names: RouteNames, + route_layout: str, +) -> None: + """Refuse to wire a route whose own files already exist. + + A re-run that changes nothing (every file and registration already in + place) is fine; anything else would register a router over files the + user owns, or ship a route without its tests. + """ + if plan.is_empty: + return + existing = [ + found + for path in route_owned_paths(project_dir, project_layout, names, route_layout) + if (found := _existing_case_insensitive(path)) is not None + ] + if existing: + shown = ", ".join(plan.display(path) for path in existing) + raise BackendExceptions( + f"Route {names.route!r} already exists or clashes with existing " + f"files: {shown}. Nothing was written; choose another route name " + "or remove those files first." + ) + + +def _top_level_bindings(tree: ast.Module) -> List[str]: + bound: List[str] = [] + for node in tree.body: + if isinstance(node, (ast.Import, ast.ImportFrom)): + bound.extend( + alias.asname or alias.name.split(".")[0] for alias in node.names + ) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + bound.append(node.name) + return bound + + +def _check_generated_modules(plan: RoutePlan, names: RouteNames) -> None: + """Refuse names that break the generated modules. + + Every new module must parse and must not bind one name twice at module + level (an ``--entity`` such as ``Page`` or ``Request`` would shadow an + import), and the route name must not equal a module the generated code + imports (``typing``, ``threading``, ``fastapi``, ...): a module named + like that shadows the real one whenever its directory is on + ``sys.path``. + """ + imported: Set[str] = set() + for planned in plan.created: + if not planned.path.endswith(".py") or not planned.content.strip(): + continue + try: + tree = ast.parse(planned.content) + except SyntaxError as e: + raise BackendExceptions( + f"The generated {plan.display(planned.path)} is not valid Python " + f"({e.msg}); choose another route or entity name." + ) from e + seen: Set[str] = set() + for name in _top_level_bindings(tree): + if name in seen: + raise BackendExceptions( + f"The name {name!r} would be defined twice in the generated " + f"{plan.display(planned.path)}; choose another --entity or " + "route name." + ) + seen.add(name) + for node in tree.body: + if isinstance(node, ast.Import): + imported.update(alias.name.split(".")[0] for alias in node.names) + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + imported.add(node.module.split(".")[0]) + if names.route in imported: + raise BackendExceptions( + f"Route name {names.route!r} would shadow the {names.route!r} module " + "the generated code imports; choose another route name." + ) + + +def route_details(names: RouteNames, route_layout: str) -> Dict[str, str]: + """Rows describing the resolved route for the confirmation table.""" + return { + "Layout": route_layout, + "Path": names.path, + "Entity": names.entity, + "Schemas": ", ".join( + f"{names.entity}{suffix}" for suffix in ("Create", "Update", "Read") + ), + } + + +__all__: List[str] = [ + "ClassicLayeredRouteGenerator", + "DomainRouteGenerator", + "ROUTE_LAYOUTS", + "RouteNames", + "derive_entity_name", + "get_route_generator", + "project_top_level_names", + "route_owned_paths", + "SHARED_CORE_MODULES", + "shared_core_source", + "plan_new_route", + "resolve_route_layout", + "resolve_route_names", + "route_details", + "singularize", + "validate_route_name", +] diff --git a/src/fastapi_fastkit/backend/route_plan.py b/src/fastapi_fastkit/backend/route_plan.py new file mode 100644 index 0000000..0580d52 --- /dev/null +++ b/src/fastapi_fastkit/backend/route_plan.py @@ -0,0 +1,309 @@ +# -------------------------------------------------------------------------- +# In-memory file plan for ``fastkit addroute``. +# +# Route generation computes every resulting file first and writes nothing +# until the plan is complete. The same plan is either rendered (``--dry-run`` +# / ``--diff``) or applied, so a preview cannot diverge from what a real run +# writes, and a failure while planning (missing template, invalid name) +# leaves the project untouched. Every planned path must resolve inside the +# project directory, and a write that fails partway is rolled back. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import difflib +import os +from dataclasses import dataclass +from typing import Callable, Dict, List, Optional, Tuple + +from fastapi_fastkit.core.exceptions import BackendExceptions +from fastapi_fastkit.utils.textio import ( + read_text_preserving_newlines, + write_generated_text, + write_text_preserving_newlines, +) + + +@dataclass +class PlannedFile: + """One file the plan creates or rewrites. + + ``original`` is None for a new file. Existing files are held the way + :func:`read_text_preserving_newlines` returns them (a CRLF file as LF + text plus ``newline="\\r\\n"``), so edits and diffs never see the + carriage returns and the write restores them. + """ + + path: str + content: str + original: Optional[str] + newline: str = "\n" + + @property + def is_new(self) -> bool: + return self.original is None + + +def _key(path: str) -> str: + return os.path.normcase(os.path.abspath(path)) + + +def _is_within(path: str, directory: str) -> bool: + """Whether ``path`` resolves (symlinks followed) inside ``directory``.""" + real_path = os.path.realpath(path) + real_dir = os.path.realpath(directory) + try: + return os.path.commonpath([real_path, real_dir]) == real_dir + except ValueError: # different drives on Windows + return False + + +class RoutePlan: + """Files ``addroute`` would create or modify, held in memory.""" + + def __init__(self, project_dir: str = "") -> None: + self.project_dir = project_dir + self._files: Dict[str, PlannedFile] = {} + self._disk: Dict[str, Optional[Tuple[str, str]]] = {} + #: ``(level, message)`` pairs: ``"info"`` or ``"warning"``. + self.notes: List[Tuple[str, str]] = [] + #: Resolved names and layout, filled in by the route generators. + self.details: Dict[str, str] = {} + + # -- reading -------------------------------------------------------- + def _read_disk(self, path: str) -> Optional[Tuple[str, str]]: + key = _key(path) + if key not in self._disk: + self._disk[key] = ( + read_text_preserving_newlines(path) if os.path.isfile(path) else None + ) + return self._disk[key] + + def exists(self, path: str) -> bool: + """Whether the file exists on disk or is created by the plan.""" + return _key(path) in self._files or self._read_disk(path) is not None + + def read(self, path: str) -> Optional[str]: + """Planned content of ``path``, else its content on disk, else None.""" + planned = self._files.get(_key(path)) + if planned is not None: + return planned.content + disk = self._read_disk(path) + return disk[0] if disk is not None else None + + # -- recording ------------------------------------------------------ + def _check_inside(self, path: str) -> None: + """Refuse a path that resolves outside the project directory.""" + if self.project_dir and not _is_within(path, self.project_dir): + raise BackendExceptions( + f"Refusing to write {path}: it resolves outside the project " + f"directory {self.project_dir}." + ) + + def note(self, message: str, level: str = "info") -> None: + if (level, message) not in self.notes: + self.notes.append((level, message)) + + def create(self, path: str, content: str) -> bool: + """Plan a new file; an existing file is kept and noted instead. + + :return: True when the file is part of the plan + """ + if self.exists(path): + self.note(f"File {self.display(path)} already exists, skipping...") + return False + self._check_inside(path) + self._files[_key(path)] = PlannedFile(path=path, content=content, original=None) + return True + + def write(self, path: str, content: str) -> None: + """Plan new content for a file, creating it when it does not exist.""" + self._check_inside(path) + key = _key(path) + planned = self._files.get(key) + if planned is not None: + planned.content = content + if planned.original is not None and planned.content == planned.original: + del self._files[key] + return + disk = self._read_disk(path) + if disk is None: + self._files[key] = PlannedFile(path=path, content=content, original=None) + elif content != disk[0]: + self._files[key] = PlannedFile( + path=path, content=content, original=disk[0], newline=disk[1] + ) + + # -- inspecting ----------------------------------------------------- + @property + def created(self) -> List[PlannedFile]: + return [item for item in self._files.values() if item.is_new] + + @property + def modified(self) -> List[PlannedFile]: + return [item for item in self._files.values() if not item.is_new] + + @property + def is_empty(self) -> bool: + return not self._files + + def display(self, path: str) -> str: + """Path relative to the project, with ``/`` separators.""" + shown = path + if self.project_dir: + try: + shown = os.path.relpath(path, self.project_dir) + except ValueError: + shown = path + return shown.replace(os.sep, "/") + + def diff(self, planned: PlannedFile) -> str: + """Unified diff of a modified file, line endings normalised.""" + before = (planned.original or "").replace("\r\n", "\n").splitlines() + after = planned.content.replace("\r\n", "\n").splitlines() + name = self.display(planned.path) + return "\n".join( + difflib.unified_diff( + before, after, fromfile=f"a/{name}", tofile=f"b/{name}", lineterm="" + ) + ) + + # -- output --------------------------------------------------------- + def _changed_since_planning(self) -> List[str]: + """Planned paths whose disk state differs from what planning read.""" + changed: List[str] = [] + for planned in self._files.values(): + if planned.is_new: + if os.path.lexists(planned.path): + changed.append(planned.path) + continue + try: + current = read_text_preserving_newlines(planned.path) + except (OSError, UnicodeDecodeError): + changed.append(planned.path) + continue + if current != (planned.original, planned.newline): + changed.append(planned.path) + return changed + + def apply(self) -> List[str]: + """Write the plan: new files first, then the rewritten ones. + + Before writing, every path is checked against what planning read; a + file created or edited in the meantime (while the confirmation + prompt was open) stops the run with nothing written. When a write + fails partway, the files and directories created so far are removed + and the files already rewritten get their original content back, + then the error is raised. + + :return: Paths written + :raises BackendExceptions: when a file changed since planning + :raises OSError: when writing fails (after the rollback) + """ + changed = self._changed_since_planning() + if changed: + raise BackendExceptions( + "These files changed after the route was planned; nothing was " + "written: " + ", ".join(self.display(path) for path in changed) + ) + for planned in self._files.values(): + self._check_inside(planned.path) + + written: List[str] = [] + created_dirs: List[str] = [] + created_files: List[str] = [] + rewritten: List[PlannedFile] = [] + try: + for planned in self.created: + self._make_parents(os.path.dirname(planned.path), created_dirs) + write_generated_text(planned.path, planned.content) + created_files.append(planned.path) + written.append(planned.path) + for planned in self.modified: + rewritten.append(planned) + write_text_preserving_newlines( + planned.path, planned.content, planned.newline + ) + written.append(planned.path) + except BaseException: + self._roll_back(created_files, created_dirs, rewritten) + raise + for planned in list(self._files.values()): + self._disk[_key(planned.path)] = (planned.content, planned.newline) + self._files.clear() + return written + + @staticmethod + def _make_parents(directory: str, created: List[str]) -> None: + """``os.makedirs`` that records each directory it creates.""" + missing: List[str] = [] + current = directory + while current and not os.path.isdir(current): + missing.append(current) + parent = os.path.dirname(current) + if parent == current: + break + current = parent + for path in reversed(missing): + os.mkdir(path) + created.append(path) + + @staticmethod + def _roll_back( + created_files: List[str], + created_dirs: List[str], + rewritten: List[PlannedFile], + ) -> None: + """Undo a partial :meth:`apply` as far as possible (best effort).""" + for planned in reversed(rewritten): + if planned.original is None: + continue + try: + write_text_preserving_newlines( + planned.path, planned.original, planned.newline + ) + except OSError: + pass + for path in reversed(created_files): + try: + os.remove(path) + except OSError: + pass + for path in reversed(created_dirs): + try: + os.rmdir(path) + except OSError: + pass + + def render(self, echo: Callable[[str], None], show_diff: bool = False) -> None: + """Describe the plan (and, with ``show_diff``, its content).""" + if self.is_empty: + echo("Nothing to change: every file this route needs is already in place.") + for _, message in self.notes: + echo(f"Note: {message}") + return + if self.created: + echo(f"Files to create ({len(self.created)}):") + for planned in self.created: + echo(f" + {self.display(planned.path)}") + if self.modified: + echo(f"Files to modify ({len(self.modified)}):") + for planned in self.modified: + echo(f" ~ {self.display(planned.path)}") + for _, message in self.notes: + echo(f"Note: {message}") + if not show_diff: + return + for planned in self.modified: + echo("") + echo(self.diff(planned)) + for planned in self.created: + name = self.display(planned.path) + echo("") + echo(f"--- /dev/null\n+++ b/{name}") + lines = planned.content.splitlines() + echo(f"@@ -0,0 +1,{len(lines)} @@" if lines else "@@ -0,0 +0,0 @@") + for line in lines: + echo(f"+{line}") + + +__all__ = ["PlannedFile", "RoutePlan"] diff --git a/src/fastapi_fastkit/backend/route_wiring.py b/src/fastapi_fastkit/backend/route_wiring.py index d584a1e..9ba134d 100644 --- a/src/fastapi_fastkit/backend/route_wiring.py +++ b/src/fastapi_fastkit/backend/route_wiring.py @@ -1,14 +1,24 @@ """Router registration helpers.""" import ast +import os from pathlib import Path -from typing import Dict +from typing import Dict, Optional, Sequence, Tuple -from fastapi_fastkit.utils.main import print_info -from fastapi_fastkit.utils.textio import ( - read_text_preserving_newlines, - write_generated_text, - write_text_preserving_newlines, +from fastapi_fastkit.backend.route_plan import RoutePlan +from fastapi_fastkit.utils.main import print_info, print_warning +from fastapi_fastkit.utils.textio import read_text_preserving_newlines + +#: Content of an API router module ``addroute`` has to create. The anchors +#: let the import land in its own isort section and the registration below +#: the router, so the new module is ruff-clean. +NEW_API_ROUTER = ( + "from fastapi import APIRouter\n" + "\n" + "# fastkit:imports\n" + "\n" + "api_router = APIRouter()\n" + "# fastkit:routes\n" ) @@ -31,26 +41,24 @@ def _router_argument(call: ast.Call) -> ast.expr | None: return next((item.value for item in call.keywords if item.arg == "router"), None) -def register_router( - project_layout: Dict[str, str], import_line: str, statement: str +def plan_router_registration( + plan: RoutePlan, + project_layout: Dict[str, str], + import_line: str, + statement: str, ) -> None: - """Register a router in the API router module.""" + """Plan the import and registration of a router in the API router module.""" from fastapi_fastkit.backend.main import insert_import_line, insert_statement_line api_dir = Path(project_layout["api_dir"]) - api_dir.mkdir(parents=True, exist_ok=True) init = api_dir / "__init__.py" - if not init.exists(): - write_generated_text(init, "") - target = Path(project_layout["api_router_file"]) - # A router module created here is generated content (LF); an existing - # one keeps its own line endings. - content, newline = "", "\n" - if target.exists(): - content, newline = read_text_preserving_newlines(target) + if not plan.exists(str(init)): + plan.write(str(init), "") + target = str(project_layout["api_router_file"]) + content = plan.read(target) or "" if not content.strip(): - content = "from fastapi import APIRouter\n\napi_router = APIRouter()\n" + content = NEW_API_ROUTER registration = ast.parse(statement).body[0] existing = None if isinstance(registration, ast.Expr) and isinstance(registration.value, ast.Call): @@ -79,34 +87,46 @@ def register_router( for item in expected.keywords if item.arg != "router" } - if ( - current_options != expected_options - or existing.args[1:] != expected.args[1:] - ): - print_info( - f"Keeping existing router registration in {target} with its current prefix and options." + # Compare the extra positional arguments by structure: AST nodes + # themselves compare by identity, so two equal calls would + # always look different. + if current_options != expected_options or [ + ast.dump(arg) for arg in existing.args[1:] + ] != [ast.dump(arg) for arg in expected.args[1:]]: + plan.note( + f"Keeping existing router registration in {plan.display(target)} " + "with its current prefix and options." ) updated = insert_import_line(content, import_line) if existing is None: updated = insert_statement_line(updated, statement) - if not target.exists() or updated != content: - write_text_preserving_newlines(target, updated, newline) + plan.write(target, updated) -def router_alias(file: str, module: str, name: str, preferred: str) -> str: - """Reuse the router import alias or choose an unused name.""" +def print_plan_notes(plan: RoutePlan) -> None: + """Print the notes a plan collected (kept files, kept registrations).""" + for level, message in plan.notes: + if level == "warning": + print_warning(message) + else: + print_info(message) - target = Path(file) - if not target.exists(): - return preferred - tree = _parse_module(target.read_text(encoding="utf-8")) + +def register_router( + project_layout: Dict[str, str], import_line: str, statement: str +) -> None: + """Register a router in the API router module (plan and apply).""" + plan = RoutePlan() + plan_router_registration(plan, project_layout, import_line, statement) + print_plan_notes(plan) + plan.apply() + + +def _bound_names(tree: ast.Module) -> set[str]: occupied: set[str] = set() for node in tree.body: if isinstance(node, ast.ImportFrom): - for imported in node.names: - if node.module == module and imported.name == name: - return imported.asname or name - occupied.add(imported.asname or imported.name) + occupied.update(item.asname or item.name for item in node.names) elif isinstance(node, ast.Import): occupied.update( item.asname or item.name.split(".")[0] for item in node.names @@ -118,6 +138,56 @@ def router_alias(file: str, module: str, name: str, preferred: str) -> str: occupied.update( target.id for target in targets if isinstance(target, ast.Name) ) + return occupied + + +def existing_router_import( + content: str, modules: Sequence[Tuple[int, str]], name: str +) -> Optional[str]: + """Return the import line already binding ``name`` from one of ``modules``. + + ``modules`` lists equivalent spellings as ``(level, module)`` pairs, e.g. + ``(0, "src.api.routes")`` and ``(1, "routes")`` for ``from .routes``, + so a project wired by an older fastkit keeps its relative import instead + of getting a second binding of the same router. + """ + for node in _parse_module(content).body: + if not isinstance(node, ast.ImportFrom): + continue + if (node.level, node.module or "") not in modules: + continue + for imported in node.names: + if imported.name == name: + module = "." * node.level + (node.module or "") + alias = f" as {imported.asname}" if imported.asname else "" + return f"from {module} import {name}{alias}" + return None + + +def router_alias( + file: str, + module: str, + name: str, + preferred: str, + plan: Optional[RoutePlan] = None, +) -> str: + """Reuse the router import alias or choose an unused name.""" + + if plan is not None: + content = plan.read(file) + else: + content = ( + read_text_preserving_newlines(file)[0] if os.path.isfile(file) else None + ) + if content is None: + return preferred + tree = _parse_module(content) + for node in tree.body: + if isinstance(node, ast.ImportFrom) and node.module == module: + for imported in node.names: + if imported.name == name: + return imported.asname or name + occupied = _bound_names(tree) alias = preferred counter = 2 while alias in occupied: diff --git a/src/fastapi_fastkit/backend/scaffolder.py b/src/fastapi_fastkit/backend/scaffolder.py index 14f3775..01308fc 100644 --- a/src/fastapi_fastkit/backend/scaffolder.py +++ b/src/fastapi_fastkit/backend/scaffolder.py @@ -452,10 +452,14 @@ def _config_generator(self, project_dir: str) -> DynamicConfigGenerator: app_module=self.app_module, main_py_relpath=self.strategist.profile.main_py_relpath, db_config_relpath=self.strategist.profile.db_config_relpath, - auth_config_relpath=self.strategist.profile.auth_config_relpath, - omit_example_routers=self.strategist.skipped_example_labels( - self.options.config or {} + auth_package_relpath=self.strategist.profile.auth_package_relpath, + settings_relpath=self.strategist.profile.settings_relpath, + shipped_paths=( + () + if self.strategist.should_regenerate_main + else self.strategist.profile.shipped_paths ), + provide_pagination=self.strategist.profile.provide_pagination, ) def _generate_dynamic_config( @@ -483,22 +487,20 @@ def _generate_dynamic_config( print_success("Generated Docker deployment files") # Presets that preserve their template's main.py still get the - # generated feature routers mounted through the file's - # ``# fastkit:`` anchors; whatever can't be spliced in safely is - # reported instead so the user knows to wire it up themselves. + # generated features mounted through the file's ``# fastkit:`` + # anchors; whatever can't be spliced in safely is reported instead + # so the user knows to wire it up themselves. wired = self.strategist.wire_generated_routers(project_dir, config) - # Features whose demo router was skipped (the base template already - # serves that collection) are wired without a router, so they are - # explained on their own line instead of listed as routers. - skipped = set(self.strategist.skipped_example_labels(config)) - routers = [label for label in wired if label not in skipped] - if routers: + if wired: print_success( - f"Registered generated routers in " - f"{self.strategist.profile.main_py_relpath}: {', '.join(routers)}" + f"Wired generated features into " + f"{self.strategist.profile.main_py_relpath}: {', '.join(wired)}" ) - for note in self.strategist.skipped_example_notes(config): + for note in self.strategist.generation_notes(config): print_info(note) + self.strategist.append_readme_notes(project_dir, config) + for conflict in self.strategist.auth_route_conflicts(project_dir, config): + print_warning(conflict, title="Authentication routes") # Surface preset-specific warnings (e.g. "you picked a preset whose # shipped main.py we kept; Prometheus must be wired manually"). diff --git a/src/fastapi_fastkit/cli.py b/src/fastapi_fastkit/cli.py index 7ee67c5..7dc10c4 100644 --- a/src/fastapi_fastkit/cli.py +++ b/src/fastapi_fastkit/cli.py @@ -7,7 +7,6 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- import atexit -import keyword import os import subprocess import sys @@ -16,8 +15,11 @@ import click from click import Command, Context from rich import print +from rich.console import Console +from rich.logging import RichHandler from rich.panel import Panel +from fastapi_fastkit.backend.doctor import DoctorOptions, run_doctor from fastapi_fastkit.backend.interactive import InteractiveConfigBuilder from fastapi_fastkit.backend.interactive.selectors import display_feature_catalog from fastapi_fastkit.backend.interactive.validators import validate_project_name @@ -26,7 +28,9 @@ ask_create_project_folder, find_template_core_modules, get_deployment_success_message, + is_within_directory, read_template_stack, + valid_app_module, ) from fastapi_fastkit.backend.project_builder import ( PresetLayoutStrategist, @@ -36,14 +40,17 @@ ConfigSchemaError, normalize_project_config, ) -from fastapi_fastkit.backend.route_generators import resolve_route_layout +from fastapi_fastkit.backend.route_generators import ( + plan_new_route, + resolve_route_names, +) from fastapi_fastkit.backend.scaffolder import ( ProjectScaffolder, ScaffoldCancelled, ScaffoldOptions, cleanup_failed_project, ) -from fastapi_fastkit.core.exceptions import CLIExceptions +from fastapi_fastkit.core.exceptions import BackendExceptions, CLIExceptions from fastapi_fastkit.core.settings import FastkitConfig from fastapi_fastkit.utils.config_file import ( ConfigFileError, @@ -80,6 +87,23 @@ _cleanup_failed_project = cleanup_failed_project +def _stderr_console() -> Console: + """A Rich console writing to stderr (looked up at print time).""" + return Console(stderr=True) + + +def _log_to_stderr() -> None: + """Send fastkit's console log records to stderr. + + Log lines are diagnostics; stdout is kept for command output, which for + ``doctor --format json`` must be the JSON document alone, also with + ``--debug``. + """ + for handler in get_logger().handlers: + if isinstance(handler, RichHandler): + handler.console = _stderr_console() + + class _FastkitGroup(click.Group): """Root command group that makes the console safe before any output. @@ -108,13 +132,16 @@ def fastkit_cli(ctx: Context, debug: bool) -> Union["Command", None]: ctx.ensure_object(dict) if debug: - print_warning("running at debugging mode!!") + # stderr: stdout may carry a machine-readable document + # (``doctor --format json``). + print_warning("running at debugging mode!!", console=_stderr_console()) settings.set_debug_mode() ctx.obj["settings"] = settings # Setup logging and get debug capture if debug mode is enabled debug_capture = setup_logging(settings=settings) + _log_to_stderr() ctx.obj["debug_capture"] = debug_capture # If debug mode is enabled, start capturing output @@ -348,8 +375,10 @@ def _scaffold( is_flag=True, default=False, help=( - "Do not ask for confirmation before overwriting existing files when " - "deploying the project in place." + "Answer yes to the confirmations: create the project without asking " + "and, when deploying in place, overwrite existing files. The " + "project-folder question is still asked; without a terminal and with " + "no answer piped in, the project goes into a new folder." ), ) @click.pass_context @@ -368,6 +397,17 @@ def startdemo( ) -> None: """ Create a new FastAPI project from templates and inject metadata. + + Exits with status 1 when it refuses to run (unknown template, invalid + project name, existing project directory, in-place overwrite without a + terminal or --yes) or generation fails. Declining a confirmation prompt + exits with status 0. + + \b + Non-interactive use: + fastkit startdemo fastapi-default --project-name demo --author me \\ + --author-email me@example.com --description demo \\ + --package-manager uv -y None: """ Add a new route to the FastAPI project. - Examples:\n - fastkit addroute user . # Add 'user' route to current directory - fastkit addroute user my_project # Add 'user' route to 'my_project' in workspace + ROUTE_NAME is lower-case ASCII (letters, digits, underscores, starting + with a letter); it names the modules and the URL segment. A route whose + files already exist, or one named like an existing module of the + project, is refused. + + \b + Examples: + fastkit addroute orders . # Add 'orders' to the current directory + fastkit addroute orders my_project # Add 'orders' to 'my_project' in workspace + fastkit addroute orders . --diff # Preview the change without writing + + Exits with status 1 when it refuses to run (missing project directory, + not a fastkit project, invalid route name or --entity, existing route) + or planning or writing the route fails; a failed write is rolled back. + Declining the confirmation prompt and a preview (--dry-run / --diff) + exit with status 0. """ settings = ctx.obj["settings"] + preview = dry_run or show_diff + + # The route name and --entity are checked before anything else, with a + # plain one-line error. + try: + resolve_route_names(route_name, entity) + except BackendExceptions as e: + print_error(str(e)) + ctx.exit(1) if project_dir == ".": actual_project_dir = os.getcwd() @@ -930,7 +1038,7 @@ def addroute( print_error( f"Project '{project_dir}' does not exist in '{settings.USER_WORKSPACE}'." ) - return + ctx.exit(1) # Verify it's a fastkit project if not is_fastkit_project(actual_project_dir): @@ -938,33 +1046,38 @@ def addroute( print_error("Current directory is not a FastAPI-fastkit project.") else: print_error(f"'{project_dir}' is not a FastAPI-fastkit project.") - return - - # Validate route name - if not route_name.isidentifier(): - print_error(f"Route name '{route_name}' is not a valid Python identifier.") - return + ctx.exit(1) - # Route name shouldn't match reserved keywords - if keyword.iskeyword(route_name): - print_error( - f"Route name '{route_name}' is a Python keyword and cannot be used." + try: + # Every file is computed before anything is written; the preview and + # the real run render / apply the same plan. + plan = plan_new_route( + actual_project_dir, route_name, layout=layout, entity=entity ) - return + except (BackendExceptions, OSError, UnicodeDecodeError) as e: + _addroute_failed(f"Error during route addition: {e}", e, settings) + ctx.exit(1) try: - route_layout = resolve_route_layout(actual_project_dir, layout) - # Show information about the operation table = create_info_table( "Adding New Route", { "Project": project_name, "Route Name": route_name, - "Layout": route_layout, + **plan.details, "Target Directory": actual_project_dir, }, ) console.print(table) + plan.render(click.echo, show_diff=show_diff) + + if preview: + print_info("Dry run: no files were written.") + return + + if plan.is_empty: + print_info(f"Route '{route_name}' is already in place; nothing to do.") + return if project_dir == ".": confirm_message = ( @@ -979,7 +1092,7 @@ def addroute( return # Add the new route - add_new_route(actual_project_dir, route_name, layout=route_layout) + add_new_route(actual_project_dir, route_name, plan=plan) if project_dir == ".": print_success( @@ -990,10 +1103,25 @@ def addroute( f"Successfully added new route '{route_name}' to project '{project_name}'!" ) + except click.exceptions.Abort: + # click.confirm without a terminal (stdin closed) cannot ask; that is + # not a success, and click reports "Aborted!" with status 1. + raise + except (BackendExceptions, OSError) as e: + _addroute_failed(f"Error during route addition: {e}", e, settings) + ctx.exit(1) + except click.exceptions.Exit: + raise except Exception as e: - logger = get_logger() - logger.exception(f"Error during route addition: {str(e)}") - print_error(f"Error during route addition: {str(e)}") + _addroute_failed(f"Error during route addition: {e}", e, settings) + ctx.exit(1) + + +def _addroute_failed(message: str, error: BaseException, settings: Any) -> None: + """Print one plain error line; the traceback only goes to the debug log.""" + if getattr(settings, "DEBUG_MODE", False): + get_logger().debug("addroute failed", exc_info=error) + print_error(message) @fastkit_cli.command() @@ -1035,6 +1163,107 @@ def deleteproject(ctx: Context, project_name: str) -> None: print_error(f"Error during project deletion: {e}") +@fastkit_cli.command() +@click.argument("path", default=".", type=click.Path(file_okay=False)) +@click.option( + "--fix", + is_flag=True, + default=False, + help=( + "Apply the safe fixes: show every change as a diff first, then ask " + "once. Advisory problems are never changed automatically." + ), +) +@click.option( + "--dry-run", + "--diff", + "dry_run", + is_flag=True, + default=False, + help="Show the changes --fix would make, without writing anything. Implies --fix.", +) +@click.option( + "--yes", + "-y", + "assume_yes", + is_flag=True, + default=False, + help="Apply --fix changes without asking (required without a terminal).", +) +@click.option( + "--format", + "output_format", + type=click.Choice(["text", "json"]), + default="text", + show_default=True, + help="Output format. json prints only the JSON document on stdout.", +) +@click.option( + "--force", + is_flag=True, + default=False, + help=( + "Check a project without [tool.fastapi-fastkit] metadata (generated " + "before fastkit 1.4.0, or not by fastkit). Checks that need the " + "metadata are skipped." + ), +) +@click.pass_context +def doctor( + ctx: Context, + path: str, + fix: bool, + dry_run: bool, + assume_yes: bool, + output_format: str, + force: bool, +) -> None: + """ + Check a generated project for known problems and fix the safe ones. + + Looks for the problems newer fastkit versions fixed in their templates: + a committed or unignored .env, example SECRET_KEYs, an unauthenticated + MCP server, CORS "*" with credentials, CRLF shell scripts, plain + sqlalchemy without greenlet, and more. Never prints secret values. + + PATH is the project directory (default: the current directory). + + Exit status: 0 no problem found (or all fixed), 1 problems remain, + 2 doctor could not run (not a fastkit project, unreadable project, a + check failed, or --fix without --yes and without a terminal). + + \b + --format json prints one JSON document (schema_version 1): + schema_version, fastkit_version, + project {path, template, preset, generated_with, app_module, + has_metadata}, + summary {problems, fixable, by_severity {high, medium, low}, + checks {ok, problem, skipped, error}}, + checks [{id, title, severity, status, fixable, note}], + findings [{check, severity, title, message, files, fixable, + remediation}], + fix null, or {dry_run, planned [{path, check, summary, + new_file, diff}], applied [path], failed [{path, reason}]}, + exit_code + When doctor cannot run: {schema_version, fastkit_version, error, + exit_code}. With json, --fix needs --yes or --dry-run. + """ + settings = ctx.obj["settings"] + exit_code = run_doctor( + DoctorOptions( + path=path, + fix=fix, + dry_run=dry_run, + assume_yes=assume_yes, + output_format=output_format, + force=force, + template_root=settings.FASTKIT_TEMPLATE_ROOT, + ), + console=console, + ) + ctx.exit(exit_code) + + def _derive_app_module(project_dir: str, main_path: str) -> str: """Convert a discovered ``main.py`` path into a uvicorn ``module:attr``. @@ -1055,13 +1284,35 @@ def _resolve_runserver_app_module(project_dir: str) -> str: on-disk scan cannot rank. Discovery is the fallback for projects created before the metadata contract existed. + The recorded value is untrusted (it comes from ``pyproject.toml``): it + must be a dotted ``package.module[:attr]`` (so it can neither name a + path nor smuggle extra uvicorn options) and, when its file exists, that + file must resolve inside the project. A recorded module whose file does + not exist falls back to discovery. + :param project_dir: Path to the project directory :return: ``module:attr`` string, or an empty string when no entrypoint exists + :raises CLIExceptions: The recorded ``app_module`` is invalid or points + outside the project """ - recorded = read_fastkit_metadata(project_dir).get("app_module") - if isinstance(recorded, str) and recorded: - module_path = recorded.split(":")[0].replace(".", os.sep) - if os.path.exists(os.path.join(project_dir, f"{module_path}.py")): + metadata = read_fastkit_metadata(project_dir) + recorded = metadata.get("app_module") + if "app_module" in metadata and recorded != "": + if not isinstance(recorded, str) or not valid_app_module(recorded): + raise CLIExceptions( + f"Invalid app_module {recorded!r} in [tool.fastapi-fastkit] of " + "pyproject.toml: expected a dotted module path such as " + "'src.main:app'." + ) + recorded = recorded.strip() + module = recorded.split(":", 1)[0] + candidate = os.path.join(project_dir, *module.split(".")) + ".py" + if os.path.isfile(candidate): + if not is_within_directory(candidate, project_dir): + raise CLIExceptions( + f"app_module {recorded!r} in [tool.fastapi-fastkit] resolves " + "outside the project directory." + ) return recorded main_path = find_template_core_modules(project_dir).get("main", "") @@ -1137,7 +1388,11 @@ def runserver( return interpreter = None - app_module = _resolve_runserver_app_module(project_dir) + try: + app_module = _resolve_runserver_app_module(project_dir) + except CLIExceptions as error: + print_error(str(error)) + ctx.exit(1) if not app_module: print_error(f"Could not find 'main.py' in '{project_dir}'.") return diff --git a/src/fastapi_fastkit/core/settings.py b/src/fastapi_fastkit/core/settings.py index 0455e03..37e2d78 100644 --- a/src/fastapi_fastkit/core/settings.py +++ b/src/fastapi_fastkit/core/settings.py @@ -265,7 +265,11 @@ class FastkitConfig: # ``asyncio`` extra, and 2.0 skipped it on some platforms (macOS arm64). DatabaseChoice.POSTGRESQL: ["asyncpg", "sqlalchemy[asyncio]"], DatabaseChoice.MYSQL: ["aiomysql", "sqlalchemy[asyncio]"], - DatabaseChoice.MONGODB: ["motor"], + # PyMongo's native asyncio client (AsyncMongoClient, PyMongo 4.13+) + # replaces Motor, which MongoDB deprecated on 2026-05-14. The + # floor keeps an older environment or constraint file from + # resolving to a release without it (or with the beta API). + DatabaseChoice.MONGODB: ["pymongo>=4.13"], # ``aioredis`` is abandoned (merged into redis-py) and does not # install on Python 3.12 — redis[hiredis] ships the asyncio client. DatabaseChoice.REDIS: ["redis[hiredis]"], @@ -273,15 +277,23 @@ class FastkitConfig: DatabaseChoice.NONE: [], }, FeatureAxis.AUTHENTICATION: { - AuthChoice.JWT: ["pyjwt[crypto]", "pwdlib[argon2]"], - # SessionMiddleware (used by the OAuth2 login flow) needs itsdangerous. - AuthChoice.OAUTH2: ["authlib", "itsdangerous", "httpx"], - AuthChoice.FASTAPI_USERS: [ - "fastapi-users[sqlalchemy]", + # OAuth2PasswordRequestForm needs python-multipart; EmailStr needs + # email-validator. PyJWT signs the tokens, pwdlib hashes (argon2). + AuthChoice.JWT: [ "pyjwt[crypto]", "pwdlib[argon2]", + "email-validator", + "python-multipart", ], - AuthChoice.SESSION: ["itsdangerous"], + # SessionMiddleware (used by the OAuth2 login flow) needs itsdangerous. + # Authlib talks to the providers through httpx2 (it falls back to + # httpx with an AuthlibDeprecationWarning), and the generated router + # catches httpx2's errors, so httpx2 is what gets installed. + AuthChoice.OAUTH2: ["authlib", "itsdangerous", "httpx2"], + # The generated module targets the FastAPI-Users 15 API (it pins + # pwdlib, PyJWT and python-multipart itself). SQL databases only. + AuthChoice.FASTAPI_USERS: ["fastapi-users[sqlalchemy]>=15.0.5,<16"], + AuthChoice.SESSION: ["itsdangerous", "pwdlib[argon2]", "email-validator"], AuthChoice.NONE: [], }, FeatureAxis.ASYNC_TASKS: { @@ -290,18 +302,23 @@ class FastkitConfig: AsyncTaskChoice.NONE: [], }, FeatureAxis.TESTING: { - TestingChoice.BASIC: ["pytest", "pytest-asyncio", "httpx"], + # Starlette's TestClient is built on httpx2 and warns when it has to + # fall back to httpx; httpx stays for tests that use its + # AsyncClient / ASGITransport directly. + TestingChoice.BASIC: ["pytest", "pytest-asyncio", "httpx", "httpx2"], TestingChoice.COVERAGE: [ "pytest", "pytest-asyncio", "pytest-cov", "httpx", + "httpx2", ], TestingChoice.ADVANCED: [ "pytest", "pytest-asyncio", "pytest-cov", "httpx", + "httpx2", "faker", "factory-boy", ], @@ -329,8 +346,15 @@ class FastkitConfig: }, FeatureAxis.UTILITIES: { UtilityChoice.CORS: [], # Built-in to FastAPI - UtilityChoice.RATE_LIMITING: ["slowapi"], - UtilityChoice.PAGINATION: ["fastapi-pagination"], + # The generated middleware uses ``limits`` directly: slowapi's + # SlowAPIMiddleware skips routes added with include_router. It + # needs ``limits.aio`` and ``WindowStats.reset_time``; 3.4 is the + # first release where that works on Python 3.12 (older ones + # import ``pkg_resources``). + UtilityChoice.RATE_LIMITING: ["limits>=3.4"], + # Pagination is built into the generated list endpoints + # (core/pagination.py); kept selectable for saved configs. + UtilityChoice.PAGINATION: [], UtilityChoice.WEBSOCKET: ["websockets"], UtilityChoice.NONE: [], }, diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.env.example-tpl index c9d6bec..50c60cb 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.env.example-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.env.example-tpl @@ -1 +1,11 @@ +# .env.example keeps a public placeholder; fastkit writes a unique key to the +# local, git-ignored .env. With any ENVIRONMENT other than development +# (staging or production) the app refuses to start when SECRET_KEY is unset, +# a public example value or shorter than 32 bytes. SECRET_KEY=changethis +# One of: development, staging, production. +# ENVIRONMENT=development +# API_V1_PREFIX=/api/v1 +# Allowed browser origins, comma-separated or a JSON list. "*" allows any +# origin, but then without credentials (cookies, Authorization headers): +# BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl index 2edd9e6..d1b4356 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl @@ -19,28 +19,32 @@ A FastAPI-based item management API implemented with asynchronous processing. ``` . ├── README.md +├── pyproject.toml ├── requirements.txt -├── setup.py ├── scripts -│   └── run-server.sh +│ └── run-server.sh ├── src -│   ├── main.py -│   ├── schemas -│   │   └── items.py -│   ├── mocks -│   │   └── mock_items.json -│   ├── crud -│   │   └── items.py -│   ├── core -│   │   └── config.py -│   └── api -│   ├── api.py -│   └── routes -│   └── items.py +│ ├── main.py +│ ├── schemas +│ │ └── items.py +│ ├── mocks +│ │ └── mock_items.json +│ ├── crud +│ │ └── items.py +│ ├── core +│ │ ├── config.py +│ │ ├── pagination.py +│ │ └── responses.py +│ └── api +│ ├── api.py +│ ├── deps.py +│ └── routes +│ └── items.py └── tests ├── __init__.py + ├── conftest.py ├── test_items.py - └── conftest.py + └── test_main.py ``` ## How to Run @@ -74,22 +78,34 @@ http://127.0.0.1:8000/docs ## API Endpoints -| Method | Endpoint | Description | -|--------|------------------|----------------------------| -| GET | `/items/` | List all items | -| GET | `/items/{id}` | Get single item | -| POST | `/items/` | Create new item | -| PUT | `/items/{id}` | Update existing item | -| DELETE | `/items/{id}` | Delete item | +Business routes are mounted under `API_V1_PREFIX` (default `/api/v1`). + +| Method | Endpoint | Status | Description | +|--------|--------------------------|--------|-----------------------------------------------| +| GET | `/health` | 200 | Liveness probe, returns `{"status": "ok"}` | +| GET | `/api/v1/items` | 200 | List items (`limit` 1-100, default 20; `offset`) | +| POST | `/api/v1/items` | 201 | Create an item (`Location` header points to it) | +| GET | `/api/v1/items/{id}` | 200 | Get one item | +| PUT | `/api/v1/items/{id}` | 200 | Replace an item (all fields required) | +| PATCH | `/api/v1/items/{id}` | 200 | Update only the fields sent | +| DELETE | `/api/v1/items/{id}` | 204 | Delete an item | + +The list endpoint returns a page: `{"items": [...], "total": 2, "limit": 20, "offset": 0}`. +A missing item answers 404 with `{"detail": "Item not found"}`. ## Key Features -- Async file I/O operations using aiofiles +- Async file I/O with aiofiles (file calls run in a worker thread; an `asyncio.Lock` guards read-modify-write) - Mock data initialization - Pydantic model validation - CRUD operations implementation -- Integrated test cases -- In-memory JSON database for development +- Integrated async test cases (pytest-asyncio, temporary data file, never `src/mocks`) +- CORS enabled only for the origins listed in `BACKEND_CORS_ORIGINS` (`*` allows any + origin, but then without credentials such as cookies or `Authorization` headers) +- Any `ENVIRONMENT` other than `development` (`staging`, `production`) refuses to + start unless `SECRET_KEY` is set explicitly, is at least 32 bytes long and is not + a public example value +- JSON file store for development (`src/mocks/mock_items.json`) ## Running Tests diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/pyproject.toml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/pyproject.toml-tpl index 25c3795..bd93ecd 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/pyproject.toml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/pyproject.toml-tpl @@ -13,7 +13,6 @@ dependencies = [ "uvicorn[standard]>=0.52.4", "pydantic>=2.13.5", "pydantic-settings>=2.15.0", - "SQLAlchemy>=2.0.52", "python-dotenv>=1.2.3", "aiofiles>=25.1.0", ] @@ -26,7 +25,6 @@ dev = [ "black>=26.10.1", "isort>=9.0.1", "mypy>=2.3.1", - "PyYAML>=6.0.3", ] [dependency-groups] @@ -37,7 +35,6 @@ dev = [ "black>=26.10.1", "isort>=9.0.1", "mypy>=2.3.1", - "PyYAML>=6.0.3", ] [tool.fastapi-fastkit] @@ -86,3 +83,4 @@ python_classes = ["Test*"] python_functions = ["test_*"] addopts = "-v --tb=short" asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/requirements.txt-tpl index 5a5f1e1..a1c5f5a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/requirements.txt-tpl @@ -1,7 +1,7 @@ aiofiles==25.1.0 annotated-doc==0.0.5 annotated-types==0.8.0 -anyio==4.15.0 +anyio==4.16.0 ast-serialize==0.9.0 black==26.10.1 certifi==2026.10.23 @@ -30,8 +30,7 @@ pytest-asyncio==1.4.0 python-dotenv==1.2.3 pytokens==0.4.1 PyYAML==6.0.3 -SQLAlchemy==2.0.52 -starlette==1.6.0 +starlette==1.10.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/setup.cfg-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/setup.cfg-tpl deleted file mode 100644 index 5bd6e8f..0000000 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/setup.cfg-tpl +++ /dev/null @@ -1,14 +0,0 @@ -[mypy] -warn_unused_configs = true -ignore_missing_imports = true - -[isort] -profile = black -line_length=100 -virtual_env=venv - -[tool:pytest] -testpaths = tests -addopts = -ra -q -asyncio_mode = auto -asyncio_default_fixture_loop_scope=session diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/deps.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/deps.py-tpl new file mode 100644 index 0000000..39c53bd --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/deps.py-tpl @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------- +# Shared route dependencies +# -------------------------------------------------------------------------- +from typing import Annotated + +from fastapi import Depends + +from src.crud.items import ItemStore, item_store + + +def get_item_store() -> ItemStore: + """Return the item store (tests override this dependency).""" + return item_store + + +ItemStoreDep = Annotated[ItemStore, Depends(get_item_store)] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/routes/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/routes/items.py-tpl index 224ebd7..2cae742 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/routes/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/routes/items.py-tpl @@ -1,56 +1,77 @@ # -------------------------------------------------------------------------- # Item CRUD Endpoint # -------------------------------------------------------------------------- +from fastapi import APIRouter, HTTPException, Request, Response, status -from fastapi import APIRouter, HTTPException +from src.api.deps import ItemStoreDep +from src.core.pagination import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from src.core.responses import error_responses +from src.schemas.items import ItemCreate, ItemRead, ItemUpdate -from src.crud.items import read_items, write_items -from src.schemas.items import ItemCreate, ItemResponse +router = APIRouter(prefix="/items", tags=["items"]) -router = APIRouter() +def item_not_found() -> HTTPException: + return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found") -@router.get("/items", response_model=list[ItemResponse]) -async def read_all_items(): - return await read_items() +@router.get("") +async def list_items( + store: ItemStoreDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> Page[ItemRead]: + items, total = await store.list_page(offset=offset, limit=limit) + return Page[ItemRead]( + items=[ItemRead.model_validate(item) for item in items], + total=total, + limit=limit, + offset=offset, + ) -@router.get("/items/{item_id}", response_model=ItemResponse) -async def read_item(item_id: int): - items = await read_items() - item = next((i for i in items if i["id"] == item_id), None) - if not item: - raise HTTPException(status_code=404, detail="Item not found") - return item +@router.get("/{item_id}", responses=error_responses(404)) +async def get_item(item_id: int, store: ItemStoreDep) -> ItemRead: + item = await store.get(item_id) + if item is None: + raise item_not_found() + return ItemRead.model_validate(item) -@router.post("/items", response_model=ItemResponse, status_code=201) -async def create_item(item: ItemCreate): - items = await read_items() - new_id = max(i["id"] for i in items) + 1 if items else 1 - new_item = {**item.model_dump(), "id": new_id} - items.append(new_item) - await write_items(items) - return new_item +@router.post("", status_code=status.HTTP_201_CREATED) +async def create_item( + payload: ItemCreate, request: Request, response: Response, store: ItemStoreDep +) -> ItemRead: + item = await store.create(payload.model_dump()) + response.headers["Location"] = str(request.url_for("get_item", item_id=item["id"])) + return ItemRead.model_validate(item) -@router.put("/items/{item_id}", response_model=ItemResponse) -async def update_item(item_id: int, item: ItemCreate): - items = await read_items() - index = next((i for i, v in enumerate(items) if v["id"] == item_id), None) - if index is None: - raise HTTPException(status_code=404, detail="Item not found") - updated_item = {**item.model_dump(), "id": item_id} - items[index] = updated_item - await write_items(items) - return updated_item +@router.put("/{item_id}", responses=error_responses(404)) +async def replace_item( + item_id: int, payload: ItemCreate, store: ItemStoreDep +) -> ItemRead: + item = await store.replace(item_id, payload.model_dump()) + if item is None: + raise item_not_found() + return ItemRead.model_validate(item) -@router.delete("/items/{item_id}") -async def delete_item(item_id: int): - items = await read_items() - new_items = [i for i in items if i["id"] != item_id] - if len(new_items) == len(items): - raise HTTPException(status_code=404, detail="Item not found") - await write_items(new_items) - return {"message": "Item deleted successfully"} + +@router.patch("/{item_id}", responses=error_responses(404)) +async def update_item( + item_id: int, payload: ItemUpdate, store: ItemStoreDep +) -> ItemRead: + item = await store.update(item_id, payload.model_dump(exclude_unset=True)) + if item is None: + raise item_not_found() + return ItemRead.model_validate(item) + + +@router.delete( + "/{item_id}", + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(404), +) +async def delete_item(item_id: int, store: ItemStoreDep) -> None: + if not await store.delete(item_id): + raise item_not_found() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/config.py-tpl index a22e29a..ca0f5a5 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/config.py-tpl @@ -1,20 +1,64 @@ # -------------------------------------------------------------------------- # Configuration module # -------------------------------------------------------------------------- +import json import secrets import warnings -from typing import Annotated, Any, Literal, Self +from typing import Annotated, Any, Literal from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator -from pydantic_settings import BaseSettings, SettingsConfigDict +from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict -def parse_cors(v: Any) -> list[str] | str: - if isinstance(v, str) and not v.startswith("["): - return [i.strip() for i in v.split(",")] - elif isinstance(v, (list, str)): - return v - raise ValueError(v) +def parse_cors(value: Any) -> Any: + """Read origins from a comma-separated string or a JSON list. + + Blank entries are dropped, so ``BACKEND_CORS_ORIGINS=`` or a trailing + comma never turns into an empty origin. + """ + if isinstance(value, str): + value = value.strip() + if value.startswith("["): + value = json.loads(value) + else: + value = value.split(",") + if isinstance(value, list): + return [str(origin).strip() for origin in value if str(origin).strip()] + raise ValueError(value) + + +# Each origin is a full URL such as http://localhost:3000, or "*" for any +# origin. "*" never goes together with credentials (cookies, Authorization +# headers): browsers refuse that, so main.py turns credentials off for it. +CorsOrigins = Annotated[ + list[Literal["*"] | AnyUrl], NoDecode, BeforeValidator(parse_cors) +] + +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + "your-secret-key-here", + "change-me-in-production", + "your-mcp-api-key-here", + } +) + +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = 32 + +_GENERATE_KEY_HINT = ( + "Generate one with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) class Settings(BaseSettings): @@ -24,40 +68,63 @@ class Settings(BaseSettings): extra="ignore", ) + PROJECT_NAME: str = "" + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + # The shipped code signs nothing with SECRET_KEY yet, but authentication + # you add later (including the JWT and Session options of fastkit init) + # signs tokens or cookies with it, so treat it as a production secret. + # fastkit writes a unique value to .env; staging and production refuse a + # missing, public or short key (see _check_secret_key below). SECRET_KEY: str = secrets.token_urlsafe(32) - ENVIRONMENT: Literal["development", "production"] = "development" - CLIENT_ORIGIN: str = "" + # Every business router is mounted under this prefix (see src/main.py). + API_V1_PREFIX: str = "/api/v1" - BACKEND_CORS_ORIGINS: Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] = ( - [] - ) + BACKEND_CORS_ORIGINS: CorsOrigins = [] @computed_field # type: ignore[prop-decorator] @property def all_cors_origins(self) -> list[str]: - return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + [ - self.CLIENT_ORIGIN - ] - - PROJECT_NAME: str = "" - - def _check_default_secret(self, var_name: str, value: str | None) -> None: - if value == "changethis": - message = ( - f'The value of {var_name} is "changethis", ' - "for security, please change it, at least for deployments." - ) - if self.ENVIRONMENT == "development": - warnings.warn(message, stacklevel=1) - else: - raise ValueError(message) + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins @model_validator(mode="after") - def _enforce_non_default_secrets(self) -> Self: - self._check_default_secret("SECRET_KEY", self.SECRET_KEY) + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) + return self + env = f"ENVIRONMENT={self.ENVIRONMENT}" + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT + ) + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: + raise ValueError( + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT + ) return self -settings = Settings() # type: ignore +settings = Settings() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/pagination.py-tpl new file mode 100644 index 0000000..2688822 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/pagination.py-tpl @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------- +# Limit/offset pagination shared by every list endpoint. +# +# List endpoints take ``limit: LimitParam = DEFAULT_LIMIT`` and +# ``offset: OffsetParam = 0`` and return a ``Page[T]`` envelope: +# {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range +# values are rejected with a 422 rather than clamped. +# -------------------------------------------------------------------------- +from typing import Annotated, Generic, TypeVar + +from fastapi import Query +from pydantic import BaseModel + +T = TypeVar("T") + +#: Page size used when the client sends no ``limit``. +DEFAULT_LIMIT = 20 +#: Largest page a client may ask for. +MAX_LIMIT = 100 + +LimitParam = Annotated[ + int, Query(ge=1, le=MAX_LIMIT, description="Maximum number of items to return.") +] +OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] + + +class Page(BaseModel, Generic[T]): + """One page of a collection, ordered by primary key. + + ``total`` counts the whole collection, so a client knows there is a next + page while ``offset + len(items) < total``. + """ + + items: list[T] + total: int + limit: int + offset: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/responses.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/responses.py-tpl new file mode 100644 index 0000000..bffc8c1 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/responses.py-tpl @@ -0,0 +1,40 @@ +# -------------------------------------------------------------------------- +# OpenAPI error responses shared by the routers. +# +# FastAPI documents 2xx and 422 on its own. Routes that can also answer 401, +# 404, 409, ... declare it with ``responses=error_responses(404)`` so clients +# see every status code and the ``{"detail": "..."}`` body in the schema. +# -------------------------------------------------------------------------- +from http import HTTPStatus +from typing import Any + +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + """Body FastAPI sends for an ``HTTPException``.""" + + detail: str + + +def error_responses(*status_codes: int) -> dict[int | str, dict[str, Any]]: + """Build ``responses=`` entries that document the given error codes. + + A 401 entry also documents the ``WWW-Authenticate`` header every 401 + response carries. + """ + responses: dict[int | str, dict[str, Any]] = {} + for code in status_codes: + entry: dict[str, Any] = { + "model": ErrorDetail, + "description": HTTPStatus(code).phrase, + } + if code == HTTPStatus.UNAUTHORIZED: + entry["headers"] = { + "WWW-Authenticate": { + "description": "Authentication scheme to use (Bearer).", + "schema": {"type": "string"}, + } + } + responses[code] = entry + return responses diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/crud/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/crud/items.py-tpl index d2b6034..a7acf66 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/crud/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/crud/items.py-tpl @@ -1,20 +1,136 @@ # -------------------------------------------------------------------------- -# Item CRUD method module +# Item CRUD method module (async) +# +# Items live in a JSON file. aiofiles runs the blocking file calls in a +# worker thread, so the event loop keeps serving other requests while a file +# is read or written. Handlers await between reading and writing the file, +# so an asyncio.Lock serialises every access: without it two requests could +# hand out the same id or lose a write. +# +# The file keeps the next id next to the items, so an id is never handed out +# twice: not after the item with the highest id is deleted, and not after a +# restart. Every write goes to a temporary file that then replaces the data +# file in one step (run in a worker thread with asyncio.to_thread), so a +# crash mid-write leaves the previous file intact. The lock covers one +# process only; with several workers, use a database. # -------------------------------------------------------------------------- +import asyncio +import contextlib import json import os +import tempfile +from collections.abc import Callable +from pathlib import Path +from typing import Any -import aiofiles # type: ignore +import aiofiles # type: ignore[import-untyped] -MOCK_FILE = os.path.join(os.path.dirname(__file__), "../mocks/mock_items.json") +MOCK_FILE = Path(__file__).resolve().parent.parent / "mocks" / "mock_items.json" +ItemData = dict[str, Any] -async def read_items(): - async with aiofiles.open(MOCK_FILE, mode="r") as file: - contents = await file.read() - return json.loads(contents) +def _parse(data: Any) -> tuple[list[ItemData], int]: + """Return the stored items ordered by id and the next id to hand out. -async def write_items(items: list[dict]): - async with aiofiles.open(MOCK_FILE, mode="w") as file: - await file.write(json.dumps(items, indent=2)) + Older data files, like the shipped mock data, are a plain list of items; + for those the next id continues after the highest id in the file. + """ + if isinstance(data, list): + items: list[ItemData] = data + next_id = 1 + else: + items = data["items"] + next_id = int(data.get("next_id", 1)) + items = sorted(items, key=lambda item: item["id"]) + highest = max((item["id"] for item in items), default=0) + return items, max(next_id, highest + 1) + + +def _dump(items: list[ItemData], next_id: int) -> str: + return json.dumps({"next_id": next_id, "items": items}, indent=2) + "\n" + + +def _write_atomic(path: Path, text: str) -> None: + """Replace ``path`` with ``text``; readers see the old or the new file.""" + fd, temp_name = tempfile.mkstemp( + dir=path.parent, prefix=f".{path.name}.", suffix=".tmp" + ) + try: + with os.fdopen(fd, "w", encoding="utf-8") as file: + file.write(text) + file.flush() + os.fsync(file.fileno()) + # The temporary file is closed before the rename, as Windows requires. + os.replace(temp_name, path) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(temp_name) + raise + + +class ItemStore: + """Item persistence backed by one JSON file, accessed asynchronously.""" + + def __init__(self, path: Path) -> None: + self.path = path + self._lock = asyncio.Lock() + + async def _load(self) -> tuple[list[ItemData], int]: + async with aiofiles.open(self.path, encoding="utf-8") as file: + contents: str = await file.read() + return _parse(json.loads(contents)) + + async def _save(self, items: list[ItemData], next_id: int) -> None: + await asyncio.to_thread(_write_atomic, self.path, _dump(items, next_id)) + + async def list_page(self, offset: int, limit: int) -> tuple[list[ItemData], int]: + """Return one page of items ordered by id, plus the total count.""" + async with self._lock: + items, _ = await self._load() + return items[offset : offset + limit], len(items) + + async def get(self, item_id: int) -> ItemData | None: + async with self._lock: + items, _ = await self._load() + return next((item for item in items if item["id"] == item_id), None) + + async def create(self, data: ItemData) -> ItemData: + async with self._lock: + items, next_id = await self._load() + item = {**data, "id": next_id} + items.append(item) + await self._save(items, next_id + 1) + return item + + async def replace(self, item_id: int, data: ItemData) -> ItemData | None: + return await self._modify(item_id, lambda current: {**data, "id": item_id}) + + async def update(self, item_id: int, changes: ItemData) -> ItemData | None: + return await self._modify( + item_id, lambda current: {**current, **changes, "id": item_id} + ) + + async def delete(self, item_id: int) -> bool: + async with self._lock: + items, next_id = await self._load() + remaining = [item for item in items if item["id"] != item_id] + if len(remaining) == len(items): + return False + await self._save(remaining, next_id) + return True + + async def _modify( + self, item_id: int, change: Callable[[ItemData], ItemData] + ) -> ItemData | None: + async with self._lock: + items, next_id = await self._load() + for index, current in enumerate(items): + if current["id"] == item_id: + items[index] = change(current) + await self._save(items, next_id) + return items[index] + return None + + +item_store = ItemStore(MOCK_FILE) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/main.py-tpl index 28449fc..e9aa39f 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/main.py-tpl @@ -14,21 +14,24 @@ app = FastAPI( title=settings.PROJECT_NAME, ) +# Origins come only from BACKEND_CORS_ORIGINS; with none configured the +# middleware is not installed at all. if settings.all_cors_origins: app.add_middleware( CORSMiddleware, allow_origins=settings.all_cors_origins, - allow_credentials=True, + # Browsers refuse credentials with the "*" wildcard; never send both. + allow_credentials="*" not in settings.all_cors_origins, allow_methods=["*"], allow_headers=["*"], ) # fastkit:routes -app.include_router(api_router) +app.include_router(api_router, prefix=settings.API_V1_PREFIX) -@app.get("/health") +@app.get("/health", tags=["health"]) async def health_check() -> dict[str, str]: - """Health check endpoint.""" - return {"status": "healthy"} + """Liveness probe: no authentication and no I/O.""" + return {"status": "ok"} diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/schemas/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/schemas/items.py-tpl index 859f4ef..13cc7fb 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/schemas/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/schemas/items.py-tpl @@ -1,21 +1,41 @@ # -------------------------------------------------------------------------- # Item schema module # -------------------------------------------------------------------------- - -from pydantic import BaseModel, ConfigDict +from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator class ItemBase(BaseModel): - name: str - description: str | None = None - price: float - category: str + name: str = Field(min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=1000) + price: float = Field(ge=0) + category: str = Field(min_length=1, max_length=50) class ItemCreate(ItemBase): - pass + """POST and PUT body: every required field must be sent.""" -class ItemResponse(ItemBase): - id: int +class ItemUpdate(BaseModel): + """PATCH body: send only the fields to change. + + ``description`` can be cleared with an explicit ``null``; the other + fields are required on an item, so ``null`` is rejected for them. + """ + + name: str | None = Field(default=None, min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=1000) + price: float | None = Field(default=None, ge=0) + category: str | None = Field(default=None, min_length=1, max_length=50) + + @field_validator("name", "price", "category") + @classmethod + def _reject_null(cls, value: object, info: ValidationInfo) -> object: + if value is None: + raise ValueError(f"{info.field_name} must not be null") + return value + + +class ItemRead(ItemBase): model_config = ConfigDict(from_attributes=True) + + id: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/conftest.py-tpl index 4102990..dfffbc4 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/conftest.py-tpl @@ -1,41 +1,39 @@ # -------------------------------------------------------------------------- # pytest runtime configuration module # -------------------------------------------------------------------------- -import asyncio -import os -import typing +import json +from collections.abc import AsyncGenerator from pathlib import Path import pytest -import pytest_asyncio from httpx import ASGITransport, AsyncClient -from src.main import app - -MOCK_PATH = os.path.join(os.path.dirname(__file__), "../src/mocks/mock_items.json") +from src.api.deps import get_item_store +from src.core.config import settings +from src.crud.items import ItemStore +from src.main import app -@pytest.fixture(scope="session") -def event_loop(request) -> typing.Generator: - loop = asyncio.get_event_loop() - yield loop - loop.close() - +ITEMS_URL = f"{settings.API_V1_PREFIX}/items" -@pytest_asyncio.fixture(scope="function", autouse=True) -def mock_data_reset(): - # Back up original data into memory - mock_path = Path(__file__).parent.parent / "src/mocks/mock_items.json" - original_data = mock_path.read_text() +SEED_ITEMS = [ + {"id": 1, "name": "Test Item 1", "price": 10.5, "category": "test"}, + {"id": 2, "name": "Test Item 2", "price": 20.0, "category": "test"}, +] - yield - # After test, restore original data - mock_path.write_text(original_data) +@pytest.fixture +def store(tmp_path: Path) -> ItemStore: + """Item store on a temporary file, so tests never touch src/mocks.""" + path = tmp_path / "items.json" + path.write_text(json.dumps(SEED_ITEMS), encoding="utf-8") + return ItemStore(path) -@pytest_asyncio.fixture(scope="module") -async def client(): +@pytest.fixture +async def client(store: ItemStore) -> AsyncGenerator[AsyncClient, None]: + app.dependency_overrides[get_item_store] = lambda: store async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as ac: yield ac + app.dependency_overrides.clear() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_config.py-tpl new file mode 100644 index 0000000..38f107b --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_config.py-tpl @@ -0,0 +1,194 @@ +# -------------------------------------------------------------------------- +# Settings validation: the SECRET_KEY rule, ENVIRONMENT values, +# environment variable names and the CORS wildcard. +# -------------------------------------------------------------------------- +import json +import os +import secrets +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest +from pydantic import ValidationError + +from src.core.config import KNOWN_EXAMPLE_SECRET_KEYS, MIN_SECRET_KEY_BYTES, Settings + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +APP_MODULE = "src.main" +#: Settings without a default; none in this template. +REQUIRED: dict[str, Any] = {} + +STRONG_KEY = "k" * MIN_SECRET_KEY_BYTES +#: Every environment except development refuses a missing, public or short +#: SECRET_KEY. +STRICT_ENVIRONMENTS = ["staging", "production"] + + +@pytest.fixture(autouse=True) +def _isolated_settings_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Shell variables, in any spelling, must not leak into Settings().""" + for name in list(os.environ): + if name.upper() in {"ENVIRONMENT", "SECRET_KEY", "BACKEND_CORS_ORIGINS"}: + monkeypatch.delenv(name) + + +def make_settings(env_file: Path | None = None, **values: Any) -> Settings: + """Settings from explicit values; a developer's .env is never read.""" + return Settings(_env_file=env_file, **{**REQUIRED, **values}) # type: ignore[call-arg] + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_require_an_explicit_secret_key(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"must be set explicitly when ENVIRONMENT={environment}" + ): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_refuse_a_short_secret_key(environment: str) -> None: + short_key = "k" * (MIN_SECRET_KEY_BYTES - 1) + + with pytest.raises(ValidationError, match=f"at least {MIN_SECRET_KEY_BYTES} bytes"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=short_key) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +@pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) +def test_strict_environments_refuse_every_public_example_key( + environment: str, example_key: str +) -> None: + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=f" {example_key} ") + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environment_errors_say_how_to_generate_a_key(environment: str) -> None: + with pytest.raises(ValidationError, match="token_urlsafe"): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_an_explicit_strong_key(environment: str) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + + assert settings.ENVIRONMENT == environment + assert settings.SECRET_KEY == STRONG_KEY + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_the_key_fastkit_writes_to_env( + tmp_path: Path, environment: str +) -> None: + env_file = tmp_path / ".env" + env_file.write_text( + f"ENVIRONMENT={environment}\nSECRET_KEY={secrets.token_urlsafe(32)}\n", + encoding="utf-8", + ) + + assert make_settings(env_file).ENVIRONMENT == environment + + +def test_development_without_a_key_uses_a_random_one() -> None: + settings = make_settings(ENVIRONMENT="development") + + assert len(settings.SECRET_KEY.encode()) >= MIN_SECRET_KEY_BYTES + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_development_only_warns_about_an_example_key() -> None: + example_key = sorted(KNOWN_EXAMPLE_SECRET_KEYS)[0] + + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings(ENVIRONMENT="development", SECRET_KEY=example_key) + + assert settings.SECRET_KEY == example_key + + +@pytest.mark.parametrize("value", ["Production", "PRODUCTION", " production", "prod"]) +def test_unknown_environment_values_fail_closed(value: str) -> None: + with pytest.raises(ValidationError, match="ENVIRONMENT"): + make_settings(ENVIRONMENT=value, SECRET_KEY=STRONG_KEY) + + +def test_environment_variable_names_are_case_insensitive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("environment", "production") + + with pytest.raises(ValidationError, match="must be set explicitly"): + make_settings() + + monkeypatch.setenv("secret_key", STRONG_KEY) + + assert make_settings().ENVIRONMENT == "production" + + +@pytest.mark.parametrize("raw", ["*", " * ", '["*"]', "*,http://localhost:3000"]) +def test_cors_wildcard_is_accepted(monkeypatch: pytest.MonkeyPatch, raw: str) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + + assert make_settings().all_cors_origins == ["*"] + + +def test_cors_origins_must_be_urls_or_the_wildcard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + + with pytest.raises(ValidationError): + make_settings() + + +#: Runs in a fresh interpreter: the app reads its settings at import time. +_PREFLIGHT = f""" +import json +from fastapi.testclient import TestClient +from {APP_MODULE} import app + +headers = {{ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "GET", +}} +response = TestClient(app).options("/", headers=headers) +allowed = {{ + k: v for k, v in response.headers.items() if k.startswith("access-control-allow-") +}} +print(json.dumps(allowed)) +""" + + +@pytest.mark.parametrize( + ("origins", "allow_origin", "allow_credentials"), + [ + ("*", "*", None), + ("http://localhost:3000", "http://localhost:3000", "true"), + ], +) +def test_cors_wildcard_is_never_combined_with_credentials( + origins: str, allow_origin: str, allow_credentials: str | None +) -> None: + env = { + **os.environ, + **{name: str(value) for name, value in REQUIRED.items()}, + "BACKEND_CORS_ORIGINS": origins, + "ENVIRONMENT": "development", + } + result = subprocess.run( + [sys.executable, "-c", _PREFLIGHT], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + check=False, + ) + + assert result.returncode == 0, result.stderr + headers = json.loads(result.stdout.strip().splitlines()[-1]) + assert headers["access-control-allow-origin"] == allow_origin + assert headers.get("access-control-allow-credentials") == allow_credentials diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_item_store.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_item_store.py-tpl new file mode 100644 index 0000000..d6d5bc4 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_item_store.py-tpl @@ -0,0 +1,85 @@ +# -------------------------------------------------------------------------- +# Item store persistence testcases +# -------------------------------------------------------------------------- +import json +from pathlib import Path +from typing import Any + +import pytest + +from src.crud.items import ItemStore + +NEW_ITEM = {"name": "New Item", "price": 30.0, "category": "new"} + + +def make_store(tmp_path: Path, data: Any) -> ItemStore: + path = tmp_path / "items.json" + path.write_text(json.dumps(data), encoding="utf-8") + return ItemStore(path) + + +def seed(*ids: int) -> list[dict[str, Any]]: + return [{**NEW_ITEM, "id": item_id} for item_id in ids] + + +async def test_deleted_id_is_not_reused(tmp_path: Path) -> None: + store = make_store(tmp_path, seed(1, 2)) + + first = await store.create(dict(NEW_ITEM)) + assert await store.delete(first["id"]) + second = await store.create(dict(NEW_ITEM)) + + assert first["id"] == 3 + assert second["id"] == 4 + + +async def test_restart_does_not_reuse_the_deleted_highest_id( + tmp_path: Path, +) -> None: + store = make_store(tmp_path, seed(1, 2)) + created = await store.create(dict(NEW_ITEM)) + assert await store.delete(created["id"]) + + restarted = ItemStore(store.path) + after_restart = await restarted.create(dict(NEW_ITEM)) + + assert after_restart["id"] == created["id"] + 1 + saved = json.loads(store.path.read_text(encoding="utf-8")) + assert saved["next_id"] == after_restart["id"] + 1 + + +async def test_old_list_format_file_still_loads(tmp_path: Path) -> None: + store = make_store(tmp_path, seed(5, 2)) + + items, total = await store.list_page(offset=0, limit=10) + + assert [item["id"] for item in items] == [2, 5] + assert total == 2 + assert await store.get(5) is not None + assert (await store.create(dict(NEW_ITEM)))["id"] == 6 + + +async def test_next_id_never_goes_below_the_highest_stored_id( + tmp_path: Path, +) -> None: + store = make_store(tmp_path, {"next_id": 2, "items": seed(1, 7)}) + + assert (await store.create(dict(NEW_ITEM)))["id"] == 8 + + +async def test_failed_write_keeps_the_file_and_leaves_no_temp_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + store = make_store(tmp_path, seed(1, 2)) + before = store.path.read_bytes() + + def fail_replace(*args: Any, **kwargs: Any) -> None: + raise OSError("simulated crash while replacing the file") + + monkeypatch.setattr("src.crud.items.os.replace", fail_replace) + + with pytest.raises(OSError, match="simulated crash"): + await store.create(dict(NEW_ITEM)) + + assert store.path.read_bytes() == before + assert list(tmp_path.iterdir()) == [store.path] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_items.py-tpl index b00a68f..0af6736 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_items.py-tpl @@ -1,48 +1,191 @@ # -------------------------------------------------------------------------- -# Item endpoint testcases (Async version) +# Item endpoint testcases (async) # -------------------------------------------------------------------------- +import asyncio + import pytest +from httpx import AsyncClient + +from src.crud.items import MOCK_FILE, ItemStore +from tests.conftest import ITEMS_URL + +NEW_ITEM = {"name": "New Item", "price": 30.0, "category": "new"} + +async def test_list_items_returns_a_page(client: AsyncClient) -> None: + response = await client.get(ITEMS_URL) -@pytest.mark.asyncio -async def test_read_all_items(client): - response = await client.get("/items") assert response.status_code == 200 - assert len(response.json()) == 1 + body = response.json() + assert set(body) == {"items", "total", "limit", "offset"} + assert body["total"] == 2 + assert body["limit"] == 20 + assert body["offset"] == 0 + assert [item["id"] for item in body["items"]] == [1, 2] -@pytest.mark.asyncio -async def test_read_item_success(client): - response = await client.get("/items/1") +async def test_list_items_limit_and_offset(client: AsyncClient) -> None: + response = await client.get(ITEMS_URL, params={"limit": 1, "offset": 1}) + + assert response.status_code == 200 + body = response.json() + assert [item["name"] for item in body["items"]] == ["Test Item 2"] + assert body["total"] == 2 + assert body["limit"] == 1 + assert body["offset"] == 1 + + +async def test_list_items_offset_past_the_end(client: AsyncClient) -> None: + body = (await client.get(ITEMS_URL, params={"offset": 10})).json() + + assert body["items"] == [] + assert body["total"] == 2 + + +@pytest.mark.parametrize( + "params", [{"limit": 0}, {"limit": 101}, {"offset": -1}, {"limit": "x"}] +) +async def test_list_items_rejects_out_of_range_pagination( + client: AsyncClient, params: dict[str, object] +) -> None: + assert (await client.get(ITEMS_URL, params=params)).status_code == 422 + + +async def test_collection_is_served_without_redirect(client: AsyncClient) -> None: + response = await client.get(ITEMS_URL, follow_redirects=False) + + assert response.status_code == 200 + + +async def test_get_item(client: AsyncClient) -> None: + response = await client.get(f"{ITEMS_URL}/1") + assert response.status_code == 200 assert response.json()["name"] == "Test Item 1" -@pytest.mark.asyncio -async def test_read_item_not_found(client): - response = await client.get("/items/999") +async def test_get_item_not_found(client: AsyncClient) -> None: + response = await client.get(f"{ITEMS_URL}/999") + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} -@pytest.mark.asyncio -async def test_create_item(client): - new_item = {"name": "New Item", "price": 30.0, "category": "new"} - response = await client.post("/items", json=new_item) +async def test_create_item_returns_201_and_location(client: AsyncClient) -> None: + response = await client.post(ITEMS_URL, json=NEW_ITEM) + assert response.status_code == 201 - assert response.json()["id"] == 2 + created = response.json() + assert created["id"] not in (1, 2) + assert created["name"] == "New Item" + location = response.headers["location"] + assert location.endswith(f"{ITEMS_URL}/{created['id']}") + assert (await client.get(location)).json() == created + + +@pytest.mark.parametrize( + "payload", + [ + {**NEW_ITEM, "name": ""}, + {**NEW_ITEM, "price": -1}, + {"name": "No price", "category": "new"}, + ], +) +async def test_create_item_validates_input( + client: AsyncClient, payload: dict[str, object] +) -> None: + assert (await client.post(ITEMS_URL, json=payload)).status_code == 422 -@pytest.mark.asyncio -async def test_update_item(client): - updated_data = {"name": "Updated Item", "price": 15.0, "category": "updated"} - response = await client.put("/items/1", json=updated_data) +async def test_put_replaces_the_whole_item(client: AsyncClient) -> None: + await client.patch(f"{ITEMS_URL}/1", json={"description": "will be dropped"}) + + response = await client.put( + f"{ITEMS_URL}/1", json={"name": "Replaced", "price": 1.0, "category": "x"} + ) + assert response.status_code == 200 - assert response.json()["name"] == "Updated Item" + assert response.json() == { + "id": 1, + "name": "Replaced", + "description": None, + "price": 1.0, + "category": "x", + } + + +async def test_put_requires_every_field(client: AsyncClient) -> None: + response = await client.put(f"{ITEMS_URL}/1", json={"name": "Only a name"}) + assert response.status_code == 422 + + +async def test_put_not_found(client: AsyncClient) -> None: + response = await client.put(f"{ITEMS_URL}/999", json=NEW_ITEM) + + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +async def test_patch_changes_only_the_sent_fields(client: AsyncClient) -> None: + response = await client.patch(f"{ITEMS_URL}/1", json={"price": 99.0}) + + assert response.status_code == 200 + body = response.json() + assert body["price"] == 99.0 + assert body["name"] == "Test Item 1" + assert body["category"] == "test" + + +async def test_patch_can_clear_a_nullable_field(client: AsyncClient) -> None: + await client.patch(f"{ITEMS_URL}/1", json={"description": "temporary"}) + + response = await client.patch(f"{ITEMS_URL}/1", json={"description": None}) -@pytest.mark.asyncio -async def test_delete_item(client): - response = await client.delete("/items/1") assert response.status_code == 200 - response = await client.get("/items/1") + assert response.json()["description"] is None + + +async def test_patch_rejects_null_for_required_fields(client: AsyncClient) -> None: + response = await client.patch(f"{ITEMS_URL}/1", json={"name": None}) + + assert response.status_code == 422 + assert (await client.get(f"{ITEMS_URL}/1")).json()["name"] == "Test Item 1" + + +async def test_patch_not_found(client: AsyncClient) -> None: + response = await client.patch(f"{ITEMS_URL}/999", json={"price": 1.0}) + assert response.status_code == 404 + + +async def test_delete_item_returns_204(client: AsyncClient) -> None: + response = await client.delete(f"{ITEMS_URL}/1") + + assert response.status_code == 204 + assert response.content == b"" + assert (await client.get(f"{ITEMS_URL}/1")).status_code == 404 + + +async def test_delete_item_not_found(client: AsyncClient) -> None: + response = await client.delete(f"{ITEMS_URL}/999") + + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +async def test_tests_do_not_modify_the_shipped_mock_file(client: AsyncClient) -> None: + before = MOCK_FILE.read_bytes() + + await client.post(ITEMS_URL, json=NEW_ITEM) + await client.delete(f"{ITEMS_URL}/1") + + assert MOCK_FILE.read_bytes() == before + + +async def test_concurrent_creates_get_unique_ids(store: ItemStore) -> None: + created = await asyncio.gather(*(store.create(dict(NEW_ITEM)) for _ in range(20))) + + ids = [item["id"] for item in created] + assert len(set(ids)) == 20 + assert (await store.list_page(offset=0, limit=100))[1] == 22 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_main.py-tpl new file mode 100644 index 0000000..245e1ad --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_main.py-tpl @@ -0,0 +1,59 @@ +# -------------------------------------------------------------------------- +# Application-level testcases (health, OpenAPI, settings) +# -------------------------------------------------------------------------- +import pytest +from httpx import AsyncClient + +from src.core.config import Settings +from tests.conftest import ITEMS_URL + + +async def test_health(client: AsyncClient) -> None: + response = await client.get("/health") + + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + +async def test_openapi_documents_routes_tags_and_errors(client: AsyncClient) -> None: + schema = (await client.get("/openapi.json")).json() + paths = schema["paths"] + + assert "/health" in paths + assert set(paths[ITEMS_URL]) == {"get", "post"} + assert set(paths[f"{ITEMS_URL}/{{item_id}}"]) == {"get", "put", "patch", "delete"} + item_routes = paths[f"{ITEMS_URL}/{{item_id}}"] + for operation in item_routes.values(): + assert operation["tags"] == ["items"] + assert "404" in operation["responses"] + assert "201" in paths[ITEMS_URL]["post"]["responses"] + assert "204" in item_routes["delete"]["responses"] + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ( + "http://localhost:3000, ,https://example.com/", + ["http://localhost:3000", "https://example.com"], + ), + ('["http://localhost:3000", ""]', ["http://localhost:3000"]), + ("", []), + ], +) +def test_cors_origins_never_contain_an_empty_origin( + monkeypatch: pytest.MonkeyPatch, raw: str, expected: list[str] +) -> None: + # _env_file=None: a developer's .env must not change the result. + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + settings = Settings(_env_file=None) # type: ignore[call-arg] + + assert settings.all_cors_origins == expected + + +def test_business_routes_default_to_the_v1_prefix( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("API_V1_PREFIX", raising=False) + + assert Settings(_env_file=None).API_V1_PREFIX == "/api/v1" # type: ignore[call-arg] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.dockerignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.dockerignore-tpl new file mode 100644 index 0000000..151b60c --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.dockerignore-tpl @@ -0,0 +1,47 @@ +# Files Docker never sends to the build, so they cannot end up in the image. + +# Secrets: settings come from the environment at run time (docker run -e / +# --env-file, compose env_file), never from a file baked into the image. +.env +.env.* + +# VCS and editor state +.git +.gitignore +.gitattributes +.idea +.vscode +**/.DS_Store + +# Virtual environments +.venv +venv +env + +# Python, test and tool caches +**/__pycache__ +**/*.py[cod] +.pytest_cache +.mypy_cache +.ruff_cache +.coverage +.coverage.* +coverage.xml +htmlcov +dist +build +*.egg-info + +# Local SQLite databases +**/*.db +**/*.db-journal +**/*.db-wal +**/*.db-shm + +# The application image does not run the test suite +tests + +# Docker files themselves +Dockerfile +docker-compose*.yml +.dockerignore diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.env.example-tpl index 74af97e..63d7e62 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.env.example-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/.env.example-tpl @@ -5,19 +5,32 @@ ENVIRONMENT=development # JWT signing key. .env.example (committed) keeps a public placeholder; fastkit # put a unique key in your local, git-ignored .env. Generate another with: # python -c "import secrets; print(secrets.token_urlsafe(32))" -# With ENVIRONMENT=production the app refuses to start on the placeholder. +# With any ENVIRONMENT other than development (staging or production) the app +# refuses to start when SECRET_KEY is unset, a public example value or shorter +# than 32 bytes. SECRET_KEY=changethis-please-generate-a-real-32-byte-key +# HS256, HS384 or HS512. JWT_ALGORITHM=HS256 ACCESS_TOKEN_EXPIRE_MINUTES=30 REFRESH_TOKEN_EXPIRE_DAYS=14 +# Requests per client address and endpoint for /auth/register, /auth/login and +# /auth/refresh, per window (counted per process). Over the budget: 429. +AUTH_RATE_LIMIT_ENABLED=true +AUTH_RATE_LIMIT_REQUESTS=10 +AUTH_RATE_LIMIT_WINDOW_SECONDS=60 + # Database — SQLite by default. For PostgreSQL: # DATABASE_URL=postgresql+psycopg://postgres:postgres@localhost:5432/app_db +# In the Docker image only /app/data is writable: when you pass this file with +# `docker run --env-file .env`, use DATABASE_URL=sqlite:////app/data/app.db. DATABASE_URL=sqlite:///./app.db # Optional bootstrap superuser, created on startup when both are set FIRST_SUPERUSER_EMAIL= FIRST_SUPERUSER_PASSWORD= -# Comma-separated list, e.g. http://localhost:3000,http://localhost:5173 +# Allowed browser origins, comma-separated or a JSON list, e.g. +# http://localhost:3000,http://localhost:5173. "*" allows any origin, but +# then without credentials (cookies, Authorization headers). BACKEND_CORS_ORIGINS= diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/Dockerfile-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/Dockerfile-tpl index bf824bb..518317c 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/Dockerfile-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/Dockerfile-tpl @@ -1,18 +1,45 @@ FROM python:3.12-slim +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + WORKDIR /app +# Unprivileged runtime user with a fixed UID/GID, so file ownership on mounted +# volumes stays predictable across rebuilds. +RUN groupadd --system --gid 10001 app \ + && useradd --system --uid 10001 --gid app --no-create-home \ + --home-dir /nonexistent --shell /usr/sbin/nologin app + COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt +# The source stays owned by root, read-only for the app user. .dockerignore +# keeps .env, tests/, virtualenvs and local databases out of the build context. COPY pyproject.toml alembic.ini ./ COPY src/ src/ -COPY tests/ tests/ COPY scripts/ scripts/ +# The default SQLite database lives in /app/data, the only directory the app +# user can write to. Mount a volume there to keep the data across containers, +# or point DATABASE_URL at PostgreSQL. +RUN mkdir -p /app/data && chown app:app /app/data + ENV PYTHONPATH=/app ENV ENVIRONMENT=production +ENV DATABASE_URL=sqlite:////app/data/app.db + +USER app EXPOSE 8000 +# Liveness probe on GET /health (the slim image has no curl, so python). +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ + CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3)"] + +# Settings come from the environment at run time, never from a file in the +# image, e.g.: +# docker run -p 8000:8000 -e SECRET_KEY=... -v app-data:/app/data +# A DATABASE_URL you pass (for example with --env-file .env, whose default is +# ./app.db) replaces the one above: keep SQLite files under /app/data. CMD ["uvicorn", "src.app.main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl index 6b326ce..3c984e6 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl @@ -14,8 +14,15 @@ Pick this template when your API needs real accounts on day one: `jti` in the database, so a used token dies immediately and a replay is rejected. - **Argon2id password hashing** through `pwdlib` — the current recommended default, not a legacy bcrypt setup. -- **Real logout.** Revoke one session (`/auth/logout`) or every session of a user - (`/auth/logout-all`). +- **Session revocation.** Revoke one session (`/auth/logout`) or every session of + a user (`/auth/logout-all`). This revokes refresh tokens only: access tokens + are not tracked, so one already issued stays valid until it expires + (`ACCESS_TOKEN_EXPIRE_MINUTES`, 30 by default). See + [Logout and access tokens](#logout-and-access-tokens). +- **Login hardening.** An unknown email is checked against a dummy hash, so + response times do not reveal which emails are registered, and + `/auth/register`, `/auth/login` and `/auth/refresh` are rate limited per + client address (429 with `Retry-After`). - **Role and scope guards** wired as FastAPI dependencies: `get_current_user`, `get_current_active_superuser`, and a reusable `require_scopes(...)` factory. - **SQLite by default, PostgreSQL by env var.** The project runs with zero external @@ -46,13 +53,17 @@ PostgreSQL-first CRUD without auth, use `fastapi-psql-orm`. │ ├── main.py # FastAPI app entry point (lifespan) │ ├── core/ │ │ ├── config.py # pydantic-settings configuration +│ │ ├── pagination.py # Page[T] envelope, limit/offset parameters +│ │ ├── rate_limit.py # per-client limit for the anonymous auth routes +│ │ ├── responses.py # error_responses() for OpenAPI │ │ └── security.py # argon2 hashing + JWT encode/decode │ ├── db/ -│ │ └── session.py # engine + get_session dependency +│ │ ├── session.py # engine, get_session, atomic() transactions +│ │ └── types.py # UTCDateTime: timezone-aware UTC timestamps │ ├── api/ -│ │ ├── router.py # aggregates health + every domain router -│ │ ├── health.py # GET /health -│ │ └── deps.py # session, current user, role/scope guards +│ │ ├── router.py # aggregates every domain router (addroute anchors) +│ │ ├── health.py # GET /health, GET /ready (app root) +│ │ └── deps.py # session, services, current user, guards │ ├── domains/ │ │ ├── auth/ # login, refresh rotation, logout │ │ │ ├── models.py # RefreshToken entity @@ -69,15 +80,20 @@ PostgreSQL-first CRUD without auth, use `fastapi-psql-orm`. │ └── alembic/ # migration environment + versions/ └── tests/ ├── conftest.py - ├── test_health.py ├── test_auth.py + ├── test_config.py + ├── test_health.py + ├── test_login_hardening.py + ├── test_refresh_rotation.py + ├── test_timestamps.py └── test_users.py ``` Each domain follows the same split: `router.py` (transport), `service.py` -(business logic), `repository.py` (data access), `models.py` (tables), and -`schemas.py` (API I/O). Add a new domain by mirroring that layout and -registering its router in `src/app/api/router.py`. +(business logic and transactions), `repository.py` (data access, never +commits), `models.py` (tables), and `schemas.py` (API I/O). Add a new domain +by mirroring that layout (or with `fastkit addroute `) and registering +its router in `src/app/api/router.py`, which is served under `/api/v1`. ## Running the app @@ -105,18 +121,35 @@ The Swagger "Authorize" button drives the same OAuth2 password flow as ## API endpoints -| Method | Endpoint | Auth | Description | -|--------|-----------------------------|-------------|--------------------------------------| -| GET | `/api/v1/health` | — | Liveness probe | -| POST | `/api/v1/auth/register` | — | Create an account | -| POST | `/api/v1/auth/login` | — | OAuth2 password form → token pair | -| POST | `/api/v1/auth/refresh` | refresh tok | Rotate into a fresh token pair | -| POST | `/api/v1/auth/logout` | refresh tok | Revoke one refresh token | -| POST | `/api/v1/auth/logout-all` | access tok | Revoke every session of the user | -| GET | `/api/v1/users/me` | access tok | Current user's profile | -| PATCH | `/api/v1/users/me` | access tok | Update the current user's profile | -| GET | `/api/v1/users/me/scopes` | scope `me` | Scope-gated example route | -| GET | `/api/v1/users` | superuser | Role-gated user listing | +Business routes are mounted under `API_V1_PREFIX` (`/api/v1`); the probes +stay at the application root. + +| Method | Endpoint | Auth | Description | +|--------|-----------------------------|-------------|-------------------------------------------| +| GET | `/health` | — | Liveness probe, no database access | +| GET | `/ready` | — | Readiness: `SELECT 1`, 503 when down | +| POST | `/api/v1/auth/register` | — | Create an account (201 + `Location`)¹ | +| POST | `/api/v1/auth/login` | — | OAuth2 password form → token pair¹ | +| POST | `/api/v1/auth/refresh` | refresh tok | Rotate into a fresh token pair¹ | +| POST | `/api/v1/auth/logout` | refresh tok | Revoke one refresh token (204) | +| POST | `/api/v1/auth/logout-all` | access tok | Revoke every session of the user (204) | +| GET | `/api/v1/users/me` | access tok | Current user's profile | +| PATCH | `/api/v1/users/me` | access tok | Update only the fields sent | +| GET | `/api/v1/users/me/scopes` | scope `me` | Scope-gated example route | +| GET | `/api/v1/users` | superuser | Paginated user listing (`limit`, `offset`)| +| GET | `/api/v1/users/{user_id}` | superuser | One user (404 when unknown) | + +Token responses carry `access_token`, `refresh_token`, `token_type` and +`expires_in` (seconds) with `Cache-Control: no-store`. A rejected refresh +token answers 400 `{"error": "invalid_grant", ...}` as in RFC 6749; every 401 +carries `WWW-Authenticate: Bearer`. `PATCH /users/me` with +`{"full_name": null}` clears the name. The user listing returns +`{"items": [...], "total": ..., "limit": ..., "offset": ...}` ordered by id. +Timestamps such as `created_at` are UTC and carry the offset (`...Z`). + +¹ Rate limited: `AUTH_RATE_LIMIT_REQUESTS` requests (10) per endpoint and +client address every `AUTH_RATE_LIMIT_WINDOW_SECONDS` (60); over the budget +the answer is `429 {"detail": "Too many requests"}` with `Retry-After`. ### Walkthrough @@ -164,13 +197,21 @@ permission model outgrows it. The app starts on SQLite (`sqlite:///./app.db`) and creates its tables on startup, so `pytest` and `uvicorn` both work with no setup. To move to -PostgreSQL, set `DATABASE_URL` and run the migrations instead: +PostgreSQL, set `DATABASE_URL` and run the migrations before the first start +(the startup call then finds the tables and leaves them alone; on a database +the app already created, run `alembic stamp head` once instead): ```bash $ export DATABASE_URL='postgresql+psycopg://postgres:postgres@localhost:5432/app_db' $ alembic upgrade head ``` +Timestamps are `TIMESTAMP WITH TIME ZONE` columns read back as UTC +(`src/app/db/types.py`), so stored instants do not depend on the server's +`TimeZone`. Migration `0002` converts the columns of databases created by an +earlier version of this template; run it with the same server time zone the +application used, so existing values keep their instant. + A new migration after a model change: ```bash @@ -187,7 +228,9 @@ $ pytest Tests use `httpx.AsyncClient` against an in-memory SQLite database, covering the register → login → me → refresh → logout flow plus the rejection paths -(wrong password, malformed token, expired token, replayed refresh token). +(wrong password, malformed token, expired token, token without a required +claim, replayed refresh token), the dummy-hash login path, the rate limits, UTC +timestamps, the paginated user listing, `/health` and `/ready`. ## Configuration @@ -196,14 +239,41 @@ register → login → me → refresh → logout flow plus the rejection paths - **`SECRET_KEY`** signs every token. fastkit generated your local `.env` from `.env.example` with a unique key. `.env` is git-ignored; commit `.env.example`, - which keeps only a placeholder. With `ENVIRONMENT=production` the app refuses - to start while `SECRET_KEY` is still an example value. Leave it unset and a - random key is generated per process, which logs everyone out on restart. + which keeps only a placeholder. With any `ENVIRONMENT` other than + `development` (`staging`, `production`) the app refuses to start when + `SECRET_KEY` is unset, a public example value or shorter than 32 bytes. In + development an unset key falls back to a random key per process, which logs + everyone out on restart and differs between workers. - **`DATABASE_URL`** selects the database. +`BACKEND_CORS_ORIGINS` takes comma-separated origins or a JSON list. `*` allows +any origin, but then the app sends no credentials (cookies, `Authorization` +headers), because browsers refuse that combination. + Set `FIRST_SUPERUSER_EMAIL` and `FIRST_SUPERUSER_PASSWORD` to have a superuser seeded on startup. +`AUTH_RATE_LIMIT_REQUESTS` and `AUTH_RATE_LIMIT_WINDOW_SECONDS` set the budget +of the anonymous auth endpoints; `AUTH_RATE_LIMIT_ENABLED=false` turns the limit +off. The counters live in each process, so with several workers or replicas +the effective budget is multiplied by their number: back `RateLimiter` in +`src/app/core/rate_limit.py` with a shared store (Redis, the `limits` package) +for a hard limit. Behind a reverse proxy, start uvicorn with `--proxy-headers +--forwarded-allow-ips=`, or every client shares the proxy's +budget. + +## Logout and access tokens + +`/auth/logout` and `/auth/logout-all` revoke refresh tokens, so a logged-out +session can never be refreshed. Access tokens are self-contained JWTs that +are not looked up on each request: one issued before the logout keeps +working until its `exp`, at most `ACCESS_TOKEN_EXPIRE_MINUTES` later. To +narrow that window, lower `ACCESS_TOKEN_EXPIRE_MINUTES` (clients refresh more +often). To cut access off immediately, check the token's `jti` against a +revocation list (or a per-user "tokens valid after" timestamp) in +`get_current_user` in `src/app/api/deps.py`; changing `SECRET_KEY` invalidates +every token of every user at once. + ## Project Origin This project was created from the **`fastapi-auth-jwt`** template shipped with diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/alembic.ini-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/alembic.ini-tpl index 65016a9..a3de810 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/alembic.ini-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/alembic.ini-tpl @@ -13,7 +13,7 @@ script_location = src/app/alembic # sys.path path, will be prepended to sys.path if present. # defaults to the current working directory. -; prepend_sys_path = . +prepend_sys_path = . # timezone to use when rendering the date within the migration file # as well as the filename. diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/pyproject.toml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/pyproject.toml-tpl index 7ad988b..e404700 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/pyproject.toml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/pyproject.toml-tpl @@ -83,4 +83,5 @@ python_files = ["test_*.py"] python_classes = ["Test*"] python_functions = ["test_*"] asyncio_mode = "strict" +asyncio_default_fixture_loop_scope = "function" addopts = "-v --tb=short" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/alembic/env.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/alembic/env.py-tpl index d0ce45b..e66e9ad 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/alembic/env.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/alembic/env.py-tpl @@ -1,9 +1,13 @@ from logging.config import fileConfig +from typing import Any, Literal from alembic import context +from alembic.autogenerate.api import AutogenContext from sqlalchemy import engine_from_config, pool from sqlmodel import SQLModel + from src.app.core.config import settings +from src.app.db.types import UTCDateTime from src.app.domains.auth import models as auth_models # noqa: F401 from src.app.domains.users import models as user_models # noqa: F401 @@ -18,12 +22,26 @@ def get_url() -> str: return settings.DATABASE_URL +def render_item( + type_: str, obj: Any, autogen_context: AutogenContext +) -> str | Literal[False]: + """Write ``UTCDateTime`` columns as ``sa.DateTime(timezone=True)``. + + Migrations then stay free of application imports. Autogenerate compares + the type through its ``impl``, so this does not hide real drift. + """ + if type_ == "type" and isinstance(obj, UTCDateTime): + return "sa.DateTime(timezone=True)" + return False + + def run_migrations_offline() -> None: context.configure( url=get_url(), target_metadata=target_metadata, literal_binds=True, compare_type=True, + render_item=render_item, ) with context.begin_transaction(): context.run_migrations() @@ -39,7 +57,10 @@ def run_migrations_online() -> None: ) with connectable.connect() as connection: context.configure( - connection=connection, target_metadata=target_metadata, compare_type=True + connection=connection, + target_metadata=target_metadata, + compare_type=True, + render_item=render_item, ) with context.begin_transaction(): context.run_migrations() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/alembic/versions/0001_initial_auth_schema.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/alembic/versions/0001_initial_auth_schema.py-tpl index d66caea..bc92d0c 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/alembic/versions/0001_initial_auth_schema.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/alembic/versions/0001_initial_auth_schema.py-tpl @@ -20,7 +20,9 @@ def upgrade() -> None: op.create_table( "users", sa.Column("id", sa.Integer(), nullable=False), - sa.Column("email", sqlmodel.sql.sqltypes.AutoString(length=320), nullable=False), + sa.Column( + "email", sqlmodel.sql.sqltypes.AutoString(length=320), nullable=False + ), sa.Column( "full_name", sqlmodel.sql.sqltypes.AutoString(length=255), nullable=True ), @@ -48,7 +50,9 @@ def upgrade() -> None: sa.ForeignKeyConstraint(["user_id"], ["users.id"]), sa.PrimaryKeyConstraint("id"), ) - op.create_index(op.f("ix_refresh_tokens_jti"), "refresh_tokens", ["jti"], unique=True) + op.create_index( + op.f("ix_refresh_tokens_jti"), "refresh_tokens", ["jti"], unique=True + ) op.create_index( op.f("ix_refresh_tokens_user_id"), "refresh_tokens", ["user_id"], unique=False ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/alembic/versions/0002_timezone_aware_timestamps.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/alembic/versions/0002_timezone_aware_timestamps.py-tpl new file mode 100644 index 0000000..8f0768f --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/alembic/versions/0002_timezone_aware_timestamps.py-tpl @@ -0,0 +1,57 @@ +"""store timestamps with a time zone + +Revision ID: 0002_timezone_aware +Revises: 0001_initial_auth +Create Date: 2026-12-01 00:00:00.000000 + +``0001_initial_auth`` created the timestamp columns as naive ``TIMESTAMP``. +PostgreSQL then stored every aware datetime the application wrote in the +session ``TimeZone``, so refresh tokens expired early or late by the +server's UTC offset. On PostgreSQL the columns become ``TIMESTAMP WITH TIME +ZONE``; existing values are read in the session ``TimeZone``, which recovers +the instant that was written, so run this migration with the same +server/session time zone the application used. + +SQLite has no time zone type; its stored values are already UTC and stay +as they are. +""" + +import sqlalchemy as sa +from alembic import op + +revision = "0002_timezone_aware" +down_revision = "0001_initial_auth" +branch_labels = None +depends_on = None + +COLUMNS = ( + ("users", "created_at"), + ("refresh_tokens", "expires_at"), + ("refresh_tokens", "created_at"), +) + + +def upgrade() -> None: + if op.get_context().dialect.name != "postgresql": + return + for table, column in COLUMNS: + op.alter_column( + table, + column, + existing_type=sa.DateTime(), + type_=sa.DateTime(timezone=True), + existing_nullable=False, + ) + + +def downgrade() -> None: + if op.get_context().dialect.name != "postgresql": + return + for table, column in COLUMNS: + op.alter_column( + table, + column, + existing_type=sa.DateTime(timezone=True), + type_=sa.DateTime(), + existing_nullable=False, + ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/api/deps.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/api/deps.py-tpl index c015ca6..8e18e4c 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/api/deps.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/api/deps.py-tpl @@ -1,5 +1,6 @@ # -------------------------------------------------------------------------- -# Shared FastAPI dependencies: DB session, current user, role/scope guards. +# Shared FastAPI dependencies: DB session, services, current user, role and +# scope guards. # -------------------------------------------------------------------------- from typing import Annotated, Callable, List @@ -21,11 +22,14 @@ reusable_oauth2 = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_PREFIX}/auth/ SessionDep = Annotated[Session, Depends(get_session)] TokenDep = Annotated[str, Depends(reusable_oauth2)] -CREDENTIALS_EXCEPTION = HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": "Bearer"}, -) + +def credentials_error() -> HTTPException: + """A fresh 401 for a missing, invalid or expired access token.""" + return HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) def get_user_service(session: SessionDep) -> UserService: @@ -36,21 +40,25 @@ def get_auth_service(session: SessionDep) -> AuthService: return AuthService(UserRepository(session), RefreshTokenRepository(session)) -def get_current_user(session: SessionDep, token: TokenDep) -> User: +UserServiceDep = Annotated[UserService, Depends(get_user_service)] +AuthServiceDep = Annotated[AuthService, Depends(get_auth_service)] + + +def get_current_user(users: UserServiceDep, token: TokenDep) -> User: """Resolve the bearer access token into a live, active user.""" try: payload = decode_token(token, ACCESS_TOKEN_TYPE) - except TokenError: - raise CREDENTIALS_EXCEPTION + except TokenError as exc: + raise credentials_error() from exc try: user_id = int(payload["sub"]) - except (KeyError, TypeError, ValueError): - raise CREDENTIALS_EXCEPTION + except (KeyError, TypeError, ValueError) as exc: + raise credentials_error() from exc - user = UserRepository(session).get(user_id) + user = users.get(user_id) if user is None: - raise CREDENTIALS_EXCEPTION + raise credentials_error() if not user.is_active: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user" @@ -70,6 +78,9 @@ def get_current_active_superuser(current_user: CurrentUser) -> User: return current_user +CurrentSuperuser = Annotated[User, Depends(get_current_active_superuser)] + + def require_scopes(*required: str) -> Callable[..., User]: """Build a dependency that enforces every one of ``required`` scopes. diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/api/health.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/api/health.py-tpl index e6616cf..42d9e72 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/api/health.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/api/health.py-tpl @@ -1,11 +1,77 @@ # -------------------------------------------------------------------------- -# Health endpoint — small, side-effect-free probe for liveness checks. +# Liveness and readiness probes, mounted at the application root. # -------------------------------------------------------------------------- -from fastapi import APIRouter +import asyncio +import logging +from typing import Literal + +from fastapi import APIRouter, status +from fastapi.responses import JSONResponse +from pydantic import BaseModel +from sqlalchemy import Engine, text + +from src.app.api.deps import SessionDep + +logger = logging.getLogger(__name__) router = APIRouter(tags=["health"]) +#: Upper bound, in seconds, for the readiness check. A database host that +#: does not answer at all would otherwise hold the probe for the operating +#: system's TCP connect timeout (often more than a minute). +READY_TIMEOUT_SECONDS = 2.0 + + +class HealthStatus(BaseModel): + status: Literal["ok", "unavailable"] + @router.get("/health") -def health() -> dict[str, str]: - return {"status": "ok"} +def health() -> HealthStatus: + """Liveness: the process is up. Touches no database.""" + return HealthStatus(status="ok") + + +def _select_one(bind: Engine) -> None: + """Open a connection of its own and run ``SELECT 1`` on it. + + The probe never uses the request session from the worker thread: after a + timeout that thread is still connecting while the request finishes and + closes its session, and a session must not be used by two threads. + """ + with bind.connect() as connection: + connection.execute(text("SELECT 1")) + + +@router.get( + "/ready", + response_model=HealthStatus, + responses={ + status.HTTP_503_SERVICE_UNAVAILABLE: { + "model": HealthStatus, + "description": "The database is unreachable", + } + }, +) +async def ready(session: SessionDep) -> HealthStatus | JSONResponse: + """Readiness: the database answers ``SELECT 1`` within the time limit. + + The driver is synchronous, so the query runs in a worker thread and only + the wait for it is bounded here. A timed-out thread finishes on its own; + the engine's connect timeout (``db/session.py``) caps how long it takes. + """ + try: + async with asyncio.timeout(READY_TIMEOUT_SECONDS): + # No I/O: the engine behind the session (``.engine`` also covers a + # session bound to a connection, as in the tests). + engine = session.get_bind().engine + await asyncio.to_thread(_select_one, engine) + except Exception as exc: + # Any failure means "not ready": driver and network errors, DNS + # failures, the timeout above. Log the kind, never the URL. + logger.warning("Readiness check failed: %s", type(exc).__name__) + return JSONResponse( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + content={"status": "unavailable"}, + ) + return HealthStatus(status="ok") diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/api/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/api/router.py-tpl index 893cfb0..45d5e29 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/api/router.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/api/router.py-tpl @@ -1,17 +1,18 @@ # -------------------------------------------------------------------------- -# Top-level API router — aggregates the health probe with every domain -# module under ``src/app/domains/``. +# Top-level API router — aggregates every domain module under +# ``src/app/domains/``. ``src/app/main.py`` mounts it under +# ``settings.API_V1_PREFIX``; ``fastkit addroute`` registers new domain +# routers at the ``# fastkit:`` anchors. The health probes live at the root +# (``src/app/api/health.py``), outside this router. # -------------------------------------------------------------------------- from fastapi import APIRouter -from src.app.api import health from src.app.domains.auth import router as auth_router from src.app.domains.users import router as users_router # fastkit:imports api_router = APIRouter() -api_router.include_router(health.router) api_router.include_router(auth_router.router) api_router.include_router(users_router.router) # fastkit:routes diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/config.py-tpl index a880a3a..e1cd90d 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/config.py-tpl @@ -2,9 +2,10 @@ # Application settings (pydantic-settings). # -------------------------------------------------------------------------- import secrets +import warnings from typing import Annotated, Any, List, Literal, Union -from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator +from pydantic import AnyUrl, BeforeValidator, Field, computed_field, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict @@ -16,17 +17,32 @@ def _parse_cors(v: Any) -> Union[List[str], str]: raise ValueError(v) -#: Example SECRET_KEY values fastkit templates have shipped in ``.env`` -#: files. They are public, so a production deployment must never sign -#: anything with one of them. +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. KNOWN_EXAMPLE_SECRET_KEYS = frozenset( { "changethis", "changethis-please-generate-a-real-32-byte-key", "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + "your-secret-key-here", + "change-me-in-production", + "your-mcp-api-key-here", } ) +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = 32 + +_GENERATE_KEY_HINT = ( + "Generate one with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) + class Settings(BaseSettings): """Centralized configuration for the application. @@ -45,13 +61,23 @@ class Settings(BaseSettings): PROJECT_NAME: str = "" ENVIRONMENT: Literal["development", "staging", "production"] = "development" - # Signing key for JWTs. Generated per-process when unset, which logs every - # user out on restart — always pin SECRET_KEY outside of development. + # Signing key for JWTs. When unset, every process generates its own random + # key, so tokens break on restart and between workers: staging and + # production refuse to start without an explicit key of at least 32 + # bytes that is not a public example value (see _check_secret_key below). SECRET_KEY: str = secrets.token_urlsafe(32) - JWT_ALGORITHM: str = "HS256" + # HMAC algorithms only: tokens are signed and verified with SECRET_KEY. + JWT_ALGORITHM: Literal["HS256", "HS384", "HS512"] = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 REFRESH_TOKEN_EXPIRE_DAYS: int = 14 + # Rate limiting of /auth/register, /auth/login and /auth/refresh: each + # client address gets this many requests per endpoint and window (see + # core/rate_limit.py; counted per process). + AUTH_RATE_LIMIT_ENABLED: bool = True + AUTH_RATE_LIMIT_REQUESTS: int = Field(default=10, ge=1) + AUTH_RATE_LIMIT_WINDOW_SECONDS: int = Field(default=60, ge=1) + API_V1_PREFIX: str = "/api/v1" # SQLite by default so the template runs with no external service. @@ -63,26 +89,54 @@ class Settings(BaseSettings): FIRST_SUPERUSER_EMAIL: str = "" FIRST_SUPERUSER_PASSWORD: str = "" + # Comma-separated list or JSON list. Each origin is a full URL such as + # http://localhost:3000, or "*" for any origin; "*" never goes together + # with credentials (browsers refuse that), so main.py turns them off. BACKEND_CORS_ORIGINS: Annotated[ - Union[List[AnyUrl], str], BeforeValidator(_parse_cors) + Union[List[Union[Literal["*"], AnyUrl]], str], BeforeValidator(_parse_cors) ] = [] @computed_field # type: ignore[prop-decorator] @property def all_cors_origins(self) -> List[str]: - return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins @model_validator(mode="after") - def _reject_example_secret_key_in_production(self) -> "Settings": - if ( - self.ENVIRONMENT == "production" - and self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS - ): + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) + return self + env = f"ENVIRONMENT={self.ENVIRONMENT}" + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT + ) + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: raise ValueError( - "SECRET_KEY is set to a public example value while " - "ENVIRONMENT=production. Generate a real key with " - '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' - "and set it as the SECRET_KEY environment variable (or in .env)." + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT ) return self diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/pagination.py-tpl new file mode 100644 index 0000000..2688822 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/pagination.py-tpl @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------- +# Limit/offset pagination shared by every list endpoint. +# +# List endpoints take ``limit: LimitParam = DEFAULT_LIMIT`` and +# ``offset: OffsetParam = 0`` and return a ``Page[T]`` envelope: +# {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range +# values are rejected with a 422 rather than clamped. +# -------------------------------------------------------------------------- +from typing import Annotated, Generic, TypeVar + +from fastapi import Query +from pydantic import BaseModel + +T = TypeVar("T") + +#: Page size used when the client sends no ``limit``. +DEFAULT_LIMIT = 20 +#: Largest page a client may ask for. +MAX_LIMIT = 100 + +LimitParam = Annotated[ + int, Query(ge=1, le=MAX_LIMIT, description="Maximum number of items to return.") +] +OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] + + +class Page(BaseModel, Generic[T]): + """One page of a collection, ordered by primary key. + + ``total`` counts the whole collection, so a client knows there is a next + page while ``offset + len(items) < total``. + """ + + items: list[T] + total: int + limit: int + offset: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/rate_limit.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/rate_limit.py-tpl new file mode 100644 index 0000000..36feba1 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/rate_limit.py-tpl @@ -0,0 +1,113 @@ +# -------------------------------------------------------------------------- +# Rate limiting for the unauthenticated auth endpoints. +# +# ``/auth/register``, ``/auth/login`` and ``/auth/refresh`` accept anonymous +# requests and two of them run argon2 (64 MiB of memory per hash), so each +# client address gets ``AUTH_RATE_LIMIT_REQUESTS`` requests per endpoint +# every ``AUTH_RATE_LIMIT_WINDOW_SECONDS``. Over the budget the client gets +# ``429 Too Many Requests`` with a ``Retry-After`` header. +# +# The counters live in this process (fixed windows, no dependency). With +# several workers or replicas every process counts on its own, so the real +# budget is multiplied by their number: replace ``RateLimiter`` with one +# backed by a shared store (Redis, or the ``limits`` package) and keep the +# ``auth_rate_limit`` dependency as the hook. +# +# Proxies: the client address is ``request.client.host``. Behind a reverse +# proxy that is the proxy's address, so every client would share one budget. +# Start uvicorn with ``--proxy-headers --forwarded-allow-ips=`` +# and only trust ``X-Forwarded-For`` from your own proxy. +# -------------------------------------------------------------------------- +import math +import threading +import time +from typing import Callable + +from fastapi import HTTPException, Request, status + +from src.app.core.config import settings + +TOO_MANY_REQUESTS = "Too many requests" + + +class RateLimiter: + """Counts hits per key in fixed windows; safe to share between threads.""" + + #: Keys kept before expired windows are pruned (bounds memory use when + #: many different addresses call in). + MAX_KEYS = 10_000 + + def __init__( + self, + requests: int, + window_seconds: float, + clock: Callable[[], float] = time.monotonic, + ) -> None: + if requests < 1 or window_seconds <= 0: + raise ValueError("a rate limit needs at least 1 request per window") + self.requests = requests + self.window_seconds = window_seconds + self._clock = clock + self._lock = threading.Lock() + self._windows: dict[str, tuple[float, int]] = {} + + def hit(self, key: str) -> float | None: + """Count one request for ``key``. + + Returns ``None`` while the key is within its budget, otherwise the + number of seconds until its window resets. + """ + now = self._clock() + with self._lock: + start, count = self._windows.get(key, (now, 0)) + if now - start >= self.window_seconds: + start, count = now, 0 + if count >= self.requests: + return self.window_seconds - (now - start) + if key not in self._windows and len(self._windows) >= self.MAX_KEYS: + self._prune(now) + self._windows[key] = (start, count + 1) + return None + + def reset(self) -> None: + """Forget every counter (used by the tests).""" + with self._lock: + self._windows.clear() + + def _prune(self, now: float) -> None: + expired = [ + key + for key, (start, _) in self._windows.items() + if now - start >= self.window_seconds + ] + for key in expired: + del self._windows[key] + # Still full: drop the oldest windows rather than grow without bound. + overflow = len(self._windows) - self.MAX_KEYS + 1 + if overflow > 0: + oldest = sorted(self._windows, key=lambda key: self._windows[key][0]) + for key in oldest[:overflow]: + del self._windows[key] + + +auth_limiter = RateLimiter( + settings.AUTH_RATE_LIMIT_REQUESTS, settings.AUTH_RATE_LIMIT_WINDOW_SECONDS +) + + +def auth_rate_limit(request: Request) -> None: + """Dependency: refuse a client that went over its budget for this route.""" + if not settings.AUTH_RATE_LIMIT_ENABLED: + return + address = request.client.host if request.client else "unknown" + # The route's path template, so every request to one endpoint shares a + # budget however its URL is spelled. + route = request.scope.get("route") + endpoint = getattr(route, "path", request.url.path) + retry_after = auth_limiter.hit(f"{endpoint}|{address}") + if retry_after is not None: + raise HTTPException( + status_code=status.HTTP_429_TOO_MANY_REQUESTS, + detail=TOO_MANY_REQUESTS, + headers={"Retry-After": str(max(math.ceil(retry_after), 1))}, + ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/responses.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/responses.py-tpl new file mode 100644 index 0000000..bffc8c1 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/responses.py-tpl @@ -0,0 +1,40 @@ +# -------------------------------------------------------------------------- +# OpenAPI error responses shared by the routers. +# +# FastAPI documents 2xx and 422 on its own. Routes that can also answer 401, +# 404, 409, ... declare it with ``responses=error_responses(404)`` so clients +# see every status code and the ``{"detail": "..."}`` body in the schema. +# -------------------------------------------------------------------------- +from http import HTTPStatus +from typing import Any + +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + """Body FastAPI sends for an ``HTTPException``.""" + + detail: str + + +def error_responses(*status_codes: int) -> dict[int | str, dict[str, Any]]: + """Build ``responses=`` entries that document the given error codes. + + A 401 entry also documents the ``WWW-Authenticate`` header every 401 + response carries. + """ + responses: dict[int | str, dict[str, Any]] = {} + for code in status_codes: + entry: dict[str, Any] = { + "model": ErrorDetail, + "description": HTTPStatus(code).phrase, + } + if code == HTTPStatus.UNAUTHORIZED: + entry["headers"] = { + "WWW-Authenticate": { + "description": "Authentication scheme to use (Bearer).", + "schema": {"type": "string"}, + } + } + responses[code] = entry + return responses diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/security.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/security.py-tpl index f9da4ae..a2133e2 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/security.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/core/security.py-tpl @@ -6,6 +6,7 @@ # -------------------------------------------------------------------------- import uuid from datetime import datetime, timedelta, timezone +from functools import lru_cache from typing import Any, Dict, List, Optional import jwt @@ -18,6 +19,10 @@ password_hash = PasswordHash.recommended() ACCESS_TOKEN_TYPE = "access" REFRESH_TOKEN_TYPE = "refresh" +#: Claims every token must carry; PyJWT refuses a token missing one. Without +#: ``exp`` a signed token would never expire; ``type`` and ``jti`` are what +#: the access/refresh split and refresh-token rotation rely on. +REQUIRED_CLAIMS = ["exp", "sub", "type", "jti"] class TokenError(Exception): @@ -32,6 +37,21 @@ def verify_password(password: str, hashed_password: str) -> bool: return password_hash.verify(password, hashed_password) +@lru_cache(maxsize=1) +def _dummy_hash() -> str: + return password_hash.hash("fastkit-timing-equaliser") + + +def verify_dummy_password(password: str) -> None: + """Spend the time of a real password check, for an unknown account. + + Login verifies the password against this dummy hash when the email does + not exist, so a wrong email takes as long to reject as a wrong password + and response times do not reveal which emails are registered. + """ + verify_password(password, _dummy_hash()) + + def _create_token( subject: str, token_type: str, @@ -84,11 +104,15 @@ def decode_token(token: str, expected_type: str) -> Dict[str, Any]: """Decode and validate a JWT, enforcing the expected token type. Raises: - TokenError: the signature, expiry, or ``type`` claim did not check out. + TokenError: the signature, expiry, a required claim or the ``type`` + claim did not check out. """ try: payload: Dict[str, Any] = jwt.decode( - token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM] + token, + settings.SECRET_KEY, + algorithms=[settings.JWT_ALGORITHM], + options={"require": REQUIRED_CLAIMS}, ) except jwt.PyJWTError as exc: raise TokenError(str(exc)) from exc diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/db/session.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/db/session.py-tpl index 0885f7d..af14071 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/db/session.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/db/session.py-tpl @@ -1,19 +1,30 @@ # -------------------------------------------------------------------------- -# Engine / session factory. +# Engine / session factory and the transaction helper. # # SQLite needs ``check_same_thread=False`` because FastAPI runs sync -# dependencies in a threadpool; PostgreSQL takes no extra arguments. +# dependencies in a threadpool; PostgreSQL gets a connect timeout so an +# unreachable server fails fast instead of after the OS TCP timeout. +# +# Transactions belong to the services: repositories only stage changes, and +# each service method wraps its writes in ``atomic(session)``. The request +# session dependency never commits; it rolls back when a request fails. # -------------------------------------------------------------------------- -from collections.abc import Generator +from collections.abc import Generator, Iterator +from contextlib import contextmanager from typing import Any, Dict from sqlmodel import Session, SQLModel, create_engine from src.app.core.config import settings +#: Seconds psycopg may spend opening a connection (libpq's minimum is 2). +CONNECT_TIMEOUT_SECONDS = 5 + _connect_args: Dict[str, Any] = {} if settings.DATABASE_URL.startswith("sqlite"): _connect_args = {"check_same_thread": False} +elif settings.DATABASE_URL.startswith("postgresql"): + _connect_args = {"connect_timeout": CONNECT_TIMEOUT_SECONDS} engine = create_engine(settings.DATABASE_URL, connect_args=_connect_args) @@ -31,6 +42,22 @@ def create_db_and_tables() -> None: SQLModel.metadata.create_all(engine) +@contextmanager +def atomic(session: Session) -> Iterator[None]: + """Commit everything staged inside the block once, or roll it all back.""" + try: + yield + session.commit() + except BaseException: + session.rollback() + raise + + def get_session() -> Generator[Session, None, None]: + """Yield a request-scoped session; roll back what a failed request left.""" with Session(engine) as session: - yield session + try: + yield session + except Exception: + session.rollback() + raise diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/db/types.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/db/types.py-tpl new file mode 100644 index 0000000..0a72e9e --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/db/types.py-tpl @@ -0,0 +1,48 @@ +# -------------------------------------------------------------------------- +# Custom column types. +# +# ``UTCDateTime`` stores timestamps as ``TIMESTAMP WITH TIME ZONE`` and +# always hands back timezone-aware UTC datetimes, whatever the database: +# +# - PostgreSQL keeps the instant; the value read back is converted to UTC so +# it does not depend on the server or session ``TimeZone``. +# - SQLite has no timezone type and drops ``tzinfo``. Values are converted to +# UTC before they are written, so a naive value read back is UTC and gets +# ``tzinfo=UTC`` attached here, in one place. +# +# Naive datetimes are refused on write: their meaning depends on the clock +# of whoever created them. Use ``datetime.now(timezone.utc)``. +# -------------------------------------------------------------------------- +from datetime import datetime, timezone + +from sqlalchemy import DateTime +from sqlalchemy.engine import Dialect +from sqlalchemy.types import TypeDecorator + + +class UTCDateTime(TypeDecorator[datetime]): + """A ``DateTime(timezone=True)`` column that reads and writes aware UTC.""" + + impl = DateTime(timezone=True) + cache_ok = True + + def process_bind_param( + self, value: datetime | None, dialect: Dialect + ) -> datetime | None: + if value is None: + return None + if value.tzinfo is None or value.utcoffset() is None: + raise ValueError( + "naive datetime given for a UTCDateTime column; " + "pass an aware datetime such as datetime.now(timezone.utc)" + ) + return value.astimezone(timezone.utc) + + def process_result_value( + self, value: datetime | None, dialect: Dialect + ) -> datetime | None: + if value is None: + return None + if value.tzinfo is None: + return value.replace(tzinfo=timezone.utc) + return value.astimezone(timezone.utc) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/models.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/models.py-tpl index 802d39c..ffa0518 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/models.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/models.py-tpl @@ -9,6 +9,8 @@ from typing import Optional from sqlmodel import Field, SQLModel +from src.app.db.types import UTCDateTime + def _utcnow() -> datetime: return datetime.now(timezone.utc) @@ -20,6 +22,7 @@ class RefreshToken(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) jti: str = Field(index=True, unique=True, max_length=64) user_id: int = Field(index=True, foreign_key="users.id") - expires_at: datetime + # Aware UTC in and out, on SQLite and PostgreSQL alike (see db/types.py). + expires_at: datetime = Field(sa_type=UTCDateTime) revoked: bool = Field(default=False) - created_at: datetime = Field(default_factory=_utcnow) + created_at: datetime = Field(default_factory=_utcnow, sa_type=UTCDateTime) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/repository.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/repository.py-tpl index a7bdff1..414ffb1 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/repository.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/repository.py-tpl @@ -14,6 +14,7 @@ from typing import Optional from sqlalchemy import update from sqlmodel import Session, select +from src.app.db.session import atomic from src.app.domains.auth.models import RefreshToken @@ -24,12 +25,8 @@ class RefreshTokenRepository: @contextmanager def atomic(self) -> Iterator[None]: """Commit everything staged inside the block once, or roll it all back.""" - try: + with atomic(self.session): yield - self.session.commit() - except BaseException: - self.session.rollback() - raise def add(self, jti: str, user_id: int, expires_at: datetime) -> RefreshToken: """Stage a new refresh token record (flushed, not committed).""" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/router.py-tpl index a8becdf..281e8c8 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/router.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/router.py-tpl @@ -1,50 +1,70 @@ # -------------------------------------------------------------------------- # Authentication endpoints: register, login, refresh rotation, logout. # -------------------------------------------------------------------------- -from typing import Annotated +import logging +from typing import Annotated, Any, Dict -from fastapi import APIRouter, Depends, HTTPException, status +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status +from fastapi.responses import JSONResponse from fastapi.security import OAuth2PasswordRequestForm -from src.app.api.deps import CurrentUser, get_auth_service, get_user_service +from src.app.api.deps import AuthServiceDep, CurrentUser, UserServiceDep +from src.app.core.rate_limit import auth_rate_limit +from src.app.core.responses import error_responses from src.app.core.security import TokenError -from src.app.domains.auth.schemas import RefreshRequest, TokenPair -from src.app.domains.auth.service import AuthService +from src.app.domains.auth.schemas import OAuth2Error, RefreshRequest, TokenPair from src.app.domains.users.schemas import UserCreate, UserRead -from src.app.domains.users.service import EmailAlreadyRegisteredError, UserService +from src.app.domains.users.service import EmailAlreadyRegisteredError + +logger = logging.getLogger(__name__) router = APIRouter(prefix="/auth", tags=["auth"]) -UserServiceDep = Annotated[UserService, Depends(get_user_service)] -AuthServiceDep = Annotated[AuthService, Depends(get_auth_service)] +# RFC 6749 section 5.1: token responses must not be cached. +_NO_STORE = {"Cache-Control": "no-store", "Pragma": "no-cache"} + +# Anonymous endpoints that hash passwords or mint tokens are rate limited per +# client address (settings.AUTH_RATE_LIMIT_*); over the budget: 429. +_RATE_LIMITED = [Depends(auth_rate_limit)] +_INVALID_GRANT: Dict[int | str, Dict[str, Any]] = { + status.HTTP_400_BAD_REQUEST: { + "model": OAuth2Error, + "description": "The refresh token is invalid, expired or revoked", + }, + **error_responses(429), +} -@router.post("/register", response_model=UserRead, status_code=status.HTTP_201_CREATED) -def register(payload: UserCreate, users: UserServiceDep) -> UserRead: + +@router.post( + "/register", + status_code=status.HTTP_201_CREATED, + responses=error_responses(409, 429), + dependencies=_RATE_LIMITED, +) +def register( + payload: UserCreate, users: UserServiceDep, request: Request, response: Response +) -> UserRead: """Create an account. Emails are unique and stored lower-cased.""" try: user = users.register(payload) - except EmailAlreadyRegisteredError: + except EmailAlreadyRegisteredError as exc: raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail="An account with this email already exists", - ) - return UserRead( - id=user.id or 0, - email=user.email, - full_name=user.full_name, - is_active=user.is_active, - is_superuser=user.is_superuser, - scopes=user.scope_list, - created_at=user.created_at, - ) - - -@router.post("/login", response_model=TokenPair) + ) from exc + response.headers["Location"] = str(request.url_for("read_user", user_id=user.id)) + return UserRead.model_validate(user) + + +@router.post( + "/login", responses=error_responses(401, 403, 429), dependencies=_RATE_LIMITED +) def login( form_data: Annotated[OAuth2PasswordRequestForm, Depends()], users: UserServiceDep, auth: AuthServiceDep, + response: Response, ) -> TokenPair: """OAuth2 password flow — ``username`` carries the email address.""" user = users.authenticate(form_data.username, form_data.password) @@ -58,16 +78,38 @@ def login( raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user" ) + response.headers.update(_NO_STORE) return auth.issue_token_pair(user) -@router.post("/refresh", response_model=TokenPair) -def refresh(payload: RefreshRequest, auth: AuthServiceDep) -> TokenPair: - """Rotate a refresh token: the presented token is revoked on success.""" +@router.post( + "/refresh", + response_model=TokenPair, + responses=_INVALID_GRANT, + dependencies=_RATE_LIMITED, +) +def refresh( + payload: RefreshRequest, auth: AuthServiceDep, response: Response +) -> TokenPair | JSONResponse: + """Rotate a refresh token: the presented token is revoked on success. + + A rejected token answers 400 ``invalid_grant`` (RFC 6749 section 5.2); + the reason is logged, not returned. + """ try: - return auth.rotate(payload.refresh_token) + tokens = auth.rotate(payload.refresh_token) except TokenError as exc: - raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc)) + logger.info("Refresh token rejected: %s", exc) + return JSONResponse( + status_code=status.HTTP_400_BAD_REQUEST, + content=OAuth2Error( + error="invalid_grant", + error_description="The refresh token is invalid, expired or revoked.", + ).model_dump(), + headers=_NO_STORE, + ) + response.headers.update(_NO_STORE) + return tokens @router.post("/logout", status_code=status.HTTP_204_NO_CONTENT) @@ -76,7 +118,11 @@ def logout(payload: RefreshRequest, auth: AuthServiceDep) -> None: auth.revoke(payload.refresh_token) -@router.post("/logout-all", status_code=status.HTTP_204_NO_CONTENT) +@router.post( + "/logout-all", + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(401, 403), +) def logout_all(current_user: CurrentUser, auth: AuthServiceDep) -> None: """Revoke every refresh token issued to the authenticated user.""" auth.revoke_all(current_user) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/schemas.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/schemas.py-tpl index fae81bf..3231e46 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/schemas.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/schemas.py-tpl @@ -1,14 +1,27 @@ # -------------------------------------------------------------------------- # Auth API I/O schemas. # -------------------------------------------------------------------------- +from typing import Literal + from pydantic import BaseModel class TokenPair(BaseModel): + """Token response (RFC 6749 section 5.1) plus the rotating refresh token.""" + access_token: str refresh_token: str token_type: str = "bearer" + #: Lifetime of the access token in seconds. + expires_in: int class RefreshRequest(BaseModel): refresh_token: str + + +class OAuth2Error(BaseModel): + """Error response of the token endpoints (RFC 6749 section 5.2).""" + + error: Literal["invalid_grant"] + error_description: str diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/service.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/service.py-tpl index 7cfeb58..574175c 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/service.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/auth/service.py-tpl @@ -6,6 +6,7 @@ # -------------------------------------------------------------------------- from datetime import datetime, timezone +from src.app.core.config import settings from src.app.core.security import ( REFRESH_TOKEN_TYPE, TokenError, @@ -51,7 +52,8 @@ class AuthService: record = self.refresh_tokens.get_by_jti(jti) if record is None or record.revoked: raise TokenError("refresh token is no longer valid") - if _as_utc(record.expires_at) <= datetime.now(timezone.utc): + # ``expires_at`` is read back as aware UTC (``UTCDateTime``). + if record.expires_at <= datetime.now(timezone.utc): raise TokenError("refresh token has expired") user = self.users.get(record.user_id) @@ -84,11 +86,8 @@ class AuthService: access_token, _, _ = create_access_token(str(user.id), scopes) refresh_token, jti, expires_at = create_refresh_token(str(user.id), scopes) self.refresh_tokens.add(jti, user.id or 0, expires_at) - return TokenPair(access_token=access_token, refresh_token=refresh_token) - - -def _as_utc(value: datetime) -> datetime: - """Treat naive datetimes read back from the database as UTC.""" - if value.tzinfo is None: - return value.replace(tzinfo=timezone.utc) - return value + return TokenPair( + access_token=access_token, + refresh_token=refresh_token, + expires_in=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60, + ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/models.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/models.py-tpl index f3fedac..b91b862 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/models.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/models.py-tpl @@ -6,6 +6,8 @@ from typing import List, Optional from sqlmodel import Field, SQLModel +from src.app.db.types import UTCDateTime + def _utcnow() -> datetime: return datetime.now(timezone.utc) @@ -28,7 +30,8 @@ class User(SQLModel, table=True): is_active: bool = Field(default=True) is_superuser: bool = Field(default=False) scopes: str = Field(default="me") - created_at: datetime = Field(default_factory=_utcnow) + # Aware UTC in and out, on SQLite and PostgreSQL alike (see db/types.py). + created_at: datetime = Field(default_factory=_utcnow, sa_type=UTCDateTime) @property def scope_list(self) -> List[str]: diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/repository.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/repository.py-tpl index 50991b7..4c6e99c 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/repository.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/repository.py-tpl @@ -1,10 +1,16 @@ # -------------------------------------------------------------------------- # User data access. +# +# Write methods only stage changes on the session; they never commit on +# their own. ``UserService`` groups them inside ``atomic()``. # -------------------------------------------------------------------------- +from collections.abc import Iterator +from contextlib import contextmanager from typing import List, Optional, Sequence -from sqlmodel import Session, select +from sqlmodel import Session, col, func, select +from src.app.db.session import atomic from src.app.domains.users.models import User @@ -14,6 +20,12 @@ class UserRepository: def __init__(self, session: Session) -> None: self.session = session + @contextmanager + def atomic(self) -> Iterator[None]: + """Commit everything staged inside the block once, or roll it all back.""" + with atomic(self.session): + yield + def get(self, user_id: int) -> Optional[User]: return self.session.get(User, user_id) @@ -21,13 +33,17 @@ class UserRepository: statement = select(User).where(User.email == email) return self.session.exec(statement).first() - def list(self, offset: int = 0, limit: int = 100) -> List[User]: - statement = select(User).offset(offset).limit(limit) + def list_page(self, *, offset: int, limit: int) -> List[User]: + """One page of users ordered by id, so pages never overlap.""" + statement = select(User).order_by(col(User.id)).offset(offset).limit(limit) rows: Sequence[User] = self.session.exec(statement).all() return list(rows) + def count(self) -> int: + return self.session.exec(select(func.count()).select_from(User)).one() + def add(self, user: User) -> User: + """Stage a new user (flushed so its id is assigned, not committed).""" self.session.add(user) - self.session.commit() - self.session.refresh(user) + self.session.flush() return user diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/router.py-tpl index 21cf95e..db247ce 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/router.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/router.py-tpl @@ -1,71 +1,75 @@ # -------------------------------------------------------------------------- -# User endpoints — /users/me and a superuser-only listing. +# User endpoints — /users/me and superuser-only user administration. # -------------------------------------------------------------------------- from typing import List -from fastapi import APIRouter, Depends +from fastapi import APIRouter, Depends, HTTPException, status from src.app.api.deps import ( CurrentUser, - SessionDep, + UserServiceDep, get_current_active_superuser, require_scopes, ) -from src.app.domains.users.models import User -from src.app.domains.users.repository import UserRepository +from src.app.core.pagination import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from src.app.core.responses import error_responses from src.app.domains.users.schemas import UserRead, UserUpdate router = APIRouter(prefix="/users", tags=["users"]) - -def _to_read(user: User) -> UserRead: - return UserRead( - id=user.id or 0, - email=user.email, - full_name=user.full_name, - is_active=user.is_active, - is_superuser=user.is_superuser, - scopes=user.scope_list, - created_at=user.created_at, - ) +superuser_only = [Depends(get_current_active_superuser)] -@router.get("/me", response_model=UserRead) +@router.get("/me", responses=error_responses(401, 403)) def read_current_user(current_user: CurrentUser) -> UserRead: """Return the profile of the authenticated user.""" - return _to_read(current_user) + return UserRead.model_validate(current_user) -@router.patch("/me", response_model=UserRead) +@router.patch("/me", responses=error_responses(401, 403)) def update_current_user( - payload: UserUpdate, current_user: CurrentUser, session: SessionDep + payload: UserUpdate, current_user: CurrentUser, users: UserServiceDep ) -> UserRead: - if payload.full_name is not None: - current_user.full_name = payload.full_name - session.add(current_user) - session.commit() - session.refresh(current_user) - return _to_read(current_user) + """Change only the fields sent; ``"full_name": null`` clears the name.""" + return UserRead.model_validate(users.update(current_user, payload)) @router.get( - "", - response_model=List[UserRead], - dependencies=[Depends(get_current_active_superuser)], + "/me/scopes", + dependencies=[Depends(require_scopes("me"))], + responses=error_responses(401, 403), ) +def read_current_user_scopes(current_user: CurrentUser) -> List[str]: + """Example of a scope-gated route (requires the ``me`` scope).""" + return current_user.scope_list + + +@router.get("", dependencies=superuser_only, responses=error_responses(401, 403)) def list_users( - session: SessionDep, offset: int = 0, limit: int = 100 -) -> List[UserRead]: + users: UserServiceDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> Page[UserRead]: """Superuser-only listing — an example of a role-gated route.""" - users = UserRepository(session).list(offset=offset, limit=limit) - return [_to_read(user) for user in users] + page, total = users.list_page(offset=offset, limit=limit) + return Page[UserRead]( + items=[UserRead.model_validate(user) for user in page], + total=total, + limit=limit, + offset=offset, + ) @router.get( - "/me/scopes", - response_model=List[str], - dependencies=[Depends(require_scopes("me"))], + "/{user_id}", + dependencies=superuser_only, + responses=error_responses(401, 403, 404), ) -def read_current_user_scopes(current_user: CurrentUser) -> List[str]: - """Example of a scope-gated route (requires the ``me`` scope).""" - return current_user.scope_list +def read_user(user_id: int, users: UserServiceDep) -> UserRead: + """Superuser-only: one user by id (the ``Location`` of a registration).""" + user = users.get(user_id) + if user is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail="User not found" + ) + return UserRead.model_validate(user) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/schemas.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/schemas.py-tpl index 6147ae5..1b10dc0 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/schemas.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/schemas.py-tpl @@ -2,9 +2,9 @@ # User API I/O schemas. # -------------------------------------------------------------------------- from datetime import datetime -from typing import List, Optional +from typing import Any, List, Optional -from pydantic import BaseModel, ConfigDict, EmailStr, Field +from pydantic import BaseModel, ConfigDict, EmailStr, Field, field_validator class UserCreate(BaseModel): @@ -14,10 +14,14 @@ class UserCreate(BaseModel): class UserUpdate(BaseModel): + """PATCH body: fields left out are unchanged, ``null`` clears ``full_name``.""" + full_name: Optional[str] = Field(default=None, max_length=255) class UserRead(BaseModel): + """Public profile; never carries the password hash.""" + model_config = ConfigDict(from_attributes=True) id: int @@ -27,3 +31,11 @@ class UserRead(BaseModel): is_superuser: bool scopes: List[str] created_at: datetime + + @field_validator("scopes", mode="before") + @classmethod + def _split_scopes(cls, value: Any) -> Any: + # The table stores scopes as a comma-separated string. + if isinstance(value, str): + return [scope for scope in value.split(",") if scope] + return value diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/service.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/service.py-tpl index 2339042..6ac3ebf 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/service.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/domains/users/service.py-tpl @@ -1,12 +1,20 @@ # -------------------------------------------------------------------------- # User business logic. +# +# Every public write method is one database transaction (``atomic()``). # -------------------------------------------------------------------------- -from typing import List, Optional +from typing import List, Optional, Tuple -from src.app.core.security import hash_password, verify_password +from sqlalchemy.exc import IntegrityError + +from src.app.core.security import ( + hash_password, + verify_dummy_password, + verify_password, +) from src.app.domains.users.models import User from src.app.domains.users.repository import UserRepository -from src.app.domains.users.schemas import UserCreate +from src.app.domains.users.schemas import UserCreate, UserUpdate class EmailAlreadyRegisteredError(Exception): @@ -17,6 +25,14 @@ class UserService: def __init__(self, repository: UserRepository) -> None: self.repository = repository + def get(self, user_id: int) -> Optional[User]: + return self.repository.get(user_id) + + def list_page(self, *, offset: int, limit: int) -> Tuple[List[User], int]: + """Return one page of users and the total number of users.""" + users = self.repository.list_page(offset=offset, limit=limit) + return users, self.repository.count() + def register( self, payload: UserCreate, @@ -39,16 +55,30 @@ class UserService: is_superuser=is_superuser, scopes=",".join(granted), ) - return self.repository.add(user) + try: + with self.repository.atomic(): + self.repository.add(user) + except IntegrityError as exc: + # A concurrent registration won the unique index on ``email``. + raise EmailAlreadyRegisteredError(email) from exc + return user + + def update(self, user: User, payload: UserUpdate) -> User: + """Apply only the fields present in the request body (PATCH).""" + with self.repository.atomic(): + user.sqlmodel_update(payload.model_dump(exclude_unset=True)) + self.repository.session.add(user) + return user def authenticate(self, email: str, password: str) -> Optional[User]: """Return the user when the credentials match, otherwise ``None``. - The hash of a non-existent user is never verified, so this leaks a - small timing difference; add a dummy verify if that matters to you. + An unknown email is still checked against a dummy hash, so both + failures cost one argon2 verification and take the same time. """ user = self.repository.get_by_email(email.lower()) if user is None: + verify_dummy_password(password) return None if not verify_password(password, user.hashed_password): return None diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/main.py-tpl index 781ab0f..c3f49e2 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/src/app/main.py-tpl @@ -8,6 +8,7 @@ from fastapi import FastAPI from sqlmodel import Session from starlette.middleware.cors import CORSMiddleware +from src.app.api import health from src.app.api.router import api_router from src.app.core.config import settings from src.app.db.session import create_db_and_tables, engine @@ -60,10 +61,12 @@ if settings.all_cors_origins: app.add_middleware( CORSMiddleware, allow_origins=settings.all_cors_origins, - allow_credentials=True, + # Browsers refuse credentials with the "*" wildcard; never send both. + allow_credentials="*" not in settings.all_cors_origins, allow_methods=["*"], allow_headers=["*"], ) -app.include_router(api_router, prefix=settings.API_V1_PREFIX) +app.include_router(health.router) # fastkit:routes +app.include_router(api_router, prefix=settings.API_V1_PREFIX) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/conftest.py-tpl index 58ff7c5..f859ed1 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/conftest.py-tpl @@ -12,7 +12,9 @@ import pytest_asyncio from httpx import ASGITransport, AsyncClient from sqlalchemy.pool import StaticPool from sqlmodel import Session, SQLModel, create_engine + from src.app.core.config import settings +from src.app.core.rate_limit import auth_limiter from src.app.db.session import get_session from src.app.domains.auth import models as auth_models # noqa: F401 from src.app.domains.users import models as user_models # noqa: F401 @@ -21,6 +23,14 @@ from src.app.main import app API = settings.API_V1_PREFIX +@pytest.fixture(autouse=True) +def _reset_rate_limits() -> Generator[None, None, None]: + """Every test starts with fresh auth rate-limit counters.""" + auth_limiter.reset() + yield + auth_limiter.reset() + + @pytest.fixture(name="session") def session_fixture() -> Generator[Session, None, None]: engine = create_engine( diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_auth.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_auth.py-tpl index cf9745b..231e6f5 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_auth.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_auth.py-tpl @@ -7,16 +7,28 @@ from datetime import timedelta from typing import Any, Dict import pytest -from httpx import AsyncClient +from httpx import AsyncClient, Response + from src.app.core.security import ( ACCESS_TOKEN_TYPE, REFRESH_TOKEN_TYPE, _create_token, ) - from tests.conftest import API +def assert_invalid_grant(response: Response) -> None: + """RFC 6749 section 5.2 error for a rejected refresh token.""" + assert response.status_code == 400 + assert response.json()["error"] == "invalid_grant" + assert response.headers["Cache-Control"] == "no-store" + + +def assert_unauthorized(response: Response) -> None: + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == "Bearer" + + @pytest.mark.asyncio async def test_full_auth_flow(client: AsyncClient) -> None: # 1. register @@ -31,6 +43,8 @@ async def test_full_auth_flow(client: AsyncClient) -> None: assert register.status_code == 201 assert register.json()["email"] == "bob@example.com" assert register.json()["scopes"] == ["me"] + assert "hashed_password" not in register.json() + assert register.headers["Location"].endswith(f"{API}/users/{register.json()['id']}") # 2. login (OAuth2 password form) login = await client.post( @@ -40,6 +54,8 @@ async def test_full_auth_flow(client: AsyncClient) -> None: assert login.status_code == 200 tokens = login.json() assert tokens["token_type"] == "bearer" + assert tokens["expires_in"] == 30 * 60 + assert login.headers["Cache-Control"] == "no-store" headers = {"Authorization": f"Bearer {tokens['access_token']}"} @@ -53,13 +69,14 @@ async def test_full_auth_flow(client: AsyncClient) -> None: f"{API}/auth/refresh", json={"refresh_token": tokens["refresh_token"]} ) assert refreshed.status_code == 200 + assert refreshed.headers["Cache-Control"] == "no-store" new_tokens = refreshed.json() assert new_tokens["refresh_token"] != tokens["refresh_token"] replay = await client.post( f"{API}/auth/refresh", json={"refresh_token": tokens["refresh_token"]} ) - assert replay.status_code == 401 + assert_invalid_grant(replay) # 5. logout revokes the current refresh token logout = await client.post( @@ -70,7 +87,7 @@ async def test_full_auth_flow(client: AsyncClient) -> None: after_logout = await client.post( f"{API}/auth/refresh", json={"refresh_token": new_tokens["refresh_token"]} ) - assert after_logout.status_code == 401 + assert_invalid_grant(after_logout) @pytest.mark.asyncio @@ -105,7 +122,7 @@ async def test_login_with_wrong_password_is_rejected( }, ) - assert response.status_code == 401 + assert_unauthorized(response) @pytest.mark.asyncio @@ -115,7 +132,7 @@ async def test_login_with_unknown_email_is_rejected(client: AsyncClient) -> None data={"username": "nobody@example.com", "password": "whatever-123"}, ) - assert response.status_code == 401 + assert_unauthorized(response) @pytest.mark.asyncio @@ -124,7 +141,7 @@ async def test_malformed_token_is_rejected(client: AsyncClient) -> None: f"{API}/users/me", headers={"Authorization": "Bearer not-a-jwt"} ) - assert response.status_code == 401 + assert_unauthorized(response) @pytest.mark.asyncio @@ -142,7 +159,7 @@ async def test_expired_access_token_is_rejected( f"{API}/users/me", headers={"Authorization": f"Bearer {expired}"} ) - assert response.status_code == 401 + assert_unauthorized(response) @pytest.mark.asyncio @@ -154,7 +171,7 @@ async def test_refresh_token_is_not_accepted_as_access_token( headers={"Authorization": f"Bearer {tokens['refresh_token']}"}, ) - assert response.status_code == 401 + assert_unauthorized(response) @pytest.mark.asyncio @@ -165,7 +182,7 @@ async def test_access_token_is_not_accepted_for_refresh( f"{API}/auth/refresh", json={"refresh_token": tokens["access_token"]} ) - assert response.status_code == 401 + assert_invalid_grant(response) @pytest.mark.asyncio @@ -174,7 +191,7 @@ async def test_unknown_refresh_token_is_rejected(client: AsyncClient) -> None: response = await client.post(f"{API}/auth/refresh", json={"refresh_token": unknown}) - assert response.status_code == 401 + assert_invalid_grant(response) @pytest.mark.asyncio @@ -198,4 +215,25 @@ async def test_logout_all_revokes_every_session( f"{API}/auth/refresh", json={"refresh_token": session_tokens["refresh_token"]}, ) - assert response.status_code == 401 + assert_invalid_grant(response) + + +@pytest.mark.asyncio +async def test_refresh_failure_reason_is_not_returned(client: AsyncClient) -> None: + expired, _, _ = _create_token("1", REFRESH_TOKEN_TYPE, timedelta(minutes=-1), []) + + response = await client.post(f"{API}/auth/refresh", json={"refresh_token": expired}) + + assert_invalid_grant(response) + assert response.json()["error_description"] == ( + "The refresh token is invalid, expired or revoked." + ) + + +@pytest.mark.asyncio +async def test_unauthenticated_request_gets_www_authenticate( + client: AsyncClient, +) -> None: + for method, path in (("GET", "/users/me"), ("POST", "/auth/logout-all")): + response = await client.request(method, f"{API}{path}") + assert_unauthorized(response) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_config.py-tpl index fba88b0..494bd0f 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_config.py-tpl @@ -1,44 +1,207 @@ # -------------------------------------------------------------------------- -# Settings validation: production refuses a public example SECRET_KEY. +# Settings validation: the SECRET_KEY rule, ENVIRONMENT values, +# environment variable names and the CORS wildcard. # -------------------------------------------------------------------------- +import json +import os import re +import secrets +import subprocess +import sys from pathlib import Path +from typing import Any import pytest from pydantic import ValidationError -from src.app.core.config import KNOWN_EXAMPLE_SECRET_KEYS, Settings +from src.app.core.config import ( + KNOWN_EXAMPLE_SECRET_KEYS, + MIN_SECRET_KEY_BYTES, + Settings, +) -ENV_EXAMPLE = Path(__file__).resolve().parents[1] / ".env.example" +PROJECT_ROOT = Path(__file__).resolve().parents[1] +ENV_EXAMPLE = PROJECT_ROOT / ".env.example" +APP_MODULE = "src.app.main" +#: Settings without a default; none in this template. +REQUIRED: dict[str, Any] = {} +STRONG_KEY = "k" * MIN_SECRET_KEY_BYTES +#: Every environment except development refuses a missing, public or short +#: SECRET_KEY. +STRICT_ENVIRONMENTS = ["staging", "production"] + +@pytest.fixture(autouse=True) +def _isolated_settings_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Shell variables, in any spelling, must not leak into Settings().""" + for name in list(os.environ): + if name.upper() in {"ENVIRONMENT", "SECRET_KEY", "BACKEND_CORS_ORIGINS"}: + monkeypatch.delenv(name) + + +def make_settings(env_file: Path | None = None, **values: Any) -> Settings: + """Settings from explicit values; a developer's .env is never read.""" + return Settings(_env_file=env_file, **{**REQUIRED, **values}) # type: ignore[call-arg] + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_require_an_explicit_secret_key(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"must be set explicitly when ENVIRONMENT={environment}" + ): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_refuse_a_short_secret_key(environment: str) -> None: + short_key = "k" * (MIN_SECRET_KEY_BYTES - 1) + + with pytest.raises(ValidationError, match=f"at least {MIN_SECRET_KEY_BYTES} bytes"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=short_key) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) @pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) -def test_production_refuses_example_secret_key(example_key: str) -> None: +def test_strict_environments_refuse_every_public_example_key( + environment: str, example_key: str +) -> None: + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=f" {example_key} ") + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environment_errors_say_how_to_generate_a_key(environment: str) -> None: with pytest.raises(ValidationError, match="token_urlsafe"): - Settings(_env_file=None, ENVIRONMENT="production", SECRET_KEY=example_key) + make_settings(ENVIRONMENT=environment) -@pytest.mark.parametrize("environment", ["development", "staging"]) -def test_example_secret_key_is_allowed_outside_production(environment: str) -> None: - settings = Settings( - _env_file=None, ENVIRONMENT=environment, SECRET_KEY="changethis" +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_an_explicit_strong_key(environment: str) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + + assert settings.ENVIRONMENT == environment + assert settings.SECRET_KEY == STRONG_KEY + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_the_key_fastkit_writes_to_env( + tmp_path: Path, environment: str +) -> None: + env_file = tmp_path / ".env" + env_file.write_text( + f"ENVIRONMENT={environment}\nSECRET_KEY={secrets.token_urlsafe(32)}\n", + encoding="utf-8", ) - assert settings.SECRET_KEY == "changethis" + assert make_settings(env_file).ENVIRONMENT == environment + + +def test_development_without_a_key_uses_a_random_one() -> None: + settings = make_settings(ENVIRONMENT="development") + + assert len(settings.SECRET_KEY.encode()) >= MIN_SECRET_KEY_BYTES + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_development_only_warns_about_an_example_key() -> None: + example_key = sorted(KNOWN_EXAMPLE_SECRET_KEYS)[0] + + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings(ENVIRONMENT="development", SECRET_KEY=example_key) + + assert settings.SECRET_KEY == example_key + +@pytest.mark.parametrize("value", ["Production", "PRODUCTION", " production", "prod"]) +def test_unknown_environment_values_fail_closed(value: str) -> None: + with pytest.raises(ValidationError, match="ENVIRONMENT"): + make_settings(ENVIRONMENT=value, SECRET_KEY=STRONG_KEY) -def test_production_accepts_a_real_secret_key() -> None: - settings = Settings( - _env_file=None, - ENVIRONMENT="production", - SECRET_KEY="a-real-unique-key-0123456789abcdef", + +def test_environment_variable_names_are_case_insensitive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("environment", "production") + + with pytest.raises(ValidationError, match="must be set explicitly"): + make_settings() + + monkeypatch.setenv("secret_key", STRONG_KEY) + + assert make_settings().ENVIRONMENT == "production" + + +@pytest.mark.parametrize("raw", ["*", " * ", '["*"]', "*,http://localhost:3000"]) +def test_cors_wildcard_is_accepted(monkeypatch: pytest.MonkeyPatch, raw: str) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + + assert make_settings().all_cors_origins == ["*"] + + +def test_cors_origins_must_be_urls_or_the_wildcard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + + with pytest.raises(ValidationError): + make_settings() + + +#: Runs in a fresh interpreter: the app reads its settings at import time. +_PREFLIGHT = f""" +import json +from fastapi.testclient import TestClient +from {APP_MODULE} import app + +headers = {{ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "GET", +}} +response = TestClient(app).options("/", headers=headers) +allowed = {{ + k: v for k, v in response.headers.items() if k.startswith("access-control-allow-") +}} +print(json.dumps(allowed)) +""" + + +@pytest.mark.parametrize( + ("origins", "allow_origin", "allow_credentials"), + [ + ("*", "*", None), + ("http://localhost:3000", "http://localhost:3000", "true"), + ], +) +def test_cors_wildcard_is_never_combined_with_credentials( + origins: str, allow_origin: str, allow_credentials: str | None +) -> None: + env = { + **os.environ, + **{name: str(value) for name, value in REQUIRED.items()}, + "BACKEND_CORS_ORIGINS": origins, + "ENVIRONMENT": "development", + } + result = subprocess.run( + [sys.executable, "-c", _PREFLIGHT], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + check=False, ) - assert settings.ENVIRONMENT == "production" + assert result.returncode == 0, result.stderr + headers = json.loads(result.stdout.strip().splitlines()[-1]) + assert headers["access-control-allow-origin"] == allow_origin + assert headers.get("access-control-allow-credentials") == allow_credentials def test_env_example_secret_key_is_a_known_example_value() -> None: - """Whatever .env.example ships must be one the production guard rejects.""" + """Whatever .env.example ships must be one the SECRET_KEY guard rejects.""" if not ENV_EXAMPLE.is_file(): pytest.skip(".env.example is not part of this checkout") @@ -48,3 +211,21 @@ def test_env_example_secret_key_is_a_known_example_value() -> None: assert match is not None assert match.group(1).strip() in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_cors_origins_drop_empty_entries(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("BACKEND_CORS_ORIGINS", raising=False) + settings = make_settings( + BACKEND_CORS_ORIGINS="http://localhost:3000, ,http://localhost:5173/", + ) + + assert settings.all_cors_origins == [ + "http://localhost:3000", + "http://localhost:5173", + ] + + +def test_api_v1_prefix_default(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("API_V1_PREFIX", raising=False) + + assert make_settings().API_V1_PREFIX == "/api/v1" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_health.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_health.py-tpl index ae702b6..3f1abea 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_health.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_health.py-tpl @@ -1,15 +1,178 @@ # -------------------------------------------------------------------------- -# Health endpoint smoke test. +# Liveness and readiness probes. # -------------------------------------------------------------------------- +import logging +import threading +import time +from collections.abc import Generator, Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Optional + import pytest from httpx import AsyncClient +from sqlalchemy import Engine +from sqlmodel import Session, create_engine + +from src.app.api import health +from src.app.db.session import get_session +from src.app.main import app + + +class _FakeSession: + """Stands in for the request session and its engine. + + ``/ready`` asks the session for its engine (``get_bind().engine``) and + runs the query on a connection of its own; ``execute`` blocks or fails. + """ + + def __init__(self, error: Optional[Exception] = None) -> None: + self.error = error + self.release = threading.Event() + + def get_bind(self) -> "_FakeSession": + return self -from tests.conftest import API + @property + def engine(self) -> "_FakeSession": + return self + + @contextmanager + def connect(self) -> Iterator["_FakeSession"]: + yield self + + def execute(self, *_: Any, **__: Any) -> None: + if self.error is not None: + raise self.error + # Block like a driver waiting on an unreachable host, until released. + self.release.wait(timeout=30) + + +@pytest.fixture(name="hanging_session") +def hanging_session_fixture() -> Iterator[_FakeSession]: + fake = _FakeSession() + app.dependency_overrides[get_session] = lambda: fake + yield fake + fake.release.set() @pytest.mark.asyncio -async def test_health_endpoint_returns_ok(client: AsyncClient) -> None: - response = await client.get(f"{API}/health") +async def test_health_is_served_at_the_root(client: AsyncClient) -> None: + response = await client.get("/health") assert response.status_code == 200 assert response.json() == {"status": "ok"} + + +@pytest.mark.asyncio +async def test_ready_reports_ok_when_the_database_answers(client: AsyncClient) -> None: + response = await client.get("/ready") + + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + +@pytest.mark.asyncio +async def test_ready_reports_503_when_the_database_is_down( + client: AsyncClient, tmp_path: Path +) -> None: + # A SQLite file inside a directory that does not exist cannot be opened. + broken = create_engine(f"sqlite:///{tmp_path / 'missing' / 'app.db'}") + + def _broken_session() -> Generator[Session, None, None]: + with Session(broken) as session: + yield session + + app.dependency_overrides[get_session] = _broken_session + + response = await client.get("/ready") + + assert response.status_code == 503 + assert response.json() == {"status": "unavailable"} + broken.dispose() + + +@pytest.mark.asyncio +async def test_ready_answers_503_within_the_timeout_when_the_database_hangs( + client: AsyncClient, + hanging_session: _FakeSession, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + monkeypatch.setattr(health, "READY_TIMEOUT_SECONDS", 0.2) + + started = time.monotonic() + with caplog.at_level(logging.WARNING, logger=health.logger.name): + response = await client.get("/ready") + elapsed = time.monotonic() - started + + assert response.status_code == 503 + assert response.json() == {"status": "unavailable"} + assert elapsed < 5 + assert "TimeoutError" in caplog.text + + +@pytest.mark.asyncio +async def test_ready_answers_503_for_any_error( + client: AsyncClient, caplog: pytest.LogCaptureFixture +) -> None: + # Not a SQLAlchemyError: the probe must still answer 503, not 500. + fake = _FakeSession(error=OSError("connection refused")) + app.dependency_overrides[get_session] = lambda: fake + + with caplog.at_level(logging.WARNING, logger=health.logger.name): + response = await client.get("/ready") + + assert response.status_code == 503 + assert response.json() == {"status": "unavailable"} + assert "OSError" in caplog.text + + +@pytest.mark.asyncio +async def test_ready_answers_503_quickly_when_postgres_refuses( + client: AsyncClient, caplog: pytest.LogCaptureFixture +) -> None: + # Nothing listens on port 1; the URL never leaves this machine. + secret = "s3cret-db-password" + refused = create_engine( + f"postgresql+psycopg://app:{secret}@127.0.0.1:1/app", + connect_args={"connect_timeout": 2}, + ) + + def _refused_session() -> Generator[Session, None, None]: + with Session(refused) as session: + yield session + + app.dependency_overrides[get_session] = _refused_session + + started = time.monotonic() + with caplog.at_level(logging.WARNING, logger=health.logger.name): + response = await client.get("/ready") + elapsed = time.monotonic() - started + + assert response.status_code == 503 + assert response.json() == {"status": "unavailable"} + assert elapsed < 5 + assert secret not in caplog.text + refused.dispose() + + +@pytest.mark.asyncio +async def test_ready_probe_never_shares_the_request_session( + client: AsyncClient, monkeypatch: pytest.MonkeyPatch +) -> None: + # The probe thread may outlive the request after a timeout, so it gets + # the engine and opens its own connection instead of using the session + # the request closes when it ends. + probed: list[object] = [] + monkeypatch.setattr(health, "_select_one", probed.append) + + response = await client.get("/ready") + + assert response.status_code == 200 + assert len(probed) == 1 + assert isinstance(probed[0], Engine) + + +def test_ready_timeout_is_a_couple_of_seconds() -> None: + assert 0 < health.READY_TIMEOUT_SECONDS <= 5 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_login_hardening.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_login_hardening.py-tpl new file mode 100644 index 0000000..a99ec0e --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_login_hardening.py-tpl @@ -0,0 +1,223 @@ +# -------------------------------------------------------------------------- +# Login hardening: no user enumeration by timing, rate limits on the +# anonymous auth endpoints, and tokens that must carry their claims. +# -------------------------------------------------------------------------- +from typing import Any, Dict, List + +import jwt +import pytest +from httpx import AsyncClient + +from src.app.core import rate_limit +from src.app.core.config import settings +from src.app.core.rate_limit import RateLimiter +from src.app.domains.users import service as user_service +from tests.conftest import API + +LIMIT = 3 + + +@pytest.fixture(name="small_limit") +def small_limit_fixture(monkeypatch: pytest.MonkeyPatch) -> RateLimiter: + """A fresh limiter allowing ``LIMIT`` requests per endpoint and minute.""" + limiter = RateLimiter(LIMIT, 60) + monkeypatch.setattr(rate_limit, "auth_limiter", limiter) + return limiter + + +@pytest.fixture(name="verify_calls") +def verify_calls_fixture(monkeypatch: pytest.MonkeyPatch) -> List[str]: + """Record every hash the login path verifies a password against.""" + calls: List[str] = [] + real_verify = user_service.verify_password + real_dummy = user_service.verify_dummy_password + + def spy_verify(password: str, hashed_password: str) -> bool: + calls.append("user") + return real_verify(password, hashed_password) + + def spy_dummy(password: str) -> None: + calls.append("dummy") + real_dummy(password) + + monkeypatch.setattr(user_service, "verify_password", spy_verify) + monkeypatch.setattr(user_service, "verify_dummy_password", spy_dummy) + return calls + + +# --- timing: an unknown email costs one password verification too ----------- + + +@pytest.mark.asyncio +async def test_unknown_email_is_verified_against_a_dummy_hash( + client: AsyncClient, verify_calls: List[str] +) -> None: + response = await client.post( + f"{API}/auth/login", + data={"username": "nobody@example.com", "password": "whatever-123"}, + ) + + assert response.status_code == 401 + assert verify_calls == ["dummy"] + + +@pytest.mark.asyncio +async def test_known_and_unknown_email_take_the_same_path( + client: AsyncClient, registered_user: Dict[str, Any], verify_calls: List[str] +) -> None: + email = registered_user["credentials"]["email"] + + wrong_password = await client.post( + f"{API}/auth/login", data={"username": email, "password": "wrong-password"} + ) + unknown_email = await client.post( + f"{API}/auth/login", + data={"username": "nobody@example.com", "password": "wrong-password"}, + ) + + assert wrong_password.status_code == unknown_email.status_code == 401 + assert wrong_password.json() == unknown_email.json() + # One argon2 verification each: the user's hash, then the dummy hash. + assert verify_calls == ["user", "dummy"] + + +# --- rate limits --------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_login_is_limited_with_retry_after( + client: AsyncClient, small_limit: RateLimiter +) -> None: + form = {"username": "nobody@example.com", "password": "whatever-123"} + statuses = [ + (await client.post(f"{API}/auth/login", data=form)).status_code + for _ in range(LIMIT) + ] + blocked = await client.post(f"{API}/auth/login", data=form) + + assert statuses == [401] * LIMIT + assert blocked.status_code == 429 + assert blocked.json() == {"detail": "Too many requests"} + assert 1 <= int(blocked.headers["Retry-After"]) <= 60 + + +@pytest.mark.asyncio +async def test_register_and_refresh_are_limited( + client: AsyncClient, small_limit: RateLimiter +) -> None: + for _ in range(LIMIT): + await client.post(f"{API}/auth/register", json={"email": "x"}) + await client.post(f"{API}/auth/refresh", json={"refresh_token": "x"}) + + register = await client.post(f"{API}/auth/register", json={"email": "x"}) + refresh = await client.post(f"{API}/auth/refresh", json={"refresh_token": "x"}) + + assert register.status_code == 429 + assert refresh.status_code == 429 + assert "Retry-After" in register.headers + + +@pytest.mark.asyncio +async def test_each_endpoint_has_its_own_budget( + client: AsyncClient, small_limit: RateLimiter +) -> None: + form = {"username": "nobody@example.com", "password": "whatever-123"} + for _ in range(LIMIT + 1): + await client.post(f"{API}/auth/login", data=form) + + refresh = await client.post(f"{API}/auth/refresh", json={"refresh_token": "x"}) + + assert refresh.status_code == 400 + + +@pytest.mark.asyncio +async def test_rate_limit_can_be_switched_off( + client: AsyncClient, small_limit: RateLimiter, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(settings, "AUTH_RATE_LIMIT_ENABLED", False) + form = {"username": "nobody@example.com", "password": "whatever-123"} + + statuses = { + (await client.post(f"{API}/auth/login", data=form)).status_code + for _ in range(LIMIT + 2) + } + + assert statuses == {401} + + +@pytest.mark.asyncio +async def test_counters_start_fresh_in_every_test(client: AsyncClient) -> None: + # The autouse fixture in conftest resets the shared limiter, so the + # login attempts of the other tests never leak in here. + assert rate_limit.auth_limiter._windows == {} + + +@pytest.mark.asyncio +async def test_rate_limit_is_documented(client: AsyncClient) -> None: + paths = (await client.get("/openapi.json")).json()["paths"] + + for path in ("/auth/register", "/auth/login", "/auth/refresh"): + assert "429" in paths[f"{API}{path}"]["post"]["responses"] + + +def test_window_resets_after_it_expires() -> None: + now = [0.0] + limiter = RateLimiter(2, 10, clock=lambda: now[0]) + + assert limiter.hit("k") is None + assert limiter.hit("k") is None + assert limiter.hit("k") == pytest.approx(10) + now[0] = 4.0 + assert limiter.hit("k") == pytest.approx(6) + now[0] = 10.0 + assert limiter.hit("k") is None + + +def test_limiter_memory_is_bounded(monkeypatch: pytest.MonkeyPatch) -> None: + now = [0.0] + limiter = RateLimiter(1, 10, clock=lambda: now[0]) + monkeypatch.setattr(RateLimiter, "MAX_KEYS", 3) + + for key in ("a", "b", "c", "d"): + now[0] += 1 + limiter.hit(key) + + assert len(limiter._windows) == 3 + assert "a" not in limiter._windows + + +def test_limiter_refuses_an_empty_budget() -> None: + with pytest.raises(ValueError): + RateLimiter(0, 60) + + +# --- required claims ----------------------------------------------------------- + + +def _signed(claims: Dict[str, Any]) -> str: + """A token signed with the real key, carrying exactly ``claims``.""" + return jwt.encode(claims, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "missing", ["exp", "sub", "type", "jti"], ids=lambda claim: f"no-{claim}" +) +async def test_signed_token_missing_a_claim_is_rejected( + client: AsyncClient, registered_user: Dict[str, Any], missing: str +) -> None: + claims: Dict[str, Any] = { + "sub": str(registered_user["user"]["id"]), + "type": "access", + "jti": "a-jti", + "exp": 4102444800, # 2100-01-01 + "scopes": ["me"], + } + del claims[missing] + + response = await client.get( + f"{API}/users/me", headers={"Authorization": f"Bearer {_signed(claims)}"} + ) + + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == "Bearer" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_refresh_rotation.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_refresh_rotation.py-tpl index 701b389..28dd97b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_refresh_rotation.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_refresh_rotation.py-tpl @@ -16,6 +16,7 @@ from sqlalchemy import func from sqlalchemy.engine import Engine from sqlalchemy.exc import IntegrityError from sqlmodel import Session, SQLModel, create_engine, select + from src.app.core.security import ( REFRESH_TOKEN_TYPE, TokenError, @@ -48,9 +49,14 @@ def engine_fixture(tmp_path: Path) -> Generator[Engine, None, None]: @pytest.fixture(name="user_id") def user_id_fixture(engine: Engine) -> int: with Session(engine) as session: - user = UserRepository(session).add( - User(email="carol@example.com", hashed_password=hash_password("pw-123456")) - ) + repository = UserRepository(session) + with repository.atomic(): + user = repository.add( + User( + email="carol@example.com", + hashed_password=hash_password("pw-123456"), + ) + ) assert user.id is not None return user.id diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_timestamps.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_timestamps.py-tpl new file mode 100644 index 0000000..520ce4c --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_timestamps.py-tpl @@ -0,0 +1,127 @@ +# -------------------------------------------------------------------------- +# Timestamps are stored and returned as aware UTC datetimes. +# +# ``UTCDateTime`` (src/app/db/types.py) converts on write and normalises on +# read, so refresh token expiry is the same instant on SQLite and on a +# PostgreSQL server in any time zone. +# -------------------------------------------------------------------------- +from datetime import datetime, timedelta, timezone +from typing import Dict + +import pytest +from httpx import AsyncClient +from sqlalchemy.exc import StatementError +from sqlmodel import Session, select + +from src.app.core.config import settings +from src.app.core.security import ( + REFRESH_TOKEN_TYPE, + TokenError, + decode_token, + hash_password, +) +from src.app.domains.auth.models import RefreshToken +from src.app.domains.auth.repository import RefreshTokenRepository +from src.app.domains.auth.service import AuthService +from src.app.domains.users.models import User +from src.app.domains.users.repository import UserRepository + +API = settings.API_V1_PREFIX +UTC_PLUS_9 = timezone(timedelta(hours=9)) +UTC_MINUS_8 = timezone(timedelta(hours=-8)) + + +def _user(session: Session) -> User: + user = User(email="dave@example.com", hashed_password=hash_password("pw-123456")) + session.add(user) + session.commit() + session.refresh(user) + return user + + +def _service(session: Session) -> AuthService: + return AuthService(UserRepository(session), RefreshTokenRepository(session)) + + +def _record(session: Session, refresh_token: str) -> RefreshToken: + jti = str(decode_token(refresh_token, REFRESH_TOKEN_TYPE)["jti"]) + session.expunge_all() + return session.exec(select(RefreshToken).where(RefreshToken.jti == jti)).one() + + +def test_created_at_round_trips_as_aware_utc(session: Session) -> None: + written = datetime(2026, 1, 2, 12, 30, tzinfo=UTC_PLUS_9) + session.add(User(email="erin@example.com", hashed_password="x", created_at=written)) + session.commit() + session.expunge_all() + + user = session.exec(select(User)).one() + + assert user.created_at.utcoffset() == timedelta(0) + assert user.created_at == written + assert user.created_at.hour == 3 + + +def test_stored_refresh_expiry_is_the_token_exp_in_utc(session: Session) -> None: + pair = _service(session).issue_token_pair(_user(session)) + exp = decode_token(pair.refresh_token, REFRESH_TOKEN_TYPE)["exp"] + + record = _record(session, pair.refresh_token) + + assert record.expires_at.utcoffset() == timedelta(0) + expected = datetime.fromtimestamp(exp, timezone.utc) + assert abs(record.expires_at - expected) < timedelta(seconds=1) + assert record.expires_at > datetime.now(timezone.utc) + + +@pytest.mark.parametrize( + ("offset_from_now", "zone", "accepted"), + [ + (timedelta(minutes=-1), UTC_PLUS_9, False), + (timedelta(hours=1), UTC_MINUS_8, True), + ], +) +def test_rotation_compares_expiry_as_an_instant( + session: Session, offset_from_now: timedelta, zone: timezone, accepted: bool +) -> None: + service = _service(session) + pair = service.issue_token_pair(_user(session)) + record = _record(session, pair.refresh_token) + # Same instant regardless of the offset it is expressed in. + record.expires_at = (datetime.now(timezone.utc) + offset_from_now).astimezone(zone) + session.add(record) + session.commit() + + if accepted: + assert service.rotate(pair.refresh_token).refresh_token + else: + with pytest.raises(TokenError, match="expired"): + service.rotate(pair.refresh_token) + + +def test_naive_datetime_is_rejected(session: Session) -> None: + session.add( + User( + email="frank@example.com", + hashed_password="x", + created_at=datetime(2026, 1, 2, 12), + ) + ) + + with pytest.raises(StatementError, match="naive datetime"): + session.commit() + session.rollback() + + +@pytest.mark.asyncio +async def test_api_created_at_carries_an_offset( + client: AsyncClient, tokens: Dict[str, str] +) -> None: + response = await client.get( + f"{API}/users/me", + headers={"Authorization": f"Bearer {tokens['access_token']}"}, + ) + assert response.status_code == 200, response.text + + created_at = datetime.fromisoformat(response.json()["created_at"]) + assert created_at.utcoffset() == timedelta(0) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_users.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_users.py-tpl index b533437..fdf899e 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_users.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/tests/test_users.py-tpl @@ -6,10 +6,10 @@ from typing import Any, Dict import pytest from httpx import AsyncClient from sqlmodel import Session + from src.app.domains.users.repository import UserRepository from src.app.domains.users.schemas import UserCreate from src.app.domains.users.service import UserService - from tests.conftest import API @@ -18,6 +18,7 @@ async def test_me_requires_authentication(client: AsyncClient) -> None: response = await client.get(f"{API}/users/me") assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == "Bearer" @pytest.mark.asyncio @@ -32,6 +33,34 @@ async def test_update_current_user(client: AsyncClient, tokens: Dict[str, str]) assert response.json()["full_name"] == "Alice Liddell" +@pytest.mark.asyncio +async def test_update_with_empty_body_changes_nothing( + client: AsyncClient, tokens: Dict[str, str] +) -> None: + headers = {"Authorization": f"Bearer {tokens['access_token']}"} + + response = await client.patch(f"{API}/users/me", json={}, headers=headers) + + assert response.status_code == 200 + assert response.json()["full_name"] == "Alice" + + +@pytest.mark.asyncio +async def test_update_with_explicit_null_clears_full_name( + client: AsyncClient, tokens: Dict[str, str] +) -> None: + headers = {"Authorization": f"Bearer {tokens['access_token']}"} + + response = await client.patch( + f"{API}/users/me", json={"full_name": None}, headers=headers + ) + + assert response.status_code == 200 + assert response.json()["full_name"] is None + me = await client.get(f"{API}/users/me", headers=headers) + assert me.json()["full_name"] is None + + @pytest.mark.asyncio async def test_me_scopes_endpoint(client: AsyncClient, tokens: Dict[str, str]) -> None: headers = {"Authorization": f"Bearer {tokens['access_token']}"} @@ -53,10 +82,7 @@ async def test_listing_users_requires_superuser( assert response.status_code == 403 -@pytest.mark.asyncio -async def test_superuser_can_list_users( - client: AsyncClient, session: Session, registered_user: Dict[str, Any] -) -> None: +async def _superuser_headers(client: AsyncClient, session: Session) -> Dict[str, str]: UserService(UserRepository(session)).register( UserCreate( email="root@example.com", password="root-password", full_name="Root" @@ -68,10 +94,91 @@ async def test_superuser_can_list_users( f"{API}/auth/login", data={"username": "root@example.com", "password": "root-password"}, ) - headers = {"Authorization": f"Bearer {login.json()['access_token']}"} + return {"Authorization": f"Bearer {login.json()['access_token']}"} + + +@pytest.mark.asyncio +async def test_superuser_can_list_users( + client: AsyncClient, session: Session, registered_user: Dict[str, Any] +) -> None: + headers = await _superuser_headers(client, session) response = await client.get(f"{API}/users", headers=headers) assert response.status_code == 200 - emails = {user["email"] for user in response.json()} - assert {"root@example.com", registered_user["user"]["email"]} <= emails + body = response.json() + assert set(body) == {"items", "total", "limit", "offset"} + assert body["total"] == 2 + assert (body["limit"], body["offset"]) == (20, 0) + # Ordered by id: the registered user came first. + assert [user["email"] for user in body["items"]] == [ + registered_user["user"]["email"], + "root@example.com", + ] + assert all("hashed_password" not in user for user in body["items"]) + + +@pytest.mark.asyncio +async def test_user_listing_is_paginated( + client: AsyncClient, session: Session, registered_user: Dict[str, Any] +) -> None: + headers = await _superuser_headers(client, session) + + response = await client.get( + f"{API}/users", params={"limit": 1, "offset": 1}, headers=headers + ) + + assert response.status_code == 200 + body = response.json() + assert body["total"] == 2 + assert [user["email"] for user in body["items"]] == ["root@example.com"] + + +@pytest.mark.asyncio +async def test_user_listing_rejects_out_of_range_parameters( + client: AsyncClient, session: Session +) -> None: + headers = await _superuser_headers(client, session) + + for params in ({"limit": 0}, {"limit": 101}, {"offset": -1}): + response = await client.get(f"{API}/users", params=params, headers=headers) + assert response.status_code == 422, params + + +@pytest.mark.asyncio +async def test_registration_location_resolves_for_a_superuser( + client: AsyncClient, session: Session +) -> None: + headers = await _superuser_headers(client, session) + register = await client.post( + f"{API}/auth/register", + json={"email": "dave@example.com", "password": "dave-password"}, + ) + + response = await client.get(register.headers["Location"], headers=headers) + + assert response.status_code == 200 + assert response.json() == register.json() + + +@pytest.mark.asyncio +async def test_unknown_user_returns_404(client: AsyncClient, session: Session) -> None: + headers = await _superuser_headers(client, session) + + response = await client.get(f"{API}/users/999999", headers=headers) + + assert response.status_code == 404 + assert response.json() == {"detail": "User not found"} + + +@pytest.mark.asyncio +async def test_reading_a_user_requires_superuser( + client: AsyncClient, tokens: Dict[str, str], registered_user: Dict[str, Any] +) -> None: + headers = {"Authorization": f"Bearer {tokens['access_token']}"} + + response = await client.get( + f"{API}/users/{registered_user['user']['id']}", headers=headers + ) + + assert response.status_code == 403 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.env.example-tpl index c9d6bec..50c60cb 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.env.example-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.env.example-tpl @@ -1 +1,11 @@ +# .env.example keeps a public placeholder; fastkit writes a unique key to the +# local, git-ignored .env. With any ENVIRONMENT other than development +# (staging or production) the app refuses to start when SECRET_KEY is unset, +# a public example value or shorter than 32 bytes. SECRET_KEY=changethis +# One of: development, staging, production. +# ENVIRONMENT=development +# API_V1_PREFIX=/api/v1 +# Allowed browser origins, comma-separated or a JSON list. "*" allows any +# origin, but then without credentials (cookies, Authorization headers): +# BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl index 5dec861..95d9455 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl @@ -16,28 +16,32 @@ A FastAPI-based REST API demonstrating asynchronous processing and standardized ``` . ├── src/ -│   ├── core -│   │   └── config.py -│   └── api -│   │ ├── api.py -│   │ └── routes -│   │ └── items.py +│ ├── main.py +│ ├── core +│ │ ├── config.py +│ │ └── pagination.py # Page[T] and limit/offset parameters +│ ├── api +│ │ ├── api.py +│ │ ├── deps.py +│ │ └── routes +│ │ └── items.py │ ├── schemas -│ │ ├── base.py # Base response schema +│ │ ├── base.py # Response envelopes │ │ └── items.py │ ├── helper -│ │ ├── exceptions.py # Exception handlers -│ │ └── pagination.py # Paginator -│   ├── crud -│   │   └── items.py -│   ├── mocks -│   │   └── mock_items.json +│ │ ├── exceptions.py # Error codes and exception handlers +│ │ └── responses.py # Success envelope builder +│ ├── crud +│ │ └── items.py +│ ├── mocks +│ │ └── mock_items.json │ └── utils │ └── documents.py # custom OpenAPI docs generator └── tests ├── __init__.py + ├── conftest.py ├── test_items.py - └── conftest.py + └── test_main.py ``` ## How to Run @@ -71,46 +75,52 @@ http://127.0.0.1:8000/docs ## API Endpoints -| Method | Endpoint | Description | -|--------|------------------|----------------------------| -| GET | `/items/` | List all items | -| GET | `/items/{id}` | Get single item | -| POST | `/items/` | Create new item | -| PUT | `/items/{id}` | Update existing item | -| DELETE | `/items/{id}` | Delete item | +Business routes are mounted under `API_V1_PREFIX` (default `/api/v1`). + +| Method | Endpoint | Status | Description | +|--------|----------------------|--------|-------------------------------------------------| +| GET | `/health` | 200 | Liveness probe, `{"status": "ok"}` (no envelope) | +| GET | `/api/v1/items` | 200 | List items (`limit` 1-100, default 20; `offset`) | +| POST | `/api/v1/items` | 201 | Create an item (`Location` header points to it) | +| GET | `/api/v1/items/{id}` | 200 | Get one item | +| PUT | `/api/v1/items/{id}` | 200 | Replace an item (all fields required) | +| PATCH | `/api/v1/items/{id}` | 200 | Update only the fields sent | +| DELETE | `/api/v1/items/{id}` | 204 | Delete an item (empty body, no envelope) | ## Key Features ### 1. Custom Response System -- **Standardized Response Format** (`schemas/base.py`): +- **One envelope for every JSON response** (`schemas/base.py`): ```python class ResponseSchema(BaseModel, Generic[T]): timestamp: str # ISO 8601 format status: int # HTTP status code - code: str # Custom error code - path: str # Request endpoint - message: T # Response payload/error + code: str # Custom code (HTTP-200, DATA-002, ...) + path: str # Request path (no host, no query string) + message: T # Payload, error text, or list of invalid fields ``` - **Exception Handling** (`helper/exceptions.py`): - - `InternalException` class with error code mapping - - Automatic error response formatting - - Custom error codes with HTTP status mapping + - `InternalException` with error code mapping for your own errors + - Handlers wrap `HTTPException` (also the 404 for unknown routes and 405), validation errors (422) and unhandled exceptions (500) in the same envelope + - A 500 answers `"Internal server error"`; the exception itself is only logged #### Response Examples -##### Success Response +##### List (a page inside the envelope) ```json { "timestamp": "2024-02-15T09:30:00.000Z", "status": 200, "code": "HTTP-200", - "path": "/items/1", + "path": "/api/v1/items", "message": { - "id": 1, - "name": "Test Item 1", - "price": 20.0, - "category": "test" + "items": [ + {"id": 1, "name": "Test Item 1", "description": null, "price": 20.0, "category": "test"} + ], + "total": 1, + "limit": 20, + "offset": 0 } } ``` @@ -122,15 +132,29 @@ http://127.0.0.1:8000/docs "timestamp": "2024-02-15T09:30:00.000Z", "status": 404, "code": "DATA-002", - "path": "/items/999", - "message": "ERROR: Item not found" + "path": "/api/v1/items/999", + "message": "Item not found" +} +``` + +##### Validation Error (422) + +```json +{ + "timestamp": "2024-02-15T09:30:00.000Z", + "status": 422, + "code": "HTTP-006", + "path": "/api/v1/items", + "message": [ + {"loc": ["query", "limit"], "msg": "Input should be less than or equal to 100", "type": "less_than_equal"} + ] } ``` ### 2. Async Operations -- Asynchronous CRUD operations with aiofiles -- Non-blocking I/O for JSON data management -- Async test client with pytest-asyncio +- Asynchronous CRUD operations with aiofiles (file calls run in a worker thread) +- An `asyncio.Lock` guards every read-modify-write of the JSON file +- Async test client with pytest-asyncio; tests use a temporary data file, never `src/mocks` ### 3. Enhanced Documentation - Custom OpenAPI tags and descriptions (`utils/documents.py`) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/pyproject.toml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/pyproject.toml-tpl index 25c3795..bd93ecd 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/pyproject.toml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/pyproject.toml-tpl @@ -13,7 +13,6 @@ dependencies = [ "uvicorn[standard]>=0.52.4", "pydantic>=2.13.5", "pydantic-settings>=2.15.0", - "SQLAlchemy>=2.0.52", "python-dotenv>=1.2.3", "aiofiles>=25.1.0", ] @@ -26,7 +25,6 @@ dev = [ "black>=26.10.1", "isort>=9.0.1", "mypy>=2.3.1", - "PyYAML>=6.0.3", ] [dependency-groups] @@ -37,7 +35,6 @@ dev = [ "black>=26.10.1", "isort>=9.0.1", "mypy>=2.3.1", - "PyYAML>=6.0.3", ] [tool.fastapi-fastkit] @@ -86,3 +83,4 @@ python_classes = ["Test*"] python_functions = ["test_*"] addopts = "-v --tb=short" asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/requirements.txt-tpl index 5a5f1e1..a1c5f5a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/requirements.txt-tpl @@ -1,7 +1,7 @@ aiofiles==25.1.0 annotated-doc==0.0.5 annotated-types==0.8.0 -anyio==4.15.0 +anyio==4.16.0 ast-serialize==0.9.0 black==26.10.1 certifi==2026.10.23 @@ -30,8 +30,7 @@ pytest-asyncio==1.4.0 python-dotenv==1.2.3 pytokens==0.4.1 PyYAML==6.0.3 -SQLAlchemy==2.0.52 -starlette==1.6.0 +starlette==1.10.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/setup.cfg-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/setup.cfg-tpl deleted file mode 100644 index 3e01a52..0000000 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/setup.cfg-tpl +++ /dev/null @@ -1,12 +0,0 @@ -[flake8] -ignore = E501, E305 - -[isort] -line_length=100 -virtual_env=venv - -[tool:pytest] -testpaths = tests -addopts = -ra -q -asyncio_mode = auto -asyncio_default_fixture_loop_scope=session diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/api.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/api.py-tpl index 76b2dcd..610135e 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/api.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/api.py-tpl @@ -8,5 +8,5 @@ from src.api.routes import items # fastkit:imports api_router = APIRouter() -api_router.include_router(items.router, prefix="/items", tags=["items"]) +api_router.include_router(items.router) # fastkit:routes diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/deps.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/deps.py-tpl new file mode 100644 index 0000000..39c53bd --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/deps.py-tpl @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------- +# Shared route dependencies +# -------------------------------------------------------------------------- +from typing import Annotated + +from fastapi import Depends + +from src.crud.items import ItemStore, item_store + + +def get_item_store() -> ItemStore: + """Return the item store (tests override this dependency).""" + return item_store + + +ItemStoreDep = Annotated[ItemStore, Depends(get_item_store)] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/routes/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/routes/items.py-tpl index 6332461..0163d9a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/routes/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/routes/items.py-tpl @@ -1,172 +1,94 @@ # -------------------------------------------------------------------------- # Item CRUD Endpoint +# +# Successful responses are wrapped in ``ResponseSchema``; errors are wrapped +# by the handlers in ``src/helper/exceptions.py``. DELETE answers 204 with +# no body, so it has no envelope. # -------------------------------------------------------------------------- -from datetime import datetime, timezone -from typing import Any +from fastapi import APIRouter, Request, Response, status -from fastapi import APIRouter, Request - -from src.crud.items import read_items, write_items -from src.helper.exceptions import ErrorCode, InternalException +from src.api.deps import ItemStoreDep +from src.core.pagination import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from src.helper.exceptions import ErrorCode, InternalException, error_responses +from src.helper.responses import success_response from src.schemas.base import ResponseSchema -from src.schemas.items import ItemCreate, ItemResponse +from src.schemas.items import ItemCreate, ItemRead, ItemUpdate -router = APIRouter(tags=["items"]) +router = APIRouter( + prefix="/items", + tags=["items"], + responses=error_responses(422, 500), +) -error_responses: dict[int | str, dict[str, Any]] = { - 404: {"model": ResponseSchema[str], "description": "Item not found"}, - 500: {"model": ResponseSchema[str], "description": "Server error"}, -} +def item_not_found() -> InternalException: + return InternalException( + message="Item not found", error_code=ErrorCode.ITEM_NOT_FOUND + ) -@router.get( - "/", - summary="Get all items", - response_model=ResponseSchema[list[ItemResponse]], - responses=error_responses, -) -async def read_all_items(request: Request): - try: - items = await read_items() - return ResponseSchema( - timestamp=datetime.now(timezone.utc) - .isoformat(timespec="milliseconds") - .replace("+00:00", "Z"), - status=200, - code="HTTP-200", - path=str(request.url), - message=items, - ) - except Exception as e: - # You can raise any custom exception you want here - raise InternalException( - message=f"Error retrieving items: {str(e)}", - error_code=ErrorCode.UNKNOWN_ERROR, # Put your custom error code here - ) - - -@router.get( - "/{item_id}", - summary="Get item by ID", - response_model=ResponseSchema[ItemResponse], - responses=error_responses, -) -async def read_item(item_id: int, request: Request): - try: - items = await read_items() - item = next((i for i in items if i["id"] == item_id), None) - if not item: - raise InternalException( - message="Item not found", error_code=ErrorCode.NOT_FOUND - ) - return ResponseSchema( - timestamp=datetime.now(timezone.utc) - .isoformat(timespec="milliseconds") - .replace("+00:00", "Z"), - status=200, - code="HTTP-200", - path=str(request.url), - message=item, - ) - except InternalException as e: - raise e - except Exception as e: - raise InternalException( - message=f"Error retrieving item: {str(e)}", - error_code=ErrorCode.UNKNOWN_ERROR, - ) - - -@router.post( - "/", - summary="Create new item", - response_model=ResponseSchema[ItemResponse], - status_code=201, - responses=error_responses, -) -async def create_item(item: ItemCreate, request: Request): - try: - items = await read_items() - new_id = max(i["id"] for i in items) + 1 if items else 1 - new_item = {**item.model_dump(), "id": new_id} - items.append(new_item) - await write_items(items) - return ResponseSchema( - timestamp=datetime.now(timezone.utc) - .isoformat(timespec="milliseconds") - .replace("+00:00", "Z"), - status=201, - code="HTTP-201", - path=str(request.url), - message=new_item, - ) - except Exception as e: - raise InternalException( - message=f"Error creating item: {str(e)}", error_code=ErrorCode.UNKNOWN_ERROR - ) - - -@router.put( - "/{item_id}", - summary="Update item", - response_model=ResponseSchema[ItemResponse], - responses=error_responses, -) -async def update_item(item_id: int, item: ItemCreate, request: Request): - try: - items = await read_items() - index = next((i for i, v in enumerate(items) if v["id"] == item_id), None) - if index is None: - raise InternalException( - message="Item not found", error_code=ErrorCode.NOT_FOUND - ) - updated_item = {**item.model_dump(), "id": item_id} - items[index] = updated_item - await write_items(items) - return ResponseSchema( - timestamp=datetime.now(timezone.utc) - .isoformat(timespec="milliseconds") - .replace("+00:00", "Z"), - status=200, - code="HTTP-200", - path=str(request.url), - message=updated_item, - ) - except InternalException as e: - raise e - except Exception as e: - raise InternalException( - message=f"Error updating item: {str(e)}", error_code=ErrorCode.UNKNOWN_ERROR - ) + +@router.get("", summary="List items") +async def list_items( + request: Request, + store: ItemStoreDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> ResponseSchema[Page[ItemRead]]: + items, total = await store.list_page(offset=offset, limit=limit) + page = Page[ItemRead]( + items=[ItemRead.model_validate(item) for item in items], + total=total, + limit=limit, + offset=offset, + ) + return success_response(request, page) + + +@router.get("/{item_id}", summary="Get item by ID", responses=error_responses(404)) +async def get_item( + item_id: int, request: Request, store: ItemStoreDep +) -> ResponseSchema[ItemRead]: + item = await store.get(item_id) + if item is None: + raise item_not_found() + return success_response(request, ItemRead.model_validate(item)) + + +@router.post("", summary="Create item", status_code=status.HTTP_201_CREATED) +async def create_item( + payload: ItemCreate, request: Request, response: Response, store: ItemStoreDep +) -> ResponseSchema[ItemRead]: + item = await store.create(payload.model_dump()) + response.headers["Location"] = str(request.url_for("get_item", item_id=item["id"])) + return success_response(request, ItemRead.model_validate(item), status_code=201) + + +@router.put("/{item_id}", summary="Replace item", responses=error_responses(404)) +async def replace_item( + item_id: int, payload: ItemCreate, request: Request, store: ItemStoreDep +) -> ResponseSchema[ItemRead]: + item = await store.replace(item_id, payload.model_dump()) + if item is None: + raise item_not_found() + return success_response(request, ItemRead.model_validate(item)) + + +@router.patch("/{item_id}", summary="Update item", responses=error_responses(404)) +async def update_item( + item_id: int, payload: ItemUpdate, request: Request, store: ItemStoreDep +) -> ResponseSchema[ItemRead]: + item = await store.update(item_id, payload.model_dump(exclude_unset=True)) + if item is None: + raise item_not_found() + return success_response(request, ItemRead.model_validate(item)) @router.delete( "/{item_id}", summary="Delete item", - response_model=ResponseSchema[str], - responses=error_responses, + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(404), ) -async def delete_item(item_id: int, request: Request): - try: - items = await read_items() - new_items = [i for i in items if i["id"] != item_id] - if len(new_items) == len(items): - raise InternalException( - message="Item not found", error_code=ErrorCode.NOT_FOUND - ) - await write_items(new_items) - return ResponseSchema( - timestamp=datetime.now(timezone.utc) - .isoformat(timespec="milliseconds") - .replace("+00:00", "Z"), - status=200, - code="HTTP-200", - path=str(request.url), - message="Item deleted successfully", - ) - except InternalException as e: - raise e - except Exception as e: - raise InternalException( - message=f"Error deleting item: {str(e)}", error_code=ErrorCode.UNKNOWN_ERROR - ) +async def delete_item(item_id: int, store: ItemStoreDep) -> None: + if not await store.delete(item_id): + raise item_not_found() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/config.py-tpl index a22e29a..ca0f5a5 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/config.py-tpl @@ -1,20 +1,64 @@ # -------------------------------------------------------------------------- # Configuration module # -------------------------------------------------------------------------- +import json import secrets import warnings -from typing import Annotated, Any, Literal, Self +from typing import Annotated, Any, Literal from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator -from pydantic_settings import BaseSettings, SettingsConfigDict +from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict -def parse_cors(v: Any) -> list[str] | str: - if isinstance(v, str) and not v.startswith("["): - return [i.strip() for i in v.split(",")] - elif isinstance(v, (list, str)): - return v - raise ValueError(v) +def parse_cors(value: Any) -> Any: + """Read origins from a comma-separated string or a JSON list. + + Blank entries are dropped, so ``BACKEND_CORS_ORIGINS=`` or a trailing + comma never turns into an empty origin. + """ + if isinstance(value, str): + value = value.strip() + if value.startswith("["): + value = json.loads(value) + else: + value = value.split(",") + if isinstance(value, list): + return [str(origin).strip() for origin in value if str(origin).strip()] + raise ValueError(value) + + +# Each origin is a full URL such as http://localhost:3000, or "*" for any +# origin. "*" never goes together with credentials (cookies, Authorization +# headers): browsers refuse that, so main.py turns credentials off for it. +CorsOrigins = Annotated[ + list[Literal["*"] | AnyUrl], NoDecode, BeforeValidator(parse_cors) +] + +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + "your-secret-key-here", + "change-me-in-production", + "your-mcp-api-key-here", + } +) + +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = 32 + +_GENERATE_KEY_HINT = ( + "Generate one with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) class Settings(BaseSettings): @@ -24,40 +68,63 @@ class Settings(BaseSettings): extra="ignore", ) + PROJECT_NAME: str = "" + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + # The shipped code signs nothing with SECRET_KEY yet, but authentication + # you add later (including the JWT and Session options of fastkit init) + # signs tokens or cookies with it, so treat it as a production secret. + # fastkit writes a unique value to .env; staging and production refuse a + # missing, public or short key (see _check_secret_key below). SECRET_KEY: str = secrets.token_urlsafe(32) - ENVIRONMENT: Literal["development", "production"] = "development" - CLIENT_ORIGIN: str = "" + # Every business router is mounted under this prefix (see src/main.py). + API_V1_PREFIX: str = "/api/v1" - BACKEND_CORS_ORIGINS: Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] = ( - [] - ) + BACKEND_CORS_ORIGINS: CorsOrigins = [] @computed_field # type: ignore[prop-decorator] @property def all_cors_origins(self) -> list[str]: - return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + [ - self.CLIENT_ORIGIN - ] - - PROJECT_NAME: str = "" - - def _check_default_secret(self, var_name: str, value: str | None) -> None: - if value == "changethis": - message = ( - f'The value of {var_name} is "changethis", ' - "for security, please change it, at least for deployments." - ) - if self.ENVIRONMENT == "development": - warnings.warn(message, stacklevel=1) - else: - raise ValueError(message) + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins @model_validator(mode="after") - def _enforce_non_default_secrets(self) -> Self: - self._check_default_secret("SECRET_KEY", self.SECRET_KEY) + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) + return self + env = f"ENVIRONMENT={self.ENVIRONMENT}" + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT + ) + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: + raise ValueError( + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT + ) return self -settings = Settings() # type: ignore +settings = Settings() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/pagination.py-tpl new file mode 100644 index 0000000..2688822 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/pagination.py-tpl @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------- +# Limit/offset pagination shared by every list endpoint. +# +# List endpoints take ``limit: LimitParam = DEFAULT_LIMIT`` and +# ``offset: OffsetParam = 0`` and return a ``Page[T]`` envelope: +# {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range +# values are rejected with a 422 rather than clamped. +# -------------------------------------------------------------------------- +from typing import Annotated, Generic, TypeVar + +from fastapi import Query +from pydantic import BaseModel + +T = TypeVar("T") + +#: Page size used when the client sends no ``limit``. +DEFAULT_LIMIT = 20 +#: Largest page a client may ask for. +MAX_LIMIT = 100 + +LimitParam = Annotated[ + int, Query(ge=1, le=MAX_LIMIT, description="Maximum number of items to return.") +] +OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] + + +class Page(BaseModel, Generic[T]): + """One page of a collection, ordered by primary key. + + ``total`` counts the whole collection, so a client knows there is a next + page while ``offset + len(items) < total``. + """ + + items: list[T] + total: int + limit: int + offset: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/crud/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/crud/items.py-tpl index d2b6034..a7acf66 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/crud/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/crud/items.py-tpl @@ -1,20 +1,136 @@ # -------------------------------------------------------------------------- -# Item CRUD method module +# Item CRUD method module (async) +# +# Items live in a JSON file. aiofiles runs the blocking file calls in a +# worker thread, so the event loop keeps serving other requests while a file +# is read or written. Handlers await between reading and writing the file, +# so an asyncio.Lock serialises every access: without it two requests could +# hand out the same id or lose a write. +# +# The file keeps the next id next to the items, so an id is never handed out +# twice: not after the item with the highest id is deleted, and not after a +# restart. Every write goes to a temporary file that then replaces the data +# file in one step (run in a worker thread with asyncio.to_thread), so a +# crash mid-write leaves the previous file intact. The lock covers one +# process only; with several workers, use a database. # -------------------------------------------------------------------------- +import asyncio +import contextlib import json import os +import tempfile +from collections.abc import Callable +from pathlib import Path +from typing import Any -import aiofiles # type: ignore +import aiofiles # type: ignore[import-untyped] -MOCK_FILE = os.path.join(os.path.dirname(__file__), "../mocks/mock_items.json") +MOCK_FILE = Path(__file__).resolve().parent.parent / "mocks" / "mock_items.json" +ItemData = dict[str, Any] -async def read_items(): - async with aiofiles.open(MOCK_FILE, mode="r") as file: - contents = await file.read() - return json.loads(contents) +def _parse(data: Any) -> tuple[list[ItemData], int]: + """Return the stored items ordered by id and the next id to hand out. -async def write_items(items: list[dict]): - async with aiofiles.open(MOCK_FILE, mode="w") as file: - await file.write(json.dumps(items, indent=2)) + Older data files, like the shipped mock data, are a plain list of items; + for those the next id continues after the highest id in the file. + """ + if isinstance(data, list): + items: list[ItemData] = data + next_id = 1 + else: + items = data["items"] + next_id = int(data.get("next_id", 1)) + items = sorted(items, key=lambda item: item["id"]) + highest = max((item["id"] for item in items), default=0) + return items, max(next_id, highest + 1) + + +def _dump(items: list[ItemData], next_id: int) -> str: + return json.dumps({"next_id": next_id, "items": items}, indent=2) + "\n" + + +def _write_atomic(path: Path, text: str) -> None: + """Replace ``path`` with ``text``; readers see the old or the new file.""" + fd, temp_name = tempfile.mkstemp( + dir=path.parent, prefix=f".{path.name}.", suffix=".tmp" + ) + try: + with os.fdopen(fd, "w", encoding="utf-8") as file: + file.write(text) + file.flush() + os.fsync(file.fileno()) + # The temporary file is closed before the rename, as Windows requires. + os.replace(temp_name, path) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(temp_name) + raise + + +class ItemStore: + """Item persistence backed by one JSON file, accessed asynchronously.""" + + def __init__(self, path: Path) -> None: + self.path = path + self._lock = asyncio.Lock() + + async def _load(self) -> tuple[list[ItemData], int]: + async with aiofiles.open(self.path, encoding="utf-8") as file: + contents: str = await file.read() + return _parse(json.loads(contents)) + + async def _save(self, items: list[ItemData], next_id: int) -> None: + await asyncio.to_thread(_write_atomic, self.path, _dump(items, next_id)) + + async def list_page(self, offset: int, limit: int) -> tuple[list[ItemData], int]: + """Return one page of items ordered by id, plus the total count.""" + async with self._lock: + items, _ = await self._load() + return items[offset : offset + limit], len(items) + + async def get(self, item_id: int) -> ItemData | None: + async with self._lock: + items, _ = await self._load() + return next((item for item in items if item["id"] == item_id), None) + + async def create(self, data: ItemData) -> ItemData: + async with self._lock: + items, next_id = await self._load() + item = {**data, "id": next_id} + items.append(item) + await self._save(items, next_id + 1) + return item + + async def replace(self, item_id: int, data: ItemData) -> ItemData | None: + return await self._modify(item_id, lambda current: {**data, "id": item_id}) + + async def update(self, item_id: int, changes: ItemData) -> ItemData | None: + return await self._modify( + item_id, lambda current: {**current, **changes, "id": item_id} + ) + + async def delete(self, item_id: int) -> bool: + async with self._lock: + items, next_id = await self._load() + remaining = [item for item in items if item["id"] != item_id] + if len(remaining) == len(items): + return False + await self._save(remaining, next_id) + return True + + async def _modify( + self, item_id: int, change: Callable[[ItemData], ItemData] + ) -> ItemData | None: + async with self._lock: + items, next_id = await self._load() + for index, current in enumerate(items): + if current["id"] == item_id: + items[index] = change(current) + await self._save(items, next_id) + return items[index] + return None + + +item_store = ItemStore(MOCK_FILE) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/exceptions.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/exceptions.py-tpl index 7871aa9..2706aa8 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/exceptions.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/exceptions.py-tpl @@ -1,12 +1,30 @@ # -------------------------------------------------------------------------- # The module defines custom Backend Application Exception class, overrides basic Exception. +# +# ``register_exception_handlers`` makes every error path answer with the +# response envelope: ``InternalException``, any ``HTTPException`` (including +# the unknown-route 404 and the 405 Starlette raises), request validation +# errors (422) and unhandled exceptions (500, details logged, never sent). # -------------------------------------------------------------------------- -from datetime import datetime, timezone +import logging +from collections.abc import Mapping from enum import Enum +from http import HTTPStatus +from typing import Any -from pydantic import BaseModel, Field +from fastapi import FastAPI, Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from starlette.exceptions import HTTPException as StarletteHTTPException -from src.schemas.base import ResponseSchema +from src.schemas.base import ( + ErrorResponse, + FieldError, + ValidationErrorResponse, + utc_timestamp, +) + +logger = logging.getLogger(__name__) class ErrorCode(Enum): @@ -51,53 +69,104 @@ class ErrorCode(Enum): self.status_code = status_code -class ExceptionSchema(BaseModel): - timestamp: str = Field( - ..., - description="Timestamp of the error occurred.", +def code_for_status(status_code: int) -> str: + """Generic error code for an HTTP status (the first matching ErrorCode).""" + for error_code in ErrorCode: + if error_code.status_code == status_code: + return error_code.code + return f"HTTP-{status_code}" + + +class InternalException(Exception): + """Raise this from application code to answer with a specific ErrorCode.""" + + def __init__(self, message: str, error_code: ErrorCode): + super().__init__(message) + self.status = error_code.status_code + self.error_code = error_code.code + self.message = message + + +def error_responses(*status_codes: int) -> dict[int | str, dict[str, Any]]: + """Build ``responses=`` entries documenting enveloped error bodies.""" + return { + code: { + "model": ValidationErrorResponse if code == 422 else ErrorResponse, + "description": HTTPStatus(code).phrase, + } + for code in status_codes + } + + +def _error( + request: Request, + status_code: int, + code: str, + message: str, + headers: Mapping[str, str] | None = None, +) -> JSONResponse: + body = ErrorResponse( + timestamp=utc_timestamp(), + status=status_code, + code=code, + path=request.url.path, + message=message, ) - status: int = Field(..., description="HTTP status code of the error") - code: str = Field( - ..., - description="Server identification code of the error.", + return JSONResponse( + status_code=status_code, content=body.model_dump(), headers=headers ) - message: str = Field( - ..., - description="Message content of the error.", + + +async def internal_exception_handler( + request: Request, exc: InternalException +) -> JSONResponse: + return _error(request, exc.status, exc.error_code, exc.message) + + +async def http_exception_handler( + request: Request, exc: StarletteHTTPException +) -> JSONResponse: + return _error( + request, + exc.status_code, + code_for_status(exc.status_code), + str(exc.detail), + headers=exc.headers, ) - path: str = Field( - ..., - description="Path where the error occurred.", + + +async def validation_exception_handler( + request: Request, exc: RequestValidationError +) -> JSONResponse: + body = ValidationErrorResponse( + timestamp=utc_timestamp(), + status=422, + code=ErrorCode.UNPROCESSABLE.code, + path=request.url.path, + message=[ + FieldError(loc=list(error["loc"]), msg=error["msg"], type=error["type"]) + for error in exc.errors() + ], ) + return JSONResponse(status_code=422, content=body.model_dump()) - class ConfigDict: - json_schema_extra = { - "example": { - "default": { - "timestamp": "2023-02-10T01:00:00.000Z", - "status": 500, - "code": "SEVR-000", - "path": "/v1/", - "message": "ERROR : Unknown error occurred in server logic.", - } - } - } + +async def unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse: + # The exception text can leak internals, so it goes to the log only. + logger.exception( + "Unhandled error on %s %s", request.method, request.url.path, exc_info=exc + ) + return _error( + request, + 500, + ErrorCode.UNKNOWN_ERROR.code, + "Internal server error", + ) -class InternalException(Exception): - def __init__(self, message: str, error_code: ErrorCode): - self.timestamp = ( - datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") - ) - self.status = error_code.status_code - self.error_code = error_code.code - self.message = f"ERROR : {message}" - - def to_response(self, path: str) -> ResponseSchema[str]: - return ResponseSchema( - timestamp=self.timestamp, - status=self.status, - code=self.error_code, - path=path, - message=self.message, - ) +def register_exception_handlers(app: FastAPI) -> None: + """Answer every error path with the response envelope.""" + app.exception_handler(InternalException)(internal_exception_handler) + app.exception_handler(StarletteHTTPException)(http_exception_handler) + app.exception_handler(RequestValidationError)(validation_exception_handler) + app.exception_handler(Exception)(unhandled_exception_handler) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/pagination.py-tpl deleted file mode 100644 index 1cd1d7a..0000000 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/pagination.py-tpl +++ /dev/null @@ -1,72 +0,0 @@ -# -------------------------------------------------------------------------- -# The module defines paginatable object schemas' helper methods. -# -------------------------------------------------------------------------- -from typing import Generic, TypeVar - -from fastapi import Request -from pydantic import AnyHttpUrl, BaseModel, Field - -T = TypeVar("T") - - -class PaginatedResponse(BaseModel, Generic[T]): - count: int = Field( - ..., title="Count", description="Indicates the total number of imported items." - ) - next: AnyHttpUrl | None = Field( - None, - title="Next", - description="Indicates the URL of the next page to import the data.", - ) - previous: AnyHttpUrl | None = Field( - None, - title="Previous", - description="Indicates the URL of the previous page from which the data was imported.", - ) - results: list[T] = Field( - ..., - title="Results", - description="Lists the information of the imported items.", - ) - - -class Paginator: - def __init__(self, data: list[T], page: int, per_page: int, request: Request): - self.data = data - self.page = page - self.page_size = per_page - self.limit = per_page - self.offset = (page - 1) * per_page - self.request = request - self.number_of_pages = self._get_number_of_pages(len(data)) - - def _get_next_page(self) -> str | None: - if self.page >= self.number_of_pages: - return None - url = self.request.url.include_query_params(page=self.page + 1) - return str(url) - - def _get_previous_page(self) -> str | None: - if self.page == 1: - return None - url = self.request.url.include_query_params(page=self.page - 1) - return str(url) - - def get_response(self) -> dict: - paginated_data = self.data[self.offset : self.offset + self.limit] - return { - "count": len(self.data), - "next": self._get_next_page(), - "previous": self._get_previous_page(), - "results": paginated_data, - } - - def _get_number_of_pages(self, count: int) -> int: - rest = count % self.page_size - quotient = count // self.page_size - return quotient if not rest else quotient + 1 - - -def paginate(data: list[T], page: int, page_size: int, request: Request) -> dict: - paginator = Paginator(data, page, page_size, request) - return paginator.get_response() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/responses.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/responses.py-tpl new file mode 100644 index 0000000..dc10ca0 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/responses.py-tpl @@ -0,0 +1,22 @@ +# -------------------------------------------------------------------------- +# The module builds the envelope for successful responses. +# -------------------------------------------------------------------------- +from typing import TypeVar + +from fastapi import Request + +from src.schemas.base import ResponseSchema, utc_timestamp + +T = TypeVar("T") + + +def success_response( + request: Request, message: T, status_code: int = 200 +) -> ResponseSchema[T]: + return ResponseSchema[T]( + timestamp=utc_timestamp(), + status=status_code, + code=f"HTTP-{status_code}", + path=request.url.path, + message=message, + ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/main.py-tpl index 2d61bff..ee50471 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/main.py-tpl @@ -1,13 +1,12 @@ # -------------------------------------------------------------------------- # Main server application module # -------------------------------------------------------------------------- -from fastapi import FastAPI, Request -from fastapi.responses import JSONResponse +from fastapi import FastAPI from starlette.middleware.cors import CORSMiddleware from src.api.api import api_router from src.core.config import settings -from src.helper.exceptions import InternalException +from src.helper.exceptions import register_exception_handlers from src.utils.documents import add_description_at_api_tags # fastkit:imports @@ -16,33 +15,31 @@ app = FastAPI( title=settings.PROJECT_NAME, ) +# Origins come only from BACKEND_CORS_ORIGINS; with none configured the +# middleware is not installed at all. if settings.all_cors_origins: app.add_middleware( CORSMiddleware, allow_origins=settings.all_cors_origins, - allow_credentials=True, + # Browsers refuse credentials with the "*" wildcard; never send both. + allow_credentials="*" not in settings.all_cors_origins, allow_methods=["*"], allow_headers=["*"], ) - -# Apply Custom Exception Handler -@app.exception_handler(InternalException) -async def internal_exception_handler(request: Request, exc: InternalException): - return JSONResponse( - status_code=exc.status, - content=exc.to_response(path=str(request.url)).model_dump(), - ) +# Every error (HTTPException, 404/405 from routing, validation errors and +# unhandled exceptions) answers with the same envelope as a success. +register_exception_handlers(app) # fastkit:routes -app.include_router(api_router) +app.include_router(api_router, prefix=settings.API_V1_PREFIX) # Apply Custom OpenAPI Tags description add_description_at_api_tags(app) -@app.get("/health") -async def health_check(): - """Health check endpoint.""" - return {"status": "healthy"} +@app.get("/health", tags=["health"]) +async def health_check() -> dict[str, str]: + """Liveness probe: no authentication and no I/O (not enveloped).""" + return {"status": "ok"} diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/schemas/base.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/schemas/base.py-tpl index 7cfab7f..37d3561 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/schemas/base.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/schemas/base.py-tpl @@ -1,49 +1,102 @@ # -------------------------------------------------------------------------- # The module defines custom base response schemas. +# +# Every JSON response of the API (success or error) uses the same envelope: +# timestamp, status, code, path and message. Only the type of ``message`` +# changes: the resource or page for a success, a text for an error, and the +# list of invalid fields for a validation error (422). # -------------------------------------------------------------------------- +from datetime import datetime, timezone from typing import Generic, TypeVar -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field T = TypeVar("T") -class ResponseSchema(BaseModel, Generic[T]): +def utc_timestamp() -> str: + """Current time as ISO 8601 UTC with milliseconds (``...T09:30:00.000Z``).""" + return ( + datetime.now(timezone.utc) + .isoformat(timespec="milliseconds") + .replace("+00:00", "Z") + ) + + +class EnvelopeBase(BaseModel): timestamp: str = Field( ..., description="The timestamp when the response was generated.", + examples=["2024-02-15T09:30:00.000Z"], ) - status: int = Field(..., description="HTTP status code.") + status: int = Field(..., description="HTTP status code.", examples=[200]) code: str = Field( ..., description="Server identification code.", + examples=["HTTP-200"], ) path: str = Field( ..., description="Request path.", + examples=["/api/v1/items/1"], ) - message: T = Field( - ..., - description="Data details or error messages requested.", + + +class ResponseSchema(EnvelopeBase, Generic[T]): + """Envelope of a successful response.""" + + message: T = Field(..., description="Requested data.") + + +class ErrorResponse(EnvelopeBase): + """Envelope of an error response.""" + + message: str = Field(..., description="What went wrong.") + + model_config = ConfigDict( + json_schema_extra={ + "examples": [ + { + "timestamp": "2024-02-15T09:30:00.000Z", + "status": 404, + "code": "DATA-002", + "path": "/api/v1/items/999", + "message": "Item not found", + } + ] + } ) - class ConfigDict: - json_schema_extra = { - "example": { - "timestamp": "2023-02-10T01:00:00.000Z", - "status": 200, - "code": "HTTP-200", - "path": "/v1/", - "message": { - "id": "123e4567-e89b-12d3-a456-426614174000", - "email": "example@example.com", - "password": "secret", - "nickname": "example_nick", - "create_at": "2023-02-10T01:00:00.000Z", - "bio": "example bio", - "profile_img": "https://example.com/profile.jpg", - "first_name": "John", - "last_name": "Doe", - }, - } + +class FieldError(BaseModel): + """One invalid field of a request.""" + + loc: list[str | int] = Field(..., description="Location of the field.") + msg: str = Field(..., description="Why the value was rejected.") + type: str = Field(..., description="Error type identifier.") + + +class ValidationErrorResponse(EnvelopeBase): + """Envelope of a 422 response: ``message`` lists the invalid fields.""" + + message: list[FieldError] + + model_config = ConfigDict( + json_schema_extra={ + "examples": [ + { + "timestamp": "2024-02-15T09:30:00.000Z", + "status": 422, + "code": "HTTP-006", + "path": "/api/v1/items", + "message": [ + { + "loc": ["query", "limit"], + "msg": "Input should be less than or equal to 100", + "type": "less_than_equal", + } + ], + } + ] } + ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/schemas/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/schemas/items.py-tpl index 859f4ef..eb590ec 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/schemas/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/schemas/items.py-tpl @@ -1,21 +1,54 @@ # -------------------------------------------------------------------------- # Item schema module # -------------------------------------------------------------------------- - -from pydantic import BaseModel, ConfigDict +from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator class ItemBase(BaseModel): - name: str - description: str | None = None - price: float - category: str + name: str = Field(min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=1000) + price: float = Field(ge=0) + category: str = Field(min_length=1, max_length=50) class ItemCreate(ItemBase): - pass + """POST and PUT body: every required field must be sent.""" + + +class ItemUpdate(BaseModel): + """PATCH body: send only the fields to change. + + ``description`` can be cleared with an explicit ``null``; the other + fields are required on an item, so ``null`` is rejected for them. + """ + + name: str | None = Field(default=None, min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=1000) + price: float | None = Field(default=None, ge=0) + category: str | None = Field(default=None, min_length=1, max_length=50) + + @field_validator("name", "price", "category") + @classmethod + def _reject_null(cls, value: object, info: ValidationInfo) -> object: + if value is None: + raise ValueError(f"{info.field_name} must not be null") + return value + +class ItemRead(ItemBase): + model_config = ConfigDict( + from_attributes=True, + json_schema_extra={ + "examples": [ + { + "id": 1, + "name": "Test Item 1", + "description": None, + "price": 20.0, + "category": "test", + } + ] + }, + ) -class ItemResponse(ItemBase): id: int - model_config = ConfigDict(from_attributes=True) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/utils/documents.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/utils/documents.py-tpl index b76e381..e3bda56 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/utils/documents.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/utils/documents.py-tpl @@ -4,9 +4,10 @@ from fastapi import FastAPI -def add_description_at_api_tags(app: FastAPI): +def add_description_at_api_tags(app: FastAPI) -> None: tag_descriptions = { "items": "Item API. Performs item CRUD operations...", + "health": "Liveness probe.", # put routers' description here after create and connect them. } diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/conftest.py-tpl index a445ba3..93294c3 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/conftest.py-tpl @@ -1,41 +1,40 @@ # -------------------------------------------------------------------------- # pytest runtime configuration module # -------------------------------------------------------------------------- -import asyncio -import os -import typing +import json +from collections.abc import AsyncGenerator from pathlib import Path import pytest -import pytest_asyncio from httpx import ASGITransport, AsyncClient -from src.main import app - -MOCK_PATH = os.path.join(os.path.dirname(__file__), "../src/mocks/mock_items.json") +from src.api.deps import get_item_store +from src.core.config import settings +from src.crud.items import ItemStore +from src.main import app -@pytest.fixture(scope="session") -def event_loop(request) -> typing.Generator: - loop = asyncio.get_event_loop() - yield loop - loop.close() - +ITEMS_URL = f"{settings.API_V1_PREFIX}/items" -@pytest_asyncio.fixture(scope="module", autouse=True) -def mock_data_reset(): - # Back up original data into memory - mock_path = Path(__file__).parent.parent / "src/mocks/mock_items.json" - original_data = mock_path.read_text() +SEED_ITEMS = [ + {"id": 1, "name": "Test Item 1", "price": 10.5, "category": "test"}, + {"id": 2, "name": "Test Item 2", "price": 20.0, "category": "test"}, +] - yield - # After test, restore original data - mock_path.write_text(original_data) +@pytest.fixture +def store(tmp_path: Path) -> ItemStore: + """Item store on a temporary file, so tests never touch src/mocks.""" + path = tmp_path / "items.json" + path.write_text(json.dumps(SEED_ITEMS), encoding="utf-8") + return ItemStore(path) -@pytest_asyncio.fixture(scope="module") -async def client(): - async with AsyncClient( - transport=ASGITransport(app=app), base_url="http://test" - ) as ac: +@pytest.fixture +async def client(store: ItemStore) -> AsyncGenerator[AsyncClient, None]: + app.dependency_overrides[get_item_store] = lambda: store + # raise_app_exceptions=False lets tests see the 500 envelope the app + # sends for an unhandled exception instead of the exception itself. + transport = ASGITransport(app=app, raise_app_exceptions=False) + async with AsyncClient(transport=transport, base_url="http://test") as ac: yield ac + app.dependency_overrides.clear() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_config.py-tpl new file mode 100644 index 0000000..38f107b --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_config.py-tpl @@ -0,0 +1,194 @@ +# -------------------------------------------------------------------------- +# Settings validation: the SECRET_KEY rule, ENVIRONMENT values, +# environment variable names and the CORS wildcard. +# -------------------------------------------------------------------------- +import json +import os +import secrets +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest +from pydantic import ValidationError + +from src.core.config import KNOWN_EXAMPLE_SECRET_KEYS, MIN_SECRET_KEY_BYTES, Settings + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +APP_MODULE = "src.main" +#: Settings without a default; none in this template. +REQUIRED: dict[str, Any] = {} + +STRONG_KEY = "k" * MIN_SECRET_KEY_BYTES +#: Every environment except development refuses a missing, public or short +#: SECRET_KEY. +STRICT_ENVIRONMENTS = ["staging", "production"] + + +@pytest.fixture(autouse=True) +def _isolated_settings_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Shell variables, in any spelling, must not leak into Settings().""" + for name in list(os.environ): + if name.upper() in {"ENVIRONMENT", "SECRET_KEY", "BACKEND_CORS_ORIGINS"}: + monkeypatch.delenv(name) + + +def make_settings(env_file: Path | None = None, **values: Any) -> Settings: + """Settings from explicit values; a developer's .env is never read.""" + return Settings(_env_file=env_file, **{**REQUIRED, **values}) # type: ignore[call-arg] + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_require_an_explicit_secret_key(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"must be set explicitly when ENVIRONMENT={environment}" + ): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_refuse_a_short_secret_key(environment: str) -> None: + short_key = "k" * (MIN_SECRET_KEY_BYTES - 1) + + with pytest.raises(ValidationError, match=f"at least {MIN_SECRET_KEY_BYTES} bytes"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=short_key) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +@pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) +def test_strict_environments_refuse_every_public_example_key( + environment: str, example_key: str +) -> None: + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=f" {example_key} ") + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environment_errors_say_how_to_generate_a_key(environment: str) -> None: + with pytest.raises(ValidationError, match="token_urlsafe"): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_an_explicit_strong_key(environment: str) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + + assert settings.ENVIRONMENT == environment + assert settings.SECRET_KEY == STRONG_KEY + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_the_key_fastkit_writes_to_env( + tmp_path: Path, environment: str +) -> None: + env_file = tmp_path / ".env" + env_file.write_text( + f"ENVIRONMENT={environment}\nSECRET_KEY={secrets.token_urlsafe(32)}\n", + encoding="utf-8", + ) + + assert make_settings(env_file).ENVIRONMENT == environment + + +def test_development_without_a_key_uses_a_random_one() -> None: + settings = make_settings(ENVIRONMENT="development") + + assert len(settings.SECRET_KEY.encode()) >= MIN_SECRET_KEY_BYTES + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_development_only_warns_about_an_example_key() -> None: + example_key = sorted(KNOWN_EXAMPLE_SECRET_KEYS)[0] + + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings(ENVIRONMENT="development", SECRET_KEY=example_key) + + assert settings.SECRET_KEY == example_key + + +@pytest.mark.parametrize("value", ["Production", "PRODUCTION", " production", "prod"]) +def test_unknown_environment_values_fail_closed(value: str) -> None: + with pytest.raises(ValidationError, match="ENVIRONMENT"): + make_settings(ENVIRONMENT=value, SECRET_KEY=STRONG_KEY) + + +def test_environment_variable_names_are_case_insensitive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("environment", "production") + + with pytest.raises(ValidationError, match="must be set explicitly"): + make_settings() + + monkeypatch.setenv("secret_key", STRONG_KEY) + + assert make_settings().ENVIRONMENT == "production" + + +@pytest.mark.parametrize("raw", ["*", " * ", '["*"]', "*,http://localhost:3000"]) +def test_cors_wildcard_is_accepted(monkeypatch: pytest.MonkeyPatch, raw: str) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + + assert make_settings().all_cors_origins == ["*"] + + +def test_cors_origins_must_be_urls_or_the_wildcard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + + with pytest.raises(ValidationError): + make_settings() + + +#: Runs in a fresh interpreter: the app reads its settings at import time. +_PREFLIGHT = f""" +import json +from fastapi.testclient import TestClient +from {APP_MODULE} import app + +headers = {{ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "GET", +}} +response = TestClient(app).options("/", headers=headers) +allowed = {{ + k: v for k, v in response.headers.items() if k.startswith("access-control-allow-") +}} +print(json.dumps(allowed)) +""" + + +@pytest.mark.parametrize( + ("origins", "allow_origin", "allow_credentials"), + [ + ("*", "*", None), + ("http://localhost:3000", "http://localhost:3000", "true"), + ], +) +def test_cors_wildcard_is_never_combined_with_credentials( + origins: str, allow_origin: str, allow_credentials: str | None +) -> None: + env = { + **os.environ, + **{name: str(value) for name, value in REQUIRED.items()}, + "BACKEND_CORS_ORIGINS": origins, + "ENVIRONMENT": "development", + } + result = subprocess.run( + [sys.executable, "-c", _PREFLIGHT], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + check=False, + ) + + assert result.returncode == 0, result.stderr + headers = json.loads(result.stdout.strip().splitlines()[-1]) + assert headers["access-control-allow-origin"] == allow_origin + assert headers.get("access-control-allow-credentials") == allow_credentials diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_item_store.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_item_store.py-tpl new file mode 100644 index 0000000..d6d5bc4 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_item_store.py-tpl @@ -0,0 +1,85 @@ +# -------------------------------------------------------------------------- +# Item store persistence testcases +# -------------------------------------------------------------------------- +import json +from pathlib import Path +from typing import Any + +import pytest + +from src.crud.items import ItemStore + +NEW_ITEM = {"name": "New Item", "price": 30.0, "category": "new"} + + +def make_store(tmp_path: Path, data: Any) -> ItemStore: + path = tmp_path / "items.json" + path.write_text(json.dumps(data), encoding="utf-8") + return ItemStore(path) + + +def seed(*ids: int) -> list[dict[str, Any]]: + return [{**NEW_ITEM, "id": item_id} for item_id in ids] + + +async def test_deleted_id_is_not_reused(tmp_path: Path) -> None: + store = make_store(tmp_path, seed(1, 2)) + + first = await store.create(dict(NEW_ITEM)) + assert await store.delete(first["id"]) + second = await store.create(dict(NEW_ITEM)) + + assert first["id"] == 3 + assert second["id"] == 4 + + +async def test_restart_does_not_reuse_the_deleted_highest_id( + tmp_path: Path, +) -> None: + store = make_store(tmp_path, seed(1, 2)) + created = await store.create(dict(NEW_ITEM)) + assert await store.delete(created["id"]) + + restarted = ItemStore(store.path) + after_restart = await restarted.create(dict(NEW_ITEM)) + + assert after_restart["id"] == created["id"] + 1 + saved = json.loads(store.path.read_text(encoding="utf-8")) + assert saved["next_id"] == after_restart["id"] + 1 + + +async def test_old_list_format_file_still_loads(tmp_path: Path) -> None: + store = make_store(tmp_path, seed(5, 2)) + + items, total = await store.list_page(offset=0, limit=10) + + assert [item["id"] for item in items] == [2, 5] + assert total == 2 + assert await store.get(5) is not None + assert (await store.create(dict(NEW_ITEM)))["id"] == 6 + + +async def test_next_id_never_goes_below_the_highest_stored_id( + tmp_path: Path, +) -> None: + store = make_store(tmp_path, {"next_id": 2, "items": seed(1, 7)}) + + assert (await store.create(dict(NEW_ITEM)))["id"] == 8 + + +async def test_failed_write_keeps_the_file_and_leaves_no_temp_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + store = make_store(tmp_path, seed(1, 2)) + before = store.path.read_bytes() + + def fail_replace(*args: Any, **kwargs: Any) -> None: + raise OSError("simulated crash while replacing the file") + + monkeypatch.setattr("src.crud.items.os.replace", fail_replace) + + with pytest.raises(OSError, match="simulated crash"): + await store.create(dict(NEW_ITEM)) + + assert store.path.read_bytes() == before + assert list(tmp_path.iterdir()) == [store.path] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_items.py-tpl index 4fc1a17..2d86371 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_items.py-tpl @@ -1,61 +1,211 @@ # -------------------------------------------------------------------------- # Item endpoint testcases # -------------------------------------------------------------------------- +import asyncio +from typing import Any + import pytest +from httpx import AsyncClient + +from src.api.deps import get_item_store +from src.crud.items import MOCK_FILE, ItemStore +from src.main import app +from tests.conftest import ITEMS_URL + +NEW_ITEM = {"name": "New Item", "price": 30.0, "category": "new"} +ENVELOPE_KEYS = {"timestamp", "status", "code", "path", "message"} + +def assert_envelope(body: dict[str, Any], status: int, code: str, path: str) -> None: + assert set(body) == ENVELOPE_KEYS + assert body["status"] == status + assert body["code"] == code + assert body["path"] == path + assert body["timestamp"].endswith("Z") + + +async def test_list_items_returns_an_enveloped_page(client: AsyncClient) -> None: + response = await client.get(ITEMS_URL) -@pytest.mark.asyncio -async def test_read_all_items(client): - response = await client.get("/items/") assert response.status_code == 200 - data = response.json() - assert data["status"] == 200 - assert data["code"] == "HTTP-200" - assert isinstance(data["message"], list) + body = response.json() + assert_envelope(body, 200, "HTTP-200", ITEMS_URL) + page = body["message"] + assert set(page) == {"items", "total", "limit", "offset"} + assert page["total"] == 2 + assert page["limit"] == 20 + assert page["offset"] == 0 + assert [item["id"] for item in page["items"]] == [1, 2] + + +async def test_list_items_limit_and_offset(client: AsyncClient) -> None: + response = await client.get(ITEMS_URL, params={"limit": 1, "offset": 1}) + page = response.json()["message"] + assert [item["name"] for item in page["items"]] == ["Test Item 2"] + assert page["total"] == 2 + assert page["limit"] == 1 + assert page["offset"] == 1 + + +@pytest.mark.parametrize("params", [{"limit": 0}, {"limit": 101}, {"offset": -1}]) +async def test_out_of_range_pagination_is_an_enveloped_422( + client: AsyncClient, params: dict[str, int] +) -> None: + response = await client.get(ITEMS_URL, params=params) + + assert response.status_code == 422 + body = response.json() + assert_envelope(body, 422, "HTTP-006", ITEMS_URL) + assert body["message"][0]["loc"][0] == "query" + + +async def test_collection_is_served_without_redirect(client: AsyncClient) -> None: + response = await client.get(ITEMS_URL, follow_redirects=False) -@pytest.mark.asyncio -async def test_get_item_success(client): - response = await client.get("/items/1") assert response.status_code == 200 - data = response.json() - assert data["message"]["id"] == 1 - assert data["message"]["name"] == "Test Item 1" -@pytest.mark.asyncio -async def test_get_item_not_found(client): - response = await client.get("/items/999") +async def test_get_item(client: AsyncClient) -> None: + response = await client.get(f"{ITEMS_URL}/1") + + assert response.status_code == 200 + body = response.json() + assert_envelope(body, 200, "HTTP-200", f"{ITEMS_URL}/1") + assert body["message"]["name"] == "Test Item 1" + + +async def test_get_item_not_found(client: AsyncClient) -> None: + response = await client.get(f"{ITEMS_URL}/999") + assert response.status_code == 404 - data = response.json() - assert data["code"] == "HTTP-002" - assert "Item not found" in data["message"] + body = response.json() + assert_envelope(body, 404, "DATA-002", f"{ITEMS_URL}/999") + assert body["message"] == "Item not found" + +async def test_create_item_returns_201_and_location(client: AsyncClient) -> None: + response = await client.post(ITEMS_URL, json=NEW_ITEM) -@pytest.mark.asyncio -async def test_create_item(client): - test_item = {"name": "New Item", "price": 30.0, "category": "test"} - response = await client.post("/items/", json=test_item) assert response.status_code == 201 - data = response.json() - assert data["message"]["id"] == 2 + body = response.json() + assert_envelope(body, 201, "HTTP-201", ITEMS_URL) + created = body["message"] + assert created["id"] not in (1, 2) + location = response.headers["location"] + assert location.endswith(f"{ITEMS_URL}/{created['id']}") + assert (await client.get(location)).json()["message"] == created + + +async def test_invalid_body_is_an_enveloped_422(client: AsyncClient) -> None: + response = await client.post(ITEMS_URL, json={**NEW_ITEM, "price": -1}) + + assert response.status_code == 422 + body = response.json() + assert_envelope(body, 422, "HTTP-006", ITEMS_URL) + assert body["message"][0]["loc"] == ["body", "price"] -@pytest.mark.asyncio -async def test_update_item(client): - update_data = {"name": "Updated Item", "price": 25.0, "category": "test"} - response = await client.put("/items/1", json=update_data) +async def test_put_replaces_the_whole_item(client: AsyncClient) -> None: + await client.patch(f"{ITEMS_URL}/1", json={"description": "will be dropped"}) + + response = await client.put( + f"{ITEMS_URL}/1", json={"name": "Replaced", "price": 1.0, "category": "x"} + ) + assert response.status_code == 200 - data = response.json() - assert data["message"]["name"] == "Updated Item" + assert response.json()["message"] == { + "id": 1, + "name": "Replaced", + "description": None, + "price": 1.0, + "category": "x", + } + + +async def test_put_not_found(client: AsyncClient) -> None: + response = await client.put(f"{ITEMS_URL}/999", json=NEW_ITEM) + + assert response.status_code == 404 + assert response.json()["code"] == "DATA-002" + +async def test_patch_changes_only_the_sent_fields(client: AsyncClient) -> None: + response = await client.patch(f"{ITEMS_URL}/1", json={"price": 99.0}) -@pytest.mark.asyncio -async def test_delete_item(client): - # First delete - response = await client.delete("/items/1") assert response.status_code == 200 + item = response.json()["message"] + assert item["price"] == 99.0 + assert item["name"] == "Test Item 1" + + +async def test_patch_rejects_null_for_required_fields(client: AsyncClient) -> None: + response = await client.patch(f"{ITEMS_URL}/1", json={"name": None}) + + assert response.status_code == 422 + assert response.json()["code"] == "HTTP-006" + + +async def test_delete_item_returns_204_without_body(client: AsyncClient) -> None: + response = await client.delete(f"{ITEMS_URL}/1") + + assert response.status_code == 204 + assert response.content == b"" + assert (await client.get(f"{ITEMS_URL}/1")).status_code == 404 + + +async def test_delete_item_not_found(client: AsyncClient) -> None: + response = await client.delete(f"{ITEMS_URL}/999") + + assert response.status_code == 404 + assert response.json()["message"] == "Item not found" + + +async def test_unknown_route_is_an_enveloped_404(client: AsyncClient) -> None: + response = await client.get("/does-not-exist") + + assert response.status_code == 404 + assert_envelope(response.json(), 404, "HTTP-002", "/does-not-exist") + + +async def test_wrong_method_is_an_enveloped_405(client: AsyncClient) -> None: + response = await client.post(f"{ITEMS_URL}/1", json=NEW_ITEM) + + assert response.status_code == 405 + assert_envelope(response.json(), 405, "HTTP-003", f"{ITEMS_URL}/1") + assert "allow" in response.headers + + +class BrokenStore(ItemStore): + async def get(self, item_id: int) -> dict[str, Any] | None: + raise RuntimeError("database password=hunter2 leaked") + + +async def test_unhandled_error_is_a_generic_enveloped_500( + client: AsyncClient, store: ItemStore +) -> None: + app.dependency_overrides[get_item_store] = lambda: BrokenStore(store.path) + + response = await client.get(f"{ITEMS_URL}/1") + + assert response.status_code == 500 + body = response.json() + assert_envelope(body, 500, "SEVR-001", f"{ITEMS_URL}/1") + assert body["message"] == "Internal server error" + assert "hunter2" not in response.text + + +async def test_tests_do_not_modify_the_shipped_mock_file(client: AsyncClient) -> None: + before = MOCK_FILE.read_bytes() + + await client.post(ITEMS_URL, json=NEW_ITEM) + await client.delete(f"{ITEMS_URL}/1") + + assert MOCK_FILE.read_bytes() == before + + +async def test_concurrent_creates_get_unique_ids(store: ItemStore) -> None: + created = await asyncio.gather(*(store.create(dict(NEW_ITEM)) for _ in range(20))) - # Verify deletion - verify_response = await client.get("/items/1") - assert verify_response.status_code == 404 + ids = [item["id"] for item in created] + assert len(set(ids)) == 20 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_main.py-tpl new file mode 100644 index 0000000..3a94e14 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_main.py-tpl @@ -0,0 +1,68 @@ +# -------------------------------------------------------------------------- +# Application-level testcases (health, OpenAPI, settings) +# -------------------------------------------------------------------------- +import pytest +from httpx import AsyncClient + +from src.core.config import Settings +from tests.conftest import ITEMS_URL + + +async def test_health(client: AsyncClient) -> None: + response = await client.get("/health") + + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + +async def test_openapi_documents_envelopes_tags_and_errors( + client: AsyncClient, +) -> None: + schema = (await client.get("/openapi.json")).json() + paths = schema["paths"] + components = schema["components"]["schemas"] + + assert set(paths[ITEMS_URL]) == {"get", "post"} + item_routes = paths[f"{ITEMS_URL}/{{item_id}}"] + assert set(item_routes) == {"get", "put", "patch", "delete"} + for operation in [*paths[ITEMS_URL].values(), *item_routes.values()]: + assert operation["tags"] == ["items"] + assert "500" in operation["responses"] + validation = operation["responses"]["422"]["content"]["application/json"] + assert validation["schema"]["$ref"].endswith("/ValidationErrorResponse") + for operation in item_routes.values(): + not_found = operation["responses"]["404"]["content"]["application/json"] + assert not_found["schema"]["$ref"].endswith("/ErrorResponse") + assert "HTTPValidationError" not in components + assert components["ErrorResponse"]["examples"][0]["status"] == 404 + assert components["ItemRead"]["examples"][0]["name"] == "Test Item 1" + assert "password" not in str(components) + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ( + "http://localhost:3000, ,https://example.com/", + ["http://localhost:3000", "https://example.com"], + ), + ('["http://localhost:3000", ""]', ["http://localhost:3000"]), + ("", []), + ], +) +def test_cors_origins_never_contain_an_empty_origin( + monkeypatch: pytest.MonkeyPatch, raw: str, expected: list[str] +) -> None: + # _env_file=None: a developer's .env must not change the result. + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + settings = Settings(_env_file=None) # type: ignore[call-arg] + + assert settings.all_cors_origins == expected + + +def test_business_routes_default_to_the_v1_prefix( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("API_V1_PREFIX", raising=False) + + assert Settings(_env_file=None).API_V1_PREFIX == "/api/v1" # type: ignore[call-arg] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.env.example-tpl index c9d6bec..50c60cb 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.env.example-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/.env.example-tpl @@ -1 +1,11 @@ +# .env.example keeps a public placeholder; fastkit writes a unique key to the +# local, git-ignored .env. With any ENVIRONMENT other than development +# (staging or production) the app refuses to start when SECRET_KEY is unset, +# a public example value or shorter than 32 bytes. SECRET_KEY=changethis +# One of: development, staging, production. +# ENVIRONMENT=development +# API_V1_PREFIX=/api/v1 +# Allowed browser origins, comma-separated or a JSON list. "*" allows any +# origin, but then without credentials (cookies, Authorization headers): +# BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl index a08884a..afca0ab 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl @@ -15,28 +15,32 @@ Simple CRUD API application using FastAPI ``` . ├── README.md +├── pyproject.toml ├── requirements.txt -├── setup.py ├── scripts -│   └── run-server.sh +│ └── run-server.sh ├── src -│   ├── main.py -│   ├── schemas -│   │   └── items.py -│   ├── mocks -│   │   └── mock_items.json -│   ├── crud -│   │   └── items.py -│   ├── core -│   │   └── config.py -│   └── api -│   ├── api.py -│   └── routes -│   └── items.py +│ ├── main.py +│ ├── schemas +│ │ └── items.py +│ ├── mocks +│ │ └── mock_items.json +│ ├── crud +│ │ └── items.py +│ ├── core +│ │ ├── config.py +│ │ ├── pagination.py +│ │ └── responses.py +│ └── api +│ ├── api.py +│ ├── deps.py +│ └── routes +│ └── items.py └── tests ├── __init__.py + ├── conftest.py ├── test_items.py - └── conftest.py + └── test_main.py ``` ## How to run @@ -67,20 +71,32 @@ http://127.0.0.1:8000/docs ## API Endpoints -| Method | Endpoint | Description | -|--------|------------------|----------------------------| -| GET | `/items/` | List all items | -| GET | `/items/{id}` | Get single item | -| POST | `/items/` | Create new item | -| PUT | `/items/{id}` | Update existing item | -| DELETE | `/items/{id}` | Delete item | +Business routes are mounted under `API_V1_PREFIX` (default `/api/v1`). + +| Method | Endpoint | Status | Description | +|--------|--------------------------|--------|-----------------------------------------------| +| GET | `/health` | 200 | Liveness probe, returns `{"status": "ok"}` | +| GET | `/api/v1/items` | 200 | List items (`limit` 1-100, default 20; `offset`) | +| POST | `/api/v1/items` | 201 | Create an item (`Location` header points to it) | +| GET | `/api/v1/items/{id}` | 200 | Get one item | +| PUT | `/api/v1/items/{id}` | 200 | Replace an item (all fields required) | +| PATCH | `/api/v1/items/{id}` | 200 | Update only the fields sent | +| DELETE | `/api/v1/items/{id}` | 204 | Delete an item | + +The list endpoint returns a page: `{"items": [...], "total": 2, "limit": 20, "offset": 0}`. +A missing item answers 404 with `{"detail": "Item not found"}`. ## Key Features - Initial data loading with mock data - Pydantic model-based data validation - Demo CRUD operations implementation (Item CRUD) -- Integrated test cases +- Integrated test cases (they run against a temporary copy of the data, never `src/mocks`) +- CORS enabled only for the origins listed in `BACKEND_CORS_ORIGINS` (`*` allows any + origin, but then without credentials such as cookies or `Authorization` headers) +- Any `ENVIRONMENT` other than `development` (`staging`, `production`) refuses to + start unless `SECRET_KEY` is set explicitly, is at least 32 bytes long and is not + a public example value ## Running Tests diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/pyproject.toml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/pyproject.toml-tpl index 5c97e69..8ad683a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/pyproject.toml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/pyproject.toml-tpl @@ -13,7 +13,6 @@ dependencies = [ "uvicorn[standard]>=0.52.4", "pydantic>=2.13.5", "pydantic-settings>=2.15.0", - "SQLAlchemy>=2.0.52", "python-dotenv>=1.2.3", ] @@ -24,7 +23,6 @@ dev = [ "black>=26.10.1", "isort>=9.0.1", "mypy>=2.3.1", - "PyYAML>=6.0.3", ] [dependency-groups] @@ -34,7 +32,6 @@ dev = [ "black>=26.10.1", "isort>=9.0.1", "mypy>=2.3.1", - "PyYAML>=6.0.3", ] [tool.fastapi-fastkit] @@ -82,3 +79,8 @@ python_files = ["test_*.py"] python_classes = ["Test*"] python_functions = ["test_*"] addopts = "-v --tb=short" +filterwarnings = [ + # starlette's TestClient now prefers `httpx2`; this project pins httpx, so only + # that advisory notice (a UserWarning subclass) is silenced. + "ignore:Using `httpx` with `starlette.testclient` is deprecated:starlette.exceptions.StarletteDeprecationWarning", +] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/requirements.txt-tpl index bc4f39d..4b4a7bf 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/requirements.txt-tpl @@ -1,6 +1,6 @@ annotated-doc==0.0.5 annotated-types==0.8.0 -anyio==4.15.0 +anyio==4.16.0 ast-serialize==0.9.0 black==26.10.1 certifi==2026.10.23 @@ -28,8 +28,7 @@ pytest==9.1.1 python-dotenv==1.2.3 pytokens==0.4.1 PyYAML==6.0.3 -SQLAlchemy==2.0.52 -starlette==1.6.0 +starlette==1.10.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/setup.cfg-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/setup.cfg-tpl deleted file mode 100644 index f8ecdbe..0000000 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/setup.cfg-tpl +++ /dev/null @@ -1,13 +0,0 @@ -[mypy] -warn_unused_configs = true -ignore_missing_imports = true - -[isort] -profile = black -line_length=100 -virtual_env=venv - -[tool:pytest] -pythonpath = src -testpaths = tests -python_files = test_*.py diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/deps.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/deps.py-tpl new file mode 100644 index 0000000..39c53bd --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/deps.py-tpl @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------- +# Shared route dependencies +# -------------------------------------------------------------------------- +from typing import Annotated + +from fastapi import Depends + +from src.crud.items import ItemStore, item_store + + +def get_item_store() -> ItemStore: + """Return the item store (tests override this dependency).""" + return item_store + + +ItemStoreDep = Annotated[ItemStore, Depends(get_item_store)] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/routes/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/routes/items.py-tpl index 7a28bcc..04bd960 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/routes/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/api/routes/items.py-tpl @@ -1,56 +1,73 @@ # -------------------------------------------------------------------------- # Item CRUD Endpoint # -------------------------------------------------------------------------- +from fastapi import APIRouter, HTTPException, Request, Response, status -from fastapi import APIRouter, HTTPException +from src.api.deps import ItemStoreDep +from src.core.pagination import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from src.core.responses import error_responses +from src.schemas.items import ItemCreate, ItemRead, ItemUpdate -from src.crud.items import read_items, write_items -from src.schemas.items import ItemCreate, ItemResponse +router = APIRouter(prefix="/items", tags=["items"]) -router = APIRouter() +def item_not_found() -> HTTPException: + return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found") -@router.get("/items", response_model=list[ItemResponse]) -async def read_all_items(): - return read_items() +@router.get("") +def list_items( + store: ItemStoreDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> Page[ItemRead]: + items, total = store.list_page(offset=offset, limit=limit) + return Page[ItemRead]( + items=[ItemRead.model_validate(item) for item in items], + total=total, + limit=limit, + offset=offset, + ) -@router.get("/items/{item_id}", response_model=ItemResponse) -async def read_item(item_id: int): - items = read_items() - item = next((i for i in items if i["id"] == item_id), None) - if not item: - raise HTTPException(status_code=404, detail="Item not found") - return item +@router.get("/{item_id}", responses=error_responses(404)) +def get_item(item_id: int, store: ItemStoreDep) -> ItemRead: + item = store.get(item_id) + if item is None: + raise item_not_found() + return ItemRead.model_validate(item) -@router.post("/items", response_model=ItemResponse, status_code=201) -async def create_item(item: ItemCreate): - items = read_items() - new_id = max(i["id"] for i in items) + 1 if items else 1 - new_item = {**item.model_dump(), "id": new_id} - items.append(new_item) - write_items(items) - return new_item +@router.post("", status_code=status.HTTP_201_CREATED) +def create_item( + payload: ItemCreate, request: Request, response: Response, store: ItemStoreDep +) -> ItemRead: + item = store.create(payload.model_dump()) + response.headers["Location"] = str(request.url_for("get_item", item_id=item["id"])) + return ItemRead.model_validate(item) -@router.put("/items/{item_id}", response_model=ItemResponse) -async def update_item(item_id: int, item: ItemCreate): - items = read_items() - index = next((i for i, v in enumerate(items) if v["id"] == item_id), None) - if index is None: - raise HTTPException(status_code=404, detail="Item not found") - updated_item = {**item.model_dump(), "id": item_id} - items[index] = updated_item - write_items(items) - return updated_item +@router.put("/{item_id}", responses=error_responses(404)) +def replace_item(item_id: int, payload: ItemCreate, store: ItemStoreDep) -> ItemRead: + item = store.replace(item_id, payload.model_dump()) + if item is None: + raise item_not_found() + return ItemRead.model_validate(item) -@router.delete("/items/{item_id}") -async def delete_item(item_id: int): - items = read_items() - new_items = [i for i in items if i["id"] != item_id] - if len(new_items) == len(items): - raise HTTPException(status_code=404, detail="Item not found") - write_items(new_items) - return {"message": "Item deleted successfully"} + +@router.patch("/{item_id}", responses=error_responses(404)) +def update_item(item_id: int, payload: ItemUpdate, store: ItemStoreDep) -> ItemRead: + item = store.update(item_id, payload.model_dump(exclude_unset=True)) + if item is None: + raise item_not_found() + return ItemRead.model_validate(item) + + +@router.delete( + "/{item_id}", + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(404), +) +def delete_item(item_id: int, store: ItemStoreDep) -> None: + if not store.delete(item_id): + raise item_not_found() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/config.py-tpl index 1c51229..ca0f5a5 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/config.py-tpl @@ -1,23 +1,64 @@ # -------------------------------------------------------------------------- # Configuration module # -------------------------------------------------------------------------- +import json import secrets import warnings -from typing import Annotated, Any, Literal, Self +from typing import Annotated, Any, Literal from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator -from pydantic_settings import BaseSettings, SettingsConfigDict - - -def parse_cors(v: Any) -> list[str] | str: - if isinstance(v, str) and not v.startswith("["): - return [i.strip() for i in v.split(",")] - elif isinstance(v, list | str): - return v - raise ValueError(v) - - -CorsOrigins = Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] +from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict + + +def parse_cors(value: Any) -> Any: + """Read origins from a comma-separated string or a JSON list. + + Blank entries are dropped, so ``BACKEND_CORS_ORIGINS=`` or a trailing + comma never turns into an empty origin. + """ + if isinstance(value, str): + value = value.strip() + if value.startswith("["): + value = json.loads(value) + else: + value = value.split(",") + if isinstance(value, list): + return [str(origin).strip() for origin in value if str(origin).strip()] + raise ValueError(value) + + +# Each origin is a full URL such as http://localhost:3000, or "*" for any +# origin. "*" never goes together with credentials (cookies, Authorization +# headers): browsers refuse that, so main.py turns credentials off for it. +CorsOrigins = Annotated[ + list[Literal["*"] | AnyUrl], NoDecode, BeforeValidator(parse_cors) +] + +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + "your-secret-key-here", + "change-me-in-production", + "your-mcp-api-key-here", + } +) + +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = 32 + +_GENERATE_KEY_HINT = ( + "Generate one with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) class Settings(BaseSettings): @@ -27,38 +68,63 @@ class Settings(BaseSettings): extra="ignore", ) + PROJECT_NAME: str = "" + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + # The shipped code signs nothing with SECRET_KEY yet, but authentication + # you add later (including the JWT and Session options of fastkit init) + # signs tokens or cookies with it, so treat it as a production secret. + # fastkit writes a unique value to .env; staging and production refuse a + # missing, public or short key (see _check_secret_key below). SECRET_KEY: str = secrets.token_urlsafe(32) - ENVIRONMENT: Literal["development", "production"] = "development" - CLIENT_ORIGIN: str = "" + # Every business router is mounted under this prefix (see src/main.py). + API_V1_PREFIX: str = "/api/v1" BACKEND_CORS_ORIGINS: CorsOrigins = [] @computed_field # type: ignore[prop-decorator] @property def all_cors_origins(self) -> list[str]: - return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + [ - self.CLIENT_ORIGIN - ] - - PROJECT_NAME: str = "" - - def _check_default_secret(self, var_name: str, value: str | None) -> None: - if value == "changethis": - message = ( - f'The value of {var_name} is "changethis", ' - "for security, please change it, at least for deployments." - ) - if self.ENVIRONMENT == "development": - warnings.warn(message, stacklevel=1) - else: - raise ValueError(message) + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins @model_validator(mode="after") - def _enforce_non_default_secrets(self) -> Self: - self._check_default_secret("SECRET_KEY", self.SECRET_KEY) - + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) + return self + env = f"ENVIRONMENT={self.ENVIRONMENT}" + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT + ) + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: + raise ValueError( + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT + ) return self -settings = Settings() # type: ignore +settings = Settings() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/pagination.py-tpl new file mode 100644 index 0000000..2688822 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/pagination.py-tpl @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------- +# Limit/offset pagination shared by every list endpoint. +# +# List endpoints take ``limit: LimitParam = DEFAULT_LIMIT`` and +# ``offset: OffsetParam = 0`` and return a ``Page[T]`` envelope: +# {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range +# values are rejected with a 422 rather than clamped. +# -------------------------------------------------------------------------- +from typing import Annotated, Generic, TypeVar + +from fastapi import Query +from pydantic import BaseModel + +T = TypeVar("T") + +#: Page size used when the client sends no ``limit``. +DEFAULT_LIMIT = 20 +#: Largest page a client may ask for. +MAX_LIMIT = 100 + +LimitParam = Annotated[ + int, Query(ge=1, le=MAX_LIMIT, description="Maximum number of items to return.") +] +OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] + + +class Page(BaseModel, Generic[T]): + """One page of a collection, ordered by primary key. + + ``total`` counts the whole collection, so a client knows there is a next + page while ``offset + len(items) < total``. + """ + + items: list[T] + total: int + limit: int + offset: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/responses.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/responses.py-tpl new file mode 100644 index 0000000..bffc8c1 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/core/responses.py-tpl @@ -0,0 +1,40 @@ +# -------------------------------------------------------------------------- +# OpenAPI error responses shared by the routers. +# +# FastAPI documents 2xx and 422 on its own. Routes that can also answer 401, +# 404, 409, ... declare it with ``responses=error_responses(404)`` so clients +# see every status code and the ``{"detail": "..."}`` body in the schema. +# -------------------------------------------------------------------------- +from http import HTTPStatus +from typing import Any + +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + """Body FastAPI sends for an ``HTTPException``.""" + + detail: str + + +def error_responses(*status_codes: int) -> dict[int | str, dict[str, Any]]: + """Build ``responses=`` entries that document the given error codes. + + A 401 entry also documents the ``WWW-Authenticate`` header every 401 + response carries. + """ + responses: dict[int | str, dict[str, Any]] = {} + for code in status_codes: + entry: dict[str, Any] = { + "model": ErrorDetail, + "description": HTTPStatus(code).phrase, + } + if code == HTTPStatus.UNAUTHORIZED: + entry["headers"] = { + "WWW-Authenticate": { + "description": "Authentication scheme to use (Bearer).", + "schema": {"type": "string"}, + } + } + responses[code] = entry + return responses diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/crud/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/crud/items.py-tpl index a87d104..d11a046 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/crud/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/crud/items.py-tpl @@ -1,17 +1,130 @@ # -------------------------------------------------------------------------- # Item CRUD method module +# +# Items live in a JSON file. The route handlers are plain ``def`` functions, +# so FastAPI runs them in a thread pool; every file access holds a lock so +# two concurrent requests can neither hand out the same id nor lose a write. +# +# The file keeps the next id next to the items, so an id is never handed out +# twice: not after the item with the highest id is deleted, and not after a +# restart. Every write goes to a temporary file that then replaces the data +# file in one step, so a crash mid-write leaves the previous file intact. +# The lock covers one process only; with several workers, use a database. # -------------------------------------------------------------------------- +import contextlib import json import os +import tempfile +import threading +from collections.abc import Callable +from pathlib import Path +from typing import Any -MOCK_FILE = os.path.join(os.path.dirname(__file__), "../mocks/mock_items.json") +MOCK_FILE = Path(__file__).resolve().parent.parent / "mocks" / "mock_items.json" +ItemData = dict[str, Any] -def read_items(): - with open(MOCK_FILE) as file: - return json.load(file) +def _parse(data: Any) -> tuple[list[ItemData], int]: + """Return the stored items ordered by id and the next id to hand out. -def write_items(items: list[dict]): - with open(MOCK_FILE, "w") as file: - json.dump(items, file, indent=2) + Older data files, like the shipped mock data, are a plain list of items; + for those the next id continues after the highest id in the file. + """ + if isinstance(data, list): + items: list[ItemData] = data + next_id = 1 + else: + items = data["items"] + next_id = int(data.get("next_id", 1)) + items = sorted(items, key=lambda item: item["id"]) + highest = max((item["id"] for item in items), default=0) + return items, max(next_id, highest + 1) + + +def _dump(items: list[ItemData], next_id: int) -> str: + return json.dumps({"next_id": next_id, "items": items}, indent=2) + "\n" + + +def _write_atomic(path: Path, text: str) -> None: + """Replace ``path`` with ``text``; readers see the old or the new file.""" + fd, temp_name = tempfile.mkstemp( + dir=path.parent, prefix=f".{path.name}.", suffix=".tmp" + ) + try: + with os.fdopen(fd, "w", encoding="utf-8") as file: + file.write(text) + file.flush() + os.fsync(file.fileno()) + # The temporary file is closed before the rename, as Windows requires. + os.replace(temp_name, path) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(temp_name) + raise + + +class ItemStore: + """Item persistence backed by one JSON file.""" + + def __init__(self, path: Path) -> None: + self.path = path + self._lock = threading.Lock() + + def _load(self) -> tuple[list[ItemData], int]: + with self.path.open(encoding="utf-8") as file: + return _parse(json.load(file)) + + def _save(self, items: list[ItemData], next_id: int) -> None: + _write_atomic(self.path, _dump(items, next_id)) + + def list_page(self, offset: int, limit: int) -> tuple[list[ItemData], int]: + """Return one page of items ordered by id, plus the total count.""" + with self._lock: + items, _ = self._load() + return items[offset : offset + limit], len(items) + + def get(self, item_id: int) -> ItemData | None: + with self._lock: + items, _ = self._load() + return next((item for item in items if item["id"] == item_id), None) + + def create(self, data: ItemData) -> ItemData: + with self._lock: + items, next_id = self._load() + item = {**data, "id": next_id} + items.append(item) + self._save(items, next_id + 1) + return item + + def replace(self, item_id: int, data: ItemData) -> ItemData | None: + return self._modify(item_id, lambda current: {**data, "id": item_id}) + + def update(self, item_id: int, changes: ItemData) -> ItemData | None: + return self._modify( + item_id, lambda current: {**current, **changes, "id": item_id} + ) + + def delete(self, item_id: int) -> bool: + with self._lock: + items, next_id = self._load() + remaining = [item for item in items if item["id"] != item_id] + if len(remaining) == len(items): + return False + self._save(remaining, next_id) + return True + + def _modify( + self, item_id: int, change: Callable[[ItemData], ItemData] + ) -> ItemData | None: + with self._lock: + items, next_id = self._load() + for index, current in enumerate(items): + if current["id"] == item_id: + items[index] = change(current) + self._save(items, next_id) + return items[index] + return None + + +item_store = ItemStore(MOCK_FILE) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/main.py-tpl index 28449fc..e9aa39f 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/main.py-tpl @@ -14,21 +14,24 @@ app = FastAPI( title=settings.PROJECT_NAME, ) +# Origins come only from BACKEND_CORS_ORIGINS; with none configured the +# middleware is not installed at all. if settings.all_cors_origins: app.add_middleware( CORSMiddleware, allow_origins=settings.all_cors_origins, - allow_credentials=True, + # Browsers refuse credentials with the "*" wildcard; never send both. + allow_credentials="*" not in settings.all_cors_origins, allow_methods=["*"], allow_headers=["*"], ) # fastkit:routes -app.include_router(api_router) +app.include_router(api_router, prefix=settings.API_V1_PREFIX) -@app.get("/health") +@app.get("/health", tags=["health"]) async def health_check() -> dict[str, str]: - """Health check endpoint.""" - return {"status": "healthy"} + """Liveness probe: no authentication and no I/O.""" + return {"status": "ok"} diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/schemas/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/schemas/items.py-tpl index 859f4ef..13cc7fb 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/schemas/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/src/schemas/items.py-tpl @@ -1,21 +1,41 @@ # -------------------------------------------------------------------------- # Item schema module # -------------------------------------------------------------------------- - -from pydantic import BaseModel, ConfigDict +from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator class ItemBase(BaseModel): - name: str - description: str | None = None - price: float - category: str + name: str = Field(min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=1000) + price: float = Field(ge=0) + category: str = Field(min_length=1, max_length=50) class ItemCreate(ItemBase): - pass + """POST and PUT body: every required field must be sent.""" -class ItemResponse(ItemBase): - id: int +class ItemUpdate(BaseModel): + """PATCH body: send only the fields to change. + + ``description`` can be cleared with an explicit ``null``; the other + fields are required on an item, so ``null`` is rejected for them. + """ + + name: str | None = Field(default=None, min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=1000) + price: float | None = Field(default=None, ge=0) + category: str | None = Field(default=None, min_length=1, max_length=50) + + @field_validator("name", "price", "category") + @classmethod + def _reject_null(cls, value: object, info: ValidationInfo) -> object: + if value is None: + raise ValueError(f"{info.field_name} must not be null") + return value + + +class ItemRead(ItemBase): model_config = ConfigDict(from_attributes=True) + + id: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl index 9f7da2f..f3a01a4 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl @@ -2,29 +2,36 @@ # pytest runtime configuration module # -------------------------------------------------------------------------- import json -import os from collections.abc import Generator +from pathlib import Path import pytest from fastapi.testclient import TestClient +from src.api.deps import get_item_store +from src.core.config import settings +from src.crud.items import ItemStore from src.main import app -MOCK_FILE = os.path.join(os.path.dirname(__file__), "../src/mocks/mock_items.json") +ITEMS_URL = f"{settings.API_V1_PREFIX}/items" +SEED_ITEMS = [ + {"id": 1, "name": "Test Item 1", "price": 10.5, "category": "test"}, + {"id": 2, "name": "Test Item 2", "price": 20.0, "category": "test"}, +] -@pytest.fixture(autouse=True) -def reset_mock_data(): - initial_data = [ - {"id": 1, "name": "Test Item 1", "price": 10.5, "category": "test"}, - {"id": 2, "name": "Test Item 2", "price": 20.0, "category": "test"}, - ] - with open(MOCK_FILE, "w") as file: - json.dump(initial_data, file) - yield +@pytest.fixture +def store(tmp_path: Path) -> ItemStore: + """Item store on a temporary file, so tests never touch src/mocks.""" + path = tmp_path / "items.json" + path.write_text(json.dumps(SEED_ITEMS), encoding="utf-8") + return ItemStore(path) -@pytest.fixture(scope="module") -def client() -> Generator[TestClient, None, None]: + +@pytest.fixture +def client(store: ItemStore) -> Generator[TestClient, None, None]: + app.dependency_overrides[get_item_store] = lambda: store with TestClient(app) as c: yield c + app.dependency_overrides.clear() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_config.py-tpl new file mode 100644 index 0000000..38f107b --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_config.py-tpl @@ -0,0 +1,194 @@ +# -------------------------------------------------------------------------- +# Settings validation: the SECRET_KEY rule, ENVIRONMENT values, +# environment variable names and the CORS wildcard. +# -------------------------------------------------------------------------- +import json +import os +import secrets +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest +from pydantic import ValidationError + +from src.core.config import KNOWN_EXAMPLE_SECRET_KEYS, MIN_SECRET_KEY_BYTES, Settings + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +APP_MODULE = "src.main" +#: Settings without a default; none in this template. +REQUIRED: dict[str, Any] = {} + +STRONG_KEY = "k" * MIN_SECRET_KEY_BYTES +#: Every environment except development refuses a missing, public or short +#: SECRET_KEY. +STRICT_ENVIRONMENTS = ["staging", "production"] + + +@pytest.fixture(autouse=True) +def _isolated_settings_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Shell variables, in any spelling, must not leak into Settings().""" + for name in list(os.environ): + if name.upper() in {"ENVIRONMENT", "SECRET_KEY", "BACKEND_CORS_ORIGINS"}: + monkeypatch.delenv(name) + + +def make_settings(env_file: Path | None = None, **values: Any) -> Settings: + """Settings from explicit values; a developer's .env is never read.""" + return Settings(_env_file=env_file, **{**REQUIRED, **values}) # type: ignore[call-arg] + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_require_an_explicit_secret_key(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"must be set explicitly when ENVIRONMENT={environment}" + ): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_refuse_a_short_secret_key(environment: str) -> None: + short_key = "k" * (MIN_SECRET_KEY_BYTES - 1) + + with pytest.raises(ValidationError, match=f"at least {MIN_SECRET_KEY_BYTES} bytes"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=short_key) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +@pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) +def test_strict_environments_refuse_every_public_example_key( + environment: str, example_key: str +) -> None: + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=f" {example_key} ") + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environment_errors_say_how_to_generate_a_key(environment: str) -> None: + with pytest.raises(ValidationError, match="token_urlsafe"): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_an_explicit_strong_key(environment: str) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + + assert settings.ENVIRONMENT == environment + assert settings.SECRET_KEY == STRONG_KEY + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_the_key_fastkit_writes_to_env( + tmp_path: Path, environment: str +) -> None: + env_file = tmp_path / ".env" + env_file.write_text( + f"ENVIRONMENT={environment}\nSECRET_KEY={secrets.token_urlsafe(32)}\n", + encoding="utf-8", + ) + + assert make_settings(env_file).ENVIRONMENT == environment + + +def test_development_without_a_key_uses_a_random_one() -> None: + settings = make_settings(ENVIRONMENT="development") + + assert len(settings.SECRET_KEY.encode()) >= MIN_SECRET_KEY_BYTES + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_development_only_warns_about_an_example_key() -> None: + example_key = sorted(KNOWN_EXAMPLE_SECRET_KEYS)[0] + + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings(ENVIRONMENT="development", SECRET_KEY=example_key) + + assert settings.SECRET_KEY == example_key + + +@pytest.mark.parametrize("value", ["Production", "PRODUCTION", " production", "prod"]) +def test_unknown_environment_values_fail_closed(value: str) -> None: + with pytest.raises(ValidationError, match="ENVIRONMENT"): + make_settings(ENVIRONMENT=value, SECRET_KEY=STRONG_KEY) + + +def test_environment_variable_names_are_case_insensitive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("environment", "production") + + with pytest.raises(ValidationError, match="must be set explicitly"): + make_settings() + + monkeypatch.setenv("secret_key", STRONG_KEY) + + assert make_settings().ENVIRONMENT == "production" + + +@pytest.mark.parametrize("raw", ["*", " * ", '["*"]', "*,http://localhost:3000"]) +def test_cors_wildcard_is_accepted(monkeypatch: pytest.MonkeyPatch, raw: str) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + + assert make_settings().all_cors_origins == ["*"] + + +def test_cors_origins_must_be_urls_or_the_wildcard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + + with pytest.raises(ValidationError): + make_settings() + + +#: Runs in a fresh interpreter: the app reads its settings at import time. +_PREFLIGHT = f""" +import json +from fastapi.testclient import TestClient +from {APP_MODULE} import app + +headers = {{ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "GET", +}} +response = TestClient(app).options("/", headers=headers) +allowed = {{ + k: v for k, v in response.headers.items() if k.startswith("access-control-allow-") +}} +print(json.dumps(allowed)) +""" + + +@pytest.mark.parametrize( + ("origins", "allow_origin", "allow_credentials"), + [ + ("*", "*", None), + ("http://localhost:3000", "http://localhost:3000", "true"), + ], +) +def test_cors_wildcard_is_never_combined_with_credentials( + origins: str, allow_origin: str, allow_credentials: str | None +) -> None: + env = { + **os.environ, + **{name: str(value) for name, value in REQUIRED.items()}, + "BACKEND_CORS_ORIGINS": origins, + "ENVIRONMENT": "development", + } + result = subprocess.run( + [sys.executable, "-c", _PREFLIGHT], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + check=False, + ) + + assert result.returncode == 0, result.stderr + headers = json.loads(result.stdout.strip().splitlines()[-1]) + assert headers["access-control-allow-origin"] == allow_origin + assert headers.get("access-control-allow-credentials") == allow_credentials diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_item_store.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_item_store.py-tpl new file mode 100644 index 0000000..f9c1e09 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_item_store.py-tpl @@ -0,0 +1,81 @@ +# -------------------------------------------------------------------------- +# Item store persistence testcases +# -------------------------------------------------------------------------- +import json +from pathlib import Path +from typing import Any + +import pytest + +from src.crud.items import ItemStore + +NEW_ITEM = {"name": "New Item", "price": 30.0, "category": "new"} + + +def make_store(tmp_path: Path, data: Any) -> ItemStore: + path = tmp_path / "items.json" + path.write_text(json.dumps(data), encoding="utf-8") + return ItemStore(path) + + +def seed(*ids: int) -> list[dict[str, Any]]: + return [{**NEW_ITEM, "id": item_id} for item_id in ids] + + +def test_deleted_id_is_not_reused(tmp_path: Path) -> None: + store = make_store(tmp_path, seed(1, 2)) + + first = store.create(dict(NEW_ITEM)) + assert store.delete(first["id"]) + second = store.create(dict(NEW_ITEM)) + + assert first["id"] == 3 + assert second["id"] == 4 + + +def test_restart_does_not_reuse_the_deleted_highest_id(tmp_path: Path) -> None: + store = make_store(tmp_path, seed(1, 2)) + created = store.create(dict(NEW_ITEM)) + assert store.delete(created["id"]) + + restarted = ItemStore(store.path) + after_restart = restarted.create(dict(NEW_ITEM)) + + assert after_restart["id"] == created["id"] + 1 + saved = json.loads(store.path.read_text(encoding="utf-8")) + assert saved["next_id"] == after_restart["id"] + 1 + + +def test_old_list_format_file_still_loads(tmp_path: Path) -> None: + store = make_store(tmp_path, seed(5, 2)) + + items, total = store.list_page(offset=0, limit=10) + + assert [item["id"] for item in items] == [2, 5] + assert total == 2 + assert store.get(5) is not None + assert store.create(dict(NEW_ITEM))["id"] == 6 + + +def test_next_id_never_goes_below_the_highest_stored_id(tmp_path: Path) -> None: + store = make_store(tmp_path, {"next_id": 2, "items": seed(1, 7)}) + + assert store.create(dict(NEW_ITEM))["id"] == 8 + + +def test_failed_write_keeps_the_file_and_leaves_no_temp_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + store = make_store(tmp_path, seed(1, 2)) + before = store.path.read_bytes() + + def fail_replace(*args: Any, **kwargs: Any) -> None: + raise OSError("simulated crash while replacing the file") + + monkeypatch.setattr("src.crud.items.os.replace", fail_replace) + + with pytest.raises(OSError, match="simulated crash"): + store.create(dict(NEW_ITEM)) + + assert store.path.read_bytes() == before + assert list(tmp_path.iterdir()) == [store.path] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_items.py-tpl index 5a27cc2..fae32e1 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_items.py-tpl @@ -1,41 +1,192 @@ # -------------------------------------------------------------------------- # Item endpoint testcases # -------------------------------------------------------------------------- +from concurrent.futures import ThreadPoolExecutor +import pytest +from fastapi.testclient import TestClient + +from src.crud.items import MOCK_FILE, ItemStore +from tests.conftest import ITEMS_URL + +NEW_ITEM = {"name": "New Item", "price": 30.0, "category": "new"} + + +def test_list_items_returns_a_page(client: TestClient) -> None: + response = client.get(ITEMS_URL) -def test_read_all_items(client): - response = client.get("/items") assert response.status_code == 200 - assert len(response.json()) == 2 + body = response.json() + assert set(body) == {"items", "total", "limit", "offset"} + assert body["total"] == 2 + assert body["limit"] == 20 + assert body["offset"] == 0 + assert [item["id"] for item in body["items"]] == [1, 2] -def test_read_item_success(client): - response = client.get("/items/1") +def test_list_items_limit_and_offset(client: TestClient) -> None: + response = client.get(ITEMS_URL, params={"limit": 1, "offset": 1}) + + assert response.status_code == 200 + body = response.json() + assert [item["name"] for item in body["items"]] == ["Test Item 2"] + assert body["total"] == 2 + assert body["limit"] == 1 + assert body["offset"] == 1 + + +def test_list_items_offset_past_the_end(client: TestClient) -> None: + body = client.get(ITEMS_URL, params={"offset": 10}).json() + + assert body["items"] == [] + assert body["total"] == 2 + + +@pytest.mark.parametrize( + "params", [{"limit": 0}, {"limit": 101}, {"offset": -1}, {"limit": "x"}] +) +def test_list_items_rejects_out_of_range_pagination( + client: TestClient, params: dict[str, object] +) -> None: + assert client.get(ITEMS_URL, params=params).status_code == 422 + + +def test_collection_is_served_without_redirect(client: TestClient) -> None: + response = client.get(ITEMS_URL, follow_redirects=False) + + assert response.status_code == 200 + + +def test_get_item(client: TestClient) -> None: + response = client.get(f"{ITEMS_URL}/1") + assert response.status_code == 200 assert response.json()["name"] == "Test Item 1" -def test_read_item_not_found(client): - response = client.get("/items/999") +def test_get_item_not_found(client: TestClient) -> None: + response = client.get(f"{ITEMS_URL}/999") + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} -def test_create_item(client): - new_item = {"name": "New Item", "price": 30.0, "category": "new"} - response = client.post("/items", json=new_item) +def test_create_item_returns_201_and_location(client: TestClient) -> None: + response = client.post(ITEMS_URL, json=NEW_ITEM) + assert response.status_code == 201 - assert response.json()["id"] == 3 + created = response.json() + assert created["id"] not in (1, 2) + assert created["name"] == "New Item" + location = response.headers["location"] + assert location.endswith(f"{ITEMS_URL}/{created['id']}") + assert client.get(location).json() == created + + +@pytest.mark.parametrize( + "payload", + [ + {**NEW_ITEM, "name": ""}, + {**NEW_ITEM, "price": -1}, + {"name": "No price", "category": "new"}, + ], +) +def test_create_item_validates_input( + client: TestClient, payload: dict[str, object] +) -> None: + assert client.post(ITEMS_URL, json=payload).status_code == 422 -def test_update_item(client): - updated_data = {"name": "Updated Item", "price": 15.0, "category": "updated"} - response = client.put("/items/1", json=updated_data) +def test_put_replaces_the_whole_item(client: TestClient) -> None: + client.patch(f"{ITEMS_URL}/1", json={"description": "will be dropped"}) + + response = client.put( + f"{ITEMS_URL}/1", json={"name": "Replaced", "price": 1.0, "category": "x"} + ) + assert response.status_code == 200 - assert response.json()["name"] == "Updated Item" + assert response.json() == { + "id": 1, + "name": "Replaced", + "description": None, + "price": 1.0, + "category": "x", + } + + +def test_put_requires_every_field(client: TestClient) -> None: + response = client.put(f"{ITEMS_URL}/1", json={"name": "Only a name"}) + assert response.status_code == 422 + + +def test_put_not_found(client: TestClient) -> None: + response = client.put(f"{ITEMS_URL}/999", json=NEW_ITEM) + + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +def test_patch_changes_only_the_sent_fields(client: TestClient) -> None: + response = client.patch(f"{ITEMS_URL}/1", json={"price": 99.0}) + + assert response.status_code == 200 + body = response.json() + assert body["price"] == 99.0 + assert body["name"] == "Test Item 1" + assert body["category"] == "test" + + +def test_patch_can_clear_a_nullable_field(client: TestClient) -> None: + client.patch(f"{ITEMS_URL}/1", json={"description": "temporary"}) + + response = client.patch(f"{ITEMS_URL}/1", json={"description": None}) -def test_delete_item(client): - response = client.delete("/items/1") assert response.status_code == 200 - response = client.get("/items/1") + assert response.json()["description"] is None + + +def test_patch_rejects_null_for_required_fields(client: TestClient) -> None: + response = client.patch(f"{ITEMS_URL}/1", json={"name": None}) + + assert response.status_code == 422 + assert client.get(f"{ITEMS_URL}/1").json()["name"] == "Test Item 1" + + +def test_patch_not_found(client: TestClient) -> None: + response = client.patch(f"{ITEMS_URL}/999", json={"price": 1.0}) + assert response.status_code == 404 + + +def test_delete_item_returns_204(client: TestClient) -> None: + response = client.delete(f"{ITEMS_URL}/1") + + assert response.status_code == 204 + assert response.content == b"" + assert client.get(f"{ITEMS_URL}/1").status_code == 404 + + +def test_delete_item_not_found(client: TestClient) -> None: + response = client.delete(f"{ITEMS_URL}/999") + + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +def test_tests_do_not_modify_the_shipped_mock_file(client: TestClient) -> None: + before = MOCK_FILE.read_bytes() + + client.post(ITEMS_URL, json=NEW_ITEM) + client.delete(f"{ITEMS_URL}/1") + + assert MOCK_FILE.read_bytes() == before + + +def test_concurrent_creates_get_unique_ids(store: ItemStore) -> None: + with ThreadPoolExecutor(max_workers=8) as pool: + created = list(pool.map(lambda _: store.create(dict(NEW_ITEM)), range(20))) + + ids = [item["id"] for item in created] + assert len(set(ids)) == 20 + assert store.list_page(offset=0, limit=100)[1] == 22 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_main.py-tpl new file mode 100644 index 0000000..f56c078 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_main.py-tpl @@ -0,0 +1,59 @@ +# -------------------------------------------------------------------------- +# Application-level testcases (health, OpenAPI, settings) +# -------------------------------------------------------------------------- +import pytest +from fastapi.testclient import TestClient + +from src.core.config import Settings +from tests.conftest import ITEMS_URL + + +def test_health(client: TestClient) -> None: + response = client.get("/health") + + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + +def test_openapi_documents_routes_tags_and_errors(client: TestClient) -> None: + schema = client.get("/openapi.json").json() + paths = schema["paths"] + + assert "/health" in paths + assert set(paths[ITEMS_URL]) == {"get", "post"} + assert set(paths[f"{ITEMS_URL}/{{item_id}}"]) == {"get", "put", "patch", "delete"} + item_routes = paths[f"{ITEMS_URL}/{{item_id}}"] + for operation in item_routes.values(): + assert operation["tags"] == ["items"] + assert "404" in operation["responses"] + assert "201" in paths[ITEMS_URL]["post"]["responses"] + assert "204" in item_routes["delete"]["responses"] + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ( + "http://localhost:3000, ,https://example.com/", + ["http://localhost:3000", "https://example.com"], + ), + ('["http://localhost:3000", ""]', ["http://localhost:3000"]), + ("", []), + ], +) +def test_cors_origins_never_contain_an_empty_origin( + monkeypatch: pytest.MonkeyPatch, raw: str, expected: list[str] +) -> None: + # _env_file=None: a developer's .env must not change the result. + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + settings = Settings(_env_file=None) # type: ignore[call-arg] + + assert settings.all_cors_origins == expected + + +def test_business_routes_default_to_the_v1_prefix( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("API_V1_PREFIX", raising=False) + + assert Settings(_env_file=None).API_V1_PREFIX == "/api/v1" # type: ignore[call-arg] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.dockerignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.dockerignore-tpl new file mode 100644 index 0000000..151b60c --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.dockerignore-tpl @@ -0,0 +1,47 @@ +# Files Docker never sends to the build, so they cannot end up in the image. + +# Secrets: settings come from the environment at run time (docker run -e / +# --env-file, compose env_file), never from a file baked into the image. +.env +.env.* + +# VCS and editor state +.git +.gitignore +.gitattributes +.idea +.vscode +**/.DS_Store + +# Virtual environments +.venv +venv +env + +# Python, test and tool caches +**/__pycache__ +**/*.py[cod] +.pytest_cache +.mypy_cache +.ruff_cache +.coverage +.coverage.* +coverage.xml +htmlcov +dist +build +*.egg-info + +# Local SQLite databases +**/*.db +**/*.db-journal +**/*.db-wal +**/*.db-shm + +# The application image does not run the test suite +tests + +# Docker files themselves +Dockerfile +docker-compose*.yml +.dockerignore diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.env.example-tpl index c9d6bec..50c60cb 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.env.example-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.env.example-tpl @@ -1 +1,11 @@ +# .env.example keeps a public placeholder; fastkit writes a unique key to the +# local, git-ignored .env. With any ENVIRONMENT other than development +# (staging or production) the app refuses to start when SECRET_KEY is unset, +# a public example value or shorter than 32 bytes. SECRET_KEY=changethis +# One of: development, staging, production. +# ENVIRONMENT=development +# API_V1_PREFIX=/api/v1 +# Allowed browser origins, comma-separated or a JSON list. "*" allows any +# origin, but then without credentials (cookies, Authorization headers): +# BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/Dockerfile-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/Dockerfile-tpl index 9d142ac..6abf722 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/Dockerfile-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/Dockerfile-tpl @@ -1,23 +1,46 @@ FROM python:3.12-slim +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + WORKDIR /app +# Unprivileged runtime user with a fixed UID/GID, so file ownership on mounted +# volumes stays predictable across rebuilds. +RUN groupadd --system --gid 10001 app \ + && useradd --system --uid 10001 --gid app --no-create-home \ + --home-dir /nonexistent --shell /usr/sbin/nologin app + RUN apt-get update && \ apt-get install -y --no-install-recommends \ build-essential \ && rm -rf /var/lib/apt/lists/* COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# The source stays owned by root, read-only for the app user. .dockerignore +# keeps .env, tests/, virtualenvs and local databases out of the build context. COPY pyproject.toml . COPY src/ src/ -COPY tests/ tests/ -RUN pip install --no-cache-dir -r requirements.txt -RUN pip install --no-cache-dir -e . +# Items are stored in src/mocks/mock_items.json: that directory is the only +# place the app user can write to. +RUN chown -R app:app /app/src/mocks +# src/ is imported from /app directly; no package install is needed. ENV PYTHONPATH=/app ENV ENVIRONMENT=production +USER app + EXPOSE 8000 +# Liveness probe on GET /health (the slim image has no curl, so python). +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ + CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3)"] + +# Settings come from the environment at run time, never from a file in the +# image, e.g.: +# docker run -p 8000:8000 -e SECRET_KEY=... CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl index 4fbe388..68faff4 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl @@ -24,28 +24,32 @@ This project is a Docker containerized FastAPI-based item management API applica . ├── Dockerfile ├── README.md +├── pyproject.toml ├── requirements.txt -├── setup.py ├── scripts -│   └── run-server.sh +│ └── run-server.sh ├── src -│   ├── main.py -│   ├── schemas -│   │   └── items.py -│   ├── mocks -│   │   └── mock_items.json -│   ├── crud -│   │   └── items.py -│   ├── core -│   │   └── config.py -│   └── api -│   ├── api.py -│   └── routes -│   └── items.py +│ ├── main.py +│ ├── schemas +│ │ └── items.py +│ ├── mocks +│ │ └── mock_items.json +│ ├── crud +│ │ └── items.py +│ ├── core +│ │ ├── config.py +│ │ ├── pagination.py +│ │ └── responses.py +│ └── api +│ ├── api.py +│ ├── deps.py +│ └── routes +│ └── items.py └── tests ├── __init__.py + ├── conftest.py ├── test_items.py - └── conftest.py + └── test_main.py ``` ## How to run @@ -88,20 +92,32 @@ http://127.0.0.1:8000/docs ## API Endpoints -| Method | Endpoint | Description | -|--------|------------------|----------------------------| -| GET | `/items/` | List all items | -| GET | `/items/{id}` | Get single item | -| POST | `/items/` | Create new item | -| PUT | `/items/{id}` | Update existing item | -| DELETE | `/items/{id}` | Delete item | +Business routes are mounted under `API_V1_PREFIX` (default `/api/v1`). + +| Method | Endpoint | Status | Description | +|--------|--------------------------|--------|-----------------------------------------------| +| GET | `/health` | 200 | Liveness probe, returns `{"status": "ok"}` | +| GET | `/api/v1/items` | 200 | List items (`limit` 1-100, default 20; `offset`) | +| POST | `/api/v1/items` | 201 | Create an item (`Location` header points to it) | +| GET | `/api/v1/items/{id}` | 200 | Get one item | +| PUT | `/api/v1/items/{id}` | 200 | Replace an item (all fields required) | +| PATCH | `/api/v1/items/{id}` | 200 | Update only the fields sent | +| DELETE | `/api/v1/items/{id}` | 204 | Delete an item | + +The list endpoint returns a page: `{"items": [...], "total": 2, "limit": 20, "offset": 0}`. +A missing item answers 404 with `{"detail": "Item not found"}`. ## Key Features - Initial data loading with mock data - Pydantic model-based data validation - Demo CRUD operations implementation (Item CRUD) -- Integrated test cases +- Integrated test cases (they run against a temporary copy of the data, never `src/mocks`) +- CORS enabled only for the origins listed in `BACKEND_CORS_ORIGINS` (`*` allows any + origin, but then without credentials such as cookies or `Authorization` headers) +- Any `ENVIRONMENT` other than `development` (`staging`, `production`) refuses to + start unless `SECRET_KEY` is set explicitly, is at least 32 bytes long and is not + a public example value ## Running Tests diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/pyproject.toml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/pyproject.toml-tpl index c7c5d16..8ad683a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/pyproject.toml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/pyproject.toml-tpl @@ -13,8 +13,6 @@ dependencies = [ "uvicorn[standard]>=0.52.4", "pydantic>=2.13.5", "pydantic-settings>=2.15.0", - "SQLAlchemy>=2.0.52", - "sqlmodel>=0.0.42", "python-dotenv>=1.2.3", ] @@ -25,8 +23,6 @@ dev = [ "black>=26.10.1", "isort>=9.0.1", "mypy>=2.3.1", - "PyYAML>=6.0.3", - "setuptools-scm>=10.2.3", ] [dependency-groups] @@ -36,8 +32,6 @@ dev = [ "black>=26.10.1", "isort>=9.0.1", "mypy>=2.3.1", - "PyYAML>=6.0.3", - "setuptools-scm>=10.2.3", ] [tool.fastapi-fastkit] @@ -85,3 +79,8 @@ python_files = ["test_*.py"] python_classes = ["Test*"] python_functions = ["test_*"] addopts = "-v --tb=short" +filterwarnings = [ + # starlette's TestClient now prefers `httpx2`; this project pins httpx, so only + # that advisory notice (a UserWarning subclass) is silenced. + "ignore:Using `httpx` with `starlette.testclient` is deprecated:starlette.exceptions.StarletteDeprecationWarning", +] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/requirements.txt-tpl index 1d2db0d..4b4a7bf 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/requirements.txt-tpl @@ -1,6 +1,6 @@ annotated-doc==0.0.5 annotated-types==0.8.0 -anyio==4.15.0 +anyio==4.16.0 ast-serialize==0.9.0 black==26.10.1 certifi==2026.10.23 @@ -28,15 +28,10 @@ pytest==9.1.1 python-dotenv==1.2.3 pytokens==0.4.1 PyYAML==6.0.3 -setuptools==84.2.1 -setuptools-scm==10.2.3 -SQLAlchemy==2.0.52 -sqlmodel==0.0.42 -starlette==1.6.0 +starlette==1.10.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 uvloop==0.22.1; sys_platform != "win32" -vcs-versioning==2.3.4 watchfiles==1.2.0 websockets==17.1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/setup.cfg-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/setup.cfg-tpl deleted file mode 100644 index f8ecdbe..0000000 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/setup.cfg-tpl +++ /dev/null @@ -1,13 +0,0 @@ -[mypy] -warn_unused_configs = true -ignore_missing_imports = true - -[isort] -profile = black -line_length=100 -virtual_env=venv - -[tool:pytest] -pythonpath = src -testpaths = tests -python_files = test_*.py diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/deps.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/deps.py-tpl new file mode 100644 index 0000000..39c53bd --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/deps.py-tpl @@ -0,0 +1,16 @@ +# -------------------------------------------------------------------------- +# Shared route dependencies +# -------------------------------------------------------------------------- +from typing import Annotated + +from fastapi import Depends + +from src.crud.items import ItemStore, item_store + + +def get_item_store() -> ItemStore: + """Return the item store (tests override this dependency).""" + return item_store + + +ItemStoreDep = Annotated[ItemStore, Depends(get_item_store)] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/routes/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/routes/items.py-tpl index 7ba6ee5..04bd960 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/routes/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/routes/items.py-tpl @@ -1,53 +1,73 @@ +# -------------------------------------------------------------------------- +# Item CRUD Endpoint +# -------------------------------------------------------------------------- +from fastapi import APIRouter, HTTPException, Request, Response, status -from fastapi import APIRouter, HTTPException +from src.api.deps import ItemStoreDep +from src.core.pagination import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from src.core.responses import error_responses +from src.schemas.items import ItemCreate, ItemRead, ItemUpdate -from src.crud.items import read_items, write_items -from src.schemas.items import ItemCreate, ItemResponse +router = APIRouter(prefix="/items", tags=["items"]) -router = APIRouter() +def item_not_found() -> HTTPException: + return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found") -@router.get("/items", response_model=list[ItemResponse]) -async def read_all_items(): - return read_items() +@router.get("") +def list_items( + store: ItemStoreDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> Page[ItemRead]: + items, total = store.list_page(offset=offset, limit=limit) + return Page[ItemRead]( + items=[ItemRead.model_validate(item) for item in items], + total=total, + limit=limit, + offset=offset, + ) -@router.get("/items/{item_id}", response_model=ItemResponse) -async def read_item(item_id: int): - items = read_items() - item = next((i for i in items if i["id"] == item_id), None) - if not item: - raise HTTPException(status_code=404, detail="Item not found") - return item +@router.get("/{item_id}", responses=error_responses(404)) +def get_item(item_id: int, store: ItemStoreDep) -> ItemRead: + item = store.get(item_id) + if item is None: + raise item_not_found() + return ItemRead.model_validate(item) -@router.post("/items", response_model=ItemResponse, status_code=201) -async def create_item(item: ItemCreate): - items = read_items() - new_id = max(i["id"] for i in items) + 1 if items else 1 - new_item = {**item.model_dump(), "id": new_id} - items.append(new_item) - write_items(items) - return new_item +@router.post("", status_code=status.HTTP_201_CREATED) +def create_item( + payload: ItemCreate, request: Request, response: Response, store: ItemStoreDep +) -> ItemRead: + item = store.create(payload.model_dump()) + response.headers["Location"] = str(request.url_for("get_item", item_id=item["id"])) + return ItemRead.model_validate(item) -@router.put("/items/{item_id}", response_model=ItemResponse) -async def update_item(item_id: int, item: ItemCreate): - items = read_items() - index = next((i for i, v in enumerate(items) if v["id"] == item_id), None) - if index is None: - raise HTTPException(status_code=404, detail="Item not found") - updated_item = {**item.model_dump(), "id": item_id} - items[index] = updated_item - write_items(items) - return updated_item +@router.put("/{item_id}", responses=error_responses(404)) +def replace_item(item_id: int, payload: ItemCreate, store: ItemStoreDep) -> ItemRead: + item = store.replace(item_id, payload.model_dump()) + if item is None: + raise item_not_found() + return ItemRead.model_validate(item) -@router.delete("/items/{item_id}") -async def delete_item(item_id: int): - items = read_items() - new_items = [i for i in items if i["id"] != item_id] - if len(new_items) == len(items): - raise HTTPException(status_code=404, detail="Item not found") - write_items(new_items) - return {"message": "Item deleted successfully"} + +@router.patch("/{item_id}", responses=error_responses(404)) +def update_item(item_id: int, payload: ItemUpdate, store: ItemStoreDep) -> ItemRead: + item = store.update(item_id, payload.model_dump(exclude_unset=True)) + if item is None: + raise item_not_found() + return ItemRead.model_validate(item) + + +@router.delete( + "/{item_id}", + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(404), +) +def delete_item(item_id: int, store: ItemStoreDep) -> None: + if not store.delete(item_id): + raise item_not_found() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/config.py-tpl index a22e29a..ca0f5a5 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/config.py-tpl @@ -1,20 +1,64 @@ # -------------------------------------------------------------------------- # Configuration module # -------------------------------------------------------------------------- +import json import secrets import warnings -from typing import Annotated, Any, Literal, Self +from typing import Annotated, Any, Literal from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator -from pydantic_settings import BaseSettings, SettingsConfigDict +from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict -def parse_cors(v: Any) -> list[str] | str: - if isinstance(v, str) and not v.startswith("["): - return [i.strip() for i in v.split(",")] - elif isinstance(v, (list, str)): - return v - raise ValueError(v) +def parse_cors(value: Any) -> Any: + """Read origins from a comma-separated string or a JSON list. + + Blank entries are dropped, so ``BACKEND_CORS_ORIGINS=`` or a trailing + comma never turns into an empty origin. + """ + if isinstance(value, str): + value = value.strip() + if value.startswith("["): + value = json.loads(value) + else: + value = value.split(",") + if isinstance(value, list): + return [str(origin).strip() for origin in value if str(origin).strip()] + raise ValueError(value) + + +# Each origin is a full URL such as http://localhost:3000, or "*" for any +# origin. "*" never goes together with credentials (cookies, Authorization +# headers): browsers refuse that, so main.py turns credentials off for it. +CorsOrigins = Annotated[ + list[Literal["*"] | AnyUrl], NoDecode, BeforeValidator(parse_cors) +] + +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + "your-secret-key-here", + "change-me-in-production", + "your-mcp-api-key-here", + } +) + +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = 32 + +_GENERATE_KEY_HINT = ( + "Generate one with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) class Settings(BaseSettings): @@ -24,40 +68,63 @@ class Settings(BaseSettings): extra="ignore", ) + PROJECT_NAME: str = "" + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + # The shipped code signs nothing with SECRET_KEY yet, but authentication + # you add later (including the JWT and Session options of fastkit init) + # signs tokens or cookies with it, so treat it as a production secret. + # fastkit writes a unique value to .env; staging and production refuse a + # missing, public or short key (see _check_secret_key below). SECRET_KEY: str = secrets.token_urlsafe(32) - ENVIRONMENT: Literal["development", "production"] = "development" - CLIENT_ORIGIN: str = "" + # Every business router is mounted under this prefix (see src/main.py). + API_V1_PREFIX: str = "/api/v1" - BACKEND_CORS_ORIGINS: Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] = ( - [] - ) + BACKEND_CORS_ORIGINS: CorsOrigins = [] @computed_field # type: ignore[prop-decorator] @property def all_cors_origins(self) -> list[str]: - return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + [ - self.CLIENT_ORIGIN - ] - - PROJECT_NAME: str = "" - - def _check_default_secret(self, var_name: str, value: str | None) -> None: - if value == "changethis": - message = ( - f'The value of {var_name} is "changethis", ' - "for security, please change it, at least for deployments." - ) - if self.ENVIRONMENT == "development": - warnings.warn(message, stacklevel=1) - else: - raise ValueError(message) + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins @model_validator(mode="after") - def _enforce_non_default_secrets(self) -> Self: - self._check_default_secret("SECRET_KEY", self.SECRET_KEY) + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) + return self + env = f"ENVIRONMENT={self.ENVIRONMENT}" + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT + ) + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: + raise ValueError( + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT + ) return self -settings = Settings() # type: ignore +settings = Settings() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/pagination.py-tpl new file mode 100644 index 0000000..2688822 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/pagination.py-tpl @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------- +# Limit/offset pagination shared by every list endpoint. +# +# List endpoints take ``limit: LimitParam = DEFAULT_LIMIT`` and +# ``offset: OffsetParam = 0`` and return a ``Page[T]`` envelope: +# {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range +# values are rejected with a 422 rather than clamped. +# -------------------------------------------------------------------------- +from typing import Annotated, Generic, TypeVar + +from fastapi import Query +from pydantic import BaseModel + +T = TypeVar("T") + +#: Page size used when the client sends no ``limit``. +DEFAULT_LIMIT = 20 +#: Largest page a client may ask for. +MAX_LIMIT = 100 + +LimitParam = Annotated[ + int, Query(ge=1, le=MAX_LIMIT, description="Maximum number of items to return.") +] +OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] + + +class Page(BaseModel, Generic[T]): + """One page of a collection, ordered by primary key. + + ``total`` counts the whole collection, so a client knows there is a next + page while ``offset + len(items) < total``. + """ + + items: list[T] + total: int + limit: int + offset: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/responses.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/responses.py-tpl new file mode 100644 index 0000000..bffc8c1 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/responses.py-tpl @@ -0,0 +1,40 @@ +# -------------------------------------------------------------------------- +# OpenAPI error responses shared by the routers. +# +# FastAPI documents 2xx and 422 on its own. Routes that can also answer 401, +# 404, 409, ... declare it with ``responses=error_responses(404)`` so clients +# see every status code and the ``{"detail": "..."}`` body in the schema. +# -------------------------------------------------------------------------- +from http import HTTPStatus +from typing import Any + +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + """Body FastAPI sends for an ``HTTPException``.""" + + detail: str + + +def error_responses(*status_codes: int) -> dict[int | str, dict[str, Any]]: + """Build ``responses=`` entries that document the given error codes. + + A 401 entry also documents the ``WWW-Authenticate`` header every 401 + response carries. + """ + responses: dict[int | str, dict[str, Any]] = {} + for code in status_codes: + entry: dict[str, Any] = { + "model": ErrorDetail, + "description": HTTPStatus(code).phrase, + } + if code == HTTPStatus.UNAUTHORIZED: + entry["headers"] = { + "WWW-Authenticate": { + "description": "Authentication scheme to use (Bearer).", + "schema": {"type": "string"}, + } + } + responses[code] = entry + return responses diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/crud/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/crud/items.py-tpl index 8660157..d11a046 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/crud/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/crud/items.py-tpl @@ -1,14 +1,130 @@ +# -------------------------------------------------------------------------- +# Item CRUD method module +# +# Items live in a JSON file. The route handlers are plain ``def`` functions, +# so FastAPI runs them in a thread pool; every file access holds a lock so +# two concurrent requests can neither hand out the same id nor lose a write. +# +# The file keeps the next id next to the items, so an id is never handed out +# twice: not after the item with the highest id is deleted, and not after a +# restart. Every write goes to a temporary file that then replaces the data +# file in one step, so a crash mid-write leaves the previous file intact. +# The lock covers one process only; with several workers, use a database. +# -------------------------------------------------------------------------- +import contextlib import json import os +import tempfile +import threading +from collections.abc import Callable +from pathlib import Path +from typing import Any -MOCK_FILE = os.path.join(os.path.dirname(__file__), "../mocks/mock_items.json") +MOCK_FILE = Path(__file__).resolve().parent.parent / "mocks" / "mock_items.json" +ItemData = dict[str, Any] -def read_items(): - with open(MOCK_FILE, "r") as file: - return json.load(file) +def _parse(data: Any) -> tuple[list[ItemData], int]: + """Return the stored items ordered by id and the next id to hand out. -def write_items(items: list[dict]): - with open(MOCK_FILE, "w") as file: - json.dump(items, file, indent=2) + Older data files, like the shipped mock data, are a plain list of items; + for those the next id continues after the highest id in the file. + """ + if isinstance(data, list): + items: list[ItemData] = data + next_id = 1 + else: + items = data["items"] + next_id = int(data.get("next_id", 1)) + items = sorted(items, key=lambda item: item["id"]) + highest = max((item["id"] for item in items), default=0) + return items, max(next_id, highest + 1) + + +def _dump(items: list[ItemData], next_id: int) -> str: + return json.dumps({"next_id": next_id, "items": items}, indent=2) + "\n" + + +def _write_atomic(path: Path, text: str) -> None: + """Replace ``path`` with ``text``; readers see the old or the new file.""" + fd, temp_name = tempfile.mkstemp( + dir=path.parent, prefix=f".{path.name}.", suffix=".tmp" + ) + try: + with os.fdopen(fd, "w", encoding="utf-8") as file: + file.write(text) + file.flush() + os.fsync(file.fileno()) + # The temporary file is closed before the rename, as Windows requires. + os.replace(temp_name, path) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(temp_name) + raise + + +class ItemStore: + """Item persistence backed by one JSON file.""" + + def __init__(self, path: Path) -> None: + self.path = path + self._lock = threading.Lock() + + def _load(self) -> tuple[list[ItemData], int]: + with self.path.open(encoding="utf-8") as file: + return _parse(json.load(file)) + + def _save(self, items: list[ItemData], next_id: int) -> None: + _write_atomic(self.path, _dump(items, next_id)) + + def list_page(self, offset: int, limit: int) -> tuple[list[ItemData], int]: + """Return one page of items ordered by id, plus the total count.""" + with self._lock: + items, _ = self._load() + return items[offset : offset + limit], len(items) + + def get(self, item_id: int) -> ItemData | None: + with self._lock: + items, _ = self._load() + return next((item for item in items if item["id"] == item_id), None) + + def create(self, data: ItemData) -> ItemData: + with self._lock: + items, next_id = self._load() + item = {**data, "id": next_id} + items.append(item) + self._save(items, next_id + 1) + return item + + def replace(self, item_id: int, data: ItemData) -> ItemData | None: + return self._modify(item_id, lambda current: {**data, "id": item_id}) + + def update(self, item_id: int, changes: ItemData) -> ItemData | None: + return self._modify( + item_id, lambda current: {**current, **changes, "id": item_id} + ) + + def delete(self, item_id: int) -> bool: + with self._lock: + items, next_id = self._load() + remaining = [item for item in items if item["id"] != item_id] + if len(remaining) == len(items): + return False + self._save(remaining, next_id) + return True + + def _modify( + self, item_id: int, change: Callable[[ItemData], ItemData] + ) -> ItemData | None: + with self._lock: + items, next_id = self._load() + for index, current in enumerate(items): + if current["id"] == item_id: + items[index] = change(current) + self._save(items, next_id) + return items[index] + return None + + +item_store = ItemStore(MOCK_FILE) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/main.py-tpl index 28449fc..e9aa39f 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/main.py-tpl @@ -14,21 +14,24 @@ app = FastAPI( title=settings.PROJECT_NAME, ) +# Origins come only from BACKEND_CORS_ORIGINS; with none configured the +# middleware is not installed at all. if settings.all_cors_origins: app.add_middleware( CORSMiddleware, allow_origins=settings.all_cors_origins, - allow_credentials=True, + # Browsers refuse credentials with the "*" wildcard; never send both. + allow_credentials="*" not in settings.all_cors_origins, allow_methods=["*"], allow_headers=["*"], ) # fastkit:routes -app.include_router(api_router) +app.include_router(api_router, prefix=settings.API_V1_PREFIX) -@app.get("/health") +@app.get("/health", tags=["health"]) async def health_check() -> dict[str, str]: - """Health check endpoint.""" - return {"status": "healthy"} + """Liveness probe: no authentication and no I/O.""" + return {"status": "ok"} diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/schemas/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/schemas/items.py-tpl index 791b84d..13cc7fb 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/schemas/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/schemas/items.py-tpl @@ -1,18 +1,41 @@ - -from pydantic import BaseModel, ConfigDict +# -------------------------------------------------------------------------- +# Item schema module +# -------------------------------------------------------------------------- +from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator class ItemBase(BaseModel): - name: str - description: str | None = None - price: float - category: str + name: str = Field(min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=1000) + price: float = Field(ge=0) + category: str = Field(min_length=1, max_length=50) class ItemCreate(ItemBase): - pass + """POST and PUT body: every required field must be sent.""" -class ItemResponse(ItemBase): - id: int +class ItemUpdate(BaseModel): + """PATCH body: send only the fields to change. + + ``description`` can be cleared with an explicit ``null``; the other + fields are required on an item, so ``null`` is rejected for them. + """ + + name: str | None = Field(default=None, min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=1000) + price: float | None = Field(default=None, ge=0) + category: str | None = Field(default=None, min_length=1, max_length=50) + + @field_validator("name", "price", "category") + @classmethod + def _reject_null(cls, value: object, info: ValidationInfo) -> object: + if value is None: + raise ValueError(f"{info.field_name} must not be null") + return value + + +class ItemRead(ItemBase): model_config = ConfigDict(from_attributes=True) + + id: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/conftest.py-tpl index 81223ae..f3a01a4 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/conftest.py-tpl @@ -2,28 +2,36 @@ # pytest runtime configuration module # -------------------------------------------------------------------------- import json -import os from collections.abc import Generator +from pathlib import Path import pytest from fastapi.testclient import TestClient + +from src.api.deps import get_item_store +from src.core.config import settings +from src.crud.items import ItemStore from src.main import app -MOCK_FILE = os.path.join(os.path.dirname(__file__), "../src/mocks/mock_items.json") +ITEMS_URL = f"{settings.API_V1_PREFIX}/items" + +SEED_ITEMS = [ + {"id": 1, "name": "Test Item 1", "price": 10.5, "category": "test"}, + {"id": 2, "name": "Test Item 2", "price": 20.0, "category": "test"}, +] -@pytest.fixture(autouse=True) -def reset_mock_data(): - initial_data = [ - {"id": 1, "name": "Test Item 1", "price": 10.5, "category": "test"}, - {"id": 2, "name": "Test Item 2", "price": 20.0, "category": "test"}, - ] - with open(MOCK_FILE, "w") as file: - json.dump(initial_data, file) - yield +@pytest.fixture +def store(tmp_path: Path) -> ItemStore: + """Item store on a temporary file, so tests never touch src/mocks.""" + path = tmp_path / "items.json" + path.write_text(json.dumps(SEED_ITEMS), encoding="utf-8") + return ItemStore(path) -@pytest.fixture(scope="module") -def client() -> Generator[TestClient, None, None]: +@pytest.fixture +def client(store: ItemStore) -> Generator[TestClient, None, None]: + app.dependency_overrides[get_item_store] = lambda: store with TestClient(app) as c: yield c + app.dependency_overrides.clear() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_config.py-tpl new file mode 100644 index 0000000..38f107b --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_config.py-tpl @@ -0,0 +1,194 @@ +# -------------------------------------------------------------------------- +# Settings validation: the SECRET_KEY rule, ENVIRONMENT values, +# environment variable names and the CORS wildcard. +# -------------------------------------------------------------------------- +import json +import os +import secrets +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest +from pydantic import ValidationError + +from src.core.config import KNOWN_EXAMPLE_SECRET_KEYS, MIN_SECRET_KEY_BYTES, Settings + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +APP_MODULE = "src.main" +#: Settings without a default; none in this template. +REQUIRED: dict[str, Any] = {} + +STRONG_KEY = "k" * MIN_SECRET_KEY_BYTES +#: Every environment except development refuses a missing, public or short +#: SECRET_KEY. +STRICT_ENVIRONMENTS = ["staging", "production"] + + +@pytest.fixture(autouse=True) +def _isolated_settings_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Shell variables, in any spelling, must not leak into Settings().""" + for name in list(os.environ): + if name.upper() in {"ENVIRONMENT", "SECRET_KEY", "BACKEND_CORS_ORIGINS"}: + monkeypatch.delenv(name) + + +def make_settings(env_file: Path | None = None, **values: Any) -> Settings: + """Settings from explicit values; a developer's .env is never read.""" + return Settings(_env_file=env_file, **{**REQUIRED, **values}) # type: ignore[call-arg] + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_require_an_explicit_secret_key(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"must be set explicitly when ENVIRONMENT={environment}" + ): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_refuse_a_short_secret_key(environment: str) -> None: + short_key = "k" * (MIN_SECRET_KEY_BYTES - 1) + + with pytest.raises(ValidationError, match=f"at least {MIN_SECRET_KEY_BYTES} bytes"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=short_key) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +@pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) +def test_strict_environments_refuse_every_public_example_key( + environment: str, example_key: str +) -> None: + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=f" {example_key} ") + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environment_errors_say_how_to_generate_a_key(environment: str) -> None: + with pytest.raises(ValidationError, match="token_urlsafe"): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_an_explicit_strong_key(environment: str) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + + assert settings.ENVIRONMENT == environment + assert settings.SECRET_KEY == STRONG_KEY + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_the_key_fastkit_writes_to_env( + tmp_path: Path, environment: str +) -> None: + env_file = tmp_path / ".env" + env_file.write_text( + f"ENVIRONMENT={environment}\nSECRET_KEY={secrets.token_urlsafe(32)}\n", + encoding="utf-8", + ) + + assert make_settings(env_file).ENVIRONMENT == environment + + +def test_development_without_a_key_uses_a_random_one() -> None: + settings = make_settings(ENVIRONMENT="development") + + assert len(settings.SECRET_KEY.encode()) >= MIN_SECRET_KEY_BYTES + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_development_only_warns_about_an_example_key() -> None: + example_key = sorted(KNOWN_EXAMPLE_SECRET_KEYS)[0] + + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings(ENVIRONMENT="development", SECRET_KEY=example_key) + + assert settings.SECRET_KEY == example_key + + +@pytest.mark.parametrize("value", ["Production", "PRODUCTION", " production", "prod"]) +def test_unknown_environment_values_fail_closed(value: str) -> None: + with pytest.raises(ValidationError, match="ENVIRONMENT"): + make_settings(ENVIRONMENT=value, SECRET_KEY=STRONG_KEY) + + +def test_environment_variable_names_are_case_insensitive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("environment", "production") + + with pytest.raises(ValidationError, match="must be set explicitly"): + make_settings() + + monkeypatch.setenv("secret_key", STRONG_KEY) + + assert make_settings().ENVIRONMENT == "production" + + +@pytest.mark.parametrize("raw", ["*", " * ", '["*"]', "*,http://localhost:3000"]) +def test_cors_wildcard_is_accepted(monkeypatch: pytest.MonkeyPatch, raw: str) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + + assert make_settings().all_cors_origins == ["*"] + + +def test_cors_origins_must_be_urls_or_the_wildcard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + + with pytest.raises(ValidationError): + make_settings() + + +#: Runs in a fresh interpreter: the app reads its settings at import time. +_PREFLIGHT = f""" +import json +from fastapi.testclient import TestClient +from {APP_MODULE} import app + +headers = {{ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "GET", +}} +response = TestClient(app).options("/", headers=headers) +allowed = {{ + k: v for k, v in response.headers.items() if k.startswith("access-control-allow-") +}} +print(json.dumps(allowed)) +""" + + +@pytest.mark.parametrize( + ("origins", "allow_origin", "allow_credentials"), + [ + ("*", "*", None), + ("http://localhost:3000", "http://localhost:3000", "true"), + ], +) +def test_cors_wildcard_is_never_combined_with_credentials( + origins: str, allow_origin: str, allow_credentials: str | None +) -> None: + env = { + **os.environ, + **{name: str(value) for name, value in REQUIRED.items()}, + "BACKEND_CORS_ORIGINS": origins, + "ENVIRONMENT": "development", + } + result = subprocess.run( + [sys.executable, "-c", _PREFLIGHT], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + check=False, + ) + + assert result.returncode == 0, result.stderr + headers = json.loads(result.stdout.strip().splitlines()[-1]) + assert headers["access-control-allow-origin"] == allow_origin + assert headers.get("access-control-allow-credentials") == allow_credentials diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_item_store.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_item_store.py-tpl new file mode 100644 index 0000000..f9c1e09 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_item_store.py-tpl @@ -0,0 +1,81 @@ +# -------------------------------------------------------------------------- +# Item store persistence testcases +# -------------------------------------------------------------------------- +import json +from pathlib import Path +from typing import Any + +import pytest + +from src.crud.items import ItemStore + +NEW_ITEM = {"name": "New Item", "price": 30.0, "category": "new"} + + +def make_store(tmp_path: Path, data: Any) -> ItemStore: + path = tmp_path / "items.json" + path.write_text(json.dumps(data), encoding="utf-8") + return ItemStore(path) + + +def seed(*ids: int) -> list[dict[str, Any]]: + return [{**NEW_ITEM, "id": item_id} for item_id in ids] + + +def test_deleted_id_is_not_reused(tmp_path: Path) -> None: + store = make_store(tmp_path, seed(1, 2)) + + first = store.create(dict(NEW_ITEM)) + assert store.delete(first["id"]) + second = store.create(dict(NEW_ITEM)) + + assert first["id"] == 3 + assert second["id"] == 4 + + +def test_restart_does_not_reuse_the_deleted_highest_id(tmp_path: Path) -> None: + store = make_store(tmp_path, seed(1, 2)) + created = store.create(dict(NEW_ITEM)) + assert store.delete(created["id"]) + + restarted = ItemStore(store.path) + after_restart = restarted.create(dict(NEW_ITEM)) + + assert after_restart["id"] == created["id"] + 1 + saved = json.loads(store.path.read_text(encoding="utf-8")) + assert saved["next_id"] == after_restart["id"] + 1 + + +def test_old_list_format_file_still_loads(tmp_path: Path) -> None: + store = make_store(tmp_path, seed(5, 2)) + + items, total = store.list_page(offset=0, limit=10) + + assert [item["id"] for item in items] == [2, 5] + assert total == 2 + assert store.get(5) is not None + assert store.create(dict(NEW_ITEM))["id"] == 6 + + +def test_next_id_never_goes_below_the_highest_stored_id(tmp_path: Path) -> None: + store = make_store(tmp_path, {"next_id": 2, "items": seed(1, 7)}) + + assert store.create(dict(NEW_ITEM))["id"] == 8 + + +def test_failed_write_keeps_the_file_and_leaves_no_temp_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + store = make_store(tmp_path, seed(1, 2)) + before = store.path.read_bytes() + + def fail_replace(*args: Any, **kwargs: Any) -> None: + raise OSError("simulated crash while replacing the file") + + monkeypatch.setattr("src.crud.items.os.replace", fail_replace) + + with pytest.raises(OSError, match="simulated crash"): + store.create(dict(NEW_ITEM)) + + assert store.path.read_bytes() == before + assert list(tmp_path.iterdir()) == [store.path] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_items.py-tpl index b194928..fae32e1 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_items.py-tpl @@ -1,42 +1,192 @@ # -------------------------------------------------------------------------- # Item endpoint testcases # -------------------------------------------------------------------------- +from concurrent.futures import ThreadPoolExecutor +import pytest +from fastapi.testclient import TestClient +from src.crud.items import MOCK_FILE, ItemStore +from tests.conftest import ITEMS_URL + +NEW_ITEM = {"name": "New Item", "price": 30.0, "category": "new"} + + +def test_list_items_returns_a_page(client: TestClient) -> None: + response = client.get(ITEMS_URL) + + assert response.status_code == 200 + body = response.json() + assert set(body) == {"items", "total", "limit", "offset"} + assert body["total"] == 2 + assert body["limit"] == 20 + assert body["offset"] == 0 + assert [item["id"] for item in body["items"]] == [1, 2] + + +def test_list_items_limit_and_offset(client: TestClient) -> None: + response = client.get(ITEMS_URL, params={"limit": 1, "offset": 1}) + + assert response.status_code == 200 + body = response.json() + assert [item["name"] for item in body["items"]] == ["Test Item 2"] + assert body["total"] == 2 + assert body["limit"] == 1 + assert body["offset"] == 1 + + +def test_list_items_offset_past_the_end(client: TestClient) -> None: + body = client.get(ITEMS_URL, params={"offset": 10}).json() + + assert body["items"] == [] + assert body["total"] == 2 + + +@pytest.mark.parametrize( + "params", [{"limit": 0}, {"limit": 101}, {"offset": -1}, {"limit": "x"}] +) +def test_list_items_rejects_out_of_range_pagination( + client: TestClient, params: dict[str, object] +) -> None: + assert client.get(ITEMS_URL, params=params).status_code == 422 + + +def test_collection_is_served_without_redirect(client: TestClient) -> None: + response = client.get(ITEMS_URL, follow_redirects=False) -def test_read_all_items(client): - response = client.get("/items") assert response.status_code == 200 - assert len(response.json()) == 2 -def test_read_item_success(client): - response = client.get("/items/1") +def test_get_item(client: TestClient) -> None: + response = client.get(f"{ITEMS_URL}/1") + assert response.status_code == 200 assert response.json()["name"] == "Test Item 1" -def test_read_item_not_found(client): - response = client.get("/items/999") +def test_get_item_not_found(client: TestClient) -> None: + response = client.get(f"{ITEMS_URL}/999") + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} -def test_create_item(client): - new_item = {"name": "New Item", "price": 30.0, "category": "new"} - response = client.post("/items", json=new_item) +def test_create_item_returns_201_and_location(client: TestClient) -> None: + response = client.post(ITEMS_URL, json=NEW_ITEM) + assert response.status_code == 201 - assert response.json()["id"] == 3 + created = response.json() + assert created["id"] not in (1, 2) + assert created["name"] == "New Item" + location = response.headers["location"] + assert location.endswith(f"{ITEMS_URL}/{created['id']}") + assert client.get(location).json() == created + + +@pytest.mark.parametrize( + "payload", + [ + {**NEW_ITEM, "name": ""}, + {**NEW_ITEM, "price": -1}, + {"name": "No price", "category": "new"}, + ], +) +def test_create_item_validates_input( + client: TestClient, payload: dict[str, object] +) -> None: + assert client.post(ITEMS_URL, json=payload).status_code == 422 + + +def test_put_replaces_the_whole_item(client: TestClient) -> None: + client.patch(f"{ITEMS_URL}/1", json={"description": "will be dropped"}) + + response = client.put( + f"{ITEMS_URL}/1", json={"name": "Replaced", "price": 1.0, "category": "x"} + ) + + assert response.status_code == 200 + assert response.json() == { + "id": 1, + "name": "Replaced", + "description": None, + "price": 1.0, + "category": "x", + } + + +def test_put_requires_every_field(client: TestClient) -> None: + response = client.put(f"{ITEMS_URL}/1", json={"name": "Only a name"}) + assert response.status_code == 422 + + +def test_put_not_found(client: TestClient) -> None: + response = client.put(f"{ITEMS_URL}/999", json=NEW_ITEM) + + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +def test_patch_changes_only_the_sent_fields(client: TestClient) -> None: + response = client.patch(f"{ITEMS_URL}/1", json={"price": 99.0}) -def test_update_item(client): - updated_data = {"name": "Updated Item", "price": 15.0, "category": "updated"} - response = client.put("/items/1", json=updated_data) assert response.status_code == 200 - assert response.json()["name"] == "Updated Item" + body = response.json() + assert body["price"] == 99.0 + assert body["name"] == "Test Item 1" + assert body["category"] == "test" + +def test_patch_can_clear_a_nullable_field(client: TestClient) -> None: + client.patch(f"{ITEMS_URL}/1", json={"description": "temporary"}) + + response = client.patch(f"{ITEMS_URL}/1", json={"description": None}) -def test_delete_item(client): - response = client.delete("/items/1") assert response.status_code == 200 - response = client.get("/items/1") + assert response.json()["description"] is None + + +def test_patch_rejects_null_for_required_fields(client: TestClient) -> None: + response = client.patch(f"{ITEMS_URL}/1", json={"name": None}) + + assert response.status_code == 422 + assert client.get(f"{ITEMS_URL}/1").json()["name"] == "Test Item 1" + + +def test_patch_not_found(client: TestClient) -> None: + response = client.patch(f"{ITEMS_URL}/999", json={"price": 1.0}) + assert response.status_code == 404 + + +def test_delete_item_returns_204(client: TestClient) -> None: + response = client.delete(f"{ITEMS_URL}/1") + + assert response.status_code == 204 + assert response.content == b"" + assert client.get(f"{ITEMS_URL}/1").status_code == 404 + + +def test_delete_item_not_found(client: TestClient) -> None: + response = client.delete(f"{ITEMS_URL}/999") + + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +def test_tests_do_not_modify_the_shipped_mock_file(client: TestClient) -> None: + before = MOCK_FILE.read_bytes() + + client.post(ITEMS_URL, json=NEW_ITEM) + client.delete(f"{ITEMS_URL}/1") + + assert MOCK_FILE.read_bytes() == before + + +def test_concurrent_creates_get_unique_ids(store: ItemStore) -> None: + with ThreadPoolExecutor(max_workers=8) as pool: + created = list(pool.map(lambda _: store.create(dict(NEW_ITEM)), range(20))) + + ids = [item["id"] for item in created] + assert len(set(ids)) == 20 + assert store.list_page(offset=0, limit=100)[1] == 22 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_main.py-tpl new file mode 100644 index 0000000..f56c078 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_main.py-tpl @@ -0,0 +1,59 @@ +# -------------------------------------------------------------------------- +# Application-level testcases (health, OpenAPI, settings) +# -------------------------------------------------------------------------- +import pytest +from fastapi.testclient import TestClient + +from src.core.config import Settings +from tests.conftest import ITEMS_URL + + +def test_health(client: TestClient) -> None: + response = client.get("/health") + + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + +def test_openapi_documents_routes_tags_and_errors(client: TestClient) -> None: + schema = client.get("/openapi.json").json() + paths = schema["paths"] + + assert "/health" in paths + assert set(paths[ITEMS_URL]) == {"get", "post"} + assert set(paths[f"{ITEMS_URL}/{{item_id}}"]) == {"get", "put", "patch", "delete"} + item_routes = paths[f"{ITEMS_URL}/{{item_id}}"] + for operation in item_routes.values(): + assert operation["tags"] == ["items"] + assert "404" in operation["responses"] + assert "201" in paths[ITEMS_URL]["post"]["responses"] + assert "204" in item_routes["delete"]["responses"] + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ( + "http://localhost:3000, ,https://example.com/", + ["http://localhost:3000", "https://example.com"], + ), + ('["http://localhost:3000", ""]', ["http://localhost:3000"]), + ("", []), + ], +) +def test_cors_origins_never_contain_an_empty_origin( + monkeypatch: pytest.MonkeyPatch, raw: str, expected: list[str] +) -> None: + # _env_file=None: a developer's .env must not change the result. + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + settings = Settings(_env_file=None) # type: ignore[call-arg] + + assert settings.all_cors_origins == expected + + +def test_business_routes_default_to_the_v1_prefix( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("API_V1_PREFIX", raising=False) + + assert Settings(_env_file=None).API_V1_PREFIX == "/api/v1" # type: ignore[call-arg] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.env.example-tpl index 665cebd..9b40d25 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.env.example-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/.env.example-tpl @@ -1,2 +1,11 @@ +# .env.example keeps a public placeholder; fastkit writes a unique key to the +# local, git-ignored .env. With any ENVIRONMENT other than development +# (staging or production) the app refuses to start when SECRET_KEY is unset, +# a public example value or shorter than 32 bytes. SECRET_KEY=changethis +# One of: development, staging, production. ENVIRONMENT=development + +# Allowed browser origins, comma-separated or a JSON list. "*" allows any +# origin, but then without credentials (cookies, Authorization headers): +# BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl index c25120f..cc1bcfa 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl @@ -17,8 +17,8 @@ Pick this template when you want: layer can evolve independently. - A **`pyproject.toml`-first** project (PEP 621) compatible with `uv`, `pdm`, or `poetry` out of the box — no `setup.py` to maintain. -- Sensible defaults for settings, testing, formatting, and a built-in - `/health` probe. +- Sensible defaults for settings, testing, formatting, a built-in + `/health` probe, and paginated list endpoints. If you only need a quick CRUD demo, start with `fastapi-default`. If you need PostgreSQL, start with `fastapi-psql-orm`. If you want a single-file @@ -42,12 +42,14 @@ sandbox, use `fastapi-single-module`. │ └── app/ │ ├── main.py # FastAPI app entry point │ ├── core/ -│ │ └── config.py # pydantic-settings configuration +│ │ ├── config.py # pydantic-settings configuration +│ │ ├── pagination.py # Page[T] envelope + limit/offset params +│ │ └── responses.py # OpenAPI error-response helper │ ├── db/ │ │ └── memory.py # in-memory store stand-in for a real DB │ ├── api/ -│ │ ├── router.py # aggregates health + every domain router -│ │ └── health.py # GET /health +│ │ ├── router.py # aggregates every domain router (/api/v1) +│ │ └── health.py # GET /health (application root) │ └── domains/ │ └── items/ # example domain (CRUD over an item entity) │ ├── models.py # entity dataclass @@ -58,16 +60,23 @@ sandbox, use `fastapi-single-module`. └── tests/ ├── conftest.py ├── test_health.py - └── test_items.py + ├── test_items.py + └── test_pagination.py ``` -The recipe for adding a new domain is: +The recipe for adding a new domain is (`fastkit addroute ` does +steps 1-3 for you): 1. Create `src/app/domains//`. 2. Mirror the `items` layout (`models.py`, `schemas.py`, `repository.py`, - `service.py`, `router.py`). -3. Register the router in `src/app/api/router.py`. -4. Add tests under `tests/test_.py`. + `service.py`, `router.py`). The router carries only its resource prefix + (`APIRouter(prefix="/orders", tags=["orders"])`); list endpoints return + `Page[...]` from `src/app/core/pagination.py`. +3. Register the router in `src/app/api/router.py`, which `main.py` mounts + under `settings.API_V1_PREFIX` (`/api/v1`). +4. Add tests under `tests/test_.py`. Give the domain's + `service.py` a `reset_store()` function and `tests/conftest.py` empties + its store before and after every test. ## Running the app @@ -92,14 +101,19 @@ API docs are then served at: ## API endpoints -| Method | Endpoint | Description | -|--------|---------------------------|------------------------------| -| GET | `/api/v1/health` | Liveness probe | -| GET | `/api/v1/items` | List items | -| GET | `/api/v1/items/{item_id}` | Read a single item | -| POST | `/api/v1/items` | Create an item | -| PUT | `/api/v1/items/{item_id}` | Replace an item | -| DELETE | `/api/v1/items/{item_id}` | Delete an item | +| Method | Endpoint | Description | +|--------|---------------------------|-----------------------------------------------| +| GET | `/health` | Liveness probe, returns `{"status": "ok"}` | +| GET | `/api/v1/items` | List items (`?limit=1..100&offset=0`), paged | +| GET | `/api/v1/items/{item_id}` | Read a single item (404 if missing) | +| POST | `/api/v1/items` | Create an item (201 + `Location` header) | +| PUT | `/api/v1/items/{item_id}` | Replace an item (full body required) | +| PATCH | `/api/v1/items/{item_id}` | Update only the fields sent | +| DELETE | `/api/v1/items/{item_id}` | Delete an item (204, no body) | + +List endpoints answer with one envelope: +`{"items": [...], "total": 42, "limit": 20, "offset": 0}`, ordered by id. +Errors use FastAPI's `{"detail": "..."}` body, e.g. `{"detail": "Item not found"}`. ## Running tests @@ -114,9 +128,17 @@ $ pytest `src/app/core/config.py` reads settings from environment variables (or a local `.env` file). fastkit generated `.env` from `.env.example` with a unique `SECRET_KEY`. `.env` is git-ignored and stays on your machine; commit -`.env.example` and keep only placeholder values in it. With -`ENVIRONMENT=production` the app refuses to start while `SECRET_KEY` is still -an example value such as `changethis`. +`.env.example` and keep only placeholder values in it. With any +`ENVIRONMENT` other than `development` (`staging`, `production`) the app +refuses to start when `SECRET_KEY` is unset, a public example value such as +`changethis` or shorter than 32 bytes. The +shipped code signs nothing with the key yet, but authentication you add later +(including the JWT and Session options of `fastkit init`) signs tokens or +cookies with it. + +`BACKEND_CORS_ORIGINS` takes comma-separated origins or a JSON list. `*` allows +any origin, but then the app sends no credentials (cookies, `Authorization` +headers), because browsers refuse that combination. ## Project Origin diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/pyproject.toml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/pyproject.toml-tpl index 8eb32ce..b857be6 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/pyproject.toml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/pyproject.toml-tpl @@ -67,3 +67,8 @@ python_files = ["test_*.py"] python_classes = ["Test*"] python_functions = ["test_*"] addopts = "-v --tb=short" +filterwarnings = [ + # starlette's TestClient now prefers `httpx2`; this project pins httpx, so only + # that advisory notice (a UserWarning subclass) is silenced. + "ignore:Using `httpx` with `starlette.testclient` is deprecated:starlette.exceptions.StarletteDeprecationWarning", +] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/requirements.txt-tpl index 02fe659..4b4a7bf 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/requirements.txt-tpl @@ -1,6 +1,6 @@ annotated-doc==0.0.5 annotated-types==0.8.0 -anyio==4.15.0 +anyio==4.16.0 ast-serialize==0.9.0 black==26.10.1 certifi==2026.10.23 @@ -28,7 +28,7 @@ pytest==9.1.1 python-dotenv==1.2.3 pytokens==0.4.1 PyYAML==6.0.3 -starlette==1.6.0 +starlette==1.10.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/api/health.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/api/health.py-tpl index e6616cf..85779aa 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/api/health.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/api/health.py-tpl @@ -1,5 +1,8 @@ # -------------------------------------------------------------------------- # Health endpoint — small, side-effect-free probe for liveness checks. +# +# Mounted at the application root (``GET /health``), outside the versioned +# API prefix, so probes keep working across API versions. # -------------------------------------------------------------------------- from fastapi import APIRouter diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/api/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/api/router.py-tpl index 37ef8bb..094d534 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/api/router.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/api/router.py-tpl @@ -1,15 +1,15 @@ # -------------------------------------------------------------------------- -# Top-level API router — aggregates the health probe with every domain -# module under ``src/app/domains/``. +# Top-level API router — aggregates every domain module under +# ``src/app/domains/``. ``src/app/main.py`` mounts it under +# ``settings.API_V1_PREFIX``; each domain router carries only its resource +# prefix (``/items``). # -------------------------------------------------------------------------- from fastapi import APIRouter -from src.app.api import health from src.app.domains.items import router as items_router # fastkit:imports api_router = APIRouter() -api_router.include_router(health.router) -api_router.include_router(items_router.router, prefix="/items", tags=["items"]) +api_router.include_router(items_router.router) # fastkit:routes diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/config.py-tpl index a88f1ce..4d47046 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/config.py-tpl @@ -2,6 +2,7 @@ # Application settings (pydantic-settings). # -------------------------------------------------------------------------- import secrets +import warnings from typing import Annotated, Any, Literal from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator @@ -16,17 +17,32 @@ def _parse_cors(v: Any) -> list[str] | str: raise ValueError(v) -#: Example SECRET_KEY values fastkit templates have shipped in ``.env`` -#: files. They are public, so a production deployment must never sign -#: anything with one of them. +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. KNOWN_EXAMPLE_SECRET_KEYS = frozenset( { "changethis", "changethis-please-generate-a-real-32-byte-key", "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + "your-secret-key-here", + "change-me-in-production", + "your-mcp-api-key-here", } ) +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = 32 + +_GENERATE_KEY_HINT = ( + "Generate one with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) + class Settings(BaseSettings): """Centralized configuration for the application. @@ -44,35 +60,65 @@ class Settings(BaseSettings): PROJECT_NAME: str = "" ENVIRONMENT: Literal["development", "staging", "production"] = "development" - # Not read by the shipped code; reserved for signing features you add. - # fastkit writes a unique value to .env, and production refuses the - # public example values (see the validator below). + # The shipped code signs nothing with SECRET_KEY yet, but authentication + # you add later (including the JWT and Session options of fastkit init) + # signs tokens or cookies with it, so treat it as a production secret. + # fastkit writes a unique value to .env; staging and production refuse a + # missing, public or short key (see _check_secret_key below). SECRET_KEY: str = secrets.token_urlsafe(32) API_V1_PREFIX: str = "/api/v1" + # Comma-separated list or JSON list. Each origin is a full URL such as + # http://localhost:3000, or "*" for any origin; "*" never goes together + # with credentials (browsers refuse that), so main.py turns them off. BACKEND_CORS_ORIGINS: Annotated[ - list[AnyUrl] | str, BeforeValidator(_parse_cors) + list[Literal["*"] | AnyUrl] | str, BeforeValidator(_parse_cors) ] = [] @computed_field # type: ignore[prop-decorator] @property def all_cors_origins(self) -> list[str]: - return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins @model_validator(mode="after") - def _reject_example_secret_key_in_production(self) -> "Settings": - if ( - self.ENVIRONMENT == "production" - and self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS - ): + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) + return self + env = f"ENVIRONMENT={self.ENVIRONMENT}" + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT + ) + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: raise ValueError( - "SECRET_KEY is set to a public example value while " - "ENVIRONMENT=production. Generate a real key with " - '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' - "and set it as the SECRET_KEY environment variable (or in .env)." + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT ) return self -settings = Settings() # type: ignore[call-arg] +settings = Settings() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/pagination.py-tpl new file mode 100644 index 0000000..2688822 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/pagination.py-tpl @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------- +# Limit/offset pagination shared by every list endpoint. +# +# List endpoints take ``limit: LimitParam = DEFAULT_LIMIT`` and +# ``offset: OffsetParam = 0`` and return a ``Page[T]`` envelope: +# {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range +# values are rejected with a 422 rather than clamped. +# -------------------------------------------------------------------------- +from typing import Annotated, Generic, TypeVar + +from fastapi import Query +from pydantic import BaseModel + +T = TypeVar("T") + +#: Page size used when the client sends no ``limit``. +DEFAULT_LIMIT = 20 +#: Largest page a client may ask for. +MAX_LIMIT = 100 + +LimitParam = Annotated[ + int, Query(ge=1, le=MAX_LIMIT, description="Maximum number of items to return.") +] +OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] + + +class Page(BaseModel, Generic[T]): + """One page of a collection, ordered by primary key. + + ``total`` counts the whole collection, so a client knows there is a next + page while ``offset + len(items) < total``. + """ + + items: list[T] + total: int + limit: int + offset: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/responses.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/responses.py-tpl new file mode 100644 index 0000000..bffc8c1 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/core/responses.py-tpl @@ -0,0 +1,40 @@ +# -------------------------------------------------------------------------- +# OpenAPI error responses shared by the routers. +# +# FastAPI documents 2xx and 422 on its own. Routes that can also answer 401, +# 404, 409, ... declare it with ``responses=error_responses(404)`` so clients +# see every status code and the ``{"detail": "..."}`` body in the schema. +# -------------------------------------------------------------------------- +from http import HTTPStatus +from typing import Any + +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + """Body FastAPI sends for an ``HTTPException``.""" + + detail: str + + +def error_responses(*status_codes: int) -> dict[int | str, dict[str, Any]]: + """Build ``responses=`` entries that document the given error codes. + + A 401 entry also documents the ``WWW-Authenticate`` header every 401 + response carries. + """ + responses: dict[int | str, dict[str, Any]] = {} + for code in status_codes: + entry: dict[str, Any] = { + "model": ErrorDetail, + "description": HTTPStatus(code).phrase, + } + if code == HTTPStatus.UNAUTHORIZED: + entry["headers"] = { + "WWW-Authenticate": { + "description": "Authentication scheme to use (Bearer).", + "schema": {"type": "string"}, + } + } + responses[code] = entry + return responses diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/db/memory.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/db/memory.py-tpl index d43aa0e..57277eb 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/db/memory.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/db/memory.py-tpl @@ -5,7 +5,8 @@ # SQLAlchemy / async drivers later is a contained change — only the # repositories need to be rewritten. # -------------------------------------------------------------------------- -from collections.abc import Iterable +from collections.abc import Callable +from threading import Lock from typing import Generic, TypeVar T = TypeVar("T") @@ -14,36 +15,55 @@ T = TypeVar("T") class InMemoryStore(Generic[T]): """Tiny ID-keyed collection backed by a dict. - Not thread-safe and not suitable for production — but lets the rest of - the application code stay realistic (repository / service / router) while - keeping the starter self-contained. + Sync route handlers run in a thread pool, so every read-modify-write is + done under a lock. Data lives in this process only: it is lost on + restart and not shared between workers, so it is not suitable for + production — but it lets the rest of the application code stay realistic + (repository / service / router) while keeping the starter self-contained. """ def __init__(self) -> None: self._data: dict[int, T] = {} self._next_id: int = 1 + self._lock = Lock() - def list(self) -> Iterable[T]: - return list(self._data.values()) + def list_page(self, offset: int, limit: int) -> list[T]: + """Return up to ``limit`` entries after skipping ``offset``, by id.""" + with self._lock: + ids = sorted(self._data)[offset : offset + limit] + return [self._data[id_] for id_ in ids] + + def count(self) -> int: + with self._lock: + return len(self._data) def get(self, id_: int) -> T | None: - return self._data.get(id_) + with self._lock: + return self._data.get(id_) - def add(self, item: T) -> int: - new_id = self._next_id - self._data[new_id] = item - self._next_id += 1 - return new_id + def add(self, build: Callable[[int], T]) -> T: + """Reserve the next id and store the entity ``build(id)`` returns.""" + with self._lock: + item = build(self._next_id) + self._data[self._next_id] = item + self._next_id += 1 + return item - def replace(self, id_: int, item: T) -> bool: - if id_ not in self._data: - return False - self._data[id_] = item - return True + def update(self, id_: int, change: Callable[[T], T]) -> T | None: + """Replace an entry with ``change(current)``; ``None`` if missing.""" + with self._lock: + current = self._data.get(id_) + if current is None: + return None + updated = change(current) + self._data[id_] = updated + return updated def delete(self, id_: int) -> bool: - return self._data.pop(id_, None) is not None + with self._lock: + return self._data.pop(id_, None) is not None def clear(self) -> None: - self._data.clear() - self._next_id = 1 + with self._lock: + self._data.clear() + self._next_id = 1 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/repository.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/repository.py-tpl index dd392f1..632b7aa 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/repository.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/repository.py-tpl @@ -4,6 +4,8 @@ # Wraps the in-memory store with item-typed methods so the service layer # stays decoupled from how items are persisted. # -------------------------------------------------------------------------- +from dataclasses import replace +from typing import Any from src.app.db.memory import InMemoryStore from src.app.domains.items.models import Item @@ -17,29 +19,35 @@ class ItemRepository: def __init__(self, store: InMemoryStore[Item] | None = None) -> None: self._store = store if store is not None else _store - def list_all(self) -> list[Item]: - return list(self._store.list()) + def list_page(self, offset: int, limit: int) -> list[Item]: + return self._store.list_page(offset=offset, limit=limit) + + def count(self) -> int: + return self._store.count() def get(self, item_id: int) -> Item | None: return self._store.get(item_id) def add(self, name: str, price: float, in_stock: bool = True) -> Item: - # Reserve the next id from the store, then back-fill it on the - # entity so the repository is the single source of identity. - item = Item(id=0, name=name, price=price, in_stock=in_stock) - new_id = self._store.add(item) - item.id = new_id - return item + # The store hands out the id, so the repository never stores an + # entity without its final identity. + return self._store.add( + lambda new_id: Item(id=new_id, name=name, price=price, in_stock=in_stock) + ) def replace( self, item_id: int, name: str, price: float, in_stock: bool ) -> Item | None: - existing = self._store.get(item_id) - if existing is None: - return None - updated = Item(id=item_id, name=name, price=price, in_stock=in_stock) - self._store.replace(item_id, updated) - return updated + return self._store.update( + item_id, + lambda _current: Item( + id=item_id, name=name, price=price, in_stock=in_stock + ), + ) + + def update(self, item_id: int, changes: dict[str, Any]) -> Item | None: + """Apply already-validated partial ``changes`` to one item.""" + return self._store.update(item_id, lambda current: replace(current, **changes)) def delete(self, item_id: int) -> bool: return self._store.delete(item_id) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/router.py-tpl index 622683c..279a3b6 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/router.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/router.py-tpl @@ -1,13 +1,19 @@ # -------------------------------------------------------------------------- # Items domain — HTTP transport (FastAPI router). +# +# The router carries only the resource prefix; ``src/app/main.py`` mounts the +# aggregated API router under ``settings.API_V1_PREFIX``. # -------------------------------------------------------------------------- +from typing import Annotated -from fastapi import APIRouter, Depends, HTTPException, Response, status +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status -from src.app.domains.items.schemas import ItemCreate, ItemRead +from src.app.core.pagination import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from src.app.core.responses import error_responses +from src.app.domains.items.schemas import ItemCreate, ItemRead, ItemUpdate from src.app.domains.items.service import ItemNotFoundError, ItemService -router = APIRouter() +router = APIRouter(prefix="/items", tags=["items"]) def get_item_service() -> ItemService: @@ -15,52 +21,73 @@ def get_item_service() -> ItemService: return ItemService() -@router.get("", response_model=list[ItemRead]) -def list_items(service: ItemService = Depends(get_item_service)) -> list[ItemRead]: - return [ItemRead.model_validate(item) for item in service.list_items()] +ItemServiceDep = Annotated[ItemService, Depends(get_item_service)] -@router.get("/{item_id}", response_model=ItemRead) -def get_item( - item_id: int, service: ItemService = Depends(get_item_service) -) -> ItemRead: +def _not_found(exc: ItemNotFoundError) -> HTTPException: + return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) + + +@router.get("") +def list_items( + service: ItemServiceDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> Page[ItemRead]: + items = service.list_page(offset=offset, limit=limit) + return Page[ItemRead]( + items=[ItemRead.model_validate(item) for item in items], + total=service.count(), + limit=limit, + offset=offset, + ) + + +@router.get("/{item_id}", responses=error_responses(404)) +def get_item(item_id: int, service: ItemServiceDep) -> ItemRead: try: return ItemRead.model_validate(service.get_item(item_id)) except ItemNotFoundError as exc: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail=str(exc) - ) from exc + raise _not_found(exc) from exc -@router.post("", response_model=ItemRead, status_code=status.HTTP_201_CREATED) +@router.post("", status_code=status.HTTP_201_CREATED) def create_item( - payload: ItemCreate, service: ItemService = Depends(get_item_service) + payload: ItemCreate, + service: ItemServiceDep, + request: Request, + response: Response, ) -> ItemRead: - return ItemRead.model_validate(service.create_item(payload)) + item = service.create_item(payload) + response.headers["Location"] = str(request.url_for("get_item", item_id=item.id)) + return ItemRead.model_validate(item) -@router.put("/{item_id}", response_model=ItemRead) +@router.put("/{item_id}", responses=error_responses(404)) def replace_item( - item_id: int, - payload: ItemCreate, - service: ItemService = Depends(get_item_service), + item_id: int, payload: ItemCreate, service: ItemServiceDep ) -> ItemRead: try: return ItemRead.model_validate(service.replace_item(item_id, payload)) except ItemNotFoundError as exc: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail=str(exc) - ) from exc + raise _not_found(exc) from exc + + +@router.patch("/{item_id}", responses=error_responses(404)) +def update_item(item_id: int, payload: ItemUpdate, service: ItemServiceDep) -> ItemRead: + try: + return ItemRead.model_validate(service.update_item(item_id, payload)) + except ItemNotFoundError as exc: + raise _not_found(exc) from exc -@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT) -def delete_item( - item_id: int, service: ItemService = Depends(get_item_service) -) -> Response: +@router.delete( + "/{item_id}", + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(404), +) +def delete_item(item_id: int, service: ItemServiceDep) -> None: try: service.delete_item(item_id) except ItemNotFoundError as exc: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail=str(exc) - ) from exc - return Response(status_code=status.HTTP_204_NO_CONTENT) + raise _not_found(exc) from exc diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/schemas.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/schemas.py-tpl index e398d8c..820fc1f 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/schemas.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/schemas.py-tpl @@ -1,17 +1,36 @@ # -------------------------------------------------------------------------- # Items domain — API I/O schemas (pydantic). # -------------------------------------------------------------------------- -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator class ItemCreate(BaseModel): - """Payload accepted on POST /items.""" + """Payload accepted on POST /items and PUT /items/{item_id}.""" name: str = Field(min_length=1, max_length=120) price: float = Field(ge=0) in_stock: bool = True +class ItemUpdate(BaseModel): + """Payload accepted on PATCH /items/{item_id}: every field optional. + + Omitted fields are left untouched. None of the fields is nullable, so an + explicit ``null`` is rejected with a 422 instead of being stored. + """ + + name: str | None = Field(default=None, min_length=1, max_length=120) + price: float | None = Field(default=None, ge=0) + in_stock: bool | None = None + + @field_validator("name", "price", "in_stock") + @classmethod + def _reject_explicit_null(cls, value: object, info: ValidationInfo) -> object: + if value is None: + raise ValueError(f"{info.field_name} must not be null") + return value + + class ItemRead(BaseModel): """Outgoing representation of an item.""" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/service.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/service.py-tpl index bb1646d..b977bc0 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/service.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/domains/items/service.py-tpl @@ -8,24 +8,36 @@ from src.app.domains.items.models import Item from src.app.domains.items.repository import ItemRepository -from src.app.domains.items.schemas import ItemCreate +from src.app.domains.items.schemas import ItemCreate, ItemUpdate + + +def reset_store() -> None: + """Empty the shared items store (called by the test suite).""" + ItemRepository().reset() class ItemNotFoundError(Exception): """Raised when an item lookup misses.""" + def __init__(self, item_id: int) -> None: + super().__init__("Item not found") + self.item_id = item_id + class ItemService: def __init__(self, repository: ItemRepository | None = None) -> None: self._repository = repository if repository is not None else ItemRepository() - def list_items(self) -> list[Item]: - return self._repository.list_all() + def list_page(self, offset: int, limit: int) -> list[Item]: + return self._repository.list_page(offset=offset, limit=limit) + + def count(self) -> int: + return self._repository.count() def get_item(self, item_id: int) -> Item: item = self._repository.get(item_id) if item is None: - raise ItemNotFoundError(f"Item {item_id} does not exist") + raise ItemNotFoundError(item_id) return item def create_item(self, payload: ItemCreate) -> Item: @@ -43,9 +55,17 @@ class ItemService: in_stock=payload.in_stock, ) if updated is None: - raise ItemNotFoundError(f"Item {item_id} does not exist") + raise ItemNotFoundError(item_id) + return updated + + def update_item(self, item_id: int, payload: ItemUpdate) -> Item: + updated = self._repository.update( + item_id, payload.model_dump(exclude_unset=True) + ) + if updated is None: + raise ItemNotFoundError(item_id) return updated def delete_item(self, item_id: int) -> None: if not self._repository.delete(item_id): - raise ItemNotFoundError(f"Item {item_id} does not exist") + raise ItemNotFoundError(item_id) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/main.py-tpl index 7e756ba..99f8906 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/src/app/main.py-tpl @@ -4,6 +4,7 @@ from fastapi import FastAPI from starlette.middleware.cors import CORSMiddleware +from src.app.api import health from src.app.api.router import api_router from src.app.core.config import settings @@ -19,10 +20,12 @@ if settings.all_cors_origins: app.add_middleware( CORSMiddleware, allow_origins=settings.all_cors_origins, - allow_credentials=True, + # Browsers refuse credentials with the "*" wildcard; never send both. + allow_credentials="*" not in settings.all_cors_origins, allow_methods=["*"], allow_headers=["*"], ) +app.include_router(health.router) # fastkit:routes app.include_router(api_router, prefix=settings.API_V1_PREFIX) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/conftest.py-tpl index 871ee68..21a2be7 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/conftest.py-tpl @@ -9,12 +9,15 @@ import pytest from fastapi.testclient import TestClient from src.app import domains -from src.app.domains.items.repository import ItemRepository from src.app.main import app def reset_stores() -> None: - ItemRepository().reset() + """Call ``service.reset_store()`` of every domain package that has one. + + Domains added later (``fastkit addroute ``) follow the same + convention, so each test starts from empty stores without edits here. + """ for module in iter_modules(domains.__path__, prefix=f"{domains.__name__}."): if module.ispkg: domain = import_module(module.name) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_config.py-tpl index fba88b0..70e4492 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_config.py-tpl @@ -1,44 +1,207 @@ # -------------------------------------------------------------------------- -# Settings validation: production refuses a public example SECRET_KEY. +# Settings validation: the SECRET_KEY rule, ENVIRONMENT values, +# environment variable names and the CORS wildcard. # -------------------------------------------------------------------------- +import json +import os import re +import secrets +import subprocess +import sys from pathlib import Path +from typing import Any import pytest from pydantic import ValidationError -from src.app.core.config import KNOWN_EXAMPLE_SECRET_KEYS, Settings +from src.app.core.config import ( + KNOWN_EXAMPLE_SECRET_KEYS, + MIN_SECRET_KEY_BYTES, + Settings, +) -ENV_EXAMPLE = Path(__file__).resolve().parents[1] / ".env.example" +PROJECT_ROOT = Path(__file__).resolve().parents[1] +ENV_EXAMPLE = PROJECT_ROOT / ".env.example" +APP_MODULE = "src.app.main" +#: Settings without a default; none in this template. +REQUIRED: dict[str, Any] = {} +STRONG_KEY = "k" * MIN_SECRET_KEY_BYTES +#: Every environment except development refuses a missing, public or short +#: SECRET_KEY. +STRICT_ENVIRONMENTS = ["staging", "production"] + +@pytest.fixture(autouse=True) +def _isolated_settings_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Shell variables, in any spelling, must not leak into Settings().""" + for name in list(os.environ): + if name.upper() in {"ENVIRONMENT", "SECRET_KEY", "BACKEND_CORS_ORIGINS"}: + monkeypatch.delenv(name) + + +def make_settings(env_file: Path | None = None, **values: Any) -> Settings: + """Settings from explicit values; a developer's .env is never read.""" + return Settings(_env_file=env_file, **{**REQUIRED, **values}) # type: ignore[call-arg] + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_require_an_explicit_secret_key(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"must be set explicitly when ENVIRONMENT={environment}" + ): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_refuse_a_short_secret_key(environment: str) -> None: + short_key = "k" * (MIN_SECRET_KEY_BYTES - 1) + + with pytest.raises(ValidationError, match=f"at least {MIN_SECRET_KEY_BYTES} bytes"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=short_key) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) @pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) -def test_production_refuses_example_secret_key(example_key: str) -> None: +def test_strict_environments_refuse_every_public_example_key( + environment: str, example_key: str +) -> None: + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=f" {example_key} ") + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environment_errors_say_how_to_generate_a_key(environment: str) -> None: with pytest.raises(ValidationError, match="token_urlsafe"): - Settings(_env_file=None, ENVIRONMENT="production", SECRET_KEY=example_key) + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_an_explicit_strong_key(environment: str) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + + assert settings.ENVIRONMENT == environment + assert settings.SECRET_KEY == STRONG_KEY -@pytest.mark.parametrize("environment", ["development", "staging"]) -def test_example_secret_key_is_allowed_outside_production(environment: str) -> None: - settings = Settings( - _env_file=None, ENVIRONMENT=environment, SECRET_KEY="changethis" +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_the_key_fastkit_writes_to_env( + tmp_path: Path, environment: str +) -> None: + env_file = tmp_path / ".env" + env_file.write_text( + f"ENVIRONMENT={environment}\nSECRET_KEY={secrets.token_urlsafe(32)}\n", + encoding="utf-8", ) - assert settings.SECRET_KEY == "changethis" + assert make_settings(env_file).ENVIRONMENT == environment + + +def test_development_without_a_key_uses_a_random_one() -> None: + settings = make_settings(ENVIRONMENT="development") + + assert len(settings.SECRET_KEY.encode()) >= MIN_SECRET_KEY_BYTES + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_development_only_warns_about_an_example_key() -> None: + example_key = sorted(KNOWN_EXAMPLE_SECRET_KEYS)[0] + + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings(ENVIRONMENT="development", SECRET_KEY=example_key) + + assert settings.SECRET_KEY == example_key + + +@pytest.mark.parametrize("value", ["Production", "PRODUCTION", " production", "prod"]) +def test_unknown_environment_values_fail_closed(value: str) -> None: + with pytest.raises(ValidationError, match="ENVIRONMENT"): + make_settings(ENVIRONMENT=value, SECRET_KEY=STRONG_KEY) + + +def test_environment_variable_names_are_case_insensitive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("environment", "production") + + with pytest.raises(ValidationError, match="must be set explicitly"): + make_settings() + + monkeypatch.setenv("secret_key", STRONG_KEY) + + assert make_settings().ENVIRONMENT == "production" + + +@pytest.mark.parametrize("raw", ["*", " * ", '["*"]', "*,http://localhost:3000"]) +def test_cors_wildcard_is_accepted(monkeypatch: pytest.MonkeyPatch, raw: str) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + + assert make_settings().all_cors_origins == ["*"] + + +def test_cors_origins_must_be_urls_or_the_wildcard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + + with pytest.raises(ValidationError): + make_settings() + + +#: Runs in a fresh interpreter: the app reads its settings at import time. +_PREFLIGHT = f""" +import json +from fastapi.testclient import TestClient +from {APP_MODULE} import app + +headers = {{ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "GET", +}} +response = TestClient(app).options("/", headers=headers) +allowed = {{ + k: v for k, v in response.headers.items() if k.startswith("access-control-allow-") +}} +print(json.dumps(allowed)) +""" -def test_production_accepts_a_real_secret_key() -> None: - settings = Settings( - _env_file=None, - ENVIRONMENT="production", - SECRET_KEY="a-real-unique-key-0123456789abcdef", +@pytest.mark.parametrize( + ("origins", "allow_origin", "allow_credentials"), + [ + ("*", "*", None), + ("http://localhost:3000", "http://localhost:3000", "true"), + ], +) +def test_cors_wildcard_is_never_combined_with_credentials( + origins: str, allow_origin: str, allow_credentials: str | None +) -> None: + env = { + **os.environ, + **{name: str(value) for name, value in REQUIRED.items()}, + "BACKEND_CORS_ORIGINS": origins, + "ENVIRONMENT": "development", + } + result = subprocess.run( + [sys.executable, "-c", _PREFLIGHT], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + check=False, ) - assert settings.ENVIRONMENT == "production" + assert result.returncode == 0, result.stderr + headers = json.loads(result.stdout.strip().splitlines()[-1]) + assert headers["access-control-allow-origin"] == allow_origin + assert headers.get("access-control-allow-credentials") == allow_credentials def test_env_example_secret_key_is_a_known_example_value() -> None: - """Whatever .env.example ships must be one the production guard rejects.""" + """Whatever .env.example ships must be one the SECRET_KEY guard rejects.""" if not ENV_EXAMPLE.is_file(): pytest.skip(".env.example is not part of this checkout") diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_health.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_health.py-tpl index 00b4a7f..7cb9648 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_health.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_health.py-tpl @@ -5,7 +5,13 @@ from src.app.core.config import settings def test_health_endpoint_returns_ok(client): - response = client.get(f"{settings.API_V1_PREFIX}/health") + response = client.get("/health") assert response.status_code == 200 assert response.json() == {"status": "ok"} + + +def test_health_endpoint_is_not_versioned(client): + response = client.get(f"{settings.API_V1_PREFIX}/health") + + assert response.status_code == 404 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_items.py-tpl index 19615a3..790aaa8 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_items.py-tpl @@ -1,30 +1,85 @@ # -------------------------------------------------------------------------- # Items domain — end-to-end coverage of the CRUD endpoints. # -------------------------------------------------------------------------- +from concurrent.futures import ThreadPoolExecutor + +import pytest + from src.app.core.config import settings +from src.app.domains.items.repository import ItemRepository ITEMS_URL = f"{settings.API_V1_PREFIX}/items" +def _create(client, name="Sticker", price=2.5, in_stock=True): + response = client.post( + ITEMS_URL, json={"name": name, "price": price, "in_stock": in_stock} + ) + assert response.status_code == 201 + return response.json() + + def test_list_items_starts_empty(client): response = client.get(ITEMS_URL) assert response.status_code == 200 - assert response.json() == [] + assert response.json() == {"items": [], "total": 0, "limit": 20, "offset": 0} + + +def test_collection_path_has_no_trailing_slash_redirect(client): + response = client.get(ITEMS_URL, follow_redirects=False) + + assert response.status_code == 200 + + +def test_list_items_paginates_in_id_order(client): + created = [_create(client, name=f"item-{n}") for n in range(5)] + + response = client.get(ITEMS_URL, params={"limit": 2, "offset": 1}) + + assert response.status_code == 200 + body = response.json() + assert body["total"] == 5 + assert body["limit"] == 2 + assert body["offset"] == 1 + assert [item["id"] for item in body["items"]] == [ + created[1]["id"], + created[2]["id"], + ] + + +def test_list_items_offset_past_the_end_is_empty(client): + _create(client) + body = client.get(ITEMS_URL, params={"offset": 10}).json() -def test_create_then_read_item(client): - create_response = client.post( + assert body["items"] == [] + assert body["total"] == 1 + + +@pytest.mark.parametrize( + "params", + [{"limit": 0}, {"limit": 101}, {"offset": -1}, {"limit": "many"}], +) +def test_list_items_rejects_out_of_range_pagination(client, params): + response = client.get(ITEMS_URL, params=params) + + assert response.status_code == 422 + + +def test_create_returns_201_with_resolvable_location(client): + response = client.post( ITEMS_URL, json={"name": "Sticker", "price": 2.5, "in_stock": True}, ) - assert create_response.status_code == 201 - created = create_response.json() - assert created["id"] == 1 + assert response.status_code == 201 + created = response.json() assert created["name"] == "Sticker" + location = response.headers["location"] + assert location.endswith(f"{ITEMS_URL}/{created['id']}") - read_response = client.get(f"{ITEMS_URL}/{created['id']}") + read_response = client.get(location) assert read_response.status_code == 200 assert read_response.json() == created @@ -34,13 +89,11 @@ def test_get_unknown_item_returns_404(client): response = client.get(f"{ITEMS_URL}/999") assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} def test_replace_item(client): - created = client.post( - ITEMS_URL, - json={"name": "Mug", "price": 9.0, "in_stock": True}, - ).json() + created = _create(client, name="Mug", price=9.0) response = client.put( f"{ITEMS_URL}/{created['id']}", @@ -48,26 +101,86 @@ def test_replace_item(client): ) assert response.status_code == 200 - body = response.json() - assert body["id"] == created["id"] - assert body["name"] == "Mug v2" - assert body["price"] == 11.0 - assert body["in_stock"] is False + assert response.json() == { + "id": created["id"], + "name": "Mug v2", + "price": 11.0, + "in_stock": False, + } + + +def test_put_is_a_full_replacement(client): + created = _create(client, name="Mug", price=9.0) + + response = client.put(f"{ITEMS_URL}/{created['id']}", json={"name": "Mug v2"}) + + assert response.status_code == 422 + assert client.get(f"{ITEMS_URL}/{created['id']}").json() == created + + +def test_put_resets_omitted_optional_fields_to_defaults(client): + created = _create(client, name="Mug", price=9.0, in_stock=False) + + response = client.put( + f"{ITEMS_URL}/{created['id']}", json={"name": "Mug", "price": 9.0} + ) + + assert response.status_code == 200 + assert response.json()["in_stock"] is True + + +def test_replace_unknown_item_returns_404(client): + response = client.put(f"{ITEMS_URL}/999", json={"name": "Mug", "price": 1.0}) + + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +def test_patch_updates_only_sent_fields(client): + created = _create(client, name="Mug", price=9.0, in_stock=True) + + response = client.patch(f"{ITEMS_URL}/{created['id']}", json={"price": 12.0}) + + assert response.status_code == 200 + assert response.json() == {**created, "price": 12.0} + + +def test_patch_rejects_explicit_null_without_mutating(client): + created = _create(client, name="Mug", price=9.0) + + response = client.patch( + f"{ITEMS_URL}/{created['id']}", json={"price": 1.0, "name": None} + ) + + assert response.status_code == 422 + assert client.get(f"{ITEMS_URL}/{created['id']}").json() == created + + +def test_patch_unknown_item_returns_404(client): + response = client.patch(f"{ITEMS_URL}/999", json={"price": 1.0}) + + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} def test_delete_item(client): - created = client.post( - ITEMS_URL, - json={"name": "Keychain", "price": 4.0, "in_stock": True}, - ).json() + created = _create(client, name="Keychain", price=4.0) delete_response = client.delete(f"{ITEMS_URL}/{created['id']}") assert delete_response.status_code == 204 + assert delete_response.content == b"" follow_up = client.get(f"{ITEMS_URL}/{created['id']}") assert follow_up.status_code == 404 +def test_delete_unknown_item_returns_404(client): + response = client.delete(f"{ITEMS_URL}/999") + + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + def test_create_item_validates_payload(client): response = client.post( ITEMS_URL, @@ -75,3 +188,29 @@ def test_create_item_validates_payload(client): ) assert response.status_code == 422 + + +def test_concurrent_creates_get_unique_ids(): + repository = ItemRepository() + + with ThreadPoolExecutor(max_workers=8) as pool: + items = list( + pool.map(lambda n: repository.add(name=f"i{n}", price=1.0), range(200)) + ) + + assert len({item.id for item in items}) == 200 + assert repository.count() == 200 + + +def test_openapi_declares_item_error_responses(client): + paths = client.get("/openapi.json").json()["paths"] + item_path = paths[f"{ITEMS_URL}/{{item_id}}"] + + for method in ("get", "put", "patch", "delete"): + assert "404" in item_path[method]["responses"] + assert item_path["delete"]["responses"].keys() >= {"204"} + assert "201" in paths[ITEMS_URL]["post"]["responses"] + assert all( + operation["tags"] == ["items"] + for operation in [*item_path.values(), *paths[ITEMS_URL].values()] + ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_pagination.py-tpl new file mode 100644 index 0000000..9c12940 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/tests/test_pagination.py-tpl @@ -0,0 +1,23 @@ +# -------------------------------------------------------------------------- +# Pagination primitives shared by list endpoints. +# -------------------------------------------------------------------------- +from src.app.core.pagination import Page +from src.app.db.memory import InMemoryStore + + +def test_page_serializes_the_envelope_keys(): + page = Page[int](items=[1, 2], total=5, limit=2, offset=0) + + assert page.model_dump() == {"items": [1, 2], "total": 5, "limit": 2, "offset": 0} + + +def test_store_pages_in_id_order_and_counts(): + store: InMemoryStore[str] = InMemoryStore() + for name in ("a", "b", "c", "d"): + store.add(lambda new_id, name=name: f"{new_id}:{name}") + store.delete(2) + + assert store.count() == 3 + assert store.list_page(offset=0, limit=2) == ["1:a", "3:c"] + assert store.list_page(offset=2, limit=2) == ["4:d"] + assert store.list_page(offset=5, limit=2) == [] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.env.example-tpl index c9d6bec..50c60cb 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.env.example-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/.env.example-tpl @@ -1 +1,11 @@ +# .env.example keeps a public placeholder; fastkit writes a unique key to the +# local, git-ignored .env. With any ENVIRONMENT other than development +# (staging or production) the app refuses to start when SECRET_KEY is unset, +# a public example value or shorter than 32 bytes. SECRET_KEY=changethis +# One of: development, staging, production. +# ENVIRONMENT=development +# API_V1_PREFIX=/api/v1 +# Allowed browser origins, comma-separated or a JSON list. "*" allows any +# origin, but then without credentials (cookies, Authorization headers): +# BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/README.md-tpl index 19e8bd6..f0a0c9f 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/README.md-tpl @@ -6,16 +6,21 @@ A minimal FastAPI template that provides the basic structure for building FastAP ## Features -- FastAPI with basic CORS support -- Basic configuration management +- FastAPI with CORS enabled only for the origins in `BACKEND_CORS_ORIGINS` (`*` allows any + origin, but then without credentials such as cookies or `Authorization` headers) +- Basic configuration management (`API_V1_PREFIX`, `ENVIRONMENT`, `SECRET_KEY`); + any `ENVIRONMENT` other than `development` (`staging`, `production`) refuses to start + unless `SECRET_KEY` is set explicitly, is at least 32 bytes long and is not a public + example value +- Shared `Page[T]` model and `limit`/`offset` parameters for list endpoints (`src/core/pagination.py`) - Environment variable support - Simple project structure - Ready for development ## Stack -- FastAPI 0.115+ -- Python 3.8+ +- FastAPI +- Python 3.12+ - Pydantic (data validation) - Uvicorn (ASGI server) @@ -24,16 +29,19 @@ A minimal FastAPI template that provides the basic structure for building FastAP ``` . ├── README.md +├── pyproject.toml ├── requirements.txt -├── setup.py ├── src/ │ ├── main.py # FastAPI application │ ├── core/ # Core configuration -│ │ └── config.py # Settings management +│ │ ├── config.py # Settings management +│ │ ├── pagination.py # Page[T] and limit/offset parameters +│ │ └── responses.py # OpenAPI error response helper │ └── __init__.py ├── tests/ # Test code -│ ├── conftest.py # pytest configuration -│ ├── test_main.py # Main application tests +│ ├── conftest.py # pytest configuration +│ ├── test_main.py # Main application tests +│ ├── test_pagination.py # Pagination helper tests │ └── __init__.py ├── .env # Local environment variables (git-ignored) └── .env.example # Shareable example, committed @@ -53,6 +61,15 @@ uvicorn src.main:app --reload The application will be available at http://localhost:8000 +## Endpoints + +| Method | Endpoint | Description | +|--------|-----------|---------------------------------------------| +| GET | `/` | Welcome message | +| GET | `/health` | Liveness probe, returns `{"status": "ok"}` | + +Mount your own routers under `settings.API_V1_PREFIX` (default `/api/v1`). + ## API Documentation After running the server, check API documentation at: diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/pyproject.toml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/pyproject.toml-tpl index f6c443e..af044e1 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/pyproject.toml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/pyproject.toml-tpl @@ -78,3 +78,8 @@ python_files = ["test_*.py"] python_classes = ["Test*"] python_functions = ["test_*"] addopts = "-v --tb=short" +filterwarnings = [ + # starlette's TestClient now prefers `httpx2`; this project pins httpx, so only + # that advisory notice (a UserWarning subclass) is silenced. + "ignore:Using `httpx` with `starlette.testclient` is deprecated:starlette.exceptions.StarletteDeprecationWarning", +] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/requirements.txt-tpl index 02fe659..4b4a7bf 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/requirements.txt-tpl @@ -1,6 +1,6 @@ annotated-doc==0.0.5 annotated-types==0.8.0 -anyio==4.15.0 +anyio==4.16.0 ast-serialize==0.9.0 black==26.10.1 certifi==2026.10.23 @@ -28,7 +28,7 @@ pytest==9.1.1 python-dotenv==1.2.3 pytokens==0.4.1 PyYAML==6.0.3 -starlette==1.6.0 +starlette==1.10.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/setup.cfg-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/setup.cfg-tpl deleted file mode 100644 index f8ecdbe..0000000 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/setup.cfg-tpl +++ /dev/null @@ -1,13 +0,0 @@ -[mypy] -warn_unused_configs = true -ignore_missing_imports = true - -[isort] -profile = black -line_length=100 -virtual_env=venv - -[tool:pytest] -pythonpath = src -testpaths = tests -python_files = test_*.py diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/config.py-tpl index fe9f5c8..715ba00 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/config.py-tpl @@ -1,29 +1,71 @@ # -------------------------------------------------------------------------- # Configuration module # -------------------------------------------------------------------------- +import json import secrets import warnings -from typing import Annotated, Any, Literal, Self +from typing import Annotated, Any, Literal from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator -from pydantic_settings import BaseSettings, SettingsConfigDict +from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict -def parse_cors(v: Any) -> list[str] | str: - if isinstance(v, str) and not v.startswith("["): - return [i.strip() for i in v.split(",")] - elif isinstance(v, list | str): - return v - raise ValueError(v) +def parse_cors(value: Any) -> Any: + """Read origins from a comma-separated string or a JSON list. - -CorsOrigins = Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] + Blank entries are dropped, so ``BACKEND_CORS_ORIGINS=`` or a trailing + comma never turns into an empty origin. + """ + if isinstance(value, str): + value = value.strip() + if value.startswith("["): + value = json.loads(value) + else: + value = value.split(",") + if isinstance(value, list): + return [str(origin).strip() for origin in value if str(origin).strip()] + raise ValueError(value) + + +# Each origin is a full URL such as http://localhost:3000, or "*" for any +# origin. "*" never goes together with credentials (cookies, Authorization +# headers): browsers refuse that, so main.py turns credentials off for it. +CorsOrigins = Annotated[ + list[Literal["*"] | AnyUrl], NoDecode, BeforeValidator(parse_cors) +] + +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + "your-secret-key-here", + "change-me-in-production", + "your-mcp-api-key-here", + } +) + +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = 32 + +_GENERATE_KEY_HINT = ( + "Generate one with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) class Settings(BaseSettings): - """Default project configuraion module + """Default project configuration module - This base module configures your project SECRET_KEY, CORS origins and project name + This base module configures your project SECRET_KEY, API prefix, CORS + origins and project name **Add your project configurations below** @@ -39,38 +81,63 @@ class Settings(BaseSettings): extra="ignore", ) + PROJECT_NAME: str = "" + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + # The shipped code signs nothing with SECRET_KEY yet, but authentication + # you add later (including the JWT and Session options of fastkit init) + # signs tokens or cookies with it, so treat it as a production secret. + # fastkit writes a unique value to .env; staging and production refuse a + # missing, public or short key (see _check_secret_key below). SECRET_KEY: str = secrets.token_urlsafe(32) - ENVIRONMENT: Literal["development", "production"] = "development" - CLIENT_ORIGIN: str = "" + # Every business router is mounted under this prefix (see src/main.py). + API_V1_PREFIX: str = "/api/v1" BACKEND_CORS_ORIGINS: CorsOrigins = [] @computed_field # type: ignore[prop-decorator] @property def all_cors_origins(self) -> list[str]: - return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + [ - self.CLIENT_ORIGIN - ] - - PROJECT_NAME: str = "" - - def _check_default_secret(self, var_name: str, value: str | None) -> None: - if value == "changethis": - message = ( - f'The value of {var_name} is "changethis", ' - "for security, please change it, at least for deployments." - ) - if self.ENVIRONMENT == "development": - warnings.warn(message, stacklevel=1) - else: - raise ValueError(message) + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins @model_validator(mode="after") - def _enforce_non_default_secrets(self) -> Self: - self._check_default_secret("SECRET_KEY", self.SECRET_KEY) - + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) + return self + env = f"ENVIRONMENT={self.ENVIRONMENT}" + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT + ) + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: + raise ValueError( + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT + ) return self -settings = Settings() # type: ignore +settings = Settings() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/pagination.py-tpl new file mode 100644 index 0000000..2688822 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/pagination.py-tpl @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------- +# Limit/offset pagination shared by every list endpoint. +# +# List endpoints take ``limit: LimitParam = DEFAULT_LIMIT`` and +# ``offset: OffsetParam = 0`` and return a ``Page[T]`` envelope: +# {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range +# values are rejected with a 422 rather than clamped. +# -------------------------------------------------------------------------- +from typing import Annotated, Generic, TypeVar + +from fastapi import Query +from pydantic import BaseModel + +T = TypeVar("T") + +#: Page size used when the client sends no ``limit``. +DEFAULT_LIMIT = 20 +#: Largest page a client may ask for. +MAX_LIMIT = 100 + +LimitParam = Annotated[ + int, Query(ge=1, le=MAX_LIMIT, description="Maximum number of items to return.") +] +OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] + + +class Page(BaseModel, Generic[T]): + """One page of a collection, ordered by primary key. + + ``total`` counts the whole collection, so a client knows there is a next + page while ``offset + len(items) < total``. + """ + + items: list[T] + total: int + limit: int + offset: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/responses.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/responses.py-tpl new file mode 100644 index 0000000..bffc8c1 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/responses.py-tpl @@ -0,0 +1,40 @@ +# -------------------------------------------------------------------------- +# OpenAPI error responses shared by the routers. +# +# FastAPI documents 2xx and 422 on its own. Routes that can also answer 401, +# 404, 409, ... declare it with ``responses=error_responses(404)`` so clients +# see every status code and the ``{"detail": "..."}`` body in the schema. +# -------------------------------------------------------------------------- +from http import HTTPStatus +from typing import Any + +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + """Body FastAPI sends for an ``HTTPException``.""" + + detail: str + + +def error_responses(*status_codes: int) -> dict[int | str, dict[str, Any]]: + """Build ``responses=`` entries that document the given error codes. + + A 401 entry also documents the ``WWW-Authenticate`` header every 401 + response carries. + """ + responses: dict[int | str, dict[str, Any]] = {} + for code in status_codes: + entry: dict[str, Any] = { + "model": ErrorDetail, + "description": HTTPStatus(code).phrase, + } + if code == HTTPStatus.UNAUTHORIZED: + entry["headers"] = { + "WWW-Authenticate": { + "description": "Authentication scheme to use (Bearer).", + "schema": {"type": "string"}, + } + } + responses[code] = entry + return responses diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/main.py-tpl index 18b83e2..1ec1abd 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/src/main.py-tpl @@ -13,32 +13,41 @@ app = FastAPI( title=settings.PROJECT_NAME, ) +# Origins come only from BACKEND_CORS_ORIGINS; with none configured the +# middleware is not installed at all. if settings.all_cors_origins: app.add_middleware( CORSMiddleware, allow_origins=settings.all_cors_origins, - allow_credentials=True, + # Browsers refuse credentials with the "*" wildcard; never send both. + allow_credentials="*" not in settings.all_cors_origins, allow_methods=["*"], allow_headers=["*"], ) +# Mount business routers under the versioned prefix, for example: +# app.include_router(items_router, prefix=settings.API_V1_PREFIX) # fastkit:routes -@app.get("/") -async def root(): - """Root endpoint.""" - return {"message": "Hello from FastAPI Empty Template!"} -@app.get("/health") -async def health_check(): - """Health check endpoint.""" - return {"status": "healthy"} +@app.get("/", tags=["root"]) +async def root() -> dict[str, str]: + """Welcome message with a pointer to the interactive API docs.""" + return {"message": f"Welcome to {settings.PROJECT_NAME}", "docs": "/docs"} + + +@app.get("/health", tags=["health"]) +async def health_check() -> dict[str, str]: + """Liveness probe: no authentication and no I/O.""" + return {"status": "ok"} """Add your FastAPI application main routine here You can attach customized middlewares, api routes, etc. +List endpoints can use the shared Page model and limit/offset parameters +from src/core/pagination.py. For more information, please refer to the following link: diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/test_config.py-tpl new file mode 100644 index 0000000..38f107b --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/test_config.py-tpl @@ -0,0 +1,194 @@ +# -------------------------------------------------------------------------- +# Settings validation: the SECRET_KEY rule, ENVIRONMENT values, +# environment variable names and the CORS wildcard. +# -------------------------------------------------------------------------- +import json +import os +import secrets +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest +from pydantic import ValidationError + +from src.core.config import KNOWN_EXAMPLE_SECRET_KEYS, MIN_SECRET_KEY_BYTES, Settings + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +APP_MODULE = "src.main" +#: Settings without a default; none in this template. +REQUIRED: dict[str, Any] = {} + +STRONG_KEY = "k" * MIN_SECRET_KEY_BYTES +#: Every environment except development refuses a missing, public or short +#: SECRET_KEY. +STRICT_ENVIRONMENTS = ["staging", "production"] + + +@pytest.fixture(autouse=True) +def _isolated_settings_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Shell variables, in any spelling, must not leak into Settings().""" + for name in list(os.environ): + if name.upper() in {"ENVIRONMENT", "SECRET_KEY", "BACKEND_CORS_ORIGINS"}: + monkeypatch.delenv(name) + + +def make_settings(env_file: Path | None = None, **values: Any) -> Settings: + """Settings from explicit values; a developer's .env is never read.""" + return Settings(_env_file=env_file, **{**REQUIRED, **values}) # type: ignore[call-arg] + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_require_an_explicit_secret_key(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"must be set explicitly when ENVIRONMENT={environment}" + ): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_refuse_a_short_secret_key(environment: str) -> None: + short_key = "k" * (MIN_SECRET_KEY_BYTES - 1) + + with pytest.raises(ValidationError, match=f"at least {MIN_SECRET_KEY_BYTES} bytes"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=short_key) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +@pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) +def test_strict_environments_refuse_every_public_example_key( + environment: str, example_key: str +) -> None: + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=f" {example_key} ") + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environment_errors_say_how_to_generate_a_key(environment: str) -> None: + with pytest.raises(ValidationError, match="token_urlsafe"): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_an_explicit_strong_key(environment: str) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + + assert settings.ENVIRONMENT == environment + assert settings.SECRET_KEY == STRONG_KEY + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_the_key_fastkit_writes_to_env( + tmp_path: Path, environment: str +) -> None: + env_file = tmp_path / ".env" + env_file.write_text( + f"ENVIRONMENT={environment}\nSECRET_KEY={secrets.token_urlsafe(32)}\n", + encoding="utf-8", + ) + + assert make_settings(env_file).ENVIRONMENT == environment + + +def test_development_without_a_key_uses_a_random_one() -> None: + settings = make_settings(ENVIRONMENT="development") + + assert len(settings.SECRET_KEY.encode()) >= MIN_SECRET_KEY_BYTES + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_development_only_warns_about_an_example_key() -> None: + example_key = sorted(KNOWN_EXAMPLE_SECRET_KEYS)[0] + + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings(ENVIRONMENT="development", SECRET_KEY=example_key) + + assert settings.SECRET_KEY == example_key + + +@pytest.mark.parametrize("value", ["Production", "PRODUCTION", " production", "prod"]) +def test_unknown_environment_values_fail_closed(value: str) -> None: + with pytest.raises(ValidationError, match="ENVIRONMENT"): + make_settings(ENVIRONMENT=value, SECRET_KEY=STRONG_KEY) + + +def test_environment_variable_names_are_case_insensitive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("environment", "production") + + with pytest.raises(ValidationError, match="must be set explicitly"): + make_settings() + + monkeypatch.setenv("secret_key", STRONG_KEY) + + assert make_settings().ENVIRONMENT == "production" + + +@pytest.mark.parametrize("raw", ["*", " * ", '["*"]', "*,http://localhost:3000"]) +def test_cors_wildcard_is_accepted(monkeypatch: pytest.MonkeyPatch, raw: str) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + + assert make_settings().all_cors_origins == ["*"] + + +def test_cors_origins_must_be_urls_or_the_wildcard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + + with pytest.raises(ValidationError): + make_settings() + + +#: Runs in a fresh interpreter: the app reads its settings at import time. +_PREFLIGHT = f""" +import json +from fastapi.testclient import TestClient +from {APP_MODULE} import app + +headers = {{ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "GET", +}} +response = TestClient(app).options("/", headers=headers) +allowed = {{ + k: v for k, v in response.headers.items() if k.startswith("access-control-allow-") +}} +print(json.dumps(allowed)) +""" + + +@pytest.mark.parametrize( + ("origins", "allow_origin", "allow_credentials"), + [ + ("*", "*", None), + ("http://localhost:3000", "http://localhost:3000", "true"), + ], +) +def test_cors_wildcard_is_never_combined_with_credentials( + origins: str, allow_origin: str, allow_credentials: str | None +) -> None: + env = { + **os.environ, + **{name: str(value) for name, value in REQUIRED.items()}, + "BACKEND_CORS_ORIGINS": origins, + "ENVIRONMENT": "development", + } + result = subprocess.run( + [sys.executable, "-c", _PREFLIGHT], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + check=False, + ) + + assert result.returncode == 0, result.stderr + headers = json.loads(result.stdout.strip().splitlines()[-1]) + assert headers["access-control-allow-origin"] == allow_origin + assert headers.get("access-control-allow-credentials") == allow_credentials diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/test_main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/test_main.py-tpl index e484022..09bcd6d 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/test_main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/test_main.py-tpl @@ -1,36 +1,75 @@ # -------------------------------------------------------------------------- # Main application testcases # -------------------------------------------------------------------------- +import pytest from fastapi.testclient import TestClient +from src.core.config import Settings +from src.core.responses import ErrorDetail, error_responses +from src.main import app -def test_root_endpoint(client: TestClient): - """Test root endpoint.""" + +def test_root_endpoint(client: TestClient) -> None: + """The root route welcomes the client and points at the docs.""" response = client.get("/") assert response.status_code == 200 - data = response.json() - assert "message" in data - assert data["message"] == "Hello from FastAPI Empty Template!" + # The app title is the configured PROJECT_NAME. + assert response.json() == {"message": f"Welcome to {app.title}", "docs": "/docs"} -def test_health_check(client: TestClient): +def test_health_check(client: TestClient) -> None: """Test health check endpoint.""" response = client.get("/health") assert response.status_code == 200 - data = response.json() - assert data["status"] == "healthy" + assert response.json() == {"status": "ok"} -def test_openapi_docs(client: TestClient): +def test_openapi_docs(client: TestClient) -> None: """Test OpenAPI documentation access.""" response = client.get("/docs") assert response.status_code == 200 -def test_openapi_json(client: TestClient): +def test_openapi_json(client: TestClient) -> None: """Test OpenAPI JSON schema access.""" response = client.get("/openapi.json") assert response.status_code == 200 data = response.json() assert "openapi" in data assert "info" in data + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ( + "http://localhost:3000, ,https://example.com/", + ["http://localhost:3000", "https://example.com"], + ), + ('["http://localhost:3000", ""]', ["http://localhost:3000"]), + ("", []), + ], +) +def test_cors_origins_never_contain_an_empty_origin( + monkeypatch: pytest.MonkeyPatch, raw: str, expected: list[str] +) -> None: + # _env_file=None: a developer's .env must not change the result. + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + settings = Settings(_env_file=None) # type: ignore[call-arg] + + assert settings.all_cors_origins == expected + + +def test_business_routes_default_to_the_v1_prefix( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("API_V1_PREFIX", raising=False) + + assert Settings(_env_file=None).API_V1_PREFIX == "/api/v1" # type: ignore[call-arg] + + +def test_error_responses_helper_documents_error_bodies() -> None: + responses = error_responses(404, 409) + + assert responses[404] == {"model": ErrorDetail, "description": "Not Found"} + assert responses[409]["description"] == "Conflict" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/test_pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/test_pagination.py-tpl new file mode 100644 index 0000000..9b8ab2f --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/tests/test_pagination.py-tpl @@ -0,0 +1,47 @@ +# -------------------------------------------------------------------------- +# Shared pagination helpers (src/core/pagination.py) +# -------------------------------------------------------------------------- +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from src.core.pagination import DEFAULT_LIMIT, LimitParam, OffsetParam, Page + +NUMBERS = list(range(1, 6)) + +demo = FastAPI() + + +@demo.get("/numbers") +def list_numbers( + limit: LimitParam = DEFAULT_LIMIT, offset: OffsetParam = 0 +) -> Page[int]: + return Page[int]( + items=NUMBERS[offset : offset + limit], + total=len(NUMBERS), + limit=limit, + offset=offset, + ) + + +@pytest.fixture +def demo_client() -> TestClient: + return TestClient(demo) + + +def test_page_envelope(demo_client: TestClient) -> None: + response = demo_client.get("/numbers", params={"limit": 2, "offset": 1}) + + assert response.status_code == 200 + assert response.json() == {"items": [2, 3], "total": 5, "limit": 2, "offset": 1} + + +def test_default_limit(demo_client: TestClient) -> None: + assert demo_client.get("/numbers").json()["limit"] == DEFAULT_LIMIT + + +@pytest.mark.parametrize("params", [{"limit": 0}, {"limit": 101}, {"offset": -1}]) +def test_out_of_range_parameters_are_rejected( + demo_client: TestClient, params: dict[str, int] +) -> None: + assert demo_client.get("/numbers", params=params).status_code == 422 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.dockerignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.dockerignore-tpl new file mode 100644 index 0000000..151b60c --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.dockerignore-tpl @@ -0,0 +1,47 @@ +# Files Docker never sends to the build, so they cannot end up in the image. + +# Secrets: settings come from the environment at run time (docker run -e / +# --env-file, compose env_file), never from a file baked into the image. +.env +.env.* + +# VCS and editor state +.git +.gitignore +.gitattributes +.idea +.vscode +**/.DS_Store + +# Virtual environments +.venv +venv +env + +# Python, test and tool caches +**/__pycache__ +**/*.py[cod] +.pytest_cache +.mypy_cache +.ruff_cache +.coverage +.coverage.* +coverage.xml +htmlcov +dist +build +*.egg-info + +# Local SQLite databases +**/*.db +**/*.db-journal +**/*.db-wal +**/*.db-shm + +# The application image does not run the test suite +tests + +# Docker files themselves +Dockerfile +docker-compose*.yml +.dockerignore diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.env.example-tpl index f4b0fd4..bd615a0 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.env.example-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/.env.example-tpl @@ -11,5 +11,23 @@ LLM_MAX_TOKENS=4096 # LLM_BASE_URL=http://localhost:4000 # LLM_AUTH_TOKEN= +# Hard stop for the tool-call loop of one chat turn (bounds API spend). +# MAX_TOOL_ITERATIONS=5 + +# Conversation memory limits. The in-memory store evicts the least recently +# used conversation beyond MAX_CONVERSATIONS; a conversation holding +# MAX_MESSAGES_PER_CONVERSATION messages gets 409 and must be restarted. +# MAX_CONVERSATIONS=1000 +# MAX_MESSAGES_PER_CONVERSATION=100 + +# .env.example keeps a public placeholder; fastkit writes a unique key to the +# local, git-ignored .env. With any ENVIRONMENT other than development +# (staging or production) the app refuses to start when SECRET_KEY is unset, +# a public example value or shorter than 32 bytes. SECRET_KEY=changethis +# One of: development, staging, production. ENVIRONMENT=development + +# Allowed browser origins, comma-separated or a JSON list. "*" allows any +# origin, but then without credentials (cookies, Authorization headers): +# BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/Dockerfile-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/Dockerfile-tpl index 39159fd..1b899ef 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/Dockerfile-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/Dockerfile-tpl @@ -1,18 +1,35 @@ FROM python:3.12-slim +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + WORKDIR /app +# Unprivileged runtime user with a fixed UID/GID, so file ownership on mounted +# volumes stays predictable across rebuilds. +RUN groupadd --system --gid 10001 app \ + && useradd --system --uid 10001 --gid app --no-create-home \ + --home-dir /nonexistent --shell /usr/sbin/nologin app + COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt +# The source stays owned by root, read-only for the app user. .dockerignore +# keeps .env, tests/, virtualenvs and local databases out of the build context. COPY src/ src/ -COPY tests/ tests/ COPY scripts/ scripts/ ENV PYTHONPATH=/app ENV ENVIRONMENT=production +USER app + EXPOSE 8000 -# ANTHROPIC_API_KEY must be supplied at run time, never baked into the image. +# Liveness probe on GET /health (the slim image has no curl, so python). +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ + CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3)"] + +# ANTHROPIC_API_KEY must be supplied at run time, never baked into the image: +# docker run -p 8000:8000 -e ANTHROPIC_API_KEY=... CMD ["uvicorn", "src.app.main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl index 74aa995..3ca4ecc 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl @@ -64,9 +64,9 @@ you need a database-backed API, use `fastapi-sqlmodel`. │ ├── schemas/ │ │ └── chat.py # request bodies + SSE event envelope │ └── api/ -│ ├── router.py # aggregates health + chat -│ ├── deps.py # store / agent dependencies -│ ├── health.py # GET /health +│ ├── router.py # chat routes, mounted under /api/v1 +│ ├── deps.py # store / agent deps, auth + rate-limit hooks +│ ├── health.py # GET /health (application root) │ └── chat.py # POST /chat (SSE), conversation history └── tests/ ├── conftest.py # scripted fake Anthropic client @@ -88,11 +88,19 @@ ANTHROPIC_API_KEY=sk-ant-... LLM_MODEL=claude-sonnet-5 LLM_MAX_TOKENS=4096 MAX_TOOL_ITERATIONS=5 +MAX_CONVERSATIONS=1000 +MAX_MESSAGES_PER_CONVERSATION=100 ``` The key is read by pydantic-settings and handed to the client at construction — it is never written into source or into the Docker image. +With any `ENVIRONMENT` other than `development` (`staging`, `production`) the +app refuses to start when `SECRET_KEY` is unset, a public example value or +shorter than 32 bytes. `BACKEND_CORS_ORIGINS` +takes comma-separated origins or a JSON list; `*` allows any origin, but then +the app sends no credentials (cookies, `Authorization` headers). + To run against an Anthropic-compatible gateway (LiteLLM, an internal proxy, a local server) instead of the Anthropic API, set `LLM_BASE_URL` and, if the gateway uses bearer auth, `LLM_AUTH_TOKEN`. The wire format stays the @@ -124,14 +132,39 @@ API docs are then served at: | Method | Endpoint | Description | |--------|-----------------------------------------|-----------------------------------| -| GET | `/api/v1/health` | Liveness probe | -| POST | `/api/v1/chat` | Stream a reply as SSE | -| GET | `/api/v1/conversations/{id}` | Read stored history | -| DELETE | `/api/v1/conversations/{id}` | Forget a conversation | - -`POST /api/v1/chat` takes `{"message": "...", "conversation_id": "..."}` — -omit `conversation_id` to start a new conversation and read it back from the -final `done` event. +| GET | `/health` | Liveness probe, `{"status": "ok"}` | +| POST | `/api/v1/chat` | Stream a reply (`text/event-stream`; 404 unknown id, 409 conversation full) | +| GET | `/api/v1/conversations/{id}` | Read stored history (404 if unknown) | +| DELETE | `/api/v1/conversations/{id}` | Forget a conversation (204, 404 if unknown) | + +`POST /api/v1/chat` takes `{"message": "...", "conversation_id": "..."}`. +Omit `conversation_id` to start a new conversation; the server issues a +random id and sends it in the final `done` event. Send that id back to +continue. An id the server never issued gets `404`, so a client cannot choose +an id. Without authentication the id acts as a password for the +conversation: keep it private. + +If the model call fails mid-stream, the client gets a generic `error` event +and the exception is written to the `app.chat` logger. Upstream failures such +as an invalid API key or an Anthropic rate limit arrive the same way, because +the `200` status line has already been sent. That is why `POST /chat` +documents no 401 or 429 until you implement the hooks described under +[Extension points](#extension-points). + +### Conversation limits + +The in-memory store keeps at most `MAX_CONVERSATIONS` conversations (default +1000). When a new conversation would exceed that limit, the store evicts the +least recently used one, which is the conversation read or continued longest +ago. An evicted id then gets `404`, like an id the server never issued. + +A conversation that already holds `MAX_MESSAGES_PER_CONVERSATION` messages +(default 100) is closed. Continuing it returns `409` with a `detail` asking +the client to start a new conversation. The server rejects the request +instead of dropping old turns, so the model's memory never changes silently +and no `tool_result` is ever separated from its `tool_use`. The check runs +before each turn, and one turn can add up to `2 * MAX_TOOL_ITERATIONS + 1` +messages. A stored conversation can therefore exceed the limit by that many. ### Stream events @@ -162,7 +195,10 @@ To add one, append a schema to `TOOL_SCHEMAS` and register the handler in instruction Claude gets about when to reach for it, so write it carefully. Handlers should return a string and should turn their own failures into a readable message rather than raising — the loop feeds that text straight back -to the model. +to the model. As a safety net, `run_tool` turns any exception a handler still +raises into a generic error message and logs the traceback to `app.tools`. +The calculator bounds its input: at most 200 characters, limited nesting, +exponents up to 1000 and values up to 1e100. ## Running tests @@ -184,8 +220,13 @@ free. `ChatAgent.stream`: fetch context before the first request and prepend it to the system prompt, or expose your index as one more tool so the model decides when to search. -- **Auth and rate limiting** — `POST /chat` is unauthenticated as shipped. - Put a dependency on the router before exposing it publicly. +- **Auth and rate limiting** — `POST /chat` is unauthenticated and unlimited + as shipped, so anyone who reaches the server can spend your API credits. + `src/app/api/deps.py` has two no-op hooks: `authorize_chat` runs before + every chat and conversation route, `limit_chat_rate` before `POST /chat`. + Implement them (raise 401/403 or 429) before exposing the API, and add + those codes to the routes' `responses=` (`error_responses(401, 429)` from + `src/app/core/responses.py`) so they appear in the OpenAPI schema. ## Project Origin diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/pyproject.toml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/pyproject.toml-tpl index a1722da..cc97189 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/pyproject.toml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/pyproject.toml-tpl @@ -73,4 +73,5 @@ python_files = ["test_*.py"] python_classes = ["Test*"] python_functions = ["test_*"] asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" addopts = "-v --tb=short" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/scripts/chat.sh-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/scripts/chat.sh-tpl index a35db3d..8c191e0 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/scripts/chat.sh-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/scripts/chat.sh-tpl @@ -5,6 +5,11 @@ set -e # Send one message to a running dev server and print the SSE stream. MESSAGE="${1:-What is 12 * 34?}" +# Build the request body with a real JSON encoder so quotes, backslashes and +# newlines in the message cannot break the JSON. +PYTHON="$(command -v python3 || command -v python)" +BODY="$("$PYTHON" -c 'import json, sys; print(json.dumps({"message": sys.argv[1]}))' "$MESSAGE")" + curl -N -X POST http://127.0.0.1:8000/api/v1/chat \ -H "Content-Type: application/json" \ - -d "{\"message\": \"${MESSAGE}\"}" + --data-binary "$BODY" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/chat.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/chat.py-tpl index ba98b06..176058e 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/chat.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/chat.py-tpl @@ -4,19 +4,108 @@ # The response is Server-Sent Events: each agent event is one SSE message # whose ``event`` field is the event type and whose ``data`` is the JSON # envelope, so a browser can attach a listener per type. +# +# Conversation ids are created by the server only: a new conversation gets a +# random 256-bit id (``secrets.token_urlsafe(32)``) that the client receives +# in the final ``done`` event. A request naming an id the server never issued +# is answered with 404 instead of starting a conversation under that name, so +# no client can pick an id another client might use. Without authentication +# the id works like a password: whoever holds it can read, continue and +# delete that conversation, and nobody can guess it. Wire ``authorize_chat`` +# (``src/app/api/deps.py``) to tie conversations to users. +# +# A conversation holding ``MAX_MESSAGES_PER_CONVERSATION`` messages or more +# is closed: continuing it is 409 and the client starts a new conversation. +# Rejecting was chosen over silently dropping old turns: trimming would +# change what the model remembers without telling anyone, and it must never +# split a ``tool_use`` from its ``tool_result`` or leave the history starting +# with an assistant turn, which the Messages API rejects. The check runs +# before a turn starts and one turn adds up to ``2 * MAX_TOOL_ITERATIONS + 1`` +# messages, so a stored conversation can exceed the limit by at most that. +# +# 401 and 429 are not declared here: the shipped ``authorize_chat`` and +# ``limit_chat_rate`` hooks never raise, and an upstream LLM failure +# (invalid key, rate limit) happens after the stream has started, so it +# arrives as an ``error`` event, not as a status code. Add them to +# ``responses=`` when you implement the hooks. # -------------------------------------------------------------------------- -import uuid +import logging +import secrets from collections.abc import AsyncIterator +from typing import Annotated -from fastapi import APIRouter, Depends, HTTPException, status -from sse_starlette.sse import EventSourceResponse, ServerSentEvent +from fastapi import APIRouter, Depends, HTTPException, Path, status +from sse_starlette import EventSourceResponse, ServerSentEvent -from src.app.api.deps import get_agent, get_store +from src.app.api.deps import AgentDep, StoreDep, authorize_chat, limit_chat_rate +from src.app.core.config import settings +from src.app.core.responses import error_responses from src.app.llm.agent import ChatAgent from src.app.memory.base import ConversationStore -from src.app.schemas.chat import AgentEvent, ChatRequest, ConversationHistory +from src.app.schemas.chat import ( + CONVERSATION_ID_MAX_LENGTH, + AgentEvent, + ChatRequest, + ConversationHistory, +) -router = APIRouter(tags=["chat"]) +logger = logging.getLogger("app.chat") + +router = APIRouter(tags=["chat"], dependencies=[Depends(authorize_chat)]) + +ConversationId = Annotated[ + str, Path(min_length=1, max_length=CONVERSATION_ID_MAX_LENGTH) +] + +#: What a client sees when the agent fails mid-stream. The exception itself +#: goes to the server log: upstream error text can carry request ids, quota +#: details or other internals that are not the caller's business. +STREAM_ERROR_DETAIL = "The assistant failed to answer. Please try again later." + +#: The 409 detail for a conversation that reached its message limit. +CONVERSATION_FULL_DETAIL = ( + "Conversation has reached its message limit; start a new conversation." +) + +_SSE_RESPONSE = { + "description": ( + "A stream of Server-Sent Events. Each event's `event` field is the " + "AgentEvent type and its `data` field is the AgentEvent as JSON. " + "The last event is `done` (with the conversation id) or `error`." + ), + "content": { + "text/event-stream": { + "schema": {"type": "string"}, + } + }, +} + + +def new_conversation_id() -> str: + return secrets.token_urlsafe(32) + + +async def _require_conversation(store: ConversationStore, conversation_id: str) -> None: + if not await store.get(conversation_id): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail="Conversation not found" + ) + + +async def _require_open_conversation( + store: ConversationStore, conversation_id: str +) -> None: + """404 for an unknown id, 409 once the conversation reached its limit.""" + history = await store.get(conversation_id) + if not history: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail="Conversation not found" + ) + if len(history) >= settings.MAX_MESSAGES_PER_CONVERSATION: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=CONVERSATION_FULL_DETAIL, + ) async def _event_source( @@ -25,25 +114,44 @@ async def _event_source( try: async for event in agent.stream(conversation_id, message): yield ServerSentEvent(event=event.type, data=event.model_dump_json()) - except Exception as exc: # noqa: BLE001 + except Exception: # The status line is long gone by now, so a failure mid-stream can # only be reported as another event. - failure = AgentEvent(type="error", detail=str(exc)) + logger.exception("chat stream failed") + failure = AgentEvent(type="error", detail=STREAM_ERROR_DETAIL) yield ServerSentEvent(event="error", data=failure.model_dump_json()) -@router.post("/chat") +@router.post( + "/chat", + response_class=EventSourceResponse, + responses={200: _SSE_RESPONSE, **error_responses(404, 409)}, + dependencies=[Depends(limit_chat_rate)], +) async def chat( - payload: ChatRequest, agent: ChatAgent = Depends(get_agent) + payload: ChatRequest, agent: AgentDep, store: StoreDep ) -> EventSourceResponse: - """Stream the assistant's reply to one user message.""" - conversation_id = payload.conversation_id or uuid.uuid4().hex + """Stream the assistant's reply to one user message. + + Omit ``conversation_id`` to start a conversation; send back the id from + the ``done`` event to continue it. An id the server did not issue (or + one the store has since evicted) is 404; a conversation that reached + ``MAX_MESSAGES_PER_CONVERSATION`` messages is 409. + """ + if payload.conversation_id is None: + conversation_id = new_conversation_id() + else: + conversation_id = payload.conversation_id + await _require_open_conversation(store, conversation_id) return EventSourceResponse(_event_source(agent, conversation_id, payload.message)) -@router.get("/conversations/{conversation_id}", response_model=ConversationHistory) +@router.get( + "/conversations/{conversation_id}", + responses=error_responses(404), +) async def read_conversation( - conversation_id: str, store: ConversationStore = Depends(get_store) + conversation_id: ConversationId, store: StoreDep ) -> ConversationHistory: messages = await store.get(conversation_id) if not messages: @@ -54,9 +162,10 @@ async def read_conversation( @router.delete( - "/conversations/{conversation_id}", status_code=status.HTTP_204_NO_CONTENT + "/conversations/{conversation_id}", + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(404), ) -async def delete_conversation( - conversation_id: str, store: ConversationStore = Depends(get_store) -) -> None: +async def delete_conversation(conversation_id: ConversationId, store: StoreDep) -> None: + await _require_conversation(store, conversation_id) await store.delete(conversation_id) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/deps.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/deps.py-tpl index 5cc126c..aa85d18 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/deps.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/deps.py-tpl @@ -4,8 +4,15 @@ # The store is a process-wide singleton; the agent is built per request from # it. Both are plain functions so tests can override them through # ``app.dependency_overrides``. +# +# ``authorize_chat`` and ``limit_chat_rate`` are the hook points for access +# control and rate limiting. They do nothing by default: as shipped, anyone +# who can reach the server can spend your LLM credits. Fill them in (or +# replace them through ``app.dependency_overrides``) before exposing the API. # -------------------------------------------------------------------------- -from fastapi import Depends +from typing import Annotated + +from fastapi import Depends, Request from src.app.llm.agent import ChatAgent from src.app.llm.client import build_client @@ -19,5 +26,34 @@ def get_store() -> ConversationStore: return _store -def get_agent(store: ConversationStore = Depends(get_store)) -> ChatAgent: +StoreDep = Annotated[ConversationStore, Depends(get_store)] + + +def get_agent(store: StoreDep) -> ChatAgent: return ChatAgent(build_client(), store) + + +AgentDep = Annotated[ChatAgent, Depends(get_agent)] + + +async def authorize_chat(request: Request) -> None: + """Hook point: decide who may use the chat and conversation endpoints. + + Runs before every route in ``src/app/api/chat.py``. The default lets + every request through; it is a placeholder, not a security control. + Typical implementations verify an API key or a bearer token here and + raise ``HTTPException(401, headers={"WWW-Authenticate": "Bearer"})`` when + it is missing or invalid (or 403 when the caller may not chat). Once + callers are identified, store their id with each conversation and check + it in ``read_conversation`` / ``delete_conversation`` as well. + """ + + +async def limit_chat_rate(request: Request) -> None: + """Hook point: rate limiting for ``POST /chat``, the endpoint that costs money. + + The default does not limit anything. Count requests per caller (the + identity ``authorize_chat`` established, or ``request.client.host``) in + Redis or a gateway, and raise ``HTTPException(429)`` with a + ``Retry-After`` header once a caller exceeds its budget. + """ diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/health.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/health.py-tpl index ff4139e..b5c5ccf 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/health.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/health.py-tpl @@ -1,5 +1,8 @@ # -------------------------------------------------------------------------- # Health endpoint — small, side-effect-free probe for liveness checks. +# +# Mounted at the application root (``GET /health``), outside the versioned +# API prefix, and never behind ``authorize_chat``. # -------------------------------------------------------------------------- from fastapi import APIRouter diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/router.py-tpl index 7868d20..f4d8620 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/router.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/api/router.py-tpl @@ -1,13 +1,13 @@ # -------------------------------------------------------------------------- -# Top-level API router — aggregates the health probe with the chat endpoints. +# Top-level API router, mounted under ``settings.API_V1_PREFIX`` by +# ``src/app/main.py``. The health probe is mounted at the root instead. # -------------------------------------------------------------------------- from fastapi import APIRouter -from src.app.api import chat, health +from src.app.api import chat # fastkit:imports api_router = APIRouter() -api_router.include_router(health.router) api_router.include_router(chat.router) # fastkit:routes diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/core/config.py-tpl index f47bcfc..9d0d721 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/core/config.py-tpl @@ -5,6 +5,7 @@ # local ``.env``) and passed to the Anthropic client at construction time. # -------------------------------------------------------------------------- import secrets +import warnings from typing import Annotated, Any, List, Literal, Union from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator @@ -19,17 +20,32 @@ def _parse_cors(v: Any) -> Union[List[str], str]: raise ValueError(v) -#: Example SECRET_KEY values fastkit templates have shipped in ``.env`` -#: files. They are public, so a production deployment must never sign -#: anything with one of them. +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. KNOWN_EXAMPLE_SECRET_KEYS = frozenset( { "changethis", "changethis-please-generate-a-real-32-byte-key", "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + "your-secret-key-here", + "change-me-in-production", + "your-mcp-api-key-here", } ) +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = 32 + +_GENERATE_KEY_HINT = ( + "Generate one with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) + class Settings(BaseSettings): """Centralized configuration for the application.""" @@ -42,9 +58,11 @@ class Settings(BaseSettings): PROJECT_NAME: str = "" ENVIRONMENT: Literal["development", "staging", "production"] = "development" - # Not read by the shipped code; reserved for signing features you add. - # fastkit writes a unique value to .env, and production refuses the - # public example values (see the validator below). + # The shipped code signs nothing with SECRET_KEY yet, but authentication + # you add later (including the JWT and Session options of fastkit init) + # signs tokens or cookies with it, so treat it as a production secret. + # fastkit writes a unique value to .env; staging and production refuse a + # missing, public or short key (see _check_secret_key below). SECRET_KEY: str = secrets.token_urlsafe(32) API_V1_PREFIX: str = "/api/v1" @@ -69,28 +87,65 @@ class Settings(BaseSettings): # spend an unbounded number of API calls. MAX_TOOL_ITERATIONS: int = 5 + # --- Conversation memory --------------------------------------------- + # The bundled in-memory store keeps at most MAX_CONVERSATIONS + # conversations and evicts the least recently used one (read or written + # longest ago) to make room for a new one. A conversation that already + # holds MAX_MESSAGES_PER_CONVERSATION messages is closed: POST /chat + # answers 409 and the client starts a new conversation. + MAX_CONVERSATIONS: int = 1000 + MAX_MESSAGES_PER_CONVERSATION: int = 100 + + # Comma-separated list or JSON list. Each origin is a full URL such as + # http://localhost:3000, or "*" for any origin; "*" never goes together + # with credentials (browsers refuse that), so main.py turns them off. BACKEND_CORS_ORIGINS: Annotated[ - Union[List[AnyUrl], str], BeforeValidator(_parse_cors) + Union[List[Union[Literal["*"], AnyUrl]], str], BeforeValidator(_parse_cors) ] = [] @computed_field # type: ignore[prop-decorator] @property def all_cors_origins(self) -> List[str]: - return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins @model_validator(mode="after") - def _reject_example_secret_key_in_production(self) -> "Settings": - if ( - self.ENVIRONMENT == "production" - and self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS - ): + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) + return self + env = f"ENVIRONMENT={self.ENVIRONMENT}" + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT + ) + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: raise ValueError( - "SECRET_KEY is set to a public example value while " - "ENVIRONMENT=production. Generate a real key with " - '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' - "and set it as the SECRET_KEY environment variable (or in .env)." + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT ) return self -settings = Settings() # type: ignore[call-arg] +settings = Settings() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/core/responses.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/core/responses.py-tpl new file mode 100644 index 0000000..bffc8c1 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/core/responses.py-tpl @@ -0,0 +1,40 @@ +# -------------------------------------------------------------------------- +# OpenAPI error responses shared by the routers. +# +# FastAPI documents 2xx and 422 on its own. Routes that can also answer 401, +# 404, 409, ... declare it with ``responses=error_responses(404)`` so clients +# see every status code and the ``{"detail": "..."}`` body in the schema. +# -------------------------------------------------------------------------- +from http import HTTPStatus +from typing import Any + +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + """Body FastAPI sends for an ``HTTPException``.""" + + detail: str + + +def error_responses(*status_codes: int) -> dict[int | str, dict[str, Any]]: + """Build ``responses=`` entries that document the given error codes. + + A 401 entry also documents the ``WWW-Authenticate`` header every 401 + response carries. + """ + responses: dict[int | str, dict[str, Any]] = {} + for code in status_codes: + entry: dict[str, Any] = { + "model": ErrorDetail, + "description": HTTPStatus(code).phrase, + } + if code == HTTPStatus.UNAUTHORIZED: + entry["headers"] = { + "WWW-Authenticate": { + "description": "Authentication scheme to use (Bearer).", + "schema": {"type": "string"}, + } + } + responses[code] = entry + return responses diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/llm/agent.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/llm/agent.py-tpl index d829a3c..4643513 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/llm/agent.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/llm/agent.py-tpl @@ -8,9 +8,10 @@ # -------------------------------------------------------------------------- import logging from collections.abc import AsyncIterator -from typing import Any +from typing import Any, cast from anthropic import AsyncAnthropic +from anthropic.types import MessageParam, ToolParam, ToolUseBlock from src.app.core.config import settings from src.app.llm.tools import TOOL_SCHEMAS, run_tool @@ -60,8 +61,8 @@ class ChatAgent: model=self._model, max_tokens=self._max_tokens, system=self._system_prompt, - messages=history + turn, - tools=TOOL_SCHEMAS, + messages=cast(list[MessageParam], history + turn), + tools=cast(list[ToolParam], TOOL_SCHEMAS), ) as stream: async for text in stream.text_stream: yield AgentEvent(type="token", text=text) @@ -98,7 +99,7 @@ class ChatAgent: tool_results: list[dict[str, Any]] = [] for block in final.content: - if getattr(block, "type", None) != "tool_use": + if not isinstance(block, ToolUseBlock): continue arguments: dict[str, Any] = dict(block.input or {}) yield AgentEvent( @@ -122,10 +123,12 @@ class ChatAgent: # Fell out of the loop: Claude kept asking for tools. await self._store.append(conversation_id, *turn) + # Only a prefix of the id is logged: without authentication the id is + # what grants access to the conversation. logger.warning( - "tool loop hit the iteration cap (%d) for conversation %s", + "tool loop hit the iteration cap (%d) for conversation %s...", self._max_tool_iterations, - conversation_id, + conversation_id[:8], ) yield AgentEvent( type="error", diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/llm/tools.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/llm/tools.py-tpl index e8a8f47..76f0c9a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/llm/tools.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/llm/tools.py-tpl @@ -6,13 +6,32 @@ # the two halves together so adding a tool is a single edit. # -------------------------------------------------------------------------- import ast +import inspect +import logging +import math import operator from datetime import datetime, timezone from typing import Any, Callable from zoneinfo import ZoneInfo, ZoneInfoNotFoundError +logger = logging.getLogger("app.tools") + ToolHandler = Callable[..., str] +# Limits for the calculator. The expression comes from the model, which may +# be repeating text a user typed, so it is bounded before it is parsed and +# every operation is checked before it runs: a deeply nested or oversized +# expression is rejected instead of exhausting memory or the stack. +MAX_EXPRESSION_LENGTH = 200 +#: Depth and node limits keep the recursive evaluator far from Python's +#: recursion limit even if MAX_EXPRESSION_LENGTH is raised. +MAX_EXPRESSION_DEPTH = 128 +MAX_EXPRESSION_NODES = 512 +#: Largest exponent ``**`` accepts, checked before the power is computed. +MAX_EXPONENT = 1000 +#: Largest magnitude an operand or a result may have. +MAX_MAGNITUDE = 1e100 + _BINARY_OPERATORS: dict[type[ast.operator], Callable[[Any, Any], Any]] = { ast.Add: operator.add, ast.Sub: operator.sub, @@ -28,20 +47,51 @@ _UNARY_OPERATORS: dict[type[ast.unaryop], Callable[[Any], Any]] = { } +class _ExpressionTooLarge(ValueError): + """The expression or one of its values exceeds the calculator's limits.""" + + +def _check_size(tree: ast.AST) -> None: + """Reject trees that are too deep or too large, without recursing.""" + pending: list[tuple[ast.AST, int]] = [(tree, 1)] + nodes = 0 + while pending: + node, depth = pending.pop() + nodes += 1 + if depth > MAX_EXPRESSION_DEPTH or nodes > MAX_EXPRESSION_NODES: + raise _ExpressionTooLarge + pending.extend((child, depth + 1) for child in ast.iter_child_nodes(node)) + + +def _bounded(value: float) -> float: + if not math.isfinite(value) or abs(value) > MAX_MAGNITUDE: + raise _ExpressionTooLarge + return value + + def _evaluate(node: ast.AST) -> float: - """Walk a parsed expression, allowing arithmetic and nothing else.""" + """Walk a parsed expression, allowing arithmetic and nothing else. + + Every value is a float, so integer arithmetic cannot grow without bound; + exponents are checked before ``**`` runs and every intermediate result + must stay finite and within ``MAX_MAGNITUDE``. + """ if isinstance(node, ast.Expression): return _evaluate(node.body) - if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)): - return float(node.value) + if ( + isinstance(node, ast.Constant) + and isinstance(node.value, (int, float)) + and not isinstance(node.value, bool) + ): + return _bounded(float(node.value)) if isinstance(node, ast.BinOp) and type(node.op) in _BINARY_OPERATORS: - return float( - _BINARY_OPERATORS[type(node.op)]( - _evaluate(node.left), _evaluate(node.right) - ) - ) + left = _evaluate(node.left) + right = _evaluate(node.right) + if isinstance(node.op, ast.Pow) and abs(right) > MAX_EXPONENT: + raise _ExpressionTooLarge + return _bounded(float(_BINARY_OPERATORS[type(node.op)](left, right))) if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY_OPERATORS: - return float(_UNARY_OPERATORS[type(node.op)](_evaluate(node.operand))) + return _bounded(float(_UNARY_OPERATORS[type(node.op)](_evaluate(node.operand)))) raise ValueError("unsupported expression") @@ -50,13 +100,24 @@ def calculator(expression: str) -> str: Parsing to an AST and whitelisting node types keeps this away from ``eval``: names, calls, attribute access and imports are all rejected. + Length, nesting, node count, exponents and magnitudes are bounded (see + the ``MAX_*`` constants above), so hostile input gets an error message + instead of a ``MemoryError`` or ``RecursionError``. """ + if len(expression) > MAX_EXPRESSION_LENGTH: + return ( + "Error: expression is too long " + f"(at most {MAX_EXPRESSION_LENGTH} characters)." + ) try: parsed = ast.parse(expression, mode="eval") + _check_size(parsed) result = _evaluate(parsed) except ZeroDivisionError: return "Error: division by zero." - except (SyntaxError, ValueError, TypeError, OverflowError): + except (_ExpressionTooLarge, OverflowError, RecursionError, MemoryError): + return "Error: expression or result is too large to evaluate." + except (SyntaxError, ValueError, TypeError): return f"Error: {expression!r} is not a supported arithmetic expression." # Render whole numbers without a trailing ".0". return str(int(result)) if result.is_integer() else str(result) @@ -121,11 +182,21 @@ TOOL_HANDLERS: dict[str, ToolHandler] = { def run_tool(name: str, arguments: dict[str, Any]) -> str: - """Dispatch a tool call, turning every failure into a message Claude can read.""" + """Dispatch a tool call, turning every failure into a message Claude can read. + + Never raises. A handler that fails unexpectedly is logged with its + traceback and reported to the model as a generic error, so exception + text (paths, internals) never reaches the model or the client. + """ handler = TOOL_HANDLERS.get(name) if handler is None: return f"Error: unknown tool {name!r}." try: - return handler(**arguments) + inspect.signature(handler).bind(**arguments) except TypeError as exc: return f"Error: bad arguments for {name!r} ({exc})." + try: + return handler(**arguments) + except Exception: + logger.exception("tool %r failed", name) + return f"Error: the {name!r} tool failed." diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/main.py-tpl index 6e10358..977fcfe 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/main.py-tpl @@ -8,6 +8,7 @@ from contextlib import asynccontextmanager from fastapi import FastAPI from starlette.middleware.cors import CORSMiddleware +from src.app.api import health from src.app.api.router import api_router from src.app.core.config import settings @@ -44,10 +45,12 @@ if settings.all_cors_origins: app.add_middleware( CORSMiddleware, allow_origins=settings.all_cors_origins, - allow_credentials=True, + # Browsers refuse credentials with the "*" wildcard; never send both. + allow_credentials="*" not in settings.all_cors_origins, allow_methods=["*"], allow_headers=["*"], ) +app.include_router(health.router) app.include_router(api_router, prefix=settings.API_V1_PREFIX) # fastkit:routes diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/memory/base.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/memory/base.py-tpl index e13e5f8..56a1d4c 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/memory/base.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/memory/base.py-tpl @@ -16,7 +16,12 @@ class ConversationStore(ABC): @abstractmethod async def get(self, conversation_id: str) -> list[Message]: - """Return the stored messages, or an empty list for an unknown id.""" + """Return the stored messages, or an empty list for an unknown id. + + Implementations may bound their size and forget old conversations + (the bundled store evicts the least recently used one); a forgotten + id is then reported like an unknown one. + """ @abstractmethod async def append(self, conversation_id: str, *messages: Message) -> None: diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/memory/in_memory.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/memory/in_memory.py-tpl index a972fcc..a576103 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/memory/in_memory.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/memory/in_memory.py-tpl @@ -4,28 +4,53 @@ # Good enough for a single-process dev server and for tests. It does not # survive a restart and is not shared between workers — swap in a Redis or # database implementation of ``ConversationStore`` before scaling out. +# +# Memory is bounded by conversation count: the store holds at most +# ``MAX_CONVERSATIONS`` conversations and, when a new one would exceed that, +# evicts the least recently used one (the conversation read or appended to +# longest ago). An evicted id behaves like an unknown one, so the API +# answers 404 for it. The length of each conversation is capped by the chat +# route (``MAX_MESSAGES_PER_CONVERSATION``, answered with 409). # -------------------------------------------------------------------------- import asyncio -from collections import defaultdict +from collections import OrderedDict +from src.app.core.config import settings from src.app.memory.base import ConversationStore, Message class InMemoryConversationStore(ConversationStore): - """Conversation history held in a dict, guarded by a lock.""" + """Conversation history in an LRU-ordered dict, guarded by a lock.""" - def __init__(self) -> None: - self._conversations: dict[str, list[Message]] = defaultdict(list) + def __init__(self, *, max_conversations: int | None = None) -> None: + limit = ( + settings.MAX_CONVERSATIONS + if max_conversations is None + else max_conversations + ) + if limit < 1: + raise ValueError("max_conversations must be at least 1") + self._max_conversations = limit + # Oldest use first: the first key is the next one to be evicted. + self._conversations: OrderedDict[str, list[Message]] = OrderedDict() self._lock = asyncio.Lock() async def get(self, conversation_id: str) -> list[Message]: async with self._lock: + messages = self._conversations.get(conversation_id) + if messages is None: + return [] + self._conversations.move_to_end(conversation_id) # Copy so callers cannot mutate stored history by accident. - return list(self._conversations.get(conversation_id, [])) + return list(messages) async def append(self, conversation_id: str, *messages: Message) -> None: async with self._lock: - self._conversations[conversation_id].extend(messages) + stored = self._conversations.setdefault(conversation_id, []) + stored.extend(messages) + self._conversations.move_to_end(conversation_id) + while len(self._conversations) > self._max_conversations: + self._conversations.popitem(last=False) async def delete(self, conversation_id: str) -> None: async with self._lock: diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/schemas/chat.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/schemas/chat.py-tpl index 58c5f8d..e9d42b1 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/schemas/chat.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/src/app/schemas/chat.py-tpl @@ -7,13 +7,19 @@ from pydantic import BaseModel, Field EventType = Literal["token", "tool_use", "tool_result", "usage", "done", "error"] +#: Server-issued ids are 43 characters; anything far longer is not one. +CONVERSATION_ID_MAX_LENGTH = 128 + class ChatRequest(BaseModel): """A single user turn.""" message: str = Field(min_length=1, max_length=8000) - # Omit to start a new conversation; pass the id back to continue one. - conversation_id: str | None = None + # Omit to start a new conversation; pass back the id the server sent in + # the ``done`` event to continue one. Ids are never chosen by the client. + conversation_id: str | None = Field( + default=None, min_length=1, max_length=CONVERSATION_ID_MAX_LENGTH + ) class AgentEvent(BaseModel): diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/conftest.py-tpl index 4b5d051..2a28c42 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/conftest.py-tpl @@ -14,6 +14,7 @@ import pytest import pytest_asyncio from anthropic.types import Message, TextBlock, ToolUseBlock, Usage from httpx import ASGITransport, AsyncClient + from src.app.api.deps import get_agent, get_store from src.app.llm.agent import ChatAgent from src.app.main import app diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_chat.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_chat.py-tpl index 19b439f..1b5f5d6 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_chat.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_chat.py-tpl @@ -2,13 +2,22 @@ # Chat endpoint — the SSE streaming path and the tool-call loop, driven by a # scripted fake Anthropic client (no network, no API key). # -------------------------------------------------------------------------- +import logging from typing import Any -from src.app.core.config import settings +import pytest +from fastapi import HTTPException +from src.app.api.chat import CONVERSATION_FULL_DETAIL, STREAM_ERROR_DETAIL +from src.app.api.deps import authorize_chat, get_agent, get_store, limit_chat_rate +from src.app.core.config import settings +from src.app.llm.agent import ChatAgent +from src.app.main import app +from src.app.memory.in_memory import InMemoryConversationStore from tests.conftest import FakeAnthropic, parse_sse, text_turn, tool_turn CHAT_URL = f"{settings.API_V1_PREFIX}/chat" +CONVERSATIONS_URL = f"{settings.API_V1_PREFIX}/conversations" async def test_chat_streams_tokens_then_done(make_client: Any) -> None: @@ -86,14 +95,20 @@ async def test_tool_loop_stops_at_the_iteration_cap(make_client: Any) -> None: assert len(fake.calls) == settings.MAX_TOOL_ITERATIONS -async def test_client_failure_becomes_an_error_event(make_client: Any) -> None: - fake = FakeAnthropic(error=RuntimeError("upstream is down")) +async def test_client_failure_becomes_a_generic_error_event( + make_client: Any, caplog: pytest.LogCaptureFixture +) -> None: + fake = FakeAnthropic(error=RuntimeError("upstream is down: key sk-123")) - async with make_client(fake) as client: - response = await client.post(CHAT_URL, json={"message": "hi"}) + with caplog.at_level(logging.ERROR, logger="app.chat"): + async with make_client(fake) as client: + response = await client.post(CHAT_URL, json={"message": "hi"}) events = parse_sse(response.text) - assert events == [{**events[0], "type": "error", "detail": "upstream is down"}] + assert events == [{**events[0], "type": "error", "detail": STREAM_ERROR_DETAIL}] + assert "sk-123" not in response.text + # The real cause is logged for the operator. + assert "upstream is down" in caplog.text async def test_history_is_stored_and_replayed(make_client: Any) -> None: @@ -127,11 +142,47 @@ async def test_history_is_stored_and_replayed(make_client: Any) -> None: async def test_unknown_conversation_returns_404(make_client: Any) -> None: async with make_client(FakeAnthropic()) as client: - response = await client.get( - f"{settings.API_V1_PREFIX}/conversations/does-not-exist" + response = await client.get(f"{CONVERSATIONS_URL}/does-not-exist") + + assert response.status_code == 404 + assert response.json() == {"detail": "Conversation not found"} + + +async def test_conversation_ids_are_issued_by_the_server(make_client: Any) -> None: + fake = FakeAnthropic([text_turn("a"), text_turn("b")]) + + async with make_client(fake) as client: + first = await client.post(CHAT_URL, json={"message": "one"}) + second = await client.post(CHAT_URL, json={"message": "two"}) + + ids = [parse_sse(r.text)[-1]["conversation_id"] for r in (first, second)] + assert ids[0] != ids[1] + assert all(len(conversation_id) >= 43 for conversation_id in ids) + + +async def test_client_chosen_conversation_id_is_rejected(make_client: Any) -> None: + """A client cannot open a conversation under a name another client might use.""" + fake = FakeAnthropic([text_turn("never sent")]) + + async with make_client(fake) as client: + response = await client.post( + CHAT_URL, json={"message": "hi", "conversation_id": "shared-name"} ) + history = await client.get(f"{CONVERSATIONS_URL}/shared-name") assert response.status_code == 404 + assert response.json() == {"detail": "Conversation not found"} + assert history.status_code == 404 + assert fake.calls == [] + + +async def test_overlong_conversation_id_is_rejected(make_client: Any) -> None: + async with make_client(FakeAnthropic()) as client: + response = await client.post( + CHAT_URL, json={"message": "hi", "conversation_id": "x" * 129} + ) + + assert response.status_code == 422 async def test_delete_conversation(make_client: Any) -> None: @@ -141,10 +192,9 @@ async def test_delete_conversation(make_client: Any) -> None: first = await client.post(CHAT_URL, json={"message": "one"}) conversation_id = parse_sse(first.text)[-1]["conversation_id"] - deleted = await client.delete( - f"{settings.API_V1_PREFIX}/conversations/{conversation_id}" - ) + deleted = await client.delete(f"{CONVERSATIONS_URL}/{conversation_id}") assert deleted.status_code == 204 + assert deleted.content == b"" follow_up = await client.get( f"{settings.API_V1_PREFIX}/conversations/{conversation_id}" @@ -153,8 +203,108 @@ async def test_delete_conversation(make_client: Any) -> None: assert follow_up.status_code == 404 +async def test_delete_unknown_conversation_returns_404(make_client: Any) -> None: + async with make_client(FakeAnthropic()) as client: + response = await client.delete(f"{CONVERSATIONS_URL}/does-not-exist") + + assert response.status_code == 404 + + +async def test_openapi_declares_the_event_stream(make_client: Any) -> None: + async with make_client(FakeAnthropic()) as client: + schema = (await client.get("/openapi.json")).json() + + chat = schema["paths"][CHAT_URL]["post"] + assert list(chat["responses"]["200"]["content"]) == ["text/event-stream"] + assert "404" in chat["responses"] + assert "409" in chat["responses"] + conversation = schema["paths"][f"{CONVERSATIONS_URL}/{{conversation_id}}"] + assert "404" in conversation["get"]["responses"] + assert "404" in conversation["delete"]["responses"] + + +async def test_authorize_chat_hook_guards_every_chat_route(make_client: Any) -> None: + def deny() -> None: + raise HTTPException(401, "Not authenticated", {"WWW-Authenticate": "Bearer"}) + + fake = FakeAnthropic([text_turn("never sent")]) + async with make_client(fake) as client: + app.dependency_overrides[authorize_chat] = deny + chat = await client.post(CHAT_URL, json={"message": "hi"}) + history = await client.get(f"{CONVERSATIONS_URL}/any") + deleted = await client.delete(f"{CONVERSATIONS_URL}/any") + health = await client.get("/health") + + assert [chat.status_code, history.status_code, deleted.status_code] == [401] * 3 + assert health.status_code == 200 + assert fake.calls == [] + + +async def test_rate_limit_hook_guards_chat_only(make_client: Any) -> None: + def too_many() -> None: + raise HTTPException(429, "Too many requests", {"Retry-After": "60"}) + + fake = FakeAnthropic([text_turn("never sent")]) + async with make_client(fake) as client: + app.dependency_overrides[limit_chat_rate] = too_many + chat = await client.post(CHAT_URL, json={"message": "hi"}) + history = await client.get(f"{CONVERSATIONS_URL}/any") + + assert chat.status_code == 429 + assert history.status_code == 404 + assert fake.calls == [] + + async def test_empty_message_is_rejected(make_client: Any) -> None: async with make_client(FakeAnthropic()) as client: response = await client.post(CHAT_URL, json={"message": ""}) assert response.status_code == 422 + + +async def test_full_conversation_is_closed_with_409( + make_client: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(settings, "MAX_MESSAGES_PER_CONVERSATION", 4) + fake = FakeAnthropic([text_turn("first"), text_turn("second"), text_turn("x")]) + + async with make_client(fake) as client: + first = await client.post(CHAT_URL, json={"message": "one"}) + conversation_id = parse_sse(first.text)[-1]["conversation_id"] + body = {"message": "more", "conversation_id": conversation_id} + + # Two stored messages: still under the limit of four. + second = await client.post(CHAT_URL, json=body) + # Four stored messages: the conversation is full. + third = await client.post(CHAT_URL, json=body) + history = await client.get(f"{CONVERSATIONS_URL}/{conversation_id}") + fresh = await client.post(CHAT_URL, json={"message": "new start"}) + + assert second.status_code == 200 + assert third.status_code == 409 + assert third.json() == {"detail": CONVERSATION_FULL_DETAIL} + # The rejected request never reached the model and stored nothing. + assert len(fake.calls) == 3 + assert len(history.json()["messages"]) == 4 + # Starting a new conversation still works. + assert fresh.status_code == 200 + assert parse_sse(fresh.text)[-1]["type"] == "done" + + +async def test_evicted_conversation_returns_404(make_client: Any) -> None: + small = InMemoryConversationStore(max_conversations=1) + fake = FakeAnthropic([text_turn("a"), text_turn("b")]) + + async with make_client(fake) as client: + app.dependency_overrides[get_store] = lambda: small + agent = ChatAgent(fake, small) # type: ignore[arg-type] + app.dependency_overrides[get_agent] = lambda: agent + first = await client.post(CHAT_URL, json={"message": "one"}) + old_id = parse_sse(first.text)[-1]["conversation_id"] + await client.post(CHAT_URL, json={"message": "two"}) + response = await client.post( + CHAT_URL, json={"message": "back", "conversation_id": old_id} + ) + + assert response.status_code == 404 + assert response.json() == {"detail": "Conversation not found"} diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_config.py-tpl index fba88b0..70e4492 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_config.py-tpl @@ -1,44 +1,207 @@ # -------------------------------------------------------------------------- -# Settings validation: production refuses a public example SECRET_KEY. +# Settings validation: the SECRET_KEY rule, ENVIRONMENT values, +# environment variable names and the CORS wildcard. # -------------------------------------------------------------------------- +import json +import os import re +import secrets +import subprocess +import sys from pathlib import Path +from typing import Any import pytest from pydantic import ValidationError -from src.app.core.config import KNOWN_EXAMPLE_SECRET_KEYS, Settings +from src.app.core.config import ( + KNOWN_EXAMPLE_SECRET_KEYS, + MIN_SECRET_KEY_BYTES, + Settings, +) -ENV_EXAMPLE = Path(__file__).resolve().parents[1] / ".env.example" +PROJECT_ROOT = Path(__file__).resolve().parents[1] +ENV_EXAMPLE = PROJECT_ROOT / ".env.example" +APP_MODULE = "src.app.main" +#: Settings without a default; none in this template. +REQUIRED: dict[str, Any] = {} +STRONG_KEY = "k" * MIN_SECRET_KEY_BYTES +#: Every environment except development refuses a missing, public or short +#: SECRET_KEY. +STRICT_ENVIRONMENTS = ["staging", "production"] + +@pytest.fixture(autouse=True) +def _isolated_settings_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Shell variables, in any spelling, must not leak into Settings().""" + for name in list(os.environ): + if name.upper() in {"ENVIRONMENT", "SECRET_KEY", "BACKEND_CORS_ORIGINS"}: + monkeypatch.delenv(name) + + +def make_settings(env_file: Path | None = None, **values: Any) -> Settings: + """Settings from explicit values; a developer's .env is never read.""" + return Settings(_env_file=env_file, **{**REQUIRED, **values}) # type: ignore[call-arg] + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_require_an_explicit_secret_key(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"must be set explicitly when ENVIRONMENT={environment}" + ): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_refuse_a_short_secret_key(environment: str) -> None: + short_key = "k" * (MIN_SECRET_KEY_BYTES - 1) + + with pytest.raises(ValidationError, match=f"at least {MIN_SECRET_KEY_BYTES} bytes"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=short_key) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) @pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) -def test_production_refuses_example_secret_key(example_key: str) -> None: +def test_strict_environments_refuse_every_public_example_key( + environment: str, example_key: str +) -> None: + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=f" {example_key} ") + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environment_errors_say_how_to_generate_a_key(environment: str) -> None: with pytest.raises(ValidationError, match="token_urlsafe"): - Settings(_env_file=None, ENVIRONMENT="production", SECRET_KEY=example_key) + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_an_explicit_strong_key(environment: str) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + + assert settings.ENVIRONMENT == environment + assert settings.SECRET_KEY == STRONG_KEY -@pytest.mark.parametrize("environment", ["development", "staging"]) -def test_example_secret_key_is_allowed_outside_production(environment: str) -> None: - settings = Settings( - _env_file=None, ENVIRONMENT=environment, SECRET_KEY="changethis" +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_the_key_fastkit_writes_to_env( + tmp_path: Path, environment: str +) -> None: + env_file = tmp_path / ".env" + env_file.write_text( + f"ENVIRONMENT={environment}\nSECRET_KEY={secrets.token_urlsafe(32)}\n", + encoding="utf-8", ) - assert settings.SECRET_KEY == "changethis" + assert make_settings(env_file).ENVIRONMENT == environment + + +def test_development_without_a_key_uses_a_random_one() -> None: + settings = make_settings(ENVIRONMENT="development") + + assert len(settings.SECRET_KEY.encode()) >= MIN_SECRET_KEY_BYTES + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_development_only_warns_about_an_example_key() -> None: + example_key = sorted(KNOWN_EXAMPLE_SECRET_KEYS)[0] + + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings(ENVIRONMENT="development", SECRET_KEY=example_key) + + assert settings.SECRET_KEY == example_key + + +@pytest.mark.parametrize("value", ["Production", "PRODUCTION", " production", "prod"]) +def test_unknown_environment_values_fail_closed(value: str) -> None: + with pytest.raises(ValidationError, match="ENVIRONMENT"): + make_settings(ENVIRONMENT=value, SECRET_KEY=STRONG_KEY) + + +def test_environment_variable_names_are_case_insensitive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("environment", "production") + + with pytest.raises(ValidationError, match="must be set explicitly"): + make_settings() + + monkeypatch.setenv("secret_key", STRONG_KEY) + + assert make_settings().ENVIRONMENT == "production" + + +@pytest.mark.parametrize("raw", ["*", " * ", '["*"]', "*,http://localhost:3000"]) +def test_cors_wildcard_is_accepted(monkeypatch: pytest.MonkeyPatch, raw: str) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + + assert make_settings().all_cors_origins == ["*"] + + +def test_cors_origins_must_be_urls_or_the_wildcard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + + with pytest.raises(ValidationError): + make_settings() + + +#: Runs in a fresh interpreter: the app reads its settings at import time. +_PREFLIGHT = f""" +import json +from fastapi.testclient import TestClient +from {APP_MODULE} import app + +headers = {{ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "GET", +}} +response = TestClient(app).options("/", headers=headers) +allowed = {{ + k: v for k, v in response.headers.items() if k.startswith("access-control-allow-") +}} +print(json.dumps(allowed)) +""" -def test_production_accepts_a_real_secret_key() -> None: - settings = Settings( - _env_file=None, - ENVIRONMENT="production", - SECRET_KEY="a-real-unique-key-0123456789abcdef", +@pytest.mark.parametrize( + ("origins", "allow_origin", "allow_credentials"), + [ + ("*", "*", None), + ("http://localhost:3000", "http://localhost:3000", "true"), + ], +) +def test_cors_wildcard_is_never_combined_with_credentials( + origins: str, allow_origin: str, allow_credentials: str | None +) -> None: + env = { + **os.environ, + **{name: str(value) for name, value in REQUIRED.items()}, + "BACKEND_CORS_ORIGINS": origins, + "ENVIRONMENT": "development", + } + result = subprocess.run( + [sys.executable, "-c", _PREFLIGHT], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + check=False, ) - assert settings.ENVIRONMENT == "production" + assert result.returncode == 0, result.stderr + headers = json.loads(result.stdout.strip().splitlines()[-1]) + assert headers["access-control-allow-origin"] == allow_origin + assert headers.get("access-control-allow-credentials") == allow_credentials def test_env_example_secret_key_is_a_known_example_value() -> None: - """Whatever .env.example ships must be one the production guard rejects.""" + """Whatever .env.example ships must be one the SECRET_KEY guard rejects.""" if not ENV_EXAMPLE.is_file(): pytest.skip(".env.example is not part of this checkout") diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_health.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_health.py-tpl index 47af278..2b6eabe 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_health.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_health.py-tpl @@ -2,11 +2,18 @@ # Health endpoint smoke test. # -------------------------------------------------------------------------- from httpx import AsyncClient + from src.app.core.config import settings async def test_health_endpoint_returns_ok(client: AsyncClient) -> None: - response = await client.get(f"{settings.API_V1_PREFIX}/health") + response = await client.get("/health") assert response.status_code == 200 assert response.json() == {"status": "ok"} + + +async def test_health_endpoint_is_not_versioned(client: AsyncClient) -> None: + response = await client.get(f"{settings.API_V1_PREFIX}/health") + + assert response.status_code == 404 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_memory.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_memory.py-tpl index 18ef2cf..1ebeb45 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_memory.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_memory.py-tpl @@ -1,6 +1,9 @@ # -------------------------------------------------------------------------- # In-memory conversation store. # -------------------------------------------------------------------------- +import pytest + +from src.app.core.config import settings from src.app.memory.in_memory import InMemoryConversationStore @@ -36,3 +39,49 @@ async def test_delete_forgets_the_conversation() -> None: await store.delete("c1") # deleting twice is not an error assert await store.get("c1") == [] + + +async def test_least_recently_used_conversation_is_evicted() -> None: + store = InMemoryConversationStore(max_conversations=2) + await store.append("c1", {"role": "user", "content": "one"}) + await store.append("c2", {"role": "user", "content": "two"}) + + # Reading c1 makes c2 the least recently used conversation. + assert await store.get("c1") + await store.append("c3", {"role": "user", "content": "three"}) + + assert await store.get("c2") == [] + assert [m["content"] for m in await store.get("c1")] == ["one"] + assert [m["content"] for m in await store.get("c3")] == ["three"] + + +async def test_appending_refreshes_a_conversation() -> None: + store = InMemoryConversationStore(max_conversations=2) + await store.append("c1", {"role": "user", "content": "one"}) + await store.append("c2", {"role": "user", "content": "two"}) + + await store.append("c1", {"role": "assistant", "content": "again"}) + await store.append("c3", {"role": "user", "content": "three"}) + + assert await store.get("c2") == [] + assert len(await store.get("c1")) == 2 + + +async def test_reading_an_unknown_id_does_not_create_it() -> None: + store = InMemoryConversationStore(max_conversations=1) + await store.append("c1", {"role": "user", "content": "one"}) + + assert await store.get("missing") == [] + + assert len(await store.get("c1")) == 1 + + +def test_default_limit_comes_from_settings(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(settings, "MAX_CONVERSATIONS", 7) + + assert InMemoryConversationStore()._max_conversations == 7 + + +def test_limit_must_be_positive() -> None: + with pytest.raises(ValueError): + InMemoryConversationStore(max_conversations=0) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_tools.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_tools.py-tpl index 62c9f71..d9ec51e 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_tools.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/tests/test_tools.py-tpl @@ -4,7 +4,18 @@ # The calculator is the one place user-controlled text is evaluated, so its # rejection cases get as much coverage as its happy path. # -------------------------------------------------------------------------- -from src.app.llm.tools import calculator, current_time, run_tool +import logging +import time + +import pytest + +from src.app.llm import tools +from src.app.llm.tools import ( + MAX_EXPRESSION_LENGTH, + calculator, + current_time, + run_tool, +) def test_calculator_evaluates_arithmetic() -> None: @@ -35,3 +46,86 @@ def test_run_tool_dispatches_and_guards() -> None: assert run_tool("calculator", {"expression": "2+2"}) == "4" assert run_tool("nope", {}).startswith("Error: unknown tool") assert run_tool("calculator", {"wrong": 1}).startswith("Error: bad arguments") + + +def test_calculator_accepts_an_expression_at_the_length_limit() -> None: + terms = (MAX_EXPRESSION_LENGTH + 1) // 2 + expression = "+".join(["1"] * terms) + assert len(expression) == MAX_EXPRESSION_LENGTH - 1 + + assert calculator(expression) == str(terms) + assert calculator("(" * 90 + "1" + ")" * 90) == "1" + assert calculator("2 ** 300").startswith("20370359763344860") + + +@pytest.mark.parametrize( + ("expression", "expected"), + [ + # Far past the length limit: used to raise MemoryError while parsing. + ("-" * 100_000 + "1", "Error: expression is too long"), + ("(" * 5_000 + "1" + ")" * 5_000, "Error: expression is too long"), + # Within the length limit but nested deeper than the evaluator allows. + ("-" * 150 + "1", "Error: expression or result is too large"), + # Exponents and magnitudes are checked before the result is used. + ("9 ** 9 ** 9", "Error: expression or result is too large"), + ("2 ** 100000", "Error: expression or result is too large"), + ("1e308 * 10", "Error: expression or result is too large"), + ("1e308 * 10 - 1e308 * 10", "Error: expression or result is too large"), + ("10 ** 101", "Error: expression or result is too large"), + ("1" + "0" * 150, "Error: expression or result is too large"), + ], +) +def test_calculator_rejects_oversized_input_quickly( + expression: str, expected: str +) -> None: + started = time.perf_counter() + + result = run_tool("calculator", {"expression": expression}) + + assert result.startswith(expected) + assert time.perf_counter() - started < 1.0 + + +def test_calculator_rejects_booleans() -> None: + assert calculator("True + 1").startswith("Error:") + + +def test_run_tool_never_raises_and_hides_internals( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + def broken(expression: str) -> str: + raise RuntimeError("secret internal detail") + + monkeypatch.setitem(tools.TOOL_HANDLERS, "calculator", broken) + + with caplog.at_level(logging.ERROR, logger="app.tools"): + result = run_tool("calculator", {"expression": "1"}) + + assert result == "Error: the 'calculator' tool failed." + assert "secret internal detail" not in result + # The operator still gets the real cause. + assert "secret internal detail" in caplog.text + + +def test_run_tool_reports_memory_errors_as_tool_errors( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def exhausted(expression: str) -> str: + raise MemoryError + + monkeypatch.setitem(tools.TOOL_HANDLERS, "calculator", exhausted) + + assert run_tool("calculator", {"expression": "1"}).startswith("Error:") + + +def test_run_tool_does_not_mistake_internal_type_errors_for_bad_arguments( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def buggy(expression: str) -> str: + raise TypeError("internal bug") + + monkeypatch.setitem(tools.TOOL_HANDLERS, "calculator", buggy) + + result = run_tool("calculator", {"expression": "1"}) + + assert result == "Error: the 'calculator' tool failed." diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.env.example-tpl index 8d1b436..d737ca9 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.env.example-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/.env.example-tpl @@ -7,10 +7,11 @@ # Application Settings PROJECT_NAME=FastAPI MCP Project VERSION=0.1.0 -API_V1_STR=/api/v1 +API_V1_PREFIX=/api/v1 # One of: development, staging, production. -# In production the app refuses to start if SECRET_KEY is unset or still an -# example value, or if ENABLE_DEMO_USERS=true. +# Outside development (staging or production) the app refuses to start if +# SECRET_KEY is unset, a public example value or shorter than 32 bytes, or if +# ENABLE_DEMO_USERS=true. ENVIRONMENT=development # Server Settings @@ -19,7 +20,8 @@ PORT=8000 DEBUG=false # CORS Settings -# Comma-separated list of allowed origins +# Comma-separated list (or JSON list) of allowed origins. "*" allows any +# origin, but then without credentials (cookies, Authorization headers). # BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:8080 # MCP (Model Context Protocol) Settings @@ -29,20 +31,25 @@ MCP_TITLE=FastAPI MCP Server MCP_DESCRIPTION=FastAPI endpoints exposed as MCP tools # Authentication Settings -# Example value only: replace it with your own key, e.g. `openssl rand -hex 32`. +# Example value only: replace it with your own key of at least 32 bytes, e.g. +# `python -c "import secrets; print(secrets.token_urlsafe(32))"`. SECRET_KEY=changethis-please-use-openssl-rand-hex-32 +# HS256, HS384 or HS512. ALGORITHM=HS256 ACCESS_TOKEN_EXPIRE_MINUTES=30 # Demo accounts (user1/password123, user2/password456, admin/admin123). # Disabled by default. Set to true only for local experiments; the app refuses -# to start with ENABLE_DEMO_USERS=true when ENVIRONMENT=production. +# to start with ENABLE_DEMO_USERS=true unless ENVIRONMENT=development. ENABLE_DEMO_USERS=false # MCP endpoint authentication # The MCP endpoint is PROTECTED by default; it is never open. # - MCP_API_KEY unset: clients must send a valid JWT access token -# (Authorization: Bearer ). -# - MCP_API_KEY set: clients must send Authorization: Bearer , -# and JWTs are no longer accepted on the MCP endpoint. +# (Authorization: Bearer ). +# - MCP_API_KEY set: clients must send the key, either as +# X-MCP-API-Key: or as Authorization: Bearer , +# and a JWT alone no longer opens the MCP endpoint. Send the key in +# X-MCP-API-Key plus Authorization: Bearer to let tools that need a +# user (create/update/delete items) act as that user. # MCP_API_KEY=your-mcp-api-key-here diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl index c5a4772..b2ceb01 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl @@ -6,9 +6,10 @@ A FastAPI application with Model Context Protocol (MCP) integration, providing a - **FastAPI Integration**: Modern, fast web framework for building APIs - **MCP Support**: Expose API endpoints as Model Context Protocol tools -- **Authentication**: JWT-based authentication with OAuth2 support +- **Authentication**: OAuth2 password flow (`POST /api/v1/auth/token`) issuing JWTs - **Protected MCP endpoint**: API key or JWT required on the MCP transport -- **Authorization**: Role-based access control for API endpoints +- **Authorization**: public item reads, owner-only item writes, superuser-only user list +- **Pagination**: every list endpoint returns `{"items", "total", "limit", "offset"}` - **Auto-generated Documentation**: Swagger UI and ReDoc integration - **Type Safety**: Full type hints and Pydantic models - **Testing**: Comprehensive test suite with pytest @@ -22,7 +23,8 @@ A FastAPI application with Model Context Protocol (MCP) integration, providing a │ │ ├── routes/ # Route handlers │ │ └── api.py # Main API router │ ├── auth/ # Authentication logic -│ ├── core/ # Core settings and config +│ ├── core/ # Settings, pagination, OpenAPI error helpers +│ ├── crud/ # In-memory item store (swap for a database) │ ├── mcp_server/ # MCP integration │ ├── schemas/ # Pydantic models │ └── main.py # FastAPI application @@ -63,7 +65,7 @@ cp .env.example .env # Application Settings PROJECT_NAME=FastAPI MCP Project VERSION=0.1.0 -API_V1_STR=/api/v1 +API_V1_PREFIX=/api/v1 # development | staging | production ENVIRONMENT=development @@ -96,21 +98,24 @@ ENABLE_DEMO_USERS=false | Variable | Default | Meaning | |---|---|---| -| `ENVIRONMENT` | `development` | `development`, `staging` or `production`. Production turns on the startup safety checks below. | -| `SECRET_KEY` | random per process | JWT signing key. When unset, a new random key is generated on every start, so tokens stop working after a restart and differ between workers. | +| `ENVIRONMENT` | `development` | `development`, `staging` or `production`. Every value except `development` turns on the startup safety checks below. | +| `SECRET_KEY` | random per process | JWT signing key. When unset, a new random key is generated on every start, so tokens stop working after a restart and differ between workers. Staging and production require an explicit key of at least 32 bytes. | | `ENABLE_DEMO_USERS` | `false` | Enables the built-in demo accounts (see [Authentication](#authentication)). | | `MCP_API_KEY` | unset | Static API key for the MCP endpoint. When unset, the MCP endpoint requires a JWT. See [MCP Authentication](#mcp-authentication). | -| `MCP_MOUNT_PATH` | `/mcp` | Path where the MCP server is mounted. | +| `MCP_MOUNT_PATH` | `/mcp` | Path where the MCP server is mounted (at the application root). | +| `API_V1_PREFIX` | `/api/v1` | Prefix of every API router. Renamed from `API_V1_STR`. | -### Production Safety Checks +### Startup Safety Checks -When `ENVIRONMENT=production`, the application refuses to start (a settings -validation error is raised at import time) if: +With any `ENVIRONMENT` other than `development` (`staging` or `production`), +the application refuses to start (a settings validation error naming the +environment is raised at import time) if: - `SECRET_KEY` is not set explicitly; -- `SECRET_KEY` is one of the public example values - (`changethis-please-use-openssl-rand-hex-32`, +- `SECRET_KEY` is one of the public example values fastkit has shipped (for + example `changethis-please-use-openssl-rand-hex-32` or `your-secret-key-here-change-in-production`); +- `SECRET_KEY` is shorter than 32 bytes; - `ENABLE_DEMO_USERS=true`. The error message explains how to generate a key: @@ -124,11 +129,13 @@ python -c "import secrets; print(secrets.token_urlsafe(32))" ### Important Security Notes - **Always set your own `SECRET_KEY`** outside local development -- Use a strong, random secret key (minimum 32 characters) +- Use a strong, random secret key (at least 32 bytes; staging and production + enforce it) - Set `DEBUG=false` in production - Keep `ENABLE_DEMO_USERS=false` anywhere other than your own machine - Set `MCP_API_KEY` (or keep JWT auth) before exposing the MCP endpoint -- Configure `BACKEND_CORS_ORIGINS` appropriately for your frontend domains +- Configure `BACKEND_CORS_ORIGINS` appropriately for your frontend domains (`*` + allows any origin, but then the app sends no credentials) ## Usage @@ -148,13 +155,16 @@ uvicorn src.main:app --host 0.0.0.0 --port 8000 --reload ### Authentication -The application provides several authentication endpoints: +One login endpoint follows the OAuth2 password flow: -1. **Login**: `POST /api/v1/auth/login` -2. **OAuth2 Token**: `POST /api/v1/auth/token` -3. **Current User**: `GET /api/v1/auth/me` +1. **Token**: `POST /api/v1/auth/token` with a form body + (`username=...&password=...`) returns `{"access_token": "...", "token_type": "bearer"}`. +2. Send the token as `Authorization: Bearer `. Swagger UI's + **Authorize** button uses the same endpoint. +3. **Current user**: `GET /api/v1/users/me`. A disabled account gets `403`. +4. **User list**: `GET /api/v1/users` (paginated, superusers only; others get `403`). -The user store is empty by default; `src/api/routes/auth.py` has a +The user store is empty by default; `src/auth/users.py` has a `get_users_db()` hook where you plug in a real database. For local experiments you can enable three demo accounts by setting @@ -162,29 +172,43 @@ For local experiments you can enable three demo accounts by setting - Username: `user1`, Password: `password123` - Username: `user2`, Password: `password456` -- Username: `admin`, Password: `admin123` +- Username: `admin`, Password: `admin123` (superuser) These passwords are public, so the demo accounts are **disabled by default**: with `ENABLE_DEMO_USERS=false` logging in as them fails with the normal `401`. -The application refuses to start with `ENABLE_DEMO_USERS=true` when -`ENVIRONMENT=production`. +The application refuses to start with `ENABLE_DEMO_USERS=true` unless +`ENVIRONMENT=development`. ### API Endpoints -- **Items**: CRUD operations for items (`/api/v1/items/`) -- **Authentication**: User authentication (`/api/v1/auth/`) -- **Health Check**: Application health (`/health`) -- **Documentation**: Swagger UI (`/docs`) and ReDoc (`/redoc`) +| Method | Path | Auth | Notes | +|---|---|---|---| +| GET | `/health` | - | `{"status": "ok"}` | +| POST | `/api/v1/auth/token` | - | OAuth2 password flow (form body) | +| GET | `/api/v1/users/me` | user | | +| GET | `/api/v1/users` | superuser | paginated | +| GET | `/api/v1/items` | - | paginated (`?limit=1..100&offset=0`), ordered by id | +| GET | `/api/v1/items/{item_id}` | - | 404 `{"detail": "Item not found"}` | +| POST | `/api/v1/items` | user | 201 + `Location` header | +| PUT | `/api/v1/items/{item_id}` | owner | full replacement (omitted optional fields reset) | +| PATCH | `/api/v1/items/{item_id}` | owner | only the fields sent; `null` rejected for `name`/`price` | +| DELETE | `/api/v1/items/{item_id}` | owner | 204 | +| GET | `/api/v1/mcp-server` | - | where the MCP endpoint lives and what it exposes | + +Item reads are public: they take no credentials, so a token (valid or not) +never changes what a read returns. Endpoints that need a user answer `401` +(with `WWW-Authenticate: Bearer`) for a missing or invalid token. +Swagger UI is at `/docs`, ReDoc at `/redoc`, the schema at `/openapi.json`. ### MCP Integration -The application exposes API endpoints as MCP tools at `/mcp` and provides additional MCP-specific endpoints. - -#### MCP Endpoints - -- **Hello World**: `GET /mcp-routes/hello` - Simple MCP hello world endpoint -- **MCP Status**: `GET /mcp-routes/status` - MCP configuration status -- **MCP Tools**: `/mcp` - Main MCP protocol endpoint (via fastapi-mcp) +The MCP server is mounted at `MCP_MOUNT_PATH` (`/mcp`). Only the item +operations become MCP tools, named after their `operation_id`: +`list_items`, `get_item`, `create_item`, `replace_item`, `update_item`, +`delete_item`. `src/mcp_server/router.py` selects them with +`include_tags=["items"]` (`MCP_TOOL_TAGS`); `/auth/token` (it takes a +password), the user endpoints, `/` and `/health` are never tools. +`GET /api/v1/mcp-server` describes the server. #### MCP Authentication @@ -193,20 +217,21 @@ is attached to the transport routes that fastapi-mcp registers (`GET {MCP_MOUNT_PATH}` for the SSE connection and `POST {MCP_MOUNT_PATH}/messages/` for messages) through `AuthConfig(dependencies=[Depends(verify_mcp_access)])` in -`src/mcp_server/router.py`. The `/mcp-routes/*` helper endpoints stay public. +`src/mcp_server/router.py`. | `MCP_API_KEY` | What the MCP endpoint requires | |---|---| -| unset (default) | `Authorization: Bearer ` obtained from `/api/v1/auth/login` or `/api/v1/auth/token` | -| set | `Authorization: Bearer ` (compared in constant time); JWTs are no longer accepted | +| unset (default) | `Authorization: Bearer ` of an existing, active user (from `POST /api/v1/auth/token`) | +| set | the key as `X-MCP-API-Key: ` or `Authorization: Bearer ` (compared in constant time); a JWT alone is no longer accepted | Requests with a missing or wrong credential get `401 Unauthorized`. -Note: fastapi-mcp forwards the client's `Authorization` header to the API -endpoints it calls as tools. In JWT mode, tools for JWT-protected endpoints -(create/update/delete items, current user) work with the caller's token. In -`MCP_API_KEY` mode the forwarded header is the MCP key, which is not a JWT, so -those tools return `401`; only public endpoints work as tools. +fastapi-mcp forwards only the client's `Authorization` header to the API +endpoints it calls as tools. Read tools are public, so they work in both +modes. Write tools act as the user whose JWT is in `Authorization`: in JWT +mode that is the token that opened the connection; in `MCP_API_KEY` mode, +send the key in `X-MCP-API-Key` and a user's JWT in `Authorization`. If the +key itself is sent in `Authorization`, write tools return `401`. The quickest way to try MCP locally is to set an API key in `.env`: @@ -216,21 +241,22 @@ MCP_API_KEY=some-long-random-string Example MCP usage: ```bash -# Test MCP hello endpoint (public) -curl http://localhost:8000/mcp-routes/hello - -# Check MCP status (public) -curl http://localhost:8000/mcp-routes/status +# Describe the MCP server (public) +curl http://localhost:8000/api/v1/mcp-server # Open the MCP SSE stream with the API key (MCP_API_KEY set) -curl -N -H "Authorization: Bearer $MCP_API_KEY" http://localhost:8000/mcp +curl -N -H "X-MCP-API-Key: $MCP_API_KEY" http://localhost:8000/mcp -# Or, with MCP_API_KEY unset, use a JWT (e.g. from a demo login when -# ENABLE_DEMO_USERS=true) -TOKEN=$(curl -s -X POST http://localhost:8000/api/v1/auth/login \ - -H "Content-Type: application/json" \ - -d '{"username": "user1", "password": "password123"}' | jq -r .access_token) +# Get a JWT (e.g. from a demo login when ENABLE_DEMO_USERS=true) +TOKEN=$(curl -s -X POST http://localhost:8000/api/v1/auth/token \ + -d "username=user1&password=password123" | jq -r .access_token) + +# MCP_API_KEY unset: the JWT opens the stream curl -N -H "Authorization: Bearer $TOKEN" http://localhost:8000/mcp + +# MCP_API_KEY set: key plus JWT, so write tools act as user1 +curl -N -H "X-MCP-API-Key: $MCP_API_KEY" -H "Authorization: Bearer $TOKEN" \ + http://localhost:8000/mcp ``` ## Development @@ -256,7 +282,7 @@ Run tests: Run specific test: ```bash -pytest tests/test_items.py::test_get_items -v +pytest tests/test_items.py::test_list_items_envelope -v ``` ### Type Checking @@ -271,26 +297,22 @@ Once the server is running, visit: - **Swagger UI**: http://localhost:8000/docs - **ReDoc**: http://localhost:8000/redoc -- **OpenAPI JSON**: http://localhost:8000/api/v1/openapi.json +- **OpenAPI JSON**: http://localhost:8000/openapi.json ## MCP Tools -The application exposes the following tools and endpoints via MCP: - -### MCP-Specific Endpoints - -- **mcp_hello**: Simple hello world endpoint (`/mcp-routes/hello`) -- **mcp_status**: MCP configuration status (`/mcp-routes/status`) - -### API Endpoints via MCP +| Tool | Endpoint | Needs a user JWT | +|---|---|---| +| `list_items` | `GET /api/v1/items` | no | +| `get_item` | `GET /api/v1/items/{item_id}` | no | +| `create_item` | `POST /api/v1/items` | yes | +| `replace_item` | `PUT /api/v1/items/{item_id}` | yes (owner) | +| `update_item` | `PATCH /api/v1/items/{item_id}` | yes (owner) | +| `delete_item` | `DELETE /api/v1/items/{item_id}` | yes (owner) | -- **get_items**: List items with pagination -- **get_item**: Get specific item by ID -- **create_item**: Create new item (requires auth) -- **update_item**: Update existing item (requires auth) -- **delete_item**: Delete item (requires auth) -- **login**: Authenticate user -- **get_current_user**: Get current user info +To expose another resource, tag its router and add the tag to +`MCP_TOOL_TAGS` in `src/mcp_server/router.py`. Give every exposed route an +explicit `operation_id`; it becomes the tool name. ## Deployment @@ -298,10 +320,11 @@ The application exposes the following tools and endpoints via MCP: For production deployment: -1. Set `ENVIRONMENT=production` (enables the startup safety checks) +1. Set `ENVIRONMENT=production` (enables the startup safety checks, as does + `staging`) 2. Set `DEBUG=False` in environment 3. Use a secure, explicit `SECRET_KEY` -4. Keep `ENABLE_DEMO_USERS=false` (required in production) +4. Keep `ENABLE_DEMO_USERS=false` (required outside development) 5. Set `MCP_API_KEY` or rely on JWT auth for the MCP endpoint 6. Configure proper CORS origins 7. Set up SSL/TLS certificates diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/pyproject.toml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/pyproject.toml-tpl index 90a1c6b..8c9511b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/pyproject.toml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/pyproject.toml-tpl @@ -13,12 +13,11 @@ dependencies = [ "uvicorn[standard]>=0.52.4", "pydantic>=2.13.5", "pydantic-settings>=2.15.0", - "SQLAlchemy>=2.0.52", "python-dotenv>=1.2.3", "fastapi-mcp>=0.3.7,<0.4.0", "mcp>=1.30.0,<2.0.0", "pwdlib[argon2]>=0.3.1", - "PyJWT[crypto]>=2.15.1", + "PyJWT>=2.15.1", "python-multipart>=0.0.32", ] @@ -30,7 +29,6 @@ dev = [ "black>=26.10.1", "isort>=9.0.1", "mypy>=2.3.1", - "PyYAML>=6.0.3", ] [dependency-groups] @@ -41,7 +39,6 @@ dev = [ "black>=26.10.1", "isort>=9.0.1", "mypy>=2.3.1", - "PyYAML>=6.0.3", ] [tool.fastapi-fastkit] @@ -83,9 +80,39 @@ warn_return_any = true warn_unused_configs = true disallow_untyped_defs = true +[[tool.mypy.overrides]] +# fastapi-mcp ships no type information. +module = ["fastapi_mcp", "fastapi_mcp.*"] +ignore_missing_imports = true + [tool.pytest.ini_options] testpaths = ["tests"] python_files = ["test_*.py"] python_classes = ["Test*"] python_functions = ["test_*"] addopts = "-v --tb=short --cov=src --cov-report=term-missing" +filterwarnings = [ + # starlette's TestClient now prefers `httpx2`; this project pins httpx, so only + # that advisory notice (a UserWarning subclass) is silenced. + "ignore:Using `httpx` with `starlette.testclient` is deprecated:starlette.exceptions.StarletteDeprecationWarning", + # fastapi-mcp 0.3.7 (fastapi_mcp/types.py, OAuthMetadataDict) uses a pydantic + # model as Annotated metadata; needs an upstream fix (0.4.0 still emits it). + "ignore:The `__get_pydantic_core_schema__` method of the `BaseModel` class is deprecated:pydantic.warnings.PydanticDeprecatedSince211", +] + +[tool.coverage.run] +source = ["src"] +omit = [ + "*/tests/*", + "*/test_*", + "*/conftest.py", +] + +[tool.coverage.report] +exclude_lines = [ + "pragma: no cover", + "def __repr__", + "raise AssertionError", + "raise NotImplementedError", + "if __name__ == .__main__.:", +] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/requirements.txt-tpl index 4b70968..7faddad 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/requirements.txt-tpl @@ -1,6 +1,6 @@ annotated-doc==0.0.5 annotated-types==0.8.0 -anyio==4.15.0 +anyio==4.16.0 argon2-cffi==25.1.0 argon2-cffi-bindings==26.1.0 ast-serialize==0.9.0 @@ -52,9 +52,8 @@ requests==2.34.2 rich==15.0.0 rpds-py==2026.6.3 shellingham==1.5.4 -SQLAlchemy==2.0.52 sse-starlette==3.4.10 -starlette==1.6.0 +starlette==1.10.0 tomli==2.4.1 typer==0.27.2 typing-extensions==4.16.0 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/setup.cfg-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/setup.cfg-tpl deleted file mode 100644 index 104d01a..0000000 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/setup.cfg-tpl +++ /dev/null @@ -1,89 +0,0 @@ -[metadata] -name = fastapi-mcp-project -version = 0.1.0 -description = FastAPI project with Model Context Protocol (MCP) integration -long_description = file: README.md -long_description_content_type = text/markdown -url = https://github.com/yourusername/fastapi-mcp-project -author = Your Name -author_email = your.email@example.com -license = MIT -classifiers = - Development Status :: 3 - Alpha - Intended Audience :: Developers - License :: OSI Approved :: MIT License - Operating System :: OS Independent - Programming Language :: Python :: 3 - Programming Language :: Python :: 3.10 - Programming Language :: Python :: 3.11 - Programming Language :: Python :: 3.12 - Framework :: FastAPI - -[options] -packages = find: -python_requires = >=3.10 -install_requires = - fastapi>=0.115.8 - fastapi-mcp>=0.3.4 - uvicorn>=0.34.0 - pydantic>=2.10.6 - pydantic-settings>=2.7.1 - python-dotenv>=1.0.1 - PyJWT[crypto]>=2.15.1 - pwdlib[argon2]>=0.3.1 - python-multipart>=0.0.17 - -[options.extras_require] -dev = - pytest>=8.3.4 - pytest-cov>=4.0.0 - black>=26.10.1 - isort>=6.0.0 - mypy>=1.15.0 - httpx>=0.28.1 - -[options.entry_points] -console_scripts = - run-server = src.main:start_server - -[tool:pytest] -testpaths = tests -python_files = test_*.py -addopts = -v --tb=short --strict-markers - -[coverage:run] -source = src -omit = - */tests/* - */test_* - */conftest.py - -[coverage:report] -exclude_lines = - pragma: no cover - def __repr__ - raise AssertionError - raise NotImplementedError - if __name__ == .__main__.: - -[mypy] -python_version = 3.10 -warn_return_any = True -warn_unused_configs = True -check_untyped_defs = True -no_implicit_optional = True -warn_redundant_casts = True -warn_unused_ignores = True - -[mypy-tests.*] -disallow_untyped_defs = False - -[isort] -profile = black -multi_line_output = 3 -line_length = 88 -known_first_party = src - -[black] -line-length = 88 -target-version = ['py310'] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/__init__.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/__init__.py-tpl index 3e99389..4e724ce 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/__init__.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/__init__.py-tpl @@ -1,4 +1,5 @@ """ FastAPI MCP Project - Main application package. """ + __version__ = "0.1.0" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/api.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/api.py-tpl index a17a4f4..25a0f0c 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/api.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/api.py-tpl @@ -1,17 +1,19 @@ """ Main API router configuration. + +``src/main.py`` mounts ``api_router`` under ``settings.API_V1_PREFIX``; each +router below carries only its resource prefix. """ + from fastapi import APIRouter -from src.api.routes import auth, items +from src.api.routes import auth, items, mcp_server, users # fastkit:imports api_router = APIRouter() - -# Include authentication routes -api_router.include_router(auth.router, prefix="/auth", tags=["authentication"]) - -# Include items routes -api_router.include_router(items.router, prefix="/items", tags=["items"]) +api_router.include_router(auth.router) +api_router.include_router(users.router) +api_router.include_router(items.router) +api_router.include_router(mcp_server.router) # fastkit:routes diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/auth.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/auth.py-tpl index a6f1524..8b1291b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/auth.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/auth.py-tpl @@ -1,142 +1,38 @@ """ -Authentication-related API endpoints. -""" -from datetime import datetime, timedelta, timezone -from functools import cache - -import jwt -from fastapi import APIRouter, Depends, HTTPException, status -from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from pwdlib import PasswordHash - -from src.auth.dependencies import get_current_active_user -from src.core.config import settings -from src.schemas.items import AuthToken, UserInfo, UserLogin - -router = APIRouter() - -# Password hashing — argon2id, the recommended default for new applications. -password_hash = PasswordHash.recommended() - -# OAuth2 scheme -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") - -# Demo accounts with well-known passwords. They only exist when -# ENABLE_DEMO_USERS=true (never allowed in production), and their hashes are -# computed lazily on first use, not at import time. -DEMO_USER_CREDENTIALS = { - "user1": "password123", - "user2": "password456", - "admin": "admin123", -} - - -@cache -def _demo_users() -> dict[str, dict]: - """Build the demo user records (hashed once, on first use).""" - return { - username: { - "user_id": username, - "username": username, - "hashed_password": password_hash.hash(password), - "active": True, - } - for username, password in DEMO_USER_CREDENTIALS.items() - } - - -def get_users_db() -> dict[str, dict]: - """Return the user store. Replace this with a real database lookup.""" - if settings.ENABLE_DEMO_USERS: - return _demo_users() - return {} - +Authentication endpoint: the OAuth2 password flow token endpoint. -def verify_password(plain_password: str, hashed_password: str) -> bool: - """Verify a password against its hash.""" - return password_hash.verify(plain_password, hashed_password) - - -def get_password_hash(password: str) -> str: - """Generate password hash.""" - return password_hash.hash(password) +Clients ``POST`` a form (``username``, ``password``) to ``/auth/token`` and +send the returned access token as ``Authorization: Bearer ``. +""" +from typing import Annotated -def authenticate_user(username: str, password: str) -> dict | None: - """Authenticate user with username and password.""" - user = get_users_db().get(username) - if not user: - return None - if not verify_password(password, user["hashed_password"]): - return None - return user +from fastapi import APIRouter, Depends +from fastapi.security import OAuth2PasswordRequestForm +from src.auth.dependencies import credentials_error +from src.auth.security import create_access_token +from src.auth.users import authenticate_user +from src.core.responses import error_responses +from src.schemas.users import Token -def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str: - """Create JWT access token.""" - to_encode = data.copy() - if expires_delta: - expire = datetime.now(timezone.utc) + expires_delta - else: - expire = datetime.now(timezone.utc) + timedelta(minutes=15) - to_encode.update({"exp": expire}) - encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) - return encoded_jwt +router = APIRouter(prefix="/auth", tags=["auth"]) -@router.post("/token", response_model=AuthToken, summary="Get access token") -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): - """ - OAuth2 compatible token login, get an access token for future requests. - """ +@router.post( + "/token", + operation_id="login_for_access_token", + summary="Get an access token", + responses=error_responses(401), +) +def login_for_access_token( + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], +) -> Token: + """OAuth2 compatible token login: exchange username and password for a JWT.""" user = authenticate_user(form_data.username, form_data.password) - if not user: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect username or password", - headers={"WWW-Authenticate": "Bearer"}, - ) - access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + if user is None: + raise credentials_error("Incorrect username or password") access_token = create_access_token( - data={"sub": user["user_id"], "username": user["username"]}, - expires_delta=access_token_expires + data={"sub": user.user_id, "username": user.username} ) - return {"access_token": access_token, "token_type": "bearer"} - - -@router.post("/login", response_model=AuthToken, summary="Login with username and password") -async def login(user_credentials: UserLogin): - """ - Login with username and password to get access token. - """ - user = authenticate_user(user_credentials.username, user_credentials.password) - if not user: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect username or password", - ) - access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) - access_token = create_access_token( - data={"sub": user["user_id"], "username": user["username"]}, - expires_delta=access_token_expires - ) - return {"access_token": access_token, "token_type": "bearer"} - - -@router.get("/me", response_model=UserInfo, summary="Get current user") -async def read_users_me(current_user: dict = Depends(get_current_active_user)): - """ - Get current user information. - """ - return UserInfo(**current_user) - - -@router.get("/users", response_model=list[UserInfo], summary="Get all users") -async def get_users(current_user: dict = Depends(get_current_active_user)): - """ - Get all users. Available to authenticated users. - """ - return [ - UserInfo(user_id=user["user_id"], username=user["username"], active=user["active"]) - for user in get_users_db().values() - ] + return Token(access_token=access_token, token_type="bearer") diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/items.py-tpl index 1b574a9..e620724 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/items.py-tpl @@ -1,188 +1,143 @@ """ Item-related API endpoints. -""" - -from fastapi import APIRouter, Depends, HTTPException, Query, status -from src.auth.dependencies import get_current_active_user, optional_auth -from src.schemas.items import ( - ItemCreate, - ItemListResponse, - ItemResponse, - ItemUpdate, -) - -router = APIRouter() - -# Mock database -mock_items = [ - { - "id": 1, - "name": "Laptop", - "description": "High-performance laptop", - "price": 999.99, - "tax": 99.99, - "owner_id": "user1", - }, - { - "id": 2, - "name": "Mouse", - "description": "Wireless mouse", - "price": 29.99, - "tax": 2.99, - "owner_id": "user1", - }, - { - "id": 3, - "name": "Keyboard", - "description": "Mechanical keyboard", - "price": 79.99, - "tax": 7.99, - "owner_id": "user2", - }, -] - - -@router.get("/", response_model=ItemListResponse, summary="Get all items") -def get_items( - page: int = Query(1, ge=1, description="Page number"), - page_size: int = Query(10, ge=1, le=100, description="Items per page"), - current_user: dict | None = Depends(optional_auth), -): - """ - Get a list of items with pagination. - - This endpoint can be used without authentication to get public items, - or with authentication to get user-specific items. - """ - # Calculate pagination - start_idx = (page - 1) * page_size - end_idx = start_idx + page_size - - # Filter items if user is authenticated - if current_user: - user_items = [item for item in mock_items if item["owner_id"] == current_user["user_id"]] - items = user_items[start_idx:end_idx] - total = len(user_items) - else: - items = mock_items[start_idx:end_idx] - total = len(mock_items) - - return ItemListResponse( - items=items, - total=total, - page=page, - page_size=page_size, - ) +Read policy: items are public. ``GET /items`` and ``GET /items/{item_id}`` +take no credentials, so every caller (anonymous, signed in, or an MCP client +whatever header it sends) sees the same collection. Writes require an +authenticated, active user, and only the owner may replace, update or +delete an item. +Every route has an explicit ``operation_id``: fastapi-mcp uses it as the MCP +tool name (see ``src/mcp_server/router.py``). +""" -@router.get("/{item_id}", response_model=ItemResponse, summary="Get item by ID") -def get_item(item_id: int, current_user: dict | None = Depends(optional_auth)): - """ - Get a specific item by ID. - - Returns the item if it exists and the user has access to it. - """ - item = next((item for item in mock_items if item["id"] == item_id), None) - if not item: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Item not found" - ) - - # Check if user has access to this item - if current_user and item["owner_id"] != current_user["user_id"]: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Not authorized to access this item" - ) +from typing import Annotated - return ItemResponse(**item) +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status +from src.auth.dependencies import CurrentUser +from src.auth.users import User +from src.core.pagination import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from src.core.responses import error_responses +from src.crud.items import Item, ItemStore, get_item_store +from src.schemas.items import ItemCreate, ItemRead, ItemUpdate -@router.post("/", response_model=ItemResponse, status_code=status.HTTP_201_CREATED, summary="Create new item") -def create_item( - item: ItemCreate, - current_user: dict = Depends(get_current_active_user), -): - """ - Create a new item. +router = APIRouter(prefix="/items", tags=["items"]) - Requires authentication. The item will be owned by the authenticated user. - """ - # Generate new ID - new_id = max([item["id"] for item in mock_items]) + 1 if mock_items else 1 +ItemStoreDep = Annotated[ItemStore, Depends(get_item_store)] - # Create new item - new_item = { - "id": new_id, - "owner_id": current_user["user_id"], - **item.model_dump(), - } - mock_items.append(new_item) +def _not_found() -> HTTPException: + return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found") - return ItemResponse(**new_item) +def _get_or_404(store: ItemStore, item_id: int) -> Item: + item = store.get(item_id) + if item is None: + raise _not_found() + return item -@router.put("/{item_id}", response_model=ItemResponse, summary="Update item") -def update_item( - item_id: int, - item_update: ItemUpdate, - current_user: dict = Depends(get_current_active_user), -): - """ - Update an existing item. - - Requires authentication. Users can only update their own items. - """ - item = next((item for item in mock_items if item["id"] == item_id), None) - if not item: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Item not found" - ) - # Check ownership - if item["owner_id"] != current_user["user_id"]: +def _get_owned_or_raise(store: ItemStore, item_id: int, user: User) -> Item: + item = _get_or_404(store, item_id) + if item.owner_id != user.user_id: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, - detail="Not authorized to update this item" + detail="Not authorized to modify this item", ) + return item + + +@router.get("", operation_id="list_items", summary="List items") +def list_items( + store: ItemStoreDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> Page[ItemRead]: + """List every item, ordered by id, one page at a time.""" + items = store.list_page(offset=offset, limit=limit) + return Page[ItemRead]( + items=[ItemRead.model_validate(item) for item in items], + total=store.count(), + limit=limit, + offset=offset, + ) - # Update item - update_data = item_update.model_dump(exclude_unset=True) - for field, value in update_data.items(): - item[field] = value - - return ItemResponse(**item) - - -@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT, summary="Delete item") -def delete_item( - item_id: int, - current_user: dict = Depends(get_current_active_user), -): - """ - Delete an item. - Requires authentication. Users can only delete their own items. - """ - item_idx = next((i for i, item in enumerate(mock_items) if item["id"] == item_id), None) - if item_idx is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Item not found" - ) +@router.get( + "/{item_id}", + operation_id="get_item", + summary="Get item by ID", + responses=error_responses(404), +) +def get_item(item_id: int, store: ItemStoreDep) -> ItemRead: + """Get one item by its id.""" + return ItemRead.model_validate(_get_or_404(store, item_id)) - item = mock_items[item_idx] - # Check ownership - if item["owner_id"] != current_user["user_id"]: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Not authorized to delete this item" - ) - - mock_items.pop(item_idx) - return None +@router.post( + "", + operation_id="create_item", + summary="Create an item", + status_code=status.HTTP_201_CREATED, + responses=error_responses(401, 403), +) +def create_item( + payload: ItemCreate, + store: ItemStoreDep, + current_user: CurrentUser, + request: Request, + response: Response, +) -> ItemRead: + """Create an item owned by the authenticated user.""" + item = store.add(owner_id=current_user.user_id, fields=payload.model_dump()) + response.headers["Location"] = str(request.url_for("get_item", item_id=item.id)) + return ItemRead.model_validate(item) + + +@router.put( + "/{item_id}", + operation_id="replace_item", + summary="Replace an item", + responses=error_responses(401, 403, 404), +) +def replace_item( + item_id: int, payload: ItemCreate, store: ItemStoreDep, current_user: CurrentUser +) -> ItemRead: + """Replace every field of an item you own (omitted optional fields reset).""" + _get_owned_or_raise(store, item_id, current_user) + updated = store.update(item_id, payload.model_dump()) + if updated is None: # deleted after the ownership check + raise _not_found() + return ItemRead.model_validate(updated) + + +@router.patch( + "/{item_id}", + operation_id="update_item", + summary="Update some fields of an item", + responses=error_responses(401, 403, 404), +) +def update_item( + item_id: int, payload: ItemUpdate, store: ItemStoreDep, current_user: CurrentUser +) -> ItemRead: + """Change only the fields sent; the others keep their values.""" + _get_owned_or_raise(store, item_id, current_user) + updated = store.update(item_id, payload.model_dump(exclude_unset=True)) + if updated is None: # deleted after the ownership check + raise _not_found() + return ItemRead.model_validate(updated) + + +@router.delete( + "/{item_id}", + operation_id="delete_item", + summary="Delete an item", + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(401, 403, 404), +) +def delete_item(item_id: int, store: ItemStoreDep, current_user: CurrentUser) -> None: + """Delete an item you own.""" + _get_owned_or_raise(store, item_id, current_user) + if not store.delete(item_id): # deleted after the ownership check + raise _not_found() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/mcp_server.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/mcp_server.py-tpl new file mode 100644 index 0000000..8a6f91e --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/mcp_server.py-tpl @@ -0,0 +1,27 @@ +""" +Read-only description of the MCP server this application mounts. + +A resource under the versioned API (``GET /api/v1/mcp-server``) rather than +helper routes outside it: clients discover where the MCP endpoint lives and +which API resources it exposes as tools. The MCP transport itself stays at +``settings.MCP_MOUNT_PATH`` at the application root. +""" + +from fastapi import APIRouter + +from src.core.config import settings +from src.mcp_server.router import MCP_TOOL_TAGS +from src.schemas.mcp_server import McpServerRead + +router = APIRouter(prefix="/mcp-server", tags=["mcp"]) + + +@router.get("", operation_id="get_mcp_server", summary="Describe the MCP server") +def get_mcp_server() -> McpServerRead: + return McpServerRead( + enabled=settings.MCP_ENABLED, + mount_path=settings.MCP_MOUNT_PATH, + title=settings.MCP_TITLE, + description=settings.MCP_DESCRIPTION, + tool_tags=list(MCP_TOOL_TAGS), + ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/users.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/users.py-tpl new file mode 100644 index 0000000..924af8a --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/api/routes/users.py-tpl @@ -0,0 +1,47 @@ +""" +User endpoints: the current user, and the user list for superusers. +""" + +from fastapi import APIRouter + +from src.auth import users +from src.auth.dependencies import CurrentSuperuser, CurrentUser +from src.core.pagination import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from src.core.responses import error_responses +from src.schemas.users import UserRead + +router = APIRouter(prefix="/users", tags=["users"]) + + +@router.get( + "/me", + operation_id="read_current_user", + summary="Get the current user", + responses=error_responses(401, 403), +) +def read_current_user(current_user: CurrentUser) -> UserRead: + """The account the access token belongs to.""" + return UserRead.model_validate(current_user) + + +@router.get( + "", + operation_id="list_users", + summary="List users (superusers only)", + responses=error_responses(401, 403), +) +def list_users( + _superuser: CurrentSuperuser, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> Page[UserRead]: + """Every account, ordered by user id. Requires a superuser token.""" + return Page[UserRead]( + items=[ + UserRead.model_validate(user) + for user in users.list_page(offset=offset, limit=limit) + ], + total=users.count(), + limit=limit, + offset=offset, + ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/dependencies.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/dependencies.py-tpl index 88c4928..f7aa472 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/dependencies.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/dependencies.py-tpl @@ -3,58 +3,91 @@ Authentication dependencies for API and MCP endpoints. """ import secrets +from typing import Annotated import jwt -from fastapi import Depends, HTTPException, status -from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer - +from fastapi import Depends, HTTPException, Security, status +from fastapi.security import ( + APIKeyHeader, + HTTPAuthorizationCredentials, + HTTPBearer, + OAuth2PasswordBearer, +) + +from src.auth.security import decode_access_token +from src.auth.users import User, get_user from src.core.config import settings -security = HTTPBearer(auto_error=False) +# The API's user authentication: OAuth2 password flow. ``tokenUrl`` is the +# login endpoint, so Swagger UI's "Authorize" button works out of the box. +oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_PREFIX}/auth/token") +# MCP transport credentials (see verify_mcp_access). Not part of the OpenAPI +# schema: fastapi-mcp registers its transport routes with +# include_in_schema=False. +MCP_API_KEY_HEADER = "X-MCP-API-Key" +mcp_bearer = HTTPBearer(auto_error=False) +mcp_api_key_header = APIKeyHeader(name=MCP_API_KEY_HEADER, auto_error=False) -def verify_token(token: str) -> dict: - """Verify JWT token and return payload.""" - try: - payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) - return payload - except jwt.PyJWTError: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": "Bearer"}, - ) +def credentials_error(detail: str = "Could not validate credentials") -> HTTPException: + """A fresh 401 for every failure (never re-raise a shared instance).""" + return HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail=detail, + headers={"WWW-Authenticate": "Bearer"}, + ) -def get_current_user(credentials: HTTPAuthorizationCredentials | None = Depends(security)): - """Get current authenticated user from JWT token.""" - if not credentials: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Not authenticated", - headers={"WWW-Authenticate": "Bearer"}, - ) - payload = verify_token(credentials.credentials) +def user_from_token(token: str) -> User: + """Resolve a JWT access token to an existing user, or raise 401.""" + try: + payload = decode_access_token(token) + except jwt.InvalidTokenError as exc: + raise credentials_error() from exc user_id = payload.get("sub") - if user_id is None: + user = get_user(user_id) if isinstance(user_id, str) else None + if user is None: + raise credentials_error() + return user + + +def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> User: + """The user the bearer token belongs to (401 if missing or invalid).""" + return user_from_token(token) + + +def get_current_active_user( + current_user: Annotated[User, Depends(get_current_user)], +) -> User: + """The current user, refused with 403 when the account is disabled.""" + if not current_user.active: raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": "Bearer"}, + status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user" ) + return current_user + - return {"user_id": user_id, "username": payload.get("username")} +CurrentUser = Annotated[User, Depends(get_current_active_user)] -def get_current_active_user(current_user: dict = Depends(get_current_user)): - """Get current active user.""" - if not current_user.get("active", True): - raise HTTPException(status_code=400, detail="Inactive user") +def get_current_superuser(current_user: CurrentUser) -> User: + if not current_user.is_superuser: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail="Not enough privileges" + ) return current_user -def verify_mcp_access(credentials: HTTPAuthorizationCredentials | None = Depends(security)): +CurrentSuperuser = Annotated[User, Depends(get_current_superuser)] + + +def verify_mcp_access( + credentials: Annotated[ + HTTPAuthorizationCredentials | None, Security(mcp_bearer) + ] = None, + api_key: Annotated[str | None, Security(mcp_api_key_header)] = None, +) -> None: """Verify access to the MCP transport endpoints. Wired into the MCP server through ``AuthConfig(dependencies=[...])`` in @@ -62,42 +95,31 @@ def verify_mcp_access(credentials: HTTPAuthorizationCredentials | None = Depends endpoint (``GET {MCP_MOUNT_PATH}``) and the message endpoint (``POST {MCP_MOUNT_PATH}/messages/``). - - ``MCP_API_KEY`` set: require ``Authorization: Bearer ``. - - ``MCP_API_KEY`` unset: require a valid JWT access token instead. + - ``MCP_API_KEY`` set: require the key, sent as ``X-MCP-API-Key: `` + or as ``Authorization: Bearer ``. A JWT alone is not enough. + - ``MCP_API_KEY`` unset: require ``Authorization: Bearer `` of an + existing, active user. The MCP endpoint is never open without credentials. + + fastapi-mcp forwards the ``Authorization`` header (only that header) to + the API endpoints it calls as tools. Sending the key in ``X-MCP-API-Key`` + keeps ``Authorization`` free for a user's JWT, so write tools act as that + user even in API-key mode. """ if settings.MCP_API_KEY: - # Use API key authentication for MCP (constant-time comparison) - if not credentials or not secrets.compare_digest( - credentials.credentials.encode("utf-8"), - settings.MCP_API_KEY.encode("utf-8"), + presented = api_key or (credentials.credentials if credentials else None) + # Constant-time comparison. + if presented is None or not secrets.compare_digest( + presented.encode("utf-8"), settings.MCP_API_KEY.encode("utf-8") ): - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid MCP API key", - headers={"WWW-Authenticate": "Bearer"}, - ) - else: - # Use JWT authentication for MCP - if not credentials: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="MCP authentication required", - headers={"WWW-Authenticate": "Bearer"}, - ) - verify_token(credentials.credentials) - - return True - - -def optional_auth(credentials: HTTPAuthorizationCredentials | None = Depends(security)): - """Optional authentication for endpoints that work with or without auth.""" - if not credentials: - return None + raise credentials_error("Invalid MCP API key") + return - try: - payload = verify_token(credentials.credentials) - return {"user_id": payload.get("sub"), "username": payload.get("username")} - except HTTPException: - return None + if credentials is None: + raise credentials_error("MCP authentication required") + user = user_from_token(credentials.credentials) + if not user.active: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user" + ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/security.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/security.py-tpl new file mode 100644 index 0000000..87f4497 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/security.py-tpl @@ -0,0 +1,58 @@ +""" +Password hashing and JWT access tokens. +""" + +from datetime import datetime, timedelta, timezone +from typing import Any + +import jwt +from pwdlib import PasswordHash + +from src.core.config import settings + +# Password hashing — argon2id, the recommended default for new applications. +password_hash = PasswordHash.recommended() + +ACCESS_TOKEN_TYPE = "access" +#: Claims every access token must carry (checked by PyJWT on decode). +REQUIRED_CLAIMS = ["exp", "sub", "type"] + + +def verify_password(plain_password: str, hashed_password: str) -> bool: + """Verify a password against its hash.""" + return password_hash.verify(plain_password, hashed_password) + + +def get_password_hash(password: str) -> str: + """Generate password hash.""" + return password_hash.hash(password) + + +def create_access_token( + data: dict[str, Any], expires_delta: timedelta | None = None +) -> str: + """Create a signed JWT access token that expires.""" + to_encode = data.copy() + if expires_delta is None: + expires_delta = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + to_encode["exp"] = datetime.now(timezone.utc) + expires_delta + to_encode["type"] = ACCESS_TOKEN_TYPE + return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) + + +def decode_access_token(token: str) -> dict[str, Any]: + """Return the token payload; raise ``jwt.InvalidTokenError`` if invalid. + + A token must carry ``exp``, ``sub`` and ``type``: a signed token without + an expiry would otherwise stay valid forever, and ``type`` keeps any other + token signed with ``SECRET_KEY`` from being used as an access token. + """ + payload: dict[str, Any] = jwt.decode( + token, + settings.SECRET_KEY, + algorithms=[settings.ALGORITHM], + options={"require": REQUIRED_CLAIMS}, + ) + if payload["type"] != ACCESS_TOKEN_TYPE: + raise jwt.InvalidTokenError("not an access token") + return payload diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/users.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/users.py-tpl new file mode 100644 index 0000000..ce67b40 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/auth/users.py-tpl @@ -0,0 +1,77 @@ +""" +User store. Replace ``get_users_db`` with a real database lookup. +""" + +from dataclasses import dataclass +from functools import cache + +from src.auth.security import get_password_hash, verify_password +from src.core.config import settings + + +@dataclass(frozen=True) +class User: + """A user account as stored (never returned as-is by the API).""" + + user_id: str + username: str + hashed_password: str + active: bool = True + is_superuser: bool = False + + +# Demo accounts with well-known passwords. They only exist when +# ENABLE_DEMO_USERS=true (allowed only in development), and their hashes are +# computed lazily on first use, not at import time. +DEMO_USER_CREDENTIALS = { + "user1": "password123", + "user2": "password456", + "admin": "admin123", +} +DEMO_SUPERUSERS = frozenset({"admin"}) + + +@cache +def _demo_users() -> dict[str, User]: + """Build the demo user records (hashed once, on first use).""" + return { + username: User( + user_id=username, + username=username, + hashed_password=get_password_hash(password), + is_superuser=username in DEMO_SUPERUSERS, + ) + for username, password in DEMO_USER_CREDENTIALS.items() + } + + +def get_users_db() -> dict[str, User]: + """Return the user store, keyed by ``user_id``.""" + if settings.ENABLE_DEMO_USERS: + return _demo_users() + return {} + + +def get_user(user_id: str) -> User | None: + return get_users_db().get(user_id) + + +def authenticate_user(username: str, password: str) -> User | None: + """Return the user when the password matches, else ``None``.""" + user = next( + (user for user in get_users_db().values() if user.username == username), + None, + ) + if user is None or not verify_password(password, user.hashed_password): + return None + return user + + +def list_page(offset: int, limit: int) -> list[User]: + """Users ordered by ``user_id``.""" + users = get_users_db() + return [users[user_id] for user_id in sorted(users)[offset : offset + limit]] + + +def count() -> int: + return len(get_users_db()) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/config.py-tpl index 9adc4b5..f367c78 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/config.py-tpl @@ -4,6 +4,7 @@ Application configuration settings. import json import secrets +import warnings from typing import Annotated, Any, Literal from pydantic import AnyHttpUrl, BeforeValidator, model_validator @@ -24,20 +25,28 @@ def parse_cors(v: Any) -> Any: return v -# SECRET_KEY values that ship in this template's docs and example files. They -# are public, so anyone could forge JWTs signed with them: the app refuses to -# start in production while SECRET_KEY is still one of these. +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. KNOWN_EXAMPLE_SECRET_KEYS = frozenset( { "changethis", "changethis-please-generate-a-real-32-byte-key", "changethis-please-use-openssl-rand-hex-32", "your-secret-key-here-change-in-production", + "your-secret-key-here", + "change-me-in-production", + "your-mcp-api-key-here", } ) +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = 32 + _GENERATE_KEY_HINT = ( - "Generate one with `openssl rand -hex 32` or " + "Generate one with " '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' "and set it as SECRET_KEY in the environment or .env." ) @@ -48,7 +57,9 @@ class Settings(BaseSettings): PROJECT_NAME: str = "FastAPI MCP Project" VERSION: str = "0.1.0" - API_V1_STR: str = "/api/v1" + # Every business router is mounted under this prefix; /health, /docs, + # /openapi.json and the MCP mount path stay at the application root. + API_V1_PREFIX: str = "/api/v1" ENVIRONMENT: Literal["development", "staging", "production"] = "development" # Server settings @@ -56,9 +67,11 @@ class Settings(BaseSettings): PORT: int = 8000 DEBUG: bool = False - # CORS settings: comma-separated (http://a,http://b) or a JSON list + # CORS settings: comma-separated (http://a,http://b) or a JSON list. Each + # origin is a full URL, or "*" for any origin; "*" never goes together + # with credentials (browsers refuse that), so main.py turns them off. BACKEND_CORS_ORIGINS: Annotated[ - list[AnyHttpUrl], NoDecode, BeforeValidator(parse_cors) + list[Literal["*"] | AnyHttpUrl], NoDecode, BeforeValidator(parse_cors) ] = [] # MCP settings @@ -69,14 +82,16 @@ class Settings(BaseSettings): # Authentication settings # Signing key for JWTs. Generated per-process when unset, which invalidates - # every token on restart and differs between workers, so production - # refuses to start without an explicit SECRET_KEY. + # every token on restart and differs between workers, so staging and + # production refuse to start without an explicit key of at least 32 + # bytes that is not a public example value (see _check_secret_key below). SECRET_KEY: str = secrets.token_urlsafe(32) - ALGORITHM: str = "HS256" + # HMAC algorithms only: tokens are signed and verified with SECRET_KEY. + ALGORITHM: Literal["HS256", "HS384", "HS512"] = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 # Built-in demo accounts (user1 / user2 / admin) with well-known passwords. - # Off by default; never allowed in production. + # Off by default; refused unless ENVIRONMENT=development. ENABLE_DEMO_USERS: bool = False # Static API key for the MCP endpoint. When set, MCP clients must send @@ -85,25 +100,49 @@ class Settings(BaseSettings): MCP_API_KEY: str | None = None @model_validator(mode="after") - def check_production_safety(self) -> "Settings": - """Refuse insecure settings when running in production.""" - if self.ENVIRONMENT != "production": + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) return self - + env = f"ENVIRONMENT={self.ENVIRONMENT}" if "SECRET_KEY" not in self.model_fields_set: raise ValueError( - "SECRET_KEY must be set explicitly when ENVIRONMENT=production " - "(the per-process random default breaks tokens across restarts " - "and workers). " + _GENERATE_KEY_HINT + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT ) - if self.SECRET_KEY in KNOWN_EXAMPLE_SECRET_KEYS: + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: raise ValueError( - "SECRET_KEY is set to a public example value, which must not be " - "used when ENVIRONMENT=production. " + _GENERATE_KEY_HINT + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT ) - if self.ENABLE_DEMO_USERS: + return self + + @model_validator(mode="after") + def _check_demo_users(self) -> "Settings": + """Refuse demo accounts and their public passwords outside development.""" + if self.ENVIRONMENT != "development" and self.ENABLE_DEMO_USERS: raise ValueError( - "ENABLE_DEMO_USERS=true is not allowed when ENVIRONMENT=production: " + "ENABLE_DEMO_USERS=true is not allowed when " + f"ENVIRONMENT={self.ENVIRONMENT}: " "the demo accounts use well-known passwords. " "Set ENABLE_DEMO_USERS=false." ) @@ -113,10 +152,11 @@ class Settings(BaseSettings): def all_cors_origins(self) -> list[str]: """CORS origins as plain strings, without the trailing slash that ``AnyHttpUrl`` adds (browsers send ``Origin`` without one).""" - return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins model_config = SettingsConfigDict( - case_sensitive=True, env_file=".env", env_ignore_empty=True, extra="ignore", diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/pagination.py-tpl new file mode 100644 index 0000000..2688822 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/pagination.py-tpl @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------- +# Limit/offset pagination shared by every list endpoint. +# +# List endpoints take ``limit: LimitParam = DEFAULT_LIMIT`` and +# ``offset: OffsetParam = 0`` and return a ``Page[T]`` envelope: +# {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range +# values are rejected with a 422 rather than clamped. +# -------------------------------------------------------------------------- +from typing import Annotated, Generic, TypeVar + +from fastapi import Query +from pydantic import BaseModel + +T = TypeVar("T") + +#: Page size used when the client sends no ``limit``. +DEFAULT_LIMIT = 20 +#: Largest page a client may ask for. +MAX_LIMIT = 100 + +LimitParam = Annotated[ + int, Query(ge=1, le=MAX_LIMIT, description="Maximum number of items to return.") +] +OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] + + +class Page(BaseModel, Generic[T]): + """One page of a collection, ordered by primary key. + + ``total`` counts the whole collection, so a client knows there is a next + page while ``offset + len(items) < total``. + """ + + items: list[T] + total: int + limit: int + offset: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/responses.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/responses.py-tpl new file mode 100644 index 0000000..bffc8c1 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/core/responses.py-tpl @@ -0,0 +1,40 @@ +# -------------------------------------------------------------------------- +# OpenAPI error responses shared by the routers. +# +# FastAPI documents 2xx and 422 on its own. Routes that can also answer 401, +# 404, 409, ... declare it with ``responses=error_responses(404)`` so clients +# see every status code and the ``{"detail": "..."}`` body in the schema. +# -------------------------------------------------------------------------- +from http import HTTPStatus +from typing import Any + +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + """Body FastAPI sends for an ``HTTPException``.""" + + detail: str + + +def error_responses(*status_codes: int) -> dict[int | str, dict[str, Any]]: + """Build ``responses=`` entries that document the given error codes. + + A 401 entry also documents the ``WWW-Authenticate`` header every 401 + response carries. + """ + responses: dict[int | str, dict[str, Any]] = {} + for code in status_codes: + entry: dict[str, Any] = { + "model": ErrorDetail, + "description": HTTPStatus(code).phrase, + } + if code == HTTPStatus.UNAUTHORIZED: + entry["headers"] = { + "WWW-Authenticate": { + "description": "Authentication scheme to use (Bearer).", + "schema": {"type": "string"}, + } + } + responses[code] = entry + return responses diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/crud/__init__.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/crud/__init__.py-tpl new file mode 100644 index 0000000..4cff75f --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/crud/__init__.py-tpl @@ -0,0 +1,3 @@ +""" +Data access layer. +""" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/crud/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/crud/items.py-tpl new file mode 100644 index 0000000..c0648a9 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/crud/items.py-tpl @@ -0,0 +1,110 @@ +""" +In-memory item store, a placeholder for a real database. + +Sync route handlers run in a thread pool, so every read-modify-write happens +under a lock. Data lives in this process only: it is lost on restart and not +shared between workers. +""" + +from dataclasses import dataclass, replace +from threading import Lock +from typing import Any + + +@dataclass(frozen=True) +class Item: + """An item as stored.""" + + id: int + name: str + price: float + owner_id: str + description: str | None = None + tax: float | None = None + + +SEED_ITEMS: tuple[Item, ...] = ( + Item( + id=1, + name="Laptop", + description="High-performance laptop", + price=999.99, + tax=99.99, + owner_id="user1", + ), + Item( + id=2, + name="Mouse", + description="Wireless mouse", + price=29.99, + tax=2.99, + owner_id="user1", + ), + Item( + id=3, + name="Keyboard", + description="Mechanical keyboard", + price=79.99, + tax=7.99, + owner_id="user2", + ), +) + + +class ItemStore: + """ID-keyed item collection; ``reset()`` restores the seed data.""" + + def __init__(self, seed: tuple[Item, ...] = SEED_ITEMS) -> None: + self._seed = seed + self._lock = Lock() + self._data: dict[int, Item] = {} + self._next_id = 1 + self.reset() + + def reset(self) -> None: + with self._lock: + self._data = {item.id: item for item in self._seed} + self._next_id = max(self._data, default=0) + 1 + + def list_page(self, offset: int, limit: int) -> list[Item]: + """Up to ``limit`` items after skipping ``offset``, ordered by id.""" + with self._lock: + ids = sorted(self._data)[offset : offset + limit] + return [self._data[item_id] for item_id in ids] + + def count(self) -> int: + with self._lock: + return len(self._data) + + def get(self, item_id: int) -> Item | None: + with self._lock: + return self._data.get(item_id) + + def add(self, owner_id: str, fields: dict[str, Any]) -> Item: + with self._lock: + item = Item(id=self._next_id, owner_id=owner_id, **fields) + self._data[item.id] = item + self._next_id += 1 + return item + + def update(self, item_id: int, changes: dict[str, Any]) -> Item | None: + """Apply already-validated ``changes``; ``None`` if the item is gone.""" + with self._lock: + current = self._data.get(item_id) + if current is None: + return None + updated = replace(current, **changes) + self._data[item_id] = updated + return updated + + def delete(self, item_id: int) -> bool: + with self._lock: + return self._data.pop(item_id, None) is not None + + +item_store = ItemStore() + + +def get_item_store() -> ItemStore: + """Dependency returning the shared store (override it in tests).""" + return item_store diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/main.py-tpl index 4696e80..1b74e2b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/main.py-tpl @@ -1,6 +1,9 @@ """ Main FastAPI application with MCP integration. """ + +from typing import Any + import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware @@ -11,37 +14,28 @@ from src.mcp_server.router import setup_mcp_server # fastkit:imports -# Create FastAPI application app = FastAPI( title=settings.PROJECT_NAME, version=settings.VERSION, description="FastAPI application with Model Context Protocol (MCP) integration", - openapi_url=f"{settings.API_V1_STR}/openapi.json", ) -# Set up CORS middleware if settings.all_cors_origins: app.add_middleware( CORSMiddleware, - allow_origins=[str(origin) for origin in settings.all_cors_origins], - allow_credentials=True, + allow_origins=settings.all_cors_origins, + # Browsers refuse credentials with the "*" wildcard; never send both. + allow_credentials="*" not in settings.all_cors_origins, allow_methods=["*"], allow_headers=["*"], ) -# fastkit:routes -# Include API routes -app.include_router(api_router, prefix=settings.API_V1_STR) -# Setup MCP server -mcp_server = setup_mcp_server(app) - -# Root endpoint @app.get("/", tags=["root"]) -async def root(): - """Root endpoint with application information.""" +def root() -> dict[str, Any]: + """Application information.""" return { - "message": "FastAPI MCP Project", + "message": settings.PROJECT_NAME, "version": settings.VERSION, "mcp_enabled": settings.MCP_ENABLED, "mcp_endpoint": settings.MCP_MOUNT_PATH if settings.MCP_ENABLED else None, @@ -49,13 +43,21 @@ async def root(): "redoc_url": "/redoc", } -# Health check endpoint + @app.get("/health", tags=["health"]) -async def health_check(): - """Health check endpoint.""" - return {"status": "healthy", "version": settings.VERSION} +def health() -> dict[str, str]: + """Liveness probe: no auth, no dependencies.""" + return {"status": "ok"} + -def start_server(): +# fastkit:routes +app.include_router(api_router, prefix=settings.API_V1_PREFIX) + +# Built last: MCP tools are generated from the routes registered above. +mcp_server = setup_mcp_server(app) + + +def start_server() -> None: """Start the server programmatically.""" uvicorn.run( "src.main:app", @@ -65,5 +67,6 @@ def start_server(): log_level="info" if not settings.DEBUG else "debug", ) + if __name__ == "__main__": start_server() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/mcp_server/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/mcp_server/router.py-tpl index 163ebca..9ddc077 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/mcp_server/router.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/mcp_server/router.py-tpl @@ -1,105 +1,50 @@ """ -MCP router configuration and setup. +MCP server configuration and setup. + +fastapi-mcp turns FastAPI operations into MCP tools, named after each +route's ``operation_id``. Only operations tagged with one of +``MCP_TOOL_TAGS`` become tools. Authentication endpoints (``/auth/token`` +takes a password) and user administration are never exposed; add a tag here +to expose another resource deliberately. """ -from fastapi import APIRouter, Depends, FastAPI +from fastapi import Depends, FastAPI from fastapi_mcp import AuthConfig, FastApiMCP from src.auth.dependencies import verify_mcp_access from src.core.config import settings -# Create MCP specific router -mcp_router = APIRouter() - - -@mcp_router.get("/hello") -async def mcp_hello() -> dict[str, str | bool]: - """Simple MCP hello world endpoint. - - Returns: - Dict with hello world message - """ - return { - "message": "Hello from MCP!", - "status": "success", - "mcp_enabled": settings.MCP_ENABLED - } - +MCP_TOOL_TAGS: tuple[str, ...] = ("items",) -@mcp_router.get("/status") -async def mcp_status() -> dict[str, str | bool]: - """MCP status endpoint. - Returns: - Dict with MCP status information - """ - return { - "mcp_enabled": settings.MCP_ENABLED, - "mcp_mount_path": settings.MCP_MOUNT_PATH, - "mcp_title": settings.MCP_TITLE, - "mcp_description": settings.MCP_DESCRIPTION - } - - -def create_mcp_router(app: FastAPI) -> FastApiMCP: - """Create and configure MCP router for the FastAPI application. +def create_mcp_server(app: FastAPI) -> FastApiMCP: + """Build the MCP server from the routes registered on ``app`` so far. - Args: - app: FastAPI application instance - - Returns: - FastApiMCP instance configured + The auth dependencies are attached by fastapi-mcp to the transport + routes it registers on mount(): the SSE connection endpoint and the + messages endpoint. See verify_mcp_access for the API key / JWT + semantics. Only the ``Authorization`` header is forwarded to the API + when a tool runs (fastapi-mcp's default), never ``X-MCP-API-Key``. """ - # Include MCP specific routes in the main app - app.include_router(mcp_router, prefix="/mcp-routes", tags=["mcp"]) - - # Create MCP instance with app. The auth dependencies are attached by - # fastapi-mcp to the transport routes it registers on mount(): the SSE - # connection endpoint and the messages endpoint. See verify_mcp_access - # for the API key / JWT semantics. - mcp = FastApiMCP( + return FastApiMCP( app, + name=settings.MCP_TITLE, + description=settings.MCP_DESCRIPTION, + include_tags=list(MCP_TOOL_TAGS), auth_config=AuthConfig(dependencies=[Depends(verify_mcp_access)]), + headers=["authorization"], ) - return mcp - - -def configure_mcp_tools(mcp: FastApiMCP) -> None: - """Configure specific MCP tools and their permissions. - - Args: - mcp: FastApiMCP instance to configure - """ - # Example: Configure specific endpoints for MCP exposure - # This can be used to customize which endpoints are exposed via MCP - # and with what permissions - - # Include all API endpoints by default - # You can add filters or custom tool configurations here - - pass - def setup_mcp_server(app: FastAPI) -> FastApiMCP | None: - """Setup MCP server for the FastAPI application. - - Args: - app: FastAPI application instance + """Create the MCP server and mount it at ``settings.MCP_MOUNT_PATH``. - Returns: - FastApiMCP instance if MCP is enabled, None otherwise + Call it after every API router is included: tools are built from the + routes that exist at that point. """ if not settings.MCP_ENABLED: return None - # Create MCP router - mcp = create_mcp_router(app) - - # Configure MCP tools - configure_mcp_tools(mcp) - - # Mount MCP server at the configured path + mcp = create_mcp_server(app) mcp.mount(mount_path=settings.MCP_MOUNT_PATH) - return mcp diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/schemas/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/schemas/items.py-tpl index de717fc..f01654d 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/schemas/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/schemas/items.py-tpl @@ -1,66 +1,50 @@ """ Pydantic schemas for items endpoints. """ -from pydantic import BaseModel, Field + +from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator class ItemBase(BaseModel): - """Base item schema.""" + """Fields shared by every item schema.""" + name: str = Field(..., min_length=1, max_length=100, description="Item name") - description: str | None = Field(None, max_length=500, description="Item description") + description: str | None = Field( + None, max_length=500, description="Item description" + ) price: float = Field(..., gt=0, description="Item price") tax: float | None = Field(None, ge=0, description="Item tax") class ItemCreate(ItemBase): - """Schema for creating a new item.""" - pass + """Body of POST /items and PUT /items/{item_id} (full replacement).""" class ItemUpdate(BaseModel): - """Schema for updating an item.""" + """Body of PATCH /items/{item_id}: every field optional. + + Omitted fields are left untouched. ``description`` and ``tax`` are + nullable, so an explicit ``null`` clears them; ``name`` and ``price`` are + required on an item, so an explicit ``null`` for them is rejected (422). + """ + name: str | None = Field(None, min_length=1, max_length=100) description: str | None = Field(None, max_length=500) price: float | None = Field(None, gt=0) tax: float | None = Field(None, ge=0) - -class ItemResponse(ItemBase): - """Schema for item response.""" - id: int = Field(..., description="Item ID") - owner_id: str = Field(..., description="Item owner ID") - - class Config: - """Pydantic configuration.""" - from_attributes = True + @field_validator("name", "price") + @classmethod + def _reject_explicit_null(cls, value: object, info: ValidationInfo) -> object: + if value is None: + raise ValueError(f"{info.field_name} must not be null") + return value -class ItemListResponse(BaseModel): - """Schema for item list response.""" - items: list[ItemResponse] - total: int - page: int - page_size: int - - class Config: - """Pydantic configuration.""" - from_attributes = True - - -class AuthToken(BaseModel): - """Schema for authentication token.""" - access_token: str - token_type: str - - -class UserLogin(BaseModel): - """Schema for user login.""" - username: str - password: str +class ItemRead(ItemBase): + """An item as returned by the API.""" + id: int = Field(..., description="Item ID") + owner_id: str = Field(..., description="Item owner ID") -class UserInfo(BaseModel): - """Schema for user information.""" - user_id: str - username: str - active: bool = True + model_config = ConfigDict(from_attributes=True) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/schemas/mcp_server.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/schemas/mcp_server.py-tpl new file mode 100644 index 0000000..4e685dc --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/schemas/mcp_server.py-tpl @@ -0,0 +1,15 @@ +""" +Pydantic schema for the MCP server description resource. +""" + +from pydantic import BaseModel + + +class McpServerRead(BaseModel): + """How this application exposes its MCP server.""" + + enabled: bool + mount_path: str + title: str + description: str + tool_tags: list[str] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/schemas/users.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/schemas/users.py-tpl new file mode 100644 index 0000000..86d3f8c --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/src/schemas/users.py-tpl @@ -0,0 +1,23 @@ +""" +Pydantic schemas for authentication and users endpoints. +""" + +from pydantic import BaseModel, ConfigDict + + +class Token(BaseModel): + """OAuth2 access token response (RFC 6749, section 5.1).""" + + access_token: str + token_type: str = "bearer" + + +class UserRead(BaseModel): + """A user as returned by the API (no password hash).""" + + user_id: str + username: str + active: bool = True + is_superuser: bool = False + + model_config = ConfigDict(from_attributes=True) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/conftest.py-tpl index 904cfa3..6580ccf 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/conftest.py-tpl @@ -1,27 +1,64 @@ """ Test configuration and fixtures. """ + +from collections.abc import Callable, Iterator +from functools import cache + import pytest from fastapi.testclient import TestClient -from src.api.routes.auth import create_access_token + +from src.auth import users +from src.auth.security import create_access_token, get_password_hash from src.core.config import settings +from src.crud.items import item_store from src.main import app +TEST_PASSWORD = "testpass123" + + +@cache +def _test_users() -> dict[str, users.User]: + """Accounts used only by the tests (hashed once per session).""" + hashed = get_password_hash(TEST_PASSWORD) + return { + "test_user": users.User("test_user", "testuser", hashed), + "other_user": users.User("other_user", "otheruser", hashed), + "inactive_user": users.User("inactive_user", "inactive", hashed, active=False), + "test_admin": users.User("test_admin", "testadmin", hashed, is_superuser=True), + } + @pytest.fixture -def client(): - """Create test client.""" - return TestClient(app) +def client() -> Iterator[TestClient]: + with TestClient(app) as test_client: + yield test_client + + +@pytest.fixture(autouse=True) +def reset_item_store() -> Iterator[None]: + """Every test starts from the three seed items.""" + item_store.reset() + yield + item_store.reset() + + +@pytest.fixture(autouse=True) +def test_users(monkeypatch: pytest.MonkeyPatch) -> dict[str, users.User]: + """Add the test accounts to whatever the user store returns.""" + original = users.get_users_db + monkeypatch.setattr(users, "get_users_db", lambda: {**original(), **_test_users()}) + return _test_users() @pytest.fixture -def demo_users(monkeypatch): +def demo_users(monkeypatch: pytest.MonkeyPatch) -> None: """Enable the built-in demo accounts (off by default) for one test.""" monkeypatch.setattr(settings, "ENABLE_DEMO_USERS", True) @pytest.fixture -def mcp_api_key(monkeypatch): +def mcp_api_key(monkeypatch: pytest.MonkeyPatch) -> str: """Protect the MCP endpoint with a static API key for one test.""" key = "test-mcp-api-key" monkeypatch.setattr(settings, "MCP_API_KEY", key) @@ -29,39 +66,34 @@ def mcp_api_key(monkeypatch): @pytest.fixture -def no_mcp_api_key(monkeypatch): +def no_mcp_api_key(monkeypatch: pytest.MonkeyPatch) -> None: """Make sure MCP_API_KEY is unset, whatever .env says.""" monkeypatch.setattr(settings, "MCP_API_KEY", None) @pytest.fixture -def test_user(): - """Test user data.""" - return { - "user_id": "test_user", - "username": "testuser", - "password": "testpass123", - } +def headers_for() -> Callable[[str], dict[str, str]]: + """``headers_for("test_admin")``: bearer headers for a test account.""" + + def make(user_id: str) -> dict[str, str]: + token = create_access_token(data={"sub": user_id}) + return {"Authorization": f"Bearer {token}"} + + return make @pytest.fixture -def auth_token(test_user): - """Create authentication token for test user.""" - token = create_access_token( - data={"sub": test_user["user_id"], "username": test_user["username"]} - ) - return token +def auth_token() -> str: + return create_access_token(data={"sub": "test_user"}) @pytest.fixture -def auth_headers(auth_token): - """Create authorization headers.""" +def auth_headers(auth_token: str) -> dict[str, str]: return {"Authorization": f"Bearer {auth_token}"} @pytest.fixture -def test_item(): - """Test item data.""" +def test_item() -> dict[str, object]: return { "name": "Test Item", "description": "This is a test item", diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_auth.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_auth.py-tpl index 2b0434f..500f956 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_auth.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_auth.py-tpl @@ -1,111 +1,167 @@ """ -Tests for authentication API endpoints. +Tests for the token endpoint, user endpoints and the demo-user gate. """ + import os import subprocess import sys +from datetime import timedelta from pathlib import Path +import jwt +import pytest from fastapi.testclient import TestClient -from src.api.routes.auth import DEMO_USER_CREDENTIALS +from src.auth.security import create_access_token +from src.auth.users import DEMO_USER_CREDENTIALS from src.core.config import Settings, settings +TOKEN_URL = f"{settings.API_V1_PREFIX}/auth/token" +ME_URL = f"{settings.API_V1_PREFIX}/users/me" +USERS_URL = f"{settings.API_V1_PREFIX}/users" + + +def _login(client: TestClient, username: str, password: str): + return client.post(TOKEN_URL, data={"username": username, "password": password}) -def test_login_valid_credentials(client: TestClient, demo_users): - """Test login with valid credentials.""" - login_data = {"username": "user1", "password": "password123"} - response = client.post("/api/v1/auth/login", json=login_data) + +def test_token_valid_credentials(client: TestClient): + response = _login(client, "testuser", "testpass123") assert response.status_code == 200 data = response.json() - assert "access_token" in data - assert "token_type" in data assert data["token_type"] == "bearer" + me = client.get(ME_URL, headers={"Authorization": f"Bearer {data['access_token']}"}) + assert me.status_code == 200 + assert me.json()["user_id"] == "test_user" -def test_login_invalid_credentials(client: TestClient, demo_users): - """Test login with invalid credentials.""" - login_data = {"username": "user1", "password": "wrongpassword"} - response = client.post("/api/v1/auth/login", json=login_data) +def test_token_invalid_credentials(client: TestClient): + response = _login(client, "testuser", "wrongpassword") assert response.status_code == 401 + assert response.headers["www-authenticate"] == "Bearer" + assert response.json() == {"detail": "Incorrect username or password"} + + +def test_token_nonexistent_user(client: TestClient): + response = _login(client, "nonexistent", "password123") + assert response.status_code == 401 + + +def test_token_endpoint_takes_a_form_not_json(client: TestClient): + response = client.post( + TOKEN_URL, json={"username": "testuser", "password": "testpass123"} + ) + assert response.status_code == 422 + +def test_json_login_endpoint_is_gone(client: TestClient): + response = client.post( + f"{settings.API_V1_PREFIX}/auth/login", + json={"username": "testuser", "password": "testpass123"}, + ) + assert response.status_code == 404 -def test_login_nonexistent_user(client: TestClient): - """Test login with nonexistent user.""" - login_data = {"username": "nonexistent", "password": "password123"} - response = client.post("/api/v1/auth/login", json=login_data) + +def test_current_user_without_token(client: TestClient): + response = client.get(ME_URL) assert response.status_code == 401 + assert response.headers["www-authenticate"] == "Bearer" -def test_oauth2_token_valid_credentials(client: TestClient, demo_users): - """Test OAuth2 token endpoint with valid credentials.""" - token_data = {"username": "user1", "password": "password123"} - response = client.post("/api/v1/auth/token", data=token_data) +def test_current_user_with_token(client: TestClient, auth_headers): + response = client.get(ME_URL, headers=auth_headers) assert response.status_code == 200 - data = response.json() - assert "access_token" in data - assert "token_type" in data - assert data["token_type"] == "bearer" + assert response.json() == { + "user_id": "test_user", + "username": "testuser", + "active": True, + "is_superuser": False, + } -def test_oauth2_token_invalid_credentials(client: TestClient, demo_users): - """Test OAuth2 token endpoint with invalid credentials.""" - token_data = {"username": "user1", "password": "wrongpassword"} - response = client.post("/api/v1/auth/token", data=token_data) +def test_current_user_with_invalid_token(client: TestClient): + response = client.get(ME_URL, headers={"Authorization": "Bearer invalid_token"}) assert response.status_code == 401 + assert response.headers["www-authenticate"] == "Bearer" -def test_get_current_user_without_token(client: TestClient): - """Test getting current user without authentication token.""" - response = client.get("/api/v1/auth/me") +def test_expired_token_is_rejected(client: TestClient): + token = create_access_token({"sub": "test_user"}, timedelta(minutes=-1)) + response = client.get(ME_URL, headers={"Authorization": f"Bearer {token}"}) assert response.status_code == 401 -def test_get_current_user_with_token(client: TestClient, demo_users): - """Test getting current user with valid token.""" - # First, login to get a token - login_data = {"username": "user1", "password": "password123"} - login_response = client.post("/api/v1/auth/login", json=login_data) - token = login_response.json()["access_token"] +def _signed(claims: dict[str, object]) -> str: + """A token signed with the real key, carrying exactly ``claims``.""" + return jwt.encode(claims, settings.SECRET_KEY, algorithm=settings.ALGORITHM) - # Then, use the token to get current user - headers = {"Authorization": f"Bearer {token}"} - response = client.get("/api/v1/auth/me", headers=headers) - assert response.status_code == 200 - data = response.json() - assert data["username"] == "user1" - assert data["user_id"] == "user1" - assert data["active"] == True + +@pytest.mark.parametrize( + "claims", + [ + {"sub": "test_user", "type": "access"}, # no exp: would never expire + {"type": "access", "exp": 4102444800}, # no subject + {"sub": "test_user", "exp": 4102444800}, # no type + {"sub": "test_user", "type": "refresh", "exp": 4102444800}, + ], + ids=["no-exp", "no-sub", "no-type", "wrong-type"], +) +def test_signed_token_without_required_claims_is_rejected( + client: TestClient, claims: dict[str, object] +): + response = client.get( + ME_URL, headers={"Authorization": f"Bearer {_signed(claims)}"} + ) + assert response.status_code == 401 + assert response.headers["www-authenticate"] == "Bearer" + + +def test_issued_tokens_carry_the_required_claims(): + token = create_access_token({"sub": "test_user"}) + payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) + assert payload["type"] == "access" + assert {"exp", "sub", "type"} <= payload.keys() -def test_get_current_user_with_invalid_token(client: TestClient): - """Test getting current user with invalid token.""" - headers = {"Authorization": "Bearer invalid_token"} - response = client.get("/api/v1/auth/me", headers=headers) +def test_token_for_unknown_user_is_rejected(client: TestClient, headers_for): + response = client.get(ME_URL, headers=headers_for("deleted_user")) assert response.status_code == 401 -def test_get_users_without_auth(client: TestClient): - """Test getting users without authentication.""" - response = client.get("/api/v1/auth/users") +def test_inactive_user_is_forbidden(client: TestClient, headers_for): + response = client.get(ME_URL, headers=headers_for("inactive_user")) + assert response.status_code == 403 + assert response.json() == {"detail": "Inactive user"} + + +def test_list_users_requires_authentication(client: TestClient): + response = client.get(USERS_URL) assert response.status_code == 401 -def test_get_users_with_auth(client: TestClient, demo_users): - """Test getting users with authentication.""" - # First, login to get a token - login_data = {"username": "user1", "password": "password123"} - login_response = client.post("/api/v1/auth/login", json=login_data) - token = login_response.json()["access_token"] +def test_list_users_forbidden_for_regular_users(client: TestClient, auth_headers): + response = client.get(USERS_URL, headers=auth_headers) + assert response.status_code == 403 + assert response.json() == {"detail": "Not enough privileges"} - # Then, use the token to get users - headers = {"Authorization": f"Bearer {token}"} - response = client.get("/api/v1/auth/users", headers=headers) + +def test_list_users_for_superuser_is_paginated(client: TestClient, headers_for): + response = client.get( + USERS_URL, params={"limit": 2, "offset": 1}, headers=headers_for("test_admin") + ) assert response.status_code == 200 - data = response.json() - assert isinstance(data, list) - assert len(data) > 0 - assert all("username" in user for user in data) + body = response.json() + assert body["total"] == 4 + assert (body["limit"], body["offset"]) == (2, 1) + assert [user["user_id"] for user in body["items"]] == ["other_user", "test_admin"] + assert all("hashed_password" not in user for user in body["items"]) + + +def test_list_users_rejects_out_of_range_limit(client: TestClient, headers_for): + response = client.get( + USERS_URL, params={"limit": 101}, headers=headers_for("test_admin") + ) + assert response.status_code == 422 def test_demo_users_flag_defaults_to_off(monkeypatch): @@ -119,34 +175,22 @@ def test_demo_users_disabled(client: TestClient, monkeypatch): """Demo accounts must not authenticate while ENABLE_DEMO_USERS is off.""" monkeypatch.setattr(settings, "ENABLE_DEMO_USERS", False) for username, password in DEMO_USER_CREDENTIALS.items(): - response = client.post( - "/api/v1/auth/login", json={"username": username, "password": password} - ) - assert response.status_code == 401 - response = client.post( - "/api/v1/auth/token", data={"username": username, "password": password} - ) - assert response.status_code == 401 + assert _login(client, username, password).status_code == 401 def test_demo_users_enabled(client: TestClient, demo_users): """Every demo account can log in once ENABLE_DEMO_USERS is on.""" for username, password in DEMO_USER_CREDENTIALS.items(): - response = client.post( - "/api/v1/auth/login", json={"username": username, "password": password} - ) + response = _login(client, username, password) assert response.status_code == 200 assert response.json()["token_type"] == "bearer" -def test_users_list_empty_without_demo_users( - client: TestClient, auth_headers, monkeypatch -): - """With demo users off the user store is empty.""" - monkeypatch.setattr(settings, "ENABLE_DEMO_USERS", False) - response = client.get("/api/v1/auth/users", headers=auth_headers) - assert response.status_code == 200 - assert response.json() == [] +def test_demo_admin_is_the_only_demo_superuser(client: TestClient, demo_users): + for username, password in DEMO_USER_CREDENTIALS.items(): + token = _login(client, username, password).json()["access_token"] + response = client.get(USERS_URL, headers={"Authorization": f"Bearer {token}"}) + assert response.status_code == (200 if username == "admin" else 403) def test_demo_user_hashes_not_computed_at_import(): @@ -155,7 +199,7 @@ def test_demo_user_hashes_not_computed_at_import(): env = {**os.environ, "ENABLE_DEMO_USERS": "false", "ENVIRONMENT": "development"} code = ( "import src.main\n" - "from src.api.routes.auth import _demo_users\n" + "from src.auth.users import _demo_users\n" "assert _demo_users.cache_info().currsize == 0\n" ) result = subprocess.run( diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_config.py-tpl index 33ba894..9268a94 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_config.py-tpl @@ -1,116 +1,265 @@ -""" -Tests for the production safety checks in application settings. -""" - +# -------------------------------------------------------------------------- +# Settings validation: the SECRET_KEY rule, ENVIRONMENT values, +# environment variable names, the CORS wildcard and the demo users. +# -------------------------------------------------------------------------- +import json +import os +import secrets +import subprocess +import sys from pathlib import Path +from typing import Any import pytest from pydantic import ValidationError -from src.core.config import KNOWN_EXAMPLE_SECRET_KEYS, Settings +from src.core.config import KNOWN_EXAMPLE_SECRET_KEYS, MIN_SECRET_KEY_BYTES, Settings -STRONG_KEY = "x" * 64 +PROJECT_ROOT = Path(__file__).resolve().parents[1] +APP_MODULE = "src.main" +#: Settings without a default; none in this template. +REQUIRED: dict[str, Any] = {} + +STRONG_KEY = "k" * MIN_SECRET_KEY_BYTES +#: Every environment except development refuses a missing, public or short +#: SECRET_KEY. +STRICT_ENVIRONMENTS = ["staging", "production"] @pytest.fixture(autouse=True) -def clean_env(monkeypatch): - """Keep shell environment variables from leaking into Settings().""" - for name in ( - "ENVIRONMENT", - "SECRET_KEY", - "ENABLE_DEMO_USERS", - "BACKEND_CORS_ORIGINS", +def _isolated_settings_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Shell variables, in any spelling, must not leak into Settings().""" + for name in list(os.environ): + if name.upper() in {"ENVIRONMENT", "SECRET_KEY", "BACKEND_CORS_ORIGINS"}: + monkeypatch.delenv(name) + + +def make_settings(env_file: Path | None = None, **values: Any) -> Settings: + """Settings from explicit values; a developer's .env is never read.""" + return Settings(_env_file=env_file, **{**REQUIRED, **values}) # type: ignore[call-arg] + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_require_an_explicit_secret_key(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"must be set explicitly when ENVIRONMENT={environment}" ): - monkeypatch.delenv(name, raising=False) + make_settings(ENVIRONMENT=environment) + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_refuse_a_short_secret_key(environment: str) -> None: + short_key = "k" * (MIN_SECRET_KEY_BYTES - 1) -def make_settings(**values) -> Settings: - """Build settings from explicit values only, ignoring any .env file.""" - return Settings(_env_file=None, **values) + with pytest.raises(ValidationError, match=f"at least {MIN_SECRET_KEY_BYTES} bytes"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=short_key) +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) @pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) -def test_production_rejects_example_secret_key(example_key: str): - with pytest.raises(ValidationError) as exc_info: - make_settings(ENVIRONMENT="production", SECRET_KEY=example_key) - message = str(exc_info.value) - assert "SECRET_KEY" in message - assert "openssl rand -hex 32" in message +def test_strict_environments_refuse_every_public_example_key( + environment: str, example_key: str +) -> None: + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=f" {example_key} ") + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environment_errors_say_how_to_generate_a_key(environment: str) -> None: + with pytest.raises(ValidationError, match="token_urlsafe"): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_an_explicit_strong_key(environment: str) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + + assert settings.ENVIRONMENT == environment + assert settings.SECRET_KEY == STRONG_KEY + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_the_key_fastkit_writes_to_env( + tmp_path: Path, environment: str +) -> None: + env_file = tmp_path / ".env" + env_file.write_text( + f"ENVIRONMENT={environment}\nSECRET_KEY={secrets.token_urlsafe(32)}\n", + encoding="utf-8", + ) + + assert make_settings(env_file).ENVIRONMENT == environment + + +def test_development_without_a_key_uses_a_random_one() -> None: + settings = make_settings(ENVIRONMENT="development") + + assert len(settings.SECRET_KEY.encode()) >= MIN_SECRET_KEY_BYTES + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_development_only_warns_about_an_example_key() -> None: + example_key = sorted(KNOWN_EXAMPLE_SECRET_KEYS)[0] + + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings(ENVIRONMENT="development", SECRET_KEY=example_key) + + assert settings.SECRET_KEY == example_key + + +@pytest.mark.parametrize("value", ["Production", "PRODUCTION", " production", "prod"]) +def test_unknown_environment_values_fail_closed(value: str) -> None: + with pytest.raises(ValidationError, match="ENVIRONMENT"): + make_settings(ENVIRONMENT=value, SECRET_KEY=STRONG_KEY) + + +def test_environment_variable_names_are_case_insensitive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("environment", "production") + + with pytest.raises(ValidationError, match="must be set explicitly"): + make_settings() + + monkeypatch.setenv("secret_key", STRONG_KEY) + + assert make_settings().ENVIRONMENT == "production" + + +@pytest.mark.parametrize("raw", ["*", " * ", '["*"]', "*,http://localhost:3000"]) +def test_cors_wildcard_is_accepted(monkeypatch: pytest.MonkeyPatch, raw: str) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + + assert make_settings().all_cors_origins == ["*"] + + +def test_cors_origins_must_be_urls_or_the_wildcard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + + with pytest.raises(ValidationError): + make_settings() + + +#: Runs in a fresh interpreter: the app reads its settings at import time. +_PREFLIGHT = f""" +import json +from fastapi.testclient import TestClient +from {APP_MODULE} import app + +headers = {{ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "GET", +}} +response = TestClient(app).options("/", headers=headers) +allowed = {{ + k: v for k, v in response.headers.items() if k.startswith("access-control-allow-") +}} +print(json.dumps(allowed)) +""" @pytest.mark.parametrize( - "example_key", + ("origins", "allow_origin", "allow_credentials"), [ - # Placeholders used by the other fastkit templates' examples; a key - # copied from one of them must not pass in production either. - "changethis", - "changethis-please-generate-a-real-32-byte-key", - "changethis-please-use-openssl-rand-hex-32", - "your-secret-key-here-change-in-production", + ("*", "*", None), + ("http://localhost:3000", "http://localhost:3000", "true"), ], ) -def test_shared_placeholder_keys_are_rejected_in_production(example_key: str): - assert example_key in KNOWN_EXAMPLE_SECRET_KEYS - with pytest.raises(ValidationError, match="public example value"): - make_settings(ENVIRONMENT="production", SECRET_KEY=example_key) +def test_cors_wildcard_is_never_combined_with_credentials( + origins: str, allow_origin: str, allow_credentials: str | None +) -> None: + env = { + **os.environ, + **{name: str(value) for name, value in REQUIRED.items()}, + "BACKEND_CORS_ORIGINS": origins, + "ENVIRONMENT": "development", + } + result = subprocess.run( + [sys.executable, "-c", _PREFLIGHT], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + check=False, + ) + + assert result.returncode == 0, result.stderr + headers = json.loads(result.stdout.strip().splitlines()[-1]) + assert headers["access-control-allow-origin"] == allow_origin + assert headers.get("access-control-allow-credentials") == allow_credentials -def test_env_example_secret_key_is_rejected_in_production(): +@pytest.fixture(autouse=True) +def clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep shell environment variables from leaking into Settings().""" + for name in ( + "ENVIRONMENT", + "SECRET_KEY", + "ENABLE_DEMO_USERS", + "BACKEND_CORS_ORIGINS", + ): + monkeypatch.delenv(name, raising=False) + + +def test_env_example_secret_key_is_rejected_outside_development() -> None: """The SECRET_KEY shipped in .env.example is on the deny list.""" env_example = Path(__file__).resolve().parent.parent / ".env.example" if not env_example.exists(): pytest.skip(".env.example not present") lines = [ line.split("=", 1)[1].strip() - for line in env_example.read_text().splitlines() + for line in env_example.read_text(encoding="utf-8").splitlines() if line.startswith("SECRET_KEY=") ] assert len(lines) == 1 assert lines[0] in KNOWN_EXAMPLE_SECRET_KEYS -def test_production_requires_explicit_secret_key(): - with pytest.raises(ValidationError, match="SECRET_KEY must be set explicitly"): - make_settings(ENVIRONMENT="production") - - -def test_production_rejects_demo_users(): - with pytest.raises(ValidationError, match="ENABLE_DEMO_USERS"): +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_reject_demo_users(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"ENABLE_DEMO_USERS.*ENVIRONMENT={environment}" + ): make_settings( - ENVIRONMENT="production", SECRET_KEY=STRONG_KEY, ENABLE_DEMO_USERS=True + ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY, ENABLE_DEMO_USERS=True ) -def test_production_accepts_strong_key_without_demo_users(): - settings = make_settings(ENVIRONMENT="production", SECRET_KEY=STRONG_KEY) - assert settings.ENVIRONMENT == "production" +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_strong_key_without_demo_users( + environment: str, +) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + assert settings.ENVIRONMENT == environment assert settings.ENABLE_DEMO_USERS is False -def test_production_guard_reads_environment_variables(monkeypatch): +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_guard_reads_environment_variables( + monkeypatch: pytest.MonkeyPatch, environment: str +) -> None: """The guard also fires when values come from the environment.""" - monkeypatch.setenv("ENVIRONMENT", "production") + monkeypatch.setenv("ENVIRONMENT", environment) monkeypatch.setenv("SECRET_KEY", "changethis-please-use-openssl-rand-hex-32") - with pytest.raises(ValidationError): - Settings(_env_file=None) + with pytest.raises(ValidationError, match="public example value"): + make_settings() -@pytest.mark.parametrize("environment", ["development", "staging"]) -def test_non_production_allows_example_key_and_demo_users(environment: str): - settings = make_settings( - ENVIRONMENT=environment, - SECRET_KEY="changethis-please-use-openssl-rand-hex-32", - ENABLE_DEMO_USERS=True, - ) +def test_development_allows_example_key_and_demo_users() -> None: + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings( + ENVIRONMENT="development", + SECRET_KEY="changethis-please-use-openssl-rand-hex-32", + ENABLE_DEMO_USERS=True, + ) assert settings.ENABLE_DEMO_USERS is True -def test_default_secret_key_is_random_per_process(): - settings = make_settings() - assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS - assert len(settings.SECRET_KEY) >= 32 - - @pytest.mark.parametrize( "raw", [ @@ -119,37 +268,33 @@ def test_default_secret_key_is_random_per_process(): '["http://localhost:3000", "http://localhost:8080"]', ], ) -def test_cors_origins_from_environment(monkeypatch, raw: str): +def test_cors_origins_from_environment( + monkeypatch: pytest.MonkeyPatch, raw: str +) -> None: """Comma-separated and JSON-list values both load from the environment.""" monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) - settings = Settings(_env_file=None) + settings = make_settings() assert settings.all_cors_origins == [ "http://localhost:3000", "http://localhost:8080", ] -def test_cors_origins_from_env_file(tmp_path: Path): +def test_cors_origins_from_env_file(tmp_path: Path) -> None: """The commented example line in .env.example works once uncommented.""" env_file = tmp_path / ".env" env_file.write_text( - "BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:8080\n" + "BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:8080\n", + encoding="utf-8", ) - settings = Settings(_env_file=env_file) + settings = make_settings(env_file) assert settings.all_cors_origins == [ "http://localhost:3000", "http://localhost:8080", ] -def test_empty_cors_origins_is_empty_list(monkeypatch): +def test_empty_cors_origins_is_empty_list(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("BACKEND_CORS_ORIGINS", "") - assert Settings(_env_file=None).all_cors_origins == [] assert make_settings(BACKEND_CORS_ORIGINS="").all_cors_origins == [] assert make_settings().all_cors_origins == [] - - -def test_invalid_cors_origin_is_rejected(monkeypatch): - monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") - with pytest.raises(ValidationError): - Settings(_env_file=None) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_items.py-tpl index 7353e34..67c49e1 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_items.py-tpl @@ -1,95 +1,259 @@ """ Tests for items API endpoints. """ + +import pytest from fastapi.testclient import TestClient +from src.core.config import settings -def test_get_items(client: TestClient): - """Test getting items without authentication.""" - response = client.get("/api/v1/items/") - assert response.status_code == 200 - data = response.json() - assert "items" in data - assert "total" in data - assert "page" in data - assert "page_size" in data +ITEMS_URL = f"{settings.API_V1_PREFIX}/items" + + +def _create(client: TestClient, headers, **overrides): + body = {"name": "Thing", "price": 10.0, **overrides} + response = client.post(ITEMS_URL, json=body, headers=headers) + assert response.status_code == 201 + return response.json() + + +# --- read policy: public, credentials never change the result -------------- -def test_get_items_with_pagination(client: TestClient): - """Test getting items with pagination.""" - response = client.get("/api/v1/items/?page=1&page_size=2") +def test_list_items_envelope(client: TestClient): + response = client.get(ITEMS_URL) assert response.status_code == 200 - data = response.json() - assert len(data["items"]) <= 2 - assert data["page"] == 1 - assert data["page_size"] == 2 + body = response.json() + assert set(body) == {"items", "total", "limit", "offset"} + assert (body["total"], body["limit"], body["offset"]) == (3, 20, 0) + assert [item["id"] for item in body["items"]] == [1, 2, 3] + + +def test_collection_path_has_no_trailing_slash_redirect(client: TestClient): + assert client.get(ITEMS_URL, follow_redirects=False).status_code == 200 + + +def test_list_items_pagination_window(client: TestClient): + body = client.get(ITEMS_URL, params={"limit": 1, "offset": 1}).json() + assert body["total"] == 3 + assert [item["id"] for item in body["items"]] == [2] + + +@pytest.mark.parametrize("params", [{"limit": 0}, {"limit": 101}, {"offset": -1}]) +def test_list_items_rejects_out_of_range_pagination(client: TestClient, params): + assert client.get(ITEMS_URL, params=params).status_code == 422 + +@pytest.mark.parametrize( + "headers", + [ + {}, + {"Authorization": "Bearer garbage"}, + {"Authorization": "Bearer test-mcp-api-key"}, + ], + ids=["anonymous", "invalid-token", "non-jwt-credential"], +) +def test_reads_ignore_credentials(client: TestClient, headers): + anonymous_list = client.get(ITEMS_URL).json() + assert client.get(ITEMS_URL, headers=headers).json() == anonymous_list + assert client.get(f"{ITEMS_URL}/3", headers=headers).status_code == 200 -def test_get_item_by_id(client: TestClient): - """Test getting a specific item by ID.""" - response = client.get("/api/v1/items/1") + +def test_authenticated_reads_see_the_same_collection(client: TestClient, auth_headers): + """Signing in never narrows the collection or hides another user's item.""" + assert ( + client.get(ITEMS_URL, headers=auth_headers).json() + == client.get(ITEMS_URL).json() + ) + response = client.get(f"{ITEMS_URL}/3", headers=auth_headers) assert response.status_code == 200 - data = response.json() - assert data["id"] == 1 - assert "name" in data - assert "price" in data + assert response.json()["owner_id"] == "user2" def test_get_item_not_found(client: TestClient): - """Test getting a non-existent item.""" - response = client.get("/api/v1/items/999") + response = client.get(f"{ITEMS_URL}/999") assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +# --- create ------------------------------------------------------------------ def test_create_item_without_auth(client: TestClient, test_item): - """Test creating item without authentication.""" - response = client.post("/api/v1/items/", json=test_item) + response = client.post(ITEMS_URL, json=test_item) assert response.status_code == 401 + assert response.headers["www-authenticate"] == "Bearer" + + +def test_create_item_with_invalid_token(client: TestClient, test_item): + response = client.post( + ITEMS_URL, json=test_item, headers={"Authorization": "Bearer garbage"} + ) + assert response.status_code == 401 + +def test_create_item_inactive_user_forbidden( + client: TestClient, test_item, headers_for +): + response = client.post( + ITEMS_URL, json=test_item, headers=headers_for("inactive_user") + ) + assert response.status_code == 403 -def test_create_item_with_auth(client: TestClient, test_item, auth_headers): - """Test creating item with authentication.""" - response = client.post("/api/v1/items/", json=test_item, headers=auth_headers) + +def test_create_item_returns_201_and_location( + client: TestClient, test_item, auth_headers +): + response = client.post(ITEMS_URL, json=test_item, headers=auth_headers) assert response.status_code == 201 - data = response.json() - assert data["name"] == test_item["name"] - assert data["price"] == test_item["price"] - assert "id" in data - assert "owner_id" in data + created = response.json() + assert created == {**test_item, "id": 4, "owner_id": "test_user"} + location = response.headers["location"] + assert location.endswith(f"{ITEMS_URL}/4") + assert client.get(location).json() == created def test_create_item_invalid_data(client: TestClient, auth_headers): - """Test creating item with invalid data.""" - invalid_item = { - "name": "", # Empty name should fail - "price": -10, # Negative price should fail + response = client.post( + ITEMS_URL, json={"name": "", "price": -10}, headers=auth_headers + ) + assert response.status_code == 422 + + +# --- replace (PUT) and update (PATCH) --------------------------------------- + + +def test_put_replaces_every_field(client: TestClient, auth_headers): + created = _create(client, auth_headers, description="old", tax=1.0) + response = client.put( + f"{ITEMS_URL}/{created['id']}", + json={"name": "New", "price": 20.0}, + headers=auth_headers, + ) + assert response.status_code == 200 + assert response.json() == { + "id": created["id"], + "owner_id": "test_user", + "name": "New", + "price": 20.0, + "description": None, + "tax": None, } - response = client.post("/api/v1/items/", json=invalid_item, headers=auth_headers) + + +def test_put_requires_the_full_body(client: TestClient, auth_headers): + created = _create(client, auth_headers) + response = client.put( + f"{ITEMS_URL}/{created['id']}", json={"name": "Only"}, headers=auth_headers + ) assert response.status_code == 422 + assert client.get(f"{ITEMS_URL}/{created['id']}").json() == created -def test_update_item_without_auth(client: TestClient): - """Test updating item without authentication.""" - update_data = {"name": "Updated Item"} - response = client.put("/api/v1/items/1", json=update_data) - assert response.status_code == 401 +def test_put_rejects_null_name_without_mutating(client: TestClient, auth_headers): + created = _create(client, auth_headers) + response = client.put( + f"{ITEMS_URL}/{created['id']}", + json={"name": None, "price": 1.0}, + headers=auth_headers, + ) + assert response.status_code == 422 + assert client.get(f"{ITEMS_URL}/{created['id']}").json() == created -def test_update_item_with_auth(client: TestClient, auth_headers): - """Test updating item with authentication.""" - update_data = {"name": "Updated Item", "price": 199.99} - response = client.put("/api/v1/items/1", json=update_data, headers=auth_headers) - # Note: This might fail if the item doesn't belong to the test user - # In a real scenario, you would need proper test data setup +def test_patch_changes_only_sent_fields(client: TestClient, auth_headers): + created = _create(client, auth_headers, description="keep", tax=1.0) + response = client.patch( + f"{ITEMS_URL}/{created['id']}", json={"price": 15.0}, headers=auth_headers + ) + assert response.status_code == 200 + assert response.json() == {**created, "price": 15.0} -def test_delete_item_without_auth(client: TestClient): - """Test deleting item without authentication.""" - response = client.delete("/api/v1/items/1") - assert response.status_code == 401 +def test_patch_null_clears_a_nullable_field(client: TestClient, auth_headers): + created = _create(client, auth_headers, description="drop me") + response = client.patch( + f"{ITEMS_URL}/{created['id']}", json={"description": None}, headers=auth_headers + ) + assert response.status_code == 200 + assert response.json()["description"] is None -def test_delete_item_not_found(client: TestClient, auth_headers): - """Test deleting non-existent item.""" - response = client.delete("/api/v1/items/999", headers=auth_headers) - assert response.status_code == 404 +@pytest.mark.parametrize("field", ["name", "price"]) +def test_patch_rejects_null_for_required_fields( + client: TestClient, auth_headers, field +): + created = _create(client, auth_headers) + response = client.patch( + f"{ITEMS_URL}/{created['id']}", json={field: None}, headers=auth_headers + ) + assert response.status_code == 422 + assert client.get(f"{ITEMS_URL}/{created['id']}").json() == created + + +def test_write_without_auth(client: TestClient): + assert ( + client.put(f"{ITEMS_URL}/1", json={"name": "x", "price": 1}).status_code == 401 + ) + assert client.patch(f"{ITEMS_URL}/1", json={"name": "x"}).status_code == 401 + assert client.delete(f"{ITEMS_URL}/1").status_code == 401 + + +def test_write_someone_elses_item_is_forbidden(client: TestClient, auth_headers): + """Seed item 1 belongs to user1, not to the test user.""" + url = f"{ITEMS_URL}/1" + before = client.get(url).json() + assert ( + client.put( + url, json={"name": "x", "price": 1}, headers=auth_headers + ).status_code + == 403 + ) + assert ( + client.patch(url, json={"name": "x"}, headers=auth_headers).status_code == 403 + ) + assert client.delete(url, headers=auth_headers).status_code == 403 + assert client.get(url).json() == before + + +def test_write_unknown_item_returns_404(client: TestClient, auth_headers): + url = f"{ITEMS_URL}/999" + for response in ( + client.put(url, json={"name": "x", "price": 1}, headers=auth_headers), + client.patch(url, json={"name": "x"}, headers=auth_headers), + client.delete(url, headers=auth_headers), + ): + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +# --- delete ------------------------------------------------------------------ + + +def test_delete_own_item_returns_204(client: TestClient, auth_headers): + created = _create(client, auth_headers) + response = client.delete(f"{ITEMS_URL}/{created['id']}", headers=auth_headers) + assert response.status_code == 204 + assert response.content == b"" + assert client.get(f"{ITEMS_URL}/{created['id']}").status_code == 404 + + +def test_store_is_reset_between_tests(client: TestClient): + """The previous tests created items; this one still sees the seed data.""" + assert client.get(ITEMS_URL).json()["total"] == 3 + + +def test_openapi_declares_error_responses(client: TestClient): + paths = client.get("/openapi.json").json()["paths"] + item = paths[f"{ITEMS_URL}/{{item_id}}"] + assert set(item["get"]["responses"]) >= {"200", "404"} + for method in ("put", "patch", "delete"): + assert set(item[method]["responses"]) >= {"401", "403", "404"} + assert set(paths[ITEMS_URL]["post"]["responses"]) >= {"201", "401"} + + +def test_openapi_documents_www_authenticate_on_401(client: TestClient): + """Every documented 401 tells the client which authentication scheme to use.""" + paths = client.get("/openapi.json").json()["paths"] + unauthorized = paths[ITEMS_URL]["post"]["responses"]["401"] + assert "WWW-Authenticate" in unauthorized["headers"] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_mcp.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_mcp.py-tpl index c8d4e26..b8311f9 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_mcp.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/tests/test_mcp.py-tpl @@ -1,42 +1,108 @@ """ Tests for MCP (Model Context Protocol) functionality. """ + import json import uuid import anyio from fastapi.testclient import TestClient +from fastapi_mcp.types import HTTPRequestInfo from src.core.config import settings -from src.main import app +from src.main import app, mcp_server MCP_PATH = settings.MCP_MOUNT_PATH MCP_MESSAGES_PATH = f"{MCP_PATH}/messages/" UNKNOWN_SESSION = "?session_id=" + uuid.uuid4().hex -def test_mcp_hello_endpoint(client: TestClient): - """Test MCP hello world endpoint.""" - response = client.get("/mcp-routes/hello") +def test_mcp_server_resource(client: TestClient): + """The MCP server is described by a resource under the API prefix.""" + response = client.get(f"{settings.API_V1_PREFIX}/mcp-server") assert response.status_code == 200 - data = response.json() + assert response.json() == { + "enabled": settings.MCP_ENABLED, + "mount_path": settings.MCP_MOUNT_PATH, + "title": settings.MCP_TITLE, + "description": settings.MCP_DESCRIPTION, + "tool_tags": ["items"], + } - assert "message" in data - assert data["message"] == "Hello from MCP!" - assert data["status"] == "success" - assert "mcp_enabled" in data +def test_old_mcp_helper_routes_are_gone(client: TestClient): + assert client.get("/mcp-routes/hello").status_code == 404 + assert client.get("/mcp-routes/status").status_code == 404 -def test_mcp_status_endpoint(client: TestClient): - """Test MCP status endpoint.""" - response = client.get("/mcp-routes/status") - assert response.status_code == 200 - data = response.json() - assert "mcp_enabled" in data - assert "mcp_mount_path" in data - assert "mcp_title" in data - assert "mcp_description" in data +# --- which operations become MCP tools --------------------------------------- + + +def test_only_item_operations_are_exposed_as_tools(): + assert mcp_server is not None + assert {tool.name for tool in mcp_server.tools} == { + "list_items", + "get_item", + "create_item", + "replace_item", + "update_item", + "delete_item", + } + + +def test_auth_and_user_operations_are_never_tools(): + assert mcp_server is not None + exposed = {tool.name for tool in mcp_server.tools} + hidden = { + operation["operationId"] + for path in app.openapi()["paths"].values() + for operation in path.values() + if {"auth", "users"} & set(operation.get("tags", [])) + } + assert hidden >= {"login_for_access_token", "read_current_user", "list_users"} + assert not exposed & hidden + # Hidden operations cannot be called by name either. + assert set(mcp_server.operation_map) == exposed + + +def _run_tool(name: str, arguments: dict, headers: dict[str, str]): + """Run one tool the way fastapi-mcp does for a ``tools/call`` request.""" + assert mcp_server is not None + request_info = HTTPRequestInfo( + method="POST", + path=MCP_MESSAGES_PATH, + headers={key.lower(): value for key, value in headers.items()}, + cookies={}, + query_params={}, + body=None, + ) + + async def call(): + return await mcp_server._execute_api_tool( + client=mcp_server._http_client, + tool_name=name, + arguments=arguments, + operation_map=mcp_server.operation_map, + http_request_info=request_info, + ) + + return anyio.run(call) + + +def test_tools_forward_only_the_authorization_header(auth_token): + """A write tool acts as the JWT's user; X-MCP-API-Key never reaches the API.""" + result = _run_tool( + "create_item", + {"name": "From MCP", "price": 5.0}, + {"Authorization": f"Bearer {auth_token}", "X-MCP-API-Key": "secret"}, + ) + created = json.loads(result[0].text) + assert created["owner_id"] == "test_user" + + +def test_read_tools_work_with_any_forwarded_credential(): + result = _run_tool("list_items", {}, {"Authorization": "Bearer test-mcp-api-key"}) + assert json.loads(result[0].text)["total"] == 3 def _bearer(token: str) -> dict[str, str]: @@ -142,6 +208,24 @@ def test_mcp_messages_endpoint_requires_api_key(client: TestClient, mcp_api_key: assert response.status_code == 404 +def test_mcp_api_key_in_dedicated_header_is_accepted( + client: TestClient, mcp_api_key: str, auth_token +): + """X-MCP-API-Key opens the stream and leaves Authorization for a user JWT.""" + status_code, first_chunk = _open_sse_stream( + client, {"X-MCP-API-Key": mcp_api_key, **_bearer(auth_token)} + ) + assert status_code == 200 + assert "event: endpoint" in first_chunk + + +def test_mcp_api_key_wrong_dedicated_header_is_rejected( + client: TestClient, mcp_api_key: str +): + status_code, _ = _open_sse_stream(client, {"X-MCP-API-Key": "wrong-key"}) + assert status_code == 401 + + # --- default mode (no MCP_API_KEY): JWT required ---------------------------- @@ -165,20 +249,25 @@ def test_mcp_without_api_key_accepts_jwt( assert "event: endpoint" in first_chunk +def test_mcp_without_api_key_rejects_inactive_user( + client: TestClient, no_mcp_api_key, headers_for +): + status_code, _ = _open_sse_stream(client, headers_for("inactive_user")) + assert status_code == 403 + + def test_mcp_with_demo_user_login(client: TestClient, no_mcp_api_key, demo_users): """A token from the demo login opens the MCP endpoint.""" login_data = {"username": "user1", "password": "password123"} - login_response = client.post("/api/v1/auth/login", json=login_data) + login_response = client.post( + f"{settings.API_V1_PREFIX}/auth/token", data=login_data + ) assert login_response.status_code == 200 token = login_response.json()["access_token"] status_code, _ = _open_sse_stream(client, _bearer(token)) assert status_code == 200 - # Plain MCP helper routes stay public - assert client.get("/mcp-routes/hello", headers=_bearer(token)).status_code == 200 - assert client.get("/mcp-routes/status", headers=_bearer(token)).status_code == 200 - def test_root_endpoint_shows_mcp_info(client: TestClient): """Test that root endpoint shows MCP information.""" @@ -199,6 +288,4 @@ def test_health_check_endpoint(client: TestClient): """Test health check endpoint.""" response = client.get("/health") assert response.status_code == 200 - data = response.json() - assert data["status"] == "healthy" - assert "version" in data + assert response.json() == {"status": "ok"} diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.dockerignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.dockerignore-tpl new file mode 100644 index 0000000..9372d04 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.dockerignore-tpl @@ -0,0 +1,49 @@ +# Files Docker never sends to the build, so they cannot end up in the image. + +# Secrets: settings come from the environment at run time (docker run -e / +# --env-file, compose env_file), never from a file baked into the image. +.env +.env.* + +# VCS and editor state +.git +.gitignore +.gitattributes +.idea +.vscode +**/.DS_Store + +# Virtual environments +.venv +venv +env + +# Python, test and tool caches +**/__pycache__ +**/*.py[cod] +.pytest_cache +.mypy_cache +.ruff_cache +.coverage +.coverage.* +coverage.xml +htmlcov +dist +build +*.egg-info + +# Local SQLite databases +**/*.db +**/*.db-journal +**/*.db-wal +**/*.db-shm + +# The application image does not run the test suite. docker-compose.yml +# mounts the project directory into the app container for development, so +# `docker compose exec app bash scripts/test.sh` still finds tests/. +tests + +# Docker files themselves +Dockerfile +docker-compose*.yml +.dockerignore diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.env.example-tpl index f486540..0a47dc7 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.env.example-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.env.example-tpl @@ -1,11 +1,24 @@ # Backend -# Must be one of the values accepted by src/core/config.py: development | production +# One of: development, staging, production. ENVIRONMENT=development +# .env.example keeps a public placeholder; fastkit writes a unique key to the +# local, git-ignored .env. With any ENVIRONMENT other than development +# (staging or production) the app refuses to start when SECRET_KEY is unset, +# a public example value or shorter than 32 bytes. SECRET_KEY=changethis +# Allowed browser origins, comma-separated or a JSON list, e.g. +# http://localhost:3000,http://localhost:5173. "*" allows any origin, but +# then without credentials (cookies, Authorization headers). +BACKEND_CORS_ORIGINS= + # Postgres POSTGRES_SERVER=db POSTGRES_PORT=5432 POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres POSTGRES_DB=item_db + +# Test database. Defaults to _test on the same server; the test +# suite creates it when missing and never touches POSTGRES_DB. +# TEST_DATABASE_URL=postgresql+psycopg://postgres:postgres@db:5432/item_db_test diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/Dockerfile-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/Dockerfile-tpl index d81b61c..d9e2c8f 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/Dockerfile-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/Dockerfile-tpl @@ -1,18 +1,37 @@ FROM python:3.12-slim +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + WORKDIR /app +# Unprivileged runtime user with a fixed UID/GID, so file ownership on mounted +# volumes stays predictable across rebuilds. +RUN groupadd --system --gid 10001 app \ + && useradd --system --uid 10001 --gid app --no-create-home \ + --home-dir /nonexistent --shell /usr/sbin/nologin app + COPY requirements.txt . -COPY pyproject.toml . +RUN pip install --no-cache-dir -r requirements.txt + +# The source stays owned by root, read-only for the app user. .dockerignore +# keeps .env, tests/, virtualenvs and local databases out of the build context. +# scripts/pre-start.sh (migrations and seed data) only reads these files. +COPY pyproject.toml alembic.ini ./ COPY src/ src/ -COPY tests/ tests/ COPY scripts/ scripts/ -RUN pip install --no-cache-dir -r requirements.txt - ENV PYTHONPATH=/app ENV ENVIRONMENT=production +USER app + EXPOSE 8000 +# Liveness probe on GET /health (the slim image has no curl, so python). +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ + CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3)"] + +# docker-compose.yml runs scripts/pre-start.sh before the server and probes +# GET /ready (database included) instead of this liveness check. CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/README.md-tpl index 1952e7b..c7e46ed 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/README.md-tpl @@ -24,37 +24,44 @@ This project is a Docker containerized FastAPI-based item management API applica ├── Dockerfile ├── README.md ├── docker-compose.yml +├── pyproject.toml ├── requirements.txt -├── setup.py ├── alembic.ini ├── scripts │ ├── pre-start.sh │ └── test.sh ├── src │ ├── api -│ │ ├── api.py -│ │ ├── deps.py +│ │ ├── api.py # aggregates business routers (fastkit addroute anchors) +│ │ ├── deps.py # SessionDep │ │ └── routes +│ │ ├── health.py # GET /health, GET /ready │ │ └── items.py │ ├── core -│ │ ├── config.py -│ │ └── db.py +│ │ ├── config.py # the project's settings +│ │ ├── db.py # engine and seed data +│ │ ├── pagination.py # Page[T], limit/offset parameters +│ │ └── responses.py # error_responses() for OpenAPI │ ├── crud │ │ └── items.py +│ ├── models +│ │ └── items.py # ItemBase and the Item table +│ ├── schemas +│ │ └── items.py # ItemCreate, ItemUpdate, ItemRead │ ├── alembic │ │ ├── env.py │ │ └── versions/ -│ ├── schemas -│ │ └── items.py │ ├── utils │ │ ├── backend_pre_start.py │ │ ├── init_data.py │ │ └── tests_pre_start.py │ └── main.py └── tests - ├── __init__.py - ├── test_items.py - └── conftest.py + ├── conftest.py + ├── test_config.py + ├── test_health.py + ├── test_init_data.py + └── test_items.py ```` @@ -64,10 +71,10 @@ This project is a Docker containerized FastAPI-based item management API applica ````bash # Build and run with Docker Compose -$ docker-compose up -d +$ docker compose up -d # Check container status -$ docker-compose ps +$ docker compose ps ```` @@ -79,23 +86,41 @@ http://localhost:8000/redoc # ReDoc format ```` -### Run in Development Mode (Inside Container) +### Development Mode (Inside Container) + +The compose file already runs the app in development mode: the project +directory is bind-mounted into the container and uvicorn starts with +`--reload`, so edits on the host restart the server. Follow its output and +run commands inside the container with: ````bash -# Run the application in development mode (using `--reload` option) -$ docker-compose exec app uvicorn src.main:app --reload --host 0.0.0.0 +$ docker compose logs -f app +$ docker compose exec app bash scripts/test.sh ```` ## API Endpoints -| Method | Endpoint | Description | -|--------|------------------|----------------------------| -| GET | `/items/` | List all items | -| GET | `/items/{id}` | Get single item | -| POST | `/items/` | Create new item | -| PUT | `/items/{id}` | Update existing item | -| DELETE | `/items/{id}` | Delete item | +Business routes are mounted under `API_V1_PREFIX` (`/api/v1`); the probes stay at the root. + +| Method | Endpoint | Description | +|--------|---------------------------|-----------------------------------------------| +| GET | `/health` | Liveness probe, no database access | +| GET | `/ready` | Readiness probe: `SELECT 1`, 503 when down | +| GET | `/api/v1/items` | List items (`limit` 1-100, `offset` >= 0) | +| POST | `/api/v1/items` | Create an item (201 + `Location` header) | +| GET | `/api/v1/items/{item_id}` | Read an item | +| PUT | `/api/v1/items/{item_id}` | Replace an item (every field) | +| PATCH | `/api/v1/items/{item_id}` | Update only the fields sent | +| DELETE | `/api/v1/items/{item_id}` | Delete an item (204) | + +The list endpoint returns a page ordered by id: + +```json +{"items": [...], "total": 42, "limit": 20, "offset": 0} +``` + +A missing item answers 404 with `{"detail": "Item not found"}`. ## Key Features @@ -104,31 +129,45 @@ $ docker-compose exec app uvicorn src.main:app --reload --host 0.0.0.0 - ORM using SQLModel (SQLAlchemy + Pydantic) - Full containerization via Docker Compose - Automatic loading of initial sample data +- Paginated, ordered list endpoint and `/health` + `/ready` probes - Pydantic model-based data validation - Integrated test cases +- `ENVIRONMENT` (`development`, `staging` or `production`): every value except `development` + refuses to start unless `SECRET_KEY` is set explicitly, is at least 32 bytes long and is not a + public example value +- `BACKEND_CORS_ORIGINS`: comma-separated origins or a JSON list; `*` allows any origin, but + then without credentials such as cookies or `Authorization` headers ## Running Tests -Tests __must__ be run inside the Docker container: +The tests never touch the application database (`POSTGRES_DB`). They use a +dedicated PostgreSQL database, `_test` on the same server (or +`TEST_DATABASE_URL` when set), which the suite creates when it is missing. +Every test runs inside a transaction that is rolled back afterwards. ````bash # Run all tests inside the container -$ docker exec fastapi-psql-orm-app-1 bash scripts/test.sh +$ docker compose exec app bash scripts/test.sh + +# Run a specific test file +$ docker compose exec app pytest tests/test_items.py -v -# Run specific test file (example) -$ docker exec fastapi-psql-orm-app-1 bash -c "cd /app && pytest tests/test_items.py -v" +# Without a PostgreSQL server: in-memory SQLite (PostgreSQL stays the reference) +$ pytest --test-database-url sqlite:// ```` ## Database Management -After making a new database's change, you must migrate it. +Alembic owns the schema; the app does not create tables on startup. +`scripts/pre-start.sh` (the container entrypoint) runs `alembic upgrade head` +and seeds two sample items into an empty table. ````bash # Apply database migrations -$ docker exec fastapi-psql-orm-app-1 bash -c "alembic upgrade head" +$ docker compose exec app alembic upgrade head -# Create new migrations -$ docker exec fastapi-psql-orm-app-1 bash -c "alembic revision --autogenerate -m 'description'" +# Create a new migration after changing a model in src/models/ +$ docker compose exec app alembic revision --autogenerate -m "description" ```` For other FastAPI guides, please refer diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/alembic.ini-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/alembic.ini-tpl index 19a1ec7..941283b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/alembic.ini-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/alembic.ini-tpl @@ -13,7 +13,7 @@ script_location = src/alembic # sys.path path, will be prepended to sys.path if present. # defaults to the current working directory. -; prepend_sys_path = . +prepend_sys_path = . # timezone to use when rendering the date within the migration file # as well as the filename. diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/docker-compose.yml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/docker-compose.yml-tpl index da8e08e..d8b9f1b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/docker-compose.yml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/docker-compose.yml-tpl @@ -9,8 +9,9 @@ services: - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_DB=${POSTGRES_DB} + # Reachable from this machine only, not from the rest of the network. ports: - - "5432:5432" + - "127.0.0.1:5432:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"] interval: 5s @@ -29,12 +30,25 @@ services: - ENVIRONMENT=${ENVIRONMENT} ports: - "8000:8000" + # Development setup: the project directory replaces the image's copy so + # --reload picks up edits and tests/ is available inside the container. + # The app runs as the image's unprivileged user (UID 10001), which only + # needs to read these files. volumes: - ./:/app/ + healthcheck: + test: + - "CMD" + - "python" + - "-c" + - "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/ready', timeout=3)" + interval: 10s + timeout: 5s + retries: 5 + start_period: 30s command: > bash -c " - chmod +x ./scripts/pre-start.sh && - ./scripts/pre-start.sh && + bash ./scripts/pre-start.sh && uvicorn src.main:app --host 0.0.0.0 --port 8000 --reload " diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/pyproject.toml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/pyproject.toml-tpl index bd7a7a1..dd35f16 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/pyproject.toml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/pyproject.toml-tpl @@ -28,7 +28,6 @@ dev = [ "black>=26.10.1", "isort>=9.0.1", "mypy>=2.3.1", - "PyYAML>=6.0.3", ] [dependency-groups] @@ -38,7 +37,6 @@ dev = [ "black>=26.10.1", "isort>=9.0.1", "mypy>=2.3.1", - "PyYAML>=6.0.3", ] [tool.fastapi-fastkit] @@ -73,6 +71,7 @@ profile = "black" multi_line_output = 3 line_length = 88 known_first_party = ["src"] +skip_glob = ["src/alembic/versions/*"] [tool.mypy] python_version = "3.12" @@ -80,6 +79,7 @@ strict = true warn_return_any = true warn_unused_configs = true disallow_untyped_defs = true +exclude = "src/alembic/versions" [tool.pytest.ini_options] testpaths = ["tests"] @@ -87,7 +87,8 @@ python_files = ["test_*.py"] python_classes = ["Test*"] python_functions = ["test_*"] addopts = "-v --tb=short" - -[tool.alembic] -script_location = "src/alembic" -sqlalchemy.url = "postgresql://postgres:postgres@localhost/test_db" +filterwarnings = [ + # starlette's TestClient now prefers `httpx2`; this project pins httpx, so only + # that advisory notice (a UserWarning subclass) is silenced. + "ignore:Using `httpx` with `starlette.testclient` is deprecated:starlette.exceptions.StarletteDeprecationWarning", +] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/requirements.txt-tpl index fb55f5d..8c287e8 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/requirements.txt-tpl @@ -1,7 +1,7 @@ alembic==1.19.1 annotated-doc==0.0.5 annotated-types==0.8.0 -anyio==4.15.0 +anyio==4.16.0 ast-serialize==0.9.0 black==26.10.1 certifi==2026.10.23 @@ -35,7 +35,7 @@ pytokens==0.4.1 PyYAML==6.0.3 SQLAlchemy==2.0.52 sqlmodel==0.0.42 -starlette==1.6.0 +starlette==1.10.0 tenacity==9.1.4 typing-extensions==4.16.0 typing-inspection==0.4.4 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/lint.sh-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/lint.sh-tpl index 08e929f..2b89458 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/lint.sh-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/lint.sh-tpl @@ -2,4 +2,5 @@ set -x black . --check +isort . --check-only mypy src diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/pre-start.sh-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/pre-start.sh-tpl index c7b0424..cd1cd1e 100755 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/pre-start.sh-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/pre-start.sh-tpl @@ -6,10 +6,7 @@ set -x # Let the DB start python src/utils/backend_pre_start.py -# Ensure tables exist -python -c "from src.core.db import create_db_and_tables; create_db_and_tables()" - -# Run migrations +# Create or upgrade the schema alembic upgrade head # Create initial data in DB diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/setup.cfg-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/setup.cfg-tpl deleted file mode 100644 index 0d9980e..0000000 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/setup.cfg-tpl +++ /dev/null @@ -1,13 +0,0 @@ -[mypy] -warn_unused_configs = true -ignore_missing_imports = true - -[isort] -profile = black -line_length=100 -virtual_env=.venv - -[tool:pytest] -pythonpath = src -testpaths = tests -python_files = test_*.py diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/env.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/env.py-tpl index 8b0b0e1..0535d80 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/env.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/env.py-tpl @@ -1,8 +1,9 @@ from logging.config import fileConfig -from alembic import context from sqlalchemy import engine_from_config, pool +from alembic import context + # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config @@ -17,8 +18,10 @@ fileConfig(config.config_file_name) # type: ignore # target_metadata = mymodel.Base.metadata # target_metadata = None -from src.core.config import settings # noqa -from src.schemas.items import SQLModel # noqa +from sqlmodel import SQLModel # noqa: E402 + +from src.core.config import settings # noqa: E402 +from src.models import items # noqa: E402,F401 (registers the table) target_metadata = SQLModel.metadata @@ -28,11 +31,11 @@ target_metadata = SQLModel.metadata # ... etc. -def get_url(): +def get_url() -> str: return str(settings.SQLALCHEMY_DATABASE_URI) -def run_migrations_offline(): +def run_migrations_offline() -> None: """Run migrations in 'offline' mode. This configures the context with just a URL @@ -53,14 +56,14 @@ def run_migrations_offline(): context.run_migrations() -def run_migrations_online(): +def run_migrations_online() -> None: """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ - configuration = config.get_section(config.config_ini_section) + configuration = config.get_section(config.config_ini_section) or {} configuration["sqlalchemy.url"] = get_url() connectable = engine_from_config( configuration, diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/versions/5f2a9c1d7e3b_constrain_item_columns.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/versions/5f2a9c1d7e3b_constrain_item_columns.py-tpl new file mode 100644 index 0000000..73c372a --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/versions/5f2a9c1d7e3b_constrain_item_columns.py-tpl @@ -0,0 +1,37 @@ +"""constrain item columns + +Revision ID: 5f2a9c1d7e3b +Revises: bedcdc35b64a +Create Date: 2026-12-01 00:00:00.000000 + +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision: str = "5f2a9c1d7e3b" +down_revision: str | None = "bedcdc35b64a" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + # Match the max_length limits declared on ``ItemBase``. + op.alter_column( + "items", "name", type_=sa.String(length=120), existing_nullable=False + ) + op.alter_column( + "items", "description", type_=sa.String(length=1000), existing_nullable=True + ) + op.alter_column( + "items", "category", type_=sa.String(length=60), existing_nullable=False + ) + + +def downgrade() -> None: + op.alter_column("items", "category", type_=sa.String(), existing_nullable=False) + op.alter_column("items", "description", type_=sa.String(), existing_nullable=True) + op.alter_column("items", "name", type_=sa.String(), existing_nullable=False) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/versions/bedcdc35b64a_first_alembic.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/versions/bedcdc35b64a_first_alembic.py-tpl index 6467d21..b55961f 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/versions/bedcdc35b64a_first_alembic.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/versions/bedcdc35b64a_first_alembic.py-tpl @@ -5,13 +5,14 @@ Revises: Create Date: 2025-03-01 17:00:43.670130 """ + from collections.abc import Sequence import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. -revision: str = 'bedcdc35b64a' +revision: str = "bedcdc35b64a" down_revision: str | None = None branch_labels: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None = None @@ -19,18 +20,19 @@ depends_on: str | Sequence[str] | None = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.create_table('items', - sa.Column('id', sa.Integer(), nullable=False), - sa.Column('name', sa.String(), nullable=False), - sa.Column('description', sa.String(), nullable=True), - sa.Column('price', sa.Float(), nullable=False), - sa.Column('category', sa.String(), nullable=False), - sa.PrimaryKeyConstraint('id') + op.create_table( + "items", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("name", sa.String(), nullable=False), + sa.Column("description", sa.String(), nullable=True), + sa.Column("price", sa.Float(), nullable=False), + sa.Column("category", sa.String(), nullable=False), + sa.PrimaryKeyConstraint("id"), ) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('items') + op.drop_table("items") # ### end Alembic commands ### diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/api.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/api.py-tpl index f665f8c..b822844 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/api.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/api.py-tpl @@ -1,7 +1,10 @@ # -------------------------------------------------------------------------- -# API router connector module +# API router aggregation +# +# Every business router is registered here; ``src/main.py`` mounts +# ``api_router`` under ``settings.API_V1_PREFIX``. ``fastkit addroute`` adds +# new routers at the ``# fastkit:`` anchors. # -------------------------------------------------------------------------- - from fastapi import APIRouter from src.api.routes import items diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/deps.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/deps.py-tpl index c4f48bf..05d0794 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/deps.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/deps.py-tpl @@ -1,19 +1,28 @@ # -------------------------------------------------------------------------- -# API router session dependency module +# Shared API dependencies # -------------------------------------------------------------------------- from collections.abc import Generator +from typing import Annotated +from fastapi import Depends from sqlmodel import Session from src.core.db import engine def get_db() -> Generator[Session, None, None]: - """ - Dependency for database session. + """Yield a request-scoped session. - Yields: - Database session that will be automatically closed after request completion + The data layer commits its own writes; this dependency only rolls back + whatever is left uncommitted when the request fails, and closes the + session afterwards. """ with Session(engine) as session: - yield session + try: + yield session + except Exception: + session.rollback() + raise + + +SessionDep = Annotated[Session, Depends(get_db)] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/routes/health.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/routes/health.py-tpl new file mode 100644 index 0000000..e9e06b8 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/routes/health.py-tpl @@ -0,0 +1,77 @@ +# -------------------------------------------------------------------------- +# Liveness and readiness probes, mounted at the application root +# -------------------------------------------------------------------------- +import asyncio +import logging +from typing import Literal + +from fastapi import APIRouter, status +from fastapi.responses import JSONResponse +from pydantic import BaseModel +from sqlalchemy import Engine, text + +from src.api.deps import SessionDep + +logger = logging.getLogger(__name__) + +router = APIRouter(tags=["health"]) + +#: Upper bound, in seconds, for the readiness check. A database host that +#: does not answer at all would otherwise hold the probe for the operating +#: system's TCP connect timeout (often more than a minute). +READY_TIMEOUT_SECONDS = 2.0 + + +class HealthStatus(BaseModel): + status: Literal["ok", "unavailable"] + + +@router.get("/health") +async def health() -> HealthStatus: + """Liveness: the process is up. Touches no database.""" + return HealthStatus(status="ok") + + +def _select_one(bind: Engine) -> None: + """Open a connection of its own and run ``SELECT 1`` on it. + + The probe never uses the request session from the worker thread: after a + timeout that thread is still connecting while the request finishes and + closes its session, and a session must not be used by two threads. + """ + with bind.connect() as connection: + connection.execute(text("SELECT 1")) + + +@router.get( + "/ready", + response_model=HealthStatus, + responses={ + status.HTTP_503_SERVICE_UNAVAILABLE: { + "model": HealthStatus, + "description": "The database is unreachable", + } + }, +) +async def ready(db: SessionDep) -> HealthStatus | JSONResponse: + """Readiness: the database answers ``SELECT 1`` within the time limit. + + The driver is synchronous, so the query runs in a worker thread and only + the wait for it is bounded here. A timed-out thread finishes on its own; + the engine's connect timeout (``src/core/db.py``) caps how long it takes. + """ + try: + async with asyncio.timeout(READY_TIMEOUT_SECONDS): + # No I/O: the engine behind the session (``.engine`` also covers a + # session bound to a connection, as in the tests). + engine = db.get_bind().engine + await asyncio.to_thread(_select_one, engine) + except Exception as exc: + # Any failure means "not ready": driver and network errors, DNS + # failures, the timeout above. Log the kind, never the URL. + logger.warning("Readiness check failed: %s", type(exc).__name__) + return JSONResponse( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + content={"status": "unavailable"}, + ) + return HealthStatus(status="ok") diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/routes/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/routes/items.py-tpl index 42ffa02..8fae1df 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/routes/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/routes/items.py-tpl @@ -1,107 +1,79 @@ # -------------------------------------------------------------------------- -# Item CRUD Endpoint +# Item CRUD endpoints +# +# Handlers are plain ``def``: the psycopg driver is synchronous, so FastAPI +# runs them in its threadpool instead of blocking the event loop. # -------------------------------------------------------------------------- - -from fastapi import APIRouter, Depends, HTTPException -from sqlmodel import Session - -from src.api.deps import get_db -from src.crud.items import create_item, delete_item, get_item, get_items, update_item -from src.schemas.items import ItemCreate, ItemResponse - -router = APIRouter() - - -@router.get("/items", response_model=list[ItemResponse]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - """ - Retrieve a list of items with optional pagination. - - Args: - skip: Number of records to skip - limit: Maximum number of records to return - db: Database session dependency - - Returns: - List of items - """ - return get_items(db, skip=skip, limit=limit) - - -@router.get("/items/{item_id}", response_model=ItemResponse) -def read_item(item_id: int, db: Session = Depends(get_db)): - """ - Retrieve a specific item by ID. - - Args: - item_id: ID of the item to retrieve - db: Database session dependency - - Returns: - The requested item - - Raises: - HTTPException: If item is not found - """ - db_item = get_item(db, item_id=item_id) - if db_item is None: - raise HTTPException(status_code=404, detail="Item not found") - return db_item - - -@router.post("/items", response_model=ItemResponse, status_code=201) -def create_new_item(item: ItemCreate, db: Session = Depends(get_db)): - """ - Create a new item. - - Args: - item: Item data from request body - db: Database session dependency - - Returns: - The created item with its new ID - """ - return create_item(db, item.model_dump()) - - -@router.put("/items/{item_id}", response_model=ItemResponse) -def update_existing_item(item_id: int, item: ItemCreate, db: Session = Depends(get_db)): - """ - Update an existing item. - - Args: - item_id: ID of the item to update - item: Updated item data from request body - db: Database session dependency - - Returns: - The updated item - - Raises: - HTTPException: If item is not found - """ - db_item = update_item(db, item_id=item_id, item_data=item.model_dump()) - if db_item is None: - raise HTTPException(status_code=404, detail="Item not found") - return db_item - - -@router.delete("/items/{item_id}") -def delete_existing_item(item_id: int, db: Session = Depends(get_db)): - """ - Delete an item. - - Args: - item_id: ID of the item to delete - db: Database session dependency - - Returns: - Success message - - Raises: - HTTPException: If item is not found - """ - success = delete_item(db, item_id=item_id) - if not success: - raise HTTPException(status_code=404, detail="Item not found") - return {"message": "Item deleted successfully"} +from fastapi import APIRouter, HTTPException, Request, Response, status + +from src.api.deps import SessionDep +from src.core.pagination import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from src.core.responses import error_responses +from src.crud import items as crud +from src.models.items import Item +from src.schemas.items import ItemCreate, ItemRead, ItemUpdate + +router = APIRouter(prefix="/items", tags=["items"]) + + +def _get_or_404(db: SessionDep, item_id: int) -> Item: + item = crud.get_item(db, item_id) + if item is None: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail="Item not found" + ) + return item + + +@router.get("") +def list_items( + db: SessionDep, limit: LimitParam = DEFAULT_LIMIT, offset: OffsetParam = 0 +) -> Page[ItemRead]: + """List items ordered by id, one page at a time.""" + items = crud.list_page(db, offset=offset, limit=limit) + return Page[ItemRead]( + items=[ItemRead.model_validate(item) for item in items], + total=crud.count(db), + limit=limit, + offset=offset, + ) + + +@router.get("/{item_id}", responses=error_responses(404)) +def read_item(item_id: int, db: SessionDep) -> ItemRead: + """Return one item.""" + return ItemRead.model_validate(_get_or_404(db, item_id)) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_item( + payload: ItemCreate, db: SessionDep, request: Request, response: Response +) -> ItemRead: + """Create an item; the ``Location`` header points at the new resource.""" + item = crud.create_item(db, payload) + response.headers["Location"] = str(request.url_for("read_item", item_id=item.id)) + return ItemRead.model_validate(item) + + +@router.put("/{item_id}", responses=error_responses(404)) +def replace_item(item_id: int, payload: ItemCreate, db: SessionDep) -> ItemRead: + """Replace every field of an item; omitted optional fields are reset.""" + item = _get_or_404(db, item_id) + return ItemRead.model_validate(crud.replace_item(db, item, payload)) + + +@router.patch("/{item_id}", responses=error_responses(404)) +def update_item(item_id: int, payload: ItemUpdate, db: SessionDep) -> ItemRead: + """Change only the fields present in the request body.""" + item = _get_or_404(db, item_id) + return ItemRead.model_validate(crud.update_item(db, item, payload)) + + +@router.delete( + "/{item_id}", + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(404), +) +def delete_item(item_id: int, db: SessionDep) -> None: + """Delete an item.""" + crud.delete_item(db, _get_or_404(db, item_id)) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/config.py-tpl index 7d9f72d..b29d031 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/config.py-tpl @@ -1,9 +1,12 @@ # -------------------------------------------------------------------------- # Configuration module +# +# The single settings object of the project: every module reads its +# configuration from ``settings`` (environment variables or ``.env``). # -------------------------------------------------------------------------- import secrets import warnings -from typing import Annotated, Any, Literal, Self +from typing import Annotated, Any, Literal from pydantic import ( AnyUrl, @@ -17,13 +20,47 @@ from pydantic_settings import BaseSettings, SettingsConfigDict def parse_cors(v: Any) -> list[str] | str: + """Accept a comma-separated string or a JSON list; drop empty entries.""" if isinstance(v, str) and not v.startswith("["): - return [i.strip() for i in v.split(",")] - elif isinstance(v, list | str): + return [item.strip() for item in v.split(",") if item.strip()] + if isinstance(v, list | str): return v raise ValueError(v) +#: Comma-separated list or JSON list, e.g. http://localhost:3000. +# Each origin is a full URL such as http://localhost:3000, or "*" for any +# origin. "*" never goes together with credentials (cookies, Authorization +# headers): browsers refuse that, so main.py turns credentials off for it. +CorsOrigins = Annotated[list[Literal["*"] | AnyUrl] | str, BeforeValidator(parse_cors)] + +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + "your-secret-key-here", + "change-me-in-production", + "your-mcp-api-key-here", + } +) + +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = 32 + +_GENERATE_KEY_HINT = ( + "Generate one with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) + + class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=".env", @@ -31,57 +68,96 @@ class Settings(BaseSettings): extra="ignore", ) + PROJECT_NAME: str = "" + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + # The shipped code signs nothing with SECRET_KEY yet, but authentication + # you add later (including the JWT and Session options of fastkit init) + # signs tokens or cookies with it, so treat it as a production secret. + # fastkit writes a unique value to .env; staging and production refuse a + # missing, public or short key (see _check_secret_key below). SECRET_KEY: str = secrets.token_urlsafe(32) - ENVIRONMENT: Literal["development", "production"] = "development" - CLIENT_ORIGIN: str = "" + API_V1_PREFIX: str = "/api/v1" - BACKEND_CORS_ORIGINS: Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] = ( - [] - ) + BACKEND_CORS_ORIGINS: CorsOrigins = [] @computed_field # type: ignore[prop-decorator] @property def all_cors_origins(self) -> list[str]: - return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + [ - self.CLIENT_ORIGIN - ] + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins - PROJECT_NAME: str = "" POSTGRES_SERVER: str POSTGRES_PORT: int = 5432 POSTGRES_USER: str POSTGRES_PASSWORD: str = "" POSTGRES_DB: str = "" + # Database the test suite uses. Defaults to ``_test`` on the + # same server; the tests create it when missing and never touch + # ``POSTGRES_DB``. + TEST_DATABASE_URL: str | None = None + + def _postgres_url(self, database: str) -> str: + return str( + MultiHostUrl.build( + scheme="postgresql+psycopg", + username=self.POSTGRES_USER, + password=self.POSTGRES_PASSWORD, + host=self.POSTGRES_SERVER, + port=self.POSTGRES_PORT, + path=database, + ) + ) + @computed_field # type: ignore[prop-decorator] @property def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn: - return MultiHostUrl.build( # type: ignore - scheme="postgresql+psycopg", - username=self.POSTGRES_USER, - password=self.POSTGRES_PASSWORD, - host=self.POSTGRES_SERVER, - port=self.POSTGRES_PORT, - path=self.POSTGRES_DB, - ) + return PostgresDsn(self._postgres_url(self.POSTGRES_DB)) - def _check_default_secret(self, var_name: str, value: str | None) -> None: - if value == "changethis": - message = ( - f'The value of {var_name} is "changethis", ' - "for security, please change it, at least for deployments." - ) - if self.ENVIRONMENT == "development": - warnings.warn(message, stacklevel=1) - else: - raise ValueError(message) + @property + def SQLALCHEMY_TEST_DATABASE_URI(self) -> str: + if self.TEST_DATABASE_URL: + return self.TEST_DATABASE_URL + return self._postgres_url(f"{self.POSTGRES_DB or 'app'}_test") @model_validator(mode="after") - def _enforce_non_default_secrets(self) -> Self: - self._check_default_secret("SECRET_KEY", self.SECRET_KEY) - + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) + return self + env = f"ENVIRONMENT={self.ENVIRONMENT}" + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT + ) + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: + raise ValueError( + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT + ) return self -settings = Settings() # type: ignore +settings = Settings() # type: ignore[call-arg] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/db.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/db.py-tpl index b9929e1..549cbce 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/db.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/db.py-tpl @@ -1,53 +1,45 @@ # -------------------------------------------------------------------------- -# Database configuration module +# Database engine and seed data +# +# The schema is owned by Alembic: run ``alembic upgrade head`` (the Docker +# entrypoint ``scripts/pre-start.sh`` does) before starting the app. # -------------------------------------------------------------------------- from sqlmodel import Session, create_engine, select from src.core.config import settings -from src.schemas.items import ItemBase +from src.models.items import Item -engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI)) +#: Seconds psycopg may spend opening a connection (libpq's minimum is 2). +#: Without it an unreachable server blocks for the OS TCP timeout. +CONNECT_TIMEOUT_SECONDS = 5 - -# make sure all SQLModel models are imported (src.schemas) before initializing DB -# otherwise, SQLModel might fail to initialize relationships properly +# ``pool_pre_ping`` replaces connections the server closed while idle. +engine = create_engine( + str(settings.SQLALCHEMY_DATABASE_URI), + pool_pre_ping=True, + connect_args={"connect_timeout": CONNECT_TIMEOUT_SECONDS}, +) def init_db(session: Session) -> None: - """ - Initialize the database with sample data. - - This function can be used to seed the database with initial data for testing or - demonstration purposes. Modify the sample data as needed for your application. - - Args: - session: Database session - """ - # Check if we already have items - statement = select(ItemBase) - results = session.exec(statement).all() - if results: - return # Database already has data - - # Add sample items - sample_items = [ - {"name": "Test Item 1", "description": "This is a test item", "price": 19.99, "category": "test"}, - {"name": "Test Item 2", "description": "Another test item", "price": 29.99, "category": "test"}, - ] - - for item_data in sample_items: - item = ItemBase(**item_data) - session.add(item) - + """Seed the database with sample items when the table is empty.""" + if session.exec(select(Item).limit(1)).first() is not None: + return + + session.add_all( + [ + Item( + name="Test Item 1", + description="This is a test item", + price=19.99, + category="test", + ), + Item( + name="Test Item 2", + description="Another test item", + price=29.99, + category="test", + ), + ] + ) session.commit() - - -def create_db_and_tables(): - """ - Create database tables. - - This function creates all tables defined via SQLModel. In production, - use Alembic migrations instead of this function. - """ - # SQLModel.metadata.create_all(engine) - pass diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/pagination.py-tpl new file mode 100644 index 0000000..2688822 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/pagination.py-tpl @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------- +# Limit/offset pagination shared by every list endpoint. +# +# List endpoints take ``limit: LimitParam = DEFAULT_LIMIT`` and +# ``offset: OffsetParam = 0`` and return a ``Page[T]`` envelope: +# {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range +# values are rejected with a 422 rather than clamped. +# -------------------------------------------------------------------------- +from typing import Annotated, Generic, TypeVar + +from fastapi import Query +from pydantic import BaseModel + +T = TypeVar("T") + +#: Page size used when the client sends no ``limit``. +DEFAULT_LIMIT = 20 +#: Largest page a client may ask for. +MAX_LIMIT = 100 + +LimitParam = Annotated[ + int, Query(ge=1, le=MAX_LIMIT, description="Maximum number of items to return.") +] +OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] + + +class Page(BaseModel, Generic[T]): + """One page of a collection, ordered by primary key. + + ``total`` counts the whole collection, so a client knows there is a next + page while ``offset + len(items) < total``. + """ + + items: list[T] + total: int + limit: int + offset: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/responses.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/responses.py-tpl new file mode 100644 index 0000000..bffc8c1 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/responses.py-tpl @@ -0,0 +1,40 @@ +# -------------------------------------------------------------------------- +# OpenAPI error responses shared by the routers. +# +# FastAPI documents 2xx and 422 on its own. Routes that can also answer 401, +# 404, 409, ... declare it with ``responses=error_responses(404)`` so clients +# see every status code and the ``{"detail": "..."}`` body in the schema. +# -------------------------------------------------------------------------- +from http import HTTPStatus +from typing import Any + +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + """Body FastAPI sends for an ``HTTPException``.""" + + detail: str + + +def error_responses(*status_codes: int) -> dict[int | str, dict[str, Any]]: + """Build ``responses=`` entries that document the given error codes. + + A 401 entry also documents the ``WWW-Authenticate`` header every 401 + response carries. + """ + responses: dict[int | str, dict[str, Any]] = {} + for code in status_codes: + entry: dict[str, Any] = { + "model": ErrorDetail, + "description": HTTPStatus(code).phrase, + } + if code == HTTPStatus.UNAUTHORIZED: + entry["headers"] = { + "WWW-Authenticate": { + "description": "Authentication scheme to use (Bearer).", + "schema": {"type": "string"}, + } + } + responses[code] = entry + return responses diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/crud/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/crud/items.py-tpl index a827917..de68b9c 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/crud/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/crud/items.py-tpl @@ -1,100 +1,59 @@ # -------------------------------------------------------------------------- -# Item CRUD method module +# Item data access +# +# Every write commits its own transaction; the request-scoped session +# dependency only rolls back when a request fails. # -------------------------------------------------------------------------- +from sqlmodel import Session, col, func, select -from sqlmodel import Session, select +from src.models.items import Item +from src.schemas.items import ItemCreate, ItemUpdate -from src.schemas.items import ItemBase +def get_item(db: Session, item_id: int) -> Item | None: + """Return the item with ``item_id``, or ``None`` when it does not exist.""" + return db.get(Item, item_id) -def get_item(db: Session, item_id: int) -> ItemBase | None: - """ - Retrieve a single item by its ID. - Args: - db: Database session - item_id: ID of the item to retrieve - - Returns: - The item if found, None otherwise - """ - return db.get(ItemBase, item_id) - - -def get_items(db: Session, skip: int = 0, limit: int = 100) -> list[ItemBase]: - """ - Retrieve a list of items with pagination. - - Args: - db: Database session - skip: Number of records to skip (for pagination) - limit: Maximum number of records to return - - Returns: - List of items - """ - statement = select(ItemBase).offset(skip).limit(limit) +def list_page(db: Session, *, offset: int, limit: int) -> list[Item]: + """Return one page of items ordered by id, so pages never overlap.""" + statement = select(Item).order_by(col(Item.id)).offset(offset).limit(limit) return list(db.exec(statement).all()) -def create_item(db: Session, item: dict[str, str | float]) -> ItemBase: - """ - Create a new item in the database. +def count(db: Session) -> int: + """Return the number of items in the table.""" + return db.exec(select(func.count()).select_from(Item)).one() - Args: - db: Database session - item: Dictionary containing item data - Returns: - The created item - """ - db_item = ItemBase(**item) - db.add(db_item) +def create_item(db: Session, payload: ItemCreate) -> Item: + """Insert a new item and return it with its generated id.""" + item = Item.model_validate(payload) + db.add(item) db.commit() - db.refresh(db_item) - return db_item - + db.refresh(item) + return item -def update_item(db: Session, item_id: int, item_data: dict[str, str | float]) -> ItemBase | None: - """ - Update an existing item. - Args: - db: Database session - item_id: ID of the item to update - item_data: Dictionary containing updated item data - - Returns: - The updated item if found, None otherwise - """ - db_item = get_item(db, item_id) - if not db_item: - return None - - for key, value in item_data.items(): - setattr(db_item, key, value) - - db.add(db_item) +def replace_item(db: Session, item: Item, payload: ItemCreate) -> Item: + """Overwrite every writable field (PUT): omitted optional fields reset.""" + item.sqlmodel_update(payload.model_dump()) + db.add(item) db.commit() - db.refresh(db_item) - return db_item + db.refresh(item) + return item -def delete_item(db: Session, item_id: int) -> bool: - """ - Delete an item from the database. - - Args: - db: Database session - item_id: ID of the item to delete +def update_item(db: Session, item: Item, payload: ItemUpdate) -> Item: + """Apply only the fields present in the request body (PATCH).""" + item.sqlmodel_update(payload.model_dump(exclude_unset=True)) + db.add(item) + db.commit() + db.refresh(item) + return item - Returns: - True if the item was deleted, False if not found - """ - db_item = get_item(db, item_id) - if not db_item: - return False - db.delete(db_item) +def delete_item(db: Session, item: Item) -> None: + """Delete ``item``.""" + db.delete(item) db.commit() - return True diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/main.py-tpl index ac9a824..6e5194a 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/main.py-tpl @@ -1,30 +1,28 @@ # -------------------------------------------------------------------------- # Main server application module # -------------------------------------------------------------------------- +from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from fastapi import FastAPI from starlette.middleware.cors import CORSMiddleware from src.api.api import api_router +from src.api.routes import health from src.core.config import settings -from src.core.db import create_db_and_tables +from src.core.db import engine # fastkit:imports @asynccontextmanager -async def lifespan(app: FastAPI): - """ - Application lifespan manager for startup and shutdown events. +async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + """Release pooled database connections on shutdown. - Creates database tables on startup. + The schema is created by Alembic (``alembic upgrade head``), not here. """ - # Create tables on startup (in development only) - if settings.ENVIRONMENT == "development": - create_db_and_tables() yield - # Clean up resources on shutdown if needed + engine.dispose() app = FastAPI( @@ -38,17 +36,13 @@ if settings.all_cors_origins: app.add_middleware( CORSMiddleware, allow_origins=settings.all_cors_origins, - allow_credentials=True, + # Browsers refuse credentials with the "*" wildcard; never send both. + allow_credentials="*" not in settings.all_cors_origins, allow_methods=["*"], allow_headers=["*"], ) +app.include_router(health.router) # fastkit:routes -app.include_router(api_router) - - -@app.get("/health") -async def health_check() -> dict[str, str]: - """Health check endpoint.""" - return {"status": "healthy"} +app.include_router(api_router, prefix=settings.API_V1_PREFIX) diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/api/__init__.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/models/__init__.py-tpl similarity index 100% rename from src/fastapi_fastkit/fastapi_project_template/modules/api/__init__.py-tpl rename to src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/models/__init__.py-tpl diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/models/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/models/items.py-tpl new file mode 100644 index 0000000..83c9011 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/models/items.py-tpl @@ -0,0 +1,25 @@ +# -------------------------------------------------------------------------- +# Item table model +# +# ``ItemBase`` holds the columns shared by the table and the API schemas in +# ``src/schemas/items.py``; ``Item`` is the ``items`` table itself. Declaring +# a column once in ``ItemBase`` makes it part of both. +# -------------------------------------------------------------------------- +from sqlmodel import Field, SQLModel + + +class ItemBase(SQLModel): + """Fields shared by the table and the request/response schemas.""" + + name: str = Field(min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=1000) + price: float = Field(ge=0) + category: str = Field(min_length=1, max_length=60) + + +class Item(ItemBase, table=True): + """The ``items`` table.""" + + __tablename__ = "items" + + id: int | None = Field(default=None, primary_key=True) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/schemas/items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/schemas/items.py-tpl index 8fba4e1..66662ad 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/schemas/items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/schemas/items.py-tpl @@ -1,53 +1,43 @@ # -------------------------------------------------------------------------- -# Item schema module +# Item API schemas +# +# The table model lives in ``src/models/items.py``; these are the request and +# response bodies built on its shared fields. # -------------------------------------------------------------------------- +from typing import Any +from pydantic import field_validator from sqlmodel import Field, SQLModel +from src.models.items import ItemBase -class ItemBase(SQLModel, table=True): - """ - Base Item model that serves both as a SQLModel table definition and a Pydantic model. - - Attributes: - name: The name of the item - description: Optional description of the item - price: The price of the item - category: The category the item belongs to - Notes: - This model can be extended with additional fields as needed for your specific - application requirements. - """ - __tablename__ = "items" +class ItemCreate(ItemBase): + """POST and PUT body: every client-writable field.""" - id: int | None = Field(default=None, primary_key=True) - name: str - description: str | None = None - price: float - category: str +class ItemUpdate(SQLModel): + """PATCH body: every field optional, only the fields sent are applied. -class ItemCreate(SQLModel): + ``name``, ``price`` and ``category`` back non-nullable columns, so an + explicit ``null`` for one of them is rejected with a 422. ``description`` + is nullable and accepts ``null`` to clear it. """ - Item creation model for API requests. - Use this model to validate incoming data when creating new items. - """ - name: str - description: str | None = None - price: float - category: str + name: str | None = Field(default=None, min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=1000) + price: float | None = Field(default=None, ge=0) + category: str | None = Field(default=None, min_length=1, max_length=60) + @field_validator("name", "price", "category") + @classmethod + def _reject_explicit_null(cls, value: Any, info: Any) -> Any: + if value is None: + raise ValueError(f"{info.field_name} must not be null") + return value -class ItemResponse(SQLModel): - """ - Item response model for API responses. - This model defines the structure of data returned to clients. - """ +class ItemRead(ItemBase): + """Response body: the shared fields plus the server-assigned id.""" + id: int - name: str - description: str | None = None - price: float - category: str diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/template-config.yml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/template-config.yml-tpl index 7bfde9f..d054595 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/template-config.yml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/template-config.yml-tpl @@ -11,10 +11,12 @@ testing: test_command: "pytest tests/ -v" # Alternative testing for environments without Docker +# The suite normally runs on a dedicated PostgreSQL test database; without +# one it can run on in-memory SQLite through the conftest option below. fallback_testing: strategy: "sqlite-mock" database_url: "sqlite:///:memory:" - test_command: "pytest tests/ -v" + test_command: "pytest tests/ -v --test-database-url sqlite://" # Default values for testing test_env_defaults: diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/conftest.py-tpl index 863aced..7e6eca8 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/conftest.py-tpl @@ -1,59 +1,123 @@ # -------------------------------------------------------------------------- # pytest runtime configuration module +# +# The tests never touch the database the app is configured with +# (``POSTGRES_DB``). They run against a dedicated PostgreSQL test database, +# ``_test`` on the same server unless ``TEST_DATABASE_URL`` (or +# ``--test-database-url``) says otherwise, which is created when missing. +# Each test runs inside a transaction that is rolled back afterwards, so +# tests do not see each other's rows and leave nothing behind. +# +# ``--test-database-url sqlite://`` runs the suite on in-memory SQLite when +# no PostgreSQL server is at hand; PostgreSQL stays the reference backend. # -------------------------------------------------------------------------- from collections.abc import Generator +from typing import Any import pytest from fastapi.testclient import TestClient -from sqlmodel import Session, delete -from src.core.db import engine, init_db +from sqlalchemy import Engine, event, text +from sqlalchemy.engine import make_url +from sqlalchemy.pool import StaticPool +from sqlmodel import Session, SQLModel, create_engine + +from src.api.deps import get_db +from src.core.config import settings from src.main import app -from src.schemas.items import ItemBase +from src.models import items # noqa: F401 (registers the table) -@pytest.fixture(scope="session", autouse=True) -def db() -> Generator[Session, None, None]: - """ - Session-scoped database fixture that sets up the test database - and cleans it up after all tests are done. +def pytest_addoption(parser: pytest.Parser) -> None: + parser.addoption( + "--test-database-url", + default=None, + help="Database URL for the test suite (default: settings.TEST_DATABASE_URL " + "or _test on the configured server).", + ) - This fixture: - 1. Initializes the database with test data - 2. Yields the session for test use - 3. Cleans up all data after tests complete - The autouse=True parameter ensures this fixture runs automatically - for all tests in the session. - """ - with Session(engine) as session: - # Initialize database with test data - init_db(session) - yield session +def _ensure_postgres_database(url: str) -> None: + """Create the PostgreSQL test database when it does not exist yet.""" + target = make_url(url) + admin = create_engine(target.set(database="postgres"), isolation_level="AUTOCOMMIT") + try: + with admin.connect() as connection: + exists = connection.execute( + text("SELECT 1 FROM pg_database WHERE datname = :name"), + {"name": target.database}, + ).first() + if exists is None: + connection.execute(text(f'CREATE DATABASE "{target.database}"')) + finally: + admin.dispose() - # Clean up - delete all records from tables after tests - statement = delete(ItemBase) - session.execute(statement) - session.commit() +def _sqlite_engine(url: str) -> Engine: + engine = create_engine( + url, connect_args={"check_same_thread": False}, poolclass=StaticPool + ) -@pytest.fixture(name="client") -def client_fixture(db: Session): - """ - Create a FastAPI test client with dependency overrides. + # pysqlite manages transactions itself, which breaks SAVEPOINTs; hand + # transaction control back to SQLAlchemy. + @event.listens_for(engine, "connect") + def _disable_pysqlite_transactions(dbapi_connection: Any, _: Any) -> None: + dbapi_connection.isolation_level = None + + @event.listens_for(engine, "begin") + def _emit_begin(connection: Any) -> None: + connection.exec_driver_sql("BEGIN") + + return engine - Args: - db: Test database session from the db fixture - Yields: - FastAPI TestClient +@pytest.fixture(scope="session") +def engine(request: pytest.FixtureRequest) -> Generator[Engine, None, None]: + url = ( + request.config.getoption("--test-database-url") + or settings.SQLALCHEMY_TEST_DATABASE_URI + ) + if make_url(url) == make_url(str(settings.SQLALCHEMY_DATABASE_URI)): + pytest.exit("The test database must not be the application database.", 2) + + if url.startswith("sqlite"): + test_engine = _sqlite_engine(url) + else: + _ensure_postgres_database(url) + test_engine = create_engine(url) + + SQLModel.metadata.drop_all(test_engine) + SQLModel.metadata.create_all(test_engine) + yield test_engine + SQLModel.metadata.drop_all(test_engine) + test_engine.dispose() + + +@pytest.fixture +def db(engine: Engine) -> Generator[Session, None, None]: + """A session inside a transaction that is rolled back after the test. + + ``join_transaction_mode="create_savepoint"`` turns the commits made by the + data layer into SAVEPOINT releases, so they never reach the database. """ - def get_session_override(): - return db + connection = engine.connect() + transaction = connection.begin() + session = Session(bind=connection, join_transaction_mode="create_savepoint") + try: + yield session + finally: + session.close() + transaction.rollback() + connection.close() + - app.dependency_overrides = {} - # Override the get_db dependency in routes to use the test session - from src.api.routes.items import get_db - app.dependency_overrides[get_db] = get_session_override +@pytest.fixture +def client(db: Session) -> Generator[TestClient, None, None]: + def _get_test_db() -> Generator[Session, None, None]: + yield db - with TestClient(app) as client: - yield client + app.dependency_overrides[get_db] = _get_test_db + try: + with TestClient(app) as test_client: + yield test_client + finally: + app.dependency_overrides.clear() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_config.py-tpl new file mode 100644 index 0000000..94a7316 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_config.py-tpl @@ -0,0 +1,231 @@ +# -------------------------------------------------------------------------- +# Settings validation: the SECRET_KEY rule, ENVIRONMENT values, +# environment variable names, the CORS wildcard and the database URLs. +# -------------------------------------------------------------------------- +import json +import os +import secrets +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest +from pydantic import ValidationError + +from src.core.config import KNOWN_EXAMPLE_SECRET_KEYS, MIN_SECRET_KEY_BYTES, Settings + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +APP_MODULE = "src.main" +#: Settings without a default. +REQUIRED: dict[str, Any] = {"POSTGRES_SERVER": "localhost", "POSTGRES_USER": "postgres"} + + +@pytest.fixture(autouse=True) +def _isolated_environment(monkeypatch: pytest.MonkeyPatch) -> None: + for name in ("BACKEND_CORS_ORIGINS", "TEST_DATABASE_URL", "POSTGRES_DB"): + monkeypatch.delenv(name, raising=False) + + +def test_cors_origins_drop_empty_entries() -> None: + settings = Settings( + _env_file=None, # type: ignore[call-arg] + BACKEND_CORS_ORIGINS="http://localhost:3000, ,http://localhost:5173/", + **REQUIRED, + ) + + assert settings.all_cors_origins == [ + "http://localhost:3000", + "http://localhost:5173", + ] + + +def test_no_cors_origins_by_default() -> None: + settings = Settings(_env_file=None, **REQUIRED) # type: ignore[call-arg] + + assert settings.all_cors_origins == [] + + +def test_test_database_defaults_to_a_separate_database() -> None: + settings = Settings( + _env_file=None, # type: ignore[call-arg] + POSTGRES_DB="item_db", + **REQUIRED, + ) + + assert settings.SQLALCHEMY_TEST_DATABASE_URI.endswith("/item_db_test") + assert str(settings.SQLALCHEMY_DATABASE_URI).endswith("/item_db") + + +STRONG_KEY = "k" * MIN_SECRET_KEY_BYTES +#: Every environment except development refuses a missing, public or short +#: SECRET_KEY. +STRICT_ENVIRONMENTS = ["staging", "production"] + + +@pytest.fixture(autouse=True) +def _isolated_settings_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Shell variables, in any spelling, must not leak into Settings().""" + for name in list(os.environ): + if name.upper() in {"ENVIRONMENT", "SECRET_KEY", "BACKEND_CORS_ORIGINS"}: + monkeypatch.delenv(name) + + +def make_settings(env_file: Path | None = None, **values: Any) -> Settings: + """Settings from explicit values; a developer's .env is never read.""" + return Settings(_env_file=env_file, **{**REQUIRED, **values}) # type: ignore[call-arg] + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_require_an_explicit_secret_key(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"must be set explicitly when ENVIRONMENT={environment}" + ): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_refuse_a_short_secret_key(environment: str) -> None: + short_key = "k" * (MIN_SECRET_KEY_BYTES - 1) + + with pytest.raises(ValidationError, match=f"at least {MIN_SECRET_KEY_BYTES} bytes"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=short_key) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +@pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) +def test_strict_environments_refuse_every_public_example_key( + environment: str, example_key: str +) -> None: + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=f" {example_key} ") + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environment_errors_say_how_to_generate_a_key(environment: str) -> None: + with pytest.raises(ValidationError, match="token_urlsafe"): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_an_explicit_strong_key(environment: str) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + + assert settings.ENVIRONMENT == environment + assert settings.SECRET_KEY == STRONG_KEY + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_the_key_fastkit_writes_to_env( + tmp_path: Path, environment: str +) -> None: + env_file = tmp_path / ".env" + env_file.write_text( + f"ENVIRONMENT={environment}\nSECRET_KEY={secrets.token_urlsafe(32)}\n", + encoding="utf-8", + ) + + assert make_settings(env_file).ENVIRONMENT == environment + + +def test_development_without_a_key_uses_a_random_one() -> None: + settings = make_settings(ENVIRONMENT="development") + + assert len(settings.SECRET_KEY.encode()) >= MIN_SECRET_KEY_BYTES + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_development_only_warns_about_an_example_key() -> None: + example_key = sorted(KNOWN_EXAMPLE_SECRET_KEYS)[0] + + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings(ENVIRONMENT="development", SECRET_KEY=example_key) + + assert settings.SECRET_KEY == example_key + + +@pytest.mark.parametrize("value", ["Production", "PRODUCTION", " production", "prod"]) +def test_unknown_environment_values_fail_closed(value: str) -> None: + with pytest.raises(ValidationError, match="ENVIRONMENT"): + make_settings(ENVIRONMENT=value, SECRET_KEY=STRONG_KEY) + + +def test_environment_variable_names_are_case_insensitive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("environment", "production") + + with pytest.raises(ValidationError, match="must be set explicitly"): + make_settings() + + monkeypatch.setenv("secret_key", STRONG_KEY) + + assert make_settings().ENVIRONMENT == "production" + + +@pytest.mark.parametrize("raw", ["*", " * ", '["*"]', "*,http://localhost:3000"]) +def test_cors_wildcard_is_accepted(monkeypatch: pytest.MonkeyPatch, raw: str) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + + assert make_settings().all_cors_origins == ["*"] + + +def test_cors_origins_must_be_urls_or_the_wildcard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + + with pytest.raises(ValidationError): + make_settings() + + +#: Runs in a fresh interpreter: the app reads its settings at import time. +_PREFLIGHT = f""" +import json +from fastapi.testclient import TestClient +from {APP_MODULE} import app + +headers = {{ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "GET", +}} +response = TestClient(app).options("/", headers=headers) +allowed = {{ + k: v for k, v in response.headers.items() if k.startswith("access-control-allow-") +}} +print(json.dumps(allowed)) +""" + + +@pytest.mark.parametrize( + ("origins", "allow_origin", "allow_credentials"), + [ + ("*", "*", None), + ("http://localhost:3000", "http://localhost:3000", "true"), + ], +) +def test_cors_wildcard_is_never_combined_with_credentials( + origins: str, allow_origin: str, allow_credentials: str | None +) -> None: + env = { + **os.environ, + **{name: str(value) for name, value in REQUIRED.items()}, + "BACKEND_CORS_ORIGINS": origins, + "ENVIRONMENT": "development", + } + result = subprocess.run( + [sys.executable, "-c", _PREFLIGHT], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + check=False, + ) + + assert result.returncode == 0, result.stderr + headers = json.loads(result.stdout.strip().splitlines()[-1]) + assert headers["access-control-allow-origin"] == allow_origin + assert headers.get("access-control-allow-credentials") == allow_credentials diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_health.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_health.py-tpl new file mode 100644 index 0000000..b0c4ae9 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_health.py-tpl @@ -0,0 +1,186 @@ +# -------------------------------------------------------------------------- +# Liveness and readiness probes +# -------------------------------------------------------------------------- +import logging +import threading +import time +from contextlib import contextmanager +from collections.abc import Generator, Iterator +from pathlib import Path +from typing import Any + +import pytest +from fastapi.testclient import TestClient +from sqlalchemy import Engine +from sqlmodel import Session, create_engine + +from src.api.deps import get_db +from src.api.routes import health +from src.main import app + + +class _FakeSession: + """Stands in for the request session and its engine. + + ``/ready`` asks the session for its engine (``get_bind().engine``) and + runs the query on a connection of its own; ``execute`` blocks or fails. + """ + + def __init__(self, error: Exception | None = None) -> None: + self.error = error + self.release = threading.Event() + + def get_bind(self) -> "_FakeSession": + return self + + @property + def engine(self) -> "_FakeSession": + return self + + @contextmanager + def connect(self) -> Iterator["_FakeSession"]: + yield self + + def execute(self, *_: Any, **__: Any) -> None: + if self.error is not None: + raise self.error + # Block like a driver waiting on an unreachable host, until released. + self.release.wait(timeout=30) + + +@pytest.fixture +def hanging_db() -> Iterator[_FakeSession]: + fake = _FakeSession() + app.dependency_overrides[get_db] = lambda: fake + yield fake + fake.release.set() + + +def test_health_is_served_at_the_root(client: TestClient) -> None: + response = client.get("/health") + + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + +def test_ready_reports_ok_when_the_database_answers( + client: TestClient, db: Session +) -> None: + # The probe opens a connection of its own. The in-memory SQLite fallback + # (--test-database-url sqlite://) shares one connection that the test + # transaction holds, so there the probe gets a database of its own. + engine = db.get_bind().engine + if engine.dialect.name == "sqlite": + spare = create_engine("sqlite://") + + def _spare_db() -> Generator[Session, None, None]: + with Session(spare) as session: + yield session + + app.dependency_overrides[get_db] = _spare_db + + response = client.get("/ready") + + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + +def test_ready_reports_503_when_the_database_is_down( + client: TestClient, tmp_path: Path +) -> None: + # A SQLite file inside a directory that does not exist cannot be opened. + broken = create_engine(f"sqlite:///{tmp_path / 'missing' / 'app.db'}") + + def _broken_db() -> Generator[Session, None, None]: + with Session(broken) as session: + yield session + + app.dependency_overrides[get_db] = _broken_db + + response = client.get("/ready") + + assert response.status_code == 503 + assert response.json() == {"status": "unavailable"} + broken.dispose() + + +def test_ready_answers_503_within_the_timeout_when_the_database_hangs( + client: TestClient, + hanging_db: _FakeSession, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + monkeypatch.setattr(health, "READY_TIMEOUT_SECONDS", 0.2) + + started = time.monotonic() + with caplog.at_level(logging.WARNING, logger=health.logger.name): + response = client.get("/ready") + elapsed = time.monotonic() - started + + assert response.status_code == 503 + assert response.json() == {"status": "unavailable"} + assert elapsed < 5 + assert "TimeoutError" in caplog.text + + +def test_ready_answers_503_for_any_error( + client: TestClient, caplog: pytest.LogCaptureFixture +) -> None: + # Not a SQLAlchemyError: the probe must still answer 503, not 500. + fake = _FakeSession(error=OSError("connection refused")) + app.dependency_overrides[get_db] = lambda: fake + + with caplog.at_level(logging.WARNING, logger=health.logger.name): + response = client.get("/ready") + + assert response.status_code == 503 + assert response.json() == {"status": "unavailable"} + assert "OSError" in caplog.text + + +def test_ready_answers_503_quickly_when_postgres_refuses( + client: TestClient, caplog: pytest.LogCaptureFixture +) -> None: + # Nothing listens on port 1; the URL never leaves this machine. + secret = "s3cret-db-password" + refused = create_engine( + f"postgresql+psycopg://app:{secret}@127.0.0.1:1/app", + connect_args={"connect_timeout": 2}, + ) + + def _refused_db() -> Generator[Session, None, None]: + with Session(refused) as session: + yield session + + app.dependency_overrides[get_db] = _refused_db + + started = time.monotonic() + with caplog.at_level(logging.WARNING, logger=health.logger.name): + response = client.get("/ready") + elapsed = time.monotonic() - started + + assert response.status_code == 503 + assert response.json() == {"status": "unavailable"} + assert elapsed < 5 + assert secret not in caplog.text + refused.dispose() + + +def test_ready_probe_never_shares_the_request_session( + client: TestClient, monkeypatch: pytest.MonkeyPatch +) -> None: + # The probe thread may outlive the request after a timeout, so it gets + # the engine and opens its own connection instead of using the session + # the request closes when it ends. + probed: list[object] = [] + monkeypatch.setattr(health, "_select_one", probed.append) + + response = client.get("/ready") + + assert response.status_code == 200 + assert len(probed) == 1 + assert isinstance(probed[0], Engine) + + +def test_ready_timeout_is_a_couple_of_seconds() -> None: + assert 0 < health.READY_TIMEOUT_SECONDS <= 5 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_init_data.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_init_data.py-tpl new file mode 100644 index 0000000..bb8df71 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_init_data.py-tpl @@ -0,0 +1,14 @@ +# -------------------------------------------------------------------------- +# Seed data +# -------------------------------------------------------------------------- +from sqlmodel import Session, func, select + +from src.core.db import init_db +from src.models.items import Item + + +def test_init_db_seeds_once(db: Session) -> None: + init_db(db) + init_db(db) + + assert db.exec(select(func.count()).select_from(Item)).one() == 2 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_items.py-tpl index b194928..7115da1 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_items.py-tpl @@ -1,42 +1,178 @@ # -------------------------------------------------------------------------- # Item endpoint testcases # -------------------------------------------------------------------------- +from typing import Any +from fastapi.testclient import TestClient +from src.core.config import settings + +ITEMS_URL = f"{settings.API_V1_PREFIX}/items" + + +def _create(client: TestClient, **overrides: Any) -> dict[str, Any]: + payload = { + "name": "Widget", + "description": "A widget", + "price": 9.5, + "category": "tools", + } + payload.update(overrides) + response = client.post(ITEMS_URL, json=payload) + assert response.status_code == 201, response.text + body: dict[str, Any] = response.json() + return body + + +def test_create_item_returns_201_and_location(client: TestClient) -> None: + response = client.post( + ITEMS_URL, json={"name": "New Item", "price": 30.0, "category": "new"} + ) + + assert response.status_code == 201 + created = response.json() + assert created["name"] == "New Item" + assert created["description"] is None + assert isinstance(created["id"], int) + + location = response.headers["Location"] + assert location.endswith(f"{ITEMS_URL}/{created['id']}") + assert client.get(location).json() == created + + +def test_create_item_validates_payload(client: TestClient) -> None: + response = client.post(ITEMS_URL, json={"name": "", "price": -1, "category": "x"}) + + assert response.status_code == 422 + + +def test_read_item(client: TestClient) -> None: + created = _create(client) + + response = client.get(f"{ITEMS_URL}/{created['id']}") -def test_read_all_items(client): - response = client.get("/items") assert response.status_code == 200 - assert len(response.json()) == 2 + assert response.json() == created + +def test_read_unknown_item_returns_404(client: TestClient) -> None: + response = client.get(f"{ITEMS_URL}/999999") + + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +def test_put_replaces_the_whole_item(client: TestClient) -> None: + created = _create(client) + + response = client.put( + f"{ITEMS_URL}/{created['id']}", + json={"name": "Updated Item", "price": 15.0, "category": "updated"}, + ) -def test_read_item_success(client): - response = client.get("/items/1") assert response.status_code == 200 - assert response.json()["name"] == "Test Item 1" + body = response.json() + assert body["name"] == "Updated Item" + # Omitted optional fields are reset by a full replacement. + assert body["description"] is None + + +def test_put_requires_every_required_field(client: TestClient) -> None: + created = _create(client) + response = client.put(f"{ITEMS_URL}/{created['id']}", json={"name": "Only name"}) + + assert response.status_code == 422 + + +def test_put_unknown_item_returns_404(client: TestClient) -> None: + response = client.put( + f"{ITEMS_URL}/999999", json={"name": "x", "price": 1.0, "category": "y"} + ) -def test_read_item_not_found(client): - response = client.get("/items/999") assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} -def test_create_item(client): - new_item = {"name": "New Item", "price": 30.0, "category": "new"} - response = client.post("/items", json=new_item) - assert response.status_code == 201 - assert response.json()["id"] == 3 +def test_patch_changes_only_sent_fields(client: TestClient) -> None: + created = _create(client) + response = client.patch(f"{ITEMS_URL}/{created['id']}", json={"price": 11.0}) -def test_update_item(client): - updated_data = {"name": "Updated Item", "price": 15.0, "category": "updated"} - response = client.put("/items/1", json=updated_data) assert response.status_code == 200 - assert response.json()["name"] == "Updated Item" + body = response.json() + assert body["price"] == 11.0 + assert body["name"] == created["name"] + assert body["description"] == created["description"] -def test_delete_item(client): - response = client.delete("/items/1") +def test_patch_accepts_null_for_nullable_field(client: TestClient) -> None: + created = _create(client) + + response = client.patch(f"{ITEMS_URL}/{created['id']}", json={"description": None}) + assert response.status_code == 200 - response = client.get("/items/1") + assert response.json()["description"] is None + + +def test_patch_rejects_null_for_required_field(client: TestClient) -> None: + created = _create(client) + + response = client.patch(f"{ITEMS_URL}/{created['id']}", json={"name": None}) + + assert response.status_code == 422 + + +def test_patch_unknown_item_returns_404(client: TestClient) -> None: + response = client.patch(f"{ITEMS_URL}/999999", json={"price": 1.0}) + assert response.status_code == 404 + + +def test_delete_item_returns_204(client: TestClient) -> None: + created = _create(client) + + response = client.delete(f"{ITEMS_URL}/{created['id']}") + + assert response.status_code == 204 + assert response.content == b"" + assert client.get(f"{ITEMS_URL}/{created['id']}").status_code == 404 + + +def test_delete_unknown_item_returns_404(client: TestClient) -> None: + response = client.delete(f"{ITEMS_URL}/999999") + + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +def test_list_items_returns_page_envelope(client: TestClient) -> None: + response = client.get(ITEMS_URL) + + assert response.status_code == 200 + assert response.json() == {"items": [], "total": 0, "limit": 20, "offset": 0} + + +def test_list_items_is_ordered_and_paginated(client: TestClient) -> None: + ids = [_create(client, name=f"Item {index}")["id"] for index in range(5)] + + response = client.get(ITEMS_URL, params={"limit": 2, "offset": 1}) + + assert response.status_code == 200 + body = response.json() + assert body["total"] == 5 + assert body["limit"] == 2 + assert body["offset"] == 1 + assert [item["id"] for item in body["items"]] == sorted(ids)[1:3] + + +def test_list_items_rejects_out_of_range_parameters(client: TestClient) -> None: + for params in ({"limit": 0}, {"limit": 101}, {"offset": -1}): + response = client.get(ITEMS_URL, params=params) + assert response.status_code == 422, params + + +def test_collection_is_served_without_a_redirect(client: TestClient) -> None: + response = client.get(ITEMS_URL, follow_redirects=False) + + assert response.status_code == 200 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.env.example-tpl index c9d6bec..50c60cb 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.env.example-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/.env.example-tpl @@ -1 +1,11 @@ +# .env.example keeps a public placeholder; fastkit writes a unique key to the +# local, git-ignored .env. With any ENVIRONMENT other than development +# (staging or production) the app refuses to start when SECRET_KEY is unset, +# a public example value or shorter than 32 bytes. SECRET_KEY=changethis +# One of: development, staging, production. +# ENVIRONMENT=development +# API_V1_PREFIX=/api/v1 +# Allowed browser origins, comma-separated or a JSON list. "*" allows any +# origin, but then without credentials (cookies, Authorization headers): +# BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/README.md-tpl index 9bfef5d..d150d7d 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/README.md-tpl @@ -2,13 +2,25 @@ This template provides a minimal FastAPI application that runs with a single `main.py` module. +`src/main.py` holds everything: a small `Settings` class (pydantic-settings, reads `.env`), the app, +CORS for the origins in `BACKEND_CORS_ORIGINS` (`*` allows any origin, but then without credentials), +and two routes. With any `ENVIRONMENT` other than `development` (`staging`, `production`) the app +refuses to start unless `SECRET_KEY` is set explicitly, is at least 32 bytes long and is not a +public example value. + +| Method | Endpoint | Description | +|--------|-----------|---------------------------------------------| +| GET | `/` | Welcome message | +| GET | `/health` | Liveness probe, returns `{"status": "ok"}` | + +Mount business routers under `settings.API_V1_PREFIX` (default `/api/v1`). + ## Structure ``` . ├── README.md ├── requirements.txt ├── pyproject.toml -├── setup.py ├── setup.cfg ├── src/ │ └── main.py @@ -23,8 +35,8 @@ uvicorn src.main:app --reload ``` ## Requirements -- Python >= 3.9 -- FastAPI, Uvicorn +- Python >= 3.12 +- FastAPI, Uvicorn, pydantic-settings # Project Origin diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/pyproject.toml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/pyproject.toml-tpl index e3e7161..7b4cbe3 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/pyproject.toml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/pyproject.toml-tpl @@ -11,6 +11,7 @@ requires-python = ">=3.12" dependencies = [ "fastapi>=0.141.1", "uvicorn[standard]>=0.52.4", + "pydantic-settings>=2.15.0", ] [dependency-groups] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/requirements.txt-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/requirements.txt-tpl index e2fd4ce..13cc423 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/requirements.txt-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/requirements.txt-tpl @@ -1,6 +1,6 @@ annotated-doc==0.0.5 annotated-types==0.8.0 -anyio==4.15.0 +anyio==4.16.0 certifi==2026.10.23 click==8.5.0 fastapi==0.141.1 @@ -14,11 +14,12 @@ packaging==26.3 pluggy==1.6.0 pydantic==2.13.5 pydantic-core==2.46.5 +pydantic-settings==2.15.0 pygments==2.21.0 pytest==9.1.1 python-dotenv==1.2.3 PyYAML==6.0.3 -starlette==1.6.0 +starlette==1.10.0 typing-extensions==4.16.0 typing-inspection==0.4.4 uvicorn==0.52.4 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/setup.cfg-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/setup.cfg-tpl index 11e142e..14df543 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/setup.cfg-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/setup.cfg-tpl @@ -2,3 +2,7 @@ pythonpath = src testpaths = tests python_files = test_*.py +filterwarnings = + # starlette's TestClient now prefers `httpx2`; this project pins httpx, so only + # that advisory notice (a UserWarning subclass) is silenced. + ignore:Using `httpx` with `starlette.testclient` is deprecated:starlette.exceptions.StarletteDeprecationWarning diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/src/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/src/main.py-tpl index 1cf3690..ad2c514 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/src/main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/src/main.py-tpl @@ -1,19 +1,154 @@ # -------------------------------------------------------------------------- # Main server application module +# +# The whole application lives in this one module: settings, app and routes. # -------------------------------------------------------------------------- +import json +import secrets +import warnings +from typing import Annotated, Any, Literal + from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from pydantic import AnyUrl, BeforeValidator, model_validator +from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict # fastkit:imports -app = FastAPI(title="") +def parse_cors(value: Any) -> Any: + """Read origins from a comma-separated string or a JSON list.""" + if isinstance(value, str): + value = value.strip() + value = json.loads(value) if value.startswith("[") else value.split(",") + if isinstance(value, list): + return [str(origin).strip() for origin in value if str(origin).strip()] + raise ValueError(value) + + +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { + "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + "your-secret-key-here", + "change-me-in-production", + "your-mcp-api-key-here", + } +) + +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = 32 + +_GENERATE_KEY_HINT = ( + "Generate one with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) + + +class Settings(BaseSettings): + """Project settings, read from environment variables and ``.env``.""" + + model_config = SettingsConfigDict( + env_file=".env", env_ignore_empty=True, extra="ignore" + ) + + PROJECT_NAME: str = "" + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + # The shipped code signs nothing with SECRET_KEY yet, but authentication + # you add later (including the JWT and Session options of fastkit init) + # signs tokens or cookies with it, so treat it as a production secret. + # fastkit writes a unique value to .env; staging and production refuse a + # missing, public or short key (see _check_secret_key below). + SECRET_KEY: str = secrets.token_urlsafe(32) + # Business routers are mounted under this prefix. + API_V1_PREFIX: str = "/api/v1" + # Each origin is a full URL such as http://localhost:3000, or "*" for any + # origin; "*" never goes together with credentials (browsers refuse that). + BACKEND_CORS_ORIGINS: Annotated[ + list[Literal["*"] | AnyUrl], NoDecode, BeforeValidator(parse_cors) + ] = [] + + @property + def all_cors_origins(self) -> list[str]: + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins + @model_validator(mode="after") + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) + return self + env = f"ENVIRONMENT={self.ENVIRONMENT}" + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT + ) + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: + raise ValueError( + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT + ) + return self + + +settings = Settings() + +app = FastAPI(title=settings.PROJECT_NAME) + +# Origins come only from BACKEND_CORS_ORIGINS; with none configured the +# middleware is not installed at all. +if settings.all_cors_origins: + app.add_middleware( + CORSMiddleware, + allow_origins=settings.all_cors_origins, + # Browsers refuse credentials with the "*" wildcard; never send both. + allow_credentials="*" not in settings.all_cors_origins, + allow_methods=["*"], + allow_headers=["*"], + ) + + +# Mount business routers under the versioned prefix, for example: +# app.include_router(items_router, prefix=settings.API_V1_PREFIX) # fastkit:routes -@app.get("/") + + +@app.get("/", tags=["root"]) async def root() -> dict[str, str]: - return {"message": "Hello from FastAPI Single Module!"} + """Welcome message with a pointer to the interactive API docs.""" + return {"message": f"Welcome to {settings.PROJECT_NAME}", "docs": "/docs"} -@app.get("/health") +@app.get("/health", tags=["health"]) async def health() -> dict[str, str]: - return {"status": "healthy"} + """Liveness probe: no authentication and no I/O.""" + return {"status": "ok"} diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/tests/test_config.py-tpl new file mode 100644 index 0000000..c128be2 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/tests/test_config.py-tpl @@ -0,0 +1,205 @@ +# -------------------------------------------------------------------------- +# Settings validation: the SECRET_KEY rule, ENVIRONMENT values, +# environment variable names and the CORS wildcard. +# -------------------------------------------------------------------------- +import json +import os +import secrets +import subprocess +import sys +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import pytest +from pydantic import ValidationError + +from src.main import settings + +# The settings class and its module, wherever the project defines them: in +# src/main.py, or in src/core/config.py when fastkit generated main.py for a +# preset. +if TYPE_CHECKING: + from src.main import Settings +else: + Settings = type(settings) +_settings_module = sys.modules[Settings.__module__] +KNOWN_EXAMPLE_SECRET_KEYS: frozenset[str] = _settings_module.KNOWN_EXAMPLE_SECRET_KEYS +MIN_SECRET_KEY_BYTES: int = _settings_module.MIN_SECRET_KEY_BYTES + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +APP_MODULE = "src.main" +#: Settings without a default; none in this template. +REQUIRED: dict[str, Any] = {} + +STRONG_KEY = "k" * MIN_SECRET_KEY_BYTES +#: Every environment except development refuses a missing, public or short +#: SECRET_KEY. +STRICT_ENVIRONMENTS = ["staging", "production"] + + +@pytest.fixture(autouse=True) +def _isolated_settings_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Shell variables, in any spelling, must not leak into Settings().""" + for name in list(os.environ): + if name.upper() in {"ENVIRONMENT", "SECRET_KEY", "BACKEND_CORS_ORIGINS"}: + monkeypatch.delenv(name) + + +def make_settings(env_file: Path | None = None, **values: Any) -> Settings: + """Settings from explicit values; a developer's .env is never read.""" + return Settings(_env_file=env_file, **{**REQUIRED, **values}) # type: ignore[call-arg] + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_require_an_explicit_secret_key(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"must be set explicitly when ENVIRONMENT={environment}" + ): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_refuse_a_short_secret_key(environment: str) -> None: + short_key = "k" * (MIN_SECRET_KEY_BYTES - 1) + + with pytest.raises(ValidationError, match=f"at least {MIN_SECRET_KEY_BYTES} bytes"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=short_key) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +@pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) +def test_strict_environments_refuse_every_public_example_key( + environment: str, example_key: str +) -> None: + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=f" {example_key} ") + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environment_errors_say_how_to_generate_a_key(environment: str) -> None: + with pytest.raises(ValidationError, match="token_urlsafe"): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_an_explicit_strong_key(environment: str) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + + assert settings.ENVIRONMENT == environment + assert settings.SECRET_KEY == STRONG_KEY + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_the_key_fastkit_writes_to_env( + tmp_path: Path, environment: str +) -> None: + env_file = tmp_path / ".env" + env_file.write_text( + f"ENVIRONMENT={environment}\nSECRET_KEY={secrets.token_urlsafe(32)}\n", + encoding="utf-8", + ) + + assert make_settings(env_file).ENVIRONMENT == environment + + +def test_development_without_a_key_uses_a_random_one() -> None: + settings = make_settings(ENVIRONMENT="development") + + assert len(settings.SECRET_KEY.encode()) >= MIN_SECRET_KEY_BYTES + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_development_only_warns_about_an_example_key() -> None: + example_key = sorted(KNOWN_EXAMPLE_SECRET_KEYS)[0] + + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings(ENVIRONMENT="development", SECRET_KEY=example_key) + + assert settings.SECRET_KEY == example_key + + +@pytest.mark.parametrize("value", ["Production", "PRODUCTION", " production", "prod"]) +def test_unknown_environment_values_fail_closed(value: str) -> None: + with pytest.raises(ValidationError, match="ENVIRONMENT"): + make_settings(ENVIRONMENT=value, SECRET_KEY=STRONG_KEY) + + +def test_environment_variable_names_are_case_insensitive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("environment", "production") + + with pytest.raises(ValidationError, match="must be set explicitly"): + make_settings() + + monkeypatch.setenv("secret_key", STRONG_KEY) + + assert make_settings().ENVIRONMENT == "production" + + +@pytest.mark.parametrize("raw", ["*", " * ", '["*"]', "*,http://localhost:3000"]) +def test_cors_wildcard_is_accepted(monkeypatch: pytest.MonkeyPatch, raw: str) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + + assert make_settings().all_cors_origins == ["*"] + + +def test_cors_origins_must_be_urls_or_the_wildcard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + + with pytest.raises(ValidationError): + make_settings() + + +#: Runs in a fresh interpreter: the app reads its settings at import time. +_PREFLIGHT = f""" +import json +from fastapi.testclient import TestClient +from {APP_MODULE} import app + +headers = {{ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "GET", +}} +response = TestClient(app).options("/", headers=headers) +allowed = {{ + k: v for k, v in response.headers.items() if k.startswith("access-control-allow-") +}} +print(json.dumps(allowed)) +""" + + +@pytest.mark.parametrize( + ("origins", "allow_origin", "allow_credentials"), + [ + ("*", "*", None), + ("http://localhost:3000", "http://localhost:3000", "true"), + ], +) +def test_cors_wildcard_is_never_combined_with_credentials( + origins: str, allow_origin: str, allow_credentials: str | None +) -> None: + env = { + **os.environ, + **{name: str(value) for name, value in REQUIRED.items()}, + "BACKEND_CORS_ORIGINS": origins, + "ENVIRONMENT": "development", + } + result = subprocess.run( + [sys.executable, "-c", _PREFLIGHT], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + check=False, + ) + + assert result.returncode == 0, result.stderr + headers = json.loads(result.stdout.strip().splitlines()[-1]) + assert headers["access-control-allow-origin"] == allow_origin + assert headers.get("access-control-allow-credentials") == allow_credentials diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/tests/test_main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/tests/test_main.py-tpl index b1afe12..105a368 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/tests/test_main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/tests/test_main.py-tpl @@ -1,16 +1,54 @@ # -------------------------------------------------------------------------- # Main endpoint testcases # -------------------------------------------------------------------------- +import pytest from fastapi.testclient import TestClient +from src.main import app, settings + +#: The settings class, wherever the project defines it: in src/main.py, or in +#: src/core/config.py when fastkit generated main.py for a preset. +Settings = type(settings) + def test_root(client: TestClient) -> None: + """The root route welcomes the client and points at the docs.""" res = client.get("/") assert res.status_code == 200 - assert res.json()["message"].startswith("Hello from FastAPI Single Module") + # The app title is the configured PROJECT_NAME. + assert res.json() == {"message": f"Welcome to {app.title}", "docs": "/docs"} def test_health(client: TestClient) -> None: res = client.get("/health") assert res.status_code == 200 - assert res.json() == {"status": "healthy"} + assert res.json() == {"status": "ok"} + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ( + "http://localhost:3000, ,https://example.com/", + ["http://localhost:3000", "https://example.com"], + ), + ('["http://localhost:3000", ""]', ["http://localhost:3000"]), + ("", []), + ], +) +def test_cors_origins_never_contain_an_empty_origin( + monkeypatch: pytest.MonkeyPatch, raw: str, expected: list[str] +) -> None: + # _env_file=None: a developer's .env must not change the result. + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + settings = Settings(_env_file=None) # type: ignore[call-arg] + + assert settings.all_cors_origins == expected + + +def test_business_routes_default_to_the_v1_prefix( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("API_V1_PREFIX", raising=False) + + assert Settings(_env_file=None).API_V1_PREFIX == "/api/v1" # type: ignore[call-arg] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.dockerignore-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.dockerignore-tpl new file mode 100644 index 0000000..151b60c --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.dockerignore-tpl @@ -0,0 +1,47 @@ +# Files Docker never sends to the build, so they cannot end up in the image. + +# Secrets: settings come from the environment at run time (docker run -e / +# --env-file, compose env_file), never from a file baked into the image. +.env +.env.* + +# VCS and editor state +.git +.gitignore +.gitattributes +.idea +.vscode +**/.DS_Store + +# Virtual environments +.venv +venv +env + +# Python, test and tool caches +**/__pycache__ +**/*.py[cod] +.pytest_cache +.mypy_cache +.ruff_cache +.coverage +.coverage.* +coverage.xml +htmlcov +dist +build +*.egg-info + +# Local SQLite databases +**/*.db +**/*.db-journal +**/*.db-wal +**/*.db-shm + +# The application image does not run the test suite +tests + +# Docker files themselves +Dockerfile +docker-compose*.yml +.dockerignore diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.env.example-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.env.example-tpl index 9c89f97..8fddc89 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.env.example-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/.env.example-tpl @@ -1,7 +1,24 @@ # SQLite by default — no external service required. # Switch to PostgreSQL by pointing DATABASE_URL at an asyncpg DSN, e.g. # DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/app +# In the Docker image only /app/data is writable: when you pass this file with +# `docker run --env-file .env`, use DATABASE_URL=sqlite+aiosqlite:////app/data/app.db. DATABASE_URL=sqlite+aiosqlite:///./app.db +# Log every SQL statement. +DB_ECHO=false +# Create the tables from the models on startup: handy for the SQLite default. +# Set it to false on PostgreSQL and in production, and run +# `alembic upgrade head` instead. +CREATE_TABLES_ON_STARTUP=true +# .env.example keeps a public placeholder; fastkit writes a unique key to the +# local, git-ignored .env. With any ENVIRONMENT other than development +# (staging or production) the app refuses to start when SECRET_KEY is unset, +# a public example value or shorter than 32 bytes. SECRET_KEY=changethis +# One of: development, staging, production. ENVIRONMENT=development + +# Allowed browser origins, comma-separated or a JSON list. "*" allows any +# origin, but then without credentials (cookies, Authorization headers): +# BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/Dockerfile-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/Dockerfile-tpl index 63bfa7c..3725fd7 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/Dockerfile-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/Dockerfile-tpl @@ -1,18 +1,45 @@ FROM python:3.12-slim +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + WORKDIR /app +# Unprivileged runtime user with a fixed UID/GID, so file ownership on mounted +# volumes stays predictable across rebuilds. +RUN groupadd --system --gid 10001 app \ + && useradd --system --uid 10001 --gid app --no-create-home \ + --home-dir /nonexistent --shell /usr/sbin/nologin app + COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt +# The source stays owned by root, read-only for the app user. .dockerignore +# keeps .env, tests/, virtualenvs and local databases out of the build context. COPY alembic.ini . COPY src/ src/ -COPY tests/ tests/ COPY scripts/ scripts/ +# The default SQLite database lives in /app/data, the only directory the app +# user can write to. Mount a volume there to keep the data across containers, +# or point DATABASE_URL at PostgreSQL. +RUN mkdir -p /app/data && chown app:app /app/data + ENV PYTHONPATH=/app ENV ENVIRONMENT=production +ENV DATABASE_URL=sqlite+aiosqlite:////app/data/app.db + +USER app EXPOSE 8000 +# Liveness probe on GET /health (the slim image has no curl, so python). +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ + CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3)"] + +# Settings come from the environment at run time, never from a file in the +# image, e.g.: +# docker run -p 8000:8000 -e SECRET_KEY=... -v app-data:/app/data +# A DATABASE_URL you pass (for example with --env-file .env, whose default is +# ./app.db) replaces the one above: keep SQLite files under /app/data. CMD ["uvicorn", "src.app.main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl index b486770..3c0a8b4 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl @@ -18,8 +18,8 @@ Pick this template when you want: `DATABASE_URL` is a local SQLite file; point it at `postgresql+asyncpg://...` and nothing else changes. - **CRUD you don't rewrite per domain.** `CRUDBase` supplies create / read / - list / count / update / delete; each domain subclasses it and adds only - what is specific to it. + paginated list / count / replace / update / delete; each domain subclasses + it and adds only what is specific to it. If you don't need a database, start with `fastapi-domain-starter`. If you want a Docker Compose PostgreSQL stack with synchronous SQLModel, use @@ -56,23 +56,26 @@ want a Docker Compose PostgreSQL stack with synchronous SQLModel, use │ └── app/ │ ├── main.py # FastAPI app + lifespan │ ├── core/ -│ │ └── config.py # pydantic-settings configuration +│ │ ├── config.py # pydantic-settings configuration +│ │ ├── pagination.py # Page[T] envelope, limit/offset parameters +│ │ └── responses.py # error_responses() for OpenAPI │ ├── db/ │ │ ├── session.py # async engine, session dependency │ │ └── base.py # metadata aggregation for Alembic │ ├── crud/ -│ │ ├── base.py # generic CRUDBase -│ │ └── pagination.py # Page[T] envelope +│ │ └── base.py # generic CRUDBase │ ├── alembic/ │ │ ├── env.py # async migration environment │ │ └── versions/ │ │ └── 0001_create_items_table.py │ ├── api/ -│ │ ├── router.py # aggregates health + domain routers -│ │ └── health.py # GET /health +│ │ ├── deps.py # SessionDep +│ │ ├── router.py # aggregates domain routers (addroute anchors) +│ │ └── health.py # GET /health, GET /ready (app root) │ └── domains/ │ └── items/ # example domain -│ ├── models.py # Item table + Create/Update/Public schemas +│ ├── models.py # ItemBase + Item table +│ ├── schemas.py # ItemCreate / ItemUpdate / ItemRead │ ├── crud.py # ItemCRUD(CRUDBase) │ └── router.py # FastAPI router └── tests/ @@ -109,21 +112,29 @@ API docs are then served at: ## API endpoints -| Method | Endpoint | Description | -|--------|---------------------------|--------------------------------------| -| GET | `/api/v1/health` | Liveness probe | -| GET | `/api/v1/items` | List items (`offset`, `limit`) | -| GET | `/api/v1/items/{item_id}` | Read a single item | -| POST | `/api/v1/items` | Create an item | -| PATCH | `/api/v1/items/{item_id}` | Partially update an item | -| DELETE | `/api/v1/items/{item_id}` | Delete an item | +Business routes are mounted under `API_V1_PREFIX` (`/api/v1`); the probes +stay at the application root. -List responses are wrapped in a page envelope: +| Method | Endpoint | Description | +|--------|---------------------------|--------------------------------------------| +| GET | `/health` | Liveness probe, no database access | +| GET | `/ready` | Readiness probe: `SELECT 1`, 503 when down | +| GET | `/api/v1/items` | List items (`limit` 1-100, `offset` >= 0) | +| GET | `/api/v1/items/{item_id}` | Read a single item | +| POST | `/api/v1/items` | Create an item (201 + `Location` header) | +| PUT | `/api/v1/items/{item_id}` | Replace an item (every field) | +| PATCH | `/api/v1/items/{item_id}` | Partially update an item | +| DELETE | `/api/v1/items/{item_id}` | Delete an item (204) | + +List responses are wrapped in a page envelope, ordered by id. A `limit` +outside 1-100 or a negative `offset` is rejected with a 422: ```json -{"items": [...], "total": 42, "offset": 0, "limit": 20} +{"items": [...], "total": 42, "limit": 20, "offset": 0} ``` +A missing item answers 404 with `{"detail": "Item not found"}`. + ## Switching to PostgreSQL ```bash @@ -138,11 +149,14 @@ $ bash scripts/migrate.sh ## Adding a domain 1. Create `src/app/domains//` mirroring `items` - (`models.py`, `crud.py`, `router.py`). + (`models.py`, `schemas.py`, `crud.py`, `router.py`), or run + `fastkit addroute `. 2. Import the table model in `src/app/db/base.py` — Alembic autogenerate and `create_db_and_tables` only see models that were imported. 3. Register the router in `src/app/api/router.py` (the `# fastkit:imports` - and `# fastkit:routes` anchors mark where `fastkit addroute` inserts code). + and `# fastkit:routes` anchors mark where `fastkit addroute` inserts code); + it is served under `/api/v1`. Paginate list endpoints with + `src/app/core/pagination.py`. 4. Generate a migration: `alembic revision --autogenerate -m "add "`. 5. Add tests under `tests/test_.py`. diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/pyproject.toml-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/pyproject.toml-tpl index a7730a8..f1e5b49 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/pyproject.toml-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/pyproject.toml-tpl @@ -60,11 +60,13 @@ packages = ["src"] [tool.black] line-length = 88 target-version = ["py312"] +extend-exclude = "src/app/alembic/versions" [tool.isort] profile = "black" line_length = 88 known_first_party = ["src"] +skip_glob = ["src/app/alembic/versions/*"] [tool.mypy] python_version = "3.12" @@ -72,6 +74,7 @@ strict = true warn_return_any = true warn_unused_configs = true disallow_untyped_defs = true +exclude = "src/app/alembic/versions" [tool.pytest.ini_options] testpaths = ["tests"] @@ -79,4 +82,5 @@ python_files = ["test_*.py"] python_classes = ["Test*"] python_functions = ["test_*"] asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" addopts = "-v --tb=short" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/alembic/env.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/alembic/env.py-tpl index abf9f3d..48f10aa 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/alembic/env.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/alembic/env.py-tpl @@ -3,15 +3,19 @@ # -------------------------------------------------------------------------- import asyncio from logging.config import fileConfig +from typing import Any, Literal from alembic import context +from alembic.autogenerate.api import AutogenContext from sqlalchemy import pool from sqlalchemy.engine import Connection from sqlalchemy.ext.asyncio import async_engine_from_config + from src.app.core.config import settings # Importing the aggregation module registers every table on the metadata. from src.app.db.base import SQLModel # noqa: F401 +from src.app.db.types import UTCDateTime config = context.config @@ -23,6 +27,19 @@ target_metadata = SQLModel.metadata config.set_main_option("sqlalchemy.url", settings.DATABASE_URL) +def render_item( + type_: str, obj: Any, autogen_context: AutogenContext +) -> str | Literal[False]: + """Write ``UTCDateTime`` columns as ``sa.DateTime(timezone=True)``. + + Migrations then stay free of application imports. Autogenerate compares + the type through its ``impl``, so this does not hide real drift. + """ + if type_ == "type" and isinstance(obj, UTCDateTime): + return "sa.DateTime(timezone=True)" + return False + + def run_migrations_offline() -> None: """Emit SQL to stdout without connecting to a database.""" context.configure( @@ -30,6 +47,7 @@ def run_migrations_offline() -> None: target_metadata=target_metadata, literal_binds=True, compare_type=True, + render_item=render_item, dialect_opts={"paramstyle": "named"}, ) @@ -42,6 +60,7 @@ def do_run_migrations(connection: Connection) -> None: connection=connection, target_metadata=target_metadata, compare_type=True, + render_item=render_item, render_as_batch=connection.dialect.name == "sqlite", ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/alembic/versions/0002_timezone_aware_created_at.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/alembic/versions/0002_timezone_aware_created_at.py-tpl new file mode 100644 index 0000000..94e710d --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/alembic/versions/0002_timezone_aware_created_at.py-tpl @@ -0,0 +1,50 @@ +"""store items.created_at with a time zone + +Revision ID: 0002 +Revises: 0001 +Create Date: 2026-12-01 00:00:00.000000 + +``0001`` created ``created_at`` as a naive ``TIMESTAMP``. On PostgreSQL +the column becomes ``TIMESTAMP WITH TIME ZONE``. Existing values are read +in the session ``TimeZone``, which is how PostgreSQL stored them when the +application wrote an aware datetime into the naive column, so run this +migration with the same server/session time zone the application used. + +SQLite has no time zone type; its stored values are already UTC and stay +as they are. +""" + +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision: str = "0002" +down_revision: Union[str, None] = "0001" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + if op.get_context().dialect.name != "postgresql": + return + op.alter_column( + "items", + "created_at", + existing_type=sa.DateTime(), + type_=sa.DateTime(timezone=True), + existing_nullable=False, + ) + + +def downgrade() -> None: + if op.get_context().dialect.name != "postgresql": + return + op.alter_column( + "items", + "created_at", + existing_type=sa.DateTime(timezone=True), + type_=sa.DateTime(), + existing_nullable=False, + ) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/api/deps.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/api/deps.py-tpl new file mode 100644 index 0000000..793dcdb --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/api/deps.py-tpl @@ -0,0 +1,11 @@ +# -------------------------------------------------------------------------- +# Shared FastAPI dependencies. +# -------------------------------------------------------------------------- +from typing import Annotated + +from fastapi import Depends +from sqlmodel.ext.asyncio.session import AsyncSession + +from src.app.db.session import get_session + +SessionDep = Annotated[AsyncSession, Depends(get_session)] diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/api/health.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/api/health.py-tpl index ff4139e..281ce22 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/api/health.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/api/health.py-tpl @@ -1,11 +1,58 @@ # -------------------------------------------------------------------------- -# Health endpoint — small, side-effect-free probe for liveness checks. +# Liveness and readiness probes, mounted at the application root. # -------------------------------------------------------------------------- -from fastapi import APIRouter +import asyncio +import logging +from typing import Literal + +from fastapi import APIRouter, status +from fastapi.responses import JSONResponse +from pydantic import BaseModel +from sqlalchemy import text + +from src.app.api.deps import SessionDep + +logger = logging.getLogger(__name__) router = APIRouter(tags=["health"]) +#: Upper bound, in seconds, for the readiness check. A database host that +#: does not answer at all would otherwise hold the probe for the driver's +#: own connect timeout (asyncpg: 60 s) while the orchestrator waits. +READY_TIMEOUT_SECONDS = 2.0 + + +class HealthStatus(BaseModel): + status: Literal["ok", "unavailable"] + @router.get("/health") -async def health() -> dict[str, str]: - return {"status": "ok"} +async def health() -> HealthStatus: + """Liveness: the process is up. Touches no database.""" + return HealthStatus(status="ok") + + +@router.get( + "/ready", + response_model=HealthStatus, + responses={ + status.HTTP_503_SERVICE_UNAVAILABLE: { + "model": HealthStatus, + "description": "The database is unreachable", + } + }, +) +async def ready(session: SessionDep) -> HealthStatus | JSONResponse: + """Readiness: the database answers ``SELECT 1`` within the time limit.""" + try: + async with asyncio.timeout(READY_TIMEOUT_SECONDS): + await session.exec(text("SELECT 1")) # type: ignore[call-overload] + except Exception as exc: + # Any failure means "not ready": driver and network errors, DNS + # failures, the timeout above. Log the kind, never the URL. + logger.warning("Readiness check failed: %s", type(exc).__name__) + return JSONResponse( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + content={"status": "unavailable"}, + ) + return HealthStatus(status="ok") diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/api/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/api/router.py-tpl index a7dbf2d..94d34e8 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/api/router.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/api/router.py-tpl @@ -1,15 +1,16 @@ # -------------------------------------------------------------------------- -# Top-level API router — aggregates the health probe with every domain -# module under ``src/app/domains/``. +# Top-level API router — aggregates every domain module under +# ``src/app/domains/``. ``src/app/main.py`` mounts it under +# ``settings.API_V1_PREFIX``; ``fastkit addroute`` registers new domain +# routers at the ``# fastkit:`` anchors. The health probes live at the root +# (``src/app/api/health.py``), outside this router. # -------------------------------------------------------------------------- from fastapi import APIRouter -from src.app.api import health from src.app.domains.items import router as items_router # fastkit:imports api_router = APIRouter() -api_router.include_router(health.router) api_router.include_router(items_router.router) # fastkit:routes diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/config.py-tpl index bccb376..2b7d55e 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/config.py-tpl @@ -2,6 +2,7 @@ # Application settings (pydantic-settings). # -------------------------------------------------------------------------- import secrets +import warnings from typing import Annotated, Any, List, Literal, Union from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator @@ -16,17 +17,32 @@ def _parse_cors(v: Any) -> Union[List[str], str]: raise ValueError(v) -#: Example SECRET_KEY values fastkit templates have shipped in ``.env`` -#: files. They are public, so a production deployment must never sign -#: anything with one of them. +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. KNOWN_EXAMPLE_SECRET_KEYS = frozenset( { "changethis", "changethis-please-generate-a-real-32-byte-key", "changethis-please-use-openssl-rand-hex-32", + "your-secret-key-here-change-in-production", + "your-secret-key-here", + "change-me-in-production", + "your-mcp-api-key-here", } ) +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = 32 + +_GENERATE_KEY_HINT = ( + "Generate one with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) + class Settings(BaseSettings): """Centralized configuration for the application. @@ -44,9 +60,11 @@ class Settings(BaseSettings): PROJECT_NAME: str = "" ENVIRONMENT: Literal["development", "staging", "production"] = "development" - # Not read by the shipped code; reserved for signing features you add. - # fastkit writes a unique value to .env, and production refuses the - # public example values (see the validator below). + # The shipped code signs nothing with SECRET_KEY yet, but authentication + # you add later (including the JWT and Session options of fastkit init) + # signs tokens or cookies with it, so treat it as a production secret. + # fastkit writes a unique value to .env; staging and production refuse a + # missing, public or short key (see _check_secret_key below). SECRET_KEY: str = secrets.token_urlsafe(32) API_V1_PREFIX: str = "/api/v1" @@ -61,31 +79,56 @@ class Settings(BaseSettings): # SQLite default; keep it off in production and use Alembic migrations. CREATE_TABLES_ON_STARTUP: bool = True - DEFAULT_PAGE_LIMIT: int = 20 - MAX_PAGE_LIMIT: int = 100 - + # Comma-separated list or JSON list. Each origin is a full URL such as + # http://localhost:3000, or "*" for any origin; "*" never goes together + # with credentials (browsers refuse that), so main.py turns them off. BACKEND_CORS_ORIGINS: Annotated[ - Union[List[AnyUrl], str], BeforeValidator(_parse_cors) + Union[List[Union[Literal["*"], AnyUrl]], str], BeforeValidator(_parse_cors) ] = [] @computed_field # type: ignore[prop-decorator] @property def all_cors_origins(self) -> List[str]: - return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins @model_validator(mode="after") - def _reject_example_secret_key_in_production(self) -> "Settings": - if ( - self.ENVIRONMENT == "production" - and self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS - ): + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) + return self + env = f"ENVIRONMENT={self.ENVIRONMENT}" + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT + ) + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: raise ValueError( - "SECRET_KEY is set to a public example value while " - "ENVIRONMENT=production. Generate a real key with " - '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' - "and set it as the SECRET_KEY environment variable (or in .env)." + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT ) return self -settings = Settings() # type: ignore[call-arg] +settings = Settings() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/pagination.py-tpl new file mode 100644 index 0000000..2688822 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/pagination.py-tpl @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------- +# Limit/offset pagination shared by every list endpoint. +# +# List endpoints take ``limit: LimitParam = DEFAULT_LIMIT`` and +# ``offset: OffsetParam = 0`` and return a ``Page[T]`` envelope: +# {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range +# values are rejected with a 422 rather than clamped. +# -------------------------------------------------------------------------- +from typing import Annotated, Generic, TypeVar + +from fastapi import Query +from pydantic import BaseModel + +T = TypeVar("T") + +#: Page size used when the client sends no ``limit``. +DEFAULT_LIMIT = 20 +#: Largest page a client may ask for. +MAX_LIMIT = 100 + +LimitParam = Annotated[ + int, Query(ge=1, le=MAX_LIMIT, description="Maximum number of items to return.") +] +OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] + + +class Page(BaseModel, Generic[T]): + """One page of a collection, ordered by primary key. + + ``total`` counts the whole collection, so a client knows there is a next + page while ``offset + len(items) < total``. + """ + + items: list[T] + total: int + limit: int + offset: int diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/responses.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/responses.py-tpl new file mode 100644 index 0000000..bffc8c1 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/core/responses.py-tpl @@ -0,0 +1,40 @@ +# -------------------------------------------------------------------------- +# OpenAPI error responses shared by the routers. +# +# FastAPI documents 2xx and 422 on its own. Routes that can also answer 401, +# 404, 409, ... declare it with ``responses=error_responses(404)`` so clients +# see every status code and the ``{"detail": "..."}`` body in the schema. +# -------------------------------------------------------------------------- +from http import HTTPStatus +from typing import Any + +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + """Body FastAPI sends for an ``HTTPException``.""" + + detail: str + + +def error_responses(*status_codes: int) -> dict[int | str, dict[str, Any]]: + """Build ``responses=`` entries that document the given error codes. + + A 401 entry also documents the ``WWW-Authenticate`` header every 401 + response carries. + """ + responses: dict[int | str, dict[str, Any]] = {} + for code in status_codes: + entry: dict[str, Any] = { + "model": ErrorDetail, + "description": HTTPStatus(code).phrase, + } + if code == HTTPStatus.UNAUTHORIZED: + entry["headers"] = { + "WWW-Authenticate": { + "description": "Authentication scheme to use (Bearer).", + "schema": {"type": "string"}, + } + } + responses[code] = entry + return responses diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/crud/base.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/crud/base.py-tpl index de465f2..778a717 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/crud/base.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/crud/base.py-tpl @@ -4,6 +4,9 @@ # Every domain gets create / read / list / update / delete for free by # instantiating ``CRUDBase`` with its table model and its I/O schemas. Add # domain-specific queries by subclassing. +# +# Write methods commit their own transaction: the request-scoped session +# dependency only rolls back when a request fails. # -------------------------------------------------------------------------- from typing import Any, Generic, Sequence, TypeVar @@ -24,16 +27,20 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): async def get(self, session: AsyncSession, obj_id: int) -> ModelType | None: return await session.get(self.model, obj_id) - async def list( - self, session: AsyncSession, *, offset: int = 0, limit: int = 20 + async def list_page( + self, session: AsyncSession, *, offset: int, limit: int ) -> Sequence[ModelType]: - statement = select(self.model).offset(offset).limit(limit) + """One page of rows ordered by primary key, so pages never overlap.""" + primary_key = self.model.__table__.primary_key.columns # type: ignore[attr-defined] + statement = ( + select(self.model).order_by(*primary_key).offset(offset).limit(limit) + ) result = await session.exec(statement) return result.all() async def count(self, session: AsyncSession) -> int: statement = select(func.count()).select_from(self.model) - result = await session.exec(statement) # type: ignore[call-overload] + result = await session.exec(statement) return int(result.one()) async def create( @@ -45,18 +52,27 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): await session.refresh(db_obj) return db_obj + async def replace( + self, session: AsyncSession, db_obj: ModelType, obj_in: CreateSchemaType + ) -> ModelType: + """PUT: overwrite every writable field; omitted optional ones reset.""" + return await self._apply(session, db_obj, obj_in.model_dump()) + async def update( self, session: AsyncSession, db_obj: ModelType, obj_in: UpdateSchemaType ) -> ModelType: - # ``exclude_unset`` keeps a PATCH from clobbering untouched columns. - changes: dict[str, Any] = obj_in.model_dump(exclude_unset=True) - for field, value in changes.items(): - setattr(db_obj, field, value) - session.add(db_obj) - await session.commit() - await session.refresh(db_obj) - return db_obj + """PATCH: ``exclude_unset`` keeps untouched columns as they are.""" + return await self._apply(session, db_obj, obj_in.model_dump(exclude_unset=True)) async def delete(self, session: AsyncSession, db_obj: ModelType) -> None: await session.delete(db_obj) await session.commit() + + async def _apply( + self, session: AsyncSession, db_obj: ModelType, changes: dict[str, Any] + ) -> ModelType: + db_obj.sqlmodel_update(changes) + session.add(db_obj) + await session.commit() + await session.refresh(db_obj) + return db_obj diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/crud/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/crud/pagination.py-tpl deleted file mode 100644 index 0a91514..0000000 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/crud/pagination.py-tpl +++ /dev/null @@ -1,21 +0,0 @@ -# -------------------------------------------------------------------------- -# Offset/limit pagination envelope shared by every list endpoint. -# -------------------------------------------------------------------------- -from typing import Generic, Sequence, TypeVar - -from pydantic import BaseModel - -ItemType = TypeVar("ItemType") - - -class Page(BaseModel, Generic[ItemType]): - """A single page of results plus the cursor the client needs to move on.""" - - items: Sequence[ItemType] - total: int - offset: int - limit: int - - @property - def has_next(self) -> bool: - return self.offset + len(self.items) < self.total diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/db/session.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/db/session.py-tpl index 5f713b3..4d2a594 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/db/session.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/db/session.py-tpl @@ -2,23 +2,43 @@ # Async SQLModel engine and session management. # # One engine is created per process; sessions are created per request and -# handed to routers through the ``get_session`` dependency. +# handed to routers through the ``get_session`` dependency (``SessionDep`` +# in ``src/app/api/deps.py``). # -------------------------------------------------------------------------- from collections.abc import AsyncGenerator +from typing import Any +from sqlalchemy.engine import make_url from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine from sqlmodel import SQLModel from sqlmodel.ext.asyncio.session import AsyncSession from src.app.core.config import settings +#: Seconds the PostgreSQL driver may spend opening a connection. Without it +#: an unreachable host blocks a request for the driver default (asyncpg: +#: 60 s, libpq: no limit). +CONNECT_TIMEOUT_SECONDS = 5 + + +def _connect_args(url: str) -> dict[str, Any]: + """Driver-specific connect timeout; SQLite needs none.""" + driver = make_url(url).get_driver_name() + if driver == "asyncpg": + return {"timeout": CONNECT_TIMEOUT_SECONDS} + if driver == "psycopg": + return {"connect_timeout": CONNECT_TIMEOUT_SECONDS} + return {} + def create_engine(url: str | None = None) -> AsyncEngine: """Build an async engine for ``url`` (defaults to ``settings.DATABASE_URL``).""" + database_url = url or settings.DATABASE_URL return create_async_engine( - url or settings.DATABASE_URL, + database_url, echo=settings.DB_ECHO, future=True, + connect_args=_connect_args(database_url), ) @@ -45,6 +65,14 @@ async def create_db_and_tables() -> None: async def get_session() -> AsyncGenerator[AsyncSession, None]: - """FastAPI dependency yielding a request-scoped session.""" + """FastAPI dependency yielding a request-scoped session. + + The CRUD layer commits its own writes; this dependency only rolls back + whatever is left uncommitted when the request fails. + """ async with async_session_factory() as session: - yield session + try: + yield session + except Exception: + await session.rollback() + raise diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/db/types.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/db/types.py-tpl new file mode 100644 index 0000000..0a72e9e --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/db/types.py-tpl @@ -0,0 +1,48 @@ +# -------------------------------------------------------------------------- +# Custom column types. +# +# ``UTCDateTime`` stores timestamps as ``TIMESTAMP WITH TIME ZONE`` and +# always hands back timezone-aware UTC datetimes, whatever the database: +# +# - PostgreSQL keeps the instant; the value read back is converted to UTC so +# it does not depend on the server or session ``TimeZone``. +# - SQLite has no timezone type and drops ``tzinfo``. Values are converted to +# UTC before they are written, so a naive value read back is UTC and gets +# ``tzinfo=UTC`` attached here, in one place. +# +# Naive datetimes are refused on write: their meaning depends on the clock +# of whoever created them. Use ``datetime.now(timezone.utc)``. +# -------------------------------------------------------------------------- +from datetime import datetime, timezone + +from sqlalchemy import DateTime +from sqlalchemy.engine import Dialect +from sqlalchemy.types import TypeDecorator + + +class UTCDateTime(TypeDecorator[datetime]): + """A ``DateTime(timezone=True)`` column that reads and writes aware UTC.""" + + impl = DateTime(timezone=True) + cache_ok = True + + def process_bind_param( + self, value: datetime | None, dialect: Dialect + ) -> datetime | None: + if value is None: + return None + if value.tzinfo is None or value.utcoffset() is None: + raise ValueError( + "naive datetime given for a UTCDateTime column; " + "pass an aware datetime such as datetime.now(timezone.utc)" + ) + return value.astimezone(timezone.utc) + + def process_result_value( + self, value: datetime | None, dialect: Dialect + ) -> datetime | None: + if value is None: + return None + if value.tzinfo is None: + return value.replace(tzinfo=timezone.utc) + return value.astimezone(timezone.utc) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/crud.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/crud.py-tpl index 14bc212..73711e4 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/crud.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/crud.py-tpl @@ -5,11 +5,12 @@ # -------------------------------------------------------------------------- from typing import Sequence -from sqlmodel import select +from sqlmodel import col, select from sqlmodel.ext.asyncio.session import AsyncSession from src.app.crud.base import CRUDBase -from src.app.domains.items.models import Item, ItemCreate, ItemUpdate +from src.app.domains.items.models import Item +from src.app.domains.items.schemas import ItemCreate, ItemUpdate class ItemCRUD(CRUDBase[Item, ItemCreate, ItemUpdate]): @@ -18,7 +19,12 @@ class ItemCRUD(CRUDBase[Item, ItemCreate, ItemUpdate]): async def search_by_name( self, session: AsyncSession, term: str, *, limit: int = 20 ) -> Sequence[Item]: - statement = select(Item).where(Item.name.like(f"%{term}%")).limit(limit) # type: ignore[attr-defined] + statement = ( + select(Item) + .where(col(Item.name).contains(term)) + .order_by(col(Item.id)) + .limit(limit) + ) result = await session.exec(statement) return result.all() diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/models.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/models.py-tpl index f024217..dc7e8a2 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/models.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/models.py-tpl @@ -1,17 +1,17 @@ # -------------------------------------------------------------------------- -# Items domain — model definitions. +# Items domain — table model. # # SQLModel lets a single class act as both the SQLAlchemy table and the -# pydantic schema. ``ItemBase`` holds the shared fields; the table model and -# the API-facing schemas all derive from it, so a new column is declared -# exactly once. +# pydantic schema. ``ItemBase`` holds the shared fields; the table model here +# and the API schemas in ``schemas.py`` derive from it, so a new column is +# declared exactly once. # -------------------------------------------------------------------------- from datetime import datetime, timezone -from typing import Any -from pydantic import field_validator from sqlmodel import Field, SQLModel +from src.app.db.types import UTCDateTime + def _utcnow() -> datetime: return datetime.now(timezone.utc) @@ -32,39 +32,5 @@ class Item(ItemBase, table=True): __tablename__ = "items" id: int | None = Field(default=None, primary_key=True) - created_at: datetime = Field(default_factory=_utcnow) - - -class ItemCreate(ItemBase): - """POST body — same shape as the base, no server-assigned fields.""" - - -class ItemUpdate(SQLModel): - """PATCH body — every field optional so partial updates work. - - ``name``, ``price`` and ``in_stock`` back non-nullable columns, so a - field omitted from the request body is left untouched (thanks to - ``exclude_unset`` in ``CRUDBase.update``), but an explicit ``null`` for - one of them is rejected with a 422 rather than being written to the - database. Only ``description`` is an actually-nullable column, so it - alone accepts an explicit ``null``. - """ - - name: str | None = Field(default=None, min_length=1, max_length=128) - description: str | None = Field(default=None, max_length=512) - price: float | None = Field(default=None, ge=0) - in_stock: bool | None = None - - @field_validator("name", "price", "in_stock") - @classmethod - def _reject_explicit_null(cls, value: object, info: Any) -> object: - if value is None: - raise ValueError(f"{info.field_name} must not be null") - return value - - -class ItemPublic(ItemBase): - """Response body — the base fields plus the server-assigned ones.""" - - id: int - created_at: datetime + # Aware UTC in and out, on SQLite and PostgreSQL alike (see db/types.py). + created_at: datetime = Field(default_factory=_utcnow, sa_type=UTCDateTime) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/router.py-tpl index 38e46d4..790ff9f 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/router.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/router.py-tpl @@ -1,19 +1,19 @@ # -------------------------------------------------------------------------- # Items domain — HTTP transport. # -------------------------------------------------------------------------- -from fastapi import APIRouter, Depends, HTTPException, Query, status -from sqlmodel.ext.asyncio.session import AsyncSession +from fastapi import APIRouter, HTTPException, Request, Response, status -from src.app.core.config import settings -from src.app.crud.pagination import Page -from src.app.db.session import get_session +from src.app.api.deps import SessionDep +from src.app.core.pagination import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from src.app.core.responses import error_responses from src.app.domains.items.crud import item_crud -from src.app.domains.items.models import Item, ItemCreate, ItemPublic, ItemUpdate +from src.app.domains.items.models import Item +from src.app.domains.items.schemas import ItemCreate, ItemRead, ItemUpdate router = APIRouter(prefix="/items", tags=["items"]) -async def _get_or_404(session: AsyncSession, item_id: int) -> Item: +async def _get_or_404(session: SessionDep, item_id: int) -> Item: item = await item_crud.get(session, item_id) if item is None: raise HTTPException( @@ -22,48 +22,56 @@ async def _get_or_404(session: AsyncSession, item_id: int) -> Item: return item -@router.get("", response_model=Page[ItemPublic]) +@router.get("") async def list_items( - session: AsyncSession = Depends(get_session), - offset: int = Query(default=0, ge=0), - limit: int = Query(default=settings.DEFAULT_PAGE_LIMIT, ge=1), -) -> Page[ItemPublic]: - limit = min(limit, settings.MAX_PAGE_LIMIT) - items = await item_crud.list(session, offset=offset, limit=limit) - total = await item_crud.count(session) - return Page[ItemPublic]( - items=[ItemPublic.model_validate(item, from_attributes=True) for item in items], - total=total, - offset=offset, + session: SessionDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> Page[ItemRead]: + items = await item_crud.list_page(session, offset=offset, limit=limit) + return Page[ItemRead]( + items=[ItemRead.model_validate(item) for item in items], + total=await item_crud.count(session), limit=limit, + offset=offset, ) -@router.get("/{item_id}", response_model=ItemPublic) -async def read_item(item_id: int, session: AsyncSession = Depends(get_session)) -> Item: - return await _get_or_404(session, item_id) +@router.get("/{item_id}", responses=error_responses(404)) +async def read_item(item_id: int, session: SessionDep) -> ItemRead: + return ItemRead.model_validate(await _get_or_404(session, item_id)) -@router.post("", response_model=ItemPublic, status_code=status.HTTP_201_CREATED) +@router.post("", status_code=status.HTTP_201_CREATED) async def create_item( - payload: ItemCreate, session: AsyncSession = Depends(get_session) -) -> Item: - return await item_crud.create(session, payload) + payload: ItemCreate, session: SessionDep, request: Request, response: Response +) -> ItemRead: + item = await item_crud.create(session, payload) + response.headers["Location"] = str(request.url_for("read_item", item_id=item.id)) + return ItemRead.model_validate(item) + + +@router.put("/{item_id}", responses=error_responses(404)) +async def replace_item( + item_id: int, payload: ItemCreate, session: SessionDep +) -> ItemRead: + item = await _get_or_404(session, item_id) + return ItemRead.model_validate(await item_crud.replace(session, item, payload)) -@router.patch("/{item_id}", response_model=ItemPublic) +@router.patch("/{item_id}", responses=error_responses(404)) async def update_item( - item_id: int, - payload: ItemUpdate, - session: AsyncSession = Depends(get_session), -) -> Item: + item_id: int, payload: ItemUpdate, session: SessionDep +) -> ItemRead: item = await _get_or_404(session, item_id) - return await item_crud.update(session, item, payload) + return ItemRead.model_validate(await item_crud.update(session, item, payload)) -@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT) -async def delete_item( - item_id: int, session: AsyncSession = Depends(get_session) -) -> None: +@router.delete( + "/{item_id}", + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(404), +) +async def delete_item(item_id: int, session: SessionDep) -> None: item = await _get_or_404(session, item_id) await item_crud.delete(session, item) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/schemas.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/schemas.py-tpl new file mode 100644 index 0000000..8b90707 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/domains/items/schemas.py-tpl @@ -0,0 +1,45 @@ +# -------------------------------------------------------------------------- +# Items domain — API schemas built on the table model's shared fields. +# -------------------------------------------------------------------------- +from datetime import datetime +from typing import Any + +from pydantic import field_validator +from sqlmodel import Field, SQLModel + +from src.app.domains.items.models import ItemBase + + +class ItemCreate(ItemBase): + """POST and PUT body — same shape as the base, no server-assigned fields.""" + + +class ItemUpdate(SQLModel): + """PATCH body — every field optional so partial updates work. + + ``name``, ``price`` and ``in_stock`` back non-nullable columns, so a + field omitted from the request body is left untouched (thanks to + ``exclude_unset`` in ``CRUDBase.update``), but an explicit ``null`` for + one of them is rejected with a 422 rather than being written to the + database. Only ``description`` is an actually-nullable column, so it + alone accepts an explicit ``null``. + """ + + name: str | None = Field(default=None, min_length=1, max_length=128) + description: str | None = Field(default=None, max_length=512) + price: float | None = Field(default=None, ge=0) + in_stock: bool | None = None + + @field_validator("name", "price", "in_stock") + @classmethod + def _reject_explicit_null(cls, value: object, info: Any) -> object: + if value is None: + raise ValueError(f"{info.field_name} must not be null") + return value + + +class ItemRead(ItemBase): + """Response body — the base fields plus the server-assigned ones.""" + + id: int + created_at: datetime diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/main.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/main.py-tpl index 4371ef9..0935eea 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/main.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/main.py-tpl @@ -7,6 +7,7 @@ from contextlib import asynccontextmanager from fastapi import FastAPI from starlette.middleware.cors import CORSMiddleware +from src.app.api import health from src.app.api.router import api_router from src.app.core.config import settings from src.app.db.session import create_db_and_tables, engine @@ -34,10 +35,12 @@ if settings.all_cors_origins: app.add_middleware( CORSMiddleware, allow_origins=settings.all_cors_origins, - allow_credentials=True, + # Browsers refuse credentials with the "*" wildcard; never send both. + allow_credentials="*" not in settings.all_cors_origins, allow_methods=["*"], allow_headers=["*"], ) -app.include_router(api_router, prefix=settings.API_V1_PREFIX) +app.include_router(health.router) # fastkit:routes +app.include_router(api_router, prefix=settings.API_V1_PREFIX) diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/conftest.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/conftest.py-tpl index 9989be1..6c12256 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/conftest.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/conftest.py-tpl @@ -13,6 +13,7 @@ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from sqlalchemy.pool import StaticPool from sqlmodel import SQLModel from sqlmodel.ext.asyncio.session import AsyncSession + from src.app.db import base # noqa: F401 (registers the models) from src.app.db.session import get_session from src.app.main import app diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_config.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_config.py-tpl index fba88b0..494bd0f 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_config.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_config.py-tpl @@ -1,44 +1,207 @@ # -------------------------------------------------------------------------- -# Settings validation: production refuses a public example SECRET_KEY. +# Settings validation: the SECRET_KEY rule, ENVIRONMENT values, +# environment variable names and the CORS wildcard. # -------------------------------------------------------------------------- +import json +import os import re +import secrets +import subprocess +import sys from pathlib import Path +from typing import Any import pytest from pydantic import ValidationError -from src.app.core.config import KNOWN_EXAMPLE_SECRET_KEYS, Settings +from src.app.core.config import ( + KNOWN_EXAMPLE_SECRET_KEYS, + MIN_SECRET_KEY_BYTES, + Settings, +) -ENV_EXAMPLE = Path(__file__).resolve().parents[1] / ".env.example" +PROJECT_ROOT = Path(__file__).resolve().parents[1] +ENV_EXAMPLE = PROJECT_ROOT / ".env.example" +APP_MODULE = "src.app.main" +#: Settings without a default; none in this template. +REQUIRED: dict[str, Any] = {} +STRONG_KEY = "k" * MIN_SECRET_KEY_BYTES +#: Every environment except development refuses a missing, public or short +#: SECRET_KEY. +STRICT_ENVIRONMENTS = ["staging", "production"] + +@pytest.fixture(autouse=True) +def _isolated_settings_environment(monkeypatch: pytest.MonkeyPatch) -> None: + """Shell variables, in any spelling, must not leak into Settings().""" + for name in list(os.environ): + if name.upper() in {"ENVIRONMENT", "SECRET_KEY", "BACKEND_CORS_ORIGINS"}: + monkeypatch.delenv(name) + + +def make_settings(env_file: Path | None = None, **values: Any) -> Settings: + """Settings from explicit values; a developer's .env is never read.""" + return Settings(_env_file=env_file, **{**REQUIRED, **values}) # type: ignore[call-arg] + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_require_an_explicit_secret_key(environment: str) -> None: + with pytest.raises( + ValidationError, match=f"must be set explicitly when ENVIRONMENT={environment}" + ): + make_settings(ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_refuse_a_short_secret_key(environment: str) -> None: + short_key = "k" * (MIN_SECRET_KEY_BYTES - 1) + + with pytest.raises(ValidationError, match=f"at least {MIN_SECRET_KEY_BYTES} bytes"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=short_key) + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) @pytest.mark.parametrize("example_key", sorted(KNOWN_EXAMPLE_SECRET_KEYS)) -def test_production_refuses_example_secret_key(example_key: str) -> None: +def test_strict_environments_refuse_every_public_example_key( + environment: str, example_key: str +) -> None: + with pytest.raises(ValidationError, match="public example value"): + make_settings(ENVIRONMENT=environment, SECRET_KEY=f" {example_key} ") + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environment_errors_say_how_to_generate_a_key(environment: str) -> None: with pytest.raises(ValidationError, match="token_urlsafe"): - Settings(_env_file=None, ENVIRONMENT="production", SECRET_KEY=example_key) + make_settings(ENVIRONMENT=environment) -@pytest.mark.parametrize("environment", ["development", "staging"]) -def test_example_secret_key_is_allowed_outside_production(environment: str) -> None: - settings = Settings( - _env_file=None, ENVIRONMENT=environment, SECRET_KEY="changethis" +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_an_explicit_strong_key(environment: str) -> None: + settings = make_settings(ENVIRONMENT=environment, SECRET_KEY=STRONG_KEY) + + assert settings.ENVIRONMENT == environment + assert settings.SECRET_KEY == STRONG_KEY + + +@pytest.mark.parametrize("environment", STRICT_ENVIRONMENTS) +def test_strict_environments_accept_the_key_fastkit_writes_to_env( + tmp_path: Path, environment: str +) -> None: + env_file = tmp_path / ".env" + env_file.write_text( + f"ENVIRONMENT={environment}\nSECRET_KEY={secrets.token_urlsafe(32)}\n", + encoding="utf-8", ) - assert settings.SECRET_KEY == "changethis" + assert make_settings(env_file).ENVIRONMENT == environment + + +def test_development_without_a_key_uses_a_random_one() -> None: + settings = make_settings(ENVIRONMENT="development") + + assert len(settings.SECRET_KEY.encode()) >= MIN_SECRET_KEY_BYTES + assert settings.SECRET_KEY not in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_development_only_warns_about_an_example_key() -> None: + example_key = sorted(KNOWN_EXAMPLE_SECRET_KEYS)[0] + + with pytest.warns(UserWarning, match="public example value"): + settings = make_settings(ENVIRONMENT="development", SECRET_KEY=example_key) + + assert settings.SECRET_KEY == example_key + +@pytest.mark.parametrize("value", ["Production", "PRODUCTION", " production", "prod"]) +def test_unknown_environment_values_fail_closed(value: str) -> None: + with pytest.raises(ValidationError, match="ENVIRONMENT"): + make_settings(ENVIRONMENT=value, SECRET_KEY=STRONG_KEY) -def test_production_accepts_a_real_secret_key() -> None: - settings = Settings( - _env_file=None, - ENVIRONMENT="production", - SECRET_KEY="a-real-unique-key-0123456789abcdef", + +def test_environment_variable_names_are_case_insensitive( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("environment", "production") + + with pytest.raises(ValidationError, match="must be set explicitly"): + make_settings() + + monkeypatch.setenv("secret_key", STRONG_KEY) + + assert make_settings().ENVIRONMENT == "production" + + +@pytest.mark.parametrize("raw", ["*", " * ", '["*"]', "*,http://localhost:3000"]) +def test_cors_wildcard_is_accepted(monkeypatch: pytest.MonkeyPatch, raw: str) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", raw) + + assert make_settings().all_cors_origins == ["*"] + + +def test_cors_origins_must_be_urls_or_the_wildcard( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("BACKEND_CORS_ORIGINS", "not-a-url") + + with pytest.raises(ValidationError): + make_settings() + + +#: Runs in a fresh interpreter: the app reads its settings at import time. +_PREFLIGHT = f""" +import json +from fastapi.testclient import TestClient +from {APP_MODULE} import app + +headers = {{ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "GET", +}} +response = TestClient(app).options("/", headers=headers) +allowed = {{ + k: v for k, v in response.headers.items() if k.startswith("access-control-allow-") +}} +print(json.dumps(allowed)) +""" + + +@pytest.mark.parametrize( + ("origins", "allow_origin", "allow_credentials"), + [ + ("*", "*", None), + ("http://localhost:3000", "http://localhost:3000", "true"), + ], +) +def test_cors_wildcard_is_never_combined_with_credentials( + origins: str, allow_origin: str, allow_credentials: str | None +) -> None: + env = { + **os.environ, + **{name: str(value) for name, value in REQUIRED.items()}, + "BACKEND_CORS_ORIGINS": origins, + "ENVIRONMENT": "development", + } + result = subprocess.run( + [sys.executable, "-c", _PREFLIGHT], + cwd=PROJECT_ROOT, + env=env, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=120, + check=False, ) - assert settings.ENVIRONMENT == "production" + assert result.returncode == 0, result.stderr + headers = json.loads(result.stdout.strip().splitlines()[-1]) + assert headers["access-control-allow-origin"] == allow_origin + assert headers.get("access-control-allow-credentials") == allow_credentials def test_env_example_secret_key_is_a_known_example_value() -> None: - """Whatever .env.example ships must be one the production guard rejects.""" + """Whatever .env.example ships must be one the SECRET_KEY guard rejects.""" if not ENV_EXAMPLE.is_file(): pytest.skip(".env.example is not part of this checkout") @@ -48,3 +211,21 @@ def test_env_example_secret_key_is_a_known_example_value() -> None: assert match is not None assert match.group(1).strip() in KNOWN_EXAMPLE_SECRET_KEYS + + +def test_cors_origins_drop_empty_entries(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("BACKEND_CORS_ORIGINS", raising=False) + settings = make_settings( + BACKEND_CORS_ORIGINS="http://localhost:3000, ,http://localhost:5173/", + ) + + assert settings.all_cors_origins == [ + "http://localhost:3000", + "http://localhost:5173", + ] + + +def test_api_v1_prefix_default(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("API_V1_PREFIX", raising=False) + + assert make_settings().API_V1_PREFIX == "/api/v1" diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_crud_base.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_crud_base.py-tpl index 111b050..88ebc33 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_crud_base.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_crud_base.py-tpl @@ -3,8 +3,9 @@ # direct coverage rather than only being exercised through HTTP. # -------------------------------------------------------------------------- from sqlmodel.ext.asyncio.session import AsyncSession + from src.app.domains.items.crud import item_crud -from src.app.domains.items.models import ItemCreate, ItemUpdate +from src.app.domains.items.schemas import ItemCreate, ItemUpdate async def test_create_and_count(session: AsyncSession) -> None: @@ -41,3 +42,27 @@ async def test_delete_removes_the_row(session: AsyncSession) -> None: await item_crud.delete(session, item) assert await item_crud.get(session, item.id) is None + + +async def test_list_page_is_ordered_by_primary_key(session: AsyncSession) -> None: + created = [ + await item_crud.create(session, ItemCreate(name=name, price=1.0)) + for name in ("Zebra", "Apple", "Mango") + ] + + page = await item_crud.list_page(session, offset=1, limit=2) + + assert [item.id for item in page] == [item.id for item in created][1:3] + + +async def test_replace_resets_omitted_optional_fields(session: AsyncSession) -> None: + item = await item_crud.create( + session, + ItemCreate(name="Mug", description="ceramic", price=9.0, in_stock=False), + ) + + replaced = await item_crud.replace(session, item, ItemCreate(name="Cup", price=3.0)) + + assert replaced.name == "Cup" + assert replaced.description is None + assert replaced.in_stock is True diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_health.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_health.py-tpl index 47af278..f0f4f0b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_health.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_health.py-tpl @@ -1,12 +1,128 @@ # -------------------------------------------------------------------------- -# Health endpoint smoke test. +# Liveness and readiness probes. # -------------------------------------------------------------------------- +import asyncio +import logging +import time +from collections.abc import AsyncGenerator +from pathlib import Path +from typing import Any + +import pytest from httpx import AsyncClient -from src.app.core.config import settings +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine +from sqlmodel.ext.asyncio.session import AsyncSession + +from src.app.api import health +from src.app.db.session import CONNECT_TIMEOUT_SECONDS, _connect_args, get_session +from src.app.main import app + + +class _FakeSession: + """Stands in for the request session; ``exec`` hangs or fails.""" + + def __init__(self, *, delay: float = 0.0, error: Exception | None = None): + self.delay = delay + self.error = error + + async def exec(self, *_: Any, **__: Any) -> None: + await asyncio.sleep(self.delay) + if self.error is not None: + raise self.error + + +def _use_session(fake: _FakeSession) -> None: + async def _override() -> AsyncGenerator[Any, None]: + yield fake + app.dependency_overrides[get_session] = _override -async def test_health_endpoint_returns_ok(client: AsyncClient) -> None: - response = await client.get(f"{settings.API_V1_PREFIX}/health") + +async def test_health_is_served_at_the_root(client: AsyncClient) -> None: + response = await client.get("/health") + + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + +async def test_ready_reports_ok_when_the_database_answers(client: AsyncClient) -> None: + response = await client.get("/ready") assert response.status_code == 200 assert response.json() == {"status": "ok"} + + +async def test_ready_reports_503_when_the_database_is_down( + client: AsyncClient, tmp_path: Path +) -> None: + # A SQLite file inside a directory that does not exist cannot be opened. + broken = create_async_engine( + f"sqlite+aiosqlite:///{tmp_path / 'missing' / 'app.db'}" + ) + factory = async_sessionmaker(bind=broken, class_=AsyncSession) + + async def _broken_session() -> AsyncGenerator[AsyncSession, None]: + async with factory() as session: + yield session + + app.dependency_overrides[get_session] = _broken_session + + response = await client.get("/ready") + + assert response.status_code == 503 + assert response.json() == {"status": "unavailable"} + await broken.dispose() + + +async def test_ready_answers_503_within_the_timeout_when_the_database_hangs( + client: AsyncClient, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + monkeypatch.setattr(health, "READY_TIMEOUT_SECONDS", 0.2) + _use_session(_FakeSession(delay=30)) + + started = time.monotonic() + with caplog.at_level(logging.WARNING, logger=health.logger.name): + response = await client.get("/ready") + elapsed = time.monotonic() - started + + assert response.status_code == 503 + assert response.json() == {"status": "unavailable"} + assert elapsed < 5 + assert "TimeoutError" in caplog.text + + +async def test_ready_answers_503_for_any_error( + client: AsyncClient, caplog: pytest.LogCaptureFixture +) -> None: + # Not a SQLAlchemyError: the probe must still answer 503, not 500. + _use_session(_FakeSession(error=OSError("connection refused"))) + + with caplog.at_level(logging.WARNING, logger=health.logger.name): + response = await client.get("/ready") + + assert response.status_code == 503 + assert response.json() == {"status": "unavailable"} + assert "OSError" in caplog.text + + +def test_ready_timeout_is_a_couple_of_seconds() -> None: + assert 0 < health.READY_TIMEOUT_SECONDS <= 5 + + +@pytest.mark.parametrize( + ("url", "expected"), + [ + ("postgresql+asyncpg://u:p@db/app", {"timeout": CONNECT_TIMEOUT_SECONDS}), + ( + "postgresql+psycopg://u:p@db/app", + {"connect_timeout": CONNECT_TIMEOUT_SECONDS}, + ), + ("sqlite+aiosqlite:///./app.db", {}), + ], +) +def test_postgres_drivers_get_a_connect_timeout( + url: str, expected: dict[str, int] +) -> None: + assert _connect_args(url) == expected diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_items.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_items.py-tpl index f86978e..14abf89 100644 --- a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_items.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_items.py-tpl @@ -1,33 +1,43 @@ # -------------------------------------------------------------------------- # Items domain — end-to-end coverage of the CRUD endpoints. # -------------------------------------------------------------------------- +from typing import Any + from httpx import AsyncClient + from src.app.core.config import settings ITEMS_URL = f"{settings.API_V1_PREFIX}/items" +async def _create(client: AsyncClient, payload: dict[str, Any]) -> dict[str, Any]: + response = await client.post(ITEMS_URL, json=payload) + assert response.status_code == 201, response.text + body: dict[str, Any] = response.json() + return body + + async def test_list_items_starts_empty(client: AsyncClient) -> None: response = await client.get(ITEMS_URL) assert response.status_code == 200 - body = response.json() - assert body["items"] == [] - assert body["total"] == 0 + assert response.json() == {"items": [], "total": 0, "limit": 20, "offset": 0} -async def test_create_then_read_item( +async def test_create_returns_201_and_a_resolvable_location( client: AsyncClient, item_payload: dict[str, object] ) -> None: create_response = await client.post(ITEMS_URL, json=item_payload) assert create_response.status_code == 201 created = create_response.json() - assert created["id"] == 1 + assert isinstance(created["id"], int) assert created["name"] == "Sticker" assert created["in_stock"] is True - read_response = await client.get(f"{ITEMS_URL}/{created['id']}") + location = create_response.headers["Location"] + assert location.endswith(f"{ITEMS_URL}/{created['id']}") + read_response = await client.get(location) assert read_response.status_code == 200 assert read_response.json() == created @@ -37,12 +47,47 @@ async def test_get_unknown_item_returns_404(client: AsyncClient) -> None: response = await client.get(f"{ITEMS_URL}/999") assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + +async def test_put_replaces_every_field( + client: AsyncClient, item_payload: dict[str, object] +) -> None: + created = await _create(client, {**item_payload, "in_stock": False}) + + response = await client.put( + f"{ITEMS_URL}/{created['id']}", json={"name": "Poster", "price": 7.0} + ) + + assert response.status_code == 200 + body = response.json() + assert body["name"] == "Poster" + # Omitted optional fields fall back to their defaults. + assert body["description"] is None + assert body["in_stock"] is True + assert body["created_at"] == created["created_at"] + + +async def test_put_requires_the_full_representation( + client: AsyncClient, item_payload: dict[str, object] +) -> None: + created = await _create(client, item_payload) + + response = await client.put(f"{ITEMS_URL}/{created['id']}", json={"price": 1.0}) + + assert response.status_code == 422 + + +async def test_put_unknown_item_returns_404(client: AsyncClient) -> None: + response = await client.put(f"{ITEMS_URL}/999", json={"name": "x", "price": 1.0}) + + assert response.status_code == 404 async def test_partial_update_leaves_other_fields_alone( client: AsyncClient, item_payload: dict[str, object] ) -> None: - created = (await client.post(ITEMS_URL, json=item_payload)).json() + created = await _create(client, item_payload) response = await client.patch(f"{ITEMS_URL}/{created['id']}", json={"price": 11.0}) @@ -56,11 +101,9 @@ async def test_partial_update_leaves_other_fields_alone( async def test_partial_update_rejects_explicit_null_for_non_nullable_field( client: AsyncClient, item_payload: dict[str, object] ) -> None: - created = (await client.post(ITEMS_URL, json=item_payload)).json() + created = await _create(client, item_payload) - response = await client.patch( - f"{ITEMS_URL}/{created['id']}", json={"name": None} - ) + response = await client.patch(f"{ITEMS_URL}/{created['id']}", json={"name": None}) assert response.status_code == 422 @@ -68,7 +111,7 @@ async def test_partial_update_rejects_explicit_null_for_non_nullable_field( async def test_partial_update_allows_explicit_null_for_nullable_field( client: AsyncClient, item_payload: dict[str, object] ) -> None: - created = (await client.post(ITEMS_URL, json=item_payload)).json() + created = await _create(client, item_payload) response = await client.patch( f"{ITEMS_URL}/{created['id']}", json={"description": None} @@ -78,18 +121,32 @@ async def test_partial_update_allows_explicit_null_for_nullable_field( assert response.json()["description"] is None +async def test_patch_unknown_item_returns_404(client: AsyncClient) -> None: + response = await client.patch(f"{ITEMS_URL}/999", json={"price": 1.0}) + + assert response.status_code == 404 + + async def test_delete_item( client: AsyncClient, item_payload: dict[str, object] ) -> None: - created = (await client.post(ITEMS_URL, json=item_payload)).json() + created = await _create(client, item_payload) delete_response = await client.delete(f"{ITEMS_URL}/{created['id']}") assert delete_response.status_code == 204 + assert delete_response.content == b"" follow_up = await client.get(f"{ITEMS_URL}/{created['id']}") assert follow_up.status_code == 404 +async def test_delete_unknown_item_returns_404(client: AsyncClient) -> None: + response = await client.delete(f"{ITEMS_URL}/999") + + assert response.status_code == 404 + assert response.json() == {"detail": "Item not found"} + + async def test_create_item_validates_payload(client: AsyncClient) -> None: response = await client.post(ITEMS_URL, json={"name": "", "price": -1.0}) @@ -97,8 +154,10 @@ async def test_create_item_validates_payload(client: AsyncClient) -> None: async def test_pagination_reports_total_and_window(client: AsyncClient) -> None: - for index in range(5): - await client.post(ITEMS_URL, json={"name": f"Item {index}", "price": 1.0}) + ids = [ + (await _create(client, {"name": f"Item {index}", "price": 1.0}))["id"] + for index in range(5) + ] response = await client.get(ITEMS_URL, params={"offset": 2, "limit": 2}) @@ -107,4 +166,16 @@ async def test_pagination_reports_total_and_window(client: AsyncClient) -> None: assert body["total"] == 5 assert body["offset"] == 2 assert body["limit"] == 2 - assert [item["name"] for item in body["items"]] == ["Item 2", "Item 3"] + assert [item["id"] for item in body["items"]] == sorted(ids)[2:4] + + +async def test_pagination_rejects_out_of_range_parameters(client: AsyncClient) -> None: + for params in ({"limit": 0}, {"limit": 101}, {"offset": -1}): + response = await client.get(ITEMS_URL, params=params) + assert response.status_code == 422, params + + +async def test_collection_is_served_without_a_redirect(client: AsyncClient) -> None: + response = await client.get(ITEMS_URL, follow_redirects=False) + + assert response.status_code == 200 diff --git a/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_timestamps.py-tpl b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_timestamps.py-tpl new file mode 100644 index 0000000..81f1d80 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_timestamps.py-tpl @@ -0,0 +1,52 @@ +# -------------------------------------------------------------------------- +# Timestamps are stored and returned as aware UTC datetimes. +# -------------------------------------------------------------------------- +from datetime import datetime, timedelta, timezone + +import pytest +from httpx import AsyncClient +from sqlalchemy.exc import StatementError +from sqlmodel import select +from sqlmodel.ext.asyncio.session import AsyncSession + +from src.app.core.config import settings +from src.app.domains.items.models import Item + +API = settings.API_V1_PREFIX + + +async def test_created_at_round_trips_as_aware_utc(session: AsyncSession) -> None: + # Written with a +09:00 offset; must come back as the same instant in UTC. + written = datetime(2026, 1, 2, 12, 30, tzinfo=timezone(timedelta(hours=9))) + session.add(Item(name="Clock", price=1.0, created_at=written)) + await session.commit() + session.expunge_all() + + item = (await session.exec(select(Item))).one() + + assert item.created_at.tzinfo is not None + assert item.created_at.utcoffset() == timedelta(0) + assert item.created_at == written + assert item.created_at.hour == 3 + + +async def test_naive_datetime_is_rejected(session: AsyncSession) -> None: + session.add(Item(name="Clock", price=1.0, created_at=datetime(2026, 1, 2, 12))) + + with pytest.raises(StatementError, match="naive datetime"): + await session.commit() + await session.rollback() + + +async def test_api_timestamps_carry_an_offset(client: AsyncClient) -> None: + before = datetime.now(timezone.utc) + response = await client.post(f"{API}/items", json={"name": "Pin", "price": 1.0}) + assert response.status_code == 201, response.text + + created_at = response.json()["created_at"] + fetched = (await client.get(response.headers["location"])).json()["created_at"] + + for value in (created_at, fetched): + parsed = datetime.fromisoformat(value) + assert parsed.utcoffset() == timedelta(0), value + assert parsed >= before - timedelta(seconds=1) diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/api/routes/__init__.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/api/routes/__init__.py-tpl deleted file mode 100644 index e69de29..0000000 diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/api/routes/new_route.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/api/routes/new_route.py-tpl index 9f3cc90..18e31bd 100644 --- a/src/fastapi_fastkit/fastapi_project_template/modules/api/routes/new_route.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/modules/api/routes/new_route.py-tpl @@ -1,64 +1,128 @@ # -------------------------------------------------------------------------- -# CRUD Endpoint +# API routes # -------------------------------------------------------------------------- -from fastapi import APIRouter - -from .crud. import * -from .schemas. import * - -router = APIRouter() - - -@router.get("/") -def get_route(): - result = read_crud() - - # Add Presentation Layer logics here - - return result - - -@router.post("/") -def post_route(): - result = create_crud() - - # Add Presentation Layer logics here - - return result - - -@router.put("/") -def put_route(): - result = edit_crud() - - # Add Presentation Layer logics here - - return result - - -@router.patch("/") -def patch_route(): - result = edit_crud() - - # Add Presentation Layer logics here - - return result - - -@router.delete("/") -def delete_route(): - result = remove_crud() - - # Add Presentation Layer logics here - - return result - - -"""Add other routers here - -For more information, please refer to the following link: - -https://fastapi.tiangolo.com/tutorial/first-steps/#operation -https://fastapi.tiangolo.com/tutorial/bigger-applications/?h=apirouter#another-module-with-apirouter -https://fastapi.tiangolo.com/tutorial/body/?h=pydantic -""" +from typing import Annotated + +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status + +from import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from import error_responses +from .crud. import ( + Repository, + get__repository, +) +from .schemas. import ( + Create, + Read, + Update, +) + +router = APIRouter(prefix="/", tags=[""]) + +RepositoryDep = Annotated[ + Repository, + Depends(get__repository), +] + +NOT_FOUND = " not found" + + +def not_found() -> HTTPException: + return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=NOT_FOUND) + + +@router.get("", response_model=Page[Read]) +def list_( + repository: RepositoryDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> Page[Read]: + """List records ordered by id, one page at a time.""" + records, total = repository.list_page(offset=offset, limit=limit) + return Page[Read]( + items=[Read.model_validate(record) for record in records], + total=total, + limit=limit, + offset=offset, + ) + + +@router.post( + "", + response_model=Read, + status_code=status.HTTP_201_CREATED, +) +def create_( + payload: Create, + request: Request, + response: Response, + repository: RepositoryDep, +) -> Read: + """Create a record; the Location header points at it.""" + record = repository.add(payload.model_dump()) + location = request.url_for("get_", _id=record.id) + response.headers["Location"] = str(location) + return Read.model_validate(record) + + +@router.get( + "/{_id}", + response_model=Read, + responses=error_responses(status.HTTP_404_NOT_FOUND), +) +def get_( + _id: int, + repository: RepositoryDep, +) -> Read: + record = repository.get(_id) + if record is None: + raise not_found() + return Read.model_validate(record) + + +@router.put( + "/{_id}", + response_model=Read, + responses=error_responses(status.HTTP_404_NOT_FOUND), +) +def replace_( + _id: int, + payload: Create, + repository: RepositoryDep, +) -> Read: + """Replace every field (PUT): omitted optional fields are cleared.""" + record = repository.replace(_id, payload.model_dump()) + if record is None: + raise not_found() + return Read.model_validate(record) + + +@router.patch( + "/{_id}", + response_model=Read, + responses=error_responses(status.HTTP_404_NOT_FOUND), +) +def update_( + _id: int, + payload: Update, + repository: RepositoryDep, +) -> Read: + """Change only the fields present in the body (PATCH).""" + changes = payload.model_dump(exclude_unset=True) + record = repository.update(_id, changes) + if record is None: + raise not_found() + return Read.model_validate(record) + + +@router.delete( + "/{_id}", + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(status.HTTP_404_NOT_FOUND), +) +def delete_( + _id: int, + repository: RepositoryDep, +) -> None: + if not repository.delete(_id): + raise not_found() diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/api/routes/new_route_envelope.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/api/routes/new_route_envelope.py-tpl new file mode 100644 index 0000000..00bfaae --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/modules/api/routes/new_route_envelope.py-tpl @@ -0,0 +1,128 @@ +# -------------------------------------------------------------------------- +# API routes +# +# Successful responses are wrapped in ``ResponseSchema`` like the project's +# other routers; errors are wrapped by its exception handlers. DELETE answers +# 204 with no body, so it has no envelope. +# -------------------------------------------------------------------------- +from typing import Annotated + +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status + +from import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from .crud. import ( + Repository, + get__repository, +) +from import error_responses +from import success_response +from import ResponseSchema +from .schemas. import ( + Create, + Read, + Update, +) + +router = APIRouter( + prefix="/", + tags=[""], + responses=error_responses(422, 500), +) + +RepositoryDep = Annotated[ + Repository, + Depends(get__repository), +] + +NOT_FOUND = " not found" + + +def not_found() -> HTTPException: + return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=NOT_FOUND) + + +@router.get("") +def list_( + request: Request, + repository: RepositoryDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> ResponseSchema[Page[Read]]: + """List records ordered by id, one page at a time.""" + records, total = repository.list_page(offset=offset, limit=limit) + page = Page[Read]( + items=[Read.model_validate(record) for record in records], + total=total, + limit=limit, + offset=offset, + ) + return success_response(request, page) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_( + payload: Create, + request: Request, + response: Response, + repository: RepositoryDep, +) -> ResponseSchema[Read]: + """Create a record; the Location header points at it.""" + record = repository.add(payload.model_dump()) + location = request.url_for("get_", _id=record.id) + response.headers["Location"] = str(location) + created = Read.model_validate(record) + return success_response(request, created, status_code=201) + + +@router.get("/{_id}", responses=error_responses(404)) +def get_( + _id: int, + request: Request, + repository: RepositoryDep, +) -> ResponseSchema[Read]: + record = repository.get(_id) + if record is None: + raise not_found() + return success_response(request, Read.model_validate(record)) + + +@router.put("/{_id}", responses=error_responses(404)) +def replace_( + _id: int, + payload: Create, + request: Request, + repository: RepositoryDep, +) -> ResponseSchema[Read]: + """Replace every field (PUT): omitted optional fields are cleared.""" + record = repository.replace(_id, payload.model_dump()) + if record is None: + raise not_found() + return success_response(request, Read.model_validate(record)) + + +@router.patch("/{_id}", responses=error_responses(404)) +def update_( + _id: int, + payload: Update, + request: Request, + repository: RepositoryDep, +) -> ResponseSchema[Read]: + """Change only the fields present in the body (PATCH).""" + changes = payload.model_dump(exclude_unset=True) + record = repository.update(_id, changes) + if record is None: + raise not_found() + return success_response(request, Read.model_validate(record)) + + +@router.delete( + "/{_id}", + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(404), +) +def delete_( + _id: int, + repository: RepositoryDep, +) -> None: + if not repository.delete(_id): + raise not_found() diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/core/pagination.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/core/pagination.py-tpl new file mode 100644 index 0000000..2688822 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/modules/core/pagination.py-tpl @@ -0,0 +1,37 @@ +# -------------------------------------------------------------------------- +# Limit/offset pagination shared by every list endpoint. +# +# List endpoints take ``limit: LimitParam = DEFAULT_LIMIT`` and +# ``offset: OffsetParam = 0`` and return a ``Page[T]`` envelope: +# {"items": [...], "total": 42, "limit": 20, "offset": 0}. Out-of-range +# values are rejected with a 422 rather than clamped. +# -------------------------------------------------------------------------- +from typing import Annotated, Generic, TypeVar + +from fastapi import Query +from pydantic import BaseModel + +T = TypeVar("T") + +#: Page size used when the client sends no ``limit``. +DEFAULT_LIMIT = 20 +#: Largest page a client may ask for. +MAX_LIMIT = 100 + +LimitParam = Annotated[ + int, Query(ge=1, le=MAX_LIMIT, description="Maximum number of items to return.") +] +OffsetParam = Annotated[int, Query(ge=0, description="Number of items to skip.")] + + +class Page(BaseModel, Generic[T]): + """One page of a collection, ordered by primary key. + + ``total`` counts the whole collection, so a client knows there is a next + page while ``offset + len(items) < total``. + """ + + items: list[T] + total: int + limit: int + offset: int diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/core/responses.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/core/responses.py-tpl new file mode 100644 index 0000000..bffc8c1 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/modules/core/responses.py-tpl @@ -0,0 +1,40 @@ +# -------------------------------------------------------------------------- +# OpenAPI error responses shared by the routers. +# +# FastAPI documents 2xx and 422 on its own. Routes that can also answer 401, +# 404, 409, ... declare it with ``responses=error_responses(404)`` so clients +# see every status code and the ``{"detail": "..."}`` body in the schema. +# -------------------------------------------------------------------------- +from http import HTTPStatus +from typing import Any + +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + """Body FastAPI sends for an ``HTTPException``.""" + + detail: str + + +def error_responses(*status_codes: int) -> dict[int | str, dict[str, Any]]: + """Build ``responses=`` entries that document the given error codes. + + A 401 entry also documents the ``WWW-Authenticate`` header every 401 + response carries. + """ + responses: dict[int | str, dict[str, Any]] = {} + for code in status_codes: + entry: dict[str, Any] = { + "model": ErrorDetail, + "description": HTTPStatus(code).phrase, + } + if code == HTTPStatus.UNAUTHORIZED: + entry["headers"] = { + "WWW-Authenticate": { + "description": "Authentication scheme to use (Bearer).", + "schema": {"type": "string"}, + } + } + responses[code] = entry + return responses diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/crud/__init__.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/crud/__init__.py-tpl deleted file mode 100644 index e69de29..0000000 diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/crud/new_route.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/crud/new_route.py-tpl index f00b64c..23abab5 100644 --- a/src/fastapi_fastkit/fastapi_project_template/modules/crud/new_route.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/modules/crud/new_route.py-tpl @@ -1,29 +1,95 @@ # -------------------------------------------------------------------------- -# CRUD method module +# data access +# +# Records are kept in memory: they are lost on restart and not shared +# between worker processes. Swap the repository for a database-backed one +# when the resource needs persistence; the routes only use its methods. # -------------------------------------------------------------------------- -def read_crud(): - # Add Business Layer logics here - pass +import dataclasses +import threading +from typing import Any -def create_crud(): - # Add Business Layer logics here - pass +@dataclasses.dataclass(frozen=True) +class : + id: int + name: str + description: str | None = None -def edit_crud(): - # Add Business Layer logics here - pass +class Repository: + """Thread-safe in-memory storage for records.""" + def __init__(self) -> None: + self._records: dict[int, ] = {} + self._next_id = 1 + self._lock = threading.Lock() -def remove_crud(): - # Add Business Layer logics here - pass + def list_page( + self, + offset: int, + limit: int, + ) -> tuple[list[], int]: + """One page ordered by id, and the total number of records.""" + with self._lock: + ids = sorted(self._records)[offset : offset + limit] + return [self._records[record_id] for record_id in ids], len(self._records) -"""Add other crud functions here + def get(self, record_id: int) -> | None: + with self._lock: + return self._records.get(record_id) -For more information, please refer to the following link: + def add(self, values: dict[str, Any]) -> : + with self._lock: + record = (id=self._next_id, **values) + self._records[record.id] = record + self._next_id += 1 + return record -https://fastapi.tiangolo.com/tutorial/first-steps/#operation -https://fastapi.tiangolo.com/tutorial/dependencies/ -""" + def replace( + self, + record_id: int, + values: dict[str, Any], + ) -> | None: + with self._lock: + if record_id not in self._records: + return None + record = (id=record_id, **values) + self._records[record_id] = record + return record + + def update( + self, + record_id: int, + changes: dict[str, Any], + ) -> | None: + with self._lock: + current = self._records.get(record_id) + if current is None: + return None + record = dataclasses.replace(current, **changes) + self._records[record_id] = record + return record + + def delete(self, record_id: int) -> bool: + with self._lock: + return self._records.pop(record_id, None) is not None + + def reset(self) -> None: + with self._lock: + self._records.clear() + self._next_id = 1 + + +# One store per process, shared by every request. +_repository = Repository() + + +def get__repository() -> Repository: + """Dependency returning the shared repository (override it in tests).""" + return _repository + + +def reset_store() -> None: + """Empty the store; the tests call it to isolate their state.""" + _repository.reset() diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/domain/models.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/domain/models.py-tpl index 574fb7f..dc03fad 100644 --- a/src/fastapi_fastkit/fastapi_project_template/modules/domain/models.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/modules/domain/models.py-tpl @@ -1,11 +1,11 @@ # -------------------------------------------------------------------------- # domain models. # -------------------------------------------------------------------------- +import dataclasses -from dataclasses import dataclass - -@dataclass +@dataclasses.dataclass(frozen=True) class : id: int name: str + description: str | None = None diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/domain/repository.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/domain/repository.py-tpl index 4423ac4..1584088 100644 --- a/src/fastapi_fastkit/fastapi_project_template/modules/domain/repository.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/modules/domain/repository.py-tpl @@ -3,40 +3,64 @@ # # Data is stored in memory, lost on restart, and not shared between workers. # -------------------------------------------------------------------------- - -from threading import Lock +import dataclasses +import threading +from typing import Any from .models import class Repository: - """In-memory storage for .""" + """Thread-safe in-memory storage for records.""" def __init__(self) -> None: self._data: dict[int, ] = {} self._next_id = 1 - self._lock = Lock() + self._lock = threading.Lock() - def list_all(self) -> list[]: + def list_page( + self, + offset: int, + limit: int, + ) -> tuple[list[], int]: + """One page ordered by id, and the total number of records.""" with self._lock: - return list(self._data.values()) + ids = sorted(self._data)[offset : offset + limit] + return [self._data[entity_id] for entity_id in ids], len(self._data) def get(self, entity_id: int) -> | None: with self._lock: return self._data.get(entity_id) - def add(self, name: str) -> : + def add(self, values: dict[str, Any]) -> : with self._lock: - entity = (id=self._next_id, name=name) + entity = (id=self._next_id, **values) self._data[entity.id] = entity self._next_id += 1 return entity - def replace(self, entity_id: int, name: str) -> | None: + def replace( + self, + entity_id: int, + values: dict[str, Any], + ) -> | None: with self._lock: if entity_id not in self._data: return None - entity = (id=entity_id, name=name) + entity = (id=entity_id, **values) + self._data[entity_id] = entity + return entity + + def update( + self, + entity_id: int, + changes: dict[str, Any], + ) -> | None: + with self._lock: + current = self._data.get(entity_id) + if current is None: + return None + entity = dataclasses.replace(current, **changes) self._data[entity_id] = entity return entity diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/domain/router.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/domain/router.py-tpl index e6a5f52..8e98184 100644 --- a/src/fastapi_fastkit/fastapi_project_template/modules/domain/router.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/modules/domain/router.py-tpl @@ -1,66 +1,136 @@ # -------------------------------------------------------------------------- # API routes. # -------------------------------------------------------------------------- +from typing import Annotated -from fastapi import APIRouter, Depends, HTTPException, Response, status -from .schemas import Create, Read -from .service import NotFoundError, Service +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status -router = APIRouter() +from import DEFAULT_LIMIT, LimitParam, OffsetParam, Page +from import error_responses +from .schemas import ( + Create, + Read, + Update, +) +from .service import ( + NotFoundError, + Service, +) +router = APIRouter(prefix="/", tags=[""]) -def get__service() -> Service: +NOT_FOUND = " not found" + + +def get__service() -> Service: return Service() -@router.get("", response_model=list[Read]) +ServiceDep = Annotated[ + Service, + Depends(get__service), +] + + +def not_found() -> HTTPException: + return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=NOT_FOUND) + + +@router.get("", response_model=Page[Read]) def list_( - service: Service = Depends(get__service), -) -> list[Read]: - return [Read.model_validate(entity) for entity in service.list_()] + service: ServiceDep, + limit: LimitParam = DEFAULT_LIMIT, + offset: OffsetParam = 0, +) -> Page[Read]: + """List records ordered by id, one page at a time.""" + entities, total = service.list_page(offset=offset, limit=limit) + return Page[Read]( + items=[Read.model_validate(entity) for entity in entities], + total=total, + limit=limit, + offset=offset, + ) + +@router.post( + "", + response_model=Read, + status_code=status.HTTP_201_CREATED, +) +def create_( + payload: Create, + request: Request, + response: Response, + service: ServiceDep, +) -> Read: + """Create a record; the Location header points at it.""" + entity = service.create(payload) + location = request.url_for("get_", _id=entity.id) + response.headers["Location"] = str(location) + return Read.model_validate(entity) -@router.get("/{entity_id}", response_model=Read) -def get_( - entity_id: int, service: Service = Depends(get__service) + +@router.get( + "/{_id}", + response_model=Read, + responses=error_responses(status.HTTP_404_NOT_FOUND), +) +def get_( + _id: int, + service: ServiceDep, ) -> Read: try: - return Read.model_validate(service.get_(entity_id)) + return Read.model_validate(service.get(_id)) except NotFoundError as exc: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail=str(exc) - ) from exc + raise not_found() from exc -@router.post("", response_model=Read, status_code=status.HTTP_201_CREATED) -def create_( - payload: Create, service: Service = Depends(get__service) +@router.put( + "/{_id}", + response_model=Read, + responses=error_responses(status.HTTP_404_NOT_FOUND), +) +def replace_( + _id: int, + payload: Create, + service: ServiceDep, ) -> Read: - return Read.model_validate(service.create_(payload)) + """Replace every field (PUT): omitted optional fields are cleared.""" + try: + entity = service.replace(_id, payload) + except NotFoundError as exc: + raise not_found() from exc + return Read.model_validate(entity) -@router.put("/{entity_id}", response_model=Read) -def replace_( - entity_id: int, - payload: Create, - service: Service = Depends(get__service), +@router.patch( + "/{_id}", + response_model=Read, + responses=error_responses(status.HTTP_404_NOT_FOUND), +) +def update_( + _id: int, + payload: Update, + service: ServiceDep, ) -> Read: + """Change only the fields present in the body (PATCH).""" try: - return Read.model_validate(service.replace_(entity_id, payload)) + entity = service.update(_id, payload) except NotFoundError as exc: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail=str(exc) - ) from exc + raise not_found() from exc + return Read.model_validate(entity) -@router.delete("/{entity_id}", status_code=status.HTTP_204_NO_CONTENT) -def delete_( - entity_id: int, service: Service = Depends(get__service) -) -> Response: +@router.delete( + "/{_id}", + status_code=status.HTTP_204_NO_CONTENT, + responses=error_responses(status.HTTP_404_NOT_FOUND), +) +def delete_( + _id: int, + service: ServiceDep, +) -> None: try: - service.delete_(entity_id) + service.delete(_id) except NotFoundError as exc: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail=str(exc) - ) from exc - return Response(status_code=status.HTTP_204_NO_CONTENT) + raise not_found() from exc diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/domain/schemas.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/domain/schemas.py-tpl index 6b60964..7903e73 100644 --- a/src/fastapi_fastkit/fastapi_project_template/modules/domain/schemas.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/modules/domain/schemas.py-tpl @@ -1,16 +1,36 @@ # -------------------------------------------------------------------------- # API schemas. # -------------------------------------------------------------------------- - -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, field_validator class Create(BaseModel): + """Body of POST (create) and PUT (full replacement).""" + name: str = Field(min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=500) + + +class Update(BaseModel): + """Body of PATCH: omitted fields keep their current value.""" + + name: str | None = Field(default=None, min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=500) + + @field_validator("name") + @classmethod + def name_is_not_null(cls, value: str | None) -> str: + # ``name`` may be omitted but not set to null: it is required. + if value is None: + raise ValueError("name cannot be null") + return value class Read(BaseModel): - id: int - name: str + """Response body for one record.""" model_config = ConfigDict(from_attributes=True) + + id: int + name: str + description: str | None diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/domain/service.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/domain/service.py-tpl index bf849cf..be46e0b 100644 --- a/src/fastapi_fastkit/fastapi_project_template/modules/domain/service.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/modules/domain/service.py-tpl @@ -1,47 +1,73 @@ # -------------------------------------------------------------------------- # service. # -------------------------------------------------------------------------- - from .models import from .repository import Repository -from .schemas import Create +from .schemas import ( + Create, + Update, +) # Share the default repository between requests. _default_repository = Repository() def reset_store() -> None: + """Empty the shared store; the tests call it to isolate their state.""" _default_repository.reset() class NotFoundError(Exception): - """Raised when is not found.""" + """Raised when no record has the requested id.""" + + def __init__(self, entity_id: int) -> None: + super().__init__(f" {entity_id} not found") + self.entity_id = entity_id class Service: - """Business logic for .""" + """Business logic for records.""" def __init__(self, repository: Repository | None = None) -> None: - self._repository = repository if repository is not None else _default_repository + self._repository = repository or _default_repository - def list_(self) -> list[]: - return self._repository.list_all() + def list_page( + self, + offset: int, + limit: int, + ) -> tuple[list[], int]: + return self._repository.list_page(offset=offset, limit=limit) - def get_(self, entity_id: int) -> : + def get(self, entity_id: int) -> : entity = self._repository.get(entity_id) if entity is None: - raise NotFoundError(f" {entity_id} does not exist") + raise NotFoundError(entity_id) return entity - def create_(self, payload: Create) -> : - return self._repository.add(name=payload.name) + def create(self, payload: Create) -> : + return self._repository.add(payload.model_dump()) + + def replace( + self, + entity_id: int, + payload: Create, + ) -> : + entity = self._repository.replace(entity_id, payload.model_dump()) + if entity is None: + raise NotFoundError(entity_id) + return entity - def replace_(self, entity_id: int, payload: Create) -> : - entity = self._repository.replace(entity_id=entity_id, name=payload.name) + def update( + self, + entity_id: int, + payload: Update, + ) -> : + changes = payload.model_dump(exclude_unset=True) + entity = self._repository.update(entity_id, changes) if entity is None: - raise NotFoundError(f" {entity_id} does not exist") + raise NotFoundError(entity_id) return entity - def delete_(self, entity_id: int) -> None: - if not self._repository.delete(entity_id=entity_id): - raise NotFoundError(f" {entity_id} does not exist") + def delete(self, entity_id: int) -> None: + if not self._repository.delete(entity_id): + raise NotFoundError(entity_id) diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/schemas/__init__.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/schemas/__init__.py-tpl deleted file mode 100644 index e69de29..0000000 diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/schemas/new_route.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/schemas/new_route.py-tpl index 1c43bbc..ea654c9 100644 --- a/src/fastapi_fastkit/fastapi_project_template/modules/schemas/new_route.py-tpl +++ b/src/fastapi_fastkit/fastapi_project_template/modules/schemas/new_route.py-tpl @@ -1,23 +1,36 @@ # -------------------------------------------------------------------------- -# schema module +# API schemas # -------------------------------------------------------------------------- -from pydantic import BaseModel +from pydantic import BaseModel, ConfigDict, Field, field_validator -class Base(BaseModel): - """Add fields here""" - pass +class Create(BaseModel): + """Body of POST (create) and PUT (full replacement).""" + name: str = Field(min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=500) -class Response(Base): - """Add fields here""" - pass +class Update(BaseModel): + """Body of PATCH: omitted fields keep their current value.""" -"""Add other schemas here + name: str | None = Field(default=None, min_length=1, max_length=120) + description: str | None = Field(default=None, max_length=500) -For more information, please refer to the following link: + @field_validator("name") + @classmethod + def name_is_not_null(cls, value: str | None) -> str: + # ``name`` may be omitted but not set to null: it is required. + if value is None: + raise ValueError("name cannot be null") + return value -https://fastapi.tiangolo.com/tutorial/query-param-models/ -https://fastapi.tiangolo.com/tutorial/response-model/ -""" + +class Read(BaseModel): + """Response body for one record.""" + + model_config = ConfigDict(from_attributes=True) + + id: int + name: str + description: str | None diff --git a/src/fastapi_fastkit/fastapi_project_template/modules/tests/test_new_route.py-tpl b/src/fastapi_fastkit/fastapi_project_template/modules/tests/test_new_route.py-tpl new file mode 100644 index 0000000..c7b4f47 --- /dev/null +++ b/src/fastapi_fastkit/fastapi_project_template/modules/tests/test_new_route.py-tpl @@ -0,0 +1,132 @@ +# -------------------------------------------------------------------------- +# Tests for the API generated by ``fastkit addroute``. +# -------------------------------------------------------------------------- +from collections.abc import Iterator +from typing import Any + +import pytest +from fastapi.testclient import TestClient +from httpx import Response + + + +# The collection path including whatever prefix the app mounts it under. +COLLECTION = app.url_path_for("list_") + + +@pytest.fixture(autouse=True) +def isolated_store() -> Iterator[None]: + reset_store() + yield + reset_store() + + +@pytest.fixture +def client() -> TestClient: + return TestClient(app) + + +def data(response: Response) -> Any: + """The record or page a successful response carries.""" + return response.json() + + +def error_message(response: Response) -> Any: + """The text of an error response.""" + return response.json() + + +def create(client: TestClient, **fields: Any) -> dict[str, Any]: + response = client.post(COLLECTION, json={"name": "First", **fields}) + assert response.status_code == 201, response.text + body: dict[str, Any] = data(response) + return body + + +def test_create_returns_201_and_location(client: TestClient) -> None: + response = client.post(COLLECTION, json={"name": "First", "description": "One"}) + + assert response.status_code == 201 + body = data(response) + assert body == {"id": body["id"], "name": "First", "description": "One"} + location = response.headers["location"] + assert location.endswith(f"{COLLECTION}/{body['id']}") + assert data(client.get(location)) == body + + +@pytest.mark.parametrize( + "payload", [{}, {"name": ""}, {"name": "x" * 121}, {"name": None}] +) +def test_create_validates_the_body(client: TestClient, payload: dict[str, Any]) -> None: + assert client.post(COLLECTION, json=payload).status_code == 422 + + +def test_list_returns_a_page(client: TestClient) -> None: + ids = [create(client, name=f"Record {index}")["id"] for index in range(3)] + + response = client.get(COLLECTION, params={"limit": 2, "offset": 1}) + + assert response.status_code == 200 + page = data(response) + assert [item["id"] for item in page["items"]] == ids[1:] + assert (page["total"], page["limit"], page["offset"]) == (3, 2, 1) + + +def test_empty_list_uses_the_default_page(client: TestClient) -> None: + response = client.get(COLLECTION, follow_redirects=False) + + assert response.status_code == 200 + assert data(response) == {"items": [], "total": 0, "limit": 20, "offset": 0} + + +@pytest.mark.parametrize("params", [{"limit": 0}, {"limit": 101}, {"offset": -1}]) +def test_list_rejects_out_of_range_bounds( + client: TestClient, params: dict[str, int] +) -> None: + assert client.get(COLLECTION, params=params).status_code == 422 + + +def test_put_replaces_every_field(client: TestClient) -> None: + created = create(client, description="Old") + url = f"{COLLECTION}/{created['id']}" + + response = client.put(url, json={"name": "New"}) + + assert response.status_code == 200 + assert data(response) == {"id": created["id"], "name": "New", "description": None} + assert client.put(url, json={}).status_code == 422 + + +def test_patch_changes_only_the_given_fields(client: TestClient) -> None: + created = create(client, description="Old") + url = f"{COLLECTION}/{created['id']}" + + response = client.patch(url, json={"description": "New"}) + + assert response.status_code == 200 + assert data(response) == { + "id": created["id"], + "name": "First", + "description": "New", + } + assert client.patch(url, json={"name": None}).status_code == 422 + assert data(client.patch(url, json={"description": None}))["description"] is None + + +def test_delete_returns_204_then_404(client: TestClient) -> None: + url = f"{COLLECTION}/{create(client)['id']}" + + response = client.delete(url) + + assert response.status_code == 204 + assert response.content == b"" + assert client.get(url).status_code == 404 + assert client.delete(url).status_code == 404 + + +@pytest.mark.parametrize("method", ["GET", "PUT", "PATCH", "DELETE"]) +def test_unknown_id_returns_404(client: TestClient, method: str) -> None: + response = client.request(method, f"{COLLECTION}/999", json={"name": "Missing"}) + + assert response.status_code == 404 + assert error_message(response) == " not found" diff --git a/src/fastapi_fastkit/fragments/README.md b/src/fastapi_fastkit/fragments/README.md index deced0e..053b3ea 100644 --- a/src/fastapi_fastkit/fragments/README.md +++ b/src/fastapi_fastkit/fragments/README.md @@ -17,24 +17,40 @@ lines without leaking whitespace. header.j2 shared "Generated by FastAPI-fastkit" banner main.py.j2 application entry point skeleton main/imports/*.j2 import lines collected into main.py's import block -main/lifespan/*.j2 4-space-indented statements inside the lifespan handler +main/startup/*.j2 4-space-indented lifespan statements before `yield` +main/shutdown/*.j2 4-space-indented lifespan statements after `yield` main/setup/*.j2 top-level statements placed right after `app = FastAPI(...)` -db/*.py.j2 database configuration modules (sqlalchemy, mongodb, redis) -auth/*.py.j2 authentication modules (jwt, fastapi_users, oauth2, session) -auth/settings.j2 shared AuthSettings macro (SECRET_KEY + production guard) +core/config.py.j2 settings module for templates that ship none +db/*.py.j2 database modules (sqlalchemy, mongodb, redis); each owns a + route-less `lifespan_router` that opens / closes its client +auth/*.py.j2 the generated auth package: JWT and Session share models, + schemas, repository (SQL / MongoDB / in-memory), service, + dependencies and router; OAuth2 has oauth2_router.py.j2; + session cookie setup in middleware.py.j2 +auth/fastapi_users/*.j2 FastAPI-Users package (SQLAlchemy backend, SQL databases only) tasks/*.py.j2 background worker modules (celery, dramatiq) -features/*.py.j2 routers main.py mounts (tasks, cache, websocket, pagination) -logging/*.py.j2 structured logging + request-id middleware +features/*.py.j2 routers main.py mounts (tasks, cache, websocket, readiness) +middleware/*.py.j2 rate limiting +monitoring/*.py.j2 OpenTelemetry tracing setup +logging/*.py.j2 structured logging + request-id middleware, Loguru setup migrations/*.j2 alembic.ini, async alembic/env.py, baseline revision, migrate.sh -tooling/*.j2 ruff / pre-commit / GitHub Actions / devcontainer / Makefile -docker/*.j2 Dockerfile / docker-compose.yml -test/*.j2 pytest config and factory-boy fixtures +tooling/*.j2 ruff / pre-commit / GitHub Actions / devcontainer / Makefile, + mypy overrides for untyped generated imports +docker/*.j2 Dockerfile / .dockerignore / docker-compose.yml +test/*.j2 pytest config, the root conftest.py (in-memory SQLite, no + OTLP export, rate-limit reset), per-feature tests and + factory-boy fixtures ``` +`core/pagination.py` and `core/responses.py` are not fragments: when the base +template lacks them, the generator copies the canonical files from +`fastapi_project_template/modules/core/`, the same files `fastkit addroute` +writes. + `main.py.j2` never hard-codes a feature. Import fragments are rendered, deduplicated and sorted into isort-style blocks by `DynamicConfigGenerator._build_import_groups()`, then handed to the template as -`import_groups`; `lifespan_fragments` and `setup_fragments` are `{% include %}`d +`import_groups`; `startup_fragments`, `shutdown_fragments` and `setup_fragments` are `{% include %}`d in order. Features therefore compose freely. ### Render context @@ -47,11 +63,33 @@ project it is being generated into, so a fragment never hard-codes `src`: | `pkg` | `src`, `src.app` | dotted import path of the app package | | `package_dir` | `src`, `src/app` | the same as a filesystem path | | `db_module` | `src.config.database`| generated database module | -| `auth_module` | `src.config.auth` | generated auth module | +| `auth_module` | `src.auth`, `src.app.domains.auth` | generated auth package | +| `main_module` | `src.main` | dotted path of the entrypoint | +| `auth_kind` | `jwt`, `session`, `oauth2`, `fastapi_users` | selected auth option | +| `backend` | `sql`, `mongo`, `memory` | where the auth package stores accounts | +| `id_type` | `int`, `str` | account id type (`str` for MongoDB) | +| `create_tables`| `True` | auth router creates `users` on startup (SQL without Alembic) | +| `rate_limit` | `True` | Rate-Limiting is selected | +| `settings_module` | `src.core.config` | project settings module (`settings`) | | `app_module` | `src.main:app` | uvicorn entrypoint | | `project_name` | `My API` | raw project name (use `| tojson`) | | `project_slug` | `my-api` | lowercase, hyphenated identifier | +Fragments call `format_imports([...])` (a Jinja global) for import sections +whose module paths depend on the layout: it sorts, merges and wraps the +`from x import y` lines so the output passes `ruff check` / `ruff format`. + +The `SECRET_KEY` rule (set explicitly, not a known example, at least 32 bytes) +applies to every `ENVIRONMENT` except `development`, so `staging` and +`production` both refuse to start without a strong key; in `development` a +known example only warns. It lives in every template's `_check_secret_key` +validator and in `core/config.py.j2`. When an auth option is selected, +`config_generator.auth_guard_lines()` adds `_check_auth_settings_for_production` +to the project's `Settings` class for what that validator does not cover: the +`ENABLE_DEMO_USERS` refusal, and the `SECRET_KEY` rule itself only when the +class has no such validator. Both render the example keys from +`PUBLIC_EXAMPLE_SECRET_KEYS`. + ## Adding a new feature 1. **Catalog.** Add the choice to `FastkitConfig.PACKAGE_CATALOG` in @@ -65,7 +103,7 @@ project it is being generated into, so a fragment never hard-codes `src`: `backend/interactive/__init__.py` and add a summary row in `selectors.confirm_selections()`. 3. **Fragments.** Drop the pieces you need into `main/imports/`, - `main/lifespan/` and/or `main/setup/`. Lifespan fragments are indented by + `main/startup/`, `main/shutdown/` and/or `main/setup/`. Lifespan fragments are indented by 4 spaces; the other two are not. Anything that adds middleware, routes or instrumentation (`add_middleware`, `include_router`, `mount`, `Instrumentator().instrument(app)`) belongs in `main/setup/`: Starlette @@ -84,10 +122,28 @@ project it is being generated into, so a fragment never hard-codes `src`: asserts each `.py` file parses with `ast.parse`; `TestFeatureModuleGeneration` pins the individual feature to the code it promises. +## Settings + +Generated code never reads `os.environ`: every value comes from the project's +settings module (`from {{ settings_module }} import settings`), which reads +the environment and `.env`. A feature that needs a new value adds a +`SettingGroup` to `DynamicConfigGenerator.settings_groups()`. The generator +adds the missing fields to the template's `Settings` class (below a +`# fastkit:settings` comment when the class has one, else after its last +field), or renders `core/config.py.j2` when the template ships no settings +module, and documents each field in `.env.example`. + ## Rules - Keep the `# fastkit:imports` / `# fastkit:routes` anchors in `main.py.j2`: `fastkit addroute` relies on them. +- Feature routers carry only their resource prefix (`/tasks`); `main.py` + mounts them with `prefix=settings.API_V1_PREFIX`. Probes, `/metrics` and the + WebSocket endpoint stay at the root. +- Presets that keep the template's `main.py` get features through + `OVERLAY_TARGETS` in `preset_layout.py`: one import plus single-line, + module-level statements below `# fastkit:routes`. Prefer a router (which can + carry its own `lifespan=`) or a `setup_*(app)` helper over multi-line code. - Anything a fragment mounts (`app.include_router(x_router)`) must have a matching module in `generate_feature_modules()`. The matrix test fails otherwise — that check exists because the catalog used to offer selections diff --git a/src/fastapi_fastkit/fragments/auth/dependencies.py.j2 b/src/fastapi_fastkit/fragments/auth/dependencies.py.j2 new file mode 100644 index 0000000..4b1ee83 --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/dependencies.py.j2 @@ -0,0 +1,194 @@ +{% include "header.j2" %} +{% if auth_kind == "jwt" %} +"""Authentication dependencies: the bearer scheme and the current user. + +``OAuth2PasswordBearer`` points Swagger UI's *Authorize* button at +``POST {API_V1_PREFIX}/auth/token``. Use :data:`CurrentUser` in any route that +needs a signed-in, active account:: + + @router.get("/orders") + async def list_orders(current_user: CurrentUser) -> ... +""" +{% else %} +"""Authentication dependencies: the account stored in the session cookie. + +Use :data:`CurrentUser` in any route that needs a signed-in, active account:: + + @router.get("/orders") + async def list_orders(current_user: CurrentUser) -> ... + +The cookie is signed, client-side state: it holds the account id, the +account's ``session_version`` at login and the login time. A session is +accepted only while + +* the version still matches the account (logout increments it, which ends + every session of that account, on every device), and +* it is younger than ``SESSION_ABSOLUTE_MAX_AGE``, however active it was + (``SESSION_MAX_AGE`` is the idle timeout of the cookie itself). + +Cookie sessions have no standard HTTP authentication scheme. A missing or +stale session still answers ``401`` (not ``403``, which means "signed in but +not allowed"), with ``WWW-Authenticate: Cookie`` naming the mechanism, since +every 401 response must carry that header (RFC 9110, section 15.5.2). +""" +{% endif %} + +{% if auth_kind == "session" %} +import time +{% endif %} +from typing import Annotated + +from fastapi import Depends, HTTPException, {% if auth_kind == "session" %}Request, {% endif %}status +{% if auth_kind == "jwt" %} +from fastapi.security import OAuth2PasswordBearer +{% endif %} + +{% set first_party = [ + "from " ~ auth_module ~ ".models import User", + "from " ~ auth_module ~ ".service import UserService", +] %} +{% if backend == "sql" %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".repository import UserRepository", + "from " ~ db_module ~ " import SessionDep", +] %} +{% elif backend == "mongo" %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".repository import UserRepository", + "from " ~ db_module ~ " import MongoDatabaseDep", +] %} +{% else %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".repository import UserRepository, user_store", +] %} +{% endif %} +{% if auth_kind == "jwt" %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".security import TokenError, decode_access_token", + "from " ~ settings_module ~ " import settings", +] %} +{% else %} +{% set first_party = first_party + ["from " ~ settings_module ~ " import settings"] %} +{% endif %} +{{ format_imports(first_party) }} +{% if backend == "sql" %} + + +def get_user_repository(session: SessionDep) -> UserRepository: + return UserRepository(session) +{% elif backend == "mongo" %} + + +def get_user_repository(database: MongoDatabaseDep) -> UserRepository: + return UserRepository(database) +{% else %} + + +def get_user_repository() -> UserRepository: + """The process-wide in-memory store (tests override this dependency).""" + return user_store +{% endif %} + + +UserRepositoryDep = Annotated[UserRepository, Depends(get_user_repository)] + + +def get_user_service(users: UserRepositoryDep) -> UserService: + return UserService(users) + + +UserServiceDep = Annotated[UserService, Depends(get_user_service)] +{% if auth_kind == "jwt" %} + +oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_PREFIX}/auth/token") + +TokenDep = Annotated[str, Depends(oauth2_scheme)] + + +def credentials_error() -> HTTPException: + """A fresh 401 for a missing, invalid or expired access token.""" + return HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + + +async def get_current_user(token: TokenDep, users: UserRepositoryDep) -> User: + """Resolve the bearer token into a live, active account.""" + try: + user_id = decode_access_token(token) + except TokenError as exc: + raise credentials_error() from exc + user = await users.get(user_id) + if user is None: + raise credentials_error() + if not user.is_active: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user" + ) + return user +{% else %} + +#: Session keys: the signed-in account id, its session version at login and +#: the login time (Unix seconds). +SESSION_USER_KEY = "user_id" +SESSION_VERSION_KEY = "session_version" +SESSION_ISSUED_AT_KEY = "issued_at" + + +def session_clock() -> float: + """The current time in Unix seconds (tests replace it to move time).""" + return time.time() + + +def not_authenticated(detail: str = "Not authenticated") -> HTTPException: + """A fresh 401 for a missing session or rejected credentials.""" + return HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail=detail, + headers={"WWW-Authenticate": "Cookie"}, + ) + + +def start_session(request: Request, user: User) -> None: + """Replace the session with a fresh one for ``user``. + + Whatever the cookie held before is dropped; the new one records the + account's current session version and the login time. + """ + request.session.clear() + request.session[SESSION_USER_KEY] = str(user.id) + request.session[SESSION_VERSION_KEY] = user.session_version + request.session[SESSION_ISSUED_AT_KEY] = int(session_clock()) + + +async def get_current_user(request: Request, users: UserRepositoryDep) -> User: + """Resolve the session cookie into a live, active account.""" + user_id = request.session.get(SESSION_USER_KEY) + version = request.session.get(SESSION_VERSION_KEY) + issued_at = request.session.get(SESSION_ISSUED_AT_KEY) + if ( + not isinstance(user_id, str) + or not isinstance(version, int) + or not isinstance(issued_at, int) + ): + request.session.clear() + raise not_authenticated() + if session_clock() - issued_at > settings.SESSION_ABSOLUTE_MAX_AGE: + request.session.clear() + raise not_authenticated("Session expired") + user = await users.get(user_id) + if user is None or user.session_version != version: + # The account is gone, or the session was ended by a logout. + request.session.clear() + raise not_authenticated() + if not user.is_active: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user" + ) + return user +{% endif %} + + +CurrentUser = Annotated[User, Depends(get_current_user)] diff --git a/src/fastapi_fastkit/fragments/auth/fastapi_users.py.j2 b/src/fastapi_fastkit/fragments/auth/fastapi_users.py.j2 deleted file mode 100644 index 0ce688d..0000000 --- a/src/fastapi_fastkit/fragments/auth/fastapi_users.py.j2 +++ /dev/null @@ -1,8 +0,0 @@ -{% include "header.j2" %} -# -# For full setup guide, visit: -# https://fastapi-users.github.io/fastapi-users/ -# -# TODO: Implement FastAPI-Users setup -# This requires database models, user manager, and auth backends -# See the official documentation for complete setup diff --git a/src/fastapi_fastkit/fragments/auth/fastapi_users/models.py.j2 b/src/fastapi_fastkit/fragments/auth/fastapi_users/models.py.j2 new file mode 100644 index 0000000..1e114e5 --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/fastapi_users/models.py.j2 @@ -0,0 +1,15 @@ +{% include "header.j2" %} +"""The FastAPI-Users ``User`` table (``users``), keyed by UUID.""" + +from fastapi_users_db_sqlalchemy import SQLAlchemyBaseUserTableUUID + +from {{ db_module }} import Base + + +class User(SQLAlchemyBaseUserTableUUID, Base): + """email, hashed_password, is_active, is_superuser, is_verified and id. + + Add your own columns here (and to the schemas in ``schemas.py``). + """ + + __tablename__ = "users" diff --git a/src/fastapi_fastkit/fragments/auth/fastapi_users/router.py.j2 b/src/fastapi_fastkit/fragments/auth/fastapi_users/router.py.j2 new file mode 100644 index 0000000..3084968 --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/fastapi_users/router.py.j2 @@ -0,0 +1,108 @@ +{% include "header.j2" %} +"""The FastAPI-Users routers, mounted under ``settings.API_V1_PREFIX``. + +``POST /auth/jwt/login`` (form: ``username`` = email, ``password``), +``POST /auth/jwt/logout``, ``POST /auth/register`` and ``/users/me`` (plus +the superuser-only ``/users/{id}`` routes). Status codes follow the library: +bad credentials and an already registered email (also when two requests +race for it) answer ``400`` with an error code in ``detail``; a missing +token or an inactive account answers ``401``. + +Where the library differs from the conventions the rest of the project +follows: + +* its ``401`` responses carry no ``WWW-Authenticate`` header; +* ``POST /auth/register`` answers ``201`` without a ``Location`` header; +* the login response has no ``Cache-Control: no-store`` header. +""" + +{% if create_tables %} +import logging +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +{% endif %} +from fastapi import APIRouter{% if rate_limit %}, Depends{% endif %}{% if create_tables %}, FastAPI{% endif %} + +{% if create_tables %} +from sqlalchemy.exc import SQLAlchemyError +{% endif %} + +{% set first_party = [ + "from " ~ auth_module ~ ".schemas import UserCreate, UserRead, UserUpdate", + "from " ~ auth_module ~ ".users import auth_backend, fastapi_users", +] %} +{% if create_tables %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".models import User", + "from " ~ db_module ~ " import Base, engine", +] %} +{% endif %} +{% if rate_limit %} +{% set first_party = first_party + [ + "from " ~ pkg ~ ".rate_limiting import RateLimit", + "from " ~ settings_module ~ " import settings", +] %} +{% endif %} +{{ format_imports(first_party) }} +{% if create_tables %} + +logger = logging.getLogger(__name__) + + +async def create_user_table() -> None: + """Create the ``users`` table if it does not exist yet. + + The project has no migration tool, so the table is created on startup. + Existing tables and rows are never touched. Once you add Alembic, remove + this and create the table in a revision instead. + """ + async with engine.begin() as connection: + await connection.run_sync( + Base.metadata.create_all, + tables=[Base.metadata.tables[User.__tablename__]], + checkfirst=True, + ) + + +@asynccontextmanager +async def lifespan(_app: FastAPI) -> AsyncIterator[None]: + """Create the users table on startup; an unreachable database is logged. + + The app still starts without its database (``GET /ready`` reports it), + and the table is created on the next start. + """ + try: + await create_user_table() + except (OSError, SQLAlchemyError): + logger.warning("Could not create the users table", exc_info=True) + yield +{% endif %} + +{% if create_tables %} + +{% endif %} +router = APIRouter({% if create_tables %}lifespan=lifespan{% endif %}) +router.include_router( + fastapi_users.get_auth_router(auth_backend), + prefix="/auth/jwt", + tags=["auth"], +{% if rate_limit %} + # Stricter budget for the credential check (RATE_LIMIT_AUTH per client). + dependencies=[Depends(RateLimit(settings.RATE_LIMIT_AUTH))], +{% endif %} +) +router.include_router( + fastapi_users.get_register_router(UserRead, UserCreate), + prefix="/auth", + tags=["auth"], +{% if rate_limit %} + # Registration hashes a password too (argon2, 64 MiB): same budget. + dependencies=[Depends(RateLimit(settings.RATE_LIMIT_AUTH))], +{% endif %} +) +router.include_router( + fastapi_users.get_users_router(UserRead, UserUpdate), + prefix="/users", + tags=["users"], +) diff --git a/src/fastapi_fastkit/fragments/auth/fastapi_users/schemas.py.j2 b/src/fastapi_fastkit/fragments/auth/fastapi_users/schemas.py.j2 new file mode 100644 index 0000000..d9f6f7e --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/fastapi_users/schemas.py.j2 @@ -0,0 +1,23 @@ +{% include "header.j2" %} +"""Request and response bodies of the FastAPI-Users routers.""" + +import uuid + +from fastapi_users import schemas +from pydantic import Field + + +class UserRead(schemas.BaseUser[uuid.UUID]): + """Public profile; never carries the password hash.""" + + +class UserCreate(schemas.BaseUserCreate): + """Registration body (``is_superuser`` and friends are ignored on register).""" + + password: str = Field(min_length=8, max_length=128) + + +class UserUpdate(schemas.BaseUserUpdate): + """PATCH body of ``/users/me``: only the fields sent are changed.""" + + password: str | None = Field(default=None, min_length=8, max_length=128) diff --git a/src/fastapi_fastkit/fragments/auth/fastapi_users/users.py.j2 b/src/fastapi_fastkit/fragments/auth/fastapi_users/users.py.j2 new file mode 100644 index 0000000..06cc201 --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/fastapi_users/users.py.j2 @@ -0,0 +1,99 @@ +{% include "header.j2" %} +"""FastAPI-Users wiring: user database, user manager, JWT bearer backend. + +Every secret and lifetime comes from the project settings: tokens (and the +password-reset / verification tokens) are signed with ``SECRET_KEY`` and +access tokens expire after ``ACCESS_TOKEN_EXPIRE_MINUTES``. Use +:data:`CurrentUser` in any route that needs a signed-in, active account:: + + @router.get("/orders") + async def list_orders(current_user: CurrentUser) -> ... +""" + +import uuid +from collections.abc import AsyncIterator +from typing import Annotated, Any + +from fastapi import Depends +from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin +from fastapi_users.authentication import ( + AuthenticationBackend, + BearerTransport, + JWTStrategy, +) +from fastapi_users.exceptions import UserAlreadyExists +from fastapi_users_db_sqlalchemy import SQLAlchemyUserDatabase +from sqlalchemy.exc import IntegrityError + +{{ format_imports([ + "from " ~ auth_module ~ ".models import User", + "from " ~ db_module ~ " import SessionDep", + "from " ~ settings_module ~ " import settings", +]) }} + + +class UserDatabase(SQLAlchemyUserDatabase[User, uuid.UUID]): + """The library's user table adapter, safe under concurrent registration. + + ``UserManager.create`` checks for an existing email before inserting, but + two simultaneous registrations of one address both pass that check; the + unique index then rejects the second insert. That violation becomes the + library's :class:`UserAlreadyExists`, which the register route answers + with ``400 REGISTER_USER_ALREADY_EXISTS``, instead of a 500. + """ + + async def create(self, create_dict: dict[str, Any]) -> User: + try: + return await super().create(create_dict) + except IntegrityError as exc: + await self.session.rollback() + raise UserAlreadyExists() from exc + + +async def get_user_db(session: SessionDep) -> AsyncIterator[UserDatabase]: + """The user table adapter; it commits each change itself.""" + yield UserDatabase(session, User) + + +class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]): + """Account logic. Override the ``on_after_*`` hooks to send emails. + + The library hashes passwords (argon2) synchronously on the event loop, + so each process computes at most one hash at a time: registration and + login requests queue behind each other instead of allocating 64 MiB + per concurrent request. + """ + + reset_password_token_secret = settings.SECRET_KEY + verification_token_secret = settings.SECRET_KEY + + +async def get_user_manager( + user_db: Annotated[UserDatabase, Depends(get_user_db)], +) -> AsyncIterator[UserManager]: + yield UserManager(user_db) + + +# Swagger UI's Authorize button posts the login form here. +bearer_transport = BearerTransport(tokenUrl=f"{settings.API_V1_PREFIX}/auth/jwt/login") + + +def get_jwt_strategy() -> JWTStrategy[User, uuid.UUID]: + return JWTStrategy( + secret=settings.SECRET_KEY, + lifetime_seconds=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60, + ) + + +auth_backend = AuthenticationBackend( + name="jwt", + transport=bearer_transport, + get_strategy=get_jwt_strategy, +) + +fastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [auth_backend]) + +#: Dependency resolving the bearer token into an active account. +current_active_user = fastapi_users.current_user(active=True) + +CurrentUser = Annotated[User, Depends(current_active_user)] diff --git a/src/fastapi_fastkit/fragments/auth/jwt.py.j2 b/src/fastapi_fastkit/fragments/auth/jwt.py.j2 deleted file mode 100644 index 4db5170..0000000 --- a/src/fastapi_fastkit/fragments/auth/jwt.py.j2 +++ /dev/null @@ -1,40 +0,0 @@ -{% include "header.j2" %} -{% from "auth/settings.j2" import auth_settings_class %} -import secrets -from datetime import UTC, datetime, timedelta -from typing import Literal - -import jwt -from pwdlib import PasswordHash -from pydantic import model_validator -from pydantic_settings import BaseSettings, SettingsConfigDict - -{% call auth_settings_class("JWT access tokens") %} - ALGORITHM: str = "HS256" - ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 -{% endcall %} - -# Password hashing — argon2id, the recommended default for new applications. -password_hash = PasswordHash.recommended() - - -def verify_password(plain_password: str, hashed_password: str) -> bool: - """Verify a password against a hash.""" - return password_hash.verify(plain_password, hashed_password) - - -def get_password_hash(password: str) -> str: - """Hash a password.""" - return password_hash.hash(password) - - -def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str: - """Create JWT access token.""" - to_encode = data.copy() - expire = datetime.now(UTC) + ( - expires_delta or timedelta(minutes=auth_settings.ACCESS_TOKEN_EXPIRE_MINUTES) - ) - to_encode.update({"exp": expire}) - return jwt.encode( - to_encode, auth_settings.SECRET_KEY, algorithm=auth_settings.ALGORITHM - ) diff --git a/src/fastapi_fastkit/fragments/auth/middleware.py.j2 b/src/fastapi_fastkit/fragments/auth/middleware.py.j2 new file mode 100644 index 0000000..48449a4 --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/middleware.py.j2 @@ -0,0 +1,29 @@ +{% include "header.j2" %} +"""The signed session cookie {% if auth_kind == "oauth2" %}(it carries the OAuth state and the signed-in profile){% else %}(it carries the signed-in account id){% endif %}. + +The cookie is signed with ``SECRET_KEY`` (it is client-side state, not a +server-side session id) and expires ``SESSION_MAX_AGE`` seconds after the +last response that renewed it: an idle timeout. ``SESSION_ABSOLUTE_MAX_AGE`` +bounds a session however active it is (checked by the code that reads the +session). The cookie is sent over HTTPS only (``Secure``) unless +``ENVIRONMENT=development`` (or always, with ``SESSION_HTTPS_ONLY=true``), +never readable from JavaScript, and ``SameSite=Lax`` keeps other sites from +sending it with their POST requests while still allowing the top-level +redirect back from an OAuth provider. +""" + +from fastapi import FastAPI +from starlette.middleware.sessions import SessionMiddleware + +from {{ settings_module }} import settings + + +def add_session_middleware(app: FastAPI) -> None: + """Install the session middleware on ``app`` (call it before CORS).""" + app.add_middleware( + SessionMiddleware, + secret_key=settings.SECRET_KEY, + max_age=settings.SESSION_MAX_AGE, + same_site="lax", + https_only=settings.SESSION_HTTPS_ONLY or settings.ENVIRONMENT != "development", + ) diff --git a/src/fastapi_fastkit/fragments/auth/models.py.j2 b/src/fastapi_fastkit/fragments/auth/models.py.j2 new file mode 100644 index 0000000..e72bddb --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/models.py.j2 @@ -0,0 +1,46 @@ +{% include "header.j2" %} +{% if backend == "sql" %} +"""The ``User`` entity: one row of the ``users`` table.""" + +from sqlalchemy import String, true +from sqlalchemy.orm import Mapped, mapped_column + +from {{ db_module }} import Base + + +class User(Base): + """A registered account. The password is only stored as an argon2 hash.""" + + __tablename__ = "users" + + id: Mapped[int] = mapped_column(primary_key=True) + email: Mapped[str] = mapped_column(String(320), unique=True, index=True) + full_name: Mapped[str | None] = mapped_column(String(255)) + hashed_password: Mapped[str] = mapped_column(String(255)) + is_active: Mapped[bool] = mapped_column(default=True, server_default=true()) +{% if auth_kind == "session" %} + #: Stored in every session cookie at login and compared on each request; + #: logout increments it, which ends every session issued before. + session_version: Mapped[int] = mapped_column(default=0, server_default="0") +{% endif %} +{% else %} +"""The ``User`` entity{% if backend == "mongo" %} (one document of the ``users`` collection){% endif %}.""" + +from dataclasses import dataclass + + +@dataclass +class User: + """A registered account. The password is only stored as an argon2 hash.""" + + id: {{ id_type }} + email: str + hashed_password: str + full_name: str | None = None + is_active: bool = True +{% if auth_kind == "session" %} + #: Stored in every session cookie at login and compared on each request; + #: logout increments it, which ends every session issued before. + session_version: int = 0 +{% endif %} +{% endif %} diff --git a/src/fastapi_fastkit/fragments/auth/oauth2.py.j2 b/src/fastapi_fastkit/fragments/auth/oauth2.py.j2 deleted file mode 100644 index bd658ca..0000000 --- a/src/fastapi_fastkit/fragments/auth/oauth2.py.j2 +++ /dev/null @@ -1,115 +0,0 @@ -{% include "header.j2" %} -{% from "auth/settings.j2" import auth_settings_class %} -"""OAuth2 social login (Google / GitHub) built on Authlib. - -Wire it up by mounting :data:`router` and adding ``SessionMiddleware`` — both -are done for you in the generated ``main.py``. - -Set the following variables (environment or ``.env``) before using a -provider: - - GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET - GITHUB_CLIENT_ID / GITHUB_CLIENT_SECRET - -The session cookie that carries the OAuth state is signed with ``SECRET_KEY``. -""" - -import secrets -from typing import Any, Literal - -from authlib.integrations.starlette_client import OAuth, OAuthError -from fastapi import APIRouter, HTTPException, Request, status -from pydantic import model_validator -from pydantic_settings import BaseSettings, SettingsConfigDict -from starlette.responses import RedirectResponse - -{% call auth_settings_class("the session cookie that stores the OAuth state") %} - GOOGLE_CLIENT_ID: str = "" - GOOGLE_CLIENT_SECRET: str = "" - GITHUB_CLIENT_ID: str = "" - GITHUB_CLIENT_SECRET: str = "" -{% endcall %} - -oauth = OAuth() - -oauth.register( - name="google", - client_id=auth_settings.GOOGLE_CLIENT_ID, - client_secret=auth_settings.GOOGLE_CLIENT_SECRET, - server_metadata_url="https://accounts.google.com/.well-known/openid-configuration", - client_kwargs={"scope": "openid email profile"}, -) - -oauth.register( - name="github", - client_id=auth_settings.GITHUB_CLIENT_ID, - client_secret=auth_settings.GITHUB_CLIENT_SECRET, - access_token_url="https://github.com/login/oauth/access_token", - authorize_url="https://github.com/login/oauth/authorize", - api_base_url="https://api.github.com/", - client_kwargs={"scope": "user:email"}, -) - -SUPPORTED_PROVIDERS = ("google", "github") - -router = APIRouter(prefix="/auth", tags=["Authentication"]) - - -def _client(provider: str) -> Any: - """Return the registered Authlib client, 404-ing on unknown providers.""" - if provider not in SUPPORTED_PROVIDERS: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Unsupported OAuth provider: {provider}", - ) - return oauth.create_client(provider) - - -@router.get("/login/{provider}") -async def login(provider: str, request: Request) -> RedirectResponse: - """Kick off the authorization-code flow for ``provider``.""" - client = _client(provider) - redirect_uri = request.url_for("auth_callback", provider=provider) - redirected: RedirectResponse = await client.authorize_redirect( - request, str(redirect_uri) - ) - return redirected - - -@router.get("/callback/{provider}", name="auth_callback") -async def auth_callback(provider: str, request: Request) -> dict[str, Any]: - """Exchange the callback code for a token and stash the user in session.""" - client = _client(provider) - try: - token = await client.authorize_access_token(request) - except OAuthError as exc: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, detail=str(exc) - ) from exc - - if provider == "google": - user_info = token.get("userinfo") or {} - else: - response = await client.get("user", token=token) - user_info = response.json() - - request.session["user"] = dict(user_info) - return {"provider": provider, "user": user_info} - - -@router.get("/me") -async def current_user(request: Request) -> dict[str, Any]: - """Return the user stored in the session cookie.""" - user = request.session.get("user") - if not user: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated" - ) - return {"user": user} - - -@router.post("/logout") -async def logout(request: Request) -> dict[str, str]: - """Drop the session cookie contents.""" - request.session.pop("user", None) - return {"status": "logged out"} diff --git a/src/fastapi_fastkit/fragments/auth/oauth2_router.py.j2 b/src/fastapi_fastkit/fragments/auth/oauth2_router.py.j2 new file mode 100644 index 0000000..57f8d0f --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/oauth2_router.py.j2 @@ -0,0 +1,236 @@ +{% include "header.j2" %} +"""OAuth2 social login (Google, GitHub) on Authlib, kept in the session cookie. + +Authlib generates the ``state`` parameter, keeps it in the session cookie and +rejects a callback whose state does not match (CSRF protection of the +authorization-code flow). Provider errors (an Authlib error, a network or +HTTP error of the ``httpx2`` client Authlib talks to the provider with, a +malformed provider answer) are logged; clients only get a generic ``401``. + +A provider is available once its credentials are set (environment or +``.env``): ``GOOGLE_CLIENT_ID`` / ``GOOGLE_CLIENT_SECRET``, +``GITHUB_CLIENT_ID`` / ``GITHUB_CLIENT_SECRET``. Register +``{API_V1_PREFIX}/auth/callback/`` as the +redirect URI at the provider. ``OAUTH_REDIRECT_BASE_URL`` is the public URL of +the API, so the redirect URI stays right behind a TLS-terminating proxy; only +with ``ENVIRONMENT=development`` may it be left empty, and the URL of the +incoming request is used instead. + +The profile lives in the signed session cookie (there is no account store), +so logout clears the cookie but cannot revoke a copy of it; every session +ends ``SESSION_ABSOLUTE_MAX_AGE`` seconds after the login. + +Cookie sessions have no standard HTTP authentication scheme; 401 responses +carry ``WWW-Authenticate: Cookie`` (every 401 must name a scheme, RFC 9110 +section 15.5.2). +""" + +import logging +import time +from typing import Annotated, Any + +import httpx2 +from authlib.common.errors import AuthlibBaseError +from authlib.integrations.starlette_client import OAuth, OAuthError +from fastapi import APIRouter, Depends, HTTPException, Request, status +from pydantic import BaseModel +from starlette.responses import RedirectResponse + +{{ format_imports([ + "from " ~ pkg ~ ".core.responses import error_responses", + "from " ~ settings_module ~ " import settings", +]) }} + +logger = logging.getLogger(__name__) + +#: Session keys: the signed-in profile and the login time (Unix seconds). +SESSION_USER_KEY = "user" +SESSION_ISSUED_AT_KEY = "issued_at" + +#: What a failed exchange with the provider raises: Authlib's own errors +#: (``OAuthError``, a mismatched ``state``, ...), the network and HTTP errors +#: of ``httpx2`` (the client Authlib uses), and ``ValueError`` for a +#: response that is not the JSON the provider documents. +PROVIDER_ERRORS = (AuthlibBaseError, httpx2.HTTPError, ValueError) + +#: Authlib client settings per provider; credentials come from the settings. +PROVIDERS: dict[str, dict[str, Any]] = { + "google": { + "server_metadata_url": ( + "https://accounts.google.com/.well-known/openid-configuration" + ), + "client_kwargs": {"scope": "openid email profile"}, + }, + "github": { + "access_token_url": "https://github.com/login/oauth/access_token", + "authorize_url": "https://github.com/login/oauth/authorize", + "api_base_url": "https://api.github.com/", + "client_kwargs": {"scope": "read:user user:email"}, + }, +} + +oauth = OAuth() + + +class OAuthUser(BaseModel): + """The profile kept in the session after a successful login.""" + + provider: str + subject: str + email: str | None = None + name: str | None = None + + +def _credentials(provider: str) -> tuple[str, str]: + credentials = { + "google": (settings.GOOGLE_CLIENT_ID, settings.GOOGLE_CLIENT_SECRET), + "github": (settings.GITHUB_CLIENT_ID, settings.GITHUB_CLIENT_SECRET), + } + return credentials[provider] + + +def session_clock() -> float: + """The current time in Unix seconds (tests replace it to move time).""" + return time.time() + + +def provider_not_found() -> HTTPException: + return HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail="OAuth provider not found" + ) + + +def get_oauth_client(provider: str) -> Any: + """The Authlib client of a configured provider; 404 for any other name.""" + if provider not in PROVIDERS or not all(_credentials(provider)): + raise provider_not_found() + client = oauth.create_client(provider) + if client is None: + client_id, client_secret = _credentials(provider) + client = oauth.register( + provider, + client_id=client_id, + client_secret=client_secret, + **PROVIDERS[provider], + ) + return client + + +def not_authenticated(detail: str = "Not authenticated") -> HTTPException: + """A fresh 401 for a missing session or a failed login.""" + return HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail=detail, + headers={"WWW-Authenticate": "Cookie"}, + ) + + +def get_current_user(request: Request) -> OAuthUser: + """The profile stored in the session cookie, while the session is valid.""" + stored = request.session.get(SESSION_USER_KEY) + issued_at = request.session.get(SESSION_ISSUED_AT_KEY) + if not isinstance(stored, dict) or not isinstance(issued_at, int): + raise not_authenticated() + if session_clock() - issued_at > settings.SESSION_ABSOLUTE_MAX_AGE: + request.session.clear() + raise not_authenticated("Session expired") + return OAuthUser.model_validate(stored) + + +def callback_url(request: Request, provider: str) -> str: + """The redirect URI sent to the provider. + + Built from ``OAUTH_REDIRECT_BASE_URL``; the URL of the incoming request + (its ``Host`` header and scheme) is trusted only in development, since + behind a proxy it names the proxy hop, not the public address. + """ + path = request.app.url_path_for("oauth_callback", provider=provider) + base = settings.OAUTH_REDIRECT_BASE_URL.strip().rstrip("/") + if base: + return f"{base}{path}" + if settings.ENVIRONMENT == "development": + return str(request.url_for("oauth_callback", provider=provider)) + logger.error( + "OAuth login with %s refused: set OAUTH_REDIRECT_BASE_URL to the public " + "URL of the API (required unless ENVIRONMENT=development).", + provider, + ) + raise provider_not_found() + + +CurrentUser = Annotated[OAuthUser, Depends(get_current_user)] + +auth_router = APIRouter(prefix="/auth", tags=["auth"]) +users_router = APIRouter(prefix="/users", tags=["users"]) + + +@auth_router.get( + "/login/{provider}", + response_class=RedirectResponse, + status_code=status.HTTP_302_FOUND, + responses=error_responses(404), +) +async def login(provider: str, request: Request) -> RedirectResponse: + """Redirect to the provider's consent page.""" + client = get_oauth_client(provider) + redirect: RedirectResponse = await client.authorize_redirect( + request, callback_url(request, provider) + ) + return redirect + + +async def _fetch_profile(provider: str, client: Any, request: Request) -> OAuthUser: + token = await client.authorize_access_token(request) + if provider == "google": + info = token.get("userinfo") or await client.userinfo(token=token) + else: + response = await client.get("user", token=token) + response.raise_for_status() + info = response.json() + subject = info.get("sub") or info.get("id") + if not subject: + raise OAuthError(description="the provider returned no user id") + return OAuthUser( + provider=provider, + subject=str(subject), + email=info.get("email"), + name=info.get("name") or info.get("login"), + ) + + +@auth_router.get( + "/callback/{provider}", + name="oauth_callback", + responses=error_responses(401, 404), +) +async def oauth_callback(provider: str, request: Request) -> OAuthUser: + """Exchange the authorization code and keep the profile in the session.""" + client = get_oauth_client(provider) + try: + user = await _fetch_profile(provider, client, request) + except PROVIDER_ERRORS as exc: + logger.warning( + "OAuth login with %s failed: %s: %s", provider, type(exc).__name__, exc + ) + raise not_authenticated("OAuth login failed") from exc + request.session.clear() + request.session[SESSION_USER_KEY] = user.model_dump() + request.session[SESSION_ISSUED_AT_KEY] = int(session_clock()) + return user + + +@auth_router.post("/logout", status_code=status.HTTP_204_NO_CONTENT) +async def logout(request: Request) -> None: + """Clear the session cookie. Always succeeds, signed in or not.""" + request.session.clear() + + +@users_router.get("/me", responses=error_responses(401)) +async def read_current_user(current_user: CurrentUser) -> OAuthUser: + """The signed-in profile.""" + return current_user + + +router = APIRouter() +router.include_router(auth_router) +router.include_router(users_router) diff --git a/src/fastapi_fastkit/fragments/auth/package_init.py.j2 b/src/fastapi_fastkit/fragments/auth/package_init.py.j2 new file mode 100644 index 0000000..e4d94ba --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/package_init.py.j2 @@ -0,0 +1,45 @@ +{% include "header.j2" %} +{% if auth_kind == "jwt" %} +"""Authentication: OAuth2 password flow with JWT access tokens. + +``POST {API_V1_PREFIX}/auth/register`` creates an account, +``POST {API_V1_PREFIX}/auth/token`` exchanges email and password for a +bearer token, and ``GET {API_V1_PREFIX}/users/me`` returns the account the +token belongs to. Protect your own routes with the :data:`CurrentUser` +dependency from ``dependencies.py``. Tokens are signed with ``SECRET_KEY`` +from the project settings. +{% elif auth_kind == "session" %} +"""Authentication: signed cookie sessions. + +``POST {API_V1_PREFIX}/auth/register`` creates an account, +``POST {API_V1_PREFIX}/auth/login`` stores the account id in the session +cookie, ``POST {API_V1_PREFIX}/auth/logout`` ends every session of the +account, and ``GET {API_V1_PREFIX}/users/me`` returns the signed-in account. +Protect your own routes with the :data:`CurrentUser` dependency from +``dependencies.py``. The cookie is signed with ``SECRET_KEY`` from the +project settings. +{% elif auth_kind == "oauth2" %} +"""Authentication: OAuth2 social login (Google, GitHub) built on Authlib. + +``GET {API_V1_PREFIX}/auth/login/{provider}`` redirects to the provider, +``GET {API_V1_PREFIX}/auth/callback/{provider}`` stores the profile in the +signed session cookie, ``GET {API_V1_PREFIX}/users/me`` returns it and +``POST {API_V1_PREFIX}/auth/logout`` clears it. A provider is available once +its ``_CLIENT_ID`` and ``_CLIENT_SECRET`` are set (and, +unless ``ENVIRONMENT=development``, ``OAUTH_REDIRECT_BASE_URL``). +{% else %} +"""Authentication with FastAPI-Users (SQLAlchemy backend, JWT bearer tokens). + +The library's standard routers are mounted under ``API_V1_PREFIX``: +``/auth/jwt/login``, ``/auth/jwt/logout``, ``/auth/register`` and +``/users/me`` (plus the superuser-only ``/users/{id}`` routes). Protect your +own routes with :data:`CurrentUser` from ``users.py``. Status codes and +headers are the library's (see ``router.py`` for where they differ from the +rest of the project). +{% endif %} +{% if backend == "memory" %} + +Accounts live in memory (``repository.py``): they are lost on every restart +and each worker process has its own copy. Select a database to keep them. +{% endif %} +""" diff --git a/src/fastapi_fastkit/fragments/auth/repository.py.j2 b/src/fastapi_fastkit/fragments/auth/repository.py.j2 new file mode 100644 index 0000000..d865919 --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/repository.py.j2 @@ -0,0 +1,254 @@ +{% include "header.j2" %} +{% if backend == "sql" %} +"""Data access for the ``users`` table. + +Each write method is one transaction: it commits on its own, so a request +never reports success for a change that was not stored. Emails are unique +(enforced by the database), compared and stored lower-cased. +""" + +from sqlalchemy import select{% if auth_kind == "session" %}, update{% endif %} + +from sqlalchemy.exc import IntegrityError +from sqlalchemy.ext.asyncio import AsyncSession + +from {{ auth_module }}.models import User + + +class EmailAlreadyRegisteredError(Exception): + """Raised when the email address already belongs to an account.""" + + +class UserRepository: + """Every SQL statement touching ``users`` lives here.""" + + def __init__(self, session: AsyncSession) -> None: + self.session = session + + async def get(self, user_id: str) -> User | None: + """The account with this id (as found in a token or session).""" + try: + key = int(user_id) + except ValueError: + return None + return await self.session.get(User, key) + + async def get_by_email(self, email: str) -> User | None: + result = await self.session.execute( + select(User).where(User.email == email.lower()) + ) + return result.scalar_one_or_none() + + async def add( + self, *, email: str, hashed_password: str, full_name: str | None = None + ) -> User: + """Store a new account and commit.""" + user = User( + email=email.lower(), + hashed_password=hashed_password, + full_name=full_name, + is_active=True, + ) + self.session.add(user) + try: + await self.session.commit() + except IntegrityError as exc: + await self.session.rollback() + raise EmailAlreadyRegisteredError(email) from exc + return user + + async def set_active(self, user_id: str, active: bool) -> bool: + """Activate or deactivate an account and commit; False when it is unknown.""" + user = await self.get(user_id) + if user is None: + return False + user.is_active = active + await self.session.commit() + return True +{% if auth_kind == "session" %} + + async def revoke_sessions(self, user_id: str) -> None: + """End every session of an account (one atomic increment) and commit.""" + try: + key = int(user_id) + except ValueError: + return + await self.session.execute( + update(User) + .where(User.id == key) + .values(session_version=User.session_version + 1) + ) + await self.session.commit() +{% endif %} +{% elif backend == "mongo" %} +"""Data access for the ``users`` collection. + +A unique index on ``email`` makes registration atomic: two concurrent +requests for the same address cannot both succeed. Emails are stored +lower-cased. +""" + +from bson import ObjectId +from pymongo.asynchronous.collection import AsyncCollection +from pymongo.asynchronous.database import AsyncDatabase +from pymongo.errors import DuplicateKeyError + +{{ format_imports(["from " ~ auth_module ~ ".models import User", "from " ~ db_module ~ " import Document"]) }} + + +class EmailAlreadyRegisteredError(Exception): + """Raised when the email address already belongs to an account.""" + + +def _to_user(document: Document) -> User: + return User( + id=str(document["_id"]), + email=document["email"], + hashed_password=document["hashed_password"], + full_name=document.get("full_name"), + is_active=document.get("is_active", True), +{% if auth_kind == "session" %} + session_version=document.get("session_version", 0), +{% endif %} + ) + + +class UserRepository: + """Every query touching ``users`` lives here.""" + + def __init__(self, database: AsyncDatabase[Document]) -> None: + self.collection: AsyncCollection[Document] = database["users"] + + async def get(self, user_id: str) -> User | None: + """The account with this id (as found in a token or session).""" + if not ObjectId.is_valid(user_id): + return None + document = await self.collection.find_one({"_id": ObjectId(user_id)}) + return None if document is None else _to_user(document) + + async def get_by_email(self, email: str) -> User | None: + document = await self.collection.find_one({"email": email.lower()}) + return None if document is None else _to_user(document) + + async def add( + self, *, email: str, hashed_password: str, full_name: str | None = None + ) -> User: + """Store a new account.""" + # Creating an index that already exists is a no-op. + await self.collection.create_index("email", unique=True) + document: Document = { + "email": email.lower(), + "hashed_password": hashed_password, + "full_name": full_name, + "is_active": True, +{% if auth_kind == "session" %} + "session_version": 0, +{% endif %} + } + try: + result = await self.collection.insert_one(document) + except DuplicateKeyError as exc: + raise EmailAlreadyRegisteredError(email) from exc + return _to_user({**document, "_id": result.inserted_id}) + + async def set_active(self, user_id: str, active: bool) -> bool: + """Activate or deactivate an account; False when it is unknown.""" + if not ObjectId.is_valid(user_id): + return False + result = await self.collection.update_one( + {"_id": ObjectId(user_id)}, {"$set": {"is_active": active}} + ) + return result.matched_count == 1 +{% if auth_kind == "session" %} + + async def revoke_sessions(self, user_id: str) -> None: + """End every session of an account (one atomic ``$inc``).""" + if not ObjectId.is_valid(user_id): + return + await self.collection.update_one( + {"_id": ObjectId(user_id)}, {"$inc": {"session_version": 1}} + ) +{% endif %} +{% else %} +"""In-memory account store. NOT PERSISTENT. + +Accounts are kept in a dictionary of this process: every restart forgets +them, and each worker process (``uvicorn --workers``, several replicas) has +its own copy. Good for trying the API out; select a database (or replace +:class:`UserRepository` with your own) before relying on it. Access is +serialised with a lock, so concurrent requests cannot register the same +email twice. +""" + +import threading +from itertools import count + +from {{ auth_module }}.models import User + + +class EmailAlreadyRegisteredError(Exception): + """Raised when the email address already belongs to an account.""" + + +class UserRepository: + """Accounts in a dictionary, protected by a lock.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._users: dict[int, User] = {} + self._ids = count(1) + + async def get(self, user_id: str) -> User | None: + """The account with this id (as found in a token or session).""" + try: + key = int(user_id) + except ValueError: + return None + with self._lock: + return self._users.get(key) + + async def get_by_email(self, email: str) -> User | None: + email = email.lower() + with self._lock: + return next((u for u in self._users.values() if u.email == email), None) + + async def add( + self, *, email: str, hashed_password: str, full_name: str | None = None + ) -> User: + """Store a new account.""" + email = email.lower() + with self._lock: + if any(user.email == email for user in self._users.values()): + raise EmailAlreadyRegisteredError(email) + user = User( + id=next(self._ids), + email=email, + hashed_password=hashed_password, + full_name=full_name, + ) + self._users[user.id] = user + return user + + async def set_active(self, user_id: str, active: bool) -> bool: + """Activate or deactivate an account; False when it is unknown.""" + user = await self.get(user_id) + if user is None: + return False + with self._lock: + user.is_active = active + return True +{% if auth_kind == "session" %} + + async def revoke_sessions(self, user_id: str) -> None: + """End every session of an account.""" + user = await self.get(user_id) + if user is None: + return + with self._lock: + user.session_version += 1 +{% endif %} + + +#: The store the API uses (see ``get_user_repository`` in ``dependencies.py``). +user_store = UserRepository() +{% endif %} diff --git a/src/fastapi_fastkit/fragments/auth/router.py.j2 b/src/fastapi_fastkit/fragments/auth/router.py.j2 new file mode 100644 index 0000000..235c4b8 --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/router.py.j2 @@ -0,0 +1,249 @@ +{% include "header.j2" %} +{% if auth_kind == "jwt" %} +"""Authentication endpoints: register, token (OAuth2 password flow), profile. + +:data:`router` is mounted under ``settings.API_V1_PREFIX`` by ``main.py``. +""" +{% else %} +"""Authentication endpoints: register, login, logout, profile. + +:data:`router` is mounted under ``settings.API_V1_PREFIX`` by ``main.py``; +the session middleware it relies on is installed by +``middleware.add_session_middleware``. +""" +{% endif %} + +{% if create_tables %} +import logging +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +{% endif %} +{% if auth_kind == "jwt" %} +from typing import Annotated +{% endif %} +{% if create_tables or auth_kind == "jwt" %} + +{% endif %} +{% set third_party = ["from fastapi import APIRouter, HTTPException, Request, Response, status"] %} +{% if auth_kind == "jwt" or rate_limit %} +{% set third_party = third_party + ["from fastapi import Depends"] %} +{% endif %} +{% if auth_kind == "jwt" %} +{% set third_party = third_party + ["from fastapi.security import OAuth2PasswordRequestForm"] %} +{% endif %} +{% if create_tables %} +{% set third_party = third_party + ["from fastapi import FastAPI", "from sqlalchemy.exc import SQLAlchemyError"] %} +{% endif %} +{{ format_imports(third_party) }} + +{% set first_party = [ + "from " ~ pkg ~ ".core.responses import error_responses", + "from " ~ auth_module ~ ".service import EmailAlreadyRegisteredError", +] %} +{% if auth_kind == "jwt" %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".dependencies import CurrentUser, UserServiceDep", + "from " ~ auth_module ~ ".schemas import Token, UserCreate, UserRead", + "from " ~ auth_module ~ ".security import create_access_token", + "from " ~ settings_module ~ " import settings", +] %} +{% else %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".dependencies import SESSION_USER_KEY, SESSION_VERSION_KEY, CurrentUser, UserRepositoryDep, UserServiceDep, not_authenticated, start_session", + "from " ~ auth_module ~ ".schemas import LoginRequest, UserCreate, UserRead", +] %} +{% if rate_limit %} +{% set first_party = first_party + ["from " ~ settings_module ~ " import settings"] %} +{% endif %} +{% endif %} +{% if create_tables %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".models import User", + "from " ~ db_module ~ " import Base, engine", +] %} +{% endif %} +{% if rate_limit %} +{% set first_party = first_party + ["from " ~ pkg ~ ".rate_limiting import RateLimit"] %} +{% endif %} +{{ format_imports(first_party) }} +{% if create_tables %} + +logger = logging.getLogger(__name__) + + +async def create_user_table() -> None: + """Create the ``users`` table if it does not exist yet. + + The project has no migration tool, so the table is created on startup. + Existing tables and rows are never touched. Once you add Alembic, remove + this and create the table in a revision instead. + """ + async with engine.begin() as connection: + await connection.run_sync( + Base.metadata.create_all, + tables=[Base.metadata.tables[User.__tablename__]], + checkfirst=True, + ) + + +@asynccontextmanager +async def lifespan(_app: FastAPI) -> AsyncIterator[None]: + """Create the users table on startup; an unreachable database is logged. + + The app still starts without its database (``GET /ready`` reports it), + and the table is created on the next start. + """ + try: + await create_user_table() + except (OSError, SQLAlchemyError): + logger.warning("Could not create the users table", exc_info=True) + yield + +{% endif %} +{% if rate_limit %} + +#: Stricter budget (RATE_LIMIT_AUTH per client and endpoint) for the +#: endpoints that hash a password: argon2 costs 64 MiB per attempt. +_auth_rate_limit = [Depends(RateLimit(settings.RATE_LIMIT_AUTH))] +{% endif %} +{% if auth_kind == "jwt" %} + +# RFC 6749 section 5.1: token responses must not be cached. +_NO_STORE = {"Cache-Control": "no-store", "Pragma": "no-cache"} +{% endif %} + +auth_router = APIRouter(prefix="/auth", tags=["auth"]) +users_router = APIRouter(prefix="/users", tags=["users"]) + + +@auth_router.post( + "/register", + status_code=status.HTTP_201_CREATED, + responses=error_responses(409{% if rate_limit %}, 429{% endif %}), +{% if rate_limit %} + dependencies=_auth_rate_limit, +{% endif %} +) +async def register( + payload: UserCreate, users: UserServiceDep, request: Request, response: Response +) -> UserRead: +{% if auth_kind == "session" %} + """Create an account. Emails are unique and stored lower-cased. + + The demo account's address is reserved: registering it always answers + 409, so nobody can plant an account that demo logins would then use. + """ +{% else %} + """Create an account. Emails are unique and stored lower-cased.""" +{% endif %} + try: + user = await users.register(payload) + except EmailAlreadyRegisteredError as exc: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="An account with this email already exists", + ) from exc + response.headers["Location"] = str(request.url_for("read_user", user_id=user.id)) + return UserRead.model_validate(user) +{% if auth_kind == "jwt" %} + + +@auth_router.post( + "/token", + responses=error_responses(401, 403{% if rate_limit %}, 429{% endif %}), +{% if rate_limit %} + dependencies=_auth_rate_limit, +{% endif %} +) +async def issue_token( + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], + users: UserServiceDep, + response: Response, +) -> Token: + """OAuth2 password flow: ``username`` carries the email address.""" + user = await users.authenticate(form_data.username, form_data.password) + if user is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect email or password", + headers={"WWW-Authenticate": "Bearer"}, + ) + if not user.is_active: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user" + ) + response.headers.update(_NO_STORE) + return Token( + access_token=create_access_token(str(user.id)), + expires_in=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60, + ) +{% else %} + + +@auth_router.post( + "/login", + responses=error_responses(401, 403{% if rate_limit %}, 429{% endif %}), +{% if rate_limit %} + dependencies=_auth_rate_limit, +{% endif %} +) +async def login( + payload: LoginRequest, users: UserServiceDep, request: Request +) -> UserRead: + """Check the credentials and store the account id in the session cookie.""" + user = await users.authenticate(str(payload.email), payload.password) + if user is None: + raise not_authenticated("Incorrect email or password") + if not user.is_active: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user" + ) + # Starts from an empty session (nothing stored before the login is + # kept) and records the account's session version and the login time. + start_session(request, user) + return UserRead.model_validate(user) + + +@auth_router.post("/logout", status_code=status.HTTP_204_NO_CONTENT) +async def logout(request: Request, users: UserRepositoryDep) -> None: + """End the session. Always succeeds, signed in or not. + + The account's session version is incremented, so this cookie, a copy + of it, and every other session of the account stop working at once + (the cookie is signed client-side state: clearing it alone would not + invalidate a copy). + """ + user_id = request.session.get(SESSION_USER_KEY) + if isinstance(user_id, str): + user = await users.get(user_id) + if user is not None and user.session_version == request.session.get( + SESSION_VERSION_KEY + ): + await users.revoke_sessions(user_id) + request.session.clear() +{% endif %} + + +@users_router.get("/me", responses=error_responses(401, 403)) +async def read_current_user(current_user: CurrentUser) -> UserRead: + """The signed-in account.""" + return UserRead.model_validate(current_user) + + +@users_router.get("/{user_id}", responses=error_responses(401, 403, 404)) +async def read_user(user_id: {{ id_type }}, current_user: CurrentUser) -> UserRead: + """One account by id (the ``Location`` of a registration). + + Accounts can only read themselves; any other id answers 404, so the ids + of other accounts are not revealed. + """ + if str(user_id) != str(current_user.id): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail="User not found" + ) + return UserRead.model_validate(current_user) + + +router = APIRouter({% if create_tables %}lifespan=lifespan{% endif %}) +router.include_router(auth_router) +router.include_router(users_router) diff --git a/src/fastapi_fastkit/fragments/auth/schemas.py.j2 b/src/fastapi_fastkit/fragments/auth/schemas.py.j2 new file mode 100644 index 0000000..1372c29 --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/schemas.py.j2 @@ -0,0 +1,42 @@ +{% include "header.j2" %} +"""Request and response bodies of the authentication endpoints.""" + +from pydantic import BaseModel, ConfigDict, EmailStr, Field + + +class UserCreate(BaseModel): + """Registration body. The email is stored lower-cased.""" + + email: EmailStr + password: str = Field(min_length=8, max_length=128) + full_name: str | None = Field(default=None, max_length=255) + + +class UserRead(BaseModel): + """Public profile of an account; never carries the password hash.""" + + model_config = ConfigDict(from_attributes=True) + + id: {{ id_type }} + email: EmailStr + full_name: str | None = None + is_active: bool +{% if auth_kind == "jwt" %} + + +class Token(BaseModel): + """Response of ``POST /auth/token`` (RFC 6749 section 5.1).""" + + access_token: str + token_type: str = "bearer" + #: Lifetime of the access token in seconds. + expires_in: int +{% else %} + + +class LoginRequest(BaseModel): + """Credentials posted to ``POST /auth/login``.""" + + email: EmailStr + password: str = Field(min_length=1, max_length=128) +{% endif %} diff --git a/src/fastapi_fastkit/fragments/auth/security.py.j2 b/src/fastapi_fastkit/fragments/auth/security.py.j2 new file mode 100644 index 0000000..5a06258 --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/security.py.j2 @@ -0,0 +1,111 @@ +{% include "header.j2" %} +{% if auth_kind == "jwt" %} +"""Password hashing (argon2id through pwdlib) and JWT access tokens (PyJWT). + +No FastAPI imports: the helpers can be reused from scripts, workers or tests. +Tokens are signed with ``SECRET_KEY`` and expire after +``ACCESS_TOKEN_EXPIRE_MINUTES`` (project settings). + +argon2id allocates 64 MiB per hash, and hashing runs in the thread pool (40 +threads by default), so at most :data:`MAX_CONCURRENT_HASHES` hashes run at +once; further requests wait for a slot instead of allocating more memory. +""" + +import threading +from datetime import UTC, datetime, timedelta +from functools import lru_cache +from typing import Any + +import jwt +from pwdlib import PasswordHash + +from {{ settings_module }} import settings +{% else %} +"""Password hashing (argon2id through pwdlib). + +argon2id allocates 64 MiB per hash, and hashing runs in the thread pool (40 +threads by default), so at most :data:`MAX_CONCURRENT_HASHES` hashes run at +once; further requests wait for a slot instead of allocating more memory. +""" + +import threading +from functools import lru_cache + +from pwdlib import PasswordHash +{% endif %} + +password_hash = PasswordHash.recommended() + +#: argon2 computations allowed at the same time in this process. +MAX_CONCURRENT_HASHES = 4 +_hash_slots = threading.BoundedSemaphore(MAX_CONCURRENT_HASHES) + + +def hash_password(password: str) -> str: + """Hash a password for storage (blocking: call it from a worker thread).""" + with _hash_slots: + return password_hash.hash(password) + + +@lru_cache(maxsize=1) +def _dummy_hash() -> str: + with _hash_slots: + return password_hash.hash("fastkit-timing-equaliser") + + +def verify_password(password: str, hashed_password: str | None) -> bool: + """Check a password against its stored hash (blocking, like hashing). + + Without a stored hash (unknown account) the password is still checked + against a dummy hash, so an unknown email takes as long to reject as a + wrong password and response times do not reveal which accounts exist. + """ + if hashed_password is None: + dummy = _dummy_hash() + with _hash_slots: + password_hash.verify(password, dummy) + return False + with _hash_slots: + return password_hash.verify(password, hashed_password) +{% if auth_kind == "jwt" %} + + +ACCESS_TOKEN_TYPE = "access" + + +class TokenError(Exception): + """The token is malformed, expired, wrongly signed or of the wrong type.""" + + +def create_access_token(subject: str) -> str: + """Sign an access token for the account id ``subject``.""" + now = datetime.now(UTC) + payload: dict[str, Any] = { + "sub": subject, + "type": ACCESS_TOKEN_TYPE, + "iat": now, + "exp": now + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES), + } + return jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM) + + +def decode_access_token(token: str) -> str: + """Validate an access token and return its subject (the account id). + + Raises: + TokenError: the signature, expiry or ``type`` claim did not check out. + """ + try: + payload = jwt.decode( + token, + settings.SECRET_KEY, + algorithms=[settings.JWT_ALGORITHM], + options={"require": ["exp", "sub", "type"]}, + ) + except jwt.PyJWTError as exc: + raise TokenError("invalid access token") from exc + subject = payload.get("sub") + if payload.get("type") != ACCESS_TOKEN_TYPE or not isinstance(subject, str): + raise TokenError("not an access token") + return subject +{% endif %} diff --git a/src/fastapi_fastkit/fragments/auth/service.py.j2 b/src/fastapi_fastkit/fragments/auth/service.py.j2 new file mode 100644 index 0000000..c079c3f --- /dev/null +++ b/src/fastapi_fastkit/fragments/auth/service.py.j2 @@ -0,0 +1,98 @@ +{% include "header.j2" %} +"""Account logic: registration and the credential check. + +:meth:`UserService.authenticate` is the single place that decides whether an +email and password are valid. To check credentials somewhere else (LDAP, an +external identity provider), change that method or override the +``get_user_service`` dependency. + +argon2 hashing is CPU-bound, so it runs in the thread pool instead of +blocking the event loop. +""" +{% if auth_kind == "session" %} + +import secrets +{% endif %} + +from starlette.concurrency import run_in_threadpool + +{% set first_party = [ + "from " ~ auth_module ~ ".models import User", + "from " ~ auth_module ~ ".repository import EmailAlreadyRegisteredError, UserRepository", + "from " ~ auth_module ~ ".schemas import UserCreate", + "from " ~ auth_module ~ ".security import hash_password, verify_password", +] %} +{% if auth_kind == "session" %} +{% set first_party = first_party + ["from " ~ settings_module ~ " import settings"] %} +{% endif %} +{{ format_imports(first_party) }} + +__all__ = ["EmailAlreadyRegisteredError", "UserService"] +{% if auth_kind == "session" %} + +#: Demo account, accepted only while ENABLE_DEMO_USERS=true (only in +#: development: the settings refuse it at startup in every other environment). +#: Its address is reserved: :meth:`UserService.register` refuses it, so the +#: account demo logins use is always the one created here, never one somebody +#: planted. +DEMO_USER_EMAIL = "demo@example.com" +DEMO_USER_PASSWORD = "demo-password" +{% endif %} + + +class UserService: + def __init__(self, users: UserRepository) -> None: + self.users = users + + async def register(self, payload: UserCreate) -> User: + """Create an account. + + Raises: + EmailAlreadyRegisteredError: the email is already taken{% if auth_kind == "session" %} (or is + the reserved demo address){% endif %}. + """ +{% if auth_kind == "session" %} + if str(payload.email).lower() == DEMO_USER_EMAIL: + raise EmailAlreadyRegisteredError(DEMO_USER_EMAIL) + return await self._create(payload) + + async def _create(self, payload: UserCreate) -> User: + """Hash the password and store the account.""" +{% endif %} + hashed_password = await run_in_threadpool(hash_password, payload.password) + return await self.users.add( + email=str(payload.email), + hashed_password=hashed_password, + full_name=payload.full_name, + ) + + async def authenticate(self, email: str, password: str) -> User | None: + """The account these credentials belong to, or None.""" +{% if auth_kind == "session" %} + if email.lower() == DEMO_USER_EMAIL: + return await self._authenticate_demo_user(password) +{% endif %} + user = await self.users.get_by_email(email) + hashed_password = user.hashed_password if user else None + if not await run_in_threadpool(verify_password, password, hashed_password): + return None + return user +{% if auth_kind == "session" %} + + async def _authenticate_demo_user(self, password: str) -> User | None: + """The demo account, created on its first login while demo users are on.""" + if not settings.ENABLE_DEMO_USERS: + return None + if not secrets.compare_digest(password, DEMO_USER_PASSWORD): + return None + user = await self.users.get_by_email(DEMO_USER_EMAIL) + if user is not None: + return user + try: + return await self._create( + UserCreate(email=DEMO_USER_EMAIL, password=DEMO_USER_PASSWORD) + ) + except EmailAlreadyRegisteredError: + # A concurrent first login created it. + return await self.users.get_by_email(DEMO_USER_EMAIL) +{% endif %} diff --git a/src/fastapi_fastkit/fragments/auth/session.py.j2 b/src/fastapi_fastkit/fragments/auth/session.py.j2 deleted file mode 100644 index 4fba73c..0000000 --- a/src/fastapi_fastkit/fragments/auth/session.py.j2 +++ /dev/null @@ -1,71 +0,0 @@ -{% include "header.j2" %} -{% from "auth/settings.j2" import auth_settings_class %} -"""Cookie-session authentication. - -``SessionMiddleware`` (Starlette + itsdangerous) signs the session cookie; the -routes below show the minimal login / logout / whoami cycle. Replace -:func:`authenticate_user` with a real user-store lookup. The cookie is signed -with ``SECRET_KEY`` (see :class:`AuthSettings`). -""" - -import secrets -from typing import Literal - -from fastapi import APIRouter, HTTPException, Request, status -from pydantic import BaseModel, model_validator -from pydantic_settings import BaseSettings, SettingsConfigDict - -{% call auth_settings_class("the session cookie") %} - SESSION_MAX_AGE: int = 1209600 # 14 days -{% endcall %} - -#: Demo credential store. Swap for your database before going to production. -_DEMO_USERS: dict[str, str] = {"demo": "demo-password"} - -router = APIRouter(prefix="/auth", tags=["Authentication"]) - - -class LoginRequest(BaseModel): - """Credentials posted to ``/auth/login``.""" - - username: str - password: str - - -def authenticate_user(username: str, password: str) -> str | None: - """Return the username when the credentials match, else ``None``.""" - expected = _DEMO_USERS.get(username) - if expected is None or not secrets.compare_digest(expected, password): - return None - return username - - -@router.post("/login") -async def login(payload: LoginRequest, request: Request) -> dict[str, str]: - """Verify credentials and store the user in the signed session cookie.""" - username = authenticate_user(payload.username, payload.password) - if username is None: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid username or password", - ) - request.session["user"] = username - return {"status": "logged in", "user": username} - - -@router.post("/logout") -async def logout(request: Request) -> dict[str, str]: - """Clear the session cookie.""" - request.session.clear() - return {"status": "logged out"} - - -@router.get("/me") -async def current_user(request: Request) -> dict[str, str]: - """Return the currently signed-in user.""" - user = request.session.get("user") - if not user: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated" - ) - return {"user": user} diff --git a/src/fastapi_fastkit/fragments/auth/settings.j2 b/src/fastapi_fastkit/fragments/auth/settings.j2 deleted file mode 100644 index 6f136ec..0000000 --- a/src/fastapi_fastkit/fragments/auth/settings.j2 +++ /dev/null @@ -1,61 +0,0 @@ -{# - Shared ``AuthSettings`` class for the auth modules that sign something - (JWT, session cookie, OAuth2 state cookie). The caller block adds the - module's own fields. The module must import ``secrets``, ``Literal``, - ``model_validator``, ``BaseSettings`` and ``SettingsConfigDict``. -#} -{% macro auth_settings_class(purpose) %} -#: SECRET_KEY values published in fastkit templates, fragments and docs. Anyone -#: can sign with them, so the app refuses to start with one of them (or without -#: an explicit SECRET_KEY) when ENVIRONMENT=production. -KNOWN_EXAMPLE_SECRET_KEYS = frozenset( - { - "changethis", - "changethis-please-generate-a-real-32-byte-key", - "changethis-please-use-openssl-rand-hex-32", - "change-me-in-production", - "your-secret-key-here", - "your-secret-key-here-change-in-production", - } -) - -_GENERATE_KEY_HINT = ( - "Generate one with `python -c " - '"import secrets; print(secrets.token_urlsafe(32))"` ' - "and set it as SECRET_KEY in the environment or .env." -) - - -class AuthSettings(BaseSettings): - """Authentication settings, read from the environment or ``.env``.""" - - model_config = SettingsConfigDict( - env_file=".env", - env_ignore_empty=True, - extra="ignore", - ) - - ENVIRONMENT: Literal["development", "staging", "production"] = "development" - # Signs {{ purpose }}. fastkit writes a unique SECRET_KEY to .env; without - # one, a per-process random key is used (development only). - SECRET_KEY: str = secrets.token_urlsafe(32) -{{ caller() }} - @model_validator(mode="after") - def _reject_unsafe_secret_key_in_production(self) -> "AuthSettings": - if self.ENVIRONMENT != "production": - return self - if "SECRET_KEY" not in self.model_fields_set: - raise ValueError( - "SECRET_KEY must be set explicitly when ENVIRONMENT=production. " - + _GENERATE_KEY_HINT - ) - if self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS: - raise ValueError( - "SECRET_KEY is set to a public example value, which must not be " - "used when ENVIRONMENT=production. " + _GENERATE_KEY_HINT - ) - return self - - -auth_settings = AuthSettings() -{% endmacro %} diff --git a/src/fastapi_fastkit/fragments/core/config.py.j2 b/src/fastapi_fastkit/fragments/core/config.py.j2 new file mode 100644 index 0000000..c42076c --- /dev/null +++ b/src/fastapi_fastkit/fragments/core/config.py.j2 @@ -0,0 +1,142 @@ +{% include "header.j2" %} +"""Application settings, read from the environment and the local ``.env``. + +Every configurable value of the project lives on :class:`Settings`; import +the shared instance with ``from {{ settings_module }} import settings``. +Environment variables win over ``.env``. +""" + +import json +import secrets +import warnings +from typing import Annotated, Any, Literal + +from pydantic import AnyUrl, BeforeValidator, computed_field, model_validator +from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict + +#: Every example SECRET_KEY fastkit has shipped in templates, ``.env`` files +#: and ``fastkit init`` modules, in any version. They are public, so anyone +#: could sign tokens or cookies with them: staging and production refuse +#: them. +KNOWN_EXAMPLE_SECRET_KEYS = frozenset( + { +{% for key in example_secret_keys %} + {{ key | tojson }}, +{% endfor %} + } +) + +#: Shortest SECRET_KEY staging and production accept. HMAC-SHA256 (HS256) +#: wants a key of at least 32 bytes. +MIN_SECRET_KEY_BYTES = {{ min_secret_key_bytes }} + +_GENERATE_KEY_HINT = ( + "Generate one with " + '`python -c "import secrets; print(secrets.token_urlsafe(32))"` ' + "and set it as SECRET_KEY in the environment or .env." +) + + +def parse_cors(value: Any) -> Any: + """Read origins from a comma-separated string or a JSON list. + + Blank entries are dropped, so ``BACKEND_CORS_ORIGINS=`` or a trailing + comma never turns into an empty origin. + """ + if isinstance(value, str): + value = value.strip() + if value.startswith("["): + value = json.loads(value) + else: + value = value.split(",") + if isinstance(value, list): + return [str(origin).strip() for origin in value if str(origin).strip()] + raise ValueError(value) + + +# Each origin is a full URL such as http://localhost:3000, or "*" for any +# origin. "*" never goes together with credentials (cookies, Authorization +# headers): browsers refuse that, so main.py turns credentials off for it. +CorsOrigins = Annotated[ + list[Literal["*"] | AnyUrl], NoDecode, BeforeValidator(parse_cors) +] + + +class Settings(BaseSettings): + """Project configuration.""" + + model_config = SettingsConfigDict( + env_file=".env", + env_ignore_empty=True, + extra="ignore", + ) + + PROJECT_NAME: str = {{ project_name | tojson }} + ENVIRONMENT: Literal["development", "staging", "production"] = "development" + # Signs the tokens and session cookies of the authentication options. + # fastkit writes a unique value to .env; without one a per-process random + # key is used. Staging and production refuse a missing, public or short + # key (see _check_secret_key below). + SECRET_KEY: str = secrets.token_urlsafe(32) + + API_V1_PREFIX: str = "/api/v1" + + # Browser origins allowed to call the API, comma-separated or a JSON list: + # "http://localhost:3000,https://app.example.com". Empty: no cross-origin + # access. + BACKEND_CORS_ORIGINS: CorsOrigins = [] +{% for group in settings_groups %} + + # {{ group.title }} +{% for field in group.fields %} + {{ field.name }}: {{ field.annotation }} = {{ field.default }} +{% endfor %} +{% endfor %} + + @computed_field # type: ignore[prop-decorator] + @property + def all_cors_origins(self) -> list[str]: + """Configured origins without trailing slashes; ``["*"]`` for any origin.""" + origins = [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + # "*" already allows every origin; other entries next to it add nothing. + return ["*"] if "*" in origins else origins + + @model_validator(mode="after") + def _check_secret_key(self) -> "Settings": + """Refuse a missing, public or short SECRET_KEY outside development. + + Staging and production are usually reachable from the internet, so + both refuse to start without a strong explicit key. In development a + public example value only warns, so a fresh checkout still starts. + """ + is_example = self.SECRET_KEY.strip() in KNOWN_EXAMPLE_SECRET_KEYS + if self.ENVIRONMENT == "development": + if is_example: + warnings.warn( + "SECRET_KEY is a public example value; never deploy it. " + + _GENERATE_KEY_HINT, + stacklevel=2, + ) + return self + env = f"ENVIRONMENT={self.ENVIRONMENT}" + if "SECRET_KEY" not in self.model_fields_set: + raise ValueError( + f"SECRET_KEY must be set explicitly when {env}: " + "the random default differs between processes and restarts, so " + "tokens and cookies signed by one would fail in another. " + + _GENERATE_KEY_HINT + ) + if is_example: + raise ValueError( + "SECRET_KEY is a public example value, which must not be used " + f"when {env}. " + _GENERATE_KEY_HINT + ) + if len(self.SECRET_KEY.encode()) < MIN_SECRET_KEY_BYTES: + raise ValueError( + f"SECRET_KEY must be at least {MIN_SECRET_KEY_BYTES} bytes when " + f"{env}. " + _GENERATE_KEY_HINT + ) + return self + + +settings = Settings() diff --git a/src/fastapi_fastkit/fragments/db/mongodb.py.j2 b/src/fastapi_fastkit/fragments/db/mongodb.py.j2 index b15e2c2..b254591 100644 --- a/src/fastapi_fastkit/fragments/db/mongodb.py.j2 +++ b/src/fastapi_fastkit/fragments/db/mongodb.py.j2 @@ -1,19 +1,63 @@ {% include "header.j2" %} -from motor.motor_asyncio import AsyncIOMotorClient -from pydantic_settings import BaseSettings, SettingsConfigDict +"""MongoDB access through PyMongo's native asyncio client. +``AsyncMongoClient`` replaces Motor, which MongoDB deprecated in favour of +it. The client is created on startup (:func:`create_mongo_client`), kept on +``app.state.mongo_client`` and closed on shutdown, either by the +application's own lifespan or by :data:`lifespan_router`, which carries +:func:`mongo_lifespan` into the application that includes it. Endpoints +receive the database through :data:`MongoDatabaseDep`. -class DatabaseSettings(BaseSettings): - """MongoDB configuration settings.""" +Configure with ``MONGODB_URL``, ``MONGODB_DB_NAME`` and +``MONGODB_TIMEOUT_MS`` (environment or ``.env``). +""" - MONGODB_URL: str = "mongodb://localhost:27017" - MONGODB_DB_NAME: str = "fastapi_db" +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from typing import Annotated, Any - model_config = SettingsConfigDict(env_file=".env", extra="ignore") +from fastapi import APIRouter, Depends, FastAPI, Request +from pymongo import AsyncMongoClient +from pymongo.asynchronous.database import AsyncDatabase +from {{ settings_module }} import settings -settings = DatabaseSettings() +Document = dict[str, Any] -# MongoDB client -client = AsyncIOMotorClient(settings.MONGODB_URL) -database = client[settings.MONGODB_DB_NAME] + +def create_mongo_client() -> AsyncMongoClient[Document]: + """Build the client; it connects lazily on the first operation.""" + return AsyncMongoClient( + settings.MONGODB_URL, + serverSelectionTimeoutMS=settings.MONGODB_TIMEOUT_MS, + ) + + +@asynccontextmanager +async def mongo_lifespan(app: FastAPI) -> AsyncIterator[None]: + """Create the client on startup and close it on shutdown.""" + app.state.mongo_client = create_mongo_client() + try: + yield + finally: + await app.state.mongo_client.close() + + +#: Route-less router running :func:`mongo_lifespan` with the application's +#: lifespan. Include it before the routers that use the client on startup. +lifespan_router = APIRouter(lifespan=mongo_lifespan) + + +def get_mongo_client(request: Request) -> AsyncMongoClient[Document]: + """The client the lifespan stored on the application.""" + client: AsyncMongoClient[Document] = request.app.state.mongo_client + return client + + +def get_mongo_database(request: Request) -> AsyncDatabase[Document]: + """Dependency returning the configured database.""" + return get_mongo_client(request)[settings.MONGODB_DB_NAME] + + +#: ``db: MongoDatabaseDep`` in an endpoint signature. +MongoDatabaseDep = Annotated[AsyncDatabase[Document], Depends(get_mongo_database)] diff --git a/src/fastapi_fastkit/fragments/db/redis.py.j2 b/src/fastapi_fastkit/fragments/db/redis.py.j2 index dc65dbc..e404601 100644 --- a/src/fastapi_fastkit/fragments/db/redis.py.j2 +++ b/src/fastapi_fastkit/fragments/db/redis.py.j2 @@ -1,19 +1,24 @@ {% include "header.j2" %} """Redis client wiring. -The single ``redis.asyncio`` connection pool is created lazily and reused by -every request through the :func:`get_redis` dependency. +One ``redis.asyncio`` connection pool is shared by every request through the +:data:`RedisDep` dependency. Connections open lazily; :func:`close_redis` +releases them on application shutdown, called by the application's own +lifespan or by :data:`lifespan_router`. Configure with ``REDIS_URL`` +(environment or ``.env``). """ -import os from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from typing import Annotated import redis.asyncio as redis +from fastapi import APIRouter, Depends, FastAPI -REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0") +from {{ settings_module }} import settings #: Shared connection pool. ``redis.asyncio`` clients are safe to share. -redis_client: redis.Redis = redis.from_url(REDIS_URL, decode_responses=True) +redis_client: redis.Redis = redis.from_url(settings.REDIS_URL, decode_responses=True) async def get_redis() -> AsyncIterator[redis.Redis]: @@ -21,6 +26,24 @@ async def get_redis() -> AsyncIterator[redis.Redis]: yield redis_client +#: ``cache: RedisDep`` in an endpoint signature. +RedisDep = Annotated[redis.Redis, Depends(get_redis)] + + async def close_redis() -> None: """Close the pool on application shutdown.""" await redis_client.aclose() + + +@asynccontextmanager +async def redis_lifespan(_app: FastAPI) -> AsyncIterator[None]: + """Close the pool when the application shuts down.""" + try: + yield + finally: + await close_redis() + + +#: Route-less router running :func:`redis_lifespan` with the application's +#: lifespan. +lifespan_router = APIRouter(lifespan=redis_lifespan) diff --git a/src/fastapi_fastkit/fragments/db/sqlalchemy.py.j2 b/src/fastapi_fastkit/fragments/db/sqlalchemy.py.j2 index 5ed676e..1f48e42 100644 --- a/src/fastapi_fastkit/fragments/db/sqlalchemy.py.j2 +++ b/src/fastapi_fastkit/fragments/db/sqlalchemy.py.j2 @@ -1,45 +1,69 @@ {% include "header.j2" %} -from collections.abc import AsyncIterator - -from pydantic_settings import BaseSettings, SettingsConfigDict -from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine -from sqlalchemy.orm import declarative_base +"""Async SQLAlchemy engine, session factory and the request session dependency. +Transactions are owned by the code that changes data: a service or +repository calls ``await session.commit()`` once its unit of work succeeded. +The request dependency below never commits on its own; it only rolls back +when the request fails, so a failed commit can never be reported to the +client as a success. -class DatabaseSettings(BaseSettings): - """Database configuration settings.""" +The engine's pool is disposed on shutdown, by the application's own +lifespan or by :data:`lifespan_router`. Configure the connection with +``DATABASE_URL`` and SQL logging with ``DB_ECHO`` (environment or ``.env``). - DATABASE_URL: str = {{ database_url | tojson }} +Statement parameters never appear in logs or exception messages +(``hide_parameters=True``): an ``IntegrityError`` from an ``INSERT`` into +``users`` would otherwise carry the email and the password hash into the +server log. +""" - model_config = SettingsConfigDict(env_file=".env", extra="ignore") +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from typing import Annotated +from fastapi import APIRouter, Depends, FastAPI +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine +from sqlalchemy.orm import DeclarativeBase -settings = DatabaseSettings() +from {{ settings_module }} import settings -# Create async engine engine = create_async_engine( settings.DATABASE_URL, - echo=True, - future=True, + echo=settings.DB_ECHO, + hide_parameters=True, + pool_pre_ping=True, ) -# Create async session factory -AsyncSessionLocal = async_sessionmaker( - engine, - class_=AsyncSession, - expire_on_commit=False, -) +SessionLocal = async_sessionmaker(engine, expire_on_commit=False) + -# Create base class for models -Base = declarative_base() +class Base(DeclarativeBase): + """Declarative base class of every ORM model (``Base.metadata`` for Alembic).""" async def get_db() -> AsyncIterator[AsyncSession]: - """Dependency for getting async database session.""" - async with AsyncSessionLocal() as session: + """Yield one session per request and roll it back if the request fails.""" + async with SessionLocal() as session: try: yield session - await session.commit() except Exception: await session.rollback() raise + + +#: ``session: SessionDep`` in an endpoint or service dependency signature. +SessionDep = Annotated[AsyncSession, Depends(get_db)] + + +@asynccontextmanager +async def engine_lifespan(_app: FastAPI) -> AsyncIterator[None]: + """Dispose of the connection pool when the application shuts down.""" + try: + yield + finally: + await engine.dispose() + + +#: Route-less router running :func:`engine_lifespan` with the application's +#: lifespan. Include it before the routers that use the engine on startup. +lifespan_router = APIRouter(lifespan=engine_lifespan) diff --git a/src/fastapi_fastkit/fragments/docker/docker_compose.j2 b/src/fastapi_fastkit/fragments/docker/docker_compose.j2 index a938c57..0230c38 100644 --- a/src/fastapi_fastkit/fragments/docker/docker_compose.j2 +++ b/src/fastapi_fastkit/fragments/docker/docker_compose.j2 @@ -1,20 +1,29 @@ {% include "header.j2" %} +# Settings are read at run time, never baked into the image: from .env +# (fastkit writes one with a unique SECRET_KEY; copy .env.example to .env if +# it is missing, or delete the env_file entries to pass everything through +# the environment) and from the variables below, which point the app at the +# services of this file. Database +# credentials default to development values; override them in the shell or +# in .env (POSTGRES_PASSWORD=..., MYSQL_PASSWORD=...) before deploying. services: app: build: . ports: - "8000:8000" + env_file: + - .env +{% if environment %} environment: - - DATABASE_URL=${DATABASE_URL} -{% if redis_service %} - - REDIS_URL=redis://redis:6379/0 - - CELERY_BROKER_URL=redis://redis:6379/0 - - DRAMATIQ_BROKER_URL=redis://redis:6379/0 +{% for line in environment %} + - {{ line }} +{% endfor %} {% endif %} {% if depends_on %} depends_on: {% for service in depends_on %} - - {{ service }} + {{ service }}: + condition: service_healthy {% endfor %} {% else %} # Add a database service here if needed @@ -24,24 +33,37 @@ services: worker: build: . command: {{ worker_command | tojson }} + env_file: + - .env +{% if environment %} environment: - - DATABASE_URL=${DATABASE_URL} - - REDIS_URL=redis://redis:6379/0 - - CELERY_BROKER_URL=redis://redis:6379/0 - - DRAMATIQ_BROKER_URL=redis://redis:6379/0 +{% for line in environment %} + - {{ line }} +{% endfor %} +{% endif %} depends_on: - - redis +{% for service in depends_on %} + {{ service }}: + condition: service_healthy +{% endfor %} + # The image's HEALTHCHECK probes the API, which the worker does not serve. + healthcheck: + disable: true {% endif %} {% if db_service == "postgres" %} postgres: image: postgres:16 environment: - - POSTGRES_USER=user - - POSTGRES_PASSWORD=password - - POSTGRES_DB=dbname - ports: - - "5432:5432" + - POSTGRES_USER=${POSTGRES_USER:-user} + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-password} + - POSTGRES_DB=${POSTGRES_DB:-dbname} + # Reachable from the app as postgres:5432; not published on the host. + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] + interval: 5s + timeout: 5s + retries: 10 volumes: - postgres_data:/var/lib/postgresql/data {% elif db_service == "mysql" %} @@ -49,20 +71,28 @@ services: mysql: image: mysql:8 environment: - - MYSQL_ROOT_PASSWORD=password - - MYSQL_USER=user - - MYSQL_PASSWORD=password - - MYSQL_DATABASE=dbname - ports: - - "3306:3306" + - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD:-password} + - MYSQL_USER=${MYSQL_USER:-user} + - MYSQL_PASSWORD=${MYSQL_PASSWORD:-password} + - MYSQL_DATABASE=${MYSQL_DATABASE:-dbname} + # Reachable from the app as mysql:3306; not published on the host. + healthcheck: + test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 --silent"] + interval: 5s + timeout: 5s + retries: 20 volumes: - mysql_data:/var/lib/mysql {% elif db_service == "mongodb" %} mongodb: image: mongo:7 - ports: - - "27017:27017" + # Reachable from the app as mongodb:27017; not published on the host. + healthcheck: + test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping')"] + interval: 5s + timeout: 5s + retries: 10 volumes: - mongo_data:/data/db {% endif %} @@ -70,8 +100,12 @@ services: redis: image: redis:7-alpine - ports: - - "6379:6379" + # Reachable from the app as redis:6379; not published on the host. + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 5s + retries: 10 volumes: - redis_data:/data {% endif %} diff --git a/src/fastapi_fastkit/fragments/docker/dockerfile.j2 b/src/fastapi_fastkit/fragments/docker/dockerfile.j2 index 20f8744..9d7a1fe 100644 --- a/src/fastapi_fastkit/fragments/docker/dockerfile.j2 +++ b/src/fastapi_fastkit/fragments/docker/dockerfile.j2 @@ -1,19 +1,50 @@ {% include "header.j2" %} FROM python:3.12-slim -WORKDIR /app - ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 +WORKDIR /app + +# Unprivileged runtime user with a fixed UID/GID, so file ownership on mounted +# volumes stays predictable across rebuilds. +RUN groupadd --system --gid 10001 app \ + && useradd --system --uid 10001 --gid app --no-create-home \ + --home-dir /nonexistent --shell /usr/sbin/nologin app + # Install dependencies COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt -# Copy application -COPY . . +# Only what the app runs is copied, never the whole directory: .env (and +# other local files) stay out of the image even without .dockerignore. The +# source stays owned by root, read-only for the app user. +{% for path in copy_paths %} +COPY {{ path }} +{% endfor %} +{% for path in writable_dirs %} + +# {{ path.comment }} +RUN mkdir -p {{ path.dir }} && chown -R app:app {{ path.dir }} +{% endfor %} + +ENV PYTHONPATH=/app +ENV ENVIRONMENT=production +{% for line in env_lines %} +ENV {{ line }} +{% endfor %} + +USER app EXPOSE 8000 -# Run application +# Liveness: GET /health answers without touching the database or cache. +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ + CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=4)"] + +# Settings come from the environment at run time, never from a file in the +# image, e.g.: +# docker run -p 8000:8000 --env-file .env -e ENVIRONMENT=production +# ENVIRONMENT=production refuses to start without an explicit, strong +# SECRET_KEY. CMD {{ cmd | tojson }} diff --git a/src/fastapi_fastkit/fragments/docker/dockerignore.j2 b/src/fastapi_fastkit/fragments/docker/dockerignore.j2 new file mode 100644 index 0000000..f76978f --- /dev/null +++ b/src/fastapi_fastkit/fragments/docker/dockerignore.j2 @@ -0,0 +1,16 @@ +# Kept out of the image: local secrets, virtualenvs, caches and databases. +.git +.venv +venv +__pycache__ +*.pyc +.pytest_cache +.ruff_cache +.mypy_cache +.coverage +htmlcov +.env +.env.* +!.env.example +*.db +*.sqlite3 diff --git a/src/fastapi_fastkit/fragments/features/cache.py.j2 b/src/fastapi_fastkit/fragments/features/cache.py.j2 index a5254e3..3e60f76 100644 --- a/src/fastapi_fastkit/fragments/features/cache.py.j2 +++ b/src/fastapi_fastkit/fragments/features/cache.py.j2 @@ -1,22 +1,47 @@ {% include "header.j2" %} -"""Example endpoints demonstrating ``fastapi-cache2``. +"""Example endpoints demonstrating ``fastapi-cache2`` on Redis. -``FastAPICache`` is initialised in the application lifespan; the ``@cache`` -decorator below stores the response in Redis for ``expire`` seconds. +The router carries its own lifespan (:func:`cache_lifespan`): including it +in the app initialises ``FastAPICache`` on startup and closes the Redis +connection pool on shutdown. If you remove these example routes but keep +using ``@cache`` elsewhere, move ``cache_lifespan`` into the application +lifespan. Configure the server with ``REDIS_URL`` (environment or ``.env``). """ import time +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager -from fastapi import APIRouter +from fastapi import APIRouter, FastAPI +from fastapi_cache import FastAPICache +from fastapi_cache.backends.redis import RedisBackend from fastapi_cache.decorator import cache +from redis import asyncio as aioredis -router = APIRouter(prefix="/api/v1/cache", tags=["Cache"]) +from {{ settings_module }} import settings + +#: Namespaces this project's keys in a Redis server shared with others. +CACHE_PREFIX = {{ (project_slug ~ "-cache") | tojson }} + + +@asynccontextmanager +async def cache_lifespan(_app: FastAPI) -> AsyncIterator[None]: + """Initialise the fastapi-cache2 Redis backend for the app's lifetime.""" + redis_client = aioredis.from_url(settings.REDIS_URL) + FastAPICache.init(RedisBackend(redis_client), prefix=CACHE_PREFIX) + try: + yield + finally: + await redis_client.aclose() + + +router = APIRouter(prefix="/cache", tags=["cache"], lifespan=cache_lifespan) @router.get("/expensive") @cache(expire=60) async def expensive_operation() -> dict[str, float]: - """Cached for 60s — the timestamp only moves once per minute.""" + """Cached for 60s: the timestamp only moves once per minute.""" return {"computed_at": time.time()} diff --git a/src/fastapi_fastkit/fragments/features/pagination.py.j2 b/src/fastapi_fastkit/fragments/features/pagination.py.j2 deleted file mode 100644 index 0b99f98..0000000 --- a/src/fastapi_fastkit/fragments/features/pagination.py.j2 +++ /dev/null @@ -1,31 +0,0 @@ -{% include "header.j2" %} -"""Example endpoint demonstrating ``fastapi-pagination``. - -``add_pagination(app)`` is called for you in the generated ``main.py``; it is -what turns the ``Page[...]`` return annotation into ``?page=&size=`` query -parameters. -""" - -from fastapi import APIRouter -from fastapi_pagination import Page, paginate -from pydantic import BaseModel - -router = APIRouter(prefix="/api/v1/items", tags=["Items"]) - - -class Item(BaseModel): - """A trivial demo record.""" - - id: int - name: str - - -#: Stand-in dataset. Replace ``paginate(...)`` with a database-backed -#: paginator (``fastapi_pagination.ext.sqlalchemy``) for real data. -_ITEMS: list[Item] = [Item(id=i, name=f"item-{i}") for i in range(1, 101)] - - -@router.get("", response_model=Page[Item]) -async def list_items() -> Page[Item]: - """Return the demo dataset one page at a time.""" - return paginate(_ITEMS) diff --git a/src/fastapi_fastkit/fragments/features/readiness.py.j2 b/src/fastapi_fastkit/fragments/features/readiness.py.j2 new file mode 100644 index 0000000..23c0609 --- /dev/null +++ b/src/fastapi_fastkit/fragments/features/readiness.py.j2 @@ -0,0 +1,85 @@ +{% include "header.j2" %} +"""Readiness probe: ``GET /ready`` checks the services the app depends on. + +Each check is cheap ({{ check_summary }}). The probe answers +``200 {"status": "ok"}`` when every check passes and +``503 {"status": "unavailable"}`` when any fails or takes longer than +:data:`READY_TIMEOUT_SECONDS`. The failure is logged, never returned. Point an +orchestrator's readiness probe here and its liveness probe at ``/health``. +""" + +import asyncio +import logging +from collections.abc import Awaitable, Callable + +{% for line in third_party_imports %} +{{ line }} +{% endfor %} +{% if first_party_imports %} + +{% for line in first_party_imports %} +{{ line }} +{% endfor %} +{% endif %} + +logger = logging.getLogger(__name__) + +READY_TIMEOUT_SECONDS = 2.0 + +router = APIRouter(tags=["health"]) + +Check = Callable[[Request], Awaitable[None]] +{% if check_sql %} + + +async def check_database(_request: Request) -> None: + """Run ``SELECT 1`` on a pooled connection.""" + async with engine.connect() as connection: + await connection.execute(text("SELECT 1")) +{% endif %} +{% if check_mongo %} + + +async def check_mongodb(request: Request) -> None: + """Ping MongoDB through the client the lifespan created.""" + await request.app.state.mongo_client.admin.command("ping") +{% endif %} +{% if check_redis_db %} + + +async def check_redis(_request: Request) -> None: + """Ping the Redis database.""" + await redis_client.ping() +{% endif %} +{% if check_cache %} + + +async def check_cache(_request: Request) -> None: + """Ping the Redis cache with a short-lived connection.""" + client = aioredis.from_url(settings.REDIS_URL) + try: + await client.ping() + finally: + await client.aclose() +{% endif %} + + +#: The checks ``/ready`` runs, in order. Tests replace this list. +CHECKS: list[Check] = [{{ check_names | join(", ") }}] + + +@router.get( + "/ready", + responses={503: {"description": "A dependency is unavailable"}}, +) +async def readiness_check(request: Request, response: Response) -> dict[str, str]: + """Report whether every dependency answers.""" + try: + async with asyncio.timeout(READY_TIMEOUT_SECONDS): + for check in CHECKS: + await check(request) + except Exception: + logger.warning("readiness check failed", exc_info=True) + response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE + return {"status": "unavailable"} + return {"status": "ok"} diff --git a/src/fastapi_fastkit/fragments/features/tasks_celery.py.j2 b/src/fastapi_fastkit/fragments/features/tasks_celery.py.j2 index 0ced7d7..d6a7331 100644 --- a/src/fastapi_fastkit/fragments/features/tasks_celery.py.j2 +++ b/src/fastapi_fastkit/fragments/features/tasks_celery.py.j2 @@ -1,15 +1,19 @@ {% include "header.j2" %} -"""Task submission / status endpoints backed by Celery.""" +"""Task submission / status endpoints backed by Celery. + +The handlers are plain ``def``: talking to the broker and the result backend +is blocking I/O, so FastAPI runs them in its threadpool. +""" from typing import Any from celery.result import AsyncResult -from fastapi import APIRouter, status +from fastapi import APIRouter, Request, Response, status from pydantic import BaseModel, Field from {{ pkg }}.worker import celery_app, example_task -router = APIRouter(prefix="/api/v1/tasks", tags=["Tasks"]) +router = APIRouter(prefix="/tasks", tags=["tasks"]) class TaskSubmission(BaseModel): @@ -26,22 +30,31 @@ class TaskAccepted(BaseModel): class TaskStatus(BaseModel): - """Current state of a submitted task.""" + """Current state of a submitted task. + + Celery cannot tell an unknown id from a queued task: both report + ``PENDING``. + """ task_id: str status: str result: Any = None -@router.post("", response_model=TaskAccepted, status_code=status.HTTP_202_ACCEPTED) -async def submit_task(submission: TaskSubmission) -> TaskAccepted: - """Queue :func:`example_task` and return its id.""" +@router.post("", status_code=status.HTTP_202_ACCEPTED) +def submit_task( + submission: TaskSubmission, request: Request, response: Response +) -> TaskAccepted: + """Queue :func:`example_task`; ``Location`` points at its status.""" async_result = example_task.delay(submission.payload) + response.headers["Location"] = str( + request.url_for("get_task_status", task_id=async_result.id) + ) return TaskAccepted(task_id=async_result.id, status=async_result.status) -@router.get("/{task_id}", response_model=TaskStatus) -async def get_task_status(task_id: str) -> TaskStatus: +@router.get("/{task_id}") +def get_task_status(task_id: str) -> TaskStatus: """Poll a previously submitted task.""" async_result = AsyncResult(task_id, app=celery_app) return TaskStatus( diff --git a/src/fastapi_fastkit/fragments/features/tasks_dramatiq.py.j2 b/src/fastapi_fastkit/fragments/features/tasks_dramatiq.py.j2 index f0237d9..396976d 100644 --- a/src/fastapi_fastkit/fragments/features/tasks_dramatiq.py.j2 +++ b/src/fastapi_fastkit/fragments/features/tasks_dramatiq.py.j2 @@ -1,15 +1,36 @@ {% include "header.j2" %} -"""Task submission / status endpoints backed by Dramatiq.""" - +"""Task submission / status endpoints backed by Dramatiq. + +The status lives in Dramatiq's result backend (Redis), not in this process: +a submission stores a ``PENDING`` marker under the message's result key +before the message is enqueued, and the worker overwrites it with the +result. Any API process or replica can therefore answer for any task, and +the entry expires after ``TASK_TTL_MS`` like the results themselves (an +expired or unknown id answers 404). + +The handlers are plain ``def``: enqueueing and reading results is blocking +Redis I/O, so FastAPI runs them in its threadpool. An unreachable Redis +answers ``503``. +""" + +import logging +import uuid from typing import Any -from dramatiq.results.errors import ResultMissing -from fastapi import APIRouter, status +from dramatiq import Message +from dramatiq.results.errors import ResultFailure, ResultMissing +from fastapi import APIRouter, HTTPException, Request, Response, status from pydantic import BaseModel, Field +from redis.exceptions import RedisError + +from {{ pkg }}.worker import TASK_TTL_MS, example_task, result_backend -from {{ pkg }}.worker import example_task +logger = logging.getLogger(__name__) -router = APIRouter(prefix="/api/v1/tasks", tags=["Tasks"]) +router = APIRouter(prefix="/tasks", tags=["tasks"]) + +#: Stored as the result of a task that has not finished yet. +PENDING_MARKER = {"fastkit_task_status": "PENDING"} class TaskSubmission(BaseModel): @@ -33,28 +54,66 @@ class TaskStatus(BaseModel): result: Any = None -#: Dramatiq has no server-side message registry, so keep the handles we -#: created in-process. Swap for a shared store when running multiple replicas. -_MESSAGES: dict[str, Any] = {} +def _queue_unavailable(exc: RedisError) -> HTTPException: + logger.warning("Task queue unavailable: %s", exc) + return HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="Task queue unavailable", + ) -@router.post("", response_model=TaskAccepted, status_code=status.HTTP_202_ACCEPTED) -async def submit_task(submission: TaskSubmission) -> TaskAccepted: - """Queue :func:`example_task` and return its message id.""" - message = example_task.send(submission.payload) - _MESSAGES[message.message_id] = message - return TaskAccepted(task_id=message.message_id, status="PENDING") +def _task_message(task_id: str) -> Message: + """A message with the identity of ``task_id`` (all its result key needs).""" + return example_task.message().copy(message_id=task_id) -@router.get("/{task_id}", response_model=TaskStatus) -async def get_task_status(task_id: str) -> TaskStatus: - """Poll a previously submitted task.""" - message = _MESSAGES.get(task_id) - if message is None: - return TaskStatus(task_id=task_id, status="UNKNOWN") +@router.post( + "", + status_code=status.HTTP_202_ACCEPTED, + responses={503: {"description": "Task queue unavailable"}}, +) +def submit_task( + submission: TaskSubmission, request: Request, response: Response +) -> TaskAccepted: + """Queue :func:`example_task`; ``Location`` points at its status.""" + message = example_task.message(submission.payload) + try: + # The marker first: a fast worker may store the result right away. + result_backend.store_result(message, PENDING_MARKER, TASK_TTL_MS) + example_task.broker.enqueue(message) + except RedisError as exc: + raise _queue_unavailable(exc) from exc + response.headers["Location"] = str( + request.url_for("get_task_status", task_id=message.message_id) + ) + return TaskAccepted(task_id=message.message_id, status="PENDING") + +@router.get( + "/{task_id}", + responses={ + 404: {"description": "Task not found"}, + 503: {"description": "Task queue unavailable"}, + }, +) +def get_task_status(task_id: str) -> TaskStatus: + """Poll a task submitted by any API process, until it expires.""" + try: + uuid.UUID(task_id) + except ValueError: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail="Task not found" + ) from None try: - result = message.get_result(block=False) + result = result_backend.get_result(_task_message(task_id), block=False) except ResultMissing: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail="Task not found" + ) from None + except ResultFailure: + return TaskStatus(task_id=task_id, status="FAILURE") + except RedisError as exc: + raise _queue_unavailable(exc) from exc + if result == PENDING_MARKER: return TaskStatus(task_id=task_id, status="PENDING") return TaskStatus(task_id=task_id, status="SUCCESS", result=result) diff --git a/src/fastapi_fastkit/fragments/features/websocket.py.j2 b/src/fastapi_fastkit/fragments/features/websocket.py.j2 index 779add9..82bfa17 100644 --- a/src/fastapi_fastkit/fragments/features/websocket.py.j2 +++ b/src/fastapi_fastkit/fragments/features/websocket.py.j2 @@ -1,13 +1,29 @@ {% include "header.j2" %} -"""WebSocket endpoint with a broadcast-capable connection manager.""" +"""WebSocket endpoint with a broadcast-capable connection manager. + +:data:`router` serves the WebSocket itself at the application root +(``/ws``); :data:`api_router` holds its HTTP companion and is mounted under +the versioned API prefix (``GET /api/v1/connections``). + +Each text message gets a personal echo (``you wrote: ...``) and is relayed +to every *other* client (``someone wrote: ...``). Binary frames and text +longer than :data:`MAX_MESSAGE_CHARS` are refused with close code 1003 / +1009; however a connection ends, it is removed from the manager. (The +server reads a frame completely before this check: uvicorn caps frames with +``--ws-max-size``, 16 MiB by default; lower it to match.) +""" import logging -from fastapi import APIRouter, WebSocket, WebSocketDisconnect +from fastapi import APIRouter, WebSocket, WebSocketDisconnect, status logger = logging.getLogger(__name__) -router = APIRouter(tags=["WebSocket"]) +router = APIRouter(tags=["websocket"]) +api_router = APIRouter(prefix="/connections", tags=["websocket"]) + +#: Longest text message accepted, in characters. +MAX_MESSAGE_CHARS = 4096 class ConnectionManager: @@ -30,17 +46,19 @@ class ConnectionManager: """Send a message to a single client.""" await websocket.send_text(message) - async def broadcast(self, message: str) -> None: - """Send a message to every connected client. + async def broadcast(self, message: str, exclude: WebSocket | None = None) -> None: + """Send a message to every connected client except ``exclude``. Clients that fail mid-broadcast are dropped rather than aborting the whole fan-out. """ for connection in list(self.active_connections): + if connection is exclude: + continue try: await connection.send_text(message) - except Exception: # pragma: no cover - transport level failure - logger.warning("dropping dead websocket connection") + except Exception: + logger.warning("dropping dead websocket connection", exc_info=True) self.disconnect(connection) @@ -49,19 +67,35 @@ manager = ConnectionManager() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket) -> None: - """Echo the sender and broadcast every message to the other clients.""" + """Echo each text message to its sender and relay it to the other clients.""" await manager.connect(websocket) try: while True: - data = await websocket.receive_text() - await manager.send_personal_message(f"you wrote: {data}", websocket) - await manager.broadcast(f"someone wrote: {data}") + message = await websocket.receive() + if message["type"] == "websocket.disconnect": + break + text = message.get("text") + if text is None: + await websocket.close( + code=status.WS_1003_UNSUPPORTED_DATA, + reason="only text messages are accepted", + ) + break + if len(text) > MAX_MESSAGE_CHARS: + await websocket.close( + code=status.WS_1009_MESSAGE_TOO_BIG, reason="message too long" + ) + break + await manager.send_personal_message(f"you wrote: {text}", websocket) + await manager.broadcast(f"someone wrote: {text}", exclude=websocket) except WebSocketDisconnect: + pass + finally: manager.disconnect(websocket) - await manager.broadcast("a client left the chat") + await manager.broadcast("a client left the chat") -@router.get("/api/v1/ws/connections") +@api_router.get("") async def connection_count() -> dict[str, int]: """How many clients are currently connected.""" return {"active_connections": len(manager.active_connections)} diff --git a/src/fastapi_fastkit/fragments/logging/loguru.py.j2 b/src/fastapi_fastkit/fragments/logging/loguru.py.j2 new file mode 100644 index 0000000..8bf2f80 --- /dev/null +++ b/src/fastapi_fastkit/fragments/logging/loguru.py.j2 @@ -0,0 +1,53 @@ +{% include "header.j2" %} +"""Loguru as the single logging backend. + +:func:`setup_loguru` replaces Loguru's default sink with one honouring +``LOG_LEVEL`` (environment or ``.env``) and routes the standard ``logging`` +module (uvicorn, SQLAlchemy, your own ``logging.getLogger`` calls) into +Loguru, so every line comes out in one format. Log from application code +with:: + + from loguru import logger + + logger.info("order {} created", order_id) +""" + +import inspect +import logging +import sys + +from loguru import logger + +from {{ settings_module }} import settings + + +class InterceptHandler(logging.Handler): + """Forward standard ``logging`` records to Loguru (Loguru's own recipe).""" + + def emit(self, record: logging.LogRecord) -> None: + try: + level: str | int = logger.level(record.levelname).name + except ValueError: + level = record.levelno + + # Find the caller that issued the record, so Loguru reports the + # original module and line instead of this handler. + frame, depth = inspect.currentframe(), 0 + while frame and (depth == 0 or frame.f_code.co_filename == logging.__file__): + frame = frame.f_back + depth += 1 + + logger.opt(depth=depth, exception=record.exc_info).log( + level, record.getMessage() + ) + + +def setup_loguru() -> None: + """Send all logs through Loguru at ``settings.LOG_LEVEL``.""" + logger.remove() + logger.add(sys.stderr, level=settings.LOG_LEVEL.upper(){% if serialize %}, serialize=True{% endif %}) + logging.basicConfig(handlers=[InterceptHandler()], level=0, force=True) + for name in ("uvicorn", "uvicorn.access", "uvicorn.error"): + uvicorn_logger = logging.getLogger(name) + uvicorn_logger.handlers = [] + uvicorn_logger.propagate = True diff --git a/src/fastapi_fastkit/fragments/logging/structured.py.j2 b/src/fastapi_fastkit/fragments/logging/structured.py.j2 index ec21dff..5bc94fc 100644 --- a/src/fastapi_fastkit/fragments/logging/structured.py.j2 +++ b/src/fastapi_fastkit/fragments/logging/structured.py.j2 @@ -6,6 +6,8 @@ Every log record emitted while handling a request carries the same header so a client can quote it in a bug report. Implemented on the standard library alone — no logging dependency needed. +:func:`setup_logging` applies both to the app at ``LOG_LEVEL`` (environment +or ``.env``). """ import contextvars @@ -16,10 +18,13 @@ import uuid from collections.abc import Awaitable, Callable from typing import Any +from fastapi import FastAPI from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from starlette.responses import Response +from {{ settings_module }} import settings + REQUEST_ID_HEADER = "X-Request-ID" #: Set per request by :class:`RequestIDMiddleware`, read by :class:`JsonFormatter`. @@ -86,3 +91,9 @@ def configure_logging(level: str = "INFO") -> None: uvicorn_logger = logging.getLogger(name) uvicorn_logger.handlers = [handler] uvicorn_logger.propagate = False + + +def setup_logging(app: FastAPI) -> None: + """JSON logs at ``settings.LOG_LEVEL`` plus the request-id middleware.""" + configure_logging(settings.LOG_LEVEL.upper()) + app.add_middleware(RequestIDMiddleware) diff --git a/src/fastapi_fastkit/fragments/main.py.j2 b/src/fastapi_fastkit/fragments/main.py.j2 index 800026c..bfd7a64 100644 --- a/src/fastapi_fastkit/fragments/main.py.j2 +++ b/src/fastapi_fastkit/fragments/main.py.j2 @@ -11,15 +11,18 @@ @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[None]: - """Application lifespan handler (startup / shutdown).""" -{% for fragment in lifespan_fragments %} + """Open shared clients on startup and close them on shutdown.""" +{% for fragment in startup_fragments %} {% include fragment %} {% endfor %} yield +{% for fragment in shutdown_fragments %} +{% include fragment %} +{% endfor %} app = FastAPI( - title={{ project_name | tojson }}, + title=settings.PROJECT_NAME, description={{ description | tojson }}, version={{ version | tojson }}, lifespan=lifespan, @@ -30,28 +33,16 @@ app = FastAPI( {% endfor %} -@app.get("/", tags=["Health"]) +@app.get("/", tags=["root"]) async def root() -> dict[str, str]: - return { - "message": {{ ("Welcome to " ~ project_name) | tojson }}, - "status": "healthy", - } + """Welcome message with a pointer to the interactive API docs.""" + return {"message": f"Welcome to {settings.PROJECT_NAME}", "docs": "/docs"} -@app.get("/health", tags=["Health"]) +@app.get("/health", tags=["health"]) async def health_check() -> dict[str, str]: - """Liveness probe — the process is up.""" + """Liveness probe: the process is up. Touches no database or cache.""" return {"status": "ok"} -@app.get("/ready", tags=["Health"]) -async def readiness_check() -> dict[str, str]: - """Readiness probe — the app is ready to serve traffic. - - Extend this with real dependency checks (database ping, cache ping) - before pointing an orchestrator's readiness probe at it. - """ - return {"status": "ready"} - - # fastkit:routes diff --git a/src/fastapi_fastkit/fragments/main/imports/auth.j2 b/src/fastapi_fastkit/fragments/main/imports/auth.j2 new file mode 100644 index 0000000..e298202 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/imports/auth.j2 @@ -0,0 +1 @@ +from {{ auth_module }}.router import router as auth_router diff --git a/src/fastapi_fastkit/fragments/main/imports/caching.j2 b/src/fastapi_fastkit/fragments/main/imports/caching.j2 index b4ae623..89b421b 100644 --- a/src/fastapi_fastkit/fragments/main/imports/caching.j2 +++ b/src/fastapi_fastkit/fragments/main/imports/caching.j2 @@ -1,5 +1 @@ -from fastapi_cache import FastAPICache -from fastapi_cache.backends.redis import RedisBackend -from redis import asyncio as aioredis - from {{ pkg }}.features.cache import router as cache_router diff --git a/src/fastapi_fastkit/fragments/main/imports/cors.j2 b/src/fastapi_fastkit/fragments/main/imports/cors.j2 new file mode 100644 index 0000000..2a6a5cb --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/imports/cors.j2 @@ -0,0 +1 @@ +from fastapi.middleware.cors import CORSMiddleware diff --git a/src/fastapi_fastkit/fragments/main/imports/fastapi_users.j2 b/src/fastapi_fastkit/fragments/main/imports/fastapi_users.j2 deleted file mode 100644 index e1c9eb9..0000000 --- a/src/fastapi_fastkit/fragments/main/imports/fastapi_users.j2 +++ /dev/null @@ -1 +0,0 @@ -# FastAPI-Users setup lives in the dedicated auth module. diff --git a/src/fastapi_fastkit/fragments/main/imports/jwt.j2 b/src/fastapi_fastkit/fragments/main/imports/jwt.j2 deleted file mode 100644 index c27a70b..0000000 --- a/src/fastapi_fastkit/fragments/main/imports/jwt.j2 +++ /dev/null @@ -1,3 +0,0 @@ -from fastapi.security import HTTPBearer # noqa: F401 - -from {{ auth_module }} import auth_settings # noqa: F401 diff --git a/src/fastapi_fastkit/fragments/main/imports/loguru.j2 b/src/fastapi_fastkit/fragments/main/imports/loguru.j2 index 7e7dbf4..0c0585f 100644 --- a/src/fastapi_fastkit/fragments/main/imports/loguru.j2 +++ b/src/fastapi_fastkit/fragments/main/imports/loguru.j2 @@ -1 +1 @@ -from loguru import logger # noqa: F401 +from {{ pkg }}.loguru_config import setup_loguru diff --git a/src/fastapi_fastkit/fragments/main/imports/mongodb.j2 b/src/fastapi_fastkit/fragments/main/imports/mongodb.j2 index cabe2a9..b5f5f0b 100644 --- a/src/fastapi_fastkit/fragments/main/imports/mongodb.j2 +++ b/src/fastapi_fastkit/fragments/main/imports/mongodb.j2 @@ -1 +1 @@ -from motor.motor_asyncio import AsyncIOMotorClient # noqa: F401 +from {{ db_module }} import create_mongo_client diff --git a/src/fastapi_fastkit/fragments/main/imports/oauth2.j2 b/src/fastapi_fastkit/fragments/main/imports/oauth2.j2 deleted file mode 100644 index 5e24871..0000000 --- a/src/fastapi_fastkit/fragments/main/imports/oauth2.j2 +++ /dev/null @@ -1,4 +0,0 @@ -from starlette.middleware.sessions import SessionMiddleware - -from {{ auth_module }} import auth_settings -from {{ auth_module }} import router as auth_router diff --git a/src/fastapi_fastkit/fragments/main/imports/opentelemetry.j2 b/src/fastapi_fastkit/fragments/main/imports/opentelemetry.j2 index 6a995ae..7984806 100644 --- a/src/fastapi_fastkit/fragments/main/imports/opentelemetry.j2 +++ b/src/fastapi_fastkit/fragments/main/imports/opentelemetry.j2 @@ -1,6 +1 @@ -from opentelemetry import trace -from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter -from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor -from opentelemetry.sdk.resources import SERVICE_NAME, Resource -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import BatchSpanProcessor +from {{ pkg }}.telemetry import setup_telemetry diff --git a/src/fastapi_fastkit/fragments/main/imports/pagination.j2 b/src/fastapi_fastkit/fragments/main/imports/pagination.j2 deleted file mode 100644 index b785cab..0000000 --- a/src/fastapi_fastkit/fragments/main/imports/pagination.j2 +++ /dev/null @@ -1,3 +0,0 @@ -from fastapi_pagination import add_pagination - -from {{ pkg }}.features.pagination import router as pagination_router diff --git a/src/fastapi_fastkit/fragments/main/imports/rate_limiting.j2 b/src/fastapi_fastkit/fragments/main/imports/rate_limiting.j2 index 809bb4d..8594e06 100644 --- a/src/fastapi_fastkit/fragments/main/imports/rate_limiting.j2 +++ b/src/fastapi_fastkit/fragments/main/imports/rate_limiting.j2 @@ -1,3 +1 @@ -from slowapi import Limiter, _rate_limit_exceeded_handler -from slowapi.errors import RateLimitExceeded -from slowapi.util import get_remote_address +from {{ pkg }}.rate_limiting import setup_rate_limiting diff --git a/src/fastapi_fastkit/fragments/main/imports/readiness.j2 b/src/fastapi_fastkit/fragments/main/imports/readiness.j2 new file mode 100644 index 0000000..55f8912 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/imports/readiness.j2 @@ -0,0 +1 @@ +from {{ pkg }}.features.readiness import router as readiness_router diff --git a/src/fastapi_fastkit/fragments/main/imports/redis_db.j2 b/src/fastapi_fastkit/fragments/main/imports/redis_db.j2 new file mode 100644 index 0000000..f8dbdb7 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/imports/redis_db.j2 @@ -0,0 +1 @@ +from {{ db_module }} import close_redis diff --git a/src/fastapi_fastkit/fragments/main/imports/session_auth.j2 b/src/fastapi_fastkit/fragments/main/imports/session_auth.j2 deleted file mode 100644 index 5e24871..0000000 --- a/src/fastapi_fastkit/fragments/main/imports/session_auth.j2 +++ /dev/null @@ -1,4 +0,0 @@ -from starlette.middleware.sessions import SessionMiddleware - -from {{ auth_module }} import auth_settings -from {{ auth_module }} import router as auth_router diff --git a/src/fastapi_fastkit/fragments/main/imports/session_middleware.j2 b/src/fastapi_fastkit/fragments/main/imports/session_middleware.j2 new file mode 100644 index 0000000..66d4d83 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/imports/session_middleware.j2 @@ -0,0 +1 @@ +from {{ auth_module }}.middleware import add_session_middleware diff --git a/src/fastapi_fastkit/fragments/main/imports/sqlalchemy.j2 b/src/fastapi_fastkit/fragments/main/imports/sqlalchemy.j2 index 657ac36..4e486dd 100644 --- a/src/fastapi_fastkit/fragments/main/imports/sqlalchemy.j2 +++ b/src/fastapi_fastkit/fragments/main/imports/sqlalchemy.j2 @@ -1,2 +1 @@ -from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine # noqa: F401 -from sqlalchemy.orm import sessionmaker # noqa: F401 +from {{ db_module }} import engine diff --git a/src/fastapi_fastkit/fragments/main/imports/structured_logging.j2 b/src/fastapi_fastkit/fragments/main/imports/structured_logging.j2 index d6343e5..6e8505c 100644 --- a/src/fastapi_fastkit/fragments/main/imports/structured_logging.j2 +++ b/src/fastapi_fastkit/fragments/main/imports/structured_logging.j2 @@ -1 +1 @@ -from {{ pkg }}.logging_config import RequestIDMiddleware, configure_logging +from {{ pkg }}.logging_config import setup_logging diff --git a/src/fastapi_fastkit/fragments/main/imports/websocket.j2 b/src/fastapi_fastkit/fragments/main/imports/websocket.j2 index 320a57b..a08d89a 100644 --- a/src/fastapi_fastkit/fragments/main/imports/websocket.j2 +++ b/src/fastapi_fastkit/fragments/main/imports/websocket.j2 @@ -1 +1 @@ -from {{ pkg }}.features.websocket import router as websocket_router +from {{ pkg }}.features import websocket diff --git a/src/fastapi_fastkit/fragments/main/lifespan/caching.j2 b/src/fastapi_fastkit/fragments/main/lifespan/caching.j2 deleted file mode 100644 index 55bd395..0000000 --- a/src/fastapi_fastkit/fragments/main/lifespan/caching.j2 +++ /dev/null @@ -1,7 +0,0 @@ - # Initialize the fastapi-cache2 Redis backend - redis_client = aioredis.from_url( - os.getenv("REDIS_URL", "redis://localhost:6379/0"), - encoding="utf-8", - decode_responses=False, - ) - FastAPICache.init(RedisBackend(redis_client), prefix="{{ project_slug }}-cache") diff --git a/src/fastapi_fastkit/fragments/main/lifespan/mongodb.j2 b/src/fastapi_fastkit/fragments/main/lifespan/mongodb.j2 deleted file mode 100644 index 220b8a2..0000000 --- a/src/fastapi_fastkit/fragments/main/lifespan/mongodb.j2 +++ /dev/null @@ -1,2 +0,0 @@ - # Initialize MongoDB - # client = AsyncIOMotorClient(settings.MONGODB_URL) diff --git a/src/fastapi_fastkit/fragments/main/lifespan/sqlalchemy.j2 b/src/fastapi_fastkit/fragments/main/lifespan/sqlalchemy.j2 deleted file mode 100644 index 30df08a..0000000 --- a/src/fastapi_fastkit/fragments/main/lifespan/sqlalchemy.j2 +++ /dev/null @@ -1,2 +0,0 @@ - # Initialize database - # await init_db() diff --git a/src/fastapi_fastkit/fragments/main/setup/async_tasks.j2 b/src/fastapi_fastkit/fragments/main/setup/async_tasks.j2 index e6a1098..92ffdec 100644 --- a/src/fastapi_fastkit/fragments/main/setup/async_tasks.j2 +++ b/src/fastapi_fastkit/fragments/main/setup/async_tasks.j2 @@ -1 +1 @@ -app.include_router(tasks_router) +app.include_router(tasks_router, prefix=settings.API_V1_PREFIX) diff --git a/src/fastapi_fastkit/fragments/main/setup/auth.j2 b/src/fastapi_fastkit/fragments/main/setup/auth.j2 new file mode 100644 index 0000000..8a7c3c0 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/setup/auth.j2 @@ -0,0 +1,2 @@ +# Authentication routes (auth package), under the versioned API prefix. +app.include_router(auth_router, prefix=settings.API_V1_PREFIX) diff --git a/src/fastapi_fastkit/fragments/main/setup/caching.j2 b/src/fastapi_fastkit/fragments/main/setup/caching.j2 index f3b5c7e..cc52bb1 100644 --- a/src/fastapi_fastkit/fragments/main/setup/caching.j2 +++ b/src/fastapi_fastkit/fragments/main/setup/caching.j2 @@ -1 +1,2 @@ -app.include_router(cache_router) +# The cache router's lifespan initialises fastapi-cache2 (see features/cache.py). +app.include_router(cache_router, prefix=settings.API_V1_PREFIX) diff --git a/src/fastapi_fastkit/fragments/main/setup/cors.j2 b/src/fastapi_fastkit/fragments/main/setup/cors.j2 index b92c80c..32a957b 100644 --- a/src/fastapi_fastkit/fragments/main/setup/cors.j2 +++ b/src/fastapi_fastkit/fragments/main/setup/cors.j2 @@ -1,11 +1,9 @@ -# CORS: BACKEND_CORS_ORIGINS is a comma-separated list of browser origins, e.g. -# "http://localhost:3000,https://app.example.com". Unset means no cross-origin -# access. "*" allows any origin, but then never with credentials (cookies). -cors_origins = [ - origin.strip().rstrip("/") - for origin in os.getenv("BACKEND_CORS_ORIGINS", "").split(",") - if origin.strip() -] +# CORS: origins come from BACKEND_CORS_ORIGINS (environment or .env), a +# comma-separated list such as "http://localhost:3000,https://app.example.com". +# Empty means no cross-origin access. "*" allows any origin, but then never +# with credentials (cookies, Authorization headers). Added last, so it wraps +# every other middleware. +cors_origins = [origin for origin in settings.all_cors_origins if origin] if cors_origins: app.add_middleware( CORSMiddleware, diff --git a/src/fastapi_fastkit/fragments/main/setup/loguru.j2 b/src/fastapi_fastkit/fragments/main/setup/loguru.j2 new file mode 100644 index 0000000..ed51e46 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/setup/loguru.j2 @@ -0,0 +1 @@ +setup_loguru() diff --git a/src/fastapi_fastkit/fragments/main/setup/oauth2.j2 b/src/fastapi_fastkit/fragments/main/setup/oauth2.j2 deleted file mode 100644 index d091d57..0000000 --- a/src/fastapi_fastkit/fragments/main/setup/oauth2.j2 +++ /dev/null @@ -1,3 +0,0 @@ -# Authlib stores the OAuth state in the session cookie. -app.add_middleware(SessionMiddleware, secret_key=auth_settings.SECRET_KEY) -app.include_router(auth_router) diff --git a/src/fastapi_fastkit/fragments/main/setup/opentelemetry.j2 b/src/fastapi_fastkit/fragments/main/setup/opentelemetry.j2 index c09216b..93684a3 100644 --- a/src/fastapi_fastkit/fragments/main/setup/opentelemetry.j2 +++ b/src/fastapi_fastkit/fragments/main/setup/opentelemetry.j2 @@ -1,19 +1 @@ -# OpenTelemetry tracing — exports over OTLP/HTTP. -# Configure with OTEL_EXPORTER_OTLP_ENDPOINT (default: http://localhost:4318). -_otel_resource = Resource.create( - {SERVICE_NAME: os.getenv("OTEL_SERVICE_NAME", {{ project_slug | tojson }})} -) -_tracer_provider = TracerProvider(resource=_otel_resource) -_tracer_provider.add_span_processor( - BatchSpanProcessor( - OTLPSpanExporter( - endpoint=os.getenv( - "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", - os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318") - + "/v1/traces", - ) - ) - ) -) -trace.set_tracer_provider(_tracer_provider) -FastAPIInstrumentor.instrument_app(app, tracer_provider=_tracer_provider) +setup_telemetry(app) diff --git a/src/fastapi_fastkit/fragments/main/setup/pagination.j2 b/src/fastapi_fastkit/fragments/main/setup/pagination.j2 deleted file mode 100644 index c7aa619..0000000 --- a/src/fastapi_fastkit/fragments/main/setup/pagination.j2 +++ /dev/null @@ -1,2 +0,0 @@ -app.include_router(pagination_router) -add_pagination(app) diff --git a/src/fastapi_fastkit/fragments/main/setup/prometheus.j2 b/src/fastapi_fastkit/fragments/main/setup/prometheus.j2 index 3fb54c3..b96098b 100644 --- a/src/fastapi_fastkit/fragments/main/setup/prometheus.j2 +++ b/src/fastapi_fastkit/fragments/main/setup/prometheus.j2 @@ -1,3 +1,3 @@ # Prometheus metrics on GET /metrics. Instrumented at import time: Starlette # refuses to add middleware once the application has started. -Instrumentator().instrument(app).expose(app) +Instrumentator().instrument(app).expose(app, tags=["monitoring"]) diff --git a/src/fastapi_fastkit/fragments/main/setup/rate_limiting.j2 b/src/fastapi_fastkit/fragments/main/setup/rate_limiting.j2 index 9447aaf..81035b6 100644 --- a/src/fastapi_fastkit/fragments/main/setup/rate_limiting.j2 +++ b/src/fastapi_fastkit/fragments/main/setup/rate_limiting.j2 @@ -1,3 +1,2 @@ -limiter = Limiter(key_func=get_remote_address) -app.state.limiter = limiter -app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) +# Limits every route to settings.RATE_LIMIT_DEFAULT per client (rate_limiting.py). +setup_rate_limiting(app) diff --git a/src/fastapi_fastkit/fragments/main/setup/readiness.j2 b/src/fastapi_fastkit/fragments/main/setup/readiness.j2 new file mode 100644 index 0000000..3d8caa1 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/setup/readiness.j2 @@ -0,0 +1 @@ +app.include_router(readiness_router) diff --git a/src/fastapi_fastkit/fragments/main/setup/session_auth.j2 b/src/fastapi_fastkit/fragments/main/setup/session_auth.j2 deleted file mode 100644 index 5e6e258..0000000 --- a/src/fastapi_fastkit/fragments/main/setup/session_auth.j2 +++ /dev/null @@ -1,6 +0,0 @@ -app.add_middleware( - SessionMiddleware, - secret_key=auth_settings.SECRET_KEY, - max_age=auth_settings.SESSION_MAX_AGE, -) -app.include_router(auth_router) diff --git a/src/fastapi_fastkit/fragments/main/setup/session_middleware.j2 b/src/fastapi_fastkit/fragments/main/setup/session_middleware.j2 new file mode 100644 index 0000000..d0c1678 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/setup/session_middleware.j2 @@ -0,0 +1,2 @@ +# Signed session cookie (SECRET_KEY), installed before CORS so CORS wraps it. +add_session_middleware(app) diff --git a/src/fastapi_fastkit/fragments/main/setup/structured_logging.j2 b/src/fastapi_fastkit/fragments/main/setup/structured_logging.j2 index 7f0b0fb..9fce78d 100644 --- a/src/fastapi_fastkit/fragments/main/setup/structured_logging.j2 +++ b/src/fastapi_fastkit/fragments/main/setup/structured_logging.j2 @@ -1,2 +1 @@ -configure_logging(os.getenv("LOG_LEVEL", "INFO")) -app.add_middleware(RequestIDMiddleware) +setup_logging(app) diff --git a/src/fastapi_fastkit/fragments/main/setup/websocket.j2 b/src/fastapi_fastkit/fragments/main/setup/websocket.j2 index b1158e1..ea7a86f 100644 --- a/src/fastapi_fastkit/fragments/main/setup/websocket.j2 +++ b/src/fastapi_fastkit/fragments/main/setup/websocket.j2 @@ -1 +1,3 @@ -app.include_router(websocket_router) +# The WebSocket endpoint stays at the root (/ws); its HTTP companion is versioned. +app.include_router(websocket.router) +app.include_router(websocket.api_router, prefix=settings.API_V1_PREFIX) diff --git a/src/fastapi_fastkit/fragments/main/shutdown/mongodb.j2 b/src/fastapi_fastkit/fragments/main/shutdown/mongodb.j2 new file mode 100644 index 0000000..31cba99 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/shutdown/mongodb.j2 @@ -0,0 +1 @@ + await app.state.mongo_client.close() diff --git a/src/fastapi_fastkit/fragments/main/shutdown/redis_db.j2 b/src/fastapi_fastkit/fragments/main/shutdown/redis_db.j2 new file mode 100644 index 0000000..3ca40f9 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/shutdown/redis_db.j2 @@ -0,0 +1 @@ + await close_redis() diff --git a/src/fastapi_fastkit/fragments/main/shutdown/sqlalchemy.j2 b/src/fastapi_fastkit/fragments/main/shutdown/sqlalchemy.j2 new file mode 100644 index 0000000..10b5067 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/shutdown/sqlalchemy.j2 @@ -0,0 +1 @@ + await engine.dispose() diff --git a/src/fastapi_fastkit/fragments/main/startup/mongodb.j2 b/src/fastapi_fastkit/fragments/main/startup/mongodb.j2 new file mode 100644 index 0000000..0254cc2 --- /dev/null +++ b/src/fastapi_fastkit/fragments/main/startup/mongodb.j2 @@ -0,0 +1 @@ + app.state.mongo_client = create_mongo_client() diff --git a/src/fastapi_fastkit/fragments/middleware/rate_limiting.py.j2 b/src/fastapi_fastkit/fragments/middleware/rate_limiting.py.j2 new file mode 100644 index 0000000..556e572 --- /dev/null +++ b/src/fastapi_fastkit/fragments/middleware/rate_limiting.py.j2 @@ -0,0 +1,140 @@ +{% include "header.j2" %} +"""Rate limiting: one default limit for every request, stricter limits per route. + +``RATE_LIMIT_DEFAULT`` (for example ``"100/minute"``) applies to every HTTP +request, counted per client address. An endpoint that needs a tighter budget +adds a dependency:: + + @router.post("/login", dependencies=[Depends(RateLimit("5/minute"))]) + +Over the limit the client gets ``429 Too Many Requests`` with a +``Retry-After`` header. A per-route limit counts per route template +(``/items/{item_id}``), so every item shares one budget. + +Clients are counted by address. An IPv6 client usually controls a whole +``/64`` network (its addresses are free to rotate), so IPv6 addresses are +counted per ``/64``; IPv4 addresses are counted one by one. + +Counters live in ``RATE_LIMIT_STORAGE_URI``. ``async+memory://`` counts per +process (the ``limits`` library drops each counter when its window ends, so +memory follows the number of clients seen in one window); with several +workers or replicas use a shared store such as +``async+redis://localhost:6379/0`` (install ``limits[async-redis]``). + +Proxies: the client address is ``request.client.host``. Behind a reverse +proxy or load balancer that is the proxy's address, so every client would +share one budget. Start uvicorn with ``--proxy-headers +--forwarded-allow-ips=`` so the address is taken from +``X-Forwarded-For``, and only trust that header from your own proxy: any +client can send it. + +Built on the ``limits`` library directly: slowapi's ``SlowAPIMiddleware`` +cannot find the endpoints of routers added with ``include_router`` on current +FastAPI versions and silently leaves them unlimited. +""" + +import ipaddress +import math +import time + +from fastapi import FastAPI, HTTPException, Request, status +from limits import RateLimitItem, parse +from limits.aio.strategies import FixedWindowRateLimiter +from limits.storage import storage_from_string +from starlette.responses import JSONResponse +from starlette.types import ASGIApp, Receive, Scope, Send + +from {{ settings_module }} import settings + +TOO_MANY_REQUESTS = "Too many requests" + + +class RateLimiter: + """Counts requests per key in fixed windows.""" + + def __init__(self, storage_uri: str) -> None: + self._storage_uri = storage_uri + self.reset() + + def reset(self) -> None: + """Start over with a fresh storage (clears ``async+memory://`` counters).""" + self._strategy = FixedWindowRateLimiter(storage_from_string(self._storage_uri)) + + async def hit(self, limit: RateLimitItem, *identifiers: str) -> float | None: + """Count one request; return the seconds to wait when over the limit.""" + if await self._strategy.hit(limit, *identifiers): + return None + stats = await self._strategy.get_window_stats(limit, *identifiers) + return max(stats.reset_time - time.time(), 0.0) + + +limiter = RateLimiter(settings.RATE_LIMIT_STORAGE_URI) + + +def _retry_after(seconds: float) -> dict[str, str]: + return {"Retry-After": str(max(math.ceil(seconds), 1))} + + +def client_key(host: str | None) -> str: + """The counter key of a client address: IPv6 per ``/64``, IPv4 as is.""" + if not host: + return "unknown" + try: + address = ipaddress.ip_address(host) + except ValueError: + return host # not an IP address (a test client, a Unix socket) + if isinstance(address, ipaddress.IPv6Address): + if address.ipv4_mapped is not None: + return str(address.ipv4_mapped) + return str(ipaddress.IPv6Network(f"{address}/64", strict=False)) + return str(address) + + +class RateLimitMiddleware: + """Apply one limit to every HTTP request (WebSocket traffic is not counted).""" + + def __init__(self, app: ASGIApp, limit: RateLimitItem) -> None: + self.app = app + self.limit = limit + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + client = scope.get("client") + retry_after = await limiter.hit( + self.limit, "default", client_key(client[0] if client else None) + ) + if retry_after is None: + await self.app(scope, receive, send) + return + response = JSONResponse( + {"detail": TOO_MANY_REQUESTS}, + status_code=status.HTTP_429_TOO_MANY_REQUESTS, + headers=_retry_after(retry_after), + ) + await response(scope, receive, send) + + +class RateLimit: + """Dependency enforcing a stricter limit on one endpoint, per client.""" + + def __init__(self, limit: str) -> None: + self.limit = parse(limit) + + async def __call__(self, request: Request) -> None: + route = request.scope.get("route") + path = getattr(route, "path", request.url.path) + address = client_key(request.client.host if request.client else None) + retry_after = await limiter.hit(self.limit, path, address) + if retry_after is not None: + raise HTTPException( + status_code=status.HTTP_429_TOO_MANY_REQUESTS, + detail=TOO_MANY_REQUESTS, + headers=_retry_after(retry_after), + ) + + +def setup_rate_limiting(app: FastAPI) -> None: + """Limit every request to ``settings.RATE_LIMIT_DEFAULT`` per client.""" + app.add_middleware(RateLimitMiddleware, limit=parse(settings.RATE_LIMIT_DEFAULT)) diff --git a/src/fastapi_fastkit/fragments/migrations/alembic_ini.j2 b/src/fastapi_fastkit/fragments/migrations/alembic_ini.j2 index 650cd24..c087aa6 100644 --- a/src/fastapi_fastkit/fragments/migrations/alembic_ini.j2 +++ b/src/fastapi_fastkit/fragments/migrations/alembic_ini.j2 @@ -3,8 +3,8 @@ script_location = alembic prepend_sys_path = . path_separator = os -# The URL is read from the DATABASE_URL environment variable in alembic/env.py; -# this value is only the fallback. +# alembic/env.py replaces this URL with DATABASE_URL from the project settings +# (environment or .env); it is only documentation. sqlalchemy.url = {{ database_url }} [loggers] diff --git a/src/fastapi_fastkit/fragments/migrations/env.py.j2 b/src/fastapi_fastkit/fragments/migrations/env.py.j2 index 525b0a7..8f0fa1a 100644 --- a/src/fastapi_fastkit/fragments/migrations/env.py.j2 +++ b/src/fastapi_fastkit/fragments/migrations/env.py.j2 @@ -1,12 +1,12 @@ {% include "header.j2" %} """Alembic environment, wired for SQLAlchemy's async engine. -``DATABASE_URL`` overrides the ``sqlalchemy.url`` in ``alembic.ini`` so the -same revisions run against local, CI and production databases. +The URL comes from the project settings (``DATABASE_URL`` in the environment +or ``.env``), not from ``alembic.ini``, so the same revisions run against +local, CI and production databases. """ import asyncio -import os from logging.config import fileConfig from alembic import context @@ -14,21 +14,25 @@ from sqlalchemy import pool from sqlalchemy.engine import Connection from sqlalchemy.ext.asyncio import async_engine_from_config +{% for module in model_modules | default([]) | sort %} +{% if loop.first %} +# Model modules register their tables on Base.metadata when imported. +{% endif %} +import {{ module }} # noqa: F401 +{% endfor %} +{{ format_imports(['from ' ~ db_module ~ ' import Base', 'from ' ~ settings_module ~ ' import settings']) }} + config = context.config if config.config_file_name is not None: fileConfig(config.config_file_name) -database_url = os.getenv("DATABASE_URL") -if database_url: - config.set_main_option("sqlalchemy.url", database_url) +# ``%`` is configparser's interpolation character. +config.set_main_option("sqlalchemy.url", settings.DATABASE_URL.replace("%", "%%")) -# Import your declarative Base and models here so ``--autogenerate`` can see -# them, then point ``target_metadata`` at ``Base.metadata``: -# -# from {{ db_module }} import Base -# target_metadata = Base.metadata -target_metadata = None +# Import every module that defines models (subclasses of ``Base``) above, so +# ``alembic revision --autogenerate`` can see their tables. +target_metadata = Base.metadata def run_migrations_offline() -> None: diff --git a/src/fastapi_fastkit/fragments/migrations/initial_revision.py.j2 b/src/fastapi_fastkit/fragments/migrations/initial_revision.py.j2 index ccbfabe..3904776 100644 --- a/src/fastapi_fastkit/fragments/migrations/initial_revision.py.j2 +++ b/src/fastapi_fastkit/fragments/migrations/initial_revision.py.j2 @@ -8,13 +8,55 @@ Create Date: generated by FastAPI-fastkit from collections.abc import Sequence +{% if users_table %} +import sqlalchemy as sa +from alembic import op +{% if users_table == "fastapi_users" %} +from fastapi_users_db_sqlalchemy.generics import GUID +{% endif %} +{% else %} import sqlalchemy as sa # noqa: F401 from alembic import op # noqa: F401 +{% endif %} revision: str = {{ revision_id | tojson }} down_revision: str | None = None branch_labels: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None = None +{% if users_table %} + + +def upgrade() -> None: + """Create the ``users`` table of the authentication package.""" + op.create_table( + "users", +{% if users_table == "fastapi_users" %} + sa.Column("id", GUID(), nullable=False), + sa.Column("email", sa.String(length=320), nullable=False), + sa.Column("hashed_password", sa.String(length=1024), nullable=False), + sa.Column("is_active", sa.Boolean(), nullable=False), + sa.Column("is_superuser", sa.Boolean(), nullable=False), + sa.Column("is_verified", sa.Boolean(), nullable=False), +{% else %} + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("email", sa.String(length=320), nullable=False), + sa.Column("full_name", sa.String(length=255), nullable=True), + sa.Column("hashed_password", sa.String(length=255), nullable=False), + sa.Column("is_active", sa.Boolean(), server_default=sa.true(), nullable=False), +{% if users_table == "session" %} + sa.Column("session_version", sa.Integer(), server_default="0", nullable=False), +{% endif %} +{% endif %} + sa.PrimaryKeyConstraint("id"), + ) + op.create_index(op.f("ix_users_email"), "users", ["email"], unique=True) + + +def downgrade() -> None: + """Drop the ``users`` table.""" + op.drop_index(op.f("ix_users_email"), table_name="users") + op.drop_table("users") +{% else %} def upgrade() -> None: @@ -25,3 +67,4 @@ def upgrade() -> None: def downgrade() -> None: """Nothing to undo for the baseline revision.""" pass +{% endif %} diff --git a/src/fastapi_fastkit/fragments/monitoring/telemetry.py.j2 b/src/fastapi_fastkit/fragments/monitoring/telemetry.py.j2 new file mode 100644 index 0000000..6134f06 --- /dev/null +++ b/src/fastapi_fastkit/fragments/monitoring/telemetry.py.j2 @@ -0,0 +1,34 @@ +{% include "header.j2" %} +"""OpenTelemetry tracing exported over OTLP/HTTP. + +Configure with ``OTEL_SERVICE_NAME``, ``OTEL_EXPORTER_OTLP_ENDPOINT`` and +``OTEL_TRACES_EXPORTER`` (environment or ``.env``); spans go to +``/v1/traces``. Spans are batched in a background thread, so an +unreachable collector never blocks a request. ``OTEL_TRACES_EXPORTER=none`` +keeps the instrumentation but exports nothing (the generated tests run that +way, so no export retries delay the end of the run). +""" + +from fastapi import FastAPI +from opentelemetry import trace +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor +from opentelemetry.sdk.resources import SERVICE_NAME, Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor + +from {{ settings_module }} import settings + + +def setup_telemetry(app: FastAPI) -> TracerProvider: + """Install a tracer provider and instrument every request of ``app``.""" + provider = TracerProvider( + resource=Resource.create({SERVICE_NAME: settings.OTEL_SERVICE_NAME}) + ) + if settings.OTEL_TRACES_EXPORTER != "none": + endpoint = settings.OTEL_EXPORTER_OTLP_ENDPOINT.rstrip("/") + "/v1/traces" + exporter = OTLPSpanExporter(endpoint=endpoint) + provider.add_span_processor(BatchSpanProcessor(exporter)) + trace.set_tracer_provider(provider) + FastAPIInstrumentor.instrument_app(app, tracer_provider=provider) + return provider diff --git a/src/fastapi_fastkit/fragments/tasks/celery_worker.py.j2 b/src/fastapi_fastkit/fragments/tasks/celery_worker.py.j2 index 1954a92..59dde1b 100644 --- a/src/fastapi_fastkit/fragments/tasks/celery_worker.py.j2 +++ b/src/fastapi_fastkit/fragments/tasks/celery_worker.py.j2 @@ -4,18 +4,24 @@ Run the worker next to the API with:: celery -A {{ pkg }}.worker.celery_app worker --loglevel=info + +Configure the broker and result backend with ``CELERY_BROKER_URL`` and +``CELERY_RESULT_BACKEND`` (environment or ``.env``). """ -import os from typing import Any from celery import Celery from celery.utils.log import get_task_logger -BROKER_URL = os.getenv("CELERY_BROKER_URL", "redis://localhost:6379/0") -RESULT_BACKEND = os.getenv("CELERY_RESULT_BACKEND", BROKER_URL) +from {{ settings_module }} import settings -celery_app = Celery("{{ project_slug }}", broker=BROKER_URL, backend=RESULT_BACKEND) +celery_app = Celery( + "{{ project_slug }}", + broker=settings.CELERY_BROKER_URL, + # Results go to the broker unless CELERY_RESULT_BACKEND names another store. + backend=settings.CELERY_RESULT_BACKEND or settings.CELERY_BROKER_URL, +) celery_app.conf.update( task_serializer="json", result_serializer="json", diff --git a/src/fastapi_fastkit/fragments/tasks/dramatiq_worker.py.j2 b/src/fastapi_fastkit/fragments/tasks/dramatiq_worker.py.j2 index 4935fa9..07a84d9 100644 --- a/src/fastapi_fastkit/fragments/tasks/dramatiq_worker.py.j2 +++ b/src/fastapi_fastkit/fragments/tasks/dramatiq_worker.py.j2 @@ -4,22 +4,40 @@ Run the worker next to the API with:: dramatiq {{ pkg }}.worker + +Configure the broker with ``DRAMATIQ_BROKER_URL`` (environment or ``.env``). +Results (and the API's task status) are kept in the same Redis for +:data:`TASK_TTL_MS` milliseconds. """ import logging -import os from typing import Any import dramatiq +import redis from dramatiq.brokers.redis import RedisBroker from dramatiq.results import Results from dramatiq.results.backends import RedisBackend -BROKER_URL = os.getenv("DRAMATIQ_BROKER_URL", "redis://localhost:6379/0") +from {{ settings_module }} import settings + +#: How long a task's status and result stay readable, in milliseconds. +TASK_TTL_MS = 60 * 60 * 1000 + +#: An unreachable Redis fails after this many seconds instead of hanging. +REDIS_CONNECT_TIMEOUT_SECONDS = 5 + + +def _redis_client() -> redis.Redis: + return redis.Redis.from_url( + settings.DRAMATIQ_BROKER_URL, + socket_connect_timeout=REDIS_CONNECT_TIMEOUT_SECONDS, + ) + -result_backend = RedisBackend(url=BROKER_URL) -broker = RedisBroker(url=BROKER_URL) -broker.add_middleware(Results(backend=result_backend)) +result_backend = RedisBackend(client=_redis_client()) +broker = RedisBroker(client=_redis_client()) +broker.add_middleware(Results(backend=result_backend, result_ttl=TASK_TTL_MS)) dramatiq.set_broker(broker) logger = logging.getLogger(__name__) diff --git a/src/fastapi_fastkit/fragments/test/_auth_settings_tests.j2 b/src/fastapi_fastkit/fragments/test/_auth_settings_tests.j2 new file mode 100644 index 0000000..4737b8c --- /dev/null +++ b/src/fastapi_fastkit/fragments/test/_auth_settings_tests.j2 @@ -0,0 +1,43 @@ + + +@pytest.mark.parametrize("environment", ["staging", "production"]) +def test_outside_development_a_missing_secret_key_is_refused( + monkeypatch: pytest.MonkeyPatch, environment: str +) -> None: + monkeypatch.delenv("SECRET_KEY", raising=False) + + with pytest.raises(ValidationError, match=f"ENVIRONMENT={environment}"): + Settings(_env_file=None, ENVIRONMENT=environment) + + +@pytest.mark.parametrize("environment", ["staging", "production"]) +@pytest.mark.parametrize("key", ["changethis", "your-secret-key-here"]) +def test_outside_development_public_example_keys_are_refused( + environment: str, key: str +) -> None: + with pytest.raises(ValidationError, match="SECRET_KEY"): + Settings(_env_file=None, ENVIRONMENT=environment, SECRET_KEY=key) + + +@pytest.mark.parametrize("environment", ["staging", "production"]) +def test_outside_development_a_short_key_is_refused(environment: str) -> None: + with pytest.raises(ValidationError, match="at least 32 bytes"): + Settings(_env_file=None, ENVIRONMENT=environment, SECRET_KEY="secret") + + +@pytest.mark.parametrize("environment", ["staging", "production"]) +def test_outside_development_a_real_key_starts(environment: str) -> None: + key = secrets.token_urlsafe(32) + + configured = Settings(_env_file=None, ENVIRONMENT=environment, SECRET_KEY=key) + + assert configured.SECRET_KEY == key + + +@pytest.mark.filterwarnings("ignore:SECRET_KEY is a public example value") +def test_development_starts_with_an_example_key() -> None: + configured = Settings( + _env_file=None, ENVIRONMENT="development", SECRET_KEY="changethis" + ) + + assert configured.SECRET_KEY == "changethis" diff --git a/src/fastapi_fastkit/fragments/test/_auth_store_fixtures.j2 b/src/fastapi_fastkit/fragments/test/_auth_store_fixtures.j2 new file mode 100644 index 0000000..c16baa4 --- /dev/null +++ b/src/fastapi_fastkit/fragments/test/_auth_store_fixtures.j2 @@ -0,0 +1,137 @@ +{# + Fixtures shared by the JWT and Session-based auth tests: ``api`` (a + TestClient on an isolated account store) and ``deactivate``. The including + test module imports what is used here; see test_auth_jwt.py.j2. +#} +{% if backend == "sql" %} +@pytest.fixture +def engine() -> AsyncEngine: + """A fresh in-memory SQLite database; the configured one is never touched.""" + return create_async_engine("sqlite+aiosqlite://", poolclass=StaticPool) + + +@pytest.fixture +def sessions(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]: + return async_sessionmaker(engine, expire_on_commit=False) + + +@pytest.fixture +def api( + engine: AsyncEngine, + sessions: async_sessionmaker[AsyncSession], + monkeypatch: pytest.MonkeyPatch, +) -> Iterator[TestClient]: + async def get_test_db() -> AsyncIterator[AsyncSession]: + async with sessions() as session: + yield session + + async def create_tables() -> None: + async with engine.begin() as connection: + await connection.run_sync(Base.metadata.create_all, tables=[User.__table__]) +{% if create_tables %} + + async def skip_startup_ddl() -> None: + """The startup hook would create the table in the configured database.""" + + monkeypatch.setattr(auth_routes, "create_user_table", skip_startup_ddl) +{% endif %} + + app.dependency_overrides[get_db] = get_test_db + try: + with TestClient(app) as client: + client.portal.call(create_tables) + yield client + client.portal.call(engine.dispose) + finally: + app.dependency_overrides.pop(get_db, None) + + +@pytest.fixture +def deactivate( + api: TestClient, sessions: async_sessionmaker[AsyncSession] +) -> Callable[[str], None]: + async def run(user_id: str) -> None: + async with sessions() as session: + assert await UserRepository(session).set_active(user_id, False) + + return lambda user_id: api.portal.call(run, user_id) +{% else %} +{% set repo_type = "FakeUserRepository" if backend == "mongo" else "UserRepository" %} +{% if backend == "mongo" %} +class FakeUserRepository: + """Dict-backed stand-in for the MongoDB repository (no server needed).""" + + def __init__(self) -> None: + self.users: dict[str, User] = {} + + async def get(self, user_id: str) -> User | None: + return self.users.get(user_id) + + async def get_by_email(self, email: str) -> User | None: + email = email.lower() + return next((u for u in self.users.values() if u.email == email), None) + + async def add( + self, *, email: str, hashed_password: str, full_name: str | None = None + ) -> User: + if await self.get_by_email(email) is not None: + raise EmailAlreadyRegisteredError(email) + user = User( + id=str(ObjectId()), + email=email.lower(), + hashed_password=hashed_password, + full_name=full_name, + ) + self.users[user.id] = user + return user + + async def set_active(self, user_id: str, active: bool) -> bool: + user = self.users.get(user_id) + if user is None: + return False + user.is_active = active + return True +{% if auth_kind == "session" %} + + async def revoke_sessions(self, user_id: str) -> None: + user = self.users.get(user_id) + if user is not None: + user.session_version += 1 +{% endif %} + + +@pytest.fixture +def users() -> FakeUserRepository: + return FakeUserRepository() +{% else %} +@pytest.fixture +def users() -> UserRepository: + """A fresh store per test instead of the process-wide one.""" + return UserRepository() +{% endif %} + + +@pytest.fixture +def api(users: {{ repo_type }}) -> Iterator[TestClient]: + app.dependency_overrides[get_user_repository] = lambda: users + try: + with TestClient(app) as client: + yield client + finally: + app.dependency_overrides.pop(get_user_repository, None) + + +@pytest.fixture +def deactivate(api: TestClient, users: {{ repo_type }}) -> Callable[[str], None]: + return lambda user_id: api.portal.call(users.set_active, user_id, False) +{% endif %} +{% if rate_limit %} + + +@pytest.fixture(autouse=True) +def fresh_limits() -> Iterator[None]: + """Start and end with empty rate-limit counters.""" + limiter.reset() + yield + limiter.reset() +{% endif %} diff --git a/src/fastapi_fastkit/fragments/test/conftest_root.py.j2 b/src/fastapi_fastkit/fragments/test/conftest_root.py.j2 new file mode 100644 index 0000000..3cf506e --- /dev/null +++ b/src/fastapi_fastkit/fragments/test/conftest_root.py.j2 @@ -0,0 +1,42 @@ +{% include "header.j2" %} +"""Test-run isolation, loaded by pytest before ``tests/conftest.py``. + +The settings are read when the application is first imported, so these +overrides are set before any test module imports it. The values in ``.env`` +are what the application uses outside of tests. +""" + +import os +{% if rate_limit %} +from collections.abc import Iterator + +import pytest +{% endif %} +{% if sql %} + +# A private in-memory SQLite database instead of DATABASE_URL: starting the +# app in a test never creates tables or files in the configured database. +os.environ["DATABASE_URL"] = "sqlite+aiosqlite://" +{% endif %} +{% if otel %} + +# No collector during tests: spans are recorded but not exported, so the +# run does not wait for export retries at exit. +os.environ["OTEL_TRACES_EXPORTER"] = "none" +{% endif %} +{% if rate_limit %} + +# Rate-limit counters stay in this process, never in a shared store. +os.environ["RATE_LIMIT_STORAGE_URI"] = "async+memory://" + + +@pytest.fixture(autouse=True) +def fresh_rate_limits() -> Iterator[None]: + """Every test starts with empty rate-limit counters.""" + # Imported here, after the overrides above are in place. + from {{ pkg }}.rate_limiting import limiter + + limiter.reset() + yield + limiter.reset() +{% endif %} diff --git a/src/fastapi_fastkit/fragments/test/pytest_ini.j2 b/src/fastapi_fastkit/fragments/test/pytest_ini.j2 index 39cd5d4..a710a41 100644 --- a/src/fastapi_fastkit/fragments/test/pytest_ini.j2 +++ b/src/fastapi_fastkit/fragments/test/pytest_ini.j2 @@ -5,6 +5,12 @@ python_files = test_*.py python_classes = Test* python_functions = test_* asyncio_mode = auto +asyncio_default_fixture_loop_scope = function +# Starlette's TestClient prefers httpx2 (installed with the test tools) and +# warns when it falls back to httpx; only that advisory notice (a UserWarning +# subclass) is silenced, as in the templates' own pytest configuration. +filterwarnings = + ignore:Using `httpx` with `starlette.testclient` is deprecated:starlette.exceptions.StarletteDeprecationWarning {% if with_coverage %} [coverage:run] diff --git a/src/fastapi_fastkit/fragments/test/test_auth_fastapi_users.py.j2 b/src/fastapi_fastkit/fragments/test/test_auth_fastapi_users.py.j2 new file mode 100644 index 0000000..a1a31d1 --- /dev/null +++ b/src/fastapi_fastkit/fragments/test/test_auth_fastapi_users.py.j2 @@ -0,0 +1,296 @@ +{% include "header.j2" %} +"""FastAPI-Users: register, JWT login / logout and ``/users/me``. + +Every test runs on its own SQLite database (in memory, or a file in the +test's temporary directory), so nothing touches the configured one. Status +codes are the library's: bad credentials and an already registered email +answer 400 with an error code. +""" + +import logging +import secrets +import threading +import uuid +from collections.abc import AsyncIterator, Iterator +from pathlib import Path +from typing import Any + +import pytest +from fastapi.testclient import TestClient +{% if rate_limit %} +from limits import parse +{% endif %} +from pydantic import ValidationError +from sqlalchemy.ext.asyncio import ( + AsyncEngine, + AsyncSession, + async_sessionmaker, + create_async_engine, +) +from sqlalchemy.pool import StaticPool + +{% set first_party = [ + "from " ~ main_module ~ " import app", + "from " ~ auth_module ~ ".models import User", + "from " ~ auth_module ~ ".users import UserDatabase", + "from " ~ db_module ~ " import Base, get_db", + "from " ~ settings_module ~ " import Settings, settings", +] %} +{% if create_tables %} +{% set first_party = first_party + ["from " ~ auth_module ~ " import router as auth_routes"] %} +{% endif %} +{% if rate_limit %} +{% set first_party = first_party + ["from " ~ pkg ~ ".rate_limiting import limiter"] %} +{% endif %} +{{ format_imports(first_party) }} + +REGISTER_URL = f"{settings.API_V1_PREFIX}/auth/register" +LOGIN_URL = f"{settings.API_V1_PREFIX}/auth/jwt/login" +LOGOUT_URL = f"{settings.API_V1_PREFIX}/auth/jwt/logout" +ME_URL = f"{settings.API_V1_PREFIX}/users/me" + +EMAIL = "alice@example.com" +PASSWORD = "correct-horse-battery" + + +@pytest.fixture +def engine() -> AsyncEngine: + """A fresh in-memory SQLite database; the configured one is never touched.""" + return create_async_engine("sqlite+aiosqlite://", poolclass=StaticPool) + + +@pytest.fixture +def sessions(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]: + return async_sessionmaker(engine, expire_on_commit=False) + + +@pytest.fixture +def api( + engine: AsyncEngine, + sessions: async_sessionmaker[AsyncSession], + monkeypatch: pytest.MonkeyPatch, +) -> Iterator[TestClient]: + async def get_test_db() -> AsyncIterator[AsyncSession]: + async with sessions() as session: + yield session + + async def create_tables() -> None: + async with engine.begin() as connection: + await connection.run_sync(Base.metadata.create_all, tables=[User.__table__]) +{% if create_tables %} + + async def skip_startup_ddl() -> None: + """The startup hook would create the table in the configured database.""" + + monkeypatch.setattr(auth_routes, "create_user_table", skip_startup_ddl) +{% endif %} + + app.dependency_overrides[get_db] = get_test_db + try: + with TestClient(app) as client: + client.portal.call(create_tables) + yield client + client.portal.call(engine.dispose) + finally: + app.dependency_overrides.pop(get_db, None) +{% if rate_limit %} + + +@pytest.fixture(autouse=True) +def fresh_limits() -> Iterator[None]: + """Start and end with empty rate-limit counters.""" + limiter.reset() + yield + limiter.reset() +{% endif %} + + +def register(api: TestClient) -> dict: + response = api.post(REGISTER_URL, json={"email": EMAIL, "password": PASSWORD}) + assert response.status_code == 201, response.text + return response.json() + + +def log_in(api: TestClient, password: str = PASSWORD) -> Any: + return api.post(LOGIN_URL, data={"username": EMAIL, "password": password}) + + +def test_register_creates_an_active_account(api: TestClient) -> None: + body = register(api) + + assert body["email"] == EMAIL + assert body["is_active"] is True + assert body["is_superuser"] is False + assert "password" not in body and "hashed_password" not in body + + +def test_duplicate_email_is_rejected(api: TestClient) -> None: + register(api) + + response = api.post(REGISTER_URL, json={"email": EMAIL, "password": PASSWORD}) + + assert response.status_code == 400 + assert response.json() == {"detail": "REGISTER_USER_ALREADY_EXISTS"} + + +def test_a_lost_registration_race_is_the_documented_400( + api: TestClient, monkeypatch: pytest.MonkeyPatch +) -> None: + """The library's email check passed, the unique index refuses the insert.""" + register(api) + + async def nobody(self: UserDatabase, email: str) -> None: + return None + + monkeypatch.setattr(UserDatabase, "get_by_email", nobody) + response = api.post(REGISTER_URL, json={"email": EMAIL, "password": PASSWORD}) + + assert response.status_code == 400 + assert response.json() == {"detail": "REGISTER_USER_ALREADY_EXISTS"} + + +@pytest.fixture +def file_api(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[TestClient]: + """Like ``api``, on a database file, so requests use separate connections.""" + engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'users.db'}") + sessions = async_sessionmaker(engine, expire_on_commit=False) + + async def get_test_db() -> AsyncIterator[AsyncSession]: + async with sessions() as session: + yield session + + async def create_tables() -> None: + async with engine.begin() as connection: + await connection.run_sync(Base.metadata.create_all, tables=[User.__table__]) +{% if create_tables %} + + async def skip_startup_ddl() -> None: + """The startup hook would create the table in the configured database.""" + + monkeypatch.setattr(auth_routes, "create_user_table", skip_startup_ddl) +{% endif %} + + app.dependency_overrides[get_db] = get_test_db + try: + with TestClient(app, raise_server_exceptions=False) as client: + client.portal.call(create_tables) + yield client + client.portal.call(engine.dispose) + finally: + app.dependency_overrides.pop(get_db, None) + + +def test_concurrent_registrations_of_one_email( + file_api: TestClient, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + """One succeeds, the others get the library's 400; no 500, nothing leaks.""" + # Below RATE_LIMIT_AUTH (5/minute by default), so no attempt gets a 429. + attempts = 4 + checked = threading.Barrier(attempts, timeout=30) + + async def nobody_yet(self: UserDatabase, email: str) -> None: + # Every request passes the library's "already registered?" check, + # as simultaneous requests do: the unique index decides. + return None + + monkeypatch.setattr(UserDatabase, "get_by_email", nobody_yet) + statuses: list[int] = [] + lock = threading.Lock() + + def attempt() -> None: + try: + checked.wait() + except threading.BrokenBarrierError: + pass + response = file_api.post( + REGISTER_URL, json={"email": EMAIL, "password": PASSWORD} + ) + with lock: + statuses.append(response.status_code) + + # INFO and above: what a server logs (driver DEBUG output is opt-in). + caplog.set_level(logging.INFO) + threads = [threading.Thread(target=attempt) for _ in range(attempts)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert sorted(statuses) == [201] + [400] * (attempts - 1) + assert "$argon2" not in caplog.text + assert EMAIL not in caplog.text + + +def test_the_engine_keeps_statement_parameters_out_of_errors() -> None: + from {{ db_module }} import engine as app_engine + + assert app_engine.sync_engine.hide_parameters is True + + +def test_login_and_profile(api: TestClient) -> None: + register(api) + + response = log_in(api) + + assert response.status_code == 200 + body = response.json() + assert body["token_type"] == "bearer" + headers = {"Authorization": f"Bearer {body['access_token']}"} + assert api.get(ME_URL, headers=headers).json()["email"] == EMAIL + assert api.post(LOGOUT_URL, headers=headers).status_code == 204 + + +def test_wrong_password_is_rejected(api: TestClient) -> None: + register(api) + + response = log_in(api, password="wrong-password") + + assert response.status_code == 400 + assert response.json() == {"detail": "LOGIN_BAD_CREDENTIALS"} + + +@pytest.mark.parametrize("headers", [{}, {"Authorization": "Bearer not-a-jwt"}]) +def test_profile_requires_a_valid_token( + api: TestClient, headers: dict[str, str] +) -> None: + assert api.get(ME_URL, headers=headers).status_code == 401 + + +def test_inactive_account_cannot_log_in( + api: TestClient, sessions: async_sessionmaker[AsyncSession] +) -> None: + user_id = uuid.UUID(register(api)["id"]) + token = log_in(api).json()["access_token"] + + async def deactivate() -> None: + async with sessions() as session: + user = await session.get(User, user_id) + assert user is not None + user.is_active = False + await session.commit() + + api.portal.call(deactivate) + + assert log_in(api).status_code == 400 + headers = {"Authorization": f"Bearer {token}"} + assert api.get(ME_URL, headers=headers).status_code == 401 + + +def test_swagger_authorize_uses_the_login_endpoint(api: TestClient) -> None: + schemes = api.get("/openapi.json").json()["components"]["securitySchemes"] + + assert schemes["OAuth2PasswordBearer"]["flows"]["password"]["tokenUrl"] == LOGIN_URL +{% if rate_limit %} + + +def test_login_has_a_stricter_rate_limit(api: TestClient) -> None: + attempts = parse(settings.RATE_LIMIT_AUTH).amount + + statuses = [log_in(api).status_code for _ in range(attempts)] + + assert set(statuses) == {400} + assert log_in(api).status_code == 429 +{% endif %} +{% include "test/_auth_settings_tests.j2" %} diff --git a/src/fastapi_fastkit/fragments/test/test_auth_jwt.py.j2 b/src/fastapi_fastkit/fragments/test/test_auth_jwt.py.j2 new file mode 100644 index 0000000..58f5b40 --- /dev/null +++ b/src/fastapi_fastkit/fragments/test/test_auth_jwt.py.j2 @@ -0,0 +1,298 @@ +{% include "header.j2" %} +"""OAuth2 password flow with JWT access tokens. + +Every test runs on its own account store ({% if backend == "sql" %}an in-memory SQLite database{% elif backend == "mongo" %}a dict-backed fake of the MongoDB repository{% else %}a fresh in-memory store{% endif %}), +so nothing touches a configured database and no network is used. +""" + +import secrets +from collections.abc import {% if backend == "sql" %}AsyncIterator, {% endif %}Callable, Iterator + +import jwt +import pytest +{% if backend == "mongo" %} +from bson import ObjectId +{% endif %} +from fastapi.testclient import TestClient +{% if rate_limit %} +from limits import parse +{% endif %} +from pydantic import ValidationError +{% if backend == "mongo" %} +from pymongo import AsyncMongoClient +from pymongo.errors import PyMongoError +{% endif %} +{% if backend == "sql" %} +from sqlalchemy.ext.asyncio import ( + AsyncEngine, + AsyncSession, + async_sessionmaker, + create_async_engine, +) +from sqlalchemy.pool import StaticPool +{% endif %} + +{% set first_party = [ + "from " ~ main_module ~ " import app", + "from " ~ settings_module ~ " import Settings, settings", +] %} +{% if backend != "memory" %} +{% set first_party = first_party + ["from " ~ auth_module ~ ".models import User"] %} +{% endif %} +{% if backend == "sql" %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".repository import UserRepository", + "from " ~ db_module ~ " import Base, get_db", +] %} +{% if create_tables %} +{% set first_party = first_party + ["from " ~ auth_module ~ " import router as auth_routes"] %} +{% endif %} +{% elif backend == "mongo" %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".dependencies import get_user_repository", + "from " ~ auth_module ~ ".repository import EmailAlreadyRegisteredError, UserRepository", +] %} +{% else %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".dependencies import get_user_repository", + "from " ~ auth_module ~ ".repository import UserRepository", +] %} +{% endif %} +{% if rate_limit %} +{% set first_party = first_party + ["from " ~ pkg ~ ".rate_limiting import limiter"] %} +{% endif %} +{{ format_imports(first_party) }} + +REGISTER_URL = f"{settings.API_V1_PREFIX}/auth/register" +TOKEN_URL = f"{settings.API_V1_PREFIX}/auth/token" +ME_URL = f"{settings.API_V1_PREFIX}/users/me" + +EMAIL = "alice@example.com" +PASSWORD = "correct-horse-battery" + + +{% include "test/_auth_store_fixtures.j2" %} + + +def register(api: TestClient, email: str = EMAIL, password: str = PASSWORD) -> dict: + response = api.post(REGISTER_URL, json={"email": email, "password": password}) + assert response.status_code == 201, response.text + return response.json() + + +def request_token(api: TestClient, password: str = PASSWORD) -> str: + response = api.post(TOKEN_URL, data={"username": EMAIL, "password": password}) + assert response.status_code == 200, response.text + return response.json()["access_token"] + + +def bearer(token: str) -> dict[str, str]: + return {"Authorization": f"Bearer {token}"} + + +def test_register_returns_201_with_location(api: TestClient) -> None: + response = api.post( + REGISTER_URL, + json={"email": "Alice@Example.com", "password": PASSWORD, "full_name": "Alice"}, + ) + + assert response.status_code == 201 + body = response.json() + assert body["email"] == EMAIL + assert body["is_active"] is True + assert "password" not in body and "hashed_password" not in body + assert response.headers["Location"].endswith( + f"{settings.API_V1_PREFIX}/users/{body['id']}" + ) + + +def test_duplicate_email_is_a_conflict(api: TestClient) -> None: + register(api) + + response = api.post( + REGISTER_URL, json={"email": EMAIL.upper(), "password": PASSWORD} + ) + + assert response.status_code == 409 + assert response.json() == {"detail": "An account with this email already exists"} + + +def test_short_password_is_rejected(api: TestClient) -> None: + response = api.post(REGISTER_URL, json={"email": EMAIL, "password": "short"}) + + assert response.status_code == 422 + + +def test_token_flow(api: TestClient) -> None: + register(api) + + response = api.post(TOKEN_URL, data={"username": EMAIL, "password": PASSWORD}) + + assert response.status_code == 200 + body = response.json() + assert body["token_type"] == "bearer" + assert body["expires_in"] == settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60 + assert response.headers["Cache-Control"] == "no-store" + + me = api.get(ME_URL, headers=bearer(body["access_token"])) + assert me.status_code == 200 + assert me.json()["email"] == EMAIL + + +@pytest.mark.parametrize("email", [EMAIL, "nobody@example.com"]) +def test_wrong_credentials_get_401_with_challenge(api: TestClient, email: str) -> None: + register(api) + + response = api.post( + TOKEN_URL, data={"username": email, "password": "wrong-password"} + ) + + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == "Bearer" + assert response.json() == {"detail": "Incorrect email or password"} + + +def test_protected_route_requires_a_token(api: TestClient) -> None: + response = api.get(ME_URL) + + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == "Bearer" + + +@pytest.mark.parametrize( + "token", + [ + "not-a-jwt", + jwt.encode( + {"sub": "1", "type": "access", "exp": 4102444800}, + "a-different-signing-key-of-at-least-32-bytes", + ), + ], +) +def test_protected_route_rejects_invalid_tokens(api: TestClient, token: str) -> None: + register(api) + + response = api.get(ME_URL, headers=bearer(token)) + + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == "Bearer" + assert response.json() == {"detail": "Could not validate credentials"} + + +@pytest.mark.parametrize( + "claims", + [ + {"sub": "1", "type": "access"}, + {"sub": "1", "exp": 4102444800}, + {"type": "access", "exp": 4102444800}, + ], +) +def test_tokens_without_a_required_claim_are_rejected( + api: TestClient, claims: dict[str, object] +) -> None: + register(api) + token = jwt.encode(claims, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM) + + response = api.get(ME_URL, headers=bearer(token)) + + assert response.status_code == 401 + + +@pytest.mark.parametrize("algorithm", ["none", "RS256", "hs256"]) +def test_only_hmac_algorithms_are_accepted(algorithm: str) -> None: + with pytest.raises(ValidationError, match="JWT_ALGORITHM"): + Settings(_env_file=None, JWT_ALGORITHM=algorithm) + + +def test_inactive_account_is_forbidden( + api: TestClient, deactivate: Callable[[str], None] +) -> None: + user = register(api) + token = request_token(api) + + deactivate(str(user["id"])) + + assert api.get(ME_URL, headers=bearer(token)).status_code == 403 + response = api.post(TOKEN_URL, data={"username": EMAIL, "password": PASSWORD}) + assert response.status_code == 403 + assert response.json() == {"detail": "Inactive user"} + + +def test_accounts_only_read_themselves(api: TestClient) -> None: + user = register(api) + headers = bearer(request_token(api)) + other = register(api, email="bob@example.com") + + own = api.get(f"{settings.API_V1_PREFIX}/users/{user['id']}", headers=headers) + foreign = api.get(f"{settings.API_V1_PREFIX}/users/{other['id']}", headers=headers) + + assert own.status_code == 200 + assert foreign.status_code == 404 + + +def test_swagger_authorize_uses_the_token_endpoint(api: TestClient) -> None: + schemes = api.get("/openapi.json").json()["components"]["securitySchemes"] + + assert schemes["OAuth2PasswordBearer"]["flows"]["password"]["tokenUrl"] == TOKEN_URL +{% if rate_limit %} + + +def test_token_endpoint_has_a_stricter_rate_limit(api: TestClient) -> None: + attempts = parse(settings.RATE_LIMIT_AUTH).amount + form = {"username": EMAIL, "password": "wrong-password"} + + statuses = [api.post(TOKEN_URL, data=form).status_code for _ in range(attempts)] + blocked = api.post(TOKEN_URL, data=form) + + assert set(statuses) == {401} + assert blocked.status_code == 429 + + +def test_registration_has_the_stricter_rate_limit(api: TestClient) -> None: + attempts = parse(settings.RATE_LIMIT_AUTH).amount + + statuses = [ + api.post( + REGISTER_URL, json={"email": f"user{n}@example.com", "password": PASSWORD} + ).status_code + for n in range(attempts) + ] + blocked = api.post( + REGISTER_URL, json={"email": "late@example.com", "password": PASSWORD} + ) + + assert set(statuses) == {201} + assert blocked.status_code == 429 +{% endif %} +{% include "test/_auth_settings_tests.j2" %} +{% if backend == "mongo" %} + + +async def test_mongo_repository_against_a_server() -> None: + """Runs against MONGODB_URL when a server answers; skipped otherwise. + + Uses a separate ``_fastkit_test`` database and drops it. + """ + client: AsyncMongoClient[dict] = AsyncMongoClient( + settings.MONGODB_URL, serverSelectionTimeoutMS=500 + ) + try: + try: + await client.admin.command("ping") + except PyMongoError: + pytest.skip("no MongoDB server reachable at MONGODB_URL") + database = client[f"{settings.MONGODB_DB_NAME}_fastkit_test"] + try: + users = UserRepository(database) + user = await users.add(email=EMAIL, hashed_password="hash") + assert (await users.get(user.id)) == user + assert (await users.get_by_email(EMAIL.upper())) == user + with pytest.raises(EmailAlreadyRegisteredError): + await users.add(email=EMAIL, hashed_password="hash") + assert await users.set_active(user.id, False) + assert (await users.get(user.id)).is_active is False + finally: + await client.drop_database(database.name) + finally: + await client.close() +{% endif %} diff --git a/src/fastapi_fastkit/fragments/test/test_auth_oauth2.py.j2 b/src/fastapi_fastkit/fragments/test/test_auth_oauth2.py.j2 new file mode 100644 index 0000000..0296756 --- /dev/null +++ b/src/fastapi_fastkit/fragments/test/test_auth_oauth2.py.j2 @@ -0,0 +1,232 @@ +{% include "header.j2" %} +"""OAuth2 social login: session handling, provider selection, CSRF state. + +No request leaves the machine: GitHub's authorize URL is static, a callback +with a forged state is rejected before any token exchange, and the token +exchange itself is replaced by a stand-in provider. +""" + +import logging +import secrets +import time +from collections.abc import Iterator +from typing import Any +from urllib.parse import parse_qs, urlparse + +import httpx2 +import pytest +from authlib.integrations.starlette_client import OAuthError +from fastapi.testclient import TestClient +from pydantic import ValidationError + +{{ format_imports([ + "from " ~ main_module ~ " import app", + "from " ~ settings_module ~ " import Settings, settings", + "from " ~ auth_module ~ " import router as oauth_routes", +]) }} + +AUTH_URL = f"{settings.API_V1_PREFIX}/auth" +ME_URL = f"{settings.API_V1_PREFIX}/users/me" + + +@pytest.fixture +def api() -> Iterator[TestClient]: + with TestClient(app) as client: + yield client + + +@pytest.fixture +def github(monkeypatch: pytest.MonkeyPatch) -> None: + """Configure GitHub credentials for one test.""" + monkeypatch.setattr(settings, "GITHUB_CLIENT_ID", "test-client-id") + monkeypatch.setattr(settings, "GITHUB_CLIENT_SECRET", "test-client-secret") + + +def test_profile_requires_a_session(api: TestClient) -> None: + response = api.get(ME_URL) + + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == "Cookie" + + +def test_logout_returns_204(api: TestClient) -> None: + response = api.post(f"{AUTH_URL}/logout") + + assert response.status_code == 204 + assert response.content == b"" + + +@pytest.mark.parametrize("provider", ["unknown", "github"]) +def test_unknown_or_unconfigured_provider_is_404( + api: TestClient, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + monkeypatch.setattr(settings, "GITHUB_CLIENT_ID", "") + + response = api.get(f"{AUTH_URL}/login/{provider}", follow_redirects=False) + + assert response.status_code == 404 + assert response.json() == {"detail": "OAuth provider not found"} + + +@pytest.mark.usefixtures("github") +def test_login_redirects_to_the_provider_with_a_state(api: TestClient) -> None: + response = api.get(f"{AUTH_URL}/login/github", follow_redirects=False) + + assert response.status_code == 302 + location = response.headers["location"] + assert location.startswith("https://github.com/login/oauth/authorize?") + assert "state=" in location + assert "client_id=test-client-id" in location + + +@pytest.mark.usefixtures("github") +def test_callback_with_a_forged_state_is_rejected(api: TestClient) -> None: + api.get(f"{AUTH_URL}/login/github", follow_redirects=False) + + response = api.get(f"{AUTH_URL}/callback/github?code=abc&state=forged") + + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == "Cookie" + assert response.json() == {"detail": "OAuth login failed"} + assert api.get(ME_URL).status_code == 401 + + +def _state(api: TestClient) -> str: + response = api.get(f"{AUTH_URL}/login/github", follow_redirects=False) + return parse_qs(urlparse(response.headers["location"]).query)["state"][0] + + +def _redirect_uri(response: Any) -> str: + query = parse_qs(urlparse(response.headers["location"]).query) + return query["redirect_uri"][0] + + +class StubResponse: + """What ``client.get("user")`` returns for the stand-in GitHub.""" + + def __init__(self, payload: Any) -> None: + self.payload = payload + + def raise_for_status(self) -> None: + return None + + def json(self) -> Any: + return self.payload + + +@pytest.fixture +def provider(github: None, monkeypatch: pytest.MonkeyPatch) -> Iterator[dict[str, Any]]: + """Stand-in for the GitHub token exchange and profile API. + + Put an exception under ``"error"`` to make the exchange fail with it. + """ + behaviour: dict[str, Any] = {"error": None, "profile": {"id": 42, "login": "o"}} + client = oauth_routes.get_oauth_client("github") + + async def authorize_access_token(request: Any, **kwargs: Any) -> dict[str, str]: + if behaviour["error"] is not None: + raise behaviour["error"] + return {"access_token": "token"} + + async def get(url: str, **kwargs: Any) -> StubResponse: + return StubResponse(behaviour["profile"]) + + monkeypatch.setattr(client, "authorize_access_token", authorize_access_token) + monkeypatch.setattr(client, "get", get) + yield behaviour + + +def test_successful_login_stores_the_profile( + api: TestClient, provider: dict[str, Any] +) -> None: + response = api.get(f"{AUTH_URL}/callback/github?code=abc&state={_state(api)}") + + assert response.status_code == 200 + assert api.get(ME_URL).json()["subject"] == "42" + + +@pytest.mark.parametrize( + "error", + [ + httpx2.ConnectError("connection refused"), + httpx2.ReadTimeout("timed out"), + OAuthError(error="invalid_grant", description="bad code"), + ValueError("not JSON"), + ], + ids=["connect", "timeout", "oauth", "malformed"], +) +def test_provider_failures_are_a_logged_401( + api: TestClient, + provider: dict[str, Any], + caplog: pytest.LogCaptureFixture, + error: Exception, +) -> None: + provider["error"] = error + + with caplog.at_level(logging.WARNING): + response = api.get(f"{AUTH_URL}/callback/github?code=abc&state={_state(api)}") + + assert response.status_code == 401 + assert response.json() == {"detail": "OAuth login failed"} + assert response.headers["WWW-Authenticate"] == "Cookie" + assert type(error).__name__ in caplog.text + + +def test_sessions_end_after_the_absolute_lifetime( + api: TestClient, provider: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + login_time = time.time() + monkeypatch.setattr(oauth_routes, "session_clock", lambda: login_time) + api.get(f"{AUTH_URL}/callback/github?code=abc&state={_state(api)}") + assert api.get(ME_URL).status_code == 200 + + monkeypatch.setattr( + oauth_routes, + "session_clock", + lambda: login_time + settings.SESSION_ABSOLUTE_MAX_AGE + 1, + ) + + assert api.get(ME_URL).status_code == 401 + + +@pytest.mark.usefixtures("github") +def test_redirect_uri_comes_from_the_configured_base_url( + api: TestClient, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(settings, "OAUTH_REDIRECT_BASE_URL", "https://api.example.com/") + + response = api.get( + f"{AUTH_URL}/login/github", + headers={"Host": "evil.example"}, + follow_redirects=False, + ) + + assert _redirect_uri(response) == ( + f"https://api.example.com{AUTH_URL}/callback/github" + ) + + +@pytest.mark.usefixtures("github") +def test_development_falls_back_to_the_request_url( + api: TestClient, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(settings, "OAUTH_REDIRECT_BASE_URL", "") + monkeypatch.setattr(settings, "ENVIRONMENT", "development") + + response = api.get(f"{AUTH_URL}/login/github", follow_redirects=False) + + assert _redirect_uri(response) == f"http://testserver{AUTH_URL}/callback/github" + + +@pytest.mark.usefixtures("github") +@pytest.mark.parametrize("environment", ["staging", "production"]) +def test_outside_development_a_base_url_is_required( + api: TestClient, monkeypatch: pytest.MonkeyPatch, environment: str +) -> None: + monkeypatch.setattr(settings, "OAUTH_REDIRECT_BASE_URL", "") + monkeypatch.setattr(settings, "ENVIRONMENT", environment) + + response = api.get(f"{AUTH_URL}/login/github", follow_redirects=False) + + assert response.status_code == 404 +{% include "test/_auth_settings_tests.j2" %} diff --git a/src/fastapi_fastkit/fragments/test/test_auth_session.py.j2 b/src/fastapi_fastkit/fragments/test/test_auth_session.py.j2 new file mode 100644 index 0000000..47bdd2b --- /dev/null +++ b/src/fastapi_fastkit/fragments/test/test_auth_session.py.j2 @@ -0,0 +1,319 @@ +{% include "header.j2" %} +"""Cookie-session authentication. + +Every test runs on its own account store ({% if backend == "sql" %}an in-memory SQLite database{% elif backend == "mongo" %}a dict-backed fake of the MongoDB repository{% else %}a fresh in-memory store{% endif %}), +so nothing touches a configured database and no network is used. +""" + +import secrets +import time +from collections.abc import {% if backend == "sql" %}AsyncIterator, {% endif %}Callable, Iterator + +import pytest +{% if backend == "mongo" %} +from bson import ObjectId +{% endif %} +from fastapi import FastAPI, Request +from fastapi.testclient import TestClient +{% if rate_limit %} +from limits import parse +{% endif %} +from pydantic import ValidationError +{% if backend == "mongo" %} +{% endif %} +{% if backend == "sql" %} +from sqlalchemy.ext.asyncio import ( + AsyncEngine, + AsyncSession, + async_sessionmaker, + create_async_engine, +) +from sqlalchemy.pool import StaticPool +{% endif %} + +{% set first_party = [ + "from " ~ main_module ~ " import app", + "from " ~ settings_module ~ " import Settings, settings", + "from " ~ auth_module ~ ".service import DEMO_USER_EMAIL, DEMO_USER_PASSWORD", + "from " ~ auth_module ~ ".middleware import add_session_middleware", + "from " ~ auth_module ~ " import dependencies as auth_dependencies", +] %} +{% if backend != "memory" %} +{% set first_party = first_party + ["from " ~ auth_module ~ ".models import User"] %} +{% endif %} +{% if backend == "sql" %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".repository import UserRepository", + "from " ~ db_module ~ " import Base, get_db", +] %} +{% if create_tables %} +{% set first_party = first_party + ["from " ~ auth_module ~ " import router as auth_routes"] %} +{% endif %} +{% elif backend == "mongo" %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".dependencies import get_user_repository", + "from " ~ auth_module ~ ".repository import EmailAlreadyRegisteredError", +] %} +{% else %} +{% set first_party = first_party + [ + "from " ~ auth_module ~ ".dependencies import get_user_repository", + "from " ~ auth_module ~ ".repository import UserRepository", +] %} +{% endif %} +{% if rate_limit %} +{% set first_party = first_party + ["from " ~ pkg ~ ".rate_limiting import limiter"] %} +{% endif %} +{{ format_imports(first_party) }} + +REGISTER_URL = f"{settings.API_V1_PREFIX}/auth/register" +LOGIN_URL = f"{settings.API_V1_PREFIX}/auth/login" +LOGOUT_URL = f"{settings.API_V1_PREFIX}/auth/logout" +ME_URL = f"{settings.API_V1_PREFIX}/users/me" + +EMAIL = "alice@example.com" +PASSWORD = "correct-horse-battery" + + +{% include "test/_auth_store_fixtures.j2" %} + + +def register(api: TestClient, email: str = EMAIL, password: str = PASSWORD) -> dict: + response = api.post(REGISTER_URL, json={"email": email, "password": password}) + assert response.status_code == 201, response.text + return response.json() + + +def log_in(api: TestClient, email: str = EMAIL, password: str = PASSWORD) -> int: + response = api.post(LOGIN_URL, json={"email": email, "password": password}) + return response.status_code + + +def test_register_returns_201_with_location(api: TestClient) -> None: + response = api.post( + REGISTER_URL, json={"email": "Alice@Example.com", "password": PASSWORD} + ) + + assert response.status_code == 201 + body = response.json() + assert body["email"] == EMAIL + assert "password" not in body and "hashed_password" not in body + assert response.headers["Location"].endswith( + f"{settings.API_V1_PREFIX}/users/{body['id']}" + ) + + +def test_duplicate_email_is_a_conflict(api: TestClient) -> None: + register(api) + + response = api.post(REGISTER_URL, json={"email": EMAIL, "password": PASSWORD}) + + assert response.status_code == 409 + + +def test_login_sets_a_signed_session_cookie(api: TestClient) -> None: + register(api) + + response = api.post(LOGIN_URL, json={"email": EMAIL, "password": PASSWORD}) + + assert response.status_code == 200 + assert response.json()["email"] == EMAIL + cookie = response.headers["set-cookie"].lower() + assert "httponly" in cookie + assert "samesite=lax" in cookie + assert api.get(ME_URL).json()["email"] == EMAIL + + +@pytest.mark.parametrize("email", [EMAIL, "nobody@example.com"]) +def test_wrong_credentials_get_401_with_challenge(api: TestClient, email: str) -> None: + register(api) + + response = api.post(LOGIN_URL, json={"email": email, "password": "wrong-password"}) + + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == "Cookie" + assert response.json() == {"detail": "Incorrect email or password"} + + +def test_protected_route_requires_a_session(api: TestClient) -> None: + response = api.get(ME_URL) + + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == "Cookie" + + +def test_forged_session_cookie_is_ignored(api: TestClient) -> None: + api.cookies.set("session", "forged-value") + + assert api.get(ME_URL).status_code == 401 + + +def test_logout_returns_204_and_ends_the_session(api: TestClient) -> None: + register(api) + assert log_in(api) == 200 + + response = api.post(LOGOUT_URL) + + assert response.status_code == 204 + assert response.content == b"" + assert api.get(ME_URL).status_code == 401 + + +def test_a_cookie_captured_before_logout_is_refused_afterwards(api: TestClient) -> None: + register(api) + assert log_in(api) == 200 + captured = api.cookies.get("session") + assert captured + + assert api.post(LOGOUT_URL).status_code == 204 + api.cookies.clear() + api.cookies.set("session", captured) + response = api.get(ME_URL) + + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == "Cookie" + + +def test_logging_in_again_after_logout_works(api: TestClient) -> None: + register(api) + assert log_in(api) == 200 + assert api.post(LOGOUT_URL).status_code == 204 + + assert log_in(api) == 200 + assert api.get(ME_URL).status_code == 200 + + +def test_sessions_end_after_the_absolute_lifetime( + api: TestClient, monkeypatch: pytest.MonkeyPatch +) -> None: + register(api) + login_time = time.time() + monkeypatch.setattr(auth_dependencies, "session_clock", lambda: login_time) + assert log_in(api) == 200 + + # Still active just before the limit (every request renews the cookie). + monkeypatch.setattr( + auth_dependencies, + "session_clock", + lambda: login_time + settings.SESSION_ABSOLUTE_MAX_AGE - 1, + ) + assert api.get(ME_URL).status_code == 200 + + monkeypatch.setattr( + auth_dependencies, + "session_clock", + lambda: login_time + settings.SESSION_ABSOLUTE_MAX_AGE + 1, + ) + response = api.get(ME_URL) + + assert response.status_code == 401 + assert response.json() == {"detail": "Session expired"} + + +@pytest.mark.parametrize( + ("environment", "secure"), + [("development", False), ("staging", True), ("production", True)], +) +def test_cookie_is_secure_unless_in_development( + monkeypatch: pytest.MonkeyPatch, environment: str, secure: bool +) -> None: + monkeypatch.setattr(settings, "ENVIRONMENT", environment) + monkeypatch.setattr(settings, "SESSION_HTTPS_ONLY", False) + probe = FastAPI() + add_session_middleware(probe) + + @probe.get("/start") + def start(request: Request) -> dict[str, str]: + request.session["probe"] = "1" + return {} + + with TestClient(probe, base_url="https://testserver") as client: + header = client.get("/start").headers["set-cookie"] + + attributes = {part.strip().lower() for part in header.split(";")[1:]} + assert "httponly" in attributes + assert "samesite=lax" in attributes + assert ("secure" in attributes) is secure + + +def test_inactive_account_is_forbidden( + api: TestClient, deactivate: Callable[[str], None] +) -> None: + user = register(api) + assert log_in(api) == 200 + + deactivate(str(user["id"])) + + assert api.get(ME_URL).status_code == 403 + assert log_in(api) == 403 + + +def test_demo_account_is_off_by_default(api: TestClient) -> None: + assert settings.ENABLE_DEMO_USERS is False + assert log_in(api, DEMO_USER_EMAIL, DEMO_USER_PASSWORD) == 401 + + +def test_demo_account_works_when_enabled( + api: TestClient, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(settings, "ENABLE_DEMO_USERS", True) + + assert log_in(api, DEMO_USER_EMAIL, "wrong-password") == 401 + assert log_in(api, DEMO_USER_EMAIL, DEMO_USER_PASSWORD) == 200 + assert api.get(ME_URL).json()["email"] == DEMO_USER_EMAIL + + +@pytest.mark.parametrize("enabled", [False, True]) +def test_the_demo_address_cannot_be_registered( + api: TestClient, monkeypatch: pytest.MonkeyPatch, enabled: bool +) -> None: + monkeypatch.setattr(settings, "ENABLE_DEMO_USERS", enabled) + + response = api.post( + REGISTER_URL, + json={"email": DEMO_USER_EMAIL.title(), "password": "attacker-password"}, + ) + + assert response.status_code == 409 + if enabled: + assert log_in(api, DEMO_USER_EMAIL, DEMO_USER_PASSWORD) == 200 + assert api.get(ME_URL).json()["full_name"] is None + + +@pytest.mark.parametrize("environment", ["staging", "production"]) +def test_outside_development_demo_users_are_refused(environment: str) -> None: + with pytest.raises(ValidationError, match=f"ENABLE_DEMO_USERS.*{environment}"): + Settings( + _env_file=None, + ENVIRONMENT=environment, + SECRET_KEY=secrets.token_urlsafe(32), + ENABLE_DEMO_USERS=True, + ) +{% if rate_limit %} + + +def test_login_has_a_stricter_rate_limit(api: TestClient) -> None: + attempts = parse(settings.RATE_LIMIT_AUTH).amount + + statuses = [log_in(api, password="wrong-password") for _ in range(attempts)] + + assert set(statuses) == {401} + assert log_in(api, password="wrong-password") == 429 + + +def test_registration_has_the_stricter_rate_limit(api: TestClient) -> None: + attempts = parse(settings.RATE_LIMIT_AUTH).amount + + statuses = [ + api.post( + REGISTER_URL, json={"email": f"user{n}@example.com", "password": PASSWORD} + ).status_code + for n in range(attempts) + ] + blocked = api.post( + REGISTER_URL, json={"email": "late@example.com", "password": PASSWORD} + ) + + assert set(statuses) == {201} + assert blocked.status_code == 429 +{% endif %} +{% include "test/_auth_settings_tests.j2" %} diff --git a/src/fastapi_fastkit/fragments/test/test_main.py.j2 b/src/fastapi_fastkit/fragments/test/test_main.py.j2 index ecfd284..e06576b 100644 --- a/src/fastapi_fastkit/fragments/test/test_main.py.j2 +++ b/src/fastapi_fastkit/fragments/test/test_main.py.j2 @@ -8,15 +8,18 @@ the entry point. from fastapi.testclient import TestClient +from {{ settings_module }} import settings + def test_root_endpoint(client: TestClient) -> None: - """The root endpoint greets the project by name.""" + """The root endpoint only welcomes and points at the docs.""" response = client.get("/") assert response.status_code == 200 - data = response.json() - assert data["message"] == {{ ("Welcome to " ~ project_name) | tojson }} - assert data["status"] == "healthy" + assert response.json() == { + "message": f"Welcome to {settings.PROJECT_NAME}", + "docs": "/docs", + } def test_health_check(client: TestClient) -> None: @@ -27,20 +30,11 @@ def test_health_check(client: TestClient) -> None: assert response.json() == {"status": "ok"} -def test_readiness_check(client: TestClient) -> None: - """The readiness probe reports the app can serve traffic.""" - response = client.get("/ready") - - assert response.status_code == 200 - assert response.json() == {"status": "ready"} - - def test_openapi_json(client: TestClient) -> None: - """The schema is served and describes both health probes.""" + """The schema is served and describes the health probe.""" response = client.get("/openapi.json") assert response.status_code == 200 schema = response.json() - assert schema["info"]["title"] == {{ project_name | tojson }} + assert schema["info"]["title"] == settings.PROJECT_NAME assert "/health" in schema["paths"] - assert "/ready" in schema["paths"] diff --git a/src/fastapi_fastkit/fragments/test/test_pagination.py.j2 b/src/fastapi_fastkit/fragments/test/test_pagination.py.j2 new file mode 100644 index 0000000..0f7b371 --- /dev/null +++ b/src/fastapi_fastkit/fragments/test/test_pagination.py.j2 @@ -0,0 +1,57 @@ +{% include "header.j2" %} +"""Tests for the shared pagination helpers in ``core/pagination.py``.""" + +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from {{ pkg }}.core.pagination import ( + DEFAULT_LIMIT, + MAX_LIMIT, + LimitParam, + OffsetParam, + Page, +) + +NUMBERS = list(range(1, 51)) + +app = FastAPI() + + +@app.get("/numbers") +def list_numbers( + limit: LimitParam = DEFAULT_LIMIT, offset: OffsetParam = 0 +) -> Page[int]: + return Page( + items=NUMBERS[offset : offset + limit], + total=len(NUMBERS), + limit=limit, + offset=offset, + ) + + +client = TestClient(app) + + +def test_default_page() -> None: + body = client.get("/numbers").json() + + assert body == { + "items": NUMBERS[:DEFAULT_LIMIT], + "total": 50, + "limit": DEFAULT_LIMIT, + "offset": 0, + } + + +def test_limit_and_offset_select_a_slice() -> None: + body = client.get("/numbers", params={"limit": 1, "offset": 1}).json() + + assert body["items"] == [2] + + +def test_bounds_are_validated() -> None: + too_large = {"limit": MAX_LIMIT + 1} + + assert client.get("/numbers", params={"limit": 0}).status_code == 422 + assert client.get("/numbers", params=too_large).status_code == 422 + assert client.get("/numbers", params={"offset": -1}).status_code == 422 diff --git a/src/fastapi_fastkit/fragments/test/test_rate_limiting.py.j2 b/src/fastapi_fastkit/fragments/test/test_rate_limiting.py.j2 new file mode 100644 index 0000000..2f56108 --- /dev/null +++ b/src/fastapi_fastkit/fragments/test/test_rate_limiting.py.j2 @@ -0,0 +1,48 @@ +{% include "header.j2" %} +"""The default rate limit really answers 429 once a client exceeds it.""" + +from collections.abc import Iterator + +import pytest +from fastapi.testclient import TestClient +from limits import parse + +from {{ settings_module }} import settings +from {{ pkg }}.rate_limiting import client_key, limiter + + +@pytest.fixture +def fresh_limits() -> Iterator[None]: + """Start and end with empty counters, so other tests are not throttled.""" + limiter.reset() + yield + limiter.reset() + + +@pytest.mark.usefixtures("fresh_limits") +def test_requests_over_the_default_limit_get_429(client: TestClient) -> None: + allowed = parse(settings.RATE_LIMIT_DEFAULT).amount + + statuses = [client.get("/health").status_code for _ in range(allowed)] + blocked = client.get("/health") + + assert set(statuses) == {200} + assert blocked.status_code == 429 + assert blocked.json() == {"detail": "Too many requests"} + assert int(blocked.headers["Retry-After"]) >= 1 + + +@pytest.mark.parametrize( + ("host", "key"), + [ + ("2001:db8::1", "2001:db8::/64"), + ("2001:db8::ffff:1234", "2001:db8::/64"), + ("2001:db8:0:1::1", "2001:db8:0:1::/64"), + ("203.0.113.7", "203.0.113.7"), + ("::ffff:203.0.113.7", "203.0.113.7"), + ("testclient", "testclient"), + (None, "unknown"), + ], +) +def test_ipv6_clients_share_a_budget_per_64(host: str | None, key: str) -> None: + assert client_key(host) == key diff --git a/src/fastapi_fastkit/fragments/test/test_readiness.py.j2 b/src/fastapi_fastkit/fragments/test/test_readiness.py.j2 new file mode 100644 index 0000000..3ec60de --- /dev/null +++ b/src/fastapi_fastkit/fragments/test/test_readiness.py.j2 @@ -0,0 +1,47 @@ +{% include "header.j2" %} +"""Tests for the readiness probe. + +The checks are swapped for stubs, so the outcome does not depend on whether +a database or cache happens to run on this machine. +""" + +import pytest +from fastapi import Request +from fastapi.testclient import TestClient + +from {{ pkg }}.features import readiness + + +async def _passing(_request: Request) -> None: + return None + + +async def _failing(_request: Request) -> None: + raise ConnectionError("dependency is down") + + +def test_ready_when_every_check_passes( + client: TestClient, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(readiness, "CHECKS", [_passing, _passing]) + + response = client.get("/ready") + + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + +def test_unavailable_when_a_check_fails( + client: TestClient, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(readiness, "CHECKS", [_passing, _failing]) + + response = client.get("/ready") + + assert response.status_code == 503 + assert response.json() == {"status": "unavailable"} + assert "dependency is down" not in response.text + + +def test_ready_is_served_at_the_root(client: TestClient) -> None: + assert "/ready" in client.get("/openapi.json").json()["paths"] diff --git a/src/fastapi_fastkit/fragments/test/test_tasks_dramatiq.py.j2 b/src/fastapi_fastkit/fragments/test/test_tasks_dramatiq.py.j2 new file mode 100644 index 0000000..cf4ca79 --- /dev/null +++ b/src/fastapi_fastkit/fragments/test/test_tasks_dramatiq.py.j2 @@ -0,0 +1,106 @@ +{% include "header.j2" %} +"""Dramatiq task routes on Dramatiq's stub broker and stub result backend. + +No Redis is needed: the actor's broker and the result backend are swapped +for the in-memory stand-ins Dramatiq ships for tests, and a real Dramatiq +worker processes the queue. +""" + +from collections.abc import Iterator + +import pytest +from dramatiq import Worker +from dramatiq.brokers.stub import StubBroker +from dramatiq.results import Results +from dramatiq.results.backends import StubBackend +from fastapi.testclient import TestClient +from redis.exceptions import ConnectionError as RedisConnectionError + +{{ format_imports([ + "from " ~ settings_module ~ " import settings", + "from " ~ pkg ~ ".features import tasks", + "from " ~ pkg ~ ".worker import TASK_TTL_MS, example_task", +]) }} + +TASKS_URL = f"{settings.API_V1_PREFIX}/tasks" + + +@pytest.fixture +def stub_broker(monkeypatch: pytest.MonkeyPatch) -> Iterator[StubBroker]: + backend = StubBackend() + backend.results = {} # the class-level dict would be shared between tests + broker = StubBroker() + broker.add_middleware(Results(backend=backend, result_ttl=TASK_TTL_MS)) + broker.emit_after("process_boot") + broker.declare_actor(example_task) + monkeypatch.setattr(example_task, "broker", broker) + monkeypatch.setattr(tasks, "result_backend", backend) + yield broker + broker.flush_all() + broker.close() + + +def run_queue(broker: StubBroker) -> None: + worker = Worker(broker, worker_timeout=100) + worker.start() + try: + broker.join(example_task.queue_name) + worker.join() + finally: + worker.stop() + + +def test_a_task_is_pending_until_the_worker_ran_it( + client: TestClient, stub_broker: StubBroker +) -> None: + response = client.post(TASKS_URL, json={"payload": {"n": 1}}) + + assert response.status_code == 202 + task_id = response.json()["task_id"] + assert response.headers["Location"].endswith(f"{TASKS_URL}/{task_id}") + assert client.get(f"{TASKS_URL}/{task_id}").json()["status"] == "PENDING" + + run_queue(stub_broker) + + body = client.get(f"{TASKS_URL}/{task_id}").json() + assert body == { + "task_id": task_id, + "status": "SUCCESS", + "result": {"received": {"n": 1}}, + } + + +@pytest.mark.parametrize( + "task_id", ["not-a-uuid", "00000000-0000-4000-8000-000000000000"] +) +def test_unknown_tasks_are_404( + client: TestClient, stub_broker: StubBroker, task_id: str +) -> None: + response = client.get(f"{TASKS_URL}/{task_id}") + + assert response.status_code == 404 + assert response.json() == {"detail": "Task not found"} + + +def test_the_status_expires( + client: TestClient, stub_broker: StubBroker, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(tasks, "TASK_TTL_MS", 0) + + task_id = client.post(TASKS_URL, json={}).json()["task_id"] + + assert client.get(f"{TASKS_URL}/{task_id}").status_code == 404 + + +def test_an_unreachable_redis_is_503( + client: TestClient, stub_broker: StubBroker, monkeypatch: pytest.MonkeyPatch +) -> None: + def unreachable(*args: object, **kwargs: object) -> None: + raise RedisConnectionError("Connection refused") + + monkeypatch.setattr(tasks.result_backend, "store_result", unreachable) + + response = client.post(TASKS_URL, json={}) + + assert response.status_code == 503 + assert response.json() == {"detail": "Task queue unavailable"} diff --git a/src/fastapi_fastkit/fragments/test/test_websocket.py.j2 b/src/fastapi_fastkit/fragments/test/test_websocket.py.j2 new file mode 100644 index 0000000..82a1525 --- /dev/null +++ b/src/fastapi_fastkit/fragments/test/test_websocket.py.j2 @@ -0,0 +1,71 @@ +{% include "header.j2" %} +"""Tests for the WebSocket example.""" + +import pytest +from fastapi.testclient import TestClient +from starlette.websockets import WebSocketDisconnect + +{{ format_imports([ + "from " ~ settings_module ~ " import settings", + "from " ~ pkg ~ ".features.websocket import MAX_MESSAGE_CHARS, manager", +]) }} + + +def test_websocket_echoes_to_the_sender_only(client: TestClient) -> None: + with client.websocket_connect("/ws") as websocket: + websocket.send_text("hello") + + assert websocket.receive_text() == "you wrote: hello" + websocket.send_text("again") + # No "someone wrote: hello" in between: the sender is not relayed to. + assert websocket.receive_text() == "you wrote: again" + + +def test_messages_are_relayed_to_the_other_clients(client: TestClient) -> None: + with client.websocket_connect("/ws") as alice: + with client.websocket_connect("/ws") as bob: + alice.send_text("hi bob") + + assert alice.receive_text() == "you wrote: hi bob" + assert bob.receive_text() == "someone wrote: hi bob" + + +def test_a_binary_frame_closes_the_connection_and_frees_it( + client: TestClient, +) -> None: + with client.websocket_connect("/ws") as websocket: + websocket.send_bytes(b"\x00\x01") + + with pytest.raises(WebSocketDisconnect) as closed: + websocket.receive_text() + + assert closed.value.code == 1003 + assert manager.active_connections == [] + + +def test_an_oversized_message_closes_the_connection(client: TestClient) -> None: + with client.websocket_connect("/ws") as websocket: + websocket.send_text("x" * (MAX_MESSAGE_CHARS + 1)) + + with pytest.raises(WebSocketDisconnect) as closed: + websocket.receive_text() + + assert closed.value.code == 1009 + assert manager.active_connections == [] + + +def test_an_abrupt_disconnect_frees_the_connection(client: TestClient) -> None: + with client.websocket_connect("/ws") as websocket: + websocket.send_text("hello") + websocket.receive_text() + # Leaving the block drops the connection without a close frame. + + response = client.get(f"{settings.API_V1_PREFIX}/connections") + assert response.json() == {"active_connections": 0} + + +def test_connection_count_is_versioned(client: TestClient) -> None: + response = client.get(f"{settings.API_V1_PREFIX}/connections") + + assert response.status_code == 200 + assert isinstance(response.json()["active_connections"], int) diff --git a/src/fastapi_fastkit/fragments/tooling/mypy_overrides_toml.j2 b/src/fastapi_fastkit/fragments/tooling/mypy_overrides_toml.j2 new file mode 100644 index 0000000..a749136 --- /dev/null +++ b/src/fastapi_fastkit/fragments/tooling/mypy_overrides_toml.j2 @@ -0,0 +1,14 @@ + +# Generated modules use packages that ship no type information. +{% if untyped_packages %} +[[tool.mypy.overrides]] +module = {{ untyped_packages | tojson }} +ignore_missing_imports = true +{% endif %} +{% if worker_module %} + +[[tool.mypy.overrides]] +module = [{{ worker_module | tojson }}] +disallow_untyped_calls = false +disallow_untyped_decorators = false +{% endif %} diff --git a/tests/conftest.py b/tests/conftest.py index 983e6c3..9f507fd 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -13,10 +13,14 @@ from fastapi_fastkit.core.settings import FastkitConfig -@pytest.fixture(autouse=True, scope="session") +@pytest.fixture(autouse=True) def temp_dir(tmp_path_factory: pytest.TempPathFactory) -> Generator[str, None, None]: """ - Fixture that yields a session-scoped temporary workspace path. + Fixture that yields a fresh temporary workspace path for each test. + + A workspace shared by the whole session let tests depend on the order + they ran in (a project another test left behind made ``startdemo`` + refuse to overwrite it, or ``addroute`` find the wrong project). ``tmp_path_factory`` is used instead of a fixed ``tests/temp_test_workspace`` directory so parallel/concurrent test runs never share (or delete) each diff --git a/tests/test_backends/doctor_helpers.py b/tests/test_backends/doctor_helpers.py new file mode 100644 index 0000000..4b5c43d --- /dev/null +++ b/tests/test_backends/doctor_helpers.py @@ -0,0 +1,216 @@ +# -------------------------------------------------------------------------- +# Shared fixtures for the ``fastkit doctor`` tests: small projects built +# from inline files, including one shaped like a v1.5.1 project. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import shutil +import subprocess +from pathlib import Path +from typing import Dict, Optional, Union + +import pytest + +from fastapi_fastkit.backend.doctor import ProjectContext +from fastapi_fastkit.core.settings import FastkitConfig + +FileContent = Union[str, bytes] + +TEMPLATE_ROOT = FastkitConfig().FASTKIT_TEMPLATE_ROOT + +#: ``[tool.fastapi-fastkit]`` of a ``fastapi-empty`` project. +DEFAULT_METADATA = """ +[tool.fastapi-fastkit] +managed = true +version = "2.0.0" +template = "fastapi-empty" +package_manager = "uv" +app_module = "src.main:app" +features = [] +""" + +CLEAN_PYPROJECT = """[project] +name = "demo" +version = "0.1.0" +description = "[FastAPI-fastkit templated] demo" +requires-python = ">=3.12" +dependencies = [ + "fastapi>=0.115", +] +""" + DEFAULT_METADATA + +CLEAN_MAIN = """from fastapi import FastAPI + +app = FastAPI() +""" + +CLEAN_GITIGNORE = "__pycache__/\n.env\n.env.*\n!.env.example\n" + +#: Files of a project that passes every check. +CLEAN_FILES: Dict[str, FileContent] = { + "pyproject.toml": CLEAN_PYPROJECT, + "src/__init__.py": "", + "src/main.py": CLEAN_MAIN, + ".gitignore": CLEAN_GITIGNORE, + ".gitattributes": "* text=auto\n*.sh text eol=lf\n", + ".env": "SECRET_KEY=Zm9vYmFyYmF6cXV4cXV1eGNvcmdlZ3JhdWx0Z2FycGx5\n", + ".env.example": "SECRET_KEY=changethis\n", +} + +#: A v1.5.1-style ``fastkit init`` project (PostgreSQL, Prometheus, CORS, +#: Session auth, pre-commit), shaped like what that release generated. +V151_FILES: Dict[str, FileContent] = { + "pyproject.toml": """[project] +name = "legacy" +version = "0.1.0" +description = "[FastAPI-fastkit templated] legacy app" +requires-python = ">=3.12" +dependencies = [ + "fastapi>=0.115", + "sqlalchemy>=2.0", + "prometheus-fastapi-instrumentator>=7.0", +] + +[tool.fastapi-fastkit] +managed = true +version = "1.5.1" +template = "fastapi-empty" +preset = "minimal" +package_manager = "uv" +app_module = "src.main:app" +features = ["database:PostgreSQL", "authentication:Session-based", "monitoring:Prometheus"] +""", + "requirements.txt": "fastapi>=0.115\nsqlalchemy>=2.0\n", + ".env": "SECRET_KEY=changethis\nENVIRONMENT=development\nPOSTGRES_PASSWORD=hunter2hunter2\n", + ".gitignore": "__pycache__/\n*.pyc\nenv\nvenv\n", + ".pre-commit-config.yaml": ( + "# pre-commit configuration\n" + "default_language_version:\n" + " python: python3.12\n" + "\n" + "repos:\n" + " - repo: https://github.com/astral-sh/ruff-pre-commit\n" + " rev: v0.9.6\n" + " hooks:\n" + " - id: ruff\n" + ), + "scripts/run-server.sh": b"#!/usr/bin/env bash\r\nuvicorn src.main:app\r\n", + "src/__init__.py": "", + "src/main.py": """from contextlib import asynccontextmanager +from typing import AsyncIterator + +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from prometheus_fastapi_instrumentator import Instrumentator +from starlette.middleware.sessions import SessionMiddleware + +from src.auth.session import SESSION_SECRET_KEY + + +@asynccontextmanager +async def lifespan(app: FastAPI) -> AsyncIterator[None]: + # Initialize Prometheus metrics + Instrumentator().instrument(app).expose(app) + yield + + +app = FastAPI(lifespan=lifespan) + +# CORS middleware +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], # Configure appropriately + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +app.add_middleware(SessionMiddleware, secret_key=SESSION_SECRET_KEY) +""", + "src/auth/__init__.py": "", + "src/auth/session.py": """import os + +SESSION_SECRET_KEY = os.getenv("SESSION_SECRET_KEY", "change-me-in-production") +""", + "src/db/session.py": """from sqlalchemy.ext.asyncio import create_async_engine + +engine = create_async_engine("postgresql+asyncpg://localhost/app") +""", +} + + +def write_files(root: Path, files: Dict[str, FileContent]) -> None: + """Write ``files`` (relative path -> text or exact bytes) under ``root``. + + Text is written with LF line endings on every OS. + """ + for relative, content in files.items(): + path = root.joinpath(*relative.split("/")) + path.parent.mkdir(parents=True, exist_ok=True) + if isinstance(content, bytes): + path.write_bytes(content) + else: + path.write_bytes(content.encode("utf-8")) + + +def make_project( + root: Path, + files: Optional[Dict[str, FileContent]] = None, + base: Optional[Dict[str, FileContent]] = None, + remove: tuple = (), +) -> Path: + """Create a project from ``base`` (clean by default) plus ``files``.""" + merged = dict(CLEAN_FILES if base is None else base) + merged.update(files or {}) + for relative in remove: + merged.pop(relative, None) + root.mkdir(parents=True, exist_ok=True) + write_files(root, merged) + return root + + +def context(root: Path) -> ProjectContext: + return ProjectContext.load(str(root), template_root=TEMPLATE_ROOT) + + +def git_env() -> Dict[str, str]: + """Environment that keeps the user's git configuration out of tests.""" + env = dict(os.environ) + env.update( + { + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_AUTHOR_NAME": "test", + "GIT_AUTHOR_EMAIL": "test@example.com", + "GIT_COMMITTER_NAME": "test", + "GIT_COMMITTER_EMAIL": "test@example.com", + } + ) + for name in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"): + env.pop(name, None) + return env + + +requires_git = pytest.mark.skipif(shutil.which("git") is None, reason="git missing") + + +def git(root: Path, *args: str) -> None: + subprocess.run( + ["git", "-c", "core.autocrlf=false", *args], + cwd=str(root), + env=git_env(), + check=True, + capture_output=True, + ) + + +def git_init_and_commit(root: Path, *paths: str) -> None: + """``git init`` and commit ``paths`` (``-f`` so ignored files go in too).""" + git(root, "init", "-q") + git(root, "add", "-f", "--", *paths) + git(root, "commit", "-q", "-m", "init") + + +def read_bytes(root: Path, relative: str) -> bytes: + return root.joinpath(*relative.split("/")).read_bytes() diff --git a/tests/test_backends/test_doctor_checks.py b/tests/test_backends/test_doctor_checks.py new file mode 100644 index 0000000..1efec23 --- /dev/null +++ b/tests/test_backends/test_doctor_checks.py @@ -0,0 +1,1324 @@ +# -------------------------------------------------------------------------- +# Unit tests of every ``fastkit doctor`` check: it detects the problem, +# stays quiet on a clean project, fixes it (when fixable) and finds nothing +# left on a second run. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import re +import stat +from pathlib import Path +from typing import List +from unittest.mock import patch + +import pytest + +from fastapi_fastkit.backend.doctor import ( + Check, + CheckSkipped, + CheckStatus, + FixRefused, + ProjectContext, + apply_edits, + run_checks, +) +from fastapi_fastkit.backend.doctor.checks_code import ( + AppModuleMissingCheck, + CorsCredentialsCheck, + McpAuthCheck, + McpDemoUsersCheck, + PrometheusLifespanCheck, +) +from fastapi_fastkit.backend.doctor.checks_files import ( + CrlfScriptsCheck, + GitattributesMissingCheck, + PreCommitPythonCheck, + RequiresPythonCheck, + SqlalchemyAsyncioCheck, + is_lf_only_file, + python_floor, + with_asyncio_extra, +) +from fastapi_fastkit.backend.doctor.checks_secrets import ( + EnvExampleMissingCheck, + EnvTrackedCheck, + ExampleSecretCheck, + GitignoreEnvCheck, + SessionSecretCheck, + append_lines, + gitignore_ignores, +) +from fastapi_fastkit.backend.doctor.envfile import ( + build_env_example, + looks_like_secret, + parse_env, +) +from fastapi_fastkit.backend.doctor.known import KNOWN_EXAMPLE_SECRETS +from fastapi_fastkit.backend.project_builder.config_generator import ( + PUBLIC_EXAMPLE_SECRET_KEYS, + DynamicConfigGenerator, +) +from tests.test_backends.doctor_helpers import ( + CLEAN_PYPROJECT, + DEFAULT_METADATA, + TEMPLATE_ROOT, + context, + git_init_and_commit, + make_project, + read_bytes, + requires_git, +) + + +def _fix_and_recheck(check: Check, root: Path) -> None: + """Apply the check's fix, then assert a second run finds nothing.""" + ctx = context(root) + findings = check.detect(ctx) + assert findings + edits = check.plan_fix(ctx, findings) + assert edits + outcome = apply_edits(ctx, edits) + assert outcome.failed == [] + second = context(root) + assert check.detect(second) == [] + # idempotent: nothing more to change + report = run_checks(second, [check]) + assert report.results[0].status is CheckStatus.OK + assert report.edits == [] + + +def _messages(check: Check, root: Path) -> List[str]: + return [f.message for f in check.detect(context(root))] + + +# ---------------------------------------------------------------------- +# 1. env-tracked +# ---------------------------------------------------------------------- + + +class TestEnvTracked: + @requires_git + def test_detects_committed_env(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {".env.local": "A=1\n"}) + git_init_and_commit(root, ".env", ".env.local", ".env.example", "src/main.py") + + findings = EnvTrackedCheck().detect(context(root)) + + assert len(findings) == 1 + assert findings[0].files == (".env", ".env.local") + assert "SECRET_KEY" not in findings[0].message + + @requires_git + def test_example_and_untracked_env_are_fine(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p") + git_init_and_commit(root, ".env.example", ".gitignore", "src/main.py") + + assert EnvTrackedCheck().detect(context(root)) == [] + + @requires_git + def test_project_in_a_subdirectory_of_the_repository(self, tmp_path: Path) -> None: + make_project(tmp_path / "repo" / "app") + git_init_and_commit(tmp_path / "repo", "app/.env") + + findings = EnvTrackedCheck().detect(context(tmp_path / "repo" / "app")) + + assert findings[0].files == (".env",) + + @requires_git + def test_not_a_git_repository_is_skipped(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p") + with patch.dict(os.environ, {"GIT_CEILING_DIRECTORIES": str(tmp_path)}): + ctx = context(root) + with pytest.raises(CheckSkipped, match="not inside a git repository"): + EnvTrackedCheck().detect(ctx) + + def test_missing_git_is_skipped(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p") + with patch( + "fastapi_fastkit.backend.doctor.context.shutil.which", return_value=None + ): + with pytest.raises(CheckSkipped, match="git is not installed"): + EnvTrackedCheck().detect(context(root)) + + def test_is_never_fixable(self) -> None: + with pytest.raises(FixRefused): + EnvTrackedCheck().plan_fix(None, []) # type: ignore[arg-type] + + +# ---------------------------------------------------------------------- +# 2. gitignore-env +# ---------------------------------------------------------------------- + + +class TestGitignoreEnv: + @pytest.mark.parametrize( + "lines,name,expected", + [ + ([".env"], ".env", True), + (["/.env"], ".env", True), + (["**/.env"], ".env", True), + ([".env*"], ".env.example", True), + ([".env*", "!.env.example"], ".env.example", False), + (["env"], ".env", False), + ([".env/"], ".env", False), + (["config/.env"], ".env", False), + (["# .env", ""], ".env", False), + (["\\#.env"], "#.env", True), + ([".env.*"], ".env.local", True), + ], + ) + def test_matcher(self, lines: List[str], name: str, expected: bool) -> None: + assert gitignore_ignores(lines, name) is expected + + def test_detects_missing_rules(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {".gitignore": "__pycache__/\nenv\n"}) + + messages = _messages(GitignoreEnvCheck(), root) + + assert len(messages) == 1 + assert ".env is not ignored" in messages[0] + assert ".env.*" in messages[0] + + def test_detects_ignored_example(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {".gitignore": ".env*\n"}) + + messages = _messages(GitignoreEnvCheck(), root) + + assert messages == [".env.example is ignored and cannot be committed."] + + def test_clean_gitignore_passes(self, tmp_path: Path) -> None: + assert _messages(GitignoreEnvCheck(), make_project(tmp_path / "p")) == [] + + def test_fix_appends_and_is_idempotent(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {".gitignore": "__pycache__/\nenv"}) + + _fix_and_recheck(GitignoreEnvCheck(), root) + + text = read_bytes(root, ".gitignore").decode() + assert text.startswith("__pycache__/\nenv\n\n# Local environment files") + assert text.endswith(".env\n.env.*\n!.env.example\n") + + def test_fix_keeps_crlf(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {".gitignore": b"node_modules/\r\nenv\r\n"}) + + _fix_and_recheck(GitignoreEnvCheck(), root) + + data = read_bytes(root, ".gitignore") + assert data.count(b"\r\n") == data.count(b"\n") + assert data.endswith(b"!.env.example\r\n") + + def test_fix_creates_missing_gitignore(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", remove=(".gitignore",)) + + assert _messages(GitignoreEnvCheck(), root) == [ + "The project has no .gitignore." + ] + _fix_and_recheck(GitignoreEnvCheck(), root) + + def test_unreadable_gitignore_is_skipped(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {".gitignore": b"\xff\xfe\x00bad"}) + + with pytest.raises(CheckSkipped): + GitignoreEnvCheck().detect(context(root)) + + @pytest.mark.parametrize( + "text,newline,expected", + [ + ("", "\n", "a\nb\n"), + ("x\n", "\n", "x\n\na\nb\n"), + ("x", "\n", "x\n\na\nb\n"), + ("x\r\ny\n", "", "x\r\ny\n\r\na\r\nb\r\n"), + ], + ) + def test_append_lines(self, text: str, newline: str, expected: str) -> None: + assert append_lines(text, newline, ["a", "b"]) == expected + + +# ---------------------------------------------------------------------- +# 3. env-example-missing +# ---------------------------------------------------------------------- + +SECRET_ENV = ( + "# local settings\n" + "SECRET_KEY=Zm9vYmFyYmF6cXV4cXV1eGNvcmdlZ3JhdWx0\n" + "ENVIRONMENT=development\n" + "PORT=8000\n" + "POSTGRES_PASSWORD=hunter2\n" + "DATABASE_URL=postgresql://user:pa55@db:5432/app\n" + 'export ANTHROPIC_API_KEY="sk-ant-abc123DEF456ghi789"\n' + "PROJECT_NAME=AbCdEfGhIjKlMnOpQrStUvWx12\n" + "# MCP_API_KEY=Xy12Ab34Cd56Ef78Gh90Ij12\n" + "# old key: Qw12Er34Ty56Ui78Op90As12Df34\n" + 'PRIVATE_KEY="-----BEGIN KEY-----\n' + "c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0\n" + '-----END KEY-----"\n' + "DEBUG=true # verbose\n" + # Found by review: a comment that does not look like a token, a + # scheme-less user:password@host on an allow-listed name, and an + # apostrophe inside a multi-line value followed by a "comment" line. + "# prod db password: Hunter2!\n" + "POSTGRES_SERVER=admin:Hunter2@db.prod\n" + 'MULTI="first\n' + "don't\n" + "# Hunter2-continued\n" + 'last"\n' + "HOST=localhost\n" +) + +SECRET_VALUES = [ + "Zm9vYmFyYmF6cXV4cXV1eGNvcmdlZ3JhdWx0", + "hunter2", + "pa55", + "sk-ant-abc123DEF456ghi789", + "AbCdEfGhIjKlMnOpQrStUvWx12", + "Xy12Ab34Cd56Ef78Gh90Ij12", + "Qw12Er34Ty56Ui78Op90As12Df34", + "c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0", + "Hunter2", + "db.prod", + "continued", +] + + +class TestEnvExampleMissing: + def test_detects_missing_example(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", remove=(".env.example",)) + + assert _messages(EnvExampleMissingCheck(), root) == [ + "There is no .env.example next to .env." + ] + + def test_example_present_passes(self, tmp_path: Path) -> None: + assert _messages(EnvExampleMissingCheck(), make_project(tmp_path / "p")) == [] + + def test_no_env_is_skipped(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", remove=(".env", ".env.example")) + + with pytest.raises(CheckSkipped): + EnvExampleMissingCheck().detect(context(root)) + + def test_fix_never_copies_a_secret(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", {".env": SECRET_ENV}, remove=(".env.example",) + ) + ctx = context(root) + edits = EnvExampleMissingCheck().plan_fix( + ctx, EnvExampleMissingCheck().detect(ctx) + ) + + content = edits[0].content + for secret in SECRET_VALUES: + assert secret not in content + assert secret not in edits[0].summary + assert "SECRET_KEY=\n" in content + assert "ENVIRONMENT=development\n" in content + assert "PORT=8000\n" in content + assert "DEBUG=true\n" in content + assert "export ANTHROPIC_API_KEY=\n" in content + assert "PROJECT_NAME=\n" in content # value looks like a secret + # Comments and commented-out assignments are dropped (fail closed). + assert "MCP_API_KEY" not in content + assert "local settings" not in content + assert "old key" not in content + assert "PRIVATE_KEY=\n" in content + assert "END KEY" not in content + assert "POSTGRES_SERVER=\n" in content # user info: blanked + assert "MULTI=\n" in content + assert "HOST=localhost\n" in content + assert "don't" not in content + # Only the header is a comment. + comments = [line for line in content.splitlines() if line.startswith("#")] + assert comments == content.splitlines()[: len(comments)] and len(comments) == 2 + + def test_fix_and_second_run(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", remove=(".env.example",)) + + _fix_and_recheck(EnvExampleMissingCheck(), root) + + assert read_bytes(root, ".env.example").endswith(b"SECRET_KEY=\n") + + def test_unreadable_env_refuses_the_fix(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", {".env": b"\xff\xfeA=1"}, remove=(".env.example",) + ) + ctx = context(root) + + with pytest.raises(FixRefused): + EnvExampleMissingCheck().plan_fix(ctx, []) + + def test_parse_env_forms(self) -> None: + entries = parse_env( + "A=1\nexport B='two words' # c\n# C=3\nD=x #y\nE=\"open\nstill\"\nF=6\n" + ) + + assert [(e.key, e.value, e.commented) for e in entries] == [ + ("A", "1", False), + ("B", "two words", False), + ("C", "3", True), + ("D", "x", False), + ("E", "open\nstill", False), + ("F", "6", False), + ] + + @pytest.mark.parametrize( + "value,expected", + [ + ("development", False), + ("8000", False), + ("http://localhost:3000,https://app.example.com", False), + ("postgresql://u:p@db/app", True), + ("Zm9vYmFyYmF6cXV4cXV1eGNvcmdl", True), + ("abcdefghijklmnopqrstuvwxyz", False), + ], + ) + def test_looks_like_secret(self, value: str, expected: bool) -> None: + assert looks_like_secret(value) is expected + + def test_build_env_example_reports_keys(self) -> None: + _, kept, blanked = build_env_example("ENVIRONMENT=dev\nSECRET_KEY=x\n\n\n") + + assert kept == ["ENVIRONMENT"] + assert blanked == ["SECRET_KEY"] + + +# ---------------------------------------------------------------------- +# 4. example-secret +# ---------------------------------------------------------------------- + + +class TestExampleSecret: + @pytest.mark.parametrize("value", sorted(KNOWN_EXAMPLE_SECRETS)) + def test_detects_example_value_in_env(self, tmp_path: Path, value: str) -> None: + root = make_project(tmp_path / "p", {".env": f"SECRET_KEY={value}\n"}) + + messages = _messages(ExampleSecretCheck(), root) + + assert messages == [".env sets SECRET_KEY to an example value."] + assert value not in messages[0] + + def test_detects_env_variants_but_not_examples(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + ".env.production": "SESSION_SECRET_KEY='change-me-in-production'\n", + ".env.example": "SECRET_KEY=changethis\n", + ".env.sample": "SECRET_KEY=changethis\n", + }, + ) + + assert _messages(ExampleSecretCheck(), root) == [ + ".env.production sets SESSION_SECRET_KEY to an example value." + ] + + def test_detects_hard_coded_values(self, tmp_path: Path) -> None: + code = ( + "import os\n" + "from pydantic import Field\n" + "\n" + "class Settings:\n" + ' SECRET_KEY: str = "your-secret-key-here-change-in-production"\n' + ' OTHER = Field(default="changethis")\n' + "\n" + 'KEY = os.getenv("JWT_SECRET", "changethis-please-use-openssl-rand-hex-32")\n' + 'def sign(data, key="changethis", *, alt="your-secret-key-here"):\n' + " return data\n" + 'self_key = os.environ.get("X", "change-me-in-production")\n' + ) + root = make_project(tmp_path / "p", {"src/core/config.py": code}) + + messages = _messages(ExampleSecretCheck(), root) + + assert messages == [ + "src/core/config.py:5 sets SECRET_KEY to an example value.", + "src/core/config.py:6 sets default to an example value.", + "src/core/config.py:8 sets JWT_SECRET to an example value.", + "src/core/config.py:9 sets alt to an example value.", + "src/core/config.py:9 sets key to an example value.", + "src/core/config.py:11 sets X to an example value.", + ] + for value in KNOWN_EXAMPLE_SECRETS: + assert all(value not in m for m in messages) + + def test_guards_tests_and_comments_do_not_count(self, tmp_path: Path) -> None: + guard = ( + "KNOWN_EXAMPLE_SECRET_KEYS = frozenset({'changethis', 'changethis-please-use-openssl-rand-hex-32'})\n" + "def check(value):\n" + " if value == 'changethis':\n" + " raise ValueError('example key')\n" + "# SECRET_KEY = 'changethis'\n" + ) + root = make_project( + tmp_path / "p", + { + "src/core/config.py": guard, + "tests/test_config.py": "Settings(SECRET_KEY='changethis')\n", + "src/broken.py": "def (:\n", + }, + ) + + assert _messages(ExampleSecretCheck(), root) == [] + + def test_virtualenvs_are_not_scanned(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + ".venv/lib/x.py": "SECRET_KEY = 'changethis'\n", + "myenv/pyvenv.cfg": "home = /usr\n", + "myenv/lib/y.py": "SECRET_KEY = 'changethis'\n", + }, + ) + + assert _messages(ExampleSecretCheck(), root) == [] + + def test_is_advisory(self) -> None: + assert ExampleSecretCheck.fixable is False + assert "token_urlsafe" in ExampleSecretCheck.remediation + assert "log in again" in ExampleSecretCheck.remediation + + +# ---------------------------------------------------------------------- +# 5. app-module-missing +# ---------------------------------------------------------------------- + + +class TestAppModuleMissing: + def test_detects_missing_module(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", remove=("src/main.py",)) + + assert _messages(AppModuleMissingCheck(), root) == [ + "app_module = src.main:app but src/main.py / src/main/__init__.py " + "does not exist." + ] + + def test_module_or_package_passes(self, tmp_path: Path) -> None: + assert _messages(AppModuleMissingCheck(), make_project(tmp_path / "a")) == [] + package = make_project( + tmp_path / "b", + {"src/main/__init__.py": ""}, + remove=("src/main.py",), + ) + assert _messages(AppModuleMissingCheck(), package) == [] + + def test_no_app_module_recorded_is_skipped(self, tmp_path: Path) -> None: + pyproject = CLEAN_PYPROJECT.replace('app_module = "src.main:app"\n', "") + root = make_project(tmp_path / "p", {"pyproject.toml": pyproject}) + + with pytest.raises(CheckSkipped, match="no app_module"): + AppModuleMissingCheck().detect(context(root)) + + def test_without_metadata_is_skipped(self, tmp_path: Path) -> None: + pyproject = CLEAN_PYPROJECT.replace(DEFAULT_METADATA, "") + root = make_project(tmp_path / "p", {"pyproject.toml": pyproject}) + ctx = ProjectContext.load(str(root), force=True) + + with pytest.raises(CheckSkipped, match="metadata"): + AppModuleMissingCheck().detect(ctx) + + +# ---------------------------------------------------------------------- +# 6. mcp-auth / mcp-demo-users +# ---------------------------------------------------------------------- + +MCP_PYPROJECT = CLEAN_PYPROJECT.replace( + 'template = "fastapi-empty"', 'template = "fastapi-mcp"' +) + +OLD_MCP_ROUTER = """from fastapi import FastAPI +from fastapi_mcp import FastApiMCP + + +def create_mcp_router(app: FastAPI) -> FastApiMCP: + mcp = FastApiMCP(app) + return mcp +""" + +NEW_MCP_ROUTER = """from fastapi import Depends, FastAPI +from fastapi_mcp import AuthConfig, FastApiMCP + +from src.auth.dependencies import verify_mcp_access + + +def create_mcp_router(app: FastAPI) -> FastApiMCP: + return FastApiMCP( + app, + auth_config=AuthConfig(dependencies=[Depends(verify_mcp_access)]), + ) +""" + +OLD_MCP_USERS = """mock_users = { + "user1": {"username": "user1", "hashed_password": hash("password123")}, + "admin": {"username": "admin", "hashed_password": hash("admin123")}, +} +""" + +NEW_MCP_USERS = """from src.core.config import settings + +DEMO_USER_CREDENTIALS = {"user1": "password123", "admin": "admin123"} + + +def get_users_db() -> dict: + if settings.ENABLE_DEMO_USERS: + return dict(DEMO_USER_CREDENTIALS) + return {} +""" + + +class TestMcp: + def test_detects_unauthenticated_server(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + "pyproject.toml": MCP_PYPROJECT, + "src/mcp_server/router.py": OLD_MCP_ROUTER, + }, + ) + + assert _messages(McpAuthCheck(), root) == [ + "src/mcp_server/router.py:6 creates FastApiMCP without auth_config." + ] + + def test_authenticated_server_passes(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + "pyproject.toml": MCP_PYPROJECT, + "src/mcp_server/router.py": NEW_MCP_ROUTER, + }, + ) + + assert _messages(McpAuthCheck(), root) == [] + + def test_mcp_found_through_imports(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + "src/mcp.py": "import fastapi_mcp\n\nfastapi_mcp.FastApiMCP(app)\n", + }, + ) + + assert len(_messages(McpAuthCheck(), root)) == 1 + + def test_non_mcp_project_is_skipped(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p") + + for check in (McpAuthCheck(), McpDemoUsersCheck()): + with pytest.raises(CheckSkipped, match="not a fastapi-mcp project"): + check.detect(context(root)) + + def test_detects_ungated_demo_users(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + {"pyproject.toml": MCP_PYPROJECT, "src/api/routes/auth.py": OLD_MCP_USERS}, + ) + + messages = _messages(McpDemoUsersCheck(), root) + + assert messages == [ + "src/api/routes/auth.py:2 defines demo accounts with known passwords " + "that are not gated by ENABLE_DEMO_USERS." + ] + assert "password123" not in messages[0] + + def test_gated_demo_users_pass(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + "pyproject.toml": MCP_PYPROJECT, + "src/api/routes/auth.py": NEW_MCP_USERS, + "tests/test_auth.py": OLD_MCP_USERS, + "src/other.py": "from x import ENABLE_DEMO_USERS\nP = 'admin123'\n", + }, + ) + + assert _messages(McpDemoUsersCheck(), root) == [] + + +# ---------------------------------------------------------------------- +# 7. gitattributes-missing / crlf-scripts +# ---------------------------------------------------------------------- + + +class TestGitattributes: + def test_detects_missing_file(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", remove=(".gitattributes",)) + + assert _messages(GitattributesMissingCheck(), root) == [ + "The project has no .gitattributes." + ] + + def test_present_file_passes(self, tmp_path: Path) -> None: + assert ( + _messages(GitattributesMissingCheck(), make_project(tmp_path / "p")) == [] + ) + + def test_fix_writes_the_template_file(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", remove=(".gitattributes",)) + + _fix_and_recheck(GitattributesMissingCheck(), root) + + template = Path(TEMPLATE_ROOT, "fastapi-empty", ".gitattributes-tpl") + expected = template.read_bytes().replace(b"\r\n", b"\n") + assert read_bytes(root, ".gitattributes") == expected + assert b"*.sh text eol=lf" in expected + + def test_unknown_template_falls_back(self, tmp_path: Path) -> None: + pyproject = CLEAN_PYPROJECT.replace("fastapi-empty", "no-such-template") + root = make_project( + tmp_path / "p", {"pyproject.toml": pyproject}, remove=(".gitattributes",) + ) + + _fix_and_recheck(GitattributesMissingCheck(), root) + + def test_fix_refused_without_templates(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", remove=(".gitattributes",)) + ctx = ProjectContext.load(str(root), template_root=str(tmp_path / "none")) + + with pytest.raises(FixRefused): + GitattributesMissingCheck().plan_fix(ctx, []) + result = run_checks(ctx, [GitattributesMissingCheck()]).results[0] + assert result.status is CheckStatus.PROBLEM + assert not result.fixable + assert result.note and result.note.startswith("no automatic fix") + + +class TestCrlfScripts: + @pytest.mark.parametrize( + "path,expected", + [ + ("scripts/run.sh", True), + ("x.bash", True), + ("Dockerfile", True), + ("docker/Dockerfile.dev", True), + ("app.dockerfile", True), + ("README.md", False), + ("src/main.py", False), + ], + ) + def test_file_selection(self, path: str, expected: bool) -> None: + assert is_lf_only_file(path) is expected + + def test_detects_crlf_and_mixed_files(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + "scripts/run.sh": b"#!/bin/sh\r\necho hi\r\n", + "Dockerfile": b"FROM python:3.12\r\nRUN true\n", + "scripts/ok.sh": b"#!/bin/sh\necho ok\n", + "README.md": b"crlf\r\n", + }, + ) + + assert _messages(CrlfScriptsCheck(), root) == [ + "Dockerfile has CRLF line endings.", + "scripts/run.sh has CRLF line endings.", + ] + + def test_lf_files_pass(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"scripts/run.sh": b"#!/bin/sh\n"}) + + assert _messages(CrlfScriptsCheck(), root) == [] + + def test_fix_converts_and_is_idempotent(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + "scripts/run.sh": b"#!/bin/sh\r\necho hi\r\n", + "Dockerfile": b"FROM python:3.12\r\nRUN true\n", + }, + ) + + _fix_and_recheck(CrlfScriptsCheck(), root) + + assert read_bytes(root, "scripts/run.sh") == b"#!/bin/sh\necho hi\n" + assert read_bytes(root, "Dockerfile") == b"FROM python:3.12\nRUN true\n" + + def test_edits_show_no_diff(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"a.sh": b"x\r\n"}) + edits = CrlfScriptsCheck().plan_fix(context(root), []) + + assert [e.show_diff for e in edits] == [False] + + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + def test_fix_keeps_the_executable_bit(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"scripts/run.sh": b"#!/bin/sh\r\n"}) + script = root / "scripts" / "run.sh" + script.chmod(0o755) + + _fix_and_recheck(CrlfScriptsCheck(), root) + + assert stat.S_IMODE(script.stat().st_mode) == 0o755 + + +# ---------------------------------------------------------------------- +# 8. requires-python +# ---------------------------------------------------------------------- + + +class TestRequiresPython: + @pytest.mark.parametrize( + "constraint,expected", + [ + (">=3.12", (3, 12)), + (">=3.8", (3, 8)), + (">=3.12,<4", (3, 12)), + ("~=3.12", (3, 12)), + ("==3.12.*", (3, 12)), + ("^3.11", (3, 11)), + ("~3.13", (3, 13)), + (">=3.12 || >=3.9", (3, 9)), + ("<3.13", None), + ("^3.12 || <3.10", None), + ("3.12", (3, 12)), + ("", None), + ], + ) + def test_python_floor(self, constraint: str, expected: object) -> None: + assert python_floor(constraint) == expected + + def test_detects_low_floor(self, tmp_path: Path) -> None: + pyproject = CLEAN_PYPROJECT.replace(">=3.12", ">=3.8") + root = make_project(tmp_path / "p", {"pyproject.toml": pyproject}) + + assert _messages(RequiresPythonCheck(), root) == [ + 'requires-python = ">=3.8" allows Python older than 3.12.' + ] + + def test_detects_missing_constraint(self, tmp_path: Path) -> None: + pyproject = CLEAN_PYPROJECT.replace('requires-python = ">=3.12"\n', "") + root = make_project(tmp_path / "p", {"pyproject.toml": pyproject}) + + assert _messages(RequiresPythonCheck(), root) == [ + "pyproject.toml declares no requires-python." + ] + + def test_poetry_constraint(self, tmp_path: Path) -> None: + pyproject = ( + '[tool.poetry]\nname = "x"\n\n[tool.poetry.dependencies]\n' + 'python = "^3.11"\n' + DEFAULT_METADATA + ) + root = make_project(tmp_path / "p", {"pyproject.toml": pyproject}) + + assert len(_messages(RequiresPythonCheck(), root)) == 1 + + def test_template_floor_passes(self, tmp_path: Path) -> None: + assert _messages(RequiresPythonCheck(), make_project(tmp_path / "p")) == [] + + def test_invalid_toml_is_skipped(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"pyproject.toml": "[project\n"}) + ctx = ProjectContext.load(str(root), force=True) + + with pytest.raises(CheckSkipped): + RequiresPythonCheck().detect(ctx) + + +# ---------------------------------------------------------------------- +# 9. sqlalchemy-asyncio +# ---------------------------------------------------------------------- + +ASYNC_SESSION = "from sqlalchemy.ext.asyncio import create_async_engine\n" + + +def _sqlalchemy_pyproject(dependency: str = '"SQLAlchemy>=2.0.52",') -> str: + return CLEAN_PYPROJECT.replace( + ' "fastapi>=0.115",\n', f' "fastapi>=0.115",\n {dependency}\n' + ) + + +class TestSqlalchemyAsyncio: + @pytest.mark.parametrize( + "spec,expected", + [ + ("SQLAlchemy>=2.0", "SQLAlchemy[asyncio]>=2.0"), + ("sqlalchemy", "sqlalchemy[asyncio]"), + ("sqlalchemy[mypy] ==2.0.1", "sqlalchemy[mypy,asyncio] ==2.0.1"), + (" SQLAlchemy==2.0.52 ", " SQLAlchemy[asyncio]==2.0.52 "), + ], + ) + def test_with_asyncio_extra(self, spec: str, expected: str) -> None: + assert with_asyncio_extra(spec) == expected + + def test_detects_plain_dependency(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + "pyproject.toml": _sqlalchemy_pyproject(), + "requirements.txt": "fastapi\nSQLAlchemy==2.0.52 # orm\n", + "alembic/env.py": "import sqlalchemy.ext.asyncio\n", + }, + ) + + findings = SqlalchemyAsyncioCheck().detect(context(root)) + + assert findings[0].files == ("pyproject.toml", "requirements.txt") + + @pytest.mark.parametrize( + "extra_files", + [ + {"pyproject.toml": _sqlalchemy_pyproject('"SQLAlchemy[asyncio]>=2.0",')}, + {"requirements.txt": "greenlet==3.1\n"}, + {"src/db.py": "from sqlalchemy import create_engine\n"}, + ], + ) + def test_safe_setups_pass(self, tmp_path: Path, extra_files: dict) -> None: + files = {"pyproject.toml": _sqlalchemy_pyproject(), "src/db.py": ASYNC_SESSION} + files.update(extra_files) + root = make_project(tmp_path / "p", files) + + assert _messages(SqlalchemyAsyncioCheck(), root) == [] + + def test_fix_edits_both_files_and_is_idempotent(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + "pyproject.toml": _sqlalchemy_pyproject(), + "requirements.txt": b"fastapi\r\nSQLAlchemy==2.0.52 # orm\r\n", + "src/db.py": ASYNC_SESSION, + }, + ) + + _fix_and_recheck(SqlalchemyAsyncioCheck(), root) + + assert b'"SQLAlchemy[asyncio]>=2.0.52",' in read_bytes(root, "pyproject.toml") + assert read_bytes(root, "requirements.txt") == ( + b"fastapi\r\nSQLAlchemy[asyncio]==2.0.52 # orm\r\n" + ) + + def test_poetry_dependency_is_advisory(self, tmp_path: Path) -> None: + pyproject = ( + '[tool.poetry.dependencies]\npython = "^3.12"\nsqlalchemy = "^2.0"\n' + + DEFAULT_METADATA + ) + root = make_project( + tmp_path / "p", {"pyproject.toml": pyproject, "src/db.py": ASYNC_SESSION} + ) + + result = run_checks(context(root), [SqlalchemyAsyncioCheck()]).results[0] + + assert result.status is CheckStatus.PROBLEM + assert result.edits == [] + assert result.note and "Poetry" in result.note + + def test_unsafe_pyproject_is_advisory(self, tmp_path: Path) -> None: + pyproject = ( + 'project.name = "x"\nproject.dependencies = ["sqlalchemy"]\n' + + DEFAULT_METADATA + ) + root = make_project( + tmp_path / "p", {"pyproject.toml": pyproject, "src/db.py": ASYNC_SESSION} + ) + + result = run_checks(context(root), [SqlalchemyAsyncioCheck()]).results[0] + + assert result.status is CheckStatus.PROBLEM + assert result.edits == [] + assert result.note and "cannot be edited safely" in result.note + + +# ---------------------------------------------------------------------- +# 10. cors-credentials / 11. prometheus-lifespan +# ---------------------------------------------------------------------- + +OLD_CORS = """from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +app = FastAPI() +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, +) +""" + + +class TestCors: + def test_detects_wildcard_with_credentials(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"src/main.py": OLD_CORS}) + + assert _messages(CorsCredentialsCheck(), root) == [ + 'src/main.py:5 combines allow_origins=["*"] with allow_credentials=True.' + ] + + @pytest.mark.parametrize( + "replacement", + [ + ('allow_origins=["*"]', "allow_origins=settings.all_cors_origins"), + ("allow_credentials=True", "allow_credentials=False"), + ("allow_credentials=True", 'allow_credentials="*" not in origins'), + ], + ) + def test_safe_setups_pass(self, tmp_path: Path, replacement: tuple) -> None: + code = OLD_CORS.replace(*replacement) + root = make_project(tmp_path / "p", {"src/main.py": code}) + + assert _messages(CorsCredentialsCheck(), root) == [] + + def test_missing_app_module_is_skipped(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", remove=("src/main.py",)) + + with pytest.raises(CheckSkipped): + CorsCredentialsCheck().detect(context(root)) + + def test_unparseable_app_module_is_skipped(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"src/main.py": "app = (\n"}) + + with pytest.raises(CheckSkipped, match="could not be parsed"): + CorsCredentialsCheck().detect(context(root)) + + +OLD_PROMETHEUS = """from contextlib import asynccontextmanager + +from fastapi import FastAPI +from prometheus_fastapi_instrumentator import Instrumentator + + +@asynccontextmanager +async def startup(app): + Instrumentator().instrument(app).expose(app) + yield + + +app = FastAPI(lifespan=startup) +""" + + +class TestPrometheus: + def test_detects_lifespan_instrumentation(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"src/main.py": OLD_PROMETHEUS}) + + assert _messages(PrometheusLifespanCheck(), root) == [ + "src/main.py:9 instruments the app inside startup()." + ] + + def test_detects_startup_event(self, tmp_path: Path) -> None: + code = ( + "from fastapi import FastAPI\n" + "from prometheus_fastapi_instrumentator import Instrumentator\n" + "app = FastAPI()\n" + "@app.on_event('startup')\n" + "def boot():\n" + " Instrumentator().instrument(app)\n" + ) + root = make_project(tmp_path / "p", {"src/main.py": code}) + + assert len(_messages(PrometheusLifespanCheck(), root)) == 1 + + def test_module_level_instrumentation_passes(self, tmp_path: Path) -> None: + code = ( + "from fastapi import FastAPI\n" + "from prometheus_fastapi_instrumentator import Instrumentator\n" + "async def lifespan(app):\n" + " yield\n" + "app = FastAPI(lifespan=lifespan)\n" + "Instrumentator().instrument(app).expose(app)\n" + "@app.on_event('shutdown')\n" + "def stop():\n" + " Instrumentator()\n" + ) + root = make_project(tmp_path / "p", {"src/main.py": code}) + + assert _messages(PrometheusLifespanCheck(), root) == [] + + +# ---------------------------------------------------------------------- +# 12. pre-commit-python +# ---------------------------------------------------------------------- + +OLD_PRE_COMMIT = ( + "# header\n" + "default_language_version:\n" + " python: python3.12\n" + "\n" + "repos:\n" + " - repo: local\n" +) + + +class TestPreCommitPython: + def test_detects_pin(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {".pre-commit-config.yaml": OLD_PRE_COMMIT}) + + assert len(_messages(PreCommitPythonCheck(), root)) == 1 + + @pytest.mark.parametrize( + "content", + [ + "repos: []\n", + "default_language_version:\n node: system\nrepos: []\n", + "repos:\n - python: python3.12\n", + ], + ) + def test_unpinned_configs_pass(self, tmp_path: Path, content: str) -> None: + root = make_project(tmp_path / "p", {".pre-commit-config.yaml": content}) + + assert _messages(PreCommitPythonCheck(), root) == [] + + def test_missing_config_is_skipped(self, tmp_path: Path) -> None: + with pytest.raises(CheckSkipped): + PreCommitPythonCheck().detect(context(make_project(tmp_path / "p"))) + + def test_fix_removes_the_block(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {".pre-commit-config.yaml": OLD_PRE_COMMIT}) + + _fix_and_recheck(PreCommitPythonCheck(), root) + + assert read_bytes(root, ".pre-commit-config.yaml") == ( + b"# header\n\nrepos:\n - repo: local\n" + ) + + def test_fix_keeps_other_languages_and_crlf(self, tmp_path: Path) -> None: + content = ( + b"default_language_version:\r\n" + b" node: system\r\n" + b" python: 'python3.11' # pinned\r\n" + b"repos: []\r\n" + ) + root = make_project(tmp_path / "p", {".pre-commit-config.yaml": content}) + + _fix_and_recheck(PreCommitPythonCheck(), root) + + assert read_bytes(root, ".pre-commit-config.yaml") == ( + b"default_language_version:\r\n node: system\r\nrepos: []\r\n" + ) + + def test_block_at_start_of_file(self, tmp_path: Path) -> None: + content = "default_language_version:\n python: python3.12\n\nrepos: []\n" + root = make_project(tmp_path / "p", {".pre-commit-config.yaml": content}) + + _fix_and_recheck(PreCommitPythonCheck(), root) + + assert read_bytes(root, ".pre-commit-config.yaml") == b"repos: []\n" + + +# ---------------------------------------------------------------------- +# 13. session-secret +# ---------------------------------------------------------------------- + + +class TestSessionSecret: + def test_detects_old_session_module(self, tmp_path: Path) -> None: + code = ( + "import os\n" + "from starlette.middleware import Middleware\n" + "from starlette.middleware.sessions import SessionMiddleware\n" + 'KEY = os.getenv("SESSION_SECRET_KEY", "change-me-in-production")\n' + 'OTHER = os.environ.get("SESSION_SECRET_KEY", default="x")\n' + "class Settings:\n" + ' SESSION_SECRET_KEY: str = "change-me-in-production"\n' + 'app.add_middleware(SessionMiddleware, secret_key="literal-secret")\n' + 'middleware = [Middleware(SessionMiddleware, secret_key="x")]\n' + ) + root = make_project(tmp_path / "p", {"src/auth/session.py": code}) + + assert _messages(SessionSecretCheck(), root) == [ + "src/auth/session.py:4 reads SESSION_SECRET_KEY with a default value.", + "src/auth/session.py:5 reads SESSION_SECRET_KEY with a default value.", + "src/auth/session.py:7 declares a SESSION_SECRET_KEY setting with a " + "default value.", + "src/auth/session.py:8 passes a hard-coded secret_key to SessionMiddleware.", + "src/auth/session.py:9 passes a hard-coded secret_key to SessionMiddleware.", + ] + + def test_required_separate_session_key_passes(self, tmp_path: Path) -> None: + code = ( + "import os\n" + "from pydantic import Field\n" + "from starlette.middleware.sessions import SessionMiddleware\n" + 'KEY = os.environ["SESSION_SECRET_KEY"]\n' + 'MAYBE = os.getenv("SESSION_SECRET_KEY")\n' + "class Settings:\n" + " SESSION_SECRET_KEY: str\n" + "class Other:\n" + " SESSION_SECRET_KEY: str = Field(...)\n" + "class Third:\n" + ' SESSION_SECRET_KEY: str = Field(description="signing key")\n' + "app.add_middleware(SessionMiddleware, secret_key=settings.SESSION_SECRET_KEY)\n" + ) + root = make_project(tmp_path / "p", {"src/auth/session.py": code}) + + assert _messages(SessionSecretCheck(), root) == [] + + def test_field_with_default_is_reported(self, tmp_path: Path) -> None: + code = ( + "from pydantic import Field\n" + "class Settings:\n" + ' SESSION_SECRET_KEY: str = Field("x")\n' + "class Other:\n" + ' SESSION_SECRET_KEY: str = Field(default_factory=lambda: "x")\n' + "class Third:\n" + ' SESSION_SECRET_KEY = "x"\n' + ) + root = make_project(tmp_path / "p", {"src/auth/session.py": code}) + + assert [m.split()[0] for m in _messages(SessionSecretCheck(), root)] == [ + "src/auth/session.py:3", + "src/auth/session.py:5", + "src/auth/session.py:7", + ] + + def test_current_session_setup_passes(self, tmp_path: Path) -> None: + code = ( + "from starlette.middleware.sessions import SessionMiddleware\n" + "app.add_middleware(SessionMiddleware, secret_key=auth_settings.SECRET_KEY)\n" + "app.add_middleware(SessionMiddleware, **options)\n" + ) + root = make_project(tmp_path / "p", {"src/main.py": code}) + + assert _messages(SessionSecretCheck(), root) == [] + + +# ---------------------------------------------------------------------- +# Known example secrets stay in sync with the templates +# ---------------------------------------------------------------------- + +_QUOTED = re.compile(r'"([^"]+)"') +#: ``SECRET_KEY=value`` / ``# MCP_API_KEY=value`` lines of env files. +_ENV_SECRET = re.compile(r"^(?:#\s*)?(?:SECRET_KEY|MCP_API_KEY)=(\S+)$") + + +def _template_example_keys() -> List[str]: + keys: List[str] = [] + package_root = Path(TEMPLATE_ROOT).parent + fragments = package_root / "fragments" + sources = list(Path(TEMPLATE_ROOT).rglob("config.py-tpl")) + sources += list(fragments.rglob("*.j2")) + # The production guard fastkit adds to settings modules with auth. + keys += list(PUBLIC_EXAMPLE_SECRET_KEYS) + for source in sources: + text = source.read_text(encoding="utf-8") + match = re.search( + r"KNOWN_EXAMPLE_SECRET_KEYS = frozenset\(\s*\{(.*?)\}", text, re.S + ) + if match: + keys += _QUOTED.findall(match.group(1)) + env_files = list(Path(TEMPLATE_ROOT).glob("*/.env*-tpl")) + for env_example in env_files + list(fragments.rglob("*.j2")): + for line in env_example.read_text(encoding="utf-8").splitlines(): + match = _ENV_SECRET.match(line) + if match: + keys.append(match.group(1)) + # The ``.env.example`` block ``fastkit init`` writes. + with_auth = DynamicConfigGenerator({"authentication": "JWT"}, str(package_root)) + for variable, block in with_auth.env_example_blocks(): + if variable == "SECRET_KEY": + keys += [line.split("=", 1)[1] for line in block if "=" in line] + return keys + + +def test_known_example_secrets_cover_every_template_value() -> None: + keys = _template_example_keys() + + assert keys, "no example keys found in the templates" + assert set(keys) <= KNOWN_EXAMPLE_SECRETS + + +# ---------------------------------------------------------------------- +# Edge cases: unreadable files, unusual syntax, files gone before fixing +# ---------------------------------------------------------------------- + + +class TestEdgeCases: + def test_unusual_assignment_targets(self, tmp_path: Path) -> None: + code = ( + "class A:\n" + " def __init__(self):\n" + " self.SECRET_KEY = 'changethis'\n" + "store = {}\n" + "store['key'] = 'changethis'\n" + ) + root = make_project(tmp_path / "p", {"src/a.py": code}) + + assert _messages(ExampleSecretCheck(), root) == [ + "src/a.py:3 sets SECRET_KEY to an example value.", + "src/a.py:5 sets to an example value.", + ] + + def test_unreadable_env_variant_is_ignored(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {".env.local": b"\xff\xfe\x00"}) + + assert _messages(ExampleSecretCheck(), root) == [] + + def test_unreadable_script_is_ignored(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"bin.sh": b"\xff\xfe\r\n"}) + + assert _messages(CrlfScriptsCheck(), root) == [] + + @pytest.mark.parametrize( + "module", + ["from fastapi_mcp import FastApiMCP\n", "import fastapi_mcp.server\n"], + ) + def test_mcp_detected_from_any_import(self, tmp_path: Path, module: str) -> None: + root = make_project(tmp_path / "p", {"src/m.py": module}) + + assert McpAuthCheck().detect(context(root)) == [] # applies, no problem + + def test_cors_wildcard_string(self, tmp_path: Path) -> None: + code = OLD_CORS.replace('allow_origins=["*"]', 'allow_origins="*"') + root = make_project(tmp_path / "p", {"src/main.py": code}) + + assert len(_messages(CorsCredentialsCheck(), root)) == 1 + + def test_requirement_without_a_name(self) -> None: + from fastapi_fastkit.backend.doctor.checks_files import is_plain_sqlalchemy + + assert is_plain_sqlalchemy("./vendor/pkg") is False + assert with_asyncio_extra("./vendor/pkg") == "./vendor/pkg" + + def test_missing_pyproject(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", remove=("pyproject.toml",)) + ctx = ProjectContext.load(str(root), force=True, template_root=TEMPLATE_ROOT) + + with pytest.raises(CheckSkipped): + RequiresPythonCheck().detect(ctx) + assert ctx.app_module_file() is None + assert ctx.app_module_candidates() == [] + + def test_fixers_refuse_when_files_vanished(self, tmp_path: Path) -> None: + ctx = context(make_project(tmp_path / "p")) + check = SqlalchemyAsyncioCheck() + + with pytest.raises(FixRefused): + check._requirements_edit(ctx) + with pytest.raises(FixRefused): + PreCommitPythonCheck().plan_fix(ctx, []) + + empty = ProjectContext(str(tmp_path / "nothing"), {}, TEMPLATE_ROOT) + with pytest.raises(FixRefused): + check._pyproject_edit(empty) + + def test_pre_commit_fix_without_pin_changes_nothing(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {".pre-commit-config.yaml": "repos: []\n"}) + + assert PreCommitPythonCheck().plan_fix(context(root), []) == [] + + def test_pyproject_dependencies_not_located(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + {"pyproject.toml": _sqlalchemy_pyproject(), "src/db.py": ASYNC_SESSION}, + ) + with patch( + "fastapi_fastkit.backend.doctor.checks_files.replace_project_dependencies", + return_value=None, + ): + with pytest.raises(FixRefused, match="could not be located"): + SqlalchemyAsyncioCheck()._pyproject_edit(context(root)) + + def test_gitattributes_template_lookup(self, tmp_path: Path) -> None: + from fastapi_fastkit.backend.doctor.checks_files import template_gitattributes + + templates = tmp_path / "templates" + (templates / "fastapi-empty").mkdir(parents=True) + (templates / "fastapi-empty" / ".gitattributes-tpl").write_bytes(b"\xff\xfe") + (templates / "fastapi-default").mkdir() + (templates / "fastapi-default" / ".gitattributes-tpl").write_bytes( + b"*.sh text eol=lf\r\n" + ) + root = make_project(tmp_path / "p") + + assert template_gitattributes(ProjectContext(str(root), {}, None)) is None + no_template = ProjectContext(str(root), {}, str(templates)) + assert template_gitattributes(no_template) == "*.sh text eol=lf\n" + broken = ProjectContext( + str(root), {"template": "fastapi-empty"}, str(templates) + ) + assert template_gitattributes(broken) == "*.sh text eol=lf\n" diff --git a/tests/test_backends/test_doctor_checks_api.py b/tests/test_backends/test_doctor_checks_api.py new file mode 100644 index 0000000..bb3a2bd --- /dev/null +++ b/tests/test_backends/test_doctor_checks_api.py @@ -0,0 +1,316 @@ +# -------------------------------------------------------------------------- +# Tests for the doctor checks about code older ``fastkit init`` releases +# generated (backend/doctor/checks_api.py): each one detects the old shape +# and stays quiet on what v2.0.0 generates. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from pathlib import Path +from typing import List + +import pytest + +from fastapi_fastkit.backend.doctor import Check, run_checks +from fastapi_fastkit.backend.doctor.checks_api import ( + CommitAfterYieldCheck, + MotorDeprecatedCheck, + PaginationDemoCheck, + SettingsSprawlCheck, + SlowapiMiddlewareCheck, +) +from fastapi_fastkit.backend.doctor.model import CheckStatus, Severity +from fastapi_fastkit.backend.project_builder.config_generator import ( + DynamicConfigGenerator, +) +from tests.test_backends.doctor_helpers import CLEAN_PYPROJECT, context, make_project + +HEADER = ( + "# " + "-" * 74 + "\n# Database Configuration\n# Generated by FastAPI-fastkit\n" + "# " + "-" * 74 + "\n" +) + + +def _messages(check: Check, root: Path) -> List[str]: + return [f.message for f in check.detect(context(root))] + + +# ---------------------------------------------------------------------- +# commit-after-yield +# ---------------------------------------------------------------------- + +OLD_GET_DB = """async def get_db(): + async with SessionLocal() as session: + try: + yield session + await session.commit() + except Exception: + await session.rollback() + raise +""" + +CURRENT_GET_DB = """async def get_db(): + async with SessionLocal() as session: + try: + yield session + except Exception: + await session.rollback() + raise +""" + + +class TestCommitAfterYield: + def test_detects_the_pre_1_6_session_dependency(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"src/db.py": OLD_GET_DB}) + + assert _messages(CommitAfterYieldCheck(), root) == [ + "src/db.py:5 commits after yield in get_db()." + ] + + @pytest.mark.parametrize( + "code", + [ + # commit in ``else`` / ``finally`` of the try that yields + "def get_db():\n s = S()\n try:\n yield s\n" + " finally:\n s.commit()\n", + "def get_db():\n s = S()\n try:\n yield s\n" + " except Exception:\n s.rollback()\n else:\n s.commit()\n", + # plain sequence + "def get_db():\n s = S()\n yield s\n s.commit()\n", + ], + ) + def test_detects_other_shapes(self, tmp_path: Path, code: str) -> None: + root = make_project(tmp_path / "p", {"src/db.py": code}) + + assert len(_messages(CommitAfterYieldCheck(), root)) == 1 + + @pytest.mark.parametrize( + "code", + [ + CURRENT_GET_DB, + # a repository committing is the intended design + "class Repo:\n async def add(self, item):\n" + " self.session.add(item)\n await self.session.commit()\n", + # a unit-of-work context manager commits when its block succeeds + "from contextlib import contextmanager\n@contextmanager\n" + "def atomic(session):\n try:\n yield\n" + " session.commit()\n except BaseException:\n" + " session.rollback()\n raise\n", + # commit before yield, and a nested function after it + "def setup():\n s = S()\n s.commit()\n yield s\n" + " def later():\n s.commit()\n", + ], + ) + def test_quiet_on_current_code(self, tmp_path: Path, code: str) -> None: + root = make_project(tmp_path / "p", {"src/db.py": code}) + + assert _messages(CommitAfterYieldCheck(), root) == [] + + def test_generated_sqlalchemy_module_passes(self, tmp_path: Path) -> None: + module = DynamicConfigGenerator( + {"database": {"type": "PostgreSQL"}}, str(tmp_path) + ).generate_database_config() + assert module is not None + root = make_project(tmp_path / "p", {"src/config/database.py": module}) + + assert _messages(CommitAfterYieldCheck(), root) == [] + + def test_tests_are_not_checked(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"tests/conftest.py": OLD_GET_DB}) + + assert _messages(CommitAfterYieldCheck(), root) == [] + + +# ---------------------------------------------------------------------- +# slowapi-middleware +# ---------------------------------------------------------------------- + +OLD_RATE_LIMITING = """from slowapi import Limiter +from slowapi.middleware import SlowAPIMiddleware + +limiter = Limiter(key_func=lambda r: "k", default_limits=["100/minute"]) + + +def setup_rate_limiting(app): + app.state.limiter = limiter + app.add_middleware(SlowAPIMiddleware) +""" + + +class TestSlowapiMiddleware: + def test_detects_the_middleware(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"src/rate_limiting.py": OLD_RATE_LIMITING}) + + assert _messages(SlowapiMiddlewareCheck(), root) == [ + "src/rate_limiting.py:9 adds SlowAPIMiddleware." + ] + + def test_generated_rate_limiting_passes(self, tmp_path: Path) -> None: + modules = DynamicConfigGenerator( + {"utilities": ["Rate-Limiting"]}, str(tmp_path) + ).generate_feature_modules() + root = make_project( + tmp_path / "p", {"src/rate_limiting.py": modules["src/rate_limiting.py"]} + ) + + assert _messages(SlowapiMiddlewareCheck(), root) == [] + + +# ---------------------------------------------------------------------- +# motor-deprecated +# ---------------------------------------------------------------------- + + +class TestMotorDeprecated: + def test_detects_dependency_and_import(self, tmp_path: Path) -> None: + pyproject = CLEAN_PYPROJECT.replace( + '"fastapi>=0.115",', '"fastapi>=0.115",\n "motor>=3.3",' + ) + root = make_project( + tmp_path / "p", + { + "pyproject.toml": pyproject, + "requirements.txt": "fastapi\nMotor==3.6.0 # driver\n", + "src/db.py": "from motor.motor_asyncio import AsyncIOMotorClient\n", + }, + ) + + findings = CommitAfterYieldCheck().detect(context(root)) + assert findings == [] + (finding,) = MotorDeprecatedCheck().detect(context(root)) + assert finding.files == ("pyproject.toml", "requirements.txt", "src/db.py") + assert MotorDeprecatedCheck.severity is Severity.LOW + + def test_pymongo_passes(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + "requirements.txt": "pymongo>=4.13\n", + "src/db.py": "import pymongo\nfrom pymongo import AsyncMongoClient\n", + }, + ) + + assert _messages(MotorDeprecatedCheck(), root) == [] + + +# ---------------------------------------------------------------------- +# settings-sprawl +# ---------------------------------------------------------------------- + +OLD_AUTH = HEADER + """import os + +from pydantic_settings import BaseSettings + + +class AuthSettings(BaseSettings): + SECRET_KEY: str = "x" + + +REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0") +LEVEL = os.environ.get("LOG_LEVEL") +""" + + +class TestSettingsSprawl: + def test_detects_second_settings_class_and_getenv(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"src/auth/jwt.py": OLD_AUTH}) + + assert _messages(SettingsSprawlCheck(), root) == [ + "src/auth/jwt.py: class AuthSettings, os.getenv(REDIS_URL), " + "os.getenv(LOG_LEVEL)." + ] + assert SettingsSprawlCheck.severity is Severity.LOW + + def test_template_modules_are_not_checked(self, tmp_path: Path) -> None: + # No "Generated by FastAPI-fastkit" header: the user's or a template's code. + root = make_project( + tmp_path / "p", {"src/custom.py": OLD_AUTH.replace(HEADER, "")} + ) + + assert _messages(SettingsSprawlCheck(), root) == [] + + def test_generated_settings_module_passes(self, tmp_path: Path) -> None: + settings = DynamicConfigGenerator( + {"authentication": "JWT", "database": {"type": "SQLite"}}, str(tmp_path) + ).generate_settings_module() + root = make_project(tmp_path / "p", {"src/core/config.py": settings}) + + assert _messages(SettingsSprawlCheck(), root) == [] + + def test_dynamic_env_name_is_reported_without_value(self, tmp_path: Path) -> None: + code = HEADER + "import os\nNAME = 'X'\nvalue = os.getenv(NAME)\n" + root = make_project(tmp_path / "p", {"src/x.py": code}) + + assert _messages(SettingsSprawlCheck(), root) == ["src/x.py: os.getenv(...)."] + + +# ---------------------------------------------------------------------- +# pagination-demo +# ---------------------------------------------------------------------- + +OLD_PAGINATION = """from fastapi import APIRouter +from fastapi_pagination import Page, paginate + +router = APIRouter(prefix="/api/v1/items", tags=["Items"]) + + +@router.get("") +async def list_items() -> Page[int]: + return paginate([1, 2]) +""" + +TEMPLATE_ITEMS = """from fastapi import APIRouter + +router = APIRouter(prefix="/items", tags=["items"]) +""" + + +class TestPaginationDemo: + def test_detects_the_shadowing_demo(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + "src/features/pagination.py": OLD_PAGINATION, + "src/api/routes/items.py": TEMPLATE_ITEMS, + }, + ) + + (finding,) = PaginationDemoCheck().detect(context(root)) + assert finding.files == ( + "src/features/pagination.py", + "src/api/routes/items.py", + ) + + def test_demo_without_an_items_list_passes(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", {"src/features/pagination.py": OLD_PAGINATION} + ) + + assert _messages(PaginationDemoCheck(), root) == [] + + def test_items_router_without_the_demo_passes(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"src/api/routes/items.py": TEMPLATE_ITEMS}) + + assert _messages(PaginationDemoCheck(), root) == [] + + +def test_new_checks_are_registered_and_advisory(tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"src/db.py": OLD_GET_DB}) + checks = [ + CommitAfterYieldCheck(), + SlowapiMiddlewareCheck(), + PaginationDemoCheck(), + MotorDeprecatedCheck(), + SettingsSprawlCheck(), + ] + + report = run_checks(context(root), checks) + + statuses = {r.check.id: r.status for r in report.results} + assert statuses["commit-after-yield"] is CheckStatus.PROBLEM + assert all( + status is CheckStatus.OK + for check_id, status in statuses.items() + if check_id != "commit-after-yield" + ) + assert report.edits == [] + assert all(not check.fixable for check in checks) diff --git a/tests/test_backends/test_doctor_hardening.py b/tests/test_backends/test_doctor_hardening.py new file mode 100644 index 0000000..3de929c --- /dev/null +++ b/tests/test_backends/test_doctor_hardening.py @@ -0,0 +1,885 @@ +# -------------------------------------------------------------------------- +# Regression tests for the ``fastkit doctor`` review findings: secrets in +# the generated ``.env.example`` and its diff, git running commands from +# an untrusted checkout, files that cannot be parsed hiding findings, +# monorepo ignore / attribute rules, symlinks under ``--fix``, URL +# redaction, hash-pinned requirements and the JSON output with --debug. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import io +import json +import os +import random +import stat +import string +import subprocess +import sys +from pathlib import Path +from typing import Callable, List, Tuple +from unittest.mock import patch + +import pytest +from click.testing import CliRunner, Result +from rich.console import Console + +from fastapi_fastkit.backend.doctor.checks_code import ( + AppModuleMissingCheck, + CorsCredentialsCheck, +) +from fastapi_fastkit.backend.doctor.checks_files import ( + GitattributesMissingCheck, + SqlalchemyAsyncioCheck, +) +from fastapi_fastkit.backend.doctor.checks_secrets import ( + EnvExampleMissingCheck, + ExampleSecretCheck, + GitignoreEnvCheck, +) +from fastapi_fastkit.backend.doctor.context import ( + GIT_HARDENING_OPTIONS, + GitUnavailable, + ProjectContext, + git_command, + git_environment, + valid_app_module, +) +from fastapi_fastkit.backend.doctor.envfile import ( + build_env_example, + is_safe_value, + looks_like_secret, + parse_env, +) +from fastapi_fastkit.backend.doctor.model import ( + CheckSkipped, + CheckStatus, + FixRefused, + PlannedEdit, +) +from fastapi_fastkit.backend.doctor.render import render_edits, report_to_json +from fastapi_fastkit.backend.doctor.runner import ( + _write_atomically, + apply_edits, + redact, + run_checks, +) +from fastapi_fastkit.cli import fastkit_cli +from fastapi_fastkit.core.settings import FastkitConfig +from tests.test_backends.doctor_helpers import ( + CLEAN_FILES, + context, + git, + make_project, + read_bytes, + requires_git, +) + +UNREADABLE_MARKER = "could not read" + + +def _doctor(*args: str, input: str = "") -> Result: + return CliRunner().invoke(fastkit_cli, ["doctor", *args], input=input) + + +def _status(report_results: list, check_id: str) -> CheckStatus: + return next(r.status for r in report_results if r.check.id == check_id) + + +# ---------------------------------------------------------------------- +# 1. .env.example never carries a secret +# ---------------------------------------------------------------------- + +REVIEW_ENV = ( + "# prod db password: Hunter2!\n" + "SECRET_KEY=abc\n" + "POSTGRES_SERVER=admin:Hunter2@db.prod\n" + 'X="a\n' + "don't\n" + "# Hunter2-continued\n" + '"\n' +) + + +class TestEnvExampleReviewInputs: + def test_review_reproducer_leaks_nothing(self) -> None: + content, kept, blanked = build_env_example(REVIEW_ENV) + + assert "Hunter2" not in content + assert "db.prod" not in content + assert "continued" not in content + assert kept == [] + assert blanked == ["SECRET_KEY", "POSTGRES_SERVER", "X"] + + def test_comments_are_replaced_by_a_neutral_header(self) -> None: + content, _, _ = build_env_example( + "# team notes: ask Bob\nENVIRONMENT=dev\n# MCP_API_KEY=abc\n" + ) + + lines = content.splitlines() + assert [line for line in lines if line.startswith("#")] == lines[:2] + assert "Bob" not in content + assert "MCP_API_KEY" not in content + assert lines[2:] == ["ENVIRONMENT=dev"] + + def test_scheme_less_user_info_on_allow_listed_names_is_blanked(self) -> None: + content, kept, _ = build_env_example( + "POSTGRES_SERVER=admin:pw@db\nHOST=user@host\nPOSTGRES_SERVER2=x\n" + ) + + assert "pw" not in content and "user@" not in content + assert kept == [] + + @pytest.mark.parametrize( + "text,value", + [ + ("A='it''s'\n", "it"), + ('A="say \\"hi\\""\n', 'say "hi"'), + ("A='don\\'t'\n", "don't"), + ("export A=1\n", "1"), + ("\ufeffA=1\n", "1"), + ("A=x # note\n", "x"), + ("A=x#not-a-comment\n", "x#not-a-comment"), + ], + ) + def test_quoting(self, text: str, value: str) -> None: + assert parse_env(text)[0].value == value + + def test_same_quote_closes_a_multi_line_value(self) -> None: + entries = parse_env('A="one\ntwo\'s\nB=inside\n"\nC=3\n') + + assert [(e.key, e.multiline) for e in entries] == [ + ("A", True), + ("C", False), + ] + assert entries[0].value == "one\ntwo's\nB=inside\n" + + def test_commented_assignment_never_opens_a_value(self) -> None: + entries = parse_env('# A="open\nB=2\n') + + assert [(e.key, e.commented) for e in entries] == [("A", True), ("B", False)] + + def test_unclosed_value_swallows_the_rest(self) -> None: + content, kept, blanked = build_env_example('A="never closed\nHOST=localhost\n') + + assert blanked == ["A"] and kept == [] + assert "localhost" not in content + + def test_blank_line_groups_are_kept(self) -> None: + content, _, _ = build_env_example("A=1\n\n\nB=2\nB=3\n\n") + + assert content.splitlines()[2:] == ["A=", "", "B="] + + @pytest.mark.parametrize( + "value,safe", + [ + ("development", True), + ("8000", True), + ("http://localhost:3000,https://app.example.com", True), + ('["http://localhost:3000","https://a.b"]', True), + ("/api/v1", True), + ("db:5432", True), + ("admin:Hunter2", False), + ("user@host", False), + ("https://u:p@h", False), + ("a b!", False), + ("x" * 201, False), + ("Zm9vYmFyYmF6cXV4cXV1eGNvcmdl", False), + ("https://host/Zm9vYmFyYmF6cXV4", False), + ], + ) + def test_is_safe_value(self, value: str, safe: bool) -> None: + assert is_safe_value(value) is safe + + def test_user_info_always_looks_like_a_secret(self) -> None: + assert looks_like_secret("admin:pw@db") + + +def _random_token(rng: random.Random) -> str: + """A credential-looking token: long, mixed case and digits.""" + length = rng.randint(20, 40) + alphabet = string.ascii_letters + string.digits + while True: + token = "".join(rng.choice(alphabet) for _ in range(length)) + if ( + any(c.islower() for c in token) + and any(c.isupper() for c in token) + and any(c.isdigit() for c in token) + ): + return token + + +#: Ways to hide a token in a ``.env``; ``{t}`` is the token. +PLACEMENTS: List[Callable[[str], str]] = [ + lambda t: f"# {t}\n", + lambda t: f"# password is {t}!\n", + lambda t: f"#{t}=old\n", + lambda t: f"SECRET_KEY={t}\n", + lambda t: f"HOST={t}\n", + lambda t: f"PROJECT_NAME={t}\n", + lambda t: f"POSTGRES_SERVER=admin:{t}@db.internal\n", + lambda t: f"POSTGRES_SERVER={t}@db\n", + lambda t: f"BACKEND_CORS_ORIGINS=https://u:{t}@app.example.com\n", + lambda t: f"BACKEND_CORS_ORIGINS=https://app.example.com/{t}\n", + lambda t: f'BACKEND_CORS_ORIGINS=["https://{t}.example.com"]\n', + lambda t: f"DATABASE_URL=postgresql://user:{t}@db/app\n", + lambda t: f'X="line one\ndon\'t\n# {t}\n"\n', + lambda t: f"X='multi\n{t}\n'\n", + lambda t: f'X="a\\"{t}"\n', + lambda t: f"HOST=localhost # {t}\n", + lambda t: f"export API_KEY='{t}'\n", + lambda t: f'PRIVATE_KEY="-----BEGIN-----\n{t}\nHOST={t}\n-----END-----"\n', + lambda t: f"LOG_LEVEL=info {t}\n", + lambda t: f"PORT={t[:6]}!{t[6:]}\n", +] + + +def _render_text(edits: List[PlannedEdit]) -> str: + buffer = io.StringIO() + render_edits(edits, Console(file=buffer, width=200, no_color=True)) + return buffer.getvalue() + + +class TestEnvExampleProperty: + """No token placed anywhere in .env reaches the file, the diff or JSON.""" + + def test_random_tokens_never_leak(self, tmp_path: Path) -> None: + rng = random.Random(20261201) + for case in range(120): + tokens = [_random_token(rng) for _ in range(3)] + body = "ENVIRONMENT=development\n" + for token in tokens: + body += rng.choice(PLACEMENTS)(token) + if rng.random() < 0.3: + body += "\n" + body += "TZ=UTC\n" + root = make_project( + tmp_path / f"p{case}", {".env": body}, remove=(".env.example",) + ) + + report = run_checks(context(root)) + edits = [e for e in report.edits if e.path == ".env.example"] + assert len(edits) == 1, body + outputs = { + "planned file": edits[0].content, + "summary": edits[0].summary, + "rendered diff": _render_text(edits), + "json": json.dumps(report_to_json(report, planned=edits)), + } + for token in tokens: + for name, text in outputs.items(): + assert token not in text, (name, body) + assert "ENVIRONMENT=development" in edits[0].content + assert "TZ=UTC" in edits[0].content + + def test_cli_text_json_and_debug_log_never_leak( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + log_file = tmp_path / "fastkit.log" + monkeypatch.setattr( + FastkitConfig, + "_writable_log_file_path", + staticmethod(lambda preferred: str(log_file)), + ) + rng = random.Random(7) + tokens = [_random_token(rng) for _ in PLACEMENTS] + body = "".join(place(token) for place, token in zip(PLACEMENTS, tokens)) + root = make_project(tmp_path / "p", {".env": body}, remove=(".env.example",)) + + runner = CliRunner() + text = runner.invoke(fastkit_cli, ["--debug", "doctor", str(root), "--dry-run"]) + as_json = runner.invoke( + fastkit_cli, + ["--debug", "doctor", str(root), "--dry-run", "--format", "json"], + ) + applied = runner.invoke( + fastkit_cli, ["--debug", "doctor", str(root), "--fix", "--yes"] + ) + + assert text.exit_code == 1, text.output + assert as_json.exit_code == 1 + assert applied.exit_code in (0, 1), applied.output + assert log_file.is_file() + log = log_file.read_text(encoding="utf-8", errors="replace") + written = read_bytes(root, ".env.example").decode("utf-8") + assert ".env.example" in text.output + for token in tokens: + assert token not in text.output + assert token not in as_json.output + assert token not in applied.output + assert token not in log + assert token not in written + document = json.loads(as_json.stdout) + planned = document["fix"]["planned"] + assert any(item["path"] == ".env.example" for item in planned) + + +# ---------------------------------------------------------------------- +# 2. git never runs repository-configured commands +# ---------------------------------------------------------------------- + + +def _marker_hook(tmp_path: Path) -> Tuple[Path, str]: + """A ``core.fsmonitor`` command that creates a marker file.""" + marker = tmp_path / "PWNED" + script = tmp_path / "hook.py" + script.write_text( + f"open({str(marker)!r}, 'w').close()\nraise SystemExit(1)\n", + encoding="utf-8", + ) + python = Path(sys.executable).as_posix() + return marker, f'"{python}" "{script.as_posix()}"' + + +@requires_git +class TestGitHardening: + def test_argv_and_environment(self) -> None: + argv = git_command("git", "ls-files") + + assert argv[:3] == ["git", "--no-pager", "--no-optional-locks"] + assert "core.fsmonitor=false" in argv + assert "protocol.allow=never" in argv + assert argv[-1] == "ls-files" + assert set(GIT_HARDENING_OPTIONS) <= set(argv) + env = git_environment() + assert env["GIT_OPTIONAL_LOCKS"] == "0" + assert env["GIT_NO_LAZY_FETCH"] == "1" + assert env["GIT_TERMINAL_PROMPT"] == "0" + + def test_fsmonitor_of_the_checkout_is_never_run(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p") + git(root, "init", "-q") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "init") + marker, hook = _marker_hook(tmp_path) + git(root, "config", "core.fsmonitor", hook) + + # The hook really runs for a plain git call: the test is meaningful. + subprocess.run(["git", "ls-files"], cwd=root, capture_output=True, check=False) + if not marker.exists(): + pytest.skip("this git does not run core.fsmonitor for ls-files") + marker.unlink() + + ctx = context(root) + assert ".env" not in ctx.git_tracked(".env") + ctx.git_ignored([".env"]) + ctx.git_attributes(["x.sh"], "eol") + result = _doctor(str(root), "--format", "json") + + assert not marker.exists() + assert json.loads(result.stdout)["exit_code"] in (0, 1) + assert not marker.exists() + + +# ---------------------------------------------------------------------- +# 3. A BOM or a file that cannot be parsed never hides findings +# ---------------------------------------------------------------------- + +INSECURE_MAIN = ( + "from fastapi import FastAPI\n" + "from starlette.middleware.cors import CORSMiddleware\n" + "from starlette.middleware.sessions import SessionMiddleware\n" + "app = FastAPI()\n" + 'app.add_middleware(SessionMiddleware, secret_key="changethis")\n' + 'app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True)\n' +) + + +class TestUnparseableFiles: + def test_bom_is_ignored_in_python_toml_and_env(self, tmp_path: Path) -> None: + bom = "\ufeff" + pyproject = bom + str(CLEAN_FILES["pyproject.toml"]) + root = make_project( + tmp_path / "p", + { + "src/main.py": (bom + INSECURE_MAIN).encode("utf-8"), + "pyproject.toml": pyproject.encode("utf-8"), + ".env": (bom + "SECRET_KEY=changethis\n").encode("utf-8"), + }, + ) + + report = run_checks(context(root)) + + assert report.unreadable == {} + problems = {r.check.id for r in report.results if r.findings} + assert {"example-secret", "session-secret", "cors-credentials"} <= problems + assert report.exit_code == 1 + env_findings = [ + f.message + for r in report.results + for f in r.findings + if ".env " in f.message + ] + assert any("SECRET_KEY" in message for message in env_findings) + + def test_syntax_error_in_the_app_module_is_an_error(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"src/main.py": "app = FastAPI(\n"}) + + report = run_checks(context(root)) + + cors = next(r for r in report.results if r.check.id == "cors-credentials") + assert cors.status is CheckStatus.ERROR + assert "src/main.py" in (cors.note or "") and "cannot be parsed" in ( + cors.note or "" + ) + assert _status(report.results, "example-secret") is CheckStatus.ERROR + assert list(report.unreadable) == ["src/main.py"] + assert report.exit_code == 2 + + def test_real_problems_win_over_unparsed_files(self, tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", + { + "src/broken.py": "def (:\n", + "src/settings.py": 'SECRET_KEY = "changethis"\n', + }, + ) + + report = run_checks(context(root)) + + secret = next(r for r in report.results if r.check.id == "example-secret") + assert secret.status is CheckStatus.PROBLEM + assert UNREADABLE_MARKER in (secret.note or "") + assert report.exit_code == 1 + + def test_non_utf8_python_file_is_reported(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"src/latin.py": b"x = '\xe9'\n"}) + + report = run_checks(context(root)) + + assert "not UTF-8" in report.unreadable["src/latin.py"] + assert report.exit_code == 2 + + def test_non_utf8_env_file_is_reported(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {".env.local": b"A=\xff\n"}) + + report = run_checks(context(root)) + + assert _status(report.results, "example-secret") is CheckStatus.ERROR + assert ".env.local" in report.unreadable + + def test_invalid_pyproject_under_force(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"pyproject.toml": "[project\n"}) + ctx = ProjectContext.load(str(root), force=True) + + report = run_checks(ctx) + + assert "not valid TOML" in report.unreadable["pyproject.toml"] + assert _status(report.results, "requires-python") is CheckStatus.ERROR + + @pytest.mark.skipif(os.name == "nt", reason="POSIX permissions") + def test_unlistable_directory_is_reported(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"src/locked/mod.py": "x = 1\n"}) + locked = root / "src" / "locked" + locked.chmod(0) + try: + if os.access(locked, os.R_OK): + pytest.skip("permissions are not enforced (running as root?)") + report = run_checks(context(root)) + finally: + locked.chmod(stat.S_IRWXU) + + assert "cannot be listed" in report.unreadable["src/locked"] + assert report.exit_code == 2 + + def test_cli_lists_unreadable_files_and_exits_2(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"src/main.py": "app = (\n"}) + + text = _doctor(str(root)) + as_json = _doctor(str(root), "--format", "json") + + assert text.exit_code == 2, text.output + assert "UNREADABLE FILES" in text.output + assert "src/main.py" in text.output + document = json.loads(as_json.stdout) + assert document["exit_code"] == 2 + assert document["unreadable"][0]["path"] == "src/main.py" + assert "No problems found" not in text.output + + def test_tree_is_walked_once_per_run(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p") + ctx = context(root) + calls = [] + real_walk = os.walk + + def counting_walk(*args, **kwargs): # type: ignore[no-untyped-def] + calls.append(args[0]) + return real_walk(*args, **kwargs) + + with patch("fastapi_fastkit.backend.doctor.context.os.walk", counting_walk): + run_checks(ctx) + + assert calls == [ctx.root] + + +# ---------------------------------------------------------------------- +# 6. app_module from metadata stays inside the project +# ---------------------------------------------------------------------- + + +class TestAppModuleContainment: + @pytest.mark.parametrize( + "value,valid", + [ + ("src.main:app", True), + ("main", True), + (".src.main:app", False), + ("src..main", False), + ("/etc/passwd", False), + ("src.main:app:x", False), + ("src.main:", False), + ("src/main:app", False), + ], + ) + def test_valid_app_module(self, value: str, valid: bool) -> None: + assert valid_app_module(value) is valid + + def test_hostile_app_module_is_reported_not_followed(self, tmp_path: Path) -> None: + outside = tmp_path / "outside" + outside.mkdir() + (outside / "main.py").write_text(INSECURE_MAIN, encoding="utf-8") + pyproject = str(CLEAN_FILES["pyproject.toml"]).replace( + 'app_module = "src.main:app"', 'app_module = ".outside.main:app"' + ) + root = make_project(tmp_path / "p", {"pyproject.toml": pyproject}) + ctx = context(root) + + assert ctx.app_module_candidates() == [] + messages = [f.message for f in AppModuleMissingCheck().detect(ctx)] + assert messages and "not a dotted module path" in messages[0] + report = run_checks(ctx) + assert _status(report.results, "cors-credentials") is CheckStatus.SKIPPED + + def test_symlinked_app_module_outside_is_not_read(self, tmp_path: Path) -> None: + outside = tmp_path / "outside" + outside.mkdir() + (outside / "main.py").write_text(INSECURE_MAIN, encoding="utf-8") + root = make_project(tmp_path / "p", remove=("src/main.py",)) + try: + os.symlink(outside / "main.py", root / "src" / "main.py") + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") + + ctx = context(root) + + assert ctx.app_module_file() is None + with pytest.raises(CheckSkipped): + CorsCredentialsCheck().detect(ctx) + + +# ---------------------------------------------------------------------- +# 7. Monorepos: parent .gitignore / .gitattributes count +# ---------------------------------------------------------------------- + + +@requires_git +class TestMonorepo: + @pytest.fixture + def monorepo(self, tmp_path: Path) -> Path: + repo = tmp_path / "repo" + repo.mkdir() + git(repo, "init", "-q") + (repo / ".gitignore").write_text( + ".env\n.env.*\n!.env.example\n", encoding="utf-8" + ) + (repo / ".gitattributes").write_text( + "* text=auto\n*.sh text eol=lf\nDockerfile text eol=lf\n", encoding="utf-8" + ) + return make_project( + repo / "services" / "api", remove=(".gitignore", ".gitattributes") + ) + + def test_parent_rules_satisfy_the_checks(self, monorepo: Path) -> None: + ctx = context(monorepo) + + assert GitignoreEnvCheck().detect(ctx) == [] + assert GitattributesMissingCheck().detect(ctx) == [] + report = run_checks(ctx) + assert report.exit_code == 0, [ + (r.check.id, r.note) for r in report.results if r.status.value != "ok" + ] + + def test_parent_without_rules_still_reports(self, monorepo: Path) -> None: + (monorepo.parent.parent / ".gitignore").write_text("*.pyc\n", encoding="utf-8") + (monorepo.parent.parent / ".gitattributes").unlink() + ctx = context(monorepo) + + messages = [f.message for f in GitignoreEnvCheck().detect(ctx)] + assert messages == [ + "The project has no .gitignore; .env is not ignored; .env.* files " + "(such as .env.local) are not ignored." + ] + assert GitattributesMissingCheck().detect(ctx) + edits = GitignoreEnvCheck().plan_fix(ctx, []) + assert [e.path for e in edits] == [".gitignore"] # the project's own file + + def test_parent_ignoring_the_example_is_reported(self, monorepo: Path) -> None: + (monorepo.parent.parent / ".gitignore").write_text(".env*\n", encoding="utf-8") + + messages = [f.message for f in GitignoreEnvCheck().detect(context(monorepo))] + + assert "cannot be committed" in messages[0] + + def test_outside_a_repository_the_builtin_matcher_is_used( + self, tmp_path: Path + ) -> None: + root = make_project(tmp_path / "p", remove=(".gitignore", ".gitattributes")) + ctx = context(root) + with patch.object(ctx, "git_root", side_effect=GitUnavailable("no repo")): + messages = [f.message for f in GitignoreEnvCheck().detect(ctx)] + attributes = [f.message for f in GitattributesMissingCheck().detect(ctx)] + + assert messages == ["The project has no .gitignore."] + assert attributes == ["The project has no .gitattributes."] + + def test_remediation_mentions_renormalize(self) -> None: + assert "git add --renormalize ." in GitattributesMissingCheck.remediation + + +# ---------------------------------------------------------------------- +# 8. --fix never writes through a symlink; temp files are unpredictable +# ---------------------------------------------------------------------- + + +def _symlink(target: Path, link: Path) -> None: + try: + os.symlink(target, link) + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") + + +class TestSymlinks: + def test_symlinked_files_are_not_fixed(self, tmp_path: Path) -> None: + shared = tmp_path / "shared" + shared.mkdir() + (shared / "shared.gitignore").write_text("*.pyc\n", encoding="utf-8") + (shared / "run.sh").write_bytes(b"#!/bin/sh\r\necho hi\r\n") + root = make_project(tmp_path / "p", remove=(".gitignore",)) + (root / "scripts").mkdir() + _symlink(shared / "shared.gitignore", root / ".gitignore") + _symlink(shared / "run.sh", root / "scripts" / "run.sh") + + report = run_checks(context(root)) + result = _doctor(str(root), "--fix", "--yes") + + notes = {r.check.id: r.note for r in report.results} + assert "symbolic link" in (notes["gitignore-env"] or "") + assert "symbolic link" in (notes["crlf-scripts"] or "") + assert not any(e.path in (".gitignore", "scripts/run.sh") for e in report.edits) + assert result.exit_code == 1, result.output + assert (root / ".gitignore").is_symlink() + assert (root / "scripts" / "run.sh").is_symlink() + assert (shared / "shared.gitignore").read_text(encoding="utf-8") == "*.pyc\n" + assert (shared / "run.sh").read_bytes() == b"#!/bin/sh\r\necho hi\r\n" + + def test_symlinked_parent_directory_is_refused(self, tmp_path: Path) -> None: + outside = tmp_path / "outside" + outside.mkdir() + root = make_project(tmp_path / "p") + _symlink(outside, root / "scripts") + edit = PlannedEdit( + path="scripts/new.sh", + content="echo\n", + newline="\n", + original=None, + summary="s", + check_id="c", + ) + + outcome = apply_edits(context(root), [edit]) + + assert outcome.applied == [] + assert "symbolic link" in outcome.failed[0][1] + assert list(outside.iterdir()) == [] + + @pytest.mark.parametrize("path", ["../escape.txt", "a/../../x", "/abs"]) + def test_paths_leaving_the_project_are_refused( + self, tmp_path: Path, path: str + ) -> None: + root = make_project(tmp_path / "p") + + assert context(root).unsafe_write_reason(path) is not None + + def test_temp_file_is_created_with_mkstemp(self, tmp_path: Path) -> None: + target = tmp_path / "file.txt" + target.write_text("old\n", encoding="utf-8") + # A predictable name that used to be followed if it existed. + decoy = tmp_path / f"file.txt.fastkit-doctor-{os.getpid()}.tmp" + decoy.write_text("decoy\n", encoding="utf-8") + + with patch( + "fastapi_fastkit.backend.doctor.runner.tempfile.mkstemp", + wraps=__import__("tempfile").mkstemp, + ) as mkstemp: + _write_atomically(str(target), "new\n", "\n") + + assert mkstemp.call_args.kwargs["dir"] == str(tmp_path) + assert target.read_text(encoding="utf-8") == "new\n" + assert decoy.read_text(encoding="utf-8") == "decoy\n" + assert sorted(p.name for p in tmp_path.iterdir()) == sorted( + ["file.txt", decoy.name] + ) + + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + def test_new_file_gets_the_umask_mode(self, tmp_path: Path) -> None: + target = tmp_path / "new.txt" + old = os.umask(0o022) + try: + _write_atomically(str(target), "x\n", "\n") + finally: + os.umask(old) + + assert stat.S_IMODE(target.stat().st_mode) == 0o644 + + +# ---------------------------------------------------------------------- +# 11-13. JSON with --debug, URL redaction, hash-pinned requirements +# ---------------------------------------------------------------------- + + +def test_debug_json_stdout_is_only_the_document( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr( + FastkitConfig, + "_writable_log_file_path", + staticmethod(lambda preferred: str(tmp_path / "fastkit.log")), + ) + root = make_project(tmp_path / "p") + + result = CliRunner().invoke( + fastkit_cli, ["--debug", "doctor", str(root), "--format", "json"] + ) + + document = json.loads(result.stdout) + assert document["schema_version"] == 1 + assert "debugging mode" in result.stderr + + +@pytest.mark.parametrize( + "text,expected", + [ + ("https://u:p@ss@host/x", "https://***@host/x"), + ("https://u:pa/ss@host/x", "https://***@host/x"), + ("postgresql://user:pw@db:5432/app", "postgresql://***@db:5432/app"), + ("see https://host/path ok", "see https://host/path ok"), + ('URL="redis://:p@ss@cache:6379/0"', 'URL="redis://***@cache:6379/0"'), + ("https://u:p@ss@ho st", "https://***@ho st"), + ("x://a@b@!!", "x://***"), + ], +) +def test_redact(text: str, expected: str) -> None: + assert redact(text) == expected + + +class TestHashPinnedRequirements: + ASYNC = {"src/db.py": "from sqlalchemy.ext.asyncio import create_async_engine\n"} + + def test_hash_pinned_file_is_advisory(self, tmp_path: Path) -> None: + requirements = "sqlalchemy==2.0.30 \\\n --hash=sha256:aaaa\nfastapi\n" + root = make_project( + tmp_path / "p", {**self.ASYNC, "requirements.txt": requirements} + ) + ctx = context(root) + check = SqlalchemyAsyncioCheck() + + assert check.detect(ctx) + with pytest.raises(FixRefused, match="hash"): + check.plan_fix(ctx, []) + report = run_checks(ctx) + result = next(r for r in report.results if r.check.id == check.id) + assert result.edits == [] and "hash" in (result.note or "") + + @pytest.mark.parametrize( + "line", ["sqlalchemy @ https://example.com/sa.whl", "sqlalchemy>=2 \\"] + ) + def test_unusual_lines_are_refused(self, tmp_path: Path, line: str) -> None: + root = make_project( + tmp_path / "p", {**self.ASYNC, "requirements.txt": line + "\nfastapi\n"} + ) + + with pytest.raises(FixRefused, match="not a plain requirement"): + SqlalchemyAsyncioCheck().plan_fix(context(root), []) + + def test_plain_line_with_marker_is_fixed(self, tmp_path: Path) -> None: + line = 'SQLAlchemy>=2.0,<3 ; python_version >= "3.12" # db' + root = make_project( + tmp_path / "p", {**self.ASYNC, "requirements.txt": line + "\n"} + ) + + edits = SqlalchemyAsyncioCheck().plan_fix(context(root), []) + + assert edits[0].content.startswith("SQLAlchemy[asyncio]>=2.0,<3 ;") + + +# ---------------------------------------------------------------------- +# 17. .env.example alternatives +# ---------------------------------------------------------------------- + + +@pytest.mark.parametrize("name", [".env.sample", ".env.template", ".env.dist"]) +def test_existing_example_variant_satisfies_the_check( + tmp_path: Path, name: str +) -> None: + root = make_project( + tmp_path / "p", {name: "SECRET_KEY=\n"}, remove=(".env.example",) + ) + ctx = context(root) + + assert EnvExampleMissingCheck().detect(ctx) == [] + assert not any(e.path == ".env.example" for e in run_checks(ctx).edits) + + +def test_example_secret_check_reads_bom_env(tmp_path: Path) -> None: + root = make_project( + tmp_path / "p", {".env": "\ufeffSECRET_KEY=changethis\n".encode("utf-8")} + ) + + messages = [f.message for f in ExampleSecretCheck().detect(context(root))] + + assert messages == [".env sets SECRET_KEY to an example value."] + + +def test_failing_check_ignore_falls_back_to_the_builtin_matcher( + tmp_path: Path, +) -> None: + root = make_project(tmp_path / "p") + ctx = context(root) + ok = subprocess.CompletedProcess( + [], 0, stdout=str(root).encode() + b"\n", stderr=b"" + ) + failed = subprocess.CompletedProcess([], 128, stdout=b"", stderr=b"fatal: bad") + with ( + patch( + "fastapi_fastkit.backend.doctor.context.subprocess.run", + side_effect=[ok, failed], + ), + patch( + "fastapi_fastkit.backend.doctor.context.shutil.which", return_value="git" + ), + ): + with pytest.raises(GitUnavailable, match="check-ignore failed: fatal: bad"): + ctx.git_ignored([".env"]) + with patch.object(ctx, "git_ignored", side_effect=GitUnavailable("x")): + assert GitignoreEnvCheck().detect(ctx) == [] + + +def test_git_attributes_parses_nul_separated_output(tmp_path: Path) -> None: + root = make_project(tmp_path / "p") + ctx = context(root) + ctx._git_checked, ctx._git_root = True, str(root) + output = b"x.sh\x00eol\x00lf\x00Dockerfile\x00eol\x00unspecified\x00" + done = subprocess.CompletedProcess([], 0, stdout=output, stderr=b"") + with ( + patch( + "fastapi_fastkit.backend.doctor.context.subprocess.run", return_value=done + ) as run, + patch( + "fastapi_fastkit.backend.doctor.context.shutil.which", return_value="git" + ), + ): + found = ctx.git_attributes(["x.sh", "Dockerfile"], "eol") + + assert found == {"x.sh": {"eol": "lf"}, "Dockerfile": {"eol": "unspecified"}} + assert run.call_args.kwargs["input"] == b"x.sh\x00Dockerfile\x00" + assert ctx.git_attributes([], "eol") == {} + assert ctx.git_ignored([]) == set() diff --git a/tests/test_backends/test_doctor_runner.py b/tests/test_backends/test_doctor_runner.py new file mode 100644 index 0000000..027e44d --- /dev/null +++ b/tests/test_backends/test_doctor_runner.py @@ -0,0 +1,523 @@ +# -------------------------------------------------------------------------- +# Tests of the ``fastkit doctor`` framework: project loading, the runner, +# applying edits, diffs and the Rich / JSON output. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import io +import json +import subprocess +from pathlib import Path +from typing import List +from unittest.mock import patch + +import pytest +from rich.console import Console + +from fastapi_fastkit.backend.doctor import ( + Check, + CheckSkipped, + CheckStatus, + DoctorError, + Finding, + PlannedEdit, + ProjectContext, + Severity, + apply_edits, + default_checks, + run_checks, +) +from fastapi_fastkit.backend.doctor.context import GitUnavailable, is_test_path +from fastapi_fastkit.backend.doctor.render import ( + JSON_SCHEMA_VERSION, + build_summary_table, + error_to_json, + render_edits, + render_header, + render_report, + report_to_json, +) +from fastapi_fastkit.backend.doctor.runner import edit_diff, redact +from tests.test_backends.doctor_helpers import ( + CLEAN_PYPROJECT, + DEFAULT_METADATA, + V151_FILES, + context, + make_project, + read_bytes, +) + +# ---------------------------------------------------------------------- +# Test doubles +# ---------------------------------------------------------------------- + + +class _Problem(Check): + id = "fake-problem" + title = "Fake problem" + severity = Severity.LOW + remediation = "Do the thing." + + def detect(self, ctx: ProjectContext) -> List[Finding]: + return [self.finding("something is wrong", "a.txt")] + + +class _Crash(Check): + id = "fake-crash" + title = "Crashes" + + def detect(self, ctx: ProjectContext) -> List[Finding]: + raise RuntimeError("boom") + + +class _Skip(Check): + id = "fake-skip" + title = "Skips" + + def detect(self, ctx: ProjectContext) -> List[Finding]: + raise CheckSkipped("does not apply") + + +class _Writer(_Problem): + fixable = True + + def __init__(self, check_id: str, path: str = "a.txt") -> None: + self.id = check_id + self.path = path + + def plan_fix( + self, ctx: ProjectContext, findings: List[Finding] + ) -> List[PlannedEdit]: + return [ + PlannedEdit( + path=self.path, + content="new\n", + newline="\n", + original=None, + summary="write a.txt", + check_id=self.id, + ) + ] + + +class _BrokenFixer(_Problem): + fixable = True + + def plan_fix( + self, ctx: ProjectContext, findings: List[Finding] + ) -> List[PlannedEdit]: + raise ValueError("planner bug") + + +class _EmptyFixer(_Problem): + fixable = True + + def plan_fix( + self, ctx: ProjectContext, findings: List[Finding] + ) -> List[PlannedEdit]: + return [] + + +# ---------------------------------------------------------------------- +# ProjectContext.load +# ---------------------------------------------------------------------- + + +class TestLoad: + def test_missing_directory(self, tmp_path: Path) -> None: + with pytest.raises(DoctorError, match="is not a directory"): + ProjectContext.load(str(tmp_path / "missing")) + + def test_not_a_fastkit_project(self, tmp_path: Path) -> None: + (tmp_path / "pyproject.toml").write_text( + "[project]\nname='x'\n", encoding="utf-8" + ) + + with pytest.raises(DoctorError, match="not a FastAPI-fastkit project"): + ProjectContext.load(str(tmp_path)) + + def test_pre_metadata_project_suggests_force(self, tmp_path: Path) -> None: + pyproject = CLEAN_PYPROJECT.replace(DEFAULT_METADATA, "") + root = make_project(tmp_path / "p", {"pyproject.toml": pyproject}) + + with pytest.raises(DoctorError, match="older than 1.4.0.*--force"): + ProjectContext.load(str(root)) + ctx = ProjectContext.load(str(root), force=True) + assert ctx.has_metadata is False + assert ctx.metadata == {} + + def test_invalid_pyproject(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"pyproject.toml": "[project\n"}) + + with pytest.raises(DoctorError, match="Cannot read"): + ProjectContext.load(str(root)) + assert ProjectContext.load(str(root), force=True).has_metadata is False + + def test_metadata_is_read(self, tmp_path: Path) -> None: + ctx = context(make_project(tmp_path / "p")) + + assert ctx.has_metadata + assert ctx.template == "fastapi-empty" + assert ctx.app_module == "src.main:app" + assert ctx.app_module_file() == "src/main.py" + + @pytest.mark.parametrize( + "path,expected", + [ + ("tests/test_x.py", True), + ("src/test/helpers.py", True), + ("conftest.py", True), + ("src/app_test.py", True), + ("src/main.py", False), + ("src/contest.py", False), + ], + ) + def test_is_test_path(self, path: str, expected: bool) -> None: + assert is_test_path(path) is expected + + +class TestGitHelpers: + def test_git_that_cannot_start(self, tmp_path: Path) -> None: + ctx = context(make_project(tmp_path / "p")) + with patch( + "fastapi_fastkit.backend.doctor.context.subprocess.run", + side_effect=OSError("denied"), + ): + with pytest.raises(GitUnavailable, match="could not be run"): + ctx.git_root() + + def test_ls_files_failure(self, tmp_path: Path) -> None: + ctx = context(make_project(tmp_path / "p")) + ok = subprocess.CompletedProcess([], 0, stdout=str(tmp_path) + "\n", stderr="") + failed = subprocess.CompletedProcess([], 128, stdout="", stderr="fatal: bad") + with patch( + "fastapi_fastkit.backend.doctor.context.subprocess.run", + side_effect=[ok, failed], + ): + with pytest.raises(GitUnavailable, match="fatal: bad"): + ctx.git_tracked(".env") + + +# ---------------------------------------------------------------------- +# Runner +# ---------------------------------------------------------------------- + + +class TestRunner: + def test_statuses_and_exit_codes(self, tmp_path: Path) -> None: + ctx = context(make_project(tmp_path / "p")) + + report = run_checks(ctx, [_Problem(), _Crash(), _Skip()]) + + statuses = [r.status for r in report.results] + assert statuses == [CheckStatus.PROBLEM, CheckStatus.ERROR, CheckStatus.SKIPPED] + assert report.results[1].note == "check failed: RuntimeError: boom" + assert report.results[2].note == "does not apply" + assert report.exit_code == 1 + assert run_checks(ctx, [_Crash()]).exit_code == 2 + assert run_checks(ctx, [_Skip()]).exit_code == 0 + + def test_fixer_failures_become_notes(self, tmp_path: Path) -> None: + ctx = context(make_project(tmp_path / "p")) + + broken, empty = run_checks(ctx, [_BrokenFixer(), _EmptyFixer()]).results + + assert broken.note == "no automatic fix: ValueError: planner bug" + assert empty.note == "no automatic fix: nothing to change" + assert not broken.fixable and not empty.fixable + + def test_two_fixes_of_one_file_are_not_combined(self, tmp_path: Path) -> None: + ctx = context(make_project(tmp_path / "p")) + + first, second = run_checks(ctx, [_Writer("one"), _Writer("two")]).results + + assert [e.check_id for e in first.edits] == ["one"] + assert second.edits == [] + assert second.note and "next run" in second.note + + def test_default_checks_have_unique_ids(self) -> None: + checks = default_checks() + ids = [check.id for check in checks] + + assert len(ids) == len(set(ids)) == 20 + for check in checks: + assert check.title and check.remediation + assert isinstance(check.severity, Severity) + + def test_count_by_severity(self, tmp_path: Path) -> None: + report = run_checks(context(make_project(tmp_path / "p")), [_Problem()]) + + assert report.count_by_severity() == {"high": 0, "medium": 0, "low": 1} + + +class TestApplyEdits: + def _edit(self, **kwargs: object) -> PlannedEdit: + values = dict( + path="a.txt", + content="new\n", + newline="\n", + original=None, + summary="s", + check_id="c", + ) + values.update(kwargs) + return PlannedEdit(**values) # type: ignore[arg-type] + + def test_creates_and_modifies(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"b.txt": b"old\r\n"}) + ctx = context(root) + edits = [ + self._edit(), + self._edit( + path="b.txt", + content="old\nmore\n", + newline="\r\n", + original="old\n", + original_newline="\r\n", + ), + ] + + outcome = apply_edits(ctx, edits) + + assert outcome.applied == ["a.txt", "b.txt"] + assert read_bytes(root, "a.txt") == b"new\n" + assert read_bytes(root, "b.txt") == b"old\r\nmore\r\n" + assert ( + sorted(p.name for p in root.iterdir() if "fastkit-doctor" in p.name) == [] + ) + + def test_refuses_files_changed_since_planning(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"a.txt": "edited\n", "b.txt": "x\n"}) + ctx = context(root) + + outcome = apply_edits( + ctx, + [ + self._edit(), # planned as new, but now exists + self._edit(path="b.txt", original="y\n"), + ], + ) + + assert outcome.applied == [] + assert [p for p, _ in outcome.failed] == ["a.txt", "b.txt"] + assert read_bytes(root, "a.txt") == b"edited\n" + + def test_write_errors_leave_no_temp_file(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", {"a.txt": "x\n"}) + ctx = context(root) + with patch( + "fastapi_fastkit.backend.doctor.runner.os.replace", + side_effect=OSError("disk full"), + ): + outcome = apply_edits(ctx, [self._edit(original="x\n")]) + + assert outcome.failed == [("a.txt", "disk full")] + assert read_bytes(root, "a.txt") == b"x\n" + assert [p.name for p in root.iterdir() if p.name.endswith(".tmp")] == [] + + +class TestDiffs: + def test_new_file_diff(self) -> None: + edit = PlannedEdit("x.txt", "a\nb", "\n", None, "s", "c") + + diff = edit_diff(edit) + + assert diff.startswith("--- /dev/null\n+++ b/x.txt\n") + assert "+a\n+b\n" in diff + + def test_crlf_is_shown_as_lf_and_credentials_redacted(self) -> None: + edit = PlannedEdit( + "requirements.txt", + "--index-url https://user:tok3n@pypi.example/simple\r\nb==1\r\n", + "", + "--index-url https://user:tok3n@pypi.example/simple\r\na==1\r\n", + "s", + "c", + ) + + diff = edit_diff(edit) + + assert "\r" not in diff + assert "tok3n" not in diff + assert "https://***@pypi.example" in diff + assert "-a==1\n+b==1\n" in diff + + def test_redact(self) -> None: + assert redact("postgres://u:p@db/x and http://plain/x") == ( + "postgres://***@db/x and http://plain/x" + ) + + +# ---------------------------------------------------------------------- +# Output +# ---------------------------------------------------------------------- + + +def _console(width: int) -> Console: + return Console(file=io.StringIO(), width=width, no_color=True, color_system=None) + + +class TestRender: + @pytest.mark.parametrize("width", [60, 80, 120]) + def test_check_ids_never_wrap(self, tmp_path: Path, width: int) -> None: + root = make_project(tmp_path / "p", base=V151_FILES) + report = run_checks(context(root)) + console = _console(width) + + render_report(report, console) + + output = console.file.getvalue() # type: ignore[attr-defined] + lines = output.splitlines() + for result in report.results: + assert any(result.check.id in line for line in lines), result.check.id + assert max(len(line) for line in lines) <= width + + @pytest.mark.parametrize("width", [60, 80]) + def test_long_project_path_folds_on_its_own_line( + self, tmp_path: Path, width: int + ) -> None: + deep = tmp_path.joinpath(*(f"segment{i}_" + "x" * 30 for i in range(3))) + root = make_project(deep / "p", base=V151_FILES) + report = run_checks(context(root)) + assert len(report.ctx.root) > width + console = _console(width) + + render_header(report, console) + + lines = console.file.getvalue().splitlines() # type: ignore[attr-defined] + assert lines[0] == "fastkit doctor" + assert max(len(line) for line in lines) <= width + # The path is folded, not truncated: its lines rejoin to the full path. + joined = "" + for line in lines[1:]: + assert line.startswith(" ") # indented under the title + joined += line.strip() + if len(joined) >= len(report.ctx.root): + break + assert joined == report.ctx.root + assert "…" not in "".join(lines) + # JSON output keeps the path as one string. + assert report_to_json(report)["project"]["path"] == report.ctx.root + + def test_markup_is_printed_verbatim(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", base=V151_FILES) + console = _console(100) + + render_report(run_checks(context(root)), console) + + output = console.file.getvalue() # type: ignore[attr-defined] + assert 'allow_origins=["*"]' in output + assert "[cors-credentials]" in output + assert "hunter2hunter2" not in output + assert "change-me-in-production" not in output + + def test_summary_table_has_one_row_per_check(self, tmp_path: Path) -> None: + report = run_checks( + context(make_project(tmp_path / "p")), [_Problem(), _Skip()] + ) + + assert build_summary_table(report).row_count == 2 + + def test_render_edits_hides_line_ending_diffs(self) -> None: + console = _console(80) + render_edits( + [ + PlannedEdit( + "a.sh", "x\n", "\n", "x\n", "convert a.sh", "c", "\r\n", False + ), + PlannedEdit("b.txt", "y\n", "\n", None, "create b.txt", "c"), + ], + console, + ) + + output = console.file.getvalue() # type: ignore[attr-defined] + assert "modify a.sh" in output and "--- a/a.sh" not in output + assert "create b.txt" in output and "+y" in output + + +class TestJson: + def test_document_shape(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", base=V151_FILES) + report = run_checks(context(root)) + + document = report_to_json(report) + + json.dumps(document) # serialisable + assert document["schema_version"] == JSON_SCHEMA_VERSION + assert set(document) == { + "schema_version", + "fastkit_version", + "project", + "summary", + "checks", + "findings", + "fix", + "unreadable", + "exit_code", + } + assert set(document["project"]) == { + "path", + "template", + "preset", + "generated_with", + "app_module", + "has_metadata", + } + assert document["project"]["generated_with"] == "1.5.1" + assert document["project"]["preset"] == "minimal" + assert set(document["summary"]) == { + "problems", + "fixable", + "by_severity", + "checks", + } + assert document["summary"]["problems"] == len(document["findings"]) + assert set(document["findings"][0]) == { + "check", + "severity", + "title", + "message", + "files", + "fixable", + "remediation", + } + assert set(document["checks"][0]) == { + "id", + "title", + "severity", + "status", + "fixable", + "note", + } + assert document["fix"] is None + assert document["exit_code"] == 1 + assert "hunter2hunter2" not in json.dumps(document) + + def test_fix_section(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", remove=(".gitattributes",)) + report = run_checks(context(root)) + + document = report_to_json(report, planned=report.edits, dry_run=True) + + assert document["fix"]["dry_run"] is True + assert document["fix"]["planned"][0]["path"] == ".gitattributes" + assert document["fix"]["planned"][0]["new_file"] is True + assert document["fix"]["planned"][0]["diff"].startswith("--- /dev/null") + assert document["fix"]["applied"] == [] and document["fix"]["failed"] == [] + + def test_error_document(self) -> None: + document = error_to_json("nope") + + assert document["error"] == "nope" + assert document["exit_code"] == 2 + assert document["schema_version"] == JSON_SCHEMA_VERSION + + +def test_render_shows_why_a_problem_is_not_fixable(tmp_path: Path) -> None: + report = run_checks(context(make_project(tmp_path / "p")), [_BrokenFixer()]) + console = _console(100) + + render_report(report, console) + + output = console.file.getvalue() # type: ignore[attr-defined] + assert output.count("no automatic fix: ValueError: planner bug") == 2 diff --git a/tests/test_backends/test_fragment_hardening.py b/tests/test_backends/test_fragment_hardening.py new file mode 100644 index 0000000..f4e3858 --- /dev/null +++ b/tests/test_backends/test_fragment_hardening.py @@ -0,0 +1,1059 @@ +# -------------------------------------------------------------------------- +# Hardening of the generated authentication, feature and Docker fragments, +# and of the settings injection (v2.0.0 generated-code review). +# +# The repository virtualenv has none of the generated projects' runtime +# dependencies, so these checks work on the rendered source (AST and text); +# the behaviour itself is pinned by the tests the fragments generate into +# each project. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +import ipaddress +import os +import re +import textwrap +from pathlib import Path +from types import SimpleNamespace +from typing import Any, Dict, List +from unittest.mock import patch + +import pytest +import yaml +from click.testing import CliRunner + +import fastapi_fastkit +from fastapi_fastkit.backend.project_builder.config_generator import ( + AUTH_GUARD_METHOD, + PUBLIC_EXAMPLE_SECRET_KEYS, + DynamicConfigGenerator, + SettingField, + SettingGroup, + SettingsInjectionError, + _verify_settings_injection, + auth_guard_lines, + ensure_import, + has_secret_key_guard, + inject_settings_fields, + inject_settings_validator, +) +from fastapi_fastkit.backend.project_builder.preset_layout import ( + PresetLayoutStrategist, + insert_before_cors, +) +from fastapi_fastkit.cli import _resolve_runserver_app_module, fastkit_cli +from fastapi_fastkit.core.exceptions import CLIExceptions +from fastapi_fastkit.core.settings import ( + AsyncTaskChoice, + AuthChoice, + FastkitConfig, + FeatureAxis, +) +from fastapi_fastkit.core.settings import TestingChoice as Tier + +TEMPLATES = Path(fastapi_fastkit.__file__).parent / "fastapi_project_template" + +GROUP = [SettingGroup("Demo", (SettingField("DEMO_URL", "str", '"x"'),))] + + +def _class(source: str, name: str = "Settings") -> ast.ClassDef: + return next( + node + for node in ast.parse(source).body + if isinstance(node, ast.ClassDef) and node.name == name + ) + + +def _members(source: str, name: str = "Settings") -> List[str]: + names: List[str] = [] + for node in _class(source, name).body: + if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + names.append(node.target.id) + elif isinstance(node, ast.Assign): + names.extend(t.id for t in node.targets if isinstance(t, ast.Name)) + elif isinstance(node, (ast.FunctionDef, ast.ClassDef)): + names.append(node.name) + return names + + +# -------------------------------------------------------------------------- +# Settings injection robustness +# -------------------------------------------------------------------------- + + +class TestSettingsInjectionShapes: + @pytest.mark.parametrize( + "source", + [ + "from pydantic_settings import BaseSettings\n\n" + "class Settings(BaseSettings): pass\n", + "from pydantic_settings import BaseSettings\n\n" + "class Settings(BaseSettings): A: str = 'a'; B: int = 1\n", + "from pydantic_settings import BaseSettings\n\n" + "class Settings(\n BaseSettings,\n): pass\n\nsettings = Settings()\n", + ], + ids=["pass", "fields-on-one-line", "multi-line-header"], + ) + def test_one_line_class_bodies(self, source: str) -> None: + fields = inject_settings_fields(source, GROUP) + validator = inject_settings_validator( + source, AUTH_GUARD_METHOD, auth_guard_lines(demo_users=True) + ) + + assert "DEMO_URL" in _members(fields) + assert AUTH_GUARD_METHOD in _members(validator) + + def test_tab_indented_class(self) -> None: + source = ( + "from pydantic_settings import BaseSettings\n\n" + "class Settings(BaseSettings):\n\tA: str = 'a'\n\n\tdef x(self):\n" + "\t\treturn 1\n" + ) + + fields = inject_settings_fields(source, GROUP) + both = inject_settings_validator( + fields, AUTH_GUARD_METHOD, auth_guard_lines(demo_users=False) + ) + + assert '\tDEMO_URL: str = "x"\n' in both + assert f'\t@model_validator(mode="after")\n\tdef {AUTH_GUARD_METHOD}' in both + assert "\t\tif self.ENVIRONMENT" in both + assert _members(both) == ["A", "DEMO_URL", "x", AUTH_GUARD_METHOD] + + def test_decorated_class_with_nested_class_and_docstring_only(self) -> None: + source = ( + "import dataclasses\n" + "from pydantic_settings import BaseSettings\n\n\n" + "@dataclasses.dataclass\n" + "class Settings(BaseSettings):\n" + ' """Docs only."""\n\n' + " class Config:\n" + " extra = 'ignore'\n" + ) + + updated = inject_settings_fields(source, GROUP) + + assert _members(updated) == ["DEMO_URL", "Config"] + assert ' """Docs only."""\n\n # Demo\n DEMO_URL' in updated + assert "@dataclasses.dataclass\nclass Settings" in updated + + def test_docstring_only_body(self) -> None: + source = ( + "from pydantic_settings import BaseSettings\n\n\n" + "class Settings(BaseSettings):\n" + ' """Docs only."""\n' + ) + + updated = inject_settings_validator( + inject_settings_fields(source, GROUP), + AUTH_GUARD_METHOD, + auth_guard_lines(demo_users=False), + ) + + assert _members(updated) == ["DEMO_URL", AUTH_GUARD_METHOD] + + def test_two_settings_classes_only_settings_changes(self) -> None: + source = ( + "from pydantic_settings import BaseSettings\n\n\n" + "class Other(BaseSettings):\n O: str = 'o'\n\n\n" + "class Settings(BaseSettings):\n S: str = 's'\n" + ) + + updated = inject_settings_fields(source, GROUP) + + assert _members(updated, "Other") == ["O"] + assert _members(updated) == ["S", "DEMO_URL"] + + @pytest.mark.parametrize( + "model_config", + [ + 'model_config = SettingsConfigDict(env_file=".env")', + "model_config: SettingsConfigDict = SettingsConfigDict(\n" + ' env_file=".env",\n extra="ignore",\n )', + "model_config = {'env_file': '.env'}", + ], + ) + def test_model_config_variants(self, model_config: str) -> None: + source = ( + "from pydantic_settings import BaseSettings, SettingsConfigDict\n\n\n" + f"class Settings(BaseSettings):\n {model_config}\n\n" + " @property\n def x(self) -> int:\n return 1\n" + ) + + updated = inject_settings_fields(source, GROUP) + + assert _members(updated) == ["model_config", "DEMO_URL", "x"] + + def test_crlf_module_keeps_its_line_endings(self, tmp_path: Path) -> None: + path = tmp_path / "src" / "core" / "config.py" + path.parent.mkdir(parents=True) + source = ( + "from pydantic_settings import BaseSettings\n\n\n" + "class Settings(BaseSettings): pass\n\n\nsettings = Settings()\n" + ) + path.write_bytes(source.replace("\n", "\r\n").encode("utf-8")) + generator = DynamicConfigGenerator( + {"authentication": "JWT", "database": {"type": "SQLite"}}, str(tmp_path) + ) + + generator.apply_settings_module() + + data = path.read_bytes() + assert data.count(b"\n") == data.count(b"\r\n") + members = _members(data.decode("utf-8")) + assert {"SECRET_KEY", "JWT_ALGORITHM", "DATABASE_URL"} <= set(members) + assert AUTH_GUARD_METHOD in members + + def test_model_validator_import_is_sorted_without_an_anchor(self) -> None: + source = ( + "from pydantic_settings import BaseSettings\n\n\n" + "class Settings(BaseSettings):\n A: str = 'a'\n" + ) + + updated = inject_settings_validator( + source, AUTH_GUARD_METHOD, auth_guard_lines(demo_users=False) + ) + + imports = [line for line in updated.splitlines() if line.startswith("from")] + assert imports == [ + "from pydantic import model_validator", + "from pydantic_settings import BaseSettings", + ] + + @pytest.mark.parametrize( + ("source", "line", "expected"), + [ + ( + "import os\nfrom pydantic_settings import BaseSettings\n\nx = 1\n", + "import secrets", + "import os\nimport secrets\nfrom pydantic_settings", + ), + ( + '"""Doc."""\n\nfrom pydantic_settings import BaseSettings\n\nx = 1\n', + "from typing import Literal", + '"""Doc."""\n\nfrom typing import Literal\n\nfrom pydantic_settings', + ), + ( + "import secrets\n\nx = 1\n", + "from pydantic import model_validator", + "import secrets\n\nfrom pydantic import model_validator\n\nx = 1", + ), + ( + "from __future__ import annotations\n\nimport secrets\n\nx = 1\n", + "import os", + "from __future__ import annotations\n\nimport os\nimport secrets", + ), + ], + ids=["same-section", "new-earlier-section", "new-later-section", "future"], + ) + def test_imports_join_their_isort_section( + self, source: str, line: str, expected: str + ) -> None: + assert expected in ensure_import(source, line) + + +class TestInjectionVerification: + def test_a_result_that_does_not_parse_is_refused(self) -> None: + source = ( + "from pydantic_settings import BaseSettings\n\n\n" + "class Settings(BaseSettings):\n A: str = 'a'\n" + ) + broken = [SettingGroup("Bad", (SettingField("B", "str", "("),))] + + with pytest.raises(SettingsInjectionError, match="unparsable"): + inject_settings_fields(source, broken) + + @pytest.mark.parametrize( + ("updated", "problem"), + [ + ("import os\n\nclass Settings:\n A = 1\n", "an import was lost"), + ( + "import secrets\nimport os\n\nclass Settings:\n A = 1\n", + "top-level statement", + ), + ( + "import secrets\nimport os\nx = 2\n\nclass Settings(Base):\n A = 1\n", + "class header changed", + ), + ( + "import secrets\nimport os\nx = 2\n\nclass Settings:\n A = 2\n", + "member of 'Settings' changed", + ), + ("import secrets\nimport os\nx = 2\n", "class is gone"), + ], + ) + def test_lost_statements_are_refused(self, updated: str, problem: str) -> None: + original = "import secrets\nimport os\nx = 2\n\nclass Settings:\n A = 1\n" + + with pytest.raises(SettingsInjectionError, match=problem): + _verify_settings_injection(original, updated, "Settings") + + def test_additions_are_accepted(self) -> None: + original = "import os\n\nclass Settings:\n A = 1\n" + updated = "import os\nimport secrets\n\nclass Settings:\n A = 1\n B = 2\n" + + assert _verify_settings_injection(original, updated, "Settings") == updated + + def test_scaffold_rolls_back_instead_of_writing_a_broken_module( + self, tmp_path: Path + ) -> None: + path = tmp_path / "src" / "core" / "config.py" + path.parent.mkdir(parents=True) + source = ( + "from pydantic_settings import BaseSettings\n\n\n" + "class Settings(BaseSettings):\n A: str = 'a'\n" + ) + path.write_text(source, encoding="utf-8") + generator = DynamicConfigGenerator( + {"database": {"type": "SQLite"}}, str(tmp_path) + ) + + with patch.object( + DynamicConfigGenerator, + "settings_groups", + return_value=[SettingGroup("Bad", (SettingField("B", "str", "("),))], + ): + with pytest.raises(SettingsInjectionError): + generator.apply_settings_module() + + assert path.read_text(encoding="utf-8") == source + + +# -------------------------------------------------------------------------- +# SECRET_KEY guard outside development (one rule, one list) +# -------------------------------------------------------------------------- + + +def _template_settings_modules() -> List[Path]: + return sorted( + path + for path in TEMPLATES.rglob("*.py-tpl") + if "KNOWN_EXAMPLE_SECRET_KEYS = frozenset" in path.read_text(encoding="utf-8") + ) + + +class TestSecretKeyGuard: + def test_every_template_uses_the_generator_list(self) -> None: + modules = _template_settings_modules() + + assert modules + for path in modules: + tree = ast.parse(path.read_text(encoding="utf-8")) + (assign,) = [ + node + for node in tree.body + if isinstance(node, ast.Assign) + and ast.unparse(node.targets[0]) == "KNOWN_EXAMPLE_SECRET_KEYS" + ] + values = { + node.value + for node in ast.walk(assign.value) + if isinstance(node, ast.Constant) and isinstance(node.value, str) + } + assert values == set(PUBLIC_EXAMPLE_SECRET_KEYS), path + + def test_template_guards_are_detected(self) -> None: + for path in _template_settings_modules(): + source = path.read_text(encoding="utf-8") + if "class Settings" in source: + assert has_secret_key_guard(source), path + + @pytest.mark.parametrize( + "source", + [ + "x = (\n", + "x = 1\n", + # only refuses the examples: weaker than the rule + "from pydantic import model_validator\n" + "class Settings:\n" + " @model_validator(mode='after')\n" + " def _g(self):\n" + " if self.ENVIRONMENT == 'production' and self.SECRET_KEY in X:\n" + " raise ValueError\n" + " return self\n", + # the full rule, but only for production: staging stays open + "from pydantic import model_validator\n" + "class Settings:\n" + " @model_validator(mode='after')\n" + " def _g(self):\n" + " if self.ENVIRONMENT != 'production':\n" + " return self\n" + " if 'SECRET_KEY' not in self.model_fields_set:\n" + " raise ValueError\n" + " if len(self.SECRET_KEY) < 32:\n" + " raise ValueError\n" + " return self\n", + # the right checks, but not a validator + "class Settings:\n" + " def _g(self):\n" + " return self.ENVIRONMENT == 'development', self.SECRET_KEY, " + "self.model_fields_set, len(x)\n", + ], + ) + def test_weak_or_missing_guards_do_not_count(self, source: str) -> None: + assert not has_secret_key_guard(source) + + @pytest.mark.parametrize( + ("auth", "expected"), + [ + ("JWT", None), + ("OAuth2", None), + ("Session-based", "Staging and production refuse demo users."), + ], + ) + def test_a_template_guard_is_not_duplicated( + self, tmp_path: Path, auth: str, expected: Any + ) -> None: + source_path = TEMPLATES / "fastapi-domain-starter/src/app/core/config.py-tpl" + target = tmp_path / "src" / "app" / "core" / "config.py" + target.parent.mkdir(parents=True) + target.write_text(source_path.read_text(encoding="utf-8"), encoding="utf-8") + generator = DynamicConfigGenerator( + {"authentication": auth}, + str(tmp_path), + settings_relpath="src/app/core/config.py", + ) + + generator.apply_settings_module() + + updated = target.read_text(encoding="utf-8") + cls = _class(updated) + validators = [ + node + for node in cls.body + if isinstance(node, ast.FunctionDef) and node.decorator_list + ] + secret_rules = [ + node.name for node in validators if "SECRET_KEY" in ast.unparse(node) + ] + assert secret_rules == ["_check_secret_key"] + injected = [node for node in validators if node.name == AUTH_GUARD_METHOD] + if expected is None: + assert injected == [] + else: + assert ast.get_docstring(injected[0]) == expected + + def test_injected_guard_refuses_short_keys(self) -> None: + source = "\n".join(auth_guard_lines(demo_users=False)) + + assert "if len(self.SECRET_KEY.encode()) < 32:" in source + assert "at least 32 bytes" in source + for key in PUBLIC_EXAMPLE_SECRET_KEYS: + assert f'"{key}",' in source + + @pytest.mark.parametrize("environment", ["staging", "production"]) + def test_injected_guard_applies_outside_development(self, environment: str) -> None: + source = "\n".join( + line.replace("{settings_class}", "Settings") + for line in auth_guard_lines(demo_users=True) + ) + namespace: Dict[str, Any] = {"model_validator": lambda **_: (lambda f: f)} + exec(textwrap.dedent(source), namespace) + guard = namespace[AUTH_GUARD_METHOD] + strong = "k" * 32 + + def state(**values: Any) -> SimpleNamespace: + values.setdefault("ENABLE_DEMO_USERS", False) + fields_set = set(values) - {"ENVIRONMENT", "ENABLE_DEMO_USERS"} + return SimpleNamespace(model_fields_set=fields_set, **values) + + named = f"ENVIRONMENT={environment}" + with pytest.raises(ValueError, match=f"set explicitly when {named}"): + unset = state(ENVIRONMENT=environment, SECRET_KEY=strong) + unset.model_fields_set = set() + guard(unset) + with pytest.raises(ValueError, match=f"public example value.*{named}"): + guard(state(ENVIRONMENT=environment, SECRET_KEY="changethis")) + with pytest.raises(ValueError, match=f"at least 32 bytes when {named}"): + guard(state(ENVIRONMENT=environment, SECRET_KEY="k" * 16)) + with pytest.raises(ValueError, match=f"ENABLE_DEMO_USERS.*{named}"): + guard( + state( + ENVIRONMENT=environment, SECRET_KEY=strong, ENABLE_DEMO_USERS=True + ) + ) + accepted = state(ENVIRONMENT=environment, SECRET_KEY=strong) + assert guard(accepted) is accepted + development = state( + ENVIRONMENT="development", ENABLE_DEMO_USERS=True, SECRET_KEY="secret" + ) + assert guard(development) is development + + def test_generated_settings_module_follows_the_template_rule(self) -> None: + source = DynamicConfigGenerator( + {"authentication": "JWT"}, "/tmp/test" + ).generate_settings_module() + + assert has_secret_key_guard(source) + assert AUTH_GUARD_METHOD not in source + assert "MIN_SECRET_KEY_BYTES = 32" in source + assert 'return ["*"] if "*" in origins else origins' in source + assert 'list[Literal["*"] | AnyUrl]' in source + + def test_jwt_algorithm_is_restricted_to_hmac(self, tmp_path: Path) -> None: + generator = DynamicConfigGenerator({"authentication": "JWT"}, str(tmp_path)) + (field,) = [ + f + for g in generator.settings_groups() + for f in g.fields + if f.name == "JWT_ALGORITHM" + ] + + assert field.annotation == 'Literal["HS256", "HS384", "HS512"]' + assert field.env_value == "HS256" + source = generator.generate_settings_module() + assert 'JWT_ALGORITHM: Literal["HS256", "HS384", "HS512"] = "HS256"' in source + security = generator.generate_auth_files()["src/auth/security.py"] + assert 'options={"require": ["exp", "sub", "type"]}' in security + + +# -------------------------------------------------------------------------- +# Rendered auth fragments +# -------------------------------------------------------------------------- + + +def _auth_files(auth: str, db: str = "SQLite", **extra: Any) -> Dict[str, str]: + config = {"authentication": auth, "database": {"type": db}, **extra} + return DynamicConfigGenerator(config, "/tmp/test").generate_auth_files() + + +def _function(source: str, name: str) -> ast.AST: + return next( + node + for node in ast.walk(ast.parse(source)) + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name == name + ) + + +class TestFastAPIUsersRace: + def test_unique_violation_becomes_user_already_exists(self) -> None: + users = _auth_files("FastAPI-Users")["src/auth/users.py"] + + create = ast.unparse(_function(users, "create")) + assert "except IntegrityError" in create + assert "await self.session.rollback()" in create + assert "raise UserAlreadyExists() from exc" in create + assert "yield UserDatabase(session, User)" in users + + def test_engine_hides_statement_parameters(self) -> None: + source = DynamicConfigGenerator( + {"database": {"type": "PostgreSQL"}}, "/tmp/test" + ).generate_database_config() + + assert source is not None + assert "hide_parameters=True," in source + + def test_register_shares_the_auth_rate_limit(self) -> None: + router = _auth_files("FastAPI-Users", utilities=["Rate-Limiting"])[ + "src/auth/router.py" + ] + + assert ( + router.count("dependencies=[Depends(RateLimit(settings.RATE_LIMIT_AUTH))]") + == 2 + ) + + def test_docstring_lists_the_library_deviations(self) -> None: + router = _auth_files("FastAPI-Users")["src/auth/router.py"] + + assert "no ``WWW-Authenticate`` header" in router + assert "without a ``Location`` header" in router + assert "``Cache-Control: no-store``" in router + + +class TestSessionInvalidation: + @pytest.mark.parametrize("db", ["SQLite", "MongoDB", "None"]) + def test_logout_revokes_and_requests_check_the_version(self, db: str) -> None: + files = _auth_files("Session-based", db) + + repository = files["src/auth/repository.py"] + assert "async def revoke_sessions(self, user_id: str) -> None:" in repository + assert "session_version" in files["src/auth/models.py"] + logout = ast.unparse(_function(files["src/auth/router.py"], "logout")) + assert "await users.revoke_sessions(user_id)" in logout + current = ast.unparse( + _function(files["src/auth/dependencies.py"], "get_current_user") + ) + assert "user.session_version != version" in current + assert "settings.SESSION_ABSOLUTE_MAX_AGE" in current + assert "session fixation" not in files["src/auth/router.py"] + + @pytest.mark.parametrize("db", ["SQLite", "MongoDB", "None"]) + def test_jwt_accounts_carry_no_session_version(self, db: str) -> None: + files = _auth_files("JWT", db) + + assert "session_version" not in files["src/auth/models.py"] + assert "revoke_sessions" not in files["src/auth/repository.py"] + + def test_sql_revoke_is_one_atomic_update(self) -> None: + repository = _auth_files("Session-based")["src/auth/repository.py"] + + assert "values(session_version=User.session_version + 1)" in repository + assert "from sqlalchemy import select, update\n" in repository + + def test_cookie_is_secure_outside_development(self) -> None: + middleware = _auth_files("Session-based")["src/auth/middleware.py"] + + assert 'settings.ENVIRONMENT != "development"' in middleware + + @pytest.mark.parametrize( + ("auth", "column"), [("Session-based", True), ("JWT", False)] + ) + def test_initial_revision_matches_the_model(self, auth: str, column: bool) -> None: + artifacts = DynamicConfigGenerator( + { + "authentication": auth, + "database": {"type": "SQLite"}, + "migrations": "Alembic", + }, + "/tmp/test", + ).generate_migration_files() + (revision,) = [ + v for k, v in artifacts.items() if k.startswith("alembic/versions/") + ] + + expected = 'sa.Column("session_version", sa.Integer(), server_default="0", nullable=False)' + assert (expected in revision) is column + ast.parse(revision) + + def test_settings_add_the_absolute_lifetime(self) -> None: + groups = DynamicConfigGenerator( + {"authentication": "Session-based"}, "/tmp/test" + ).settings_groups() + fields = {f.name: f for g in groups for f in g.fields} + + assert fields["SESSION_ABSOLUTE_MAX_AGE"].default == "2592000" + + +class TestDemoAccountReservation: + def test_register_refuses_the_demo_address(self) -> None: + service = _auth_files("Session-based")["src/auth/service.py"] + + register = ast.unparse(_function(service, "register")) + assert "== DEMO_USER_EMAIL" in register + assert "raise EmailAlreadyRegisteredError(DEMO_USER_EMAIL)" in register + demo = ast.unparse(_function(service, "_authenticate_demo_user")) + assert "self._create(" in demo + assert "self.register(" not in demo + + def test_jwt_has_no_demo_account(self) -> None: + assert "DEMO_USER" not in _auth_files("JWT")["src/auth/service.py"] + + +class TestPasswordHashingBounds: + @pytest.mark.parametrize("auth", ["JWT", "Session-based"]) + def test_hashing_is_bounded(self, auth: str) -> None: + security = _auth_files(auth)["src/auth/security.py"] + + assert ( + "_hash_slots = threading.BoundedSemaphore(MAX_CONCURRENT_HASHES)" + in security + ) + for name in ("hash_password", "verify_password", "_dummy_hash"): + assert "with _hash_slots:" in ast.unparse(_function(security, name)) + + @pytest.mark.parametrize("auth", ["JWT", "Session-based"]) + def test_register_has_the_auth_rate_limit(self, auth: str) -> None: + router = _auth_files(auth, utilities=["Rate-Limiting"])["src/auth/router.py"] + + assert router.count("dependencies=_auth_rate_limit,") == 2 + + +class TestOAuth2Hardening: + def test_provider_errors_cover_httpx2_and_authlib(self) -> None: + router = _auth_files("OAuth2")["src/auth/router.py"] + + assert ( + "PROVIDER_ERRORS = (AuthlibBaseError, httpx2.HTTPError, ValueError)" + in router + ) + assert "except PROVIDER_ERRORS as exc:" in router + assert "import httpx\n" not in router + + def test_redirect_uri_comes_from_the_public_base_url(self) -> None: + router = _auth_files("OAuth2")["src/auth/router.py"] + + callback = ast.unparse(_function(router, "callback_url")) + assert "settings.OAUTH_REDIRECT_BASE_URL" in callback + assert "settings.ENVIRONMENT == 'development'" in callback + login = ast.unparse(_function(router, "login")) + assert "callback_url(request, provider)" in login + assert "url_for" not in login + + def test_env_example_documents_the_base_url(self, tmp_path: Path) -> None: + generator = DynamicConfigGenerator({"authentication": "OAuth2"}, str(tmp_path)) + + generator.apply_env_example() + + example = (tmp_path / ".env.example").read_text(encoding="utf-8") + assert "# OAUTH_REDIRECT_BASE_URL=\n" in example + assert "TLS" not in example or "proxy" in example + + def test_catalog_installs_httpx2(self) -> None: + catalog = FastkitConfig.PACKAGE_CATALOG + assert "httpx2" in catalog[FeatureAxis.AUTHENTICATION][AuthChoice.OAUTH2] + assert "httpx" not in catalog[FeatureAxis.AUTHENTICATION][AuthChoice.OAUTH2] + for tier in (Tier.BASIC, Tier.COVERAGE, Tier.ADVANCED): + assert "httpx2" in catalog[FeatureAxis.TESTING][tier] + + +# -------------------------------------------------------------------------- +# Rate limiting, WebSocket, Dramatiq, pytest configuration +# -------------------------------------------------------------------------- + + +def _feature_modules(**config: Any) -> Dict[str, str]: + return DynamicConfigGenerator(config, "/tmp/test").generate_feature_modules() + + +class TestRateLimitingKeys: + @pytest.fixture + def client_key(self) -> Any: + source = _feature_modules(utilities=["Rate-Limiting"])["src/rate_limiting.py"] + function = _function(source, "client_key") + namespace: Dict[str, Any] = {"ipaddress": ipaddress} + exec(compile(ast.Module([function], []), "rate_limiting.py", "exec"), namespace) + return namespace["client_key"] + + @pytest.mark.parametrize( + ("host", "key"), + [ + ("2001:db8::1", "2001:db8::/64"), + ("2001:db8::abcd:1", "2001:db8::/64"), + ("2001:db8:0:1::1", "2001:db8:0:1::/64"), + ("::ffff:203.0.113.7", "203.0.113.7"), + ("203.0.113.7", "203.0.113.7"), + ("testclient", "testclient"), + (None, "unknown"), + ("", "unknown"), + ], + ) + def test_ipv6_is_grouped_per_64(self, client_key: Any, host: Any, key: str) -> None: + assert client_key(host) == key + + def test_route_limits_count_per_route_template(self) -> None: + source = _feature_modules(utilities=["Rate-Limiting"])["src/rate_limiting.py"] + + call = ast.unparse(_function(source, "__call__")) + assert "getattr(route, 'path', request.url.path)" in source.replace( + '"', "'" + ) or ("getattr(route" in call) + assert "client_key(" in call + + +class TestWebSocketFragment: + def test_receive_is_generic_and_the_connection_always_removed(self) -> None: + source = _feature_modules(utilities=["WebSocket"])["src/features/websocket.py"] + + endpoint = _function(source, "websocket_endpoint") + text = ast.unparse(endpoint) + assert "await websocket.receive()" in text + assert "receive_text" not in text + assert "WS_1003_UNSUPPORTED_DATA" in text + assert "WS_1009_MESSAGE_TOO_BIG" in text + assert "exclude=websocket" in text + (try_node,) = [n for n in ast.walk(endpoint) if isinstance(n, ast.Try)] + assert "manager.disconnect(websocket)" in ast.unparse(try_node.finalbody) + + +class TestDramatiqTasks: + def test_status_lives_in_the_result_backend(self) -> None: + modules = _feature_modules(async_tasks="Dramatiq") + + routes = modules["src/features/tasks.py"] + worker = modules["src/worker.py"] + assert "_MESSAGES" not in routes and "threading" not in routes + submit = ast.unparse(_function(routes, "submit_task")) + assert submit.index("store_result") < submit.index("enqueue") + assert "result_ttl=TASK_TTL_MS" in worker + assert "socket_connect_timeout=REDIS_CONNECT_TIMEOUT_SECONDS" in worker + + def test_a_stub_broker_test_is_generated(self) -> None: + tests = DynamicConfigGenerator( + {"async_tasks": AsyncTaskChoice.DRAMATIQ, "testing": "Basic"}, "/tmp/test" + ).generate_feature_tests() + + assert ( + "from dramatiq.brokers.stub import StubBroker" + in tests["tests/test_tasks.py"] + ) + ast.parse(tests["tests/test_tasks.py"]) + + +class TestPytestConfig: + def test_only_the_starlette_httpx_notice_is_filtered(self) -> None: + ini = DynamicConfigGenerator( + {"testing": "Basic"}, "/tmp/test" + ).generate_test_config() + + assert ini is not None + assert ( + "ignore:Using `httpx` with `starlette.testclient` is deprecated:" + "starlette.exceptions.StarletteDeprecationWarning" + ) in ini + + +# -------------------------------------------------------------------------- +# Docker (H2) +# -------------------------------------------------------------------------- + + +class TestDockerFiles: + def _generate(self, tmp_path: Path, **config: Any) -> Dict[str, str]: + generator = DynamicConfigGenerator( + {"deployment": ["Docker", "docker-compose"], **config}, + str(tmp_path), + main_py_relpath=config.pop("main", "src/main.py"), + ) + generator.generate_docker_files(app_module=generator.app_module) + return { + name: (tmp_path / name).read_text(encoding="utf-8") + for name in ("Dockerfile", "docker-compose.yml") + } + + def test_runs_as_a_non_root_user_and_copies_only_the_app( + self, tmp_path: Path + ) -> None: + dockerfile = self._generate(tmp_path)["Dockerfile"] + + assert "COPY . ." not in dockerfile + assert "COPY src/ src/" in dockerfile + assert re.search(r"^USER app$", dockerfile, re.M) + assert dockerfile.index("USER app") < dockerfile.index("CMD") + assert "useradd --system --uid 10001" in dockerfile + assert "ENV ENVIRONMENT=production" in dockerfile + + def test_migrations_and_sqlite_data(self, tmp_path: Path) -> None: + dockerfile = self._generate( + tmp_path, database={"type": "SQLite"}, migrations="Alembic" + )["Dockerfile"] + + assert "COPY alembic.ini ./" in dockerfile + assert "COPY alembic/ alembic/" in dockerfile + assert "RUN mkdir -p /app/data && chown -R app:app /app/data" in dockerfile + assert "ENV DATABASE_URL=sqlite+aiosqlite:////app/data/app.db" in dockerfile + + def test_template_item_store_stays_writable(self, tmp_path: Path) -> None: + (tmp_path / "src" / "mocks").mkdir(parents=True) + + dockerfile = self._generate(tmp_path)["Dockerfile"] + + assert "chown -R app:app /app/src/mocks" in dockerfile + + def test_nested_package_copies_its_top_directory(self, tmp_path: Path) -> None: + dockerfile = self._generate(tmp_path, main="src/app/main.py")["Dockerfile"] + + assert "COPY src/ src/" in dockerfile + + @pytest.mark.parametrize("db", ["PostgreSQL", "MySQL", "MongoDB", "Redis"]) + def test_compose_never_passes_an_empty_url(self, tmp_path: Path, db: str) -> None: + compose = yaml.safe_load( + self._generate(tmp_path, database={"type": db})["docker-compose.yml"] + ) + + for line in compose["services"]["app"]["environment"]: + name, _, value = line.partition("=") + assert name.endswith("_URL") + assert value and not value.startswith("${" + name + "}") + assert value.startswith(("redis://", "${" + name + ":-")) + assert compose["services"]["app"]["env_file"] == [".env"] + + +# -------------------------------------------------------------------------- +# Domain-starter items note (M4) +# -------------------------------------------------------------------------- + + +class TestItemsStoreNote: + @pytest.mark.parametrize( + ("preset", "db", "fragment"), + [ + ("domain-starter", "PostgreSQL", "in process memory"), + ("classic-layered", "SQLite", "JSON file"), + ("domain-starter", "None", ""), + ("minimal", "SQLite", ""), + ], + ) + def test_summary_and_readme( + self, tmp_path: Path, preset: str, db: str, fragment: str + ) -> None: + strategist = PresetLayoutStrategist(preset) + config = {"database": {"type": db}} + readme = tmp_path / "README.md" + readme.write_bytes(b"# Project\r\n") + + note = strategist.items_store_note(config) + changed = strategist.append_readme_notes(str(tmp_path), config) + + assert (fragment in note) and bool(note) is bool(fragment) + assert (note in strategist.generation_notes(config)) is bool(fragment) + assert changed is bool(fragment) + text = readme.read_bytes().decode("utf-8") + if fragment: + assert note in text + assert text.count("\n") == text.count("\r\n") + assert strategist.append_readme_notes(str(tmp_path), config) is False + + def test_missing_readme_is_left_alone(self, tmp_path: Path) -> None: + strategist = PresetLayoutStrategist("domain-starter") + + assert not strategist.append_readme_notes( + str(tmp_path), {"database": {"type": "SQLite"}} + ) + + +# -------------------------------------------------------------------------- +# Presence checks ignore comments; runserver validates app_module (item 11) +# -------------------------------------------------------------------------- + + +class TestInsertBeforeCors: + MAIN = ( + "from fastapi import FastAPI\n\napp = FastAPI()\n" + "{extra}" + "# CORS\n" + "app.add_middleware(CORSMiddleware, allow_origins=[])\n" + ) + + def test_a_commented_out_copy_does_not_count(self) -> None: + content = self.MAIN.format(extra="# add_session_middleware(app)\n") + + updated = insert_before_cors(content, "add_session_middleware(app)") + + assert updated is not None + # placed above the comment block attached to the CORS statement + assert ( + "\nadd_session_middleware(app)\n# add_session_middleware(app)\n# CORS" + in updated + ) + + def test_real_code_counts(self) -> None: + content = self.MAIN.format(extra="add_session_middleware(app)\n") + + assert insert_before_cors(content, "add_session_middleware(app)") == content + + +def _project_with_metadata(tmp_path: Path, app_module: Any) -> Path: + project = tmp_path / "project" + (project / "src").mkdir(parents=True) + (project / "src" / "main.py").write_text("app = None\n", encoding="utf-8") + value = repr(app_module) if not isinstance(app_module, str) else f'"{app_module}"' + (project / "pyproject.toml").write_text( + f'[project]\nname = "p"\n\n[tool.fastapi-fastkit]\napp_module = {value}\n', + encoding="utf-8", + ) + return project + + +class TestRunserverAppModule: + @pytest.mark.parametrize( + "value", + ["--reload-dir=/", "src.main:app --workers 9", "../evil:app", "/etc/x:app", 5], + ) + def test_invalid_values_are_refused(self, tmp_path: Path, value: Any) -> None: + project = _project_with_metadata(tmp_path, value) + + with pytest.raises(CLIExceptions, match="Invalid app_module"): + _resolve_runserver_app_module(str(project)) + + def test_valid_value_is_used(self, tmp_path: Path) -> None: + project = _project_with_metadata(tmp_path, " src.main:app ") + + assert _resolve_runserver_app_module(str(project)) == "src.main:app" + + def test_missing_module_falls_back_to_discovery(self, tmp_path: Path) -> None: + project = _project_with_metadata(tmp_path, "src.gone:app") + + assert _resolve_runserver_app_module(str(project)) == "src.main:app" + + @pytest.mark.skipif(os.name == "nt", reason="symlinks need privileges on Windows") + def test_a_module_outside_the_project_is_refused(self, tmp_path: Path) -> None: + outside = tmp_path / "outside" + outside.mkdir() + (outside / "evil.py").write_text("app = None\n", encoding="utf-8") + project = _project_with_metadata(tmp_path, "src.evil:app") + (project / "src" / "evil.py").symlink_to(outside / "evil.py") + + with pytest.raises(CLIExceptions, match="outside the project"): + _resolve_runserver_app_module(str(project)) + + def test_cli_prints_a_plain_error_and_exits_1( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + project = _project_with_metadata(tmp_path, "src.main:app --reload-dir /") + (project / ".venv").mkdir() + monkeypatch.chdir(project) + + with ( + patch( + "fastapi_fastkit.core.settings.FastkitConfig.USER_WORKSPACE", + str(project), + ), + patch("fastapi_fastkit.cli.subprocess.run") as mock_run, + ): + result = CliRunner().invoke( + fastkit_cli, ["runserver"], input="y\n", catch_exceptions=False + ) + + assert result.exit_code == 1 + assert "Invalid app_module" in result.output + mock_run.assert_not_called() + + +class TestFormatImportsAliases: + def test_aliased_names_get_their_own_statements(self) -> None: + from fastapi_fastkit.backend.project_builder.config_generator import ( + format_imports, + ) + + block = format_imports( + [ + "from src.db import engine as app_engine", + "from src.db import Base, get_db", + "from src.auth import router as r", + "from src.auth import dependencies as d", + ] + ) + + assert block.split("\n") == [ + "from src.auth import dependencies as d", + "from src.auth import router as r", + "from src.db import Base, get_db", + "from src.db import engine as app_engine", + ] + + +class TestInjectionHelpersEdgeCases: + def test_body_split_leaves_other_sources_alone(self) -> None: + from fastapi_fastkit.backend.project_builder.config_generator import ( + _with_body_on_own_lines, + ) + + for source in ("def broken(:\n", "x = 1\n"): + assert _with_body_on_own_lines(source) == source + + def test_unchanged_source_is_returned(self) -> None: + assert _verify_settings_injection("x = 1\n", "x = 1\n", "Settings") == "x = 1\n" + + def test_module_without_imports_gets_one(self) -> None: + updated = ensure_import("x = 1\n", "import secrets") + + assert "import secrets" in updated + ast.parse(updated) + + def test_relative_imports_sort_last(self) -> None: + updated = ensure_import("from . import local\n\nx = 1\n", "import secrets") + + assert updated.index("import secrets") < updated.index("from . import local") + + def test_readme_without_final_newline(self, tmp_path: Path) -> None: + (tmp_path / "README.md").write_text("# Project", encoding="utf-8") + strategist = PresetLayoutStrategist("domain-starter") + + assert strategist.append_readme_notes( + str(tmp_path), {"database": {"type": "SQLite"}} + ) + text = (tmp_path / "README.md").read_text(encoding="utf-8") + assert text.startswith("# Project\n\n## Notes\n") diff --git a/tests/test_backends/test_generated_runtime_safety.py b/tests/test_backends/test_generated_runtime_safety.py index 1f50721..4a85ce7 100644 --- a/tests/test_backends/test_generated_runtime_safety.py +++ b/tests/test_backends/test_generated_runtime_safety.py @@ -7,7 +7,8 @@ # - The CORS setup takes its origins from BACKEND_CORS_ORIGINS only and never # combines a wildcard origin with credentials. # - Auth modules carry no usable public default secret and refuse the known -# example values in production; the local .env gets a unique SECRET_KEY. +# example values outside development; the local .env gets a unique +# SECRET_KEY. # # The repository's virtualenv does not have the generated projects' # dependencies, so these checks work on the rendered source (AST) and on @@ -18,16 +19,20 @@ import ast import itertools import re +import warnings from pathlib import Path +from types import SimpleNamespace from typing import Any, Dict, List, Optional import pytest import fastapi_fastkit from fastapi_fastkit.backend.project_builder.config_generator import ( + PUBLIC_EXAMPLE_SECRET_KEYS, DynamicConfigGenerator, get_environment, ) +from fastapi_fastkit.backend.project_builder.config_schema import ConfigSchemaError from fastapi_fastkit.backend.project_builder.preset_layout import ( PresetLayoutStrategist, ) @@ -50,6 +55,8 @@ KNOWN_EXAMPLE_SECRETS = frozenset( { "changethis", + "changethis-please-generate-a-real-32-byte-key", + "changethis-please-use-openssl-rand-hex-32", "change-me-in-production", "your-secret-key-here", "your-secret-key-here-change-in-production", @@ -138,6 +145,19 @@ def _render_cors_fragment() -> str: return get_environment().get_template("main/setup/cors.j2").render() +def _parse_origins_function() -> Any: + """``parse_cors`` of the generated settings module, without pydantic.""" + source = DynamicConfigGenerator(_config(), "/tmp/test").generate_settings_module() + (function,) = [ + node + for node in ast.parse(source).body + if isinstance(node, ast.FunctionDef) and node.name == "parse_cors" + ] + namespace: Dict[str, Any] = {"Any": Any, "json": __import__("json")} + exec(compile(ast.Module([function], []), "config.py", "exec"), namespace) + return namespace["parse_cors"] + + class _RecordingApp: """Stand-in for ``FastAPI`` that records ``add_middleware`` calls.""" @@ -148,17 +168,11 @@ def add_middleware(self, cls: Any, **options: Any) -> None: self.middleware.append({"cls": cls, **options}) -def _run_cors_setup( - monkeypatch: pytest.MonkeyPatch, origins: Optional[str] -) -> _RecordingApp: - """Execute the rendered CORS setup with a stub app and ``origins`` env.""" - if origins is None: - monkeypatch.delenv("BACKEND_CORS_ORIGINS", raising=False) - else: - monkeypatch.setenv("BACKEND_CORS_ORIGINS", origins) +def _run_cors_setup(origins: List[str]) -> _RecordingApp: + """Execute the rendered CORS setup with a stub app and stub settings.""" app = _RecordingApp() namespace = { - "os": __import__("os"), + "settings": SimpleNamespace(all_cors_origins=origins), "app": app, "CORSMiddleware": "CORSMiddleware", } @@ -232,20 +246,30 @@ def test_prometheus_is_instrumented_at_module_level(self) -> None: module_level = [ ast.unparse(node) for node in tree.body if isinstance(node, ast.Expr) ] - assert "Instrumentator().instrument(app).expose(app)" in module_level + assert ( + "Instrumentator().instrument(app).expose(app, tags=['monitoring'])" + in module_level + ) assert app_calls_inside_lifespan(source) == [] # After the app exists, so the statement has something to instrument. assert source.index("app = FastAPI(") < source.index("Instrumentator()") @pytest.mark.parametrize("preset", ["classic-layered", "domain-starter"]) - def test_preserved_main_explains_how_to_wire_prometheus(self, preset: str) -> None: - warnings = PresetLayoutStrategist(preset).compatibility_warnings( - {"monitoring": "Prometheus"} - ) + def test_preserved_main_gets_prometheus_at_module_level( + self, preset: str, tmp_path: Path + ) -> None: + source = _generated_main(preset, _config(monitoring="Prometheus"), tmp_path) - hint = next(line for line in warnings if line.startswith("Prometheus:")) - assert "Instrumentator().instrument(app).expose(app)" in hint - assert "app = FastAPI(...)" in hint + tree = ast.parse(source) + module_level = [ + ast.unparse(node) for node in tree.body if isinstance(node, ast.Expr) + ] + assert ( + "Instrumentator().instrument(app).expose(app, tags=['monitoring'])" + in module_level + ) + assert source.index("app = FastAPI(") < source.index("Instrumentator()") + assert app_calls_inside_lifespan(source) == [] # -------------------------------------------------------------------------- @@ -277,6 +301,9 @@ def test_rendered_setup_has_no_wildcard_with_credentials(self) -> None: ) assert '["*"], # Configure' not in source assert "BACKEND_CORS_ORIGINS" in source + # Origins come from the settings module (which reads .env), not os. + assert "settings.all_cors_origins" in source + assert "os.getenv" not in source def test_middleware_is_added_only_when_origins_are_configured(self) -> None: source = DynamicConfigGenerator( @@ -296,20 +323,16 @@ def test_middleware_is_added_only_when_origins_are_configured(self) -> None: ] assert not any("CORSMiddleware" in call for call in module_calls) - @pytest.mark.parametrize("origins", [None, "", " , ,"]) - def test_unset_or_empty_origins_add_no_middleware( - self, monkeypatch: pytest.MonkeyPatch, origins: Optional[str] - ) -> None: - app = _run_cors_setup(monkeypatch, origins) + @pytest.mark.parametrize("origins", [[], [""]]) + def test_unset_or_empty_origins_add_no_middleware(self, origins: List[str]) -> None: + # [""] is what a template's all_cors_origins used to return when only + # an empty CLIENT_ORIGIN was set. + app = _run_cors_setup(origins) assert app.middleware == [] - def test_listed_origins_are_stripped_and_allow_credentials( - self, monkeypatch: pytest.MonkeyPatch - ) -> None: - app = _run_cors_setup( - monkeypatch, " http://localhost:3000 , ,https://app.example.com/ " - ) + def test_listed_origins_allow_credentials(self) -> None: + app = _run_cors_setup(["http://localhost:3000", "https://app.example.com"]) (middleware,) = app.middleware assert middleware["allow_origins"] == [ @@ -318,16 +341,38 @@ def test_listed_origins_are_stripped_and_allow_credentials( ] assert middleware["allow_credentials"] is True - @pytest.mark.parametrize("origins", ["*", "http://localhost:3000,*"]) - def test_wildcard_origin_never_allows_credentials( - self, monkeypatch: pytest.MonkeyPatch, origins: str - ) -> None: - app = _run_cors_setup(monkeypatch, origins) + @pytest.mark.parametrize("origins", [["*"], ["http://localhost:3000", "*"]]) + def test_wildcard_origin_never_allows_credentials(self, origins: List[str]) -> None: + app = _run_cors_setup(origins) (middleware,) = app.middleware assert "*" in middleware["allow_origins"] assert middleware["allow_credentials"] is False + @pytest.mark.parametrize( + ("raw", "parsed"), + [ + # Entries are stripped and blank ones dropped; pydantic then + # validates each as a URL (or "*"), and all_cors_origins drops + # the trailing "/". + ( + " http://localhost:3000 , ,https://app.example.com/ ", + [ + "http://localhost:3000", + "https://app.example.com/", + ], + ), + ('["http://a.example", "*"]', ["http://a.example", "*"]), + ('[" http://a.example/ ", ""]', ["http://a.example/"]), + ("", []), + ("*", ["*"]), + ], + ) + def test_generated_settings_parse_comma_lists_and_json( + self, raw: str, parsed: List[str] + ) -> None: + assert _parse_origins_function()(raw) == parsed + def test_env_example_documents_the_variable_commented_out( self, tmp_path: Path ) -> None: @@ -343,117 +388,544 @@ def test_env_example_documents_the_variable_commented_out( assert "# BACKEND_CORS_ORIGINS=http://localhost:3000" in example assert not re.search(r"^BACKEND_CORS_ORIGINS=", example, re.M) - def test_preserved_main_gets_no_cors_entry(self, tmp_path: Path) -> None: - """Template entrypoints configure CORS through their own settings.""" + def test_preserved_main_documents_the_variable_too(self, tmp_path: Path) -> None: + """Every preset reads BACKEND_CORS_ORIGINS from its settings (.env).""" generator = DynamicConfigGenerator(_config(utilities=["CORS"]), str(tmp_path)) - assert generator.env_example_blocks(include_main=False) == [] - assert ".env.example" not in generator.planned_files(include_main=False) + assert [name for name, _ in generator.env_example_blocks(False)] == [ + "BACKEND_CORS_ORIGINS" + ] + assert ".env.example" in generator.planned_files(include_main=False) # -------------------------------------------------------------------------- -# F6: no public default secret in the auth modules +# F6 / convention 16: auth reads the one settings module, which guards +# staging and production; F7 / F8 / F14: the generated auth flows (AST checks) # -------------------------------------------------------------------------- +#: Every valid preset x auth x database combination the matrix covers. +AUTH_MATRIX = [ + (preset, auth, db) + for preset in PRESETS + for auth in ["JWT", "Session-based", "OAuth2", "FastAPI-Users"] + for db in ["SQLite", "PostgreSQL", "MongoDB", "Redis", "None"] + if auth != "FastAPI-Users" or db in ("SQLite", "PostgreSQL") +] -def _auth_module(auth: str) -> str: - content = DynamicConfigGenerator( - _config(authentication=auth), "/tmp/test" - ).generate_auth_config() - assert content is not None - return content +def _python_files(project: Path) -> Dict[str, ast.Module]: + return { + path.relative_to(project).as_posix(): ast.parse( + path.read_text(encoding="utf-8") + ) + for path in sorted(project.rglob("*.py")) + } -def _example_set_node(tree: ast.Module) -> ast.AST: - for node in tree.body: - if isinstance(node, ast.Assign) and any( - isinstance(target, ast.Name) and target.id == "KNOWN_EXAMPLE_SECRET_KEYS" - for target in node.targets - ): - return node - raise AssertionError("KNOWN_EXAMPLE_SECRET_KEYS is not defined") +def _settings_class(tree: ast.Module) -> ast.ClassDef: + (cls,) = [ + node + for node in tree.body + if isinstance(node, ast.ClassDef) + and any(ast.unparse(base).endswith("BaseSettings") for base in node.bases) + ] + return cls -class TestAuthModuleSecrets: - @pytest.mark.parametrize("auth", SIGNING_AUTHS) - def test_example_secrets_appear_only_in_the_refusal_list(self, auth: str) -> None: - tree = ast.parse(_auth_module(auth)) - allowed = {id(node) for node in ast.walk(_example_set_node(tree))} - leaked = [ - node.value - for node in ast.walk(tree) - if isinstance(node, ast.Constant) - and node.value in KNOWN_EXAMPLE_SECRETS - and id(node) not in allowed - ] - assert leaked == [] +def _declared(cls: ast.ClassDef) -> set: + names = set() + for node in cls.body: + if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + names.add(node.target.id) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + names.add(node.name) + return names - @pytest.mark.parametrize("auth", SIGNING_AUTHS) - def test_refusal_list_covers_every_published_example(self, auth: str) -> None: - tree = ast.parse(_auth_module(auth)) - listed = { - node.value - for node in ast.walk(_example_set_node(tree)) - if isinstance(node, ast.Constant) - } - assert KNOWN_EXAMPLE_SECRETS <= listed - @pytest.mark.parametrize("auth", SIGNING_AUTHS) - def test_secret_key_has_no_literal_default(self, auth: str) -> None: - tree = ast.parse(_auth_module(auth)) +def _settings_attributes(tree: ast.Module) -> set: + """``settings.X`` names a module reads.""" + return { + node.attr + for node in ast.walk(tree) + if isinstance(node, ast.Attribute) + and isinstance(node.value, ast.Name) + and node.value.id == "settings" + } - (field,) = [ - node - for node in ast.walk(tree) - if isinstance(node, ast.AnnAssign) - and isinstance(node.target, ast.Name) - and node.target.id == "SECRET_KEY" - ] - assert field.value is not None - assert ast.unparse(field.value) == "secrets.token_urlsafe(32)" - @pytest.mark.parametrize("auth", SIGNING_AUTHS) - def test_production_guard_is_present(self, auth: str) -> None: - source = _auth_module(auth) +#: The SECRET_KEY validators: the template's (or generated module's) own +#: SECRET_KEY rule and the guard the generator injects. +GUARD_METHODS = ("_check_secret_key", "_check_auth_settings_for_production") - assert '@model_validator(mode="after")' in source - assert 'self.ENVIRONMENT != "production"' in source - assert '"SECRET_KEY" not in self.model_fields_set' in source - assert "in KNOWN_EXAMPLE_SECRET_KEYS" in source - assert 'env_file=".env"' in source +#: Module-level names those validators read. +GUARD_CONSTANTS = ( + "KNOWN_EXAMPLE_SECRET_KEYS", + "MIN_SECRET_KEY_BYTES", + "_GENERATE_KEY_HINT", +) - @pytest.mark.parametrize("auth", ["OAuth2", "Session-based"]) - def test_session_middleware_signs_with_secret_key(self, auth: str) -> None: - main_py = DynamicConfigGenerator( - _config(authentication=auth), "/tmp/test" - ).generate_main_py() - assert "secret_key=auth_settings.SECRET_KEY" in main_py - assert "SESSION_SECRET_KEY" not in main_py - assert "SESSION_SECRET_KEY" not in _auth_module(auth) +def _guard_methods(cls: ast.ClassDef) -> List[ast.FunctionDef]: + return [ + node + for node in cls.body + if isinstance(node, ast.FunctionDef) and node.name in GUARD_METHODS + ] + + +def _guard(module: ast.Module, cls: ast.ClassDef) -> Any: + """Every SECRET_KEY validator of ``cls``, run in order, without pydantic.""" + methods = _guard_methods(cls) + constants = [ + node + for node in module.body + if isinstance(node, ast.Assign) + and any( + isinstance(t, ast.Name) and t.id in GUARD_CONSTANTS for t in node.targets + ) + ] + namespace: Dict[str, Any] = { + "model_validator": lambda **_: (lambda f: f), + "warnings": warnings, + } + exec(compile(ast.Module(constants + methods, []), "config.py", "exec"), namespace) + + def run(state: Any) -> Any: + for method in methods: + state = namespace[method.name](state) + return state + + return run + + +def _matrix_project( + tmp_path: Path, preset: str, auth: str, db: str, **extra: Any +) -> Path: + config = { + "authentication": auth, + "database": {"type": db}, + "testing": "Basic", + **extra, + } + name = f"p_{PRESETS.index(preset)}_{auth[:3]}_{db[:3]}".lower().replace("-", "") + return _scaffold(tmp_path, preset, config, name) + + +@pytest.fixture(scope="module") +def auth_projects(tmp_path_factory: pytest.TempPathFactory) -> Dict[tuple, Path]: + """One scaffolded project (no install) per valid matrix combination.""" + root = tmp_path_factory.mktemp("auth-matrix") + return {combo: _matrix_project(root, *combo) for combo in AUTH_MATRIX} - def test_jwt_settings_are_validated_at_startup(self) -> None: - """main.py imports the JWT settings, so the guard runs on startup.""" - main_py = DynamicConfigGenerator( - _config(authentication="JWT"), "/tmp/test" - ).generate_main_py() - assert "from src.config.auth import auth_settings # noqa: F401" in main_py +class TestAuthSettingsAndGuard: + @pytest.mark.parametrize("combo", AUTH_MATRIX, ids=lambda c: "/".join(c)) + def test_one_settings_class_and_every_setting_declared( + self, auth_projects: Dict[tuple, Path], combo: tuple + ) -> None: + trees = _python_files(auth_projects[combo]) + + settings_classes = [ + relative + for relative, tree in trees.items() + for node in tree.body + if isinstance(node, ast.ClassDef) + and any(ast.unparse(base).endswith("BaseSettings") for base in node.bases) + ] + assert len(settings_classes) == 1, settings_classes + declared = _declared(_settings_class(trees[settings_classes[0]])) + used = set().union(*(_settings_attributes(tree) for tree in trees.values())) + assert used - declared == set() + + @pytest.mark.parametrize("combo", AUTH_MATRIX, ids=lambda c: "/".join(c)) + def test_no_example_secret_getenv_or_noqa_import( + self, auth_projects: Dict[tuple, Path], combo: tuple + ) -> None: + project = auth_projects[combo] + trees = _python_files(project) + settings_file = next( + relative + for relative, tree in trees.items() + if any( + isinstance(node, ast.ClassDef) and node.name == "Settings" + for node in tree.body + ) + ) + allowed = { + id(node) + for guard in ast.walk(trees[settings_file]) + if isinstance(guard, ast.FunctionDef) and guard.name in GUARD_METHODS + for node in ast.walk(guard) + } + allowed |= { + id(node) + for tree in trees.values() + for assign in tree.body + if isinstance(assign, ast.Assign) + and "KNOWN_EXAMPLE_SECRET_KEYS" in ast.unparse(assign.targets[0]) + for node in ast.walk(assign) + } + # Comparisons refuse a value (``if value == "changethis"``). + allowed |= { + id(node) + for tree in trees.values() + for compare in ast.walk(tree) + if isinstance(compare, ast.Compare) + for node in ast.walk(compare) + } + for relative, tree in trees.items(): + # Test code: the root conftest.py overrides settings on purpose. + if relative.startswith("tests/") or relative == "conftest.py": + continue + leaked = [ + node.value + for node in ast.walk(tree) + if isinstance(node, ast.Constant) + and node.value in KNOWN_EXAMPLE_SECRETS + and id(node) not in allowed + ] + assert leaked == [], relative + source = ast.unparse(tree) + assert "os.getenv" not in source and "os.environ" not in source + main_py = PresetLayoutStrategist(combo[0]).profile.main_py_relpath + main_source = (project / main_py).read_text(encoding="utf-8") + assert "noqa" not in main_source + assert "auth_router" in main_source + + @pytest.mark.parametrize("combo", AUTH_MATRIX, ids=lambda c: "/".join(c)) + @pytest.mark.parametrize("environment", ["staging", "production"]) + def test_guard_refuses_missing_and_example_keys_outside_development( + self, auth_projects: Dict[tuple, Path], combo: tuple, environment: str + ) -> None: + trees = _python_files(auth_projects[combo]) + settings_file = PresetLayoutStrategist(combo[0]).profile.settings_relpath + cls = _settings_class(trees[settings_file]) + guard = _guard(trees[settings_file], cls) + # The SECRET_KEY rule is enforced by exactly one validator: the + # template's own when it has one, else the injected guard. + assert [ + method.name + for method in _guard_methods(cls) + if "SECRET_KEY" in ast.unparse(method) + ] in (["_check_secret_key"], ["_check_auth_settings_for_production"]) + fields = { + node.target.id: ast.unparse(node.value) + for node in cls.body + if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) + } + + def run(**values: Any) -> Any: + state = {"ENABLE_DEMO_USERS": False, **values} + state.setdefault("model_fields_set", set(values) - {"ENVIRONMENT"}) + return guard(SimpleNamespace(**state)) + + assert fields["SECRET_KEY"] == "secrets.token_urlsafe(32)" + strong = "x" * 43 + with warnings.catch_warnings(): + # templates warn about an example key in development + warnings.simplefilter("ignore") + assert run(ENVIRONMENT="development", SECRET_KEY="changethis") is not None + if combo[1] == "Session-based": + assert run( + ENVIRONMENT="development", SECRET_KEY=strong, ENABLE_DEMO_USERS=True + ).ENABLE_DEMO_USERS + assert run(ENVIRONMENT=environment, SECRET_KEY=strong).SECRET_KEY == strong + named = f"ENVIRONMENT={environment}" + with pytest.raises(ValueError, match=f"must be set explicitly when {named}"): + run(ENVIRONMENT=environment, SECRET_KEY=strong, model_fields_set=set()) + with pytest.raises(ValueError, match=f"at least 32 bytes when {named}"): + run(ENVIRONMENT=environment, SECRET_KEY="k" * 16) + for example in sorted(KNOWN_EXAMPLE_SECRETS): + with pytest.raises(ValueError, match="public example"): + run(ENVIRONMENT=environment, SECRET_KEY=f" {example} ") + if combo[1] == "Session-based": + assert fields["ENABLE_DEMO_USERS"] == "False" + with pytest.raises(ValueError, match=f"ENABLE_DEMO_USERS.*{named}"): + run(ENVIRONMENT=environment, SECRET_KEY=strong, ENABLE_DEMO_USERS=True) + + def test_guard_is_added_once_and_keeps_template_validators( + self, tmp_path: Path + ) -> None: + (tmp_path / "src" / "core").mkdir(parents=True) + config_py = tmp_path / "src" / "core" / "config.py" + config_py.write_text( + "from pydantic_settings import BaseSettings\n\n\n" + "class Settings(BaseSettings):\n" + ' PROJECT_NAME: str = "demo"\n\n\n' + "settings = Settings()\n", + encoding="utf-8", + ) + generator = DynamicConfigGenerator(_config(authentication="JWT"), str(tmp_path)) + + generator.apply_settings_module() + once = config_py.read_text(encoding="utf-8") + generator.apply_settings_module() + + assert config_py.read_text(encoding="utf-8") == once + tree = ast.parse(once) + fields = _declared(_settings_class(tree)) + assert {"ENVIRONMENT", "SECRET_KEY", "JWT_ALGORITHM"} <= fields + assert "_check_auth_settings_for_production" in fields + assert "import secrets" in once + assert "from typing import Literal" in once + assert "from pydantic import model_validator" in once + + def test_the_guard_needs_no_unused_import_to_run(self) -> None: + """The guard sits on the Settings class: importing settings runs it.""" + source = DynamicConfigGenerator( + _config(authentication="Session-based"), "/tmp/test" + ).generate_settings_module() + + cls = _settings_class(ast.parse(source)) + assert "_check_auth_settings_for_production" in _declared(cls) + assert "ENABLE_DEMO_USERS" in _declared(cls) def test_no_fragment_ships_a_known_example_secret_as_a_value(self) -> None: - """Across every fragment, example secrets only sit in the refusal list.""" fragments = Path(fastapi_fastkit.__file__).parent / "fragments" offenders = [] for path in fragments.rglob("*.j2"): - if path.name == "settings.j2" and path.parent.name == "auth": - continue # defines KNOWN_EXAMPLE_SECRET_KEYS + if path.name == "config.py.j2" and path.parent.name == "core": + continue # defines the KNOWN_EXAMPLE_SECRET_KEYS refusal list + if path.parent.name == "test": + continue # generated tests assert that the values are refused text = path.read_text(encoding="utf-8") for secret in KNOWN_EXAMPLE_SECRETS - {"changethis"}: if secret in text: offenders.append(f"{path.name}: {secret}") assert offenders == [] + def test_guard_lists_every_published_example(self) -> None: + assert KNOWN_EXAMPLE_SECRETS <= set(PUBLIC_EXAMPLE_SECRET_KEYS) + + @pytest.mark.parametrize("auth", ["OAuth2", "Session-based"]) + def test_session_cookie_is_signed_with_secret_key(self, auth: str) -> None: + files = DynamicConfigGenerator( + _config(authentication=auth), "/tmp/test" + ).generate_auth_files() + middleware = files["src/auth/middleware.py"] + + assert "secret_key=settings.SECRET_KEY" in middleware + assert 'same_site="lax"' in middleware + assert ( + 'https_only=settings.SESSION_HTTPS_ONLY or settings.ENVIRONMENT != "development"' + in middleware + ) + assert "SESSION_SECRET_KEY" not in "".join(files.values()) + + +def _routes(tree: ast.Module) -> Dict[tuple, Dict[str, str]]: + """``(router, method, path) -> decorator keywords`` of a router module.""" + routes: Dict[tuple, Dict[str, str]] = {} + for node in ast.walk(tree): + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + for decorator in node.decorator_list: + if ( + isinstance(decorator, ast.Call) + and isinstance(decorator.func, ast.Attribute) + and decorator.args + ): + key = ( + ast.unparse(decorator.func.value), + decorator.func.attr, + ast.literal_eval(decorator.args[0]), + ) + routes[key] = { + str(kw.arg): ast.unparse(kw.value) for kw in decorator.keywords + } + return routes + + +def _routers(tree: ast.Module) -> Dict[str, str]: + return { + ast.unparse(node.targets[0]): ast.unparse(node.value) + for node in tree.body + if isinstance(node, ast.Assign) + and isinstance(node.value, ast.Call) + and ast.unparse(node.value.func) == "APIRouter" + } + + +class TestAuthFlowsShape: + @pytest.mark.parametrize("combo", AUTH_MATRIX, ids=lambda c: "/".join(c)) + def test_every_401_carries_a_challenge_and_no_error_text_leaks( + self, auth_projects: Dict[tuple, Path], combo: tuple + ) -> None: + package = ( + auth_projects[combo] + / PresetLayoutStrategist(combo[0]).profile.auth_package_relpath + ) + for path in package.glob("*.py"): + tree = ast.parse(path.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if not ( + isinstance(node, ast.Call) + and ast.unparse(node.func) == "HTTPException" + ): + continue + keywords = {kw.arg: ast.unparse(kw.value) for kw in node.keywords} + assert "str(" not in keywords.get("detail", ""), path.name + if keywords["status_code"] == "status.HTTP_401_UNAUTHORIZED": + assert "WWW-Authenticate" in keywords.get("headers", ""), path + + @pytest.mark.parametrize("db", ["SQLite", "MongoDB", "None"]) + def test_jwt_password_flow(self, auth_projects: Dict[tuple, Path], db: str) -> None: + project = auth_projects[("minimal", "JWT", db)] + router = ast.parse((project / "src/auth/router.py").read_text("utf-8")) + deps = (project / "src/auth/dependencies.py").read_text("utf-8") + + routes = _routes(router) + assert _routers(router) == { + "auth_router": "APIRouter(prefix='/auth', tags=['auth'])", + "users_router": "APIRouter(prefix='/users', tags=['users'])", + "router": ( + "APIRouter()" if db != "SQLite" else "APIRouter(lifespan=lifespan)" + ), + } + assert routes[("auth_router", "post", "/register")]["status_code"] == ( + "status.HTTP_201_CREATED" + ) + assert "409" in routes[("auth_router", "post", "/register")]["responses"] + assert "401, 403" in routes[("auth_router", "post", "/token")]["responses"] + assert ("users_router", "get", "/me") in routes + assert ("users_router", "get", "/{user_id}") in routes + assert ( + 'OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_PREFIX}/auth/token")' + in deps + ) + assert "CurrentUser = Annotated[User, Depends(get_current_user)]" in deps + source = (project / "src/auth/router.py").read_text("utf-8") + assert "OAuth2PasswordRequestForm" in source + assert '"Cache-Control": "no-store"' in source + assert "expires_in=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60" in source + assert "passlib" not in source and "jose" not in source + + @pytest.mark.parametrize( + ("db", "marker"), + [ + ("SQLite", "class User(Base):"), + ("PostgreSQL", "class User(Base):"), + ("MongoDB", "@dataclass"), + ("Redis", "@dataclass"), + ("None", "@dataclass"), + ], + ) + def test_user_store_follows_the_database( + self, auth_projects: Dict[tuple, Path], db: str, marker: str + ) -> None: + project = auth_projects[("classic-layered", "JWT", db)] + models = (project / "src/auth/models.py").read_text("utf-8") + repository = (project / "src/auth/repository.py").read_text("utf-8") + + assert marker in models + if db in ("SQLite", "PostgreSQL"): + assert "await self.session.commit()" in repository + assert "except IntegrityError" in repository + elif db == "MongoDB": + assert 'create_index("email", unique=True)' in repository + assert "except DuplicateKeyError" in repository + else: + assert "NOT PERSISTENT" in repository + assert "threading.Lock()" in repository + assert "with self._lock:" in repository + + @pytest.mark.parametrize("db", ["SQLite", "None"]) + def test_session_routes(self, auth_projects: Dict[tuple, Path], db: str) -> None: + project = auth_projects[("domain-starter", "Session-based", db)] + package = project / "src/app/domains/auth" + routes = _routes(ast.parse((package / "router.py").read_text("utf-8"))) + deps = (package / "dependencies.py").read_text("utf-8") + + assert routes[("auth_router", "post", "/logout")]["status_code"] == ( + "status.HTTP_204_NO_CONTENT" + ) + assert ("auth_router", "post", "/login") in routes + assert '"WWW-Authenticate": "Cookie"' in deps + assert "request.session.clear()" in (package / "router.py").read_text("utf-8") + service = (package / "service.py").read_text("utf-8") + assert "if not settings.ENABLE_DEMO_USERS:" in service + + def test_oauth2_routes(self, auth_projects: Dict[tuple, Path]) -> None: + project = auth_projects[("single-module", "OAuth2", "None")] + source = (project / "src/auth/router.py").read_text("utf-8") + routes = _routes(ast.parse(source)) + + assert routes[("auth_router", "post", "/logout")]["status_code"] == ( + "status.HTTP_204_NO_CONTENT" + ) + assert routes[("auth_router", "get", "/callback/{provider}")]["responses"] == ( + "error_responses(401, 404)" + ) + assert "str(exc)" not in source + assert "authorize_access_token(request)" in source + + @pytest.mark.parametrize("migrations", ["Alembic", "None"]) + def test_fastapi_users_routers(self, tmp_path: Path, migrations: str) -> None: + project = _matrix_project( + tmp_path, + "classic-layered", + "FastAPI-Users", + "PostgreSQL", + migrations=migrations, + utilities=["Rate-Limiting"], + ) + router = (project / "src/auth/router.py").read_text("utf-8") + users = (project / "src/auth/users.py").read_text("utf-8") + + for prefix, tag in ( + ("/auth/jwt", "auth"), + ("/auth", "auth"), + ("/users", "users"), + ): + assert f'prefix="{prefix}",\n tags=["{tag}"],' in router + assert "RateLimit(settings.RATE_LIMIT_AUTH)" in router + assert 'tokenUrl=f"{settings.API_V1_PREFIX}/auth/jwt/login"' in users + assert "secret=settings.SECRET_KEY" in users + assert "current_active_user = fastapi_users.current_user(active=True)" in users + assert ("lifespan=lifespan" in router) is (migrations == "None") + if migrations == "Alembic": + env = (project / "alembic/env.py").read_text("utf-8") + assert "import src.auth.models # noqa: F401" in env + (revision,) = (project / "alembic/versions").glob("*_initial.py") + text = revision.read_text("utf-8") + assert 'op.create_table(\n "users",' in text + assert 'sa.Column("id", GUID(), nullable=False)' in text + + def test_jwt_alembic_revision_matches_the_model(self, tmp_path: Path) -> None: + project = _matrix_project( + tmp_path, "minimal", "JWT", "SQLite", migrations="Alembic" + ) + (revision,) = (project / "alembic/versions").glob("*_initial.py") + text = revision.read_text("utf-8") + + assert 'sa.Column("email", sa.String(length=320), nullable=False)' in text + assert ( + 'op.create_index(op.f("ix_users_email"), "users", ["email"], unique=True)' + in text + ) + assert "lifespan" not in (project / "src/auth/router.py").read_text("utf-8") + + def test_rate_limited_login_reads_its_own_setting(self, tmp_path: Path) -> None: + project = _matrix_project( + tmp_path, "minimal", "Session-based", "None", utilities=["Rate-Limiting"] + ) + router = (project / "src/auth/router.py").read_text("utf-8") + config = (project / "src/core/config.py").read_text("utf-8") + + assert ( + "_auth_rate_limit = [Depends(RateLimit(settings.RATE_LIMIT_AUTH))]" + in router + ) + # login and register (both hash a password) share the stricter budget + assert router.count("dependencies=_auth_rate_limit,") == 2 + assert 'RATE_LIMIT_AUTH: str = "5/minute"' in config + + def test_invalid_combination_is_refused_before_generation( + self, tmp_path: Path + ) -> None: + with pytest.raises(ConfigSchemaError, match="FastAPI-Users"): + _matrix_project(tmp_path, "minimal", "FastAPI-Users", "MongoDB") + # -------------------------------------------------------------------------- # .env generation for the auth selections @@ -497,7 +969,9 @@ def test_env_gets_a_unique_value_for_every_secret( assert _secret_key(example) == "changethis" assert _secret_key(env) not in KNOWN_EXAMPLE_SECRETS assert len(_secret_key(env)) >= 32 - assert re.search(r"^ENVIRONMENT=development$", env, re.M) + # Documented (templates may leave it commented: it defaults to + # development either way). + assert re.search(r"^(# )?ENVIRONMENT=development$", env, re.M) keys.append(_secret_key(env)) assert keys[0] != keys[1] diff --git a/tests/test_backends/test_import_ordering.py b/tests/test_backends/test_import_ordering.py index e50c13a..6722c54 100644 --- a/tests/test_backends/test_import_ordering.py +++ b/tests/test_backends/test_import_ordering.py @@ -127,17 +127,18 @@ def test_preset_wiring_produces_a_sorted_block(tmp_path: Path) -> None: str(tmp_path), config ) - # then: fastapi-default already serves an items list, so Pagination is - # wired as ``add_pagination`` only and no example router is imported + # then: Pagination is built into list endpoints and wires nothing; the + # generated routers land sorted below the anchor content = main_py.read_text(encoding="utf-8") - assert set(wired) == {"WebSocket", "Pagination", "Background tasks"} + assert wired == ["Background tasks", "WebSocket"] assert ( - SORTED_IMPORTS.replace( - "from src.features.pagination import router as pagination_router\n", "" - ) - in content - ) - assert "pagination_router" not in content + "from src.core.config import settings\n" + "\n" + "# fastkit:imports\n" + "from src.features import websocket\n" + "from src.features.tasks import router as tasks_router\n" + ) in content + assert "pagination" not in content # ------------------------------------------------------------------ @@ -173,12 +174,12 @@ def test_addroute_singular_next_to_plural_imports_the_router(tmp_path: Path) -> encoding="utf-8", ) - _update_api_router(str(api), "user") + _update_api_router(str(api), "user", package_module="src") first = api.read_text(encoding="utf-8") - _update_api_router(str(api), "user") + _update_api_router(str(api), "user", package_module="src") - assert "from .routes import user\n" in first - assert "include_router(user.router" in first + assert "from src.api.routes.user import router as user_router\n" in first + assert "include_router(user_router)" in first assert api.read_text(encoding="utf-8") == first # The module must bind every router it registers. tree = ast.parse(first) @@ -189,18 +190,41 @@ def test_addroute_singular_next_to_plural_imports_the_router(tmp_path: Path) -> for alias in node.names } registered = { - node.args[0].value.id + ast.unparse(node.args[0]).split(".")[0] for node in ast.walk(tree) if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "include_router" - and isinstance(node.args[0], ast.Attribute) - and isinstance(node.args[0].value, ast.Name) } - assert registered == {"users", "user"} + assert registered == {"users", "user_router"} assert registered <= bound +def test_addroute_imports_stay_sorted_in_a_template_router(tmp_path: Path) -> None: + """Route imports join the template's block in isort order, one per line.""" + api = tmp_path / "api.py" + api.write_text( + "from fastapi import APIRouter\n\nfrom src.api.routes import items\n\n" + "# fastkit:imports\n\napi_router = APIRouter()\n" + "api_router.include_router(items.router)\n# fastkit:routes\n", + encoding="utf-8", + ) + + for name in ("users", "user", "accounts", "items"): + _update_api_router(str(api), name, package_module="src") + + content = api.read_text(encoding="utf-8") + imports = [line for line in content.splitlines() if line.startswith("from src")] + assert imports == [ + "from src.api.routes import items", + "from src.api.routes.accounts import router as accounts_router", + "from src.api.routes.user import router as user_router", + "from src.api.routes.users import router as users_router", + ] + assert content.count("include_router(items.router)") == 1 + assert content.count("include_router(") == 4 + + def test_import_joins_its_section_below_the_anchor() -> None: content = ( "from fastapi import FastAPI\n\n# fastkit:imports\nfrom src.api.a import x\n" diff --git a/tests/test_backends/test_interactive_config_builder.py b/tests/test_backends/test_interactive_config_builder.py index 966d46d..904be29 100644 --- a/tests/test_backends/test_interactive_config_builder.py +++ b/tests/test_backends/test_interactive_config_builder.py @@ -178,7 +178,7 @@ def test_collect_dependencies_with_utilities(self) -> None: dependencies = builder._collect_all_dependencies() # then - assert "slowapi" in dependencies + assert "limits>=3.4" in dependencies class TestBuildFinalConfig: @@ -422,7 +422,7 @@ def test_run_interactive_flow_with_warnings( mock_template.return_value = None mock_features.return_value = { "database": {"type": "None"}, - "authentication": "FastAPI-Users", # Requires database + "authentication": "JWT", "async_tasks": "None", "caching": "None", "monitoring": "None", @@ -440,7 +440,48 @@ def test_run_interactive_flow_with_warnings( # then assert config is not None - assert config["authentication"] == "FastAPI-Users" + assert config["authentication"] == "JWT" + + @patch("fastapi_fastkit.backend.interactive.config_builder.print_error") + @patch("fastapi_fastkit.backend.interactive.config_builder.confirm_selections") + @patch( + "fastapi_fastkit.backend.interactive.config_builder.validate_feature_compatibility" + ) + @patch( + "fastapi_fastkit.backend.interactive.config_builder.prompt_additional_features" + ) + @patch( + "fastapi_fastkit.backend.interactive.config_builder.prompt_architecture_preset" + ) + @patch("fastapi_fastkit.backend.interactive.config_builder.prompt_basic_info") + def test_incompatible_selection_stops_before_confirmation( + self, + mock_basic_info, + mock_preset, + mock_features, + mock_validate, + mock_confirm, + mock_error, + ) -> None: + # given + builder = InteractiveConfigBuilder(FastkitConfig()) + mock_basic_info.return_value = { + "project_name": "test-project", + "author": "Test", + "author_email": "test@example.com", + "description": "Test", + } + mock_preset.return_value = "minimal" + mock_features.return_value = {"database": {"type": "SQLite"}} + mock_validate.return_value = (False, "FastAPI-Users needs a SQL database") + + # when + config = builder.run_interactive_flow() + + # then + assert config == {} + mock_error.assert_called_once_with("FastAPI-Users needs a SQL database") + mock_confirm.assert_not_called() class TestGetConfig: diff --git a/tests/test_backends/test_interactive_prompts.py b/tests/test_backends/test_interactive_prompts.py index 309ef9b..e4ff33b 100644 --- a/tests/test_backends/test_interactive_prompts.py +++ b/tests/test_backends/test_interactive_prompts.py @@ -393,6 +393,66 @@ def test_never_offers_the_none_sentinel(self, mock_console) -> None: assert len(result) == 5 +class TestPromptUtilitiesSelection: + """Test cases for prompt_utilities_selection function.""" + + @patch("fastapi_fastkit.backend.interactive.prompts.console") + def test_descriptions_name_what_is_generated(self, mock_console) -> None: + """Rate-Limiting uses ``limits``; Pagination is built in.""" + # given + settings = FastkitConfig() + mock_console.input.return_value = "" + + # when + result = prompts.prompt_utilities_selection(settings) + + # then + assert result == [] + printed = " ".join(str(c.args[0]) for c in mock_console.print.call_args_list) + assert "Rate-Limiting Per-client API rate limits (limits)" in printed + assert "Pagination (Built-in, list endpoints are always paginated)" in printed + assert "slowapi" not in printed + + +class TestFastapiUsersNeedsASqlDatabase: + """The auth prompt is asked again until the pair can be generated.""" + + @patch("fastapi_fastkit.backend.interactive.prompts.print_error") + @patch("fastapi_fastkit.backend.interactive.prompts.prompt_custom_packages") + @patch( + "fastapi_fastkit.backend.interactive.prompts.prompt_package_manager_selection" + ) + @patch("fastapi_fastkit.backend.interactive.prompts.prompt_deployment_options") + @patch("fastapi_fastkit.backend.interactive.prompts.prompt_tooling_selection") + @patch("fastapi_fastkit.backend.interactive.prompts.prompt_utilities_selection") + @patch("fastapi_fastkit.backend.interactive.prompts.prompt_migrations_selection") + @patch("fastapi_fastkit.backend.interactive.prompts.prompt_testing_selection") + @patch("fastapi_fastkit.backend.interactive.prompts.prompt_logging_selection") + @patch("fastapi_fastkit.backend.interactive.prompts.prompt_monitoring_selection") + @patch("fastapi_fastkit.backend.interactive.prompts.prompt_caching_selection") + @patch("fastapi_fastkit.backend.interactive.prompts.prompt_async_tasks_selection") + @patch( + "fastapi_fastkit.backend.interactive.prompts.prompt_authentication_selection" + ) + @patch("fastapi_fastkit.backend.interactive.prompts.prompt_database_selection") + def test_fastapi_users_on_mongodb_is_asked_again( + self, mock_database, mock_auth, *others + ) -> None: + # given + mock_error = others[-1] + mock_database.return_value = {"type": "MongoDB", "packages": []} + mock_auth.side_effect = ["FastAPI-Users", "JWT"] + + # when + features = prompts.prompt_additional_features(FastkitConfig()) + + # then + assert features["authentication"] == "JWT" + assert mock_auth.call_count == 2 + (message,), _ = mock_error.call_args + assert "'FastAPI-Users' needs a SQL database" in message + + class TestPromptAdditionalFeaturesCoversEveryAxis: """The aggregate flow must ask about every catalog axis.""" diff --git a/tests/test_backends/test_interactive_validators.py b/tests/test_backends/test_interactive_validators.py index 250c6c8..6c792f2 100644 --- a/tests/test_backends/test_interactive_validators.py +++ b/tests/test_backends/test_interactive_validators.py @@ -4,6 +4,8 @@ # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- +import pytest + from fastapi_fastkit.backend.interactive.validators import ( sanitize_custom_packages, validate_email_format, @@ -397,21 +399,38 @@ def test_compatible_features_full_stack(self) -> None: if warning: assert "Redis" in warning - def test_fastapi_users_without_database_warning(self) -> None: - """Test warning when FastAPI-Users selected without database.""" + @pytest.mark.parametrize( + ("database", "selected"), + [ + ("None", "no database"), + ("MongoDB", "database 'MongoDB'"), + ("Redis", "database 'Redis'"), + ], + ) + def test_fastapi_users_without_sql_database_is_incompatible( + self, database: str, selected: str + ) -> None: + """FastAPI-Users is generated on SQLAlchemy only; other databases fail.""" # given config = { - "database": {"type": "None"}, + "database": {"type": database}, "authentication": "FastAPI-Users", } # when - is_valid, warning = validate_feature_compatibility(config) + is_valid, message = validate_feature_compatibility(config) # then - assert is_valid is True - assert warning is not None - assert "FastAPI-Users requires a database" in warning + assert is_valid is False + assert message is not None + assert "'FastAPI-Users' needs a SQL database" in message + assert f"but {selected} is selected" in message + + @pytest.mark.parametrize("database", ["PostgreSQL", "MySQL", "SQLite"]) + def test_fastapi_users_with_sql_database_is_compatible(self, database: str) -> None: + config = {"database": {"type": database}, "authentication": "FastAPI-Users"} + + assert validate_feature_compatibility(config) == (True, None) def test_fastapi_users_with_database_no_warning(self) -> None: """Test no warning when FastAPI-Users with database.""" diff --git a/tests/test_backends/test_main.py b/tests/test_backends/test_main.py index c86f5bf..06e3b20 100644 --- a/tests/test_backends/test_main.py +++ b/tests/test_backends/test_main.py @@ -789,245 +789,90 @@ def test_process_config_file_read_error(self) -> None: ): _process_config_file(str(config_py), "test-project") - @patch("fastapi_fastkit.backend.main._ensure_project_structure") - @patch("fastapi_fastkit.backend.main._create_route_files") - @patch("fastapi_fastkit.backend.main._handle_api_router_file") - @patch("fastapi_fastkit.backend.main._update_main_app") - def test_add_new_route( - self, - mock_update_main: MagicMock, - mock_handle_api: MagicMock, - mock_create_route: MagicMock, - mock_ensure_structure: MagicMock, - ) -> None: - """Test add_new_route function.""" + @patch("fastapi_fastkit.backend.route_generators.plan_new_route") + def test_add_new_route(self, mock_plan: MagicMock) -> None: + """add_new_route computes the plan, then applies it.""" # given - mock_ensure_structure.return_value = { - "api_routes": "/fake/api/routes", - "crud": "/fake/crud", - "schemas": "/fake/schemas", - } + plan = MagicMock() + plan.notes = [] + mock_plan.return_value = plan # when - add_new_route(str(self.project_path), "test_route") + result = add_new_route(str(self.project_path), "test_route", entity="Thing") # then - mock_ensure_structure.assert_called_once() - mock_create_route.assert_called_once() - mock_handle_api.assert_called_once() - mock_update_main.assert_called_once() - - def test_ensure_project_structure_success(self) -> None: - """Test _ensure_project_structure function with successful structure creation.""" - # given - src_dir = self.project_path / "src" - src_dir.mkdir() - - # when - from fastapi_fastkit.backend.main import _ensure_project_structure - - result = _ensure_project_structure(str(src_dir)) - - # then - assert "api" in result - assert "api_routes" in result - assert "crud" in result - assert "schemas" in result - - # Check directories were created - assert (src_dir / "api").exists() - assert (src_dir / "api" / "routes").exists() - assert (src_dir / "crud").exists() - assert (src_dir / "schemas").exists() - - # Check __init__.py files were created - assert (src_dir / "api" / "__init__.py").exists() - assert (src_dir / "api" / "routes" / "__init__.py").exists() - assert (src_dir / "crud" / "__init__.py").exists() - assert (src_dir / "schemas" / "__init__.py").exists() - - def test_ensure_project_structure_missing_src_dir(self) -> None: - """Test _ensure_project_structure function when src directory doesn't exist.""" - # given - nonexistent_dir = str(self.project_path / "nonexistent") - - # when & then - from fastapi_fastkit.backend.main import _ensure_project_structure - - with pytest.raises(BackendExceptions, match="Source directory not found"): - _ensure_project_structure(nonexistent_dir) - - def test_ensure_project_structure_existing_directories(self) -> None: - """Test _ensure_project_structure function when directories already exist.""" + mock_plan.assert_called_once_with( + str(self.project_path), "test_route", layout=None, entity="Thing" + ) + plan.apply.assert_called_once_with() + assert result is plan + + def test_add_new_route_applies_a_given_plan(self) -> None: + """A plan the caller already computed is applied as is.""" + plan = MagicMock() + with patch("fastapi_fastkit.backend.route_generators.plan_new_route") as mock: + add_new_route(str(self.project_path), "test_route", plan=plan) + mock.assert_not_called() + plan.apply.assert_called_once_with() + + def test_update_api_router_registers_route_module(self) -> None: + """A route module is imported on its own line and registered.""" # given - src_dir = self.project_path / "src" - src_dir.mkdir() - api_dir = src_dir / "api" + api_dir = self.project_path / "api" api_dir.mkdir() - (api_dir / "__init__.py").write_text("# existing") - - # when - from fastapi_fastkit.backend.main import _ensure_project_structure - - result = _ensure_project_structure(str(src_dir)) - - # then - assert result["api"] == str(api_dir) - # Should preserve existing __init__.py content - assert (api_dir / "__init__.py").read_text() == "# existing" - - @patch("fastapi_fastkit.backend.main.copy_and_convert_template_file") - def test_create_route_files_success(self, mock_copy: MagicMock) -> None: - """Test _create_route_files function with successful file creation.""" - # given - modules_dir = str(self.project_path / "modules") - target_dirs = { - "api_routes": str(self.project_path / "api" / "routes"), - "crud": str(self.project_path / "crud"), - "schemas": str(self.project_path / "schemas"), - } - route_name = "test_route" - mock_copy.return_value = True - - # Create target directories - for dir_path in target_dirs.values(): - os.makedirs(dir_path, exist_ok=True) - - # when - from fastapi_fastkit.backend.main import _create_route_files - - _create_route_files(modules_dir, target_dirs, route_name) - - # then - assert mock_copy.call_count == 3 # api/routes, crud, schemas - - @patch("fastapi_fastkit.backend.main.copy_and_convert_template_file") - def test_create_route_files_existing_file(self, mock_copy: MagicMock) -> None: - """Test _create_route_files function when target file already exists.""" - # given - modules_dir = str(self.project_path / "modules") - target_dirs = { - "api_routes": str(self.project_path / "api" / "routes"), - "crud": str(self.project_path / "crud"), - "schemas": str(self.project_path / "schemas"), - } - route_name = "test_route" - - # Create target directories and existing file - os.makedirs(target_dirs["api_routes"], exist_ok=True) - os.makedirs(target_dirs["crud"], exist_ok=True) - os.makedirs(target_dirs["schemas"], exist_ok=True) - - existing_file = Path(target_dirs["api_routes"]) / f"{route_name}.py" - existing_file.write_text("# existing") - - # when - from fastapi_fastkit.backend.main import _create_route_files - - _create_route_files(modules_dir, target_dirs, route_name) - - # then - # Only crud and schemas should be called (api_routes file exists) - assert mock_copy.call_count == 2 # Only crud and schemas, not api_routes - - @patch("fastapi_fastkit.backend.main.copy_and_convert_template_file") - def test_handle_api_router_file_no_existing_file( - self, mock_copy: MagicMock - ) -> None: - """Test _handle_api_router_file function when no api.py exists.""" - # given - target_dirs = {"api": str(self.project_path / "api")} - modules_dir = str(self.project_path / "modules") - route_name = "test_route" - mock_copy.return_value = True - - os.makedirs(target_dirs["api"], exist_ok=True) - - # Create the source template file - os.makedirs(os.path.join(modules_dir, "api"), exist_ok=True) - source_file = Path(modules_dir) / "api" / "__init__.py-tpl" - source_file.write_text( - "from fastapi import APIRouter\napi_router = APIRouter()" + api_file = api_dir / "api.py" + api_file.write_text( + "from fastapi import APIRouter\n\napi_router = APIRouter()\n", + encoding="utf-8", ) # when - from fastapi_fastkit.backend.main import _handle_api_router_file + from fastapi_fastkit.backend.main import _update_api_router - _handle_api_router_file(target_dirs, modules_dir, route_name) + _update_api_router(str(api_file), "users", package_module="src") # then - # Should be called to create api.py file - mock_copy.assert_called() + updated_content = api_file.read_text(encoding="utf-8") + assert ( + "from src.api.routes.users import router as users_router" in updated_content + ) + assert "api_router.include_router(users_router)" in updated_content + assert (api_dir / "__init__.py").exists() - def test_handle_api_router_file_existing_file(self) -> None: - """Test _handle_api_router_file function when api.py already exists.""" - # given + def test_update_api_router_without_package_uses_relative_import(self) -> None: + """Without a package the import is relative to the router module.""" api_dir = self.project_path / "api" api_dir.mkdir() api_file = api_dir / "api.py" - existing_content = """ -from fastapi import APIRouter -api_router = APIRouter() + from fastapi_fastkit.backend.main import _update_api_router -@api_router.get("/items") -def get_items(): - return {"items": []} -""" - api_file.write_text(existing_content) + _update_api_router(str(api_file), "users") - target_dirs = {"api": str(api_dir)} - modules_dir = str(self.project_path / "modules") - route_name = "users" + content = api_file.read_text(encoding="utf-8") + assert "from .routes.users import router as users_router" in content + assert "api_router = APIRouter()" in content + assert content.count("include_router(users_router)") == 1 - # when - from fastapi_fastkit.backend.main import _handle_api_router_file - - _handle_api_router_file(target_dirs, modules_dir, route_name) - - # then - updated_content = api_file.read_text() - # Check for the actual import pattern used in _update_api_router - assert "from .routes import users" in updated_content - assert ( - 'api_router.include_router(users.router, prefix="/users", tags=["users"])' - in updated_content + def test_update_api_router_keeps_a_module_import(self) -> None: + """``from .routes import users`` written by older fastkit is reused.""" + api_dir = self.project_path / "api" + api_dir.mkdir() + api_file = api_dir / "api.py" + original = ( + "from fastapi import APIRouter\n\nfrom .routes import users\n\n" + "api_router = APIRouter()\n" + 'api_router.include_router(users.router, prefix="/users", tags=["users"])\n' ) + api_file.write_text(original, encoding="utf-8") - @patch("fastapi_fastkit.backend.main.copy_and_convert_template_file") - def test_process_init_files_success(self, mock_copy: MagicMock) -> None: - """Test _process_init_files function.""" - # given - modules_dir = str(self.project_path / "modules") - # _process_init_files looks for module_base in target_dirs, not exact module_type - target_dirs = { - "api": str(self.project_path / "api"), # api/routes -> api - "crud": str(self.project_path / "crud"), - "schemas": str(self.project_path / "schemas"), - } - module_types = ["api/routes", "crud", "schemas"] - mock_copy.return_value = True - - # Create target directories - for dir_path in target_dirs.values(): - os.makedirs(dir_path, exist_ok=True) - - # Create source template files for each module_base (not module_type) - for module_type in module_types: - module_base = module_type.split("/")[0] # api/routes -> api - source_dir = Path(modules_dir) / module_base - source_dir.mkdir(parents=True, exist_ok=True) - source_file = source_dir / "__init__.py-tpl" - source_file.write_text("# init file") + from fastapi_fastkit.backend.main import _update_api_router - # when - from fastapi_fastkit.backend.main import _process_init_files - - _process_init_files(modules_dir, target_dirs, module_types) + with patch("fastapi_fastkit.backend.route_wiring.print_info") as info: + _update_api_router(str(api_file), "users", package_module="src") - # then - # Only unique module_bases will be processed: api, crud, schemas = 3 calls - assert mock_copy.call_count == 3 + assert api_file.read_text(encoding="utf-8") == original + info.assert_called_once() def test_update_main_app_success(self) -> None: """Test _update_main_app function with successful update.""" @@ -1133,44 +978,22 @@ def test_update_main_app_file_read_error(self) -> None: # Should complete without raising exception _update_main_app(str(src_dir), "test_route") - def test_add_new_route_with_exception(self) -> None: - """Test add_new_route function with OSError.""" - # given - project_dir = str(self.project_path) - - # when & then - with patch( - "fastapi_fastkit.backend.main._ensure_project_structure", - side_effect=OSError("Permission denied"), - ): - with pytest.raises(BackendExceptions, match="Failed to add new route"): - add_new_route(project_dir, "test_route") - - def test_add_new_route_with_backend_exception(self) -> None: - """Test add_new_route function with BackendExceptions.""" - # given - project_dir = str(self.project_path) - - # when & then - with patch( - "fastapi_fastkit.backend.main._ensure_project_structure", - side_effect=BackendExceptions("Backend error"), - ): - with pytest.raises(BackendExceptions, match="Backend error"): - add_new_route(project_dir, "test_route") - - def test_add_new_route_with_unexpected_exception(self) -> None: - """Test add_new_route function with unexpected exception.""" - # given - project_dir = str(self.project_path) - - # when & then + @pytest.mark.parametrize( + "error, message", + [ + (OSError("Permission denied"), "Failed to add new route"), + (BackendExceptions("Backend error"), "Backend error"), + (ValueError("Unexpected error"), "Failed to add new route"), + ], + ) + def test_add_new_route_errors(self, error: Exception, message: str) -> None: + """Planning errors surface as BackendExceptions.""" with patch( - "fastapi_fastkit.backend.main._ensure_project_structure", - side_effect=ValueError("Unexpected error"), + "fastapi_fastkit.backend.route_generators.plan_new_route", + side_effect=error, ): - with pytest.raises(BackendExceptions, match="Failed to add new route"): - add_new_route(project_dir, "test_route") + with pytest.raises(BackendExceptions, match=message): + add_new_route(str(self.project_path), "test_route") class TestProjectFolderFunctions: diff --git a/tests/test_backends/test_preset_layout.py b/tests/test_backends/test_preset_layout.py index 08c0e10..8010e14 100644 --- a/tests/test_backends/test_preset_layout.py +++ b/tests/test_backends/test_preset_layout.py @@ -6,12 +6,18 @@ # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- +import ast +import dataclasses from pathlib import Path import pytest from fastapi_fastkit.backend.project_builder.preset_layout import ( + PAGINATION_NOTE, PresetLayoutStrategist, + auth_generation_notes, + generated_auth, + insert_before_cors, ) @@ -86,25 +92,25 @@ class TestFileTargets: "minimal", "src/main.py", "src/config/database.py", - "src/config/auth.py", + "src/auth", ), ( "single-module", "src/main.py", "src/config/database.py", - "src/config/auth.py", + "src/auth", ), ( "classic-layered", "src/main.py", "src/core/database.py", - "src/core/auth.py", + "src/auth", ), ( "domain-starter", "src/app/main.py", "src/app/core/database.py", - "src/app/core/auth.py", + "src/app/domains/auth", ), ], ) @@ -120,7 +126,7 @@ def test_targets_match_documented_matrix( assert strategist.main_py_target(project) == Path(project) / expected_main assert strategist.db_config_target(project) == Path(project) / expected_db - assert strategist.auth_config_target(project) == Path(project) / expected_auth + assert strategist.profile.auth_package_relpath == expected_auth class TestAppModule: @@ -188,15 +194,22 @@ def test_preserve_main_silent_for_cors_only(self) -> None: def test_classic_layered_silent_when_no_overlay_features(self) -> None: strategist = PresetLayoutStrategist("classic-layered") - # Database / auth only — these don't trigger main.py overlay - # warnings (config files still get generated at the preset path). + # Database / auth only: mounting the readiness probe and the auth + # routes is all main.py needs, and the anchors take care of both. config = { "database": {"type": "PostgreSQL"}, "authentication": "JWT", "utilities": [], "monitoring": "None", } - assert strategist.compatibility_warnings(config) == [] + wired = ["Database lifespan", "Readiness probe", "Authentication routes"] + assert strategist.compatibility_warnings(config, wired=wired) == [] + assert ( + strategist.compatibility_warnings( + {"authentication": "JWT"}, wired=["Authentication routes"] + ) + == [] + ) def test_domain_starter_collects_multiple_warnings(self) -> None: strategist = PresetLayoutStrategist("domain-starter") @@ -233,8 +246,11 @@ class TestNewOverlayWarningTargets: ({"async_tasks": "Celery"}, "Background tasks"), ({"caching": "Redis"}, "Caching (Redis)"), ({"utilities": ["WebSocket"]}, "WebSocket"), - ({"utilities": ["Pagination"]}, "Pagination"), - ({"authentication": "OAuth2"}, "OAuth2 session middleware"), + ({"authentication": "OAuth2"}, "Session middleware"), + ({"authentication": "Session-based"}, "Authentication routes"), + ({"monitoring": "Loguru"}, "Loguru"), + ({"database": {"type": "SQLite"}}, "Readiness probe"), + ({"database": {"type": "MongoDB"}}, "Database lifespan"), ({"logging": "structured"}, "Structured logging"), ({"monitoring": "OpenTelemetry"}, "OpenTelemetry"), ], @@ -310,14 +326,27 @@ def test_routers_are_inserted_at_anchors(self, tmp_path: Path) -> None: # then content = main_py.read_text(encoding="utf-8") - assert set(wired) == {"WebSocket", "Pagination", "Background tasks"} + assert wired == ["Background tasks", "WebSocket"] assert "from src.features.tasks import router as tasks_router" in content + assert "from src.features import websocket" in content + assert "from src.core.config import settings" in content + # F10: business routers under the API prefix, the WebSocket at the root. assert ( - "from src.features.websocket import router as websocket_router" in content + "app.include_router(tasks_router, prefix=settings.API_V1_PREFIX)" in content + ) + assert "app.include_router(websocket.router)\n" in content + assert ( + "app.include_router(websocket.api_router, prefix=settings.API_V1_PREFIX)" + in content + ) + assert "pagination" not in content + # Declared order is kept below the anchor, above the template's router. + assert ( + content.index("tasks_router, prefix") + < content.index("websocket.router)") + < content.index("websocket.api_router") + < content.index("app.include_router(api_router)") ) - assert "from fastapi_pagination import add_pagination" in content - assert "app.include_router(tasks_router)" in content - assert "add_pagination(app)" in content def test_domain_starter_uses_nested_package_root(self, tmp_path: Path) -> None: # given @@ -332,96 +361,410 @@ def test_domain_starter_uses_nested_package_root(self, tmp_path: Path) -> None: ) # then + content = main_py.read_text(encoding="utf-8") assert wired == ["Background tasks"] + assert "from src.app.features.tasks import router as tasks_router" in content + assert "from src.app.core.config import settings" in content + + def test_module_level_setup_is_wired_after_the_app_exists( + self, tmp_path: Path + ) -> None: + main_py = tmp_path / "src" / "main.py" + main_py.parent.mkdir(parents=True) + main_py.write_text(self.MAIN_PY, encoding="utf-8") + config = { + "caching": "Redis", + "monitoring": "Prometheus", + "logging": "structured", + "utilities": ["Rate-Limiting"], + } + + wired = PresetLayoutStrategist("classic-layered").wire_generated_routers( + str(tmp_path), config + ) + + content = main_py.read_text(encoding="utf-8") + assert wired == [ + "Structured logging", + "Rate-Limiting", + "Prometheus", + "Caching (Redis)", + "Readiness probe", + ] + for statement in ( + "setup_logging(app)", + "setup_rate_limiting(app)", + 'Instrumentator().instrument(app).expose(app, tags=["monitoring"])', + "app.include_router(cache_router, prefix=settings.API_V1_PREFIX)", + "app.include_router(readiness_router)", + ): + assert content.index("app = FastAPI()") < content.index(statement) + assert "from prometheus_fastapi_instrumentator import Instrumentator" in content + ast.parse(content) assert ( - "from src.app.features.tasks import router as tasks_router" - in main_py.read_text(encoding="utf-8") + PresetLayoutStrategist("classic-layered").compatibility_warnings( + config, wired=wired + ) + == [] ) - def test_caching_is_never_auto_wired(self, tmp_path: Path) -> None: + def test_wiring_twice_changes_nothing_and_keeps_crlf(self, tmp_path: Path) -> None: + main_py = tmp_path / "src" / "main.py" + main_py.parent.mkdir(parents=True) + main_py.write_bytes(self.MAIN_PY.replace("\n", "\r\n").encode()) + strategist = PresetLayoutStrategist("classic-layered") + config = {"utilities": ["WebSocket", "Rate-Limiting"]} + + strategist.wire_generated_routers(str(tmp_path), config) + once = main_py.read_bytes() + strategist.wire_generated_routers(str(tmp_path), config) + + assert main_py.read_bytes() == once + assert once.count(b"\n") == once.count(b"\r\n") + assert once.count(b"setup_rate_limiting(app)\r\n") == 1 + + def test_template_serving_ready_gets_no_generated_probe( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + strategist = PresetLayoutStrategist("classic-layered") + monkeypatch.setattr( + strategist, + "profile", + dataclasses.replace( + strategist.profile, shipped_paths=("/health", "/ready") + ), + ) + main_py = tmp_path / "src" / "main.py" + main_py.parent.mkdir(parents=True) + main_py.write_text(self.MAIN_PY, encoding="utf-8") + config = {"database": {"type": "SQLite"}} + + wired = strategist.wire_generated_routers(str(tmp_path), config) + + assert wired == ["Database lifespan"] + assert strategist.compatibility_warnings(config, wired=wired) == [] + assert "readiness" not in main_py.read_text(encoding="utf-8") + + +class TestDatabaseLifespanWiring: + """The database module's lifespan router is included, nothing is manual.""" + + MAIN_PY = TestWireGeneratedRouters.MAIN_PY + + @pytest.mark.parametrize( + ("preset", "main_relpath", "module"), + [ + ("classic-layered", "src/main.py", "src.core.database"), + ("domain-starter", "src/app/main.py", "src.app.core.database"), + ], + ) + @pytest.mark.parametrize("database", ["MongoDB", "SQLite", "PostgreSQL", "Redis"]) + def test_lifespan_router_is_included_before_feature_routers( + self, tmp_path: Path, preset: str, main_relpath: str, module: str, database: str + ) -> None: + # given + main_py = tmp_path.joinpath(*main_relpath.split("/")) + main_py.parent.mkdir(parents=True) + main_py.write_text(self.MAIN_PY, encoding="utf-8") + strategist = PresetLayoutStrategist(preset) + config = {"database": {"type": database}, "authentication": "JWT"} + + # when + wired = strategist.wire_generated_routers(str(tmp_path), config) + + # then + content = main_py.read_text(encoding="utf-8") + assert wired[0] == "Database lifespan" + assert f"from {module} import lifespan_router as database_lifespan" in content + # First included: it starts before the auth router's table creation + # and shuts down after it. + assert ( + content.index("app.include_router(database_lifespan)") + < content.index("app.include_router(readiness_router)") + < content.index("app.include_router(auth_router") + ) + assert strategist.compatibility_warnings(config, wired=wired) == [] + ast.parse(content) + + def test_mongodb_leaves_no_manual_step(self) -> None: + config = {"database": {"type": "MongoDB"}, "authentication": "JWT"} + strategist = PresetLayoutStrategist("classic-layered") + + notes = strategist.generation_notes(config) + + assert not any("yourself" in note for note in notes) + + def test_no_database_wires_no_lifespan(self, tmp_path: Path) -> None: main_py = tmp_path / "src" / "main.py" main_py.parent.mkdir(parents=True) main_py.write_text(self.MAIN_PY, encoding="utf-8") wired = PresetLayoutStrategist("classic-layered").wire_generated_routers( - str(tmp_path), {"caching": "Redis"} + str(tmp_path), {"authentication": "JWT"} ) - assert wired == [] - assert main_py.read_text(encoding="utf-8") == self.MAIN_PY + assert "Database lifespan" not in wired + assert "lifespan" not in main_py.read_text(encoding="utf-8") + + +class TestGenerationNotes: + @pytest.mark.parametrize("preset", PresetLayoutStrategist.supported_presets()) + def test_pagination_prints_one_info_line(self, preset: str) -> None: + strategist = PresetLayoutStrategist(preset) + notes = strategist.generation_notes({"utilities": ["Pagination"]}) -class TestSkippedExampleRouters: - """Demo routers are skipped where the base template ships the collection.""" + assert notes == [PAGINATION_NOTE] + assert "core/pagination.py" in notes[0] + assert strategist.generation_notes({"utilities": ["CORS"]}) == [] - PAGINATION = {"utilities": ["Pagination"]} +class TestProfiles: @pytest.mark.parametrize( - "preset,expected", + ("preset", "settings", "pagination"), [ - ("minimal", []), - ("single-module", []), - ("classic-layered", ["Pagination"]), - ("domain-starter", ["Pagination"]), + ("minimal", "src/core/config.py", True), + ("single-module", "src/core/config.py", True), + ("classic-layered", "src/core/config.py", False), + ("domain-starter", "src/app/core/config.py", False), ], ) - def test_presets_with_an_items_api_skip_the_pagination_demo( - self, preset: str, expected: list + def test_settings_module_and_pagination( + self, preset: str, settings: str, pagination: bool ) -> None: - strategist = PresetLayoutStrategist(preset) + profile = PresetLayoutStrategist(preset).profile + + assert profile.settings_relpath == settings + assert profile.provide_pagination is pagination + - assert strategist.skipped_example_labels(self.PAGINATION) == expected - assert strategist.skipped_example_labels({"utilities": ["WebSocket"]}) == [] +# -------------------------------------------------------------------------- +# Authentication wiring for presets that keep the template main.py +# -------------------------------------------------------------------------- + +CORS_MAIN_PY = ( + "from fastapi import FastAPI\n" + "from starlette.middleware.cors import CORSMiddleware\n" + "\n" + "from src.core.config import settings\n" + "\n" + "# fastkit:imports\n" + "\n" + "app = FastAPI()\n" + "\n" + "# CORS comment that belongs to the block below.\n" + "if settings.all_cors_origins:\n" + " app.add_middleware(CORSMiddleware, allow_origins=settings.all_cors_origins)\n" + "\n" + "# fastkit:routes\n" +) + + +def _wire(tmp_path: Path, preset: str, config: dict) -> str: + strategist = PresetLayoutStrategist(preset) + main_py = tmp_path / strategist.profile.main_py_relpath + main_py.parent.mkdir(parents=True, exist_ok=True) + main_py.write_text(CORS_MAIN_PY, encoding="utf-8") + strategist.wire_generated_routers(str(tmp_path), config) + return main_py.read_text(encoding="utf-8") + + +class TestAuthWiring: + @pytest.mark.parametrize( + ("preset", "package"), + [("classic-layered", "src.auth"), ("domain-starter", "src.app.domains.auth")], + ) + @pytest.mark.parametrize("auth", ["JWT", "Session-based", "OAuth2"]) + def test_auth_router_is_mounted_under_the_api_prefix( + self, tmp_path: Path, preset: str, package: str, auth: str + ) -> None: + source = _wire(tmp_path, preset, {"authentication": auth}) - def test_note_names_the_shipped_endpoint_and_the_skipped_module(self) -> None: - notes = PresetLayoutStrategist("domain-starter").skipped_example_notes( - self.PAGINATION + assert f"from {package}.router import router as auth_router" in source + statements = [ast.unparse(node) for node in ast.parse(source).body] + assert ( + "app.include_router(auth_router, prefix=settings.API_V1_PREFIX)" + in statements ) - assert len(notes) == 1 - assert "GET /api/v1/items" in notes[0] - assert "src/app/features/pagination.py was not generated" in notes[0] + @pytest.mark.parametrize("auth", ["Session-based", "OAuth2"]) + def test_session_middleware_is_added_before_cors( + self, tmp_path: Path, auth: str + ) -> None: + source = _wire( + tmp_path, + "classic-layered", + {"authentication": auth, "utilities": ["Rate-Limiting"]}, + ) + + lines = source.split("\n") + session = lines.index("add_session_middleware(app)") + rate_limit = lines.index("setup_rate_limiting(app)") + comment = lines.index("# CORS comment that belongs to the block below.") + # Added earlier = inner: CORS (added last) wraps both. + assert rate_limit < session < comment + assert "from src.auth.middleware import add_session_middleware" in source + + def test_jwt_adds_no_session_middleware(self, tmp_path: Path) -> None: + source = _wire(tmp_path, "classic-layered", {"authentication": "JWT"}) + + assert "add_session_middleware" not in source - def test_wiring_adds_only_add_pagination_after_the_template_routers( + def test_wiring_is_idempotent(self, tmp_path: Path) -> None: + strategist = PresetLayoutStrategist("classic-layered") + config = {"authentication": "Session-based"} + once = _wire(tmp_path, "classic-layered", config) + + strategist.wire_generated_routers(str(tmp_path), config) + + assert (tmp_path / "src" / "main.py").read_text(encoding="utf-8") == once + + def test_fastapi_users_without_sql_database_is_not_wired( self, tmp_path: Path ) -> None: - # given - main_py = tmp_path / "src" / "app" / "main.py" - main_py.parent.mkdir(parents=True) - main_py.write_text(TestWireGeneratedRouters.MAIN_PY, encoding="utf-8") - strategist = PresetLayoutStrategist("domain-starter") + config = {"authentication": "FastAPI-Users", "database": {"type": "MongoDB"}} - # when: wired twice, the second run must not duplicate anything - wired = strategist.wire_generated_routers(str(tmp_path), self.PAGINATION) - strategist.wire_generated_routers(str(tmp_path), self.PAGINATION) + source = _wire(tmp_path, "classic-layered", config) - # then - content = main_py.read_text(encoding="utf-8") - assert wired == ["Pagination"] - assert "from fastapi_pagination import add_pagination" in content - assert "pagination_router" not in content - assert content.count("add_pagination(app)") == 1 - assert content.index("app.include_router(api_router)") < content.index( - "add_pagination(app)" - ) - assert content.rstrip().endswith("add_pagination(app)") - assert "response_model=Page[ItemRead]" in content - assert "src/app/domains/items/router.py" in content - assert all(len(line) <= 88 for line in content.splitlines()) - assert strategist.compatibility_warnings(self.PAGINATION, wired=wired) == [] - - def test_wiring_without_example_keeps_crlf(self, tmp_path: Path) -> None: + assert "auth_router" not in source + assert generated_auth(config) == "None" + assert generated_auth({**config, "database": {"type": "SQLite"}}) == ( + "FastAPI-Users" + ) + + def test_no_auth_option_needs_manual_wiring(self) -> None: + for auth in ("JWT", "Session-based", "OAuth2"): + warnings = PresetLayoutStrategist("domain-starter").compatibility_warnings( + {"authentication": auth}, + wired=["Authentication routes", "Session middleware"], + ) + assert warnings == [], auth + + +class TestInsertBeforeCors: + def test_goes_above_the_comment_attached_to_the_cors_block(self) -> None: + updated = insert_before_cors(CORS_MAIN_PY, "setup(app)") + + assert updated is not None + assert "app = FastAPI()\n\nsetup(app)\n# CORS comment" in updated + + def test_unchanged_when_the_statement_is_present(self) -> None: + once = insert_before_cors(CORS_MAIN_PY, "setup(app)") + + assert insert_before_cors(once or "", "setup(app)") == once + + @pytest.mark.parametrize( + "content", ["app = FastAPI()\n", "def broken(:\n", "app.add_middleware()\n"] + ) + def test_none_without_a_cors_block(self, content: str) -> None: + assert insert_before_cors(content, "setup(app)") is None + + def test_falls_back_to_the_routes_anchor_without_cors(self, tmp_path: Path) -> None: + strategist = PresetLayoutStrategist("classic-layered") main_py = tmp_path / "src" / "main.py" main_py.parent.mkdir(parents=True) - main_py.write_bytes( - TestWireGeneratedRouters.MAIN_PY.replace("\n", "\r\n").encode() + main_py.write_text( + "from fastapi import FastAPI\n\n# fastkit:imports\n\napp = FastAPI()\n" + "\n# fastkit:routes\n", + encoding="utf-8", + ) + + strategist.wire_generated_routers(str(tmp_path), {"authentication": "OAuth2"}) + + source = main_py.read_text(encoding="utf-8") + assert source.index("# fastkit:routes") < source.index( + "add_session_middleware(app)" + ) + + +class TestAuthRouteConflicts: + def test_template_router_with_auth_prefix_is_reported(self, tmp_path: Path) -> None: + routes = tmp_path / "src" / "api" / "routes" + routes.mkdir(parents=True) + (routes / "users.py").write_text( + 'from fastapi import APIRouter\nrouter = APIRouter(prefix="/users")\n', + encoding="utf-8", + ) + (routes / "login.py").write_text( + "from fastapi import APIRouter\nrouter = APIRouter()\n" + '@router.post("/auth/login")\ndef login(): ...\n', + encoding="utf-8", + ) + (routes / "broken.py").write_text("def (:\n", encoding="utf-8") + generated = tmp_path / "src" / "auth" + generated.mkdir() + (generated / "router.py").write_text( + 'from fastapi import APIRouter\nrouter = APIRouter(prefix="/auth")\n', + encoding="utf-8", + ) + + warnings = PresetLayoutStrategist("classic-layered").auth_route_conflicts( + str(tmp_path), {"authentication": "JWT"} ) - PresetLayoutStrategist("classic-layered").wire_generated_routers( - str(tmp_path), self.PAGINATION + assert len(warnings) == 2 + assert warnings[0].startswith("src/api/routes/login.py already defines /auth") + assert warnings[1].startswith("src/api/routes/users.py already defines /users") + + def test_nothing_is_scanned_without_auth(self, tmp_path: Path) -> None: + routes = tmp_path / "src" + routes.mkdir() + (routes / "users.py").write_text( + 'router = APIRouter(prefix="/users")\n', encoding="utf-8" + ) + strategist = PresetLayoutStrategist("classic-layered") + + assert strategist.auth_route_conflicts(str(tmp_path), {}) == [] + assert ( + strategist.auth_route_conflicts( + str(tmp_path / "missing"), {"authentication": "JWT"} + ) + == [] + ) + + +class TestAuthGenerationNotes: + def test_in_memory_store_is_labelled_non_persistent(self) -> None: + notes = auth_generation_notes({"authentication": "JWT"}, "src/auth") + + assert notes[0] == "Authentication (JWT): generated in src/auth/." + assert any("IN MEMORY" in note for note in notes) + + def test_mongodb_store(self) -> None: + notes = auth_generation_notes( + {"authentication": "Session-based", "database": {"type": "MongoDB"}}, + "src/auth", + ) + + assert any("'users' collection" in note for note in notes) + assert any("ENABLE_DEMO_USERS=true" in note for note in notes) + + @pytest.mark.parametrize( + ("migrations", "expected"), + [("Alembic", "alembic upgrade head"), ("None", "created on startup")], + ) + def test_sql_table_creation(self, migrations: str, expected: str) -> None: + notes = auth_generation_notes( + { + "authentication": "FastAPI-Users", + "database": {"type": "PostgreSQL"}, + "migrations": migrations, + }, + "src/auth", + ) + + assert any(expected in note for note in notes) + assert not any("IN MEMORY" in note for note in notes) + + def test_oauth2_and_no_auth(self) -> None: + notes = auth_generation_notes({"authentication": "OAuth2"}, "src/auth") + + assert any("GOOGLE_*" in note for note in notes) + assert auth_generation_notes({}, "src/auth") == [] + + def test_strategist_adds_them_to_the_summary(self) -> None: + notes = PresetLayoutStrategist("domain-starter").generation_notes( + {"authentication": "JWT"} ) - data = main_py.read_bytes() - assert data.count(b"\n") == data.count(b"\r\n") - assert b"add_pagination(app)\r\n" in data - assert b"Page[ItemResponse]" in data + assert notes[0] == "Authentication (JWT): generated in src/app/domains/auth/." diff --git a/tests/test_backends/test_project_builder_config_generator.py b/tests/test_backends/test_project_builder_config_generator.py index 0c8f770..1bc9ce2 100644 --- a/tests/test_backends/test_project_builder_config_generator.py +++ b/tests/test_backends/test_project_builder_config_generator.py @@ -18,6 +18,7 @@ from fastapi_fastkit.backend.project_builder.config_generator import ( DynamicConfigGenerator, ) +from fastapi_fastkit.backend.route_generators import shared_core_source class TestDynamicConfigGeneratorInitialization: @@ -58,12 +59,20 @@ def test_generate_main_py_minimal(self) -> None: # then assert "from fastapi import FastAPI" in content - assert "from fastapi.middleware.cors import CORSMiddleware" in content - assert 'title="TestProject"' in content + # CORS is always wired, like the templates' own main.py: the + # middleware is only added once BACKEND_CORS_ORIGINS lists an origin. + assert "if cors_origins:" in content + assert 'allow_credentials="*" not in cors_origins' in content + # Configuration comes from the project settings module (.env aware). + assert "from src.core.config import settings" in content + assert "title=settings.PROJECT_NAME" in content + assert "os.getenv" not in content assert 'description="A test project"' in content - assert '@app.get("/", tags=["Health"])' in content + assert '@app.get("/", tags=["root"])' in content assert "async def root()" in content - assert '@app.get("/health", tags=["Health"])' in content + assert '@app.get("/health", tags=["health"])' in content + # No database or cache: no readiness probe. + assert "/ready" not in content # Modernized: lifespan context manager, never the removed on_event hook. assert "@asynccontextmanager" in content assert "lifespan=lifespan" in content @@ -89,11 +98,10 @@ def test_generate_main_py_with_postgresql(self) -> None: content = generator.generate_main_py() # then - assert ( - "from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine" - in content - ) - assert "from sqlalchemy.orm import sessionmaker" in content + # The engine is disposed on shutdown and /ready is mounted. + assert "from src.config.database import engine" in content + assert " await engine.dispose()" in content + assert "app.include_router(readiness_router)" in content def test_generate_main_py_with_mongodb(self) -> None: """Test generating main.py with MongoDB database.""" @@ -112,7 +120,13 @@ def test_generate_main_py_with_mongodb(self) -> None: content = generator.generate_main_py() # then - assert "from motor.motor_asyncio import AsyncIOMotorClient" in content + assert "motor_asyncio" not in content + assert "from src.config.database import create_mongo_client" in content + assert " app.state.mongo_client = create_mongo_client()" in content + assert " await app.state.mongo_client.close()" in content + lifespan = content.split("async def lifespan", 1)[1].split("app = FastAPI")[0] + assert lifespan.index("create_mongo_client()") < lifespan.index("yield") + assert lifespan.index("yield") < lifespan.index(".close()") def test_generate_main_py_with_jwt_auth(self) -> None: """Test generating main.py with JWT authentication.""" @@ -130,9 +144,12 @@ def test_generate_main_py_with_jwt_auth(self) -> None: # when content = generator.generate_main_py() - # then - # JWT imports HTTPBearer security - assert "HTTPBearer" in content or "Security" in content + # then: the auth router is mounted under the versioned prefix + assert "from src.auth.router import router as auth_router" in content + assert ( + "app.include_router(auth_router, prefix=settings.API_V1_PREFIX)" in content + ) + assert "noqa" not in content def test_generate_main_py_with_cors_utility(self) -> None: """Test generating main.py with CORS utility.""" @@ -171,7 +188,8 @@ def test_generate_main_py_with_rate_limiting(self) -> None: content = generator.generate_main_py() # then - assert "Limiter" in content or "slowapi" in content + assert "from src.rate_limiting import setup_rate_limiting" in content + assert "\nsetup_rate_limiting(app)\n" in content def test_generate_main_py_with_prometheus(self) -> None: """Test generating main.py with Prometheus monitoring.""" @@ -220,9 +238,15 @@ def test_generate_database_config_postgresql(self) -> None: # then assert content is not None assert "Database Configuration" in content - assert "SQLAlchemy" in content or "sqlalchemy" in content - assert "postgresql+asyncpg" in content assert "AsyncSession" in content + # F4: URL and echo come from the project settings, DeclarativeBase. + assert "from src.core.config import settings" in content + assert "settings.DATABASE_URL" in content + assert "echo=settings.DB_ECHO" in content + assert "echo=True" not in content + assert "class Base(DeclarativeBase):" in content + assert "declarative_base()" not in content + assert "postgresql+asyncpg" in generator.generate_settings_module() def test_generate_database_config_mysql(self) -> None: """Test generating MySQL database config.""" @@ -235,7 +259,7 @@ def test_generate_database_config_mysql(self) -> None: # then assert content is not None - assert "mysql+aiomysql" in content + assert "mysql+aiomysql" in generator.generate_settings_module() def test_generate_database_config_sqlite(self) -> None: """Test generating SQLite database config.""" @@ -248,7 +272,7 @@ def test_generate_database_config_sqlite(self) -> None: # then assert content is not None - assert "sqlite+aiosqlite" in content + assert "sqlite+aiosqlite" in generator.generate_settings_module() def test_generate_database_config_mongodb(self) -> None: """Test generating MongoDB database config.""" @@ -262,52 +286,63 @@ def test_generate_database_config_mongodb(self) -> None: # then assert content is not None assert "MongoDB Configuration" in content - assert "motor" in content.lower() + # F13: PyMongo's native async client, not the deprecated Motor. + assert "from pymongo import AsyncMongoClient" in content + assert "motor_asyncio" not in content + assert "MongoDatabaseDep = Annotated[" in content -class TestGenerateAuthConfig: - """Test cases for generate_auth_config method.""" +class TestGenerateAuthFiles: + """Test cases for generate_auth_files method.""" - def test_generate_auth_config_none(self) -> None: - """Test that None authentication returns None.""" - # given - config = {"authentication": "None"} - generator = DynamicConfigGenerator(config, "/tmp/test") + def test_no_auth_generates_nothing(self) -> None: + generator = DynamicConfigGenerator({"authentication": "None"}, "/tmp/test") - # when - content = generator.generate_auth_config() + assert generator.generate_auth_files() == {} - # then - assert content is None + def test_jwt_generates_the_auth_package(self) -> None: + generator = DynamicConfigGenerator({"authentication": "JWT"}, "/tmp/test") - def test_generate_auth_config_jwt(self) -> None: - """Test generating JWT authentication config.""" - # given - config = {"authentication": "JWT"} - generator = DynamicConfigGenerator(config, "/tmp/test") + files = generator.generate_auth_files() - # when - content = generator.generate_auth_config() - - # then - assert content is not None - assert "JWT Authentication Configuration" in content - assert "import jwt" in content - assert "pwdlib" in content or "password" in content.lower() - assert "SECRET_KEY" in content - - def test_generate_auth_config_fastapi_users(self) -> None: - """Test generating FastAPI-Users authentication config.""" - # given - config = {"authentication": "FastAPI-Users"} - generator = DynamicConfigGenerator(config, "/tmp/test") - - # when - content = generator.generate_auth_config() + assert sorted(files) == [ + f"src/auth/{name}.py" + for name in ( + "__init__", + "dependencies", + "models", + "repository", + "router", + "schemas", + "security", + "service", + ) + ] + for name, content in files.items(): + ast.parse(content, filename=name) + assert "import jwt" in files["src/auth/security.py"] + assert "PasswordHash.recommended()" in files["src/auth/security.py"] + assert "settings.SECRET_KEY" in files["src/auth/security.py"] + + def test_fastapi_users_needs_a_sql_database(self) -> None: + without_db = DynamicConfigGenerator( + {"authentication": "FastAPI-Users"}, "/tmp/test" + ) + with_db = DynamicConfigGenerator( + {"authentication": "FastAPI-Users", "database": {"type": "SQLite"}}, + "/tmp/test", + ) - # then - assert content is not None - assert "FastAPI-Users" in content + assert without_db.generate_auth_files() == {} + files = with_db.generate_auth_files() + assert sorted(files) == [ + "src/auth/__init__.py", + "src/auth/models.py", + "src/auth/router.py", + "src/auth/schemas.py", + "src/auth/users.py", + ] + assert "FastAPIUsers[User, uuid.UUID]" in files["src/auth/users.py"] class TestGenerateTestConfig: @@ -457,6 +492,23 @@ def test_build_code_block(self) -> None: assert result == [" line1", " line2"] +def _declared_settings(path: Path) -> set: + """Fields and properties of the ``Settings`` class in a settings module.""" + tree = ast.parse(path.read_text(encoding="utf-8")) + (cls,) = [ + node + for node in tree.body + if isinstance(node, ast.ClassDef) and node.name == "Settings" + ] + names = set() + for node in cls.body: + if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + names.add(node.target.id) + elif isinstance(node, ast.FunctionDef): + names.add(node.name) + return names + + class TestRenderedOutputIsValidPython: """Every rendered Python artifact must parse. @@ -516,20 +568,36 @@ def test_all_feature_combinations_render_valid_python(self) -> None: main_py = (Path(tmp) / "src/main.py").read_text(encoding="utf-8") assert "# fastkit:imports" in main_py, label assert "# fastkit:routes" in main_py, label - assert '@app.get("/health", tags=["Health"])' in main_py, label - assert '@app.get("/ready", tags=["Health"])' in main_py, label + assert '@app.get("/health", tags=["health"])' in main_py, label + # Caching is always Redis here, so /ready is always mounted. + assert "app.include_router(readiness_router)" in main_py, label assert "on_event" not in main_py, label + assert "fastapi_pagination" not in main_py, label # Every router the app mounts must have been generated. for module, path in ( ("tasks", "src/features/tasks.py"), ("cache", "src/features/cache.py"), ("websocket", "src/features/websocket.py"), - ("pagination", "src/features/pagination.py"), + ("readiness", "src/features/readiness.py"), ): - if f"{module}_router" in main_py: + if f"{module}_router" in main_py or f"{module}.router" in main_py: assert path in written, f"{label}: {path} not generated" + # Every setting a generated module reads is declared, and no + # generated module reads the environment directly. + declared = _declared_settings(Path(tmp) / "src/core/config.py") + for relative in written: + if not relative.endswith(".py"): + continue + source = (Path(tmp) / relative).read_text(encoding="utf-8") + used = set( + re.findall(r"\bsettings\.([A-Za-z_][A-Za-z0-9_]*)", source) + ) + assert used <= declared, f"{label}:{relative}: {used - declared}" + if "/auth" not in relative: + assert "os.getenv" not in source, f"{label}:{relative}" + dockerfile = Path(tmp) / "Dockerfile" compose = Path(tmp) / "docker-compose.yml" assert dockerfile.exists() is with_docker, label @@ -609,11 +677,22 @@ def test_celery_generates_worker_and_task_routes(self) -> None: ast.parse(worker) ast.parse(routes) assert "Celery(" in worker + assert "broker=settings.CELERY_BROKER_URL" in worker + assert "os.getenv" not in worker assert "autoretry_for=(Exception,)" in worker assert "max_retries=3" in worker - assert 'APIRouter(prefix="/api/v1/tasks"' in routes + # F10: the router carries only its resource prefix ... + assert 'APIRouter(prefix="/tasks", tags=["tasks"])' in routes + # ... and main.py mounts it under the versioned API prefix. + assert ( + "app.include_router(tasks_router, prefix=settings.API_V1_PREFIX)" + in artifacts["src/main.py"] + ) assert "example_task.delay" in routes assert "AsyncResult" in routes + # Broker calls block: plain ``def`` handlers run in the threadpool. + assert "async def" not in routes + assert '"Location"' in routes def test_dramatiq_generates_equivalent_worker_and_routes(self) -> None: """Dramatiq must reach the same shape as the Celery option.""" @@ -626,9 +705,20 @@ def test_dramatiq_generates_equivalent_worker_and_routes(self) -> None: ast.parse(worker) ast.parse(routes) assert "RedisBroker" in worker + assert "settings.DRAMATIQ_BROKER_URL" in worker assert "@dramatiq.actor" in worker - assert 'APIRouter(prefix="/api/v1/tasks"' in routes - assert "example_task.send" in routes + assert 'APIRouter(prefix="/tasks", tags=["tasks"])' in routes + # The status lives in the result backend (shared, expiring), not in + # a process-local registry. + assert "result_backend.store_result(message, PENDING_MARKER, TASK_TTL_MS)" in ( + routes + ) + assert "example_task.broker.enqueue(message)" in routes + assert "_MESSAGES" not in routes + assert "result_ttl=TASK_TTL_MS" in worker + assert "async def" not in routes + assert 'detail="Task not found"' in routes + assert "status.HTTP_503_SERVICE_UNAVAILABLE" in routes def test_async_tasks_add_worker_and_redis_compose_services(self) -> None: """docker-compose must run the worker beside the API.""" @@ -652,7 +742,7 @@ def test_async_tasks_add_worker_and_redis_compose_services(self) -> None: assert "image: redis:7-alpine" in compose def test_caching_initializes_backend_and_ships_cached_endpoint(self) -> None: - """Redis caching must be initialised in lifespan and demonstrated.""" + """Redis caching is initialised by the cache router's lifespan.""" # given / when artifacts = self._generate(caching="Redis") @@ -661,9 +751,18 @@ def test_caching_initializes_backend_and_ships_cached_endpoint(self) -> None: cache_module = artifacts["src/features/cache.py"] ast.parse(main_py) ast.parse(cache_module) - assert "FastAPICache.init(RedisBackend(" in main_py - assert "from fastapi_cache import FastAPICache" in main_py + assert "FastAPICache.init(RedisBackend(redis_client)" in cache_module + assert "aioredis.from_url(settings.REDIS_URL)" in cache_module + assert "await redis_client.aclose()" in cache_module + assert ( + 'APIRouter(prefix="/cache", tags=["cache"], lifespan=cache_lifespan)' + in cache_module + ) assert "@cache(expire=60)" in cache_module + assert ( + "app.include_router(cache_router, prefix=settings.API_V1_PREFIX)" in main_py + ) + assert "FastAPICache" not in main_py def test_websocket_utility_generates_connection_manager(self) -> None: """The WebSocket utility must produce a real /ws endpoint.""" @@ -676,40 +775,80 @@ def test_websocket_utility_generates_connection_manager(self) -> None: assert "class ConnectionManager" in module assert '@router.websocket("/ws")' in module assert "async def broadcast" in module - assert "app.include_router(websocket_router)" in artifacts["src/main.py"] + assert 'api_router = APIRouter(prefix="/connections"' in module + assert '"/api/v1' not in module + main_py = artifacts["src/main.py"] + # The WebSocket stays at the root, its HTTP companion is versioned. + assert "app.include_router(websocket.router)\n" in main_py + assert ( + "app.include_router(websocket.api_router, prefix=settings.API_V1_PREFIX)" + in main_py + ) - def test_pagination_utility_calls_add_pagination(self) -> None: - """Pagination is inert unless ``add_pagination(app)`` is called.""" + def test_pagination_utility_generates_no_demo_router(self) -> None: + """Pagination is built into list endpoints: nothing extra is generated.""" # given / when artifacts = self._generate(utilities=["Pagination"]) # then - module = artifacts["src/features/pagination.py"] - ast.parse(module) - assert "Page[Item]" in module - assert "add_pagination(app)" in artifacts["src/main.py"] + assert not any("pagination" in path for path in artifacts) + assert "pagination" not in artifacts["src/main.py"] - def test_omitted_pagination_example_is_neither_written_nor_planned( - self, + def test_pagination_module_is_written_only_when_missing( + self, tmp_path: Path ) -> None: - """A skipped demo router is absent from both the plan and the output.""" + """Shared core modules (and the test) fill a gap, never overwrite.""" # given - config = {"project_name": "p", "utilities": ["Pagination", "WebSocket"]} - - with tempfile.TemporaryDirectory() as tmp: - generator = DynamicConfigGenerator( - config, tmp, omit_example_routers=["Pagination"] - ) + config = {"project_name": "p", "testing": "Basic"} + generator = DynamicConfigGenerator( + config, str(tmp_path), provide_pagination=True + ) - # when - planned = generator.planned_files(include_main=False) - written = generator.generate_all_files(include_main=False) + # when + planned = generator.planned_files() + written = generator.generate_all_files() + + # then: the canonical content addroute also writes + for path in ( + "src/core/pagination.py", + "src/core/responses.py", + "tests/test_pagination.py", + ): + assert path in planned + assert path in written + module = (tmp_path / "src/core/pagination.py").read_text(encoding="utf-8") + assert module == shared_core_source("pagination.py") + assert "fastapi_pagination" not in module + assert (tmp_path / "src/core/__init__.py").exists() + test_module = (tmp_path / "tests/test_pagination.py").read_text("utf-8") + ast.parse(test_module) + imported = re.search( + r"from src\.core\.pagination import \((.*?)\)", test_module, re.S + ) + assert imported is not None + names = {name.strip() for name in imported.group(1).split(",") if name.strip()} + assert names <= set(re.findall(r"^(\w+)\b", module, re.M)) | {"Page"} + + # and a template-shipped module is kept as it is + (tmp_path / "src/core/pagination.py").write_text("# mine\n", encoding="utf-8") + (tmp_path / "tests/test_pagination.py").unlink() + again = DynamicConfigGenerator(config, str(tmp_path), provide_pagination=True) + assert again.planned_files() == sorted( + set(again.planned_files()) - {"src/core/pagination.py"} + ) + assert again.generate_all_files().count("src/core/pagination.py") == 0 + assert (tmp_path / "src/core/pagination.py").read_text( + encoding="utf-8" + ) == "# mine\n" + assert not (tmp_path / "tests/test_pagination.py").exists() + + def test_presets_with_their_own_lists_get_no_pagination_module( + self, tmp_path: Path + ) -> None: + generator = DynamicConfigGenerator({"project_name": "p"}, str(tmp_path)) - # then - assert "src/features/pagination.py" not in planned - assert "src/features/pagination.py" not in written - assert "src/features/websocket.py" in planned - assert "src/features/websocket.py" in written + assert generator.apply_pagination_module() == [] + assert not (tmp_path / "src/core/pagination.py").exists() def test_opentelemetry_instruments_the_app(self) -> None: """OpenTelemetry must instrument the app and configure an exporter.""" @@ -718,10 +857,14 @@ def test_opentelemetry_instruments_the_app(self) -> None: # then main_py = artifacts["src/main.py"] + telemetry = artifacts["src/telemetry.py"] ast.parse(main_py) - assert "FastAPIInstrumentor.instrument_app(app" in main_py - assert "OTLPSpanExporter" in main_py - assert "OTEL_EXPORTER_OTLP_ENDPOINT" in main_py + ast.parse(telemetry) + assert "\nsetup_telemetry(app)\n" in main_py + assert "FastAPIInstrumentor.instrument_app(app" in telemetry + assert "OTLPSpanExporter" in telemetry + assert "settings.OTEL_EXPORTER_OTLP_ENDPOINT" in telemetry + assert "settings.OTEL_SERVICE_NAME" in telemetry def test_oauth2_generates_provider_routes_and_session_middleware(self) -> None: """OAuth2 must produce Google/GitHub routes plus session wiring.""" @@ -729,14 +872,16 @@ def test_oauth2_generates_provider_routes_and_session_middleware(self) -> None: artifacts = self._generate(authentication="OAuth2") # then - auth_module = artifacts["src/config/auth.py"] + auth_module = artifacts["src/auth/router.py"] + middleware = artifacts["src/auth/middleware.py"] main_py = artifacts["src/main.py"] ast.parse(auth_module) ast.parse(main_py) - assert 'oauth.register(\n name="google"' in auth_module - assert 'name="github"' in auth_module - assert '@router.get("/login/{provider}")' in auth_module - assert "app.add_middleware(SessionMiddleware" in main_py + assert '"google": {' in auth_module + assert '"github": {' in auth_module + assert '"/login/{provider}",' in auth_module + assert "app.add_middleware(\n SessionMiddleware" in middleware + assert "add_session_middleware(app)" in main_py def test_session_auth_generates_login_logout(self) -> None: """Session-based auth must produce a working login/logout cycle.""" @@ -744,14 +889,17 @@ def test_session_auth_generates_login_logout(self) -> None: artifacts = self._generate(authentication="Session-based") # then - auth_module = artifacts["src/config/auth.py"] + auth_module = artifacts["src/auth/router.py"] main_py = artifacts["src/main.py"] ast.parse(auth_module) ast.parse(main_py) - assert '@router.post("/login")' in auth_module - assert '@router.post("/logout")' in auth_module + assert ' "/login",' in auth_module + assert ( + '@auth_router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)' + in (auth_module) + ) assert "request.session" in auth_module - assert "SessionMiddleware" in main_py + assert "add_session_middleware(app)" in main_py def test_redis_database_generates_async_client(self) -> None: """Selecting Redis as the database must yield a client module.""" @@ -763,6 +911,8 @@ def test_redis_database_generates_async_client(self) -> None: ast.parse(module) assert "import redis.asyncio as redis" in module assert "async def get_redis(" in module + assert "redis.from_url(settings.REDIS_URL" in module + assert " await close_redis()" in artifacts["src/main.py"] def test_mysql_gets_a_compose_service(self) -> None: """MySQL used to be silently dropped from docker-compose.""" @@ -810,17 +960,93 @@ def test_structured_logging_generates_json_logger_and_request_id(self) -> None: assert "class JsonFormatter(logging.Formatter)" in module assert "class RequestIDMiddleware" in module assert "X-Request-ID" in module - assert "app.add_middleware(RequestIDMiddleware)" in main_py + assert "configure_logging(settings.LOG_LEVEL.upper())" in module + assert "app.add_middleware(RequestIDMiddleware)" in module + assert "\nsetup_logging(app)\n" in main_py - def test_health_and_ready_endpoints_are_always_generated(self) -> None: - """Both probes ship regardless of the feature selection.""" + def test_health_is_always_generated_and_ready_only_with_a_dependency( + self, + ) -> None: + """F12: /health always, /ready only when there is something to check.""" # given / when - artifacts = self._generate() + bare = self._generate() + with_db = self._generate(database={"type": "SQLite"}, testing="Basic") # then - main_py = artifacts["src/main.py"] - assert '@app.get("/health", tags=["Health"])' in main_py - assert '@app.get("/ready", tags=["Health"])' in main_py + main_py = bare["src/main.py"] + assert '@app.get("/health", tags=["health"])' in main_py + assert '"status": "healthy"' not in main_py + assert "readiness" not in main_py + assert "src/features/readiness.py" not in bare + assert "app.include_router(readiness_router)" in with_db["src/main.py"] + readiness = with_db["src/features/readiness.py"] + assert '@router.get(\n "/ready",' in readiness + assert 'text("SELECT 1")' in readiness + assert "HTTP_503_SERVICE_UNAVAILABLE" in readiness + assert "CHECKS: list[Check] = [check_database]" in readiness + assert "tests/test_readiness.py" in with_db + + @pytest.mark.parametrize( + ("overrides", "checks"), + [ + ({"database": {"type": "PostgreSQL"}}, "[check_database]"), + ({"database": {"type": "MongoDB"}}, "[check_mongodb]"), + ({"database": {"type": "Redis"}}, "[check_redis]"), + ({"caching": "Redis"}, "[check_cache]"), + ( + {"database": {"type": "MySQL"}, "caching": "Redis"}, + "[check_database, check_cache]", + ), + ], + ) + def test_readiness_checks_follow_the_selection( + self, overrides: dict, checks: str + ) -> None: + readiness = self._generate(**overrides)["src/features/readiness.py"] + + ast.parse(readiness) + assert f"CHECKS: list[Check] = {checks}" in readiness + + def test_preserved_template_serving_ready_gets_no_generated_probe( + self, tmp_path: Path + ) -> None: + generator = DynamicConfigGenerator( + {"project_name": "p", "database": {"type": "SQLite"}}, + str(tmp_path), + shipped_paths=["/health", "/ready"], + ) + + assert not generator.generates_readiness + assert "src/features/readiness.py" not in generator.build_artifacts() + + def test_rate_limiting_generates_a_limiting_middleware(self) -> None: + """F9: the default limit is enforced by a middleware, from settings.""" + artifacts = self._generate(utilities=["Rate-Limiting"], testing="Basic") + + module = artifacts["src/rate_limiting.py"] + ast.parse(module) + assert "parse(settings.RATE_LIMIT_DEFAULT)" in module + assert "app.add_middleware(RateLimitMiddleware" in module + assert "HTTP_429_TOO_MANY_REQUESTS" in module + assert "Retry-After" in module + assert "--forwarded-allow-ips" in module + assert "slowapi" not in artifacts["src/main.py"] + test = artifacts["tests/test_rate_limiting.py"] + assert "blocked.status_code == 429" in test + + def test_loguru_is_configured_not_only_imported(self) -> None: + artifacts = self._generate(monitoring="Loguru") + + module = artifacts["src/loguru_config.py"] + ast.parse(module) + assert "class InterceptHandler(logging.Handler)" in module + assert "level=settings.LOG_LEVEL.upper()" in module + assert "serialize" not in module + assert "noqa" not in artifacts["src/main.py"] + assert "\nsetup_loguru()\n" in artifacts["src/main.py"] + # With structured logging too, Loguru writes JSON lines. + both = self._generate(monitoring="Loguru", logging="structured") + assert "serialize=True" in both["src/loguru_config.py"] def test_generated_main_py_imports_are_isort_ordered(self) -> None: """Fragments compose freely, so the generator has to sort imports.""" @@ -876,6 +1102,12 @@ def test_alembic_generates_async_environment(self) -> None: ast.parse(env_py) assert "async_engine_from_config" in env_py assert "asyncio.run(run_async_migrations())" in env_py + # The URL and the metadata come from the project's own modules. + assert "from src.config.database import Base" in env_py + assert "from src.core.config import settings" in env_py + assert "settings.DATABASE_URL" in env_py + assert "target_metadata = Base.metadata" in env_py + assert "os.getenv" not in env_py assert "script_location = alembic" in artifacts["alembic.ini"] assert "alembic upgrade" in artifacts["scripts/migrate.sh"] @@ -1197,11 +1429,14 @@ def test_writes_every_artifact_to_disk(self) -> None: "src/features/tasks.py", "src/features/cache.py", "src/features/websocket.py", - "src/features/pagination.py", + "src/features/readiness.py", "src/features/__init__.py", "src/logging_config.py", + "src/rate_limiting.py", + "src/core/config.py", "src/config/database.py", - "src/config/auth.py", + "src/auth/router.py", + "tests/test_auth.py", "alembic/env.py", "scripts/migrate.sh", "Makefile", @@ -1271,7 +1506,7 @@ def test_layout_paths_flow_into_generated_imports(self) -> None: app_module="src.app.main:app", main_py_relpath="src/app/main.py", db_config_relpath="src/app/core/database.py", - auth_config_relpath="src/app/core/auth.py", + auth_package_relpath="src/app/domains/auth", ) # when @@ -1287,3 +1522,334 @@ def test_layout_paths_flow_into_generated_imports(self) -> None: assert "from src.app.worker import" in routes main_py = (Path(tmp) / "src/app/main.py").read_text(encoding="utf-8") assert "from src.app.features.tasks import router" in main_py + + +class TestTestIsolation: + """The root conftest.py keeps test runs away from real services.""" + + @staticmethod + def _conftest(config: dict, tmp_path: Path) -> str: + files = DynamicConfigGenerator(config, str(tmp_path)).generate_test_isolation() + return files.get("conftest.py", "") + + def test_sql_database_runs_tests_in_memory(self, tmp_path: Path) -> None: + content = self._conftest( + {"database": {"type": "PostgreSQL"}, "testing": "Basic"}, tmp_path + ) + + assert 'os.environ["DATABASE_URL"] = "sqlite+aiosqlite://"' in content + assert "OTEL_TRACES_EXPORTER" not in content + assert "limiter" not in content + ast.parse(content) + + def test_opentelemetry_and_rate_limits_are_isolated(self, tmp_path: Path) -> None: + content = self._conftest( + { + "monitoring": "OpenTelemetry", + "utilities": ["Rate-Limiting"], + "testing": "Basic", + }, + tmp_path, + ) + + assert 'os.environ["OTEL_TRACES_EXPORTER"] = "none"' in content + assert 'os.environ["RATE_LIMIT_STORAGE_URI"] = "async+memory://"' in content + assert "@pytest.fixture(autouse=True)" in content + assert "from src.rate_limiting import limiter" in content + assert "DATABASE_URL" not in content + ast.parse(content) + + @pytest.mark.parametrize( + "config", + [ + {"database": {"type": "SQLite"}, "testing": "None"}, + {"database": {"type": "MongoDB"}, "testing": "Basic"}, + {"monitoring": "Prometheus", "testing": "Basic"}, + ], + ) + def test_nothing_to_isolate_writes_no_conftest( + self, config: dict, tmp_path: Path + ) -> None: + assert self._conftest(config, tmp_path) == "" + + def test_conftest_is_planned_and_written(self, tmp_path: Path) -> None: + config = {"database": {"type": "SQLite"}, "testing": "Basic"} + generator = DynamicConfigGenerator(config, str(tmp_path)) + + planned = generator.planned_files(include_main=False) + written = generator.generate_all_files(include_main=False) + + assert "conftest.py" in planned + assert "conftest.py" in written + assert (tmp_path / "conftest.py").is_file() + + def test_telemetry_export_can_be_turned_off(self, tmp_path: Path) -> None: + generator = DynamicConfigGenerator( + {"monitoring": "OpenTelemetry"}, str(tmp_path) + ) + + telemetry = generator.generate_feature_modules()["src/telemetry.py"] + + assert 'if settings.OTEL_TRACES_EXPORTER != "none":' in telemetry + assert ( + 'OTEL_TRACES_EXPORTER: str = "otlp"' in generator.generate_settings_module() + ) + ast.parse(telemetry) + + +class TestGitignore: + """Local SQLite files are ignored by the generated project.""" + + def test_sqlite_patterns_are_appended_once_keeping_crlf( + self, tmp_path: Path + ) -> None: + gitignore = tmp_path / ".gitignore" + gitignore.write_bytes(b"__pycache__\r\ntest.db") + generator = DynamicConfigGenerator( + {"database": {"type": "SQLite"}}, str(tmp_path) + ) + + assert ".gitignore" in generator.planned_files(include_main=False) + assert generator.apply_gitignore() == ".gitignore" + once = gitignore.read_bytes() + + assert once.endswith(b"*.db\r\n*.sqlite3\r\n") + assert once.startswith(b"__pycache__\r\ntest.db\r\n\r\n# Local SQLite") + assert once.count(b"\n") == once.count(b"\r\n") + assert generator.apply_gitignore() is None + assert gitignore.read_bytes() == once + + def test_missing_gitignore_is_created(self, tmp_path: Path) -> None: + generator = DynamicConfigGenerator( + {"database": {"type": "SQLite"}}, str(tmp_path) + ) + + assert generator.apply_gitignore() == ".gitignore" + + lines = (tmp_path / ".gitignore").read_text(encoding="utf-8").splitlines() + assert lines[-2:] == ["*.db", "*.sqlite3"] + + def test_only_the_missing_pattern_is_added(self, tmp_path: Path) -> None: + (tmp_path / ".gitignore").write_text("*.db\n", encoding="utf-8") + generator = DynamicConfigGenerator( + {"database": {"type": "SQLite"}}, str(tmp_path) + ) + + generator.apply_gitignore() + + content = (tmp_path / ".gitignore").read_text(encoding="utf-8") + assert content.count("*.db") == 1 + assert content.endswith("*.sqlite3\n") + + @pytest.mark.parametrize("database", ["PostgreSQL", "MongoDB", "None"]) + def test_other_databases_leave_gitignore_alone( + self, tmp_path: Path, database: str + ) -> None: + generator = DynamicConfigGenerator( + {"database": {"type": database}}, str(tmp_path) + ) + + assert generator.apply_gitignore() is None + assert not (tmp_path / ".gitignore").exists() + + +class TestMypyOverrides: + """Templates running strict mypy accept the generated worker and OAuth2 code.""" + + PYPROJECT = '[project]\nname = "p"\n\n[tool.mypy]\nstrict = true\n' + + def _generator(self, tmp_path: Path, config: dict, pyproject: str) -> Path: + (tmp_path / "pyproject.toml").write_text(pyproject, encoding="utf-8") + generator = DynamicConfigGenerator( + config, str(tmp_path), main_py_relpath="src/app/main.py" + ) + assert generator.apply_mypy_configuration() == "pyproject.toml" + assert generator.apply_mypy_configuration() is None # idempotent + return tmp_path / "pyproject.toml" + + def test_celery_and_oauth2(self, tmp_path: Path) -> None: + path = self._generator( + tmp_path, + {"async_tasks": "Celery", "authentication": "OAuth2"}, + self.PYPROJECT, + ) + + overrides = tomllib.loads(path.read_text(encoding="utf-8"))["tool"]["mypy"][ + "overrides" + ] + assert overrides == [ + { + "module": ["celery", "celery.*", "authlib.*"], + "ignore_missing_imports": True, + }, + { + "module": ["src.app.worker"], + "disallow_untyped_calls": False, + "disallow_untyped_decorators": False, + }, + ] + + def test_dramatiq_relaxes_only_the_worker(self, tmp_path: Path) -> None: + path = self._generator(tmp_path, {"async_tasks": "Dramatiq"}, self.PYPROJECT) + + overrides = tomllib.loads(path.read_text(encoding="utf-8"))["tool"]["mypy"][ + "overrides" + ] + assert overrides == [ + { + "module": ["src.app.worker"], + "disallow_untyped_calls": False, + "disallow_untyped_decorators": False, + } + ] + + @pytest.mark.parametrize( + ("config", "pyproject"), + [ + ({"async_tasks": "Celery"}, '[project]\nname = "p"\n'), + ({"authentication": "JWT"}, PYPROJECT), + ( + {"async_tasks": "Celery"}, + PYPROJECT + '\n[[tool.mypy.overrides]]\nmodule = "celery"\n', + ), + ], + ) + def test_nothing_to_add(self, tmp_path: Path, config: dict, pyproject: str) -> None: + (tmp_path / "pyproject.toml").write_text(pyproject, encoding="utf-8") + generator = DynamicConfigGenerator(config, str(tmp_path)) + + assert generator.apply_mypy_configuration() is None + assert "pyproject.toml" not in generator.planned_files(include_main=False) + + def test_without_pyproject(self, tmp_path: Path) -> None: + generator = DynamicConfigGenerator({"async_tasks": "Celery"}, str(tmp_path)) + + assert generator.apply_mypy_configuration() is None + + def test_unparseable_pyproject_is_left_alone(self, tmp_path: Path) -> None: + (tmp_path / "pyproject.toml").write_text( + "[tool.mypy]\nstrict = = true\n", encoding="utf-8" + ) + generator = DynamicConfigGenerator({"async_tasks": "Celery"}, str(tmp_path)) + + assert generator.apply_mypy_configuration() is None + + +class TestDockerDeployment: + """Compose services reach each other by name; images keep secrets out.""" + + @staticmethod + def _compose(tmp_path: Path, **config: object) -> dict: + yaml = pytest.importorskip("yaml") + generator = DynamicConfigGenerator( + {"deployment": ["Docker", "docker-compose"], **config}, str(tmp_path) + ) + written = generator.generate_docker_files() + assert ".dockerignore" in written + loaded: dict = yaml.safe_load( + (tmp_path / "docker-compose.yml").read_text(encoding="utf-8") + ) + return loaded + + @pytest.mark.parametrize( + ("database", "expected"), + [ + ( + "PostgreSQL", + "DATABASE_URL=${DATABASE_URL:-postgresql+asyncpg://" + "${POSTGRES_USER:-user}:${POSTGRES_PASSWORD:-password}" + "@postgres:5432/${POSTGRES_DB:-dbname}}", + ), + ( + "MySQL", + "DATABASE_URL=${DATABASE_URL:-mysql+aiomysql://" + "${MYSQL_USER:-user}:${MYSQL_PASSWORD:-password}" + "@mysql:3306/${MYSQL_DATABASE:-dbname}}", + ), + ("MongoDB", "MONGODB_URL=${MONGODB_URL:-mongodb://mongodb:27017}"), + ("Redis", "REDIS_URL=redis://redis:6379/0"), + ], + ) + def test_app_points_at_the_compose_service( + self, tmp_path: Path, database: str, expected: str + ) -> None: + compose = self._compose(tmp_path, database={"type": database}) + + assert compose["services"]["app"]["environment"] == [expected] + + def test_worker_shares_the_settings_and_skips_the_api_healthcheck( + self, tmp_path: Path + ) -> None: + compose = self._compose( + tmp_path, database={"type": "PostgreSQL"}, async_tasks="Dramatiq" + ) + + app, worker = compose["services"]["app"], compose["services"]["worker"] + assert app["environment"] == worker["environment"] + assert "DRAMATIQ_BROKER_URL=redis://redis:6379/0" in app["environment"] + assert not any("CELERY" in line for line in app["environment"]) + healthy = {"condition": "service_healthy"} + assert worker["depends_on"] == {"postgres": healthy, "redis": healthy} + assert app["depends_on"] == worker["depends_on"] + assert worker["healthcheck"] == {"disable": True} + assert app["env_file"] == worker["env_file"] == [".env"] + # The services' own probes gate the app; no database port is published. + for service in ("postgres", "redis"): + assert "healthcheck" in compose["services"][service] + assert "ports" not in compose["services"][service] + + def test_sqlite_without_services_sets_no_environment(self, tmp_path: Path) -> None: + compose = self._compose(tmp_path, database={"type": "SQLite"}) + + assert "environment" not in compose["services"]["app"] + + def test_dockerfile_checks_health_and_ignores_secrets(self, tmp_path: Path) -> None: + generator = DynamicConfigGenerator({"deployment": ["Docker"]}, str(tmp_path)) + + assert ".dockerignore" in generator.planned_files(include_main=False) + generator.generate_docker_files() + + dockerfile = (tmp_path / "Dockerfile").read_text(encoding="utf-8") + assert "http://127.0.0.1:8000/health" in dockerfile + ignored = (tmp_path / ".dockerignore").read_text(encoding="utf-8").split() + assert {".env", ".venv", "*.db"} <= set(ignored) + assert "!.env.example" in ignored + + def test_existing_dockerignore_is_kept(self, tmp_path: Path) -> None: + (tmp_path / ".dockerignore").write_text("custom\n", encoding="utf-8") + generator = DynamicConfigGenerator({"deployment": ["Docker"]}, str(tmp_path)) + + written = generator.generate_docker_files() + + assert ".dockerignore" not in written + assert (tmp_path / ".dockerignore").read_text(encoding="utf-8") == "custom\n" + + def test_overrides_are_planned_and_join_an_unterminated_file( + self, tmp_path: Path + ) -> None: + (tmp_path / "pyproject.toml").write_text( + TestMypyOverrides.PYPROJECT.rstrip("\n"), encoding="utf-8" + ) + generator = DynamicConfigGenerator({"async_tasks": "Celery"}, str(tmp_path)) + + assert "pyproject.toml" in generator.planned_files(include_main=False) + generator.apply_mypy_configuration() + + parsed = tomllib.loads((tmp_path / "pyproject.toml").read_text("utf-8")) + assert parsed["tool"]["mypy"]["strict"] is True + assert len(parsed["tool"]["mypy"]["overrides"]) == 2 + + +def test_isort_header_with_a_comment_is_left_alone(tmp_path: Path) -> None: + """The alembic hint is only added to a plain ``[tool.isort]`` header.""" + (tmp_path / "pyproject.toml").write_text( + '[tool.isort] # sorted like black\nprofile = "black"\n', encoding="utf-8" + ) + generator = DynamicConfigGenerator( + {"database": {"type": "SQLite"}, "migrations": "Alembic"}, str(tmp_path) + ) + + assert generator.apply_isort_configuration() is None + assert "known_third_party" not in (tmp_path / "pyproject.toml").read_text( + encoding="utf-8" + ) diff --git a/tests/test_backends/test_project_builder_dependency_collector.py b/tests/test_backends/test_project_builder_dependency_collector.py index da4959a..ca94b45 100644 --- a/tests/test_backends/test_project_builder_dependency_collector.py +++ b/tests/test_backends/test_project_builder_dependency_collector.py @@ -25,6 +25,7 @@ merge_requirements, ) from fastapi_fastkit.core.settings import ( + AuthChoice, FastkitConfig, FeatureAxis, MigrationsChoice, @@ -132,7 +133,8 @@ def test_collect_with_mongodb(self) -> None: dependencies = collector.collect_from_config(config) # then - assert "motor" in dependencies + assert "pymongo>=4.13" in dependencies # AsyncMongoClient GA + assert "motor" not in dependencies assert "fastapi" in dependencies def test_collect_with_jwt_authentication(self) -> None: @@ -456,7 +458,7 @@ def test_add_utility_dependencies_rate_limiting(self) -> None: collector.add_utility_dependencies("Rate-Limiting") # then - assert "slowapi" in collector.dependencies + assert "limits>=3.4" in collector.dependencies class TestGetFinalDependencies: @@ -520,7 +522,7 @@ def test_collect_resets_dependencies(self) -> None: # then # Should have MongoDB dependencies, not PostgreSQL - assert "motor" in deps2 + assert "pymongo>=4.13" in deps2 assert "asyncpg" not in deps2 # But PostgreSQL was in first collection assert "asyncpg" in deps1 @@ -613,12 +615,14 @@ def test_every_catalog_axis_is_walked(self) -> None: "loguru", "factory-boy", "alembic", - "slowapi", - "fastapi-pagination", + "limits>=3.4", "ruff", "pre-commit", ): assert expected in dependencies, expected + # Pagination is built in: selecting it installs nothing. + assert "fastapi-pagination" not in dependencies + assert "slowapi" not in dependencies def test_add_feature_dependencies_replays_metadata_strings(self) -> None: """Project metadata records ``":"`` — replay it back.""" @@ -748,6 +752,8 @@ def _sql_asyncio_cases() -> List[Any]: catalog[FeatureAxis.MIGRATIONS], ) if migrations != MigrationsChoice.ALEMBIC or database in SQL_DATABASES + # FastAPI-Users without a SQL database is rejected by validation. + if auth != AuthChoice.FASTAPI_USERS or database in SQL_DATABASES ] @@ -780,7 +786,7 @@ def test_asyncio_imports_resolve_greenlet( app_module=strategist.app_module, main_py_relpath=strategist.profile.main_py_relpath, db_config_relpath=strategist.profile.db_config_relpath, - auth_config_relpath=strategist.profile.auth_config_relpath, + auth_package_relpath=strategist.profile.auth_package_relpath, ) # when @@ -811,3 +817,41 @@ def test_every_sql_database_uses_asyncio(self) -> None: if any("sqlalchemy.ext.asyncio" in c for c in artifacts.values()): checked.append(database) assert set(checked) >= {"PostgreSQL", "MySQL", "SQLite"} + + +class TestCombinationDependencies: + """Packages one selection needs only together with another.""" + + @pytest.mark.parametrize( + ("database", "auth", "testing", "expected"), + [ + ("PostgreSQL", "JWT", "Basic", True), + ("MySQL", "Session-based", "Coverage", True), + ("PostgreSQL", "FastAPI-Users", "Advanced", True), + ("SQLite", "JWT", "Basic", True), + ("PostgreSQL", "JWT", "None", False), + ("PostgreSQL", "OAuth2", "Basic", True), + ("MySQL", "None", "Basic", True), + ("MongoDB", "JWT", "Basic", False), + ("None", "JWT", "Basic", False), + ], + ) + def test_sql_database_tests_get_aiosqlite( + self, database: str, auth: str, testing: str, expected: bool + ) -> None: + config = { + "database": {"type": database}, + "authentication": auth, + "testing": testing, + } + + dependencies = DependencyCollector(FastkitConfig()).collect_from_config(config) + + assert ("aiosqlite" in dependencies) is expected + + def test_fastapi_users_is_pinned_to_the_generated_api(self) -> None: + dependencies = DependencyCollector(FastkitConfig()).collect_from_config( + {"database": {"type": "SQLite"}, "authentication": "FastAPI-Users"} + ) + + assert "fastapi-users[sqlalchemy]>=15.0.5,<16" in dependencies diff --git a/tests/test_backends/test_project_builder_settings.py b/tests/test_backends/test_project_builder_settings.py new file mode 100644 index 0000000..fc75f78 --- /dev/null +++ b/tests/test_backends/test_project_builder_settings.py @@ -0,0 +1,479 @@ +# -------------------------------------------------------------------------- +# One settings module per generated project (spec convention 16). +# +# Generated features read their configuration from the project's settings +# module. A template-shipped ``Settings`` class gets the fields the selected +# features need; a template without one (fastapi-single-module) gets a +# generated module. The repository virtualenv has no pydantic-settings, so +# these checks work on the rendered source. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +import re +from pathlib import Path +from typing import Any, Dict, List + +import pytest + +from fastapi_fastkit.backend.project_builder.config_generator import ( + AUTH_GUARD_METHOD, + DynamicConfigGenerator, + SettingField, + SettingGroup, + auth_guard_lines, + ensure_import, + format_imports, + inject_settings_fields, + inject_settings_validator, +) + +TEMPLATE_SETTINGS = """\ +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + model_config = SettingsConfigDict(env_file=".env", extra="ignore") + + PROJECT_NAME: str = "demo" + REDIS_URL: str = "redis://cache:6379/1" + + @property + def all_cors_origins(self) -> list[str]: + return [] + + +settings = Settings() +""" + +FULL = { + "project_name": "demo", + "database": {"type": "PostgreSQL"}, + "async_tasks": "Celery", + "caching": "Redis", + "monitoring": "OpenTelemetry", + "logging": "structured", + "utilities": ["CORS", "Rate-Limiting"], +} + + +def _fields(source: str) -> Dict[str, str]: + """``name -> default source`` of the ``Settings`` class fields.""" + tree = ast.parse(source) + (cls,) = [n for n in tree.body if isinstance(n, ast.ClassDef)] + return { + node.target.id: ast.unparse(node.value) + for node in cls.body + if isinstance(node, ast.AnnAssign) + and isinstance(node.target, ast.Name) + and node.value is not None + } + + +def _groups(**fields: str) -> List[SettingGroup]: + return [ + SettingGroup( + "Feature", + tuple(SettingField(name, "str", f'"{v}"') for name, v in fields.items()), + ) + ] + + +class TestInjectSettingsFields: + def test_missing_fields_follow_the_last_field(self) -> None: + updated = inject_settings_fields( + TEMPLATE_SETTINGS, _groups(LOG_LEVEL="INFO", OTHER="x") + ) + + fields = _fields(updated) + assert fields["LOG_LEVEL"] == "'INFO'" + assert list(fields)[-2:] == ["LOG_LEVEL", "OTHER"] + assert ' # Feature\n LOG_LEVEL: str = "INFO"\n' in updated + # a blank line still separates the fields from the property + assert ' OTHER: str = "x"\n\n @property' in updated + + def test_declared_fields_are_kept(self) -> None: + updated = inject_settings_fields( + TEMPLATE_SETTINGS, _groups(REDIS_URL="redis://localhost:6379/0") + ) + + assert updated == TEMPLATE_SETTINGS + assert _fields(updated)["REDIS_URL"] == "'redis://cache:6379/1'" + + def test_anchor_wins_over_the_last_field(self) -> None: + source = TEMPLATE_SETTINGS.replace( + ' PROJECT_NAME: str = "demo"\n', + ' PROJECT_NAME: str = "demo"\n # fastkit:settings\n', + ) + + updated = inject_settings_fields(source, _groups(LOG_LEVEL="INFO")) + + assert ( + ' # fastkit:settings\n # Feature\n LOG_LEVEL: str = "INFO"\n\n' + " REDIS_URL" in updated + ) + + @pytest.mark.parametrize( + "source", ["settings = {}\n", "class Settings(:\n", "x = 1\n"] + ) + def test_modules_without_a_settings_class_are_left_alone(self, source: str) -> None: + assert inject_settings_fields(source, _groups(A="b")) == source + + def test_any_base_settings_subclass_is_accepted(self) -> None: + source = TEMPLATE_SETTINGS.replace("class Settings(", "class AppSettings(") + + updated = inject_settings_fields(source, _groups(A="b")) + + assert "A" in _fields(updated) + + +class TestApplySettingsModule: + def test_template_module_gets_feature_fields_and_keeps_crlf( + self, tmp_path: Path + ) -> None: + # given + path = tmp_path / "src" / "core" / "config.py" + path.parent.mkdir(parents=True) + path.write_bytes(TEMPLATE_SETTINGS.replace("\n", "\r\n").encode()) + generator = DynamicConfigGenerator(FULL, str(tmp_path)) + + # when + planned = generator.planned_files() + written = generator.apply_settings_module() + + # then + assert "src/core/config.py" in planned + assert written == ["src/core/config.py"] + data = path.read_bytes() + assert data.count(b"\n") == data.count(b"\r\n") + fields = _fields(data.decode("utf-8")) + for name in ( + "API_V1_PREFIX", + "DATABASE_URL", + "DB_ECHO", + "CELERY_BROKER_URL", + "CELERY_RESULT_BACKEND", + "LOG_LEVEL", + "OTEL_SERVICE_NAME", + "OTEL_EXPORTER_OTLP_ENDPOINT", + "RATE_LIMIT_DEFAULT", + "RATE_LIMIT_STORAGE_URI", + ): + assert name in fields, name + assert fields["DB_ECHO"] == "False" + assert fields["REDIS_URL"] == "'redis://cache:6379/1'" # template wins + + def test_complete_module_is_a_no_op(self, tmp_path: Path) -> None: + path = tmp_path / "src" / "core" / "config.py" + path.parent.mkdir(parents=True) + source = TEMPLATE_SETTINGS.replace( + ' REDIS_URL: str = "redis://cache:6379/1"\n', + ' API_V1_PREFIX: str = "/api/v1"\n', + ) + path.write_text(source, encoding="utf-8") + generator = DynamicConfigGenerator({"project_name": "demo"}, str(tmp_path)) + + assert "src/core/config.py" not in generator.planned_files() + assert generator.apply_settings_module() == [] + assert path.read_text(encoding="utf-8") == source + + def test_missing_module_is_generated(self, tmp_path: Path) -> None: + generator = DynamicConfigGenerator(FULL, str(tmp_path)) + + written = generator.apply_settings_module() + + assert written == ["src/core/__init__.py", "src/core/config.py"] + source = (tmp_path / "src/core/config.py").read_text(encoding="utf-8") + fields = _fields(source) + assert fields["PROJECT_NAME"] == "'demo'" + assert fields["API_V1_PREFIX"] == "'/api/v1'" + assert fields["DATABASE_URL"].startswith("'postgresql+asyncpg://") + assert fields["OTEL_SERVICE_NAME"] == "'demo'" + assert 'env_file=".env"' in source + assert "def all_cors_origins(self) -> list[str]:" in source + assert "NoDecode" in source + # the templates' SECRET_KEY rule, with the same names + assert "def _check_secret_key(self)" in source + assert "KNOWN_EXAMPLE_SECRET_KEYS = frozenset(" in source + assert "MIN_SECRET_KEY_BYTES = 32" in source + assert '"SECRET_KEY" not in self.model_fields_set' in source + + +class TestGeneratedSettingsModule: + @pytest.mark.parametrize( + "overrides", + [ + {}, + FULL, + {"database": {"type": "MongoDB"}, "monitoring": "Loguru"}, + {"database": {"type": "Redis"}, "async_tasks": "Dramatiq"}, + ], + ) + def test_renders_valid_python(self, overrides: Dict[str, Any]) -> None: + config = {**overrides, "project_name": 'Quote "me"'} + + source = DynamicConfigGenerator(config, "/tmp/test").generate_settings_module() + + ast.parse(source) + assert _fields(source)["PROJECT_NAME"] == "'Quote \"me\"'" + + def test_mongodb_fields(self) -> None: + source = DynamicConfigGenerator( + {"project_name": "my-app", "database": {"type": "MongoDB"}}, "/tmp/test" + ).generate_settings_module() + + fields = _fields(source) + assert fields["MONGODB_URL"] == "'mongodb://localhost:27017'" + assert fields["MONGODB_DB_NAME"] == "'my_app'" + assert fields["MONGODB_TIMEOUT_MS"] == "5000" + + +class TestEnvExampleBlocks: + def test_every_feature_setting_is_documented_commented_out( + self, tmp_path: Path + ) -> None: + (tmp_path / ".env.example").write_text("SECRET_KEY=changethis\n", "utf-8") + generator = DynamicConfigGenerator(FULL, str(tmp_path)) + + generator.apply_env_example() + + example = (tmp_path / ".env.example").read_text(encoding="utf-8") + for name in ( + "BACKEND_CORS_ORIGINS", + "DATABASE_URL", + "DB_ECHO", + "REDIS_URL", + "LOG_LEVEL", + "OTEL_EXPORTER_OTLP_ENDPOINT", + "RATE_LIMIT_DEFAULT", + ): + assert re.search(rf"^# {name}=", example, re.M), name + assert "# DB_ECHO=false" in example + assert "# RATE_LIMIT_DEFAULT=100/minute" in example + # nothing is set for real: the settings defaults apply + assert re.findall(r"^[A-Z_]+=", example, re.M) == ["SECRET_KEY="] + + def test_template_entries_win(self, tmp_path: Path) -> None: + (tmp_path / ".env.example").write_text( + "REDIS_URL=redis://cache:6379/1\n", "utf-8" + ) + + DynamicConfigGenerator({"caching": "Redis"}, str(tmp_path)).apply_env_example() + + example = (tmp_path / ".env.example").read_text(encoding="utf-8") + assert example.count("REDIS_URL=") == 1 + + +# -------------------------------------------------------------------------- +# Helpers used by the auth settings (imports, validator injection) +# -------------------------------------------------------------------------- + + +class TestFormatImports: + def test_sorts_merges_and_orders_names_by_type(self) -> None: + block = format_imports( + [ + "from src.core.config import settings", + "from src.auth.models import User", + "from src.auth.models import ADMIN, helper", + ] + ) + + assert block == ( + "from src.auth.models import ADMIN, User, helper\n" + "from src.core.config import settings" + ) + + def test_wraps_long_statements_like_black(self) -> None: + names = ", ".join(f"Name{index}" for index in range(12)) + + block = format_imports([f"from src.app.domains.auth.models import {names}"]) + + lines = block.split("\n") + assert lines[0] == "from src.app.domains.auth.models import (" + assert lines[1] == " Name0," + assert lines[-1] == ")" + assert all(len(line) <= 88 for line in lines) + + +class TestEnsureImport: + def test_merges_into_an_existing_from_import(self) -> None: + source = "from pydantic import AnyUrl, BeforeValidator\n\nx = 1\n" + + updated = ensure_import(source, "from pydantic import model_validator") + + assert updated.startswith( + "from pydantic import AnyUrl, BeforeValidator, model_validator\n" + ) + + def test_inserts_a_missing_import(self) -> None: + source = "from pydantic import AnyUrl\n\nx = 1\n" + + updated = ensure_import(source, "import secrets") + + assert "import secrets" in updated + ast.parse(updated) + + @pytest.mark.parametrize( + ("source", "line"), + [ + ("import secrets\n", "import secrets"), + ("from typing import Literal\n", "from typing import Literal"), + ("def Literal(): ...\n", "from typing import Literal"), + ("class secrets: ...\n", "import secrets"), + ("secrets = None\n", "import secrets"), + ("def broken(:\n", "import secrets"), + ("x = 1\n", "not an import"), + ("x = 1\n", "x = 2"), + ], + ) + def test_leaves_the_module_alone_when_nothing_is_missing( + self, source: str, line: str + ) -> None: + assert ensure_import(source, line) == source + + def test_aliased_imports_are_not_merged(self) -> None: + source = "from pydantic import AnyUrl as Url\n\nx = 1\n" + + updated = ensure_import(source, "from pydantic import model_validator") + + assert "from pydantic import AnyUrl as Url" in updated + assert "from pydantic import model_validator" in updated + + +class TestInjectSettingsValidator: + def test_appends_the_guard_and_its_import(self) -> None: + updated = inject_settings_validator( + TEMPLATE_SETTINGS, AUTH_GUARD_METHOD, auth_guard_lines(demo_users=False) + ) + + tree = ast.parse(updated) + (cls,) = [n for n in tree.body if isinstance(n, ast.ClassDef)] + methods = [n.name for n in cls.body if isinstance(n, ast.FunctionDef)] + assert methods[-1] == AUTH_GUARD_METHOD + assert 'def _check_auth_settings_for_production(self) -> "Settings":' in updated + assert "from pydantic import model_validator" in updated + assert "ENABLE_DEMO_USERS" not in updated + assert updated.rstrip().endswith("settings = Settings()") + + @pytest.mark.parametrize( + "source", + ["x = 1\n", "def broken(:\n"], + ) + def test_no_settings_class_means_no_change(self, source: str) -> None: + assert ( + inject_settings_validator(source, AUTH_GUARD_METHOD, [" pass"]) == source + ) + + def test_existing_method_is_kept(self) -> None: + once = inject_settings_validator( + TEMPLATE_SETTINGS, AUTH_GUARD_METHOD, auth_guard_lines(demo_users=True) + ) + + assert ( + inject_settings_validator( + once, AUTH_GUARD_METHOD, auth_guard_lines(demo_users=True) + ) + == once + ) + + +class TestAuthSettingsGroup: + @pytest.mark.parametrize( + ("config", "expected"), + [ + ( + {"authentication": "JWT"}, + ["JWT_ALGORITHM", "ACCESS_TOKEN_EXPIRE_MINUTES"], + ), + ( + {"authentication": "FastAPI-Users", "database": {"type": "SQLite"}}, + ["ACCESS_TOKEN_EXPIRE_MINUTES"], + ), + ( + {"authentication": "Session-based", "utilities": ["Rate-Limiting"]}, + [ + "SESSION_MAX_AGE", + "SESSION_ABSOLUTE_MAX_AGE", + "SESSION_HTTPS_ONLY", + "ENABLE_DEMO_USERS", + "RATE_LIMIT_AUTH", + ], + ), + ( + {"authentication": "OAuth2", "utilities": ["Rate-Limiting"]}, + [ + "SESSION_MAX_AGE", + "SESSION_ABSOLUTE_MAX_AGE", + "SESSION_HTTPS_ONLY", + "GOOGLE_CLIENT_ID", + "GOOGLE_CLIENT_SECRET", + "GITHUB_CLIENT_ID", + "GITHUB_CLIENT_SECRET", + "OAUTH_REDIRECT_BASE_URL", + ], + ), + ({"authentication": "None"}, []), + ], + ) + def test_fields_per_option( + self, config: Dict[str, Any], expected: List[str] + ) -> None: + groups = DynamicConfigGenerator(config, "/tmp/test").settings_groups() + + auth = [g for g in groups if g.title == "Authentication"] + names = [f.name for f in auth[0].fields] if auth else [] + assert names == expected + + def test_generated_module_without_auth_has_no_guard(self) -> None: + source = DynamicConfigGenerator({}, "/tmp/test").generate_settings_module() + + assert AUTH_GUARD_METHOD not in source + + +class TestIsortAlembicHint: + ALEMBIC = {"database": {"type": "SQLite"}, "migrations": "Alembic"} + + def _write(self, tmp_path: Path, text: str) -> Path: + pyproject = tmp_path / "pyproject.toml" + pyproject.write_bytes(text.encode("utf-8")) + return pyproject + + def test_marks_alembic_third_party_once(self, tmp_path: Path) -> None: + pyproject = self._write( + tmp_path, + '[project]\r\nname = "p"\r\n\r\n[tool.isort]\r\nprofile = "black"\r\n', + ) + generator = DynamicConfigGenerator(self.ALEMBIC, str(tmp_path)) + + assert "pyproject.toml" in generator.planned_files() + assert generator.apply_isort_configuration() == "pyproject.toml" + assert generator.apply_isort_configuration() is None + + text = pyproject.read_bytes().decode("utf-8") + assert '[tool.isort]\r\nknown_third_party = ["alembic"]\r\nprofile' in text + + @pytest.mark.parametrize( + ("config", "text"), + [ + ({"database": {"type": "SQLite"}}, '[tool.isort]\nprofile = "black"\n'), + (ALEMBIC, '[project]\nname = "p"\n'), + (ALEMBIC, '[tool.isort]\nknown_third_party = ["x"]\n'), + (ALEMBIC, "[tool.isort\nbroken"), + ], + ) + def test_leaves_other_projects_alone( + self, tmp_path: Path, config: Dict[str, Any], text: str + ) -> None: + pyproject = self._write(tmp_path, text) + + assert ( + DynamicConfigGenerator(config, str(tmp_path)).apply_isort_configuration() + is None + ) + assert pyproject.read_text(encoding="utf-8") == text + + def test_no_pyproject(self, tmp_path: Path) -> None: + generator = DynamicConfigGenerator(self.ALEMBIC, str(tmp_path)) + + assert generator.apply_isort_configuration() is None diff --git a/tests/test_backends/test_project_metadata.py b/tests/test_backends/test_project_metadata.py index 17cc82d..82c343b 100644 --- a/tests/test_backends/test_project_metadata.py +++ b/tests/test_backends/test_project_metadata.py @@ -353,8 +353,8 @@ def test_domain_starter_main_py_gets_the_right_router_import( # then router_content = Path(layout["api_router_file"]).read_text() - assert "from .routes import user" in router_content - assert 'api_router.include_router(user.router, prefix="/user"' in router_content + assert "from .routes.user import router as user_router" in router_content + assert "api_router.include_router(user_router)" in router_content main_content = Path(layout["main"]).read_text() # src/main.py was never assumed, and the existing import is untouched diff --git a/tests/test_backends/test_route_generators.py b/tests/test_backends/test_route_generators.py index 23c0b57..7385154 100644 --- a/tests/test_backends/test_route_generators.py +++ b/tests/test_backends/test_route_generators.py @@ -2,6 +2,7 @@ import importlib.util import json +import shutil import subprocess import sys from pathlib import Path @@ -137,6 +138,9 @@ def snapshot(root: Path) -> dict[str, bytes]: } +SHARED_CORE = ("core/pagination.py", "core/responses.py") + + def test_shipped_items_domain_is_preserved(tmp_path: Path) -> None: """Keep the starter items domain unchanged.""" template = Path(settings.FASTKIT_TEMPLATE_ROOT) / "fastapi-domain-starter" @@ -147,24 +151,20 @@ def test_shipped_items_domain_is_preserved(tmp_path: Path) -> None: ) before = snapshot(tmp_path) add_new_route(str(tmp_path), "items") - assert snapshot(tmp_path) == before + after = snapshot(tmp_path) + # Only the shared core modules may be added (when the template predates + # them); every shipped file stays byte-identical. + added = set(after) - set(before) + assert added <= {str(Path("src/app") / name) for name in SHARED_CORE} + assert {name: after[name] for name in before} == before add_new_route(str(tmp_path), "users") for name, content in before.items(): if name != str(Path("src/app/api/router.py")): assert (tmp_path / name).read_bytes() == content router = (tmp_path / "src/app/api/router.py").read_text(encoding="utf-8") - assert ( - router.count( - 'api_router.include_router(items_router.router, prefix="/items", tags=["items"])' - ) - == 1 - ) - assert ( - router.count( - 'api_router.include_router(users_router.router, prefix="/users", tags=["users"])' - ) - == 1 - ) + assert router.count("api_router.include_router(items_router.router") == 1 + assert router.count("api_router.include_router(users_router.router)") == 1 + assert (tmp_path / "tests/test_users.py").exists() if all(importlib.util.find_spec(name) for name in ("fastapi", "httpx")): result = subprocess.run( @@ -179,17 +179,19 @@ def test_shipped_items_domain_is_preserved(tmp_path: Path) -> None: app.include_router(api_router, prefix="/api/v1") client = TestClient(app) assert client.get("/api/v1/items").status_code == 200 -created = client.post("/api/v1/items", json={"name": "Mug", "price": 9.5}) +created = client.post("/api/v1/users", json={"name": "Ann"}) assert created.status_code == 201 -assert client.get("/api/v1/items/" + str(created.json()["id"])).status_code == 200 +assert client.get(created.headers["location"]).status_code == 200 paths = app.openapi()["paths"] -assert paths["/api/v1/items"]["get"]["tags"] == ["items"] -assert "/api/v1/items/items" not in paths +assert paths["/api/v1/users"]["get"]["tags"] == ["users"] +assert "/api/v1/users/users" not in paths """, ], cwd=tmp_path, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=30, ) assert result.returncode == 0, result.stdout + result.stderr @@ -197,7 +199,7 @@ def test_shipped_items_domain_is_preserved(tmp_path: Path) -> None: @pytest.mark.parametrize("nested", [False, True]) @pytest.mark.parametrize("layout", ["classic-layer", "domain"]) -def test_generation_preserves_edits_and_restores_missing_files( +def test_generation_preserves_edits_and_refuses_partial_routes( tmp_path: Path, nested: bool, layout: str ) -> None: package = make_project(tmp_path, nested=nested) @@ -215,11 +217,16 @@ def test_generation_preserves_edits_and_restores_missing_files( assert not (package / "domains").exists() edited.write_text("# User-edited implementation\n", encoding="utf-8") before = snapshot(tmp_path) + # A re-run that would change nothing is a no-op. add_new_route(str(tmp_path), "users", layout=layout) assert snapshot(tmp_path) == before + # A partly present route is refused (nothing written), never re-wired + # over the files that remain. missing.unlink() - add_new_route(str(tmp_path), "users", layout=layout) - assert snapshot(tmp_path) == before + partial = snapshot(tmp_path) + with pytest.raises(BackendExceptions, match="already exists"): + add_new_route(str(tmp_path), "users", layout=layout) + assert snapshot(tmp_path) == partial assert (tmp_path / "pyproject.toml").read_bytes() == metadata @@ -250,9 +257,15 @@ def test_partial_classic_module_allows_domain(tmp_path: Path, directory: str) -> @pytest.mark.parametrize( - "name, class_name", [("checkups", "Checkups"), ("health_checks", "HealthChecks")] + "name, class_name, snake", + [ + ("checkups", "Checkup", "checkup"), + ("health_checks", "HealthCheck", "health_check"), + ], ) -def test_domain_uses_subject_names(tmp_path: Path, name: str, class_name: str) -> None: +def test_domain_uses_singular_entity_names( + tmp_path: Path, name: str, class_name: str, snake: str +) -> None: package = make_project(tmp_path) add_new_route(str(tmp_path), name) assert f"class {class_name}:" in (package / f"domains/{name}/models.py").read_text() @@ -260,32 +273,47 @@ def test_domain_uses_subject_names(tmp_path: Path, name: str, class_name: str) - f"class {class_name}Create" in (package / f"domains/{name}/schemas.py").read_text() ) - assert ( - f"def get_{name}_service" in (package / f"domains/{name}/router.py").read_text() - ) + router = (package / f"domains/{name}/router.py").read_text() + assert f"def get_{snake}_service" in router + assert f"def list_{name}(" in router + assert f'"/{{{snake}_id}}"' in router + + +def test_entity_option_overrides_the_derived_name(tmp_path: Path) -> None: + package = make_project(tmp_path, preset="minimal") + add_new_route(str(tmp_path), "people", entity="Member") + assert "class Member:" in (package / "crud/people.py").read_text() + assert "class MemberUpdate" in (package / "schemas/people.py").read_text() + assert "def get_member(" in (package / "api/routes/people.py").read_text() +@pytest.mark.parametrize("layout", ["classic-layer", "domain"]) @pytest.mark.parametrize("nested", [False, True]) @pytest.mark.parametrize("anchors", [False, True]) @pytest.mark.parametrize("aggregator", [False, True]) -def test_generated_domain_crud( - tmp_path: Path, nested: bool, anchors: bool, aggregator: bool +def test_generated_crud( + tmp_path: Path, layout: str, nested: bool, anchors: bool, aggregator: bool ) -> None: """Run CRUD checks in a separate process to avoid src import collisions.""" if any(importlib.util.find_spec(name) is None for name in ("fastapi", "httpx")): pytest.skip("Generated application runtime requires fastapi and httpx") make_project(tmp_path, nested=nested, aggregator=aggregator, anchors=anchors) - add_new_route(str(tmp_path), "users") - add_new_route(str(tmp_path), "groups") - add_new_route(str(tmp_path), "users") + add_new_route(str(tmp_path), "users", layout=layout) + add_new_route(str(tmp_path), "groups", layout=layout) + add_new_route(str(tmp_path), "users", layout=layout) prefix = "src.app" if nested else "src" api_prefix = "/api/v1" if aggregator else "" - script = f"PACKAGE = {prefix!r}\nAPI = {api_prefix!r}\n" + CRUD_CHECK + script = ( + f"PACKAGE = {prefix!r}\nAPI = {api_prefix!r}\nLAYOUT = {layout!r}\n" + + CRUD_CHECK + ) result = subprocess.run( [sys.executable, "-c", script], cwd=tmp_path, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=30, ) assert result.returncode == 0, result.stdout + result.stderr @@ -297,59 +325,89 @@ def test_generated_domain_crud( from fastapi.testclient import TestClient app = importlib.import_module(PACKAGE + ".main").app -repository = importlib.import_module(PACKAGE + ".domains.users.repository") -service = importlib.import_module(PACKAGE + ".domains.users.service") -router = importlib.import_module(PACKAGE + ".domains.users.router") client = TestClient(app) users = API + "/users" groups = API + "/groups" -assert client.get(users).json() == [] + + +def page(items, total, limit=20, offset=0): + return {"items": items, "total": total, "limit": limit, "offset": offset} + + +assert client.get(users).json() == page([], 0) created = client.post(users, json={"name": "Alice"}) assert created.status_code == 201 -assert created.json() == {"id": 1, "name": "Alice"} -assert client.get(users + "/1").json() == created.json() -assert client.get(users).json() == [created.json()] +assert created.json() == {"id": 1, "name": "Alice", "description": None} +assert created.headers["location"] == "http://testserver" + users + "/1" +assert client.get(created.headers["location"]).json() == created.json() +assert client.get(users).json() == page([created.json()], 1) for payload in ({}, {"name": ""}, {"name": "a" * 121}, {"name": None}): assert client.post(users, json=payload).status_code == 422 assert client.put(users + "/1", json=payload).status_code == 422 +assert client.patch(users + "/1", json={"name": None}).status_code == 422 +assert client.patch(users + "/1", json={"name": ""}).status_code == 422 assert client.post(users, json={"name": "a" * 120}).status_code == 201 assert client.post(users, json={"name": "a"}).json()["id"] == 3 +listing = client.get(users, params={"limit": 2, "offset": 1}).json() +assert [user["id"] for user in listing["items"]] == [2, 3] +assert (listing["total"], listing["limit"], listing["offset"]) == (3, 2, 1) +for params in ({"limit": 0}, {"limit": 101}, {"offset": -1}): + assert client.get(users, params=params).status_code == 422 +assert client.get(users, params={"offset": 10}).json() == page([], 3, offset=10) +patched = client.patch(users + "/1", json={"description": "x"}) +assert patched.json() == {"id": 1, "name": "Alice", "description": "x"} updated = client.put(users + "/1", json={"name": "Bob"}) assert updated.status_code == 200 -assert updated.json() == {"id": 1, "name": "Bob"} -assert client.get(users + "/1").json() == updated.json() -assert client.get(groups).json() == [] -assert client.post(groups, json={"name": "Team"}).json() == {"id": 1, "name": "Team"} +assert updated.json() == {"id": 1, "name": "Bob", "description": None} +assert client.get(groups).json() == page([], 0) +assert client.post(groups, json={"name": "Team"}).json()["id"] == 1 deleted = client.delete(users + "/1") assert deleted.status_code == 204 and deleted.content == b"" -assert client.get(users + "/1").status_code == 404 -assert client.get(users + "/999").status_code == 404 -assert client.put(users + "/999", json={"name": "Missing"}).status_code == 404 -assert client.delete(users + "/999").status_code == 404 -assert client.delete(users + "/1").status_code == 404 +for method in ("GET", "PUT", "PATCH", "DELETE"): + missing = client.request(method, users + "/1", json={"name": "Missing"}) + assert missing.status_code == 404 + assert missing.json() == {"detail": "User not found"} assert client.get(groups + "/1").status_code == 200 assert client.post(users, json={"name": "Next"}).json()["id"] == 4 -assert client.patch(users + "/2", json={"name": "No PATCH"}).status_code == 405 +assert client.get(users, follow_redirects=False).status_code == 200 schema = client.get("/openapi.json").json() assert set(schema["paths"][users]) == {"get", "post"} -assert set(schema["paths"][users + "/{entity_id}"]) == {"get", "put", "delete"} +item = schema["paths"][users + "/{user_id}"] +assert set(item) == {"get", "put", "patch", "delete"} +assert "404" in item["get"]["responses"] +assert schema["paths"][users]["post"]["responses"].keys() >= {"201", "422"} operations = [op["operationId"] for path in schema["paths"].values() for op in path.values()] assert len(set(operations)) == len(operations) assert schema["paths"][users]["get"]["tags"] == ["users"] -isolated = repository.UsersRepository() -assert isolated.list_all() == [] -assert isolated.add(name="Isolated").id == 1 -assert repository.UsersRepository().list_all() == [] -app.dependency_overrides[router.get_users_service] = lambda: service.UsersService(isolated) -assert client.get(users).json() == [{"id": 1, "name": "Isolated"}] +if LAYOUT == "domain": + repository = importlib.import_module(PACKAGE + ".domains.users.repository") + service = importlib.import_module(PACKAGE + ".domains.users.service") + router = importlib.import_module(PACKAGE + ".domains.users.router") + Repository = repository.UserRepository + dependency = router.get_user_service + factory = lambda store: (lambda: service.UserService(store)) +else: + crud = importlib.import_module(PACKAGE + ".crud.users") + Repository = crud.UserRepository + dependency = crud.get_user_repository + factory = lambda store: (lambda: store) + +isolated = Repository() +assert isolated.list_page(0, 20) == ([], 0) +assert isolated.add({"name": "Isolated"}).id == 1 +assert Repository().list_page(0, 20) == ([], 0) +app.dependency_overrides[dependency] = factory(isolated) +assert client.get(users).json()["items"] == [ + {"id": 1, "name": "Isolated", "description": None} +] app.dependency_overrides.clear() -assert len(client.get(users).json()) == 3 -parallel = repository.UsersRepository() +assert client.get(users).json()["total"] == 3 +parallel = Repository() with ThreadPoolExecutor(max_workers=8) as pool: - entities = list(pool.map(lambda i: parallel.add(name=str(i)), range(100))) + entities = list(pool.map(lambda i: parallel.add({"name": str(i)}), range(100))) assert {entity.id for entity in entities} == set(range(1, 101)) -assert len(parallel.list_all()) == 100 +assert parallel.list_page(0, 200)[1] == 100 """ @@ -435,7 +493,7 @@ def test_router_alias_collisions(tmp_path: Path, domain_first: bool) -> None: [ sys.executable, "-c", - "from src.app.main import app; paths = app.openapi()['paths']; assert '/api/v1/users' in paths; assert '/api/v1/users_router/' in paths", + "from src.app.main import app; paths = app.openapi()['paths']; assert '/api/v1/users' in paths; assert '/api/v1/users_router' in paths", ], cwd=tmp_path, capture_output=True, @@ -452,30 +510,21 @@ def test_existing_domain_registration_is_preserved( package = make_project(tmp_path) add_new_route(str(tmp_path), "users") aggregator = package / "api/router.py" - if legacy: - router = package / "domains/users/router.py" - router.write_text( - router.read_text().replace( - "router = APIRouter()", - 'router = APIRouter(prefix="/users", tags=["users"])', - ) - ) - aggregator.write_text( - aggregator.read_text().replace( - 'include_router(users_router.router, prefix="/users", tags=["users"])', - "include_router(users_router.router)", - ) - ) - else: - aggregator.write_text( - aggregator.read_text().replace( - 'prefix="/users", tags=["users"]', - 'prefix="/custom-users", tags=["custom"]', - ) + # A registration fastkit < 1.6 wrote, or one the user customised. + options = 'prefix="/users", tags=["users"]' if legacy else 'prefix="/custom"' + aggregator.write_text( + aggregator.read_text().replace( + "include_router(users_router.router)", + f"include_router(users_router.router, {options})", ) + ) before = snapshot(tmp_path) - add_new_route(str(tmp_path), "users") + with patch("fastapi_fastkit.backend.route_wiring.print_info") as info: + add_new_route(str(tmp_path), "users") assert snapshot(tmp_path) == before + assert any( + "Keeping existing router registration" in str(c) for c in info.call_args_list + ) @pytest.mark.parametrize( @@ -541,23 +590,23 @@ def test_generated_domains_reset_between_tests(tmp_path: Path) -> None: pytest.skip("Starter runtime dependencies are required") project = scaffold_starter(tmp_path) add_new_route(str(project), "users") - test_file = project / "tests/test_generated_users.py" + test_file = project / "tests/test_generated_users_reset.py" test_file.write_text( """ from src.app.domains.users import models, repository, router, schemas, service def test_first(client): - assert client.get('/api/v1/users').json() == [] + assert client.get('/api/v1/users').json()['items'] == [] assert client.post('/api/v1/users', json={'name': 'first'}).json()['id'] == 1 - isolated = repository.UsersRepository() - isolated.add(name='isolated') + isolated = repository.UserRepository() + isolated.add({'name': 'isolated'}) isolated.reset() - assert isolated.list_all() == [] - assert isolated.add(name='fresh').id == 1 - assert len(client.get('/api/v1/users').json()) == 1 + assert isolated.list_page(0, 20) == ([], 0) + assert isolated.add({'name': 'fresh'}).id == 1 + assert client.get('/api/v1/users').json()['total'] == 1 def test_second(client): - assert client.get('/api/v1/users').json() == [] + assert client.get('/api/v1/users').json()['items'] == [] assert client.post('/api/v1/users', json={'name': 'second'}).json()['id'] == 1 """, encoding="utf-8", @@ -567,6 +616,8 @@ def test_second(client): cwd=project, capture_output=True, text=True, + encoding="utf-8", + errors="replace", timeout=60, ) assert result.returncode == 0, result.stdout + result.stderr @@ -610,17 +661,37 @@ def test_missing_domain_templates( assert snapshot(tmp_path) == before -def test_domain_template_copy_failure(tmp_path: Path) -> None: - make_project(tmp_path) - with patch( - "fastapi_fastkit.backend.route_generators.copy_and_convert_template_file", - return_value=False, - ): - with pytest.raises(BackendExceptions, match="Failed to create domain file"): - add_new_route(str(tmp_path), "users") - - -@pytest.mark.parametrize("name", ["_", "none"]) +@pytest.mark.parametrize( + "layout, missing, message", + [ + ("domain", "domain/router.py-tpl", "Missing domain template"), + ("classic-layer", "crud/new_route.py-tpl", "Missing route template"), + ("domain", "core/pagination.py-tpl", "Missing route template"), + ("classic-layer", "tests/test_new_route.py-tpl", "Missing route template"), + ], +) +def test_missing_module_template_writes_nothing( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + layout: str, + missing: str, + message: str, +) -> None: + project = tmp_path / "project" + make_project(project) + (project / "tests").mkdir() + (project / "src/app/core").mkdir() + root = tmp_path / "templates" + shutil.copytree(Path(settings.FASTKIT_TEMPLATE_ROOT) / "modules", root / "modules") + (root / "modules" / missing).unlink() + monkeypatch.setattr(settings, "FASTKIT_TEMPLATE_ROOT", str(root)) + before = snapshot(project) + with pytest.raises(BackendExceptions, match=message): + add_new_route(str(project), "users", layout=layout) + assert snapshot(project) == before + + +@pytest.mark.parametrize("name", ["none", "v2", "data"]) def test_unusual_domain_names_compile(tmp_path: Path, name: str) -> None: package = make_project(tmp_path) add_new_route(str(tmp_path), name) @@ -631,3 +702,78 @@ def test_unusual_domain_names_compile(tmp_path: Path, name: str) -> None: def test_invalid_generator_layout() -> None: with pytest.raises(BackendExceptions, match="Unknown route layout"): get_route_generator("invalid") + + +def test_envelope_project_gets_enveloped_routes_and_tests(tmp_path: Path) -> None: + """A route added to fastapi-custom-response answers with its envelope.""" + template = Path(settings.FASTKIT_TEMPLATE_ROOT) / "fastapi-custom-response" + copy_and_convert_template(str(template), str(tmp_path)) + write_fastkit_metadata( + str(tmp_path), + {"template": "fastapi-custom-response", "app_module": "src.main:app"}, + ) + + add_new_route(str(tmp_path), "orders") + + route = (tmp_path / "src/api/routes/orders.py").read_text(encoding="utf-8") + assert "from src.helper.exceptions import error_responses" in route + assert "from src.helper.responses import success_response" in route + assert "from src.schemas.base import ResponseSchema" in route + assert "responses=error_responses(422, 500)," in route + assert "-> ResponseSchema[Page[OrderRead]]:" in route + assert "return success_response(request, created, status_code=201)" in route + # The project's own error_responses() is used, not a second helper. + assert not (tmp_path / "src/core/responses.py").exists() + tests = (tmp_path / "tests/test_orders.py").read_text(encoding="utf-8") + assert 'return response.json()["message"]' in tests + assert '"detail"' not in tests + for source in (route, tests): + compile(source, "generated", "exec") + + +def test_plain_project_reads_detail_in_generated_tests(tmp_path: Path) -> None: + template = Path(settings.FASTKIT_TEMPLATE_ROOT) / "fastapi-default" + copy_and_convert_template(str(template), str(tmp_path)) + write_fastkit_metadata( + str(tmp_path), {"template": "fastapi-default", "app_module": "src.main:app"} + ) + + add_new_route(str(tmp_path), "orders") + + route = (tmp_path / "src/api/routes/orders.py").read_text(encoding="utf-8") + tests = (tmp_path / "tests/test_orders.py").read_text(encoding="utf-8") + assert "from src.core.responses import error_responses" in route + assert "success_response" not in route + assert " return response.json()\n" in tests + assert 'return response.json()["detail"]' in tests + + +def test_incomplete_envelope_modules_fall_back_to_plain_routes(tmp_path: Path) -> None: + package = make_project(tmp_path, nested=False, preset="classic-layered") + helper = package / "helper" + helper.mkdir() + (helper / "exceptions.py").write_text( + "def error_responses(*codes): ...\n", encoding="utf-8" + ) + + add_new_route(str(tmp_path), "orders") + + route = (package / "api/routes/orders.py").read_text(encoding="utf-8") + assert "from src.core.responses import error_responses" in route + + +def test_envelope_helpers_without_their_definitions_are_ignored( + tmp_path: Path, +) -> None: + package = make_project(tmp_path, nested=False, preset="classic-layered") + helper = package / "helper" + helper.mkdir() + (helper / "exceptions.py").write_text( + "def error_responses(*codes): ...\n", encoding="utf-8" + ) + (helper / "responses.py").write_text("# no success_response here\n", "utf-8") + + add_new_route(str(tmp_path), "orders") + + route = (package / "api/routes/orders.py").read_text(encoding="utf-8") + assert "success_response" not in route diff --git a/tests/test_backends/test_route_hardening.py b/tests/test_backends/test_route_hardening.py new file mode 100644 index 0000000..0694e41 --- /dev/null +++ b/tests/test_backends/test_route_hardening.py @@ -0,0 +1,678 @@ +# -------------------------------------------------------------------------- +# Regression tests for the ``fastkit addroute`` review findings: routes +# whose files already exist, unusable names, a hostile ``app_module``, +# commented-out registrations, partial writes, plain CLI errors, help +# formatting and ``startdemo --yes``. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +import os +from pathlib import Path +from typing import List +from unittest.mock import patch + +import pytest +from click.testing import CliRunner + +from fastapi_fastkit.backend import route_plan as route_plan_module +from fastapi_fastkit.backend.main import ( + _plan_main_app, + add_new_route, + code_without_comments, + insert_statement_line, + recorded_app_module_path, + resolve_project_layout, + statement_present, + valid_app_module, +) +from fastapi_fastkit.backend.route_generators import ( + plan_new_route, + project_top_level_names, + resolve_route_names, + validate_route_name, +) +from fastapi_fastkit.backend.route_plan import RoutePlan +from fastapi_fastkit.backend.route_wiring import plan_router_registration +from fastapi_fastkit.cli import fastkit_cli +from fastapi_fastkit.core.exceptions import BackendExceptions +from tests.test_backends.test_route_generators import make_project, snapshot + + +def _flat(text: str) -> str: + return " ".join( + "".join(" " if 0x2500 <= ord(c) <= 0x257F else c for c in text).split() + ) + + +# ---------------------------------------------------------------------- +# 5. Names +# ---------------------------------------------------------------------- + + +class TestNames: + @pytest.mark.parametrize( + "name", + [ + "café", + "Orders", + "orderItems", + "__init__", + "_private", + "__orders__", + "1orders", + "bad-name", + "orders\n", + "", + ], + ) + def test_invalid_route_names(self, name: str) -> None: + with pytest.raises(BackendExceptions, match="not a valid Python identifier"): + validate_route_name(name) + + @pytest.mark.parametrize("name", ["class", "import", "match", "case", "type"]) + def test_keywords_and_soft_keywords(self, name: str) -> None: + with pytest.raises(BackendExceptions, match="keyword"): + validate_route_name(name) + + @pytest.mark.parametrize("name", ["orders", "order_items", "v2", "a1_b2_"]) + def test_valid_route_names(self, name: str) -> None: + validate_route_name(name) + + @pytest.mark.parametrize("entity", ["Order\n", "Ördér", "Match", "None"]) + def test_invalid_entities(self, entity: str) -> None: + with pytest.raises(BackendExceptions): + resolve_route_names("orders", entity) + + def test_derived_identifier_must_not_be_a_soft_keyword(self) -> None: + # ``matches`` -> ``Match`` -> ``match``: refused, with a pointer to + # --entity, which fixes it. + with pytest.raises(BackendExceptions, match="--entity"): + resolve_route_names("matches") + assert resolve_route_names("matches", "Fixture").snake == "fixture" + + def test_cafe_project_is_untouched(self, tmp_path: Path) -> None: + make_project(tmp_path, preset="minimal") + before = snapshot(tmp_path) + + with pytest.raises(BackendExceptions): + add_new_route(str(tmp_path), "café") + + assert snapshot(tmp_path) == before + + +# ---------------------------------------------------------------------- +# 4. Existing routes and name collisions +# ---------------------------------------------------------------------- + + +class TestExistingRoutes: + @pytest.mark.parametrize( + "existing", + ["api/routes/orders.py", "crud/orders.py", "schemas/orders.py"], + ) + def test_classic_route_with_an_existing_module_is_refused( + self, tmp_path: Path, existing: str + ) -> None: + package = make_project(tmp_path, preset="minimal") + target = package / existing + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("# mine\n", encoding="utf-8") + before = snapshot(tmp_path) + + with pytest.raises(BackendExceptions, match="already exists") as info: + plan_new_route(str(tmp_path), "orders") + + assert existing in str(info.value) + assert snapshot(tmp_path) == before + + def test_existing_module_is_found_case_insensitively(self, tmp_path: Path) -> None: + package = make_project(tmp_path, preset="minimal") + routes = package / "api" / "routes" + routes.mkdir(parents=True) + (routes / "Orders.py").write_text("# left by an old run\n", encoding="utf-8") + + with pytest.raises(BackendExceptions, match="Orders.py"): + plan_new_route(str(tmp_path), "orders") + + def test_existing_domain_is_refused(self, tmp_path: Path) -> None: + package = make_project(tmp_path) + (package / "domains" / "auth").mkdir(parents=True) + (package / "domains" / "auth" / "router.py").write_text( + "router = None\n", encoding="utf-8" + ) + + with pytest.raises(BackendExceptions, match="domains/auth"): + plan_new_route(str(tmp_path), "auth") + + @pytest.mark.parametrize("layout", ["classic-layer", "domain"]) + def test_existing_test_module_is_refused(self, tmp_path: Path, layout: str) -> None: + make_project(tmp_path) + (tmp_path / "tests").mkdir() + (tmp_path / "tests" / "test_orders.py").write_text( + "def test_x():\n pass\n", encoding="utf-8" + ) + + with pytest.raises(BackendExceptions, match="tests/test_orders.py"): + plan_new_route(str(tmp_path), "orders", layout=layout) + + @pytest.mark.parametrize("layout", ["classic-layer", "domain"]) + def test_complete_rerun_is_a_no_op(self, tmp_path: Path, layout: str) -> None: + make_project(tmp_path) + (tmp_path / "tests").mkdir() + add_new_route(str(tmp_path), "orders", layout=layout) + before = snapshot(tmp_path) + + plan = plan_new_route(str(tmp_path), "orders", layout=layout) + + assert plan.is_empty + add_new_route(str(tmp_path), "orders", layout=layout) + assert snapshot(tmp_path) == before + + @pytest.mark.parametrize("name", ["main", "core", "api", "domains", "billing"]) + def test_names_of_project_modules_are_refused( + self, tmp_path: Path, name: str + ) -> None: + package = make_project(tmp_path) + (package / "core").mkdir() + (package / "billing.py").write_text("", encoding="utf-8") + (package / "domains").mkdir() + + with pytest.raises(BackendExceptions, match="collides with"): + plan_new_route(str(tmp_path), name) + + def test_top_level_names_come_from_the_tree(self, tmp_path: Path) -> None: + package = make_project(tmp_path) + (package / "health").mkdir() + (package / "Auth.py").write_text("", encoding="utf-8") + (package / "_private.py").write_text("", encoding="utf-8") + (package / "notes.txt").write_text("", encoding="utf-8") + + names = set(project_top_level_names(str(package))) + + assert names == {"main", "api", "health", "auth"} + + def test_route_named_like_an_imported_module_is_refused( + self, tmp_path: Path + ) -> None: + make_project(tmp_path) + + with pytest.raises(BackendExceptions, match="shadow"): + plan_new_route(str(tmp_path), "typing") + + @pytest.mark.parametrize("layout", ["classic-layer", "domain"]) + def test_entity_shadowing_an_import_is_refused( + self, tmp_path: Path, layout: str + ) -> None: + # ``Any`` is imported from typing next to the entity class. + make_project(tmp_path) + + with pytest.raises(BackendExceptions, match="defined twice"): + plan_new_route(str(tmp_path), "things", layout=layout, entity="Any") + + +# ---------------------------------------------------------------------- +# 6. A hostile app_module never redirects writes +# ---------------------------------------------------------------------- + + +class TestAppModule: + def _set_app_module(self, root: Path, value: str) -> None: + pyproject = root / "pyproject.toml" + text = pyproject.read_text(encoding="utf-8") + start = text.index("app_module = ") + end = text.index("\n", start) + pyproject.write_text( + text[:start] + f'app_module = "{value}"' + text[end:], encoding="utf-8" + ) + + def test_leading_dot_does_not_escape(self, tmp_path: Path) -> None: + project = tmp_path / "p" + project.mkdir() + make_project(project, nested=False, preset="minimal") + outside = tmp_path / "outside" + outside.mkdir() + (outside / "main.py").write_text( + "from fastapi import FastAPI\napp = FastAPI()\n", encoding="utf-8" + ) + dotted = ".".join(part for part in outside.parts if part not in ("/", "\\")) + self._set_app_module(project, f".{dotted}.main:app") + + layout = resolve_project_layout(str(project)) + plan_new_route(str(project), "orders").apply() + + assert os.path.commonpath( + [os.path.realpath(layout["main"]), os.path.realpath(project)] + ) == os.path.realpath(project) + assert sorted(p.name for p in outside.iterdir()) == ["main.py"] + + @pytest.mark.parametrize( + "value", [".src.main:app", "src..main", "src/main:app", "src.main:a b"] + ) + def test_invalid_values_are_ignored(self, tmp_path: Path, value: str) -> None: + make_project(tmp_path, nested=False) + + assert not valid_app_module(value) + assert recorded_app_module_path(str(tmp_path), value) == "" + + def test_symlink_out_of_the_project_is_ignored(self, tmp_path: Path) -> None: + project = tmp_path / "p" + project.mkdir() + make_project(project, nested=False) + outside = tmp_path / "outside" + outside.mkdir() + (outside / "app.py").write_text("app = None\n", encoding="utf-8") + try: + os.symlink(outside / "app.py", project / "src" / "entry.py") + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") + + assert recorded_app_module_path(str(project), "src.entry:app") == "" + assert recorded_app_module_path(str(project), "src.main:app").endswith( + "main.py" + ) + + def test_hostile_app_module_never_reaches_the_test_import( + self, tmp_path: Path + ) -> None: + make_project(tmp_path) + (tmp_path / "tests").mkdir() + self._set_app_module(tmp_path, "os; import evil:app") + + plan = plan_new_route(str(tmp_path), "orders") + test_file = next(p for p in plan.created if p.path.endswith("test_orders.py")) + + assert "evil" not in test_file.content + ast.parse(test_file.content) + + def test_plan_refuses_paths_outside_the_project(self, tmp_path: Path) -> None: + project = tmp_path / "p" + project.mkdir() + plan = RoutePlan(str(project)) + + with pytest.raises(BackendExceptions, match="outside the project"): + plan.write(str(tmp_path / "escape.py"), "x") + with pytest.raises(BackendExceptions, match="outside the project"): + plan.create(str(project / ".." / "escape.py"), "x") + + def test_plan_refuses_a_symlinked_directory_leading_out( + self, tmp_path: Path + ) -> None: + project = tmp_path / "p" + project.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + try: + os.symlink(outside, project / "linked") + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") + + with pytest.raises(BackendExceptions, match="outside the project"): + RoutePlan(str(project)).create(str(project / "linked" / "x.py"), "x") + + +# ---------------------------------------------------------------------- +# 9. A commented-out registration does not count +# ---------------------------------------------------------------------- + + +class TestRegistrationDetection: + @pytest.mark.parametrize( + "content,present", + [ + ("api_router.include_router(orders_router)\n", True), + ("api_router.include_router( orders_router ) # ok\n", True), + ("# api_router.include_router(orders_router)\n", False), + ('NOTE = "api_router.include_router(orders_router)"\n', False), + ("if True:\n api_router.include_router(orders_router)\n", True), + ("broken (\n# api_router.include_router(orders_router)\n", False), + ("broken (\napi_router.include_router(orders_router)\n", True), + ], + ) + def test_statement_present(self, content: str, present: bool) -> None: + statement = "api_router.include_router(orders_router)" + + assert statement_present(content, statement) is present + + def test_commented_registration_gets_a_real_one(self) -> None: + content = ( + "from fastapi import APIRouter\n\napi_router = APIRouter()\n" + "# api_router.include_router(orders_router)\n# fastkit:routes\n" + ) + + updated = insert_statement_line( + content, "api_router.include_router(orders_router)" + ) + + assert "\napi_router.include_router(orders_router)" in updated + + def test_addroute_registers_despite_a_commented_copy(self, tmp_path: Path) -> None: + package = make_project(tmp_path, nested=False, preset="minimal") + api = package / "api" / "api.py" + api.write_text( + api.read_text(encoding="utf-8").replace( + "# fastkit:routes", + "# api_router.include_router(orders_router)\n# fastkit:routes", + ), + encoding="utf-8", + ) + + add_new_route(str(tmp_path), "orders") + + code = code_without_comments(api.read_text(encoding="utf-8")) + assert "api_router.include_router(orders_router)" in code + + def test_commented_main_include_is_not_enough(self, tmp_path: Path) -> None: + main = ( + "from fastapi import FastAPI\n\napp = FastAPI()\n" + "# app.include_router(api_router)\n" + ) + plan = RoutePlan(str(tmp_path)) + main_path = str(tmp_path / "main.py") + + _plan_main_app(plan, str(tmp_path), main_path, main, "api.api") + + written = plan.read(main_path) or "" + assert "from api.api import api_router" in written + assert "app.include_router(api_router)" in code_without_comments(written) + + def test_equal_extra_arguments_do_not_trigger_the_note( + self, tmp_path: Path + ) -> None: + router = tmp_path / "api" / "api.py" + router.parent.mkdir() + router.write_text( + "from fastapi import APIRouter\napi_router = APIRouter()\n" + 'api_router.include_router(orders_router, "/x")\n', + encoding="utf-8", + ) + layout = {"api_dir": str(router.parent), "api_router_file": str(router)} + + same = RoutePlan(str(tmp_path)) + plan_router_registration( + same, + layout, + "from x import router as orders_router", + 'api_router.include_router(orders_router, "/x")', + ) + other = RoutePlan(str(tmp_path)) + plan_router_registration( + other, + layout, + "from x import router as orders_router", + 'api_router.include_router(orders_router, "/y")', + ) + + assert not any("Keeping existing" in note for _, note in same.notes) + assert any("Keeping existing" in note for _, note in other.notes) + + +# ---------------------------------------------------------------------- +# 10. A failed write is rolled back; changes after planning stop the run +# ---------------------------------------------------------------------- + + +class TestRollback: + def test_failure_removes_created_files_and_restores_modified( + self, tmp_path: Path + ) -> None: + first = tmp_path / "first.py" + second = tmp_path / "second.py" + first.write_text("one\n", encoding="utf-8") + second.write_bytes(b"two\r\n") + plan = RoutePlan(str(tmp_path)) + plan.create(str(tmp_path / "pkg" / "sub" / "new.py"), "new\n") + plan.create(str(tmp_path / "other.py"), "other\n") + plan.write(str(first), "ONE\n") + plan.write(str(second), "TWO\n") + real_write = route_plan_module.write_text_preserving_newlines + calls: List[str] = [] + + def failing_write(path: str, content: str, newline: str) -> None: + calls.append(path) + if path == str(second) and content == "TWO\n": + raise PermissionError(13, "Permission denied", path) + real_write(path, content, newline) + + with patch.object( + route_plan_module, "write_text_preserving_newlines", failing_write + ): + with pytest.raises(PermissionError): + plan.apply() + + assert sorted(p.name for p in tmp_path.iterdir()) == ["first.py", "second.py"] + assert first.read_text(encoding="utf-8") == "one\n" + assert second.read_bytes() == b"two\r\n" + + def test_cli_permission_error_leaves_no_new_files( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + package = make_project(tmp_path, nested=False, preset="minimal") + (tmp_path / "tests").mkdir() + before = snapshot(tmp_path) + monkeypatch.chdir(tmp_path) + real_write = route_plan_module.write_text_preserving_newlines + + def failing_write(path: str, content: str, newline: str) -> None: + if path.endswith("api.py"): + raise PermissionError(13, "Permission denied", path) + real_write(path, content, newline) + + with patch.object( + route_plan_module, "write_text_preserving_newlines", failing_write + ): + result = CliRunner().invoke( + fastkit_cli, ["addroute", "orders", "."], input="Y\n" + ) + + assert result.exit_code == 1, result.output + assert "Permission denied" in _flat(result.output) + assert "Traceback" not in result.output + assert snapshot(tmp_path) == before + assert not (package / "crud").exists() + + def test_file_changed_after_planning_stops_the_run(self, tmp_path: Path) -> None: + target = tmp_path / "a.py" + target.write_text("a\n", encoding="utf-8") + plan = RoutePlan(str(tmp_path)) + plan.write(str(target), "b\n") + plan.create(str(tmp_path / "new.py"), "n\n") + target.write_text("edited meanwhile\n", encoding="utf-8") + + with pytest.raises(BackendExceptions, match="changed after the route"): + plan.apply() + + assert target.read_text(encoding="utf-8") == "edited meanwhile\n" + assert not (tmp_path / "new.py").exists() + + def test_file_created_after_planning_stops_the_run(self, tmp_path: Path) -> None: + plan = RoutePlan(str(tmp_path)) + plan.create(str(tmp_path / "new.py"), "n\n") + (tmp_path / "new.py").write_text("theirs\n", encoding="utf-8") + + with pytest.raises(BackendExceptions, match="new.py"): + plan.apply() + + assert (tmp_path / "new.py").read_text(encoding="utf-8") == "theirs\n" + + +# ---------------------------------------------------------------------- +# 8, 15, 16. CLI: plain errors, help text, startdemo --yes +# ---------------------------------------------------------------------- + + +class TestCli: + def test_entity_is_validated_before_any_work( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + # Not even a project: the --entity error still comes first. + monkeypatch.chdir(tmp_path) + + result = CliRunner().invoke( + fastkit_cli, ["addroute", "orders", ".", "--entity", "order", "--dry-run"] + ) + + assert result.exit_code == 1 + assert "PascalCase" in _flat(result.output) + assert "Traceback" not in result.output + assert "not a FastAPI-fastkit project" not in _flat(result.output) + + @pytest.mark.parametrize("name", ["café", "Orders", "__init__"]) + def test_invalid_names_exit_1_plainly( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, name: str + ) -> None: + make_project(tmp_path, preset="minimal") + monkeypatch.chdir(tmp_path) + before = snapshot(tmp_path) + + result = CliRunner().invoke(fastkit_cli, ["addroute", name, "."], input="Y\n") + + assert result.exit_code == 1 + assert "Traceback" not in result.output + assert snapshot(tmp_path) == before + + def test_existing_route_exits_1_with_the_file_names( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + package = make_project(tmp_path, preset="minimal") + (package / "crud").mkdir() + (package / "crud" / "orders.py").write_text("# mine\n", encoding="utf-8") + monkeypatch.chdir(tmp_path) + before = snapshot(tmp_path) + + result = CliRunner().invoke( + fastkit_cli, ["addroute", "orders", "."], input="Y\n" + ) + + assert result.exit_code == 1 + assert "crud/orders.py" in _flat(result.output) + assert "Do you want to add route" not in result.output + assert "Traceback" not in result.output + assert snapshot(tmp_path) == before + + def test_help_examples_keep_their_lines(self) -> None: + result = CliRunner().invoke(fastkit_cli, ["addroute", "--help"]) + + lines = [line.strip() for line in result.output.splitlines()] + assert any(line.startswith("fastkit addroute orders . ") for line in lines) + assert any( + line.startswith("fastkit addroute orders my_project") for line in lines + ) + assert any( + line.startswith("fastkit addroute orders . --diff") for line in lines + ) + + def test_startdemo_help_documents_yes(self) -> None: + result = CliRunner().invoke(fastkit_cli, ["startdemo", "--help"]) + + flat = _flat(result.output) + assert "create the project without asking" in flat + assert "-y None: + monkeypatch.chdir(tmp_path) + self.workspace = tmp_path + + def test_yes_needs_no_answers(self) -> None: + result = CliRunner().invoke(fastkit_cli, [*STARTDEMO, "-y"], input="") + + assert result.exit_code == 0, result.output + assert (self.workspace / "demo" / "pyproject.toml").is_file() + assert "proceed with project creation" not in result.output + + def test_yes_with_a_piped_folder_answer_deploys_in_place(self) -> None: + (self.workspace / "README.md").write_text("mine\n", encoding="utf-8") + + result = CliRunner().invoke(fastkit_cli, [*STARTDEMO, "-y"], input="n\n") + + assert result.exit_code == 0, result.output + assert (self.workspace / "pyproject.toml").is_file() + assert (self.workspace / "README.md").read_text(encoding="utf-8") != "mine\n" + + def test_existing_project_directory_is_still_refused(self) -> None: + (self.workspace / "demo").mkdir() + (self.workspace / "demo" / "keep.txt").write_text("x", encoding="utf-8") + + result = CliRunner().invoke(fastkit_cli, [*STARTDEMO, "-y"], input="") + + assert result.exit_code == 1 + assert "already exists" in _flat(result.output) + assert sorted(p.name for p in (self.workspace / "demo").iterdir()) == [ + "keep.txt" + ] + + def test_without_yes_the_creation_prompt_is_asked(self) -> None: + result = CliRunner().invoke(fastkit_cli, STARTDEMO, input="n\n") + + assert result.exit_code == 0 + assert "proceed with project creation" in result.output + assert not (self.workspace / "demo").exists() + + +class TestRemainingPaths: + def test_generated_module_that_does_not_parse_is_refused( + self, tmp_path: Path + ) -> None: + from fastapi_fastkit.backend.route_generators import _check_generated_modules + + plan = RoutePlan(str(tmp_path)) + plan.create(str(tmp_path / "broken.py"), "def (:\n") + + with pytest.raises(BackendExceptions, match="not valid Python"): + _check_generated_modules(plan, resolve_route_names("orders")) + + def test_unexpected_error_is_one_line( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + make_project(tmp_path, preset="minimal") + monkeypatch.chdir(tmp_path) + + with patch( + "fastapi_fastkit.cli.create_info_table", side_effect=RuntimeError("boom") + ): + result = CliRunner().invoke(fastkit_cli, ["addroute", "orders", "."]) + + assert result.exit_code == 1 + assert "Error during route addition: boom" in _flat(result.output) + assert "Traceback" not in result.output + + def test_debug_mode_logs_the_failure_without_a_traceback_on_screen( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + from fastapi_fastkit.core.settings import FastkitConfig + + monkeypatch.setattr( + FastkitConfig, + "_writable_log_file_path", + staticmethod(lambda preferred: str(tmp_path / "fastkit.log")), + ) + package = make_project(tmp_path, preset="minimal") + (package / "crud").mkdir() + (package / "crud" / "orders.py").write_text("# mine\n", encoding="utf-8") + monkeypatch.chdir(tmp_path) + + result = CliRunner().invoke(fastkit_cli, ["--debug", "addroute", "orders", "."]) + + assert result.exit_code == 1 + assert "already exists" in _flat(result.output) + assert "Traceback (most recent call last)" not in result.stdout diff --git a/tests/test_backends/test_route_naming.py b/tests/test_backends/test_route_naming.py new file mode 100644 index 0000000..bf201b9 --- /dev/null +++ b/tests/test_backends/test_route_naming.py @@ -0,0 +1,188 @@ +# -------------------------------------------------------------------------- +# addroute naming (route -> singular PascalCase entity) and layout +# resolution (metadata first, then a ``domains/`` package). +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import keyword +from pathlib import Path +from typing import Optional +from unittest.mock import patch + +import pytest + +from fastapi_fastkit.backend.route_generators import ( + RouteNames, + derive_entity_name, + resolve_route_layout, + resolve_route_names, + route_details, + singularize, +) +from fastapi_fastkit.core.exceptions import BackendExceptions +from tests.test_backends.test_route_generators import make_project + + +@pytest.mark.parametrize( + "word, expected", + [ + ("orders", "order"), + ("users", "user"), + ("categories", "category"), + ("addresses", "address"), + ("boxes", "box"), + ("matches", "match"), + ("wishes", "wish"), + ("buzzes", "buzz"), + ("people", "person"), + ("children", "child"), + ("People", "Person"), + ("news", "news"), + ("data", "data"), + ("status", "status"), + ("analysis", "analysis"), + ("class", "class"), + ("ties", "tie"), + ("s", "s"), + ("order", "order"), + ("orderItems", "orderItem"), + ], +) +def test_singularize(word: str, expected: str) -> None: + assert singularize(word) == expected + + +@pytest.mark.parametrize( + "route, entity", + [ + ("orders", "Order"), + ("health_checks", "HealthCheck"), + ("order_items", "OrderItem"), + ("people", "Person"), + ("news", "News"), + ("user", "User"), + ("v2_items", "V2Item"), + ("__orders__", "Order"), + ("_", "Entity"), + ("_2", "Entity2"), + ("none", "NoneEntity"), + ("trues", "TrueEntity"), + ("orderItems", "OrderItem"), + ], +) +def test_derive_entity_name(route: str, entity: str) -> None: + name = derive_entity_name(route) + assert name == entity + assert name.isidentifier() and not keyword.iskeyword(name) + assert name[0].isupper() + + +def test_route_names_derive_every_spelling() -> None: + names = RouteNames("health_checks", "HealthCheck") + assert (names.snake, names.label, names.title, names.path) == ( + "health_check", + "health check", + "Health check", + "/health_checks", + ) + assert RouteNames("requests", "HTTPRequest").snake == "http_request" + assert route_details(names, "domain") == { + "Layout": "domain", + "Path": "/health_checks", + "Entity": "HealthCheck", + "Schemas": "HealthCheckCreate, HealthCheckUpdate, HealthCheckRead", + } + + +def test_entity_option_wins_over_derivation() -> None: + assert resolve_route_names("people", "Member").entity == "Member" + assert resolve_route_names("people").entity == "Person" + + +@pytest.mark.parametrize("entity", ["order", "Order-Item", "1Order", "Ord er", ""]) +def test_invalid_entity_is_rejected(entity: str) -> None: + with pytest.raises(BackendExceptions, match="PascalCase"): + resolve_route_names("orders", entity) + + +@pytest.mark.parametrize("route", ["bad-name", "class", "1orders"]) +def test_invalid_route_name_is_rejected(route: str) -> None: + with pytest.raises(BackendExceptions, match="Python identifier"): + resolve_route_names(route) + + +# ------------------------------------------------------------ +# Layout resolution +# ------------------------------------------------------------ + + +def _with_domains(package: Path) -> None: + (package / "domains").mkdir() + (package / "domains" / "__init__.py").write_text("", encoding="utf-8") + + +@pytest.mark.parametrize( + "preset, template, domains, expected", + [ + # The four preset layouts, recorded in metadata. + ("domain-starter", None, True, "domain"), + ("classic-layered", None, False, "classic-layer"), + ("minimal", None, False, "classic-layer"), + ("single-module", None, False, "classic-layer"), + # Metadata is the first signal: a classic preset stays classic. + ("classic-layered", None, True, "classic-layer"), + # Template-only projects: the domain-starter template, then the + # project's own domains/ package (fastapi-sqlmodel, fastapi-auth-jwt). + (None, "fastapi-domain-starter", False, "domain"), + (None, "fastapi-sqlmodel", True, "domain"), + (None, "fastapi-auth-jwt", True, "domain"), + (None, "fastapi-default", False, "classic-layer"), + (None, None, True, "domain"), + (None, None, False, "classic-layer"), + ], +) +def test_layout_resolution( + tmp_path: Path, + preset: Optional[str], + template: Optional[str], + domains: bool, + expected: str, +) -> None: + package = make_project(tmp_path, preset=preset) + if template is not None: + metadata = tmp_path / "pyproject.toml" + metadata.write_text( + metadata.read_text(encoding="utf-8") + f'template = "{template}"\n', + encoding="utf-8", + ) + if domains: + _with_domains(package) + with patch("fastapi_fastkit.backend.route_generators.print_warning") as warning: + assert resolve_route_layout(str(tmp_path)) == expected + warning.assert_not_called() + + +@pytest.mark.parametrize( + "domains, expected", [(True, "domain"), (False, "classic-layer")] +) +def test_unknown_preset_falls_back_to_the_project_shape( + tmp_path: Path, domains: bool, expected: str +) -> None: + package = make_project(tmp_path, preset="future-preset") + if domains: + _with_domains(package) + with patch("fastapi_fastkit.backend.route_generators.print_warning") as warning: + assert resolve_route_layout(str(tmp_path)) == expected + assert warning.called is (not domains) + + +def test_domains_package_of_a_project_without_metadata(tmp_path: Path) -> None: + """Discovery finds ``src/app/main.py`` and its ``domains`` sibling.""" + package = tmp_path / "src" / "app" + package.mkdir(parents=True) + (package / "main.py").write_text( + "from fastapi import FastAPI\napp = FastAPI()\n", encoding="utf-8" + ) + (package / "domains").mkdir() + assert resolve_route_layout(str(tmp_path)) == "domain" + assert resolve_route_layout(str(tmp_path), "classic-layer") == "classic-layer" diff --git a/tests/test_backends/test_route_plan.py b/tests/test_backends/test_route_plan.py new file mode 100644 index 0000000..ab43cb9 --- /dev/null +++ b/tests/test_backends/test_route_plan.py @@ -0,0 +1,606 @@ +# -------------------------------------------------------------------------- +# addroute plans every file before writing: the plan itself, preview / +# real-run equality, CRLF projects, idempotency, shared core modules, +# generated tests and the shape of the generated routers. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import ast +import os +import shutil +from pathlib import Path +from typing import Dict, List, Optional, Tuple +from unittest.mock import patch + +import pytest + +from fastapi_fastkit.backend.main import ( + _package_of_router_module, + _update_main_app, + add_new_route, + resolve_project_layout, +) +from fastapi_fastkit.backend.route_generators import ( + SHARED_CORE_MODULES, + ClassicLayeredRouteGenerator, + get_route_generator, + plan_new_route, + shared_core_source, +) +from fastapi_fastkit.backend.route_plan import RoutePlan +from fastapi_fastkit.core.exceptions import BackendExceptions +from fastapi_fastkit.core.settings import settings +from tests.test_backends.test_route_generators import make_project, snapshot + +# ------------------------------------------------------------ +# RoutePlan +# ------------------------------------------------------------ + + +def test_plan_reads_through_to_disk_and_tracks_changes(tmp_path: Path) -> None: + existing = tmp_path / "a.py" + existing.write_bytes(b"one\r\ntwo\r\n") + plan = RoutePlan(str(tmp_path)) + + assert plan.read(str(existing)) == "one\ntwo\n" + assert plan.read(str(tmp_path / "missing.py")) is None + assert not plan.exists(str(tmp_path / "missing.py")) + + plan.write(str(existing), "one\ntwo\n") + assert plan.is_empty # identical content is not a change + plan.write(str(existing), "one\nTWO\n") + plan.write(str(existing), "one\ntwo\n") + assert plan.is_empty # reverting drops the change again + + plan.write(str(existing), "one\nthree\n") + assert plan.create(str(tmp_path / "pkg" / "new.py"), "new\n") + assert not plan.create(str(tmp_path / "pkg" / "new.py"), "other\n") + assert not plan.create(str(existing), "x") + assert [plan.display(f.path) for f in plan.created] == ["pkg/new.py"] + assert [plan.display(f.path) for f in plan.modified] == ["a.py"] + assert ("info", "File a.py already exists, skipping...") in plan.notes + + plan.write(str(tmp_path / "pkg" / "new.py"), "newer\n") + written = plan.apply() + + assert written == [str(tmp_path / "pkg" / "new.py"), str(existing)] + assert (tmp_path / "pkg" / "new.py").read_bytes() == b"newer\n" + assert existing.read_bytes() == b"one\r\nthree\r\n" + assert plan.is_empty + assert plan.read(str(existing)) == "one\nthree\n" + + +def test_plan_diff_ignores_crlf(tmp_path: Path) -> None: + target = tmp_path / "api.py" + target.write_bytes(b"a\r\nb\r\nc\r\n") + plan = RoutePlan(str(tmp_path)) + plan.write(str(target), "a\nb\nnew\nc\n") + + diff = plan.diff(plan.modified[0]) + + assert "\r" not in diff + assert diff.splitlines()[:2] == ["--- a/api.py", "+++ b/api.py"] + changed = [line for line in diff.splitlines()[2:] if line[:1] in "+-"] + assert changed == ["+new"] + + +def test_plan_render(tmp_path: Path) -> None: + lines: List[str] = [] + plan = RoutePlan(str(tmp_path)) + plan.render(lines.append) + assert lines == [ + "Nothing to change: every file this route needs is already in place." + ] + + (tmp_path / "old.py").write_text("x\n", encoding="utf-8") + plan.write(str(tmp_path / "old.py"), "x\ny\n") + plan.create(str(tmp_path / "new.py"), "first\nsecond\n") + plan.create(str(tmp_path / "empty.py"), "") + plan.note("kept something") + lines.clear() + plan.render(lines.append) + assert "Files to create (2):" in lines and " + new.py" in lines + assert "Files to modify (1):" in lines and " ~ old.py" in lines + assert "Note: kept something" in lines + assert not any(line.startswith("@@") for line in lines) + + lines.clear() + plan.render(lines.append, show_diff=True) + text = "\n".join(lines) + assert "+++ b/old.py" in text and "+y" in text + assert "--- /dev/null\n+++ b/new.py\n@@ -0,0 +1,2 @@\n+first\n+second" in text + assert "+++ b/empty.py\n@@ -0,0 +0,0 @@" in text + + +def test_plan_display_outside_project(tmp_path: Path) -> None: + plan = RoutePlan() + assert plan.display(os.path.join("a", "b.py")) == "a/b.py" + + +# ------------------------------------------------------------ +# Preview and real run produce the same bytes +# ------------------------------------------------------------ + + +def _expected_bytes(plan: RoutePlan) -> Dict[str, bytes]: + expected: Dict[str, bytes] = {} + for planned in plan.created + plan.modified: + newline = planned.newline or "\n" + content = planned.content + if planned.newline == "\r\n": + content = content.replace("\n", "\r\n") + assert newline in ("\n", "\r\n") + relative = str(Path(planned.path).relative_to(plan.project_dir)) + expected[relative] = content.encode("utf-8") + return expected + + +def _crlf_tree(root: Path) -> None: + for path in root.rglob("*.py"): + path.write_bytes( + path.read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n") + ) + + +@pytest.mark.parametrize("layout", ["classic-layer", "domain"]) +@pytest.mark.parametrize("crlf", [False, True]) +@pytest.mark.parametrize("aggregator", [False, True]) +def test_plan_matches_the_real_run_byte_for_byte( + tmp_path: Path, layout: str, crlf: bool, aggregator: bool +) -> None: + preview = tmp_path / "preview" + real = tmp_path / "real" + make_project(preview, aggregator=aggregator) + (preview / "tests").mkdir() + if crlf: + _crlf_tree(preview) + shutil.copytree(preview, real) + before = snapshot(preview) + + plan = plan_new_route(str(preview), "orders", layout=layout) + expected = _expected_bytes(plan) + assert snapshot(preview) == before # planning writes nothing + + add_new_route(str(real), "orders", layout=layout) + after = snapshot(real) + changed = {name: data for name, data in after.items() if before.get(name) != data} + assert changed == expected + if crlf: + for planned in plan.modified: + data = after[str(Path(planned.path).relative_to(preview))] + assert data.count(b"\r\n") == data.count(b"\n") + for planned in plan.created: + assert b"\r" not in after[str(Path(planned.path).relative_to(preview))] + + # A second run has nothing left to do. + again = plan_new_route(str(real), "orders", layout=layout) + assert again.is_empty + assert any("already exists" in message for _, message in again.notes) + + +def test_crlf_router_diff_shows_only_the_new_lines(tmp_path: Path) -> None: + make_project(tmp_path, nested=False, preset="minimal") + _crlf_tree(tmp_path) + + plan = plan_new_route(str(tmp_path), "orders") + (router,) = plan.modified + diff = plan.diff(router) + + assert "\r" not in diff + changed = [ + line + for line in diff.splitlines() + if line[:1] in "+-" and not line.startswith(("+++", "---")) + ] + assert changed == [ + "+from src.api.routes.orders import router as orders_router", + "+api_router.include_router(orders_router)", + ] + + +# ------------------------------------------------------------ +# What the plan contains +# ------------------------------------------------------------ + + +@pytest.mark.parametrize("layout", ["classic-layer", "domain"]) +def test_missing_shared_core_modules_are_created(tmp_path: Path, layout: str) -> None: + package = make_project(tmp_path) + add_new_route(str(tmp_path), "orders", layout=layout) + for filename in SHARED_CORE_MODULES: + assert (package / "core" / filename).read_text( + encoding="utf-8" + ) == shared_core_source(filename) + assert (package / "core" / "__init__.py").read_text(encoding="utf-8") == "" + + +def test_existing_shared_core_modules_are_kept(tmp_path: Path) -> None: + package = make_project(tmp_path) + core = package / "core" + core.mkdir() + for filename in SHARED_CORE_MODULES: + (core / filename).write_text("# project's own\n", encoding="utf-8") + plan = plan_new_route(str(tmp_path), "orders") + paths = {Path(planned.path) for planned in plan.created + plan.modified} + assert not any(path.parent == core for path in paths) + + +#: Templates known to ship each shared core module; the scan below must find +#: at least these, so a moved or renamed copy cannot silently drop out. +_EXPECTED_CORE_COPIES = { + "pagination.py": { + "fastapi-async-crud", + "fastapi-auth-jwt", + "fastapi-custom-response", + "fastapi-default", + "fastapi-dockerized", + "fastapi-domain-starter", + "fastapi-empty", + "fastapi-mcp", + "fastapi-psql-orm", + "fastapi-sqlmodel", + }, + "responses.py": { + "fastapi-async-crud", + "fastapi-auth-jwt", + "fastapi-default", + "fastapi-dockerized", + "fastapi-domain-starter", + "fastapi-empty", + "fastapi-llm-agent", + "fastapi-mcp", + "fastapi-psql-orm", + "fastapi-sqlmodel", + }, +} + + +@pytest.mark.parametrize("filename", sorted(SHARED_CORE_MODULES)) +def test_canonical_core_modules_match_the_templates(filename: str) -> None: + """Every template copy of a shared ``core/`` module is the canonical file. + + Content is compared with line endings normalised, because a working copy + checked out with ``core.autocrlf=true`` holds CRLF files. + """ + root = Path(settings.FASTKIT_TEMPLATE_ROOT) + canonical = shared_core_source(filename).replace("\r\n", "\n") + assert "<" not in canonical.split("\n", 1)[0] + compile(canonical, filename, "exec") + + found = set() + for template in sorted(p for p in root.iterdir() if p.is_dir()): + if template.name == "modules": + continue + for shipped in template.rglob(f"{filename}-tpl"): + if shipped.parent.name != "core": + continue + found.add(template.name) + text = shipped.read_bytes().decode("utf-8").replace("\r\n", "\n") + assert text == canonical, shipped + assert found >= _EXPECTED_CORE_COPIES[filename] + + +def test_canonical_responses_document_www_authenticate_on_401() -> None: + """``error_responses(401)`` documents the header every 401 carries.""" + namespace: Dict[str, object] = {} + exec(compile(shared_core_source("responses.py"), "responses.py", "exec"), namespace) + error_responses = namespace["error_responses"] + assert callable(error_responses) + documented = error_responses(401, 404) + assert set(documented) == {401, 404} + assert "WWW-Authenticate" in documented[401]["headers"] + assert "headers" not in documented[404] + assert documented[404]["description"] == "Not Found" + + +@pytest.mark.parametrize("layout", ["classic-layer", "domain"]) +def test_test_module_is_generated_when_the_project_has_tests( + tmp_path: Path, layout: str +) -> None: + package = make_project(tmp_path) + store = ( + "src.app.crud.orders" + if layout == "classic-layer" + else ("src.app.domains.orders.service") + ) + plan = plan_new_route(str(tmp_path), "orders", layout=layout) + assert not any(Path(p.path).name == "test_orders.py" for p in plan.created) + + (tmp_path / "tests").mkdir() + add_new_route(str(tmp_path), "orders", layout=layout) + source = (tmp_path / "tests" / "test_orders.py").read_text(encoding="utf-8") + assert f"from {store} import reset_store" in source + assert "from src.app.main import app" in source + assert 'COLLECTION = app.url_path_for("list_orders")' in source + assert 'assert error_message(response) == "Order not found"' in source + assert 'return response.json()["detail"]' in source + imports = [line for line in source.splitlines() if line.startswith("from src")] + assert imports == sorted(imports, key=lambda line: line.split()[1].lower()) + compile(source, "test_orders.py", "exec") + assert package.is_dir() + + +def test_test_module_imports_a_differently_named_app(tmp_path: Path) -> None: + make_project(tmp_path, nested=False) + metadata = tmp_path / "pyproject.toml" + metadata.write_text( + metadata.read_text(encoding="utf-8").replace( + 'app_module = "src.main:app"', 'app_module = "src.main:application"' + ), + encoding="utf-8", + ) + main = tmp_path / "src" / "main.py" + main.write_text(main.read_text(encoding="utf-8") + "application = app\n") + (tmp_path / "tests").mkdir() + add_new_route(str(tmp_path), "orders") + source = (tmp_path / "tests" / "test_orders.py").read_text(encoding="utf-8") + assert "from src.main import application as app" in source + + +def test_template_module_import_is_reused(tmp_path: Path) -> None: + """``addroute items`` on fastapi-default must not register items twice.""" + package = make_project(tmp_path, nested=False, preset="classic-layered") + api = package / "api" / "api.py" + api.write_text( + "from fastapi import APIRouter\n\nfrom src.api.routes import items\n\n" + "# fastkit:imports\n\napi_router = APIRouter()\n" + "api_router.include_router(items.router)\n# fastkit:routes\n", + encoding="utf-8", + ) + before = api.read_bytes() + add_new_route(str(tmp_path), "items") + assert api.read_bytes() == before + + +# ------------------------------------------------------------ +# main.py mounts the API router under API_V1_PREFIX +# ------------------------------------------------------------ + +_MAIN = "from fastapi import FastAPI\n\n# fastkit:imports\n\napp = FastAPI()\n# fastkit:routes\n" + + +def _main_project( + root: Path, main: str, config: Optional[str] = None +) -> Tuple[Path, Path]: + src = root / "src" + src.mkdir() + (src / "main.py").write_text(main, encoding="utf-8") + if config is not None: + (src / "core").mkdir() + (src / "core" / "config.py").write_text(config, encoding="utf-8") + return src, src / "main.py" + + +def test_main_mounts_under_the_config_prefix(tmp_path: Path) -> None: + src, main = _main_project( + tmp_path, _MAIN, 'class S:\n API_V1_PREFIX = "/api/v1"\nsettings = S()\n' + ) + _update_main_app(str(src), "orders") + content = main.read_text(encoding="utf-8") + assert "from src.core.config import settings" in content + assert "app.include_router(api_router, prefix=settings.API_V1_PREFIX)" in content + + +def test_main_that_already_imports_settings_is_not_reimported(tmp_path: Path) -> None: + main_source = _MAIN.replace( + "# fastkit:imports", + "from src.core.config import settings as settings\n# fastkit:imports", + ) + src, main = _main_project(tmp_path, main_source, "API_V1_PREFIX = '/v1'\n") + _update_main_app(str(src), "orders") + content = main.read_text(encoding="utf-8") + assert content.count("import settings") == 1 + assert "prefix=settings.API_V1_PREFIX" in content + + +def test_single_module_settings_in_main(tmp_path: Path) -> None: + """``fastapi-single-module`` keeps ``Settings`` inside ``src/main.py``.""" + main_source = _MAIN.replace( + "app = FastAPI()", + 'class Settings:\n API_V1_PREFIX: str = "/api/v1"\n\n\n' + "settings: Settings = Settings()\napp = FastAPI()", + ) + src, main = _main_project(tmp_path, main_source) + _update_main_app(str(src), "orders") + content = main.read_text(encoding="utf-8") + assert "core.config" not in content + assert "app.include_router(api_router, prefix=settings.API_V1_PREFIX)" in content + + +def test_project_without_a_prefix_setting_mounts_at_the_root(tmp_path: Path) -> None: + src, main = _main_project(tmp_path, _MAIN, "PROJECT_NAME = 'x'\n") + (tmp_path / "pyproject.toml").write_text( + '[tool.fastapi-fastkit]\napp_module = "src.main:app"\npreset = "minimal"\n', + encoding="utf-8", + ) + plan = plan_new_route(str(tmp_path), "orders") + lines: List[str] = [] + plan.render(lines.append) + assert any("define no API_V1_PREFIX" in line for line in lines) + plan.apply() + content = main.read_text(encoding="utf-8") + assert "app.include_router(api_router)\n" in content + assert "settings" not in content + + +def test_unparsable_main_is_treated_as_not_binding_settings(tmp_path: Path) -> None: + broken = "app = FastAPI(\n# fastkit:routes\n" + src, main = _main_project(tmp_path, broken, "API_V1_PREFIX = '/v1'\n") + _update_main_app(str(src), "orders") + content = main.read_text(encoding="utf-8") + assert "from src.core.config import settings" in content + + +# ------------------------------------------------------------ +# Generated router shape (no runtime dependencies needed) +# ------------------------------------------------------------ + + +def _decorated_routes(source: str) -> Dict[str, Dict[str, object]]: + routes: Dict[str, Dict[str, object]] = {} + for node in ast.parse(source).body: + if not isinstance(node, ast.FunctionDef): + continue + for decorator in node.decorator_list: + if not ( + isinstance(decorator, ast.Call) + and isinstance(decorator.func, ast.Attribute) + and isinstance(decorator.func.value, ast.Name) + and decorator.func.value.id == "router" + ): + continue + keywords = {k.arg: ast.unparse(k.value) for k in decorator.keywords} + routes[node.name] = { + "method": decorator.func.attr, + "path": ast.literal_eval(decorator.args[0]), + "status": keywords.get("status_code"), + "response_model": keywords.get("response_model"), + "responses": keywords.get("responses"), + "returns": ast.unparse(node.returns) if node.returns else None, + "params": [arg.arg for arg in node.args.args], + } + return routes + + +@pytest.mark.parametrize( + "layout, router_file", + [ + ("classic-layer", "api/routes/health_checks.py"), + ("domain", "domains/health_checks/router.py"), + ], +) +def test_generated_router_declares_the_rest_contract( + tmp_path: Path, layout: str, router_file: str +) -> None: + package = make_project(tmp_path) + add_new_route(str(tmp_path), "health_checks", layout=layout) + source = (package / router_file).read_text(encoding="utf-8") + tree = ast.parse(source) + + assert "import *" not in source + router_call = next( + node.value + for node in tree.body + if isinstance(node, ast.Assign) + and isinstance(node.targets[0], ast.Name) + and node.targets[0].id == "router" + ) + assert ast.unparse(router_call) == ( + "APIRouter(prefix='/health_checks', tags=['health_checks'])" + ) + not_found = "error_responses(status.HTTP_404_NOT_FOUND)" + expected = { + "list_health_checks": ("get", "", None, "Page[HealthCheckRead]", None), + "create_health_check": ( + "post", + "", + "status.HTTP_201_CREATED", + "HealthCheckRead", + None, + ), + "get_health_check": ( + "get", + "/{health_check_id}", + None, + "HealthCheckRead", + not_found, + ), + "replace_health_check": ( + "put", + "/{health_check_id}", + None, + "HealthCheckRead", + not_found, + ), + "update_health_check": ( + "patch", + "/{health_check_id}", + None, + "HealthCheckRead", + not_found, + ), + "delete_health_check": ( + "delete", + "/{health_check_id}", + "status.HTTP_204_NO_CONTENT", + None, + not_found, + ), + } + routes = _decorated_routes(source) + assert set(routes) == set(expected) + for name, (method, path, status, model, responses) in expected.items(): + route = routes[name] + assert (route["method"], route["path"], route["status"]) == ( + method, + path, + status, + ) + assert route["response_model"] == model + assert route["responses"] == responses + assert route["returns"] == (model or "None") + assert routes["list_health_checks"]["params"][-2:] == ["limit", "offset"] + assert {"request", "response"} <= set(routes["create_health_check"]["params"]) + assert "Annotated[" in source and "= Depends(" not in source + assert 'response.headers["Location"]' in source + assert "exclude_unset=True" in ( + source + if layout == "classic-layer" + else (package / "domains/health_checks/service.py").read_text(encoding="utf-8") + ) + schemas = ( + package + / ( + "schemas/health_checks.py" + if layout == "classic-layer" + else "domains/health_checks/schemas.py" + ) + ).read_text(encoding="utf-8") + classes = {n.name for n in ast.parse(schemas).body if isinstance(n, ast.ClassDef)} + assert classes == {"HealthCheckCreate", "HealthCheckUpdate", "HealthCheckRead"} + + +# ------------------------------------------------------------ +# Smaller paths +# ------------------------------------------------------------ + + +def test_planned_content_is_read_back(tmp_path: Path) -> None: + plan = RoutePlan(str(tmp_path)) + plan.create(str(tmp_path / "a.py"), "planned\n") + assert plan.read(str(tmp_path / "a.py")) == "planned\n" + + +def test_display_falls_back_when_relpath_fails(tmp_path: Path) -> None: + plan = RoutePlan(str(tmp_path)) + with patch("os.path.relpath", side_effect=ValueError("other drive")): + assert plan.display(str(tmp_path / "a.py")).endswith("/a.py") + + +@pytest.mark.parametrize( + "router_module, package", + [("src.app.api.router", "src.app"), ("src.api", "src"), ("api.api", "")], +) +def test_package_of_router_module(router_module: str, package: str) -> None: + assert _package_of_router_module(router_module) == package + + +@pytest.mark.parametrize("layout", ["classic-layer", "domain"]) +def test_generator_add_new_route_plans_and_writes(tmp_path: Path, layout: str) -> None: + package = make_project(tmp_path) + generator = get_route_generator(layout) + plan = generator.add_new_route( + str(tmp_path), + "orders", + resolve_project_layout(str(tmp_path)), + entity="Purchase", + ) + assert plan.is_empty + assert (package / "core" / "pagination.py").exists() + + +def test_classic_generator_requires_the_source_directory(tmp_path: Path) -> None: + with pytest.raises(BackendExceptions, match="Source directory not found"): + ClassicLayeredRouteGenerator().add_new_route( + str(tmp_path), "orders", {"package_dir": str(tmp_path / "absent")} + ) diff --git a/tests/test_backends/test_scaffolder.py b/tests/test_backends/test_scaffolder.py index ae4dd22..9490d34 100644 --- a/tests/test_backends/test_scaffolder.py +++ b/tests/test_backends/test_scaffolder.py @@ -237,3 +237,27 @@ def test_noop_when_folder_was_not_created(self, tmp_path: Path) -> None: # then assert project.exists() + + +def test_auth_route_conflicts_are_reported(tmp_path: Path) -> None: + """A template router claiming /auth or /users is warned about.""" + config = {"authentication": "JWT"} + options = _options( + template="fastapi-default", preset_id="classic-layered", config=config + ) + scaffolder = ProjectScaffolder(_settings(str(tmp_path)), options) + project = tmp_path / "project" + project.mkdir() + + with ( + patch.object( + scaffolder.strategist, + "auth_route_conflicts", + return_value=["src/api/routes/users.py already defines /users routes"], + ), + patch("fastapi_fastkit.backend.scaffolder.print_warning") as warn, + ): + scaffolder._generate_dynamic_config(str(project), config) + + titles = [call.kwargs.get("title") for call in warn.call_args_list] + assert "Authentication routes" in titles diff --git a/tests/test_backends/test_windows_portability.py b/tests/test_backends/test_windows_portability.py index 1ebf677..04fd206 100644 --- a/tests/test_backends/test_windows_portability.py +++ b/tests/test_backends/test_windows_portability.py @@ -281,7 +281,10 @@ def test_preset_router_wiring_keeps_crlf(self, tmp_path: Path) -> None: data = main_py.read_bytes() assert wired == ["Background tasks"] assert _only_crlf(data), data - assert b"app.include_router(tasks_router)\r\n" in data + assert ( + b"app.include_router(tasks_router, prefix=settings.API_V1_PREFIX)\r\n" + in data + ) def test_ruff_merge_keeps_crlf(self, tmp_path: Path) -> None: pyproject = tmp_path / "pyproject.toml" diff --git a/tests/test_cli_operations/test_cli.py b/tests/test_cli_operations/test_cli.py index f75346b..ad47c8d 100644 --- a/tests/test_cli_operations/test_cli.py +++ b/tests/test_cli_operations/test_cli.py @@ -130,8 +130,9 @@ def test_startdemo_invalid_template(self, temp_dir: str) -> None: ) # then - assert result.exit_code != 0 - assert "Error" in result.output or "Invalid" in result.output + assert result.exit_code == 1 + assert isinstance(result.exception, SystemExit) + assert "does not exist" in result.output def test_startdemo_cancel_confirmation(self, temp_dir: str) -> None: # given @@ -154,7 +155,7 @@ def test_startdemo_cancel_confirmation(self, temp_dir: str) -> None: ) # then - # CLI returns 0 even when user cancels (just prints error and returns) + # Declining the confirmation is a cancel, not a failure: exit status 0 assert result.exit_code == 0 assert "Project creation aborted!" in result.output @@ -181,12 +182,8 @@ def test_startdemo_backend_error(self, temp_dir: str) -> None: ) # then - # CLI should handle error gracefully - assert ( - result.exit_code != 0 - or "Error" in result.output - or "does not exist" in result.output - ) + assert result.exit_code == 1 + assert "does not exist" in result.output def test_delete_demoproject(self, temp_dir: str) -> None: # given @@ -714,8 +711,7 @@ def test_addroute_nonexistent_project(self, temp_dir: str) -> None: ) # then - # CLI returns 0 even when project doesn't exist (just prints error and returns) - assert result.exit_code == 0 + assert result.exit_code == 1 assert "does not exist" in result.output def test_addroute_cancel_confirmation(self, temp_dir: str) -> None: @@ -748,7 +744,7 @@ def test_addroute_cancel_confirmation(self, temp_dir: str) -> None: ) # then - # CLI returns 0 even when user cancels (just prints error and returns) + # Declining the confirmation is not an error. assert result.exit_code == 0 assert "Operation cancelled!" in result.output @@ -804,7 +800,7 @@ def test_addroute_current_directory_not_fastkit_project( result = self.runner.invoke(fastkit_cli, ["addroute", "user", "."], input="Y") # then - assert result.exit_code == 0 + assert result.exit_code == 1 assert "Current directory is not a FastAPI-fastkit project." in result.output def test_startdemo_no_project_folder(self, tmp_path: Path) -> None: diff --git a/tests/test_cli_operations/test_cli_addroute_exit_codes.py b/tests/test_cli_operations/test_cli_addroute_exit_codes.py new file mode 100644 index 0000000..6de8740 --- /dev/null +++ b/tests/test_cli_operations/test_cli_addroute_exit_codes.py @@ -0,0 +1,218 @@ +# -------------------------------------------------------------------------- +# Testcases of ``fastkit addroute`` exit statuses: refusals and failures +# exit with 1 like ``init`` and ``startdemo``; declining the confirmation and +# a preview (including "nothing to do") exit with 0. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path +from unittest.mock import patch + +import pytest +from click.testing import CliRunner + +from fastapi_fastkit.cli import fastkit_cli +from fastapi_fastkit.core.exceptions import BackendExceptions +from tests.test_backends.test_route_generators import make_project, snapshot + + +def _flat(text: str) -> str: + """Output with panel borders and line wrapping removed.""" + return " ".join(re.sub(r"[─-╿]", " ", text).split()) + + +def _run_closed_stdin(cwd: Path, *args: str) -> "subprocess.CompletedProcess[str]": + env = dict(os.environ, PYTHONIOENCODING="utf-8", PYTHONUTF8="1") + return subprocess.run( + [sys.executable, "-m", "fastapi_fastkit", *args], + cwd=str(cwd), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + encoding="utf-8", + errors="replace", + env=env, + timeout=120, + ) + + +@pytest.fixture +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + make_project(tmp_path, preset="minimal") + monkeypatch.chdir(tmp_path) + return tmp_path + + +class TestAddrouteRefusalsExit1: + def test_invalid_route_name(self, project: Path) -> None: + before = snapshot(project) + result = CliRunner().invoke(fastkit_cli, ["addroute", "1orders", "."]) + + assert result.exit_code == 1, result.output + assert "not a valid Python identifier" in _flat(result.output) + assert snapshot(project) == before + + def test_keyword_route_name(self, project: Path) -> None: + result = CliRunner().invoke(fastkit_cli, ["addroute", "import", "."]) + + assert result.exit_code == 1, result.output + assert "Python keyword" in _flat(result.output) + + def test_invalid_entity(self, project: Path) -> None: + before = snapshot(project) + result = CliRunner().invoke( + fastkit_cli, ["addroute", "orders", ".", "--entity", "order"] + ) + + assert result.exit_code == 1, result.output + assert "PascalCase" in _flat(result.output) + assert snapshot(project) == before + + def test_invalid_entity_in_preview(self, project: Path) -> None: + result = CliRunner().invoke( + fastkit_cli, + ["addroute", "orders", ".", "--entity", "class", "--dry-run"], + ) + + assert result.exit_code == 1, result.output + + def test_not_a_fastkit_project( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.chdir(tmp_path) + result = CliRunner().invoke(fastkit_cli, ["addroute", "orders", "."]) + + assert result.exit_code == 1, result.output + assert "not a FastAPI-fastkit project" in _flat(result.output) + + def test_missing_project_directory( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.chdir(tmp_path) + with patch( + "fastapi_fastkit.core.settings.FastkitConfig.USER_WORKSPACE", + str(tmp_path), + ): + result = CliRunner().invoke( + fastkit_cli, ["addroute", "orders", "no-such-project"] + ) + + assert result.exit_code == 1, result.output + assert "does not exist" in _flat(result.output) + + def test_planning_failure(self, project: Path) -> None: + # A fastkit project whose source package is gone cannot be planned. + shutil.rmtree(project / "src") + result = CliRunner().invoke(fastkit_cli, ["addroute", "orders", "."]) + + assert result.exit_code == 1, result.output + assert "Error during route addition" in _flat(result.output) + + def test_planning_failure_in_preview(self, project: Path) -> None: + with patch( + "fastapi_fastkit.cli.plan_new_route", + side_effect=BackendExceptions("Unknown route layout: 'flat'"), + ): + result = CliRunner().invoke( + fastkit_cli, ["addroute", "orders", ".", "--diff"] + ) + + assert result.exit_code == 1, result.output + assert "Unknown route layout" in _flat(result.output) + + def test_write_failure(self, project: Path) -> None: + with patch( + "fastapi_fastkit.cli.add_new_route", + side_effect=BackendExceptions("disk full"), + ): + result = CliRunner().invoke( + fastkit_cli, ["addroute", "orders", "."], input="Y\n" + ) + + assert result.exit_code == 1, result.output + assert "disk full" in _flat(result.output) + + def test_unknown_layout_option_is_a_usage_error(self, project: Path) -> None: + result = CliRunner().invoke( + fastkit_cli, ["addroute", "orders", ".", "--layout", "flat"] + ) + + # Click rejects a value outside --layout's choices as a usage error. + assert result.exit_code == 2, result.output + assert "flat" in result.output + + def test_confirmation_at_end_of_input_aborts(self, project: Path) -> None: + before = snapshot(project) + result = CliRunner().invoke(fastkit_cli, ["addroute", "orders", "."]) + + assert result.exit_code == 1, result.output + assert "Aborted" in result.output + assert "Error during route addition" not in result.output + assert snapshot(project) == before + + +class TestAddrouteNonErrorsExit0: + def test_declined_confirmation(self, project: Path) -> None: + before = snapshot(project) + result = CliRunner().invoke( + fastkit_cli, ["addroute", "orders", "."], input="N\n" + ) + + assert result.exit_code == 0, result.output + assert "Operation cancelled" in _flat(result.output) + assert snapshot(project) == before + + @pytest.mark.parametrize("flag", ["--dry-run", "--diff"]) + def test_preview(self, project: Path, flag: str) -> None: + result = CliRunner().invoke(fastkit_cli, ["addroute", "orders", ".", flag]) + + assert result.exit_code == 0, result.output + assert "no files were written" in _flat(result.output) + + def test_nothing_to_do(self, project: Path) -> None: + runner = CliRunner() + assert ( + runner.invoke( + fastkit_cli, ["addroute", "orders", "."], input="Y\n" + ).exit_code + == 0 + ) + + result = runner.invoke(fastkit_cli, ["addroute", "orders", "."]) + + assert result.exit_code == 0, result.output + assert "nothing to do" in _flat(result.output) + + +class TestAddrouteWithClosedStdin: + def test_invalid_route_name_exits_1(self, project: Path) -> None: + result = _run_closed_stdin(project, "addroute", "1orders", ".") + + assert result.returncode == 1, result.stdout + assert "not a valid Python identifier" in _flat(result.stdout) + assert "Traceback" not in result.stdout + + def test_not_a_fastkit_project_exits_1(self, tmp_path: Path) -> None: + result = _run_closed_stdin(tmp_path, "addroute", "orders", ".") + + assert result.returncode == 1, result.stdout + assert "not a FastAPI-fastkit project" in _flat(result.stdout) + + def test_confirmation_without_terminal_is_not_success(self, project: Path) -> None: + before = snapshot(project) + result = _run_closed_stdin(project, "addroute", "orders", ".") + + assert result.returncode == 1, result.stdout + assert "Traceback" not in result.stdout + assert snapshot(project) == before + + def test_preview_exits_0(self, project: Path) -> None: + result = _run_closed_stdin(project, "addroute", "orders", ".", "--dry-run") + + assert result.returncode == 0, result.stdout + assert "no files were written" in _flat(result.stdout) diff --git a/tests/test_cli_operations/test_cli_addroute_preview.py b/tests/test_cli_operations/test_cli_addroute_preview.py new file mode 100644 index 0000000..fb384aa --- /dev/null +++ b/tests/test_cli_operations/test_cli_addroute_preview.py @@ -0,0 +1,147 @@ +# -------------------------------------------------------------------------- +# ``fastkit addroute --dry-run / --diff / --entity``. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +from pathlib import Path +from typing import Dict + +import pytest +from click.testing import CliRunner + +from fastapi_fastkit.backend.route_generators import plan_new_route +from fastapi_fastkit.backend.route_plan import PlannedFile +from fastapi_fastkit.cli import fastkit_cli +from tests.test_backends.test_route_generators import make_project, snapshot + + +@pytest.fixture +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + make_project(tmp_path, preset="minimal") + monkeypatch.chdir(tmp_path) + return tmp_path + + +@pytest.mark.parametrize("flag", ["--dry-run", "--diff"]) +def test_preview_lists_the_plan_and_writes_nothing(project: Path, flag: str) -> None: + before = snapshot(project) + + result = CliRunner().invoke(fastkit_cli, ["addroute", "orders", ".", flag]) + + assert result.exit_code == 0, result.output + assert snapshot(project) == before + assert "Files to create" in result.output + assert " + src/app/api/routes/orders.py" in result.output + assert " + src/app/core/pagination.py" in result.output + assert " ~ src/app/api/router.py" in result.output + assert "Dry run: no files were written." in result.output + assert "Do you want to add route" not in result.output + has_diff = "+++ b/src/app/api/router.py" in result.output + assert has_diff is (flag == "--diff") + assert ("+++ b/src/app/crud/orders.py" in result.output) is (flag == "--diff") + + +def _expected_bytes(planned: PlannedFile) -> bytes: + """The bytes ``RoutePlan.apply`` writes for a planned file.""" + content = planned.content + if planned.newline == "\r\n": + content = content.replace("\n", "\r\n") + return content.encode("utf-8") + + +def _preview_new_files(output: str) -> Dict[str, str]: + """``{path: content}`` of the new files a ``--diff`` preview prints.""" + files: Dict[str, str] = {} + lines = output.splitlines() + for index, line in enumerate(lines): + if line != "--- /dev/null" or not lines[index + 1].startswith("+++ b/"): + continue + name = lines[index + 1][len("+++ b/") :] + hunk = lines[index + 2] + count = 0 if "+0,0" in hunk else int(hunk.split("+1,")[1].split()[0]) + body = lines[index + 3 : index + 3 + count] + assert all(item.startswith("+") for item in body), name + files[name] = "".join(item[1:] + "\n" for item in body) + return files + + +def test_preview_matches_what_the_real_run_writes(project: Path) -> None: + plan = plan_new_route(str(project), "orders") + planned = {plan.display(item.path): item for item in plan.created + plan.modified} + preview = CliRunner().invoke(fastkit_cli, ["addroute", "orders", ".", "--diff"]) + listed = { + line[4:] + for line in preview.output.splitlines() + if line.startswith((" + ", " ~ ")) + } + before = snapshot(project) + + result = CliRunner().invoke(fastkit_cli, ["addroute", "orders", "."], input="Y\n") + + assert result.exit_code == 0, result.output + assert "Successfully added new route 'orders'" in result.output + after = snapshot(project) + changed = { + name.replace("\\", "/") + for name, data in after.items() + if before.get(name) != data + } + # The preview lists exactly the files the real run writes ... + assert listed == set(planned) == changed + # ... the files are byte for byte what was planned ... + for name, item in planned.items(): + assert (project / name).read_bytes() == _expected_bytes(item), name + # ... and the preview printed each new file's full planned content. + shown = _preview_new_files(preview.output) + created = {plan.display(item.path): item.content for item in plan.created} + assert shown == created + + +def test_rerun_preview_reports_nothing_to_change(project: Path) -> None: + runner = CliRunner() + runner.invoke(fastkit_cli, ["addroute", "orders", "."], input="Y\n") + before = snapshot(project) + + preview = runner.invoke(fastkit_cli, ["addroute", "orders", ".", "--diff"]) + rerun = runner.invoke(fastkit_cli, ["addroute", "orders", "."]) + + assert preview.exit_code == 0 and rerun.exit_code == 0 + assert "Nothing to change" in preview.output + assert "already in place; nothing to do" in rerun.output + assert "Do you want to add route" not in rerun.output + assert snapshot(project) == before + + +def test_confirmation_table_shows_resolved_names(project: Path) -> None: + result = CliRunner().invoke( + fastkit_cli, + ["addroute", "health_checks", ".", "--dry-run"], + ) + assert "HealthCheck" in result.output + assert "HealthCheckCreate, HealthCheckUpdate, HealthCheckRead" in result.output + assert "/health_checks" in result.output + + custom = CliRunner().invoke( + fastkit_cli, + ["addroute", "people", ".", "--entity", "Member", "--dry-run"], + ) + assert "MemberCreate, MemberUpdate, MemberRead" in custom.output + + +def test_invalid_entity_is_reported_without_writing(project: Path) -> None: + before = snapshot(project) + result = CliRunner().invoke( + fastkit_cli, ["addroute", "orders", ".", "--entity", "order"], input="Y\n" + ) + assert result.exit_code == 1, result.output + assert "PascalCase" in result.output + assert "Traceback" not in result.output + assert snapshot(project) == before + + +def test_cancelled_run_writes_nothing(project: Path) -> None: + before = snapshot(project) + result = CliRunner().invoke(fastkit_cli, ["addroute", "orders", "."], input="N\n") + assert result.exit_code == 0, result.output + assert "Operation cancelled" in result.output + assert snapshot(project) == before diff --git a/tests/test_cli_operations/test_cli_config_options.py b/tests/test_cli_operations/test_cli_config_options.py index 9edb679..3575280 100644 --- a/tests/test_cli_operations/test_cli_config_options.py +++ b/tests/test_cli_operations/test_cli_config_options.py @@ -158,6 +158,26 @@ def test_init_from_config_reports_validation_errors(self, tmp_path: Path) -> Non assert "Invalid author email" in result.output assert not (tmp_path / "config-driven").exists() + @pytest.mark.parametrize("database", ["None", "MongoDB", "Redis"]) + def test_init_from_config_rejects_fastapi_users_without_sql( + self, tmp_path: Path, database: str + ) -> None: + # given + config_path = self._write_config( + tmp_path, authentication="FastAPI-Users", database={"type": database} + ) + os.chdir(tmp_path) + + # when + result = self.runner.invoke( + fastkit_cli, ["init", "--config", config_path, "--no-venv"] + ) + + # then + assert result.exit_code == 1 + assert "'FastAPI-Users' needs a SQL database" in result.output + assert not (tmp_path / "config-driven").exists() + def test_init_from_config_reports_missing_file(self, tmp_path: Path) -> None: # given os.chdir(tmp_path) @@ -324,10 +344,7 @@ def test_addroute_targets_the_domain_starter_layout(self, tmp_path: Path) -> Non assert ( "from src.app.domains.user import router as user_router" in router_content ) - assert ( - 'api_router.include_router(user_router.router, prefix="/user", tags=["user"])' - in router_content - ) + assert "api_router.include_router(user_router.router)" in router_content @pytest.mark.parametrize("route_layout", ["domain", "classic-layer"]) def test_addroute_imports_resolve_for_the_domain_starter_layout( @@ -353,20 +370,16 @@ def test_addroute_imports_resolve_for_the_domain_starter_layout( route_content = (package / "domains" / "user" / "router.py").read_text( encoding="utf-8" ) - assert ( - "from src.app.domains.user.schemas import UserCreate, UserRead" - in route_content - ) - assert ( - "from src.app.domains.user.service import UserNotFoundError, UserService" - in route_content - ) + assert "from src.app.domains.user.schemas import (" in route_content + assert "from src.app.domains.user.service import (" in route_content + assert " UserNotFoundError,\n UserService,\n" in route_content else: route_content = (package / "api" / "routes" / "user.py").read_text( encoding="utf-8" ) - assert "from src.app.crud.user import *" in route_content - assert "from src.app.schemas.user import *" in route_content + assert "from src.app.crud.user import (" in route_content + assert "from src.app.schemas.user import (" in route_content + assert "import *" not in route_content assert "" not in route_content assert "" not in route_content assert _unresolved_project_imports(project_path) == [] @@ -386,8 +399,9 @@ def test_addroute_imports_resolve_for_the_classic_layout( route_content = (project_path / "src" / "api" / "routes" / "user.py").read_text( encoding="utf-8" ) - assert "from src.crud.user import *" in route_content - assert "from src.schemas.user import *" in route_content + assert "from src.crud.user import (" in route_content + assert "from src.schemas.user import (" in route_content + assert "import *" not in route_content assert _unresolved_project_imports(project_path) == [] def test_runserver_prefers_the_recorded_app_module(self, tmp_path: Path) -> None: diff --git a/tests/test_cli_operations/test_cli_doctor.py b/tests/test_cli_operations/test_cli_doctor.py new file mode 100644 index 0000000..b34c4c5 --- /dev/null +++ b/tests/test_cli_operations/test_cli_doctor.py @@ -0,0 +1,501 @@ +# -------------------------------------------------------------------------- +# Testcases of ``fastkit doctor``: exit statuses, JSON output, --fix with +# and without confirmation, and real projects (every current template, +# and a v1.5.1-style project built from inline files). +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import json +import os +import re +import subprocess +import sys +from pathlib import Path +from typing import Any, Dict, List +from unittest.mock import patch + +import pytest +from click.testing import CliRunner, Result + +from fastapi_fastkit.backend.doctor.context import GitUnavailable, ProjectContext +from fastapi_fastkit.backend.doctor.runner import ApplyResult +from fastapi_fastkit.backend.scaffolder import ProjectScaffolder, ScaffoldOptions +from fastapi_fastkit.cli import fastkit_cli +from fastapi_fastkit.core.settings import FastkitConfig +from tests.test_backends.doctor_helpers import ( + CLEAN_PYPROJECT, + DEFAULT_METADATA, + V151_FILES, + git_init_and_commit, + make_project, + read_bytes, + requires_git, +) + +#: Problems of the v1.5.1 fixture that ``--fix`` resolves. +V151_FIXABLE = { + "gitignore-env", + "env-example-missing", + "sqlalchemy-asyncio", + "crlf-scripts", + "gitattributes-missing", + "pre-commit-python", +} +#: Problems of the v1.5.1 fixture that stay advisory. +V151_ADVISORY = { + "example-secret", + "session-secret", + "cors-credentials", + "prometheus-lifespan", +} +SECRET_VALUES = ("hunter2hunter2", "changethis", "change-me-in-production") + + +def _doctor(*args: str, input: str = "") -> Result: + return CliRunner().invoke(fastkit_cli, ["doctor", *args], input=input) + + +def _out(result: Result) -> str: + """Output with panel borders and line wrapping removed.""" + return " ".join(re.sub(r"[\u2500-\u257f]", " ", result.output).split()) + + +def _json(result: Result) -> Dict[str, Any]: + return json.loads(result.stdout) + + +def _problem_ids(document: Dict[str, Any]) -> set: + return {c["id"] for c in document["checks"] if c["status"] == "problem"} + + +@pytest.fixture +def no_git_repo(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """Make doctor see every project as outside a git work tree. + + The git runner itself is replaced, so the result does not depend on + where pytest's temporary directory lives (inside a checkout, a git + repository in a parent directory, ...). + """ + + def not_a_repository(self: ProjectContext) -> str: + raise GitUnavailable("the project is not inside a git repository") + + monkeypatch.setattr(ProjectContext, "git_root", not_a_repository) + with pytest.raises(GitUnavailable): + ProjectContext(str(tmp_path)).git_tracked(".env") + + +class TestExitCodes: + def test_clean_project_exits_0(self, tmp_path: Path, no_git_repo: None) -> None: + root = make_project(tmp_path / "p") + + result = _doctor(str(root)) + + assert result.exit_code == 0, result.output + assert "No problems found" in _out(result) + assert "env-tracked" in _out(result) # summary table lists every check + + def test_problems_exit_1(self, tmp_path: Path, no_git_repo: None) -> None: + root = make_project(tmp_path / "p", base=V151_FILES) + + result = _doctor(str(root)) + + assert result.exit_code == 1 + assert "problem(s) found" in _out(result) + assert "fastkit doctor --fix" in _out(result) + for secret in SECRET_VALUES: + assert secret not in _out(result).replace(" ", "") + + def test_default_path_is_the_current_directory( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_git_repo: None + ) -> None: + root = make_project(tmp_path / "p") + monkeypatch.chdir(root) + + assert _doctor().exit_code == 0 + + def test_missing_path_exits_2(self, tmp_path: Path) -> None: + result = _doctor(str(tmp_path / "missing")) + + assert result.exit_code == 2 + assert "is not a directory" in _out(result) + + def test_non_fastkit_directory_exits_2(self, tmp_path: Path) -> None: + (tmp_path / "pyproject.toml").write_text( + "[project]\nname = 'x'\n", encoding="utf-8" + ) + + result = _doctor(str(tmp_path)) + + assert result.exit_code == 2 + assert "not a FastAPI-fastkit project" in _out(result) + + def test_pre_metadata_project_needs_force( + self, tmp_path: Path, no_git_repo: None + ) -> None: + pyproject = CLEAN_PYPROJECT.replace(DEFAULT_METADATA, "") + root = make_project(tmp_path / "p", {"pyproject.toml": pyproject}) + + refused = _doctor(str(root)) + forced = _doctor(str(root), "--force") + + assert refused.exit_code == 2 + assert "--force" in " ".join(refused.output.split()) + assert forced.exit_code == 0, forced.output + assert "no [tool.fastapi-fastkit] metadata" in " ".join(forced.output.split()) + + def test_crashing_check_exits_2(self, tmp_path: Path, no_git_repo: None) -> None: + root = make_project(tmp_path / "p") + with patch( + "fastapi_fastkit.backend.doctor.checks_files.RequiresPythonCheck.detect", + side_effect=RuntimeError("bug"), + ): + result = _doctor(str(root)) + + assert result.exit_code == 2 + assert "could not run" in _out(result) + + +class TestJsonOutput: + def test_clean_project(self, tmp_path: Path, no_git_repo: None) -> None: + result = _doctor(str(make_project(tmp_path / "p")), "--format", "json") + + document = _json(result) + assert result.exit_code == 0 + assert document["exit_code"] == 0 + assert document["summary"]["problems"] == 0 + assert document["findings"] == [] + statuses = {c["id"]: c["status"] for c in document["checks"]} + assert statuses["env-tracked"] == "skipped" + + def test_problems_are_listed(self, tmp_path: Path, no_git_repo: None) -> None: + root = make_project(tmp_path / "p", base=V151_FILES) + + result = _doctor(str(root), "--format", "json") + + document = _json(result) + assert result.exit_code == 1 == document["exit_code"] + assert _problem_ids(document) == V151_FIXABLE | V151_ADVISORY + fixable = {f["check"] for f in document["findings"] if f["fixable"]} + assert fixable == V151_FIXABLE + for secret in SECRET_VALUES: + assert secret not in result.stdout + + def test_error_is_a_json_document(self, tmp_path: Path) -> None: + result = _doctor(str(tmp_path), "--format", "json") + + document = _json(result) + assert result.exit_code == 2 + assert document["exit_code"] == 2 + assert "not a FastAPI-fastkit project" in document["error"] + + def test_fix_needs_yes_or_dry_run(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p", base=V151_FILES) + + result = _doctor(str(root), "--format", "json", "--fix") + + assert result.exit_code == 2 + assert "--yes" in _json(result)["error"] + assert not (root / ".gitattributes").exists() + + def test_fix_dry_run_lists_diffs(self, tmp_path: Path, no_git_repo: None) -> None: + root = make_project(tmp_path / "p", base=V151_FILES) + + result = _doctor(str(root), "--format", "json", "--dry-run") + + document = _json(result) + assert result.exit_code == 1 + assert document["fix"]["dry_run"] is True + planned = {item["path"] for item in document["fix"]["planned"]} + assert {".gitattributes", ".env.example", ".gitignore"} <= planned + assert document["fix"]["applied"] == [] + assert not (root / ".gitattributes").exists() + + def test_fix_yes_reports_applied_files( + self, tmp_path: Path, no_git_repo: None + ) -> None: + root = make_project(tmp_path / "p", base=V151_FILES) + + result = _doctor(str(root), "--format", "json", "--fix", "--yes") + + document = _json(result) + assert result.exit_code == 1 + assert ".gitattributes" in document["fix"]["applied"] + assert _problem_ids(document) == V151_ADVISORY + + def test_nothing_fixable(self, tmp_path: Path, no_git_repo: None) -> None: + root = make_project(tmp_path / "p", remove=("src/main.py",)) + + result = _doctor(str(root), "--format", "json", "--fix", "--yes") + + document = _json(result) + assert result.exit_code == 1 + assert document["fix"]["planned"] == [] + + +class TestFix: + def test_yes_applies_and_rechecks(self, tmp_path: Path, no_git_repo: None) -> None: + root = make_project(tmp_path / "p", base=V151_FILES) + + result = _doctor(str(root), "--fix", "--yes") + + assert result.exit_code == 1 # advisory problems remain + assert "Planned changes" in _out(result) + assert "updated .gitattributes" in _out(result) + assert "After the fixes" in _out(result) + assert (root / ".gitattributes").is_file() + assert read_bytes(root, "scripts/run-server.sh") == ( + b"#!/usr/bin/env bash\nuvicorn src.main:app\n" + ) + example = read_bytes(root, ".env.example").decode() + assert "SECRET_KEY=\n" in example and "hunter2hunter2" not in example + for secret in SECRET_VALUES: + assert secret not in _out(result).replace(" ", "") + + again = _doctor(str(root), "--format", "json") + assert _problem_ids(_json(again)) == V151_ADVISORY + + def test_all_fixed_exits_0(self, tmp_path: Path, no_git_repo: None) -> None: + root = make_project( + tmp_path / "p", + {".gitignore": "env\n", "scripts/a.sh": b"echo\r\n"}, + remove=(".gitattributes", ".env.example"), + ) + + result = _doctor(str(root), "--fix", "--yes") + + assert result.exit_code == 0, result.output + assert "No problems found" in _out(result) + + def test_without_terminal_refuses(self, tmp_path: Path, no_git_repo: None) -> None: + root = make_project(tmp_path / "p", remove=(".gitattributes",)) + + result = _doctor(str(root), "--fix") + + assert result.exit_code == 2 + assert "Refusing to change files" in _out(result) + assert "+++ b/.gitattributes" in _out(result) # the diff is still shown + assert not (root / ".gitattributes").exists() + + def test_confirmed_interactively(self, tmp_path: Path, no_git_repo: None) -> None: + root = make_project(tmp_path / "p", remove=(".gitattributes",)) + with patch( + "fastapi_fastkit.backend.doctor.command.stdin_is_interactive", + return_value=True, + ): + result = _doctor(str(root), "--fix", input="y\n") + + assert result.exit_code == 0, result.output + assert (root / ".gitattributes").is_file() + + def test_declined_interactively(self, tmp_path: Path, no_git_repo: None) -> None: + root = make_project(tmp_path / "p", remove=(".gitattributes",)) + with patch( + "fastapi_fastkit.backend.doctor.command.stdin_is_interactive", + return_value=True, + ): + result = _doctor(str(root), "--fix", input="n\n") + + assert result.exit_code == 1 + assert "No changes were made" in _out(result) + assert not (root / ".gitattributes").exists() + + @pytest.mark.parametrize("flag", ["--dry-run", "--diff"]) + def test_dry_run_writes_nothing( + self, tmp_path: Path, no_git_repo: None, flag: str + ) -> None: + root = make_project(tmp_path / "p", base=V151_FILES) + before = {p: p.read_bytes() for p in root.rglob("*") if p.is_file()} + + result = _doctor(str(root), "--fix", flag) + + assert result.exit_code == 1 + assert "Dry run" in _out(result) + assert "--- /dev/null" in _out(result) + assert "create .env.example" in _out(result) + assert "convert scripts/run-server.sh from CRLF to LF" in _out(result) + after = {p: p.read_bytes() for p in root.rglob("*") if p.is_file()} + assert after == before + + def test_nothing_fixable_is_explained( + self, tmp_path: Path, no_git_repo: None + ) -> None: + root = make_project(tmp_path / "p", remove=("src/main.py",)) + + result = _doctor(str(root), "--fix") + + assert result.exit_code == 1 + assert "None of the problems can be fixed automatically" in _out(result) + + def test_failed_write_is_reported(self, tmp_path: Path, no_git_repo: None) -> None: + root = make_project(tmp_path / "p", remove=(".gitattributes",)) + with patch( + "fastapi_fastkit.backend.doctor.command.apply_edits", + return_value=ApplyResult(failed=[(".gitattributes", "read-only")]), + ): + result = _doctor(str(root), "--fix", "--yes") + + assert result.exit_code == 1 + assert "Could not update .gitattributes" in _out(result) + + def test_crlf_project_keeps_line_endings( + self, tmp_path: Path, no_git_repo: None + ) -> None: + files = { + name: content.encode().replace(b"\n", b"\r\n") + for name, content in V151_FILES.items() + if isinstance(content, str) + } + root = make_project(tmp_path / "p", files, base=V151_FILES) + + result = _doctor(str(root), "--fix", "--yes") + + assert result.exit_code == 1, result.output + for name in (".gitignore", "requirements.txt", "pyproject.toml"): + data = read_bytes(root, name) + assert data.count(b"\r\n") == data.count(b"\n"), name + assert b"sqlalchemy[asyncio]" in read_bytes(root, "pyproject.toml") + + +class TestGit: + @requires_git + def test_committed_env_is_reported_not_fixed(self, tmp_path: Path) -> None: + root = make_project(tmp_path / "p") + git_init_and_commit(root, ".env", "pyproject.toml") + + result = _doctor(str(root), "--fix", "--yes", "--format", "json") + + document = _json(result) + assert result.exit_code == 1 + assert _problem_ids(document) == {"env-tracked"} + assert document["fix"]["planned"] == [] + assert "git rm --cached" in document["findings"][0]["remediation"] + + def test_non_git_directory_is_fine(self, tmp_path: Path, no_git_repo: None) -> None: + result = _doctor(str(make_project(tmp_path / "p")), "--format", "json") + + checks = {c["id"]: c for c in _json(result)["checks"]} + assert result.exit_code == 0 + assert checks["env-tracked"]["status"] == "skipped" + assert checks["env-tracked"]["note"] + + +# ---------------------------------------------------------------------- +# Projects generated by the current version +# ---------------------------------------------------------------------- + + +def _templates() -> List[str]: + root = Path(FastkitConfig().FASTKIT_TEMPLATE_ROOT) + return sorted( + d.name + for d in root.iterdir() + if d.is_dir() and d.name not in {"__pycache__", "modules"} + ) + + +@pytest.mark.parametrize("template", _templates()) +def test_current_template_has_no_problems( + template: str, tmp_path: Path, no_git_repo: None +) -> None: + # given + settings = FastkitConfig() + settings.USER_WORKSPACE = str(tmp_path) + options = ScaffoldOptions( + project_name="doctor-app", + author="bnbong", + author_email="bbbong9@gmail.com", + description="doctor smoke test", + package_manager="pip", + template=template, + with_venv=False, + with_install=False, + ) + project = ProjectScaffolder(settings, options).run().project_dir + + # when + result = _doctor(project, "--format", "json") + + # then + document = _json(result) + assert document["findings"] == [], document["findings"] + assert result.exit_code == 0 + assert document["project"]["template"] == template + + +@pytest.mark.parametrize( + "preset,auth", + [ + ("minimal", "Session-based"), + ("single-module", "OAuth2"), + ("classic-layered", "JWT"), + ("domain-starter", "Session-based"), + ], +) +def test_current_init_project_has_no_problems( + preset: str, + auth: str, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + no_git_repo: None, +) -> None: + # given: the features whose v1.5.1 output doctor reports + config = { + "project_name": "initapp", + "author": "bnbong", + "author_email": "bbbong9@gmail.com", + "description": "doctor init smoke test", + "package_manager": "uv", + "architecture_preset": preset, + "database": {"type": "PostgreSQL"}, + "authentication": {"type": auth}, + "monitoring": "Prometheus", + "tooling": ["ruff", "pre-commit"], + "deployment": ["Docker", "docker-compose"], + "utilities": ["CORS", "Pagination"], + } + config_path = tmp_path / "fastkit.config.json" + config_path.write_text(json.dumps(config), encoding="utf-8") + monkeypatch.chdir(tmp_path) + created = CliRunner().invoke( + fastkit_cli, ["init", "--config", str(config_path), "--no-venv"] + ) + assert created.exit_code == 0, created.output + + # when + result = _doctor(str(tmp_path / "initapp"), "--format", "json") + + # then + document = _json(result) + assert document["findings"] == [], document["findings"] + assert result.exit_code == 0 + + +def test_templates_are_all_covered() -> None: + assert len(_templates()) == 12 + + +# ---------------------------------------------------------------------- +# Real process, no terminal +# ---------------------------------------------------------------------- + + +def test_fix_without_terminal_in_a_child_process(tmp_path: Path) -> None: + root = make_project(tmp_path / "p", remove=(".gitattributes",)) + env = dict(os.environ, PYTHONIOENCODING="utf-8", PYTHONUTF8="1") + env["GIT_CEILING_DIRECTORIES"] = str(tmp_path) + + result = subprocess.run( + [sys.executable, "-m", "fastapi_fastkit", "doctor", str(root), "--fix"], + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + encoding="utf-8", + errors="replace", + env=env, + timeout=120, + ) + + assert result.returncode == 2, result.stdout + assert "Refusing to change files" in result.stdout + assert not (root / ".gitattributes").exists() diff --git a/tests/test_cli_operations/test_cli_error_paths.py b/tests/test_cli_operations/test_cli_error_paths.py index 6b042ff..3a3e6bc 100644 --- a/tests/test_cli_operations/test_cli_error_paths.py +++ b/tests/test_cli_operations/test_cli_error_paths.py @@ -243,7 +243,9 @@ def test_invalid_project_name_is_rejected(self, tmp_path: Path) -> None: ) # then + assert result.exit_code == 1 assert "Invalid project name" in result.output + assert not (tmp_path / "1bad-name").exists() def test_existing_project_directory_is_rejected(self, tmp_path: Path) -> None: # given @@ -268,6 +270,7 @@ def test_existing_project_directory_is_rejected(self, tmp_path: Path) -> None: ) # then + assert result.exit_code == 1 assert "already exists" in result.output @@ -280,6 +283,7 @@ def test_named_project_directory_missing_is_reported(self, tmp_path: Path) -> No result = self.runner.invoke(fastkit_cli, ["addroute", "user", "does-not-exist"]) # then + assert result.exit_code == 1 assert "does not exist" in result.output def test_named_project_not_a_fastkit_project_is_reported( @@ -293,6 +297,7 @@ def test_named_project_not_a_fastkit_project_is_reported( result = self.runner.invoke(fastkit_cli, ["addroute", "user", "plain-dir"]) # then + assert result.exit_code == 1 assert "is not a FastAPI-fastkit project" in result.output def test_non_identifier_route_name_is_rejected(self, tmp_path: Path) -> None: @@ -307,6 +312,7 @@ def test_non_identifier_route_name_is_rejected(self, tmp_path: Path) -> None: result = self.runner.invoke(fastkit_cli, ["addroute", "1-bad", "proj"]) # then + assert result.exit_code == 1 assert "not a valid Python identifier" in result.output def test_keyword_route_name_is_rejected(self, tmp_path: Path) -> None: @@ -321,6 +327,7 @@ def test_keyword_route_name_is_rejected(self, tmp_path: Path) -> None: result = self.runner.invoke(fastkit_cli, ["addroute", "class", "proj"]) # then + assert result.exit_code == 1 assert "Python keyword" in result.output def test_add_new_route_exception_is_reported(self, tmp_path: Path) -> None: @@ -340,6 +347,7 @@ def test_add_new_route_exception_is_reported(self, tmp_path: Path) -> None: ) # then + assert result.exit_code == 1 assert "Error during route addition" in result.output diff --git a/tests/test_cli_operations/test_cli_extended.py b/tests/test_cli_operations/test_cli_extended.py index 0f15b39..b5f9e56 100644 --- a/tests/test_cli_operations/test_cli_extended.py +++ b/tests/test_cli_operations/test_cli_extended.py @@ -135,15 +135,14 @@ def test_addroute_command(self, temp_dir: str) -> None: ) # then - # The command should execute without crashing (exit code 0 or 1 acceptable) - assert result.exit_code in [0, 1] - - # Check that the CLI showed the project information - assert project_name in result.output - assert route_name in result.output - - # The command might fail due to missing src directory or template files, - # but should handle it gracefully and show meaningful error messages + # The project has no src/ package: the command refuses with one plain + # error line (no traceback) and writes nothing. + assert result.exit_code == 1 + output = " ".join(result.output.split()) + assert "Error during route addition" in output + assert "Source" in output + assert "Traceback" not in result.output + assert sorted(p.name for p in project_path.iterdir()) == ["setup.py"] def test_addroute_command_cancel(self, temp_dir: str) -> None: """Test addroute command with cancellation.""" @@ -152,17 +151,26 @@ def test_addroute_command_cancel(self, temp_dir: str) -> None: project_name = "test-project" route_name = "users" - # Create a dummy project directory - project_path = Path(temp_dir) / project_name - project_path.mkdir(exist_ok=True) + # Create a minimal fastkit project with an entrypoint + project_path = Path(temp_dir) / "test-project-cancel" + (project_path / "src").mkdir(parents=True, exist_ok=True) + (project_path / "src" / "main.py").write_text( + "from fastapi import FastAPI\n\napp = FastAPI()\n", encoding="utf-8" + ) + (project_path / "setup.py").write_text( + "from setuptools import setup\n" + "setup(description='Created with FastAPI-fastkit')\n", + encoding="utf-8", + ) # when result = self.runner.invoke( - fastkit_cli, ["addroute", route_name, project_name], input="N" + fastkit_cli, ["addroute", route_name, project_path.name], input="N" ) # then assert "Operation cancelled" in result.output or "Aborted" in result.output + assert not (project_path / "src" / "api").exists() def test_startdemo_with_different_templates(self, temp_dir: str) -> None: """Test startdemo with different template types.""" @@ -300,8 +308,9 @@ def test_startdemo_invalid_template(self, temp_dir: str) -> None: ) # then - # Should handle invalid template gracefully - assert result.exit_code in [0, 1] + # Refused: an unknown template is a failure, reported without a traceback + assert result.exit_code == 1 + assert result.exception is None or isinstance(result.exception, SystemExit) def test_init_with_existing_directory(self, temp_dir: str) -> None: """Test init command when directory already exists.""" diff --git a/tests/test_cli_operations/test_cli_interactive_integration.py b/tests/test_cli_operations/test_cli_interactive_integration.py index 9e70cf7..8e38032 100644 --- a/tests/test_cli_operations/test_cli_interactive_integration.py +++ b/tests/test_cli_operations/test_cli_interactive_integration.py @@ -3,6 +3,7 @@ # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- +import ast import os from pathlib import Path from typing import Any @@ -256,11 +257,14 @@ def mock_subprocess_side_effect(*args: Any, **kwargs: Any) -> MagicMock: # roots the application package at ``src/app``. for relative, marker in ( ("src/app/worker.py", "Celery("), - ("src/app/features/tasks.py", "/api/v1/tasks"), + # Feature routers carry only their resource prefix; main.py + # mounts them under settings.API_V1_PREFIX (checked below). + ("src/app/features/tasks.py", 'APIRouter(prefix="/tasks", tags=["tasks"])'), ("src/app/features/cache.py", "@cache(expire=60)"), ("src/app/logging_config.py", "class RequestIDMiddleware"), ("src/app/core/database.py", "sqlalchemy"), - ("src/app/core/auth.py", "JWT"), + ("src/app/domains/auth/router.py", '"/token",'), + ("src/app/domains/auth/security.py", "import jwt"), ("alembic/env.py", "async_engine_from_config"), ("alembic.ini", "script_location = alembic"), ("scripts/migrate.sh", "alembic upgrade"), @@ -272,6 +276,23 @@ def mock_subprocess_side_effect(*args: Any, **kwargs: Any) -> MagicMock: encoding="utf-8" ), f"{relative} missing {marker!r}" + tasks_source = (project_path / "src/app/features/tasks.py").read_text( + encoding="utf-8" + ) + assert "/api/v1" not in tasks_source + main_statements = { + ast.unparse(node) + for node in ast.parse( + (project_path / "src/app/main.py").read_text(encoding="utf-8") + ).body + } + for statement in ( + "app.include_router(tasks_router, prefix=settings.API_V1_PREFIX)", + "app.include_router(auth_router, prefix=settings.API_V1_PREFIX)", + "Instrumentator().instrument(app).expose(app, tags=['monitoring'])", + ): + assert statement in main_statements, statement + # ruff was selected, so its configuration belongs in pyproject.toml. assert "[tool.ruff]" in (project_path / "pyproject.toml").read_text( encoding="utf-8" @@ -637,44 +658,27 @@ def _mock_subprocess(*args: Any, **kwargs: Any) -> MagicMock: f"content head:\n{main_text[:400]}" ) - # Compatibility warnings only fire on preserve-main presets, and - # only for selections whose dynamic main.py overlay isn't applied. - # CORS is pre-wired in the shipped main.py for both preserve-main - # presets, so the warning must NOT mention it — it should mention - # Prometheus (selected above) which truly does need manual wiring. - if regenerates_main: - assert "Preset compatibility" not in result.output, ( - f"[{suffix}] unexpected compatibility warning. " - f"output:\n{result.output}" - ) - else: - assert "Preset compatibility" in result.output, ( - f"[{suffix}] expected a 'Preset compatibility' warning for " - f"Prometheus on a preserve-main preset.\n" - f"output:\n{result.output}" - ) - assert "Prometheus" in result.output, ( - f"[{suffix}] warning must list Prometheus.\n" - f"output:\n{result.output}" - ) - # The warning's "affected selections" line lists each affected - # feature individually; CORS must not appear there because it - # is already wired in the shipped main.py. - warning_section = result.output.split("Preset compatibility", 1)[1] - affected_line = next( - ( - line - for line in warning_section.splitlines() - if "Affected selections" in line - ), - "", - ) - assert affected_line, ( - f"[{suffix}] expected an 'Affected selections' line.\n" - f"output:\n{result.output}" - ) - assert "CORS" not in affected_line, ( - f"[{suffix}] CORS must NOT appear in the affected-selections " - f"line — it is pre-wired in the shipped main.py.\n" - f"output:\n{result.output}" + # Nothing selected here needs manual wiring on any preset: the + # regenerated main.py includes Prometheus itself, and preserve-main + # presets get it spliced in at module level through the anchors + # (CORS is already wired in their shipped main.py). + assert "Preset compatibility" not in result.output, ( + f"[{suffix}] unexpected compatibility warning. " f"output:\n{result.output}" + ) + module_level = [ast.unparse(node) for node in ast.parse(main_text).body] + assert ( + "Instrumentator().instrument(app).expose(app, tags=['monitoring'])" + in module_level + ), ( + f"[{suffix}] Prometheus is not instrumented at module level.\n" + f"{main_text}" + ) + assert main_text.index("app = FastAPI(") < main_text.index("Instrumentator()") + if not regenerates_main: + assert "Wired generated features into" in result.output + wired_line = next( + line + for line in result.output.splitlines() + if "Wired generated features into" in line ) + assert "Prometheus" in wired_line and "CORS" not in wired_line diff --git a/tests/test_cli_operations/test_cli_startdemo_exit_codes.py b/tests/test_cli_operations/test_cli_startdemo_exit_codes.py new file mode 100644 index 0000000..97cb4f0 --- /dev/null +++ b/tests/test_cli_operations/test_cli_startdemo_exit_codes.py @@ -0,0 +1,163 @@ +# -------------------------------------------------------------------------- +# Testcases of ``fastkit startdemo`` exit statuses: refusals and failures +# exit with 1 like ``init``; declining a confirmation exits with 0. +# +# @author bnbong bbbong9@gmail.com +# -------------------------------------------------------------------------- +import os +import re +import subprocess +import sys +from pathlib import Path +from typing import List +from unittest.mock import patch + +import pytest +from click.testing import CliRunner + +from fastapi_fastkit.cli import fastkit_cli +from fastapi_fastkit.core.exceptions import BackendExceptions + +IDENTITY = [ + "--author", + "bnbong", + "--author-email", + "bbbong9@gmail.com", + "--description", + "exit status test", + "--package-manager", + "pip", +] + + +def _flat(text: str) -> str: + """Output with panel borders and line wrapping removed.""" + return " ".join(re.sub(r"[\u2500-\u257f]", " ", text).split()) + + +def _startdemo_args(template: str, name: str) -> List[str]: + return ["startdemo", template, "--project-name", name, *IDENTITY] + + +def _run_closed_stdin(cwd: Path, *args: str) -> "subprocess.CompletedProcess[str]": + env = dict(os.environ, PYTHONIOENCODING="utf-8", PYTHONUTF8="1") + return subprocess.run( + [sys.executable, "-m", "fastapi_fastkit", *args], + cwd=str(cwd), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + encoding="utf-8", + errors="replace", + env=env, + timeout=120, + ) + + +class TestStartdemoRefusalsWithClosedStdin: + def test_unknown_template(self, tmp_path: Path) -> None: + result = _run_closed_stdin(tmp_path, *_startdemo_args("no-such", "demo")) + + assert result.returncode == 1, result.stdout + assert "does not exist" in _flat(result.stdout) + assert "Traceback" not in _flat(result.stdout) + + def test_invalid_project_name(self, tmp_path: Path) -> None: + result = _run_closed_stdin( + tmp_path, *_startdemo_args("fastapi-default", "1bad") + ) + + assert result.returncode == 1, result.stdout + assert "Invalid project name" in _flat(result.stdout) + assert not (tmp_path / "1bad").exists() + + def test_existing_project_directory(self, tmp_path: Path) -> None: + (tmp_path / "taken").mkdir() + (tmp_path / "taken" / "keep.txt").write_text("mine", encoding="utf-8") + + result = _run_closed_stdin( + tmp_path, *_startdemo_args("fastapi-default", "taken") + ) + + assert result.returncode == 1, result.stdout + assert "already exists" in _flat(result.stdout) + assert os.listdir(tmp_path / "taken") == ["keep.txt"] + + def test_confirmation_without_terminal_is_not_success(self, tmp_path: Path) -> None: + result = _run_closed_stdin( + tmp_path, *_startdemo_args("fastapi-default", "nostdin") + ) + + assert result.returncode != 0, result.stdout + assert not (tmp_path / "nostdin").exists() + + +class TestStartdemoExitCodes: + @pytest.fixture(autouse=True) + def _workspace(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.chdir(tmp_path) + self.workspace = tmp_path + + def test_in_place_overwrite_without_terminal_exits_1(self) -> None: + (self.workspace / "README.md").write_text("mine\n", encoding="utf-8") + + # proceed: yes; create a project folder: no (deploy in place) + result = CliRunner().invoke( + fastkit_cli, + [*_startdemo_args("fastapi-default", "inplace"), "--no-venv"], + input="y\nn\n", + ) + + assert result.exit_code == 1, result.output + assert "--yes" in _flat(result.output) + assert (self.workspace / "README.md").read_text(encoding="utf-8") == "mine\n" + + def test_declined_overwrite_exits_0(self) -> None: + (self.workspace / "README.md").write_text("mine\n", encoding="utf-8") + + with patch( + "fastapi_fastkit.backend.scaffolder.stdin_is_interactive", + return_value=True, + ): + result = CliRunner().invoke( + fastkit_cli, + [*_startdemo_args("fastapi-default", "inplace"), "--no-venv"], + input="y\nn\nn\n", + ) + + assert result.exit_code == 0, result.output + assert "aborted" in _flat(result.output).lower() + assert (self.workspace / "README.md").read_text(encoding="utf-8") == "mine\n" + + def test_declined_confirmation_exits_0(self) -> None: + result = CliRunner().invoke( + fastkit_cli, _startdemo_args("fastapi-default", "declined"), input="n\n" + ) + + assert result.exit_code == 0 + assert "Project creation aborted!" in _flat(result.output) + assert not (self.workspace / "declined").exists() + + def test_generation_failure_exits_1(self) -> None: + with patch( + "fastapi_fastkit.cli.ProjectScaffolder.run", + side_effect=BackendExceptions("disk full"), + ): + result = CliRunner().invoke( + fastkit_cli, + [*_startdemo_args("fastapi-default", "broken"), "--no-venv"], + input="y\ny\n", + ) + + assert result.exit_code == 1 + assert "disk full" in _flat(result.output) + + def test_success_exits_0(self) -> None: + result = CliRunner().invoke( + fastkit_cli, + [*_startdemo_args("fastapi-default", "works"), "--no-venv"], + input="y\ny\n", + ) + + assert result.exit_code == 0, result.output + assert (self.workspace / "works" / "pyproject.toml").is_file() diff --git a/tests/test_core.py b/tests/test_core.py index 78fedf8..f8cc64a 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -336,11 +336,23 @@ def test_settings_user_workspace_initialization(self) -> None: assert len(workspace) > 0 assert os.path.exists(workspace) - def test_settings_error_handling_for_missing_template_files(self) -> None: + def test_settings_error_handling_for_missing_template_files( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: """Test error handling when template files are missing.""" # given from fastapi_fastkit.core.settings import FastkitConfig + # FastkitConfig() writes these class attributes, which every other + # test reads through the shared ``settings``: restore them afterwards. + for name in ( + "FASTKIT_PROJECT_ROOT", + "FASTKIT_TEMPLATE_ROOT", + "LOG_FILE_PATH", + "USER_WORKSPACE", + ): + monkeypatch.setattr(FastkitConfig, name, getattr(FastkitConfig, name)) + # Mock pathlib to simulate missing files with patch("pathlib.Path.exists", return_value=False): with patch("fastapi_fastkit.core.settings.Path") as mock_path: diff --git a/tests/test_templates/test_domain_starter_e2e.py b/tests/test_templates/test_domain_starter_e2e.py index 1bbd9a1..1bc5312 100644 --- a/tests/test_templates/test_domain_starter_e2e.py +++ b/tests/test_templates/test_domain_starter_e2e.py @@ -12,7 +12,7 @@ # - exercise the full ``fastkit startdemo fastapi-domain-starter`` flow # once and pin down what the generated artefact must contain; # - import the generated app inside its own ``.venv`` and verify -# ``GET /api/v1/health`` actually responds 200. +# ``GET /health`` (application root) actually responds 200. # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- @@ -228,16 +228,15 @@ def test_generated_app_serves_health_endpoint( f"startdemo did not provision a uv venv." ) - # Tiny driver script: import the app, hit /api/v1/health, write + # Tiny driver script: import the app, hit /health, write # status code + body to stdout. Keep this to one process so we # don't have to bring up an HTTP server. driver = ( "import sys\n" "from fastapi.testclient import TestClient\n" "from src.app.main import app\n" - "from src.app.core.config import settings\n" "client = TestClient(app)\n" - "r = client.get(f'{settings.API_V1_PREFIX}/health')\n" + "r = client.get('/health')\n" "sys.stdout.write(f'{r.status_code}|{r.text}')\n" ) @@ -255,10 +254,8 @@ def test_generated_app_serves_health_endpoint( ) status_str, _, body = completed.stdout.partition("|") - assert ( - status_str == "200" - ), f"/api/v1/health returned {status_str!r}; body: {body!r}" - assert "ok" in body, f"/api/v1/health body must mention 'ok'; got: {body!r}" + assert status_str == "200", f"/health returned {status_str!r}; body: {body!r}" + assert body == '{"status":"ok"}', f"unexpected /health body: {body!r}" # -------------------------------------------------------------------------- diff --git a/tests/test_templates/test_feature_route_collisions.py b/tests/test_templates/test_feature_route_collisions.py index 74d8999..1cf6708 100644 --- a/tests/test_templates/test_feature_route_collisions.py +++ b/tests/test_templates/test_feature_route_collisions.py @@ -11,8 +11,10 @@ # template serves. This guards against feature fragments shadowing an API # the base template already ships, such as the pagination demo on # ``GET /api/v1/items`` that used to be mounted in front of the -# domain-starter items domain. Presets whose base template ships an items -# collection now get ``add_pagination(app)`` without the demo router. +# domain-starter items domain. It also pins the v2.0.0 layout: feature +# routers carry only their resource prefix and are mounted under the +# preset's ``API_V1_PREFIX``; probes, ``/metrics`` and ``/ws`` stay at the +# root. # # @author bnbong bbbong9@gmail.com # -------------------------------------------------------------------------- @@ -43,9 +45,7 @@ "websocket": "WS", } -_PAGINATION_PATH = "/api/v1/items" - -#: Presets whose base template ships an items collection (no pagination demo). +#: Presets whose base template ships an items collection. _SHIPS_ITEMS = {"classic-layered", "domain-starter"} #: ``(module, attribute)`` naming one router (or the ``FastAPI`` app). @@ -290,10 +290,28 @@ def _overlaps(left: str, right: str) -> bool: ) +def _more_specific(first: str, later: str) -> bool: + """``first`` has a literal wherever ``later`` differs (``/me`` vs ``/{id}``). + + FastAPI tries routes in the order they were added, so a literal route + added before a parametrised one is answered first and the parametrised + route still serves every other value: the documented ``/users/me`` + pattern, not a collision. + """ + first_parts = first.rstrip("/").split("/") + later_parts = later.rstrip("/").split("/") + return first != later and all( + a == b or (not _PARAM.match(a) and _PARAM.match(b)) + for a, b in zip(first_parts, later_parts) + ) + + def _collisions(routes: List[Tuple[str, str, str]]) -> List[str]: found = [] for index, (method, path, owner) in enumerate(routes): for other_method, other_path, other_owner in routes[index + 1 :]: + if _more_specific(path, other_path): + continue if method == other_method and _overlaps(path, other_path): found.append( f"{method} {path} ({owner}) vs {other_path} ({other_owner})" @@ -304,6 +322,7 @@ def _collisions(routes: List[Tuple[str, str, str]]) -> List[str]: def _base_config(preset: str) -> Dict[str, object]: """The preset with nothing that registers a route of its own.""" config = _route_config(preset, "JWT") + config["authentication"] = {"type": "None"} config["utilities"] = [] config["async_tasks"] = {"type": "None"} config["caching"] = {"type": "None"} @@ -314,10 +333,10 @@ def _base_config(preset: str) -> Dict[str, object]: def _is_generated_feature(owner: str) -> bool: """Routers fastkit generates for a feature (not the template, not main).""" module = owner.split(":", 1)[0] - return ".features." in module or module.endswith((".auth", ".main")) + return ".features." in module or module.endswith((".auth.router", ".main")) -@pytest.mark.parametrize("auth", ["Session-based", "OAuth2"]) +@pytest.mark.parametrize("auth", ["JWT", "Session-based", "OAuth2"]) @pytest.mark.parametrize("preset", PresetLayoutStrategist.supported_presets()) def test_generated_routes_do_not_collide( preset: str, auth: str, tmp_path: Path @@ -328,23 +347,29 @@ def test_generated_routes_do_not_collide( # when routes = _mounted_routes(project) - # then: the resolver actually reached the generated feature routers + # then: the resolver actually reached the generated feature routers, + # business routes are versioned and infrastructure stays at the root pairs = {(method, path) for method, path, _ in routes} - assert ("POST", "/api/v1/tasks") in pairs, sorted(pairs) - assert ("WS", "/ws") in pairs, sorted(pairs) - pagination_owners = [ - owner for _, _, owner in routes if owner.endswith("features.pagination:router") - ] + for expected in ( + ("POST", "/api/v1/tasks"), + ("GET", "/api/v1/tasks/{task_id}"), + ("GET", "/api/v1/cache/expensive"), + ("GET", "/api/v1/connections"), + ("WS", "/ws"), + ("GET", "/health"), + ("GET", "/ready"), + ("GET", "/metrics"), + ("GET", "/api/v1/users/me"), + ("POST", "/api/v1/auth/logout" if auth != "JWT" else "/api/v1/auth/token"), + ): + assert expected in pairs, (expected, sorted(pairs)) + generated = [path for _, path, owner in routes if ".features." in owner] + assert all( + path.startswith("/api/v1/") or path in ("/ws", "/ready") for path in generated + ), generated + assert not any("pagination" in owner for _, _, owner in routes) if preset in _SHIPS_ITEMS: - # the template's own items list is served, no demo router is mounted - assert pagination_owners == [] - else: - assert len(pagination_owners) == 1 - if preset == "classic-layered": - assert ("GET", "/items") in pairs, sorted(pairs) - else: - # the demo (minimal, single-module) or the domain-starter items list - assert ("GET", _PAGINATION_PATH) in pairs, sorted(pairs) + assert ("GET", "/api/v1/items") in pairs, sorted(pairs) # and no two mounted routes compete for the same request assert _collisions(routes) == [] @@ -378,10 +403,8 @@ def test_no_generated_router_claims_a_base_template_route( @pytest.mark.parametrize("preset", PresetLayoutStrategist.supported_presets()) -def test_pagination_demo_only_for_presets_without_an_items_api( - preset: str, tmp_path: Path -) -> None: - # given +def test_pagination_selection_generates_no_router(preset: str, tmp_path: Path) -> None: + # given: a saved config that still selects Pagination config = _route_config(preset, "JWT") config["utilities"] = ["Pagination"] config_path = tmp_path / "fastkit.config.json" @@ -395,25 +418,24 @@ def test_pagination_demo_only_for_presets_without_an_items_api( fastkit_cli, ["init", "--config", str(config_path), "--no-venv", "--dry-run"], ) + real = CliRunner().invoke( + fastkit_cli, ["init", "--config", str(config_path), "--no-venv"] + ) finally: os.chdir(previous) - project = _generate(config, tmp_path) + project = tmp_path / str(config["project_name"]) - # then: the plan and the generated files agree + # then: it is accepted, explained once, and generates no demo router assert dry.exit_code == 0, dry.output - demo_files = list(project.rglob("features/pagination.py")) + assert real.exit_code == 0, real.output + assert " ".join(real.output.split()).count("paginated by default") == 1 main_text = ( project / PresetLayoutStrategist(preset).profile.main_py_relpath ).read_text(encoding="utf-8") - assert "add_pagination(app)" in main_text - if preset in _SHIPS_ITEMS: - assert demo_files == [] - assert "pagination.py" not in dry.output - assert "pagination_router" not in main_text - # the hint follows the template's own routers, which it applies to - assert main_text.rstrip().endswith("add_pagination(app)") - assert "Page[" in main_text - else: - assert len(demo_files) == 1 - assert "pagination.py" in dry.output - assert "app.include_router(pagination_router)" in main_text + assert "pagination" not in main_text + assert list(project.rglob("features/pagination.py")) == [] + assert "fastapi-pagination" not in (project / "pyproject.toml").read_text( + encoding="utf-8" + ) + # every preset has the shared Page model for list endpoints + assert list(project.rglob("core/pagination.py")) From d33cf319005b28354dadd476396c4d0ddcae6a79 Mon Sep 17 00:00:00 2001 From: bnbong Date: Wed, 2 Dec 2026 11:15:23 +0900 Subject: [PATCH 3/4] [FEAT, TEMPLATE, DOCS] add fastapi-hello, multi-database sqlmodel, remove three templates --- CHANGELOG.md | 26 +- Makefile | 2 +- README.md | 14 +- docs/de/contributing/development-setup.md | 4 +- docs/de/index.md | 40 +- docs/de/reference/faq.md | 32 +- .../reference/template-quality-assurance.md | 18 +- docs/de/tutorial/async-crud-api.md | 665 --------- docs/de/tutorial/basic-api-server.md | 7 +- docs/de/tutorial/custom-response-handling.md | 2 +- docs/de/tutorial/database-integration.md | 1028 -------------- docs/de/tutorial/docker-deployment.md | 1178 ---------------- docs/de/tutorial/domain-starter.md | 2 +- docs/de/tutorial/first-project.md | 2 +- docs/de/tutorial/sqlmodel.md | 2 +- docs/de/user-guide/choosing-a-starter.md | 19 +- docs/de/user-guide/cli-reference.md | 44 +- docs/de/user-guide/using-templates.md | 261 +--- docs/en/contributing/development-setup.md | 4 +- docs/en/index.md | 55 +- docs/en/reference/faq.md | 36 +- docs/en/reference/preset-feature-matrix.md | 4 +- .../reference/template-quality-assurance.md | 18 +- docs/en/reference/translation-status.md | 42 +- docs/en/tutorial/async-crud-api.md | 565 -------- docs/en/tutorial/basic-api-server.md | 7 +- docs/en/tutorial/custom-response-handling.md | 2 +- docs/en/tutorial/database-integration.md | 1041 -------------- docs/en/tutorial/docker-deployment.md | 1205 ----------------- docs/en/tutorial/domain-starter.md | 4 +- docs/en/tutorial/first-project.md | 2 +- docs/en/tutorial/getting-started.md | 2 +- docs/en/tutorial/sqlmodel.md | 44 +- docs/en/user-guide/choosing-a-starter.md | 41 +- docs/en/user-guide/cli-reference.md | 103 +- docs/en/user-guide/creating-projects.md | 1 + docs/en/user-guide/installation.md | 30 +- docs/en/user-guide/using-templates.md | 277 +--- docs/es/contributing/development-setup.md | 4 +- docs/es/index.md | 40 +- docs/es/reference/faq.md | 32 +- .../reference/template-quality-assurance.md | 18 +- docs/es/tutorial/async-crud-api.md | 665 --------- docs/es/tutorial/basic-api-server.md | 7 +- docs/es/tutorial/custom-response-handling.md | 2 +- docs/es/tutorial/database-integration.md | 1027 -------------- docs/es/tutorial/docker-deployment.md | 1177 ---------------- docs/es/tutorial/domain-starter.md | 2 +- docs/es/tutorial/first-project.md | 2 +- docs/es/tutorial/sqlmodel.md | 4 +- docs/es/user-guide/choosing-a-starter.md | 19 +- docs/es/user-guide/cli-reference.md | 46 +- docs/es/user-guide/using-templates.md | 261 +--- docs/fr/contributing/development-setup.md | 4 +- docs/fr/index.md | 40 +- docs/fr/reference/faq.md | 32 +- .../reference/template-quality-assurance.md | 18 +- docs/fr/tutorial/async-crud-api.md | 665 --------- docs/fr/tutorial/basic-api-server.md | 7 +- docs/fr/tutorial/custom-response-handling.md | 2 +- docs/fr/tutorial/database-integration.md | 1027 -------------- docs/fr/tutorial/docker-deployment.md | 1177 ---------------- docs/fr/tutorial/domain-starter.md | 2 +- docs/fr/tutorial/first-project.md | 2 +- docs/fr/tutorial/sqlmodel.md | 2 +- docs/fr/user-guide/choosing-a-starter.md | 19 +- docs/fr/user-guide/cli-reference.md | 44 +- docs/fr/user-guide/using-templates.md | 261 +--- docs/ja/contributing/development-setup.md | 4 +- docs/ja/index.md | 40 +- docs/ja/reference/faq.md | 32 +- .../reference/template-quality-assurance.md | 18 +- docs/ja/tutorial/async-crud-api.md | 665 --------- docs/ja/tutorial/basic-api-server.md | 7 +- docs/ja/tutorial/custom-response-handling.md | 2 +- docs/ja/tutorial/database-integration.md | 1027 -------------- docs/ja/tutorial/docker-deployment.md | 1177 ---------------- docs/ja/tutorial/domain-starter.md | 2 +- docs/ja/tutorial/first-project.md | 2 +- docs/ja/tutorial/sqlmodel.md | 3 +- docs/ja/user-guide/choosing-a-starter.md | 22 +- docs/ja/user-guide/cli-reference.md | 45 +- docs/ja/user-guide/using-templates.md | 261 +--- docs/ko/contributing/development-setup.md | 4 +- docs/ko/index.md | 29 +- docs/ko/reference/faq.md | 32 +- .../reference/template-quality-assurance.md | 18 +- docs/ko/tutorial/async-crud-api.md | 665 --------- docs/ko/tutorial/basic-api-server.md | 7 +- docs/ko/tutorial/custom-response-handling.md | 2 +- docs/ko/tutorial/database-integration.md | 1027 -------------- docs/ko/tutorial/docker-deployment.md | 1177 ---------------- docs/ko/tutorial/domain-starter.md | 2 +- docs/ko/tutorial/first-project.md | 2 +- docs/ko/tutorial/sqlmodel.md | 4 +- docs/ko/user-guide/choosing-a-starter.md | 22 +- docs/ko/user-guide/cli-reference.md | 46 +- docs/ko/user-guide/using-templates.md | 261 +--- docs/zh/contributing/development-setup.md | 4 +- docs/zh/index.md | 40 +- docs/zh/reference/faq.md | 32 +- .../reference/template-quality-assurance.md | 18 +- docs/zh/tutorial/async-crud-api.md | 665 --------- docs/zh/tutorial/basic-api-server.md | 7 +- docs/zh/tutorial/custom-response-handling.md | 2 +- docs/zh/tutorial/database-integration.md | 1027 -------------- docs/zh/tutorial/docker-deployment.md | 1177 ---------------- docs/zh/tutorial/domain-starter.md | 2 +- docs/zh/tutorial/first-project.md | 2 +- docs/zh/tutorial/sqlmodel.md | 2 +- docs/zh/user-guide/choosing-a-starter.md | 19 +- docs/zh/user-guide/cli-reference.md | 44 +- docs/zh/user-guide/using-templates.md | 259 +--- mkdocs.yml | 3 - scripts/inspect-templates.py | 2 +- .../backend/doctor/checks_api.py | 9 +- .../backend/doctor/checks_code.py | 5 + .../backend/doctor/checks_files.py | 44 +- .../backend/doctor/checks_secrets.py | 16 + src/fastapi_fastkit/backend/doctor/context.py | 44 + src/fastapi_fastkit/backend/doctor/model.py | 4 + src/fastapi_fastkit/backend/doctor/render.py | 19 +- .../backend/interactive/prompts.py | 30 +- .../backend/interactive/selectors.py | 16 +- src/fastapi_fastkit/backend/main.py | 58 + .../backend/package_managers/base.py | 17 +- .../backend/package_managers/pdm_manager.py | 56 +- .../package_managers/poetry_manager.py | 190 ++- .../backend/package_managers/pyproject.py | 131 +- .../backend/route_generators.py | 117 +- src/fastapi_fastkit/backend/scaffolder.py | 13 + src/fastapi_fastkit/cli.py | 265 +++- .../fastapi_project_template/README.md | 7 +- .../fastapi-async-crud/.env.example-tpl | 11 - .../fastapi-async-crud/.gitattributes-tpl | 27 - .../fastapi-async-crud/.gitignore-tpl | 36 - .../fastapi-async-crud/README.md-tpl | 130 -- .../fastapi-async-crud/pyproject.toml-tpl | 86 -- .../fastapi-async-crud/requirements.txt-tpl | 39 - .../fastapi-async-crud/scripts/format.sh-tpl | 5 - .../fastapi-async-crud/scripts/lint.sh-tpl | 5 - .../scripts/run-server.sh-tpl | 8 - .../fastapi-async-crud/scripts/test.sh-tpl | 6 - .../fastapi-async-crud/src/__init__.py-tpl | 0 .../src/api/__init__.py-tpl | 0 .../fastapi-async-crud/src/api/api.py-tpl | 12 - .../fastapi-async-crud/src/api/deps.py-tpl | 16 - .../src/api/routes/__init__.py-tpl | 0 .../src/api/routes/items.py-tpl | 77 -- .../src/core/__init__.py-tpl | 0 .../fastapi-async-crud/src/core/config.py-tpl | 130 -- .../src/core/pagination.py-tpl | 37 - .../src/core/responses.py-tpl | 40 - .../src/crud/__init__.py-tpl | 0 .../fastapi-async-crud/src/crud/items.py-tpl | 136 -- .../fastapi-async-crud/src/main.py-tpl | 37 - .../src/mocks/__init__.py-tpl | 0 .../src/mocks/mock_items.json-tpl | 8 - .../src/schemas/__init__.py-tpl | 0 .../src/schemas/items.py-tpl | 41 - .../fastapi-async-crud/tests/__init__.py-tpl | 0 .../fastapi-async-crud/tests/conftest.py-tpl | 39 - .../tests/test_config.py-tpl | 194 --- .../tests/test_item_store.py-tpl | 85 -- .../tests/test_items.py-tpl | 191 --- .../fastapi-async-crud/tests/test_main.py-tpl | 59 - .../fastapi-auth-jwt/README.md-tpl | 2 +- .../fastapi-dockerized/.dockerignore-tpl | 47 - .../fastapi-dockerized/.env.example-tpl | 11 - .../fastapi-dockerized/.gitattributes-tpl | 27 - .../fastapi-dockerized/.gitignore-tpl | 36 - .../fastapi-dockerized/Dockerfile-tpl | 46 - .../fastapi-dockerized/README.md-tpl | 142 -- .../fastapi-dockerized/pyproject.toml-tpl | 86 -- .../fastapi-dockerized/requirements.txt-tpl | 37 - .../fastapi-dockerized/scripts/format.sh-tpl | 5 - .../fastapi-dockerized/scripts/lint.sh-tpl | 5 - .../scripts/run-server.sh-tpl | 8 - .../fastapi-dockerized/scripts/test.sh-tpl | 6 - .../fastapi-dockerized/src/__init__.py-tpl | 0 .../src/api/__init__.py-tpl | 0 .../fastapi-dockerized/src/api/api.py-tpl | 9 - .../fastapi-dockerized/src/api/deps.py-tpl | 16 - .../src/api/routes/__init__.py-tpl | 0 .../src/api/routes/items.py-tpl | 73 - .../src/core/__init__.py-tpl | 0 .../fastapi-dockerized/src/core/config.py-tpl | 130 -- .../src/core/pagination.py-tpl | 37 - .../src/core/responses.py-tpl | 40 - .../src/crud/__init__.py-tpl | 0 .../fastapi-dockerized/src/crud/items.py-tpl | 130 -- .../fastapi-dockerized/src/main.py-tpl | 37 - .../src/mocks/__init__.py-tpl | 0 .../src/mocks/mock_items.json-tpl | 8 - .../src/schemas/__init__.py-tpl | 0 .../src/schemas/items.py-tpl | 41 - .../fastapi-dockerized/tests/__init__.py-tpl | 0 .../fastapi-dockerized/tests/conftest.py-tpl | 37 - .../tests/test_config.py-tpl | 194 --- .../tests/test_item_store.py-tpl | 81 -- .../tests/test_items.py-tpl | 192 --- .../fastapi-dockerized/tests/test_main.py-tpl | 59 - .../fastapi-domain-starter/README.md-tpl | 2 +- .../fastapi-empty/README.md-tpl | 2 +- .../fastapi-hello/.gitignore-tpl | 19 + .../fastapi-hello/README.md-tpl | 61 + .../fastapi-hello/main.py-tpl | 54 + .../fastapi-hello/pyproject.toml-tpl | 32 + .../fastapi-hello/requirements.txt-tpl | 4 + .../fastapi-hello/tests/test_main.py-tpl | 80 ++ .../fastapi-psql-orm/.dockerignore-tpl | 49 - .../fastapi-psql-orm/.env.example-tpl | 24 - .../fastapi-psql-orm/.gitattributes-tpl | 27 - .../fastapi-psql-orm/.gitignore-tpl | 36 - .../fastapi-psql-orm/Dockerfile-tpl | 37 - .../fastapi-psql-orm/README.md-tpl | 183 --- .../fastapi-psql-orm/alembic.ini-tpl | 119 -- .../fastapi-psql-orm/docker-compose.yml-tpl | 56 - .../fastapi-psql-orm/pyproject.toml-tpl | 94 -- .../fastapi-psql-orm/requirements.txt-tpl | 45 - .../fastapi-psql-orm/scripts/format.sh-tpl | 5 - .../fastapi-psql-orm/scripts/lint.sh-tpl | 6 - .../fastapi-psql-orm/scripts/pre-start.sh-tpl | 13 - .../scripts/run-server.sh-tpl | 8 - .../fastapi-psql-orm/scripts/test.sh-tpl | 10 - .../fastapi-psql-orm/src/__init__.py-tpl | 0 .../fastapi-psql-orm/src/alembic/README-tpl | 1 - .../fastapi-psql-orm/src/alembic/env.py-tpl | 86 -- .../src/alembic/script.py.mako-tpl | 26 - ...5f2a9c1d7e3b_constrain_item_columns.py-tpl | 37 - .../bedcdc35b64a_first_alembic.py-tpl | 38 - .../fastapi-psql-orm/src/api/__init__.py-tpl | 0 .../fastapi-psql-orm/src/api/api.py-tpl | 16 - .../fastapi-psql-orm/src/api/deps.py-tpl | 28 - .../src/api/routes/__init__.py-tpl | 0 .../src/api/routes/health.py-tpl | 77 -- .../src/api/routes/items.py-tpl | 79 -- .../fastapi-psql-orm/src/core/__init__.py-tpl | 0 .../fastapi-psql-orm/src/core/config.py-tpl | 163 --- .../fastapi-psql-orm/src/core/db.py-tpl | 45 - .../src/core/pagination.py-tpl | 37 - .../src/core/responses.py-tpl | 40 - .../fastapi-psql-orm/src/crud/__init__.py-tpl | 0 .../fastapi-psql-orm/src/crud/items.py-tpl | 59 - .../fastapi-psql-orm/src/main.py-tpl | 48 - .../src/models/__init__.py-tpl | 0 .../fastapi-psql-orm/src/models/items.py-tpl | 25 - .../src/schemas/__init__.py-tpl | 0 .../fastapi-psql-orm/src/schemas/items.py-tpl | 43 - .../src/utils/__init__.py-tpl | 0 .../src/utils/backend_pre_start.py-tpl | 39 - .../src/utils/init_data.py-tpl | 23 - .../src/utils/tests_pre_start.py-tpl | 39 - .../fastapi-psql-orm/template-config.yml-tpl | 26 - .../fastapi-psql-orm/tests/__init__.py-tpl | 0 .../fastapi-psql-orm/tests/conftest.py-tpl | 123 -- .../fastapi-psql-orm/tests/test_config.py-tpl | 231 ---- .../fastapi-psql-orm/tests/test_health.py-tpl | 186 --- .../tests/test_init_data.py-tpl | 14 - .../fastapi-psql-orm/tests/test_items.py-tpl | 178 --- .../fastapi-sqlmodel/.env.example-tpl | 17 +- .../fastapi-sqlmodel/Dockerfile-tpl | 3 +- .../fastapi-sqlmodel/README.md-tpl | 76 +- .../fastapi-sqlmodel/docker-compose.yml-tpl | 61 + .../docker/mysql-init.sql-tpl | 5 + .../docker/postgres-init.sql-tpl | 4 + .../fastapi-sqlmodel/pyproject.toml-tpl | 7 + .../fastapi-sqlmodel/requirements.txt-tpl | 8 +- .../src/app/alembic/env.py-tpl | 26 +- .../versions/0001_create_items_table.py-tpl | 17 +- .../src/app/core/config.py-tpl | 16 +- .../src/app/db/session.py-tpl | 81 +- .../fastapi-sqlmodel/src/app/db/types.py-tpl | 28 +- .../fastapi-sqlmodel/src/app/db/url.py-tpl | 83 ++ .../src/app/domains/items/crud.py-tpl | 7 +- .../src/app/domains/items/models.py-tpl | 11 +- .../fastapi-sqlmodel/template-config.yml-tpl | 2 +- .../fastapi-sqlmodel/tests/conftest.py-tpl | 55 +- .../tests/test_crud_base.py-tpl | 13 + .../tests/test_database.py-tpl | 310 +++++ tests/test_backends/test_console_sizing.py | 2 +- .../test_doctor_render_status.py | 233 ++++ tests/test_backends/test_hello_template.py | 388 ++++++ .../test_backends/test_interactive_prompts.py | 46 +- tests/test_backends/test_local_env.py | 32 +- .../test_package_manager_compat.py | 514 +++++++ tests/test_backends/test_pyproject_safety.py | 4 +- tests/test_backends/test_route_plan.py | 6 - .../test_single_file_detection.py | 117 ++ .../test_template_pyproject_preparation.py | 360 +++++ tests/test_cli_operations/test_cli.py | 7 +- tests/test_cli_operations/test_cli_doctor.py | 2 +- .../test_cli_error_paths.py | 17 +- .../test_cli_operations/test_cli_extended.py | 9 +- .../test_cli_interactive_integration.py | 37 +- .../test_cli_portability.py | 2 +- .../test_cli_rough_edges.py | 360 +++++ .../test_cli_runserver_fallback.py | 136 ++ tests/test_templates/template_configs.yaml | 46 - tests/test_templates/test_all_templates.py | 16 +- .../test_generated_line_endings.py | 13 +- .../test_generated_pyproject.py | 2 +- .../test_templates/test_sqlmodel_databases.py | 86 ++ 303 files changed, 5351 insertions(+), 27972 deletions(-) delete mode 100644 docs/de/tutorial/async-crud-api.md delete mode 100644 docs/de/tutorial/database-integration.md delete mode 100644 docs/de/tutorial/docker-deployment.md delete mode 100644 docs/en/tutorial/async-crud-api.md delete mode 100644 docs/en/tutorial/database-integration.md delete mode 100644 docs/en/tutorial/docker-deployment.md delete mode 100644 docs/es/tutorial/async-crud-api.md delete mode 100644 docs/es/tutorial/database-integration.md delete mode 100644 docs/es/tutorial/docker-deployment.md delete mode 100644 docs/fr/tutorial/async-crud-api.md delete mode 100644 docs/fr/tutorial/database-integration.md delete mode 100644 docs/fr/tutorial/docker-deployment.md delete mode 100644 docs/ja/tutorial/async-crud-api.md delete mode 100644 docs/ja/tutorial/database-integration.md delete mode 100644 docs/ja/tutorial/docker-deployment.md delete mode 100644 docs/ko/tutorial/async-crud-api.md delete mode 100644 docs/ko/tutorial/database-integration.md delete mode 100644 docs/ko/tutorial/docker-deployment.md delete mode 100644 docs/zh/tutorial/async-crud-api.md delete mode 100644 docs/zh/tutorial/database-integration.md delete mode 100644 docs/zh/tutorial/docker-deployment.md delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.env.example-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.gitattributes-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.gitignore-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/pyproject.toml-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/requirements.txt-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/scripts/format.sh-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/scripts/lint.sh-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/scripts/run-server.sh-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/scripts/test.sh-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/api.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/deps.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/routes/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/routes/items.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/config.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/pagination.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/responses.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/crud/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/crud/items.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/main.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/mocks/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/mocks/mock_items.json-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/schemas/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/schemas/items.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/conftest.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_config.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_item_store.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_items.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_main.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.dockerignore-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.env.example-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.gitattributes-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.gitignore-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/Dockerfile-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/pyproject.toml-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/requirements.txt-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/scripts/format.sh-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/scripts/lint.sh-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/scripts/run-server.sh-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/scripts/test.sh-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/api.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/deps.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/routes/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/routes/items.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/config.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/pagination.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/responses.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/crud/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/crud/items.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/main.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/mocks/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/mocks/mock_items.json-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/schemas/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/schemas/items.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/conftest.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_config.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_item_store.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_items.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_main.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-hello/.gitignore-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-hello/README.md-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-hello/main.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-hello/pyproject.toml-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-hello/requirements.txt-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-hello/tests/test_main.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.dockerignore-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.env.example-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.gitattributes-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.gitignore-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/Dockerfile-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/README.md-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/alembic.ini-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/docker-compose.yml-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/pyproject.toml-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/requirements.txt-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/format.sh-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/lint.sh-tpl delete mode 100755 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/pre-start.sh-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/run-server.sh-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/test.sh-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/README-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/env.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/script.py.mako-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/versions/5f2a9c1d7e3b_constrain_item_columns.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/versions/bedcdc35b64a_first_alembic.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/api.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/deps.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/routes/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/routes/health.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/routes/items.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/config.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/db.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/pagination.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/responses.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/crud/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/crud/items.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/main.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/models/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/models/items.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/schemas/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/schemas/items.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/utils/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/utils/backend_pre_start.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/utils/init_data.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/utils/tests_pre_start.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/template-config.yml-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/__init__.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/conftest.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_config.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_health.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_init_data.py-tpl delete mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_items.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/docker-compose.yml-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/docker/mysql-init.sql-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/docker/postgres-init.sql-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/src/app/db/url.py-tpl create mode 100644 src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/tests/test_database.py-tpl create mode 100644 tests/test_backends/test_doctor_render_status.py create mode 100644 tests/test_backends/test_hello_template.py create mode 100644 tests/test_backends/test_package_manager_compat.py create mode 100644 tests/test_backends/test_single_file_detection.py create mode 100644 tests/test_backends/test_template_pyproject_preparation.py create mode 100644 tests/test_cli_operations/test_cli_rough_edges.py create mode 100644 tests/test_cli_operations/test_cli_runserver_fallback.py create mode 100644 tests/test_templates/test_sqlmodel_databases.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cd0eab..309fc12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,11 @@ ### Breaking changes -All 12 templates, the code `fastkit init` generates for its options, and `fastkit addroute` output now share one HTTP contract: +Every template except `fastapi-hello`, the code `fastkit init` generates for its options, and `fastkit addroute` output now share one HTTP contract: | | v1.5.2 | v2.0.0 | |---|---|---| -| Business routes | `/items` at the root in `fastapi-default`, `fastapi-async-crud`, `fastapi-dockerized`, `fastapi-psql-orm` and `fastapi-custom-response`; `init` auth routes at `/auth/...` | Under `API_V1_PREFIX` (default `/api/v1`), e.g. `/api/v1/items`, `/api/v1/auth/...` | +| Business routes | `/items` at the root in `fastapi-default` and `fastapi-custom-response`; `init` auth routes at `/auth/...` | Under `API_V1_PREFIX` (default `/api/v1`), e.g. `/api/v1/items`, `/api/v1/auth/...` | | Liveness | `/api/v1/health` in `fastapi-domain-starter`, `fastapi-sqlmodel`, `fastapi-auth-jwt`, `fastapi-llm-agent`; elsewhere `/health` returning `{"status": "healthy"}` | `GET /health` at the root, always `{"status": "ok"}` | | Readiness | none | `GET /ready` where a database or cache exists: 200 `{"status": "ok"}` or 503 `{"status": "unavailable"}` | | List endpoints | Plain JSON array (`fastapi-mcp`: `page` / `page_size`) | `limit` (1-100, default 20) and `offset`; body `{"items", "total", "limit", "offset"}` | @@ -21,6 +21,7 @@ All 12 templates, the code `fastkit init` generates for its options, and `fastki Every 401 carries `WWW-Authenticate`, and each project reads its configuration from one settings module that loads `.env`. +- **Removed templates:** `fastapi-async-crud`, `fastapi-dockerized` and `fastapi-psql-orm` are gone, together with their tutorials. Projects generated from them keep working, and `fastkit doctor` still recognises their example secrets. Use `fastapi-sqlmodel` (async; SQLite, PostgreSQL or MySQL) or `fastapi-default` for new projects. - **Secrets outside development:** every template and generated settings module now refuses to start with any `ENVIRONMENT` other than `development` (`staging` or `production`) and a missing, example, or shorter than 32-byte `SECRET_KEY`. In `development` an example key only warns. - **`fastapi-mcp`:** `API_V1_STR` is renamed `API_V1_PREFIX`, and the OpenAPI schema moves to `/openapi.json`. `POST /api/v1/auth/login` is removed (use `POST /api/v1/auth/token`), `/auth/me` becomes `GET /api/v1/users/me`, and `/auth/users` becomes `GET /api/v1/users` (superusers only). `/mcp-routes/*` is replaced by `GET /api/v1/mcp-server`. Only the six item operations are MCP tools. Send the MCP key as `X-MCP-API-Key` (`Authorization: Bearer ` still works) so `Authorization` can carry a user token and write tools work in API-key mode. - **`fastapi-auth-jwt`:** a rejected refresh token returns 400 `{"error": "invalid_grant"}` instead of 401; token responses add `expires_in`; `GET /api/v1/users` returns the page envelope. @@ -30,7 +31,8 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - **`init` Session-based / OAuth2:** `GET /auth/me` moves to `GET /api/v1/users/me`, and logout returns 204. - **`init` FastAPI-Users** needs PostgreSQL, MySQL or SQLite; other database choices are rejected. - **`init` WebSocket:** the connection list moves from `/api/v1/ws/connections` to `/api/v1/connections`; `/ws` is unchanged. -- **CLI:** `startdemo` exits with status 1 when it refuses to run or fails, including an in-place overwrite without a terminal or `--yes`. `addroute` exits with status 1 on errors and refuses route names that are not lower-case ASCII. +- **CLI:** `startdemo` exits with status 1 when it refuses to run or fails, including an in-place overwrite without a terminal or `--yes`. `addroute` exits with status 1 on errors and refuses route names that are not lower-case ASCII. `deleteproject` exits with status 1 when the project does not exist, is not a fastkit project or cannot be deleted (declining the confirmation still exits 0). `runserver` in a project without `.venv` exits with status 1 unless you choose to continue with the current Python. +- **`init` utilities menu:** CORS and Pagination are no longer offered, because every project includes them; the menu is now 1 = Rate-Limiting, 2 = WebSocket. Saved configs that list them still load. ### CLI @@ -38,13 +40,21 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f - `doctor --fix` shows the diff of the safe fixes and asks once (`--yes` skips the question and is required without a terminal); `--dry-run` / `--diff` only previews. `--format json` is for CI, and `--force` checks projects generated before 1.4.0. Exit status: 0 no problem left, 1 problems remain, 2 doctor could not run. - `fastkit addroute` generates a typed CRUD resource with tests in both layouts (schemas, 201 with `Location`, 204, 404, paginated list) and adds `core/pagination.py` to older projects. The domain layout is chosen when the project has a `domains/` package. New options: `--entity` (class name), `--dry-run` (list files) and `--diff` (show changes). It refuses a route whose files already exist. - `startdemo -y` also skips the creation prompt. `runserver` rejects an invalid `app_module` in `[tool.fastapi-fastkit]`. +- `startdemo` checks the template name before it asks anything, suggests close matches and points to `fastkit list-templates`; the internal template path is shown only with `--debug`. +- `runserver` in a project without `.venv` prints the commands that create it for the project's package manager (for PDM, ones that keep the `.venv` inside the project) before offering to continue. If you continue, it runs the uvicorn of the Python that runs fastkit and exits with a clear message if that Python has none. +- `addroute` on a real single-file project such as `fastapi-hello` explains how to extend it by hand instead of adding packages. Projects that keep `main.py` at the root with their code in packages are handled as before. +- `doctor` passed checks say only what was verified, with no severity, and checks that do not apply to a project (secrets, settings, `.gitattributes`) are skipped. JSON output is unchanged. +- `list-features` shows the utility and tooling options that `init` offers and lists CORS and pagination as built into every project. +- Projects created with Poetry now get a working virtual environment and install with `poetry install`; fastkit sets `package-mode = false` so Poetry installs the dependencies without packaging the application. Poetry 2 or later is required: with an older Poetry, fastkit stops before creating anything, reports the version it found and explains how to upgrade or choose another package manager. +- Projects created with PDM now get their `.venv` inside the project even when PDM is configured with `venv.in_project = false`, and `fastapi-hello` installs with PDM without being built as a package. +- `list-templates` lists templates from the simplest to the most involved, in the same order on every operating system. `fastkit --help` has a one-sentence description and a "Start here" section. ### `fastkit init` options - **JWT** generates an OAuth2 password flow: `POST /api/v1/auth/register`, `POST /api/v1/auth/token` and `GET /api/v1/users/me`, with users stored in the selected SQL database or MongoDB (in memory otherwise). - **FastAPI-Users** generates working routes (`/api/v1/auth/jwt/*`, `/api/v1/auth/register`, `/api/v1/users/*`) with tests. - **Session-based:** logout invalidates the session, sessions have an absolute lifetime (`SESSION_ABSOLUTE_MAX_AGE`), and the demo account needs `ENABLE_DEMO_USERS=true` (refused outside development). **OAuth2** requires `OAUTH_REDIRECT_BASE_URL` outside development. -- **Pagination** is built into every list endpoint, so the option does nothing and `fastapi-pagination` is no longer installed. +- **CORS and Pagination** are built into every project and no longer offered in the menu; `fastapi-pagination` is no longer installed. - **Rate-Limiting** applies `RATE_LIMIT_DEFAULT` to every route and the stricter `RATE_LIMIT_AUTH` to the auth endpoints, using `limits` instead of slowapi. - **MongoDB** uses PyMongo's async client instead of Motor. The SQL session dependency no longer commits; services commit. - `classic-layered` and `domain-starter` wire every selected feature into the template's `main.py`. @@ -53,10 +63,11 @@ Every 401 carries `WWW-Authenticate`, and each project reads its configuration f ### Templates +- New `fastapi-hello`: a single `main.py` and its tests, for people who have never written a FastAPI app. `POST /items` stores an item in memory and returns it with an id, and `GET /items/{item_id}` returns it or 404. It has no settings module and no secrets. +- `fastapi-sqlmodel` runs on SQLite, PostgreSQL or MySQL, selected by `DATABASE_URL`. Install the `postgresql` or `mysql` driver extra, start a local server with the new docker compose file, and use the migrations, which work on all three. A malformed `DATABASE_URL` is reported without echoing credentials. - `fastapi-mcp`: item reads are public; PUT and PATCH work as specified. - `fastapi-auth-jwt`: login, register and refresh are rate limited (`AUTH_RATE_LIMIT_*`); timestamps are timezone-aware (new migration); `GET /api/v1/users/{user_id}` (superusers only) is added. - `fastapi-sqlmodel`: timestamps are timezone-aware (new migration) and PUT is added. -- `fastapi-psql-orm`: tests use a separate database (`_test` or `TEST_DATABASE_URL`), and Alembic creates the schema (new migration adds column constraints). - `fastapi-llm-agent`: the SSE stream is declared in OpenAPI, the calculator tool and the conversation store are bounded (`MAX_CONVERSATIONS`, `MAX_MESSAGES_PER_CONVERSATION`), and there are hook points for authentication and rate limiting. - Templates that store items in a JSON file no longer reuse ids, write atomically, and their tests no longer overwrite the shipped data. - Unused dependencies and `setup.cfg` files are removed. Template Dockerfiles run as a non-root user and ship a `.dockerignore`. @@ -72,8 +83,9 @@ Upgrading fastkit does not change an existing project. Run `fastkit doctor` in i 1. **Clients of a regenerated project:** apply the contract changes above (paths under `/api/v1`, `/health`, the list envelope, 204 on delete). 2. **Docker:** new images set `ENVIRONMENT=production` and do not contain `.env`; pass `SECRET_KEY` (at least 32 bytes) and the other settings at run time, e.g. `docker run --env-file .env ...`. -3. **`fastapi-auth-jwt`, `fastapi-sqlmodel`, `fastapi-psql-orm` projects that adopt the new template code:** run `alembic upgrade head` for the new migration. -4. **Saved `--config` files** with the Pagination option still work. +3. **`fastapi-auth-jwt` and `fastapi-sqlmodel` projects that adopt the new template code:** run `alembic upgrade head` for the new migration. +4. **Projects from the removed templates** need no change. To move to PostgreSQL or MySQL with `fastapi-sqlmodel`, set `DATABASE_URL` and install the matching driver extra. +5. **Saved `--config` files** with the CORS or Pagination option still work. ## v1.5.2 (2026-12-01) diff --git a/Makefile b/Makefile index 3970ebc..3661f58 100644 --- a/Makefile +++ b/Makefile @@ -45,7 +45,7 @@ inspect-templates-verbose: ## Run template inspection with verbose output inspect-template: ## Inspect specific template(s) - Usage: make inspect-template TEMPLATES="template-name" @if [ -z "$(TEMPLATES)" ]; then \ echo "Usage: make inspect-template TEMPLATES=\"template-name1,template-name2\""; \ - echo "Example: make inspect-template TEMPLATES=\"fastapi-default,fastapi-async-crud\""; \ + echo "Example: make inspect-template TEMPLATES=\"fastapi-default,fastapi-hello\""; \ exit 1; \ fi python scripts/inspect-templates.py --templates "$(TEMPLATES)" diff --git a/README.md b/README.md index 389bde3..2437dab 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ fastkit init --interactive - **Caching**: Redis, fastapi-cache2 - **Monitoring**: Loguru, OpenTelemetry, Prometheus - **Testing**: Basic (pytest), Coverage, Advanced (with faker, factory-boy) - - **Utilities**: CORS, Rate-Limiting, WebSocket (Pagination is built into every list endpoint) + - **Utilities**: Rate-Limiting, WebSocket (CORS and pagination are built into every project) - **Logging**: structured JSON logging with a request-id middleware - **Migrations**: Alembic (async env, baseline revision) - **Tooling**: ruff, pre-commit, GitHub Actions, devcontainer, Makefile (multi-select) @@ -114,7 +114,8 @@ fastkit startdemo [TEMPLATE] [OPTIONS] - `--package-manager` [pip|uv|pdm|poetry] - `--dry-run`, `--no-venv`, `--no-install`, `--yes`/`-y` — same meaning as on `init` - Refuses to run if the target project directory already exists (`--dry-run` excepted), and then exits with status 1 -- Tip: List available templates with `fastkit list-templates` +- Tip: List available templates with `fastkit list-templates` (simplest first). A misspelled name suggests the closest match +- New to FastAPI? Start with `fastkit startdemo fastapi-hello`: one `main.py` with three endpoints and their tests ### Add a new route ```console @@ -154,25 +155,24 @@ Available templates: | Template | Description | Notes | |---|---|---| +| [`fastapi-hello`](src/fastapi_fastkit/fastapi_project_template/fastapi-hello/README.md-tpl) | Smallest FastAPI app: three endpoints, one pydantic model, one test file | Start here | | [`fastapi-default`](src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl) | Simple FastAPI project with a classic layered layout | Good first choice | | [`fastapi-empty`](src/fastapi_fastkit/fastapi_project_template/fastapi-empty/README.md-tpl) | Minimal FastAPI template | Base for `minimal` preset | | [`fastapi-single-module`](src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/README.md-tpl) | Single-file FastAPI app | Base for `single-module` preset | | [`fastapi-domain-starter`](src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl) | Domain-oriented, pyproject-first starter for medium-sized APIs | Base for `domain-starter` preset | | [`fastapi-auth-jwt`](src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl) | JWT authentication with refresh-token rotation, argon2 hashing and scopes | New in v1.4.0 | -| [`fastapi-sqlmodel`](src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl) | Async SQLModel + Alembic migrations + generic CRUD with pagination | New in v1.4.0 | +| [`fastapi-sqlmodel`](src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl) | Async SQLModel + Alembic migrations + generic CRUD with pagination; SQLite, PostgreSQL or MySQL through one `DATABASE_URL` | New in v1.4.0 | | [`fastapi-llm-agent`](src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl) | Streaming Claude chat agent (SSE) with a tool-call loop | New in v1.4.0 | | [`fastapi-mcp`](src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl) | FastAPI app exposed as an MCP server | | -| [`fastapi-psql-orm`](src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/README.md-tpl) | Item management API with PostgreSQL, SQLModel, Alembic and docker-compose | Requires Docker | | [`fastapi-custom-response`](src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl) | Item management API with a custom response envelope, error handling and pagination | | -| [`fastapi-async-crud`](src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl) | Async item management API | **Deprecated** — use `fastapi-sqlmodel` | -| [`fastapi-dockerized`](src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl) | Dockerized item management API | **Deprecated** — use `fastapi-default` with the Docker option in `init --interactive` | -Deprecated templates still work but are no longer recommended starting points. See [Which starter should I choose?](https://bnbong.github.io/FastAPI-fastkit/user-guide/choosing-a-starter/) for a decision guide. +See [Which starter should I choose?](https://bnbong.github.io/FastAPI-fastkit/user-guide/choosing-a-starter/) for a decision guide. ### Delete a project ```console fastkit deleteproject ``` +Exits with status 1 when the project does not exist, is not a fastkit project or cannot be deleted; declining the confirmation exits with status 0. ## Documentation diff --git a/docs/de/contributing/development-setup.md b/docs/de/contributing/development-setup.md index 9f63f89..4e43210 100644 --- a/docs/de/contributing/development-setup.md +++ b/docs/de/contributing/development-setup.md @@ -322,13 +322,11 @@ FastAPI-fastkit/ │ │ ├── fastapi_project_template/ │ │ │ ├── PROJECT_README_TEMPLATE.md # fastkit template project base README file │ │ │ ├── README.md # fastkit template README -│ │ │ ├── fastapi-async-crud/ │ │ │ ├── fastapi-custom-response/ │ │ │ ├── fastapi-default/ -│ │ │ ├── fastapi-dockerized/ │ │ │ ├── fastapi-empty/ +│ │ │ ├── fastapi-hello/ │ │ │ ├── fastapi-mcp/ -│ │ │ ├── fastapi-psql-orm/ │ │ │ ├── fastapi-single-module/ │ │ │ └── modules/ │ │ │ ├── api/ diff --git a/docs/de/index.md b/docs/de/index.md index 50ec32d..0a795d9 100644 --- a/docs/de/index.md +++ b/docs/de/index.md @@ -507,21 +507,20 @@ Um die Liste der verfügbaren FastAPI-Demos anzuzeigen, prüfen Sie mit: ```console $ fastkit list-templates Available Templates -┌────────────────────────┬───────────────────────────────────────────────────────┐ -│ fastapi-custom-response│ Async Item Management API with Custom Response System │ -│ fastapi-mcp │ FastAPI MCP Project │ -│ fastapi-domain-starter │ FastAPI Domain Starter │ -│ fastapi-dockerized │ Dockerized FastAPI Item Management API │ -│ fastapi-empty │ Minimal FastAPI Template │ -│ fastapi-async-crud │ Async Item Management API Server │ -│ fastapi-psql-orm │ Dockerized FastAPI Item Management API with │ -│ │ PostgreSQL │ -│ fastapi-default │ Simple FastAPI Project │ -│ fastapi-single-module │ FastAPI Single Module Template │ -│ fastapi-auth-jwt │ FastAPI JWT Authentication │ -│ fastapi-sqlmodel │ FastAPI SQLModel │ -│ fastapi-llm-agent │ FastAPI LLM Agent │ -└────────────────────────┴───────────────────────────────────────────────────────┘ +┌───────────────────────────┬──────────────────────────────────────────────────┐ +│fastapi-hello │ Smallest FastAPI app: three endpoints, one model,│ +│ │ their tests │ +│fastapi-empty │ Minimal FastAPI Template │ +│fastapi-single-module │ FastAPI Single Module Template │ +│fastapi-default │ Simple FastAPI Project │ +│fastapi-domain-starter │ FastAPI Domain Starter │ +│fastapi-custom-response │ Async Item Management API with Custom Response │ +│ │ System │ +│fastapi-auth-jwt │ FastAPI JWT Authentication │ +│fastapi-sqlmodel │ FastAPI SQLModel │ +│fastapi-mcp │ FastAPI MCP Project │ +│fastapi-llm-agent │ FastAPI LLM Agent │ +└───────────────────────────┴──────────────────────────────────────────────────┘ ```
@@ -530,20 +529,18 @@ Verfügbare Vorlagen: | Vorlage | Beschreibung | Hinweise | |---|---|---| +| [`fastapi-hello`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-hello/README.md-tpl) | Kleinste FastAPI-App: drei Endpunkte, ein pydantic-Modell, eine Testdatei | Hier beginnen | | [`fastapi-default`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl) | Einfaches FastAPI-Projekt mit klassischem Schichten-Layout | Gute erste Wahl | | [`fastapi-empty`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-empty/README.md-tpl) | Minimale FastAPI-Vorlage | Basis für das Preset `minimal` | | [`fastapi-single-module`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-single-module/README.md-tpl) | FastAPI-App in einer Datei | Basis für das Preset `single-module` | | [`fastapi-domain-starter`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-domain-starter/README.md-tpl) | Domänenorientierter, pyproject-first Starter für mittelgroße APIs | Basis für das Preset `domain-starter` | | [`fastapi-auth-jwt`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-auth-jwt/README.md-tpl) | JWT-Authentifizierung mit Refresh-Token-Rotation, argon2-Hashing und Scopes | Neu in v1.4.0 | -| [`fastapi-sqlmodel`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl) | Asynchrones SQLModel + Alembic-Migrationen + generisches CRUD mit Paginierung | Neu in v1.4.0 | +| [`fastapi-sqlmodel`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-sqlmodel/README.md-tpl) | Asynchrones SQLModel + Alembic-Migrationen + generisches CRUD mit Paginierung; SQLite, PostgreSQL oder MySQL über eine einzige `DATABASE_URL` | Neu in v1.4.0 | | [`fastapi-llm-agent`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-llm-agent/README.md-tpl) | Streaming-Claude-Chat-Agent (SSE) mit Tool-Call-Schleife | Neu in v1.4.0 | | [`fastapi-mcp`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-mcp/README.md-tpl) | FastAPI-App, die als MCP-Server bereitgestellt wird | | -| [`fastapi-psql-orm`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/README.md-tpl) | Item-Management-API mit PostgreSQL, SQLModel, Alembic und docker-compose | Erfordert Docker | | [`fastapi-custom-response`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl) | Item-Management-API mit eigener Antwort-Hülle, Fehlerbehandlung und Paginierung | | -| [`fastapi-async-crud`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl) | Asynchrone Item-Management-API | **Veraltet** — verwenden Sie `fastapi-sqlmodel` | -| [`fastapi-dockerized`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl) | Dockerisierte Item-Management-API | **Veraltet** — verwenden Sie `fastapi-default` mit der Docker-Option in `init --interactive` | -Veraltete Vorlagen funktionieren weiterhin, werden aber nicht mehr als Ausgangspunkt empfohlen. Eine Entscheidungshilfe finden Sie unter [Welchen Starter soll ich wählen?](user-guide/choosing-a-starter.md). +Eine Entscheidungshilfe finden Sie unter [Welchen Starter soll ich wählen?](user-guide/choosing-a-starter.md). ## Dokumentation @@ -563,15 +560,12 @@ Lernen Sie die FastAPI-Entwicklung anhand praktischer Anwendungsfälle mit unser ### 📖 Kerntutorials - **[Einen einfachen API-Server bauen](tutorial/basic-api-server.md)** — erstellen Sie Ihren ersten FastAPI-Server mit der Vorlage `fastapi-default` -- **[Eine asynchrone CRUD-API bauen](tutorial/async-crud-api.md)** — entwickeln Sie eine leistungsstarke asynchrone API mit der Vorlage `fastapi-async-crud` - **[Domänenorientiertes Projekt (Domain Starter)](tutorial/domain-starter.md)** — bauen Sie eine mittelgroße API mit der Vorlage `fastapi-domain-starter`, dem empfohlenen modernen Standard - **[JWT-Authentifizierung](tutorial/auth-jwt.md)** — fügen Sie mit der Vorlage `fastapi-auth-jwt` echte Konten hinzu: rotierende Refresh-Tokens, argon2id-Hashing, Rollen- und Scope-Guards ### 🗄️ Datenbank und Infrastruktur -- **[Integration einer Datenbank](tutorial/database-integration.md)** — nutzen Sie PostgreSQL + SQLAlchemy mit der Vorlage `fastapi-psql-orm` - **[Asynchrone Persistenz mit SQLModel](tutorial/sqlmodel.md)** — asynchrones SQLModel, Alembic-Migrationen, eine generische CRUD-Basis und paginierte Listen mit der Vorlage `fastapi-sqlmodel` -- **[Docker-Containerisierung und Deployment](tutorial/docker-deployment.md)** — richten Sie eine produktionsreife Deployment-Umgebung mit der Vorlage `fastapi-dockerized` ein *(veraltete Vorlage — für bestehende Nutzer beibehalten)* ### ⚡ Erweiterte Funktionen diff --git a/docs/de/reference/faq.md b/docs/de/reference/faq.md index b9f71db..a189c45 100644 --- a/docs/de/reference/faq.md +++ b/docs/de/reference/faq.md @@ -320,17 +320,21 @@ async def upload_file(file: UploadFile = File(...)): ```console $ fastkit list-templates - Available Templates -┌─────────────────────────┬───────────────────────────────────┐ -│ fastapi-default │ Simple FastAPI Project │ -│ fastapi-async-crud │ Async Item Management API Server │ -│ fastapi-custom-response │ Custom Response System │ -│ fastapi-dockerized │ Dockerized FastAPI API │ -│ fastapi-empty │ Minimal FastAPI Project │ -│ fastapi-mcp │ MCP (Model Context Protocol) API │ -│ fastapi-psql-orm │ PostgreSQL FastAPI API │ -│ fastapi-single-module │ Single-file FastAPI Project │ -└─────────────────────────┴───────────────────────────────────┘ + Available Templates +┌───────────────────────────┬──────────────────────────────────────────────────┐ +│fastapi-hello │ Smallest FastAPI app: three endpoints, one model,│ +│ │ their tests │ +│fastapi-empty │ Minimal FastAPI Template │ +│fastapi-single-module │ FastAPI Single Module Template │ +│fastapi-default │ Simple FastAPI Project │ +│fastapi-domain-starter │ FastAPI Domain Starter │ +│fastapi-custom-response │ Async Item Management API with Custom Response │ +│ │ System │ +│fastapi-auth-jwt │ FastAPI JWT Authentication │ +│fastapi-sqlmodel │ FastAPI SQLModel │ +│fastapi-mcp │ FastAPI MCP Project │ +│fastapi-llm-agent │ FastAPI LLM Agent │ +└───────────────────────────┴──────────────────────────────────────────────────┘ ```
@@ -344,7 +348,7 @@ $ fastkit list-templates ```console $ fastkit startdemo Enter the project name: my-blog -Select template: fastapi-psql-orm +Select template: fastapi-hello ```
@@ -447,8 +451,8 @@ $ fastkit runserver --reload $ pip install gunicorn $ gunicorn src.main:app -w 4 -k uvicorn.workers.UvicornWorker -# Or use Docker with the fastapi-dockerized template -$ fastkit startdemo # Select fastapi-dockerized +# Or use Docker with a template that ships a Dockerfile +$ fastkit startdemo fastapi-sqlmodel $ docker build -t my-app . $ docker run -p 8000:8000 my-app ``` diff --git a/docs/de/reference/template-quality-assurance.md b/docs/de/reference/template-quality-assurance.md index 44ff401..0dc6d8c 100644 --- a/docs/de/reference/template-quality-assurance.md +++ b/docs/de/reference/template-quality-assurance.md @@ -68,9 +68,7 @@ $ pytest tests/test_templates/test_all_templates.py -v # Results show all discovered templates PASSED tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[fastapi-default] -PASSED tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[fastapi-async-crud] -PASSED tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[fastapi-dockerized] -PASSED tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[fastapi-psql-orm] +PASSED tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[fastapi-hello] ``` ### Umfassende Testabdeckung @@ -163,7 +161,7 @@ Für Entwicklung und Debugging können Sie Vorlagen manuell mit unserem lokalen $ python scripts/inspect-templates.py # Inspect specific templates -$ python scripts/inspect-templates.py --templates fastapi-default,fastapi-async-crud +$ python scripts/inspect-templates.py --templates fastapi-default,fastapi-hello # Verbose output with detailed information $ python scripts/inspect-templates.py --verbose @@ -206,7 +204,7 @@ $ make inspect-templates $ make inspect-templates-verbose # Inspect specific templates -$ make inspect-template TEMPLATES="fastapi-default,fastapi-async-crud" +$ make inspect-template TEMPLATES="fastapi-default,fastapi-hello" ``` ## Ergebnisse der Inspektion @@ -220,12 +218,8 @@ $ make inspect-template TEMPLATES="fastapi-default,fastapi-async-crud" Beim Ausführen der Vorlagen-Inspektion sehen Sie eine Ausgabe wie diese: ```console -📋 Found 6 templates to inspect: fastapi-async-crud, fastapi-custom-response, fastapi-default, fastapi-dockerized, fastapi-empty, fastapi-psql-orm +📋 Found 4 templates to inspect: fastapi-custom-response, fastapi-default, fastapi-empty, fastapi-hello ============================================================ -🔍 Inspecting template: fastapi-async-crud - Path: /path/to/src/fastapi_fastkit/fastapi_project_template/fastapi-async-crud -✅ fastapi-async-crud: PASSED ----------------------------------------- 🔍 Inspecting template: fastapi-custom-response Path: /path/to/src/fastapi_fastkit/fastapi_project_template/fastapi-custom-response ✅ fastapi-custom-response: PASSED @@ -233,8 +227,8 @@ Beim Ausführen der Vorlagen-Inspektion sehen Sie eine Ausgabe wie diese: ... ============================================================ 📊 INSPECTION SUMMARY - Total templates: 6 - ✅ Passed: 6 + Total templates: 4 + ✅ Passed: 4 ❌ Failed: 0 🎉 All templates passed inspection! 📄 Results saved to: template_inspection_results.json diff --git a/docs/de/tutorial/async-crud-api.md b/docs/de/tutorial/async-crud-api.md deleted file mode 100644 index d0ae533..0000000 --- a/docs/de/tutorial/async-crud-api.md +++ /dev/null @@ -1,665 +0,0 @@ -# Asynchrone CRUD-APIs bauen - -Lernen Sie, wie Sie hochperformante CRUD-APIs mit den asynchronen Verarbeitungsmöglichkeiten von FastAPI bauen. In diesem Tutorial implementieren wir asynchrone Datei-I/O und effiziente Datenverarbeitung mit der Vorlage `fastapi-async-crud`. - -## Was Sie in diesem Tutorial lernen - -- Asynchrone FastAPI-Anwendungen verstehen -- Asynchrone CRUD-Operationen mit der `async/await`-Syntax -- Asynchrone Dateiverarbeitung mit aiofiles -- Asynchrone Tests schreiben und ausführen -- Techniken zur Leistungsoptimierung - -## Voraussetzungen - -- Das [Tutorial Einfacher API-Server](basic-api-server.md) abgeschlossen -- Verständnis der Grundkonzepte von Pythons `async/await` -- FastAPI-fastkit installiert - -## Warum asynchrone Verarbeitung nötig ist - -Verstehen wir den Unterschied zwischen synchroner und asynchroner Verarbeitung: - -### Synchrone Verarbeitung - -```python -def process_items(): - item1 = read_file("item1.json") # Wait 2 seconds - item2 = read_file("item2.json") # Wait 2 seconds - item3 = read_file("item3.json") # Wait 2 seconds - return [item1, item2, item3] # Total: 6 seconds -``` - -### Asynchrone Verarbeitung - -```python -async def process_items(): - item1_task = read_file_async("item1.json") # Start concurrently - item2_task = read_file_async("item2.json") # Start concurrently - item3_task = read_file_async("item3.json") # Start concurrently - - items = await asyncio.gather(item1_task, item2_task, item3_task) - return items # Total: 2 seconds -``` - -## Schritt 1: Ein asynchrones CRUD-Projekt erstellen - -Erstellen Sie ein Projekt mit der Vorlage `fastapi-async-crud`: - -
- -```console -$ fastkit startdemo fastapi-async-crud -Enter the project name: async-todo-api -Enter the author name: Developer Kim -Enter the author email: developer@example.com -Enter the project description: Asynchronous todo management API -Deploying FastAPI project using 'fastapi-async-crud' template - - Project Information -┌──────────────┬─────────────────────────────────────────┐ -│ Project Name │ async-todo-api │ -│ Author │ Developer Kim │ -│ Author Email │ developer@example.com │ -│ Description │ Asynchronous todo management API │ -└──────────────┴─────────────────────────────────────────┘ - - Template Dependencies -┌──────────────┬───────────────────┐ -│ Dependency 1 │ fastapi │ -│ Dependency 2 │ uvicorn │ -│ Dependency 3 │ pydantic │ -│ Dependency 4 │ pydantic-settings │ -│ Dependency 5 │ aiofiles │ -│ Dependency 6 │ pytest-asyncio │ -└──────────────┴───────────────────┘ - -Select package manager (pip, uv, pdm, poetry) [uv]: uv -Do you want to proceed with project creation? [y/N]: y - -✨ FastAPI project 'async-todo-api' from 'fastapi-async-crud' has been created successfully! -``` - -
- -## Schritt 2: Projektstruktur analysieren - -Sehen wir uns die wichtigsten Unterschiede des generierten Projekts an: - -``` -async-todo-api/ -├── src/ -│ ├── main.py # Asynchronous FastAPI application -│ ├── api/ -│ │ └── routes/ -│ │ └── items.py # Asynchronous CRUD endpoints -│ ├── crud/ -│ │ └── items.py # Asynchronous data processing logic -│ ├── schemas/ -│ │ └── items.py # Data models (same) -│ ├── mocks/ -│ │ └── mock_items.json # JSON file database -│ └── core/ -│ └── config.py # Configuration file -└── tests/ - ├── conftest.py # Asynchronous test configuration - └── test_items.py # Asynchronous test cases -``` - -### Wichtige Unterschiede - -1. **aiofiles**: asynchrone Datei-I/O-Verarbeitung -2. **pytest-asyncio**: Unterstützung für asynchrone Tests -3. **async/await-Muster**: alle CRUD-Operationen asynchron implementiert - -## Schritt 3: Die asynchrone CRUD-Logik verstehen - -### Asynchrone Datenverarbeitung (`src/crud/items.py`) - -```python -import json -import asyncio -from typing import List, Optional -from aiofiles import open as aio_open -from pathlib import Path - -from src.schemas.items import Item, ItemCreate, ItemUpdate - -class AsyncItemCRUD: - def __init__(self, data_file: str = "src/mocks/mock_items.json"): - self.data_file = Path(data_file) - - async def _read_data(self) -> List[dict]: - """Asynchronously read data from JSON file""" - try: - async with aio_open(self.data_file, 'r', encoding='utf-8') as f: - content = await f.read() - return json.loads(content) - except FileNotFoundError: - return [] - - async def _write_data(self, data: List[dict]) -> None: - """Asynchronously write data to JSON file""" - async with aio_open(self.data_file, 'w', encoding='utf-8') as f: - await f.write(json.dumps(data, indent=2, ensure_ascii=False)) - - async def get_items(self) -> List[Item]: - """Retrieve all items (asynchronous)""" - data = await self._read_data() - return [Item(**item) for item in data] - - async def get_item(self, item_id: int) -> Optional[Item]: - """Retrieve specific item (asynchronous)""" - data = await self._read_data() - item_data = next((item for item in data if item["id"] == item_id), None) - return Item(**item_data) if item_data else None - - async def create_item(self, item: ItemCreate) -> Item: - """Create new item (asynchronous)""" - data = await self._read_data() - new_id = max([item["id"] for item in data], default=0) + 1 - - new_item = Item(id=new_id, **item.dict()) - data.append(new_item.dict()) - - await self._write_data(data) - return new_item - - async def update_item(self, item_id: int, item_update: ItemUpdate) -> Optional[Item]: - """Update item (asynchronous)""" - data = await self._read_data() - - for i, item in enumerate(data): - if item["id"] == item_id: - update_data = item_update.dict(exclude_unset=True) - data[i].update(update_data) - await self._write_data(data) - return Item(**data[i]) - - return None - - async def delete_item(self, item_id: int) -> bool: - """Delete item (asynchronous)""" - data = await self._read_data() - original_length = len(data) - - data = [item for item in data if item["id"] != item_id] - - if len(data) < original_length: - await self._write_data(data) - return True - - return False -``` - -### Asynchrone API-Endpunkte (`src/api/routes/items.py`) - -```python -from typing import List -from fastapi import APIRouter, HTTPException, status - -from src.schemas.items import Item, ItemCreate, ItemUpdate -from src.crud.items import AsyncItemCRUD - -router = APIRouter() -crud = AsyncItemCRUD() - -@router.get("/", response_model=List[Item]) -async def read_items(): - """Retrieve all items (asynchronous)""" - return await crud.get_items() - -@router.get("/{item_id}", response_model=Item) -async def read_item(item_id: int): - """Retrieve specific item (asynchronous)""" - item = await crud.get_item(item_id) - if item is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item with id {item_id} not found" - ) - return item - -@router.post("/", response_model=Item, status_code=status.HTTP_201_CREATED) -async def create_item(item: ItemCreate): - """Create new item (asynchronous)""" - return await crud.create_item(item) - -@router.put("/{item_id}", response_model=Item) -async def update_item(item_id: int, item_update: ItemUpdate): - """Update item (asynchronous)""" - updated_item = await crud.update_item(item_id, item_update) - if updated_item is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item with id {item_id} not found" - ) - return updated_item - -@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT) -async def delete_item(item_id: int): - """Delete item (asynchronous)""" - deleted = await crud.delete_item(item_id) - if not deleted: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item with id {item_id} not found" - ) -``` - -## Schritt 4: Server starten und testen - -Wechseln Sie ins Projektverzeichnis und starten Sie den Server: - -
- -```console -$ cd async-todo-api -$ fastkit runserver -Starting FastAPI server at 127.0.0.1:8000... - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [12345] using WatchFiles -INFO: Started server process [12346] -INFO: Waiting for application startup. -INFO: Application startup complete. -``` - -
- -### Leistungstests - -Prüfen wir die Leistung der asynchronen Verarbeitung. Versuchen Sie, mehrere Anfragen gleichzeitig zu senden: - -**Test paralleler Anfragen (Python-Skript)** - -```python -import asyncio -import aiohttp -import time - -async def create_item(session, item_data): - async with session.post("http://127.0.0.1:8000/items/", json=item_data) as response: - return await response.json() - -async def test_concurrent_requests(): - start_time = time.time() - - items_to_create = [ - {"name": f"Item {i}", "description": f"Description {i}", "price": i * 10, "tax": i} - for i in range(1, 11) # Create 10 items concurrently - ] - - async with aiohttp.ClientSession() as session: - tasks = [create_item(session, item) for item in items_to_create] - results = await asyncio.gather(*tasks) - - end_time = time.time() - print(f"Created 10 items in: {end_time - start_time:.2f} seconds") - print(f"Number of items created: {len(results)}") - -# Run test -# asyncio.run(test_concurrent_requests()) -``` - -## Schritt 5: Asynchrone Tests schreiben - -### Test-Konfiguration (`tests/conftest.py`) - -```python -import pytest -import asyncio -from httpx import AsyncClient -from src.main import app - -@pytest.fixture(scope="session") -def event_loop(): - """Event loop configuration""" - loop = asyncio.get_event_loop_policy().new_event_loop() - yield loop - loop.close() - -@pytest.fixture -async def async_client(): - """Asynchronous test client""" - async with AsyncClient(app=app, base_url="http://test") as client: - yield client -``` - -### Asynchrone Testfälle (`tests/test_items.py`) - -```python -import pytest -from httpx import AsyncClient - -@pytest.mark.asyncio -async def test_create_item_async(async_client: AsyncClient): - """Asynchronous item creation test""" - item_data = { - "name": "Test Item", - "description": "Item for asynchronous testing", - "price": 100.0, - "tax": 10.0 - } - - response = await async_client.post("/items/", json=item_data) - - assert response.status_code == 201 - data = response.json() - assert data["name"] == item_data["name"] - assert data["price"] == item_data["price"] - assert "id" in data - -@pytest.mark.asyncio -async def test_read_items_async(async_client: AsyncClient): - """Asynchronous item list retrieval test""" - response = await async_client.get("/items/") - - assert response.status_code == 200 - items = response.json() - assert isinstance(items, list) - -@pytest.mark.asyncio -async def test_concurrent_operations(async_client: AsyncClient): - """Concurrent operations test""" - import asyncio - - # Create multiple items concurrently - tasks = [] - for i in range(5): - item_data = { - "name": f"ConcurrentItem{i}", - "description": f"Description{i}", - "price": i * 10, - "tax": i - } - task = async_client.post("/items/", json=item_data) - tasks.append(task) - - responses = await asyncio.gather(*tasks) - - # Verify all requests succeeded - for response in responses: - assert response.status_code == 201 - - # Verify created items - response = await async_client.get("/items/") - items = response.json() - assert len(items) >= 5 -``` - -### Tests ausführen - -
- -```console -$ pytest tests/ -v --asyncio-mode=auto -======================== test session starts ======================== -collected 8 items - -tests/test_items.py::test_create_item_async PASSED [ 12%] -tests/test_items.py::test_read_items_async PASSED [ 25%] -tests/test_items.py::test_read_item_async PASSED [ 37%] -tests/test_items.py::test_update_item_async PASSED [ 50%] -tests/test_items.py::test_delete_item_async PASSED [ 62%] -tests/test_items.py::test_concurrent_operations PASSED [ 75%] -tests/test_items.py::test_item_not_found_async PASSED [ 87%] -tests/test_items.py::test_invalid_item_data_async PASSED [100%] - -======================== 8 passed in 0.24s ======================== -``` - -
- -## Schritt 6: Performance-Monitoring und -Optimierung - -### Middleware zur Messung der Antwortzeit hinzufügen - -Fügen wir Performance-Monitoring in `src/main.py` hinzu: - -```python -import time -from fastapi import FastAPI, Request -from src.api.api import api_router -from src.core.config import settings - -app = FastAPI( - title=settings.PROJECT_NAME, - version=settings.VERSION, - description=settings.DESCRIPTION, -) - -@app.middleware("http") -async def add_process_time_header(request: Request, call_next): - """Add request processing time to headers""" - start_time = time.time() - response = await call_next(request) - process_time = time.time() - start_time - response.headers["X-Process-Time"] = str(process_time) - return response - -app.include_router(api_router) - -@app.get("/") -async def read_root(): - return {"message": "Welcome to the Asynchronous Todo API!"} -``` - -### Asynchrone Batch-Verarbeitung implementieren - -Fügen wir Batch-Endpunkte hinzu, um mehrere Items gleichzeitig zu verarbeiten: - -```python -# Add to src/api/routes/items.py - -@router.post("/batch", response_model=List[Item]) -async def create_items_batch(items: List[ItemCreate]): - """Create multiple items concurrently (batch processing)""" - import asyncio - - # Execute all item creation tasks concurrently - tasks = [crud.create_item(item) for item in items] - created_items = await asyncio.gather(*tasks) - - return created_items - -@router.get("/batch/{item_ids}") -async def read_items_batch(item_ids: str): - """Retrieve multiple items concurrently (batch processing)""" - import asyncio - - # Parse comma-separated IDs - ids = [int(id.strip()) for id in item_ids.split(",")] - - # Execute all item retrieval tasks concurrently - tasks = [crud.get_item(item_id) for item_id in ids] - items = await asyncio.gather(*tasks) - - # Return only non-None items - return [item for item in items if item is not None] -``` - -### Batch-Verarbeitung testen - -
- -```console -# Batch creation test -$ curl -X POST "http://127.0.0.1:8000/items/batch" \ - -H "Content-Type: application/json" \ - -d '[ - {"name": "Item1", "description": "Description1", "price": 10.0, "tax": 1.0}, - {"name": "Item2", "description": "Description2", "price": 20.0, "tax": 2.0}, - {"name": "Item3", "description": "Description3", "price": 30.0, "tax": 3.0} - ]' - -# Batch retrieval test -$ curl -X GET "http://127.0.0.1:8000/items/batch/1,2,3" -``` - -
- -## Schritt 7: Fortgeschrittene asynchrone Muster - -### Rate-Limiting implementieren - -```python -import asyncio -from collections import defaultdict -from fastapi import HTTPException, Request -from datetime import datetime, timedelta - -class AsyncRateLimiter: - def __init__(self, max_requests: int = 100, window_seconds: int = 60): - self.max_requests = max_requests - self.window_seconds = window_seconds - self.requests = defaultdict(list) - - async def is_allowed(self, client_ip: str) -> bool: - now = datetime.now() - cutoff = now - timedelta(seconds=self.window_seconds) - - # remove old request records - self.requests[client_ip] = [ - req_time for req_time in self.requests[client_ip] - if req_time > cutoff - ] - - # check current request count - if len(self.requests[client_ip]) >= self.max_requests: - return False - - # add current request record - self.requests[client_ip].append(now) - return True - -# global rate limiter instance -rate_limiter = AsyncRateLimiter() - -@app.middleware("http") -async def rate_limit_middleware(request: Request, call_next): - client_ip = request.client.host - - if not await rate_limiter.is_allowed(client_ip): - raise HTTPException( - status_code=429, - detail="Too many requests" - ) - - response = await call_next(request) - return response -``` - -### Asynchrones Caching implementieren - -```python -import asyncio -from typing import Optional, Any -from datetime import datetime, timedelta - -class AsyncCache: - def __init__(self): - self._cache = {} - self._expiry = {} - - async def get(self, key: str) -> Optional[Any]: - # remove expired items - if key in self._expiry and datetime.now() > self._expiry[key]: - del self._cache[key] - del self._expiry[key] - return None - - return self._cache.get(key) - - async def set(self, key: str, value: Any, ttl_seconds: int = 300): - self._cache[key] = value - self._expiry[key] = datetime.now() + timedelta(seconds=ttl_seconds) - - async def delete(self, key: str): - self._cache.pop(key, None) - self._expiry.pop(key, None) - -# global cache instance -cache = AsyncCache() - -# modify CRUD methods to use cache -async def get_items_cached(self) -> List[Item]: - """Retrieve items using cache""" - cache_key = "all_items" - cached_items = await cache.get(cache_key) - - if cached_items: - return cached_items - - # if cache is not found, read from file - items = await self.get_items() - await cache.set(cache_key, items, ttl_seconds=60) # 1 minute cache - - return items -``` - -## Schritt 8: Produktionsüberlegungen - -### Verbindungspools verwalten - -```python -# add to src/core/config.py -class Settings(BaseSettings): - # ... existing settings ... - - # asynchronous processing related settings - MAX_CONCURRENT_REQUESTS: int = 100 - REQUEST_TIMEOUT: int = 30 - CONNECTION_POOL_SIZE: int = 20 - -settings = Settings() -``` - -### Fehlerbehandlung verbessern - -```python -import logging -from fastapi import HTTPException -from typing import Union - -logger = logging.getLogger(__name__) - -async def safe_async_operation(operation, *args, **kwargs) -> Union[Any, None]: - """Execute safe asynchronous operation""" - try: - return await operation(*args, **kwargs) - except asyncio.TimeoutError: - logger.error(f"Timeout in {operation.__name__}") - raise HTTPException(status_code=504, detail="Request timeout") - except Exception as e: - logger.error(f"Error in {operation.__name__}: {str(e)}") - raise HTTPException(status_code=500, detail="Internal server error") - -# usage example -@router.get("/safe/{item_id}") -async def read_item_safe(item_id: int): - return await safe_async_operation(crud.get_item, item_id) -``` - -## Nächste Schritte - -Sie haben den Bau einer asynchronen CRUD-API abgeschlossen! Nächste Schritte zum Ausprobieren: - -1. **[Datenbankintegration](database-integration.md)** — PostgreSQL mit asynchronem SQLAlchemy nutzen -2. **[Docker-Containerisierung](docker-deployment.md)** — asynchrone Anwendungen containerisieren -3. **[Benutzerdefinierte Antwortbehandlung](custom-response-handling.md)** — fortgeschrittene Antwortformate und Fehlerbehandlung - - - -## Zusammenfassung - -In diesem Tutorial haben wir mit asynchronem FastAPI: - -- ✅ Asynchrone CRUD-Operationen implementiert -- ✅ Datei-I/O mit aiofiles optimiert -- ✅ Parallele Anfragen behandelt und Leistung getestet -- ✅ Asynchrone Tests geschrieben und ausgeführt -- ✅ Batch-Verarbeitung und fortgeschrittene asynchrone Muster implementiert -- ✅ Produktionsüberlegungen behandelt (Caching, Fehlerbehandlung, Verbindungsverwaltung) - -Asynchrone Verarbeitung zu beherrschen ermöglicht es Ihnen, hochperformante API-Server zu bauen! diff --git a/docs/de/tutorial/basic-api-server.md b/docs/de/tutorial/basic-api-server.md index 0271d91..77479d9 100644 --- a/docs/de/tutorial/basic-api-server.md +++ b/docs/de/tutorial/basic-api-server.md @@ -367,10 +367,9 @@ tests/test_items.py::test_update_item PASSED [100%] Sie haben den Bau eines einfachen API-Servers abgeschlossen! Nächste Schritte zum Ausprobieren: -1. **[Asynchrone CRUD-APIs bauen](async-crud-api.md)** — lernen Sie komplexere asynchrone Verarbeitung -2. **[Datenbankintegration](database-integration.md)** — PostgreSQL und SQLAlchemy nutzen -3. **[Docker-Containerisierung](docker-deployment.md)** — auf ein Produktionsdeployment vorbereiten -4. **[Benutzerdefinierte Antwortbehandlung](custom-response-handling.md)** — erweiterte Konfiguration der Antwortformate +1. **[Asynchrone Persistenz mit SQLModel](sqlmodel.md)** — asynchroner Datenzugriff mit SQLite, PostgreSQL oder MySQL +2. **[Domänenorientiertes Projekt](domain-starter.md)** — eine mittelgroße API strukturieren +3. **[Benutzerdefinierte Antwortbehandlung](custom-response-handling.md)** — erweiterte Konfiguration der Antwortformate ## Fehlerbehebung diff --git a/docs/de/tutorial/custom-response-handling.md b/docs/de/tutorial/custom-response-handling.md index 92fcf10..3b23c2d 100644 --- a/docs/de/tutorial/custom-response-handling.md +++ b/docs/de/tutorial/custom-response-handling.md @@ -14,7 +14,7 @@ Lernen Sie, wie Sie mit den fortgeschrittenen Funktionen von FastAPI konsistente ## Voraussetzungen -- Das [Tutorial Docker-Containerisierung](docker-deployment.md) abgeschlossen +- Das Tutorial [Einfacher API-Server](basic-api-server.md) abgeschlossen - Verständnis der REST-API-Designprinzipien - Kenntnisse der HTTP-Statuscodes - Grundkonzepte von OpenAPI / Swagger diff --git a/docs/de/tutorial/database-integration.md b/docs/de/tutorial/database-integration.md deleted file mode 100644 index 0ad41bd..0000000 --- a/docs/de/tutorial/database-integration.md +++ /dev/null @@ -1,1028 +0,0 @@ -# Datenbankintegration (PostgreSQL + SQLAlchemy) - -Bauen Sie eine FastAPI-Anwendung mit PostgreSQL-Datenbank und SQLAlchemy-ORM, die in echten Produktionsumgebungen eingesetzt werden kann. In diesem Tutorial implementieren wir ein vollständiges Datenbankintegrationssystem mit der Vorlage `fastapi-psql-orm`. - -## Was Sie in diesem Tutorial lernen - -- PostgreSQL-Datenbank einrichten und integrieren -- Datenmodellierung mit SQLAlchemy-ORM -- Datenbankmigrationen mit Alembic -- Entwicklungsumgebung mit Docker Compose einrichten -- Verbindungspool der Datenbank verwalten -- Transaktionsverarbeitung und Datenintegrität - -## Voraussetzungen - -- Das [Tutorial Asynchrone CRUD-API](async-crud-api.md) abgeschlossen -- Docker und Docker Compose installiert -- Grundkenntnisse von PostgreSQL -- Verständnis der Grundkonzepte des SQLAlchemy-ORM - -## Warum PostgreSQL und SQLAlchemy? - -### Vergleich JSON-Dateien vs. PostgreSQL - -| Kategorie | JSON-Dateien | PostgreSQL | -|----------|------------|------------| -| **Leistung** | Begrenzt | Hochleistungs-Indexierung | -| **Nebenläufigkeit** | Datei-Sperrprobleme | Transaktionsunterstützung | -| **Skalierbarkeit** | Speicherbegrenzt | Verarbeitung großer Datenmengen | -| **Integrität** | Nicht garantiert | ACID-Eigenschaften garantiert | -| **Abfragen** | Müssen alle Daten laden | Unterstützung komplexer Abfragen | -| **Backup** | Dateikopie | Vollständiges Backup/Restore | - -## Schritt 1: Ein PostgreSQL-+-ORM-Projekt erstellen - -Erstellen Sie ein Projekt mit der Vorlage `fastapi-psql-orm`: - -
- -```console -$ fastkit startdemo fastapi-psql-orm -Enter the project name: todo-postgres-api -Enter the author name: Developer Kim -Enter the author email: developer@example.com -Enter the project description: Todo management API using PostgreSQL -Deploying FastAPI project using 'fastapi-psql-orm' template - - Project Information -┌──────────────┬─────────────────────────────────────────┐ -│ Project Name │ todo-postgres-api │ -│ Author │ Developer Kim │ -│ Author Email │ developer@example.com │ -│ Description │ Todo management API using PostgreSQL │ -└──────────────┴─────────────────────────────────────────┘ - - Template Dependencies -┌──────────────┬────────────────┐ -│ Dependency 1 │ fastapi │ -│ Dependency 2 │ uvicorn │ -│ Dependency 3 │ sqlalchemy │ -│ Dependency 4 │ alembic │ -│ Dependency 5 │ psycopg2 │ -│ Dependency 6 │ asyncpg │ -│ Dependency 7 │ sqlmodel │ -└──────────────┴────────────────┘ - -Select package manager (pip, uv, pdm, poetry) [uv]: uv -Do you want to proceed with project creation? [y/N]: y - -✨ FastAPI project 'todo-postgres-api' from 'fastapi-psql-orm' has been created successfully! -``` - -
- -## Schritt 2: Projektstruktur analysieren - -Das generierte Projekt bietet eine vollständige Datenbankintegrationsumgebung: - -``` -todo-postgres-api/ -├── docker-compose.yml # PostgreSQL container configuration -├── Dockerfile # Application container -├── alembic.ini # Alembic configuration -├── template-config.yml # Template configuration -├── scripts/ -│ ├── pre-start.sh # Pre-start initialization -│ └── test.sh # Test execution script -├── src/ -│ ├── main.py # FastAPI application -│ ├── core/ -│ │ ├── config.py # Environment configuration -│ │ └── db.py # Database connection setup -│ ├── api/ -│ │ ├── deps.py # Dependency injection -│ │ └── routes/ -│ │ └── items.py # API endpoints -│ ├── crud/ -│ │ └── items.py # Database operations -│ ├── schemas/ -│ │ └── items.py # Pydantic models -│ ├── utils/ -│ │ ├── backend_pre_start.py # Backend initialization -│ │ ├── init_data.py # Initial data loading -│ │ └── tests_pre_start.py # Test preparation -│ └── alembic/ -│ ├── env.py # Alembic environment configuration -│ └── versions/ # Migration files -└── tests/ - ├── conftest.py # Test configuration - └── test_items.py # API tests -``` - -### Kernkomponenten - -1. **SQLModel**: SQLAlchemy + Pydantic-Integration -2. **Alembic**: Schema-Migration für die Datenbank -3. **asyncpg**: asynchroner PostgreSQL-Treiber -4. **Docker Compose**: Containerisierung der Entwicklungsumgebung - -## Schritt 3: Die Datenbankkonfiguration verstehen - -### Konfiguration der Datenbankverbindung (`src/core/db.py`) - -```python -from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine -from sqlalchemy.orm import sessionmaker -from sqlmodel import SQLModel - -from src.core.config import settings - -# Create asynchronous PostgreSQL engine -engine = create_async_engine( - settings.DATABASE_URL, - echo=settings.DEBUG, # Output SQL logs - pool_size=20, # Connection pool size - max_overflow=0, # Number of additional connections allowed - pool_pre_ping=True, # Check connection status -) - -# Asynchronous session factory -AsyncSessionLocal = sessionmaker( - autocommit=False, - autoflush=False, - bind=engine, - class_=AsyncSession, - expire_on_commit=False, -) - -async def create_tables(): - """Create database tables""" - async with engine.begin() as conn: - await conn.run_sync(SQLModel.metadata.create_all) - -async def get_session() -> AsyncSession: - """Provide database session (for dependency injection)""" - async with AsyncSessionLocal() as session: - try: - yield session - finally: - await session.close() -``` - -### Umgebungskonfiguration (`src/core/config.py`) - -```python -from pydantic_settings import BaseSettings -from typing import Optional - -class Settings(BaseSettings): - PROJECT_NAME: str = "Todo PostgreSQL API" - VERSION: str = "1.0.0" - DESCRIPTION: str = "Todo management API using PostgreSQL" - - # Database configuration - POSTGRES_SERVER: str = "localhost" - POSTGRES_USER: str = "postgres" - POSTGRES_PASSWORD: str = "password" - POSTGRES_DB: str = "todoapp" - POSTGRES_PORT: int = 5432 - - # Test database - TEST_DATABASE_URL: Optional[str] = None - - # Debug mode - DEBUG: bool = False - - @property - def DATABASE_URL(self) -> str: - """Generate PostgreSQL connection URL""" - return ( - f"postgresql+asyncpg://{self.POSTGRES_USER}:" - f"{self.POSTGRES_PASSWORD}@{self.POSTGRES_SERVER}:" - f"{self.POSTGRES_PORT}/{self.POSTGRES_DB}" - ) - - class Config: - env_file = ".env" - -settings = Settings() -``` - -## Schritt 4: Datenmodell definieren - -### Datenmodell mit SQLModel (`src/schemas/items.py`) - -```python -from sqlmodel import SQLModel, Field -from typing import Optional -from datetime import datetime - -# Define common fields -class ItemBase(SQLModel): - name: str = Field(index=True, max_length=100) - description: Optional[str] = Field(default=None, max_length=500) - price: float = Field(gt=0, description="Price must be greater than 0") - tax: Optional[float] = Field(default=None, ge=0) - is_active: bool = Field(default=True) - -# Database table model -class Item(ItemBase, table=True): - __tablename__ = "items" - - id: Optional[int] = Field(default=None, primary_key=True) - created_at: datetime = Field(default_factory=datetime.utcnow) - updated_at: Optional[datetime] = Field(default=None) - - # Set index - class Config: - schema_extra = { - "example": { - "name": "notebook", - "description": "High-performance gaming notebook", - "price": 1500000.0, - "tax": 150000.0, - "is_active": True - } - } - -# API request/response model -class ItemCreate(ItemBase): - pass - -class ItemUpdate(SQLModel): - name: Optional[str] = Field(default=None, max_length=100) - description: Optional[str] = Field(default=None, max_length=500) - price: Optional[float] = Field(default=None, gt=0) - tax: Optional[float] = Field(default=None, ge=0) - is_active: Optional[bool] = Field(default=None) - -class ItemResponse(ItemBase): - id: int - created_at: datetime - updated_at: Optional[datetime] -``` - -## Schritt 5: CRUD-Operationen implementieren - -### Datenbank-CRUD-Logik (`src/crud/items.py`) - -```python -from typing import List, Optional -from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy import select, update, delete -from sqlalchemy.orm import selectinload -from datetime import datetime - -from src.schemas.items import Item, ItemCreate, ItemUpdate - -class ItemCRUD: - def __init__(self, db: AsyncSession): - self.db = db - - async def create(self, item_create: ItemCreate) -> Item: - """Create new item""" - db_item = Item(**item_create.dict()) - - self.db.add(db_item) - await self.db.commit() - await self.db.refresh(db_item) - - return db_item - - async def get_by_id(self, item_id: int) -> Optional[Item]: - """Get item by ID""" - statement = select(Item).where(Item.id == item_id) - result = await self.db.execute(statement) - return result.scalar_one_or_none() - - async def get_many( - self, - skip: int = 0, - limit: int = 100, - active_only: bool = True - ) -> List[Item]: - """Get multiple items (pagination supported)""" - statement = select(Item) - - if active_only: - statement = statement.where(Item.is_active == True) - - statement = statement.offset(skip).limit(limit) - result = await self.db.execute(statement) - return result.scalars().all() - - async def update(self, item_id: int, item_update: ItemUpdate) -> Optional[Item]: - """Update item""" - # Prepare update data - update_data = item_update.dict(exclude_unset=True) - if update_data: - update_data["updated_at"] = datetime.utcnow() - - # Execute update - statement = ( - update(Item) - .where(Item.id == item_id) - .values(**update_data) - .returning(Item) - ) - - result = await self.db.execute(statement) - await self.db.commit() - - return result.scalar_one_or_none() - - async def delete(self, item_id: int) -> bool: - """Delete item (soft delete)""" - statement = ( - update(Item) - .where(Item.id == item_id) - .values(is_active=False, updated_at=datetime.utcnow()) - ) - - result = await self.db.execute(statement) - await self.db.commit() - - return result.rowcount > 0 - - async def hard_delete(self, item_id: int) -> bool: - """Delete item completely""" - statement = delete(Item).where(Item.id == item_id) - result = await self.db.execute(statement) - await self.db.commit() - - return result.rowcount > 0 - - async def search(self, query: str) -> List[Item]: - """Search item (name, description)""" - statement = select(Item).where( - (Item.name.ilike(f"%{query}%")) | - (Item.description.ilike(f"%{query}%")) - ).where(Item.is_active == True) - - result = await self.db.execute(statement) - return result.scalars().all() - - async def get_total_count(self, active_only: bool = True) -> int: - """Get total item count""" - from sqlalchemy import func - - statement = select(func.count(Item.id)) - if active_only: - statement = statement.where(Item.is_active == True) - - result = await self.db.execute(statement) - return result.scalar() -``` - -## Schritt 6: API-Endpunkte implementieren - -### Dependency-Injection einrichten (`src/api/deps.py`) - -```python -from typing import AsyncGenerator -from fastapi import Depends -from sqlalchemy.ext.asyncio import AsyncSession - -from src.core.db import get_session -from src.crud.items import ItemCRUD - -async def get_db() -> AsyncGenerator[AsyncSession, None]: - """Database session dependency""" - async for session in get_session(): - yield session - -def get_item_crud(db: AsyncSession = Depends(get_db)) -> ItemCRUD: - """Item CRUD dependency""" - return ItemCRUD(db) -``` - -### API-Router-Implementierung (`src/api/routes/items.py`) - -```python -from typing import List -from fastapi import APIRouter, Depends, HTTPException, Query, status - -from src.api.deps import get_item_crud -from src.crud.items import ItemCRUD -from src.schemas.items import Item, ItemCreate, ItemUpdate, ItemResponse - -router = APIRouter() - -@router.post("/", response_model=ItemResponse, status_code=status.HTTP_201_CREATED) -async def create_item( - item_create: ItemCreate, - crud: ItemCRUD = Depends(get_item_crud) -): - """Create new item""" - return await crud.create(item_create) - -@router.get("/", response_model=List[ItemResponse]) -async def read_items( - skip: int = Query(0, ge=0, description="Skip items"), - limit: int = Query(100, ge=1, le=1000, description="Maximum items to retrieve"), - active_only: bool = Query(True, description="Only active items"), - crud: ItemCRUD = Depends(get_item_crud) -): - """Get item list (pagination supported)""" - return await crud.get_many(skip=skip, limit=limit, active_only=active_only) - -@router.get("/search", response_model=List[ItemResponse]) -async def search_items( - q: str = Query(..., min_length=1, description="Search term"), - crud: ItemCRUD = Depends(get_item_crud) -): - """Search item""" - return await crud.search(q) - -@router.get("/count") -async def get_items_count( - active_only: bool = Query(True, description="Only active items"), - crud: ItemCRUD = Depends(get_item_crud) -): - """Get total item count""" - count = await crud.get_total_count(active_only) - return {"total": count} - -@router.get("/{item_id}", response_model=ItemResponse) -async def read_item( - item_id: int, - crud: ItemCRUD = Depends(get_item_crud) -): - """Get specific item""" - item = await crud.get_by_id(item_id) - if not item: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item ID {item_id} not found" - ) - return item - -@router.put("/{item_id}", response_model=ItemResponse) -async def update_item( - item_id: int, - item_update: ItemUpdate, - crud: ItemCRUD = Depends(get_item_crud) -): - """Update item""" - updated_item = await crud.update(item_id, item_update) - if not updated_item: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item ID {item_id} not found" - ) - return updated_item - -@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT) -async def delete_item( - item_id: int, - hard_delete: bool = Query(False, description="Complete delete"), - crud: ItemCRUD = Depends(get_item_crud) -): - """Delete item""" - if hard_delete: - deleted = await crud.hard_delete(item_id) - else: - deleted = await crud.delete(item_id) - - if not deleted: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Item ID {item_id} not found" - ) -``` - -## Schritt 7: Docker-Container starten - -### Docker-Compose-Konfiguration prüfen (`docker-compose.yml`) - -```yaml -version: '3.8' - -services: - db: - image: postgres:15 - restart: always - environment: - POSTGRES_DB: todoapp - POSTGRES_USER: postgres - POSTGRES_PASSWORD: password - ports: - - "5432:5432" - volumes: - - postgres_data:/var/lib/postgresql/data - - app: - build: . - restart: always - ports: - - "8000:8000" - environment: - POSTGRES_SERVER: db - POSTGRES_USER: postgres - POSTGRES_PASSWORD: password - POSTGRES_DB: todoapp - depends_on: - - db - volumes: - - ./src:/app/src - -volumes: - postgres_data: -``` - -### Container starten - -
- -```console -$ cd todo-postgres-api - -# Start service in background -$ docker-compose up -d -Creating network "todo-postgres-api_default" with the default driver -Creating volume "todo-postgres-api_postgres_data" with default driver -Pulling db (postgres:15)... -Creating todo-postgres-api_db_1 ... done -Building app -Creating todo-postgres-api_app_1 ... done - -# Check service status -$ docker-compose ps - Name Command State Ports -------------------------------------------------------------------------------------- -todo-postgres-api_app_1 uvicorn src.main:app --host=0.0.0.0 --port=8000 Up 0.0.0.0:8000->8000/tcp -todo-postgres-api_db_1 docker-entrypoint.sh postgres Up 0.0.0.0:5432->5432/tcp - -# Check log -$ docker-compose logs app -``` - -
- -## Schritt 8: Datenbankmigration - -### Erste Migration mit Alembic erstellen - -
- -```console -# Run migration inside container -$ docker-compose exec app alembic revision --autogenerate -m "Create items table" -INFO [alembic.runtime.migration] Context impl PostgresqlImpl. -INFO [alembic.runtime.migration] Will assume transactional DDL. -INFO [alembic.autogenerate.compare] Detected added table 'items' -Generating migration script /app/src/alembic/versions/001_create_items_table.py ... done - -# Apply migration -$ docker-compose exec app alembic upgrade head -INFO [alembic.runtime.migration] Context impl PostgresqlImpl. -INFO [alembic.runtime.migration] Will assume transactional DDL. -INFO [alembic.runtime.migration] Running upgrade -> 001, Create items table -``` - -
- -### Migrationsdatei prüfen - -Sehen Sie sich die erstellte Migrationsdatei an: - -```python -# src/alembic/versions/001_create_items_table.py -"""Create items table - -Revision ID: 001 -Revises: -Create Date: 2024-01-01 12:00:00.000000 - -""" -from alembic import op -import sqlalchemy as sa -import sqlmodel - -# revision identifiers -revision = '001' -down_revision = None -branch_labels = None -depends_on = None - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.create_table('items', - sa.Column('name', sqlmodel.sql.sqltypes.AutoString(length=100), nullable=False), - sa.Column('description', sqlmodel.sql.sqltypes.AutoString(length=500), nullable=True), - sa.Column('price', sa.Float(), nullable=False), - sa.Column('tax', sa.Float(), nullable=True), - sa.Column('is_active', sa.Boolean(), nullable=False), - sa.Column('id', sa.Integer(), nullable=False), - sa.Column('created_at', sa.DateTime(), nullable=False), - sa.Column('updated_at', sa.DateTime(), nullable=True), - sa.PrimaryKeyConstraint('id') - ) - op.create_index(op.f('ix_items_name'), 'items', ['name'], unique=False) - # ### end Alembic commands ### - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_items_name'), table_name='items') - op.drop_table('items') - # ### end Alembic commands ### -``` - -## Schritt 9: API testen - -### Grundlegender CRUD-Test - -
- -```console -# Create new item -$ curl -X POST "http://localhost:8000/items/" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "MacBook Pro", - "description": "M2 chipset-equipped high-performance notebook", - "price": 2500000, - "tax": 250000 - }' - -{ - "id": 1, - "name": "MacBook Pro", - "description": "M2 chipset-equipped high-performance notebook", - "price": 2500000.0, - "tax": 250000.0, - "is_active": true, - "created_at": "2024-01-01T12:00:00.123456", - "updated_at": null -} - -# Get item list -$ curl "http://localhost:8000/items/" - -# Get item list with pagination -$ curl "http://localhost:8000/items/?skip=0&limit=10" - -# Search item -$ curl "http://localhost:8000/items/search?q=MacBook" - -# Get item count -$ curl "http://localhost:8000/items/count" -{"total": 1} -``` - -
- -### Test fortgeschrittener Abfragefunktionen - -
- -```console -# Get item list with inactive items -$ curl "http://localhost:8000/items/?active_only=false" - -# Update item -$ curl -X PUT "http://localhost:8000/items/1" \ - -H "Content-Type: application/json" \ - -d '{ - "price": 2300000, - "tax": 230000 - }' - -# Soft delete item -$ curl -X DELETE "http://localhost:8000/items/1" - -# Hard delete item -$ curl -X DELETE "http://localhost:8000/items/1?hard_delete=true" -``` - -
- -## Schritt 10: Erweiterte Datenbankfunktionen - -### Transaktionsverarbeitung - -```python -# Add to src/crud/items.py - -from sqlalchemy.exc import SQLAlchemyError - -async def create_items_batch(self, items_create: List[ItemCreate]) -> List[Item]: - """Create multiple items in a transaction""" - created_items = [] - - try: - for item_create in items_create: - db_item = Item(**item_create.dict()) - self.db.add(db_item) - created_items.append(db_item) - - await self.db.commit() - - # Refresh all items - for item in created_items: - await self.db.refresh(item) - - return created_items - - except SQLAlchemyError: - await self.db.rollback() - raise -``` - -### Relationale Datenmodellierung - -```python -# Add to src/schemas/items.py - -from sqlmodel import Relationship - -class Category(SQLModel, table=True): - __tablename__ = "categories" - - id: Optional[int] = Field(default=None, primary_key=True) - name: str = Field(max_length=50, unique=True) - description: Optional[str] = None - - # Set relationship - items: List["Item"] = Relationship(back_populates="category") - -class Item(ItemBase, table=True): - __tablename__ = "items" - - id: Optional[int] = Field(default=None, primary_key=True) - created_at: datetime = Field(default_factory=datetime.utcnow) - updated_at: Optional[datetime] = Field(default=None) - - # Add foreign key - category_id: Optional[int] = Field(foreign_key="categories.id") - - # Set relationship - category: Optional[Category] = Relationship(back_populates="items") -``` - -### Index-Optimierung - -```python -# Add to src/schemas/items.py - -from sqlalchemy import Index - -class Item(ItemBase, table=True): - __tablename__ = "items" - - # ... existing fields ... - - # Set composite index - __table_args__ = ( - Index('ix_items_price_active', 'price', 'is_active'), - Index('ix_items_created_at', 'created_at'), - Index('ix_items_name_description', 'name', 'description'), # For full text search - ) -``` - -## Schritt 11: Tests schreiben - -### Test-Setup für die Datenbank (`tests/conftest.py`) - -```python -import pytest -import asyncio -from httpx import AsyncClient -from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine -from sqlalchemy.orm import sessionmaker -from sqlmodel import SQLModel - -from src.main import app -from src.core.db import get_session -from src.core.config import settings - -# Test database engine -test_engine = create_async_engine( - settings.TEST_DATABASE_URL or "sqlite+aiosqlite:///./test.db", - echo=False, -) - -TestSessionLocal = sessionmaker( - autocommit=False, - autoflush=False, - bind=test_engine, - class_=AsyncSession, - expire_on_commit=False, -) - -@pytest.fixture(scope="session") -def event_loop(): - loop = asyncio.get_event_loop_policy().new_event_loop() - yield loop - loop.close() - -@pytest.fixture(scope="function") -async def db_session(): - # Create test table - async with test_engine.begin() as conn: - await conn.run_sync(SQLModel.metadata.create_all) - - # Provide session - async with TestSessionLocal() as session: - yield session - - # Delete table after test - async with test_engine.begin() as conn: - await conn.run_sync(SQLModel.metadata.drop_all) - -@pytest.fixture -async def client(db_session: AsyncSession): - # Override dependency - async def override_get_session(): - yield db_session - - app.dependency_overrides[get_session] = override_get_session - - async with AsyncClient(app=app, base_url="http://test") as client: - yield client - - app.dependency_overrides.clear() -``` - -### Integrationstests (`tests/test_items.py`) - -```python -import pytest -from httpx import AsyncClient - -@pytest.mark.asyncio -async def test_create_and_read_item(client: AsyncClient): - """Integration test for creating and reading item""" - # Create item - item_data = { - "name": "Test Item", - "description": "Database test", - "price": 50000, - "tax": 5000 - } - - response = await client.post("/items/", json=item_data) - assert response.status_code == 201 - - created_item = response.json() - assert created_item["name"] == item_data["name"] - assert "id" in created_item - assert "created_at" in created_item - - # Get created item - item_id = created_item["id"] - response = await client.get(f"/items/{item_id}") - assert response.status_code == 200 - - retrieved_item = response.json() - assert retrieved_item["id"] == item_id - assert retrieved_item["name"] == item_data["name"] - -@pytest.mark.asyncio -async def test_item_pagination(client: AsyncClient): - """Test pagination feature""" - # Create multiple items - for i in range(15): - item_data = { - "name": f"Item {i}", - "description": f"Description {i}", - "price": i * 1000, - "tax": i * 100 - } - await client.post("/items/", json=item_data) - - # Get first page - response = await client.get("/items/?skip=0&limit=10") - assert response.status_code == 200 - - items = response.json() - assert len(items) == 10 - - # Get second page - response = await client.get("/items/?skip=10&limit=10") - assert response.status_code == 200 - - items = response.json() - assert len(items) == 5 - -@pytest.mark.asyncio -async def test_item_search(client: AsyncClient): - """Test search feature""" - # Create test items - items = [ - {"name": "iPhone 15", "description": "Latest smartphone", "price": 1200000, "tax": 120000}, - {"name": "Galaxy S24", "description": "Samsung flagship", "price": 1100000, "tax": 110000}, - {"name": "MacBook Air", "description": "Apple notebook", "price": 1500000, "tax": 150000}, - ] - - for item in items: - await client.post("/items/", json=item) - - # Search "iPhone" - response = await client.get("/items/search?q=iPhone") - assert response.status_code == 200 - - results = response.json() - assert len(results) == 1 - assert results[0]["name"] == "iPhone 15" - - # Search "smartphone" (description) - response = await client.get("/items/search?q=smartphone") - assert response.status_code == 200 - - results = response.json() - assert len(results) == 1 - assert results[0]["description"] == "Latest smartphone" -``` - -### Tests ausführen - -
- -```console -# Tests im Container ausführen -$ docker-compose exec app python -m pytest tests/ -v -======================== test session starts ======================== -collected 12 items - -tests/test_items.py::test_create_and_read_item PASSED [ 8%] -tests/test_items.py::test_item_pagination PASSED [16%] -tests/test_items.py::test_item_search PASSED [25%] -tests/test_items.py::test_update_item PASSED [33%] -tests/test_items.py::test_delete_item PASSED [41%] -tests/test_items.py::test_soft_delete PASSED [50%] -tests/test_items.py::test_item_not_found PASSED [58%] -tests/test_items.py::test_invalid_item_data PASSED [66%] -tests/test_items.py::test_database_transaction PASSED [75%] -tests/test_items.py::test_concurrent_operations PASSED [83%] -tests/test_items.py::test_item_count PASSED [91%] -tests/test_items.py::test_batch_operations PASSED [100%] - -======================== 12 passed in 2.34s ======================== -``` - -
- -## Schritt 12: Überlegungen für ein Produktionsdeployment - -### Verbindungspool optimieren - -```python -# Add to src/core/config.py - -class Settings(BaseSettings): - # ... existing settings ... - - # Database connection pool settings - DB_POOL_SIZE: int = 20 - DB_MAX_OVERFLOW: int = 0 - DB_POOL_PRE_PING: bool = True - DB_POOL_RECYCLE: int = 300 # 5 minutes - - # Query timeout - DB_QUERY_TIMEOUT: int = 30 - - # Connection retry settings - DB_RETRY_ATTEMPTS: int = 3 - DB_RETRY_DELAY: int = 1 -``` - -### Datenbank-Monitoring - -```python -# Add to src/core/db.py - -import logging -from sqlalchemy import event -from sqlalchemy.engine import Engine - -logger = logging.getLogger(__name__) - -@event.listens_for(Engine, "before_cursor_execute") -def receive_before_cursor_execute(conn, cursor, statement, parameters, context, executemany): - """Log before query execution""" - context._query_start_time = time.time() - -@event.listens_for(Engine, "after_cursor_execute") -def receive_after_cursor_execute(conn, cursor, statement, parameters, context, executemany): - """Log after query execution""" - total = time.time() - context._query_start_time - if total > 1.0: # Log slow queries (1 second or more) - logger.warning(f"Slow query: {total:.2f}s - {statement[:100]}...") -``` - -## Nächste Schritte - -Sie haben die PostgreSQL-Datenbankintegration abgeschlossen! Nächste Schritte zum Ausprobieren: - -1. **[Docker-Containerisierung](docker-deployment.md)** — eine Produktionsumgebung aufbauen -2. **[Benutzerdefinierte Antwortbehandlung](custom-response-handling.md)** — erweiterte API-Antwortformate - - - - -## Zusammenfassung - -In diesem Tutorial haben wir mit PostgreSQL und SQLAlchemy: - -- ✅ Eine PostgreSQL-Datenbank integriert -- ✅ ORM mit SQLModel implementiert -- ✅ Das Alembic-Migrationssystem eingerichtet -- ✅ Fortgeschrittene CRUD-Operationen und Abfrageoptimierung umgesetzt -- ✅ Transaktionsverarbeitung und Datenintegrität behandelt -- ✅ Paginierung, Suche und Sortierung implementiert -- ✅ Integrationstests und Datenbank-Tests geschrieben -- ✅ Überlegungen zum Produktionsdeployment angestellt - -Jetzt können Sie robuste, datenbankgetriebene APIs für echte Produktionsumgebungen bauen! diff --git a/docs/de/tutorial/docker-deployment.md b/docs/de/tutorial/docker-deployment.md deleted file mode 100644 index 166cf4c..0000000 --- a/docs/de/tutorial/docker-deployment.md +++ /dev/null @@ -1,1178 +0,0 @@ -# Docker-Containerisierung und Deployment - -Lernen Sie, wie Sie FastAPI-Anwendungen mit Docker containerisieren, um konsistente Entwicklungsumgebungen zu bauen und sich auf das Produktionsdeployment vorzubereiten. Wir richten eine vollständige Docker-basierte Deployment-Umgebung mit der Vorlage `fastapi-dockerized` ein. - -## Was Sie in diesem Tutorial lernen - -- FastAPI-Anwendungen mit Docker containerisieren -- Optimierte Docker-Images mit mehrstufigen Builds erstellen -- Entwicklungsumgebungen mit Docker Compose einrichten -- Docker-Konfiguration für das Produktionsdeployment -- Container-Monitoring und Log-Verwaltung -- CI/CD-Pipelines aufbauen - -## Voraussetzungen - -- Das [Tutorial Datenbankintegration](database-integration.md) abgeschlossen -- Docker und Docker Compose installiert -- Verständnis der grundlegenden Docker-Befehle -- Grundkenntnisse zu Container-Konzepten - -## Vorteile der Docker-Containerisierung - -### Klassischer Ansatz vs. Docker - -| Kategorie | Klassischer Ansatz | Docker-Ansatz | -|----------|---------------------|-----------------| -| **Umgebungskonsistenz** | Unterschiede zwischen Umgebungen | Überall gleiche Umgebung | -| **Abhängigkeitsverwaltung** | Manuelle Installation erforderlich | Alle Abhängigkeiten im Image | -| **Deployment-Geschwindigkeit** | Langsam | Schnelles Deployment möglich | -| **Skalierbarkeit** | Begrenzt | Einfache Skalierung | -| **Rollback** | Komplex | Sofortiger Rollback auf vorherige Version | -| **Ressourcennutzung** | Schwer | Leichtgewichtige Container | - -## Schritt 1: Ein Docker-basiertes Projekt erstellen - -Erstellen Sie ein Projekt mit der Vorlage `fastapi-dockerized`: - -
- -```console -$ fastkit startdemo fastapi-dockerized -Enter the project name: dockerized-todo-api -Enter the author name: Developer Kim -Enter the author email: developer@example.com -Enter the project description: Dockerized todo management API -Deploying FastAPI project using 'fastapi-dockerized' template - - Project Information -┌──────────────┬─────────────────────────────────────────────┐ -│ Project Name │ dockerized-todo-api │ -│ Author │ Developer Kim │ -│ Author Email │ developer@example.com │ -│ Description │ Dockerized todo management API │ -└──────────────┴─────────────────────────────────────────────┘ - - Template Dependencies -┌──────────────┬───────────────────┐ -│ Dependency 1 │ fastapi │ -│ Dependency 2 │ uvicorn │ -│ Dependency 3 │ pydantic │ -│ Dependency 4 │ pydantic-settings │ -│ Dependency 5 │ python-dotenv │ -└──────────────┴───────────────────┘ - -Select package manager (pip, uv, pdm, poetry) [uv]: uv -Do you want to proceed with project creation? [y/N]: y - -✨ FastAPI project 'dockerized-todo-api' from 'fastapi-dockerized' has been created successfully! -``` - -
- -## Schritt 2: Docker-Konfigurationsdateien analysieren - -Untersuchen wir die Docker-bezogenen Dateien im generierten Projekt: - -``` -dockerized-todo-api/ -├── Dockerfile # Docker image build configuration -├── docker-compose.yml # Development environment container setup -├── docker-compose.prod.yml # Production environment configuration -├── .dockerignore # Files to exclude during Docker build -├── scripts/ -│ ├── start.sh # Container startup script -│ ├── prestart.sh # Pre-start initialization script -│ └── gunicorn.conf.py # Gunicorn configuration -├── src/ -│ ├── main.py # FastAPI application -│ └── ... # Other source code -└── requirements.txt # Python dependencies -``` - -### Dockerfile-Analyse - -```dockerfile -# Optimized Dockerfile using multi-stage build - -# ============================================ -# Stage 1: Build stage -# ============================================ -FROM python:3.12-slim as builder - -# Install build tools -RUN apt-get update && apt-get install -y \ - build-essential \ - curl \ - && rm -rf /var/lib/apt/lists/* - -# Copy dependency file and install -COPY requirements.txt . -RUN pip install --user --no-cache-dir -r requirements.txt - -# ============================================ -# Stage 2: Runtime stage -# ============================================ -FROM python:3.12-slim - -# System update and essential package installation -RUN apt-get update && apt-get install -y \ - curl \ - && rm -rf /var/lib/apt/lists/* \ - && apt-get clean - -# Create non-root user (security enhancement) -RUN groupadd -r appuser && useradd -r -g appuser appuser - -# Create application directory -WORKDIR /app - -# Copy Python packages from build stage -COPY --from=builder /root/.local /home/appuser/.local - -# Copy application code -COPY . . - -# Set file permissions -RUN chown -R appuser:appuser /app -RUN chmod +x scripts/start.sh scripts/prestart.sh - -# Add Python package path to PATH -ENV PATH=/home/appuser/.local/bin:$PATH - -# Switch to non-root user -USER appuser - -# Configure health check -HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \ - CMD curl -f http://localhost:8000/health || exit 1 - -# Expose port -EXPOSE 8000 - -# Execute startup script -CMD ["./scripts/start.sh"] -``` - -### Docker-Compose-Entwicklungsumgebung (`docker-compose.yml`) - -```yaml -version: '3.8' - -services: - app: - build: - context: . - dockerfile: Dockerfile - container_name: dockerized-todo-api - restart: unless-stopped - ports: - - "8000:8000" - environment: - - ENVIRONMENT=development - - DEBUG=true - - RELOAD=true - volumes: - # Mount volume for development (auto-reload on code changes) - - ./src:/app/src:ro - - ./scripts:/app/scripts:ro - networks: - - app-network - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:8000/health"] - interval: 30s - timeout: 10s - retries: 3 - start_period: 40s - - # Redis (für Caching und Session-Speicher) - redis: - image: redis:7-alpine - container_name: dockerized-todo-redis - restart: unless-stopped - ports: - - "6379:6379" - volumes: - - redis_data:/data - networks: - - app-network - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 30s - timeout: 10s - retries: 3 - - # Nginx (reverse proxy) - nginx: - image: nginx:alpine - container_name: dockerized-todo-nginx - restart: unless-stopped - ports: - - "80:80" - - "443:443" - volumes: - - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro - - ./nginx/ssl:/etc/nginx/ssl:ro - depends_on: - - app - networks: - - app-network - healthcheck: - test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost/health"] - interval: 30s - timeout: 10s - retries: 3 - -volumes: - redis_data: - -networks: - app-network: - driver: bridge -``` - -### Docker-Compose-Produktionsumgebung (`docker-compose.prod.yml`) - -```yaml -version: '3.8' - -services: - app: - build: - context: . - dockerfile: Dockerfile - restart: always - environment: - - ENVIRONMENT=production - - DEBUG=false - - WORKERS=4 - - MAX_WORKERS=8 - volumes: - - app_logs:/app/logs - networks: - - app-network - deploy: - replicas: 2 - resources: - limits: - cpus: '1.0' - memory: 1G - reservations: - cpus: '0.5' - memory: 512M - restart_policy: - condition: on-failure - delay: 5s - max_attempts: 3 - - redis: - image: redis:7-alpine - restart: always - command: redis-server --appendonly yes --requirepass ${REDIS_PASSWORD} - volumes: - - redis_data:/data - networks: - - app-network - deploy: - resources: - limits: - cpus: '0.5' - memory: 512M - - nginx: - image: nginx:alpine - restart: always - ports: - - "80:80" - - "443:443" - volumes: - - ./nginx/nginx.prod.conf:/etc/nginx/nginx.conf:ro - - ./nginx/ssl:/etc/nginx/ssl:ro - - nginx_logs:/var/log/nginx - depends_on: - - app - networks: - - app-network - deploy: - resources: - limits: - cpus: '0.5' - memory: 256M - -volumes: - redis_data: - app_logs: - nginx_logs: - -networks: - app-network: - driver: overlay - attachable: true -``` - -## Schritt 3: Startskripte konfigurieren - -### Haupt-Startskript (`scripts/start.sh`) - -```bash -#!/bin/bash - -set -e - -# Set environment variables -export PYTHONPATH=/app:$PYTHONPATH - -# Run pre-start script -echo "Running pre-start script..." -./scripts/prestart.sh - -# Determine execution mode based on environment -if [[ "$ENVIRONMENT" == "production" ]]; then - echo "Starting production server with Gunicorn..." - exec gunicorn src.main:app \ - --config scripts/gunicorn.conf.py \ - --bind 0.0.0.0:8000 \ - --workers ${WORKERS:-4} \ - --worker-class uvicorn.workers.UvicornWorker \ - --max-requests 1000 \ - --max-requests-jitter 100 \ - --preload \ - --access-logfile - \ - --error-logfile - -else - echo "Starting development server with Uvicorn..." - if [[ "$RELOAD" == "true" ]]; then - exec uvicorn src.main:app \ - --host 0.0.0.0 \ - --port 8000 \ - --reload \ - --reload-dir src \ - --log-level debug - else - exec uvicorn src.main:app \ - --host 0.0.0.0 \ - --port 8000 \ - --log-level info - fi -fi -``` - -### Pre-Start-Skript (`scripts/prestart.sh`) - -```bash -#!/bin/bash - -set -e - -echo "Running pre-start checks..." - -# Check Python modules and dependencies -echo "Checking Python dependencies..." -python -c "import fastapi, uvicorn, pydantic; print('✓ Core dependencies OK')" - -# Check environment variables -if [[ -z "$ENVIRONMENT" ]]; then - export ENVIRONMENT="development" - echo "ℹ ENVIRONMENT not set, defaulting to development" -fi - -# Create log directory -mkdir -p /app/logs -touch /app/logs/app.log - -# Check if health endpoint is present -echo "Checking health endpoint..." -python -c " -from src.main import app -routes = [route.path for route in app.routes] -if '/health' not in routes: - print('⚠ Warning: /health endpoint not found') -else: - print('✓ Health endpoint OK') -" - -echo "Pre-start checks completed successfully!" -``` - -### Gunicorn-Konfiguration (`scripts/gunicorn.conf.py`) - -```python -import multiprocessing -import os - -# Server socket -bind = "0.0.0.0:8000" -backlog = 2048 - -# Worker process -workers = int(os.getenv("WORKERS", multiprocessing.cpu_count() * 2 + 1)) -worker_class = "uvicorn.workers.UvicornWorker" -worker_connections = 1000 -max_requests = 1000 -max_requests_jitter = 100 - -# Worker restart settings -preload_app = True -timeout = 120 -keepalive = 2 - -# Logging -accesslog = "-" -errorlog = "-" -loglevel = "info" -access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(D)s' - -# Process name -proc_name = "dockerized-todo-api" - -# Security -limit_request_line = 4094 -limit_request_fields = 100 -limit_request_field_size = 8190 - -# Performance tuning -def when_ready(server): - server.log.info("Server is ready. Spawning workers") - -def worker_int(worker): - worker.log.info("worker received INT or QUIT signal") - -def pre_fork(server, worker): - server.log.info("Worker spawned (pid: %s)", worker.pid) - -def post_fork(server, worker): - server.log.info("Worker spawned (pid: %s)", worker.pid) - -def worker_abort(worker): - worker.log.info("worker received SIGABRT signal") -``` - -## Schritt 4: Health-Check und Monitoring implementieren - -### Health-Check-Endpunkt hinzufügen (`src/main.py`) - -```python -from fastapi import FastAPI, status, Depends -from fastapi.responses import JSONResponse -import psutil -import time -from datetime import datetime - -app = FastAPI( - title="Dockerized Todo API", - description="Dockerized todo management API", - version="1.0.0" -) - -# Application start time -start_time = time.time() - -@app.get("/health", status_code=status.HTTP_200_OK) -async def health_check(): - """ - Container health check endpoint - """ - current_time = time.time() - uptime = current_time - start_time - - # System resource information - memory_info = psutil.virtual_memory() - cpu_percent = psutil.cpu_percent(interval=1) - - health_data = { - "status": "healthy", - "timestamp": datetime.utcnow().isoformat(), - "uptime_seconds": round(uptime, 2), - "version": app.version, - "system": { - "memory_usage_percent": memory_info.percent, - "memory_available_mb": round(memory_info.available / 1024 / 1024, 2), - "cpu_usage_percent": cpu_percent, - }, - "checks": { - "database": await check_database_connection(), - "redis": await check_redis_connection(), - "disk_space": check_disk_space(), - } - } - - # Check if all checks passed - all_checks_passed = all(health_data["checks"].values()) - - if not all_checks_passed: - return JSONResponse( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - content=health_data - ) - - return health_data - -async def check_database_connection() -> bool: - """Check database connection status""" - try: - # In der echten Implementierung sollte hier die Datenbankverbindung geprüft werden - return True - except Exception: - return False - -async def check_redis_connection() -> bool: - """Status der Redis-Verbindung prüfen""" - try: - # In einer echten Implementierung würde hier die Redis-Verbindung geprüft - return True - except Exception: - return False - -def check_disk_space() -> bool: - """Check disk space""" - disk_usage = psutil.disk_usage('/') - free_percentage = (disk_usage.free / disk_usage.total) * 100 - return free_percentage > 10 # 10% or more free space needed - -@app.get("/health/ready", status_code=status.HTTP_200_OK) -async def readiness_check(): - """ - Kubernetes readiness probe endpoint - """ - # Check if application is ready to receive traffic - return {"status": "ready", "timestamp": datetime.utcnow().isoformat()} - -@app.get("/health/live", status_code=status.HTTP_200_OK) -async def liveness_check(): - """ - Kubernetes liveness probe endpoint - """ - return {"status": "alive", "timestamp": datetime.utcnow().isoformat()} -``` - -## Schritt 5: Nginx-Reverse-Proxy konfigurieren - -### Nginx-Konfiguration für die Entwicklung (`nginx/nginx.conf`) - -```nginx -events { - worker_connections 1024; -} - -http { - upstream fastapi_backend { - # Specify backend by container name - server app:8000; - } - - # Define log format - log_format main '$remote_addr - $remote_user [$time_local] "$request" ' - '$status $body_bytes_sent "$http_referer" ' - '"$http_user_agent" "$http_x_forwarded_for" ' - 'rt=$request_time uct="$upstream_connect_time" ' - 'uht="$upstream_header_time" urt="$upstream_response_time"'; - - access_log /var/log/nginx/access.log main; - error_log /var/log/nginx/error.log warn; - - # Default settings - sendfile on; - tcp_nopush on; - tcp_nodelay on; - keepalive_timeout 65; - types_hash_max_size 2048; - client_max_body_size 100M; - - # Gzip compression - gzip on; - gzip_vary on; - gzip_min_length 1024; - gzip_types text/plain text/css text/xml text/javascript - application/json application/javascript application/xml+rss - application/atom+xml image/svg+xml; - - server { - listen 80; - server_name localhost; - - # Security headers - add_header X-Content-Type-Options nosniff; - add_header X-Frame-Options DENY; - add_header X-XSS-Protection "1; mode=block"; - - # Health check endpoint - location /health { - proxy_pass http://fastapi_backend; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - - # Health check should respond quickly - proxy_connect_timeout 5s; - proxy_send_timeout 5s; - proxy_read_timeout 5s; - } - - # API endpoint - location / { - proxy_pass http://fastapi_backend; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - - # Timeout settings - proxy_connect_timeout 30s; - proxy_send_timeout 30s; - proxy_read_timeout 30s; - - # Buffering settings - proxy_buffering on; - proxy_buffer_size 4k; - proxy_buffers 8 4k; - } - - # Static file caching (future use) - location /static { - expires 1y; - add_header Cache-Control public; - add_header ETag ""; - } - } -} -``` - -### Nginx-Konfiguration für die Produktion (`nginx/nginx.prod.conf`) - -```nginx -events { - worker_connections 2048; -} - -http { - upstream fastapi_backend { - # Load balancing for multiple app instances - server app:8000 max_fails=3 fail_timeout=30s; - # server app2:8000 max_fails=3 fail_timeout=30s; # For scaling - - # Keep-alive - keepalive 32; - } - - # Security settings - server_tokens off; - - # Rate limiting - limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; - limit_req_zone $binary_remote_addr zone=health:10m rate=100r/s; - - # SSL settings - ssl_protocols TLSv1.2 TLSv1.3; - ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384; - ssl_prefer_server_ciphers off; - ssl_session_cache shared:SSL:10m; - ssl_session_timeout 10m; - - server { - listen 80; - server_name your-domain.com; - return 301 https://$server_name$request_uri; - } - - server { - listen 443 ssl http2; - server_name your-domain.com; - - ssl_certificate /etc/nginx/ssl/cert.pem; - ssl_certificate_key /etc/nginx/ssl/key.pem; - - # Security headers - add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; - add_header X-Content-Type-Options nosniff always; - add_header X-Frame-Options DENY always; - add_header X-XSS-Protection "1; mode=block" always; - add_header Referrer-Policy "strict-origin-when-cross-origin" always; - - # Health check (rate limit applied) - location /health { - limit_req zone=health burst=20 nodelay; - proxy_pass http://fastapi_backend; - include /etc/nginx/proxy_params; - } - - # API endpoint (rate limit applied) - location / { - limit_req zone=api burst=20 nodelay; - proxy_pass http://fastapi_backend; - include /etc/nginx/proxy_params; - } - } -} -``` - -## Schritt 6: Container bauen und starten - -### In der Entwicklungsumgebung ausführen - -
- -```console -$ cd dockerized-todo-api - -# Build Docker image -$ docker-compose build -Building app -Step 1/15 : FROM python:3.12-slim as builder - ---> abc123def456 -Step 2/15 : RUN apt-get update && apt-get install -y build-essential curl - ---> Running in xyz789abc123 -... -Successfully built def456ghi789 -Successfully tagged dockerized-todo-api_app:latest - -# Run container (background) -$ docker-compose up -d -Creating network "dockerized-todo-api_app-network" with driver "bridge" -Creating volume "dockerized-todo-api_redis_data" with default driver -Creating dockerized-todo-redis ... done -Creating dockerized-todo-api ... done -Creating dockerized-todo-nginx ... done - -# Check container status -$ docker-compose ps - Name Command State Ports ------------------------------------------------------------------------------------------------- -dockerized-todo-api ./scripts/start.sh Up (healthy) 8000/tcp -dockerized-todo-nginx /docker-entrypoint.sh ngin ... Up 0.0.0.0:80->80/tcp, :::80->80/tcp -dockerized-todo-redis docker-entrypoint.sh redis ... Up (healthy) 0.0.0.0:6379->6379/tcp, :::6379->6379/tcp -``` - -
- -### Logs prüfen - -
- -```console -# Check all service logs -$ docker-compose logs - -# Check specific service logs -$ docker-compose logs app -$ docker-compose logs nginx -$ docker-compose logs redis - -# Check real-time logs -$ docker-compose logs -f app -``` - -
- -### Health-Check-Test - -
- -```console -# Basic health check -$ curl http://localhost/health -{ - "status": "healthy", - "timestamp": "2024-01-01T12:00:00.123456", - "uptime_seconds": 45.67, - "version": "1.0.0", - "system": { - "memory_usage_percent": 25.3, - "memory_available_mb": 3072.45, - "cpu_usage_percent": 5.2 - }, - "checks": { - "database": true, - "redis": true, - "disk_space": true - } -} - -# Kubernetes probe test -$ curl http://localhost/health/ready -$ curl http://localhost/health/live -``` - -
- -## Schritt 7: Produktionsdeployment - -### Umgebungsvariablen setzen (`.env.prod`) - -```bash -# Application settings -ENVIRONMENT=production -DEBUG=false -SECRET_KEY=your-super-secret-key-here -WORKERS=4 - -# Database settings -DATABASE_URL=postgresql://user:password@db:5432/todoapp -REDIS_URL=redis://:password@redis:6379/0 -REDIS_PASSWORD=your-redis-password - -# Logging settings -LOG_LEVEL=info -LOG_FILE=/app/logs/app.log - -# Security settings -ALLOWED_HOSTS=["your-domain.com"] -CORS_ORIGINS=["https://your-frontend.com"] - -# Monitoring -SENTRY_DSN=https://your-sentry-dsn@sentry.io/project-id -``` - -### Befehle für das Produktionsdeployment - -
- -```console -# Deploy in production environment -$ docker-compose -f docker-compose.prod.yml --env-file .env.prod up -d - -# Scaling (app instance scaling) -$ docker-compose -f docker-compose.prod.yml up -d --scale app=3 - -# Rolling update -$ docker-compose -f docker-compose.prod.yml build app -$ docker-compose -f docker-compose.prod.yml up -d --no-deps app - -# Safe shutdown before backup -$ docker-compose -f docker-compose.prod.yml down --timeout 30 -``` - -
- -## Schritt 8: Monitoring und Logging - -### Ressourcen-Monitoring von Docker-Containern - -
- -```console -# Check real-time resource usage -$ docker stats - -CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS -abc123def456 dockerized-todo-api 2.34% 128.5MiB / 1GiB 12.55% 1.23MB / 456kB 12.3MB / 4.56MB 15 -def456ghi789 dockerized-todo-nginx 0.12% 12.5MiB / 256MiB 4.88% 456kB / 1.23MB 1.23MB / 456kB 3 -ghi789jkl012 dockerized-todo-redis 1.45% 32.1MiB / 512MiB 6.27% 789kB / 2.34MB 4.56MB / 1.23MB 4 - -# Check specific container details -$ docker inspect dockerized-todo-api - -# Check container internal processes -$ docker-compose exec app ps aux -``` - -
- -### Log-Aggregation und -Analyse - -```yaml -# docker-compose.logging.yml -version: '3.8' - -services: - # ELK Stack for log aggregation - elasticsearch: - image: docker.elastic.co/elasticsearch/elasticsearch:8.6.0 - environment: - - discovery.type=single-node - - xpack.security.enabled=false - volumes: - - elasticsearch_data:/usr/share/elasticsearch/data - networks: - - logging - - logstash: - image: docker.elastic.co/logstash/logstash:8.6.0 - volumes: - - ./logstash/pipeline:/usr/share/logstash/pipeline:ro - - ./logstash/config:/usr/share/logstash/config:ro - networks: - - logging - depends_on: - - elasticsearch - - kibana: - image: docker.elastic.co/kibana/kibana:8.6.0 - ports: - - "5601:5601" - environment: - - ELASTICSEARCH_HOSTS=http://elasticsearch:9200 - networks: - - logging - depends_on: - - elasticsearch - - # Fluentd for log collection - fluentd: - image: fluent/fluentd:v1.16-debian-1 - volumes: - - ./fluentd/conf:/fluentd/etc:ro - - /var/log:/var/log:ro - networks: - - logging - depends_on: - - elasticsearch - -volumes: - elasticsearch_data: - -networks: - logging: - driver: bridge -``` - -### Prometheus-Metriken sammeln - -```python -# src/monitoring.py -from prometheus_client import Counter, Histogram, Gauge, generate_latest -from fastapi import Request, Response -import time - -# Define metrics -REQUEST_COUNT = Counter( - 'http_requests_total', - 'Total HTTP requests', - ['method', 'endpoint', 'status_code'] -) - -REQUEST_DURATION = Histogram( - 'http_request_duration_seconds', - 'HTTP request duration in seconds', - ['method', 'endpoint'] -) - -ACTIVE_CONNECTIONS = Gauge( - 'active_connections', - 'Number of active connections' -) - -async def metrics_middleware(request: Request, call_next): - """Prometheus metric collection middleware""" - start_time = time.time() - method = request.method - endpoint = request.url.path - - ACTIVE_CONNECTIONS.inc() - - try: - response = await call_next(request) - status_code = response.status_code - except Exception as e: - status_code = 500 - raise - finally: - duration = time.time() - start_time - REQUEST_DURATION.labels(method=method, endpoint=endpoint).observe(duration) - REQUEST_COUNT.labels(method=method, endpoint=endpoint, status_code=status_code).inc() - ACTIVE_CONNECTIONS.dec() - - return response - -@app.get("/metrics") -async def get_metrics(): - """Prometheus metric endpoint""" - return Response(generate_latest(), media_type="text/plain") -``` - -## Schritt 9: CI/CD-Pipeline aufbauen - -### GitHub-Actions-Workflow (`.github/workflows/deploy.yml`) - -```yaml -name: Deploy to Production - -on: - push: - branches: [main] - pull_request: - branches: [main] - -env: - REGISTRY: ghcr.io - IMAGE_NAME: ${{ github.repository }} - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Set up Python - uses: actions/setup-python@v4 - with: - python-version: '3.12' - - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install -r requirements.txt - pip install pytest pytest-asyncio httpx - - - name: Run tests - run: | - pytest tests/ -v --cov=src --cov-report=xml - - - name: Upload coverage reports - uses: codecov/codecov-action@v3 - with: - file: ./coverage.xml - - build: - needs: test - runs-on: ubuntu-latest - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - - steps: - - uses: actions/checkout@v4 - - - name: Log in to Container Registry - uses: docker/login-action@v3 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Extract metadata - id: meta - uses: docker/metadata-action@v5 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - tags: | - type=ref,event=branch - type=ref,event=pr - type=sha - type=raw,value=latest - - - name: Build and push Docker image - uses: docker/build-push-action@v5 - with: - context: . - file: ./Dockerfile - push: true - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max - - deploy: - needs: build - runs-on: ubuntu-latest - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - - steps: - - uses: actions/checkout@v4 - - - name: Deploy to production - uses: appleboy/ssh-action@v1.0.0 - with: - host: ${{ secrets.PROD_HOST }} - username: ${{ secrets.PROD_USERNAME }} - key: ${{ secrets.PROD_SSH_KEY }} - script: | - cd /opt/dockerized-todo-api - - # Pull new image - docker-compose -f docker-compose.prod.yml pull - - # Rolling update - docker-compose -f docker-compose.prod.yml up -d --no-deps app - - # Health check - sleep 30 - curl -f http://localhost/health || exit 1 - - # Clean up previous image - docker image prune -f -``` - -## Schritt 10: Sicherheit verbessern - -### Sicherheitsoptionen für Container - -```dockerfile -# Add security enhancement to Dockerfile - -# Run as non-root user -USER appuser - -# Read-only root filesystem -# docker run --read-only --tmpfs /tmp dockerized-todo-api - -# Limit permissions -# docker run --cap-drop=ALL dockerized-todo-api - -# Network isolation -# docker run --network=none dockerized-todo-api -``` - -### Sicherheitsoptionen für Docker Compose - -```yaml -# Add security settings to docker-compose.yml -services: - app: - # ... existing settings ... - security_opt: - - no-new-privileges:true - cap_drop: - - ALL - cap_add: - - NET_BIND_SERVICE - read_only: true - tmpfs: - - /tmp - - /app/logs - user: "1000:1000" -``` - -### Secrets-Verwaltung - -```yaml -# Add secrets settings to docker-compose.yml -version: '3.8' - -services: - app: - secrets: - - db_password - - api_key - environment: - - DB_PASSWORD_FILE=/run/secrets/db_password - - API_KEY_FILE=/run/secrets/api_key - -secrets: - db_password: - file: ./secrets/db_password.txt - api_key: - external: true -``` - -## Nächste Schritte - -Sie haben die Docker-Containerisierung abgeschlossen! Nächste Schritte zum Ausprobieren: - -1. **[Benutzerdefinierte Antwortbehandlung](custom-response-handling.md)** — fortgeschrittene API-Antwortformate implementieren - - - - - -## Zusammenfassung - -In diesem Tutorial haben wir mit Docker: - -- ✅ Optimierte Container-Images mit mehrstufigen Builds erstellt -- ✅ Entwicklungs-/Produktionsumgebungen mit Docker Compose eingerichtet -- ✅ Nginx-Reverse-Proxy und Lastverteilung konfiguriert -- ✅ Health-Check- und Monitoring-Systeme aufgebaut -- ✅ Automatisiertes Deployment über CI/CD-Pipelines implementiert -- ✅ Produktionsreife Sicherheitsoptionen konfiguriert -- ✅ Systeme für Logging und Metrik-Sammlung implementiert - -Jetzt können Sie FastAPI-Anwendungen sicher und effizient in Produktionsumgebungen deployen! diff --git a/docs/de/tutorial/domain-starter.md b/docs/de/tutorial/domain-starter.md index c06775c..a46cf4b 100644 --- a/docs/de/tutorial/domain-starter.md +++ b/docs/de/tutorial/domain-starter.md @@ -363,7 +363,7 @@ Ein erneutes Ausführen von `addroute` erhält bestehende Domänendateien, erste - Die [Architektur-Preset-Matrix](../reference/preset-feature-matrix.md) zeigt, was `fastkit init --interactive` für jedes Preset generiert, einschließlich der Funktionsauswahlen, die unter `domain-starter` manuelle Verdrahtung benötigen. - Das [`fastapi-default`-Tutorial](basic-api-server.md) behandelt die geschichtete Alternative, falls Sie Layouts vergleichen möchten, bevor Sie sich festlegen. -- Für die Datenbankintegration zeigt das [Tutorial Datenbankintegration](database-integration.md) das Muster PostgreSQL + SQLAlchemy + Alembic. Dieselben Ideen passen in `src/app/db/` und die `repository.py`-Dateien je Domäne. +- Für die Datenbankanbindung zeigt das [SQLModel-Tutorial](sqlmodel.md) das Muster asynchrones SQLModel + Alembic. Dieselben Ideen passen in `src/app/db/` und die `repository.py`-Dateien je Domäne. ## Rückblick diff --git a/docs/de/tutorial/first-project.md b/docs/de/tutorial/first-project.md index 26cf657..0aa0222 100644 --- a/docs/de/tutorial/first-project.md +++ b/docs/de/tutorial/first-project.md @@ -1238,7 +1238,7 @@ Glückwunsch! Sie haben erfolgreich eine vollständige Blog-API gebaut mit: ### Weiter lernen -1. **[Vorlagen verwenden](../user-guide/using-templates.md)**: erkunden Sie die Vorlage `fastapi-psql-orm` für Datenbankintegration +1. **[Vorlagen verwenden](../user-guide/using-templates.md)**: erkunden Sie die Vorlage `fastapi-sqlmodel` für Datenbankintegration 2. **[Routen hinzufügen](../user-guide/adding-routes.md)**: lernen Sie fortgeschrittenere Routenmuster 3. **[Mitwirken](../contributing/development-setup.md)**: tragen Sie zu FastAPI-fastkit bei diff --git a/docs/de/tutorial/sqlmodel.md b/docs/de/tutorial/sqlmodel.md index c0a6d5b..d90b800 100644 --- a/docs/de/tutorial/sqlmodel.md +++ b/docs/de/tutorial/sqlmodel.md @@ -16,7 +16,7 @@ Bauen Sie eine datenbankgestützte API, in der jedes Konzept **einmal** definier - FastAPI-fastkit installiert (`pip install fastapi-fastkit`) - Vertrautheit mit `async`/`await` und grundlegenden SQL-Konzepten -Wenn Sie stattdessen den synchronen, Compose-basierten PostgreSQL-Stack möchten, lesen Sie [Datenbankintegration](database-integration.md), das `fastapi-psql-orm` verwendet. +`fastapi-sqlmodel` funktioniert mit SQLite, PostgreSQL oder MySQL über eine einzige `DATABASE_URL`. ## Schritt 1: Generieren und ausführen diff --git a/docs/de/user-guide/choosing-a-starter.md b/docs/de/user-guide/choosing-a-starter.md index 2a003b5..cb667d4 100644 --- a/docs/de/user-guide/choosing-a-starter.md +++ b/docs/de/user-guide/choosing-a-starter.md @@ -13,10 +13,10 @@ Der Rest dieser Seite erklärt, warum das so ist und wann eine andere Wahl sinnv | Sie sind … | Beginnen Sie mit | |---|---| | Neu bei FastAPI und möchten eine geführte Tour | `fastkit init --interactive` (Preset: **`domain-starter`**) | +| Möchten zuerst die kleinste App lesen | `fastkit startdemo fastapi-hello` | | Möchten eine funktionierende CRUD-Demo zum Lesen und Anpassen | `fastkit startdemo fastapi-default` | | Möchten das kleinstmögliche Gerüst | `fastkit init --interactive` (Preset: **`minimal`**) | | Schreiben einen schnellen Prototyp / ein Single-File-Skript | `fastkit init --interactive` (Preset: **`single-module`**) | -| Brauchen eine echte Datenbank (PostgreSQL + SQLAlchemy + Alembic) | `fastkit startdemo fastapi-psql-orm` | | Möchten asynchrone Persistenz mit Migrationen und generischem CRUD | `fastkit startdemo fastapi-sqlmodel` | | Brauchen vom ersten Tag an Benutzerkonten, Login und geschützte Routen | `fastkit startdemo fastapi-auth-jwt` | | Bauen ein LLM-Chat-Backend mit Streaming und Tools | `fastkit startdemo fastapi-llm-agent` | @@ -28,7 +28,7 @@ Dies sind die beiden Haupteinstiegspunkte. Sie decken unterschiedliche Bedürfni ### `fastkit startdemo