From 2c541698f3dfc203f8da451452b603dcfbde25e3 Mon Sep 17 00:00:00 2001 From: "h.nejati" Date: Sun, 22 Nov 2026 11:57:06 +0330 Subject: [PATCH 1/2] refactor!: remove deprecated APIs for 6.0 BREAKING CHANGE: Drop flat settings and deprecated imports and adapter behaviors. Use nested config groups and the replacement APIs documented in the 6.0 upgrade guide and changelog. Refs #625 --- .env.example | 366 +++++++------- .env.test | 34 +- archipy/adapters/base/sqlalchemy/atomic.py | 56 --- archipy/adapters/email/adapters.py | 77 +-- archipy/configs/config_template.py | 2 - archipy/configs/sections/_common.py | 51 -- archipy/configs/sections/auth.py | 227 +-------- archipy/configs/sections/elasticsearch.py | 168 ------- archipy/configs/sections/email.py | 106 +--- archipy/configs/sections/fastapi.py | 238 +-------- archipy/configs/sections/grpc.py | 78 --- archipy/configs/sections/kafka.py | 84 +--- archipy/configs/sections/keycloak.py | 120 +---- archipy/configs/sections/otel.py | 68 --- archipy/configs/sections/redis.py | 145 ------ archipy/configs/sections/scylladb.py | 289 ----------- archipy/configs/sections/sqlalchemy.py | 83 ---- archipy/configs/sections/temporal.py | 332 ------------- archipy/configs/sections/uvicorn.py | 124 +---- archipy/configs/sections/vault.py | 344 +------------ archipy/configs/vault_settings_source.py | 129 +++-- archipy/helpers/_deprecation.py | 54 -- archipy/helpers/decorators/__init__.py | 123 +---- archipy/helpers/decorators/_legacy_modules.py | 11 - archipy/helpers/decorators/cache.py | 5 - archipy/helpers/decorators/grpc_rate_limit.py | 5 - .../decorators/grpc_rate_limit_window.py | 4 - archipy/helpers/decorators/metrics.py | 71 +-- archipy/helpers/decorators/retry.py | 5 - archipy/helpers/decorators/retry_policy.py | 4 - archipy/helpers/decorators/singleton.py | 5 - archipy/helpers/decorators/singleton_class.py | 5 - .../helpers/decorators/sqlalchemy_atomic.py | 15 - .../decorators/sqlalchemy_transaction.py | 60 --- archipy/helpers/decorators/timeout.py | 5 - archipy/helpers/decorators/timeout_limit.py | 4 - archipy/helpers/decorators/timing.py | 5 - archipy/helpers/decorators/timing_log.py | 5 - archipy/helpers/decorators/tracing.py | 96 +--- archipy/helpers/decorators/ttl_caching.py | 4 - .../helpers/utils/_otel/logging_handler.py | 8 +- archipy/helpers/utils/app_utils.py | 62 +-- archipy/helpers/utils/base_utils.py | 3 +- archipy/helpers/utils/error_utils.py | 66 --- archipy/helpers/utils/keycloak_utils.py | 53 -- archipy/models/dtos/keycloak/__init__.py | 2 - archipy/models/dtos/keycloak/base.py | 46 +- archipy/models/dtos/keycloak_dtos.py | 8 - docs/api_reference/configs.md | 3 +- docs/api_reference/helpers/decorators.md | 17 +- docs/api_reference/helpers/utils.md | 16 +- docs/community/changelog/5/5.10.0.md | 2 +- docs/community/changelog/5/5.32.0.md | 2 +- docs/community/changelog/6/6.0.0.md | 69 +++ docs/community/changelog/6/index.md | 12 + docs/community/changelog/index.md | 4 + docs/community/deprecations.md | 468 ++++++++++++++---- docs/community/faq.md | 4 +- docs/tutorials/adapters/elasticsearch.md | 38 +- docs/tutorials/adapters/email.md | 47 +- docs/tutorials/adapters/kafka.md | 28 +- docs/tutorials/adapters/keycloak.md | 43 +- docs/tutorials/adapters/mysql.md | 2 +- docs/tutorials/adapters/postgres.md | 33 +- docs/tutorials/adapters/redis.md | 25 +- docs/tutorials/adapters/scylladb.md | 42 +- docs/tutorials/adapters/sqlalchemy.md | 8 +- docs/tutorials/adapters/sqlite.md | 4 +- docs/tutorials/adapters/starrocks.md | 2 +- docs/tutorials/adapters/temporal.md | 47 +- docs/tutorials/adapters/vault.md | 50 +- docs/tutorials/cache.md | 5 - docs/tutorials/config_management.md | 14 +- docs/tutorials/helpers/decorators.md | 28 +- docs/tutorials/helpers/utils.md | 15 +- docs/tutorials/observability.md | 6 +- features/app_utils.feature | 115 +---- features/base_config.feature | 81 ++- features/decorators.feature | 77 --- features/elastic_adapter.feature | 18 +- features/email_adapter.feature | 67 +-- features/environment.py | 2 +- features/jwt_utils.feature | 4 - features/kafka_clients_spans.feature | 18 +- features/keycloak_adapter_management.feature | 33 +- features/keycloak_auth_guards.feature | 34 +- features/keycloak_dtos.feature | 24 +- features/redis_adapter.feature | 13 +- features/scylladb_adapter.feature | 10 +- features/steps/app_utils_steps.py | 49 +- features/steps/atomic_transaction_steps.py | 2 +- features/steps/base_config_steps.py | 275 +++------- .../steps/deprecation_decorators_steps.py | 92 ---- features/steps/elastic_adapter_steps.py | 20 +- features/steps/email_adapter_steps.py | 41 +- features/steps/jwt_utils_steps.py | 12 - features/steps/kafka_adapter_steps.py | 72 ++- features/steps/keycloak_adapter_steps.py | 105 ++-- features/steps/keycloak_auth_steps.py | 122 ++--- features/steps/keycloak_authz_uma_steps.py | 45 +- features/steps/keycloak_chaining_steps.py | 4 +- features/steps/keycloak_dtos_steps.py | 65 +-- features/steps/keycloak_realms_extra_steps.py | 18 +- features/steps/password_utils_steps.py | 4 +- features/steps/redis_adapter_steps.py | 58 +-- features/steps/scylladb_adapter_steps.py | 41 +- features/steps/temporal_adapter_steps.py | 18 - features/steps/vault_adapter_steps.py | 30 +- features/temporal_adapter.feature | 5 - features/temporal_schedules_errors.feature | 7 - features/test_containers.py | 24 +- features/vault_adapter.feature | 32 +- mkdocs.yml | 3 +- .../adapters/elasticsearch/adapters.py | 49 +- .../kafka/archipy/adapters/kafka/adapters.py | 36 +- .../archipy/adapters/keycloak/_base.py | 22 +- .../keycloak/_protocols/oidc/adapter.py | 36 +- .../keycloak/_protocols/uma/adapter.py | 16 +- .../adapters/keycloak/_protocols/uma/port.py | 16 +- .../adapters/keycloak/_resources/__init__.py | 12 - .../_resources/authentication/adapter.py | 37 +- .../_resources/authentication/port.py | 38 +- .../_resources/authorization/adapter.py | 60 +-- .../keycloak/_resources/authorization/port.py | 60 +-- .../_resources/client_certificates/adapter.py | 9 +- .../_resources/client_certificates/port.py | 10 +- .../client_initial_access/adapter.py | 5 +- .../_resources/client_initial_access/port.py | 6 +- .../_resources/client_scopes/adapter.py | 18 +- .../keycloak/_resources/client_scopes/port.py | 18 +- .../keycloak/_resources/clients/adapter.py | 8 +- .../keycloak/_resources/clients/port.py | 8 +- .../keycloak/_resources/components/adapter.py | 8 +- .../keycloak/_resources/components/port.py | 8 +- .../keycloak/_resources/groups/adapter.py | 16 +- .../keycloak/_resources/groups/port.py | 16 +- .../_resources/identity_providers/adapter.py | 20 +- .../_resources/identity_providers/port.py | 20 +- .../_resources/organizations/adapter.py | 4 +- .../_resources/organizations/group_adapter.py | 28 +- .../_resources/organizations/group_port.py | 28 +- .../keycloak/_resources/organizations/port.py | 4 +- .../_resources/protocol_mappers/adapter.py | 25 +- .../_resources/protocol_mappers/port.py | 26 +- .../keycloak/_resources/realms/adapter.py | 24 +- .../keycloak/_resources/realms/port.py | 24 +- .../_resources/required_actions/adapter.py | 9 +- .../_resources/required_actions/port.py | 10 +- .../_resources/role_mappings/adapter.py | 17 +- .../keycloak/_resources/role_mappings/port.py | 18 +- .../keycloak/_resources/roles/adapter.py | 32 +- .../keycloak/_resources/roles/port.py | 32 +- .../_resources/roles_by_id/adapter.py | 16 +- .../keycloak/_resources/roles_by_id/port.py | 16 +- .../_resources/scope_mappings/adapter.py | 33 +- .../_resources/scope_mappings/port.py | 34 +- .../keycloak/_resources/users/adapter.py | 16 +- .../keycloak/_resources/users/port.py | 16 +- .../adapters/keycloak/_type_aliases.py | 14 - .../archipy/adapters/keycloak/auth.py | 30 +- .../adapters/keycloak/deprecated_state.py | 93 ---- .../archipy/adapters/keycloak/ports.py | 12 - .../redis/archipy/adapters/redis/search.py | 21 +- .../archipy/adapters/redis/search_ports.py | 8 +- .../archipy/adapters/scylladb/adapters.py | 31 -- .../archipy/adapters/temporal/adapters.py | 18 - .../archipy/adapters/temporal/base.py | 2 +- .../archipy/adapters/temporal/ports.py | 10 +- .../archipy/adapters/temporal/tracing.py | 2 - .../archipy/adapters/temporal/worker.py | 22 +- pyproject.toml | 3 - 171 files changed, 1916 insertions(+), 5843 deletions(-) delete mode 100644 archipy/configs/sections/_common.py delete mode 100644 archipy/helpers/_deprecation.py delete mode 100644 archipy/helpers/decorators/_legacy_modules.py delete mode 100644 archipy/helpers/decorators/cache.py delete mode 100644 archipy/helpers/decorators/grpc_rate_limit.py delete mode 100644 archipy/helpers/decorators/retry.py delete mode 100644 archipy/helpers/decorators/singleton.py delete mode 100644 archipy/helpers/decorators/sqlalchemy_atomic.py delete mode 100644 archipy/helpers/decorators/sqlalchemy_transaction.py delete mode 100644 archipy/helpers/decorators/timeout.py delete mode 100644 archipy/helpers/decorators/timing.py delete mode 100644 archipy/helpers/utils/error_utils.py delete mode 100644 archipy/helpers/utils/keycloak_utils.py delete mode 100644 archipy/models/dtos/keycloak_dtos.py create mode 100644 docs/community/changelog/6/6.0.0.md create mode 100644 docs/community/changelog/6/index.md delete mode 100644 packages/keycloak/archipy/adapters/keycloak/deprecated_state.py diff --git a/.env.example b/.env.example index be2a7e9a2..76b7fcf11 100644 --- a/.env.example +++ b/.env.example @@ -8,35 +8,35 @@ LANGUAGE=FA # Authentication Configuration # JWT signing key: random, at least 32 bytes for HS256 (48 for HS384, 64 for HS512) AUTH__SECRET_KEY= -AUTH__ACCESS_TOKEN_EXPIRES_IN=3600 -AUTH__REFRESH_TOKEN_EXPIRES_IN=86400 -AUTH__HASH_ALGORITHM=HS256 -AUTH__JWT_ISSUER=your-app-name -AUTH__JWT_AUDIENCE=your-app-audience -AUTH__TOKEN_VERSION=1 -AUTH__TOTP_SECRET_KEY= -AUTH__TOTP_HASH_ALGORITHM=SHA1 -AUTH__TOTP_LENGTH=6 -AUTH__TOTP_EXPIRES_IN=300 -AUTH__TOTP_TIME_STEP=30 -AUTH__TOTP_VERIFICATION_WINDOW=1 -AUTH__TOTP_MAX_ATTEMPTS=3 -AUTH__TOTP_LOCKOUT_TIME=300 -AUTH__LOGIN_RATE_LIMIT=5 -AUTH__TOTP_RATE_LIMIT=3 -AUTH__PASSWORD_RESET_RATE_LIMIT=3 -AUTH__HASH_ITERATIONS=600000 -AUTH__MIN_LENGTH=12 -AUTH__REQUIRE_DIGIT=true -AUTH__REQUIRE_LOWERCASE=true -AUTH__REQUIRE_SPECIAL=true -AUTH__REQUIRE_UPPERCASE=true -AUTH__SALT_LENGTH=16 -AUTH__SPECIAL_CHARACTERS=!@#$%^&*()-_+= -AUTH__PASSWORD_HISTORY_SIZE=3 -AUTH__ENABLE_JTI_CLAIM=true -AUTH__ENABLE_TOKEN_ROTATION=true -AUTH__REFRESH_TOKEN_REUSE_INTERVAL=60 +AUTH__JWT__ACCESS_TOKEN_EXPIRES_IN=3600 +AUTH__JWT__REFRESH_TOKEN_EXPIRES_IN=86400 +AUTH__JWT__ALGORITHM=HS256 +AUTH__JWT__ISSUER=your-app-name +AUTH__JWT__AUDIENCE=your-app-audience +AUTH__JWT__TOKEN_VERSION=1 +AUTH__TOTP__SECRET_KEY= +AUTH__TOTP__HASH_ALGORITHM=SHA1 +AUTH__TOTP__LENGTH=6 +AUTH__TOTP__EXPIRES_IN=300 +AUTH__TOTP__TIME_STEP=30 +AUTH__TOTP__VERIFICATION_WINDOW=1 +AUTH__TOTP__MAX_ATTEMPTS=3 +AUTH__TOTP__LOCKOUT_TIME=300 +AUTH__RATE_LIMITS__LOGIN=5 +AUTH__RATE_LIMITS__TOTP=3 +AUTH__RATE_LIMITS__PASSWORD_RESET=3 +AUTH__PASSWORD_POLICY__HASH_ITERATIONS=600000 +AUTH__PASSWORD_POLICY__MIN_LENGTH=12 +AUTH__PASSWORD_POLICY__REQUIRE_DIGIT=true +AUTH__PASSWORD_POLICY__REQUIRE_LOWERCASE=true +AUTH__PASSWORD_POLICY__REQUIRE_SPECIAL=true +AUTH__PASSWORD_POLICY__REQUIRE_UPPERCASE=true +AUTH__PASSWORD_POLICY__SALT_LENGTH=16 +AUTH__PASSWORD_POLICY__SPECIAL_CHARACTERS=["!","@","#","$","%","^","&","*","(",")","-","_","+","="] +AUTH__PASSWORD_POLICY__HISTORY_SIZE=3 +AUTH__JWT__ENABLE_JTI_CLAIM=true +AUTH__JWT__ENABLE_TOKEN_ROTATION=true +AUTH__JWT__REFRESH_TOKEN_REUSE_INTERVAL=60 # Datetime Configuration DATETIME__TIME_IR_API_KEY=ZAVdqwuySASubByCed5KYuYMzb9uB2f7 @@ -48,25 +48,25 @@ DATETIME__HISTORICAL_CACHE_TTL=604800 # Elasticsearch Configuration ELASTIC__HOSTS=["https://localhost:9200"] -ELASTIC__HTTP_USER_NAME= -ELASTIC__HTTP_PASSWORD= -ELASTIC__API_KEY= -ELASTIC__API_SECRET= -ELASTIC__CA_CERTS= -ELASTIC__SSL_ASSERT_FINGERPRINT= -ELASTIC__VERIFY_CERTS=true -ELASTIC__CLIENT_CERT= -ELASTIC__CLIENT_KEY= +ELASTIC__AUTH__USER_NAME= +ELASTIC__AUTH__PASSWORD= +ELASTIC__AUTH__API_KEY= +ELASTIC__AUTH__API_SECRET= +ELASTIC__TLS__CA_CERTS= +ELASTIC__TLS__ASSERT_FINGERPRINT= +ELASTIC__TLS__VERIFY_CERTS=true +ELASTIC__TLS__CLIENT_CERT= +ELASTIC__TLS__CLIENT_KEY= ELASTIC__HTTP_COMPRESS=true ELASTIC__REQUEST_TIMEOUT=1.0 -ELASTIC__MAX_RETRIES=1 -ELASTIC__RETRY_ON_TIMEOUT=true -ELASTIC__RETRY_ON_STATUS=[429,502,503,504] +ELASTIC__RETRY__MAX_RETRIES=1 +ELASTIC__RETRY__ON_TIMEOUT=true +ELASTIC__RETRY__ON_STATUS=[429,502,503,504] ELASTIC__IGNORE_STATUS=[] -ELASTIC__SNIFF_ON_START=false -ELASTIC__SNIFF_BEFORE_REQUESTS=false -ELASTIC__SNIFF_ON_NODE_FAILURE=true -ELASTIC__MIN_DELAY_BETWEEN_SNIFFING=60.0 +ELASTIC__SNIFFING__ON_START=false +ELASTIC__SNIFFING__BEFORE_REQUESTS=false +ELASTIC__SNIFFING__ON_NODE_FAILURE=true +ELASTIC__SNIFFING__MIN_DELAY=60.0 ELASTIC__NODE_SELECTOR_CLASS=round_robin ELASTIC__CONNECTIONS_PER_NODE=10 ELASTIC__DEAD_NODE_BACKOFF_FACTOR=1.0 @@ -77,11 +77,11 @@ EMAIL__SMTP_SERVER= EMAIL__SMTP_PORT=587 EMAIL__USERNAME= EMAIL__PASSWORD= -EMAIL__POOL_SIZE=5 -EMAIL__CONNECTION_TIMEOUT=30 -EMAIL__CONNECTION_REFRESH_SECONDS=300 +EMAIL__POOL__SIZE=5 +EMAIL__POOL__CONNECTION_TIMEOUT=30 +EMAIL__POOL__CONNECTION_REFRESH_SECONDS=300 EMAIL__MAX_RETRIES=3 -EMAIL__ATTACHMENT_MAX_SIZE=5242880 +EMAIL__ATTACHMENTS__MAX_SIZE=5242880 # Environment Configuration ENVIRONMENT= @@ -114,43 +114,45 @@ OTEL__LOGS_LEVEL=INFO # FastAPI Configuration FASTAPI__PROJECT_NAME=project_name FASTAPI__API_PREFIX=/api -FASTAPI__ACCESS_LOG=true -FASTAPI__BACKLOG=2048 -FASTAPI__DATE_HEADER=true -FASTAPI__FORWARDED_ALLOW_IPS= -FASTAPI__LIMIT_CONCURRENCY= -FASTAPI__LIMIT_MAX_REQUESTS= -FASTAPI__CORS_MIDDLEWARE_ALLOW_CREDENTIALS=true -FASTAPI__CORS_MIDDLEWARE_ALLOW_HEADERS=["*"] -FASTAPI__CORS_MIDDLEWARE_ALLOW_METHODS=["*"] -FASTAPI__CORS_MIDDLEWARE_ALLOW_ORIGIN_REGEX= -FASTAPI__CORS_MIDDLEWARE_ALLOW_ORIGINS=["*"] -FASTAPI__CORS_MIDDLEWARE_EXPOSE_HEADERS=[] -FASTAPI__CORS_MIDDLEWARE_MAX_AGE=600 -FASTAPI__GZIP_MIDDLEWARE_IS_ENABLED=false -FASTAPI__GZIP_MIDDLEWARE_MINIMUM_SIZE=500 -FASTAPI__GZIP_MIDDLEWARE_COMPRESSLEVEL=6 -FASTAPI__TRUSTED_HOST_MIDDLEWARE_IS_ENABLED=false -FASTAPI__TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS=[] -FASTAPI__TRUSTED_HOST_MIDDLEWARE_WWW_REDIRECT=true -FASTAPI__HTTPS_REDIRECT_MIDDLEWARE_IS_ENABLED=false -FASTAPI__PROXY_HEADERS=true -FASTAPI__RELOAD=false -FASTAPI__SERVER_HEADER=true +FASTAPI__CORS__ALLOW_CREDENTIALS=true +FASTAPI__CORS__ALLOW_HEADERS=["*"] +FASTAPI__CORS__ALLOW_METHODS=["*"] +FASTAPI__CORS__ALLOW_ORIGIN_REGEX= +FASTAPI__CORS__ALLOW_ORIGINS=["*"] +FASTAPI__CORS__EXPOSE_HEADERS=[] +FASTAPI__CORS__MAX_AGE=600 +FASTAPI__GZIP__IS_ENABLED=false +FASTAPI__GZIP__MINIMUM_SIZE=500 +FASTAPI__GZIP__COMPRESSLEVEL=6 +FASTAPI__TRUSTED_HOST__IS_ENABLED=false +FASTAPI__TRUSTED_HOST__ALLOWED_HOSTS=[] +FASTAPI__TRUSTED_HOST__WWW_REDIRECT=true +FASTAPI__HTTPS_REDIRECT__IS_ENABLED=false FASTAPI__SERVE_HOST=0.0.0.0 FASTAPI__SERVE_PORT=8100 -FASTAPI__TIMEOUT_GRACEFUL_SHUTDOWN= -FASTAPI__TIMEOUT_KEEP_ALIVE=5 -FASTAPI__WORKERS_COUNT=4 -FASTAPI__WS_MAX_SIZE=16777216 -FASTAPI__WS_PER_MESSAGE_DEFLATE=true -FASTAPI__WS_PING_INTERVAL=20.0 -FASTAPI__WS_PING_TIMEOUT=20.0 FASTAPI__OPENAPI_URL=/openapi.json FASTAPI__DOCS_URL= -FASTAPI__RE_DOCS_URL= +FASTAPI__RE_DOC_URL= FASTAPI__SWAGGER_UI_PARAMS={"docExpansion": "none"} +# Uvicorn Configuration +UVICORN__ACCESS_LOG=true +UVICORN__LIMITS__BACKLOG=2048 +UVICORN__DATE_HEADER=true +UVICORN__FORWARDED_ALLOW_IPS= +UVICORN__LIMITS__CONCURRENCY= +UVICORN__LIMITS__MAX_REQUESTS= +UVICORN__PROXY_HEADERS=true +UVICORN__RELOAD=false +UVICORN__SERVER_HEADER=true +UVICORN__TIMEOUT_GRACEFUL_SHUTDOWN= +UVICORN__TIMEOUT_KEEP_ALIVE=5 +UVICORN__WORKERS_COUNT=4 +UVICORN__WEBSOCKET__MAX_SIZE=16777216 +UVICORN__WEBSOCKET__PER_MESSAGE_DEFLATE=true +UVICORN__WEBSOCKET__PING_INTERVAL=20.0 +UVICORN__WEBSOCKET__PING_TIMEOUT=20.0 + # File Configuration FILE__SECRET_KEY= FILE__DEFAULT_EXPIRY_MINUTES=60 @@ -161,8 +163,8 @@ GRPC__SERVE_PORT=8100 GRPC__SERVE_HOST=[::] GRPC__THREAD_WORKER_COUNT= GRPC__THREAD_PER_CPU_CORE=40 -GRPC__SERVER_OPTIONS_CONFIG_LIST=[("grpc.max_metadata_size",1048576),("grpc.max_message_length",134217728),("grpc.max_receive_message_length",134217728),("grpc.max_send_message_length",134217728),("grpc.keepalive_time_ms",5000),("grpc.keepalive_timeout_ms",1000),("grpc.http2.min_ping_interval_without_data_ms",5000),("grpc.max_connection_idle_ms",10000),("grpc.max_connection_age_ms",30000),("grpc.max_connection_age_grace_ms",5000),("grpc.http2.max_pings_without_data",0),("grpc.keepalive_permit_without_calls",1),("grpc.http2.max_ping_strikes",0),("grpc.http2.min_recv_ping_interval_without_data_ms",4000)] -GRPC__STUB_OPTIONS_CONFIG_LIST=[("grpc.max_metadata_size",1048576),("grpc.max_message_length",134217728),("grpc.max_receive_message_length",134217728),("grpc.max_send_message_length",134217728),("grpc.keepalive_time_ms",5000),("grpc.keepalive_timeout_ms",1000),("grpc.http2.max_pings_without_data",0),("grpc.keepalive_permit_without_calls",1),("grpc.service_config","{\"methodConfig\": [{\"name\": [], \"timeout\": \"1s\", \"waitForReady\": true, \"retryPolicy\": {\"maxAttempts\": 5, \"initialBackoff\": \"0.1s\", \"maxBackoff\": \"1s\", \"backoffMultiplier\": 2, \"retryableStatusCodes\": [\"UNAVAILABLE\", \"ABORTED\", \"RESOURCE_EXHAUSTED\"]}}]}")] +GRPC__SERVER_OPTIONS_CONFIG_LIST=[["grpc.max_metadata_size",1048576],["grpc.max_message_length",134217728],["grpc.max_receive_message_length",134217728],["grpc.max_send_message_length",134217728],["grpc.keepalive_time_ms",5000],["grpc.keepalive_timeout_ms",1000],["grpc.http2.min_ping_interval_without_data_ms",5000],["grpc.max_connection_idle_ms",10000],["grpc.max_connection_age_ms",30000],["grpc.max_connection_age_grace_ms",5000],["grpc.http2.max_pings_without_data",0],["grpc.keepalive_permit_without_calls",1],["grpc.http2.max_ping_strikes",0],["grpc.http2.min_recv_ping_interval_without_data_ms",4000]] +GRPC__STUB_OPTIONS_CONFIG_LIST=[["grpc.max_metadata_size",1048576],["grpc.max_message_length",134217728],["grpc.max_receive_message_length",134217728],["grpc.max_send_message_length",134217728],["grpc.keepalive_time_ms",5000],["grpc.keepalive_timeout_ms",1000],["grpc.http2.max_pings_without_data",0],["grpc.keepalive_permit_without_calls",1],["grpc.service_config","{\"methodConfig\": [{\"name\": [], \"timeout\": \"1s\", \"waitForReady\": true, \"retryPolicy\": {\"maxAttempts\": 5, \"initialBackoff\": \"0.1s\", \"maxBackoff\": \"1s\", \"backoffMultiplier\": 2, \"retryableStatusCodes\": [\"UNAVAILABLE\", \"ABORTED\", \"RESOURCE_EXHAUSTED\"]}}]}"]] # gRPC Rate Limit Configuration GRPC_RATE_LIMIT__IS_ENABLED=false @@ -172,12 +174,12 @@ GRPC_RATE_LIMIT__IDENTITY_FROM_ACCESS_TOKEN=true # Kafka Configuration KAFKA__BROKERS_LIST=["localhost:9092"] KAFKA__SECURITY_PROTOCOL=PLAINTEXT -KAFKA__SASL_MECHANISM= -KAFKA__USERNAME= -KAFKA__PASSWORD= -KAFKA__SSL_CA_FILE= -KAFKA__SSL_CERT_FILE= -KAFKA__SSL_KEY_FILE= +KAFKA__SASL__MECHANISM= +KAFKA__SASL__USERNAME= +KAFKA__SASL__PASSWORD= +KAFKA__SSL__CA_FILE= +KAFKA__SSL__CERT_FILE= +KAFKA__SSL__KEY_FILE= KAFKA__ACKS=all KAFKA__AUTO_OFFSET_RESET=earliest KAFKA__ENABLE_AUTO_COMMIT=false @@ -209,14 +211,14 @@ KEYCLOAK__SERVER_URL= KEYCLOAK__CLIENT_ID= KEYCLOAK__REALM_NAME=master KEYCLOAK__CLIENT_SECRET_KEY= -KEYCLOAK__VERIFY_SSL=true +KEYCLOAK__TLS__VERIFY_SSL=true KEYCLOAK__TIMEOUT=10 -KEYCLOAK__TOKEN_LEEWAY_SECONDS=0 -KEYCLOAK__REQUIRE_ORGANIZATION=false -KEYCLOAK__IS_ADMIN_MODE_ENABLED=false -KEYCLOAK__ADMIN_USERNAME= -KEYCLOAK__ADMIN_PASSWORD= -KEYCLOAK__ADMIN_REALM_NAME=master +KEYCLOAK__TOKEN_VALIDATION__LEEWAY_SECONDS=0 +KEYCLOAK__TOKEN_VALIDATION__REQUIRE_ORGANIZATION=false +KEYCLOAK__ADMIN__IS_ENABLED=false +KEYCLOAK__ADMIN__USERNAME= +KEYCLOAK__ADMIN__PASSWORD= +KEYCLOAK__ADMIN__REALM_NAME=master # MinIO Configuration MINIO__ENDPOINT= @@ -241,25 +243,23 @@ SAMAN_SHAPARAK__REVERSE_URL=https://sadad.shaparak.ir/api/v2/reverse SAMAN_SHAPARAK__PROXIES= # Redis Configuration -REDIS__MODE=standalone +REDIS={"DECODE_RESPONSES":true,"PROTOCOL":3} +REDIS__MODE=STANDALONE REDIS__MASTER_HOST=localhost REDIS__SLAVE_HOST= -REDIS__CLUSTER_NODES=[] -REDIS__CLUSTER_REQUIRE_FULL_COVERAGE=true -REDIS__CLUSTER_READ_FROM_REPLICAS=true -REDIS__CLUSTER_SKIP_FULL_COVERAGE_CHECK=false -REDIS__SENTINEL_NODES=[] -REDIS__SENTINEL_SERVICE_NAME= -REDIS__SENTINEL_SOCKET_TIMEOUT=0.1 +REDIS__CLUSTER__NODES=[] +REDIS__CLUSTER__REQUIRE_FULL_COVERAGE=true +REDIS__CLUSTER__READ_FROM_REPLICAS=true +REDIS__SENTINEL__NODES=[] +REDIS__SENTINEL__SERVICE_NAME= +REDIS__SENTINEL__SOCKET_TIMEOUT=0.1 REDIS__PORT=6379 REDIS__DATABASE=0 REDIS__PASSWORD= -REDIS__DECODE_RESPONSES=true -REDIS__PROTOCOL=3 -REDIS__SENTINEL_PASSWORD= +REDIS__SENTINEL__PASSWORD= REDIS__HEALTH_CHECK_INTERVAL=10 REDIS__MAX_CONNECTIONS=50 -REDIS__RETRY_ON_TIMEOUT=true +REDIS__RETRY__ON_TIMEOUT=true REDIS__SOCKET_CONNECT_TIMEOUT=5.0 REDIS__SOCKET_TIMEOUT=5.0 @@ -267,35 +267,35 @@ REDIS__SOCKET_TIMEOUT=5.0 PAGINATION__MAX_ITEMS=10000 # SQLAlchemy Configuration (PostgreSQL) -SQLALCHEMY__COUNT_CACHE_ENABLED=false -SQLALCHEMY__COUNT_CACHE_MAX_SIZE=1000 -SQLALCHEMY__COUNT_CACHE_TTL_SECONDS=60 -SQLALCHEMY__COUNT_THRESHOLD= -SQLALCHEMY__DATABASE= -SQLALCHEMY__DRIVER_NAME=postgresql+psycopg -SQLALCHEMY__ECHO=false -SQLALCHEMY__ECHO_POOL=false -SQLALCHEMY__ENABLE_FROM_LINTING=true -SQLALCHEMY__HIDE_PARAMETERS=false -SQLALCHEMY__HOST= -SQLALCHEMY__ISOLATION_LEVEL=REPEATABLE READ -SQLALCHEMY__PASSWORD= -SQLALCHEMY__POOL_MAX_OVERFLOW=1 -SQLALCHEMY__POOL_PRE_PING=true -SQLALCHEMY__POOL_RECYCLE_SECONDS=600 -SQLALCHEMY__POOL_RESET_ON_RETURN=rollback -SQLALCHEMY__POOL_SIZE=20 -SQLALCHEMY__POOL_TIMEOUT=30 -SQLALCHEMY__POOL_USE_LIFO=true -SQLALCHEMY__PORT=5432 -SQLALCHEMY__QUERY_CACHE_SIZE=500 -SQLALCHEMY__USERNAME= -SQLALCHEMY__POSTGRES_DSN= +POSTGRES_SQLALCHEMY__COUNT_CACHE__IS_ENABLED=false +POSTGRES_SQLALCHEMY__COUNT_CACHE__MAX_SIZE=1000 +POSTGRES_SQLALCHEMY__COUNT_CACHE__TTL_SECONDS=60 +POSTGRES_SQLALCHEMY__COUNT_THRESHOLD= +POSTGRES_SQLALCHEMY__DATABASE= +POSTGRES_SQLALCHEMY__DRIVER_NAME=postgresql+psycopg +POSTGRES_SQLALCHEMY__ECHO=false +POSTGRES_SQLALCHEMY__ECHO_POOL=false +POSTGRES_SQLALCHEMY__ENABLE_FROM_LINTING=true +POSTGRES_SQLALCHEMY__HIDE_PARAMETERS=false +POSTGRES_SQLALCHEMY__HOST= +POSTGRES_SQLALCHEMY__ISOLATION_LEVEL=REPEATABLE READ +POSTGRES_SQLALCHEMY__PASSWORD= +POSTGRES_SQLALCHEMY__POOL__MAX_OVERFLOW=1 +POSTGRES_SQLALCHEMY__POOL__PRE_PING=true +POSTGRES_SQLALCHEMY__POOL__RECYCLE_SECONDS=600 +POSTGRES_SQLALCHEMY__POOL__RESET_ON_RETURN=rollback +POSTGRES_SQLALCHEMY__POOL__SIZE=20 +POSTGRES_SQLALCHEMY__POOL__TIMEOUT=30 +POSTGRES_SQLALCHEMY__POOL__USE_LIFO=true +POSTGRES_SQLALCHEMY__PORT=5432 +POSTGRES_SQLALCHEMY__QUERY_CACHE_SIZE=500 +POSTGRES_SQLALCHEMY__USERNAME= +POSTGRES_SQLALCHEMY__POSTGRES_DSN= # MySQL SQLAlchemy Configuration -MYSQL_SQLALCHEMY__COUNT_CACHE_ENABLED=false -MYSQL_SQLALCHEMY__COUNT_CACHE_MAX_SIZE=1000 -MYSQL_SQLALCHEMY__COUNT_CACHE_TTL_SECONDS=60 +MYSQL_SQLALCHEMY__COUNT_CACHE__IS_ENABLED=false +MYSQL_SQLALCHEMY__COUNT_CACHE__MAX_SIZE=1000 +MYSQL_SQLALCHEMY__COUNT_CACHE__TTL_SECONDS=60 MYSQL_SQLALCHEMY__COUNT_THRESHOLD= MYSQL_SQLALCHEMY__DATABASE= MYSQL_SQLALCHEMY__DRIVER_NAME=mysql+pymysql @@ -306,21 +306,21 @@ MYSQL_SQLALCHEMY__HIDE_PARAMETERS=false MYSQL_SQLALCHEMY__HOST= MYSQL_SQLALCHEMY__ISOLATION_LEVEL=REPEATABLE READ MYSQL_SQLALCHEMY__PASSWORD= -MYSQL_SQLALCHEMY__POOL_MAX_OVERFLOW=1 -MYSQL_SQLALCHEMY__POOL_PRE_PING=true -MYSQL_SQLALCHEMY__POOL_RECYCLE_SECONDS=600 -MYSQL_SQLALCHEMY__POOL_RESET_ON_RETURN=rollback -MYSQL_SQLALCHEMY__POOL_SIZE=20 -MYSQL_SQLALCHEMY__POOL_TIMEOUT=30 -MYSQL_SQLALCHEMY__POOL_USE_LIFO=true +MYSQL_SQLALCHEMY__POOL__MAX_OVERFLOW=1 +MYSQL_SQLALCHEMY__POOL__PRE_PING=true +MYSQL_SQLALCHEMY__POOL__RECYCLE_SECONDS=600 +MYSQL_SQLALCHEMY__POOL__RESET_ON_RETURN=rollback +MYSQL_SQLALCHEMY__POOL__SIZE=20 +MYSQL_SQLALCHEMY__POOL__TIMEOUT=30 +MYSQL_SQLALCHEMY__POOL__USE_LIFO=true MYSQL_SQLALCHEMY__PORT=3306 MYSQL_SQLALCHEMY__QUERY_CACHE_SIZE=500 MYSQL_SQLALCHEMY__USERNAME= # SQLite SQLAlchemy Configuration -SQLITE_SQLALCHEMY__COUNT_CACHE_ENABLED=false -SQLITE_SQLALCHEMY__COUNT_CACHE_MAX_SIZE=1000 -SQLITE_SQLALCHEMY__COUNT_CACHE_TTL_SECONDS=60 +SQLITE_SQLALCHEMY__COUNT_CACHE__IS_ENABLED=false +SQLITE_SQLALCHEMY__COUNT_CACHE__MAX_SIZE=1000 +SQLITE_SQLALCHEMY__COUNT_CACHE__TTL_SECONDS=60 SQLITE_SQLALCHEMY__COUNT_THRESHOLD= SQLITE_SQLALCHEMY__DATABASE=:memory: SQLITE_SQLALCHEMY__DRIVER_NAME=sqlite+aiosqlite @@ -331,21 +331,21 @@ SQLITE_SQLALCHEMY__HIDE_PARAMETERS=false SQLITE_SQLALCHEMY__HOST= SQLITE_SQLALCHEMY__ISOLATION_LEVEL= SQLITE_SQLALCHEMY__PASSWORD= -SQLITE_SQLALCHEMY__POOL_MAX_OVERFLOW=1 -SQLITE_SQLALCHEMY__POOL_PRE_PING=true -SQLITE_SQLALCHEMY__POOL_RECYCLE_SECONDS=600 -SQLITE_SQLALCHEMY__POOL_RESET_ON_RETURN=rollback -SQLITE_SQLALCHEMY__POOL_SIZE=20 -SQLITE_SQLALCHEMY__POOL_TIMEOUT=30 -SQLITE_SQLALCHEMY__POOL_USE_LIFO=true +SQLITE_SQLALCHEMY__POOL__MAX_OVERFLOW=1 +SQLITE_SQLALCHEMY__POOL__PRE_PING=true +SQLITE_SQLALCHEMY__POOL__RECYCLE_SECONDS=600 +SQLITE_SQLALCHEMY__POOL__RESET_ON_RETURN=rollback +SQLITE_SQLALCHEMY__POOL__SIZE=20 +SQLITE_SQLALCHEMY__POOL__TIMEOUT=30 +SQLITE_SQLALCHEMY__POOL__USE_LIFO=true SQLITE_SQLALCHEMY__PORT= SQLITE_SQLALCHEMY__QUERY_CACHE_SIZE=500 SQLITE_SQLALCHEMY__USERNAME= # StarRocks SQLAlchemy Configuration -STARROCKS_SQLALCHEMY__COUNT_CACHE_ENABLED=false -STARROCKS_SQLALCHEMY__COUNT_CACHE_MAX_SIZE=1000 -STARROCKS_SQLALCHEMY__COUNT_CACHE_TTL_SECONDS=60 +STARROCKS_SQLALCHEMY__COUNT_CACHE__IS_ENABLED=false +STARROCKS_SQLALCHEMY__COUNT_CACHE__MAX_SIZE=1000 +STARROCKS_SQLALCHEMY__COUNT_CACHE__TTL_SECONDS=60 STARROCKS_SQLALCHEMY__COUNT_THRESHOLD= STARROCKS_SQLALCHEMY__DATABASE= STARROCKS_SQLALCHEMY__DRIVER_NAME=postgresql+psycopg @@ -354,15 +354,15 @@ STARROCKS_SQLALCHEMY__ECHO_POOL=false STARROCKS_SQLALCHEMY__ENABLE_FROM_LINTING=true STARROCKS_SQLALCHEMY__HIDE_PARAMETERS=false STARROCKS_SQLALCHEMY__HOST= -STARROCKS_SQLALCHEMY__ISOLATION_LEVEL=REPEATABLE READ +STARROCKS_SQLALCHEMY__ISOLATION_LEVEL=READ COMMITTED STARROCKS_SQLALCHEMY__PASSWORD= -STARROCKS_SQLALCHEMY__POOL_MAX_OVERFLOW=1 -STARROCKS_SQLALCHEMY__POOL_PRE_PING=true -STARROCKS_SQLALCHEMY__POOL_RECYCLE_SECONDS=600 -STARROCKS_SQLALCHEMY__POOL_RESET_ON_RETURN=rollback -STARROCKS_SQLALCHEMY__POOL_SIZE=20 -STARROCKS_SQLALCHEMY__POOL_TIMEOUT=30 -STARROCKS_SQLALCHEMY__POOL_USE_LIFO=true +STARROCKS_SQLALCHEMY__POOL__MAX_OVERFLOW=1 +STARROCKS_SQLALCHEMY__POOL__PRE_PING=true +STARROCKS_SQLALCHEMY__POOL__RECYCLE_SECONDS=600 +STARROCKS_SQLALCHEMY__POOL__RESET_ON_RETURN=rollback +STARROCKS_SQLALCHEMY__POOL__SIZE=20 +STARROCKS_SQLALCHEMY__POOL__TIMEOUT=30 +STARROCKS_SQLALCHEMY__POOL__USE_LIFO=true STARROCKS_SQLALCHEMY__PORT=5432 STARROCKS_SQLALCHEMY__QUERY_CACHE_SIZE=500 STARROCKS_SQLALCHEMY__USERNAME= @@ -378,24 +378,24 @@ TEMPORAL__METRICS_PULL_PORT=8201 TEMPORAL__CLIENT_IDENTITY= TEMPORAL__API_KEY= TEMPORAL__LAZY_CONNECT=false -TEMPORAL__KEEP_ALIVE_INTERVAL_MS=30000 -TEMPORAL__KEEP_ALIVE_TIMEOUT_MS=15000 -TEMPORAL__CLIENT_RPC_RETRY_MAX_RETRIES=10 -TEMPORAL__CLIENT_RPC_RETRY_INITIAL_INTERVAL_MS=100 -TEMPORAL__CLIENT_RPC_RETRY_MAX_INTERVAL_MS=5000 -TEMPORAL__WORKER_GRACEFUL_SHUTDOWN_SECONDS=30 -TEMPORAL__WORKER_MAX_CACHED_WORKFLOWS=1000 -TEMPORAL__WORKER_DEBUG_MODE=false -TEMPORAL__WORKER_DISABLE_EAGER_ACTIVITY_EXECUTION=false -TEMPORAL__TLS_CA_CERT= -TEMPORAL__TLS_CLIENT_CERT= -TEMPORAL__TLS_CLIENT_KEY= -TEMPORAL__WORKFLOW_EXECUTION_TIMEOUT=300 -TEMPORAL__WORKFLOW_RUN_TIMEOUT=60 -TEMPORAL__WORKFLOW_TASK_TIMEOUT=30 -TEMPORAL__ACTIVITY_START_TO_CLOSE_TIMEOUT=30 -TEMPORAL__ACTIVITY_HEARTBEAT_TIMEOUT=10 -TEMPORAL__RETRY_MAXIMUM_ATTEMPTS=3 -TEMPORAL__RETRY_BACKOFF_COEFFICIENT=2.0 -TEMPORAL__RETRY_MAXIMUM_INTERVAL=60 -TEMPORAL__RETRY_INITIAL_INTERVAL=1 +TEMPORAL__KEEP_ALIVE__INTERVAL_MS=30000 +TEMPORAL__KEEP_ALIVE__TIMEOUT_MS=15000 +TEMPORAL__CLIENT_RETRY__MAX_RETRIES=10 +TEMPORAL__CLIENT_RETRY__INITIAL_INTERVAL_MS=100 +TEMPORAL__CLIENT_RETRY__MAX_INTERVAL_MS=5000 +TEMPORAL__WORKER__GRACEFUL_SHUTDOWN_SECONDS=30 +TEMPORAL__WORKER__MAX_CACHED_WORKFLOWS=1000 +TEMPORAL__WORKER__DEBUG_MODE=false +TEMPORAL__WORKER__DISABLE_EAGER_ACTIVITY_EXECUTION=false +TEMPORAL__TLS__CA_CERT= +TEMPORAL__TLS__CLIENT_CERT= +TEMPORAL__TLS__CLIENT_KEY= +TEMPORAL__WORKFLOW__EXECUTION_TIMEOUT=300 +TEMPORAL__WORKFLOW__RUN_TIMEOUT=60 +TEMPORAL__WORKFLOW__TASK_TIMEOUT=30 +TEMPORAL__ACTIVITY__START_TO_CLOSE_TIMEOUT=30 +TEMPORAL__ACTIVITY__HEARTBEAT_TIMEOUT=10 +TEMPORAL__RETRY__MAXIMUM_ATTEMPTS=3 +TEMPORAL__RETRY__BACKOFF_COEFFICIENT=2.0 +TEMPORAL__RETRY__MAXIMUM_INTERVAL=60 +TEMPORAL__RETRY__INITIAL_INTERVAL=1 diff --git a/.env.test b/.env.test index d5b87b059..6a9a06729 100644 --- a/.env.test +++ b/.env.test @@ -18,23 +18,23 @@ APM_SERVER__IMAGE=elastic/apm-server:9.5.6 SCYLLADB__IMAGE=scylladb/scylla:2026.3.6 AUTH__SECRET_KEY=test-only-jwt-signing-key-not-a-secret-0123456789 -AUTH__TOTP_SECRET_KEY=CHANGE_ME +AUTH__TOTP__SECRET_KEY=CHANGE_ME FILE__SECRET_KEY=CHANGE_ME FILE__DEFAULT_EXPIRY_MINUTES=10 FILE__ALLOWED_EXTENSIONS=["jpg","png","pdf","txt"] FASTAPI__PROJECT_NAME="Test API" -FASTAPI__CORS_MIDDLEWARE_ALLOW_ORIGINS=["https://example.com"] -FASTAPI__CORS_MIDDLEWARE_ALLOW_CREDENTIALS=True -FASTAPI__CORS_MIDDLEWARE_ALLOW_METHODS=["GET", "POST"] -FASTAPI__CORS_MIDDLEWARE_ALLOW_HEADERS=["Content-Type", "Authorization"] -FASTAPI__CORS_MIDDLEWARE_ALLOW_ORIGIN_REGEX= -FASTAPI__CORS_MIDDLEWARE_EXPOSE_HEADERS=["X-Total-Count", "X-Request-ID"] -FASTAPI__CORS_MIDDLEWARE_MAX_AGE=600 +FASTAPI__CORS__ALLOW_ORIGINS=["https://example.com"] +FASTAPI__CORS__ALLOW_CREDENTIALS=True +FASTAPI__CORS__ALLOW_METHODS=["GET", "POST"] +FASTAPI__CORS__ALLOW_HEADERS=["Content-Type", "Authorization"] +FASTAPI__CORS__ALLOW_ORIGIN_REGEX= +FASTAPI__CORS__EXPOSE_HEADERS=["X-Total-Count", "X-Request-ID"] +FASTAPI__CORS__MAX_AGE=600 FASTAPI__OPENAPI_URL="/openapi.json" FASTAPI__DOCS_URL="/docs" -FASTAPI__RE_DOCS_URL="/redoc" +FASTAPI__RE_DOC_URL="/redoc" FASTAPI__SWAGGER_UI_PARAMS={} # Temporal Configuration @@ -78,19 +78,19 @@ STARROCKS_SQLALCHEMY__PASSWORD= # Keycloak Configuration KEYCLOAK__SERVER_URL=http://localhost:8080 -KEYCLOAK__ADMIN_USERNAME=admin -KEYCLOAK__ADMIN_PASSWORD=admin +KEYCLOAK__ADMIN__USERNAME=admin +KEYCLOAK__ADMIN__PASSWORD=admin KEYCLOAK__REALM_NAME=master KEYCLOAK__CLIENT_ID=admin-cli -KEYCLOAK__IS_ADMIN_MODE_ENABLED=true -KEYCLOAK__ADMIN_REALM_NAME=master -KEYCLOAK__VERIFY_SSL=false +KEYCLOAK__ADMIN__IS_ENABLED=true +KEYCLOAK__ADMIN__REALM_NAME=master +KEYCLOAK__TLS__VERIFY_SSL=false KEYCLOAK__TIMEOUT=30 # Elasticsearch Configuration ELASTIC__HOSTS=["http://localhost:9200"] -ELASTIC__HTTP_USER_NAME=elastic -ELASTIC__HTTP_PASSWORD=test_password +ELASTIC__AUTH__USER_NAME=elastic +ELASTIC__AUTH__PASSWORD=test_password # Kafka Configuration KAFKA__BROKERS_LIST=["localhost:9092"] @@ -104,7 +104,7 @@ MINIO__SECRET_KEY=test_secret_key VAULT__ENABLED=false VAULT__AUTH_METHOD=token VAULT__MOUNT_POINT=secret -VAULT__VERIFY_SSL=false +VAULT__TLS__VERIFY_SSL=false # ScyllaDB Configuration SCYLLADB__CONTACT_POINTS=["localhost"] diff --git a/archipy/adapters/base/sqlalchemy/atomic.py b/archipy/adapters/base/sqlalchemy/atomic.py index 79fd451b0..85002bc04 100644 --- a/archipy/adapters/base/sqlalchemy/atomic.py +++ b/archipy/adapters/base/sqlalchemy/atomic.py @@ -34,7 +34,6 @@ log_driver_error, ) from archipy.adapters.base.sqlalchemy.session_manager_registry import SessionManagerRegistry -from archipy.helpers._deprecation import deprecated_alias, warn_deprecated_name from archipy.models.errors import ( BaseError, DatabaseConfigurationError, @@ -807,58 +806,3 @@ def mysql_sqlalchemy_atomic[**P, R]( Callable: The wrapped function, or a decorator to apply later when ``function`` is None. """ return _atomic_for("mysql", function, registry, savepoint) - - -def sqlalchemy_atomic_decorator( - db_type: str, - is_async: bool = False, - function: Callable[..., Any] | None = None, -) -> Callable[..., Any]: - """Deprecated: use :func:`sqlalchemy_atomic`, which detects async functions itself. - - Args: - db_type (str): The database type ("postgres", "sqlite", "starrocks", or "mysql"). - is_async (bool): Ignored; the function kind is detected automatically. - function (Callable | None): The function to wrap. If None, returns a decorator to apply later. - - Returns: - Callable: The wrapped function, or a decorator to apply later when ``function`` is None. - """ - del is_async - warn_deprecated_name("sqlalchemy_atomic_decorator", "sqlalchemy_atomic") - return sqlalchemy_atomic(db_type, function) - - -postgres_sqlalchemy_atomic_decorator = deprecated_alias( - "postgres_sqlalchemy_atomic_decorator", - postgres_sqlalchemy_atomic, -) - -async_postgres_sqlalchemy_atomic_decorator = deprecated_alias( - "async_postgres_sqlalchemy_atomic_decorator", - postgres_sqlalchemy_atomic, -) - -sqlite_sqlalchemy_atomic_decorator = deprecated_alias("sqlite_sqlalchemy_atomic_decorator", sqlite_sqlalchemy_atomic) - -async_sqlite_sqlalchemy_atomic_decorator = deprecated_alias( - "async_sqlite_sqlalchemy_atomic_decorator", - sqlite_sqlalchemy_atomic, -) - -starrocks_sqlalchemy_atomic_decorator = deprecated_alias( - "starrocks_sqlalchemy_atomic_decorator", - starrocks_sqlalchemy_atomic, -) - -async_starrocks_sqlalchemy_atomic_decorator = deprecated_alias( - "async_starrocks_sqlalchemy_atomic_decorator", - starrocks_sqlalchemy_atomic, -) - -mysql_sqlalchemy_atomic_decorator = deprecated_alias("mysql_sqlalchemy_atomic_decorator", mysql_sqlalchemy_atomic) - -async_mysql_sqlalchemy_atomic_decorator = deprecated_alias( - "async_mysql_sqlalchemy_atomic_decorator", - mysql_sqlalchemy_atomic, -) diff --git a/archipy/adapters/email/adapters.py b/archipy/adapters/email/adapters.py index 4034b99cb..9ba84f6b7 100644 --- a/archipy/adapters/email/adapters.py +++ b/archipy/adapters/email/adapters.py @@ -7,7 +7,6 @@ import os import smtplib import ssl -import warnings from email import encoders from email.errors import MessageError from email.mime.audio import MIMEAudio @@ -26,7 +25,7 @@ from archipy.adapters.email.ports import EmailPort from archipy.configs.base_config import BaseConfig from archipy.helpers.decorators.tracing import trace_span -from archipy.helpers.utils.base_utils import BaseUtils +from archipy.helpers.errors import capture_exception from archipy.helpers.utils.datetime_utils import DatetimeUtils from archipy.models.dtos.email_dtos import EmailAttachmentDTO from archipy.models.errors import ConfigurationError, InvalidArgumentError, UnavailableError @@ -75,7 +74,7 @@ def __init__(self, config: EmailConfig) -> None: """Initialize EmailConnectionManager. Raises: - ConfigurationError: If only one of ``USERNAME`` and ``PASSWORD`` is set while ``TLS.MODE`` is not ``auto``. + ConfigurationError: If credentials are incomplete or SMTP authentication is configured without TLS. """ self.config = config self.smtp_connection: smtplib.SMTP | None = None @@ -84,53 +83,24 @@ def __init__(self, config: EmailConfig) -> None: self._validate_security() def _validate_security(self) -> None: - """Check the TLS and credential settings; the legacy ``auto`` mode only warns.""" - half_set = bool(self.config.USERNAME) != bool(self.config.PASSWORD) - if self.config.TLS.MODE == "auto": - warnings.warn( - "EMAIL.TLS.MODE='auto' is deprecated: STARTTLS is opportunistic, the certificate is not verified " - "and a failed upgrade falls back to clear text. Set TLS.MODE to 'starttls' or 'implicit'.", - DeprecationWarning, - stacklevel=3, - ) - if half_set: - warnings.warn( - "EMAIL.USERNAME and EMAIL.PASSWORD must be set together; login is skipped. " - "This will be an error in a future release.", - DeprecationWarning, - stacklevel=3, - ) - elif half_set: + """Require paired credentials and TLS for SMTP authentication.""" + if bool(self.config.USERNAME) != bool(self.config.PASSWORD): raise ConfigurationError( operation="email_credentials", reason="USERNAME and PASSWORD must be set together", ) - if self.config.TLS.MODE == "none" and self.config.USERNAME and self.config.PASSWORD: - warnings.warn( - "EMAIL.TLS.MODE='none' sends USERNAME and PASSWORD in clear text. " - "Set TLS.MODE to 'starttls' or 'implicit'; clear-text login will be rejected in a future release.", - DeprecationWarning, - stacklevel=3, - ) - if self.config.TLS.MODE in ("starttls", "implicit") and not self.config.TLS.VERIFY: - warnings.warn( - "EMAIL.TLS.VERIFY=False disables certificate and host name verification, which exposes the " - "session and credentials to interception. Use TLS.CA_FILE for a private CA; " - "TLS.VERIFY=False will be rejected in a future release.", - DeprecationWarning, - stacklevel=3, + if self.config.TLS.MODE == "none" and self.config.USERNAME: + raise ConfigurationError( + operation="email_credentials", + reason="SMTP authentication requires TLS.MODE 'starttls' or 'implicit'", ) def _build_ssl_context(self) -> ssl.SSLContext: - """Build the TLS context from ``TLS.CA_FILE`` and ``TLS.VERIFY``.""" - context = ssl.create_default_context(cafile=self.config.TLS.CA_FILE) - if not self.config.TLS.VERIFY: - context.check_hostname = False - context.verify_mode = ssl.CERT_NONE - return context + """Build the TLS context with certificate and hostname verification.""" + return ssl.create_default_context(cafile=self.config.TLS.CA_FILE) def _open_session(self) -> tuple[smtplib.SMTP, str]: - """Open the SMTP session for ``TLS_MODE`` and return it with the TLS mode actually in use.""" + """Open the SMTP session for ``TLS.MODE`` and return it with the TLS mode actually in use.""" mode = self.config.TLS.MODE source_address = (self.config.SOURCE_ADDRESS, self.config.SOURCE_PORT) if self.config.SOURCE_ADDRESS else None common: dict[str, Any] = { @@ -157,39 +127,38 @@ def _open_session(self) -> tuple[smtplib.SMTP, str]: return session, tls_mode def _negotiate_tls(self, session: smtplib.SMTP) -> str: - """Greet the server and upgrade with STARTTLS as ``TLS_MODE`` demands; return the TLS mode in use.""" + """Greet the server and upgrade with STARTTLS as ``TLS.MODE`` demands; return the TLS mode in use.""" mode = self.config.TLS.MODE session.ehlo() - offered = session.has_extn("starttls") - if mode == "starttls" and not offered: + if mode == "none": + return "none" + if not session.has_extn("starttls"): message = "STARTTLS is required but the server does not offer it" raise smtplib.SMTPNotSupportedError(message) - if mode == "none" or (mode == "auto" and not offered): - return "none" - session.starttls(context=self._build_ssl_context() if mode == "starttls" else None) + session.starttls(context=self._build_ssl_context()) session.ehlo() return "starttls" def connect(self) -> None: """Establish the SMTP connection with the configured transport security and authentication. - ``TLS_MODE`` ``starttls`` fails when the server does not offer STARTTLS or the upgrade fails, and + ``TLS.MODE`` ``starttls`` fails when the server does not offer STARTTLS or the upgrade fails, and ``implicit`` opens a TLS connection from the start; neither falls back to clear text. Failures are captured and leave ``smtp_connection`` as ``None``; the cause is kept in ``last_error``. Raises: InvalidArgumentError: If no SMTP server is configured. + ConfigurationError: If the SMTP credentials or transport settings are incompatible. """ if not self.config.SMTP_SERVER: raise InvalidArgumentError(argument_name="SMTP_SERVER") + self._validate_security() try: session, tls_mode = self._open_session() try: _annotate_current_span({"email.tls_mode": tls_mode}) if self.config.USERNAME and self.config.PASSWORD: - if tls_mode == "none": - logger.warning("Logging in to the SMTP server without TLS: credentials are sent in clear text") session.login(self.config.USERNAME, self.config.PASSWORD) except BaseException: session.close() @@ -198,7 +167,7 @@ def connect(self) -> None: self.last_used = DatetimeUtils.get_datetime_now() self.last_error = None except (smtplib.SMTPException, OSError, TimeoutError) as e: - BaseUtils.capture_exception(e) + capture_exception(e) self.smtp_connection = None self.last_error = e @@ -209,7 +178,7 @@ def disconnect(self) -> None: self.smtp_connection.quit() self.smtp_connection = None except (smtplib.SMTPException, OSError, TimeoutError) as e: - BaseUtils.capture_exception(e) + capture_exception(e) finally: self.smtp_connection = None @@ -574,7 +543,7 @@ def _send_email_traced( additional_data={"reason": "invalid_header", "detail": str(e)}, ) from e except (smtplib.SMTPException, OSError, TimeoutError) as e: - BaseUtils.capture_exception(e) + capture_exception(e) last_error = e connection.disconnect() # Close the broken session; reconnect on next attempt if isinstance(e, smtplib.SMTPResponseException) and e.smtp_code >= _PERMANENT_FAILURE_CODE: @@ -582,7 +551,7 @@ def _send_email_traced( raise UnavailableError(resource_type="SMTP") from last_error except (smtplib.SMTPException, OSError, TimeoutError) as e: - BaseUtils.capture_exception(e) + capture_exception(e) raise UnavailableError(resource_type="SMTP") from e finally: if connection: diff --git a/archipy/configs/config_template.py b/archipy/configs/config_template.py index 7e3669a87..7b4566e99 100644 --- a/archipy/configs/config_template.py +++ b/archipy/configs/config_template.py @@ -65,7 +65,6 @@ _extract_postgres_host_port_from_url, # noqa: F401 ) from archipy.configs.sections.temporal import ( - TLS_CERT_PARTS_REQUIRED, TemporalConfig, ) from archipy.configs.sections.uvicorn import UvicornConfig @@ -74,7 +73,6 @@ ) __all__ = [ - "TLS_CERT_PARTS_REQUIRED", "AuthConfig", "DatetimeConfig", "ElasticsearchConfig", diff --git a/archipy/configs/sections/_common.py b/archipy/configs/sections/_common.py deleted file mode 100644 index 6e8543dc6..000000000 --- a/archipy/configs/sections/_common.py +++ /dev/null @@ -1,51 +0,0 @@ -"""Helpers for config sections that move flat fields into nested groups.""" - -from typing import TYPE_CHECKING, Any - -if TYPE_CHECKING: - from collections.abc import Mapping - - from pydantic import BaseModel - - -def deprecated_flat_message(section: str, flat_name: str, group: str, field: str) -> str: - """Return the deprecation message of a flat setting that moved into a nested group. - - Args: - section: Config section name, for example ``"VAULT"``. - flat_name: Old flat field name, for example ``"APPROLE_ROLE_ID"``. - group: New group name, for example ``"APPROLE"``. - field: Field name inside the group, for example ``"ROLE_ID"``. - - Returns: - The message to pass to ``Field(deprecated=...)``. - """ - return f"Use {section}.{group}.{field} instead; {section}.{flat_name} will be removed in 6.0.0" - - -def fold_flat_fields( - owner: BaseModel, - group: str, - group_type: type[BaseModel], - flat_to_field: Mapping[str, str], -) -> None: - """Copy deprecated flat settings into a nested group. - - Only flat fields the user set explicitly are used. Declare them with ``Field(deprecated=...)``: reading them here - makes pydantic emit one ``DeprecationWarning`` per field. A value already set on the group wins. The group is - created when it is ``None``. Call this from a ``model_validator(mode="after")`` of the section. - - Args: - owner: The section model that holds the flat fields and the group. - group: Attribute name of the group on ``owner``. - group_type: Model class of the group. - flat_to_field: Maps each flat field name to its field name inside the group. - """ - used = sorted(name for name in flat_to_field if name in owner.model_fields_set) - if not used: - return - current: BaseModel | None = getattr(owner, group) - values: dict[str, Any] = current.model_dump(exclude_unset=True) if current is not None else {} - for name in used: - values.setdefault(flat_to_field[name], getattr(owner, name)) - object.__setattr__(owner, group, group_type(**values)) diff --git a/archipy/configs/sections/auth.py b/archipy/configs/sections/auth.py index 87d17962f..9ab6f3184 100644 --- a/archipy/configs/sections/auth.py +++ b/archipy/configs/sections/auth.py @@ -1,10 +1,6 @@ """Authentication configuration.""" -from typing import Self - -from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator - -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields +from pydantic import BaseModel, ConfigDict, Field, SecretStr class JwtConfig(BaseModel): @@ -102,224 +98,3 @@ class AuthConfig(BaseModel): default_factory=PasswordPolicyConfig, description="Password hashing and strength policy", ) - - ACCESS_TOKEN_EXPIRES_IN: int = Field( - default=1 * 60 * 60, - description="Access token expiration in seconds", - deprecated=deprecated_flat_message("AUTH", "ACCESS_TOKEN_EXPIRES_IN", "JWT", "ACCESS_TOKEN_EXPIRES_IN"), - ) # 1 hour - REFRESH_TOKEN_EXPIRES_IN: int = Field( - default=24 * 60 * 60, - description="Refresh token expiration in seconds", - deprecated=deprecated_flat_message("AUTH", "REFRESH_TOKEN_EXPIRES_IN", "JWT", "REFRESH_TOKEN_EXPIRES_IN"), - ) # 24 hours - HASH_ALGORITHM: str = Field( - default="HS256", - description="JWT signing algorithm", - deprecated=deprecated_flat_message("AUTH", "HASH_ALGORITHM", "JWT", "ALGORITHM"), - ) - JWT_ISSUER: str = Field( - default="your-app-name", - description="JWT issuer claim", - deprecated=deprecated_flat_message("AUTH", "JWT_ISSUER", "JWT", "ISSUER"), - ) - JWT_AUDIENCE: str = Field( - default="your-app-audience", - description="JWT audience claim", - deprecated=deprecated_flat_message("AUTH", "JWT_AUDIENCE", "JWT", "AUDIENCE"), - ) - TOKEN_VERSION: int = Field( - default=1, - description="JWT token version", - deprecated=deprecated_flat_message("AUTH", "TOKEN_VERSION", "JWT", "TOKEN_VERSION"), - ) - JWT_LEEWAY: int = Field( - default=0, - ge=0, - description="Clock-skew tolerance in seconds applied to exp, nbf and iat when verifying tokens", - deprecated=deprecated_flat_message("AUTH", "JWT_LEEWAY", "JWT", "LEEWAY"), - ) - ENABLE_JTI_CLAIM: bool = Field( - default=True, - description="Enable JWT ID claim for token tracking", - deprecated=deprecated_flat_message("AUTH", "ENABLE_JTI_CLAIM", "JWT", "ENABLE_JTI_CLAIM"), - ) - ENABLE_TOKEN_ROTATION: bool = Field( - default=True, - description="Enable refresh token rotation", - deprecated=deprecated_flat_message("AUTH", "ENABLE_TOKEN_ROTATION", "JWT", "ENABLE_TOKEN_ROTATION"), - ) - REFRESH_TOKEN_REUSE_INTERVAL: int = Field( - default=60, - description="Grace period for refresh token reuse in seconds", - deprecated=deprecated_flat_message( - "AUTH", - "REFRESH_TOKEN_REUSE_INTERVAL", - "JWT", - "REFRESH_TOKEN_REUSE_INTERVAL", - ), - ) - TOTP_SECRET_KEY: SecretStr | None = Field( - default=None, - description="TOTP master key", - deprecated=deprecated_flat_message("AUTH", "TOTP_SECRET_KEY", "TOTP", "SECRET_KEY"), - ) - TOTP_HASH_ALGORITHM: str = Field( - default="SHA1", - description="Hash algorithm for TOTP generation (SHA1, SHA256, SHA512)", - deprecated=deprecated_flat_message("AUTH", "TOTP_HASH_ALGORITHM", "TOTP", "HASH_ALGORITHM"), - ) - TOTP_LENGTH: int = Field( - default=6, - ge=6, - le=8, - description="TOTP code length", - deprecated=deprecated_flat_message("AUTH", "TOTP_LENGTH", "TOTP", "LENGTH"), - ) - TOTP_EXPIRES_IN: int = Field( - default=300, - description="TOTP expiration time in seconds (5 minutes)", - deprecated=deprecated_flat_message("AUTH", "TOTP_EXPIRES_IN", "TOTP", "EXPIRES_IN"), - ) - TOTP_TIME_STEP: int = Field( - default=30, - description="TOTP time step in seconds", - deprecated=deprecated_flat_message("AUTH", "TOTP_TIME_STEP", "TOTP", "TIME_STEP"), - ) - TOTP_VERIFICATION_WINDOW: int = Field( - default=1, - description="Number of time steps to check before/after", - deprecated=deprecated_flat_message("AUTH", "TOTP_VERIFICATION_WINDOW", "TOTP", "VERIFICATION_WINDOW"), - ) - TOTP_MAX_ATTEMPTS: int = Field( - default=3, - description="Maximum failed TOTP attempts before lockout", - deprecated=deprecated_flat_message("AUTH", "TOTP_MAX_ATTEMPTS", "TOTP", "MAX_ATTEMPTS"), - ) - TOTP_LOCKOUT_TIME: int = Field( - default=300, - description="Lockout time in seconds after max attempts", - deprecated=deprecated_flat_message("AUTH", "TOTP_LOCKOUT_TIME", "TOTP", "LOCKOUT_TIME"), - ) - LOGIN_RATE_LIMIT: int = Field( - default=5, - description="Maximum login attempts per minute", - deprecated=deprecated_flat_message("AUTH", "LOGIN_RATE_LIMIT", "RATE_LIMITS", "LOGIN"), - ) - TOTP_RATE_LIMIT: int = Field( - default=3, - description="Maximum TOTP requests per minute", - deprecated=deprecated_flat_message("AUTH", "TOTP_RATE_LIMIT", "RATE_LIMITS", "TOTP"), - ) - PASSWORD_RESET_RATE_LIMIT: int = Field( - default=3, - description="Maximum password reset requests per hour", - deprecated=deprecated_flat_message("AUTH", "PASSWORD_RESET_RATE_LIMIT", "RATE_LIMITS", "PASSWORD_RESET"), - ) - HASH_ITERATIONS: int = Field( - default=600000, - ge=1, - description="Password hash iterations (PBKDF2-HMAC-SHA256); stored hashes record their own count", - deprecated=deprecated_flat_message("AUTH", "HASH_ITERATIONS", "PASSWORD_POLICY", "HASH_ITERATIONS"), - ) - MIN_LENGTH: int = Field( - default=12, - ge=8, - description="Minimum password length", - deprecated=deprecated_flat_message("AUTH", "MIN_LENGTH", "PASSWORD_POLICY", "MIN_LENGTH"), - ) - REQUIRE_DIGIT: bool = Field( - default=True, - description="Whether password requires digits", - deprecated=deprecated_flat_message("AUTH", "REQUIRE_DIGIT", "PASSWORD_POLICY", "REQUIRE_DIGIT"), - ) - REQUIRE_LOWERCASE: bool = Field( - default=True, - description="Whether password requires lowercase", - deprecated=deprecated_flat_message("AUTH", "REQUIRE_LOWERCASE", "PASSWORD_POLICY", "REQUIRE_LOWERCASE"), - ) - REQUIRE_SPECIAL: bool = Field( - default=True, - description="Whether password requires special chars", - deprecated=deprecated_flat_message("AUTH", "REQUIRE_SPECIAL", "PASSWORD_POLICY", "REQUIRE_SPECIAL"), - ) - REQUIRE_UPPERCASE: bool = Field( - default=True, - description="Whether password requires uppercase", - deprecated=deprecated_flat_message("AUTH", "REQUIRE_UPPERCASE", "PASSWORD_POLICY", "REQUIRE_UPPERCASE"), - ) - SALT_LENGTH: int = Field( - default=16, - description="Password salt length", - deprecated=deprecated_flat_message("AUTH", "SALT_LENGTH", "PASSWORD_POLICY", "SALT_LENGTH"), - ) - SPECIAL_CHARACTERS: set[str] = Field( - default=set("!@#$%^&*()-_+="), - description="Set of allowed special characters", - deprecated=deprecated_flat_message("AUTH", "SPECIAL_CHARACTERS", "PASSWORD_POLICY", "SPECIAL_CHARACTERS"), - ) - PASSWORD_HISTORY_SIZE: int = Field( - default=3, - ge=0, - description="Number of previous passwords to remember (0 disables the history check)", - deprecated=deprecated_flat_message("AUTH", "PASSWORD_HISTORY_SIZE", "PASSWORD_POLICY", "HISTORY_SIZE"), - ) - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "JWT", - JwtConfig, - { - "ACCESS_TOKEN_EXPIRES_IN": "ACCESS_TOKEN_EXPIRES_IN", - "REFRESH_TOKEN_EXPIRES_IN": "REFRESH_TOKEN_EXPIRES_IN", - "HASH_ALGORITHM": "ALGORITHM", - "JWT_ISSUER": "ISSUER", - "JWT_AUDIENCE": "AUDIENCE", - "TOKEN_VERSION": "TOKEN_VERSION", - "JWT_LEEWAY": "LEEWAY", - "ENABLE_JTI_CLAIM": "ENABLE_JTI_CLAIM", - "ENABLE_TOKEN_ROTATION": "ENABLE_TOKEN_ROTATION", - "REFRESH_TOKEN_REUSE_INTERVAL": "REFRESH_TOKEN_REUSE_INTERVAL", - }, - ) - fold_flat_fields( - self, - "TOTP", - TotpConfig, - { - "TOTP_SECRET_KEY": "SECRET_KEY", - "TOTP_HASH_ALGORITHM": "HASH_ALGORITHM", - "TOTP_LENGTH": "LENGTH", - "TOTP_EXPIRES_IN": "EXPIRES_IN", - "TOTP_TIME_STEP": "TIME_STEP", - "TOTP_VERIFICATION_WINDOW": "VERIFICATION_WINDOW", - "TOTP_MAX_ATTEMPTS": "MAX_ATTEMPTS", - "TOTP_LOCKOUT_TIME": "LOCKOUT_TIME", - }, - ) - fold_flat_fields( - self, - "RATE_LIMITS", - RateLimitsConfig, - {"LOGIN_RATE_LIMIT": "LOGIN", "TOTP_RATE_LIMIT": "TOTP", "PASSWORD_RESET_RATE_LIMIT": "PASSWORD_RESET"}, - ) - fold_flat_fields( - self, - "PASSWORD_POLICY", - PasswordPolicyConfig, - { - "HASH_ITERATIONS": "HASH_ITERATIONS", - "MIN_LENGTH": "MIN_LENGTH", - "REQUIRE_DIGIT": "REQUIRE_DIGIT", - "REQUIRE_LOWERCASE": "REQUIRE_LOWERCASE", - "REQUIRE_SPECIAL": "REQUIRE_SPECIAL", - "REQUIRE_UPPERCASE": "REQUIRE_UPPERCASE", - "SALT_LENGTH": "SALT_LENGTH", - "SPECIAL_CHARACTERS": "SPECIAL_CHARACTERS", - "PASSWORD_HISTORY_SIZE": "HISTORY_SIZE", - }, - ) - return self diff --git a/archipy/configs/sections/elasticsearch.py b/archipy/configs/sections/elasticsearch.py index 3efc1f9f0..5c06bf37c 100644 --- a/archipy/configs/sections/elasticsearch.py +++ b/archipy/configs/sections/elasticsearch.py @@ -6,7 +6,6 @@ from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields from archipy.models.errors import FailedPreconditionError, InvalidArgumentError logger = logging.getLogger(__name__) @@ -137,13 +136,6 @@ class ElasticsearchConfig(BaseModel): default=1.0, description="Timeout for HTTP requests in seconds (1.0 is short for bulk and heavy searches; raise it)", ) - MAP_ERRORS: bool = Field( - default=False, - description=( - "Raise ArchiPy errors instead of raw elasticsearch-py exceptions. " - "Deprecated default: this will become True in a future release." - ), - ) IGNORE_STATUS: tuple[int, ...] = Field(default=(), description="HTTP status codes to ignore as errors") NODE_SELECTOR_CLASS: Literal["round_robin", "random"] = Field( default="round_robin", @@ -178,166 +170,6 @@ class ElasticsearchConfig(BaseModel): description="Node sniffing settings", ) - HTTP_USER_NAME: str | None = Field( - default=None, - deprecated=deprecated_flat_message("ELASTIC", "HTTP_USER_NAME", "AUTH", "USER_NAME"), - ) - HTTP_PASSWORD: SecretStr | None = Field( - default=None, - deprecated=deprecated_flat_message("ELASTIC", "HTTP_PASSWORD", "AUTH", "PASSWORD"), - ) - API_KEY: str | None = Field( - default=None, - deprecated=deprecated_flat_message("ELASTIC", "API_KEY", "AUTH", "API_KEY"), - ) - API_SECRET: SecretStr | None = Field( - default=None, - deprecated=deprecated_flat_message("ELASTIC", "API_SECRET", "AUTH", "API_SECRET"), - ) - BEARER_AUTH: SecretStr | None = Field( - default=None, - description="Bearer token for token or OIDC auth (exclusive with API key and basic auth)", - deprecated=deprecated_flat_message("ELASTIC", "BEARER_AUTH", "AUTH", "BEARER"), - ) - CA_CERTS: str | None = Field( - default=None, - description="Path to CA bundle for SSL verification", - deprecated=deprecated_flat_message("ELASTIC", "CA_CERTS", "TLS", "CA_CERTS"), - ) - SSL_ASSERT_FINGERPRINT: str | None = Field( - default=None, - description="SSL certificate fingerprint for verification", - deprecated=deprecated_flat_message("ELASTIC", "SSL_ASSERT_FINGERPRINT", "TLS", "ASSERT_FINGERPRINT"), - ) - VERIFY_CERTS: bool = Field( - default=True, - description="Whether to verify SSL certificates", - deprecated=deprecated_flat_message("ELASTIC", "VERIFY_CERTS", "TLS", "VERIFY_CERTS"), - ) - CLIENT_CERT: str | None = Field( - default=None, - description="Path to client certificate for TLS authentication", - deprecated=deprecated_flat_message("ELASTIC", "CLIENT_CERT", "TLS", "CLIENT_CERT"), - ) - CLIENT_KEY: str | None = Field( - default=None, - description="Path to client key for TLS authentication", - deprecated=deprecated_flat_message("ELASTIC", "CLIENT_KEY", "TLS", "CLIENT_KEY"), - ) - SSL_VERSION: ssl.TLSVersion | None = Field( - default=None, - description="TLS protocol version (client default if unset)", - deprecated=deprecated_flat_message("ELASTIC", "SSL_VERSION", "TLS", "VERSION"), - ) - SSL_CONTEXT: ssl.SSLContext | None = Field( - default=None, - description="Custom SSL context; takes precedence over the other TLS file settings in the client", - deprecated=deprecated_flat_message("ELASTIC", "SSL_CONTEXT", "TLS", "CONTEXT"), - ) - MAX_RETRIES: int = Field( - default=1, - ge=0, - description="Maximum number of retries per request", - deprecated=deprecated_flat_message("ELASTIC", "MAX_RETRIES", "RETRY", "MAX_RETRIES"), - ) - RETRY_ON_TIMEOUT: bool = Field( - default=True, - description="Retry on connection timeouts", - deprecated=deprecated_flat_message("ELASTIC", "RETRY_ON_TIMEOUT", "RETRY", "ON_TIMEOUT"), - ) - RETRY_ON_STATUS: tuple[int, ...] = Field( - default=(429, 502, 503, 504), - description="HTTP status codes to retry on", - deprecated=deprecated_flat_message("ELASTIC", "RETRY_ON_STATUS", "RETRY", "ON_STATUS"), - ) - RETRY_BACKOFF_BASE: float | None = Field( - default=None, - gt=0, - description="Base delay in seconds for exponential retry backoff (None: retry immediately)", - deprecated=deprecated_flat_message("ELASTIC", "RETRY_BACKOFF_BASE", "RETRY", "BACKOFF_BASE"), - ) - RETRY_BACKOFF_CAP: float | None = Field( - default=None, - gt=0, - description="Maximum delay in seconds between retries (None: client default)", - deprecated=deprecated_flat_message("ELASTIC", "RETRY_BACKOFF_CAP", "RETRY", "BACKOFF_CAP"), - ) - SNIFF_ON_START: bool = Field( - default=False, - description="Sniff nodes on client instantiation", - deprecated=deprecated_flat_message("ELASTIC", "SNIFF_ON_START", "SNIFFING", "ON_START"), - ) - SNIFF_BEFORE_REQUESTS: bool = Field( - default=False, - description="Sniff nodes before requests", - deprecated=deprecated_flat_message("ELASTIC", "SNIFF_BEFORE_REQUESTS", "SNIFFING", "BEFORE_REQUESTS"), - ) - SNIFF_ON_NODE_FAILURE: bool = Field( - default=True, - description="Sniff nodes on node failure", - deprecated=deprecated_flat_message("ELASTIC", "SNIFF_ON_NODE_FAILURE", "SNIFFING", "ON_NODE_FAILURE"), - ) - MIN_DELAY_BETWEEN_SNIFFING: float = Field( - default=60.0, - ge=0.0, - description="Minimum delay between sniffing attempts in seconds (needs SNIFF_BEFORE_REQUESTS)", - deprecated=deprecated_flat_message("ELASTIC", "MIN_DELAY_BETWEEN_SNIFFING", "SNIFFING", "MIN_DELAY"), - ) - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "AUTH", - ElasticsearchAuthConfig, - { - "HTTP_USER_NAME": "USER_NAME", - "HTTP_PASSWORD": "PASSWORD", - "API_KEY": "API_KEY", - "API_SECRET": "API_SECRET", - "BEARER_AUTH": "BEARER", - }, - ) - fold_flat_fields( - self, - "TLS", - ElasticsearchTlsConfig, - { - "CA_CERTS": "CA_CERTS", - "SSL_ASSERT_FINGERPRINT": "ASSERT_FINGERPRINT", - "VERIFY_CERTS": "VERIFY_CERTS", - "CLIENT_CERT": "CLIENT_CERT", - "CLIENT_KEY": "CLIENT_KEY", - "SSL_VERSION": "VERSION", - "SSL_CONTEXT": "CONTEXT", - }, - ) - fold_flat_fields( - self, - "RETRY", - ElasticsearchRetryConfig, - { - "MAX_RETRIES": "MAX_RETRIES", - "RETRY_ON_TIMEOUT": "ON_TIMEOUT", - "RETRY_ON_STATUS": "ON_STATUS", - "RETRY_BACKOFF_BASE": "BACKOFF_BASE", - "RETRY_BACKOFF_CAP": "BACKOFF_CAP", - }, - ) - fold_flat_fields( - self, - "SNIFFING", - ElasticsearchSniffingConfig, - { - "SNIFF_ON_START": "ON_START", - "SNIFF_BEFORE_REQUESTS": "BEFORE_REQUESTS", - "SNIFF_ON_NODE_FAILURE": "ON_NODE_FAILURE", - "MIN_DELAY_BETWEEN_SNIFFING": "MIN_DELAY", - }, - ) - return self - @model_validator(mode="after") def warn_insecure_transport(self) -> Self: """Warn when credentials travel over plaintext HTTP or without certificate verification.""" diff --git a/archipy/configs/sections/email.py b/archipy/configs/sections/email.py index 56e339cee..edb7a48a2 100644 --- a/archipy/configs/sections/email.py +++ b/archipy/configs/sections/email.py @@ -1,10 +1,8 @@ """Email configuration.""" -from typing import Literal, Self +from typing import Literal -from pydantic import BaseModel, ConfigDict, Field, model_validator - -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields +from pydantic import BaseModel, ConfigDict, Field class EmailTlsConfig(BaseModel): @@ -12,22 +10,16 @@ class EmailTlsConfig(BaseModel): model_config = ConfigDict(extra="forbid") - MODE: Literal["auto", "none", "starttls", "implicit"] = Field( - default="auto", + MODE: Literal["none", "starttls", "implicit"] = Field( + default="starttls", description=( "Transport security. 'starttls' requires a successful STARTTLS upgrade, 'implicit' opens a TLS " - "connection from the start (SMTPS, port 465), 'none' sends in clear text. 'auto' (default, deprecated) " - "upgrades only when the server offers STARTTLS, without verifying the certificate, and continues in " - "clear text otherwise" + "connection from the start (SMTPS, port 465), and 'none' allows unauthenticated clear-text SMTP" ), ) CA_FILE: str | None = Field( default=None, - description="PEM file with the CA certificates that verify the server (TLS_MODE 'starttls' or 'implicit')", - ) - VERIFY: bool = Field( - default=True, - description="Verify the server certificate and host name (TLS_MODE 'starttls' or 'implicit')", + description="PEM file with the CA certificates that verify the server (MODE 'starttls' or 'implicit')", ) @@ -85,89 +77,3 @@ class EmailConfig(BaseModel): TLS: EmailTlsConfig = Field(default_factory=EmailTlsConfig, description="TLS settings of the SMTP connection") POOL: EmailPoolConfig = Field(default_factory=EmailPoolConfig, description="Connection pool settings") ATTACHMENTS: EmailAttachmentsConfig = Field(default_factory=EmailAttachmentsConfig, description="Attachment limits") - - TLS_MODE: Literal["auto", "none", "starttls", "implicit"] = Field( - default="auto", - description=( - "Transport security. 'starttls' requires a successful STARTTLS upgrade, 'implicit' opens a TLS " - "connection from the start (SMTPS, port 465), 'none' sends in clear text. 'auto' (default, deprecated) " - "upgrades only when the server offers STARTTLS, without verifying the certificate, and continues in " - "clear text otherwise" - ), - deprecated=deprecated_flat_message("EMAIL", "TLS_MODE", "TLS", "MODE"), - ) - TLS_CA_FILE: str | None = Field( - default=None, - description="PEM file with the CA certificates that verify the server (TLS_MODE 'starttls' or 'implicit')", - deprecated=deprecated_flat_message("EMAIL", "TLS_CA_FILE", "TLS", "CA_FILE"), - ) - TLS_VERIFY: bool = Field( - default=True, - description="Verify the server certificate and host name (TLS_MODE 'starttls' or 'implicit')", - deprecated=deprecated_flat_message("EMAIL", "TLS_VERIFY", "TLS", "VERIFY"), - ) - POOL_SIZE: int = Field( - default=5, - ge=1, - description="Connection pool size", - deprecated=deprecated_flat_message("EMAIL", "POOL_SIZE", "POOL", "SIZE"), - ) - CONNECTION_TIMEOUT: int = Field( - default=30, - gt=0, - description="Connection timeout in seconds", - deprecated=deprecated_flat_message("EMAIL", "CONNECTION_TIMEOUT", "POOL", "CONNECTION_TIMEOUT"), - ) - CONNECTION_REFRESH_SECONDS: int = Field( - default=300, - ge=1, - description="Idle seconds after which a pooled SMTP connection is reconnected", - deprecated=deprecated_flat_message("EMAIL", "CONNECTION_REFRESH_SECONDS", "POOL", "CONNECTION_REFRESH_SECONDS"), - ) - ATTACHMENT_URL_TIMEOUT: int = Field( - default=30, - gt=0, - description="Timeout in seconds for downloading URL attachments", - deprecated=deprecated_flat_message("EMAIL", "ATTACHMENT_URL_TIMEOUT", "ATTACHMENTS", "URL_TIMEOUT"), - ) - ATTACHMENT_URL_ALLOWED_HOSTS: list[str] | None = Field( - default=None, - description="Host names URL attachments may be downloaded from; None allows any host (http and https only)", - deprecated=deprecated_flat_message("EMAIL", "ATTACHMENT_URL_ALLOWED_HOSTS", "ATTACHMENTS", "URL_ALLOWED_HOSTS"), - ) - ATTACHMENT_MAX_SIZE: int = Field( - default=5 * 1024 * 1024, - description="Maximum attachment size in bytes", - deprecated=deprecated_flat_message("EMAIL", "ATTACHMENT_MAX_SIZE", "ATTACHMENTS", "MAX_SIZE"), - ) - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "TLS", - EmailTlsConfig, - {"TLS_MODE": "MODE", "TLS_CA_FILE": "CA_FILE", "TLS_VERIFY": "VERIFY"}, - ) - fold_flat_fields( - self, - "POOL", - EmailPoolConfig, - { - "POOL_SIZE": "SIZE", - "CONNECTION_TIMEOUT": "CONNECTION_TIMEOUT", - "CONNECTION_REFRESH_SECONDS": "CONNECTION_REFRESH_SECONDS", - }, - ) - fold_flat_fields( - self, - "ATTACHMENTS", - EmailAttachmentsConfig, - { - "ATTACHMENT_URL_TIMEOUT": "URL_TIMEOUT", - "ATTACHMENT_URL_ALLOWED_HOSTS": "URL_ALLOWED_HOSTS", - "ATTACHMENT_MAX_SIZE": "MAX_SIZE", - }, - ) - return self diff --git a/archipy/configs/sections/fastapi.py b/archipy/configs/sections/fastapi.py index f52b0ae6f..c7dd06e7e 100644 --- a/archipy/configs/sections/fastapi.py +++ b/archipy/configs/sections/fastapi.py @@ -1,17 +1,6 @@ """FastAPI configuration.""" -import warnings -from typing import Self - -from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, model_validator - -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields -from archipy.configs.sections.uvicorn import UVICORN_FIELDS_ON_FASTAPI - - -def _moved(name: str) -> str: - """Return the deprecation message of a uvicorn setting that moved to ``UVICORN``.""" - return f"Use UVICORN.{name} instead; FASTAPI.{name} will be removed in 6.0.0" +from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt class FastAPIFormLimits(BaseModel): @@ -107,79 +96,11 @@ class FastAPIConfig(BaseModel): default=None, description="Limits for automatic form parsing, with FastAPI defaults for omitted keys", ) - ACCESS_LOG: bool = Field( - default=True, - description="Whether to enable access logging", - deprecated=_moved("ACCESS_LOG"), - ) - BACKLOG: int = Field(default=2048, description="Maximum number of queued connections", deprecated=_moved("BACKLOG")) - DATE_HEADER: bool = Field( - default=True, - description="Whether to include date header in responses", - deprecated=_moved("DATE_HEADER"), - ) - FORWARDED_ALLOW_IPS: list[str] | None = Field( - default=None, - description="List of allowed forwarded IPs", - deprecated=_moved("FORWARDED_ALLOW_IPS"), - ) - LIMIT_CONCURRENCY: int | None = Field( - default=None, - description="Maximum concurrent requests", - deprecated=_moved("LIMIT_CONCURRENCY"), - ) - LIMIT_MAX_REQUESTS: int | None = Field( - default=None, - description="Maximum number of requests", - deprecated=_moved("LIMIT_MAX_REQUESTS"), - ) - PROXY_HEADERS: bool = Field( - default=True, - description="Whether to trust proxy headers", - deprecated=_moved("PROXY_HEADERS"), - ) - RELOAD: bool = Field(default=False, description="Whether to enable auto-reload", deprecated=_moved("RELOAD")) - SERVER_HEADER: bool = Field( - default=True, - description="Whether to include server header", - deprecated=_moved("SERVER_HEADER"), - ) SERVE_HOST: str = Field( default="127.0.0.1", description="Host to serve the application on (set to 0.0.0.0 for container/public binding)", ) SERVE_PORT: int = Field(default=8100, description="Port to serve the application on") - TIMEOUT_GRACEFUL_SHUTDOWN: int | None = Field( - default=None, - description="Graceful shutdown timeout", - deprecated=_moved("TIMEOUT_GRACEFUL_SHUTDOWN"), - ) - TIMEOUT_KEEP_ALIVE: int = Field( - default=5, - description="Keep-alive timeout", - deprecated=_moved("TIMEOUT_KEEP_ALIVE"), - ) - WORKERS_COUNT: int = Field(default=4, description="Number of worker processes", deprecated=_moved("WORKERS_COUNT")) - WS_MAX_SIZE: int = Field( - default=16777216, - description="Maximum WebSocket message size", - deprecated=_moved("WS_MAX_SIZE"), - ) - WS_PER_MESSAGE_DEFLATE: bool = Field( - default=True, - description="Whether to enable WebSocket compression", - deprecated=_moved("WS_PER_MESSAGE_DEFLATE"), - ) - WS_PING_INTERVAL: float = Field( - default=20.0, - description="WebSocket ping interval", - deprecated=_moved("WS_PING_INTERVAL"), - ) - WS_PING_TIMEOUT: float = Field( - default=20.0, - description="WebSocket ping timeout", - deprecated=_moved("WS_PING_TIMEOUT"), - ) OPENAPI_URL: str | None = Field(default=None, description="URL for OpenAPI schema") DOCS_URL: str | None = Field(default=None, description="URL for API documentation") RE_DOC_URL: str | None = Field(default=None, description="URL for ReDoc documentation") @@ -198,160 +119,3 @@ class FastAPIConfig(BaseModel): default_factory=FastAPIHttpsRedirectConfig, description="HTTPS redirect middleware settings", ) - - CORS_MIDDLEWARE_ALLOW_CREDENTIALS: bool = Field( - default=True, - description="Whether to allow credentials in CORS", - deprecated=deprecated_flat_message("FASTAPI", "CORS_MIDDLEWARE_ALLOW_CREDENTIALS", "CORS", "ALLOW_CREDENTIALS"), - ) - CORS_MIDDLEWARE_ALLOW_HEADERS: list[str] = Field( - default=["*"], - description="Allowed CORS headers", - deprecated=deprecated_flat_message("FASTAPI", "CORS_MIDDLEWARE_ALLOW_HEADERS", "CORS", "ALLOW_HEADERS"), - ) - CORS_MIDDLEWARE_ALLOW_METHODS: list[str] = Field( - default=["*"], - description="Allowed CORS methods", - deprecated=deprecated_flat_message("FASTAPI", "CORS_MIDDLEWARE_ALLOW_METHODS", "CORS", "ALLOW_METHODS"), - ) - CORS_MIDDLEWARE_ALLOW_ORIGIN_REGEX: str | None = Field( - default=None, - description="Regex pattern for allowed origins", - deprecated=deprecated_flat_message( - "FASTAPI", - "CORS_MIDDLEWARE_ALLOW_ORIGIN_REGEX", - "CORS", - "ALLOW_ORIGIN_REGEX", - ), - ) - CORS_MIDDLEWARE_ALLOW_ORIGINS: list[str] = Field( - default=["*"], - description="Allowed CORS origins", - deprecated=deprecated_flat_message("FASTAPI", "CORS_MIDDLEWARE_ALLOW_ORIGINS", "CORS", "ALLOW_ORIGINS"), - ) - CORS_MIDDLEWARE_EXPOSE_HEADERS: list[str] = Field( - default=[], - description="Exposed CORS headers", - deprecated=deprecated_flat_message("FASTAPI", "CORS_MIDDLEWARE_EXPOSE_HEADERS", "CORS", "EXPOSE_HEADERS"), - ) - CORS_MIDDLEWARE_MAX_AGE: int = Field( - default=600, - description="Preflight cache duration in seconds", - deprecated=deprecated_flat_message("FASTAPI", "CORS_MIDDLEWARE_MAX_AGE", "CORS", "MAX_AGE"), - ) - GZIP_MIDDLEWARE_IS_ENABLED: bool = Field( - default=False, - description="Whether GZip response compression is enabled", - deprecated=deprecated_flat_message("FASTAPI", "GZIP_MIDDLEWARE_IS_ENABLED", "GZIP", "IS_ENABLED"), - ) - GZIP_MIDDLEWARE_MINIMUM_SIZE: int = Field( - default=500, - ge=0, - description="Minimum response body size in bytes before compression is applied", - deprecated=deprecated_flat_message("FASTAPI", "GZIP_MIDDLEWARE_MINIMUM_SIZE", "GZIP", "MINIMUM_SIZE"), - ) - GZIP_MIDDLEWARE_COMPRESSLEVEL: int = Field( - default=6, - ge=1, - le=9, - description="GZip compression level (1=fastest, 9=best compression)", - deprecated=deprecated_flat_message("FASTAPI", "GZIP_MIDDLEWARE_COMPRESSLEVEL", "GZIP", "COMPRESSLEVEL"), - ) - TRUSTED_HOST_MIDDLEWARE_IS_ENABLED: bool = Field( - default=False, - description="Whether TrustedHost middleware validates the Host header", - deprecated=deprecated_flat_message( - "FASTAPI", - "TRUSTED_HOST_MIDDLEWARE_IS_ENABLED", - "TRUSTED_HOST", - "IS_ENABLED", - ), - ) - TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS: list[str] = Field( - default=[], - description="Allowed hostnames (e.g. example.com, *.example.com)", - deprecated=deprecated_flat_message( - "FASTAPI", - "TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS", - "TRUSTED_HOST", - "ALLOWED_HOSTS", - ), - ) - TRUSTED_HOST_MIDDLEWARE_WWW_REDIRECT: bool = Field( - default=True, - description="Redirect www hosts to bare domain when allowed", - deprecated=deprecated_flat_message( - "FASTAPI", - "TRUSTED_HOST_MIDDLEWARE_WWW_REDIRECT", - "TRUSTED_HOST", - "WWW_REDIRECT", - ), - ) - HTTPS_REDIRECT_MIDDLEWARE_IS_ENABLED: bool = Field( - default=False, - description="Whether HTTP requests are redirected to HTTPS", - deprecated=deprecated_flat_message( - "FASTAPI", - "HTTPS_REDIRECT_MIDDLEWARE_IS_ENABLED", - "HTTPS_REDIRECT", - "IS_ENABLED", - ), - ) - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "CORS", - FastAPICorsConfig, - { - "CORS_MIDDLEWARE_ALLOW_CREDENTIALS": "ALLOW_CREDENTIALS", - "CORS_MIDDLEWARE_ALLOW_HEADERS": "ALLOW_HEADERS", - "CORS_MIDDLEWARE_ALLOW_METHODS": "ALLOW_METHODS", - "CORS_MIDDLEWARE_ALLOW_ORIGIN_REGEX": "ALLOW_ORIGIN_REGEX", - "CORS_MIDDLEWARE_ALLOW_ORIGINS": "ALLOW_ORIGINS", - "CORS_MIDDLEWARE_EXPOSE_HEADERS": "EXPOSE_HEADERS", - "CORS_MIDDLEWARE_MAX_AGE": "MAX_AGE", - }, - ) - fold_flat_fields( - self, - "GZIP", - FastAPIGzipConfig, - { - "GZIP_MIDDLEWARE_IS_ENABLED": "IS_ENABLED", - "GZIP_MIDDLEWARE_MINIMUM_SIZE": "MINIMUM_SIZE", - "GZIP_MIDDLEWARE_COMPRESSLEVEL": "COMPRESSLEVEL", - }, - ) - fold_flat_fields( - self, - "TRUSTED_HOST", - FastAPITrustedHostConfig, - { - "TRUSTED_HOST_MIDDLEWARE_IS_ENABLED": "IS_ENABLED", - "TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS": "ALLOWED_HOSTS", - "TRUSTED_HOST_MIDDLEWARE_WWW_REDIRECT": "WWW_REDIRECT", - }, - ) - fold_flat_fields( - self, - "HTTPS_REDIRECT", - FastAPIHttpsRedirectConfig, - {"HTTPS_REDIRECT_MIDDLEWARE_IS_ENABLED": "IS_ENABLED"}, - ) - return self - - @model_validator(mode="after") - def warn_deprecated_uvicorn_fields(self) -> Self: - """Warn when a deprecated uvicorn setting is set here; ``UVICORN`` holds it now.""" - used = sorted(name for name in UVICORN_FIELDS_ON_FASTAPI if name in self.model_fields_set) - if used: - warnings.warn( - f"FASTAPI.{', FASTAPI.'.join(used)} are deprecated and will be removed in 6.0.0; " - "set the same names on UVICORN instead", - DeprecationWarning, - stacklevel=2, - ) - return self diff --git a/archipy/configs/sections/grpc.py b/archipy/configs/sections/grpc.py index 9bcd0dab9..15b07e369 100644 --- a/archipy/configs/sections/grpc.py +++ b/archipy/configs/sections/grpc.py @@ -5,7 +5,6 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields from archipy.models.errors import InvalidArgumentError @@ -215,83 +214,6 @@ class GrpcConfig(BaseModel): description="Client channel TLS and mTLS settings", ) - TLS_ENABLED: bool = Field( - default=False, - description=( - "When True, ``AppUtils.add_grpc_port`` binds a TLS port with ``grpc.ssl_server_credentials`` instead of " - "an insecure port. Requires ``TLS_CERT_FILE`` and ``TLS_KEY_FILE``." - ), - deprecated=deprecated_flat_message("GRPC", "TLS_ENABLED", "TLS", "IS_ENABLED"), - ) - TLS_CERT_FILE: str | None = Field( - default=None, - description="Path to the PEM server certificate chain", - deprecated=deprecated_flat_message("GRPC", "TLS_CERT_FILE", "TLS", "CERT_FILE"), - ) - TLS_KEY_FILE: str | None = Field( - default=None, - description="Path to the PEM server private key", - deprecated=deprecated_flat_message("GRPC", "TLS_KEY_FILE", "TLS", "KEY_FILE"), - ) - TLS_CA_FILE: str | None = Field( - default=None, - description="Path to the PEM CA bundle used to verify client certificates (mTLS)", - deprecated=deprecated_flat_message("GRPC", "TLS_CA_FILE", "TLS", "CA_FILE"), - ) - TLS_REQUIRE_CLIENT_AUTH: bool = Field( - default=False, - description="When True, reject clients without a valid certificate. Requires ``TLS_CA_FILE``.", - deprecated=deprecated_flat_message("GRPC", "TLS_REQUIRE_CLIENT_AUTH", "TLS", "REQUIRE_CLIENT_AUTH"), - ) - STUB_TLS_ENABLED: bool = Field( - default=False, - description="When True, ``AppUtils.create_grpc_channel`` opens a TLS channel instead of a plaintext one.", - deprecated=deprecated_flat_message("GRPC", "STUB_TLS_ENABLED", "STUB_TLS", "IS_ENABLED"), - ) - STUB_TLS_CA_FILE: str | None = Field( - default=None, - description="Path to the PEM CA bundle that verifies the server. None uses the gRPC default roots.", - deprecated=deprecated_flat_message("GRPC", "STUB_TLS_CA_FILE", "STUB_TLS", "CA_FILE"), - ) - STUB_TLS_CERT_FILE: str | None = Field( - default=None, - description="Path to the PEM client certificate chain for mTLS. Requires ``STUB_TLS_KEY_FILE``.", - deprecated=deprecated_flat_message("GRPC", "STUB_TLS_CERT_FILE", "STUB_TLS", "CERT_FILE"), - ) - STUB_TLS_KEY_FILE: str | None = Field( - default=None, - description="Path to the PEM client private key for mTLS. Requires ``STUB_TLS_CERT_FILE``.", - deprecated=deprecated_flat_message("GRPC", "STUB_TLS_KEY_FILE", "STUB_TLS", "KEY_FILE"), - ) - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "TLS", - GrpcTlsConfig, - { - "TLS_ENABLED": "IS_ENABLED", - "TLS_CERT_FILE": "CERT_FILE", - "TLS_KEY_FILE": "KEY_FILE", - "TLS_CA_FILE": "CA_FILE", - "TLS_REQUIRE_CLIENT_AUTH": "REQUIRE_CLIENT_AUTH", - }, - ) - fold_flat_fields( - self, - "STUB_TLS", - GrpcStubTlsConfig, - { - "STUB_TLS_ENABLED": "IS_ENABLED", - "STUB_TLS_CA_FILE": "CA_FILE", - "STUB_TLS_CERT_FILE": "CERT_FILE", - "STUB_TLS_KEY_FILE": "KEY_FILE", - }, - ) - return self - @model_validator(mode="after") def resolve_thread_worker_count(self) -> Self: """Resolve worker thread count from CPU cores when not explicitly set. diff --git a/archipy/configs/sections/kafka.py b/archipy/configs/sections/kafka.py index 22f26256d..2f0bc42e7 100644 --- a/archipy/configs/sections/kafka.py +++ b/archipy/configs/sections/kafka.py @@ -1,11 +1,10 @@ """Kafka configuration.""" import logging -from typing import Literal, Self +from typing import Literal from pydantic import BaseModel, ConfigDict, Field, SecretStr, field_validator, model_validator -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields from archipy.models.errors import ConfigurationError logger = logging.getLogger(__name__) @@ -116,14 +115,6 @@ class KafkaConfig(BaseModel): default=None, description="Consumer enable.auto.offset.store; None keeps the librdkafka default (true)", ) - EMPTY_KEY_FOR_MISSING_KEY: bool = Field( - default=True, - description=( - "Deprecated legacy behavior: send messages produced without a key with an empty key (b''), so keyless " - "messages share one key and consumers read b'' instead of None. Set to False to send no key; False " - "becomes the default in a future release" - ), - ) ENABLE_IDEMPOTENCE: bool = Field(default=False, description="Enable idempotent producer for exactly-once delivery") TRANSACTIONAL_ID: str | None = Field(default=None, description="Transactional ID for the producer") TRANSACTION_TIMEOUT_MS: int | None = Field( @@ -179,77 +170,10 @@ class KafkaConfig(BaseModel): SASL: KafkaSaslConfig = Field(default_factory=KafkaSaslConfig, description="SASL authentication settings") SSL: KafkaSslConfig = Field(default_factory=KafkaSslConfig, description="SSL and TLS file settings") - SASL_MECHANISM: str | None = Field( - default=None, - description="SASL mechanism for authentication", - deprecated=deprecated_flat_message("KAFKA", "SASL_MECHANISM", "SASL", "MECHANISM"), - ) - USERNAME: str | None = Field( - default=None, - description="Username for SASL authentication", - deprecated=deprecated_flat_message("KAFKA", "USERNAME", "SASL", "USERNAME"), - ) - PASSWORD: SecretStr | None = Field( - default=None, - description="Password for SASL authentication", - deprecated=deprecated_flat_message("KAFKA", "PASSWORD", "SASL", "PASSWORD"), - ) - SSL_CA_FILE: str | None = Field( - default=None, - description="Path to SSL CA certificate file", - deprecated=deprecated_flat_message("KAFKA", "SSL_CA_FILE", "SSL", "CA_FILE"), - ) - SSL_CERT_FILE: str | None = Field( - default=None, - description="Path to SSL certificate file", - deprecated=deprecated_flat_message("KAFKA", "SSL_CERT_FILE", "SSL", "CERT_FILE"), - ) - SSL_KEY_FILE: str | None = Field( - default=None, - description="Path to SSL key file", - deprecated=deprecated_flat_message("KAFKA", "SSL_KEY_FILE", "SSL", "KEY_FILE"), - ) - SSL_ENDPOINT_IDENTIFICATION_ALGORITHM: Literal["https", "none"] = Field( - default="https", - description=( - "Broker hostname verification for SSL connections. 'https' checks the broker certificate against the " - "broker hostname; 'none' turns the check off and should only be used for brokers whose certificates " - "do not match their address" - ), - deprecated=deprecated_flat_message( - "KAFKA", - "SSL_ENDPOINT_IDENTIFICATION_ALGORITHM", - "SSL", - "ENDPOINT_IDENTIFICATION_ALGORITHM", - ), - ) - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "SASL", - KafkaSaslConfig, - {"SASL_MECHANISM": "MECHANISM", "USERNAME": "USERNAME", "PASSWORD": "PASSWORD"}, - ) - fold_flat_fields( - self, - "SSL", - KafkaSslConfig, - { - "SSL_CA_FILE": "CA_FILE", - "SSL_CERT_FILE": "CERT_FILE", - "SSL_KEY_FILE": "KEY_FILE", - "SSL_ENDPOINT_IDENTIFICATION_ALGORITHM": "ENDPOINT_IDENTIFICATION_ALGORITHM", - }, - ) - return self - - @field_validator("SECURITY_PROTOCOL", "SASL_MECHANISM", mode="before") + @field_validator("SECURITY_PROTOCOL", mode="before") @classmethod def normalize_security_names(cls, value: object) -> object: - """Uppercase the security protocol and the SASL mechanism, so ``ssl`` and ``plain`` behave like ``SSL``. + """Normalize the security protocol to uppercase. Args: value: The raw setting. @@ -314,7 +238,7 @@ def validate_security_settings(self) -> KafkaConfig: logger.warning("SSL enabled but no SSL certificates provided; this may cause connection issues.") if self.SSL.ENDPOINT_IDENTIFICATION_ALGORITHM == "none": logger.warning( - "Kafka broker hostname verification is disabled (SSL_ENDPOINT_IDENTIFICATION_ALGORITHM='none'); " + "Kafka broker hostname verification is disabled (SSL.ENDPOINT_IDENTIFICATION_ALGORITHM='none'); " "SSL connections will not check that the broker certificate matches its hostname.", ) return self diff --git a/archipy/configs/sections/keycloak.py b/archipy/configs/sections/keycloak.py index 8702af1fe..24985fc22 100644 --- a/archipy/configs/sections/keycloak.py +++ b/archipy/configs/sections/keycloak.py @@ -4,8 +4,6 @@ from pydantic import BaseModel, ConfigDict, Field, SecretStr, field_validator, model_validator -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields - _TRUE_WORDS = frozenset({"true", "1", "yes", "on", "t", "y"}) _FALSE_WORDS = frozenset({"false", "0", "no", "off", "f", "n"}) @@ -71,17 +69,13 @@ class KeycloakTokenValidationConfig(BaseModel): ) EXPECTED_ISSUER: str | None = Field( default=None, - description=( - "Required `iss` claim of locally verified tokens. When set, a mismatching issuer (and a `typ` other than " - "Bearer) is rejected. When unset, a mismatch against `{SERVER_URL}/realms/{REALM_NAME}` only emits a " - "DeprecationWarning; enforcement becomes the default in 6.0." - ), + description="Required issuer of locally verified tokens; None uses SERVER_URL and REALM_NAME", ) EXPECTED_AUDIENCE: str | None = Field( default=None, description=( "Required `aud` claim of locally verified tokens (typically CLIENT_ID). When set, tokens whose audience " - "does not include it (and tokens whose `typ` is not Bearer) are rejected." + "does not include it are rejected." ), ) REQUIRE_ORGANIZATION: bool = Field( @@ -128,113 +122,3 @@ class KeycloakConfig(BaseModel): default_factory=KeycloakTokenValidationConfig, description="Local token validation settings", ) - - IS_ADMIN_MODE_ENABLED: bool = Field( - default=False, - deprecated=deprecated_flat_message("KEYCLOAK", "IS_ADMIN_MODE_ENABLED", "ADMIN", "IS_ENABLED"), - ) - ADMIN_USERNAME: str | None = Field( - default=None, - deprecated=deprecated_flat_message("KEYCLOAK", "ADMIN_USERNAME", "ADMIN", "USERNAME"), - ) - ADMIN_PASSWORD: SecretStr | None = Field( - default=None, - deprecated=deprecated_flat_message("KEYCLOAK", "ADMIN_PASSWORD", "ADMIN", "PASSWORD"), - ) - ADMIN_REALM_NAME: str = Field( - default="master", - deprecated=deprecated_flat_message("KEYCLOAK", "ADMIN_REALM_NAME", "ADMIN", "REALM_NAME"), - ) - VERIFY_SSL: bool | str = Field( - default=True, - description="True/False toggles TLS verification; a string is the path of a CA bundle to verify against", - deprecated=deprecated_flat_message("KEYCLOAK", "VERIFY_SSL", "TLS", "VERIFY_SSL"), - ) - CLIENT_CERT_FILE: str | None = Field( - default=None, - description="Path of a client certificate (PEM) for mutual TLS; a combined cert+key file needs no key file", - deprecated=deprecated_flat_message("KEYCLOAK", "CLIENT_CERT_FILE", "TLS", "CLIENT_CERT_FILE"), - ) - CLIENT_KEY_FILE: str | None = Field( - default=None, - description="Path of the private key matching CLIENT_CERT_FILE", - deprecated=deprecated_flat_message("KEYCLOAK", "CLIENT_KEY_FILE", "TLS", "CLIENT_KEY_FILE"), - ) - TOKEN_LEEWAY_SECONDS: int = Field( - default=0, - ge=0, - description="Clock-skew tolerance in seconds when validating token expiry (python-keycloak defaults to 60)", - deprecated=deprecated_flat_message("KEYCLOAK", "TOKEN_LEEWAY_SECONDS", "TOKEN_VALIDATION", "LEEWAY_SECONDS"), - ) - EXPECTED_ISSUER: str | None = Field( - default=None, - description=( - "Required `iss` claim of locally verified tokens. When set, a mismatching issuer (and a `typ` other than " - "Bearer) is rejected. When unset, a mismatch against `{SERVER_URL}/realms/{REALM_NAME}` only emits a " - "DeprecationWarning; enforcement becomes the default in 6.0." - ), - deprecated=deprecated_flat_message("KEYCLOAK", "EXPECTED_ISSUER", "TOKEN_VALIDATION", "EXPECTED_ISSUER"), - ) - EXPECTED_AUDIENCE: str | None = Field( - default=None, - description=( - "Required `aud` claim of locally verified tokens (typically CLIENT_ID). When set, tokens whose audience " - "does not include it (and tokens whose `typ` is not Bearer) are rejected." - ), - deprecated=deprecated_flat_message("KEYCLOAK", "EXPECTED_AUDIENCE", "TOKEN_VALIDATION", "EXPECTED_AUDIENCE"), - ) - REQUIRE_ORGANIZATION: bool = Field( - default=False, - description="Require a selected organization in FastAPI and gRPC guards unless the guard overrides this value", - deprecated=deprecated_flat_message( - "KEYCLOAK", - "REQUIRE_ORGANIZATION", - "TOKEN_VALIDATION", - "REQUIRE_ORGANIZATION", - ), - ) - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "ADMIN", - KeycloakAdminConfig, - { - "IS_ADMIN_MODE_ENABLED": "IS_ENABLED", - "ADMIN_USERNAME": "USERNAME", - "ADMIN_PASSWORD": "PASSWORD", - "ADMIN_REALM_NAME": "REALM_NAME", - }, - ) - fold_flat_fields( - self, - "TLS", - KeycloakTlsConfig, - {"VERIFY_SSL": "VERIFY_SSL", "CLIENT_CERT_FILE": "CLIENT_CERT_FILE", "CLIENT_KEY_FILE": "CLIENT_KEY_FILE"}, - ) - fold_flat_fields( - self, - "TOKEN_VALIDATION", - KeycloakTokenValidationConfig, - { - "TOKEN_LEEWAY_SECONDS": "LEEWAY_SECONDS", - "EXPECTED_ISSUER": "EXPECTED_ISSUER", - "EXPECTED_AUDIENCE": "EXPECTED_AUDIENCE", - "REQUIRE_ORGANIZATION": "REQUIRE_ORGANIZATION", - }, - ) - return self - - @field_validator("VERIFY_SSL", mode="before") - @classmethod - def _parse_verify_ssl(cls, value: object) -> object: - """Keep boolean spellings from env vars ("false", "0", ...) as booleans; any other string is a CA path.""" - if isinstance(value, str): - lowered = value.strip().lower() - if lowered in _TRUE_WORDS: - return True - if lowered in _FALSE_WORDS: - return False - return value diff --git a/archipy/configs/sections/otel.py b/archipy/configs/sections/otel.py index afa18aea4..71ee0f899 100644 --- a/archipy/configs/sections/otel.py +++ b/archipy/configs/sections/otel.py @@ -7,7 +7,6 @@ from pydantic import BaseModel, ConfigDict, Field, HttpUrl, model_validator -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields from archipy.models.errors import ConfigurationError logger = logging.getLogger(__name__) @@ -413,73 +412,6 @@ class OpentelemetryConfig(BaseModel): description="Prometheus Pushgateway settings (METRICS_EXPORTER=pushgateway)", ) - METRICS_PUSHGATEWAY_URL: str | None = Field( - default=None, - description="Prometheus Pushgateway base URL when METRICS_EXPORTER=pushgateway (e.g. http://host:9091)", - deprecated=deprecated_flat_message("OTEL", "METRICS_PUSHGATEWAY_URL", "PUSHGATEWAY", "URL"), - ) - METRICS_PUSHGATEWAY_JOB: str | None = Field( - default=None, - description="Pushgateway job label (defaults to SERVICE_NAME when unset)", - deprecated=deprecated_flat_message("OTEL", "METRICS_PUSHGATEWAY_JOB", "PUSHGATEWAY", "JOB"), - ) - METRICS_PUSHGATEWAY_INTERVAL_SECONDS: int = Field( - default=60, - ge=1, - description="Interval between Pushgateway pushes when METRICS_EXPORTER=pushgateway", - deprecated=deprecated_flat_message( - "OTEL", - "METRICS_PUSHGATEWAY_INTERVAL_SECONDS", - "PUSHGATEWAY", - "INTERVAL_SECONDS", - ), - ) - METRICS_PUSHGATEWAY_TIMEOUT_SECONDS: float = Field( - default=10.0, - gt=0, - description="HTTP timeout in seconds for Pushgateway push/delete calls", - deprecated=deprecated_flat_message( - "OTEL", - "METRICS_PUSHGATEWAY_TIMEOUT_SECONDS", - "PUSHGATEWAY", - "TIMEOUT_SECONDS", - ), - ) - METRICS_PUSHGATEWAY_GROUPING_KEY: dict[str, str] = Field( - default_factory=dict, - max_length=16, - description="Extra Pushgateway grouping labels (instance, component, ...)", - deprecated=deprecated_flat_message("OTEL", "METRICS_PUSHGATEWAY_GROUPING_KEY", "PUSHGATEWAY", "GROUPING_KEY"), - ) - METRICS_PUSHGATEWAY_DELETE_ON_SHUTDOWN: bool = Field( - default=True, - description="Delete the Pushgateway grouping key on graceful OTel shutdown", - deprecated=deprecated_flat_message( - "OTEL", - "METRICS_PUSHGATEWAY_DELETE_ON_SHUTDOWN", - "PUSHGATEWAY", - "DELETE_ON_SHUTDOWN", - ), - ) - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "PUSHGATEWAY", - OtelPushgatewayConfig, - { - "METRICS_PUSHGATEWAY_URL": "URL", - "METRICS_PUSHGATEWAY_JOB": "JOB", - "METRICS_PUSHGATEWAY_INTERVAL_SECONDS": "INTERVAL_SECONDS", - "METRICS_PUSHGATEWAY_TIMEOUT_SECONDS": "TIMEOUT_SECONDS", - "METRICS_PUSHGATEWAY_GROUPING_KEY": "GROUPING_KEY", - "METRICS_PUSHGATEWAY_DELETE_ON_SHUTDOWN": "DELETE_ON_SHUTDOWN", - }, - ) - return self - def _fit_batch_sizes_to_queues(self) -> None: """Keep each batch no larger than its queue. diff --git a/archipy/configs/sections/redis.py b/archipy/configs/sections/redis.py index a68ebc63d..5f630c31a 100644 --- a/archipy/configs/sections/redis.py +++ b/archipy/configs/sections/redis.py @@ -6,7 +6,6 @@ from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields from archipy.models.errors import ConfigurationError logger = logging.getLogger(__name__) @@ -111,150 +110,6 @@ class RedisConfig(BaseModel): TLS: RedisTlsConfig = Field(default_factory=RedisTlsConfig, description="TLS settings of the Redis connection") RETRY: RedisRetryConfig = Field(default_factory=RedisRetryConfig, description="Retry and backoff settings") - CLUSTER_NODES: list[str] = Field( - default=[], - description="List of cluster node addresses (host:port)", - deprecated=deprecated_flat_message("REDIS", "CLUSTER_NODES", "CLUSTER", "NODES"), - ) - CLUSTER_REQUIRE_FULL_COVERAGE: bool = Field( - default=True, - description="Require full cluster coverage", - deprecated=deprecated_flat_message( - "REDIS", - "CLUSTER_REQUIRE_FULL_COVERAGE", - "CLUSTER", - "REQUIRE_FULL_COVERAGE", - ), - ) - CLUSTER_READ_FROM_REPLICAS: bool = Field( - default=True, - description="Allow reading from replica nodes", - deprecated=deprecated_flat_message("REDIS", "CLUSTER_READ_FROM_REPLICAS", "CLUSTER", "READ_FROM_REPLICAS"), - ) - SENTINEL_NODES: list[str] = Field( - default=[], - description="List of sentinel addresses (host:port)", - deprecated=deprecated_flat_message("REDIS", "SENTINEL_NODES", "SENTINEL", "NODES"), - ) - SENTINEL_SERVICE_NAME: str | None = Field( - default=None, - description="Master service name for sentinel", - deprecated=deprecated_flat_message("REDIS", "SENTINEL_SERVICE_NAME", "SENTINEL", "SERVICE_NAME"), - ) - SENTINEL_SOCKET_TIMEOUT: float = Field( - default=0.1, - description="Sentinel socket timeout", - deprecated=deprecated_flat_message("REDIS", "SENTINEL_SOCKET_TIMEOUT", "SENTINEL", "SOCKET_TIMEOUT"), - ) - SENTINEL_PASSWORD: SecretStr | None = Field( - default=None, - description="Password for sentinel nodes (if distinct)", - deprecated=deprecated_flat_message("REDIS", "SENTINEL_PASSWORD", "SENTINEL", "PASSWORD"), - ) - SENTINEL_USERNAME: str | None = Field( - default=None, - description="ACL username for sentinel nodes (if distinct)", - deprecated=deprecated_flat_message("REDIS", "SENTINEL_USERNAME", "SENTINEL", "USERNAME"), - ) - SSL: bool = Field( - default=False, - description="Connect to Redis over TLS", - deprecated=deprecated_flat_message("REDIS", "SSL", "TLS", "IS_ENABLED"), - ) - SSL_CA_CERTS: str | None = Field( - default=None, - description="Path to the CA bundle used to verify the server", - deprecated=deprecated_flat_message("REDIS", "SSL_CA_CERTS", "TLS", "CA_CERTS"), - ) - SSL_CERTFILE: str | None = Field( - default=None, - description="Path to the client certificate (mTLS)", - deprecated=deprecated_flat_message("REDIS", "SSL_CERTFILE", "TLS", "CERTFILE"), - ) - SSL_KEYFILE: str | None = Field( - default=None, - description="Path to the client private key (mTLS)", - deprecated=deprecated_flat_message("REDIS", "SSL_KEYFILE", "TLS", "KEYFILE"), - ) - SSL_CHECK_HOSTNAME: bool = Field( - default=True, - description="Verify the server hostname against its certificate", - deprecated=deprecated_flat_message("REDIS", "SSL_CHECK_HOSTNAME", "TLS", "CHECK_HOSTNAME"), - ) - RETRY_ATTEMPTS: int | None = Field( - default=None, - ge=0, - description="Retries per command with exponential backoff on connection errors; None keeps redis-py defaults", - deprecated=deprecated_flat_message("REDIS", "RETRY_ATTEMPTS", "RETRY", "ATTEMPTS"), - ) - RETRY_BACKOFF_BASE: float = Field( - default=0.008, - gt=0, - description="Exponential backoff base delay in seconds", - deprecated=deprecated_flat_message("REDIS", "RETRY_BACKOFF_BASE", "RETRY", "BACKOFF_BASE"), - ) - RETRY_BACKOFF_CAP: float = Field( - default=0.512, - gt=0, - description="Exponential backoff maximum delay in seconds", - deprecated=deprecated_flat_message("REDIS", "RETRY_BACKOFF_CAP", "RETRY", "BACKOFF_CAP"), - ) - RETRY_ON_TIMEOUT: bool = Field( - default=False, - description="Also retry commands that hit a socket timeout", - deprecated=deprecated_flat_message("REDIS", "RETRY_ON_TIMEOUT", "RETRY", "ON_TIMEOUT"), - ) - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "CLUSTER", - RedisClusterConfig, - { - "CLUSTER_NODES": "NODES", - "CLUSTER_REQUIRE_FULL_COVERAGE": "REQUIRE_FULL_COVERAGE", - "CLUSTER_READ_FROM_REPLICAS": "READ_FROM_REPLICAS", - }, - ) - fold_flat_fields( - self, - "SENTINEL", - RedisSentinelConfig, - { - "SENTINEL_NODES": "NODES", - "SENTINEL_SERVICE_NAME": "SERVICE_NAME", - "SENTINEL_SOCKET_TIMEOUT": "SOCKET_TIMEOUT", - "SENTINEL_PASSWORD": "PASSWORD", - "SENTINEL_USERNAME": "USERNAME", - }, - ) - fold_flat_fields( - self, - "TLS", - RedisTlsConfig, - { - "SSL": "IS_ENABLED", - "SSL_CA_CERTS": "CA_CERTS", - "SSL_CERTFILE": "CERTFILE", - "SSL_KEYFILE": "KEYFILE", - "SSL_CHECK_HOSTNAME": "CHECK_HOSTNAME", - }, - ) - fold_flat_fields( - self, - "RETRY", - RedisRetryConfig, - { - "RETRY_ATTEMPTS": "ATTEMPTS", - "RETRY_BACKOFF_BASE": "BACKOFF_BASE", - "RETRY_BACKOFF_CAP": "BACKOFF_CAP", - "RETRY_ON_TIMEOUT": "ON_TIMEOUT", - }, - ) - return self - @staticmethod def _validate_node_address(node: str, *, port_required: bool) -> None: """Validate a ``host[:port]`` node address.""" diff --git a/archipy/configs/sections/scylladb.py b/archipy/configs/sections/scylladb.py index a25364814..a0046fc79 100644 --- a/archipy/configs/sections/scylladb.py +++ b/archipy/configs/sections/scylladb.py @@ -5,13 +5,8 @@ from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields from archipy.models.errors import InvalidArgumentError -_NO_POOL_SIZING = ( - "scylla-driver has no per-host connection pool sizing, so this setting has no effect; it will be removed in 6.0.0" -) - class ScyllaTlsConfig(BaseModel): """TLS settings of the cluster connection.""" @@ -351,30 +346,6 @@ class ScyllaDBConfig(BaseModel): default=None, description="Consistency level of the Paxos phase of lightweight transactions (IF clauses); unset keeps SERIAL", ) - MAX_CONNECTIONS_PER_HOST: int = Field( - default=2, - ge=1, - description="Maximum connections per host (recommended: 1-3 per CPU core)", - deprecated=_NO_POOL_SIZING, - ) - MIN_CONNECTIONS_PER_HOST: int = Field( - default=1, - ge=1, - description="Minimum connections per host", - deprecated=_NO_POOL_SIZING, - ) - CORE_CONNECTIONS_PER_HOST: int = Field( - default=1, - ge=1, - description="Core connections per host to maintain", - deprecated=_NO_POOL_SIZING, - ) - MAX_REQUESTS_PER_CONNECTION: int = Field( - default=100, - ge=1, - description="Maximum concurrent requests per connection", - deprecated=_NO_POOL_SIZING, - ) LOCAL_DC: str | None = Field( default=None, description="Local datacenter name for datacenter-aware routing", @@ -403,180 +374,6 @@ class ScyllaDBConfig(BaseModel): description="Keyspace replication settings", ) - TLS_ENABLED: bool = Field( - default=False, - description=( - "Encrypt the connection to the cluster with TLS. When disabled (default) credentials and data " - "travel in plain text." - ), - deprecated=deprecated_flat_message("SCYLLADB", "TLS_ENABLED", "TLS", "IS_ENABLED"), - ) - TLS_CA_FILE: str | None = Field( - default=None, - description="Path to the CA bundle used to verify the server certificate (system CAs when unset)", - deprecated=deprecated_flat_message("SCYLLADB", "TLS_CA_FILE", "TLS", "CA_FILE"), - ) - TLS_CERT_FILE: str | None = Field( - default=None, - description="Path to the client certificate for mutual TLS (requires TLS_KEY_FILE)", - deprecated=deprecated_flat_message("SCYLLADB", "TLS_CERT_FILE", "TLS", "CERT_FILE"), - ) - TLS_KEY_FILE: str | None = Field( - default=None, - description="Path to the client private key for mutual TLS (requires TLS_CERT_FILE)", - deprecated=deprecated_flat_message("SCYLLADB", "TLS_KEY_FILE", "TLS", "KEY_FILE"), - ) - TLS_VERIFY_MODE: Literal["CERT_REQUIRED", "CERT_NONE"] = Field( - default="CERT_REQUIRED", - description=( - "Server certificate verification. 'CERT_REQUIRED' validates the chain; " - "'CERT_NONE' disables verification (and hostname checking) and is insecure" - ), - deprecated=deprecated_flat_message("SCYLLADB", "TLS_VERIFY_MODE", "TLS", "VERIFY_MODE"), - ) - TLS_CHECK_HOSTNAME: bool = Field( - default=True, - description="Check that the server certificate matches the contact point host name", - deprecated=deprecated_flat_message("SCYLLADB", "TLS_CHECK_HOSTNAME", "TLS", "CHECK_HOSTNAME"), - ) - TLS_SERVER_NAME: str | None = Field( - default=None, - description="Host name to match the server certificate against, when it differs from the contact point address", - deprecated=deprecated_flat_message("SCYLLADB", "TLS_SERVER_NAME", "TLS", "SERVER_NAME"), - ) - TLS_SESSION_CACHE_ENABLED: bool = Field( - default=True, - description=( - "Resume TLS sessions. A resumed session skips the certificate check, so a revoked or expired certificate " - "can be accepted until the cached session expires; disable to verify on every connection" - ), - deprecated=deprecated_flat_message("SCYLLADB", "TLS_SESSION_CACHE_ENABLED", "TLS", "SESSION_CACHE_ENABLED"), - ) - RETRY_POLICY: Literal["EXPONENTIAL_BACKOFF", "FALLTHROUGH"] = Field( - default="EXPONENTIAL_BACKOFF", - description="Retry policy type (uses native driver RetryPolicy). " - "Options: 'EXPONENTIAL_BACKOFF' (retries with exponential backoff), " - "'FALLTHROUGH' (never retries, propagates failures to application)", - deprecated=deprecated_flat_message("SCYLLADB", "RETRY_POLICY", "RETRY", "POLICY"), - ) - RETRY_MAX_NUM_RETRIES: float = Field( - default=3.0, - ge=0.0, - description="Maximum number of retries for ExponentialBackoffRetryPolicy", - deprecated=deprecated_flat_message("SCYLLADB", "RETRY_MAX_NUM_RETRIES", "RETRY", "MAX_NUM_RETRIES"), - ) - RETRY_MIN_INTERVAL: float = Field( - default=0.1, - ge=0.0, - description="Minimum interval in seconds between retries for ExponentialBackoffRetryPolicy", - deprecated=deprecated_flat_message("SCYLLADB", "RETRY_MIN_INTERVAL", "RETRY", "MIN_INTERVAL"), - ) - RETRY_MAX_INTERVAL: float = Field( - default=10.0, - ge=0.0, - description="Maximum interval in seconds between retries for ExponentialBackoffRetryPolicy", - deprecated=deprecated_flat_message("SCYLLADB", "RETRY_MAX_INTERVAL", "RETRY", "MAX_INTERVAL"), - ) - RECONNECTION_POLICY: Literal["CONSTANT", "EXPONENTIAL"] | None = Field( - default=None, - description=( - "How the driver retries a down host. 'CONSTANT' waits RECONNECTION_BASE_DELAY between attempts; " - "'EXPONENTIAL' grows the wait from RECONNECTION_BASE_DELAY up to RECONNECTION_MAX_DELAY. " - "Unset keeps the driver default (exponential, 1s to 600s)" - ), - deprecated=deprecated_flat_message("SCYLLADB", "RECONNECTION_POLICY", "RECONNECTION", "POLICY"), - ) - RECONNECTION_BASE_DELAY: float = Field( - default=1.0, - gt=0.0, - description="Seconds between reconnection attempts (first delay for EXPONENTIAL)", - deprecated=deprecated_flat_message("SCYLLADB", "RECONNECTION_BASE_DELAY", "RECONNECTION", "BASE_DELAY"), - ) - RECONNECTION_MAX_DELAY: float = Field( - default=600.0, - gt=0.0, - description="Upper bound in seconds of the delay between attempts for EXPONENTIAL", - deprecated=deprecated_flat_message("SCYLLADB", "RECONNECTION_MAX_DELAY", "RECONNECTION", "MAX_DELAY"), - ) - RECONNECTION_MAX_ATTEMPTS: int | None = Field( - default=None, - ge=1, - description="Stop reconnecting to a host after this many attempts (unlimited when unset)", - deprecated=deprecated_flat_message("SCYLLADB", "RECONNECTION_MAX_ATTEMPTS", "RECONNECTION", "MAX_ATTEMPTS"), - ) - SPECULATIVE_EXECUTION_DELAY: float | None = Field( - default=None, - gt=0.0, - description=( - "Seconds to wait for a response before the driver sends the query to the next host. " - "Applies only to idempotent statements. Unset disables speculative execution" - ), - deprecated=deprecated_flat_message("SCYLLADB", "SPECULATIVE_EXECUTION_DELAY", "SPECULATIVE_EXECUTION", "DELAY"), - ) - SPECULATIVE_EXECUTION_MAX_ATTEMPTS: int = Field( - default=2, - ge=1, - description="Extra executions allowed per query when SPECULATIVE_EXECUTION_DELAY is set", - deprecated=deprecated_flat_message( - "SCYLLADB", - "SPECULATIVE_EXECUTION_MAX_ATTEMPTS", - "SPECULATIVE_EXECUTION", - "MAX_ATTEMPTS", - ), - ) - ENABLE_PREPARED_STATEMENT_CACHE: bool = Field( - default=True, - description="Enable prepared statement caching", - deprecated=deprecated_flat_message( - "SCYLLADB", - "ENABLE_PREPARED_STATEMENT_CACHE", - "PREPARED_CACHE", - "IS_ENABLED", - ), - ) - PREPARED_STATEMENT_CACHE_SIZE: int = Field( - default=100, - ge=1, - description="Maximum cached prepared statements", - deprecated=deprecated_flat_message("SCYLLADB", "PREPARED_STATEMENT_CACHE_SIZE", "PREPARED_CACHE", "SIZE"), - ) - PREPARED_STATEMENT_CACHE_TTL_SECONDS: int = Field( - default=3600, - ge=1, - description="TTL for prepared statement cache in seconds (1 hour)", - deprecated=deprecated_flat_message( - "SCYLLADB", - "PREPARED_STATEMENT_CACHE_TTL_SECONDS", - "PREPARED_CACHE", - "TTL_SECONDS", - ), - ) - IDLE_HEARTBEAT_INTERVAL: float | None = Field( - default=None, - ge=0.0, - description=( - "Seconds of connection idleness before the driver sends a heartbeat to detect dead connections. " - "0 disables heartbeats; unset keeps the driver default (30)" - ), - deprecated=deprecated_flat_message("SCYLLADB", "IDLE_HEARTBEAT_INTERVAL", "HEARTBEAT", "IDLE_INTERVAL"), - ) - IDLE_HEARTBEAT_TIMEOUT: float | None = Field( - default=None, - gt=0.0, - description="Seconds to wait for a heartbeat response before the connection is dropped (driver default 30)", - deprecated=deprecated_flat_message("SCYLLADB", "IDLE_HEARTBEAT_TIMEOUT", "HEARTBEAT", "IDLE_TIMEOUT"), - ) - REPLICATION_STRATEGY: Literal["SimpleStrategy", "NetworkTopologyStrategy"] = Field( - default="NetworkTopologyStrategy", - description="Replication strategy for keyspace creation", - deprecated=deprecated_flat_message("SCYLLADB", "REPLICATION_STRATEGY", "REPLICATION", "STRATEGY"), - ) - REPLICATION_CONFIG: dict[str, int] | None = Field( - default={"datacenter1": 1}, - description="Replication configuration (e.g., {'dc1': 3, 'dc2': 2} for NetworkTopologyStrategy)", - deprecated=deprecated_flat_message("SCYLLADB", "REPLICATION_CONFIG", "REPLICATION", "CONFIG"), - ) - @model_validator(mode="after") def validate_contact_points(self) -> Self: """Validate that at least one contact point is provided.""" @@ -597,92 +394,6 @@ def validate_authentication(self) -> Self: ) return self - @model_validator(mode="after") - def validate_connection_pool(self) -> Self: - """Validate connection pool configuration.""" - pool = vars(self) # read without the pydantic deprecation warning - if pool["MIN_CONNECTIONS_PER_HOST"] > pool["MAX_CONNECTIONS_PER_HOST"]: - raise InvalidArgumentError( - argument_name="connection_pool", - additional_data={"error": "MIN_CONNECTIONS_PER_HOST cannot exceed MAX_CONNECTIONS_PER_HOST"}, - ) - if pool["CORE_CONNECTIONS_PER_HOST"] > pool["MAX_CONNECTIONS_PER_HOST"]: - raise InvalidArgumentError( - argument_name="connection_pool", - additional_data={"error": "CORE_CONNECTIONS_PER_HOST cannot exceed MAX_CONNECTIONS_PER_HOST"}, - ) - return self - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "TLS", - ScyllaTlsConfig, - { - "TLS_ENABLED": "IS_ENABLED", - "TLS_CA_FILE": "CA_FILE", - "TLS_CERT_FILE": "CERT_FILE", - "TLS_KEY_FILE": "KEY_FILE", - "TLS_VERIFY_MODE": "VERIFY_MODE", - "TLS_CHECK_HOSTNAME": "CHECK_HOSTNAME", - "TLS_SERVER_NAME": "SERVER_NAME", - "TLS_SESSION_CACHE_ENABLED": "SESSION_CACHE_ENABLED", - }, - ) - fold_flat_fields( - self, - "RETRY", - ScyllaRetryConfig, - { - "RETRY_POLICY": "POLICY", - "RETRY_MAX_NUM_RETRIES": "MAX_NUM_RETRIES", - "RETRY_MIN_INTERVAL": "MIN_INTERVAL", - "RETRY_MAX_INTERVAL": "MAX_INTERVAL", - }, - ) - fold_flat_fields( - self, - "RECONNECTION", - ScyllaReconnectionConfig, - { - "RECONNECTION_POLICY": "POLICY", - "RECONNECTION_BASE_DELAY": "BASE_DELAY", - "RECONNECTION_MAX_DELAY": "MAX_DELAY", - "RECONNECTION_MAX_ATTEMPTS": "MAX_ATTEMPTS", - }, - ) - fold_flat_fields( - self, - "SPECULATIVE_EXECUTION", - ScyllaSpeculativeExecutionConfig, - {"SPECULATIVE_EXECUTION_DELAY": "DELAY", "SPECULATIVE_EXECUTION_MAX_ATTEMPTS": "MAX_ATTEMPTS"}, - ) - fold_flat_fields( - self, - "PREPARED_CACHE", - ScyllaPreparedCacheConfig, - { - "ENABLE_PREPARED_STATEMENT_CACHE": "IS_ENABLED", - "PREPARED_STATEMENT_CACHE_SIZE": "SIZE", - "PREPARED_STATEMENT_CACHE_TTL_SECONDS": "TTL_SECONDS", - }, - ) - fold_flat_fields( - self, - "HEARTBEAT", - ScyllaHeartbeatConfig, - {"IDLE_HEARTBEAT_INTERVAL": "IDLE_INTERVAL", "IDLE_HEARTBEAT_TIMEOUT": "IDLE_TIMEOUT"}, - ) - fold_flat_fields( - self, - "REPLICATION", - ScyllaReplicationConfig, - {"REPLICATION_STRATEGY": "STRATEGY", "REPLICATION_CONFIG": "CONFIG"}, - ) - return self - def build_ssl_context(self) -> ssl.SSLContext | None: """Build the TLS context for the cluster connection (see ``TLS``).""" return self.TLS.build_ssl_context() diff --git a/archipy/configs/sections/sqlalchemy.py b/archipy/configs/sections/sqlalchemy.py index 013a2aff4..787fab1bf 100644 --- a/archipy/configs/sections/sqlalchemy.py +++ b/archipy/configs/sections/sqlalchemy.py @@ -7,7 +7,6 @@ from pydantic import BaseModel, ConfigDict, Field, PostgresDsn, SecretStr, field_validator, model_validator -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields from archipy.models.errors import ConfigurationError @@ -84,88 +83,6 @@ class SQLAlchemyConfig(BaseModel): description="Search query count cache settings", ) - POOL_MAX_OVERFLOW: int = Field( - default=1, - description="Maximum number of connections to allow in pool overflow", - deprecated=deprecated_flat_message("SQLALCHEMY", "POOL_MAX_OVERFLOW", "POOL", "MAX_OVERFLOW"), - ) - POOL_PRE_PING: bool = Field( - default=True, - description="Whether to ping connections before use", - deprecated=deprecated_flat_message("SQLALCHEMY", "POOL_PRE_PING", "POOL", "PRE_PING"), - ) - POOL_RECYCLE_SECONDS: int = Field( - default=10 * 60, - description="Number of seconds between connection recycling", - deprecated=deprecated_flat_message("SQLALCHEMY", "POOL_RECYCLE_SECONDS", "POOL", "RECYCLE_SECONDS"), - ) - POOL_RESET_ON_RETURN: str = Field( - default="rollback", - description="Action to take when returning connections to pool", - deprecated=deprecated_flat_message("SQLALCHEMY", "POOL_RESET_ON_RETURN", "POOL", "RESET_ON_RETURN"), - ) - POOL_SIZE: int = Field( - default=20, - description="Number of connections to keep open in the pool", - deprecated=deprecated_flat_message("SQLALCHEMY", "POOL_SIZE", "POOL", "SIZE"), - ) - POOL_TIMEOUT: int = Field( - default=30, - description="Seconds to wait before giving up on getting a connection", - deprecated=deprecated_flat_message("SQLALCHEMY", "POOL_TIMEOUT", "POOL", "TIMEOUT"), - ) - POOL_USE_LIFO: bool = Field( - default=True, - description="Whether to use LIFO for connection pool", - deprecated=deprecated_flat_message("SQLALCHEMY", "POOL_USE_LIFO", "POOL", "USE_LIFO"), - ) - COUNT_CACHE_ENABLED: bool = Field( - default=False, - description="Whether to cache the total count of search queries, so only the first page runs a COUNT", - deprecated=deprecated_flat_message("SQLALCHEMY", "COUNT_CACHE_ENABLED", "COUNT_CACHE", "IS_ENABLED"), - ) - COUNT_CACHE_MAX_SIZE: int = Field( - default=1000, - ge=1, - description="Maximum number of cached search query totals", - deprecated=deprecated_flat_message("SQLALCHEMY", "COUNT_CACHE_MAX_SIZE", "COUNT_CACHE", "MAX_SIZE"), - ) - COUNT_CACHE_TTL_SECONDS: int = Field( - default=60, - ge=1, - description="Seconds a cached search query total stays valid", - deprecated=deprecated_flat_message("SQLALCHEMY", "COUNT_CACHE_TTL_SECONDS", "COUNT_CACHE", "TTL_SECONDS"), - ) - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "POOL", - SQLAlchemyPoolConfig, - { - "POOL_MAX_OVERFLOW": "MAX_OVERFLOW", - "POOL_PRE_PING": "PRE_PING", - "POOL_RECYCLE_SECONDS": "RECYCLE_SECONDS", - "POOL_RESET_ON_RETURN": "RESET_ON_RETURN", - "POOL_SIZE": "SIZE", - "POOL_TIMEOUT": "TIMEOUT", - "POOL_USE_LIFO": "USE_LIFO", - }, - ) - fold_flat_fields( - self, - "COUNT_CACHE", - SQLAlchemyCountCacheConfig, - { - "COUNT_CACHE_ENABLED": "IS_ENABLED", - "COUNT_CACHE_MAX_SIZE": "MAX_SIZE", - "COUNT_CACHE_TTL_SECONDS": "TTL_SECONDS", - }, - ) - return self - class SQLiteSQLAlchemyConfig(SQLAlchemyConfig): """Configuration settings for SQLite SQLAlchemy ORM. diff --git a/archipy/configs/sections/temporal.py b/archipy/configs/sections/temporal.py index 19a7d6653..0f80c929c 100644 --- a/archipy/configs/sections/temporal.py +++ b/archipy/configs/sections/temporal.py @@ -4,12 +4,8 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields from archipy.models.errors import InvalidArgumentError -# Kept for backward compatibility; the TLS files no longer have to be set all together. -TLS_CERT_PARTS_REQUIRED = 3 - class TemporalTlsConfig(BaseModel): """TLS settings of the Temporal connection.""" @@ -356,252 +352,6 @@ class TemporalConfig(BaseModel): description="Default workflow and activity retry policy", ) - TLS_ENABLED: bool | None = Field( - default=None, - description=( - "Force TLS on (system CA bundle) or off; None enables it when API_KEY or any TLS_* file is set " - "(server-only TLS needs just TLS_CA_CERT or nothing)" - ), - deprecated=deprecated_flat_message("TEMPORAL", "TLS_ENABLED", "TLS", "IS_ENABLED"), - ) - TLS_CA_CERT: str | None = Field( - default=None, - description="Path to TLS CA certificate", - deprecated=deprecated_flat_message("TEMPORAL", "TLS_CA_CERT", "TLS", "CA_CERT"), - ) - TLS_CLIENT_CERT: str | None = Field( - default=None, - description="Path to TLS client certificate", - deprecated=deprecated_flat_message("TEMPORAL", "TLS_CLIENT_CERT", "TLS", "CLIENT_CERT"), - ) - TLS_CLIENT_KEY: str | None = Field( - default=None, - description="Path to TLS client private key", - deprecated=deprecated_flat_message("TEMPORAL", "TLS_CLIENT_KEY", "TLS", "CLIENT_KEY"), - ) - TLS_SERVER_NAME: str | None = Field( - default=None, - description="Server name to verify the TLS certificate against, when it differs from HOST", - deprecated=deprecated_flat_message("TEMPORAL", "TLS_SERVER_NAME", "TLS", "SERVER_NAME"), - ) - TLS_VERIFICATION_SERVER_NAME: str | None = Field( - default=None, - description=( - "Name checked against the server certificate without changing the SNI sent, e.g. behind an " - "SNI-inspecting proxy (requires TLS_CA_CERT)" - ), - deprecated=deprecated_flat_message( - "TEMPORAL", - "TLS_VERIFICATION_SERVER_NAME", - "TLS", - "VERIFICATION_SERVER_NAME", - ), - ) - WORKER_GRACEFUL_SHUTDOWN_SECONDS: int = Field( - default=30, - ge=0, - description="Maximum time in seconds to wait for graceful worker shutdown", - deprecated=deprecated_flat_message( - "TEMPORAL", - "WORKER_GRACEFUL_SHUTDOWN_SECONDS", - "WORKER", - "GRACEFUL_SHUTDOWN_SECONDS", - ), - ) - WORKER_MAX_CACHED_WORKFLOWS: int = Field( - default=1000, - ge=0, - description="Maximum number of workflow instances cached in worker memory", - deprecated=deprecated_flat_message("TEMPORAL", "WORKER_MAX_CACHED_WORKFLOWS", "WORKER", "MAX_CACHED_WORKFLOWS"), - ) - WORKER_DEBUG_MODE: bool = Field( - default=False, - description="Enable worker debug mode (e.g. breakpoint support in workflow sandbox)", - deprecated=deprecated_flat_message("TEMPORAL", "WORKER_DEBUG_MODE", "WORKER", "DEBUG_MODE"), - ) - WORKER_MAX_CONCURRENT_LOCAL_ACTIVITIES: int | None = Field( - default=None, - ge=1, - description="Maximum concurrent local activities (None uses server default)", - deprecated=deprecated_flat_message( - "TEMPORAL", - "WORKER_MAX_CONCURRENT_LOCAL_ACTIVITIES", - "WORKER", - "MAX_CONCURRENT_LOCAL_ACTIVITIES", - ), - ) - WORKER_DISABLE_EAGER_ACTIVITY_EXECUTION: bool = Field( - default=False, - description="Disable eager activity execution on the worker", - deprecated=deprecated_flat_message( - "TEMPORAL", - "WORKER_DISABLE_EAGER_ACTIVITY_EXECUTION", - "WORKER", - "DISABLE_EAGER_ACTIVITY_EXECUTION", - ), - ) - WORKER_MAX_EAGER_ACTIVITY_RESERVATIONS: int | None = Field( - default=None, - ge=1, - description="Maximum eager activities one workflow task may reserve (None: SDK default of 3)", - deprecated=deprecated_flat_message( - "TEMPORAL", - "WORKER_MAX_EAGER_ACTIVITY_RESERVATIONS", - "WORKER", - "MAX_EAGER_ACTIVITY_RESERVATIONS", - ), - ) - WORKER_POLLER_AUTOSCALING: bool = Field( - default=False, - description=( - "Let the worker scale its workflow and activity task pollers to the backlog " - "(requires Temporal Server 1.28+)" - ), - deprecated=deprecated_flat_message("TEMPORAL", "WORKER_POLLER_AUTOSCALING", "WORKER", "POLLER_AUTOSCALING"), - ) - WORKER_MAX_ACTIVITIES_PER_SECOND: float | None = Field( - default=None, - gt=0, - description="Rate limit for activities this worker starts per second (None: unlimited)", - deprecated=deprecated_flat_message( - "TEMPORAL", - "WORKER_MAX_ACTIVITIES_PER_SECOND", - "WORKER", - "MAX_ACTIVITIES_PER_SECOND", - ), - ) - WORKER_MAX_TASK_QUEUE_ACTIVITIES_PER_SECOND: float | None = Field( - default=None, - gt=0, - description="Server-enforced rate limit for activities across the whole task queue (None: unlimited)", - deprecated=deprecated_flat_message( - "TEMPORAL", - "WORKER_MAX_TASK_QUEUE_ACTIVITIES_PER_SECOND", - "WORKER", - "MAX_TASK_QUEUE_ACTIVITIES_PER_SECOND", - ), - ) - CLIENT_RPC_RETRY_MAX_RETRIES: int = Field( - default=10, - ge=0, - description="Maximum client-side RPC retry attempts", - deprecated=deprecated_flat_message("TEMPORAL", "CLIENT_RPC_RETRY_MAX_RETRIES", "CLIENT_RETRY", "MAX_RETRIES"), - ) - CLIENT_RPC_RETRY_INITIAL_INTERVAL_MS: int = Field( - default=100, - ge=1, - description="Initial backoff interval for client-side RPC retries in milliseconds", - deprecated=deprecated_flat_message( - "TEMPORAL", - "CLIENT_RPC_RETRY_INITIAL_INTERVAL_MS", - "CLIENT_RETRY", - "INITIAL_INTERVAL_MS", - ), - ) - CLIENT_RPC_RETRY_MAX_INTERVAL_MS: int = Field( - default=5000, - ge=1, - description="Maximum backoff interval for client-side RPC retries in milliseconds", - deprecated=deprecated_flat_message( - "TEMPORAL", - "CLIENT_RPC_RETRY_MAX_INTERVAL_MS", - "CLIENT_RETRY", - "MAX_INTERVAL_MS", - ), - ) - KEEP_ALIVE_INTERVAL_MS: int = Field( - default=30000, - ge=1, - description="gRPC keep-alive ping interval in milliseconds", - deprecated=deprecated_flat_message("TEMPORAL", "KEEP_ALIVE_INTERVAL_MS", "KEEP_ALIVE", "INTERVAL_MS"), - ) - KEEP_ALIVE_TIMEOUT_MS: int = Field( - default=15000, - ge=1, - description="gRPC keep-alive timeout in milliseconds", - deprecated=deprecated_flat_message("TEMPORAL", "KEEP_ALIVE_TIMEOUT_MS", "KEEP_ALIVE", "TIMEOUT_MS"), - ) - WORKFLOW_EXECUTION_TIMEOUT: int | None = Field( - default=None, - ge=1, - description="Maximum workflow execution time in seconds, retries included (None: unbounded)", - deprecated=deprecated_flat_message("TEMPORAL", "WORKFLOW_EXECUTION_TIMEOUT", "WORKFLOW", "EXECUTION_TIMEOUT"), - ) - WORKFLOW_RUN_TIMEOUT: int | None = Field( - default=None, - ge=1, - description="Maximum single workflow run time in seconds (None: unbounded)", - deprecated=deprecated_flat_message("TEMPORAL", "WORKFLOW_RUN_TIMEOUT", "WORKFLOW", "RUN_TIMEOUT"), - ) - WORKFLOW_TASK_TIMEOUT: int = Field( - default=30, - ge=1, - description="Maximum workflow task processing time in seconds", - deprecated=deprecated_flat_message("TEMPORAL", "WORKFLOW_TASK_TIMEOUT", "WORKFLOW", "TASK_TIMEOUT"), - ) - WORKFLOW_RETRY_ENABLED: bool = Field( - default=False, - description=( - "Apply the RETRY_* policy to whole workflow executions started by the adapter " - "(a workflow retry reruns the workflow from the start)" - ), - deprecated=deprecated_flat_message("TEMPORAL", "WORKFLOW_RETRY_ENABLED", "WORKFLOW", "RETRY_ENABLED"), - ) - ACTIVITY_START_TO_CLOSE_TIMEOUT: int = Field( - default=30, - ge=1, - description="Maximum activity execution time in seconds", - deprecated=deprecated_flat_message( - "TEMPORAL", - "ACTIVITY_START_TO_CLOSE_TIMEOUT", - "ACTIVITY", - "START_TO_CLOSE_TIMEOUT", - ), - ) - ACTIVITY_HEARTBEAT_TIMEOUT: int | None = Field( - default=None, - ge=1, - description=( - "Activity heartbeat timeout in seconds (None disables it; set only for activities that heartbeat, " - "otherwise they fail with a heartbeat timeout)" - ), - deprecated=deprecated_flat_message("TEMPORAL", "ACTIVITY_HEARTBEAT_TIMEOUT", "ACTIVITY", "HEARTBEAT_TIMEOUT"), - ) - RETRY_MAXIMUM_ATTEMPTS: int = Field( - default=3, - ge=1, - description="Maximum retry attempts for failed activities", - deprecated=deprecated_flat_message("TEMPORAL", "RETRY_MAXIMUM_ATTEMPTS", "RETRY", "MAXIMUM_ATTEMPTS"), - ) - RETRY_BACKOFF_COEFFICIENT: float = Field( - default=2.0, - ge=1.0, - description="Backoff multiplier for retry delays", - deprecated=deprecated_flat_message("TEMPORAL", "RETRY_BACKOFF_COEFFICIENT", "RETRY", "BACKOFF_COEFFICIENT"), - ) - RETRY_MAXIMUM_INTERVAL: int = Field( - default=60, - ge=1, - description="Maximum retry interval in seconds", - deprecated=deprecated_flat_message("TEMPORAL", "RETRY_MAXIMUM_INTERVAL", "RETRY", "MAXIMUM_INTERVAL"), - ) - RETRY_INITIAL_INTERVAL: int = Field( - default=1, - ge=1, - description="Initial retry interval in seconds for workflow and activity retry policies", - deprecated=deprecated_flat_message("TEMPORAL", "RETRY_INITIAL_INTERVAL", "RETRY", "INITIAL_INTERVAL"), - ) - RETRY_NON_RETRYABLE_ERROR_TYPES: list[str] | None = Field( - default=None, - description="Error type names that should not be retried by workflow/activity retry policies", - deprecated=deprecated_flat_message( - "TEMPORAL", - "RETRY_NON_RETRYABLE_ERROR_TYPES", - "RETRY", - "NON_RETRYABLE_ERROR_TYPES", - ), - ) - @model_validator(mode="after") def validate_rpc_metadata(self) -> Self: """Validate RPC metadata keys and values are non-empty strings.""" @@ -613,85 +363,3 @@ def validate_rpc_metadata(self) -> Self: raise InvalidArgumentError() return self - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "TLS", - TemporalTlsConfig, - { - "TLS_ENABLED": "IS_ENABLED", - "TLS_CA_CERT": "CA_CERT", - "TLS_CLIENT_CERT": "CLIENT_CERT", - "TLS_CLIENT_KEY": "CLIENT_KEY", - "TLS_SERVER_NAME": "SERVER_NAME", - "TLS_VERIFICATION_SERVER_NAME": "VERIFICATION_SERVER_NAME", - }, - ) - fold_flat_fields( - self, - "WORKER", - TemporalWorkerConfig, - { - "WORKER_GRACEFUL_SHUTDOWN_SECONDS": "GRACEFUL_SHUTDOWN_SECONDS", - "WORKER_MAX_CACHED_WORKFLOWS": "MAX_CACHED_WORKFLOWS", - "WORKER_DEBUG_MODE": "DEBUG_MODE", - "WORKER_MAX_CONCURRENT_LOCAL_ACTIVITIES": "MAX_CONCURRENT_LOCAL_ACTIVITIES", - "WORKER_DISABLE_EAGER_ACTIVITY_EXECUTION": "DISABLE_EAGER_ACTIVITY_EXECUTION", - "WORKER_MAX_EAGER_ACTIVITY_RESERVATIONS": "MAX_EAGER_ACTIVITY_RESERVATIONS", - "WORKER_POLLER_AUTOSCALING": "POLLER_AUTOSCALING", - "WORKER_MAX_ACTIVITIES_PER_SECOND": "MAX_ACTIVITIES_PER_SECOND", - "WORKER_MAX_TASK_QUEUE_ACTIVITIES_PER_SECOND": "MAX_TASK_QUEUE_ACTIVITIES_PER_SECOND", - }, - ) - fold_flat_fields( - self, - "CLIENT_RETRY", - TemporalClientRetryConfig, - { - "CLIENT_RPC_RETRY_MAX_RETRIES": "MAX_RETRIES", - "CLIENT_RPC_RETRY_INITIAL_INTERVAL_MS": "INITIAL_INTERVAL_MS", - "CLIENT_RPC_RETRY_MAX_INTERVAL_MS": "MAX_INTERVAL_MS", - }, - ) - fold_flat_fields( - self, - "KEEP_ALIVE", - TemporalKeepAliveConfig, - {"KEEP_ALIVE_INTERVAL_MS": "INTERVAL_MS", "KEEP_ALIVE_TIMEOUT_MS": "TIMEOUT_MS"}, - ) - fold_flat_fields( - self, - "WORKFLOW", - TemporalWorkflowConfig, - { - "WORKFLOW_EXECUTION_TIMEOUT": "EXECUTION_TIMEOUT", - "WORKFLOW_RUN_TIMEOUT": "RUN_TIMEOUT", - "WORKFLOW_TASK_TIMEOUT": "TASK_TIMEOUT", - "WORKFLOW_RETRY_ENABLED": "RETRY_ENABLED", - }, - ) - fold_flat_fields( - self, - "ACTIVITY", - TemporalActivityConfig, - { - "ACTIVITY_START_TO_CLOSE_TIMEOUT": "START_TO_CLOSE_TIMEOUT", - "ACTIVITY_HEARTBEAT_TIMEOUT": "HEARTBEAT_TIMEOUT", - }, - ) - fold_flat_fields( - self, - "RETRY", - TemporalRetryConfig, - { - "RETRY_MAXIMUM_ATTEMPTS": "MAXIMUM_ATTEMPTS", - "RETRY_BACKOFF_COEFFICIENT": "BACKOFF_COEFFICIENT", - "RETRY_MAXIMUM_INTERVAL": "MAXIMUM_INTERVAL", - "RETRY_INITIAL_INTERVAL": "INITIAL_INTERVAL", - "RETRY_NON_RETRYABLE_ERROR_TYPES": "NON_RETRYABLE_ERROR_TYPES", - }, - ) - return self diff --git a/archipy/configs/sections/uvicorn.py b/archipy/configs/sections/uvicorn.py index 7624e0675..5a730b45c 100644 --- a/archipy/configs/sections/uvicorn.py +++ b/archipy/configs/sections/uvicorn.py @@ -4,37 +4,16 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields from archipy.models.errors import ConfigurationError -# Uvicorn settings that ``FastAPIConfig`` used to hold; they still work there as a fallback and are deprecated. -UVICORN_FIELDS_ON_FASTAPI = ( - "ACCESS_LOG", - "BACKLOG", - "DATE_HEADER", - "FORWARDED_ALLOW_IPS", - "LIMIT_CONCURRENCY", - "LIMIT_MAX_REQUESTS", - "PROXY_HEADERS", - "RELOAD", - "SERVER_HEADER", - "TIMEOUT_GRACEFUL_SHUTDOWN", - "TIMEOUT_KEEP_ALIVE", - "WORKERS_COUNT", - "WS_MAX_SIZE", - "WS_PER_MESSAGE_DEFLATE", - "WS_PING_INTERVAL", - "WS_PING_TIMEOUT", -) - class UvicornTlsConfig(BaseModel): """TLS settings of the server.""" model_config = ConfigDict(extra="forbid") - KEYFILE: str | None = Field(default=None, description="Path to the PEM TLS private key (with SSL_CERTFILE)") - CERTFILE: str | None = Field(default=None, description="Path to the PEM TLS certificate (with SSL_KEYFILE)") + KEYFILE: str | None = Field(default=None, description="Path to the PEM TLS private key (with CERTFILE)") + CERTFILE: str | None = Field(default=None, description="Path to the PEM TLS certificate (with KEYFILE)") CA_CERTS: str | None = Field( default=None, description="Path to the CA bundle that verifies client certificates", @@ -51,7 +30,7 @@ def validate_tls_pair(self) -> Self: raise ConfigurationError( operation="uvicorn", reason="ssl_keyfile_and_certfile_required_together", - additional_data={"hint": "Set both SSL_KEYFILE and SSL_CERTFILE"}, + additional_data={"hint": "Set both UVICORN.TLS.KEYFILE and UVICORN.TLS.CERTFILE"}, ) return self @@ -77,26 +56,10 @@ class UvicornLimitsConfig(BaseModel): MAX_REQUESTS: int | None = Field(default=None, description="Requests served before the worker restarts") -# Settings of ``UvicornConfig`` that moved into a group: flat name -> (group, field inside the group). -UVICORN_GROUPED_FIELDS = { - "SSL_KEYFILE": ("TLS", "KEYFILE"), - "SSL_CERTFILE": ("TLS", "CERTFILE"), - "SSL_CA_CERTS": ("TLS", "CA_CERTS"), - "WS_MAX_SIZE": ("WEBSOCKET", "MAX_SIZE"), - "WS_PER_MESSAGE_DEFLATE": ("WEBSOCKET", "PER_MESSAGE_DEFLATE"), - "WS_PING_INTERVAL": ("WEBSOCKET", "PING_INTERVAL"), - "WS_PING_TIMEOUT": ("WEBSOCKET", "PING_TIMEOUT"), - "BACKLOG": ("LIMITS", "BACKLOG"), - "LIMIT_CONCURRENCY": ("LIMITS", "CONCURRENCY"), - "LIMIT_MAX_REQUESTS": ("LIMITS", "MAX_REQUESTS"), -} - - class UvicornConfig(BaseModel): """Settings of the Uvicorn server that runs a FastAPI application. - ``AppUtils.uvicorn_config()`` turns them into keyword arguments for ``uvicorn.run`` or ``uvicorn.Config``. The - same names on ``FASTAPI`` are deprecated; they apply when the matching field here is not set. + ``AppUtils.uvicorn_config()`` turns them into keyword arguments for ``uvicorn.run`` or ``uvicorn.Config``. """ ACCESS_LOG: bool = Field(default=True, description="Whether to enable access logging") @@ -118,82 +81,3 @@ class UvicornConfig(BaseModel): default_factory=UvicornLimitsConfig, description="Connection and request limits", ) - - SSL_KEYFILE: str | None = Field( - default=None, - description="Path to the PEM TLS private key (with SSL_CERTFILE)", - deprecated=deprecated_flat_message("UVICORN", "SSL_KEYFILE", "TLS", "KEYFILE"), - ) - SSL_CERTFILE: str | None = Field( - default=None, - description="Path to the PEM TLS certificate (with SSL_KEYFILE)", - deprecated=deprecated_flat_message("UVICORN", "SSL_CERTFILE", "TLS", "CERTFILE"), - ) - SSL_CA_CERTS: str | None = Field( - default=None, - description="Path to the CA bundle that verifies client certificates", - deprecated=deprecated_flat_message("UVICORN", "SSL_CA_CERTS", "TLS", "CA_CERTS"), - ) - WS_MAX_SIZE: int = Field( - default=16777216, - description="Maximum WebSocket message size in bytes", - deprecated=deprecated_flat_message("UVICORN", "WS_MAX_SIZE", "WEBSOCKET", "MAX_SIZE"), - ) - WS_PER_MESSAGE_DEFLATE: bool = Field( - default=True, - description="Whether to enable WebSocket compression", - deprecated=deprecated_flat_message("UVICORN", "WS_PER_MESSAGE_DEFLATE", "WEBSOCKET", "PER_MESSAGE_DEFLATE"), - ) - WS_PING_INTERVAL: float = Field( - default=20.0, - description="WebSocket ping interval in seconds", - deprecated=deprecated_flat_message("UVICORN", "WS_PING_INTERVAL", "WEBSOCKET", "PING_INTERVAL"), - ) - WS_PING_TIMEOUT: float = Field( - default=20.0, - description="WebSocket ping timeout in seconds", - deprecated=deprecated_flat_message("UVICORN", "WS_PING_TIMEOUT", "WEBSOCKET", "PING_TIMEOUT"), - ) - BACKLOG: int = Field( - default=2048, - description="Maximum number of queued connections", - deprecated=deprecated_flat_message("UVICORN", "BACKLOG", "LIMITS", "BACKLOG"), - ) - LIMIT_CONCURRENCY: int | None = Field( - default=None, - description="Maximum concurrent connections or tasks", - deprecated=deprecated_flat_message("UVICORN", "LIMIT_CONCURRENCY", "LIMITS", "CONCURRENCY"), - ) - LIMIT_MAX_REQUESTS: int | None = Field( - default=None, - description="Requests served before the worker restarts", - deprecated=deprecated_flat_message("UVICORN", "LIMIT_MAX_REQUESTS", "LIMITS", "MAX_REQUESTS"), - ) - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "TLS", - UvicornTlsConfig, - {"SSL_KEYFILE": "KEYFILE", "SSL_CERTFILE": "CERTFILE", "SSL_CA_CERTS": "CA_CERTS"}, - ) - fold_flat_fields( - self, - "WEBSOCKET", - UvicornWebSocketConfig, - { - "WS_MAX_SIZE": "MAX_SIZE", - "WS_PER_MESSAGE_DEFLATE": "PER_MESSAGE_DEFLATE", - "WS_PING_INTERVAL": "PING_INTERVAL", - "WS_PING_TIMEOUT": "PING_TIMEOUT", - }, - ) - fold_flat_fields( - self, - "LIMITS", - UvicornLimitsConfig, - {"BACKLOG": "BACKLOG", "LIMIT_CONCURRENCY": "CONCURRENCY", "LIMIT_MAX_REQUESTS": "MAX_REQUESTS"}, - ) - return self diff --git a/archipy/configs/sections/vault.py b/archipy/configs/sections/vault.py index 5e711b2c5..dd3762846 100644 --- a/archipy/configs/sections/vault.py +++ b/archipy/configs/sections/vault.py @@ -1,10 +1,8 @@ """HashiCorp Vault configuration.""" -from typing import Literal, Self +from typing import Literal -from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator - -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields +from pydantic import BaseModel, ConfigDict, Field, SecretStr class VaultAppRoleConfig(BaseModel): @@ -205,8 +203,7 @@ class VaultConfig(BaseModel): Controls connection, authentication, TLS, and secret-retrieval parameters for both the BaseConfig settings source and VaultAdapter. - Auth, TLS, request and token-renewal settings are grouped (for example ``APPROLE``, ``TLS``). The flat names - they replaced (for example ``APPROLE_ROLE_ID``) still work and are deprecated; a value set on a group wins. + Auth, TLS, request and token-renewal settings are grouped, for example under ``APPROLE`` and ``TLS``. """ ENABLED: bool = Field(default=False, description="Whether Vault integration is active") @@ -271,338 +268,3 @@ class VaultConfig(BaseModel): default_factory=VaultTokenRenewalConfig, description="Token renewal settings (adapter only)", ) - - APPROLE_ROLE_ID: str | None = Field( - default=None, - description="AppRole role_id", - deprecated=deprecated_flat_message("VAULT", "APPROLE_ROLE_ID", "APPROLE", "ROLE_ID"), - ) - APPROLE_SECRET_ID: SecretStr | None = Field( - default=None, - description="AppRole secret_id", - deprecated=deprecated_flat_message("VAULT", "APPROLE_SECRET_ID", "APPROLE", "SECRET_ID"), - ) - APPROLE_SECRET_ID_FILE: str | None = Field( - default=None, - description="Path to a file containing the AppRole secret_id; takes precedence over APPROLE_SECRET_ID", - deprecated=deprecated_flat_message("VAULT", "APPROLE_SECRET_ID_FILE", "APPROLE", "SECRET_ID_FILE"), - ) - APPROLE_MOUNT_POINT: str = Field( - default="approle", - description="Mount point of the AppRole auth method", - deprecated=deprecated_flat_message("VAULT", "APPROLE_MOUNT_POINT", "APPROLE", "MOUNT_POINT"), - ) - KUBERNETES_ROLE: str | None = Field( - default=None, - description="Vault role bound to the Kubernetes service account", - deprecated=deprecated_flat_message("VAULT", "KUBERNETES_ROLE", "KUBERNETES", "ROLE"), - ) - KUBERNETES_JWT_PATH: str = Field( - default="/var/run/secrets/kubernetes.io/serviceaccount/token", - description="Path to the service account JWT used for Kubernetes auth", - deprecated=deprecated_flat_message("VAULT", "KUBERNETES_JWT_PATH", "KUBERNETES", "JWT_PATH"), - ) - KUBERNETES_MOUNT_POINT: str = Field( - default="kubernetes", - description="Mount point of the Kubernetes auth method", - deprecated=deprecated_flat_message("VAULT", "KUBERNETES_MOUNT_POINT", "KUBERNETES", "MOUNT_POINT"), - ) - USERPASS_MOUNT_POINT: str = Field( - default="userpass", - description="Mount point of the userpass auth method", - deprecated=deprecated_flat_message("VAULT", "USERPASS_MOUNT_POINT", "USERPASS", "MOUNT_POINT"), - ) - LDAP_MOUNT_POINT: str = Field( - default="ldap", - description="Mount point of the LDAP auth method", - deprecated=deprecated_flat_message("VAULT", "LDAP_MOUNT_POINT", "LDAP", "MOUNT_POINT"), - ) - OKTA_MOUNT_POINT: str = Field( - default="okta", - description="Mount point of the Okta auth method", - deprecated=deprecated_flat_message("VAULT", "OKTA_MOUNT_POINT", "OKTA", "MOUNT_POINT"), - ) - JWT_ROLE: str | None = Field( - default=None, - description="Role name for JWT auth", - deprecated=deprecated_flat_message("VAULT", "JWT_ROLE", "JWT_AUTH", "ROLE"), - ) - JWT: SecretStr | None = Field( - default=None, - description="JWT for JWT auth", - deprecated=deprecated_flat_message("VAULT", "JWT", "JWT_AUTH", "JWT"), - ) - JWT_FILE: str | None = Field( - default=None, - description="Path to a file containing the JWT; takes precedence over JWT", - deprecated=deprecated_flat_message("VAULT", "JWT_FILE", "JWT_AUTH", "JWT_FILE"), - ) - JWT_MOUNT_POINT: str = Field( - default="jwt", - description="Mount path of the JWT auth method", - deprecated=deprecated_flat_message("VAULT", "JWT_MOUNT_POINT", "JWT_AUTH", "MOUNT_POINT"), - ) - AWS_ACCESS_KEY: str | None = Field( - default=None, - description="AWS access key for IAM auth", - deprecated=deprecated_flat_message("VAULT", "AWS_ACCESS_KEY", "AWS", "ACCESS_KEY"), - ) - AWS_SECRET_KEY: SecretStr | None = Field( - default=None, - description="AWS secret key for IAM auth", - deprecated=deprecated_flat_message("VAULT", "AWS_SECRET_KEY", "AWS", "SECRET_KEY"), - ) - AWS_SESSION_TOKEN: SecretStr | None = Field( - default=None, - description="Optional AWS session token for IAM auth", - deprecated=deprecated_flat_message("VAULT", "AWS_SESSION_TOKEN", "AWS", "SESSION_TOKEN"), - ) - AWS_ROLE: str | None = Field( - default=None, - description="Optional Vault role for AWS IAM auth", - deprecated=deprecated_flat_message("VAULT", "AWS_ROLE", "AWS", "ROLE"), - ) - AWS_REGION: str = Field( - default="us-east-1", - description="AWS region used for IAM auth signing", - deprecated=deprecated_flat_message("VAULT", "AWS_REGION", "AWS", "REGION"), - ) - AWS_MOUNT_POINT: str = Field( - default="aws", - description="Mount point of the AWS auth method", - deprecated=deprecated_flat_message("VAULT", "AWS_MOUNT_POINT", "AWS", "MOUNT_POINT"), - ) - AZURE_ROLE: str | None = Field( - default=None, - description="Role name for Azure auth", - deprecated=deprecated_flat_message("VAULT", "AZURE_ROLE", "AZURE", "ROLE"), - ) - AZURE_JWT: SecretStr | None = Field( - default=None, - description="JWT for Azure auth", - deprecated=deprecated_flat_message("VAULT", "AZURE_JWT", "AZURE", "JWT"), - ) - AZURE_JWT_FILE: str | None = Field( - default=None, - description="Path to a file containing the Azure JWT; takes precedence over AZURE_JWT", - deprecated=deprecated_flat_message("VAULT", "AZURE_JWT_FILE", "AZURE", "JWT_FILE"), - ) - AZURE_SUBSCRIPTION_ID: str | None = Field( - default=None, - description="Optional Azure subscription id", - deprecated=deprecated_flat_message("VAULT", "AZURE_SUBSCRIPTION_ID", "AZURE", "SUBSCRIPTION_ID"), - ) - AZURE_RESOURCE_GROUP_NAME: str | None = Field( - default=None, - description="Optional Azure resource group name", - deprecated=deprecated_flat_message("VAULT", "AZURE_RESOURCE_GROUP_NAME", "AZURE", "RESOURCE_GROUP_NAME"), - ) - AZURE_VM_NAME: str | None = Field( - default=None, - description="Optional Azure VM name", - deprecated=deprecated_flat_message("VAULT", "AZURE_VM_NAME", "AZURE", "VM_NAME"), - ) - AZURE_VMSS_NAME: str | None = Field( - default=None, - description="Optional Azure VMSS name", - deprecated=deprecated_flat_message("VAULT", "AZURE_VMSS_NAME", "AZURE", "VMSS_NAME"), - ) - AZURE_MOUNT_POINT: str = Field( - default="azure", - description="Mount point of the Azure auth method", - deprecated=deprecated_flat_message("VAULT", "AZURE_MOUNT_POINT", "AZURE", "MOUNT_POINT"), - ) - GCP_ROLE: str | None = Field( - default=None, - description="Role name for GCP auth", - deprecated=deprecated_flat_message("VAULT", "GCP_ROLE", "GCP", "ROLE"), - ) - GCP_JWT: SecretStr | None = Field( - default=None, - description="JWT for GCP auth", - deprecated=deprecated_flat_message("VAULT", "GCP_JWT", "GCP", "JWT"), - ) - GCP_JWT_FILE: str | None = Field( - default=None, - description="Path to a file containing the GCP JWT; takes precedence over GCP_JWT", - deprecated=deprecated_flat_message("VAULT", "GCP_JWT_FILE", "GCP", "JWT_FILE"), - ) - GCP_MOUNT_POINT: str = Field( - default="gcp", - description="Mount point of the GCP auth method", - deprecated=deprecated_flat_message("VAULT", "GCP_MOUNT_POINT", "GCP", "MOUNT_POINT"), - ) - GITHUB_TOKEN: SecretStr | None = Field( - default=None, - description="GitHub personal access token for GitHub auth", - deprecated=deprecated_flat_message("VAULT", "GITHUB_TOKEN", "GITHUB", "TOKEN"), - ) - GITHUB_TOKEN_FILE: str | None = Field( - default=None, - description="Path to a file containing the GitHub token; takes precedence over GITHUB_TOKEN", - deprecated=deprecated_flat_message("VAULT", "GITHUB_TOKEN_FILE", "GITHUB", "TOKEN_FILE"), - ) - GITHUB_MOUNT_POINT: str = Field( - default="github", - description="Mount point of the GitHub auth method", - deprecated=deprecated_flat_message("VAULT", "GITHUB_MOUNT_POINT", "GITHUB", "MOUNT_POINT"), - ) - CERT_NAME: str = Field( - default="", - description="Optional named cert role for the cert auth method", - deprecated=deprecated_flat_message("VAULT", "CERT_NAME", "CERT", "NAME"), - ) - CERT_MOUNT_POINT: str = Field( - default="cert", - description="Mount point of the cert auth method", - deprecated=deprecated_flat_message("VAULT", "CERT_MOUNT_POINT", "CERT", "MOUNT_POINT"), - ) - VERIFY_SSL: bool = Field( - default=True, - description="Verify the Vault server's TLS certificate", - deprecated=deprecated_flat_message("VAULT", "VERIFY_SSL", "TLS", "VERIFY_SSL"), - ) - CA_CERT_PATH: str | None = Field( - default=None, - description="Path to a CA bundle for verifying Vault's TLS certificate", - deprecated=deprecated_flat_message("VAULT", "CA_CERT_PATH", "TLS", "CA_CERT_PATH"), - ) - CLIENT_CERT_PATH: str | None = Field( - default=None, - description="Path to a client certificate for mutual TLS", - deprecated=deprecated_flat_message("VAULT", "CLIENT_CERT_PATH", "TLS", "CLIENT_CERT_PATH"), - ) - CLIENT_KEY_PATH: str | None = Field( - default=None, - description="Path to the client private key for mutual TLS", - deprecated=deprecated_flat_message("VAULT", "CLIENT_KEY_PATH", "TLS", "CLIENT_KEY_PATH"), - ) - CONNECT_TIMEOUT: float = Field( - default=5.0, - description="Connection timeout in seconds", - deprecated=deprecated_flat_message("VAULT", "CONNECT_TIMEOUT", "HTTP", "CONNECT_TIMEOUT"), - ) - READ_TIMEOUT: float = Field( - default=10.0, - description="Read timeout in seconds", - deprecated=deprecated_flat_message("VAULT", "READ_TIMEOUT", "HTTP", "READ_TIMEOUT"), - ) - RETRIES_MAX_ATTEMPTS: int = Field( - default=3, - description="Maximum retry attempts for failed requests", - deprecated=deprecated_flat_message("VAULT", "RETRIES_MAX_ATTEMPTS", "HTTP", "RETRIES_MAX_ATTEMPTS"), - ) - AUTO_RENEW_TOKEN: bool = Field( - default=False, - description="Automatically renew the token before it expires", - deprecated=deprecated_flat_message("VAULT", "AUTO_RENEW_TOKEN", "TOKEN_RENEWAL", "AUTO_RENEW_TOKEN"), - ) - RENEW_THRESHOLD_SECONDS: int = Field( - default=60, - description="Renew the token once its remaining TTL drops below this many seconds", - deprecated=deprecated_flat_message( - "VAULT", - "RENEW_THRESHOLD_SECONDS", - "TOKEN_RENEWAL", - "RENEW_THRESHOLD_SECONDS", - ), - ) - - @model_validator(mode="after") - def fold_deprecated_flat_fields(self) -> Self: - """Copy deprecated flat settings into their groups.""" - fold_flat_fields( - self, - "APPROLE", - VaultAppRoleConfig, - { - "APPROLE_ROLE_ID": "ROLE_ID", - "APPROLE_SECRET_ID": "SECRET_ID", - "APPROLE_SECRET_ID_FILE": "SECRET_ID_FILE", - "APPROLE_MOUNT_POINT": "MOUNT_POINT", - }, - ) - fold_flat_fields( - self, - "KUBERNETES", - VaultKubernetesConfig, - {"KUBERNETES_ROLE": "ROLE", "KUBERNETES_JWT_PATH": "JWT_PATH", "KUBERNETES_MOUNT_POINT": "MOUNT_POINT"}, - ) - fold_flat_fields(self, "USERPASS", VaultUserpassConfig, {"USERPASS_MOUNT_POINT": "MOUNT_POINT"}) - fold_flat_fields(self, "LDAP", VaultLdapConfig, {"LDAP_MOUNT_POINT": "MOUNT_POINT"}) - fold_flat_fields(self, "OKTA", VaultOktaConfig, {"OKTA_MOUNT_POINT": "MOUNT_POINT"}) - fold_flat_fields( - self, - "JWT_AUTH", - VaultJwtConfig, - {"JWT_ROLE": "ROLE", "JWT": "JWT", "JWT_FILE": "JWT_FILE", "JWT_MOUNT_POINT": "MOUNT_POINT"}, - ) - fold_flat_fields( - self, - "AWS", - VaultAwsConfig, - { - "AWS_ACCESS_KEY": "ACCESS_KEY", - "AWS_SECRET_KEY": "SECRET_KEY", - "AWS_SESSION_TOKEN": "SESSION_TOKEN", - "AWS_ROLE": "ROLE", - "AWS_REGION": "REGION", - "AWS_MOUNT_POINT": "MOUNT_POINT", - }, - ) - fold_flat_fields( - self, - "AZURE", - VaultAzureConfig, - { - "AZURE_ROLE": "ROLE", - "AZURE_JWT": "JWT", - "AZURE_JWT_FILE": "JWT_FILE", - "AZURE_SUBSCRIPTION_ID": "SUBSCRIPTION_ID", - "AZURE_RESOURCE_GROUP_NAME": "RESOURCE_GROUP_NAME", - "AZURE_VM_NAME": "VM_NAME", - "AZURE_VMSS_NAME": "VMSS_NAME", - "AZURE_MOUNT_POINT": "MOUNT_POINT", - }, - ) - fold_flat_fields( - self, - "GCP", - VaultGcpConfig, - {"GCP_ROLE": "ROLE", "GCP_JWT": "JWT", "GCP_JWT_FILE": "JWT_FILE", "GCP_MOUNT_POINT": "MOUNT_POINT"}, - ) - fold_flat_fields( - self, - "GITHUB", - VaultGithubConfig, - {"GITHUB_TOKEN": "TOKEN", "GITHUB_TOKEN_FILE": "TOKEN_FILE", "GITHUB_MOUNT_POINT": "MOUNT_POINT"}, - ) - fold_flat_fields(self, "CERT", VaultCertConfig, {"CERT_NAME": "NAME", "CERT_MOUNT_POINT": "MOUNT_POINT"}) - fold_flat_fields( - self, - "TLS", - VaultTlsConfig, - { - "VERIFY_SSL": "VERIFY_SSL", - "CA_CERT_PATH": "CA_CERT_PATH", - "CLIENT_CERT_PATH": "CLIENT_CERT_PATH", - "CLIENT_KEY_PATH": "CLIENT_KEY_PATH", - }, - ) - fold_flat_fields( - self, - "HTTP", - VaultHttpConfig, - { - "CONNECT_TIMEOUT": "CONNECT_TIMEOUT", - "READ_TIMEOUT": "READ_TIMEOUT", - "RETRIES_MAX_ATTEMPTS": "RETRIES_MAX_ATTEMPTS", - }, - ) - fold_flat_fields( - self, - "TOKEN_RENEWAL", - VaultTokenRenewalConfig, - {"AUTO_RENEW_TOKEN": "AUTO_RENEW_TOKEN", "RENEW_THRESHOLD_SECONDS": "RENEW_THRESHOLD_SECONDS"}, - ) - return self diff --git a/archipy/configs/vault_settings_source.py b/archipy/configs/vault_settings_source.py index 84bf769ae..78416d36f 100644 --- a/archipy/configs/vault_settings_source.py +++ b/archipy/configs/vault_settings_source.py @@ -227,7 +227,7 @@ def create_vault_client(config: VaultConfig) -> hvac.Client: elif config.TLS.CLIENT_CERT_PATH or config.TLS.CLIENT_KEY_PATH: raise ConfigurationError( operation="vault_tls", - reason="Both CLIENT_CERT_PATH and CLIENT_KEY_PATH must be set for mutual TLS", + reason="Both TLS.CLIENT_CERT_PATH and TLS.CLIENT_KEY_PATH must be set for mutual TLS", ) # hvac copies ``session.verify`` (requests default: True) and ``session.cert`` @@ -287,13 +287,13 @@ def _authenticate_approle(client: hvac.Client, config: VaultConfig) -> None: if not config.APPROLE.ROLE_ID: raise ConfigurationError( operation="vault_auth", - reason="APPROLE_ROLE_ID is required for approle auth", + reason="APPROLE.ROLE_ID is required for approle auth", ) secret_id = _resolve_approle_secret_id(config) if not secret_id: raise ConfigurationError( operation="vault_auth", - reason="APPROLE_SECRET_ID or APPROLE_SECRET_ID_FILE is required for approle auth", + reason="APPROLE.SECRET_ID or APPROLE.SECRET_ID_FILE is required for approle auth", ) response = client.auth.approle.login( role_id=config.APPROLE.ROLE_ID, @@ -308,7 +308,7 @@ def _authenticate_kubernetes(client: hvac.Client, config: VaultConfig) -> None: if not config.KUBERNETES.ROLE: raise ConfigurationError( operation="vault_auth", - reason="KUBERNETES_ROLE is required for kubernetes auth", + reason="KUBERNETES.ROLE is required for kubernetes auth", ) jwt = _read_file_secret(config.KUBERNETES.JWT_PATH) response = client.auth.kubernetes.login( @@ -356,12 +356,12 @@ def _authenticate_username_password(client: hvac.Client, config: VaultConfig) -> def _authenticate_jwt(client: hvac.Client, config: VaultConfig) -> None: """Authenticate with the JWT auth method.""" if not config.JWT_AUTH.ROLE: - raise ConfigurationError(operation="vault_auth", reason="JWT_ROLE is required for jwt auth") + raise ConfigurationError(operation="vault_auth", reason="JWT_AUTH.ROLE is required for jwt auth") jwt = _resolve_optional_file_or_value(config.JWT_AUTH.JWT_FILE, config.JWT_AUTH.JWT) if not jwt: raise ConfigurationError( operation="vault_auth", - reason="JWT or JWT_FILE is required for jwt auth", + reason="JWT_AUTH.JWT or JWT_AUTH.JWT_FILE is required for jwt auth", ) response = client.auth.jwt.jwt_login( role=config.JWT_AUTH.ROLE, @@ -376,7 +376,7 @@ def _authenticate_aws(client: hvac.Client, config: VaultConfig) -> None: if not config.AWS.ACCESS_KEY or not config.AWS.SECRET_KEY: raise ConfigurationError( operation="vault_auth", - reason="AWS_ACCESS_KEY and AWS_SECRET_KEY are required for aws auth", + reason="AWS.ACCESS_KEY and AWS.SECRET_KEY are required for aws auth", ) response = client.auth.aws.iam_login( access_key=config.AWS.ACCESS_KEY, @@ -392,12 +392,12 @@ def _authenticate_aws(client: hvac.Client, config: VaultConfig) -> None: def _authenticate_azure(client: hvac.Client, config: VaultConfig) -> None: """Authenticate with Azure.""" if not config.AZURE.ROLE: - raise ConfigurationError(operation="vault_auth", reason="AZURE_ROLE is required for azure auth") + raise ConfigurationError(operation="vault_auth", reason="AZURE.ROLE is required for azure auth") jwt = _resolve_optional_file_or_value(config.AZURE.JWT_FILE, config.AZURE.JWT) if not jwt: raise ConfigurationError( operation="vault_auth", - reason="AZURE_JWT or AZURE_JWT_FILE is required for azure auth", + reason="AZURE.JWT or AZURE.JWT_FILE is required for azure auth", ) response = client.auth.azure.login( role=config.AZURE.ROLE, @@ -414,12 +414,12 @@ def _authenticate_azure(client: hvac.Client, config: VaultConfig) -> None: def _authenticate_gcp(client: hvac.Client, config: VaultConfig) -> None: """Authenticate with GCP.""" if not config.GCP.ROLE: - raise ConfigurationError(operation="vault_auth", reason="GCP_ROLE is required for gcp auth") + raise ConfigurationError(operation="vault_auth", reason="GCP.ROLE is required for gcp auth") jwt = _resolve_optional_file_or_value(config.GCP.JWT_FILE, config.GCP.JWT) if not jwt: raise ConfigurationError( operation="vault_auth", - reason="GCP_JWT or GCP_JWT_FILE is required for gcp auth", + reason="GCP.JWT or GCP.JWT_FILE is required for gcp auth", ) response = client.auth.gcp.login( role=config.GCP.ROLE, @@ -435,7 +435,7 @@ def _authenticate_github(client: hvac.Client, config: VaultConfig) -> None: if not token: raise ConfigurationError( operation="vault_auth", - reason="GITHUB_TOKEN or GITHUB_TOKEN_FILE is required for github auth", + reason="GITHUB.TOKEN or GITHUB.TOKEN_FILE is required for github auth", ) response = client.auth.github.login(token=token, mount_point=config.GITHUB.MOUNT_POINT) _set_client_token_from_auth_response(client, response) @@ -556,7 +556,7 @@ def _env_mount(name: str, default: str) -> str: def _parse_verify_ssl(raw: str | None) -> bool: - """Parse ``VAULT__VERIFY_SSL``; unknown spellings fail closed instead of disabling TLS checks.""" + """Parse ``VAULT__TLS__VERIFY_SSL``; unknown spellings fail closed instead of disabling TLS checks.""" if raw is None or raw.strip() == "": return True value = raw.strip().lower() @@ -566,19 +566,10 @@ def _parse_verify_ssl(raw: str | None) -> bool: return False raise ConfigurationError( operation="vault_config", - reason="Invalid VAULT__VERIFY_SSL: use one of 1/true/yes/on or 0/false/no/off", + reason="Invalid VAULT__TLS__VERIFY_SSL: use one of 1/true/yes/on or 0/false/no/off", ) -def _env_name(group: str, field: str, flat: str) -> str: - """Return the env var that holds a grouped Vault setting. - - ``VAULT____`` wins; the deprecated flat ``VAULT__`` is the fallback. - """ - nested = f"VAULT__{group}__{field}" - return nested if nested in os.environ else f"VAULT__{flat}" - - def _vault_config_from_env() -> VaultConfig: """Build a ``VaultConfig`` from raw ``VAULT__*`` environment variables. @@ -606,80 +597,80 @@ def _vault_config_from_env() -> VaultConfig: SECRET_PATHS=_parse_secret_paths(os.environ.get("VAULT__SECRET_PATHS")), SECRET_CACHE_TTL=_env_int("VAULT__SECRET_CACHE_TTL", 0), APPROLE=VaultAppRoleConfig( - ROLE_ID=_env_opt(_env_name("APPROLE", "ROLE_ID", "APPROLE_ROLE_ID")), - SECRET_ID=_env_opt(_env_name("APPROLE", "SECRET_ID", "APPROLE_SECRET_ID")), - SECRET_ID_FILE=_env_opt(_env_name("APPROLE", "SECRET_ID_FILE", "APPROLE_SECRET_ID_FILE")), - MOUNT_POINT=_env_mount(_env_name("APPROLE", "MOUNT_POINT", "APPROLE_MOUNT_POINT"), "approle"), + ROLE_ID=_env_opt("VAULT__APPROLE__ROLE_ID"), + SECRET_ID=_env_opt("VAULT__APPROLE__SECRET_ID"), + SECRET_ID_FILE=_env_opt("VAULT__APPROLE__SECRET_ID_FILE"), + MOUNT_POINT=_env_mount("VAULT__APPROLE__MOUNT_POINT", "approle"), ), KUBERNETES=VaultKubernetesConfig( - ROLE=_env_opt(_env_name("KUBERNETES", "ROLE", "KUBERNETES_ROLE")), - JWT_PATH=os.environ.get(_env_name("KUBERNETES", "JWT_PATH", "KUBERNETES_JWT_PATH")) + ROLE=_env_opt("VAULT__KUBERNETES__ROLE"), + JWT_PATH=os.environ.get("VAULT__KUBERNETES__JWT_PATH") or "/var/run/secrets/kubernetes.io/serviceaccount/token", - MOUNT_POINT=_env_mount(_env_name("KUBERNETES", "MOUNT_POINT", "KUBERNETES_MOUNT_POINT"), "kubernetes"), + MOUNT_POINT=_env_mount("VAULT__KUBERNETES__MOUNT_POINT", "kubernetes"), ), USERPASS=VaultUserpassConfig( - MOUNT_POINT=_env_mount(_env_name("USERPASS", "MOUNT_POINT", "USERPASS_MOUNT_POINT"), "userpass"), + MOUNT_POINT=_env_mount("VAULT__USERPASS__MOUNT_POINT", "userpass"), ), LDAP=VaultLdapConfig( - MOUNT_POINT=_env_mount(_env_name("LDAP", "MOUNT_POINT", "LDAP_MOUNT_POINT"), "ldap"), + MOUNT_POINT=_env_mount("VAULT__LDAP__MOUNT_POINT", "ldap"), ), OKTA=VaultOktaConfig( - MOUNT_POINT=_env_mount(_env_name("OKTA", "MOUNT_POINT", "OKTA_MOUNT_POINT"), "okta"), + MOUNT_POINT=_env_mount("VAULT__OKTA__MOUNT_POINT", "okta"), ), JWT_AUTH=VaultJwtConfig( - ROLE=_env_opt(_env_name("JWT_AUTH", "ROLE", "JWT_ROLE")), - JWT=_env_opt(_env_name("JWT_AUTH", "JWT", "JWT")), - JWT_FILE=_env_opt(_env_name("JWT_AUTH", "JWT_FILE", "JWT_FILE")), - MOUNT_POINT=_env_mount(_env_name("JWT_AUTH", "MOUNT_POINT", "JWT_MOUNT_POINT"), "jwt"), + ROLE=_env_opt("VAULT__JWT_AUTH__ROLE"), + JWT=_env_opt("VAULT__JWT_AUTH__JWT"), + JWT_FILE=_env_opt("VAULT__JWT_AUTH__JWT_FILE"), + MOUNT_POINT=_env_mount("VAULT__JWT_AUTH__MOUNT_POINT", "jwt"), ), AWS=VaultAwsConfig( - ACCESS_KEY=_env_opt(_env_name("AWS", "ACCESS_KEY", "AWS_ACCESS_KEY")), - SECRET_KEY=_env_opt(_env_name("AWS", "SECRET_KEY", "AWS_SECRET_KEY")), - SESSION_TOKEN=_env_opt(_env_name("AWS", "SESSION_TOKEN", "AWS_SESSION_TOKEN")), - ROLE=_env_opt(_env_name("AWS", "ROLE", "AWS_ROLE")), - REGION=_env_mount(_env_name("AWS", "REGION", "AWS_REGION"), "us-east-1"), - MOUNT_POINT=_env_mount(_env_name("AWS", "MOUNT_POINT", "AWS_MOUNT_POINT"), "aws"), + ACCESS_KEY=_env_opt("VAULT__AWS__ACCESS_KEY"), + SECRET_KEY=_env_opt("VAULT__AWS__SECRET_KEY"), + SESSION_TOKEN=_env_opt("VAULT__AWS__SESSION_TOKEN"), + ROLE=_env_opt("VAULT__AWS__ROLE"), + REGION=_env_mount("VAULT__AWS__REGION", "us-east-1"), + MOUNT_POINT=_env_mount("VAULT__AWS__MOUNT_POINT", "aws"), ), AZURE=VaultAzureConfig( - ROLE=_env_opt(_env_name("AZURE", "ROLE", "AZURE_ROLE")), - JWT=_env_opt(_env_name("AZURE", "JWT", "AZURE_JWT")), - JWT_FILE=_env_opt(_env_name("AZURE", "JWT_FILE", "AZURE_JWT_FILE")), - SUBSCRIPTION_ID=_env_opt(_env_name("AZURE", "SUBSCRIPTION_ID", "AZURE_SUBSCRIPTION_ID")), - RESOURCE_GROUP_NAME=_env_opt(_env_name("AZURE", "RESOURCE_GROUP_NAME", "AZURE_RESOURCE_GROUP_NAME")), - VM_NAME=_env_opt(_env_name("AZURE", "VM_NAME", "AZURE_VM_NAME")), - VMSS_NAME=_env_opt(_env_name("AZURE", "VMSS_NAME", "AZURE_VMSS_NAME")), - MOUNT_POINT=_env_mount(_env_name("AZURE", "MOUNT_POINT", "AZURE_MOUNT_POINT"), "azure"), + ROLE=_env_opt("VAULT__AZURE__ROLE"), + JWT=_env_opt("VAULT__AZURE__JWT"), + JWT_FILE=_env_opt("VAULT__AZURE__JWT_FILE"), + SUBSCRIPTION_ID=_env_opt("VAULT__AZURE__SUBSCRIPTION_ID"), + RESOURCE_GROUP_NAME=_env_opt("VAULT__AZURE__RESOURCE_GROUP_NAME"), + VM_NAME=_env_opt("VAULT__AZURE__VM_NAME"), + VMSS_NAME=_env_opt("VAULT__AZURE__VMSS_NAME"), + MOUNT_POINT=_env_mount("VAULT__AZURE__MOUNT_POINT", "azure"), ), GCP=VaultGcpConfig( - ROLE=_env_opt(_env_name("GCP", "ROLE", "GCP_ROLE")), - JWT=_env_opt(_env_name("GCP", "JWT", "GCP_JWT")), - JWT_FILE=_env_opt(_env_name("GCP", "JWT_FILE", "GCP_JWT_FILE")), - MOUNT_POINT=_env_mount(_env_name("GCP", "MOUNT_POINT", "GCP_MOUNT_POINT"), "gcp"), + ROLE=_env_opt("VAULT__GCP__ROLE"), + JWT=_env_opt("VAULT__GCP__JWT"), + JWT_FILE=_env_opt("VAULT__GCP__JWT_FILE"), + MOUNT_POINT=_env_mount("VAULT__GCP__MOUNT_POINT", "gcp"), ), GITHUB=VaultGithubConfig( - TOKEN=_env_opt(_env_name("GITHUB", "TOKEN", "GITHUB_TOKEN")), - TOKEN_FILE=_env_opt(_env_name("GITHUB", "TOKEN_FILE", "GITHUB_TOKEN_FILE")), - MOUNT_POINT=_env_mount(_env_name("GITHUB", "MOUNT_POINT", "GITHUB_MOUNT_POINT"), "github"), + TOKEN=_env_opt("VAULT__GITHUB__TOKEN"), + TOKEN_FILE=_env_opt("VAULT__GITHUB__TOKEN_FILE"), + MOUNT_POINT=_env_mount("VAULT__GITHUB__MOUNT_POINT", "github"), ), CERT=VaultCertConfig( - NAME=os.environ.get(_env_name("CERT", "NAME", "CERT_NAME"), "") or "", - MOUNT_POINT=_env_mount(_env_name("CERT", "MOUNT_POINT", "CERT_MOUNT_POINT"), "cert"), + NAME=os.environ.get("VAULT__CERT__NAME", "") or "", + MOUNT_POINT=_env_mount("VAULT__CERT__MOUNT_POINT", "cert"), ), TLS=VaultTlsConfig( - VERIFY_SSL=_parse_verify_ssl(os.environ.get(_env_name("TLS", "VERIFY_SSL", "VERIFY_SSL"))), - CA_CERT_PATH=_env_opt(_env_name("TLS", "CA_CERT_PATH", "CA_CERT_PATH")), - CLIENT_CERT_PATH=_env_opt(_env_name("TLS", "CLIENT_CERT_PATH", "CLIENT_CERT_PATH")), - CLIENT_KEY_PATH=_env_opt(_env_name("TLS", "CLIENT_KEY_PATH", "CLIENT_KEY_PATH")), + VERIFY_SSL=_parse_verify_ssl(os.environ.get("VAULT__TLS__VERIFY_SSL")), + CA_CERT_PATH=_env_opt("VAULT__TLS__CA_CERT_PATH"), + CLIENT_CERT_PATH=_env_opt("VAULT__TLS__CLIENT_CERT_PATH"), + CLIENT_KEY_PATH=_env_opt("VAULT__TLS__CLIENT_KEY_PATH"), ), HTTP=VaultHttpConfig( - CONNECT_TIMEOUT=_env_float(_env_name("HTTP", "CONNECT_TIMEOUT", "CONNECT_TIMEOUT"), 5.0), - READ_TIMEOUT=_env_float(_env_name("HTTP", "READ_TIMEOUT", "READ_TIMEOUT"), 10.0), - RETRIES_MAX_ATTEMPTS=_env_int(_env_name("HTTP", "RETRIES_MAX_ATTEMPTS", "RETRIES_MAX_ATTEMPTS"), 3), + CONNECT_TIMEOUT=_env_float("VAULT__HTTP__CONNECT_TIMEOUT", 5.0), + READ_TIMEOUT=_env_float("VAULT__HTTP__READ_TIMEOUT", 10.0), + RETRIES_MAX_ATTEMPTS=_env_int("VAULT__HTTP__RETRIES_MAX_ATTEMPTS", 3), ), TOKEN_RENEWAL=VaultTokenRenewalConfig( - AUTO_RENEW_TOKEN=_env_truthy(_env_name("TOKEN_RENEWAL", "AUTO_RENEW_TOKEN", "AUTO_RENEW_TOKEN")), + AUTO_RENEW_TOKEN=_env_truthy("VAULT__TOKEN_RENEWAL__AUTO_RENEW_TOKEN"), RENEW_THRESHOLD_SECONDS=_env_int( - _env_name("TOKEN_RENEWAL", "RENEW_THRESHOLD_SECONDS", "RENEW_THRESHOLD_SECONDS"), + "VAULT__TOKEN_RENEWAL__RENEW_THRESHOLD_SECONDS", 60, ), ), diff --git a/archipy/helpers/_deprecation.py b/archipy/helpers/_deprecation.py deleted file mode 100644 index f49cc0871..000000000 --- a/archipy/helpers/_deprecation.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Helpers for keeping deprecated names working while warning callers.""" - -from __future__ import annotations - -import warnings -from functools import wraps -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from collections.abc import Callable - - -REMOVAL_VERSION = "6.0.0" -"""The release that drops every name deprecated through this module.""" - - -def warn_deprecated_name(old_name: str, new_name: str, *, stacklevel: int = 3) -> None: - """Emit a ``DeprecationWarning`` that points at the caller of the deprecated name. - - Args: - old_name: The deprecated name. - new_name: The replacement name. - stacklevel: Frames to skip. The default targets the caller of the function that called this helper. - """ - warnings.warn( - f"{old_name} is deprecated and will be removed in {REMOVAL_VERSION}; use {new_name} instead.", - DeprecationWarning, - stacklevel=stacklevel, - ) - - -def deprecated_alias[**P, R](old_name: str, replacement: Callable[P, R]) -> Callable[P, R]: - """Return a callable that behaves like ``replacement`` but warns that ``old_name`` is deprecated. - - The warning is raised when the alias is called (for decorator factories that is when the - decorator is applied), and points at the calling code. - - Args: - old_name: The deprecated public name. - replacement: The function that supersedes it. - - Returns: - A wrapper with the signature and docstring of ``replacement`` and the name ``old_name``. - """ - new_name = getattr(replacement, "__name__", "the replacement") - - @wraps(replacement) - def alias(*args: P.args, **kwargs: P.kwargs) -> R: - warn_deprecated_name(old_name, new_name) - return replacement(*args, **kwargs) - - alias.__name__ = old_name - alias.__qualname__ = old_name - return alias diff --git a/archipy/helpers/decorators/__init__.py b/archipy/helpers/decorators/__init__.py index e522972bd..1dd74a7d2 100644 --- a/archipy/helpers/decorators/__init__.py +++ b/archipy/helpers/decorators/__init__.py @@ -1,137 +1,30 @@ """Reusable decorator helpers for ArchiPy.""" -from typing import TYPE_CHECKING - -from archipy.models.errors import ConfigurationError, InvalidArgumentError - -# Old module paths stay importable as thin shims; they must load before the decorator names are bound below. -from . import ( - _legacy_modules, # noqa: F401 - sqlalchemy_transaction as _sqlalchemy_transaction, -) from .deprecation_exception import class_deprecation_error, method_deprecation_error from .deprecation_warnings import class_deprecation_warning, method_deprecation_warning -from .grpc_rate_limit_window import grpc_rate_limit, grpc_rate_limit_decorator -from .metrics import async_count_calls, async_measure_duration, count_calls, measure_duration -from .retry_policy import retry, retry_decorator -from .singleton_class import singleton, singleton_decorator -from .timeout_limit import timeout, timeout_decorator -from .timing_log import timing, timing_decorator -from .tracing import async_trace_root, async_trace_span, trace_class, trace_root, trace_span -from .ttl_caching import ttl_cache, ttl_cache_decorator - -# ``sqlalchemy_atomic`` is both a decorator name and the old shim module name; resolve it lazily instead -globals().pop("sqlalchemy_atomic", None) - - -# SQLAlchemy decorators moved to archipy.adapters.base.sqlalchemy.atomic; they are resolved lazily from there to avoid -# requiring SQLAlchemy when using archipy without the sqlalchemy extra (e.g., archipy[scylladb]) -# Type stubs for IDE support - these are only used for static type checking -# The actual implementations are provided via __getattr__ at runtime -if TYPE_CHECKING: - from archipy.adapters.base.sqlalchemy.atomic import ( - async_mysql_sqlalchemy_atomic_decorator, - async_postgres_sqlalchemy_atomic_decorator, - async_sqlite_sqlalchemy_atomic_decorator, - async_starrocks_sqlalchemy_atomic_decorator, - mysql_sqlalchemy_atomic, - mysql_sqlalchemy_atomic_decorator, - postgres_sqlalchemy_atomic, - postgres_sqlalchemy_atomic_decorator, - sqlalchemy_atomic, - sqlalchemy_atomic_decorator, - sqlite_sqlalchemy_atomic, - sqlite_sqlalchemy_atomic_decorator, - starrocks_sqlalchemy_atomic, - starrocks_sqlalchemy_atomic_decorator, - ) - -_SQLALCHEMY_DECORATOR_NAMES = frozenset( - { - "async_mysql_sqlalchemy_atomic_decorator", - "async_postgres_sqlalchemy_atomic_decorator", - "async_sqlite_sqlalchemy_atomic_decorator", - "async_starrocks_sqlalchemy_atomic_decorator", - "mysql_sqlalchemy_atomic", - "mysql_sqlalchemy_atomic_decorator", - "postgres_sqlalchemy_atomic", - "postgres_sqlalchemy_atomic_decorator", - "sqlalchemy_atomic", - "sqlalchemy_atomic_decorator", - "sqlite_sqlalchemy_atomic", - "sqlite_sqlalchemy_atomic_decorator", - "starrocks_sqlalchemy_atomic", - "starrocks_sqlalchemy_atomic_decorator", - }, -) - - -def __getattr__(name: str) -> object: - """Lazy import for the deprecated SQLAlchemy decorator names. - - This function is called when an attribute is not found in the module. - It defers importing the SQLAlchemy decorators until they're accessed, - preventing SQLAlchemy from being required when using archipy without the - sqlalchemy extra. Names that moved to ``archipy.adapters.base.sqlalchemy.atomic`` - emit a ``DeprecationWarning``. - - Args: - name: The name of the attribute to import. - - Returns: - The requested decorator. - - Raises: - ConfigurationError: If SQLAlchemy is not installed and a SQLAlchemy decorator is requested. - InvalidArgumentError: If the requested attribute is not a SQLAlchemy decorator. - """ - if name not in _SQLALCHEMY_DECORATOR_NAMES: - raise InvalidArgumentError(argument_name=name, additional_data={"module": __name__}) - - try: - return _sqlalchemy_transaction.resolve(name) - except ImportError as e: - raise ConfigurationError(operation="import", reason="sqlalchemy_extra_required") from e - +from .grpc_rate_limit_window import grpc_rate_limit +from .metrics import count_calls, measure_duration +from .retry_policy import retry +from .singleton_class import singleton +from .timeout_limit import timeout +from .timing_log import timing +from .tracing import trace_class, trace_root, trace_span +from .ttl_caching import ttl_cache __all__ = [ - "async_count_calls", - "async_measure_duration", - "async_mysql_sqlalchemy_atomic_decorator", - "async_postgres_sqlalchemy_atomic_decorator", - "async_sqlite_sqlalchemy_atomic_decorator", - "async_starrocks_sqlalchemy_atomic_decorator", - "async_trace_root", - "async_trace_span", "class_deprecation_error", "class_deprecation_warning", "count_calls", "grpc_rate_limit", - "grpc_rate_limit_decorator", "measure_duration", "method_deprecation_error", "method_deprecation_warning", - "mysql_sqlalchemy_atomic", - "mysql_sqlalchemy_atomic_decorator", - "postgres_sqlalchemy_atomic", - "postgres_sqlalchemy_atomic_decorator", "retry", - "retry_decorator", "singleton", - "singleton_decorator", - "sqlalchemy_atomic", - "sqlalchemy_atomic_decorator", - "sqlite_sqlalchemy_atomic", - "sqlite_sqlalchemy_atomic_decorator", - "starrocks_sqlalchemy_atomic", - "starrocks_sqlalchemy_atomic_decorator", "timeout", - "timeout_decorator", "timing", - "timing_decorator", "trace_class", "trace_root", "trace_span", "ttl_cache", - "ttl_cache_decorator", ] diff --git a/archipy/helpers/decorators/_legacy_modules.py b/archipy/helpers/decorators/_legacy_modules.py deleted file mode 100644 index 71cb514be..000000000 --- a/archipy/helpers/decorators/_legacy_modules.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Import the deprecated module paths (``decorators.retry`` and friends) before any public name is bound. - -Importing a submodule sets an attribute with its name on the package. The suffix-less decorators -(``retry``, ``timeout``, ...) share those names, so the shims must be loaded first and the -decorators bound afterwards for the decorators to win. -""" - -import importlib - -for _shim in ("cache", "grpc_rate_limit", "retry", "singleton", "sqlalchemy_atomic", "timeout", "timing"): - importlib.import_module(f"archipy.helpers.decorators.{_shim}") diff --git a/archipy/helpers/decorators/cache.py b/archipy/helpers/decorators/cache.py deleted file mode 100644 index 9e612f63a..000000000 --- a/archipy/helpers/decorators/cache.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Deprecated import path; use ``archipy.helpers.decorators`` and ``ttl_cache`` instead.""" - -from .ttl_caching import CachedFunction, ttl_cache_decorator - -__all__ = ["CachedFunction", "ttl_cache_decorator"] diff --git a/archipy/helpers/decorators/grpc_rate_limit.py b/archipy/helpers/decorators/grpc_rate_limit.py deleted file mode 100644 index 02f1ae5cf..000000000 --- a/archipy/helpers/decorators/grpc_rate_limit.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Deprecated import path; use ``archipy.helpers.decorators`` and the suffix-less decorator names instead.""" - -from .grpc_rate_limit_window import grpc_rate_limit_decorator - -__all__ = ["grpc_rate_limit_decorator"] diff --git a/archipy/helpers/decorators/grpc_rate_limit_window.py b/archipy/helpers/decorators/grpc_rate_limit_window.py index f766d7420..69b4783e9 100644 --- a/archipy/helpers/decorators/grpc_rate_limit_window.py +++ b/archipy/helpers/decorators/grpc_rate_limit_window.py @@ -4,7 +4,6 @@ from typing import TYPE_CHECKING -from archipy.helpers._deprecation import deprecated_alias from archipy.helpers.utils.rate_limit_utils import RateLimitUtils if TYPE_CHECKING: @@ -54,6 +53,3 @@ def decorator(func: Callable[P, R]) -> Callable[P, R]: return func return decorator - - -grpc_rate_limit_decorator = deprecated_alias("grpc_rate_limit_decorator", grpc_rate_limit) diff --git a/archipy/helpers/decorators/metrics.py b/archipy/helpers/decorators/metrics.py index 34be66a13..2d7350c79 100644 --- a/archipy/helpers/decorators/metrics.py +++ b/archipy/helpers/decorators/metrics.py @@ -9,15 +9,14 @@ import logging import threading import time -from typing import TYPE_CHECKING, Never, Protocol, cast +from typing import TYPE_CHECKING, Protocol, cast from archipy.configs.base_config import BaseConfig -from archipy.helpers._deprecation import warn_deprecated_name from archipy.helpers.utils.otel_utils import OtelUtils from archipy.models.errors import InvalidArgumentError if TYPE_CHECKING: - from collections.abc import Awaitable, Callable, Coroutine, Mapping + from collections.abc import Awaitable, Callable, Mapping from opentelemetry.metrics import Counter, Histogram from opentelemetry.util.types import AttributeValue @@ -34,12 +33,6 @@ class _MetricDecorator(Protocol): def __call__[**P, R](self, func: Callable[P, R], /) -> Callable[P, R]: ... -class _AsyncMetricDecorator(Protocol): - """A decorator that records a metric around a coroutine function and keeps its signature.""" - - def __call__[**P, C: Coroutine[object, Never, object]](self, func: Callable[P, C], /) -> Callable[P, C]: ... - - def _active_metrics_config() -> BaseConfig | None: """Return the global config when OTel metrics should be recorded, else None. @@ -358,37 +351,6 @@ def decorator[**P, R](func: Callable[P, R]) -> Callable[P, R]: return decorator -def async_measure_duration( - name: str | None = None, - *, - unit: str = "s", - attributes: Mapping[str, AttributeValue] | None = None, -) -> _AsyncMetricDecorator: - """Decorate an async function to record execution duration as a histogram. - - Deprecated: - Use :func:`measure_duration`, which supports async functions directly. - - Args: - name: Histogram instrument name. Defaults to module-qualified duration name. - unit: Unit of the recorded duration. Defaults to ``"s"``. - attributes: Optional static attributes merged into each recording. - - Returns: - A decorator that records duration around the target coroutine function. - - Raises: - InvalidArgumentError: If the decorated object is not a coroutine function. - """ - warn_deprecated_name("async_measure_duration", "measure_duration") - - def decorator[**P, C: Coroutine[object, Never, object]](func: Callable[P, C]) -> Callable[P, C]: - _require_coroutine_function(func, "async_measure_duration") - return _duration_wrapper(func, name, unit, attributes) - - return decorator - - def count_calls( name: str | None = None, *, @@ -415,32 +377,3 @@ def decorator[**P, R](func: Callable[P, R]) -> Callable[P, R]: return _counter_wrapper(func, name, attributes) return decorator - - -def async_count_calls( - name: str | None = None, - *, - attributes: Mapping[str, AttributeValue] | None = None, -) -> _AsyncMetricDecorator: - """Decorate an async function to increment a call counter. - - Deprecated: - Use :func:`count_calls`, which supports async functions directly. - - Args: - name: Counter instrument name. Defaults to module-qualified calls name. - attributes: Optional static attributes merged into each recording. - - Returns: - A decorator that counts invocations of the target coroutine function. - - Raises: - InvalidArgumentError: If the decorated object is not a coroutine function. - """ - warn_deprecated_name("async_count_calls", "count_calls") - - def decorator[**P, C: Coroutine[object, Never, object]](func: Callable[P, C]) -> Callable[P, C]: - _require_coroutine_function(func, "async_count_calls") - return _counter_wrapper(func, name, attributes) - - return decorator diff --git a/archipy/helpers/decorators/retry.py b/archipy/helpers/decorators/retry.py deleted file mode 100644 index 0eb2b09a3..000000000 --- a/archipy/helpers/decorators/retry.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Deprecated import path; use ``archipy.helpers.decorators`` and the suffix-less decorator names instead.""" - -from .retry_policy import retry_decorator - -__all__ = ["retry_decorator"] diff --git a/archipy/helpers/decorators/retry_policy.py b/archipy/helpers/decorators/retry_policy.py index 43f6d9fb9..3d8cc5425 100644 --- a/archipy/helpers/decorators/retry_policy.py +++ b/archipy/helpers/decorators/retry_policy.py @@ -11,7 +11,6 @@ from functools import wraps from typing import TYPE_CHECKING, cast -from archipy.helpers._deprecation import deprecated_alias from archipy.models.errors import InvalidArgumentError, ResourceExhaustedError if TYPE_CHECKING: @@ -168,6 +167,3 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: raise policy.exhausted(last_exception) return wrapper - - -retry_decorator = deprecated_alias("retry_decorator", retry) diff --git a/archipy/helpers/decorators/singleton.py b/archipy/helpers/decorators/singleton.py deleted file mode 100644 index 441891693..000000000 --- a/archipy/helpers/decorators/singleton.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Deprecated import path; use ``archipy.helpers.decorators`` and the suffix-less decorator names instead.""" - -from .singleton_class import singleton_decorator - -__all__ = ["singleton_decorator"] diff --git a/archipy/helpers/decorators/singleton_class.py b/archipy/helpers/decorators/singleton_class.py index a91ef3551..b1814eeca 100644 --- a/archipy/helpers/decorators/singleton_class.py +++ b/archipy/helpers/decorators/singleton_class.py @@ -6,8 +6,6 @@ from contextlib import nullcontext from typing import TYPE_CHECKING, Any -from archipy.helpers._deprecation import deprecated_alias - if TYPE_CHECKING: from collections.abc import Callable from contextlib import AbstractContextManager @@ -89,6 +87,3 @@ def singleton_init(self: object, *args: object, **kwargs: object) -> None: return cls return decorator - - -singleton_decorator = deprecated_alias("singleton_decorator", singleton) diff --git a/archipy/helpers/decorators/sqlalchemy_atomic.py b/archipy/helpers/decorators/sqlalchemy_atomic.py deleted file mode 100644 index 9c9364e29..000000000 --- a/archipy/helpers/decorators/sqlalchemy_atomic.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Deprecated import path; use ``archipy.adapters.base.sqlalchemy.atomic`` and the ``*_sqlalchemy_atomic`` names. - -SQLAlchemy is an optional extra, so everything is resolved lazily from ``sqlalchemy_transaction``. -""" - -from typing import Any - -from archipy.helpers.decorators.sqlalchemy_transaction import resolve - - -def __getattr__(name: str) -> Any: # noqa: ANN401 - lazy re-export: typed callers must see the real attribute, not object - """Resolve names from the real implementation module on first access.""" - if name.startswith("__"): - raise AttributeError(name) - return resolve(name) diff --git a/archipy/helpers/decorators/sqlalchemy_transaction.py b/archipy/helpers/decorators/sqlalchemy_transaction.py deleted file mode 100644 index 9552438c8..000000000 --- a/archipy/helpers/decorators/sqlalchemy_transaction.py +++ /dev/null @@ -1,60 +0,0 @@ -"""Deprecated import path; the SQLAlchemy atomic decorators live in ``archipy.adapters.base.sqlalchemy.atomic``. - -SQLAlchemy is an optional extra, so every name is resolved lazily from the new module on first access. -""" - -from __future__ import annotations - -from typing import Any - -from archipy.helpers._deprecation import warn_deprecated_name - -_MOVED_NAMES = frozenset( - { - "mysql_sqlalchemy_atomic", - "postgres_sqlalchemy_atomic", - "sqlalchemy_atomic", - "sqlite_sqlalchemy_atomic", - "starrocks_sqlalchemy_atomic", - }, -) -"""Names that are not deprecated on their own, so the move is what the warning reports.""" - - -def resolve(name: str) -> object: - """Return ``name`` from ``archipy.adapters.base.sqlalchemy.atomic``, warning when the name moved. - - Names that were already deprecated (the ``*_sqlalchemy_atomic_decorator`` aliases) warn about their own - replacement instead. - - Args: - name: The attribute to resolve. - - Returns: - The attribute of the new module. - - Raises: - ImportError: If SQLAlchemy is not installed. - AttributeError: If the new module has no such attribute. - """ - from archipy.adapters.base.sqlalchemy import atomic - - try: - value = getattr(atomic, name) - except AttributeError as e: - msg = f"module {__name__!r} has no attribute {name!r}" - raise AttributeError(msg) from e - if name in _MOVED_NAMES: - warn_deprecated_name( - f"archipy.helpers.decorators.{name}", - f"archipy.adapters.base.sqlalchemy.atomic.{name}", - stacklevel=4, - ) - return value - - -def __getattr__(name: str) -> Any: # noqa: ANN401 - lazy re-export: typed callers must see the real attribute, not object - """Resolve names from the real implementation module on first access.""" - if name.startswith("__"): - raise AttributeError(name) - return resolve(name) diff --git a/archipy/helpers/decorators/timeout.py b/archipy/helpers/decorators/timeout.py deleted file mode 100644 index e4f64dd3b..000000000 --- a/archipy/helpers/decorators/timeout.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Deprecated import path; use ``archipy.helpers.decorators`` and the suffix-less decorator names instead.""" - -from .timeout_limit import timeout_decorator - -__all__ = ["timeout_decorator"] diff --git a/archipy/helpers/decorators/timeout_limit.py b/archipy/helpers/decorators/timeout_limit.py index 88f7110a2..81f37776f 100644 --- a/archipy/helpers/decorators/timeout_limit.py +++ b/archipy/helpers/decorators/timeout_limit.py @@ -10,7 +10,6 @@ from functools import wraps from typing import TYPE_CHECKING, cast -from archipy.helpers._deprecation import deprecated_alias from archipy.models.errors import DeadlineExceededError, FailedPreconditionError if TYPE_CHECKING: @@ -105,6 +104,3 @@ def handle_timeout(_signum: int, _frame: FrameType | None) -> None: return wrapper return decorator - - -timeout_decorator = deprecated_alias("timeout_decorator", timeout) diff --git a/archipy/helpers/decorators/timing.py b/archipy/helpers/decorators/timing.py deleted file mode 100644 index 7c2d8c534..000000000 --- a/archipy/helpers/decorators/timing.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Deprecated import path; use ``archipy.helpers.decorators`` and the suffix-less decorator names instead.""" - -from .timing_log import timing_decorator - -__all__ = ["timing_decorator"] diff --git a/archipy/helpers/decorators/timing_log.py b/archipy/helpers/decorators/timing_log.py index e70c741a4..7bb529d6d 100644 --- a/archipy/helpers/decorators/timing_log.py +++ b/archipy/helpers/decorators/timing_log.py @@ -8,8 +8,6 @@ from functools import wraps from typing import TYPE_CHECKING, cast -from archipy.helpers._deprecation import deprecated_alias - if TYPE_CHECKING: from collections.abc import Awaitable, Callable @@ -78,6 +76,3 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: logger.debug("%s took %.4f seconds to execute.", func_name, time.perf_counter() - start_time) return wrapper - - -timing_decorator = deprecated_alias("timing_decorator", timing) diff --git a/archipy/helpers/decorators/tracing.py b/archipy/helpers/decorators/tracing.py index ec518e461..a7d5e143f 100644 --- a/archipy/helpers/decorators/tracing.py +++ b/archipy/helpers/decorators/tracing.py @@ -7,15 +7,14 @@ import asyncio import functools import inspect -from typing import TYPE_CHECKING, Never, Protocol, TypedDict, cast +from typing import TYPE_CHECKING, Protocol, TypedDict, cast from archipy.configs.base_config import BaseConfig -from archipy.helpers._deprecation import warn_deprecated_name from archipy.helpers.utils.otel_utils import OtelUtils from archipy.models.errors import InvalidArgumentError if TYPE_CHECKING: - from collections.abc import Awaitable, Callable, Coroutine, Mapping + from collections.abc import Awaitable, Callable, Mapping from opentelemetry.context import Context from opentelemetry.trace import Span, SpanKind, Tracer @@ -60,12 +59,6 @@ class _NamedFunction[**P, R](Protocol): def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... -class _AsyncSpanDecorator(Protocol): - """A decorator that wraps a coroutine function in a span and keeps its signature.""" - - def __call__[**P, C: Coroutine[object, Never, object]](self, func: _NamedFunction[P, C], /) -> Callable[P, C]: ... - - class _SpanStartOptions(TypedDict, total=False): """Keyword arguments passed to ``Tracer.start_as_current_span``.""" @@ -461,47 +454,6 @@ def decorator[**P, R](func: Callable[P, R]) -> Callable[P, R]: return decorator -def async_trace_span( - name: str | None = None, - *, - kind: SpanKind | None = None, - attributes: Mapping[str, object] | None = None, - capture_args: list[str] | None = None, -) -> _AsyncSpanDecorator: - """Decorate an async function with an OpenTelemetry child span. - - Deprecated: - Use :func:`trace_span`, which supports async functions directly. - - Args: - name: Span name. Defaults to the function name. - kind: OpenTelemetry ``SpanKind``. Defaults to ``SpanKind.INTERNAL``. - attributes: Optional static attributes set on the span. - capture_args: Parameter names whose call values are recorded as attributes. - Sensitive names (password, token, …) are redacted to ``***``. - - Returns: - A decorator that wraps the target coroutine function in a span. - - Raises: - InvalidArgumentError: If the decorated object is not a coroutine function. - """ - warn_deprecated_name("async_trace_span", "trace_span") - - def decorator[**P, C: Coroutine[object, Never, object]](func: _NamedFunction[P, C]) -> Callable[P, C]: - _require_coroutine_function(func, "async_trace_span") - return _traced_wrapper( - func, - name=name, - kind=kind, - attributes=attributes, - capture_args=capture_args, - root=False, - ) - - return decorator - - def trace_root( name: str | None = None, *, @@ -538,50 +490,6 @@ def decorator[**P, R](func: Callable[P, R]) -> Callable[P, R]: return decorator -def async_trace_root( - name: str | None = None, - *, - kind: SpanKind | None = None, - attributes: Mapping[str, object] | None = None, - capture_args: list[str] | None = None, -) -> _AsyncSpanDecorator: - """Decorate an async function with a root OpenTelemetry span. - - Deprecated: - Use :func:`trace_root`, which supports async functions directly. - - Starts the span with a fresh context detached from any parent span - (``INVALID_SPAN`` context). - - Args: - name: Span name. Defaults to the function name. - kind: OpenTelemetry ``SpanKind``. Defaults to ``SpanKind.INTERNAL``. - attributes: Optional static attributes set on the span. - capture_args: Parameter names whose call values are recorded as attributes. - Sensitive names (password, token, …) are redacted to ``***``. - - Returns: - A decorator that wraps the target coroutine function in a root span. - - Raises: - InvalidArgumentError: If the decorated object is not a coroutine function. - """ - warn_deprecated_name("async_trace_root", "trace_root") - - def decorator[**P, C: Coroutine[object, Never, object]](func: _NamedFunction[P, C]) -> Callable[P, C]: - _require_coroutine_function(func, "async_trace_root") - return _traced_wrapper( - func, - name=name, - kind=kind, - attributes=attributes, - capture_args=capture_args, - root=True, - ) - - return decorator - - def _wrap_method[**P, R]( cls: type, method_name: str, diff --git a/archipy/helpers/decorators/ttl_caching.py b/archipy/helpers/decorators/ttl_caching.py index 63f8ef7e7..de60f6948 100644 --- a/archipy/helpers/decorators/ttl_caching.py +++ b/archipy/helpers/decorators/ttl_caching.py @@ -8,7 +8,6 @@ from functools import wraps from typing import TYPE_CHECKING, Final, cast -from archipy.helpers._deprecation import deprecated_alias from archipy.models.errors import ConfigurationError if TYPE_CHECKING: @@ -291,6 +290,3 @@ def decorator(func: Callable[P, R]) -> CachedFunction[P, R]: ) return decorator - - -ttl_cache_decorator = deprecated_alias("ttl_cache_decorator", ttl_cache) diff --git a/archipy/helpers/utils/_otel/logging_handler.py b/archipy/helpers/utils/_otel/logging_handler.py index 5ac7f9cec..70f4839d9 100644 --- a/archipy/helpers/utils/_otel/logging_handler.py +++ b/archipy/helpers/utils/_otel/logging_handler.py @@ -22,9 +22,6 @@ def filter(self, record: logging.LogRecord) -> bool: def attach_logging_handler(level: int, logger_provider: OwnedLoggerProvider) -> logging.Handler: """Attach an OpenTelemetry ``LoggingHandler`` to the root logger. - Uses the handler from ``opentelemetry-instrumentation-logging`` (the SDK's own ``LoggingHandler`` is deprecated - since OpenTelemetry 1.40) and falls back to the SDK handler when that package is not installed. - Args: level: Minimum level the handler forwards. logger_provider: Provider the handler exports through. @@ -32,10 +29,7 @@ def attach_logging_handler(level: int, logger_provider: OwnedLoggerProvider) -> Returns: The attached handler. """ - try: - from opentelemetry.instrumentation.logging.handler import LoggingHandler - except ImportError: - from opentelemetry.sdk._logs import LoggingHandler # deprecated; kept for installs without the new package + from opentelemetry.instrumentation.logging.handler import LoggingHandler handler: logging.Handler = LoggingHandler(level=level, logger_provider=logger_provider) handler.addFilter(_DropOtelInternalLogs()) diff --git a/archipy/helpers/utils/app_utils.py b/archipy/helpers/utils/app_utils.py index 4769ee642..f8fbe3abf 100644 --- a/archipy/helpers/utils/app_utils.py +++ b/archipy/helpers/utils/app_utils.py @@ -4,7 +4,6 @@ import logging import re -import warnings from concurrent import futures from pathlib import Path from typing import TYPE_CHECKING, Any, cast @@ -432,10 +431,8 @@ class AppUtils: def uvicorn_config(config: BaseConfig | None = None, **overrides: Any) -> dict[str, Any]: # noqa: ANN401 """Build the keyword arguments of ``uvicorn.run`` or ``uvicorn.Config`` from the configuration. - Each setting comes from ``UVICORN`` when it is set there, else from the deprecated field of the same name on - ``FASTAPI`` when that is set (with a ``DeprecationWarning``), else from the ``UVICORN`` default. Unset - optional settings are left out so uvicorn keeps its own defaults. ``host`` and ``port`` come from - ``FASTAPI.SERVE_HOST`` and ``FASTAPI.SERVE_PORT``. + Optional settings with no value are left out so uvicorn keeps its defaults. ``host`` and ``port`` + come from ``FASTAPI.SERVE_HOST`` and ``FASTAPI.SERVE_PORT``. Args: config (BaseConfig | None, optional): Custom configuration. If not provided, uses global config. @@ -444,56 +441,33 @@ def uvicorn_config(config: BaseConfig | None = None, **overrides: Any) -> dict[s Returns: dict[str, Any]: Keyword arguments for uvicorn. Pass the application separately. """ - from archipy.configs.sections.uvicorn import UVICORN_FIELDS_ON_FASTAPI, UVICORN_GROUPED_FIELDS - config = config or BaseConfig.global_config() uvicorn_section, fastapi_section = config.UVICORN, config.FASTAPI - def uvicorn_value(name: str) -> tuple[Any, bool]: - """Return the ``UVICORN`` value of a setting and whether it was set explicitly.""" - if name in UVICORN_GROUPED_FIELDS: - group_name, field = UVICORN_GROUPED_FIELDS[name] - group = getattr(uvicorn_section, group_name) - return getattr(group, field), field in group.model_fields_set - return getattr(uvicorn_section, name), name in uvicorn_section.model_fields_set - - def resolve(name: str) -> Any: # noqa: ANN401 - value, is_set = uvicorn_value(name) - if is_set or name not in UVICORN_FIELDS_ON_FASTAPI: - return value - if name in fastapi_section.model_fields_set: - warnings.warn( - f"FASTAPI.{name} is deprecated and will be removed in 6.0.0; set UVICORN.{name} instead", - DeprecationWarning, - stacklevel=3, - ) - return vars(fastapi_section)[name] # read without the pydantic deprecation warning - return value - values = { "host": fastapi_section.SERVE_HOST, "port": fastapi_section.SERVE_PORT, - "reload": resolve("RELOAD"), - "backlog": resolve("BACKLOG"), - "access_log": resolve("ACCESS_LOG"), - "date_header": resolve("DATE_HEADER"), - "server_header": resolve("SERVER_HEADER"), - "proxy_headers": resolve("PROXY_HEADERS"), - "forwarded_allow_ips": resolve("FORWARDED_ALLOW_IPS"), - "limit_concurrency": resolve("LIMIT_CONCURRENCY"), - "limit_max_requests": resolve("LIMIT_MAX_REQUESTS"), - "timeout_keep_alive": resolve("TIMEOUT_KEEP_ALIVE"), - "timeout_graceful_shutdown": resolve("TIMEOUT_GRACEFUL_SHUTDOWN"), - "ws_max_size": resolve("WS_MAX_SIZE"), - "ws_per_message_deflate": resolve("WS_PER_MESSAGE_DEFLATE"), - "ws_ping_interval": resolve("WS_PING_INTERVAL"), - "ws_ping_timeout": resolve("WS_PING_TIMEOUT"), + "reload": uvicorn_section.RELOAD, + "backlog": uvicorn_section.LIMITS.BACKLOG, + "access_log": uvicorn_section.ACCESS_LOG, + "date_header": uvicorn_section.DATE_HEADER, + "server_header": uvicorn_section.SERVER_HEADER, + "proxy_headers": uvicorn_section.PROXY_HEADERS, + "forwarded_allow_ips": uvicorn_section.FORWARDED_ALLOW_IPS, + "limit_concurrency": uvicorn_section.LIMITS.CONCURRENCY, + "limit_max_requests": uvicorn_section.LIMITS.MAX_REQUESTS, + "timeout_keep_alive": uvicorn_section.TIMEOUT_KEEP_ALIVE, + "timeout_graceful_shutdown": uvicorn_section.TIMEOUT_GRACEFUL_SHUTDOWN, + "ws_max_size": uvicorn_section.WEBSOCKET.MAX_SIZE, + "ws_per_message_deflate": uvicorn_section.WEBSOCKET.PER_MESSAGE_DEFLATE, + "ws_ping_interval": uvicorn_section.WEBSOCKET.PING_INTERVAL, + "ws_ping_timeout": uvicorn_section.WEBSOCKET.PING_TIMEOUT, "ssl_keyfile": uvicorn_section.TLS.KEYFILE, "ssl_certfile": uvicorn_section.TLS.CERTFILE, "ssl_ca_certs": uvicorn_section.TLS.CA_CERTS, } if not values["reload"]: - values["workers"] = resolve("WORKERS_COUNT") + values["workers"] = uvicorn_section.WORKERS_COUNT result = {name: value for name, value in values.items() if value is not None} result.update(overrides) return result diff --git a/archipy/helpers/utils/base_utils.py b/archipy/helpers/utils/base_utils.py index 675277699..b6d4b9d19 100644 --- a/archipy/helpers/utils/base_utils.py +++ b/archipy/helpers/utils/base_utils.py @@ -3,7 +3,6 @@ import re from archipy.helpers.utils.datetime_utils import DatetimeUtils -from archipy.helpers.utils.error_utils import ErrorUtils from archipy.helpers.utils.file_utils import FileUtils from archipy.helpers.utils.jwt_utils import JWTUtils from archipy.helpers.utils.password_utils import PasswordUtils @@ -21,7 +20,7 @@ NATIONAL_CODE_MODULUS = 11 -class BaseUtils(ErrorUtils, DatetimeUtils, PasswordUtils, JWTUtils, TOTPUtils, FileUtils, StringUtils): +class BaseUtils(DatetimeUtils, PasswordUtils, JWTUtils, TOTPUtils, FileUtils, StringUtils): """A utility class that combines multiple utility functionalities into a single class. This class inherits from various utility classes to provide a centralized place for common utility methods. diff --git a/archipy/helpers/utils/error_utils.py b/archipy/helpers/utils/error_utils.py deleted file mode 100644 index 2fbb2c53f..000000000 --- a/archipy/helpers/utils/error_utils.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Deprecated error handling helpers; use ``archipy.helpers.errors`` instead.""" - -from __future__ import annotations - -from typing import TYPE_CHECKING - -from archipy.helpers._deprecation import warn_deprecated_name -from archipy.helpers.errors.capture import capture_exception - -if TYPE_CHECKING: - from fastapi import Request - from fastapi.responses import JSONResponse - - from archipy.models.errors import BaseError - - -class ErrorUtils: - """Deprecated wrappers kept for ``BaseUtils`` callers; each method names its replacement in the warning.""" - - @staticmethod - def capture_exception(exception: BaseException) -> None: - """Deprecated: use ``archipy.helpers.errors.capture_exception``. - - Args: - exception (BaseException): The exception to capture and report. - """ - warn_deprecated_name("BaseUtils.capture_exception", "archipy.helpers.errors.capture_exception") - capture_exception(exception) - - @staticmethod - async def async_handle_fastapi_exception(_request: Request, exception: BaseError) -> JSONResponse: - """Deprecated: use ``archipy.helpers.errors.fastapi.handle_fastapi_exception``. - - Args: - _request (Request): The incoming FastAPI request. - exception (BaseError): The exception to handle. - - Returns: - JSONResponse: A JSON response containing the exception details. - """ - from archipy.helpers.errors.fastapi import handle_fastapi_exception - - warn_deprecated_name( - "BaseUtils.async_handle_fastapi_exception", - "archipy.helpers.errors.fastapi.handle_fastapi_exception", - ) - return await handle_fastapi_exception(_request, exception) - - @staticmethod - def get_fastapi_exception_responses(exceptions: list[type[BaseError]]) -> dict[int, dict[str, object]]: - """Deprecated: use ``archipy.helpers.errors.fastapi.get_fastapi_exception_responses``. - - Args: - exceptions (list[type[BaseError]]): A list of exception types to generate responses for. - - Returns: - dict[int, dict[str, object]]: A dictionary mapping HTTP status codes to their corresponding response - schemas. - """ - from archipy.helpers.errors.fastapi import get_fastapi_exception_responses - - warn_deprecated_name( - "BaseUtils.get_fastapi_exception_responses", - "archipy.helpers.errors.fastapi.get_fastapi_exception_responses", - ) - return get_fastapi_exception_responses(exceptions) diff --git a/archipy/helpers/utils/keycloak_utils.py b/archipy/helpers/utils/keycloak_utils.py deleted file mode 100644 index 7ea292ba3..000000000 --- a/archipy/helpers/utils/keycloak_utils.py +++ /dev/null @@ -1,53 +0,0 @@ -"""Deprecated import path; the Keycloak guards live in ``archipy.adapters.keycloak.auth``. - -``KeycloakUtils.fastapi_auth`` and the other class methods are now plain functions of that module. Names are resolved -lazily on first access, so importing this module does not require the keycloak extra. -""" - -from __future__ import annotations - -from typing import Any - -from archipy.helpers._deprecation import deprecated_alias, warn_deprecated_name - -_MOVED_NAMES = frozenset({"AuthContextManager", "clear_keycloak_remote_cache"}) -_LEGACY_CLASS_METHODS = ("fastapi_auth", "grpc_auth") -_LEGACY_ASYNC_METHODS = {"async_fastapi_auth": "fastapi_auth", "async_grpc_auth": "grpc_auth"} - - -def _legacy_keycloak_utils() -> type: - """Build the ``KeycloakUtils`` namespace whose methods delegate to the functions of the new module.""" - from archipy.adapters.keycloak import auth # noqa: PLC0415 - - namespace: dict[str, object] = {name: staticmethod(getattr(auth, name)) for name in _LEGACY_CLASS_METHODS} - for old_name, new_name in _LEGACY_ASYNC_METHODS.items(): - namespace[old_name] = staticmethod(deprecated_alias(f"KeycloakUtils.{old_name}", getattr(auth, new_name))) - namespace["_get_keycloak_adapter"] = staticmethod(auth._get_keycloak_adapter) - namespace["_get_async_keycloak_adapter"] = staticmethod(auth._get_async_keycloak_adapter) - namespace["__doc__"] = "Deprecated namespace; use the functions of ``archipy.adapters.keycloak.auth``." - return type("KeycloakUtils", (), namespace) - - -def __getattr__(name: str) -> Any: # noqa: ANN401 - module __getattr__ forwards names of any type - """Return ``name`` from ``archipy.adapters.keycloak.auth``, warning for the names that moved or were replaced.""" - if name.startswith("__"): - raise AttributeError(name) - if name == "KeycloakUtils": - warn_deprecated_name( - "archipy.helpers.utils.keycloak_utils.KeycloakUtils", - "the functions of archipy.adapters.keycloak.auth", - ) - return _legacy_keycloak_utils() - from archipy.adapters.keycloak import auth # noqa: PLC0415 - - try: - value = getattr(auth, name) - except AttributeError as e: - msg = f"module {__name__!r} has no attribute {name!r}" - raise AttributeError(msg) from e - if name in _MOVED_NAMES: - warn_deprecated_name( - f"archipy.helpers.utils.keycloak_utils.{name}", - f"archipy.adapters.keycloak.auth.{name}", - ) - return value diff --git a/archipy/models/dtos/keycloak/__init__.py b/archipy/models/dtos/keycloak/__init__.py index 87818b877..9a896d7aa 100644 --- a/archipy/models/dtos/keycloak/__init__.py +++ b/archipy/models/dtos/keycloak/__init__.py @@ -2,7 +2,6 @@ from archipy.models.dtos.keycloak.auth_dtos import ActorDTO, AuthenticatedUserDTO from archipy.models.dtos.keycloak.base import ( - DictCompatMixin, KeycloakBaseDTO, KeycloakRequestDTO, KeycloakResponseDTO, @@ -12,7 +11,6 @@ __all__ = [ "ActorDTO", "AuthenticatedUserDTO", - "DictCompatMixin", "KeycloakBaseDTO", "KeycloakRequestDTO", "KeycloakResponseDTO", diff --git a/archipy/models/dtos/keycloak/base.py b/archipy/models/dtos/keycloak/base.py index 5e581178c..5abe16a73 100644 --- a/archipy/models/dtos/keycloak/base.py +++ b/archipy/models/dtos/keycloak/base.py @@ -1,54 +1,10 @@ """Base classes for Keycloak representation DTOs.""" -import warnings from typing import Any from pydantic import BaseModel, ConfigDict from pydantic.alias_generators import to_camel -_REMOVAL_VERSION = "6.0.0" - - -class DictCompatMixin(BaseModel): - """Read-only dict-style access for DTOs that replaced plain ``dict`` return values. - - Every access emits a ``DeprecationWarning``. Keys are the camelCase Keycloak field names and - fields that are unset (``None``) are absent, matching the dicts these DTOs replaced. - """ - - def _compat_dict(self, access: str) -> dict[str, Any]: - warnings.warn( - f"dict-style access ({access}) on {type(self).__name__} is deprecated and will be removed in " - f"{_REMOVAL_VERSION}; use attribute access instead.", - DeprecationWarning, - stacklevel=3, - ) - return self.model_dump(by_alias=True, exclude_none=True) - - def __getitem__(self, key: str) -> Any: # noqa: ANN401 - """Return the value stored under ``key``.""" - return self._compat_dict("[]")[key] - - def __contains__(self, key: object) -> bool: - """Return whether ``key`` is a set field.""" - return key in self._compat_dict("in") - - def get(self, key: str, default: Any = None) -> Any: # noqa: ANN401 - """Return the value stored under ``key`` or ``default``.""" - return self._compat_dict("get()").get(key, default) - - def keys(self) -> Any: # noqa: ANN401 - """Return the set field names.""" - return self._compat_dict("keys()").keys() - - def values(self) -> Any: # noqa: ANN401 - """Return the set field values.""" - return self._compat_dict("values()").values() - - def items(self) -> Any: # noqa: ANN401 - """Return the set ``(name, value)`` pairs.""" - return self._compat_dict("items()").items() - class KeycloakBaseDTO(BaseModel): """Standalone base for Keycloak admin API representations. @@ -82,7 +38,7 @@ class KeycloakRequestDTO(KeycloakBaseDTO): model_config = ConfigDict(extra="forbid") -class KeycloakResponseDTO(DictCompatMixin, KeycloakBaseDTO): +class KeycloakResponseDTO(KeycloakBaseDTO): """Base for representations returned by Keycloak. Unknown fields (added by newer Keycloak versions) are kept in ``model_extra`` instead of failing validation. diff --git a/archipy/models/dtos/keycloak_dtos.py b/archipy/models/dtos/keycloak_dtos.py deleted file mode 100644 index 167e3f4d9..000000000 --- a/archipy/models/dtos/keycloak_dtos.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Keycloak-related data transfer objects (kept for backward compatibility). - -The DTOs now live in :mod:`archipy.models.dtos.keycloak`. -""" - -from archipy.models.dtos.keycloak.auth_dtos import ActorDTO, AuthenticatedUserDTO - -__all__ = ["ActorDTO", "AuthenticatedUserDTO"] diff --git a/docs/api_reference/configs.md b/docs/api_reference/configs.md index 9645a2d3b..983703705 100644 --- a/docs/api_reference/configs.md +++ b/docs/api_reference/configs.md @@ -42,8 +42,7 @@ from archipy.configs.config_template import RedisConfig RedisConfig(TLS={"IS_ENABLED": True, "CA_CERTS": "/certs/ca.pem"}) ``` -The flat names they replace (`REDIS__SSL`, `VAULT__APPROLE_ROLE_ID`, `AUTH__JWT_ISSUER`) still work, emit a -`DeprecationWarning`, and are removed in 6.0.0. A value set on a group wins over the flat one. +See the [6.0 upgrade guide](../community/deprecations.md#configuration) for the former flat field names. Grouped sections: `VAULT`, `SCYLLADB`, `TEMPORAL`, `REDIS`, `ELASTIC`, `SQLALCHEMY` (`POOL`, `COUNT_CACHE`), `AUTH`, `KEYCLOAK`, `EMAIL`, `GRPC` (`TLS`, `STUB_TLS`), `KAFKA` (`SASL`, `SSL`), and `FASTAPI` (`CORS`, `GZIP`, diff --git a/docs/api_reference/helpers/decorators.md b/docs/api_reference/helpers/decorators.md index 406700992..ba494be26 100644 --- a/docs/api_reference/helpers/decorators.md +++ b/docs/api_reference/helpers/decorators.md @@ -8,10 +8,8 @@ description: API reference for ArchiPy helper decorators. The `helpers/decorators` subpackage provides function and class decorators for cross-cutting concerns including caching, retry logic, deprecation, timing, tracing, and transaction management. -Decorators are named without a `_decorator` suffix (`retry`, `timeout`, `ttl_cache`, ...) and detect `async def` -functions automatically. The old names (`retry_decorator`, `async_trace_span`, ...) keep working and emit a -`DeprecationWarning` and will be removed in 6.0.0; see the -[Decorators tutorial](../../tutorials/helpers/decorators.md#deprecated-names). +Import general-purpose decorators from `archipy.helpers.decorators`. The tracing and metrics decorators accept +both synchronous and asynchronous functions. ## Cache @@ -51,8 +49,7 @@ heading_level: 3 ## Tracing -OpenTelemetry span decorators for functions and classes (`trace_span`, `trace_root`, `trace_class`). The old -`async_trace_span` and `async_trace_root` names are deprecated aliases that will be removed in 6.0.0. +OpenTelemetry span decorators for functions and classes (`trace_span`, `trace_root`, `trace_class`). ::: archipy.helpers.decorators.tracing options: @@ -62,7 +59,7 @@ heading_level: 3 ## Metrics OpenTelemetry metrics decorators for duration histograms and call counters (`measure_duration`, `count_calls`). Both -accept sync and async functions; the `async_*` names are deprecated aliases that will be removed in 6.0.0. +accept synchronous and asynchronous functions. ::: archipy.helpers.decorators.metrics options: @@ -80,9 +77,9 @@ heading_level: 3 ## SQLAlchemy Atomic -The SQLAlchemy atomic decorators moved to the adapters layer; see -[Base SQLAlchemy](../adapters/base.md#atomic-transaction-decorators). The old -`archipy.helpers.decorators` names still work and emit a `DeprecationWarning`; they will be removed in 6.0.0. + +Import the atomic decorators from `archipy.adapters.base.sqlalchemy.atomic`. +[Base SQLAlchemy](../adapters/base.md#atomic-transaction-decorators) documents the database-specific variants. ## Deprecation Warnings diff --git a/docs/api_reference/helpers/utils.md b/docs/api_reference/helpers/utils.md index b8c8244b0..d39486be4 100644 --- a/docs/api_reference/helpers/utils.md +++ b/docs/api_reference/helpers/utils.md @@ -63,16 +63,6 @@ options: show_root_toc_entry: false heading_level: 3 -## Error Utils - -Deprecated wrappers (`capture_exception`, `async_handle_fastapi_exception`, `get_fastapi_exception_responses`) -that redirect to [`archipy.helpers.errors`](errors.md). They will be removed in 6.0.0. - -::: archipy.helpers.utils.error_utils -options: -show_root_toc_entry: false -heading_level: 3 - ## JWT Utils Utilities for JWT generation, verification, and decoding with configurable signing algorithms and expiration. @@ -100,11 +90,9 @@ options: show_root_toc_entry: false heading_level: 3 -## Keycloak Utils +## Keycloak Auth Guards -The Keycloak authentication guards moved to the adapters layer; see -[Keycloak](../adapters/keycloak.md#auth-guards). `archipy.helpers.utils.keycloak_utils` still resolves the old names -and emits a `DeprecationWarning`; the old module will be removed in 6.0.0. +The [Keycloak auth guards](../adapters/keycloak.md#auth-guards) live in `archipy.adapters.keycloak.auth`. ## OpenTelemetry Utils diff --git a/docs/community/changelog/5/5.10.0.md b/docs/community/changelog/5/5.10.0.md index 98461e6fe..99b287da8 100644 --- a/docs/community/changelog/5/5.10.0.md +++ b/docs/community/changelog/5/5.10.0.md @@ -17,7 +17,7 @@ description: "Release notes for ArchiPy 5.10.0" - The old `*_decorator` names, the `async_*` names and the old module paths keep working and emit a `DeprecationWarning` that names the replacement - Implementations moved to modules that do not clash with the new function names (for example `retry_policy.py` - and `sqlalchemy_transaction.py`); see [Deprecated names](../../../tutorials/helpers/decorators.md#deprecated-names) + and `sqlalchemy_transaction.py`); see [6.0 decorator migration](../../deprecations.md#decorators) - **Automatic async detection** - `retry`, `timeout`, `timing`, `ttl_cache`, `measure_duration`, `count_calls`, `trace_span`, `trace_root` and the SQLAlchemy atomic decorators accept `async def` functions, so the separate `async_*` variants are no longer needed. diff --git a/docs/community/changelog/5/5.32.0.md b/docs/community/changelog/5/5.32.0.md index e231f97c3..a7b2750a8 100644 --- a/docs/community/changelog/5/5.32.0.md +++ b/docs/community/changelog/5/5.32.0.md @@ -5,7 +5,7 @@ description: "Release notes for ArchiPy 5.32.0" # 5.32.0 — 2026-11-21 -[← 5.31.2](5.31.2.md) | [↑ 5.x series](index.md) +[← 6.0.0](../6/6.0.0.md) | [5.31.2 →](5.31.2.md) | [↑ 5.x series](index.md) ## Added diff --git a/docs/community/changelog/6/6.0.0.md b/docs/community/changelog/6/6.0.0.md new file mode 100644 index 000000000..5a146e32a --- /dev/null +++ b/docs/community/changelog/6/6.0.0.md @@ -0,0 +1,69 @@ +--- +title: "Changelog 6.0.0" +description: "Release notes for ArchiPy 6.0.0" +--- + +# 6.0.0 — Unreleased + +[← 5.32.0](../5/5.32.0.md) | [↑ 6.x series](index.md) + +Migrate imports, settings, and adapter calls with the [ArchiPy 6.0 upgrade guide](../../deprecations.md). + +## Changed + +### Adapters - Security + +- **Email** - SMTP defaults to STARTTLS. STARTTLS and implicit TLS verify the server certificate and hostname. Set + `EMAIL__TLS__CA_FILE` for a private CA. SMTP authentication requires TLS and both credentials. Choose `none` for + unauthenticated clear-text delivery. +- **Keycloak** - Local token verification requires a matching issuer and `typ == "Bearer"`. The issuer defaults to the + configured server and realm URL. Set `KEYCLOAK__TOKEN_VALIDATION__EXPECTED_ISSUER` when tokens use a different URL. + Set `EXPECTED_AUDIENCE` in the same group to verify the token audience. + +### Adapters - Kafka and Elasticsearch + +- **Kafka Keys** - Omitting the producer key sends a Kafka null key. Pass `key=""` to send an explicit empty key. +- **Elasticsearch Errors** - The adapters raise ArchiPy errors for Elasticsearch API and transport failures. The + original exception remains available through `__cause__`. + +### Helpers - Optional Imports + +- **Lazy SDK Loading** - Python 3.15 defers selected SDK-backed public imports until use. Keycloak loads resource + mixins on demand. Adapters with explicit clients, config, or SQLAlchemy engines defer reading global settings + where possible. [#624](https://github.com/SyntaxArc/ArchiPy/pull/624) + +## Removed + +### Configs - Flat Settings + +- **Config Aliases** - Use nested groups in Python and double underscores between fields in environment variables. + For example, replace `REDIS__SSL` with `REDIS__TLS__IS_ENABLED`. Vault bootstrap also uses nested names. +- **Uvicorn Fields on FastAPI** - Move server options to `UVICORN`, including its `TLS`, `LIMITS`, and `WEBSOCKET` + groups. Set bind host and port under `FASTAPI`. +- **Retired Options** - Remove `ELASTIC.MAP_ERRORS`, `KAFKA.EMPTY_KEY_FOR_MISSING_KEY`, and the four ScyllaDB per-host + pool-sizing fields from configuration. SMTP drops opportunistic `auto` mode and the TLS verification toggle. + +### Helpers - Imports + +- **Decorator Aliases** - Replace deprecated import paths, `*_decorator` names, and the separate async tracing, + metrics, and atomic aliases. Import SQLAlchemy atomic decorators from `archipy.adapters.base.sqlalchemy.atomic`. +- **Error and Auth Utilities** - Import the error helpers directly from `archipy.helpers.errors` and + `archipy.helpers.errors.fastapi`. Import Keycloak guards from `archipy.adapters.keycloak.auth`. +- **OpenTelemetry Logging** - The logging bridge uses the handler supplied by the `otel` extra. The SDK handler + fallback is removed. + +### Adapters - Keycloak, Redis, and Temporal + +- **Keycloak Compatibility APIs** - Pass request DTOs and read response DTO attributes. Use + `AuthContextManager.get_auth_context()` for auth data previously stored on FastAPI's `request.state`. Migrate + old Keycloak type aliases and auth DTO imports to `archipy.models.dtos.keycloak` and its submodules. +- **Redis HASH Upserts** - Remove the `replace` argument from `upsert_hash()` and `upsert_hash_dto()`. + Both operations merge supplied fields into the hash. +- **Temporal Compatibility APIs** - Replace `stop_schedule()` with `delete_schedule()` or `pause_schedule()`. + Pass deployment versions through `start_worker(deployment_config=...)`. Configure TLS through `TEMPORAL.TLS` + and read `messaging.operation.type` on Temporal spans. + +## Tests + +- **Migration Coverage** - Exercise nested settings, SMTP security, Kafka null and empty keys, Keycloak DTOs and + auth context, Elasticsearch error mapping, and Redis HASH merges. diff --git a/docs/community/changelog/6/index.md b/docs/community/changelog/6/index.md new file mode 100644 index 000000000..4c3ddc3e9 --- /dev/null +++ b/docs/community/changelog/6/index.md @@ -0,0 +1,12 @@ +--- +title: "6.x Changelog" +description: "Release history for the ArchiPy 6.x series" +--- + +# 6.x Changelog + +[↑ All versions](../index.md) + +| Version | Date | Summary | +|---------|------|---------| +| [6.0.0](6.0.0.md) | Unreleased | Removes deprecated APIs and flat config fields. Enforces SMTP TLS for login and Keycloak issuer checks. | diff --git a/docs/community/changelog/index.md b/docs/community/changelog/index.md index 89cfc6f45..f5510fc6a 100644 --- a/docs/community/changelog/index.md +++ b/docs/community/changelog/index.md @@ -7,6 +7,10 @@ description: "Release history and version changelog for ArchiPy." All notable changes to ArchiPy are documented here, organized by major version series. +## [6.x Series](6/index.md) + +6.0.0 is unreleased. + ## [5.x Series](5/index.md) 61 releases — from 5.0.0 to 5.32.0 diff --git a/docs/community/deprecations.md b/docs/community/deprecations.md index 051122f35..f910a8572 100644 --- a/docs/community/deprecations.md +++ b/docs/community/deprecations.md @@ -1,23 +1,21 @@ --- -title: Deprecations -description: Every deprecated ArchiPy import path, name and behavior, with its replacement and removal version. +title: Upgrade to ArchiPy 6.0 +description: Replace the deprecated APIs, settings, and behaviors removed in ArchiPy 6.0. --- -# Deprecations +# Upgrade to ArchiPy 6.0 -ArchiPy does not break a public path in a minor release. A moved or renamed name keeps working and emits a -`DeprecationWarning` that names its replacement. Every name on this page is removed in **6.0.0**. - -To find the calls in your code, turn the warning into an error: +Run a representative workload on the latest 5.x release with deprecation warnings enabled to locate calls that +need migration. Review configuration files and environment variables as well. ```bash -uv run python -W error::DeprecationWarning -m your_app +uv run python -W default::DeprecationWarning -m your_app ``` ## Decorators -Decorators dropped the `_decorator` suffix and detect `async def` functions themselves, so the `async_*` variants -are no longer needed. Import everything from `archipy.helpers.decorators`. Deprecated since 5.10.0. +Import the replacement names from `archipy.helpers.decorators`. The decorators support synchronous and asynchronous +functions through the same API. | Deprecated | Replacement | |-----------------------------|--------------------| @@ -32,13 +30,7 @@ are no longer needed. Import everything from `archipy.helpers.decorators`. Depre | `async_trace_span` | `trace_span` | | `async_trace_root` | `trace_root` | -The warning is raised when the deprecated function is called. For a decorator factory that is when the decorator is -applied. - -### Deprecated decorator modules - -The old submodule paths still export the old names. The implementations moved to modules whose names do not clash -with the new function names. Deprecated since 5.10.0. +### Removed import paths | Deprecated import path | Replacement | |----------------------------------------------|-------------------------------------------------------| @@ -50,14 +42,11 @@ with the new function names. Deprecated since 5.10.0. | `archipy.helpers.decorators.grpc_rate_limit` | `from archipy.helpers.decorators import grpc_rate_limit` | | `archipy.helpers.decorators.sqlalchemy_atomic` | `archipy.adapters.base.sqlalchemy.atomic` | -The package exposes the decorator under the same name as the old module, so import the function from -`archipy.helpers.decorators` and not from the submodule. The implementations live in the internal modules -`retry_policy.py`, `timeout_limit.py`, `timing_log.py`, `singleton_class.py`, `ttl_caching.py`, -`grpc_rate_limit_window.py` and `sqlalchemy_transaction.py`. +The `archipy.helpers.decorators.sqlalchemy_transaction` path also moves to `archipy.adapters.base.sqlalchemy.atomic`. -## SQLAlchemy atomic decorators +### SQLAlchemy atomic decorators -The atomic decorators moved to the adapters layer, `archipy.adapters.base.sqlalchemy.atomic`. +Import all atomic decorators from `archipy.adapters.base.sqlalchemy.atomic`. | Deprecated | Replacement | Since | |----------------------------------------------------------------------------------------|-----------------------------------------------------------------------|--------| @@ -66,17 +55,13 @@ The atomic decorators moved to the adapters layer, `archipy.adapters.base.sqlalc | `archipy.helpers.decorators.mysql_sqlalchemy_atomic` | `archipy.adapters.base.sqlalchemy.atomic.mysql_sqlalchemy_atomic` | 5.16.0 | | `archipy.helpers.decorators.sqlite_sqlalchemy_atomic` | `archipy.adapters.base.sqlalchemy.atomic.sqlite_sqlalchemy_atomic` | 5.16.0 | | `archipy.helpers.decorators.starrocks_sqlalchemy_atomic` | `archipy.adapters.base.sqlalchemy.atomic.starrocks_sqlalchemy_atomic` | 5.16.0 | -| `sqlalchemy_atomic_decorator(db_type, is_async=...)` | `sqlalchemy_atomic(db_type)`; `is_async` is ignored | 5.10.0 | +| `sqlalchemy_atomic_decorator(db_type, is_async=...)` | `sqlalchemy_atomic(db_type)` | 5.10.0 | | `postgres_sqlalchemy_atomic_decorator`, `async_postgres_sqlalchemy_atomic_decorator` | `postgres_sqlalchemy_atomic` | 5.10.0 | | `mysql_sqlalchemy_atomic_decorator`, `async_mysql_sqlalchemy_atomic_decorator` | `mysql_sqlalchemy_atomic` | 5.10.0 | | `sqlite_sqlalchemy_atomic_decorator`, `async_sqlite_sqlalchemy_atomic_decorator` | `sqlite_sqlalchemy_atomic` | 5.10.0 | | `starrocks_sqlalchemy_atomic_decorator`, `async_starrocks_sqlalchemy_atomic_decorator` | `starrocks_sqlalchemy_atomic` | 5.10.0 | -The `*_decorator` and `async_*` names warn about their own replacement. - -## Utilities and error handling - -Deprecated since 5.15.0. Each method emits a `DeprecationWarning` and returns the same result as its replacement. +## Error helpers | Deprecated | Replacement | |---------------------------------------------|------------------------------------------------------------------| @@ -84,21 +69,22 @@ Deprecated since 5.15.0. Each method emits a `DeprecationWarning` and returns th | `BaseUtils.async_handle_fastapi_exception` | `archipy.helpers.errors.fastapi.handle_fastapi_exception` | | `BaseUtils.get_fastapi_exception_responses` | `archipy.helpers.errors.fastapi.get_fastapi_exception_responses` | -## Keycloak - -| Deprecated | Replacement | Since | Notes | -|----------------------------------------------------------------------------------|---------------------------------------------------|--------|--------------------------------------------------------------------------------------------| -| `archipy.helpers.utils.keycloak_utils` module | `archipy.adapters.keycloak.auth` | 5.16.0 | `AuthContextManager` and `clear_keycloak_remote_cache` warn when read from the old module. | -| `KeycloakUtils` class | The functions of `archipy.adapters.keycloak.auth` | 5.16.0 | `fastapi_auth` and `grpc_auth` are plain functions of the new module. | -| `KeycloakUtils.async_fastapi_auth`, `KeycloakUtils.async_grpc_auth` | `fastapi_auth`, `grpc_auth` | 5.16.0 | `fastapi_auth` is always async and serves both endpoint kinds. | -| Reading `request.state.user_info`, `token_info`, `actor_chain`, `user_roles` | `AuthContextManager.get_auth_context()` | 5.16.0 | Read `raw_user_info`, `token_info`, `actor_chain` and `roles` of the auth context. | -| Dict-style access on Keycloak response DTOs (`result["id"]`, `result.get("id")`) | Attribute access (`result.id`) | 5.21.0 | Applies to the DTOs that replaced dict return values. | -| Passing a plain `dict` as a Keycloak request payload | A `Keycloak*RequestDTO` | 5.21.0 | The dict is passed through unchanged until removal. | +Import replacement functions directly. The `archipy.helpers.utils.error_utils` module was removed. -### Keycloak type aliases +## Keycloak -These aliases point at the pydantic DTOs that replaced the old TypedDicts. They emit no warning at runtime. Deprecated -since 5.21.0. +- Import `fastapi_auth`, `grpc_auth`, `AuthContextManager`, and `clear_keycloak_remote_cache` from + `archipy.adapters.keycloak.auth`. Replace `KeycloakUtils.async_fastapi_auth` and `KeycloakUtils.async_grpc_auth` + with the same guard functions. +- Read `raw_user_info`, `token_info`, `actor_chain`, and `roles` from + `AuthContextManager.get_auth_context()`. FastAPI guards no longer put those values on `request.state`. +- Pass request DTOs to the adapters. Convert existing dictionaries with the matching DTO's `model_validate()`. + Read response DTO attributes directly, or call `model_dump(by_alias=True, exclude_none=True)` when a dictionary is + needed. +- Import `ActorDTO` and `AuthenticatedUserDTO` from `archipy.models.dtos.keycloak`. +- Locally verified tokens must have `typ == "Bearer"` and a matching issuer. Set + `KEYCLOAK__TOKEN_VALIDATION__EXPECTED_ISSUER` if tokens use a different URL from the one configured for the adapter. + Set `KEYCLOAK__TOKEN_VALIDATION__EXPECTED_AUDIENCE` to validate the audience. | Deprecated | Replacement | |------------------------------|-----------------------------| @@ -109,46 +95,358 @@ since 5.21.0. | `KeycloakProtocolMapperType` | `KeycloakProtocolMapperDTO` | | `KeycloakComponentType` | `KeycloakComponentDTO` | -## FastAPI config - -The Uvicorn settings moved from `FASTAPI` to the new `UVICORN` section, which also gains `SSL_KEYFILE`, -`SSL_CERTFILE` and `SSL_CA_CERTS`. `AppUtils.uvicorn_config()` builds the `uvicorn.run` arguments from it. An old -field still works when the matching `UVICORN` field is not set. Building `FastAPIConfig` with one, and reading it -through `AppUtils.uvicorn_config()`, emits a `DeprecationWarning`. Deprecated since 5.25.0. - -| Deprecated | Replacement | -|-----------------------------------------------------------------------------------------------|------------------------------------------------| -| `FASTAPI.ACCESS_LOG`, `BACKLOG`, `DATE_HEADER`, `SERVER_HEADER`, `RELOAD`, `WORKERS_COUNT` | The same names on `UVICORN` | -| `FASTAPI.PROXY_HEADERS`, `FORWARDED_ALLOW_IPS` | The same names on `UVICORN` | -| `FASTAPI.LIMIT_CONCURRENCY`, `LIMIT_MAX_REQUESTS` | The same names on `UVICORN` | -| `FASTAPI.TIMEOUT_KEEP_ALIVE`, `TIMEOUT_GRACEFUL_SHUTDOWN` | The same names on `UVICORN` | -| `FASTAPI.WS_MAX_SIZE`, `WS_PER_MESSAGE_DEFLATE`, `WS_PING_INTERVAL`, `WS_PING_TIMEOUT` | The same names on `UVICORN` | - -`FASTAPI.SERVE_HOST` and `FASTAPI.SERVE_PORT` stay where they are. - -These fields are marked with pydantic `deprecated`: reading one (`config.FASTAPI.RELOAD`) emits a -`DeprecationWarning` that names the replacement, and the JSON schema flags the field. ArchiPy's own reads do not warn. - -## ScyllaDB config - -`MAX_CONNECTIONS_PER_HOST`, `MIN_CONNECTIONS_PER_HOST`, `CORE_CONNECTIONS_PER_HOST` and -`MAX_REQUESTS_PER_CONNECTION` of `SCYLLADB` never had an effect, because scylla-driver has no per-host pool sizing. -Reading one emits a `DeprecationWarning`, and building a cluster with a non-default value warns too. They are removed -in **6.0.0** with no replacement. Deprecated since 5.23.0. - -## Adding a deprecation - -Keep the old name working and route it through `archipy.helpers._deprecation`: - -- `warn_deprecated_name(old_name, new_name)` emits the warning from inside a function. -- `deprecated_alias(old_name, replacement)` returns a wrapper that warns and then calls the replacement. - -Both put `REMOVAL_VERSION` in the message. Add each new deprecation to this page and to the `Deprecated` section of the -release changelog. - -## See Also - -- [Changelog](changelog/index.md) - Release notes, including the `Deprecated` section of each release -- [Decorators](../tutorials/helpers/decorators.md#deprecated-names) - Decorator usage and the deprecated names -- [FAQ](faq.md) - Answers to common questions -- [Contributing](contributing.md) - How to propose and land changes +## Adapter behavior + +| Removed behavior | Migration | +|------------------|-----------| +| SMTP opportunistic `auto` TLS and clear-text login | Use verified `starttls` (the default) or `implicit`. Set `EMAIL__TLS__CA_FILE` for a private CA. Use `none` only for unauthenticated SMTP. | +| SMTP certificate-verification toggle | Remove `EMAIL__TLS__VERIFY` or `EMAIL__TLS_VERIFY`. ArchiPy always verifies certificates and hostnames when using TLS. | +| Kafka implicit empty key | Omit the key to send a Kafka null key. Pass `key=""` explicitly to send an empty key. Remove `KAFKA__EMPTY_KEY_FOR_MISSING_KEY`. | +| Raw Elasticsearch API and transport errors | Catch the [ArchiPy errors](../tutorials/adapters/elasticsearch.md#error-mapping). Remove `ELASTIC__MAP_ERRORS`. | +| Redis HASH upsert `replace` argument | Remove the argument from `upsert_hash` and `upsert_hash_dto`. Both methods merge the supplied fields. | +| Temporal `stop_schedule` | Use `delete_schedule` to remove a schedule or `pause_schedule` to keep it. | +| Temporal `start_worker(build_id=...)` | Pass `deployment_config=WorkerDeploymentConfig(...)` with a `WorkerDeploymentVersion`. | +| Temporal `TLS_CERT_PARTS_REQUIRED` | Configure server TLS through `TEMPORAL.TLS`. Supply client certificate and key together when using mTLS. | +| Temporal span attribute `messaging.operation` | Read `messaging.operation.type`. | +| OpenTelemetry SDK logging handler fallback | Install the `otel` extra to get `opentelemetry-instrumentation-logging`. | +| ScyllaDB per-host pool-size fields | Remove `MAX_CONNECTIONS_PER_HOST`, `MIN_CONNECTIONS_PER_HOST`, `CORE_CONNECTIONS_PER_HOST`, and `MAX_REQUESTS_PER_CONNECTION`. The driver manages the connections. | + +## Configuration + +Use the paths below in Python code. For environment variables, replace each dot with a double underscore. +For example, `REDIS__SSL=true` becomes `REDIS__TLS__IS_ENABLED=true`. If you set a value under both 5.x names, +keep the value you configured under the nested name. + +### AUTH + +| 5.x field | 6.0 field | +|-----------|-----------| +| `AUTH.ACCESS_TOKEN_EXPIRES_IN` | `AUTH.JWT.ACCESS_TOKEN_EXPIRES_IN` | +| `AUTH.REFRESH_TOKEN_EXPIRES_IN` | `AUTH.JWT.REFRESH_TOKEN_EXPIRES_IN` | +| `AUTH.HASH_ALGORITHM` | `AUTH.JWT.ALGORITHM` | +| `AUTH.JWT_ISSUER` | `AUTH.JWT.ISSUER` | +| `AUTH.JWT_AUDIENCE` | `AUTH.JWT.AUDIENCE` | +| `AUTH.TOKEN_VERSION` | `AUTH.JWT.TOKEN_VERSION` | +| `AUTH.JWT_LEEWAY` | `AUTH.JWT.LEEWAY` | +| `AUTH.ENABLE_JTI_CLAIM` | `AUTH.JWT.ENABLE_JTI_CLAIM` | +| `AUTH.ENABLE_TOKEN_ROTATION` | `AUTH.JWT.ENABLE_TOKEN_ROTATION` | +| `AUTH.REFRESH_TOKEN_REUSE_INTERVAL` | `AUTH.JWT.REFRESH_TOKEN_REUSE_INTERVAL` | +| `AUTH.TOTP_SECRET_KEY` | `AUTH.TOTP.SECRET_KEY` | +| `AUTH.TOTP_HASH_ALGORITHM` | `AUTH.TOTP.HASH_ALGORITHM` | +| `AUTH.TOTP_LENGTH` | `AUTH.TOTP.LENGTH` | +| `AUTH.TOTP_EXPIRES_IN` | `AUTH.TOTP.EXPIRES_IN` | +| `AUTH.TOTP_TIME_STEP` | `AUTH.TOTP.TIME_STEP` | +| `AUTH.TOTP_VERIFICATION_WINDOW` | `AUTH.TOTP.VERIFICATION_WINDOW` | +| `AUTH.TOTP_MAX_ATTEMPTS` | `AUTH.TOTP.MAX_ATTEMPTS` | +| `AUTH.TOTP_LOCKOUT_TIME` | `AUTH.TOTP.LOCKOUT_TIME` | +| `AUTH.LOGIN_RATE_LIMIT` | `AUTH.RATE_LIMITS.LOGIN` | +| `AUTH.TOTP_RATE_LIMIT` | `AUTH.RATE_LIMITS.TOTP` | +| `AUTH.PASSWORD_RESET_RATE_LIMIT` | `AUTH.RATE_LIMITS.PASSWORD_RESET` | +| `AUTH.HASH_ITERATIONS` | `AUTH.PASSWORD_POLICY.HASH_ITERATIONS` | +| `AUTH.MIN_LENGTH` | `AUTH.PASSWORD_POLICY.MIN_LENGTH` | +| `AUTH.REQUIRE_DIGIT` | `AUTH.PASSWORD_POLICY.REQUIRE_DIGIT` | +| `AUTH.REQUIRE_LOWERCASE` | `AUTH.PASSWORD_POLICY.REQUIRE_LOWERCASE` | +| `AUTH.REQUIRE_SPECIAL` | `AUTH.PASSWORD_POLICY.REQUIRE_SPECIAL` | +| `AUTH.REQUIRE_UPPERCASE` | `AUTH.PASSWORD_POLICY.REQUIRE_UPPERCASE` | +| `AUTH.SALT_LENGTH` | `AUTH.PASSWORD_POLICY.SALT_LENGTH` | +| `AUTH.SPECIAL_CHARACTERS` | `AUTH.PASSWORD_POLICY.SPECIAL_CHARACTERS` | +| `AUTH.PASSWORD_HISTORY_SIZE` | `AUTH.PASSWORD_POLICY.HISTORY_SIZE` | + +### ELASTIC + +| 5.x field | 6.0 field | +|-----------|-----------| +| `ELASTIC.HTTP_USER_NAME` | `ELASTIC.AUTH.USER_NAME` | +| `ELASTIC.HTTP_PASSWORD` | `ELASTIC.AUTH.PASSWORD` | +| `ELASTIC.API_KEY` | `ELASTIC.AUTH.API_KEY` | +| `ELASTIC.API_SECRET` | `ELASTIC.AUTH.API_SECRET` | +| `ELASTIC.BEARER_AUTH` | `ELASTIC.AUTH.BEARER` | +| `ELASTIC.CA_CERTS` | `ELASTIC.TLS.CA_CERTS` | +| `ELASTIC.SSL_ASSERT_FINGERPRINT` | `ELASTIC.TLS.ASSERT_FINGERPRINT` | +| `ELASTIC.VERIFY_CERTS` | `ELASTIC.TLS.VERIFY_CERTS` | +| `ELASTIC.CLIENT_CERT` | `ELASTIC.TLS.CLIENT_CERT` | +| `ELASTIC.CLIENT_KEY` | `ELASTIC.TLS.CLIENT_KEY` | +| `ELASTIC.SSL_VERSION` | `ELASTIC.TLS.VERSION` | +| `ELASTIC.SSL_CONTEXT` | `ELASTIC.TLS.CONTEXT` | +| `ELASTIC.MAX_RETRIES` | `ELASTIC.RETRY.MAX_RETRIES` | +| `ELASTIC.RETRY_ON_TIMEOUT` | `ELASTIC.RETRY.ON_TIMEOUT` | +| `ELASTIC.RETRY_ON_STATUS` | `ELASTIC.RETRY.ON_STATUS` | +| `ELASTIC.RETRY_BACKOFF_BASE` | `ELASTIC.RETRY.BACKOFF_BASE` | +| `ELASTIC.RETRY_BACKOFF_CAP` | `ELASTIC.RETRY.BACKOFF_CAP` | +| `ELASTIC.SNIFF_ON_START` | `ELASTIC.SNIFFING.ON_START` | +| `ELASTIC.SNIFF_BEFORE_REQUESTS` | `ELASTIC.SNIFFING.BEFORE_REQUESTS` | +| `ELASTIC.SNIFF_ON_NODE_FAILURE` | `ELASTIC.SNIFFING.ON_NODE_FAILURE` | +| `ELASTIC.MIN_DELAY_BETWEEN_SNIFFING` | `ELASTIC.SNIFFING.MIN_DELAY` | + +### EMAIL + +| 5.x field | 6.0 field | +|-----------|-----------| +| `EMAIL.TLS_MODE` | `EMAIL.TLS.MODE` | +| `EMAIL.TLS_CA_FILE` | `EMAIL.TLS.CA_FILE` | +| `EMAIL.POOL_SIZE` | `EMAIL.POOL.SIZE` | +| `EMAIL.CONNECTION_TIMEOUT` | `EMAIL.POOL.CONNECTION_TIMEOUT` | +| `EMAIL.CONNECTION_REFRESH_SECONDS` | `EMAIL.POOL.CONNECTION_REFRESH_SECONDS` | +| `EMAIL.ATTACHMENT_URL_TIMEOUT` | `EMAIL.ATTACHMENTS.URL_TIMEOUT` | +| `EMAIL.ATTACHMENT_URL_ALLOWED_HOSTS` | `EMAIL.ATTACHMENTS.URL_ALLOWED_HOSTS` | +| `EMAIL.ATTACHMENT_MAX_SIZE` | `EMAIL.ATTACHMENTS.MAX_SIZE` | + +### FASTAPI + +| 5.x field | 6.0 field | +|-----------|-----------| +| `FASTAPI.CORS_MIDDLEWARE_ALLOW_CREDENTIALS` | `FASTAPI.CORS.ALLOW_CREDENTIALS` | +| `FASTAPI.CORS_MIDDLEWARE_ALLOW_HEADERS` | `FASTAPI.CORS.ALLOW_HEADERS` | +| `FASTAPI.CORS_MIDDLEWARE_ALLOW_METHODS` | `FASTAPI.CORS.ALLOW_METHODS` | +| `FASTAPI.CORS_MIDDLEWARE_ALLOW_ORIGIN_REGEX` | `FASTAPI.CORS.ALLOW_ORIGIN_REGEX` | +| `FASTAPI.CORS_MIDDLEWARE_ALLOW_ORIGINS` | `FASTAPI.CORS.ALLOW_ORIGINS` | +| `FASTAPI.CORS_MIDDLEWARE_EXPOSE_HEADERS` | `FASTAPI.CORS.EXPOSE_HEADERS` | +| `FASTAPI.CORS_MIDDLEWARE_MAX_AGE` | `FASTAPI.CORS.MAX_AGE` | +| `FASTAPI.GZIP_MIDDLEWARE_IS_ENABLED` | `FASTAPI.GZIP.IS_ENABLED` | +| `FASTAPI.GZIP_MIDDLEWARE_MINIMUM_SIZE` | `FASTAPI.GZIP.MINIMUM_SIZE` | +| `FASTAPI.GZIP_MIDDLEWARE_COMPRESSLEVEL` | `FASTAPI.GZIP.COMPRESSLEVEL` | +| `FASTAPI.TRUSTED_HOST_MIDDLEWARE_IS_ENABLED` | `FASTAPI.TRUSTED_HOST.IS_ENABLED` | +| `FASTAPI.TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS` | `FASTAPI.TRUSTED_HOST.ALLOWED_HOSTS` | +| `FASTAPI.TRUSTED_HOST_MIDDLEWARE_WWW_REDIRECT` | `FASTAPI.TRUSTED_HOST.WWW_REDIRECT` | +| `FASTAPI.HTTPS_REDIRECT_MIDDLEWARE_IS_ENABLED` | `FASTAPI.HTTPS_REDIRECT.IS_ENABLED` | +| `FASTAPI.ACCESS_LOG` | `UVICORN.ACCESS_LOG` | +| `FASTAPI.BACKLOG` | `UVICORN.LIMITS.BACKLOG` | +| `FASTAPI.DATE_HEADER` | `UVICORN.DATE_HEADER` | +| `FASTAPI.FORWARDED_ALLOW_IPS` | `UVICORN.FORWARDED_ALLOW_IPS` | +| `FASTAPI.LIMIT_CONCURRENCY` | `UVICORN.LIMITS.CONCURRENCY` | +| `FASTAPI.LIMIT_MAX_REQUESTS` | `UVICORN.LIMITS.MAX_REQUESTS` | +| `FASTAPI.PROXY_HEADERS` | `UVICORN.PROXY_HEADERS` | +| `FASTAPI.RELOAD` | `UVICORN.RELOAD` | +| `FASTAPI.SERVER_HEADER` | `UVICORN.SERVER_HEADER` | +| `FASTAPI.TIMEOUT_GRACEFUL_SHUTDOWN` | `UVICORN.TIMEOUT_GRACEFUL_SHUTDOWN` | +| `FASTAPI.TIMEOUT_KEEP_ALIVE` | `UVICORN.TIMEOUT_KEEP_ALIVE` | +| `FASTAPI.WORKERS_COUNT` | `UVICORN.WORKERS_COUNT` | +| `FASTAPI.WS_MAX_SIZE` | `UVICORN.WEBSOCKET.MAX_SIZE` | +| `FASTAPI.WS_PER_MESSAGE_DEFLATE` | `UVICORN.WEBSOCKET.PER_MESSAGE_DEFLATE` | +| `FASTAPI.WS_PING_INTERVAL` | `UVICORN.WEBSOCKET.PING_INTERVAL` | +| `FASTAPI.WS_PING_TIMEOUT` | `UVICORN.WEBSOCKET.PING_TIMEOUT` | + +### GRPC + +| 5.x field | 6.0 field | +|-----------|-----------| +| `GRPC.TLS_ENABLED` | `GRPC.TLS.IS_ENABLED` | +| `GRPC.TLS_CERT_FILE` | `GRPC.TLS.CERT_FILE` | +| `GRPC.TLS_KEY_FILE` | `GRPC.TLS.KEY_FILE` | +| `GRPC.TLS_CA_FILE` | `GRPC.TLS.CA_FILE` | +| `GRPC.TLS_REQUIRE_CLIENT_AUTH` | `GRPC.TLS.REQUIRE_CLIENT_AUTH` | +| `GRPC.STUB_TLS_ENABLED` | `GRPC.STUB_TLS.IS_ENABLED` | +| `GRPC.STUB_TLS_CA_FILE` | `GRPC.STUB_TLS.CA_FILE` | +| `GRPC.STUB_TLS_CERT_FILE` | `GRPC.STUB_TLS.CERT_FILE` | +| `GRPC.STUB_TLS_KEY_FILE` | `GRPC.STUB_TLS.KEY_FILE` | + +### KAFKA + +| 5.x field | 6.0 field | +|-----------|-----------| +| `KAFKA.SASL_MECHANISM` | `KAFKA.SASL.MECHANISM` | +| `KAFKA.USERNAME` | `KAFKA.SASL.USERNAME` | +| `KAFKA.PASSWORD` | `KAFKA.SASL.PASSWORD` | +| `KAFKA.SSL_CA_FILE` | `KAFKA.SSL.CA_FILE` | +| `KAFKA.SSL_CERT_FILE` | `KAFKA.SSL.CERT_FILE` | +| `KAFKA.SSL_KEY_FILE` | `KAFKA.SSL.KEY_FILE` | +| `KAFKA.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM` | `KAFKA.SSL.ENDPOINT_IDENTIFICATION_ALGORITHM` | + +### KEYCLOAK + +| 5.x field | 6.0 field | +|-----------|-----------| +| `KEYCLOAK.IS_ADMIN_MODE_ENABLED` | `KEYCLOAK.ADMIN.IS_ENABLED` | +| `KEYCLOAK.ADMIN_USERNAME` | `KEYCLOAK.ADMIN.USERNAME` | +| `KEYCLOAK.ADMIN_PASSWORD` | `KEYCLOAK.ADMIN.PASSWORD` | +| `KEYCLOAK.ADMIN_REALM_NAME` | `KEYCLOAK.ADMIN.REALM_NAME` | +| `KEYCLOAK.VERIFY_SSL` | `KEYCLOAK.TLS.VERIFY_SSL` | +| `KEYCLOAK.CLIENT_CERT_FILE` | `KEYCLOAK.TLS.CLIENT_CERT_FILE` | +| `KEYCLOAK.CLIENT_KEY_FILE` | `KEYCLOAK.TLS.CLIENT_KEY_FILE` | +| `KEYCLOAK.TOKEN_LEEWAY_SECONDS` | `KEYCLOAK.TOKEN_VALIDATION.LEEWAY_SECONDS` | +| `KEYCLOAK.EXPECTED_ISSUER` | `KEYCLOAK.TOKEN_VALIDATION.EXPECTED_ISSUER` | +| `KEYCLOAK.EXPECTED_AUDIENCE` | `KEYCLOAK.TOKEN_VALIDATION.EXPECTED_AUDIENCE` | +| `KEYCLOAK.REQUIRE_ORGANIZATION` | `KEYCLOAK.TOKEN_VALIDATION.REQUIRE_ORGANIZATION` | + +### OTEL + +| 5.x field | 6.0 field | +|-----------|-----------| +| `OTEL.METRICS_PUSHGATEWAY_URL` | `OTEL.PUSHGATEWAY.URL` | +| `OTEL.METRICS_PUSHGATEWAY_JOB` | `OTEL.PUSHGATEWAY.JOB` | +| `OTEL.METRICS_PUSHGATEWAY_INTERVAL_SECONDS` | `OTEL.PUSHGATEWAY.INTERVAL_SECONDS` | +| `OTEL.METRICS_PUSHGATEWAY_TIMEOUT_SECONDS` | `OTEL.PUSHGATEWAY.TIMEOUT_SECONDS` | +| `OTEL.METRICS_PUSHGATEWAY_GROUPING_KEY` | `OTEL.PUSHGATEWAY.GROUPING_KEY` | +| `OTEL.METRICS_PUSHGATEWAY_DELETE_ON_SHUTDOWN` | `OTEL.PUSHGATEWAY.DELETE_ON_SHUTDOWN` | + +### REDIS + +| 5.x field | 6.0 field | +|-----------|-----------| +| `REDIS.CLUSTER_NODES` | `REDIS.CLUSTER.NODES` | +| `REDIS.CLUSTER_REQUIRE_FULL_COVERAGE` | `REDIS.CLUSTER.REQUIRE_FULL_COVERAGE` | +| `REDIS.CLUSTER_READ_FROM_REPLICAS` | `REDIS.CLUSTER.READ_FROM_REPLICAS` | +| `REDIS.SENTINEL_NODES` | `REDIS.SENTINEL.NODES` | +| `REDIS.SENTINEL_SERVICE_NAME` | `REDIS.SENTINEL.SERVICE_NAME` | +| `REDIS.SENTINEL_SOCKET_TIMEOUT` | `REDIS.SENTINEL.SOCKET_TIMEOUT` | +| `REDIS.SENTINEL_PASSWORD` | `REDIS.SENTINEL.PASSWORD` | +| `REDIS.SENTINEL_USERNAME` | `REDIS.SENTINEL.USERNAME` | +| `REDIS.SSL` | `REDIS.TLS.IS_ENABLED` | +| `REDIS.SSL_CA_CERTS` | `REDIS.TLS.CA_CERTS` | +| `REDIS.SSL_CERTFILE` | `REDIS.TLS.CERTFILE` | +| `REDIS.SSL_KEYFILE` | `REDIS.TLS.KEYFILE` | +| `REDIS.SSL_CHECK_HOSTNAME` | `REDIS.TLS.CHECK_HOSTNAME` | +| `REDIS.RETRY_ATTEMPTS` | `REDIS.RETRY.ATTEMPTS` | +| `REDIS.RETRY_BACKOFF_BASE` | `REDIS.RETRY.BACKOFF_BASE` | +| `REDIS.RETRY_BACKOFF_CAP` | `REDIS.RETRY.BACKOFF_CAP` | +| `REDIS.RETRY_ON_TIMEOUT` | `REDIS.RETRY.ON_TIMEOUT` | + +### SCYLLADB + +| 5.x field | 6.0 field | +|-----------|-----------| +| `SCYLLADB.TLS_ENABLED` | `SCYLLADB.TLS.IS_ENABLED` | +| `SCYLLADB.TLS_CA_FILE` | `SCYLLADB.TLS.CA_FILE` | +| `SCYLLADB.TLS_CERT_FILE` | `SCYLLADB.TLS.CERT_FILE` | +| `SCYLLADB.TLS_KEY_FILE` | `SCYLLADB.TLS.KEY_FILE` | +| `SCYLLADB.TLS_VERIFY_MODE` | `SCYLLADB.TLS.VERIFY_MODE` | +| `SCYLLADB.TLS_CHECK_HOSTNAME` | `SCYLLADB.TLS.CHECK_HOSTNAME` | +| `SCYLLADB.TLS_SERVER_NAME` | `SCYLLADB.TLS.SERVER_NAME` | +| `SCYLLADB.TLS_SESSION_CACHE_ENABLED` | `SCYLLADB.TLS.SESSION_CACHE_ENABLED` | +| `SCYLLADB.RETRY_POLICY` | `SCYLLADB.RETRY.POLICY` | +| `SCYLLADB.RETRY_MAX_NUM_RETRIES` | `SCYLLADB.RETRY.MAX_NUM_RETRIES` | +| `SCYLLADB.RETRY_MIN_INTERVAL` | `SCYLLADB.RETRY.MIN_INTERVAL` | +| `SCYLLADB.RETRY_MAX_INTERVAL` | `SCYLLADB.RETRY.MAX_INTERVAL` | +| `SCYLLADB.RECONNECTION_POLICY` | `SCYLLADB.RECONNECTION.POLICY` | +| `SCYLLADB.RECONNECTION_BASE_DELAY` | `SCYLLADB.RECONNECTION.BASE_DELAY` | +| `SCYLLADB.RECONNECTION_MAX_DELAY` | `SCYLLADB.RECONNECTION.MAX_DELAY` | +| `SCYLLADB.RECONNECTION_MAX_ATTEMPTS` | `SCYLLADB.RECONNECTION.MAX_ATTEMPTS` | +| `SCYLLADB.SPECULATIVE_EXECUTION_DELAY` | `SCYLLADB.SPECULATIVE_EXECUTION.DELAY` | +| `SCYLLADB.SPECULATIVE_EXECUTION_MAX_ATTEMPTS` | `SCYLLADB.SPECULATIVE_EXECUTION.MAX_ATTEMPTS` | +| `SCYLLADB.ENABLE_PREPARED_STATEMENT_CACHE` | `SCYLLADB.PREPARED_CACHE.IS_ENABLED` | +| `SCYLLADB.PREPARED_STATEMENT_CACHE_SIZE` | `SCYLLADB.PREPARED_CACHE.SIZE` | +| `SCYLLADB.PREPARED_STATEMENT_CACHE_TTL_SECONDS` | `SCYLLADB.PREPARED_CACHE.TTL_SECONDS` | +| `SCYLLADB.IDLE_HEARTBEAT_INTERVAL` | `SCYLLADB.HEARTBEAT.IDLE_INTERVAL` | +| `SCYLLADB.IDLE_HEARTBEAT_TIMEOUT` | `SCYLLADB.HEARTBEAT.IDLE_TIMEOUT` | +| `SCYLLADB.REPLICATION_STRATEGY` | `SCYLLADB.REPLICATION.STRATEGY` | +| `SCYLLADB.REPLICATION_CONFIG` | `SCYLLADB.REPLICATION.CONFIG` | + +### SQLALCHEMY + +The same groups apply in `MYSQL_SQLALCHEMY`, `POSTGRES_SQLALCHEMY`, `SQLITE_SQLALCHEMY`, and +`STARROCKS_SQLALCHEMY`. + +| 5.x field | 6.0 field | +|-----------|-----------| +| `SQLALCHEMY.POOL_MAX_OVERFLOW` | `SQLALCHEMY.POOL.MAX_OVERFLOW` | +| `SQLALCHEMY.POOL_PRE_PING` | `SQLALCHEMY.POOL.PRE_PING` | +| `SQLALCHEMY.POOL_RECYCLE_SECONDS` | `SQLALCHEMY.POOL.RECYCLE_SECONDS` | +| `SQLALCHEMY.POOL_RESET_ON_RETURN` | `SQLALCHEMY.POOL.RESET_ON_RETURN` | +| `SQLALCHEMY.POOL_SIZE` | `SQLALCHEMY.POOL.SIZE` | +| `SQLALCHEMY.POOL_TIMEOUT` | `SQLALCHEMY.POOL.TIMEOUT` | +| `SQLALCHEMY.POOL_USE_LIFO` | `SQLALCHEMY.POOL.USE_LIFO` | +| `SQLALCHEMY.COUNT_CACHE_ENABLED` | `SQLALCHEMY.COUNT_CACHE.IS_ENABLED` | +| `SQLALCHEMY.COUNT_CACHE_MAX_SIZE` | `SQLALCHEMY.COUNT_CACHE.MAX_SIZE` | +| `SQLALCHEMY.COUNT_CACHE_TTL_SECONDS` | `SQLALCHEMY.COUNT_CACHE.TTL_SECONDS` | + +### TEMPORAL + +| 5.x field | 6.0 field | +|-----------|-----------| +| `TEMPORAL.TLS_ENABLED` | `TEMPORAL.TLS.IS_ENABLED` | +| `TEMPORAL.TLS_CA_CERT` | `TEMPORAL.TLS.CA_CERT` | +| `TEMPORAL.TLS_CLIENT_CERT` | `TEMPORAL.TLS.CLIENT_CERT` | +| `TEMPORAL.TLS_CLIENT_KEY` | `TEMPORAL.TLS.CLIENT_KEY` | +| `TEMPORAL.TLS_SERVER_NAME` | `TEMPORAL.TLS.SERVER_NAME` | +| `TEMPORAL.TLS_VERIFICATION_SERVER_NAME` | `TEMPORAL.TLS.VERIFICATION_SERVER_NAME` | +| `TEMPORAL.WORKER_GRACEFUL_SHUTDOWN_SECONDS` | `TEMPORAL.WORKER.GRACEFUL_SHUTDOWN_SECONDS` | +| `TEMPORAL.WORKER_MAX_CACHED_WORKFLOWS` | `TEMPORAL.WORKER.MAX_CACHED_WORKFLOWS` | +| `TEMPORAL.WORKER_DEBUG_MODE` | `TEMPORAL.WORKER.DEBUG_MODE` | +| `TEMPORAL.WORKER_MAX_CONCURRENT_LOCAL_ACTIVITIES` | `TEMPORAL.WORKER.MAX_CONCURRENT_LOCAL_ACTIVITIES` | +| `TEMPORAL.WORKER_DISABLE_EAGER_ACTIVITY_EXECUTION` | `TEMPORAL.WORKER.DISABLE_EAGER_ACTIVITY_EXECUTION` | +| `TEMPORAL.WORKER_MAX_EAGER_ACTIVITY_RESERVATIONS` | `TEMPORAL.WORKER.MAX_EAGER_ACTIVITY_RESERVATIONS` | +| `TEMPORAL.WORKER_POLLER_AUTOSCALING` | `TEMPORAL.WORKER.POLLER_AUTOSCALING` | +| `TEMPORAL.WORKER_MAX_ACTIVITIES_PER_SECOND` | `TEMPORAL.WORKER.MAX_ACTIVITIES_PER_SECOND` | +| `TEMPORAL.WORKER_MAX_TASK_QUEUE_ACTIVITIES_PER_SECOND` | `TEMPORAL.WORKER.MAX_TASK_QUEUE_ACTIVITIES_PER_SECOND` | +| `TEMPORAL.CLIENT_RPC_RETRY_MAX_RETRIES` | `TEMPORAL.CLIENT_RETRY.MAX_RETRIES` | +| `TEMPORAL.CLIENT_RPC_RETRY_INITIAL_INTERVAL_MS` | `TEMPORAL.CLIENT_RETRY.INITIAL_INTERVAL_MS` | +| `TEMPORAL.CLIENT_RPC_RETRY_MAX_INTERVAL_MS` | `TEMPORAL.CLIENT_RETRY.MAX_INTERVAL_MS` | +| `TEMPORAL.KEEP_ALIVE_INTERVAL_MS` | `TEMPORAL.KEEP_ALIVE.INTERVAL_MS` | +| `TEMPORAL.KEEP_ALIVE_TIMEOUT_MS` | `TEMPORAL.KEEP_ALIVE.TIMEOUT_MS` | +| `TEMPORAL.WORKFLOW_EXECUTION_TIMEOUT` | `TEMPORAL.WORKFLOW.EXECUTION_TIMEOUT` | +| `TEMPORAL.WORKFLOW_RUN_TIMEOUT` | `TEMPORAL.WORKFLOW.RUN_TIMEOUT` | +| `TEMPORAL.WORKFLOW_TASK_TIMEOUT` | `TEMPORAL.WORKFLOW.TASK_TIMEOUT` | +| `TEMPORAL.WORKFLOW_RETRY_ENABLED` | `TEMPORAL.WORKFLOW.RETRY_ENABLED` | +| `TEMPORAL.ACTIVITY_START_TO_CLOSE_TIMEOUT` | `TEMPORAL.ACTIVITY.START_TO_CLOSE_TIMEOUT` | +| `TEMPORAL.ACTIVITY_HEARTBEAT_TIMEOUT` | `TEMPORAL.ACTIVITY.HEARTBEAT_TIMEOUT` | +| `TEMPORAL.RETRY_MAXIMUM_ATTEMPTS` | `TEMPORAL.RETRY.MAXIMUM_ATTEMPTS` | +| `TEMPORAL.RETRY_BACKOFF_COEFFICIENT` | `TEMPORAL.RETRY.BACKOFF_COEFFICIENT` | +| `TEMPORAL.RETRY_MAXIMUM_INTERVAL` | `TEMPORAL.RETRY.MAXIMUM_INTERVAL` | +| `TEMPORAL.RETRY_INITIAL_INTERVAL` | `TEMPORAL.RETRY.INITIAL_INTERVAL` | +| `TEMPORAL.RETRY_NON_RETRYABLE_ERROR_TYPES` | `TEMPORAL.RETRY.NON_RETRYABLE_ERROR_TYPES` | + +### UVICORN + +| 5.x field | 6.0 field | +|-----------|-----------| +| `UVICORN.SSL_KEYFILE` | `UVICORN.TLS.KEYFILE` | +| `UVICORN.SSL_CERTFILE` | `UVICORN.TLS.CERTFILE` | +| `UVICORN.SSL_CA_CERTS` | `UVICORN.TLS.CA_CERTS` | +| `UVICORN.WS_MAX_SIZE` | `UVICORN.WEBSOCKET.MAX_SIZE` | +| `UVICORN.WS_PER_MESSAGE_DEFLATE` | `UVICORN.WEBSOCKET.PER_MESSAGE_DEFLATE` | +| `UVICORN.WS_PING_INTERVAL` | `UVICORN.WEBSOCKET.PING_INTERVAL` | +| `UVICORN.WS_PING_TIMEOUT` | `UVICORN.WEBSOCKET.PING_TIMEOUT` | +| `UVICORN.BACKLOG` | `UVICORN.LIMITS.BACKLOG` | +| `UVICORN.LIMIT_CONCURRENCY` | `UVICORN.LIMITS.CONCURRENCY` | +| `UVICORN.LIMIT_MAX_REQUESTS` | `UVICORN.LIMITS.MAX_REQUESTS` | + +### VAULT + +| 5.x field | 6.0 field | +|-----------|-----------| +| `VAULT.APPROLE_ROLE_ID` | `VAULT.APPROLE.ROLE_ID` | +| `VAULT.APPROLE_SECRET_ID` | `VAULT.APPROLE.SECRET_ID` | +| `VAULT.APPROLE_SECRET_ID_FILE` | `VAULT.APPROLE.SECRET_ID_FILE` | +| `VAULT.APPROLE_MOUNT_POINT` | `VAULT.APPROLE.MOUNT_POINT` | +| `VAULT.KUBERNETES_ROLE` | `VAULT.KUBERNETES.ROLE` | +| `VAULT.KUBERNETES_JWT_PATH` | `VAULT.KUBERNETES.JWT_PATH` | +| `VAULT.KUBERNETES_MOUNT_POINT` | `VAULT.KUBERNETES.MOUNT_POINT` | +| `VAULT.USERPASS_MOUNT_POINT` | `VAULT.USERPASS.MOUNT_POINT` | +| `VAULT.LDAP_MOUNT_POINT` | `VAULT.LDAP.MOUNT_POINT` | +| `VAULT.OKTA_MOUNT_POINT` | `VAULT.OKTA.MOUNT_POINT` | +| `VAULT.JWT_ROLE` | `VAULT.JWT_AUTH.ROLE` | +| `VAULT.JWT` | `VAULT.JWT_AUTH.JWT` | +| `VAULT.JWT_FILE` | `VAULT.JWT_AUTH.JWT_FILE` | +| `VAULT.JWT_MOUNT_POINT` | `VAULT.JWT_AUTH.MOUNT_POINT` | +| `VAULT.AWS_ACCESS_KEY` | `VAULT.AWS.ACCESS_KEY` | +| `VAULT.AWS_SECRET_KEY` | `VAULT.AWS.SECRET_KEY` | +| `VAULT.AWS_SESSION_TOKEN` | `VAULT.AWS.SESSION_TOKEN` | +| `VAULT.AWS_ROLE` | `VAULT.AWS.ROLE` | +| `VAULT.AWS_REGION` | `VAULT.AWS.REGION` | +| `VAULT.AWS_MOUNT_POINT` | `VAULT.AWS.MOUNT_POINT` | +| `VAULT.AZURE_ROLE` | `VAULT.AZURE.ROLE` | +| `VAULT.AZURE_JWT` | `VAULT.AZURE.JWT` | +| `VAULT.AZURE_JWT_FILE` | `VAULT.AZURE.JWT_FILE` | +| `VAULT.AZURE_SUBSCRIPTION_ID` | `VAULT.AZURE.SUBSCRIPTION_ID` | +| `VAULT.AZURE_RESOURCE_GROUP_NAME` | `VAULT.AZURE.RESOURCE_GROUP_NAME` | +| `VAULT.AZURE_VM_NAME` | `VAULT.AZURE.VM_NAME` | +| `VAULT.AZURE_VMSS_NAME` | `VAULT.AZURE.VMSS_NAME` | +| `VAULT.AZURE_MOUNT_POINT` | `VAULT.AZURE.MOUNT_POINT` | +| `VAULT.GCP_ROLE` | `VAULT.GCP.ROLE` | +| `VAULT.GCP_JWT` | `VAULT.GCP.JWT` | +| `VAULT.GCP_JWT_FILE` | `VAULT.GCP.JWT_FILE` | +| `VAULT.GCP_MOUNT_POINT` | `VAULT.GCP.MOUNT_POINT` | +| `VAULT.GITHUB_TOKEN` | `VAULT.GITHUB.TOKEN` | +| `VAULT.GITHUB_TOKEN_FILE` | `VAULT.GITHUB.TOKEN_FILE` | +| `VAULT.GITHUB_MOUNT_POINT` | `VAULT.GITHUB.MOUNT_POINT` | +| `VAULT.CERT_NAME` | `VAULT.CERT.NAME` | +| `VAULT.CERT_MOUNT_POINT` | `VAULT.CERT.MOUNT_POINT` | +| `VAULT.VERIFY_SSL` | `VAULT.TLS.VERIFY_SSL` | +| `VAULT.CA_CERT_PATH` | `VAULT.TLS.CA_CERT_PATH` | +| `VAULT.CLIENT_CERT_PATH` | `VAULT.TLS.CLIENT_CERT_PATH` | +| `VAULT.CLIENT_KEY_PATH` | `VAULT.TLS.CLIENT_KEY_PATH` | +| `VAULT.CONNECT_TIMEOUT` | `VAULT.HTTP.CONNECT_TIMEOUT` | +| `VAULT.READ_TIMEOUT` | `VAULT.HTTP.READ_TIMEOUT` | +| `VAULT.RETRIES_MAX_ATTEMPTS` | `VAULT.HTTP.RETRIES_MAX_ATTEMPTS` | +| `VAULT.AUTO_RENEW_TOKEN` | `VAULT.TOKEN_RENEWAL.AUTO_RENEW_TOKEN` | +| `VAULT.RENEW_THRESHOLD_SECONDS` | `VAULT.TOKEN_RENEWAL.RENEW_THRESHOLD_SECONDS` | diff --git a/docs/community/faq.md b/docs/community/faq.md index 1a6418ea3..5f9749c6d 100644 --- a/docs/community/faq.md +++ b/docs/community/faq.md @@ -251,8 +251,8 @@ class AppConfig(BaseConfig): | `@timing` | Execution time logging | | `@method_deprecation_warning` | Deprecation warning | -All are imported from `archipy.helpers.decorators` and work for sync and `async def` functions. The older -`*_decorator` and `async_*` names still work but emit a `DeprecationWarning`; they will be removed in 6.0.0. +Import atomic decorators from `archipy.adapters.base.sqlalchemy.atomic` and the other decorators from +`archipy.helpers.decorators`. See the [Decorators tutorial](../tutorials/helpers/decorators.md) for examples. diff --git a/docs/tutorials/adapters/elasticsearch.md b/docs/tutorials/adapters/elasticsearch.md index 046e1eb94..eb9cbd2cd 100644 --- a/docs/tutorials/adapters/elasticsearch.md +++ b/docs/tutorials/adapters/elasticsearch.md @@ -25,7 +25,7 @@ Configure Elasticsearch via environment variables or an `ElasticsearchConfig` ob ### Environment Variables !!! warning - Keep `ELASTIC__HTTP_PASSWORD` and `ELASTIC__API_SECRET` out of source control. Prefer API key authentication over + Keep `ELASTIC__AUTH__PASSWORD` and `ELASTIC__AUTH__API_SECRET` out of source control. Prefer API key authentication over basic auth. !!! note @@ -42,15 +42,15 @@ Configure Elasticsearch via environment variables or an `ElasticsearchConfig` ob ELASTIC__HOSTS='["https://localhost:9200"]' # Basic auth (alternative to API key) -ELASTIC__HTTP_USER_NAME=elastic -ELASTIC__HTTP_PASSWORD=your-password +ELASTIC__AUTH__USER_NAME=elastic +ELASTIC__AUTH__PASSWORD=your-password # API key auth (preferred over basic auth) -ELASTIC__API_KEY=your-api-key-id -ELASTIC__API_SECRET=your-api-key-secret +ELASTIC__AUTH__API_KEY=your-api-key-id +ELASTIC__AUTH__API_SECRET=your-api-key-secret # Bearer token / OIDC auth (exclusive with API key and basic auth) -ELASTIC__BEARER_AUTH=your-token +ELASTIC__AUTH__BEARER=your-token # Elastic Cloud (replaces HOSTS) ELASTIC__CLOUD_ID=name:base64-cloud-id @@ -60,23 +60,22 @@ ELASTIC__OPAQUE_ID=billing-service # sent as X-Opaque-Id ELASTIC__HEADERS='{"X-Team": "core"}' # TLS/SSL -ELASTIC__SSL_VERSION=772 # ssl.TLSVersion value (772 = TLS 1.3) -ELASTIC__CA_CERTS=/path/to/ca.crt -ELASTIC__VERIFY_CERTS=true +ELASTIC__TLS__VERSION=772 # ssl.TLSVersion value (772 = TLS 1.3) +ELASTIC__TLS__CA_CERTS=/path/to/ca.crt +ELASTIC__TLS__VERIFY_CERTS=true # Raise ArchiPy errors instead of raw elasticsearch-py exceptions (default false, will become true) -ELASTIC__MAP_ERRORS=true # Connection behaviour ELASTIC__REQUEST_TIMEOUT=5.0 -ELASTIC__MAX_RETRIES=3 -ELASTIC__RETRY_ON_TIMEOUT=true +ELASTIC__RETRY__MAX_RETRIES=3 +ELASTIC__RETRY__ON_TIMEOUT=true # Node pool and sniffing ELASTIC__NODE_SELECTOR_CLASS=random # 'round_robin' (default) or 'random' ELASTIC__DEAD_NODE_BACKOFF_FACTOR=1.0 ELASTIC__MAX_DEAD_NODE_BACKOFF=300.0 -ELASTIC__MIN_DELAY_BETWEEN_SNIFFING=60.0 # applied when SNIFF_BEFORE_REQUESTS=true +ELASTIC__SNIFFING__MIN_DELAY=60.0 # applied when SNIFF_BEFORE_REQUESTS=true ELASTIC__IGNORE_STATUS='[404]' # status codes not raised as errors ``` @@ -95,16 +94,11 @@ try: es_config = ElasticsearchConfig( HOSTS=["https://localhost:9200"], # API key auth (takes precedence over HTTP basic auth) - API_KEY="my-key-id", - API_SECRET="my-key-secret", # type: ignore[arg-type] + AUTH={"API_KEY": "my-key-id", "API_SECRET": "my-key-secret"}, TLS={"CA_CERTS": "/path/to/ca.crt", "VERIFY_CERTS": True}, RETRY={"MAX_RETRIES": 3, "ON_TIMEOUT": True, "ON_STATUS": (429, 502, 503, 504)}, + # type: ignore[arg-type] # TLS - CA_CERTS="/path/to/ca.crt", - VERIFY_CERTS=True, # Timeouts and retries REQUEST_TIMEOUT=5.0, - MAX_RETRIES=3, - RETRY_ON_TIMEOUT=True, - RETRY_ON_STATUS=(429, 502, 503, 504), # Connection pool CONNECTIONS_PER_NODE=10, HTTP_COMPRESS=True, @@ -126,9 +120,7 @@ needs both values to back off. ### Error Mapping -By default the adapters raise raw `elasticsearch` exceptions (`NotFoundError`, `ApiError`, `ConnectionError`), and -creating an adapter with `MAP_ERRORS=False` emits a `DeprecationWarning` because mapping will become the default. -Set `ELASTIC__MAP_ERRORS=true` to get ArchiPy errors, chained from the original exception: +The adapters map Elasticsearch API and transport failures to ArchiPy errors and chain the original exception. | Elasticsearch failure | ArchiPy error | |-----------------------|---------------| diff --git a/docs/tutorials/adapters/email.md b/docs/tutorials/adapters/email.md index 508ef17b4..0acdb94f7 100644 --- a/docs/tutorials/adapters/email.md +++ b/docs/tutorials/adapters/email.md @@ -24,47 +24,34 @@ Configure the email adapter via environment variables or an `EmailConfig` object Keep `EMAIL__PASSWORD` out of source control. Load it from the environment or a secrets store. !!! note - `EMAIL__CONNECTION_TIMEOUT` defaults to `30` seconds. Pooled connections idle longer than - `EMAIL__CONNECTION_REFRESH_SECONDS` are reconnected. + `EMAIL__POOL__CONNECTION_TIMEOUT` defaults to `30` seconds. Pooled connections idle longer than + `EMAIL__POOL__CONNECTION_REFRESH_SECONDS` are reconnected. ```bash EMAIL__SMTP_SERVER=smtp.example.com EMAIL__SMTP_PORT=587 EMAIL__USERNAME=your-username EMAIL__PASSWORD=your-password -EMAIL__POOL_SIZE=5 # at least 1 +EMAIL__POOL__SIZE=5 # at least 1 EMAIL__FROM_ADDRESS=noreply@example.org # defaults to USERNAME; set it when USERNAME is not an address -EMAIL__CONNECTION_TIMEOUT=30 # seconds, greater than 0 -EMAIL__CONNECTION_REFRESH_SECONDS=300 # reconnect pooled connections idle longer than this -EMAIL__TLS_MODE=starttls # auto (deprecated), none, starttls or implicit -EMAIL__TLS_CA_FILE=/etc/ssl/smtp-ca.pem # optional CA bundle that verifies the server -EMAIL__TLS_VERIFY=true +EMAIL__POOL__CONNECTION_TIMEOUT=30 # seconds, greater than 0 +EMAIL__POOL__CONNECTION_REFRESH_SECONDS=300 # reconnect pooled connections idle longer than this +EMAIL__TLS__MODE=starttls # starttls (default), implicit or none +EMAIL__TLS__CA_FILE=/etc/ssl/smtp-ca.pem # optional CA bundle that verifies the server ``` ### Transport Security -`EMAIL__TLS_MODE` selects how the SMTP session is protected: +`EMAIL__TLS__MODE` selects how the SMTP session is protected: -| Mode | Behavior | -|------------|-----------------------------------------------------------------------------------------------| -| `starttls` | Requires the server to offer STARTTLS and the upgrade to succeed; never falls back to clear text. | -| `implicit` | Opens a TLS connection from the start (SMTPS, usually port 465). | -| `none` | Sends in clear text, only for trusted networks. | -| `auto` | Default, deprecated: upgrades only if STARTTLS is offered, without verifying the certificate. | +| Mode | Behavior | +|------|----------| +| `starttls` | Default. Requires the server to offer STARTTLS and the upgrade to succeed. | +| `implicit` | Opens a TLS connection from the start (SMTPS, usually port 465). | +| `none` | Allows unauthenticated SMTP in clear text. | -`starttls` and `implicit` verify the certificate and host name against the system CAs, or against -`EMAIL__TLS_CA_FILE` when set. `EMAIL__TLS_VERIFY=false` turns verification off. - -!!! warning - `auto` keeps the previous behavior and emits a `DeprecationWarning`. Set `EMAIL__TLS_MODE` - explicitly; the default will change in a future major release. - -`TLS_MODE=none` with credentials and `TLS_VERIFY=false` each emit a `DeprecationWarning` (clear-text login -and unverified certificates expose credentials to interception); both will be rejected in a future major -release. A login over a session without TLS is also logged as a warning. - -`USERNAME` and `PASSWORD` must be set together. A half-set pair raises `ConfigurationError` when -`TLS_MODE` is not `auto`; in `auto` mode login is skipped with a `DeprecationWarning`. +Both TLS modes verify the certificate and hostname using system CAs or the bundle specified by `EMAIL__TLS__CA_FILE`. +Set `USERNAME` and `PASSWORD` together. SMTP authentication requires either `starttls` or `implicit`. `EMAIL__LOCAL_HOSTNAME` sets the name sent in `EHLO`, and `EMAIL__SOURCE_ADDRESS` with `EMAIL__SOURCE_PORT` binds the local end of the connection. @@ -377,8 +364,8 @@ rejections are not retried. A header that cannot be encoded (for example a subje ### URL Attachments -URL attachments accept `http` and `https` only, are downloaded with the `EMAIL__ATTACHMENT_URL_TIMEOUT` -timeout, and stop once `ATTACHMENT_MAX_SIZE` is exceeded. Set `EMAIL__ATTACHMENT_URL_ALLOWED_HOSTS` when the +URL attachments accept `http` and `https` only, are downloaded with the `EMAIL__ATTACHMENTS__URL_TIMEOUT` +timeout, and stop once `ATTACHMENT_MAX_SIZE` is exceeded. Set `EMAIL__ATTACHMENTS__URL_ALLOWED_HOSTS` when the URL can come from user input, to avoid server-side request forgery. ## See Also diff --git a/docs/tutorials/adapters/kafka.md b/docs/tutorials/adapters/kafka.md index c334cd030..5d59a98ed 100644 --- a/docs/tutorials/adapters/kafka.md +++ b/docs/tutorials/adapters/kafka.md @@ -29,35 +29,42 @@ KAFKA__ACKS=all KAFKA__AUTO_OFFSET_RESET=earliest ``` +The `KAFKA.SSL` group configures TLS using librdkafka options named `ssl.*`. + ### Direct Configuration !!! warning - With `SECURITY_PROTOCOL` set to `SASL_PLAINTEXT` or `SASL_SSL`, `SASL_MECHANISM` is required, and `USERNAME` and - `PASSWORD` are required for `PLAIN`, `SCRAM-SHA-256` and `SCRAM-SHA-512`. `GSSAPI` and `OAUTHBEARER` need no + With `SECURITY_PROTOCOL` set to `SASL_PLAINTEXT` or `SASL_SSL`, `SASL.MECHANISM` is required, and `SASL.USERNAME` and + `SASL.PASSWORD` are required for `PLAIN`, `SCRAM-SHA-256` and `SCRAM-SHA-512`. `GSSAPI` and `OAUTHBEARER` need no username or password. Load the password from the environment or a secrets store, not from source code. Each security setting is applied when it is set, based on `SECURITY_PROTOCOL`: SASL settings for the `SASL_*` - protocols, and `SSL_CA_FILE`, `SSL_CERT_FILE`, `SSL_KEY_FILE` for `SSL` and `SASL_SSL`. mTLS without SASL works - with `SECURITY_PROTOCOL="SSL"` and a certificate and key; leave `SSL_CA_FILE` unset to use the system CA store. + protocols, and `SSL.CA_FILE`, `SSL.CERT_FILE`, `SSL.KEY_FILE` for `SSL` and `SASL_SSL`. mTLS without SASL works + with `SECURITY_PROTOCOL="SSL"` and a certificate and key; leave `SSL.CA_FILE` unset to use the system CA store. ```python +import os + from archipy.configs.config_template import KafkaConfig config = KafkaConfig( BROKERS_LIST=["kafka1:9092", "kafka2:9092"], CLIENT_ID="my-app", SECURITY_PROTOCOL="SASL_SSL", - SASL_MECHANISM="PLAIN", - USERNAME="kafka-user", + SASL={ + "MECHANISM": "PLAIN", + "USERNAME": "kafka-user", + "PASSWORD": os.environ["KAFKA__SASL__PASSWORD"], + }, ) ``` !!! warning "Broker hostname verification is on by default" With `SECURITY_PROTOCOL` set to `SSL` or `SASL_SSL`, the adapters verify that each broker certificate matches the broker - hostname (`SSL_ENDPOINT_IDENTIFICATION_ALGORITHM="https"`, the default). Earlier releases turned this check off. + hostname (`SSL.ENDPOINT_IDENTIFICATION_ALGORITHM="https"`, the default). Earlier releases turned this check off. Brokers reached by IP address, or whose certificate SAN does not list the address you connect to, now fail the TLS handshake. Fix the certificates if you can. To keep the old behavior, set - `SSL_ENDPOINT_IDENTIFICATION_ALGORITHM="none"` (or `KAFKA__SSL_ENDPOINT_IDENTIFICATION_ALGORITHM=none`); a warning + `SSL.ENDPOINT_IDENTIFICATION_ALGORITHM="none"` (or `KAFKA__SSL__ENDPOINT_IDENTIFICATION_ALGORITHM=none`); a warning is logged because this leaves connections open to man-in-the-middle attacks. ### Connection, Identity and Timeout Settings @@ -180,7 +187,7 @@ else: Other combinations raise a `ConfigurationError` when the config is validated. !!! note - `SECURITY_PROTOCOL` and `SASL_MECHANISM` are case-insensitive (`ssl` equals `SSL`). `SECURITY_PROTOCOL` must be + `SECURITY_PROTOCOL` and `SASL.MECHANISM` are case-insensitive (`ssl` equals `SSL`). `SECURITY_PROTOCOL` must be `PLAINTEXT`, `SSL`, `SASL_PLAINTEXT` or `SASL_SSL`; any other value raises a `ConfigurationError`. ```python @@ -209,8 +216,7 @@ except InternalError as e: else: logger.info("Message enqueued successfully") -# Publish with a message key (for partition affinity). Without a key the message is currently sent with an empty -# key (b""), which emits a DeprecationWarning; set KAFKA.EMPTY_KEY_FOR_MISSING_KEY=False to send no key (None). +# Publish with a message key for partition affinity. Omitting the key sends a keyless message. try: producer.produce("Hello, Kafka with key!", key="user-123") except InternalError as e: diff --git a/docs/tutorials/adapters/keycloak.md b/docs/tutorials/adapters/keycloak.md index d92bac65c..129a17dcc 100644 --- a/docs/tutorials/adapters/keycloak.md +++ b/docs/tutorials/adapters/keycloak.md @@ -24,28 +24,27 @@ Configure the Keycloak adapter via environment variables or a `KeycloakConfig` o !!! warning Keep `KEYCLOAK__CLIENT_SECRET_KEY` out of source control. Load it from the environment or a secrets store, and keep - `KEYCLOAK__VERIFY_SSL=true` outside local development. + `KEYCLOAK__TLS__VERIFY_SSL=true` outside local development. ```bash KEYCLOAK__SERVER_URL=https://keycloak.example.com KEYCLOAK__REALM_NAME=my-realm KEYCLOAK__CLIENT_ID=my-client KEYCLOAK__CLIENT_SECRET_KEY=client-secret -KEYCLOAK__VERIFY_SSL=true # true, false, or the path of a CA bundle for a private CA +KEYCLOAK__TLS__VERIFY_SSL=true # true, false, or the path of a CA bundle for a private CA KEYCLOAK__TIMEOUT=10 # seconds, fractions allowed (2.5) -KEYCLOAK__REQUIRE_ORGANIZATION=false # guards allow personal and wildcard organization contexts by default -KEYCLOAK__TOKEN_LEEWAY_SECONDS=0 # clock-skew tolerance when validating token expiry -KEYCLOAK__EXPECTED_ISSUER=https://keycloak.example.com/realms/my-realm # enforce the iss claim (and typ=Bearer) of locally verified tokens -KEYCLOAK__EXPECTED_AUDIENCE=my-client # enforce the aud claim (and typ=Bearer) of locally verified tokens +KEYCLOAK__TOKEN_VALIDATION__REQUIRE_ORGANIZATION=false # guards allow personal and wildcard organization contexts by default +KEYCLOAK__TOKEN_VALIDATION__LEEWAY_SECONDS=0 # clock-skew tolerance when validating token expiry +KEYCLOAK__TOKEN_VALIDATION__EXPECTED_ISSUER=https://keycloak.example.com/realms/my-realm # enforce the iss claim (and typ=Bearer) of locally verified tokens +KEYCLOAK__TOKEN_VALIDATION__EXPECTED_AUDIENCE=my-client # require this audience in locally verified tokens KEYCLOAK__REMOTE_CACHE_TTL_SECONDS=0 # opt-in cache for the keycloak auth guards' UserInfo/permission lookups (0 = off) ``` -!!! warning "Token claim checks" - Local verification (`validate_token`, `get_token_info`, role checks) always checks the signature and expiry. Set - `KEYCLOAK__EXPECTED_ISSUER` and/or `KEYCLOAK__EXPECTED_AUDIENCE` to also require the `iss` / `aud` claims and - `typ == "Bearer"`; mismatching tokens are rejected (`validate_token` returns `False`, `get_token_info` raises - `InvalidTokenError`). Without these settings a mismatch only emits a `DeprecationWarning`, and enforcement becomes - the default in 6.0. +Local verification checks the token signature, expiry, issuer, and `typ == "Bearer"`. The issuer defaults to +`{SERVER_URL}/realms/{REALM_NAME}`. Set `KEYCLOAK__TOKEN_VALIDATION__EXPECTED_ISSUER` if Keycloak issues tokens under a +different URL, such as a public hostname in front of an internal connection. Set +`KEYCLOAK__TOKEN_VALIDATION__EXPECTED_AUDIENCE` to enforce the `aud` claim. A rejected token makes `validate_token` +return `False` and `get_token_info` raise `InvalidTokenError`. ### Connection Options @@ -64,9 +63,9 @@ previous behaviour. | `CUSTOM_HEADERS` | none | Extra headers sent with every request | ```bash -KEYCLOAK__VERIFY_SSL=/etc/ssl/private-ca.pem -KEYCLOAK__CLIENT_CERT_FILE=/etc/ssl/client.pem -KEYCLOAK__CLIENT_KEY_FILE=/etc/ssl/client.key +KEYCLOAK__TLS__VERIFY_SSL=/etc/ssl/private-ca.pem +KEYCLOAK__TLS__CLIENT_CERT_FILE=/etc/ssl/client.pem +KEYCLOAK__TLS__CLIENT_KEY_FILE=/etc/ssl/client.key KEYCLOAK__PROXIES='{"https://": "http://proxy:3128"}' KEYCLOAK__CUSTOM_HEADERS='{"X-Tenant": "acme"}' ``` @@ -86,7 +85,7 @@ config = KeycloakConfig( REALM_NAME="my-realm", CLIENT_ID="my-client", CLIENT_SECRET_KEY="client-secret", # noqa: S105 - VERIFY_SSL=True, + TLS={"VERIFY_SSL": True}, TIMEOUT=10, ) ``` @@ -573,10 +572,6 @@ group = keycloak.get_group(group_id) logger.info("Group %s at %s", group.name, group.path) ``` -!!! warning "Deprecated: dicts" - Passing a `dict` payload and reading results with `result["key"]` or `result.get("key")` still work but emit a - `DeprecationWarning`. Both are removed in 6.0.0. See [Create Results and Ids](#create-results-and-ids). - ### Resources Overview Both adapters expose one method group per Keycloak resource area. Every method exists on `KeycloakAdapter` and, as a @@ -744,10 +739,6 @@ if result.id is None: logger.info("Provider skipped: %s", result.msg) ``` -!!! warning "Deprecated: dicts" - Dict payloads and dict-style reads (`result["id"]`, `result.get("id")`) still work but emit a `DeprecationWarning`. - They are removed in 6.0.0. Use the request DTOs and the attributes of the response DTOs. - ### Error Mapping The adapter maps Keycloak failures to ArchiPy errors, chained with `from`. A `404` raises `ResourceNotFoundError`, @@ -823,7 +814,7 @@ client or logs in to Keycloak. - For production use, prefer the authorization code flow over direct username/password authentication. - The auth guards' role checks read `realm_access` and `resource_access` from the UserInfo response. Stock Keycloak omits them there, so enable "Add to userinfo" on the realm roles and client roles mappers of the `roles` client scope. -- Token expiry is checked locally with `KEYCLOAK__TOKEN_LEEWAY_SECONDS` (default `0`) of clock-skew tolerance; raise it +- Token expiry is checked locally with `KEYCLOAK__TOKEN_VALIDATION__LEEWAY_SECONDS` (default `0`) of clock-skew tolerance; raise it only if your servers' clocks drift. - The auth guards call Keycloak for UserInfo (and UMA permissions) on every request. Set `KEYCLOAK__REMOTE_CACHE_TTL_SECONDS` to a few seconds to cache those lookups per access token. A revoked token or a @@ -851,7 +842,7 @@ token" and "Add to ID token" off to keep tokens minimal. UserInfo carries the or - Multiple organization IDs without the wildcard scope are denied. - Invalid organization field types or UUIDs fail UserInfo DTO validation. -Organizations are optional by default. Set `KEYCLOAK__REQUIRE_ORGANIZATION=true` to require a selected organization +Organizations are optional by default. Set `KEYCLOAK__TOKEN_VALIDATION__REQUIRE_ORGANIZATION=true` to require a selected organization across both guards. Pass `require_organization=True` or `False` to override this setting for a specific guard; omitting the argument inherits the configuration. Requiring an organization rejects personal and wildcard contexts. The verified token's `scope` claim distinguishes diff --git a/docs/tutorials/adapters/mysql.md b/docs/tutorials/adapters/mysql.md index 0cdf75250..6c1e9c5ba 100644 --- a/docs/tutorials/adapters/mysql.md +++ b/docs/tutorials/adapters/mysql.md @@ -33,7 +33,7 @@ MYSQL_SQLALCHEMY__PORT=3306 MYSQL_SQLALCHEMY__USERNAME=root MYSQL_SQLALCHEMY__PASSWORD=password MYSQL_SQLALCHEMY__DATABASE=app_db -MYSQL_SQLALCHEMY__POOL_SIZE=20 +MYSQL_SQLALCHEMY__POOL__SIZE=20 MYSQL_SQLALCHEMY__ECHO=false ``` diff --git a/docs/tutorials/adapters/postgres.md b/docs/tutorials/adapters/postgres.md index 29653f496..d23708d65 100644 --- a/docs/tutorials/adapters/postgres.md +++ b/docs/tutorials/adapters/postgres.md @@ -36,10 +36,10 @@ POSTGRES_SQLALCHEMY__PASSWORD=secret POSTGRES_SQLALCHEMY__POSTGRES_DSN=postgresql+psycopg://myuser:secret@localhost:5432/mydb # Connection pool -POSTGRES_SQLALCHEMY__POOL_SIZE=20 -POSTGRES_SQLALCHEMY__POOL_MAX_OVERFLOW=5 -POSTGRES_SQLALCHEMY__POOL_TIMEOUT=30 -POSTGRES_SQLALCHEMY__POOL_RECYCLE_SECONDS=600 +POSTGRES_SQLALCHEMY__POOL__SIZE=20 +POSTGRES_SQLALCHEMY__POOL__MAX_OVERFLOW=5 +POSTGRES_SQLALCHEMY__POOL__TIMEOUT=30 +POSTGRES_SQLALCHEMY__POOL__RECYCLE_SECONDS=600 # SQL logging (useful for debugging) POSTGRES_SQLALCHEMY__ECHO=false @@ -102,12 +102,7 @@ try: USERNAME="myuser", PASSWORD="secret", # Pool settings - POOL_SIZE=20, - POOL_MAX_OVERFLOW=5, - POOL_TIMEOUT=30, - POOL_RECYCLE_SECONDS=600, - POOL_USE_LIFO=True, - POOL_PRE_PING=True, + POOL={"SIZE": 20, "MAX_OVERFLOW": 5, "TIMEOUT": 30, "RECYCLE_SECONDS": 600, "USE_LIFO": True, "PRE_PING": True}, # Isolation level ISOLATION_LEVEL="REPEATABLE READ", ) @@ -911,12 +906,12 @@ api_config = PostgresSQLAlchemyConfig( DATABASE="mydb", USERNAME="myuser", PASSWORD="secret", - POOL_SIZE=20, # Keep 20 persistent connections open - POOL_MAX_OVERFLOW=10, # Allow up to 10 additional overflow connections - POOL_TIMEOUT=5, # Fail fast if pool is exhausted (5 s) - POOL_RECYCLE_SECONDS=300, # Recycle connections every 5 min (avoids stale TCP) - POOL_PRE_PING=True, # Validate connections before use - POOL_USE_LIFO=True, # LIFO: reuse warm connections, keep cold ones idle + POOL={"SIZE": 20, "MAX_OVERFLOW": 10, "TIMEOUT": 5, "RECYCLE_SECONDS": 300, "PRE_PING": True, "USE_LIFO": True}, # Keep 20 persistent connections open + # Allow up to 10 additional overflow connections + # Fail fast if pool is exhausted (5 s) + # Recycle connections every 5 min (avoids stale TCP) + # Validate connections before use + # LIFO: reuse warm connections, keep cold ones idle ) # Batch/worker process — smaller pool @@ -926,9 +921,7 @@ worker_config = PostgresSQLAlchemyConfig( DATABASE="mydb", USERNAME="myuser", PASSWORD="secret", - POOL_SIZE=5, - POOL_MAX_OVERFLOW=2, - POOL_TIMEOUT=30, + POOL={"SIZE": 5, "MAX_OVERFLOW": 2, "TIMEOUT": 30}, ) ``` @@ -958,7 +951,7 @@ loaded attributes readable after the commit. ### Pool exhaustion (`QueuePool limit exceeded`) -- Increase `POOL_SIZE` and/or `POOL_MAX_OVERFLOW`. +- Increase `POOL.SIZE` and/or `POOL.MAX_OVERFLOW`. - Reduce transaction scope — avoid holding sessions open during slow external calls. - Reduce `POOL_TIMEOUT` to fail fast and surface exhaustion early rather than queuing indefinitely. diff --git a/docs/tutorials/adapters/redis.md b/docs/tutorials/adapters/redis.md index eb1cc5f97..dd3795ec6 100644 --- a/docs/tutorials/adapters/redis.md +++ b/docs/tutorials/adapters/redis.md @@ -53,11 +53,11 @@ Managed Redis often requires TLS and an ACL user. The settings apply to standalo ```bash REDIS__USERNAME=app-user REDIS__PASSWORD=your-password -REDIS__SSL=true -REDIS__SSL_CA_CERTS=/certs/ca.pem -REDIS__SSL_CERTFILE=/certs/client.pem # mTLS only, requires SSL_KEYFILE -REDIS__SSL_KEYFILE=/certs/client.key -REDIS__SSL_CHECK_HOSTNAME=true +REDIS__TLS__IS_ENABLED=true +REDIS__TLS__CA_CERTS=/certs/ca.pem +REDIS__TLS__CERTFILE=/certs/client.pem # mTLS only, requires SSL_KEYFILE +REDIS__TLS__KEYFILE=/certs/client.key +REDIS__TLS__CHECK_HOSTNAME=true ``` `SSL_CERTFILE` and `SSL_KEYFILE` must be set together. `SSL_CA_CERTS` and `SSL_CERTFILE` require `SSL=true`. @@ -71,13 +71,13 @@ versions ignored them, so a sentinel setup with a non-zero `DATABASE` now select All settings are optional; unset ones keep the redis-py defaults. They apply to standalone, cluster and sentinel modes. ```bash -REDIS__RETRY_ATTEMPTS=3 # retries per command with exponential backoff -REDIS__RETRY_BACKOFF_BASE=0.008 # base delay in seconds -REDIS__RETRY_BACKOFF_CAP=0.512 # maximum delay in seconds -REDIS__RETRY_ON_TIMEOUT=true # also retry on socket timeouts +REDIS__RETRY__ATTEMPTS=3 # retries per command with exponential backoff +REDIS__RETRY__BACKOFF_BASE=0.008 # base delay in seconds +REDIS__RETRY__BACKOFF_CAP=0.512 # maximum delay in seconds +REDIS__RETRY__ON_TIMEOUT=true # also retry on socket timeouts REDIS__SOCKET_KEEPALIVE=true # detect dead peers behind NAT REDIS__CLIENT_NAME=my-service # shown in CLIENT LIST -REDIS__SENTINEL_USERNAME=sentinel-user # sentinel ACL user, used with SENTINEL_PASSWORD +REDIS__SENTINEL__USERNAME=sentinel-user # sentinel ACL user, used with SENTINEL_PASSWORD ``` `RETRY_ON_TIMEOUT` adds `TimeoutError` to the retried errors. The backoff settings take effect once `RETRY_ATTEMPTS` is set. @@ -594,7 +594,7 @@ cluster_schema = IndexSchemaDTO( redis = RedisAdapter( redis_config=RedisConfig( MODE=RedisMode.CLUSTER, - CLUSTER_NODES=["127.0.0.1:7000", "127.0.0.1:7001", "127.0.0.1:7002"], + CLUSTER={"NODES": ["127.0.0.1:7000", "127.0.0.1:7001", "127.0.0.1:7002"]}, ), ) handle = redis.search_index("cluster-products") @@ -638,8 +638,7 @@ handle.upsert_hash_dto( logger.info("HASH documents indexed") ``` -`upsert_hash` writes all fields with one atomic `HSET` and merges them into the existing hash. The `replace` argument -is ignored; passing `replace=False` emits a `DeprecationWarning`. +`upsert_hash` merges the supplied fields into the existing hash with one atomic `HSET`. JSON documents store the full payload at a JSON path (default `$`): diff --git a/docs/tutorials/adapters/scylladb.md b/docs/tutorials/adapters/scylladb.md index 6ea781f68..101ae1d99 100644 --- a/docs/tutorials/adapters/scylladb.md +++ b/docs/tutorials/adapters/scylladb.md @@ -67,9 +67,7 @@ config = ScyllaDBConfig( ### Connection Pool Monitoring -`scylla-driver` keeps one connection per host (per shard when shard-aware), so there is no pool to size. -`MAX_CONNECTIONS_PER_HOST`, `MIN_CONNECTIONS_PER_HOST`, `CORE_CONNECTIONS_PER_HOST` and `MAX_REQUESTS_PER_CONNECTION` have -no effect, are deprecated and will be removed in 6.0.0. To watch the connections, turn on monitoring: +The driver keeps one connection per host, or per shard with shard awareness. Enable monitoring to inspect those connections. ```python config = ScyllaDBConfig( @@ -86,8 +84,7 @@ config = ScyllaDBConfig( CONTACT_POINTS=["dc1-node1", "dc1-node2"], PORT=9042, LOCAL_DC="datacenter1", - REPLICATION_STRATEGY="NetworkTopologyStrategy", - REPLICATION_CONFIG={"datacenter1": 3, "datacenter2": 2}, + REPLICATION={"STRATEGY": "NetworkTopologyStrategy", "CONFIG": {"datacenter1": 3, "datacenter2": 2}}, ) ``` @@ -98,13 +95,8 @@ These settings are optional. A setting left unset keeps the driver default. ```python config = ScyllaDBConfig( CONTACT_POINTS=["scylla-1", "scylla-2"], - IDLE_HEARTBEAT_INTERVAL=10.0, - IDLE_HEARTBEAT_TIMEOUT=10.0, - RECONNECTION_POLICY="EXPONENTIAL", - RECONNECTION_BASE_DELAY=1.0, - RECONNECTION_MAX_DELAY=60.0, + HEARTBEAT={"IDLE_INTERVAL": 10.0, "IDLE_TIMEOUT": 10.0}, RECONNECTION={"POLICY": "EXPONENTIAL", "BASE_DELAY": 1.0, "MAX_DELAY": 60.0}, SPECULATIVE_EXECUTION={"DELAY": 0.2}, SERIAL_CONSISTENCY_LEVEL="LOCAL_SERIAL", - SPECULATIVE_EXECUTION_DELAY=0.2, ) ``` @@ -134,10 +126,9 @@ config = ScyllaDBConfig( CONTACT_POINTS=["node1.example.com"], USERNAME="scylla_user", PASSWORD="secure_password", - TLS_ENABLED=True, - TLS_CA_FILE="/etc/ssl/scylla-ca.pem", # system CAs when unset - TLS_CERT_FILE="/etc/ssl/client.pem", # optional, mutual TLS (needs TLS_KEY_FILE) - TLS_KEY_FILE="/etc/ssl/client.key", + TLS={"IS_ENABLED": True, "CA_FILE": "/etc/ssl/scylla-ca.pem", "CERT_FILE": "/etc/ssl/client.pem", "KEY_FILE": "/etc/ssl/client.key"}, + # system CAs when unset + # optional, mutual TLS (needs TLS_KEY_FILE) ) ``` @@ -412,9 +403,8 @@ Prepared statements are cached automatically when enabled in configuration: ```python config = ScyllaDBConfig( - ENABLE_PREPARED_STATEMENT_CACHE=True, - PREPARED_STATEMENT_CACHE_SIZE=100, - PREPARED_STATEMENT_CACHE_TTL_SECONDS=3600, # 1 hour + PREPARED_CACHE={"IS_ENABLED": True, "SIZE": 100, "TTL_SECONDS": 3600}, + # 1 hour ) adapter = ScyllaDBAdapter(config) ``` @@ -580,15 +570,12 @@ for host_stat in stats.get('hosts', []): ```python # Exponential backoff (default) config = ScyllaDBConfig( - RETRY_POLICY="EXPONENTIAL_BACKOFF", - RETRY_MAX_NUM_RETRIES=3, - RETRY_MIN_INTERVAL=0.1, - RETRY_MAX_INTERVAL=10.0, + RETRY={"POLICY": "EXPONENTIAL_BACKOFF", "MAX_NUM_RETRIES": 3, "MIN_INTERVAL": 0.1, "MAX_INTERVAL": 10.0}, ) # No retries (fail fast) config = ScyllaDBConfig( - RETRY_POLICY="FALLTHROUGH", + RETRY={"POLICY": "FALLTHROUGH"}, ) ``` @@ -685,9 +672,8 @@ config = ScyllaDBConfig( USERNAME="scylla", PASSWORD=SecretStr("password"), CONSISTENCY_LEVEL="QUORUM", - MAX_CONNECTIONS_PER_HOST=2, + PREPARED_CACHE={"IS_ENABLED": True}, ENABLE_CONNECTION_POOL_MONITORING=True, - ENABLE_PREPARED_STATEMENT_CACHE=True, ) adapter = ScyllaDBAdapter(config) @@ -755,9 +741,6 @@ Configure connection pools based on your cluster size and workload: ```python # For production: 1-3 connections per CPU core per node config = ScyllaDBConfig( - MAX_CONNECTIONS_PER_HOST=2, - MIN_CONNECTIONS_PER_HOST=1, - CORE_CONNECTIONS_PER_HOST=1, ) ``` @@ -824,8 +807,7 @@ For multi-datacenter deployments: ```python config = ScyllaDBConfig( LOCAL_DC="datacenter1", - REPLICATION_STRATEGY="NetworkTopologyStrategy", - REPLICATION_CONFIG={"datacenter1": 3, "datacenter2": 2}, + REPLICATION={"STRATEGY": "NetworkTopologyStrategy", "CONFIG": {"datacenter1": 3, "datacenter2": 2}}, ) ``` diff --git a/docs/tutorials/adapters/sqlalchemy.md b/docs/tutorials/adapters/sqlalchemy.md index a69414962..6b87499b4 100644 --- a/docs/tutorials/adapters/sqlalchemy.md +++ b/docs/tutorials/adapters/sqlalchemy.md @@ -66,7 +66,7 @@ reported as estimated too. ## Count cache -With `COUNT_CACHE_ENABLED=true` each total is cached in process, so only the first page of a search runs a `COUNT` and +With `COUNT_CACHE.IS_ENABLED=true` each total is cached in process, so only the first page of a search runs a `COUNT` and later pages reuse the total. A total can be stale for up to the TTL, so a row created just before a search may be missing from it. @@ -75,9 +75,9 @@ missing from it. | Setting | Default | Meaning | |---------------------------|---------|--------------------------------------------| -| `COUNT_CACHE_ENABLED` | `false` | Turns the cache on | -| `COUNT_CACHE_TTL_SECONDS` | `60` | Seconds a cached total stays valid | -| `COUNT_CACHE_MAX_SIZE` | `1000` | Number of cached searches kept per adapter | +| `COUNT_CACHE.IS_ENABLED` | `false` | Turns the cache on | +| `COUNT_CACHE.TTL_SECONDS` | `60` | Seconds a cached total stays valid | +| `COUNT_CACHE.MAX_SIZE` | `1000` | Number of cached searches kept per adapter | The cache is off by default and needs the `cache` extra: `ttl_cache` serves the sync adapter and `async-lru` serves the async one. Enabling it without the extra fails when the adapter is created. diff --git a/docs/tutorials/adapters/sqlite.md b/docs/tutorials/adapters/sqlite.md index 63635ece0..5f1ce5fd3 100644 --- a/docs/tutorials/adapters/sqlite.md +++ b/docs/tutorials/adapters/sqlite.md @@ -27,8 +27,8 @@ Configure the SQLite adapter via environment variables or a `SQLiteSQLAlchemyCon ```bash SQLITE_SQLALCHEMY__DATABASE=./app.db SQLITE_SQLALCHEMY__ECHO=false -SQLITE_SQLALCHEMY__POOL_SIZE=20 -SQLITE_SQLALCHEMY__POOL_TIMEOUT=30 +SQLITE_SQLALCHEMY__POOL__SIZE=20 +SQLITE_SQLALCHEMY__POOL__TIMEOUT=30 ``` ### Busy Timeout and Thread Check diff --git a/docs/tutorials/adapters/starrocks.md b/docs/tutorials/adapters/starrocks.md index 50c12b082..059474ca1 100644 --- a/docs/tutorials/adapters/starrocks.md +++ b/docs/tutorials/adapters/starrocks.md @@ -41,7 +41,7 @@ STARROCKS_SQLALCHEMY__PORT=9030 STARROCKS_SQLALCHEMY__USERNAME=root STARROCKS_SQLALCHEMY__PASSWORD=password STARROCKS_SQLALCHEMY__DATABASE=analytics_db -STARROCKS_SQLALCHEMY__POOL_SIZE=20 +STARROCKS_SQLALCHEMY__POOL__SIZE=20 STARROCKS_SQLALCHEMY__ECHO=false ``` diff --git a/docs/tutorials/adapters/temporal.md b/docs/tutorials/adapters/temporal.md index 72b7d8d14..b44e2938a 100644 --- a/docs/tutorials/adapters/temporal.md +++ b/docs/tutorials/adapters/temporal.md @@ -29,25 +29,25 @@ TEMPORAL__ENABLE_METRICS=false TEMPORAL__CLIENT_IDENTITY= TEMPORAL__API_KEY= TEMPORAL__LAZY_CONNECT=false -TEMPORAL__KEEP_ALIVE_INTERVAL_MS=30000 -TEMPORAL__KEEP_ALIVE_TIMEOUT_MS=15000 -TEMPORAL__CLIENT_RPC_RETRY_MAX_RETRIES=10 -TEMPORAL__CLIENT_RPC_RETRY_INITIAL_INTERVAL_MS=100 -TEMPORAL__CLIENT_RPC_RETRY_MAX_INTERVAL_MS=5000 -TEMPORAL__WORKER_GRACEFUL_SHUTDOWN_SECONDS=30 -TEMPORAL__WORKER_MAX_CACHED_WORKFLOWS=1000 -TEMPORAL__WORKER_DEBUG_MODE=false -TEMPORAL__WORKER_DISABLE_EAGER_ACTIVITY_EXECUTION=false -TEMPORAL__TLS_CA_CERT=/path/to/ca.crt -TEMPORAL__TLS_CLIENT_CERT=/path/to/client.crt -TEMPORAL__TLS_CLIENT_KEY=/path/to/client.key -TEMPORAL__WORKFLOW_EXECUTION_TIMEOUT=300 -TEMPORAL__WORKFLOW_RUN_TIMEOUT=60 -TEMPORAL__ACTIVITY_START_TO_CLOSE_TIMEOUT=30 -TEMPORAL__RETRY_MAXIMUM_ATTEMPTS=3 -TEMPORAL__RETRY_BACKOFF_COEFFICIENT=2.0 -TEMPORAL__RETRY_MAXIMUM_INTERVAL=60 -TEMPORAL__RETRY_INITIAL_INTERVAL=1 +TEMPORAL__KEEP_ALIVE__INTERVAL_MS=30000 +TEMPORAL__KEEP_ALIVE__TIMEOUT_MS=15000 +TEMPORAL__CLIENT_RETRY__MAX_RETRIES=10 +TEMPORAL__CLIENT_RETRY__INITIAL_INTERVAL_MS=100 +TEMPORAL__CLIENT_RETRY__MAX_INTERVAL_MS=5000 +TEMPORAL__WORKER__GRACEFUL_SHUTDOWN_SECONDS=30 +TEMPORAL__WORKER__MAX_CACHED_WORKFLOWS=1000 +TEMPORAL__WORKER__DEBUG_MODE=false +TEMPORAL__WORKER__DISABLE_EAGER_ACTIVITY_EXECUTION=false +TEMPORAL__TLS__CA_CERT=/path/to/ca.crt +TEMPORAL__TLS__CLIENT_CERT=/path/to/client.crt +TEMPORAL__TLS__CLIENT_KEY=/path/to/client.key +TEMPORAL__WORKFLOW__EXECUTION_TIMEOUT=300 +TEMPORAL__WORKFLOW__RUN_TIMEOUT=60 +TEMPORAL__ACTIVITY__START_TO_CLOSE_TIMEOUT=30 +TEMPORAL__RETRY__MAXIMUM_ATTEMPTS=3 +TEMPORAL__RETRY__BACKOFF_COEFFICIENT=2.0 +TEMPORAL__RETRY__MAXIMUM_INTERVAL=60 +TEMPORAL__RETRY__INITIAL_INTERVAL=1 ``` !!! note @@ -92,15 +92,8 @@ config = TemporalConfig( PORT=7233, NAMESPACE="default", TASK_QUEUE="my-task-queue", - WORKFLOW_EXECUTION_TIMEOUT=300, - WORKFLOW_RUN_TIMEOUT=60, - ACTIVITY_START_TO_CLOSE_TIMEOUT=30, - RETRY_MAXIMUM_ATTEMPTS=3, - RETRY_BACKOFF_COEFFICIENT=2.0, - RETRY_MAXIMUM_INTERVAL=60, - RETRY_INITIAL_INTERVAL=1, + WORKFLOW={"EXECUTION_TIMEOUT": 300, "RUN_TIMEOUT": 60}, ACTIVITY={"START_TO_CLOSE_TIMEOUT": 30}, RETRY={"MAXIMUM_ATTEMPTS": 3, "BACKOFF_COEFFICIENT": 2.0, "MAXIMUM_INTERVAL": 60, "INITIAL_INTERVAL": 1}, WORKER={"DEBUG_MODE": False}, CLIENT_IDENTITY="my-service-client", - WORKER_DEBUG_MODE=False, ) ``` diff --git a/docs/tutorials/adapters/vault.md b/docs/tutorials/adapters/vault.md index d03248e02..194d98e0b 100644 --- a/docs/tutorials/adapters/vault.md +++ b/docs/tutorials/adapters/vault.md @@ -27,11 +27,11 @@ Configure the Vault adapter via environment variables or a `VaultConfig` object. !!! warning Keep `VAULT__TOKEN` and other credentials out of source control. For AppRole, userpass and JWT, prefer the `*_FILE` - variants (for example `VAULT__APPROLE_SECRET_ID_FILE`) over inline secrets. + variants (for example `VAULT__APPROLE__SECRET_ID_FILE`) over inline secrets. !!! note - `VAULT__SECRET_CACHE_TTL=0` disables caching of `read_secret()` results. `VAULT__CONNECT_TIMEOUT` and - `VAULT__READ_TIMEOUT` default to `5.0` and `10.0` seconds. + `VAULT__SECRET_CACHE_TTL=0` disables caching of `read_secret()` results. `VAULT__HTTP__CONNECT_TIMEOUT` and + `VAULT__HTTP__READ_TIMEOUT` default to `5.0` and `10.0` seconds. ```bash VAULT__ENABLED=true @@ -40,14 +40,14 @@ VAULT__NAMESPACE= # Vault Enterprise namespace (optional) VAULT__AUTH_METHOD=token VAULT__TOKEN=s.xxxxx VAULT__MOUNT_POINT=secret -VAULT__VERIFY_SSL=true -# VAULT__CA_CERT_PATH=/etc/ssl/certs/vault-ca.pem -# VAULT__CLIENT_CERT_PATH=/etc/ssl/certs/client.pem -# VAULT__CLIENT_KEY_PATH=/etc/ssl/private/client.key -VAULT__CONNECT_TIMEOUT=5.0 -VAULT__READ_TIMEOUT=10.0 +VAULT__TLS__VERIFY_SSL=true +# VAULT__TLS__CA_CERT_PATH=/etc/ssl/certs/vault-ca.pem +# VAULT__TLS__CLIENT_CERT_PATH=/etc/ssl/certs/client.pem +# VAULT__TLS__CLIENT_KEY_PATH=/etc/ssl/private/client.key +VAULT__HTTP__CONNECT_TIMEOUT=5.0 +VAULT__HTTP__READ_TIMEOUT=10.0 VAULT__SECRET_CACHE_TTL=0 -VAULT__AUTO_RENEW_TOKEN=false +VAULT__TOKEN_RENEWAL__AUTO_RENEW_TOKEN=false ``` Supported `VAULT__AUTH_METHOD` values (hvac backends): @@ -58,16 +58,16 @@ AppRole example: ```bash VAULT__AUTH_METHOD=approle -VAULT__APPROLE_ROLE_ID=... -VAULT__APPROLE_SECRET_ID_FILE=/run/secrets/approle_secret_id +VAULT__APPROLE__ROLE_ID=... +VAULT__APPROLE__SECRET_ID_FILE=/run/secrets/approle_secret_id ``` Kubernetes example: ```bash VAULT__AUTH_METHOD=kubernetes -VAULT__KUBERNETES_ROLE=my-app -VAULT__KUBERNETES_JWT_PATH=/var/run/secrets/kubernetes.io/serviceaccount/token +VAULT__KUBERNETES__ROLE=my-app +VAULT__KUBERNETES__JWT_PATH=/var/run/secrets/kubernetes.io/serviceaccount/token ``` Userpass / LDAP / Okta example: @@ -82,18 +82,18 @@ JWT example: ```bash VAULT__AUTH_METHOD=jwt -VAULT__JWT_ROLE=my-role -VAULT__JWT_FILE=/run/secrets/vault.jwt +VAULT__JWT_AUTH__ROLE=my-role +VAULT__JWT_AUTH__JWT_FILE=/run/secrets/vault.jwt ``` AWS IAM example: ```bash VAULT__AUTH_METHOD=aws -VAULT__AWS_ACCESS_KEY=... -VAULT__AWS_SECRET_KEY=... -VAULT__AWS_ROLE=my-role -VAULT__AWS_REGION=us-east-1 +VAULT__AWS__ACCESS_KEY=... +VAULT__AWS__SECRET_KEY=... +VAULT__AWS__ROLE=my-role +VAULT__AWS__REGION=us-east-1 ``` GitHub / cert / cloud JWT (azure, gcp) follow the same pattern — see `VaultConfig` @@ -110,7 +110,7 @@ config = VaultConfig( AUTH_METHOD="token", TOKEN="s.xxxxx", # noqa: S106 MOUNT_POINT="secret", - VERIFY_SSL=True, + TLS={"VERIFY_SSL": True}, # CA_CERT_PATH="/etc/ssl/certs/vault-ca.pem", # CLIENT_CERT_PATH="/etc/ssl/certs/client.pem", # CLIENT_KEY_PATH="/etc/ssl/private/client.key", @@ -211,8 +211,8 @@ settings-source details. ### Token Renewal and Re-login -With `VAULT__AUTO_RENEW_TOKEN=true` the adapter looks the token up once, caches its expiry locally -and renews it with `renew_self` when the remaining TTL drops to `VAULT__RENEW_THRESHOLD_SECONDS`. +With `VAULT__TOKEN_RENEWAL__AUTO_RENEW_TOKEN=true` the adapter looks the token up once, caches its expiry locally +and renews it with `renew_self` when the remaining TTL drops to `VAULT__TOKEN_RENEWAL__RENEW_THRESHOLD_SECONDS`. Tokens that never expire (`ttl == 0`, such as root or periodic tokens) and non-renewable tokens are left alone, and a failed renewal is logged without failing the call. For auth methods other than `token` (AppRole, Kubernetes, ...), a call rejected with 403 triggers one new login and one replay @@ -220,7 +220,7 @@ of the call; with a static `token` there is nothing to log in again with. ### Retries and Outages -`VAULT__RETRIES_MAX_ATTEMPTS` retries failed connections for every call. Read errors and +`VAULT__HTTP__RETRIES_MAX_ATTEMPTS` retries failed connections for every call. Read errors and `500`/`502`/`503`/`504` responses are retried only for idempotent reads (`GET`, `HEAD`, `LIST`), so a write, delete or lease operation is never replayed. When Vault stays unavailable the adapter raises `UnavailableError` with a fixed message (the Vault address and path are logged, not @@ -229,7 +229,7 @@ returned in the error). ### Good to Know - `read_secret` returns a copy of the payload, so changing the result never alters the cached value. -- `VAULT__VERIFY_SSL` accepts `1/true/yes/on` and `0/false/no/off` (case-insensitive). Any other value raises a +- `VAULT__TLS__VERIFY_SSL` accepts `1/true/yes/on` and `0/false/no/off` (case-insensitive). Any other value raises a `ConfigurationError` instead of silently turning verification off. - Credential fields of `VaultConfig` (`TOKEN`, `APPROLE_SECRET_ID`, `PASSWORD`, the JWT and AWS secrets) are excluded from `repr()`. Error reasons are generic; the underlying detail is logged. diff --git a/docs/tutorials/cache.md b/docs/tutorials/cache.md index b7bb2d69c..ce6c48391 100644 --- a/docs/tutorials/cache.md +++ b/docs/tutorials/cache.md @@ -123,11 +123,6 @@ def expensive_lookup(key: str) -> str: - On methods, `self` is passed to the function but is not part of the key, so two instances share entries. - The cache lives in the process. It is not shared between workers and is lost on restart. -## Deprecated Names - -`ttl_cache_decorator` is a deprecated alias that emits a `DeprecationWarning`; the module path -`archipy.helpers.decorators.cache` is a kept legacy import path. Use `ttl_cache` from `archipy.helpers.decorators`. - ## Tests The behavior above is covered by the `features/cache_decorator.feature` scenarios (basic caching, TTL expiry, maxsize, diff --git a/docs/tutorials/config_management.md b/docs/tutorials/config_management.md index 9b0be3e0f..28961549a 100644 --- a/docs/tutorials/config_management.md +++ b/docs/tutorials/config_management.md @@ -260,13 +260,13 @@ files outside version control and load their paths from the environment. | Setting | Purpose | |--------------------------------------------------------------|-----------------------------------------------------------------| -| `GRPC__TLS_ENABLED` | Bind the server port with TLS | -| `GRPC__TLS_CERT_FILE`, `GRPC__TLS_KEY_FILE` | PEM server certificate chain and private key (both required) | -| `GRPC__TLS_CA_FILE` | PEM CA bundle that verifies client certificates | -| `GRPC__TLS_REQUIRE_CLIENT_AUTH` | Reject clients without a valid certificate (needs the CA file) | -| `GRPC__STUB_TLS_ENABLED` | Open client channels with TLS | -| `GRPC__STUB_TLS_CA_FILE` | PEM CA bundle that verifies the server (default: gRPC roots) | -| `GRPC__STUB_TLS_CERT_FILE`, `GRPC__STUB_TLS_KEY_FILE` | Client certificate and key for mutual TLS (set together) | +| `GRPC__TLS__IS_ENABLED` | Bind the server port with TLS | +| `GRPC__TLS__CERT_FILE`, `GRPC__TLS__KEY_FILE` | PEM server certificate chain and private key (both required) | +| `GRPC__TLS__CA_FILE` | PEM CA bundle that verifies client certificates | +| `GRPC__TLS__REQUIRE_CLIENT_AUTH` | Reject clients without a valid certificate (needs the CA file) | +| `GRPC__STUB_TLS__IS_ENABLED` | Open client channels with TLS | +| `GRPC__STUB_TLS__CA_FILE` | PEM CA bundle that verifies the server (default: gRPC roots) | +| `GRPC__STUB_TLS__CERT_FILE`, `GRPC__STUB_TLS__KEY_FILE` | Client certificate and key for mutual TLS (set together) | ```python from archipy.configs.base_config import BaseConfig diff --git a/docs/tutorials/helpers/decorators.md b/docs/tutorials/helpers/decorators.md index 0c42629e9..59a43dc05 100644 --- a/docs/tutorials/helpers/decorators.md +++ b/docs/tutorials/helpers/decorators.md @@ -233,9 +233,7 @@ fetch_user_data.clear_cache() These decorators automatically manage database transactions. -!!! note "Moved to the adapters layer" - They now live in `archipy.adapters.base.sqlalchemy.atomic`. Importing them from `archipy.helpers.decorators` still - works and emits a `DeprecationWarning`. The old import path will be removed in 6.0.0. +Import the decorators from `archipy.adapters.base.sqlalchemy.atomic`. ```python import logging @@ -452,26 +450,4 @@ See [Interceptor Tutorials — Rate Limiting](interceptors.md#rate-limiting-inte API - [Helper Tutorials](index.md) - Overview of all helper tutorials -## Deprecated names - -Decorators dropped their `_decorator` suffix and now detect `async def` functions themselves, so the separate -`async_*` variants are no longer needed. The old names still work and emit a `DeprecationWarning` that names the -replacement. They will be removed in 6.0.0. - -| Deprecated | Use instead | -|----------------------------------------------------------------------------|--------------------------------------------------------| -| `retry_decorator` | `retry` | -| `timeout_decorator` | `timeout` | -| `timing_decorator` | `timing` | -| `singleton_decorator` | `singleton` | -| `ttl_cache_decorator` | `ttl_cache` | -| `grpc_rate_limit_decorator` | `grpc_rate_limit` | -| `sqlalchemy_atomic_decorator(db_type, is_async=...)` | `sqlalchemy_atomic(db_type)` | -| `postgres_/mysql_/sqlite_/starrocks_sqlalchemy_atomic_decorator` | `postgres_/mysql_/sqlite_/starrocks_sqlalchemy_atomic` | -| `async_postgres_/async_mysql_/async_sqlite_/async_starrocks_..._decorator` | `postgres_/mysql_/sqlite_/starrocks_sqlalchemy_atomic` | -| `async_measure_duration`, `async_count_calls` | `measure_duration`, `count_calls` | -| `async_trace_span`, `async_trace_root` | `trace_span`, `trace_root` | - -Import everything from `archipy.helpers.decorators`. The old submodule paths (for example -`archipy.helpers.decorators.retry`) keep exporting the deprecated names until 6.0.0, which removes them with the other -deprecated names above. +See the [6.0 upgrade guide](../../community/deprecations.md#decorators) for the decorator names removed in 6.0. diff --git a/docs/tutorials/helpers/utils.md b/docs/tutorials/helpers/utils.md index d8dbee46c..06f728d50 100644 --- a/docs/tutorials/helpers/utils.md +++ b/docs/tutorials/helpers/utils.md @@ -220,12 +220,8 @@ String manipulation utilities. `StringUtils` provides helpers for common string Authentication and authorization utilities with Keycloak integration: -!!! note "Moved to the Keycloak adapter" - The guards are now the functions `fastapi_auth` and `grpc_auth` of `archipy.adapters.keycloak.auth`. - `fastapi_auth` returns an async dependency and `grpc_auth` detects `async def` servicer methods, so - `async_fastapi_auth`, `async_grpc_auth` and the `KeycloakUtils` class (in `archipy.helpers.utils.keycloak_utils`) - are deprecated and emit a `DeprecationWarning`. They will be removed in 6.0.0, together with the - `archipy.helpers.utils.keycloak_utils` module. +Import `fastapi_auth` and `grpc_auth` from `archipy.adapters.keycloak.auth`. The FastAPI guard is an async dependency. +The gRPC decorator supports synchronous and asynchronous servicer methods. ```python import logging @@ -296,12 +292,7 @@ def audit_log(action: str) -> None: The context is visible to `async def` and `def` endpoints, background tasks and streamed responses, and it is cleared when the request ends. -!!! warning "`request.state` is deprecated for the auth data" - The dependency still fills `request.state.user_info`, `token_info`, `actor_chain` and `user_roles`, but each of - them is now a dict, list or set that emits a `DeprecationWarning` when you read it (iterate, index, `get`, `in`, - `len`, ...), naming its replacement on `AuthContextManager.get_auth_context()`: `raw_user_info`, `token_info`, - `actor_chain` and `roles`. The values are the same as before. The dict the dependency returns does not warn. - `request.state` will stop carrying this data in 6.0.0. +Read `raw_user_info`, `token_info`, `actor_chain` and `roles` from the auth context. ## See Also diff --git a/docs/tutorials/observability.md b/docs/tutorials/observability.md index 19745ec9b..d9169ca3d 100644 --- a/docs/tutorials/observability.md +++ b/docs/tutorials/observability.md @@ -209,9 +209,9 @@ OTEL__METRICS_PULL_PORT=8200 # Prometheus Pushgateway (no local /metrics server) OTEL__METRICS_ENABLED=true OTEL__METRICS_EXPORTER=pushgateway -OTEL__METRICS_PUSHGATEWAY_URL=http://pushgateway.monitoring:9091 -OTEL__METRICS_PUSHGATEWAY_JOB=my-service -OTEL__METRICS_PUSHGATEWAY_INTERVAL_SECONDS=60 +OTEL__PUSHGATEWAY__URL=http://pushgateway.monitoring:9091 +OTEL__PUSHGATEWAY__JOB=my-service +OTEL__PUSHGATEWAY__INTERVAL_SECONDS=60 ``` `OtelUtils.metrics_registry()` returns the Prometheus `CollectorRegistry` when diff --git a/features/app_utils.feature b/features/app_utils.feature index bf2d421e5..7bd050534 100644 --- a/features/app_utils.feature +++ b/features/app_utils.feature @@ -310,13 +310,6 @@ Feature: App Utilities Examples: | settings | outcome | - | TLS_ENABLED | rejected | - | TLS_ENABLED,TLS_CERT_FILE | rejected | - | TLS_ENABLED,TLS_CERT_FILE,TLS_KEY_FILE | accepted | - | TLS_REQUIRE_CLIENT_AUTH | rejected | - | TLS_REQUIRE_CLIENT_AUTH,TLS_CA_FILE | accepted | - | STUB_TLS_CERT_FILE | rejected | - | STUB_TLS_CERT_FILE,STUB_TLS_KEY_FILE | accepted | | TLS.IS_ENABLED | rejected | | TLS.IS_ENABLED,TLS.CERT_FILE | rejected | | TLS.IS_ENABLED,TLS.CERT_FILE,TLS.KEY_FILE | accepted | @@ -371,7 +364,7 @@ Feature: App Utilities And the uvicorn arguments leave out "forwarded_allow_ips" And no deprecation warning is raised - Scenario: A UVICORN setting wins over the deprecated FASTAPI setting without a warning + Scenario: A UVICORN setting overrides the Uvicorn default Given a configuration built from: """ { @@ -384,24 +377,7 @@ Feature: App Utilities Then the uvicorn argument "timeout_keep_alive" is 30 And no deprecation warning is raised - Scenario: A deprecated FASTAPI uvicorn setting still applies and warns - Given a configuration built from: - """ - { - "FASTAPI": { - "TIMEOUT_KEEP_ALIVE": 9, - "FORWARDED_ALLOW_IPS": [ - "10.0.0.1" - ] - } - } - """ - When the uvicorn arguments are built - Then the uvicorn argument "timeout_keep_alive" is 9 - And the uvicorn argument "forwarded_allow_ips" is ["10.0.0.1"] - And a deprecation warning mentions "UVICORN.TIMEOUT_KEEP_ALIVE" - - Scenario: Grouped UVICORN settings reach the uvicorn arguments and win over the FASTAPI mirror + Scenario: Grouped UVICORN settings reach the uvicorn arguments Given a configuration built from: """ { @@ -413,9 +389,6 @@ Feature: App Utilities "BACKLOG": 10, "CONCURRENCY": 5 } - }, - "FASTAPI": { - "WS_MAX_SIZE": 2048 } } """ @@ -425,25 +398,6 @@ Feature: App Utilities And the uvicorn argument "limit_concurrency" is 5 And no deprecation warning is raised - Scenario: A deprecated FASTAPI WebSocket setting applies when the UVICORN group leaves it unset - Given a configuration built from: - """ - { - "UVICORN": { - "WEBSOCKET": { - "PING_INTERVAL": 5.0 - } - }, - "FASTAPI": { - "WS_MAX_SIZE": 2048 - } - } - """ - When the uvicorn arguments are built - Then the uvicorn argument "ws_max_size" is 2048 - And the uvicorn argument "ws_ping_interval" is 5.0 - And a deprecation warning mentions "UVICORN.WS_MAX_SIZE" - Scenario: Reload leaves the worker count out Given a configuration built from: """ @@ -462,9 +416,11 @@ Feature: App Utilities """ { "UVICORN": { - "SSL_KEYFILE": "/tls/key.pem", - "SSL_CERTFILE": "/tls/cert.pem", - "SSL_CA_CERTS": "/tls/ca.pem" + "TLS": { + "KEYFILE": "/tls/key.pem", + "CERTFILE": "/tls/cert.pem", + "CA_CERTS": "/tls/ca.pem" + } } } """ @@ -478,60 +434,9 @@ Feature: App Utilities """ { "UVICORN": { - "SSL_KEYFILE": "/tls/key.pem" - } - } - """ - - Scenario: Building a FASTAPI section with a deprecated uvicorn field warns - When the FASTAPI section is built with a deprecated uvicorn field - Then a deprecation warning mentions "UVICORN" - - Scenario Outline: Reading a deprecated FASTAPI uvicorn field warns and names its replacement - Given a configuration built from: - """ - {} - """ - When the FASTAPI field "" is read - Then a deprecation warning mentions "UVICORN." - - Examples: - | field | - | TIMEOUT_KEEP_ALIVE | - | FORWARDED_ALLOW_IPS | - | RELOAD | - | TIMEOUT_GRACEFUL_SHUTDOWN | - - Scenario: Reading the UVICORN field and dumping the FASTAPI section do not warn - Given a configuration built from: - """ - { - "FASTAPI": { - "TIMEOUT_KEEP_ALIVE": 9 - } - } - """ - When the UVICORN field "TIMEOUT_KEEP_ALIVE" is read and the FASTAPI section is dumped - Then no deprecation warning is raised - - Scenario: The deprecated FASTAPI fields are marked deprecated in the JSON schema - Then the JSON schema of the FASTAPI section marks "TIMEOUT_KEEP_ALIVE" as deprecated - - Scenario Outline: Reading a deprecated ScyllaDB pool field warns, loading the config does not - Given a configuration built from: - """ - { - "SCYLLADB": { - "MAX_CONNECTIONS_PER_HOST": 4 + "TLS": { + "KEYFILE": "/tls/key.pem" + } } } """ - When the SCYLLADB field "" is read - Then a deprecation warning mentions "no per-host connection pool sizing" - - Examples: - | field | - | MAX_CONNECTIONS_PER_HOST | - | MIN_CONNECTIONS_PER_HOST | - | CORE_CONNECTIONS_PER_HOST | - | MAX_REQUESTS_PER_CONNECTION | diff --git a/features/base_config.feature b/features/base_config.feature index b3a088142..a37c68ed0 100644 --- a/features/base_config.feature +++ b/features/base_config.feature @@ -183,24 +183,24 @@ Feature: Base Configuration System And the error should mention "" Examples: Incomplete Vault settings - | auth_method | problem | fragment | - | token | no token is set | TOKEN or TOKEN_FILE | - | token | the token file cannot be read | Failed to read secret | - | approle | no role id is set | APPROLE_ROLE_ID | - | approle | no secret id is set | APPROLE_SECRET_ID | - | userpass | no username is set | USERNAME | - | userpass | no password is set | PASSWORD | - | kubernetes | no role is set | KUBERNETES_ROLE | - | jwt | no role is set | JWT_ROLE | - | jwt | no jwt is set | JWT or JWT_FILE | - | aws | no access key is set | AWS_ACCESS_KEY | - | azure | no role is set | AZURE_ROLE | - | azure | no jwt is set | AZURE_JWT | - | gcp | no role is set | GCP_ROLE | - | gcp | no jwt is set | GCP_JWT | - | github | no github token is set | GITHUB_TOKEN | - | token | no address is set | VAULT.ADDR | - | token | only a client certificate is set | CLIENT_KEY_PATH | + | auth_method | problem | fragment | + | token | no token is set | TOKEN or TOKEN_FILE | + | token | the token file cannot be read | Failed to read secret | + | approle | no role id is set | APPROLE.ROLE_ID | + | approle | no secret id is set | APPROLE.SECRET_ID | + | userpass | no username is set | USERNAME | + | userpass | no password is set | PASSWORD | + | kubernetes | no role is set | KUBERNETES.ROLE | + | jwt | no role is set | JWT_AUTH.ROLE | + | jwt | no jwt is set | JWT_AUTH.JWT or JWT_AUTH.JWT_FILE | + | aws | no access key is set | AWS.ACCESS_KEY | + | azure | no role is set | AZURE.ROLE | + | azure | no jwt is set | AZURE.JWT | + | gcp | no role is set | GCP.ROLE | + | gcp | no jwt is set | GCP.JWT | + | github | no github token is set | GITHUB.TOKEN | + | token | no address is set | VAULT.ADDR | + | token | only a client certificate is set | TLS.CLIENT_KEY_PATH | Scenario Outline: A Vault client logs in with Given Vault accepts logins for a test identity @@ -239,8 +239,6 @@ Feature: Base Configuration System | Kafka | auto commit and no offset reset | rejected | | Kafka | a heartbeat longer than the session | rejected | | Redis | cluster mode without nodes | rejected | - | Redis | cluster mode with nodes | accepted | - | Redis | sentinel mode without a service name | rejected | | Redis | standalone mode without a host | rejected | | Redis | grouped cluster mode without nodes | rejected | | Redis | grouped cluster mode with nodes | accepted | @@ -249,18 +247,12 @@ Feature: Base Configuration System | Redis | grouped CA file with TLS disabled | rejected | | ScyllaDB | no contact points | rejected | | ScyllaDB | a username without a password | rejected | - | ScyllaDB | a minimum pool above the maximum | rejected | | ScyllaDB | a client certificate without a key | rejected | | ScyllaDB | a CA file with TLS disabled | rejected | | ScyllaDB | TLS enabled with a CA file | accepted | | ScyllaDB | an exponential reconnection base above the maximum | rejected | | ScyllaDB | an exponential reconnection within bounds | accepted | - | ScyllaDB | a grouped client certificate without a key | rejected | - | ScyllaDB | a grouped CA file with TLS disabled | rejected | - | ScyllaDB | a grouped exponential reconnection above the max | rejected | | ScyllaDB | a grouped replication without datacenters | rejected | - | ScyllaDB | grouped TLS enabled with a CA file | accepted | - | Elasticsearch | only a username | rejected | | Elasticsearch | grouped username without a password | rejected | | Elasticsearch | grouped client cert without a key | rejected | | Elasticsearch | grouped CA file with verification disabled | rejected | @@ -277,12 +269,9 @@ Feature: Base Configuration System | OpenTelemetry | a pushgateway exporter with a grouped URL | accepted | | Temporal | only a CA certificate | accepted | | Temporal | a client key without a certificate | rejected | - | Temporal | a run timeout above the execution one | rejected | - | Temporal | a keep alive timeout above the interval | rejected | | Temporal | a task timeout above the run timeout | accepted | | Temporal | a verification name without a CA | rejected | | Temporal | a verification name with a CA | accepted | - | Temporal | a grouped client certificate without a key | rejected | | Temporal | a grouped run timeout above the execution one | rejected | | Temporal | a grouped keep alive timeout above the interval | rejected | | Temporal | a grouped client certificate with a key | accepted | @@ -305,19 +294,19 @@ Feature: Base Configuration System Examples: Temporal defaults | field | expected | - | ACTIVITY_HEARTBEAT_TIMEOUT | None | - | WORKER_POLLER_AUTOSCALING | False | - | WORKFLOW_RETRY_ENABLED | False | + | ACTIVITY.HEARTBEAT_TIMEOUT | None | + | WORKER.POLLER_AUTOSCALING | False | + | WORKFLOW.RETRY_ENABLED | False | | PYDANTIC_DATA_CONVERTER | True | - | WORKFLOW_EXECUTION_TIMEOUT | None | - | WORKFLOW_RUN_TIMEOUT | None | + | WORKFLOW.EXECUTION_TIMEOUT | None | + | WORKFLOW.RUN_TIMEOUT | None | | CONNECT_TIMEOUT | None | - | TLS_VERIFICATION_SERVER_NAME | None | + | TLS.VERIFICATION_SERVER_NAME | None | | GRPC_COMPRESSION | None | | PAYLOADS_WARN_SIZE | None | | MEMO_WARN_SIZE | None | | RUNTIME_DISABLE_ENVIRONMENT_INFO | False | - | WORKER_MAX_EAGER_ACTIVITY_RESERVATIONS | None | + | WORKER.MAX_EAGER_ACTIVITY_RESERVATIONS | None | Scenario Outline: The SQLAlchemy session factory follows EXPIRE_ON_COMMIT When I build a sqlite session manager with EXPIRE_ON_COMMIT @@ -420,15 +409,15 @@ Feature: Base Configuration System | sync | sqlite | CHECK_SAME_THREAD | false | {"check_same_thread": false} | | async | sqlite | CHECK_SAME_THREAD | false | {} | - Scenario Outline: Deprecated flat settings fold into a nested group - Given a test section with flat "" set to and group "" set to - When the test section is validated - Then the group value should be - And deprecation warning should be raised + Scenario Outline: Removed config keys are absent from the section model + Then the "
" configuration has no "" field Examples: - | flat | flat_value | group | group_value | expected | warnings | - | NAME | "old" | none | none | "old" | 1 | - | NAME | "old" | NAME | "new" | "new" | 1 | - | none | none | NAME | "new" | "new" | 0 | - | none | none | none | none | null | 0 | + | section | field | + | AUTH | JWT_ISSUER | + | ELASTIC | MAP_ERRORS | + | FASTAPI | ACCESS_LOG | + | KAFKA | EMPTY_KEY_FOR_MISSING_KEY | + | SCYLLADB | MAX_CONNECTIONS_PER_HOST | + | UVICORN | SSL_KEYFILE | + | VAULT | APPROLE_ROLE_ID | diff --git a/features/decorators.feature b/features/decorators.feature index 0dcbfb568..75207a696 100644 --- a/features/decorators.feature +++ b/features/decorators.feature @@ -328,29 +328,6 @@ Feature: Helper decorators Rule: Renamed decorators keep their old names working - Scenario Outline: Old name still works and warns once pointing at - When the old decorator name "" is applied - Then exactly one DeprecationWarning should name "" - And the DeprecationWarning should point at the calling code - - Examples: - | old | new | - | retry_decorator | retry | - | timeout_decorator | timeout | - | timing_decorator | timing | - | singleton_decorator | singleton | - | ttl_cache_decorator | ttl_cache | - | grpc_rate_limit_decorator | grpc_rate_limit | - | sqlalchemy_atomic_decorator | sqlalchemy_atomic | - | postgres_sqlalchemy_atomic_decorator | postgres_sqlalchemy_atomic | - | mysql_sqlalchemy_atomic_decorator | mysql_sqlalchemy_atomic | - | sqlite_sqlalchemy_atomic_decorator | sqlite_sqlalchemy_atomic | - | starrocks_sqlalchemy_atomic_decorator | starrocks_sqlalchemy_atomic | - | async_postgres_sqlalchemy_atomic_decorator | postgres_sqlalchemy_atomic | - | async_mysql_sqlalchemy_atomic_decorator | mysql_sqlalchemy_atomic | - | async_sqlite_sqlalchemy_atomic_decorator | sqlite_sqlalchemy_atomic | - | async_starrocks_sqlalchemy_atomic_decorator | starrocks_sqlalchemy_atomic | - Scenario Outline: New name is exported without a warning When the new decorator name "" is imported from the decorators package Then it should be a function and not a module @@ -365,20 +342,6 @@ Feature: Helper decorators | ttl_cache | | grpc_rate_limit | - Scenario Outline: Moved name still resolves from the decorators package and warns - When the new decorator name "" is imported from the decorators package - Then it should be a function and not a module - And exactly one DeprecationWarning should name "archipy.adapters.base.sqlalchemy.atomic." - And the DeprecationWarning should point at the calling code - - Examples: - | name | - | sqlalchemy_atomic | - | postgres_sqlalchemy_atomic | - | mysql_sqlalchemy_atomic | - | sqlite_sqlalchemy_atomic | - | starrocks_sqlalchemy_atomic | - Scenario Outline: Name is exported from the adapters module without a warning When the decorator name "" is imported from the module "archipy.adapters.base.sqlalchemy.atomic" Then it should be a function and not a module @@ -391,43 +354,3 @@ Feature: Helper decorators | mysql_sqlalchemy_atomic | | sqlite_sqlalchemy_atomic | | starrocks_sqlalchemy_atomic | - - Scenario Outline: Old module path still exports - When "" is imported from the old module path "" - Then the old module path should resolve to a callable - - Examples: - | module | name | - | retry | retry_decorator | - | timeout | timeout_decorator | - | timing | timing_decorator | - | singleton | singleton_decorator | - | cache | ttl_cache_decorator | - | grpc_rate_limit | grpc_rate_limit_decorator | - | sqlalchemy_atomic | postgres_sqlalchemy_atomic_decorator | - | sqlalchemy_atomic | _handle_db_exception | - - Scenario Outline: Deprecated KeycloakUtils method warns and builds the same guard - When the deprecated KeycloakUtils method "" is called - Then exactly one DeprecationWarning should name "" - And the Keycloak auth result is callable - - Examples: - | name | replacement | - | async_fastapi_auth | fastapi_auth | - | async_grpc_auth | grpc_auth | - - Scenario Outline: Old path name still resolves and warns - When "" is read from the old Keycloak utils module - Then exactly one DeprecationWarning should name "" - And the Keycloak auth result is callable - - Examples: - | name | replacement | - | AuthContextManager | archipy.adapters.keycloak.auth.AuthContextManager | - | clear_keycloak_remote_cache | archipy.adapters.keycloak.auth.clear_keycloak_remote_cache | - - Scenario: The legacy KeycloakUtils namespace keeps its methods - When "KeycloakUtils" is read from the old Keycloak utils module - Then exactly one DeprecationWarning should name "the functions of archipy.adapters.keycloak.auth" - And the legacy KeycloakUtils exposes fastapi_auth, async_fastapi_auth, grpc_auth and async_grpc_auth diff --git a/features/elastic_adapter.feature b/features/elastic_adapter.feature index 53899a040..0766f43ef 100644 --- a/features/elastic_adapter.feature +++ b/features/elastic_adapter.feature @@ -227,24 +227,20 @@ Feature: Elasticsearch Operations Testing | mode | | asynchronously | - Scenario Outline: Map missing document errors only when enabled - Given an Elasticsearch config with "MAP_ERRORS" set to "" - And index "test-index" exists + Scenario Outline: Missing documents raise ArchiPy errors + Given index "test-index" exists When I create the Elasticsearch adapter from that config And I get a missing document through that adapter - Then the Elasticsearch error kind should be "" - And the adapter creation should the ArchiPy error mapping deprecation warning + Then the Elasticsearch error kind should be "ArchiPy NotFoundError" Examples: sync - | mode | map_errors | error | warning | - | synchronously | true | ArchiPy NotFoundError | not emit | - | synchronously | false | client NotFoundError | emit | + | mode | + | synchronously | @async Examples: async - | mode | map_errors | error | warning | - | asynchronously | true | ArchiPy NotFoundError | not emit | - | asynchronously | false | client NotFoundError | emit | + | mode | + | asynchronously | Scenario Outline: Disable retries only for non-idempotent calls Given a valid Elasticsearch client connection diff --git a/features/email_adapter.feature b/features/email_adapter.feature index 4efbbbce4..9d95837e4 100644 --- a/features/email_adapter.feature +++ b/features/email_adapter.feature @@ -64,23 +64,6 @@ Feature: Email adapter Then Mailpit holds 1 email And the adapter session is encrypted with TLS - Scenario: STARTTLS is skipped when the server does not advertise it - Given the plain Mailpit SMTP server is configured - And an email adapter - When I send an email to "alice@example.com" with subject "Hello" and body "Hi there" - Then Mailpit holds 1 email - And the delivered email is sent from "mailer@example.com" - And the adapter session is not encrypted with TLS - - Scenario: A wrong SMTP password is rejected by the plain server too - Given the plain Mailpit SMTP server is configured - And SMTP credentials "mailer@example.com" and "wrong-password" - And an email adapter - When I try to send an email to "alice@example.com" with subject "Hello" and body "Hi there" - Then an unavailable error is raised for "SMTP" - And the unavailable error was caused by an authentication failure - And Mailpit holds 0 emails - Scenario: Required STARTTLS delivers over a verified TLS session Given the Mailpit SMTP server is configured And the SMTP transport security is "starttls" verified with the Mailpit CA @@ -98,17 +81,17 @@ Feature: Email adapter And the unavailable error was caused by a certificate verification failure And Mailpit holds 0 emails - Scenario: Required STARTTLS accepts an untrusted certificate when verification is off - Given the Mailpit SMTP server is configured - And the SMTP transport security is "starttls" without certificate verification - And an email adapter - When I send an email to "alice@example.com" with subject "Hello" and body "Hi there" - Then Mailpit holds 1 email - And the adapter session is encrypted with TLS + Scenario Outline: Removed SMTP security settings fail validation + When I build an email config with TLS setting set to + Then the email config is rejected for + + Examples: + | field | value | + | MODE | "auto" | + | VERIFY | false | - Scenario: Required STARTTLS fails instead of falling back to clear text + Scenario: Default STARTTLS fails instead of falling back to clear text Given the plain Mailpit SMTP server is configured - And the SMTP transport security is "starttls" And an email adapter When I try to send an email to "alice@example.com" with subject "Hello" and body "Hi there" Then an unavailable error is raised for "SMTP" @@ -117,8 +100,8 @@ Feature: Email adapter And the adapter holds no open SMTP session Scenario: Transport security none sends in clear text on request - Given the Mailpit SMTP server is configured - And the SMTP transport security is "none" + Given the plain Mailpit SMTP server is configured + And the SMTP transport security is "none" without credentials And an email adapter When I send an email to "alice@example.com" with subject "Hello" and body "Hi there" Then Mailpit holds 1 email @@ -132,32 +115,21 @@ Feature: Email adapter Then the connection is established And the pooled session is encrypted with TLS - Scenario: The deprecated auto transport security warns - Given the Mailpit SMTP server is configured - When I create an email adapter - Then an email deprecation warning mentions "TLS.MODE" - - Scenario Outline: Insecure credential and verification settings warn + Scenario: Authentication without TLS is rejected Given the Mailpit SMTP server is configured - And the SMTP transport security is "" + And the SMTP transport security is "none" verified with the Mailpit CA When I create an email adapter - Then an email deprecation warning mentions "" - - Examples: - | mode | verification | text | - | none | verified with the Mailpit CA | sends USERNAME and PASSWORD | - | starttls | without certificate verification | TLS.VERIFY=False | - | implicit | without certificate verification | TLS.VERIFY=False | + Then a configuration error is raised for "email_credentials" Scenario Outline: Out-of-range pool, retry and timeout settings are rejected When I build an email config with set to Then the email config is rejected for Examples: - | field | value | - | POOL_SIZE | 0 | - | MAX_RETRIES | 0 | - | CONNECTION_TIMEOUT | 0 | + | field | value | + | POOL.SIZE | 0 | + | MAX_RETRIES | 0 | + | POOL.CONNECTION_TIMEOUT | 0 | Scenario: The configured sender address is used as the From header Given the Mailpit SMTP server is configured @@ -369,9 +341,10 @@ Feature: Email adapter And the "email.send" span has attribute "email.attachment_count" equal to "0" And the "email.send" span has attribute "email.tls_mode" equal to "starttls" - Scenario: The SMTP span reports no TLS when the server does not advertise STARTTLS + Scenario: The SMTP span reports no TLS for an unauthenticated clear-text session Given adapter spans are exported to the collector And the plain Mailpit SMTP server is configured + And the SMTP transport security is "none" without credentials And an email adapter When I send an email to "alice@example.com" with subject "Hello" and body "Hi there" Then the "email.send" span has attribute "email.tls_mode" equal to "none" diff --git a/features/environment.py b/features/environment.py index 9000ff462..50a07e8f8 100644 --- a/features/environment.py +++ b/features/environment.py @@ -213,7 +213,7 @@ def after_scenario(context: Context, scenario: Scenario) -> None: "VAULT__SECRET_PATHS", "VAULT__AUTH_METHOD", "VAULT__MOUNT_POINT", - "VAULT__VERIFY_SSL", + "VAULT__TLS__VERIFY_SSL", ) for key in vault_runtime_keys: os.environ.pop(key, None) diff --git a/features/jwt_utils.feature b/features/jwt_utils.feature index 8e4fea911..bfe264afc 100644 --- a/features/jwt_utils.feature +++ b/features/jwt_utils.feature @@ -71,10 +71,6 @@ Feature: JWT Utilities When the token is decoded requiring an empty token type Then an InvalidTokenError should be raised - Scenario: A negative flat leeway is still rejected by the configuration - When an authentication configuration is built with the deprecated flat leeway of -1 - Then the configuration is rejected - Scenario: A negative leeway is rejected by the configuration When an authentication configuration is built with a leeway of -1 Then the configuration is rejected diff --git a/features/kafka_clients_spans.feature b/features/kafka_clients_spans.feature index 6222a9c54..ab6034bdb 100644 --- a/features/kafka_clients_spans.feature +++ b/features/kafka_clients_spans.feature @@ -147,17 +147,17 @@ Feature: Kafka Clients and Spans Testing Then the delivery failure should be passed to the on_delivery callback And the logs should mention topic "failed-delivery-topic" but not "secret-payload" - Scenario Outline: A producer with missing keys sent as delivers a keyless message with - Given a test topic named "test-topic-keyless--" - When a producer with missing keys sent as produces a message without a key to topic "test-topic-keyless--" - Then the message on topic "test-topic-keyless--" should have and the deprecation warning should be + Scenario Outline: A producer distinguishes missing keys from empty keys + Given a test topic named "test-topic-keyless--" + When a producer sends a message with to topic "test-topic-keyless--" + Then the message on topic "test-topic-keyless--" should have Examples: - | mode | setting | code | key_state | warned | - | sync | an empty key | legacy | an empty key | raised | - | sync | no key | none | no key | not raised | - | async | an empty key | legacy | an empty key | raised | - | async | no key | none | no key | not raised | + | mode | case | key_state | + | sync | none | no key | + | sync | empty | an empty key | + | async | none | no key | + | async | empty | an empty key | Scenario Outline: A Kafka configuration with protocol , mechanism and username logs When the Kafka settings are assembled with protocol , mechanism and username while warnings are collected diff --git a/features/keycloak_adapter_management.feature b/features/keycloak_adapter_management.feature index 89cc478d0..df11cc647 100644 --- a/features/keycloak_adapter_management.feature +++ b/features/keycloak_adapter_management.feature @@ -250,22 +250,29 @@ Feature: Keycloak Management Testing | async | async-test-realm-envoy | Async Test Realm | async-test-client | envoy | @realms - Scenario Outline: Keycloak rejects unknown fields in payloads - Given a configured Keycloak adapter via - And I create a realm named "test-realm" with display name "Test Realm" using adapter - When I send a payload with the unknown field "typoField" to Keycloak using adapter + Scenario Outline: The adapter rejects plain dictionaries + Given a configured Keycloak adapter via direct + When I send a dictionary to the Keycloak adapter + Then the Keycloak adapter rejects the payload argument + + Examples: + | adapter_type | kind | + | sync | group | + | sync | user | + | async | group | + | async | user | + + @realms + Scenario Outline: Keycloak rejects unknown fields in realm updates + Given a configured sync Keycloak adapter via + And I create a realm named "test-realm" with display name "Test Realm" using sync adapter + When I update the realm with the unknown field "typoField" Then Keycloak rejects the payload as invalid and names the field "typoField" Examples: - | adapter_type | kind | via | - | sync | group | direct | - | sync | user | direct | - | sync | realm | direct | - | async | group | direct | - | sync | group | envoy | - | sync | user | envoy | - | sync | realm | envoy | - | async | group | envoy | + | via | + | direct | + | envoy | @users Scenario Outline: User counts, credentials, groups, federated identities, sessions and profile diff --git a/features/keycloak_auth_guards.feature b/features/keycloak_auth_guards.feature index 4ba9366ff..8121f5dc7 100644 --- a/features/keycloak_auth_guards.feature +++ b/features/keycloak_auth_guards.feature @@ -8,7 +8,7 @@ Feature: Keycloak Auth Guards Testing # --- Keycloak auth dependencies and decorators --- # Real tokens issued by the Keycloak container drive keycloak.auth fastapi_auth, grpc_auth and # AuthContextManager. gRPC uses a ServicerContext fake only to record aborts. - Scenario Outline: Auth FastAPI dependency populates request state for a valid token + Scenario Outline: Auth FastAPI dependency sets the auth context for a valid token Given a configured sync Keycloak adapter via And I create a realm named "auth-realm" with display name "Auth Realm" using sync adapter And I create a client named "auth-client" in realm "auth-realm" with service accounts and update adapter using sync adapter @@ -19,9 +19,10 @@ Feature: Keycloak Auth Guards Testing And the keycloak fastapi auth requires any of roles "auth-reader" When the keycloak auth fastapi dependency is called with the access token of user "authuser" Then the keycloak auth dependency returns the user info of user "authuser" - And the keycloak auth request state user roles include "auth-reader" - And the keycloak auth request state has an empty actor chain + And the keycloak auth context user roles include "auth-reader" + And the keycloak auth context has an empty actor chain And the keycloak auth context holds user "authuser" while the dependency is active + And the request state has no Keycloak auth fields And the keycloak auth context is cleared after the dependency ends Examples: @@ -30,31 +31,6 @@ Feature: Keycloak Auth Guards Testing | envoy | @auth-guards - Scenario Outline: Reading from the request state warns and points to the auth context - Given a configured sync Keycloak adapter via - And I create a realm named "auth-realm" with display name "Auth Realm" using sync adapter - And I create a client named "auth-client" in realm "auth-realm" with service accounts and update adapter using sync adapter - And I create a user with username "authuser" and password "pass123" using sync adapter - And I create a realm role named "auth-reader" with description "Reader" using sync adapter - And I assign realm role "auth-reader" to user "authuser" using sync adapter - And the keycloak auth access token of user "authuser" is obtained with password "pass123" - And the keycloak fastapi auth requires any of roles "auth-reader" - When the keycloak auth fastapi dependency is called with the access token of user "authuser" - Then reading "" from the request state warns and names "" - And the value the keycloak auth dependency returned does not warn when it is read - And the request state keeps the same content as the auth context - - Examples: - | field | replacement | via | - | user_info | AuthContextManager.get_auth_context().raw_user_info | direct | - | token_info | AuthContextManager.get_auth_context().token_info | direct | - | actor_chain | AuthContextManager.get_auth_context().actor_chain | direct | - | user_roles | AuthContextManager.get_auth_context().roles | direct | - | user_info | AuthContextManager.get_auth_context().raw_user_info | envoy | - | token_info | AuthContextManager.get_auth_context().token_info | envoy | - | actor_chain | AuthContextManager.get_auth_context().actor_chain | envoy | - | user_roles | AuthContextManager.get_auth_context().roles | envoy | - Scenario Outline: Auth FastAPI dependency accepts a client role from resource access Given a configured sync Keycloak adapter via And I create a realm named "auth-realm" with display name "Auth Realm" using sync adapter @@ -67,7 +43,7 @@ Feature: Keycloak Auth Guards Testing And I assign client role "auth-operator" of client "auth-client" to user "authuser" using sync adapter And the keycloak fastapi auth requires all roles "auth-reader,auth-operator" When the keycloak auth fastapi dependency is called with the access token of user "authuser" - Then the keycloak auth request state user roles include "auth-reader,auth-operator" + Then the keycloak auth context user roles include "auth-reader,auth-operator" Examples: | via | diff --git a/features/keycloak_dtos.feature b/features/keycloak_dtos.feature index 287edcb72..3df080a64 100644 --- a/features/keycloak_dtos.feature +++ b/features/keycloak_dtos.feature @@ -53,30 +53,18 @@ Feature: Keycloak DTOs | KeycloakComponentRequestDTO | field name | provider_id | provider_id | ldap | | KeycloakComponentRequestDTO | wire name | providerId | provider_id | ldap | - Scenario Outline: Reading a response DTO like a dict warns + Scenario: Response DTOs expose attributes and serialize to dictionaries explicitly Given a Keycloak KeycloakRoleDTO response with name "admin" - When the response is read with - Then a dict-style access deprecation warning is raised - And the value read is "admin" - - Examples: - | access | - | brackets | - | get | + Then the role name attribute is "admin" + And the role does not support dict-style access Scenario: Empty claims are falsy Given a Keycloak KeycloakTokenClaimsDTO response without claims Then the response is falsy - Scenario Outline: Adapter request payloads accept a DTO or a deprecated dict - When a payload is converted for the Keycloak adapter - Then the adapter payload is {"name": "ops"} - And the dict deprecation warning is - - Examples: - | kind | warned | - | DTO | absent | - | dict | raised | + Scenario: Plain dictionaries are rejected as Keycloak adapter request payloads + When a dict payload is converted for the Keycloak adapter + Then the adapter rejects the payload as an invalid argument Scenario Outline: Mutation responses become a typed result When the Keycloak mutation body is converted diff --git a/features/redis_adapter.feature b/features/redis_adapter.feature index 5f6e090cb..e587356de 100644 --- a/features/redis_adapter.feature +++ b/features/redis_adapter.feature @@ -1505,16 +1505,11 @@ Feature: Redis Testing | TLS disabled | without SSL | | TLS enabled without hostname checks | TLS.CHECK_HOSTNAME | - Scenario Outline: upsert_hash writes one atomic HSET and deprecates replace False + Scenario: Upserting a hash document preserves fields outside the update Given a configured container - And search index "" exists with prefix ":" for HASH documents - When I upsert the hash document ":1" with replace - Then the hash document ":1" should be stored and the deprecation warning should be - - Examples: Replace flags - | index_name | prefix | replace | warned | - | upsert-true | upt | True | absent | - | upsert-off | upf | False | raised | + And search index "upsert-merge" exists with prefix "upm:" for HASH documents + When I upsert a hash document "upm:1" twice with different fields + Then the hash document "upm:1" contains both fields Scenario Outline: Server errors surface as CacheError and stay redis-py errors Given a configured diff --git a/features/scylladb_adapter.feature b/features/scylladb_adapter.feature index cb49f2fd6..6385b19fb 100644 --- a/features/scylladb_adapter.feature +++ b/features/scylladb_adapter.feature @@ -620,15 +620,9 @@ Feature: ScyllaDB Adapter Then the retry policy should retry unavailable errors for non-idempotent statements @needs-scylladb - Scenario Outline: The cluster applies policies and timeout through the default execution profile with set - When I build a ScyllaDB cluster with set to + Scenario: The cluster applies policies and timeout through the default execution profile + When I build a ScyllaDB cluster with request timeout 8 Then the default execution profile should use the configured request timeout and retry policy - And a DeprecationWarning should - - Examples: Pool settings - | setting | value | warning | - | MAX_CONNECTIONS_PER_HOST | 4 | name "MAX_CONNECTIONS_PER_HOST" | - | MAX_REQUESTS_PER_CONNECTION | 100 | not be raised | @needs-scylladb Scenario Outline: The cluster and default profile apply the resilience settings diff --git a/features/steps/app_utils_steps.py b/features/steps/app_utils_steps.py index c96fffcf9..f21393d7c 100644 --- a/features/steps/app_utils_steps.py +++ b/features/steps/app_utils_steps.py @@ -824,7 +824,7 @@ def step_when_grpc_config_built(context, settings): for key in keys: group, _, name = key.rpartition(".") target = values.setdefault(group, {}) if group else values - if name in {"IS_ENABLED", "TLS_ENABLED", "REQUIRE_CLIENT_AUTH", "TLS_REQUIRE_CLIENT_AUTH"}: + if name in {"IS_ENABLED", "REQUIRE_CLIENT_AUTH"}: target[name] = True elif name.endswith("_FILE"): target[name] = "/nonexistent/x.pem" @@ -980,10 +980,6 @@ def step_then_no_deprecation_warning(context): assert get_current_scenario_context(context).get("caught_warnings") == [] -@then('a deprecation warning mentions "{text}"') -def step_then_deprecation_warning_mentions(context, text): - messages = get_current_scenario_context(context).get("caught_warnings") - assert any(text in message for message in messages), messages @then('building a configuration from the following fails with "{reason}":') @@ -996,49 +992,6 @@ def step_then_config_build_fails(context, reason): raise AssertionError("the config was accepted") -@when("the FASTAPI section is built with a deprecated uvicorn field") -def step_when_fastapi_section_built(context): - scenario_context = get_current_scenario_context(context) - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - FastAPIConfig(TIMEOUT_KEEP_ALIVE=9) - scenario_context.store("caught_warnings", [str(item.message) for item in caught if item.category is DeprecationWarning]) - - -@when('the {section} field "{name}" is read') -def step_when_config_field_read(context, section, name): - scenario_context = get_current_scenario_context(context) - config = scenario_context.get("built_config") - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - getattr(getattr(config, section), name) - scenario_context.store( - "caught_warnings", - [str(item.message) for item in caught if item.category is DeprecationWarning], - ) - - -@when('the UVICORN field "{name}" is read and the FASTAPI section is dumped') -def step_when_uvicorn_field_read_and_fastapi_dumped(context, name): - scenario_context = get_current_scenario_context(context) - config = scenario_context.get("built_config") - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - getattr(config.UVICORN, name) - config.FASTAPI.model_dump() - repr(config.FASTAPI) - scenario_context.store( - "caught_warnings", - [str(item.message) for item in caught if item.category is DeprecationWarning], - ) - - -@then('the JSON schema of the FASTAPI section marks "{name}" as deprecated') -def step_then_fastapi_schema_deprecated(context, name): - schema = FastAPIConfig.model_json_schema() - assert schema["properties"][name].get("deprecated") is True, schema["properties"][name] - - def _compression_grpc_config(compression: str) -> BaseConfig: return _config_with_grpc( GrpcConfig( diff --git a/features/steps/atomic_transaction_steps.py b/features/steps/atomic_transaction_steps.py index 6a9eb8d4d..2c6d1bc47 100644 --- a/features/steps/atomic_transaction_steps.py +++ b/features/steps/atomic_transaction_steps.py @@ -2823,7 +2823,7 @@ def step_given_count_cache_enabled(context, ttl): from archipy.configs.config_template import SQLAlchemyConfig scenario_context = get_current_scenario_context(context) - cache_config = SQLAlchemyConfig(COUNT_CACHE_ENABLED=True, COUNT_CACHE_TTL_SECONDS=ttl) + cache_config = SQLAlchemyConfig(COUNT_CACHE={"IS_ENABLED": True, "TTL_SECONDS": ttl}) scenario_context.store("count_cache_ttl", ttl) if scenario_context.adapter is not None: scenario_context.adapter._cached_count = _build_count_cache(cache_config) # noqa: SLF001 diff --git a/features/steps/base_config_steps.py b/features/steps/base_config_steps.py index f886a3702..1b99bb684 100644 --- a/features/steps/base_config_steps.py +++ b/features/steps/base_config_steps.py @@ -16,7 +16,7 @@ from cryptography.x509.oid import NameOID from features.environment import TestConfig from features.test_helpers import get_current_scenario_context -from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator +from pydantic import ValidationError from archipy.adapters.vault.adapters import VaultAdapter from archipy.configs.base_config import BaseConfig @@ -32,7 +32,6 @@ VaultConfig, ) from archipy.configs.environment_type import EnvironmentType -from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields from archipy.configs.vault_settings_source import create_vault_client from archipy.models.errors import ConfigurationError @@ -167,7 +166,7 @@ def step_when_init_with_vault(context): os.environ["VAULT__ADDR"] = vault.ADDR or "" os.environ["VAULT__AUTH_METHOD"] = vault.AUTH_METHOD os.environ["VAULT__MOUNT_POINT"] = vault.MOUNT_POINT - os.environ["VAULT__VERIFY_SSL"] = "true" if vault.VERIFY_SSL else "false" + os.environ["VAULT__TLS__VERIFY_SSL"] = "true" if vault.TLS.VERIFY_SSL else "false" os.environ["VAULT__SECRET_PATHS"] = '["myapp/config"]' if scenario_context.get("vault_force_invalid_token"): @@ -485,15 +484,15 @@ def step_then_starrocks_outcome(context, outcome): "no token is set": {}, "the token file cannot be read": {"TOKEN_FILE": "/nonexistent/vault-token"}, "no role id is set": {}, - "no secret id is set": {"APPROLE_ROLE_ID": "role"}, + "no secret id is set": {"APPROLE": {"ROLE_ID": "role"}}, "no username is set": {}, "no password is set": {"USERNAME": "user"}, "no role is set": {}, - "no jwt is set": {"JWT_ROLE": "role", "AZURE_ROLE": "role", "GCP_ROLE": "role"}, + "no jwt is set": {"JWT_AUTH": {"ROLE": "role"}, "AZURE": {"ROLE": "role"}, "GCP": {"ROLE": "role"}}, "no access key is set": {}, "no github token is set": {}, "no address is set": {"ADDR": None, "TOKEN": "t"}, - "only a client certificate is set": {"TOKEN": "t", "CLIENT_CERT_PATH": "/tmp/client.pem"}, + "only a client certificate is set": {"TOKEN": "t", "TLS": {"CLIENT_CERT_PATH": "/tmp/client.pem"}}, } @@ -543,9 +542,7 @@ def step_given_vault_accepts_logins(context, method): settings.update( { "AUTH_METHOD": "approle", - "APPROLE_ROLE_ID": role_id, - "APPROLE_SECRET_ID": secret_id, - "APPROLE_MOUNT_POINT": mount, + "APPROLE": {"ROLE_ID": role_id, "SECRET_ID": secret_id, "MOUNT_POINT": mount}, }, ) else: @@ -553,7 +550,7 @@ def step_given_vault_accepts_logins(context, method): admin.sys.enable_auth_method("userpass", path=mount) admin.auth.userpass.create_or_update_user("alice", "s3cret-pass", policies=["default"], mount_point=mount) settings.update( - {"AUTH_METHOD": "userpass", "USERNAME": "alice", "PASSWORD": "s3cret-pass", "USERPASS_MOUNT_POINT": mount}, + {"AUTH_METHOD": "userpass", "USERNAME": "alice", "PASSWORD": "s3cret-pass", "USERPASS": {"MOUNT_POINT": mount}}, ) scenario_context.store("vault_login_settings", settings) @@ -589,7 +586,7 @@ def step_then_vault_client_authenticated(context): def step_given_test_identity_tls_and_timeouts(context, tls, connect, read): scenario_context = get_current_scenario_context(context) settings = scenario_context.get("vault_login_settings") - settings.update({**_VAULT_TLS_SETTINGS[tls], "CONNECT_TIMEOUT": connect, "READ_TIMEOUT": read}) + settings.update(TLS=_VAULT_TLS_SETTINGS[tls], HTTP={"CONNECT_TIMEOUT": connect, "READ_TIMEOUT": read}) scenario_context.store("vault_login_settings", settings) @@ -604,158 +601,48 @@ def step_then_vault_client_request_options(context, verify, connect, read): _SECTION_SETTINGS = { ("Kafka", "SASL_SSL without credentials"): (KafkaConfig, {"SECURITY_PROTOCOL": "SASL_SSL"}), - ( - "Kafka", - "SASL_SSL with credentials", - ): ( - KafkaConfig, - {"SECURITY_PROTOCOL": "SASL_SSL", "SASL_MECHANISM": "PLAIN", "USERNAME": "user", "PASSWORD": "pass"}, - ), - ("Kafka", "grouped SASL_SSL with credentials"): ( - KafkaConfig, - {"SECURITY_PROTOCOL": "SASL_SSL", "SASL": {"MECHANISM": "plain", "USERNAME": "user", "PASSWORD": "pass"}}, - ), - ("Kafka", "grouped SASL_SSL without a password"): ( - KafkaConfig, - {"SECURITY_PROTOCOL": "SASL_SSL", "SASL": {"MECHANISM": "PLAIN", "USERNAME": "user"}}, - ), - ("Kafka", "auto commit and no offset reset"): ( - KafkaConfig, - {"ENABLE_AUTO_COMMIT": True, "AUTO_OFFSET_RESET": "none"}, - ), - ("Kafka", "a heartbeat longer than the session"): ( - KafkaConfig, - {"HEARTBEAT_INTERVAL_MS": 20000, "SESSION_TIMEOUT_MS": 10000}, - ), + ("Kafka", "SASL_SSL with credentials"): (KafkaConfig, {"SECURITY_PROTOCOL": "SASL_SSL", "SASL": {"MECHANISM": "PLAIN", "USERNAME": "user", "PASSWORD": "pass"}}), + ("Kafka", "grouped SASL_SSL with credentials"): (KafkaConfig, {"SECURITY_PROTOCOL": "SASL_SSL", "SASL": {"MECHANISM": "plain", "USERNAME": "user", "PASSWORD": "pass"}}), + ("Kafka", "grouped SASL_SSL without a password"): (KafkaConfig, {"SECURITY_PROTOCOL": "SASL_SSL", "SASL": {"MECHANISM": "PLAIN", "USERNAME": "user"}}), + ("Kafka", "auto commit and no offset reset"): (KafkaConfig, {"ENABLE_AUTO_COMMIT": True, "AUTO_OFFSET_RESET": "none"}), + ("Kafka", "a heartbeat longer than the session"): (KafkaConfig, {"HEARTBEAT_INTERVAL_MS": 20000, "SESSION_TIMEOUT_MS": 10000}), ("Redis", "cluster mode without nodes"): (RedisConfig, {"MODE": "CLUSTER"}), ("Redis", "grouped cluster mode without nodes"): (RedisConfig, {"MODE": "CLUSTER", "CLUSTER": {"NODES": []}}), - ("Redis", "grouped cluster mode with nodes"): ( - RedisConfig, - {"MODE": "CLUSTER", "CLUSTER": {"NODES": ["localhost:7000"]}}, - ), - ("Redis", "grouped sentinel mode without a service name"): ( - RedisConfig, - {"MODE": "SENTINEL", "SENTINEL": {"NODES": ["localhost:26379"]}}, - ), - ("Redis", "grouped client certificate without a key"): ( - RedisConfig, - {"TLS": {"IS_ENABLED": True, "CERTFILE": "/tmp/c.pem"}}, - ), + ("Redis", "grouped cluster mode with nodes"): (RedisConfig, {"MODE": "CLUSTER", "CLUSTER": {"NODES": ["localhost:7000"]}}), + ("Redis", "grouped sentinel mode without a service name"): (RedisConfig, {"MODE": "SENTINEL", "SENTINEL": {"NODES": ["localhost:26379"]}}), + ("Redis", "grouped client certificate without a key"): (RedisConfig, {"TLS": {"IS_ENABLED": True, "CERTFILE": "/tmp/c.pem"}}), ("Redis", "grouped CA file with TLS disabled"): (RedisConfig, {"TLS": {"CA_CERTS": "/tmp/ca.pem"}}), - ("Redis", "cluster mode with nodes"): (RedisConfig, {"MODE": "CLUSTER", "CLUSTER_NODES": ["localhost:7000"]}), - ("Redis", "sentinel mode without a service name"): ( - RedisConfig, - {"MODE": "SENTINEL", "SENTINEL_NODES": ["localhost:26379"]}, - ), ("Redis", "standalone mode without a host"): (RedisConfig, {"MODE": "STANDALONE", "MASTER_HOST": ""}), ("ScyllaDB", "no contact points"): (ScyllaDBConfig, {"CONTACT_POINTS": []}), ("ScyllaDB", "a username without a password"): (ScyllaDBConfig, {"USERNAME": "user"}), - ("ScyllaDB", "a minimum pool above the maximum"): ( - ScyllaDBConfig, - {"MIN_CONNECTIONS_PER_HOST": 10, "MAX_CONNECTIONS_PER_HOST": 2}, - ), - ("ScyllaDB", "a client certificate without a key"): ( - ScyllaDBConfig, - {"TLS_ENABLED": True, "TLS_CERT_FILE": "/tmp/client.pem"}, - ), - ("ScyllaDB", "a CA file with TLS disabled"): (ScyllaDBConfig, {"TLS_CA_FILE": "/tmp/ca.pem"}), - ("ScyllaDB", "an exponential reconnection base above the maximum"): ( - ScyllaDBConfig, - {"RECONNECTION_POLICY": "EXPONENTIAL", "RECONNECTION_BASE_DELAY": 20.0, "RECONNECTION_MAX_DELAY": 5.0}, - ), - ("ScyllaDB", "an exponential reconnection within bounds"): ( - ScyllaDBConfig, - {"RECONNECTION_POLICY": "EXPONENTIAL", "RECONNECTION_BASE_DELAY": 1.0, "RECONNECTION_MAX_DELAY": 5.0}, - ), - ("ScyllaDB", "TLS enabled with a CA file"): (ScyllaDBConfig, {"TLS_ENABLED": True, "TLS_CA_FILE": "/tmp/ca.pem"}), - ("ScyllaDB", "a grouped client certificate without a key"): ( - ScyllaDBConfig, - {"TLS": {"IS_ENABLED": True, "CERT_FILE": "/tmp/client.pem"}}, - ), - ("ScyllaDB", "a grouped CA file with TLS disabled"): (ScyllaDBConfig, {"TLS": {"CA_FILE": "/tmp/ca.pem"}}), - ("ScyllaDB", "a grouped exponential reconnection above the max"): ( - ScyllaDBConfig, - {"RECONNECTION": {"POLICY": "EXPONENTIAL", "BASE_DELAY": 20.0, "MAX_DELAY": 5.0}}, - ), - ("ScyllaDB", "a grouped replication without datacenters"): ( - ScyllaDBConfig, - {"REPLICATION": {"STRATEGY": "NetworkTopologyStrategy", "CONFIG": {}}}, - ), - ("ScyllaDB", "grouped TLS enabled with a CA file"): ( - ScyllaDBConfig, - {"TLS": {"IS_ENABLED": True, "CA_FILE": "/tmp/ca.pem"}}, - ), + ("ScyllaDB", "a client certificate without a key"): (ScyllaDBConfig, {"TLS": {"IS_ENABLED": True, "CERT_FILE": "/tmp/client.pem"}}), + ("ScyllaDB", "a CA file with TLS disabled"): (ScyllaDBConfig, {"TLS": {"CA_FILE": "/tmp/ca.pem"}}), + ("ScyllaDB", "an exponential reconnection base above the maximum"): (ScyllaDBConfig, {"RECONNECTION": {"POLICY": "EXPONENTIAL", "BASE_DELAY": 20.0, "MAX_DELAY": 5.0}}), + ("ScyllaDB", "an exponential reconnection within bounds"): (ScyllaDBConfig, {"RECONNECTION": {"POLICY": "EXPONENTIAL", "BASE_DELAY": 1.0, "MAX_DELAY": 5.0}}), + ("ScyllaDB", "TLS enabled with a CA file"): (ScyllaDBConfig, {"TLS": {"IS_ENABLED": True, "CA_FILE": "/tmp/ca.pem"}}), + ("ScyllaDB", "a grouped replication without datacenters"): (ScyllaDBConfig, {"REPLICATION": {"STRATEGY": "NetworkTopologyStrategy", "CONFIG": {}}}), ("Elasticsearch", "grouped username without a password"): (ElasticsearchConfig, {"AUTH": {"USER_NAME": "user"}}), - ("Elasticsearch", "grouped client cert without a key"): ( - ElasticsearchConfig, - {"TLS": {"CLIENT_CERT": "/tmp/c.pem"}}, - ), - ("Elasticsearch", "grouped CA file with verification disabled"): ( - ElasticsearchConfig, - {"TLS": {"VERIFY_CERTS": False, "CA_CERTS": "/tmp/ca.pem"}}, - ), - ("Elasticsearch", "only a username"): (ElasticsearchConfig, {"HTTP_USER_NAME": "user"}), - ("Elasticsearch", "only a password"): (ElasticsearchConfig, {"HTTP_PASSWORD": "secret"}), - ("Elasticsearch", "only an API key"): (ElasticsearchConfig, {"API_KEY": "id"}), - ("Elasticsearch", "only an API secret"): (ElasticsearchConfig, {"API_SECRET": "secret"}), - ("Elasticsearch", "a username and password"): ( - ElasticsearchConfig, - {"HTTP_USER_NAME": "user", "HTTP_PASSWORD": "secret"}, - ), - ("Elasticsearch", "a client key without a certificate"): (ElasticsearchConfig, {"CLIENT_KEY": "/tmp/c.key"}), - ("Elasticsearch", "a client certificate and key"): ( - ElasticsearchConfig, - {"CLIENT_CERT": "/tmp/c.pem", "CLIENT_KEY": "/tmp/c.key"}, - ), + ("Elasticsearch", "grouped client cert without a key"): (ElasticsearchConfig, {"TLS": {"CLIENT_CERT": "/tmp/c.pem"}}), + ("Elasticsearch", "grouped CA file with verification disabled"): (ElasticsearchConfig, {"TLS": {"VERIFY_CERTS": False, "CA_CERTS": "/tmp/ca.pem"}}), + ("Elasticsearch", "only a password"): (ElasticsearchConfig, {"AUTH": {"PASSWORD": "secret"}}), + ("Elasticsearch", "only an API key"): (ElasticsearchConfig, {"AUTH": {"API_KEY": "id"}}), + ("Elasticsearch", "only an API secret"): (ElasticsearchConfig, {"AUTH": {"API_SECRET": "secret"}}), + ("Elasticsearch", "a username and password"): (ElasticsearchConfig, {"AUTH": {"USER_NAME": "user", "PASSWORD": "secret"}}), + ("Elasticsearch", "a client key without a certificate"): (ElasticsearchConfig, {"TLS": {"CLIENT_KEY": "/tmp/c.key"}}), + ("Elasticsearch", "a client certificate and key"): (ElasticsearchConfig, {"TLS": {"CLIENT_CERT": "/tmp/c.pem", "CLIENT_KEY": "/tmp/c.key"}}), ("Elasticsearch", "an unknown node selector"): (ElasticsearchConfig, {"NODE_SELECTOR_CLASS": "fastest"}), ("Elasticsearch", "the random node selector"): (ElasticsearchConfig, {"NODE_SELECTOR_CLASS": "random"}), - ("OpenTelemetry", "a pushgateway exporter without a URL"): ( - OpentelemetryConfig, - {"METRICS_EXPORTER": "pushgateway"}, - ), - ("OpenTelemetry", "a pushgateway exporter with a grouped URL"): ( - OpentelemetryConfig, - {"METRICS_EXPORTER": "pushgateway", "PUSHGATEWAY": {"URL": "http://pushgateway:9091"}}, - ), - ("Temporal", "only a client certificate"): (TemporalConfig, {"TLS_CLIENT_CERT": "/tmp/client.pem"}), - ("Temporal", "a grouped client certificate without a key"): ( - TemporalConfig, - {"TLS": {"CLIENT_CERT": "/tmp/client.pem"}}, - ), - ("Temporal", "a grouped run timeout above the execution one"): ( - TemporalConfig, - {"WORKFLOW": {"RUN_TIMEOUT": 7200, "EXECUTION_TIMEOUT": 3600}}, - ), - ("Temporal", "a grouped keep alive timeout above the interval"): ( - TemporalConfig, - {"KEEP_ALIVE": {"TIMEOUT_MS": 60000, "INTERVAL_MS": 30000}}, - ), - ("Temporal", "a grouped client certificate with a key"): ( - TemporalConfig, - {"TLS": {"CLIENT_CERT": "/tmp/client.pem", "CLIENT_KEY": "/tmp/client.key"}}, - ), - ("Temporal", "only a CA certificate"): (TemporalConfig, {"TLS_CA_CERT": "/tmp/ca.pem"}), - ("Temporal", "a client key without a certificate"): (TemporalConfig, {"TLS_CLIENT_KEY": "/tmp/client.key"}), - ("Temporal", "a verification name without a CA"): ( - TemporalConfig, - {"TLS_VERIFICATION_SERVER_NAME": "temporal.internal"}, - ), - ("Temporal", "a verification name with a CA"): ( - TemporalConfig, - {"TLS_VERIFICATION_SERVER_NAME": "temporal.internal", "TLS_CA_CERT": "/tmp/ca.pem"}, - ), - ("Temporal", "a run timeout above the execution one"): ( - TemporalConfig, - {"WORKFLOW_RUN_TIMEOUT": 7200, "WORKFLOW_EXECUTION_TIMEOUT": 3600}, - ), - ("Temporal", "a task timeout above the run timeout"): ( - TemporalConfig, - {"WORKFLOW_TASK_TIMEOUT": 60, "WORKFLOW_RUN_TIMEOUT": 30, "WORKFLOW_EXECUTION_TIMEOUT": 120}, - ), - ("Temporal", "a keep alive timeout above the interval"): ( - TemporalConfig, - {"KEEP_ALIVE_TIMEOUT_MS": 60000, "KEEP_ALIVE_INTERVAL_MS": 30000}, - ), + ("OpenTelemetry", "a pushgateway exporter without a URL"): (OpentelemetryConfig, {"METRICS_EXPORTER": "pushgateway"}), + ("OpenTelemetry", "a pushgateway exporter with a grouped URL"): (OpentelemetryConfig, {"METRICS_EXPORTER": "pushgateway", "PUSHGATEWAY": {"URL": "http://pushgateway:9091"}}), + ("Temporal", "only a client certificate"): (TemporalConfig, {"TLS": {"CLIENT_CERT": "/tmp/client.pem"}}), + ("Temporal", "a grouped run timeout above the execution one"): (TemporalConfig, {"WORKFLOW": {"RUN_TIMEOUT": 7200, "EXECUTION_TIMEOUT": 3600}}), + ("Temporal", "a grouped keep alive timeout above the interval"): (TemporalConfig, {"KEEP_ALIVE": {"TIMEOUT_MS": 60000, "INTERVAL_MS": 30000}}), + ("Temporal", "a grouped client certificate with a key"): (TemporalConfig, {"TLS": {"CLIENT_CERT": "/tmp/client.pem", "CLIENT_KEY": "/tmp/client.key"}}), + ("Temporal", "only a CA certificate"): (TemporalConfig, {"TLS": {"CA_CERT": "/tmp/ca.pem"}}), + ("Temporal", "a client key without a certificate"): (TemporalConfig, {"TLS": {"CLIENT_KEY": "/tmp/client.key"}}), + ("Temporal", "a verification name without a CA"): (TemporalConfig, {"TLS": {"VERIFICATION_SERVER_NAME": "temporal.internal"}}), + ("Temporal", "a verification name with a CA"): (TemporalConfig, {"TLS": {"VERIFICATION_SERVER_NAME": "temporal.internal", "CA_CERT": "/tmp/ca.pem"}}), + ("Temporal", "a task timeout above the run timeout"): (TemporalConfig, {"WORKFLOW": {"TASK_TIMEOUT": 60, "RUN_TIMEOUT": 30, "EXECUTION_TIMEOUT": 120}}), } @@ -786,7 +673,9 @@ def step_when_default_temporal_config_built(context): @then("the default Temporal setting {field} should be {expected}") def step_then_temporal_default(context, field, expected): - actual = getattr(get_current_scenario_context(context).get("temporal_config"), field) + actual = get_current_scenario_context(context).get("temporal_config") + for part in field.split("."): + actual = getattr(actual, part) assert str(actual) == expected, f"Expected {field}={expected}, got {actual!r}" @@ -836,13 +725,13 @@ def step_when_elasticsearch_bearer_conflict(context, other): from archipy.configs.config_template import ElasticsearchConfig from archipy.models.errors import InvalidArgumentError - updates = {"BEARER_AUTH": "token"} + auth = {"BEARER": "token"} if other == "API key": - updates.update(API_KEY="id", API_SECRET="secret") + auth.update(API_KEY="id", API_SECRET="secret") else: - updates.update(HTTP_USER_NAME="user", HTTP_PASSWORD="password") + auth.update(USER_NAME="user", PASSWORD="password") try: - ElasticsearchConfig(**updates) + ElasticsearchConfig(AUTH=auth) except InvalidArgumentError: get_current_scenario_context(context).store("es_config_rejected", True) else: @@ -916,8 +805,8 @@ def _write_test_certificate(directory: Path) -> tuple[Path, Path]: _SCYLLADB_TLS_SETTINGS = { "TLS disabled": {}, "a CA file": {}, - "a CA file and no host name check": {"TLS_CHECK_HOSTNAME": False}, - "verification disabled": {"TLS_VERIFY_MODE": "CERT_NONE"}, + "a CA file and no host name check": {"CHECK_HOSTNAME": False}, + "verification disabled": {"VERIFY_MODE": "CERT_NONE"}, "a CA file and a client certificate": {}, } @@ -929,12 +818,12 @@ def step_when_scylladb_tls_context_built(context, tls): cert_path, key_path = _write_test_certificate(directory) settings = dict(_SCYLLADB_TLS_SETTINGS[tls]) if tls != "TLS disabled": - settings["TLS_ENABLED"] = True + settings["IS_ENABLED"] = True if "CA file" in tls: - settings["TLS_CA_FILE"] = str(cert_path) + settings["CA_FILE"] = str(cert_path) if "client certificate" in tls: - settings.update(TLS_CERT_FILE=str(cert_path), TLS_KEY_FILE=str(key_path)) - ssl_context = ScyllaDBConfig(**settings).build_ssl_context() + settings.update(CERT_FILE=str(cert_path), KEY_FILE=str(key_path)) + ssl_context = ScyllaDBConfig(TLS=settings).build_ssl_context() get_current_scenario_context(context).store("scylladb_ssl_context", ssl_context) @@ -958,11 +847,11 @@ def step_then_scylladb_tls_context(context, expected): @when("an Elasticsearch config is built with {credential} and {transport}") def step_when_elasticsearch_insecure_config(context, credential, transport): - updates = {"HTTP_USER_NAME": "user", "HTTP_PASSWORD": "secret"} if credential == "credentials" else {} + updates = {"AUTH": {"USER_NAME": "user", "PASSWORD": "secret"}} if credential == "credentials" else {} if transport == "an http host": updates["HOSTS"] = ["http://es:9200"] elif transport == "verification disabled": - updates["VERIFY_CERTS"] = False + updates["TLS"] = {"VERIFY_CERTS": False} messages: list[str] = [] class _Capture(logging.Handler): @@ -986,51 +875,7 @@ def step_then_elasticsearch_warning_count(context, count): assert len(messages) == count, messages -class _FoldGroup(BaseModel): - model_config = ConfigDict(extra="forbid") - - NAME: str | None = None - - -class _FoldSection(BaseModel): - NAME: str | None = Field(default=None, deprecated=deprecated_flat_message("TEST", "NAME", "GROUP", "NAME")) - GROUP: _FoldGroup | None = None - - @model_validator(mode="after") - def _fold(self): - fold_flat_fields(self, "GROUP", _FoldGroup, {"NAME": "NAME"}) - return self - - -@given('a test section with flat "{flat}" set to {flat_value} and group "{group}" set to {group_value}') -def step_given_fold_section(context, flat, flat_value, group, group_value): - scenario_context = get_current_scenario_context(context) - scenario_context.store("fold_flat", {} if flat == "none" else {flat: json.loads(flat_value)}) - scenario_context.store("fold_group", None if group == "none" else {group: json.loads(group_value)}) - - -@when("the test section is validated") -def step_when_fold_validated(context): - scenario_context = get_current_scenario_context(context) - group = scenario_context.get("fold_group") - data = dict(scenario_context.get("fold_flat")) - if group is not None: - data["GROUP"] = group - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - section = _FoldSection(**data) - scenario_context.store("fold_section", section) - scenario_context.store("fold_warnings", [w for w in caught if issubclass(w.category, DeprecationWarning)]) - - -@then("the group value should be {expected}") -def step_then_fold_value(context, expected): - section = get_current_scenario_context(context).get("fold_section") - actual = section.GROUP.NAME if section.GROUP else None - assert actual == json.loads(expected), actual - - -@then("{count:d} deprecation warning should be raised") -def step_then_fold_warnings(context, count): - caught = get_current_scenario_context(context).get("fold_warnings") - assert len(caught) == count, [str(w.message) for w in caught] +@then('the "{section}" configuration has no "{field}" field') +def step_then_config_schema_excludes_field(context, section, field): + config_type = type(getattr(BaseConfig.global_config(), section)) + assert field not in config_type.model_fields diff --git a/features/steps/deprecation_decorators_steps.py b/features/steps/deprecation_decorators_steps.py index b3fa20930..df887fd53 100644 --- a/features/steps/deprecation_decorators_steps.py +++ b/features/steps/deprecation_decorators_steps.py @@ -234,47 +234,6 @@ def step_then_error_class_doc(context): # ---- renamed decorators ---- -_OLD_NAME_CALLS = { - "retry_decorator": lambda fn: fn(max_retries=2), - "timeout_decorator": lambda fn: fn(1), - "timing_decorator": lambda fn: fn(lambda: None), - "singleton_decorator": lambda fn: fn(), - "ttl_cache_decorator": lambda fn: fn(ttl_seconds=1), - "grpc_rate_limit_decorator": lambda fn: fn(calls_count=1, seconds=1), - "sqlalchemy_atomic_decorator": lambda fn: fn("sqlite"), -} - - -def _call_old_name(fn, name): - call = _OLD_NAME_CALLS.get(name, lambda f: f()) - return call(fn) - - -@when('the old decorator name "{old_name}" is applied') -def step_when_old_name_applied(context, old_name): - from archipy.helpers import decorators - - sc = get_current_scenario_context(context) - fn = getattr(decorators, old_name) - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - sc.store("old_name_result", _call_old_name(fn, old_name)) - sc.store("deprecation_warnings", [w for w in caught if issubclass(w.category, DeprecationWarning)]) - - -@then('exactly one DeprecationWarning should name "{replacement}"') -def step_then_one_warning_names(context, replacement): - caught = get_current_scenario_context(context).get("deprecation_warnings") - assert len(caught) == 1, f"Got {[str(w.message) for w in caught]}" - assert f"use {replacement} instead" in str(caught[0].message), str(caught[0].message) - - -@then("the DeprecationWarning should point at the calling code") -def step_then_warning_points_at_caller(context): - caught = get_current_scenario_context(context).get("deprecation_warnings") - assert caught[0].filename.endswith("deprecation_decorators_steps.py"), caught[0].filename - - @when('the new decorator name "{new_name}" is imported from the decorators package') def step_when_new_name_imported(context, new_name): from archipy.helpers import decorators @@ -305,54 +264,3 @@ def step_then_function_not_module(context): def step_then_no_deprecation_warning(context): caught = get_current_scenario_context(context).get("deprecation_warnings") assert caught == [], f"Got {[str(w.message) for w in caught]}" - - -@when('"{name}" is imported from the old module path "{module}"') -def step_when_imported_from_old_path(context, name, module): - imported = importlib.import_module(f"archipy.helpers.decorators.{module}") - get_current_scenario_context(context).store("old_path_object", getattr(imported, name)) - - -@then("the old module path should resolve to a callable") -def step_then_old_path_callable(context): - assert callable(get_current_scenario_context(context).get("old_path_object")) - - -# Keycloak auth guards moved to archipy.adapters.keycloak.auth - - -@when('the deprecated KeycloakUtils method "{name}" is called') -def step_when_deprecated_auth_function_called(context, name): - from archipy.helpers.utils import keycloak_utils - - sc = get_current_scenario_context(context) - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - function = getattr(keycloak_utils.KeycloakUtils, name) - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - sc.store("result", function()) - sc.store("deprecation_warnings", [w for w in caught if issubclass(w.category, DeprecationWarning)]) - - -@when('"{name}" is read from the old Keycloak utils module') -def step_when_read_from_old_keycloak_utils(context, name): - from archipy.helpers.utils import keycloak_utils - - sc = get_current_scenario_context(context) - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - sc.store("result", getattr(keycloak_utils, name)) - sc.store("deprecation_warnings", [w for w in caught if issubclass(w.category, DeprecationWarning)]) - - -@then("the Keycloak auth result is callable") -def step_then_keycloak_auth_module_result_callable(context): - assert callable(get_current_scenario_context(context).get("result")) - - -@then("the legacy KeycloakUtils exposes fastapi_auth, async_fastapi_auth, grpc_auth and async_grpc_auth") -def step_then_legacy_namespace_methods(context): - legacy = get_current_scenario_context(context).get("result") - for name in ("fastapi_auth", "async_fastapi_auth", "grpc_auth", "async_grpc_auth"): - assert callable(getattr(legacy, name)), name diff --git a/features/steps/elastic_adapter_steps.py b/features/steps/elastic_adapter_steps.py index 65c75ea17..cd60d3085 100644 --- a/features/steps/elastic_adapter_steps.py +++ b/features/steps/elastic_adapter_steps.py @@ -977,7 +977,6 @@ def step_es_config_field(context: Context, field: str, value: str) -> None: "SSL_VERSION": lambda text: ssl.TLSVersion[text], "OPAQUE_ID": str, "HEADERS": lambda text: dict(pair.split("=", 1) for pair in text.split(",")), - "MAP_ERRORS": lambda text: text == "true", "IGNORE_STATUS": lambda text: tuple(int(code) for code in text.split(",")), } updates[_ES_GROUPED_FIELDS.get(field, field)] = parsers[field](value) @@ -992,16 +991,10 @@ async def step_create_adapter_from_config(context: Context, mode: str) -> None: """Build an adapter from the overridden config.""" scenario_context = _get_scenario_context(context) config = _apply_es_updates(BaseConfig.global_config().ELASTIC, scenario_context.get("es_config_updates", {})) - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - if _is_async_scenario(context): - scenario_context.async_adapter = AsyncElasticsearchAdapter(config) - else: - scenario_context.adapter = ElasticsearchAdapter(config) - scenario_context.store( - "creation_warnings", - [w for w in caught if issubclass(w.category, DeprecationWarning) and "MAP_ERRORS" in str(w.message)], - ) + if _is_async_scenario(context): + scenario_context.async_adapter = AsyncElasticsearchAdapter(config) + else: + scenario_context.adapter = ElasticsearchAdapter(config) @then('the client should apply "{field}" as "{value}"') @@ -1082,11 +1075,6 @@ def step_raised_error_kind(context: Context, kind: str) -> None: assert isinstance(error.__cause__, ClientNotFoundError), "Original error must be chained" -@then("the adapter creation should {outcome} the ArchiPy error mapping deprecation warning") -def step_creation_warning(context: Context, outcome: str) -> None: - """Verify whether adapter creation warned about the opt-in error mapping.""" - caught = _get_scenario_context(context).get("creation_warnings") - assert bool(caught) == (outcome == "emit"), f"Unexpected warnings: {caught}" @when("I {operation} through an adapter that records retry options") diff --git a/features/steps/email_adapter_steps.py b/features/steps/email_adapter_steps.py index a829391ab..f1cf6af18 100644 --- a/features/steps/email_adapter_steps.py +++ b/features/steps/email_adapter_steps.py @@ -6,7 +6,6 @@ import tempfile import threading import time -import warnings from http.server import BaseHTTPRequestHandler, HTTPServer from pathlib import Path from unittest import mock @@ -118,6 +117,7 @@ def _configure_mailpit(context, name): SMTP_PORT=mailpit.smtp_port, USERNAME=mailpit.USERNAME, PASSWORD=mailpit.PASSWORD, + TLS={"CA_FILE": mailpit.ca_file}, ) @@ -706,7 +706,9 @@ def step_no_span_exposes(context, secret): @given('the SMTP transport security is "{mode}"') def step_given_transport_security(context, mode): - BaseConfig.global_config().EMAIL.TLS.MODE = mode + config = BaseConfig.global_config().EMAIL + config.TLS.MODE = mode + config.TLS.CA_FILE = None @given('the SMTP transport security is "{mode}" verified with the Mailpit CA') @@ -716,11 +718,12 @@ def step_given_transport_security_mailpit_ca(context, mode): config.TLS.CA_FILE = _mailpit("mailpit").ca_file -@given('the SMTP transport security is "{mode}" without certificate verification') -def step_given_transport_security_unverified(context, mode): +@given('the SMTP transport security is "{mode}" without credentials') +def step_given_transport_security_no_credentials(context, mode): config = BaseConfig.global_config().EMAIL config.TLS.MODE = mode - config.TLS.VERIFY = False + config.USERNAME = None + config.PASSWORD = None @given('the SMTP transport security is "{mode}" verified with the local SMTPS CA') @@ -791,19 +794,10 @@ def step_given_local_identity(context, hostname, address): def step_when_create_adapter(context): scenario_context = get_current_scenario_context(context) scenario_context.store("error", None) - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - try: - scenario_context.store("email_adapter", EmailAdapter()) - except Exception as exception: - scenario_context.store("error", exception) - scenario_context.store("warnings", [w for w in caught if issubclass(w.category, DeprecationWarning)]) - - -@then('an email deprecation warning mentions "{text}"') -def step_then_deprecation_warning(context, text): - caught = get_current_scenario_context(context).get("warnings") - assert any(text in str(w.message) for w in caught), [str(w.message) for w in caught] + try: + scenario_context.store("email_adapter", EmailAdapter()) + except ConfigurationError as exception: + scenario_context.store("error", exception) @then('a configuration error is raised for "{operation}"') @@ -843,7 +837,9 @@ def step_when_build_config(context, field, value): scenario_context = get_current_scenario_context(context) scenario_context.store("error", None) try: - EmailConfig(**{field: value}) + group, separator, name = field.partition(".") + values = {group: {name: value}} if separator else {field: value} + EmailConfig(**values) except ValidationError as exception: scenario_context.store("error", exception) @@ -852,9 +848,14 @@ def step_when_build_config(context, field, value): def step_then_config_rejected(context, field): error = get_current_scenario_context(context).get("error") assert isinstance(error, ValidationError), repr(error) - assert field in {location for item in error.errors() for location in item["loc"]}, str(error) + assert any(tuple(item["loc"][-len(field.split(".")):]) == tuple(field.split(".")) for item in error.errors()), str(error) @given('the SMTP sender address "{address}"') def step_given_sender_address(context, address): BaseConfig.global_config().EMAIL.FROM_ADDRESS = address + + +@when("I build an email config with TLS setting {field} set to {value}") +def step_when_build_tls_config(context, field, value): + step_when_build_config(context, f"TLS.{field}", json.loads(value)) diff --git a/features/steps/jwt_utils_steps.py b/features/steps/jwt_utils_steps.py index 053848a70..031ab8d02 100644 --- a/features/steps/jwt_utils_steps.py +++ b/features/steps/jwt_utils_steps.py @@ -205,18 +205,6 @@ def step_when_auth_config_leeway(context, leeway): scenario_context.store("config_error", e) -@when("an authentication configuration is built with the deprecated flat leeway of {leeway:d}") -def step_when_auth_config_flat_leeway(context, leeway): - from pydantic import ValidationError - - from archipy.configs.config_template import AuthConfig - - scenario_context = get_current_scenario_context(context) - try: - AuthConfig(JWT_LEEWAY=leeway) - scenario_context.store("config_error", None) - except ValidationError as e: - scenario_context.store("config_error", e) @then("the configuration is rejected") diff --git a/features/steps/kafka_adapter_steps.py b/features/steps/kafka_adapter_steps.py index 10eb0da46..d6bcee463 100644 --- a/features/steps/kafka_adapter_steps.py +++ b/features/steps/kafka_adapter_steps.py @@ -1266,35 +1266,26 @@ def step_logs_hide_payload(context, topic_name, payload): assert payload not in logs, f"Payload leaked into logs: {logs}" -@when('a {mode} producer with missing keys sent as {setting} produces a message without a key to topic "{topic_name}"') -def step_produce_without_key(context, mode, setting, topic_name): - """Produce a keyless message, noting whether the legacy empty key raised a DeprecationWarning.""" - import warnings - - config = _get_kafka_config(context).model_copy( - update={"EMPTY_KEY_FOR_MISSING_KEY": setting == "an empty key"}, - ) - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - if mode == "sync": - producer = KafkaProducerAdapter(topic_name, kafka_configs=config) - producer.produce("keyless") +@when('a {mode} producer sends a message with {key_state} to topic "{topic_name}"') +async def step_produce_with_optional_key(context, mode, key_state, topic_name): + config = _get_kafka_config(context) + key = "" if key_state == "an empty key" else None + if mode == "sync": + producer = KafkaProducerAdapter(topic_name, kafka_configs=config) + try: + producer.produce("keyless", key=key) + finally: producer.close() - else: - - async def run(): - producer = AsyncKafkaProducerAdapter(topic_name, kafka_configs=config) - await producer.produce("keyless") - await producer.close() - - asyncio.run(run()) - scenario_context = get_current_scenario_context(context) - scenario_context.store("kafka_deprecation_warned", any(issubclass(w.category, DeprecationWarning) for w in caught)) + else: + producer = AsyncKafkaProducerAdapter(topic_name, kafka_configs=config) + try: + await producer.produce("keyless", key=key) + finally: + await producer.close() -@then('the message on topic "{topic_name}" should have {key_state} and the deprecation warning should be {warned}') -def step_keyless_message_key(context, topic_name, key_state, warned): - """Read the keyless message and check the key and the deprecation warning.""" +@then('the message on topic "{topic_name}" should have {key_state}') +def step_keyless_message_key(context, topic_name, key_state): config = _get_kafka_config(context) consumer = KafkaConsumerAdapter(f"keyless-group-{topic_name}", topic_list=[topic_name], kafka_configs=config) try: @@ -1304,8 +1295,6 @@ def step_keyless_message_key(context, topic_name, key_state, warned): assert message is not None, "No message received" expected_key = None if key_state == "no key" else b"" assert message.key() == expected_key, f"Expected key {expected_key!r}, got {message.key()!r}" - expected_warning = warned == "raised" - assert get_current_scenario_context(context).get("kafka_deprecation_warned") is expected_warning @when( @@ -1636,16 +1625,14 @@ async def run(): def _sasl_ssl_config(setting): """Build a SASL_SSL configuration, leaving hostname verification at its default unless a value is given.""" - values = { - "SECURITY_PROTOCOL": "SASL_SSL", - "SASL_MECHANISM": "PLAIN", - "USERNAME": "user", - "PASSWORD": "pass", - "SSL_CA_FILE": "/etc/ssl/certs/kafka-ca.pem", - } + ssl = {"CA_FILE": "/etc/ssl/certs/kafka-ca.pem"} if setting != "default": - values["SSL_ENDPOINT_IDENTIFICATION_ALGORITHM"] = setting - return KafkaConfig(**values) + ssl["ENDPOINT_IDENTIFICATION_ALGORITHM"] = setting + return KafkaConfig( + SECURITY_PROTOCOL="SASL_SSL", + SASL={"MECHANISM": "PLAIN", "USERNAME": "user", "PASSWORD": "pass"}, + SSL=ssl, + ) @when("Kafka client settings are built for a {role} with hostname verification {setting}") @@ -1679,13 +1666,12 @@ def _optional(value): def _security_values(protocol, mechanism, username, extra): """Build KafkaConfig keyword arguments, leaving out every setting given as '-'.""" - values = {"SECURITY_PROTOCOL": protocol, **extra} + sasl = {} if _optional(mechanism): - values["SASL_MECHANISM"] = mechanism + sasl["MECHANISM"] = mechanism if _optional(username): - values["USERNAME"] = username - values["PASSWORD"] = "pass" - return values + sasl.update(USERNAME=username, PASSWORD="pass") + return {"SECURITY_PROTOCOL": protocol, "SASL": sasl, "SSL": extra} @when( @@ -1694,7 +1680,7 @@ def _security_values(protocol, mechanism, username, extra): ) def step_build_protocol_settings(context, protocol, mechanism, username, ca, cert, key): """Build the librdkafka settings for a protocol and the security options that are set.""" - files = {"SSL_CA_FILE": ca, "SSL_CERT_FILE": cert, "SSL_KEY_FILE": key} + files = {"CA_FILE": ca, "CERT_FILE": cert, "KEY_FILE": key} extra = {name: value for name, value in files.items() if _optional(value)} config = KafkaConfig(**_security_values(protocol, mechanism, username, extra)) settings = {} diff --git a/features/steps/keycloak_adapter_steps.py b/features/steps/keycloak_adapter_steps.py index 6e3d1243d..458bcb01f 100644 --- a/features/steps/keycloak_adapter_steps.py +++ b/features/steps/keycloak_adapter_steps.py @@ -11,7 +11,7 @@ from behave.runner import Context from keycloak.exceptions import KeycloakGetError from features.scenario_context import ScenarioContext -from features.test_containers import ContainerManager +from features.test_containers import ContainerManager, keycloak_test_issuer from features.test_helpers import get_current_scenario_context from archipy.adapters.keycloak.adapters import AsyncKeycloakAdapter, KeycloakAdapter @@ -212,6 +212,11 @@ async def step_create_client_with_service_accounts( context.logger.exception("Client creation failed") +def _configure_realm(config, realm): + config.REALM_NAME = realm + config.TOKEN_VALIDATION.EXPECTED_ISSUER = keycloak_test_issuer(config.SERVER_URL, realm) + + async def update_adapter_config( adapter: AsyncKeycloakAdapter | KeycloakAdapter, client_name: str, @@ -221,7 +226,7 @@ async def update_adapter_config( ) -> None: try: original_realm = adapter.configs.REALM_NAME - adapter.configs.REALM_NAME = realm_name + _configure_realm(adapter.configs, realm_name) adapter._admin_adapter = None adapter._admin_token_expiry = 0 if adapter.configs.ADMIN.IS_ENABLED and ( @@ -229,9 +234,9 @@ async def update_adapter_config( ): adapter._initialize_admin_client() client_result = scenario_context.get(f"client_{client_name}") - if not client_result or "internal_client_id" not in client_result: + if not client_result or not client_result.internal_client_id: raise ValueError(f"Client result not found or missing ID for client {client_name}") - client_id = client_result["internal_client_id"] + client_id = client_result.internal_client_id # For confidential clients, we need to get the client secret adapter.configs.CLIENT_ID = client_name @@ -272,7 +277,7 @@ async def _ensure_introspection_audience_mapper( logger: logging.Logger, ) -> None: """Add audience mapper so the introspecting client is included in token ``aud`` (Keycloak 26.6.2+).""" - adapter.configs.REALM_NAME = realm_name + _configure_realm(adapter.configs, realm_name) adapter._admin_adapter = None adapter._admin_token_expiry = 0 if adapter.configs.ADMIN.IS_ENABLED: @@ -342,7 +347,7 @@ async def step_create_client_and_update_adapter( # Ensure the adapter is properly configured for the new client # Reinitialize the adapter with the updated configuration - adapter.configs.REALM_NAME = realm_name + _configure_realm(adapter.configs, realm_name) adapter.configs.CLIENT_ID = client_name # Force reinitialization of the OpenID client adapter._admin_adapter = None @@ -351,10 +356,10 @@ async def step_create_client_and_update_adapter( adapter._initialize_admin_client() # Extract the internal client ID from the result - if not client_result or "internal_client_id" not in client_result: + if not client_result or not client_result.internal_client_id: raise ValueError(f"Client result not found or missing ID for client {client_name}") - client_id = client_result["internal_client_id"] # This is the internal UUID + client_id = client_result.internal_client_id # This is the internal UUID # Get the client secret using the internal client ID with retry logic import asyncio @@ -363,7 +368,7 @@ async def step_create_client_and_update_adapter( for attempt in range(max_retries): try: # Ensure admin adapter is properly configured for the correct realm - adapter.configs.REALM_NAME = realm_name + _configure_realm(adapter.configs, realm_name) adapter._admin_adapter = None adapter._admin_token_expiry = 0 if adapter.configs.ADMIN.IS_ENABLED: @@ -384,9 +389,9 @@ async def step_create_client_and_update_adapter( new_config = KeycloakConfig() new_config.SERVER_URL = adapter.configs.SERVER_URL new_config.CLIENT_ID = client_name # Use client name for configuration - new_config.REALM_NAME = realm_name + _configure_realm(new_config, realm_name) new_config.CLIENT_SECRET_KEY = SecretStr(client_secret) - new_config.VERIFY_SSL = adapter.configs.VERIFY_SSL + new_config.TLS = adapter.configs.TLS.model_copy() new_config.TIMEOUT = adapter.configs.TIMEOUT new_config.ADMIN.USERNAME = adapter.configs.ADMIN.USERNAME new_config.ADMIN.PASSWORD = adapter.configs.ADMIN.PASSWORD @@ -422,14 +427,14 @@ async def step_create_client_and_update_adapter( scenario_context.store(f"client_{client_name}", client_result) # Extract the internal client ID from the result - if not client_result or "internal_client_id" not in client_result: + if not client_result or not client_result.internal_client_id: raise ValueError(f"Client result not found or missing ID for client {client_name}") - client_id = client_result["internal_client_id"] # This is the internal UUID + client_id = client_result.internal_client_id # This is the internal UUID # Update the adapter configuration adapter.configs.CLIENT_ID = client_name - adapter.configs.REALM_NAME = realm_name + _configure_realm(adapter.configs, realm_name) # Get the client secret for confidential client with retry logic import time @@ -438,7 +443,7 @@ async def step_create_client_and_update_adapter( for attempt in range(max_retries): try: # Ensure admin adapter is properly configured for the correct realm - adapter.configs.REALM_NAME = realm_name + _configure_realm(adapter.configs, realm_name) adapter._admin_adapter = None adapter._admin_token_expiry = 0 if adapter.configs.ADMIN.IS_ENABLED: @@ -725,7 +730,7 @@ def step_rotate_realm_signing_key(context: Context, realm_name: str) -> None: password=config.ADMIN.PASSWORD.get_secret_value() if config.ADMIN.PASSWORD else None, realm_name=realm_name, user_realm_name=config.ADMIN.REALM_NAME, - verify=config.VERIFY_SSL, + verify=config.TLS.VERIFY_SSL, ) admin.create_component( { @@ -1344,7 +1349,7 @@ def step_client_credentials_token_succeeds(context: Context, adapter_type: str) scenario_context = get_current_scenario_context(context) token_response = scenario_context.get("latest_token_response") assert token_response is not None, f"{adapter_type.capitalize()} client credentials token request failed" - assert "access_token" in token_response, "Access token missing from client credentials response" + assert token_response.access_token, "Access token missing from client credentials response" context.logger.info(f"{adapter_type.capitalize()} client credentials token request verified") @@ -1380,8 +1385,8 @@ def step_token_info_contains_claims(context: Context) -> None: """Verify that the token info contains user claims.""" scenario_context = get_current_scenario_context(context) result = scenario_context.get("token_info_result") - assert "sub" in result, "Token info missing 'sub' claim" - assert "preferred_username" in result, "Token info missing 'preferred_username' claim" + assert result.sub, "Token info missing 'sub' claim" + assert result.preferred_username, "Token info missing 'preferred_username' claim" context.logger.info("Verified token info contains user claims") @@ -1512,9 +1517,9 @@ def step_integration_verification(context: Context, adapter_type: str) -> None: user_info = scenario_context.get("latest_user_info") if token_response: - assert "access_token" in token_response, "Integration failed: no access token" + assert token_response.access_token, "Integration failed: no access token" if user_info: - assert "sub" in user_info, "Integration failed: no user subject" + assert user_info.user_uuid, "Integration failed: no user subject" context.logger.info(f"{adapter_type.capitalize()} adapter integration with Keycloak verified") @@ -1725,8 +1730,8 @@ def step_sync_token_response_contains_tokens(context: Context) -> None: scenario_context = get_current_scenario_context(context) token_response = scenario_context.get("latest_token_response") assert token_response is not None, "No token response found" - assert "access_token" in token_response, "Access token missing from response" - assert "refresh_token" in token_response, "Refresh token missing from response" + assert token_response.access_token, "Access token missing from response" + assert token_response.refresh_token, "Refresh token missing from response" context.logger.info("Verified sync token response contains access_token and refresh_token") @@ -1754,8 +1759,8 @@ def step_sync_user_info_contains_fields(context: Context) -> None: scenario_context = get_current_scenario_context(context) user_info = scenario_context.get("latest_user_info") assert user_info is not None, "No user info found" - assert "sub" in user_info, "User info missing 'sub' field" - assert "preferred_username" in user_info, "User info missing 'preferred_username' field" + assert user_info.user_uuid, "User info missing 'sub' field" + assert user_info.preferred_username, "User info missing 'preferred_username' field" context.logger.info("Verified sync user info contains sub and preferred_username") @@ -1834,7 +1839,7 @@ def step_sync_token_response_contains_access_token(context: Context) -> None: scenario_context = get_current_scenario_context(context) token_response = scenario_context.get("latest_token_response") assert token_response is not None, "No token response found" - assert "access_token" in token_response, "Access token missing from response" + assert token_response.access_token, "Access token missing from response" context.logger.info("Verified sync token response contains access_token") @@ -1844,7 +1849,7 @@ def step_async_token_response_contains_access_token(context: Context) -> None: scenario_context = get_current_scenario_context(context) token_response = scenario_context.get("latest_token_response") assert token_response is not None, "No token response found" - assert "access_token" in token_response, "Access token missing from response" + assert token_response.access_token, "Access token missing from response" context.logger.info("Verified async token response contains access_token") @@ -1893,8 +1898,8 @@ def step_async_token_response_contains_tokens(context: Context) -> None: scenario_context = get_current_scenario_context(context) token_response = scenario_context.get("latest_token_response") assert token_response is not None, "No token response found" - assert "access_token" in token_response, "Access token missing from response" - assert "refresh_token" in token_response, "Refresh token missing from response" + assert token_response.access_token, "Access token missing from response" + assert token_response.refresh_token, "Refresh token missing from response" context.logger.info("Verified async token response contains access_token and refresh_token") @@ -1922,8 +1927,8 @@ def step_async_user_info_contains_fields(context: Context) -> None: scenario_context = get_current_scenario_context(context) user_info = scenario_context.get("latest_user_info") assert user_info is not None, "No user info found" - assert "sub" in user_info, "User info missing 'sub' field" - assert "preferred_username" in user_info, "User info missing 'preferred_username' field" + assert user_info.user_uuid, "User info missing 'sub' field" + assert user_info.preferred_username, "User info missing 'preferred_username' field" context.logger.info("Verified async user info contains sub and preferred_username") @@ -3812,7 +3817,7 @@ async def step_add_coverage_default_client_scope(context: Context, client_name: "add_client_default_client_scope", internal_client_id, scope_id, - {}, + KeycloakClientScopeRequestDTO(), ) scenario_context.store(_op_error_key("add_client_default_client_scope"), None) except Exception as exc: @@ -3882,7 +3887,7 @@ async def step_add_coverage_optional_client_scope(context: Context, client_name: if not internal_client_id: internal_client_id = await _adapter_call(adapter, is_async, "get_client_id", client_name) scenario_context.store("coverage_internal_client_id", internal_client_id) - await _adapter_call(adapter, is_async, "add_client_optional_client_scope", internal_client_id, scope_id, {}) + await _adapter_call(adapter, is_async, "add_client_optional_client_scope", internal_client_id, scope_id, KeycloakClientScopeRequestDTO()) scenario_context.store(_op_error_key("add_client_optional_client_scope"), None) except Exception as exc: scenario_context.store(_op_error_key("add_client_optional_client_scope"), str(exc)) @@ -4230,6 +4235,7 @@ def _async_adapter_for(realm_name: str, client_name: str) -> AsyncKeycloakAdapte "ADMIN": BaseConfig.global_config().KEYCLOAK.ADMIN.model_copy(update={"IS_ENABLED": False}), }, ) + _configure_realm(config, realm_name) return AsyncKeycloakAdapter(config) @@ -4334,11 +4340,13 @@ def _no_admin_adapter( ) -> AsyncKeycloakAdapter | KeycloakAdapter: """Build a sync or async adapter without admin mode, overriding config fields.""" base = BaseConfig.global_config().KEYCLOAK + issuer = keycloak_test_issuer(base.SERVER_URL, overrides.get("REALM_NAME", base.REALM_NAME)) + claims = {"EXPECTED_ISSUER": issuer, **(token_validation or {})} config = base.model_copy( update={ "CLIENT_SECRET_KEY": None, "ADMIN": base.ADMIN.model_copy(update={"IS_ENABLED": False}), - "TOKEN_VALIDATION": base.TOKEN_VALIDATION.model_copy(update=token_validation), + "TOKEN_VALIDATION": base.TOKEN_VALIDATION.model_copy(update=claims), **overrides, }, ) @@ -4513,25 +4521,24 @@ async def step_adapter_enforces_correct_issuer( @then('forged claims with token type "{token_type}" are {outcome} by the claim check') def step_forged_claims_checked(context: Context, token_type: str, outcome: str) -> None: """A signed non-access token cannot be minted by the container, so feed forged claims to the claim check.""" - import warnings - from archipy.adapters.keycloak._protocols.oidc.adapter import _check_token_claims base = BaseConfig.global_config().KEYCLOAK - claims = {"iss": f"{base.SERVER_URL}/realms/{base.REALM_NAME}", "typ": token_type} - enforcing = base.model_copy( - update={"TOKEN_VALIDATION": base.TOKEN_VALIDATION.model_copy(update={"EXPECTED_ISSUER": claims["iss"]})}, - ) + config = KeycloakConfig(SERVER_URL=base.SERVER_URL, REALM_NAME=base.REALM_NAME) + issuer = f"{config.SERVER_URL.rstrip('/')}/realms/{config.REALM_NAME}" + claims = {"iss": issuer, "typ": token_type} try: - _check_token_claims(claims, enforcing) + _check_token_claims(claims, config) except BaseError as error: assert outcome == "rejected" and error.code == "INVALID_TOKEN", error + assert error.additional_data["claims"] == ["typ"] else: - assert outcome == "accepted", "forged claims passed the enforcing claim check" - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - _check_token_claims(claims, base) - warned = any(issubclass(w.category, DeprecationWarning) and "EXPECTED_ISSUER" in str(w.message) for w in caught) - assert warned == (outcome == "rejected"), ( - "the default (warn-only) mode must warn exactly when enforcement would reject" - ) + assert outcome == "accepted" + + try: + _check_token_claims({"iss": "https://wrong-issuer.example/realms/example", "typ": "Bearer"}, config) + except BaseError as error: + assert error.code == "INVALID_TOKEN" + assert error.additional_data["claims"] == ["iss"] + else: + raise AssertionError("Token issuer mismatch was accepted") diff --git a/features/steps/keycloak_auth_steps.py b/features/steps/keycloak_auth_steps.py index ec31486f1..9e53c4dc7 100644 --- a/features/steps/keycloak_auth_steps.py +++ b/features/steps/keycloak_auth_steps.py @@ -1,7 +1,6 @@ import asyncio import json import time -import warnings from contextlib import ExitStack, contextmanager from types import SimpleNamespace from unittest.mock import patch @@ -20,6 +19,17 @@ from archipy.adapters.keycloak.adapters import AsyncKeycloakAdapter from archipy.adapters.keycloak.auth import AuthContextManager from archipy.helpers.errors.fastapi import setup_exception_handlers +from archipy.models.dtos.keycloak.auth_dtos import AuthenticatedUserDTO +from archipy.models.dtos.keycloak.authz_dtos import ( + KeycloakAuthzPolicyRequestDTO, + KeycloakAuthzResourceRequestDTO, + KeycloakAuthzScopeRequestDTO, +) +from archipy.models.dtos.keycloak.authz_policy_dtos import ( + KeycloakAuthzPolicyRoleDTO, + KeycloakAuthzRolePolicyRequestDTO, +) +from archipy.models.dtos.keycloak.client_scope_dtos import KeycloakClientScopeRequestDTO from archipy.models.dtos.keycloak.organization_dtos import ( KeycloakOrganizationDomainRequestDTO, KeycloakOrganizationRequestDTO, @@ -28,8 +38,8 @@ KeycloakOidcHardcodedClaimMapperConfigDTO, KeycloakOidcOrganizationMembershipMapperConfigDTO, ) -from archipy.models.dtos.keycloak.token_dtos import KeycloakOrganizationClaimDTO, KeycloakUserInfoDTO -from archipy.models.dtos.keycloak_dtos import AuthenticatedUserDTO +from archipy.models.dtos.keycloak.realm_dtos import KeycloakRealmRequestDTO +from archipy.models.dtos.keycloak.token_dtos import KeycloakOrganizationClaimDTO from archipy.models.errors import BaseError @@ -279,7 +289,7 @@ def step_keycloak_auth_clear_sessions(context, username): def step_keycloak_auth_delete_permission(context, scope, resource, client): sc = _ctx(context) adapter = _real_sync_adapter(sc) - internal_id = sc.get(f"client_{client}")["internal_client_id"] + internal_id = sc.get(f"client_{client}").internal_client_id permission_name = f"{resource}-{scope}-permission" permission_id = next( p["id"] for p in adapter.admin_adapter.get_client_authz_permissions(internal_id) if p["name"] == permission_name @@ -368,41 +378,10 @@ def step_keycloak_auth_context_during(context, username): assert auth_context.username == username, f"expected {username}, got {auth_context.username}" -@then('reading "{field}" from the request state warns and names "{replacement}"') -def step_keycloak_auth_state_read_warns(context, field, replacement): +@then("the request state has no Keycloak auth fields") +def step_keycloak_auth_state_has_no_fields(context): state = _ctx(context).get("request").state - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - list(getattr(state, field)) - deprecations = [w for w in caught if issubclass(w.category, DeprecationWarning)] - assert deprecations, "reading the request state did not warn" - message = str(deprecations[0].message) - assert f"request.state.{field}" in message and replacement in message, message - assert deprecations[0].filename.endswith("keycloak_auth_steps.py"), deprecations[0].filename - - -@then("the value the keycloak auth dependency returned does not warn when it is read") -def step_keycloak_auth_returned_value_silent(context): - result = _ctx(context).get("result") - assert isinstance(result, KeycloakUserInfoDTO) - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - result.to_dict() - assert not [w for w in caught if issubclass(w.category, DeprecationWarning)] - - -@then("the request state keeps the same content as the auth context") -def step_keycloak_auth_state_matches_context(context): - sc = _ctx(context) - state = sc.get("request").state - during = sc.get("auth_context_during") - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - assert dict(state.user_info) == during.raw_user_info.to_dict() - assert set(state.user_roles) == set(during.roles) - assert list(state.actor_chain) == list(during.actor_chain) - assert dict(state.token_info) == during.token_info.to_dict() - assert during.token_info.sub == str(during.user_uuid) + assert not vars(state), vars(state) @then("the keycloak auth context is cleared after the dependency ends") @@ -430,9 +409,9 @@ def step_keycloak_auth_error_missing_permission(context, perm): assert error.additional_data["missing_permissions"] == [perm] -@then("the keycloak auth request state has an empty actor chain") -def step_keycloak_auth_state_empty_chain(context): - assert _ctx(context).get("request").state.actor_chain == [] +@then("the keycloak auth context has an empty actor chain") +def step_keycloak_auth_context_empty_chain(context): + assert not _ctx(context).get("auth_context_during").actor_chain # gRPC @@ -696,7 +675,7 @@ def step_keycloak_auth_obtain_token(context, username, password): def step_keycloak_auth_userinfo_subject(context, subject, username): scenario = _ctx(context) adapter = _real_sync_adapter(scenario) - client_id = scenario.get("client_auth-client")["internal_client_id"] + client_id = scenario.get("client_auth-client").internal_client_id mapper = adapter.add_client_mapper_with_config( client_id, "malformed-userinfo-subject", @@ -743,9 +722,7 @@ def step_keycloak_auth_malformed_identity_rejected(context): @given('the keycloak auth realm "{realm}" has an access token lifespan of {seconds:d} seconds') def step_keycloak_auth_token_lifespan(context, realm, seconds): adapter = _real_sync_adapter(_ctx(context)) - realm_representation = dict(adapter.get_realm(realm)) - realm_representation["accessTokenLifespan"] = seconds - adapter.update_realm(realm, **realm_representation) + adapter.update_realm(realm, config=KeycloakRealmRequestDTO(access_token_lifespan=seconds)) @when("the keycloak auth access token lifespan has elapsed") @@ -761,7 +738,7 @@ def step_keycloak_auth_wait_expiry(context): def step_keycloak_auth_uma_setup(context, client, resource, scopes, scope, role): sc = _ctx(context) adapter = _real_sync_adapter(sc) - internal_id = sc.get(f"client_{client}")["internal_client_id"] + internal_id = sc.get(f"client_{client}").internal_client_id admin = adapter.admin_adapter admin_client = admin.get_client(internal_id) @@ -772,7 +749,11 @@ def step_keycloak_auth_uma_setup(context, client, resource, scopes, scope, role) resource_type = f"urn:{client}:resources:{resource}" adapter.create_client_authz_resource( internal_id, - {"name": resource, "type": resource_type, "scopes": [{"name": name} for name in _split(scopes)]}, + KeycloakAuthzResourceRequestDTO( + name=resource, + type=resource_type, + scopes=[KeycloakAuthzScopeRequestDTO(name=name) for name in _split(scopes)], + ), skip_exists=True, ) resource_id = next(r["_id"] for r in admin.get_client_authz_resources(internal_id) if r["name"] == resource) @@ -782,28 +763,27 @@ def step_keycloak_auth_uma_setup(context, client, resource, scopes, scope, role) policy_name = f"{resource}-{role}-policy" adapter.create_client_authz_role_based_policy( internal_id, - { - "name": policy_name, - "type": "role", - "logic": "POSITIVE", - "decisionStrategy": "UNANIMOUS", - "roles": [{"id": role_id}], - }, + KeycloakAuthzRolePolicyRequestDTO( + name=policy_name, + logic="POSITIVE", + decision_strategy="UNANIMOUS", + roles=[KeycloakAuthzPolicyRoleDTO(id=role_id)], + ), skip_exists=True, ) policy_id = next(p["id"] for p in admin.get_client_authz_policies(internal_id) if p["name"] == policy_name) permission_name = f"{resource}-{scope}-permission" if not any(p["name"] == permission_name for p in admin.get_client_authz_permissions(internal_id)): adapter.create_client_authz_scope_permission( - { - "name": permission_name, - "type": "scope", - "logic": "POSITIVE", - "decisionStrategy": "UNANIMOUS", - "resources": [resource_id], - "scopes": [scope_id], - "policies": [policy_id], - }, + KeycloakAuthzPolicyRequestDTO( + name=permission_name, + type="scope", + logic="POSITIVE", + decision_strategy="UNANIMOUS", + resources=[resource_id], + scopes=[scope_id], + policies=[policy_id], + ), internal_id, ) @@ -847,16 +827,18 @@ def step_keycloak_auth_result_user(context, username): assert info.user_uuid == _user_id(sc, username) assert info.preferred_username == username assert info.email == f"{username}@test.com" - assert sc.get("request").state.user_info == info.to_dict() - assert sc.get("request").state.token_info["sub"] == info.user_uuid + auth = sc.get("auth_context_during") + assert auth.raw_user_info == info + assert auth.token_info.sub == str(auth.user_uuid) -@then('the keycloak auth request state user roles include "{roles}"') -def step_keycloak_auth_state_roles_include(context, roles): +@then('the keycloak auth context user roles include "{roles}"') +def step_keycloak_auth_context_roles_include(context, roles): sc = _ctx(context) assert sc.get("error") is None, f"unexpected error {sc.get('error')!r}" - missing = set(_split(roles)) - set(sc.get("request").state.user_roles) - assert not missing, f"missing roles {missing}; got {sc.get('request').state.user_roles}" + actual_roles = sc.get("auth_context_during").roles + missing = set(_split(roles)) - set(actual_roles) + assert not missing, f"missing roles {missing}; got {actual_roles}" @then('the keycloak auth grpc handler ran as user "{username}" with roles including "{roles}"') @@ -1023,7 +1005,7 @@ def step_organization_token_memberships(context, username, count): ), ) client_id = adapter.get_client_id(adapter.configs.CLIENT_ID) - adapter.add_client_optional_client_scope(client_id, scope.id, {}) + adapter.add_client_optional_client_scope(client_id, scope.id, KeycloakClientScopeRequestDTO()) @given("the default organization requirement is {required}") diff --git a/features/steps/keycloak_authz_uma_steps.py b/features/steps/keycloak_authz_uma_steps.py index 7908a9563..b48fdd299 100644 --- a/features/steps/keycloak_authz_uma_steps.py +++ b/features/steps/keycloak_authz_uma_steps.py @@ -1,5 +1,3 @@ -import warnings - from behave import then, when from behave.runner import Context from features.steps.keycloak_adapter_steps import _adapter_call, _adapter_parts @@ -17,6 +15,7 @@ KeycloakAuthzRolePolicyRequestDTO, ) from archipy.models.dtos.keycloak.uma_dtos import KeycloakUmaPolicyRequestDTO, KeycloakUmaResourceRequestDTO +from archipy.models.errors import InvalidArgumentError async def _client_uuid(adapter, is_async: bool, client_name: str) -> str: @@ -279,23 +278,33 @@ async def step_uma_deleted(context: Context, name: str, adapter_type: str) -> No # --- unknown request fields --- -@when('I send a {kind} payload with the unknown field "{field}" to Keycloak using {adapter_type} adapter') -async def step_send_unknown_field(context: Context, kind: str, field: str, adapter_type: str) -> None: +@when("I send a {kind} dictionary to the Keycloak adapter") +async def step_send_dict_payload(context, kind): adapter, is_async, sc = _adapter_parts(context) - calls = { - "group": ("create_group", ({"name": "typo-group", field: "x"},)), - "user": ("create_user", ({"username": "typo-user", field: "x"},)), - "realm": ("update_realm", ("test-realm",)), - } - method, args = calls[kind] - kwargs = {field: "x"} if kind == "realm" else {} - sc.store("unknown_field_error", None) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - try: - await _adapter_call(adapter, is_async, method, *args, **kwargs) - except Exception as e: # noqa: BLE001 - the scenario asserts on whichever error Keycloak's rejection maps to - sc.store("unknown_field_error", e) + method, payload = { + "group": ("create_group", {"name": "test-group"}), + "user": ("create_user", {"username": "test-user"}), + }[kind] + try: + await _adapter_call(adapter, is_async, method, payload) + except InvalidArgumentError as error: + sc.store("dict_payload_error", error) + + +@then("the Keycloak adapter rejects the payload argument") +def step_verify_dict_payload_rejected(context): + error = get_current_scenario_context(context).get("dict_payload_error") + assert isinstance(error, InvalidArgumentError) + assert error.additional_data["argument"] == "payload" + + +@when('I update the realm with the unknown field "{field}"') +def step_send_unknown_realm_field(context, field): + adapter, _, sc = _adapter_parts(context) + try: + adapter.update_realm("test-realm", **{field: "x"}) + except Exception as error: + sc.store("unknown_field_error", error) @then('Keycloak rejects the payload as invalid and names the field "{field}"') diff --git a/features/steps/keycloak_chaining_steps.py b/features/steps/keycloak_chaining_steps.py index 52476208f..3677d809f 100644 --- a/features/steps/keycloak_chaining_steps.py +++ b/features/steps/keycloak_chaining_steps.py @@ -1,5 +1,6 @@ from behave import then, when from behave.runner import Context +from features.test_containers import keycloak_test_issuer from features.steps.keycloak_adapter_steps import _adapter_call, _adapter_parts from features.test_helpers import realm_issuer @@ -36,7 +37,8 @@ def _client_adapter(adapter, is_async: bool, realm: str, client: str, secret: st REALM_NAME=realm, CLIENT_ID=client, CLIENT_SECRET_KEY=secret, - VERIFY_SSL=False, + TLS={"VERIFY_SSL": False}, + TOKEN_VALIDATION={"EXPECTED_ISSUER": keycloak_test_issuer(adapter.configs.SERVER_URL, realm)}, ADMIN={"IS_ENABLED": False}, ) return AsyncKeycloakAdapter(configs) if is_async else KeycloakAdapter(configs) diff --git a/features/steps/keycloak_dtos_steps.py b/features/steps/keycloak_dtos_steps.py index 7eae1a755..70b960ccf 100644 --- a/features/steps/keycloak_dtos_steps.py +++ b/features/steps/keycloak_dtos_steps.py @@ -1,5 +1,4 @@ import datetime -import warnings from pathlib import Path from tempfile import mkdtemp @@ -82,26 +81,18 @@ def step_role_response(context, name): get_current_scenario_context(context).store("response", role_dtos.KeycloakRoleDTO(name=name)) -@when("the response is read with {access}") -def step_read_response(context, access): - sc = get_current_scenario_context(context) - response = sc.get("response") - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - value = response["name"] if access == "brackets" else response.get("name") - sc.store("value", value) - sc.store("warnings", [w for w in caught if issubclass(w.category, DeprecationWarning)]) - +@then('the role name attribute is "{value}"') +def step_role_name(context, value): + role = get_current_scenario_context(context).get("response") + assert role.name == value + assert role.to_payload()["name"] == value -@then("a dict-style access deprecation warning is raised") -def step_dict_warning(context): - caught = get_current_scenario_context(context).get("warnings") - assert len(caught) == 1 and "dict-style access" in str(caught[0].message), caught - -@then('the value read is "{value}"') -def step_value_read(context, value): - assert get_current_scenario_context(context).get("value") == value +@then("the role does not support dict-style access") +def step_role_no_dict_access(context): + role = get_current_scenario_context(context).get("response") + assert not hasattr(role, "__getitem__") + assert not hasattr(role, "get") @given("a Keycloak KeycloakTokenClaimsDTO response without claims") @@ -114,25 +105,19 @@ def step_response_falsy(context): assert not get_current_scenario_context(context).get("response") -@when("a {kind} payload is converted for the Keycloak adapter") -def step_convert_payload(context, kind): - sc = get_current_scenario_context(context) - value = group_dtos.KeycloakGroupRequestDTO(name="ops") if kind == "DTO" else {"name": "ops"} - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - sc.store("adapter_payload", to_request_payload(value)) - sc.store("warnings", [w for w in caught if issubclass(w.category, DeprecationWarning)]) +@when("a dict payload is converted for the Keycloak adapter") +def step_reject_dict_payload(context): + from archipy.models.errors import InvalidArgumentError - -@then('the adapter payload is {{"name": "ops"}}') -def step_adapter_payload(context): - assert get_current_scenario_context(context).get("adapter_payload") == {"name": "ops"} + try: + to_request_payload({"name": "ops"}) + except InvalidArgumentError as error: + get_current_scenario_context(context).store("validation_error", error) -@then("the dict deprecation warning is {state}") -def step_dict_deprecation_state(context, state): - caught = get_current_scenario_context(context).get("warnings") - assert bool(caught) == (state == "raised"), caught +@then("the adapter rejects the payload as an invalid argument") +def step_invalid_adapter_payload(context): + assert get_current_scenario_context(context).get("validation_error") is not None _MUTATION_BODIES = { @@ -261,10 +246,8 @@ def step_connection_options_config(context): config = KeycloakConfig( SERVER_URL="https://keycloak.invalid", CLIENT_ID="client", - VERIFY_SSL=cert_file, + TLS={"VERIFY_SSL": cert_file, "CLIENT_CERT_FILE": cert_file, "CLIENT_KEY_FILE": key_file}, TIMEOUT=2.5, - CLIENT_CERT_FILE=cert_file, - CLIENT_KEY_FILE=key_file, MAX_RETRIES=4, POOL_MAXSIZE=7, PROXIES={"https://": "http://proxy.invalid:3128"}, @@ -311,7 +294,7 @@ def step_connections_use_options(context): def step_config_key_without_cert(context): sc = get_current_scenario_context(context) try: - KeycloakConfig(CLIENT_KEY_FILE="/etc/ssl/client.key") + KeycloakConfig(TLS={"CLIENT_KEY_FILE": "/etc/ssl/client.key"}) except ValidationError as e: sc.store("validation_error", e) else: @@ -320,9 +303,9 @@ def step_config_key_without_cert(context): @when('a Keycloak config is built with VERIFY_SSL "{value}"') def step_config_verify_ssl(context, value): - get_current_scenario_context(context).store("keycloak_config", KeycloakConfig(VERIFY_SSL=value)) + get_current_scenario_context(context).store("keycloak_config", KeycloakConfig(TLS={"VERIFY_SSL": value})) @then('the Keycloak config VERIFY_SSL is "{parsed}"') def step_config_verify_ssl_is(context, parsed): - assert str(get_current_scenario_context(context).get("keycloak_config").VERIFY_SSL) == parsed + assert str(get_current_scenario_context(context).get("keycloak_config").TLS.VERIFY_SSL) == parsed diff --git a/features/steps/keycloak_realms_extra_steps.py b/features/steps/keycloak_realms_extra_steps.py index 6341fd4bd..4321058e0 100644 --- a/features/steps/keycloak_realms_extra_steps.py +++ b/features/steps/keycloak_realms_extra_steps.py @@ -2,6 +2,8 @@ from behave.runner import Context from features.steps.keycloak_adapter_steps import _adapter_call, _adapter_parts +from archipy.models.dtos.keycloak.client_policy_dtos import KeycloakClientPoliciesRequestDTO +from archipy.models.dtos.keycloak.client_policy_dtos import KeycloakClientProfilesRequestDTO from archipy.models.dtos.keycloak.event_dtos import KeycloakRealmEventsConfigRequestDTO from archipy.models.dtos.keycloak.group_dtos import KeycloakGroupRequestDTO from archipy.models.dtos.keycloak.management_permission_dtos import KeycloakManagementPermissionDTO @@ -27,9 +29,21 @@ async def step_realm_listing_and_settings(context: Context, realm: str, adapter_ updated = await _adapter_call(adapter, is_async, "get_realm_events_config", realm) assert updated.events_enabled is True and updated.admin_events_enabled is True, (config, updated) policies = await _adapter_call(adapter, is_async, "get_realm_client_policies", realm, include_global_policies=True) - await _adapter_call(adapter, is_async, "update_realm_client_policies", realm, {"policies": policies.policies or []}) + await _adapter_call( + adapter, + is_async, + "update_realm_client_policies", + realm, + KeycloakClientPoliciesRequestDTO.model_validate({"policies": policies.policies or []}), + ) profiles = await _adapter_call(adapter, is_async, "get_realm_client_profiles", realm, include_global_profiles=True) - await _adapter_call(adapter, is_async, "update_realm_client_profiles", realm, {"profiles": profiles.profiles or []}) + await _adapter_call( + adapter, + is_async, + "update_realm_client_profiles", + realm, + KeycloakClientProfilesRequestDTO.model_validate({"profiles": profiles.profiles or []}), + ) try: types = await _adapter_call(adapter, is_async, "get_realm_client_types", realm) except Exception as e: # noqa: BLE001 - client types are a preview feature the server may not enable diff --git a/features/steps/password_utils_steps.py b/features/steps/password_utils_steps.py index 64b566ae6..c0c7e6cb2 100644 --- a/features/steps/password_utils_steps.py +++ b/features/steps/password_utils_steps.py @@ -196,7 +196,7 @@ def step_when_verified_with_changed_iterations(context, iterations): def _legacy_hash(password, iterations): auth = BaseConfig.global_config().AUTH - salt = os.urandom(auth.SALT_LENGTH) + salt = os.urandom(auth.PASSWORD_POLICY.SALT_LENGTH) return b64encode(salt + hashlib.pbkdf2_hmac("sha256", password.encode(), salt, iterations)).decode("utf-8") @@ -232,7 +232,7 @@ def step_when_auth_config_history_size(context, size): scenario_context = get_current_scenario_context(context) try: - AuthConfig(PASSWORD_HISTORY_SIZE=size) + AuthConfig(PASSWORD_POLICY={"HISTORY_SIZE": size}) scenario_context.store("config_error", None) except ValidationError as e: scenario_context.store("config_error", e) diff --git a/features/steps/redis_adapter_steps.py b/features/steps/redis_adapter_steps.py index d10c783ec..f2d665f0d 100644 --- a/features/steps/redis_adapter_steps.py +++ b/features/steps/redis_adapter_steps.py @@ -127,7 +127,7 @@ def step_given_configured_cluster_mock(context): scenario_context = get_current_scenario_context(context) redis_config = RedisConfig( MODE=RedisMode.CLUSTER, - CLUSTER_NODES=["127.0.0.1:7000", "127.0.0.1:7001", "127.0.0.1:7002"], + CLUSTER={"NODES": ["127.0.0.1:7000", "127.0.0.1:7001", "127.0.0.1:7002"]}, DECODE_RESPONSES=True, ) scenario_context.adapter = RedisMock(redis_config=redis_config) @@ -139,7 +139,7 @@ def step_given_configured_async_cluster_mock(context): scenario_context = get_current_scenario_context(context) redis_config = RedisConfig( MODE=RedisMode.CLUSTER, - CLUSTER_NODES=["127.0.0.1:7000", "127.0.0.1:7001", "127.0.0.1:7002"], + CLUSTER={"NODES": ["127.0.0.1:7000", "127.0.0.1:7001", "127.0.0.1:7002"]}, DECODE_RESPONSES=True, ) scenario_context.async_adapter = AsyncRedisMock(redis_config=redis_config) @@ -3665,13 +3665,10 @@ def step_given_tls_config(context, mode, user): scenario_context = get_current_scenario_context(context) extra = {} if mode == "sentinel": - extra = {"MODE": "SENTINEL", "SENTINEL_NODES": ["localhost:26379"], "SENTINEL_SERVICE_NAME": "mymaster"} + extra = {"MODE": "SENTINEL", "SENTINEL": {"NODES": ["localhost:26379"], "SERVICE_NAME": "mymaster"}} scenario_context.tls_config = RedisConfig( USERNAME=user, - SSL=True, - SSL_CA_CERTS="/certs/ca.pem", - SSL_CERTFILE="/certs/client.pem", - SSL_KEYFILE="/certs/client.key", + TLS={"IS_ENABLED": True, "CA_CERTS": "/certs/ca.pem", "CERTFILE": "/certs/client.pem", "KEYFILE": "/certs/client.key"}, **extra, ) @@ -3708,7 +3705,8 @@ def step_then_client_username(context, user): def _resilience_config(mode, **extra): """Build a Redis config for the given mode with extra settings.""" if mode == "sentinel": - extra.update(MODE="SENTINEL", SENTINEL_NODES=["localhost:26379"], SENTINEL_SERVICE_NAME="mymaster") + sentinel = extra.pop("SENTINEL", {}) + extra.update(MODE="SENTINEL", SENTINEL={"NODES": ["localhost:26379"], "SERVICE_NAME": "mymaster", **sentinel}) return RedisConfig(**extra) @@ -3721,11 +3719,10 @@ def step_given_resilience_config(context, mode, retries, name, user): scenario_context = get_current_scenario_context(context) scenario_context.tls_config = _resilience_config( mode, - RETRY_ATTEMPTS=int(retries), - RETRY_ON_TIMEOUT=True, + RETRY={"ATTEMPTS": int(retries), "ON_TIMEOUT": True}, SOCKET_KEEPALIVE=True, CLIENT_NAME=name, - SENTINEL_USERNAME=user, + SENTINEL={"USERNAME": user}, ) scenario_context.resilience_mode = mode @@ -3797,9 +3794,9 @@ def step_when_invalid_tls_config(context, settings): """Try to build an invalid Redis config and keep the outcome.""" scenario_context = get_current_scenario_context(context) kwargs = ( - {"SSL": True, "SSL_CERTFILE": "/certs/client.pem"} + {"TLS": {"IS_ENABLED": True, "CERTFILE": "/certs/client.pem"}} if settings.startswith("a client") - else {"SSL": False, "SSL_CA_CERTS": "/certs/ca.pem"} + else {"TLS": {"IS_ENABLED": False, "CA_CERTS": "/certs/ca.pem"}} ) try: RedisConfig(**kwargs) @@ -3954,9 +3951,9 @@ def step_when_invalid_node_config(context, mode, node): """Try to build a config with a malformed node address and keep the outcome.""" scenario_context = get_current_scenario_context(context) kwargs = ( - {"MODE": "SENTINEL", "SENTINEL_NODES": [node], "SENTINEL_SERVICE_NAME": "mymaster"} + {"MODE": "SENTINEL", "SENTINEL": {"NODES": [node], "SERVICE_NAME": "mymaster"}} if mode == "sentinel" - else {"MODE": "CLUSTER", "CLUSTER_NODES": [node]} + else {"MODE": "CLUSTER", "CLUSTER": {"NODES": [node]}} ) try: RedisConfig(**kwargs) @@ -3983,8 +3980,8 @@ def step_when_credential_config(context, password, settings): config_logger = logging.getLogger("archipy.configs.sections.redis") config_logger.addHandler(handler) try: - kwargs = {"SSL": False} if settings == "TLS disabled" else {"SSL": True, "SSL_CHECK_HOSTNAME": False} - config = RedisConfig(PASSWORD=password, **kwargs) + kwargs = {"IS_ENABLED": False} if settings == "TLS disabled" else {"IS_ENABLED": True, "CHECK_HOSTNAME": False} + config = RedisConfig(PASSWORD=password, TLS=kwargs) finally: config_logger.removeHandler(handler) store_result(context, "credential_config", config) @@ -4008,27 +4005,18 @@ def step_then_config_warning(context, text): assert any(text in message for message in messages), messages -@when(r'I upsert the hash document "(?P[^"]+)" with replace (?PTrue|False)') -def step_when_upsert_hash_replace(context, doc_id, replace): - """Upsert a hash document and record any DeprecationWarning.""" - import warnings - - adapter = get_current_scenario_context(context).adapter - handle = adapter.search_index(get_current_scenario_context(context).get("last_index_name")) - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - handle.upsert_hash(doc_id, {"title": "T", "category": "c"}, replace=replace == "True") - store_result(context, "deprecations", [w for w in caught if issubclass(w.category, DeprecationWarning)]) +@when(r'I upsert a hash document "(?P[^"]+)" twice with different fields') +def step_when_upsert_hash_merge(context, doc_id): + scenario_context = get_current_scenario_context(context) + handle = scenario_context.adapter.search_index(scenario_context.get("last_index_name")) + handle.upsert_hash(doc_id, {"title": "T"}) + handle.upsert_hash(doc_id, {"category": "c"}) -@then( - r'the hash document "(?P[^"]+)" should be stored and the deprecation warning should be (?Pabsent|raised)', -) -def step_then_upsert_hash(context, doc_id, warned): - """Assert the document exists and the deprecation matches.""" +@then(r'the hash document "(?P[^"]+)" contains both fields') +def step_then_upsert_hash_merge(context, doc_id): adapter = get_current_scenario_context(context).adapter - assert adapter.hgetall(doc_id).get("title") == "T" - assert bool(get_result(context, "deprecations")) == (warned == "raised") + assert adapter.hgetall(doc_id) == {"title": "T", "category": "c"} @when(r'I increment the non-numeric key "(?P[^"]+)" in (?Pmock|container|cluster)') diff --git a/features/steps/scylladb_adapter_steps.py b/features/steps/scylladb_adapter_steps.py index 4e4b9dc8e..937fdbd07 100644 --- a/features/steps/scylladb_adapter_steps.py +++ b/features/steps/scylladb_adapter_steps.py @@ -1737,28 +1737,16 @@ def step_scylladb_pool_stats_hosts(context: Context) -> None: assert stats["total_hosts"] >= 1, stats -@when("I build a ScyllaDB cluster with {setting} set to {value:d}") -def step_build_scylladb_cluster(context: Context, setting: str, value: int) -> None: - """Build the cluster without connecting and keep the warnings raised while building. - - Args: - context (Context): Behave context. - setting (str): The ScyllaDB config field to override. - value (int): The value to set. - """ - import warnings - +@when("I build a ScyllaDB cluster with request timeout {timeout:d}") +def step_build_scylladb_cluster(context, timeout): from archipy.adapters.scylladb.adapters import ScyllaDBAdapter - config = get_scylladb_adapter(context).config.model_copy(update={setting: value}) - adapter = ScyllaDBAdapter.__new__(ScyllaDBAdapter) # skip __init__, which would open a second connection + config = get_scylladb_adapter(context).config.model_copy(update={"REQUEST_TIMEOUT": timeout}) + adapter = ScyllaDBAdapter.__new__(ScyllaDBAdapter) adapter.config = config - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - cluster = adapter._create_cluster() - context.cluster = cluster + context.cluster = adapter._create_cluster() + context.add_cleanup(context.cluster.shutdown) context.cluster_config = config - context.cluster_warnings = [str(item.message) for item in caught if issubclass(item.category, DeprecationWarning)] @when("I build a ScyllaDB cluster with consistency level {level}") @@ -1877,25 +1865,8 @@ def step_default_profile_configured(context: Context) -> None: assert profile.load_balancing_policy is not None -@then('a DeprecationWarning should name "{setting}"') -def step_deprecation_names_setting(context: Context, setting: str) -> None: - """Check a DeprecationWarning mentions the ignored setting. - Args: - context (Context): Behave context. - setting (str): The setting expected in the warning. - """ - assert any(setting in message for message in context.cluster_warnings), context.cluster_warnings - - -@then("a DeprecationWarning should not be raised") -def step_no_deprecation(context: Context) -> None: - """Check no pool-setting DeprecationWarning was raised. - Args: - context (Context): Behave context. - """ - assert not [m for m in context.cluster_warnings if "no effect" in m], context.cluster_warnings _RESILIENCE_PROFILES: dict[str, dict[str, Any]] = { diff --git a/features/steps/temporal_adapter_steps.py b/features/steps/temporal_adapter_steps.py index c64ffd313..0181bf6c7 100644 --- a/features/steps/temporal_adapter_steps.py +++ b/features/steps/temporal_adapter_steps.py @@ -236,7 +236,6 @@ async def start_test_worker( task_queue: str, workflows: list[type] | None = None, activities: list | None = None, - build_id: str | None = None, max_concurrent_activities: int | None = None, deployment_config: WorkerDeploymentConfig | None = None, ) -> WorkerHandle: @@ -247,7 +246,6 @@ async def start_test_worker( task_queue (str): Task queue name for the worker. workflows (list[type], optional): List of workflow classes. Defaults to None. activities (list, optional): List of activity functions. Defaults to None. - build_id (str, optional): Build identifier for versioning. Defaults to None. max_concurrent_activities (int, optional): Activity slot limit for the worker. Defaults to None. Returns: @@ -295,7 +293,6 @@ async def start_test_worker( task_queue=task_queue, workflows=workflows, activities=activities, - build_id=build_id, deployment_config=deployment_config, max_concurrent_activities=max_concurrent_activities, ) @@ -726,11 +723,6 @@ def step_start_worker(context, task_queue): context.logger.info(f"Started worker for task queue {task_queue}") -@when('I start a worker for task queue "{task_queue}" with build_id "{build_id}"') -def step_start_worker_with_build_id(context, task_queue, build_id): - """Start a worker with specific build ID.""" - run_async(context, start_test_worker(context, task_queue, build_id=build_id)) - context.logger.info(f"Started worker for task queue {task_queue} with build_id {build_id}") @when("I stop the worker") @@ -1989,7 +1981,6 @@ def step_run_span_has_messaging_attributes(context, span_prefix, task_queue, ope assert run_spans, f"No {span_prefix} span among {[span.name for span in spans]}" expected = { "messaging.system": "temporal", - "messaging.operation": operation, "messaging.operation.type": operation, "messaging.destination.name": task_queue, } @@ -2654,15 +2645,6 @@ def step_schedule_list_contains(context, schedule_id): assert schedule_id in [schedule.id for schedule in schedules], [schedule.id for schedule in schedules] -@when('I call the deprecated stop_schedule for "{schedule_id}"') -def step_call_deprecated_stop_schedule(context, schedule_id): - import warnings - - adapter = get_temporal_adapter(context) - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - run_async(context, adapter.stop_schedule(schedule_id)) - get_current_scenario_context(context).store("caught_warnings", caught) @then("a DeprecationWarning should have been emitted") diff --git a/features/steps/vault_adapter_steps.py b/features/steps/vault_adapter_steps.py index 3f0e9777d..3ffb04921 100644 --- a/features/steps/vault_adapter_steps.py +++ b/features/steps/vault_adapter_steps.py @@ -583,10 +583,10 @@ def step_mutate_returned_secret(context, path): adapter.read_secret(path)["v"] = "mutated" -@when('I parse VAULT__VERIFY_SSL "{value}"') +@when('I parse VAULT__TLS__VERIFY_SSL "{value}"') def step_parse_verify_ssl(context, value): - previous = os.environ.get("VAULT__VERIFY_SSL") - os.environ["VAULT__VERIFY_SSL"] = value + previous = os.environ.get("VAULT__TLS__VERIFY_SSL") + os.environ["VAULT__TLS__VERIFY_SSL"] = value result: object try: result = _vault_config_from_env().TLS.VERIFY_SSL @@ -594,13 +594,13 @@ def step_parse_verify_ssl(context, value): result = e finally: if previous is None: - os.environ.pop("VAULT__VERIFY_SSL", None) + os.environ.pop("VAULT__TLS__VERIFY_SSL", None) else: - os.environ["VAULT__VERIFY_SSL"] = previous + os.environ["VAULT__TLS__VERIFY_SSL"] = previous get_current_scenario_context(context).store("verify_ssl_result", result) -@then('VAULT__VERIFY_SSL should resolve to "{outcome}"') +@then('VAULT__TLS__VERIFY_SSL should resolve to "{outcome}"') def step_then_verify_ssl(context, outcome): result = get_current_scenario_context(context).get("verify_ssl_result") if outcome == "rejected": @@ -611,7 +611,7 @@ def step_then_verify_ssl(context, outcome): @then("the Vault config repr should not contain its credentials") def step_then_repr_hides_credentials(context): - config = VaultConfig(TOKEN="tok-secret-1", APPROLE_SECRET_ID="sid-secret-2", PASSWORD="pw-secret-3") + config = VaultConfig(TOKEN="tok-secret-1", APPROLE={"SECRET_ID": "sid-secret-2"}, PASSWORD="pw-secret-3") text = repr(config) for secret in ("tok-secret-1", "sid-secret-2", "pw-secret-3"): assert secret not in text, f"repr leaks {secret}" @@ -626,14 +626,8 @@ def _vault_setting(config, path): @when("a Vault config is built with {settings}") def step_when_vault_config_built(context, settings): - import warnings - - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - config = VaultConfig(**json.loads(settings)) - scenario_context = get_current_scenario_context(context) - scenario_context.store("vault_grouped_config", config) - scenario_context.store("vault_grouped_warnings", [w for w in caught if issubclass(w.category, DeprecationWarning)]) + config = VaultConfig(**json.loads(settings)) + get_current_scenario_context(context).store("vault_grouped_config", config) @when("the Vault bootstrap config is read with environment {env}") @@ -657,9 +651,3 @@ def step_then_vault_setting(context, path, expected): config = get_current_scenario_context(context).get("vault_grouped_config") actual = _vault_setting(config, path) assert str(actual) == expected, f"{path}: expected {expected}, got {actual}" - - -@then("{count:d} Vault deprecation warning should be raised") -def step_then_vault_warnings(context, count): - caught = get_current_scenario_context(context).get("vault_grouped_warnings") - assert len(caught) == count, [str(w.message) for w in caught] diff --git a/features/temporal_adapter.feature b/features/temporal_adapter.feature index 32545ddd2..791e6bb98 100644 --- a/features/temporal_adapter.feature +++ b/features/temporal_adapter.feature @@ -200,11 +200,6 @@ Feature: Temporal Adapter Operations Then the worker manager should have 2 workers And each worker should be on a different task queue - Scenario: Worker with build_id for versioning - When I start a worker for task queue "versioned-queue" with build_id "v1.0.0" - Then the worker should be running - And the worker should have build_id "v1.0.0" - Scenario: Worker with poller autoscaling and an activity rate limit runs workflows Given a Temporal worker manager is configured with poller autoscaling and 50 activities per second And a worker is started for task queue "test-queue" with GreetingWorkflow diff --git a/features/temporal_schedules_errors.feature b/features/temporal_schedules_errors.feature index f8d1e68f8..3729f9991 100644 --- a/features/temporal_schedules_errors.feature +++ b/features/temporal_schedules_errors.feature @@ -26,13 +26,6 @@ Feature: Temporal Schedules, Timeouts and Errors Then schedule "manage-schedule-1" should not be paused And the schedule list should contain "manage-schedule-1" - Scenario: The deprecated stop_schedule warns and still deletes the schedule - Given a worker is started for task queue "test-queue" with ScheduledWorkflow - When I create a schedule "deprecated-stop-1" for workflow "ScheduledWorkflow" with interval 3600 seconds - And I call the deprecated stop_schedule for "deprecated-stop-1" - Then a DeprecationWarning should have been emitted - And the schedule "deprecated-stop-1" should be stopped - Scenario: Schedule with interval spec Given a worker is started for task queue "test-queue" with ScheduledWorkflow When I create a schedule "interval-schedule-1" with interval spec: diff --git a/features/test_containers.py b/features/test_containers.py index 6df70e04a..25e8b4dec 100644 --- a/features/test_containers.py +++ b/features/test_containers.py @@ -379,11 +379,9 @@ def __init__(self, image: str | None = None) -> None: self._containers: list[DockerContainer] = [] self.cluster_config = RedisConfig( MODE=RedisMode.CLUSTER, - CLUSTER_NODES=list(_CLUSTER_NODE_ADDRESSES), + CLUSTER={"NODES": list(_CLUSTER_NODE_ADDRESSES), "REQUIRE_FULL_COVERAGE": True, "READ_FROM_REPLICAS": True}, DECODE_RESPONSES=True, PASSWORD=None, - CLUSTER_REQUIRE_FULL_COVERAGE=True, - CLUSTER_READ_FROM_REPLICAS=True, ) def _create_containers(self) -> list[DockerContainer]: @@ -614,6 +612,13 @@ def _readiness_probe(self) -> None: super()._readiness_probe() +def keycloak_test_issuer(server_url, realm): + """Return the issuer URL configured by the Keycloak test container.""" + if os.environ.get("KEYCLOAK_SPLIT_HOSTNAME", "1") != "0": + server_url = KEYCLOAK_ADMIN_HOSTNAME if realm == "master" else KEYCLOAK_PUBLIC_HOSTNAME + return f"{server_url.rstrip('/')}/realms/{realm}" + + @ContainerManager.register("keycloak") class KeycloakTestContainer(metaclass=Singleton, thread_safe=True): def __init__(self, config: KeycloakConfig | None = None, image: str | None = None) -> None: @@ -694,7 +699,9 @@ def start(self) -> KeycloakContainer: # Update global config with actual container endpoint global_config = BaseConfig.global_config() - global_config.KEYCLOAK.SERVER_URL = f"http://{self.host}:{self.port}" + config = global_config.KEYCLOAK + config.SERVER_URL = f"http://{self.host}:{self.port}" + config.TOKEN_VALIDATION.EXPECTED_ISSUER = keycloak_test_issuer(config.SERVER_URL, config.REALM_NAME) logger.info("Keycloak container started on %s:%s", self.host, self.port) @@ -763,8 +770,8 @@ def __init__(self, config: ElasticsearchConfig | None = None, image: str | None self.host: str | None = None self.port: int | None = None - self.username: str | None = self.config.HTTP_USER_NAME - self.password: str | None = self.config.HTTP_PASSWORD.get_secret_value() if self.config.HTTP_PASSWORD else None + self.username: str | None = self.config.AUTH.USER_NAME + self.password: str | None = self.config.AUTH.PASSWORD.get_secret_value() if self.config.AUTH.PASSWORD else None self.cluster_name: str = "test-cluster" self._container: ElasticSearchContainer | None = _build_elasticsearch_container(self.image) @@ -1523,7 +1530,6 @@ def _build(self) -> DockerContainer: container = ( DockerContainer(self.image) .with_exposed_ports(self.SMTP_PORT, self.API_PORT) - .with_env("MP_SMTP_AUTH", f"{self.USERNAME}:{self.PASSWORD}") # Mailpit resolves the name of every SMTP client; with no DNS in the container each connection waits 20 s. .with_env("MP_SMTP_DISABLE_RDNS", "true") # Keep the /api/v1/info trace probe independent of GitHub's release API. @@ -1536,12 +1542,10 @@ def _build(self) -> DockerContainer: _write_self_signed_certificate(cert_path) container = ( container.with_volume_mapping(str(cert_path), "/certs", "ro") + .with_env("MP_SMTP_AUTH", f"{self.USERNAME}:{self.PASSWORD}") .with_env("MP_SMTP_TLS_CERT", "/certs/cert.pem") .with_env("MP_SMTP_TLS_KEY", "/certs/key.pem") ) - else: - # Without TLS Mailpit only offers AUTH on an insecure connection when told to. - container = container.with_env("MP_SMTP_AUTH_ALLOW_INSECURE", "1") return container def start(self) -> DockerContainer: diff --git a/features/vault_adapter.feature b/features/vault_adapter.feature index 9b5810ca5..824750aa9 100644 --- a/features/vault_adapter.feature +++ b/features/vault_adapter.feature @@ -41,9 +41,9 @@ Feature: Vault Adapter When I mutate the dict returned by reading Vault secret "app/cached-copy" Then reading Vault secret "app/cached-copy" should return key "v" with value "one" - Scenario Outline: VAULT__VERIFY_SSL accepts explicit booleans and rejects unknown spellings - When I parse VAULT__VERIFY_SSL "" - Then VAULT__VERIFY_SSL should resolve to "" + Scenario Outline: VAULT__TLS__VERIFY_SSL accepts explicit booleans and rejects unknown spellings + When I parse VAULT__TLS__VERIFY_SSL "" + Then VAULT__TLS__VERIFY_SSL should resolve to "" Examples: | value | outcome | @@ -143,27 +143,21 @@ Feature: Vault Adapter When I call the Vault API with requests Then the collector should have a span with attribute "http.url" containing "/v1/sys/health" - Scenario Outline: Vault settings are grouped and the flat names still work + Scenario Outline: Vault settings are grouped When a Vault config is built with Then the Vault setting "" should be "" - And Vault deprecation warning should be raised Examples: - | settings | path | expected | warnings | - | {"APPROLE": {"ROLE_ID": "r1"}} | APPROLE.ROLE_ID | r1 | 0 | - | {"APPROLE_ROLE_ID": "r2"} | APPROLE.ROLE_ID | r2 | 1 | - | {"APPROLE": {"ROLE_ID": "new"}, "APPROLE_ROLE_ID": "old"} | APPROLE.ROLE_ID | new | 1 | - | {"VERIFY_SSL": false} | TLS.VERIFY_SSL | False | 1 | - | {"TLS": {"VERIFY_SSL": false}} | TLS.VERIFY_SSL | False | 0 | - | {} | AWS.REGION | us-east-1 | 0 | - - Scenario Outline: The Vault bootstrap reads grouped and flat environment variables + | settings | path | expected | + | {"APPROLE": {"ROLE_ID": "r1"}} | APPROLE.ROLE_ID | r1 | + | {"TLS": {"VERIFY_SSL": false}} | TLS.VERIFY_SSL | False | + | {} | AWS.REGION | us-east-1 | + + Scenario Outline: The Vault bootstrap reads grouped environment variables When the Vault bootstrap config is read with environment Then the Vault setting "" should be "" Examples: - | env | path | expected | - | {"VAULT__APPROLE__ROLE_ID": "nested"} | APPROLE.ROLE_ID | nested | - | {"VAULT__APPROLE_ROLE_ID": "flat"} | APPROLE.ROLE_ID | flat | - | {"VAULT__APPROLE__ROLE_ID": "n", "VAULT__APPROLE_ROLE_ID": "f"} | APPROLE.ROLE_ID | n | - | {"VAULT__TLS__VERIFY_SSL": "off"} | TLS.VERIFY_SSL | False | + | env | path | expected | + | {"VAULT__APPROLE__ROLE_ID": "nested"} | APPROLE.ROLE_ID | nested | + | {"VAULT__TLS__VERIFY_SSL": "off"} | TLS.VERIFY_SSL | False | diff --git a/mkdocs.yml b/mkdocs.yml index b2da0d94c..2a44720a1 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -203,10 +203,11 @@ nav: - Contributing: community/contributing.md - Code of Conduct: community/code_of_conduct.md - FAQ: community/faq.md - - Deprecations: community/deprecations.md + - Upgrade to ArchiPy 6.0: community/deprecations.md - Security: community/security.md - Changelog: - Overview: community/changelog/index.md + - "6.x": community/changelog/6/index.md - "5.x": community/changelog/5/index.md - "4.x": community/changelog/4/index.md - "3.x": community/changelog/3/index.md diff --git a/packages/elasticsearch/archipy/adapters/elasticsearch/adapters.py b/packages/elasticsearch/archipy/adapters/elasticsearch/adapters.py index 148ea2361..5b4629209 100644 --- a/packages/elasticsearch/archipy/adapters/elasticsearch/adapters.py +++ b/packages/elasticsearch/archipy/adapters/elasticsearch/adapters.py @@ -7,7 +7,6 @@ import functools import inspect import logging -import warnings from functools import cache from typing import TYPE_CHECKING, Any, NoReturn, override @@ -69,11 +68,6 @@ # Elasticsearch error types that are more specific than their status code (409 covers both) _ERROR_TYPE_ERRORS: dict[str, type[BaseError]] = {"resource_already_exists_exception": AlreadyExistsError} -_ERROR_MAPPING_DEPRECATION = ( - "Elasticsearch adapters currently raise raw elasticsearch-py exceptions. " - "Set ELASTIC.MAP_ERRORS=True to raise ArchiPy errors instead; this will become the default in a future release." -) - def _to_archipy_error(error: Exception) -> BaseError | None: """Translate an elasticsearch-py exception into an ArchiPy error. @@ -115,22 +109,14 @@ def _raise_mapped(error: Exception) -> NoReturn: raise mapped from error -def _errors_mapped(adapter: object) -> bool: - """Return whether the adapter was configured to map client errors.""" - return bool(getattr(adapter, "_map_errors", False)) - - def _map_sync_errors[**P, R](function: Callable[P, R]) -> Callable[P, R]: - """Map client exceptions to ArchiPy errors when the adapter has MAP_ERRORS enabled.""" + """Map client exceptions to ArchiPy errors.""" @functools.wraps(function) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: - adapter = args[0] try: return function(*args, **kwargs) - except Exception as error: - if not _errors_mapped(adapter): - raise + except (ApiError, TransportError) as error: _raise_mapped(error) return wrapper @@ -141,12 +127,9 @@ def _map_sync_gen_errors[**P, R](function: Callable[P, Iterable[R]]) -> Callable @functools.wraps(function) def wrapper(*args: P.args, **kwargs: P.kwargs) -> Iterator[R]: - adapter = args[0] try: yield from function(*args, **kwargs) - except Exception as error: - if not _errors_mapped(adapter): - raise + except (ApiError, TransportError) as error: _raise_mapped(error) return wrapper @@ -157,12 +140,9 @@ def _map_async_errors[**P, R](function: Callable[P, Awaitable[R]]) -> Callable[P @functools.wraps(function) async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: - adapter = args[0] try: return await function(*args, **kwargs) - except Exception as error: - if not _errors_mapped(adapter): - raise + except (ApiError, TransportError) as error: _raise_mapped(error) return wrapper @@ -173,32 +153,15 @@ def _map_async_gen_errors[**P, R](function: Callable[P, AsyncIterator[R]]) -> Ca @functools.wraps(function) async def wrapper(*args: P.args, **kwargs: P.kwargs) -> AsyncIterator[R]: - adapter = args[0] try: async for item in function(*args, **kwargs): yield item - except Exception as error: - if not _errors_mapped(adapter): - raise + except (ApiError, TransportError) as error: _raise_mapped(error) return wrapper -def _warn_error_mapping_disabled(configs: ElasticsearchConfig) -> bool: - """Return the MAP_ERRORS flag and warn when it is off. - - Args: - configs (ElasticsearchConfig): Configuration settings for Elasticsearch. - - Returns: - bool: Whether ArchiPy error mapping is enabled. - """ - if not configs.MAP_ERRORS: - warnings.warn(_ERROR_MAPPING_DEPRECATION, DeprecationWarning, stacklevel=3) - return configs.MAP_ERRORS - - def _apply_optional_client_kwargs(kwargs: dict[str, Any], configs: ElasticsearchConfig) -> None: """Add the client options that are only passed when set, so unset keeps the client defaults. @@ -291,7 +254,6 @@ def __init__(self, elasticsearch_config: ElasticsearchConfig | None = None) -> N If None, retrieves from global config. Defaults to None. """ configs: ElasticsearchConfig = elasticsearch_config or BaseConfig.global_config().ELASTIC - self._map_errors = _warn_error_mapping_disabled(configs) self.client = self._get_client(configs) @staticmethod @@ -614,7 +576,6 @@ def __init__(self, elasticsearch_config: ElasticsearchConfig | None = None) -> N If None, retrieves from global config. Defaults to None. """ configs: ElasticsearchConfig = elasticsearch_config or BaseConfig.global_config().ELASTIC - self._map_errors = _warn_error_mapping_disabled(configs) self.client = self._get_client(configs) @staticmethod diff --git a/packages/kafka/archipy/adapters/kafka/adapters.py b/packages/kafka/archipy/adapters/kafka/adapters.py index b788bd294..0c2d21428 100644 --- a/packages/kafka/archipy/adapters/kafka/adapters.py +++ b/packages/kafka/archipy/adapters/kafka/adapters.py @@ -7,7 +7,6 @@ import asyncio import contextlib import logging -import warnings from typing import TYPE_CHECKING, NoReturn, override import confluent_kafka @@ -153,37 +152,6 @@ def _apply_transactional_config(config: dict[str, str | int | float], configs: K config["transaction.timeout.ms"] = configs.TRANSACTION_TIMEOUT_MS or max(60000, delivery_timeout) -def _resolve_message_key( - configs: KafkaConfig, - key: str | None, - encode: Callable[[str | bytes], bytes], -) -> bytes | None: - """Return the key to send for a message. - - A missing key is sent as ``None`` (no key) when ``EMPTY_KEY_FOR_MISSING_KEY`` is False. The legacy behavior, - still the default, sends empty bytes and is deprecated. - - Args: - configs: Kafka configuration. - key: The key given by the caller, or None. - encode: Function that converts the key to bytes. - - Returns: - bytes | None: The key to pass to the client. - """ - if key is not None: - return encode(key) - if not configs.EMPTY_KEY_FOR_MISSING_KEY: - return None - warnings.warn( - "Messages without a key are sent with an empty key (b''). Set KAFKA.EMPTY_KEY_FOR_MISSING_KEY=False to " - "send them without a key; that will become the default in a future release.", - DeprecationWarning, - stacklevel=4, - ) - return b"" - - def _effective_delivery_timeout_seconds(configs: KafkaConfig) -> float: """Return how long a produced message can legitimately stay pending, in seconds.""" return (configs.MESSAGE_TIMEOUT_MS or configs.DELIVERY_TIMEOUT_MS) / 1000 @@ -923,7 +891,7 @@ def produce( try: callback = self._build_delivery_callback(on_delivery) processed_message = self._pre_process_message(message) - processed_key = _resolve_message_key(self._configs, key, self._pre_process_message) + processed_key = self._pre_process_message(key) if key is not None else None try: self._adapter.produce( topic=self._topic_name, @@ -1210,7 +1178,7 @@ async def produce(self, message: str | bytes, key: str | None = None) -> None: try: adapter = await self._get_adapter() processed_message = self._pre_process_message(message) - processed_key = _resolve_message_key(self._configs, key, self._pre_process_message) + processed_key = self._pre_process_message(key) if key is not None else None await adapter.produce( topic=self._topic_name, value=processed_message, diff --git a/packages/keycloak/archipy/adapters/keycloak/_base.py b/packages/keycloak/archipy/adapters/keycloak/_base.py index f4272d71b..c667bf1a1 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_base.py +++ b/packages/keycloak/archipy/adapters/keycloak/_base.py @@ -22,7 +22,6 @@ raise_error_from_response, ) -from archipy.helpers._deprecation import warn_deprecated_name from archipy.models.dtos.keycloak.base import KeycloakBaseDTO, KeycloakResponseDTO from archipy.models.dtos.keycloak.common_dtos import KeycloakCreateResultDTO, KeycloakMutationResultDTO from archipy.models.dtos.keycloak.token_dtos import KeycloakOidcResponseDTO, KeycloakUserInfoDTO @@ -32,6 +31,7 @@ ConflictError, InsufficientPermissionsError, InternalError, + InvalidArgumentError, InvalidCredentialsError, KeycloakConnectionTimeoutError, KeycloakServiceUnavailableError, @@ -152,21 +152,11 @@ def admin_body(body: object | None) -> str: return "" if body is None else json.dumps(body) -def to_request_payload(value: KeycloakBaseDTO | dict[str, Any]) -> dict[str, Any]: - """Return the camelCase payload python-keycloak expects for a request body. - - Plain dicts are still accepted but deprecated; they are passed through unchanged. - - Args: - value: A Keycloak DTO or a raw payload dict. - - Returns: - The payload dict. - """ - if isinstance(value, KeycloakBaseDTO): - return value.to_payload() - warn_deprecated_name("Passing a dict payload", "a Keycloak request DTO", stacklevel=4) - return value +def to_request_payload(value: KeycloakBaseDTO) -> dict[str, Any]: + """Serialize a Keycloak representation to the camelCase request body.""" + if not isinstance(value, KeycloakBaseDTO): + raise InvalidArgumentError(argument_name="payload", additional_data={"reason": "Expected a Keycloak DTO"}) + return value.to_payload() def to_claims_dict(value: KeycloakOidcResponseDTO | Mapping[str, Any] | None) -> dict[str, Any]: diff --git a/packages/keycloak/archipy/adapters/keycloak/_protocols/oidc/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_protocols/oidc/adapter.py index c23ee1b10..a54b91828 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_protocols/oidc/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_protocols/oidc/adapter.py @@ -6,7 +6,6 @@ import json import logging import time -import warnings from typing import TYPE_CHECKING, Any from async_lru import alru_cache @@ -99,9 +98,8 @@ def _build_jwk_set(raw: dict[str, Any]) -> jwk.JWKSet: def _check_token_claims(claims: dict[str, Any], configs: KeycloakConfig) -> None: """Check issuer, audience and token type of a locally verified token. - A claim is enforced only when its setting is configured (``EXPECTED_ISSUER`` for ``iss``, - ``EXPECTED_AUDIENCE`` for ``aud``; the ``typ == "Bearer"`` check is enforced when either is set). Without them a - mismatch only emits a ``DeprecationWarning``, because enforcement will become the default in 6.0. + The token issuer must match the configured issuer or the adapter's realm URL. The token type must be + ``Bearer``. The audience is checked when ``EXPECTED_AUDIENCE`` is configured. Args: claims: Verified token claims. @@ -114,27 +112,19 @@ def _check_token_claims(claims: dict[str, Any], configs: KeycloakConfig) -> None configs.TOKEN_VALIDATION.EXPECTED_ISSUER or f"{(configs.SERVER_URL or '').rstrip('/')}/realms/{configs.REALM_NAME}" ) - audience = claims.get("aud") - audiences = [audience] if isinstance(audience, str) else list(audience or []) - enforce_any = bool(configs.TOKEN_VALIDATION.EXPECTED_ISSUER or configs.TOKEN_VALIDATION.EXPECTED_AUDIENCE) - enforced: list[str] = [] - advisory: list[str] = [] + invalid_claims: list[str] = [] if claims.get("iss") != expected_issuer: - (enforced if configs.TOKEN_VALIDATION.EXPECTED_ISSUER else advisory).append("iss") - if configs.TOKEN_VALIDATION.EXPECTED_AUDIENCE and configs.TOKEN_VALIDATION.EXPECTED_AUDIENCE not in audiences: - enforced.append("aud") + invalid_claims.append("iss") + expected_audience = configs.TOKEN_VALIDATION.EXPECTED_AUDIENCE + if expected_audience: + audience = claims.get("aud") + audiences = audience if isinstance(audience, list) else [audience] + if expected_audience not in audiences: + invalid_claims.append("aud") if claims.get("typ") != "Bearer": - (enforced if enforce_any else advisory).append("typ") - if enforced: - raise InvalidTokenError(additional_data={"claims": enforced}) - if advisory: - warnings.warn( - f"Token claims {advisory} do not match the expected values; set " - "KEYCLOAK.TOKEN_VALIDATION.EXPECTED_ISSUER or KEYCLOAK.TOKEN_VALIDATION.EXPECTED_AUDIENCE " - "to enforce them. Enforcement becomes the default in 6.0.", - DeprecationWarning, - stacklevel=3, - ) + invalid_claims.append("typ") + if invalid_claims: + raise InvalidTokenError(additional_data={"claims": invalid_claims}) def _normalize_userinfo(raw: dict[str, Any] | bytes) -> KeycloakUserType: diff --git a/packages/keycloak/archipy/adapters/keycloak/_protocols/uma/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_protocols/uma/adapter.py index 05fefbad0..15e614cc9 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_protocols/uma/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_protocols/uma/adapter.py @@ -53,7 +53,7 @@ def _all_granted(wanted: list[UMAPermission], granted: object) -> bool: class KeycloakUmaMixin(SyncKeycloakMixinBase): """Sync Keycloak mixin for UMA operations.""" - def resource_set_create(self, payload: KeycloakUmaResourceRequestDTO | dict[str, Any]) -> KeycloakUmaResourceDTO: + def resource_set_create(self, payload: KeycloakUmaResourceRequestDTO) -> KeycloakUmaResourceDTO: """Create a UMA resource set. Args: @@ -90,7 +90,7 @@ def resource_set_read(self, resource_id: str) -> KeycloakUmaResourceDTO: def resource_set_update( self, resource_id: str, - payload: KeycloakUmaResourceRequestDTO | dict[str, Any], + payload: KeycloakUmaResourceRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a UMA resource set. @@ -189,7 +189,7 @@ def resource_set_list_ids( def policy_resource_create( self, resource_id: str, - payload: KeycloakUmaPolicyRequestDTO | dict[str, Any], + payload: KeycloakUmaPolicyRequestDTO, ) -> KeycloakUmaPolicyDTO: """Create a UMA policy for a resource. @@ -214,7 +214,7 @@ def policy_resource_create( def policy_update( self, policy_id: str, - payload: KeycloakUmaPolicyRequestDTO | dict[str, Any], + payload: KeycloakUmaPolicyRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a UMA policy. @@ -343,7 +343,7 @@ class AsyncKeycloakUmaMixin(AsyncKeycloakMixinBase): async def resource_set_create( self, - payload: KeycloakUmaResourceRequestDTO | dict[str, Any], + payload: KeycloakUmaResourceRequestDTO, ) -> KeycloakUmaResourceDTO: """Create a UMA resource set. @@ -381,7 +381,7 @@ async def resource_set_read(self, resource_id: str) -> KeycloakUmaResourceDTO: async def resource_set_update( self, resource_id: str, - payload: KeycloakUmaResourceRequestDTO | dict[str, Any], + payload: KeycloakUmaResourceRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a UMA resource set. @@ -478,7 +478,7 @@ async def resource_set_list_ids( async def policy_resource_create( self, resource_id: str, - payload: KeycloakUmaPolicyRequestDTO | dict[str, Any], + payload: KeycloakUmaPolicyRequestDTO, ) -> KeycloakUmaPolicyDTO: """Create a UMA policy for a resource. @@ -503,7 +503,7 @@ async def policy_resource_create( async def policy_update( self, policy_id: str, - payload: KeycloakUmaPolicyRequestDTO | dict[str, Any], + payload: KeycloakUmaPolicyRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a UMA policy. diff --git a/packages/keycloak/archipy/adapters/keycloak/_protocols/uma/port.py b/packages/keycloak/archipy/adapters/keycloak/_protocols/uma/port.py index fb6e56abd..8cfffc40f 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_protocols/uma/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_protocols/uma/port.py @@ -24,7 +24,7 @@ class KeycloakUmaPort: """Sync Keycloak port interface for UMA operations.""" @abstractmethod - def resource_set_create(self, payload: KeycloakUmaResourceRequestDTO | dict[str, Any]) -> KeycloakUmaResourceDTO: + def resource_set_create(self, payload: KeycloakUmaResourceRequestDTO) -> KeycloakUmaResourceDTO: """Create a UMA resource set. Args: @@ -51,7 +51,7 @@ def resource_set_read(self, resource_id: str) -> KeycloakUmaResourceDTO: def resource_set_update( self, resource_id: str, - payload: KeycloakUmaResourceRequestDTO | dict[str, Any], + payload: KeycloakUmaResourceRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a UMA resource set. @@ -120,7 +120,7 @@ def resource_set_list_ids( def policy_resource_create( self, resource_id: str, - payload: KeycloakUmaPolicyRequestDTO | dict[str, Any], + payload: KeycloakUmaPolicyRequestDTO, ) -> KeycloakUmaPolicyDTO: """Create a UMA policy for a resource. @@ -137,7 +137,7 @@ def policy_resource_create( def policy_update( self, policy_id: str, - payload: KeycloakUmaPolicyRequestDTO | dict[str, Any], + payload: KeycloakUmaPolicyRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a UMA policy. @@ -218,7 +218,7 @@ class AsyncKeycloakUmaPort: @abstractmethod async def resource_set_create( self, - payload: KeycloakUmaResourceRequestDTO | dict[str, Any], + payload: KeycloakUmaResourceRequestDTO, ) -> KeycloakUmaResourceDTO: """Create a UMA resource set. @@ -246,7 +246,7 @@ async def resource_set_read(self, resource_id: str) -> KeycloakUmaResourceDTO: async def resource_set_update( self, resource_id: str, - payload: KeycloakUmaResourceRequestDTO | dict[str, Any], + payload: KeycloakUmaResourceRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a UMA resource set. @@ -315,7 +315,7 @@ async def resource_set_list_ids( async def policy_resource_create( self, resource_id: str, - payload: KeycloakUmaPolicyRequestDTO | dict[str, Any], + payload: KeycloakUmaPolicyRequestDTO, ) -> KeycloakUmaPolicyDTO: """Create a UMA policy for a resource. @@ -332,7 +332,7 @@ async def policy_resource_create( async def policy_update( self, policy_id: str, - payload: KeycloakUmaPolicyRequestDTO | dict[str, Any], + payload: KeycloakUmaPolicyRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a UMA policy. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/__init__.py b/packages/keycloak/archipy/adapters/keycloak/_resources/__init__.py index 195490c38..0ac1d41ba 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/__init__.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/__init__.py @@ -232,13 +232,7 @@ KeycloakUsersPort, ) from archipy.adapters.keycloak._type_aliases import ( - KeycloakClientScopeType, - KeycloakComponentType, - KeycloakGroupType, - KeycloakOrganizationType, - KeycloakProtocolMapperType, KeycloakResponseType, - KeycloakRoleType, KeycloakTokenType, KeycloakUserType, PublicKeyType, @@ -311,16 +305,13 @@ "KeycloakClientInitialAccessPort", "KeycloakClientRegistrationPolicyMixin", "KeycloakClientRegistrationPolicyPort", - "KeycloakClientScopeType", "KeycloakClientScopesMixin", "KeycloakClientScopesPort", "KeycloakClientsMixin", "KeycloakClientsPort", - "KeycloakComponentType", "KeycloakComponentsMixin", "KeycloakComponentsPort", "KeycloakExceptionHandlerMixin", - "KeycloakGroupType", "KeycloakGroupsMixin", "KeycloakGroupsPort", "KeycloakIdentityProvidersMixin", @@ -329,10 +320,8 @@ "KeycloakKeysPort", "KeycloakOrganizationGroupsMixin", "KeycloakOrganizationGroupsPort", - "KeycloakOrganizationType", "KeycloakOrganizationsMixin", "KeycloakOrganizationsPort", - "KeycloakProtocolMapperType", "KeycloakProtocolMappersMixin", "KeycloakProtocolMappersPort", "KeycloakRealmsMixin", @@ -342,7 +331,6 @@ "KeycloakResponseType", "KeycloakRoleMappingsMixin", "KeycloakRoleMappingsPort", - "KeycloakRoleType", "KeycloakRolesByIdMixin", "KeycloakRolesByIdPort", "KeycloakRolesMixin", diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/authentication/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/authentication/adapter.py index 46391ce08..63f66da24 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/authentication/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/authentication/adapter.py @@ -3,7 +3,6 @@ from __future__ import annotations from http import HTTPStatus -from typing import Any from archipy.adapters.keycloak._base import ( AsyncKeycloakMixinBase, @@ -65,7 +64,7 @@ def _find_execution_config_id(self, execution_id: str) -> str | None: def create_authentication_flow( self, - payload: KeycloakAuthenticationFlowRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowRequestDTO, skip_exists: bool = False, ) -> KeycloakCreateResultDTO: """Create a new authentication flow.""" @@ -85,7 +84,7 @@ def create_authentication_flow( def copy_authentication_flow( self, - payload: KeycloakAuthenticationFlowCopyRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowCopyRequestDTO, flow_alias: str, ) -> KeycloakCreateResultDTO: """Copy an existing authentication flow.""" @@ -157,7 +156,7 @@ def get_authentication_flow_execution(self, execution_id: str) -> KeycloakAuthen def create_authentication_flow_execution( self, - payload: KeycloakAuthenticationFlowExecutionCreateRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowExecutionCreateRequestDTO, flow_alias: str, ) -> KeycloakCreateResultDTO: """Create an execution in an authentication flow.""" @@ -177,7 +176,7 @@ def create_authentication_flow_execution( def update_authentication_flow_executions( self, - payload: KeycloakAuthenticationExecutionInfoRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationExecutionInfoRequestDTO, flow_alias: str, ) -> KeycloakUpdateResultDTO: """Update executions in an authentication flow.""" @@ -194,7 +193,7 @@ def update_authentication_flow_executions( def create_authentication_flow_subflow( self, - payload: KeycloakAuthenticationSubflowCreateRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationSubflowCreateRequestDTO, flow_alias: str, skip_exists: bool = False, ) -> KeycloakCreateResultDTO: @@ -234,7 +233,7 @@ def change_execution_priority(self, execution_id: str, diff: int) -> None: def update_authentication_flow( self, flow_id: str, - payload: KeycloakAuthenticationFlowRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an authentication flow.""" return to_mutation_result( @@ -282,7 +281,7 @@ def get_authenticator_config(self, config_id: str) -> KeycloakAuthenticatorConfi def update_authenticator_config( self, - payload: KeycloakAuthenticatorConfigRequestDTO | dict[str, Any], + payload: KeycloakAuthenticatorConfigRequestDTO, config_id: str, ) -> KeycloakUpdateResultDTO: """Update authenticator configuration.""" @@ -310,7 +309,7 @@ def delete_authenticator_config(self, config_id: str) -> KeycloakDeleteResultDTO def create_execution_config( self, execution_id: str, - payload: KeycloakAuthenticatorConfigRequestDTO | dict[str, Any], + payload: KeycloakAuthenticatorConfigRequestDTO, ) -> KeycloakCreateResultDTO: """Create configuration for an authentication flow execution.""" return with_created_id( @@ -405,7 +404,7 @@ def get_per_client_config_description(self) -> dict[str, list[KeycloakConfigProp def create_execution( self, - payload: KeycloakAuthenticationExecutionRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationExecutionRequestDTO, ) -> KeycloakCreateResultDTO: """Add an execution to a flow by its representation. @@ -476,7 +475,7 @@ async def _find_execution_config_id(self, execution_id: str) -> str | None: async def create_authentication_flow( self, - payload: KeycloakAuthenticationFlowRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowRequestDTO, skip_exists: bool = False, ) -> KeycloakCreateResultDTO: """Create a new authentication flow.""" @@ -496,7 +495,7 @@ async def create_authentication_flow( async def copy_authentication_flow( self, - payload: KeycloakAuthenticationFlowCopyRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowCopyRequestDTO, flow_alias: str, ) -> KeycloakCreateResultDTO: """Copy an existing authentication flow.""" @@ -568,7 +567,7 @@ async def get_authentication_flow_execution(self, execution_id: str) -> Keycloak async def create_authentication_flow_execution( self, - payload: KeycloakAuthenticationFlowExecutionCreateRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowExecutionCreateRequestDTO, flow_alias: str, ) -> KeycloakCreateResultDTO: """Create an execution in an authentication flow.""" @@ -588,7 +587,7 @@ async def create_authentication_flow_execution( async def update_authentication_flow_executions( self, - payload: KeycloakAuthenticationExecutionInfoRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationExecutionInfoRequestDTO, flow_alias: str, ) -> KeycloakUpdateResultDTO: """Update executions in an authentication flow.""" @@ -605,7 +604,7 @@ async def update_authentication_flow_executions( async def create_authentication_flow_subflow( self, - payload: KeycloakAuthenticationSubflowCreateRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationSubflowCreateRequestDTO, flow_alias: str, skip_exists: bool = False, ) -> KeycloakCreateResultDTO: @@ -645,7 +644,7 @@ async def change_execution_priority(self, execution_id: str, diff: int) -> None: async def update_authentication_flow( self, flow_id: str, - payload: KeycloakAuthenticationFlowRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an authentication flow.""" return to_mutation_result( @@ -696,7 +695,7 @@ async def get_authenticator_config(self, config_id: str) -> KeycloakAuthenticato async def update_authenticator_config( self, - payload: KeycloakAuthenticatorConfigRequestDTO | dict[str, Any], + payload: KeycloakAuthenticatorConfigRequestDTO, config_id: str, ) -> KeycloakUpdateResultDTO: """Update authenticator configuration.""" @@ -724,7 +723,7 @@ async def delete_authenticator_config(self, config_id: str) -> KeycloakDeleteRes async def create_execution_config( self, execution_id: str, - payload: KeycloakAuthenticatorConfigRequestDTO | dict[str, Any], + payload: KeycloakAuthenticatorConfigRequestDTO, ) -> KeycloakCreateResultDTO: """Create configuration for an authentication flow execution.""" return await with_created_id_async( @@ -817,7 +816,7 @@ async def get_per_client_config_description(self) -> dict[str, list[KeycloakConf async def create_execution( self, - payload: KeycloakAuthenticationExecutionRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationExecutionRequestDTO, ) -> KeycloakCreateResultDTO: """Add an execution to a flow by its representation. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/authentication/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/authentication/port.py index 205d8af3e..bd0015593 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/authentication/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/authentication/port.py @@ -3,7 +3,7 @@ from __future__ import annotations from abc import abstractmethod -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from archipy.models.dtos.keycloak.common_dtos import ( KeycloakCreateResultDTO, @@ -43,7 +43,7 @@ class KeycloakAuthFlowsPort: @abstractmethod def create_authentication_flow( self, - payload: KeycloakAuthenticationFlowRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowRequestDTO, skip_exists: bool = False, ) -> KeycloakCreateResultDTO: """Create a new authentication flow.""" @@ -52,7 +52,7 @@ def create_authentication_flow( @abstractmethod def copy_authentication_flow( self, - payload: KeycloakAuthenticationFlowCopyRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowCopyRequestDTO, flow_alias: str, ) -> KeycloakCreateResultDTO: """Copy an existing authentication flow.""" @@ -88,7 +88,7 @@ def get_authentication_flow_execution(self, execution_id: str) -> KeycloakAuthen @abstractmethod def create_authentication_flow_execution( self, - payload: KeycloakAuthenticationFlowExecutionCreateRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowExecutionCreateRequestDTO, flow_alias: str, ) -> KeycloakCreateResultDTO: """Create an execution in an authentication flow.""" @@ -97,7 +97,7 @@ def create_authentication_flow_execution( @abstractmethod def update_authentication_flow_executions( self, - payload: KeycloakAuthenticationExecutionInfoRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationExecutionInfoRequestDTO, flow_alias: str, ) -> KeycloakUpdateResultDTO: """Update executions in an authentication flow.""" @@ -106,7 +106,7 @@ def update_authentication_flow_executions( @abstractmethod def create_authentication_flow_subflow( self, - payload: KeycloakAuthenticationSubflowCreateRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationSubflowCreateRequestDTO, flow_alias: str, skip_exists: bool = False, ) -> KeycloakCreateResultDTO: @@ -127,7 +127,7 @@ def change_execution_priority(self, execution_id: str, diff: int) -> None: def update_authentication_flow( self, flow_id: str, - payload: KeycloakAuthenticationFlowRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an authentication flow.""" raise NotImplementedError @@ -152,7 +152,7 @@ def get_authenticator_config(self, config_id: str) -> KeycloakAuthenticatorConfi @abstractmethod def update_authenticator_config( self, - payload: KeycloakAuthenticatorConfigRequestDTO | dict[str, Any], + payload: KeycloakAuthenticatorConfigRequestDTO, config_id: str, ) -> KeycloakUpdateResultDTO: """Update authenticator configuration.""" @@ -167,7 +167,7 @@ def delete_authenticator_config(self, config_id: str) -> KeycloakDeleteResultDTO def create_execution_config( self, execution_id: str, - payload: KeycloakAuthenticatorConfigRequestDTO | dict[str, Any], + payload: KeycloakAuthenticatorConfigRequestDTO, ) -> KeycloakCreateResultDTO: """Create configuration for an authentication flow execution.""" raise NotImplementedError @@ -195,7 +195,7 @@ def get_per_client_config_description(self) -> dict[str, list[KeycloakConfigProp @abstractmethod def create_execution( self, - payload: KeycloakAuthenticationExecutionRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationExecutionRequestDTO, ) -> KeycloakCreateResultDTO: """Add an execution to a flow by its representation.""" raise NotImplementedError @@ -212,7 +212,7 @@ class AsyncKeycloakAuthFlowsPort: @abstractmethod async def create_authentication_flow( self, - payload: KeycloakAuthenticationFlowRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowRequestDTO, skip_exists: bool = False, ) -> KeycloakCreateResultDTO: """Create a new authentication flow.""" @@ -221,7 +221,7 @@ async def create_authentication_flow( @abstractmethod async def copy_authentication_flow( self, - payload: KeycloakAuthenticationFlowCopyRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowCopyRequestDTO, flow_alias: str, ) -> KeycloakCreateResultDTO: """Copy an existing authentication flow.""" @@ -257,7 +257,7 @@ async def get_authentication_flow_execution(self, execution_id: str) -> Keycloak @abstractmethod async def create_authentication_flow_execution( self, - payload: KeycloakAuthenticationFlowExecutionCreateRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowExecutionCreateRequestDTO, flow_alias: str, ) -> KeycloakCreateResultDTO: """Create an execution in an authentication flow.""" @@ -266,7 +266,7 @@ async def create_authentication_flow_execution( @abstractmethod async def update_authentication_flow_executions( self, - payload: KeycloakAuthenticationExecutionInfoRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationExecutionInfoRequestDTO, flow_alias: str, ) -> KeycloakUpdateResultDTO: """Update executions in an authentication flow.""" @@ -275,7 +275,7 @@ async def update_authentication_flow_executions( @abstractmethod async def create_authentication_flow_subflow( self, - payload: KeycloakAuthenticationSubflowCreateRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationSubflowCreateRequestDTO, flow_alias: str, skip_exists: bool = False, ) -> KeycloakCreateResultDTO: @@ -296,7 +296,7 @@ async def change_execution_priority(self, execution_id: str, diff: int) -> None: async def update_authentication_flow( self, flow_id: str, - payload: KeycloakAuthenticationFlowRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationFlowRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an authentication flow.""" raise NotImplementedError @@ -324,7 +324,7 @@ async def get_authenticator_config(self, config_id: str) -> KeycloakAuthenticato @abstractmethod async def update_authenticator_config( self, - payload: KeycloakAuthenticatorConfigRequestDTO | dict[str, Any], + payload: KeycloakAuthenticatorConfigRequestDTO, config_id: str, ) -> KeycloakUpdateResultDTO: """Update authenticator configuration.""" @@ -339,7 +339,7 @@ async def delete_authenticator_config(self, config_id: str) -> KeycloakDeleteRes async def create_execution_config( self, execution_id: str, - payload: KeycloakAuthenticatorConfigRequestDTO | dict[str, Any], + payload: KeycloakAuthenticatorConfigRequestDTO, ) -> KeycloakCreateResultDTO: """Create configuration for an authentication flow execution.""" raise NotImplementedError @@ -367,7 +367,7 @@ async def get_per_client_config_description(self) -> dict[str, list[KeycloakConf @abstractmethod async def create_execution( self, - payload: KeycloakAuthenticationExecutionRequestDTO | dict[str, Any], + payload: KeycloakAuthenticationExecutionRequestDTO, ) -> KeycloakCreateResultDTO: """Add an execution to a flow by its representation.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/authorization/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/authorization/adapter.py index 4ee710825..7f0768959 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/authorization/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/authorization/adapter.py @@ -44,7 +44,7 @@ class KeycloakAuthzMixin(SyncKeycloakMixinBase): def create_client_authz_resource( self, client_id: str, - payload: KeycloakAuthzResourceRequestDTO | dict[str, Any], + payload: KeycloakAuthzResourceRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzResourceDTO: """Create an authorization resource for a client.""" @@ -84,7 +84,7 @@ def update_client_authz_resource( self, client_id: str, resource_id: str, - payload: KeycloakAuthzResourceRequestDTO | dict[str, Any], + payload: KeycloakAuthzResourceRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an authorization resource.""" return to_mutation_result( @@ -112,7 +112,7 @@ def delete_client_authz_resource(self, client_id: str, resource_id: str) -> Keyc def create_client_authz_scopes( self, client_id: str, - payload: KeycloakAuthzScopeRequestDTO | dict[str, Any], + payload: KeycloakAuthzScopeRequestDTO, ) -> KeycloakAuthzScopeDTO: """Create authorization scopes for a client.""" return to_dto( @@ -139,7 +139,7 @@ def get_client_authz_scopes(self, client_id: str) -> list[KeycloakAuthzScopeDTO] def create_client_authz_role_based_policy( self, client_id: str, - payload: KeycloakAuthzRolePolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzRolePolicyRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzRolePolicyDTO: """Create a role-based authorization policy.""" @@ -157,7 +157,7 @@ def create_client_authz_role_based_policy( def create_client_authz_client_policy( self, - payload: KeycloakAuthzClientPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzClientPolicyRequestDTO, client_id: str, ) -> KeycloakAuthzClientPolicyDTO: """Create a client-based authorization policy.""" @@ -175,7 +175,7 @@ def create_client_authz_client_policy( def create_client_authz_policy( self, client_id: str, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzPolicyDTO: """Create an authorization policy.""" @@ -224,7 +224,7 @@ def delete_client_authz_policy(self, client_id: str, policy_id: str) -> Keycloak def create_client_authz_resource_based_permission( self, client_id: str, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzPolicyDTO: """Create a resource-based permission.""" @@ -242,7 +242,7 @@ def create_client_authz_resource_based_permission( def create_client_authz_scope_permission( self, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, client_id: str, ) -> KeycloakAuthzPolicyDTO: """Create a scope-based permission.""" @@ -279,7 +279,7 @@ def get_client_authz_scope_permission(self, client_id: str, scope_id: str) -> Ke def update_client_authz_scope_permission( self, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, client_id: str, scope_id: str, ) -> KeycloakUpdateResultDTO: @@ -298,7 +298,7 @@ def update_client_authz_scope_permission( def update_client_authz_resource_permission( self, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, client_id: str, resource_id: str, ) -> KeycloakUpdateResultDTO: @@ -375,7 +375,7 @@ def get_client_authz_policy_scopes(self, client_id: str, policy_id: str) -> list def import_client_authz_config( self, client_id: str, - payload: KeycloakAuthzSettingsRequestDTO | dict[str, Any], + payload: KeycloakAuthzSettingsRequestDTO, ) -> KeycloakUpdateResultDTO: """Import authorization configuration for a client.""" return to_mutation_result( @@ -392,7 +392,7 @@ def import_client_authz_config( def update_client_authz_settings( self, client_id: str, - settings: KeycloakAuthzSettingsRequestDTO | dict[str, Any], + settings: KeycloakAuthzSettingsRequestDTO, ) -> KeycloakUpdateResultDTO: """Update the resource server settings of a client. @@ -588,7 +588,7 @@ def update_client_authz_scope( self, client_id: str, scope_id: str, - payload: KeycloakAuthzScopeRequestDTO | dict[str, Any], + payload: KeycloakAuthzScopeRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a scope. @@ -807,7 +807,7 @@ def get_client_authz_permission_providers(self, client_id: str) -> list[Keycloak def evaluate_client_authz_policies( self, client_id: str, - request: KeycloakAuthzPolicyEvaluationRequestRequestDTO | dict[str, Any], + request: KeycloakAuthzPolicyEvaluationRequestRequestDTO, ) -> KeycloakAuthzPolicyEvaluationResponseDTO: """Evaluate the policies for a user and resources, as the admin console's evaluation tool does. @@ -832,7 +832,7 @@ def evaluate_client_authz_policies( def evaluate_client_authz_permissions( self, client_id: str, - request: KeycloakAuthzPolicyEvaluationRequestRequestDTO | dict[str, Any], + request: KeycloakAuthzPolicyEvaluationRequestRequestDTO, ) -> KeycloakAuthzPolicyEvaluationResponseDTO: """Evaluate the permissions for a user and resources. @@ -861,7 +861,7 @@ class AsyncKeycloakAuthzMixin(AsyncKeycloakMixinBase): async def create_client_authz_resource( self, client_id: str, - payload: KeycloakAuthzResourceRequestDTO | dict[str, Any], + payload: KeycloakAuthzResourceRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzResourceDTO: """Create an authorization resource for a client.""" @@ -901,7 +901,7 @@ async def update_client_authz_resource( self, client_id: str, resource_id: str, - payload: KeycloakAuthzResourceRequestDTO | dict[str, Any], + payload: KeycloakAuthzResourceRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an authorization resource.""" return to_mutation_result( @@ -929,7 +929,7 @@ async def delete_client_authz_resource(self, client_id: str, resource_id: str) - async def create_client_authz_scopes( self, client_id: str, - payload: KeycloakAuthzScopeRequestDTO | dict[str, Any], + payload: KeycloakAuthzScopeRequestDTO, ) -> KeycloakAuthzScopeDTO: """Create authorization scopes for a client.""" return to_dto( @@ -956,7 +956,7 @@ async def get_client_authz_scopes(self, client_id: str) -> list[KeycloakAuthzSco async def create_client_authz_role_based_policy( self, client_id: str, - payload: KeycloakAuthzRolePolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzRolePolicyRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzRolePolicyDTO: """Create a role-based authorization policy.""" @@ -974,7 +974,7 @@ async def create_client_authz_role_based_policy( async def create_client_authz_client_policy( self, - payload: KeycloakAuthzClientPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzClientPolicyRequestDTO, client_id: str, ) -> KeycloakAuthzClientPolicyDTO: """Create a client-based authorization policy.""" @@ -992,7 +992,7 @@ async def create_client_authz_client_policy( async def create_client_authz_policy( self, client_id: str, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzPolicyDTO: """Create an authorization policy.""" @@ -1041,7 +1041,7 @@ async def delete_client_authz_policy(self, client_id: str, policy_id: str) -> Ke async def create_client_authz_resource_based_permission( self, client_id: str, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzPolicyDTO: """Create a resource-based permission.""" @@ -1059,7 +1059,7 @@ async def create_client_authz_resource_based_permission( async def create_client_authz_scope_permission( self, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, client_id: str, ) -> KeycloakAuthzPolicyDTO: """Create a scope-based permission.""" @@ -1096,7 +1096,7 @@ async def get_client_authz_scope_permission(self, client_id: str, scope_id: str) async def update_client_authz_scope_permission( self, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, client_id: str, scope_id: str, ) -> KeycloakUpdateResultDTO: @@ -1115,7 +1115,7 @@ async def update_client_authz_scope_permission( async def update_client_authz_resource_permission( self, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, client_id: str, resource_id: str, ) -> KeycloakUpdateResultDTO: @@ -1195,7 +1195,7 @@ async def get_client_authz_policy_scopes(self, client_id: str, policy_id: str) - async def import_client_authz_config( self, client_id: str, - payload: KeycloakAuthzSettingsRequestDTO | dict[str, Any], + payload: KeycloakAuthzSettingsRequestDTO, ) -> KeycloakUpdateResultDTO: """Import authorization configuration for a client.""" return to_mutation_result( @@ -1212,7 +1212,7 @@ async def import_client_authz_config( async def update_client_authz_settings( self, client_id: str, - settings: KeycloakAuthzSettingsRequestDTO | dict[str, Any], + settings: KeycloakAuthzSettingsRequestDTO, ) -> KeycloakUpdateResultDTO: """Update the resource server settings of a client. @@ -1412,7 +1412,7 @@ async def update_client_authz_scope( self, client_id: str, scope_id: str, - payload: KeycloakAuthzScopeRequestDTO | dict[str, Any], + payload: KeycloakAuthzScopeRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a scope. @@ -1631,7 +1631,7 @@ async def get_client_authz_permission_providers(self, client_id: str) -> list[Ke async def evaluate_client_authz_policies( self, client_id: str, - request: KeycloakAuthzPolicyEvaluationRequestRequestDTO | dict[str, Any], + request: KeycloakAuthzPolicyEvaluationRequestRequestDTO, ) -> KeycloakAuthzPolicyEvaluationResponseDTO: """Evaluate the policies for a user and resources, as the admin console's evaluation tool does. @@ -1656,7 +1656,7 @@ async def evaluate_client_authz_policies( async def evaluate_client_authz_permissions( self, client_id: str, - request: KeycloakAuthzPolicyEvaluationRequestRequestDTO | dict[str, Any], + request: KeycloakAuthzPolicyEvaluationRequestRequestDTO, ) -> KeycloakAuthzPolicyEvaluationResponseDTO: """Evaluate the permissions for a user and resources. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/authorization/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/authorization/port.py index bbdf98170..bd273adbc 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/authorization/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/authorization/port.py @@ -46,7 +46,7 @@ class KeycloakAuthzPort: def create_client_authz_resource( self, client_id: str, - payload: KeycloakAuthzResourceRequestDTO | dict[str, Any], + payload: KeycloakAuthzResourceRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzResourceDTO: """Create an authorization resource for a client.""" @@ -67,7 +67,7 @@ def update_client_authz_resource( self, client_id: str, resource_id: str, - payload: KeycloakAuthzResourceRequestDTO | dict[str, Any], + payload: KeycloakAuthzResourceRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an authorization resource.""" raise NotImplementedError @@ -81,7 +81,7 @@ def delete_client_authz_resource(self, client_id: str, resource_id: str) -> Keyc def create_client_authz_scopes( self, client_id: str, - payload: KeycloakAuthzScopeRequestDTO | dict[str, Any], + payload: KeycloakAuthzScopeRequestDTO, ) -> KeycloakAuthzScopeDTO: """Create authorization scopes for a client.""" raise NotImplementedError @@ -95,7 +95,7 @@ def get_client_authz_scopes(self, client_id: str) -> list[KeycloakAuthzScopeDTO] def create_client_authz_role_based_policy( self, client_id: str, - payload: KeycloakAuthzRolePolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzRolePolicyRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzRolePolicyDTO: """Create a role-based authorization policy.""" @@ -104,7 +104,7 @@ def create_client_authz_role_based_policy( @abstractmethod def create_client_authz_client_policy( self, - payload: KeycloakAuthzClientPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzClientPolicyRequestDTO, client_id: str, ) -> KeycloakAuthzClientPolicyDTO: """Create a client-based authorization policy.""" @@ -114,7 +114,7 @@ def create_client_authz_client_policy( def create_client_authz_policy( self, client_id: str, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzPolicyDTO: """Create an authorization policy.""" @@ -139,7 +139,7 @@ def delete_client_authz_policy(self, client_id: str, policy_id: str) -> Keycloak def create_client_authz_resource_based_permission( self, client_id: str, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzPolicyDTO: """Create a resource-based permission.""" @@ -148,7 +148,7 @@ def create_client_authz_resource_based_permission( @abstractmethod def create_client_authz_scope_permission( self, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, client_id: str, ) -> KeycloakAuthzPolicyDTO: """Create a scope-based permission.""" @@ -167,7 +167,7 @@ def get_client_authz_scope_permission(self, client_id: str, scope_id: str) -> Ke @abstractmethod def update_client_authz_scope_permission( self, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, client_id: str, scope_id: str, ) -> KeycloakUpdateResultDTO: @@ -177,7 +177,7 @@ def update_client_authz_scope_permission( @abstractmethod def update_client_authz_resource_permission( self, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, client_id: str, resource_id: str, ) -> KeycloakUpdateResultDTO: @@ -217,7 +217,7 @@ def get_client_authz_policy_scopes(self, client_id: str, policy_id: str) -> list def import_client_authz_config( self, client_id: str, - payload: KeycloakAuthzSettingsRequestDTO | dict[str, Any], + payload: KeycloakAuthzSettingsRequestDTO, ) -> KeycloakUpdateResultDTO: """Import authorization configuration for a client.""" raise NotImplementedError @@ -226,7 +226,7 @@ def import_client_authz_config( def update_client_authz_settings( self, client_id: str, - settings: KeycloakAuthzSettingsRequestDTO | dict[str, Any], + settings: KeycloakAuthzSettingsRequestDTO, ) -> KeycloakUpdateResultDTO: """Update the resource server settings of a client.""" raise NotImplementedError @@ -284,7 +284,7 @@ def update_client_authz_scope( self, client_id: str, scope_id: str, - payload: KeycloakAuthzScopeRequestDTO | dict[str, Any], + payload: KeycloakAuthzScopeRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a scope.""" raise NotImplementedError @@ -346,7 +346,7 @@ def get_client_authz_permission_providers(self, client_id: str) -> list[Keycloak def evaluate_client_authz_policies( self, client_id: str, - request: KeycloakAuthzPolicyEvaluationRequestRequestDTO | dict[str, Any], + request: KeycloakAuthzPolicyEvaluationRequestRequestDTO, ) -> KeycloakAuthzPolicyEvaluationResponseDTO: """Evaluate the policies for a user and resources, as the admin console's evaluation tool does.""" raise NotImplementedError @@ -355,7 +355,7 @@ def evaluate_client_authz_policies( def evaluate_client_authz_permissions( self, client_id: str, - request: KeycloakAuthzPolicyEvaluationRequestRequestDTO | dict[str, Any], + request: KeycloakAuthzPolicyEvaluationRequestRequestDTO, ) -> KeycloakAuthzPolicyEvaluationResponseDTO: """Evaluate the permissions for a user and resources.""" raise NotImplementedError @@ -368,7 +368,7 @@ class AsyncKeycloakAuthzPort: async def create_client_authz_resource( self, client_id: str, - payload: KeycloakAuthzResourceRequestDTO | dict[str, Any], + payload: KeycloakAuthzResourceRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzResourceDTO: """Create an authorization resource for a client.""" @@ -389,7 +389,7 @@ async def update_client_authz_resource( self, client_id: str, resource_id: str, - payload: KeycloakAuthzResourceRequestDTO | dict[str, Any], + payload: KeycloakAuthzResourceRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an authorization resource.""" raise NotImplementedError @@ -403,7 +403,7 @@ async def delete_client_authz_resource(self, client_id: str, resource_id: str) - async def create_client_authz_scopes( self, client_id: str, - payload: KeycloakAuthzScopeRequestDTO | dict[str, Any], + payload: KeycloakAuthzScopeRequestDTO, ) -> KeycloakAuthzScopeDTO: """Create authorization scopes for a client.""" raise NotImplementedError @@ -417,7 +417,7 @@ async def get_client_authz_scopes(self, client_id: str) -> list[KeycloakAuthzSco async def create_client_authz_role_based_policy( self, client_id: str, - payload: KeycloakAuthzRolePolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzRolePolicyRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzRolePolicyDTO: """Create a role-based authorization policy.""" @@ -426,7 +426,7 @@ async def create_client_authz_role_based_policy( @abstractmethod async def create_client_authz_client_policy( self, - payload: KeycloakAuthzClientPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzClientPolicyRequestDTO, client_id: str, ) -> KeycloakAuthzClientPolicyDTO: """Create a client-based authorization policy.""" @@ -436,7 +436,7 @@ async def create_client_authz_client_policy( async def create_client_authz_policy( self, client_id: str, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzPolicyDTO: """Create an authorization policy.""" @@ -461,7 +461,7 @@ async def delete_client_authz_policy(self, client_id: str, policy_id: str) -> Ke async def create_client_authz_resource_based_permission( self, client_id: str, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, skip_exists: bool = False, ) -> KeycloakAuthzPolicyDTO: """Create a resource-based permission.""" @@ -470,7 +470,7 @@ async def create_client_authz_resource_based_permission( @abstractmethod async def create_client_authz_scope_permission( self, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, client_id: str, ) -> KeycloakAuthzPolicyDTO: """Create a scope-based permission.""" @@ -489,7 +489,7 @@ async def get_client_authz_scope_permission(self, client_id: str, scope_id: str) @abstractmethod async def update_client_authz_scope_permission( self, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, client_id: str, scope_id: str, ) -> KeycloakUpdateResultDTO: @@ -499,7 +499,7 @@ async def update_client_authz_scope_permission( @abstractmethod async def update_client_authz_resource_permission( self, - payload: KeycloakAuthzPolicyRequestDTO | dict[str, Any], + payload: KeycloakAuthzPolicyRequestDTO, client_id: str, resource_id: str, ) -> KeycloakUpdateResultDTO: @@ -539,7 +539,7 @@ async def get_client_authz_policy_scopes(self, client_id: str, policy_id: str) - async def import_client_authz_config( self, client_id: str, - payload: KeycloakAuthzSettingsRequestDTO | dict[str, Any], + payload: KeycloakAuthzSettingsRequestDTO, ) -> KeycloakUpdateResultDTO: """Import authorization configuration for a client.""" raise NotImplementedError @@ -548,7 +548,7 @@ async def import_client_authz_config( async def update_client_authz_settings( self, client_id: str, - settings: KeycloakAuthzSettingsRequestDTO | dict[str, Any], + settings: KeycloakAuthzSettingsRequestDTO, ) -> KeycloakUpdateResultDTO: """Update the resource server settings of a client.""" raise NotImplementedError @@ -610,7 +610,7 @@ async def update_client_authz_scope( self, client_id: str, scope_id: str, - payload: KeycloakAuthzScopeRequestDTO | dict[str, Any], + payload: KeycloakAuthzScopeRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a scope.""" raise NotImplementedError @@ -672,7 +672,7 @@ async def get_client_authz_permission_providers(self, client_id: str) -> list[Ke async def evaluate_client_authz_policies( self, client_id: str, - request: KeycloakAuthzPolicyEvaluationRequestRequestDTO | dict[str, Any], + request: KeycloakAuthzPolicyEvaluationRequestRequestDTO, ) -> KeycloakAuthzPolicyEvaluationResponseDTO: """Evaluate the policies for a user and resources, as the admin console's evaluation tool does.""" raise NotImplementedError @@ -681,7 +681,7 @@ async def evaluate_client_authz_policies( async def evaluate_client_authz_permissions( self, client_id: str, - request: KeycloakAuthzPolicyEvaluationRequestRequestDTO | dict[str, Any], + request: KeycloakAuthzPolicyEvaluationRequestRequestDTO, ) -> KeycloakAuthzPolicyEvaluationResponseDTO: """Evaluate the permissions for a user and resources.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/client_certificates/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/client_certificates/adapter.py index d2011c1b9..0649a3088 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/client_certificates/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/client_certificates/adapter.py @@ -3,7 +3,6 @@ from __future__ import annotations from http import HTTPStatus -from typing import Any from archipy.adapters.keycloak._base import ( AsyncKeycloakMixinBase, @@ -65,7 +64,7 @@ def download_client_keystore( self, client_uuid: str, attribute: str, - config: KeycloakKeyStoreConfigRequestDTO | dict[str, Any], + config: KeycloakKeyStoreConfigRequestDTO, ) -> bytes: """Download the client attribute's key and certificate as a key store. @@ -89,7 +88,7 @@ def generate_and_download_client_keystore( self, client_uuid: str, attribute: str, - config: KeycloakKeyStoreConfigRequestDTO | dict[str, Any], + config: KeycloakKeyStoreConfigRequestDTO, ) -> bytes: """Generate a new key pair for a client attribute and download it as a key store. @@ -157,7 +156,7 @@ async def download_client_keystore( self, client_uuid: str, attribute: str, - config: KeycloakKeyStoreConfigRequestDTO | dict[str, Any], + config: KeycloakKeyStoreConfigRequestDTO, ) -> bytes: """Download the client attribute's key and certificate as a key store. @@ -181,7 +180,7 @@ async def generate_and_download_client_keystore( self, client_uuid: str, attribute: str, - config: KeycloakKeyStoreConfigRequestDTO | dict[str, Any], + config: KeycloakKeyStoreConfigRequestDTO, ) -> bytes: """Generate a new key pair for a client attribute and download it as a key store. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/client_certificates/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/client_certificates/port.py index b28303bf4..ac85feba8 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/client_certificates/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/client_certificates/port.py @@ -3,7 +3,7 @@ from __future__ import annotations from abc import abstractmethod -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING if TYPE_CHECKING: from archipy.models.dtos.keycloak.certificate_dtos import ( @@ -30,7 +30,7 @@ def download_client_keystore( self, client_uuid: str, attribute: str, - config: KeycloakKeyStoreConfigRequestDTO | dict[str, Any], + config: KeycloakKeyStoreConfigRequestDTO, ) -> bytes: """Download the client attribute's key and certificate as a key store.""" raise NotImplementedError @@ -40,7 +40,7 @@ def generate_and_download_client_keystore( self, client_uuid: str, attribute: str, - config: KeycloakKeyStoreConfigRequestDTO | dict[str, Any], + config: KeycloakKeyStoreConfigRequestDTO, ) -> bytes: """Generate a new key pair for a client attribute and download it as a key store.""" raise NotImplementedError @@ -64,7 +64,7 @@ async def download_client_keystore( self, client_uuid: str, attribute: str, - config: KeycloakKeyStoreConfigRequestDTO | dict[str, Any], + config: KeycloakKeyStoreConfigRequestDTO, ) -> bytes: """Download the client attribute's key and certificate as a key store.""" raise NotImplementedError @@ -74,7 +74,7 @@ async def generate_and_download_client_keystore( self, client_uuid: str, attribute: str, - config: KeycloakKeyStoreConfigRequestDTO | dict[str, Any], + config: KeycloakKeyStoreConfigRequestDTO, ) -> bytes: """Generate a new key pair for a client attribute and download it as a key store.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/client_initial_access/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/client_initial_access/adapter.py index 3bf8b2e7f..e1717f9cb 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/client_initial_access/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/client_initial_access/adapter.py @@ -3,7 +3,6 @@ from __future__ import annotations from http import HTTPStatus -from typing import Any from archipy.adapters.keycloak._base import ( AsyncKeycloakMixinBase, @@ -47,7 +46,7 @@ def get_client_initial_access_tokens(self) -> list[KeycloakClientInitialAccessDT def create_client_initial_access( self, - payload: KeycloakClientInitialAccessCreateRequestDTO | dict[str, Any], + payload: KeycloakClientInitialAccessCreateRequestDTO, ) -> KeycloakClientInitialAccessDTO: """Create a client initial access token. @@ -115,7 +114,7 @@ async def get_client_initial_access_tokens(self) -> list[KeycloakClientInitialAc async def create_client_initial_access( self, - payload: KeycloakClientInitialAccessCreateRequestDTO | dict[str, Any], + payload: KeycloakClientInitialAccessCreateRequestDTO, ) -> KeycloakClientInitialAccessDTO: """Create a client initial access token. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/client_initial_access/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/client_initial_access/port.py index 3f58b7b8c..19d52752c 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/client_initial_access/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/client_initial_access/port.py @@ -3,7 +3,7 @@ from __future__ import annotations from abc import abstractmethod -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING if TYPE_CHECKING: from archipy.models.dtos.keycloak.client_initial_access_dtos import ( @@ -26,7 +26,7 @@ def get_client_initial_access_tokens(self) -> list[KeycloakClientInitialAccessDT @abstractmethod def create_client_initial_access( self, - payload: KeycloakClientInitialAccessCreateRequestDTO | dict[str, Any], + payload: KeycloakClientInitialAccessCreateRequestDTO, ) -> KeycloakClientInitialAccessDTO: """Create a client initial access token.""" raise NotImplementedError @@ -48,7 +48,7 @@ async def get_client_initial_access_tokens(self) -> list[KeycloakClientInitialAc @abstractmethod async def create_client_initial_access( self, - payload: KeycloakClientInitialAccessCreateRequestDTO | dict[str, Any], + payload: KeycloakClientInitialAccessCreateRequestDTO, ) -> KeycloakClientInitialAccessDTO: """Create a client initial access token.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/client_scopes/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/client_scopes/adapter.py index d4fb9dc86..96f88aef7 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/client_scopes/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/client_scopes/adapter.py @@ -2,8 +2,6 @@ from __future__ import annotations -from typing import Any - from archipy.adapters.keycloak._base import ( AsyncKeycloakMixinBase, SyncKeycloakMixinBase, @@ -61,7 +59,7 @@ def get_client_scope_by_name(self, client_scope_name: str) -> KeycloakClientScop def create_client_scope( self, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, skip_exists: bool = False, ) -> str: """Create a new client scope.""" @@ -76,7 +74,7 @@ def create_client_scope( def update_client_scope( self, client_scope_id: str, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a client scope.""" return to_mutation_result( @@ -114,7 +112,7 @@ def add_client_default_client_scope( self, client_id: str, client_scope_id: str, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, ) -> KeycloakAssignResultDTO: """Add a default client scope to a client.""" return to_mutation_result( @@ -156,7 +154,7 @@ def add_client_optional_client_scope( self, client_id: str, client_scope_id: str, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, ) -> KeycloakAssignResultDTO: """Add an optional client scope to a client.""" return to_mutation_result( @@ -286,7 +284,7 @@ async def get_client_scope_by_name(self, client_scope_name: str) -> KeycloakClie async def create_client_scope( self, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, skip_exists: bool = False, ) -> str: """Create a new client scope.""" @@ -301,7 +299,7 @@ async def create_client_scope( async def update_client_scope( self, client_scope_id: str, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a client scope.""" return to_mutation_result( @@ -339,7 +337,7 @@ async def add_client_default_client_scope( self, client_id: str, client_scope_id: str, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, ) -> KeycloakAssignResultDTO: """Add a default client scope to a client.""" return to_mutation_result( @@ -385,7 +383,7 @@ async def add_client_optional_client_scope( self, client_id: str, client_scope_id: str, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, ) -> KeycloakAssignResultDTO: """Add an optional client scope to a client.""" return to_mutation_result( diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/client_scopes/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/client_scopes/port.py index 952e94067..71007761e 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/client_scopes/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/client_scopes/port.py @@ -3,7 +3,7 @@ from __future__ import annotations from abc import abstractmethod -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from archipy.models.dtos.keycloak.common_dtos import ( KeycloakAssignResultDTO, @@ -46,7 +46,7 @@ def get_client_scope_by_name(self, client_scope_name: str) -> KeycloakClientScop @abstractmethod def create_client_scope( self, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, skip_exists: bool = False, ) -> str: """Create a new client scope.""" @@ -56,7 +56,7 @@ def create_client_scope( def update_client_scope( self, client_scope_id: str, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a client scope.""" raise NotImplementedError @@ -76,7 +76,7 @@ def add_client_default_client_scope( self, client_id: str, client_scope_id: str, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, ) -> KeycloakAssignResultDTO: """Add a default client scope to a client.""" raise NotImplementedError @@ -96,7 +96,7 @@ def add_client_optional_client_scope( self, client_id: str, client_scope_id: str, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, ) -> KeycloakAssignResultDTO: """Add an optional client scope to a client.""" raise NotImplementedError @@ -164,7 +164,7 @@ async def get_client_scope_by_name(self, client_scope_name: str) -> KeycloakClie @abstractmethod async def create_client_scope( self, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, skip_exists: bool = False, ) -> str: """Create a new client scope.""" @@ -174,7 +174,7 @@ async def create_client_scope( async def update_client_scope( self, client_scope_id: str, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a client scope.""" raise NotImplementedError @@ -194,7 +194,7 @@ async def add_client_default_client_scope( self, client_id: str, client_scope_id: str, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, ) -> KeycloakAssignResultDTO: """Add a default client scope to a client.""" raise NotImplementedError @@ -218,7 +218,7 @@ async def add_client_optional_client_scope( self, client_id: str, client_scope_id: str, - payload: KeycloakClientScopeRequestDTO | dict[str, Any], + payload: KeycloakClientScopeRequestDTO, ) -> KeycloakAssignResultDTO: """Add an optional client scope to a client.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/clients/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/clients/adapter.py index ea070fc48..7259554c1 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/clients/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/clients/adapter.py @@ -238,7 +238,7 @@ def get_client(self, client_uuid: str) -> KeycloakClientDTO: def update_client( self, client_uuid: str, - payload: KeycloakClientRequestDTO | dict[str, Any], + payload: KeycloakClientRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a client. @@ -609,7 +609,7 @@ def get_client_management_permissions(self, client_uuid: str) -> KeycloakManagem def update_client_management_permissions( self, client_uuid: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a client. @@ -995,7 +995,7 @@ async def get_client(self, client_uuid: str) -> KeycloakClientDTO: async def update_client( self, client_uuid: str, - payload: KeycloakClientRequestDTO | dict[str, Any], + payload: KeycloakClientRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a client. @@ -1370,7 +1370,7 @@ async def get_client_management_permissions(self, client_uuid: str) -> KeycloakM async def update_client_management_permissions( self, client_uuid: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a client. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/clients/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/clients/port.py index 84658557e..a8051cd33 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/clients/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/clients/port.py @@ -74,7 +74,7 @@ def get_client(self, client_uuid: str) -> KeycloakClientDTO: def update_client( self, client_uuid: str, - payload: KeycloakClientRequestDTO | dict[str, Any], + payload: KeycloakClientRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a client.""" raise NotImplementedError @@ -189,7 +189,7 @@ def get_client_management_permissions(self, client_uuid: str) -> KeycloakManagem def update_client_management_permissions( self, client_uuid: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a client.""" raise NotImplementedError @@ -287,7 +287,7 @@ async def get_client(self, client_uuid: str) -> KeycloakClientDTO: async def update_client( self, client_uuid: str, - payload: KeycloakClientRequestDTO | dict[str, Any], + payload: KeycloakClientRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a client.""" raise NotImplementedError @@ -406,7 +406,7 @@ async def get_client_management_permissions(self, client_uuid: str) -> KeycloakM async def update_client_management_permissions( self, client_uuid: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a client.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/components/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/components/adapter.py index cb29d453f..9697b3ae5 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/components/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/components/adapter.py @@ -25,7 +25,7 @@ class KeycloakComponentsMixin(SyncKeycloakMixinBase): """Sync Keycloak mixin for component operations.""" - def create_component(self, payload: KeycloakComponentRequestDTO | dict[str, Any]) -> str: + def create_component(self, payload: KeycloakComponentRequestDTO) -> str: """Create a Keycloak component. Args: @@ -76,7 +76,7 @@ def get_components(self, query: dict[str, Any] | None = None) -> list[KeycloakCo def update_component( self, component_id: str, - payload: KeycloakComponentRequestDTO | dict[str, Any], + payload: KeycloakComponentRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a component. @@ -140,7 +140,7 @@ def get_component_sub_types(self, component_id: str, component_type: str) -> lis class AsyncKeycloakComponentsMixin(AsyncKeycloakMixinBase): """Async Keycloak mixin for component operations.""" - async def create_component(self, payload: KeycloakComponentRequestDTO | dict[str, Any]) -> str: + async def create_component(self, payload: KeycloakComponentRequestDTO) -> str: """Create a Keycloak component. Args: @@ -191,7 +191,7 @@ async def get_components(self, query: dict[str, Any] | None = None) -> list[Keyc async def update_component( self, component_id: str, - payload: KeycloakComponentRequestDTO | dict[str, Any], + payload: KeycloakComponentRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a component. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/components/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/components/port.py index dc10140a3..e42f8d6b4 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/components/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/components/port.py @@ -20,7 +20,7 @@ class KeycloakComponentsPort: """Sync Keycloak port interface for component operations.""" @abstractmethod - def create_component(self, payload: KeycloakComponentRequestDTO | dict[str, Any]) -> str: + def create_component(self, payload: KeycloakComponentRequestDTO) -> str: """Create a Keycloak component. Args: @@ -59,7 +59,7 @@ def get_components(self, query: dict[str, Any] | None = None) -> list[KeycloakCo def update_component( self, component_id: str, - payload: KeycloakComponentRequestDTO | dict[str, Any], + payload: KeycloakComponentRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a component. @@ -94,7 +94,7 @@ class AsyncKeycloakComponentsPort: """Async Keycloak port interface for component operations.""" @abstractmethod - async def create_component(self, payload: KeycloakComponentRequestDTO | dict[str, Any]) -> str: + async def create_component(self, payload: KeycloakComponentRequestDTO) -> str: """Create a Keycloak component. Args: @@ -133,7 +133,7 @@ async def get_components(self, query: dict[str, Any] | None = None) -> list[Keyc async def update_component( self, component_id: str, - payload: KeycloakComponentRequestDTO | dict[str, Any], + payload: KeycloakComponentRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a component. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/groups/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/groups/adapter.py index 5824d13ef..7c3809f5e 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/groups/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/groups/adapter.py @@ -36,7 +36,7 @@ class KeycloakGroupsMixin(SyncKeycloakMixinBase): def create_group( self, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, parent: str | None = None, skip_exists: bool = False, ) -> str | None: @@ -53,7 +53,7 @@ def create_group( def update_group( self, group_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a group.""" return to_mutation_result( @@ -128,7 +128,7 @@ def get_groups(self, query: dict[str, Any] | None = None, full_hierarchy: bool = ), ) - def get_subgroups(self, group: KeycloakGroupDTO | dict[str, Any], path: str) -> KeycloakGroupDTO | None: + def get_subgroups(self, group: KeycloakGroupDTO, path: str) -> KeycloakGroupDTO | None: """Get subgroups for a group at the given path.""" return to_dto_or_none( KeycloakGroupDTO, @@ -347,7 +347,7 @@ def get_group_management_permissions(self, group_id: str) -> KeycloakManagementP def update_group_management_permissions( self, group_id: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a group. @@ -375,7 +375,7 @@ class AsyncKeycloakGroupsMixin(AsyncKeycloakMixinBase): async def create_group( self, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, parent: str | None = None, skip_exists: bool = False, ) -> str | None: @@ -392,7 +392,7 @@ async def create_group( async def update_group( self, group_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a group.""" return to_mutation_result( @@ -471,7 +471,7 @@ async def get_groups( ), ) - async def get_subgroups(self, group: KeycloakGroupDTO | dict[str, Any], path: str) -> KeycloakGroupDTO | None: + async def get_subgroups(self, group: KeycloakGroupDTO, path: str) -> KeycloakGroupDTO | None: """Get subgroups for a group at the given path.""" return to_dto_or_none( KeycloakGroupDTO, @@ -690,7 +690,7 @@ async def get_group_management_permissions(self, group_id: str) -> KeycloakManag async def update_group_management_permissions( self, group_id: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a group. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/groups/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/groups/port.py index 32cba7ad6..694e1d68a 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/groups/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/groups/port.py @@ -31,7 +31,7 @@ class KeycloakGroupsPort: @abstractmethod def create_group( self, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, parent: str | None = None, skip_exists: bool = False, ) -> str | None: @@ -42,7 +42,7 @@ def create_group( def update_group( self, group_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a group.""" raise NotImplementedError @@ -83,7 +83,7 @@ def get_groups(self, query: dict[str, Any] | None = None, full_hierarchy: bool = raise NotImplementedError @abstractmethod - def get_subgroups(self, group: KeycloakGroupDTO | dict[str, Any], path: str) -> KeycloakGroupDTO | None: + def get_subgroups(self, group: KeycloakGroupDTO, path: str) -> KeycloakGroupDTO | None: """Get subgroups for a group at the given path.""" raise NotImplementedError @@ -194,7 +194,7 @@ def get_group_management_permissions(self, group_id: str) -> KeycloakManagementP def update_group_management_permissions( self, group_id: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a group.""" raise NotImplementedError @@ -208,7 +208,7 @@ class AsyncKeycloakGroupsPort: @abstractmethod async def create_group( self, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, parent: str | None = None, skip_exists: bool = False, ) -> str | None: @@ -219,7 +219,7 @@ async def create_group( async def update_group( self, group_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a group.""" raise NotImplementedError @@ -264,7 +264,7 @@ async def get_groups( raise NotImplementedError @abstractmethod - async def get_subgroups(self, group: KeycloakGroupDTO | dict[str, Any], path: str) -> KeycloakGroupDTO | None: + async def get_subgroups(self, group: KeycloakGroupDTO, path: str) -> KeycloakGroupDTO | None: """Get subgroups for a group at the given path.""" raise NotImplementedError @@ -375,7 +375,7 @@ async def get_group_management_permissions(self, group_id: str) -> KeycloakManag async def update_group_management_permissions( self, group_id: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a group.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/identity_providers/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/identity_providers/adapter.py index c7d990beb..3bf10d2ce 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/identity_providers/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/identity_providers/adapter.py @@ -69,7 +69,7 @@ def get_identity_providers(self, query: dict[str, Any] | None = None) -> list[Ke def create_identity_provider( self, - payload: KeycloakIdentityProviderRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderRequestDTO, ) -> KeycloakCreateResultDTO: """Create an identity provider. @@ -119,7 +119,7 @@ def get_identity_provider(self, alias: str) -> KeycloakIdentityProviderDTO: def update_identity_provider( self, alias: str, - payload: KeycloakIdentityProviderRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an identity provider. @@ -202,7 +202,7 @@ def get_identity_provider_management_permissions(self, alias: str) -> KeycloakMa def update_identity_provider_management_permissions( self, alias: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of an identity provider. @@ -262,7 +262,7 @@ def get_identity_provider_mappers(self, alias: str) -> list[KeycloakIdentityProv def create_identity_provider_mapper( self, alias: str, - payload: KeycloakIdentityProviderMapperRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderMapperRequestDTO, ) -> KeycloakCreateResultDTO: """Create a mapper of an identity provider. @@ -315,7 +315,7 @@ def update_identity_provider_mapper( self, alias: str, mapper_id: str, - payload: KeycloakIdentityProviderMapperRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderMapperRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a mapper of an identity provider. @@ -443,7 +443,7 @@ async def get_identity_providers(self, query: dict[str, Any] | None = None) -> l async def create_identity_provider( self, - payload: KeycloakIdentityProviderRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderRequestDTO, ) -> KeycloakCreateResultDTO: """Create an identity provider. @@ -493,7 +493,7 @@ async def get_identity_provider(self, alias: str) -> KeycloakIdentityProviderDTO async def update_identity_provider( self, alias: str, - payload: KeycloakIdentityProviderRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an identity provider. @@ -576,7 +576,7 @@ async def get_identity_provider_management_permissions(self, alias: str) -> Keyc async def update_identity_provider_management_permissions( self, alias: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of an identity provider. @@ -636,7 +636,7 @@ async def get_identity_provider_mappers(self, alias: str) -> list[KeycloakIdenti async def create_identity_provider_mapper( self, alias: str, - payload: KeycloakIdentityProviderMapperRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderMapperRequestDTO, ) -> KeycloakCreateResultDTO: """Create a mapper of an identity provider. @@ -689,7 +689,7 @@ async def update_identity_provider_mapper( self, alias: str, mapper_id: str, - payload: KeycloakIdentityProviderMapperRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderMapperRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a mapper of an identity provider. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/identity_providers/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/identity_providers/port.py index 9c094cd39..467d0ffe6 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/identity_providers/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/identity_providers/port.py @@ -34,7 +34,7 @@ def get_identity_providers(self, query: dict[str, Any] | None = None) -> list[Ke @abstractmethod def create_identity_provider( self, - payload: KeycloakIdentityProviderRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderRequestDTO, ) -> KeycloakCreateResultDTO: """Create an identity provider.""" raise NotImplementedError @@ -48,7 +48,7 @@ def get_identity_provider(self, alias: str) -> KeycloakIdentityProviderDTO: def update_identity_provider( self, alias: str, - payload: KeycloakIdentityProviderRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an identity provider.""" raise NotImplementedError @@ -72,7 +72,7 @@ def get_identity_provider_management_permissions(self, alias: str) -> KeycloakMa def update_identity_provider_management_permissions( self, alias: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of an identity provider.""" raise NotImplementedError @@ -91,7 +91,7 @@ def get_identity_provider_mappers(self, alias: str) -> list[KeycloakIdentityProv def create_identity_provider_mapper( self, alias: str, - payload: KeycloakIdentityProviderMapperRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderMapperRequestDTO, ) -> KeycloakCreateResultDTO: """Create a mapper of an identity provider.""" raise NotImplementedError @@ -106,7 +106,7 @@ def update_identity_provider_mapper( self, alias: str, mapper_id: str, - payload: KeycloakIdentityProviderMapperRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderMapperRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a mapper of an identity provider.""" raise NotImplementedError @@ -143,7 +143,7 @@ async def get_identity_providers(self, query: dict[str, Any] | None = None) -> l @abstractmethod async def create_identity_provider( self, - payload: KeycloakIdentityProviderRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderRequestDTO, ) -> KeycloakCreateResultDTO: """Create an identity provider.""" raise NotImplementedError @@ -157,7 +157,7 @@ async def get_identity_provider(self, alias: str) -> KeycloakIdentityProviderDTO async def update_identity_provider( self, alias: str, - payload: KeycloakIdentityProviderRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an identity provider.""" raise NotImplementedError @@ -181,7 +181,7 @@ async def get_identity_provider_management_permissions(self, alias: str) -> Keyc async def update_identity_provider_management_permissions( self, alias: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of an identity provider.""" raise NotImplementedError @@ -200,7 +200,7 @@ async def get_identity_provider_mappers(self, alias: str) -> list[KeycloakIdenti async def create_identity_provider_mapper( self, alias: str, - payload: KeycloakIdentityProviderMapperRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderMapperRequestDTO, ) -> KeycloakCreateResultDTO: """Create a mapper of an identity provider.""" raise NotImplementedError @@ -215,7 +215,7 @@ async def update_identity_provider_mapper( self, alias: str, mapper_id: str, - payload: KeycloakIdentityProviderMapperRequestDTO | dict[str, Any], + payload: KeycloakIdentityProviderMapperRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a mapper of an identity provider.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/adapter.py index f74f7d973..84dcb10f1 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/adapter.py @@ -332,7 +332,7 @@ def update_organization_idp( self, organization_id: str, idp_alias: str, - link: KeycloakOrganizationIdentityProviderLinkRequestDTO | dict[str, Any], + link: KeycloakOrganizationIdentityProviderLinkRequestDTO, ) -> KeycloakUpdateResultDTO: """Update how an identity provider is linked to an organization. @@ -783,7 +783,7 @@ async def update_organization_idp( self, organization_id: str, idp_alias: str, - link: KeycloakOrganizationIdentityProviderLinkRequestDTO | dict[str, Any], + link: KeycloakOrganizationIdentityProviderLinkRequestDTO, ) -> KeycloakUpdateResultDTO: """Update how an identity provider is linked to an organization. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/group_adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/group_adapter.py index 7fd66385e..c06312797 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/group_adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/group_adapter.py @@ -70,7 +70,7 @@ def get_organization_groups( def create_organization_group( self, organization_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakCreateResultDTO: """Create a top-level group in an organization. @@ -145,7 +145,7 @@ def update_organization_group( self, organization_id: str, group_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an organization group. @@ -219,7 +219,7 @@ def create_organization_subgroup( self, organization_id: str, group_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakCreateResultDTO: """Create a child group under an organization group. @@ -477,7 +477,7 @@ def assign_organization_group_realm_roles( self, organization_id: str, group_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Assign realm roles to an organization group. @@ -504,7 +504,7 @@ def delete_organization_group_realm_roles( self, organization_id: str, group_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from an organization group. @@ -610,7 +610,7 @@ def assign_organization_group_client_roles( organization_id: str, group_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Assign client roles to an organization group. @@ -639,7 +639,7 @@ def delete_organization_group_client_roles( organization_id: str, group_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from an organization group. @@ -709,7 +709,7 @@ async def get_organization_groups( async def create_organization_group( self, organization_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakCreateResultDTO: """Create a top-level group in an organization. @@ -784,7 +784,7 @@ async def update_organization_group( self, organization_id: str, group_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an organization group. @@ -858,7 +858,7 @@ async def create_organization_subgroup( self, organization_id: str, group_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakCreateResultDTO: """Create a child group under an organization group. @@ -1120,7 +1120,7 @@ async def assign_organization_group_realm_roles( self, organization_id: str, group_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Assign realm roles to an organization group. @@ -1147,7 +1147,7 @@ async def delete_organization_group_realm_roles( self, organization_id: str, group_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from an organization group. @@ -1253,7 +1253,7 @@ async def assign_organization_group_client_roles( organization_id: str, group_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Assign client roles to an organization group. @@ -1282,7 +1282,7 @@ async def delete_organization_group_client_roles( organization_id: str, group_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from an organization group. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/group_port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/group_port.py index 948efa39e..a39858611 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/group_port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/group_port.py @@ -33,7 +33,7 @@ def get_organization_groups( def create_organization_group( self, organization_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakCreateResultDTO: """Create a top-level group in an organization.""" raise NotImplementedError @@ -53,7 +53,7 @@ def update_organization_group( self, organization_id: str, group_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an organization group.""" raise NotImplementedError @@ -78,7 +78,7 @@ def create_organization_subgroup( self, organization_id: str, group_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakCreateResultDTO: """Create a child group under an organization group.""" raise NotImplementedError @@ -166,7 +166,7 @@ def assign_organization_group_realm_roles( self, organization_id: str, group_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Assign realm roles to an organization group.""" raise NotImplementedError @@ -176,7 +176,7 @@ def delete_organization_group_realm_roles( self, organization_id: str, group_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from an organization group.""" raise NotImplementedError @@ -217,7 +217,7 @@ def assign_organization_group_client_roles( organization_id: str, group_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Assign client roles to an organization group.""" raise NotImplementedError @@ -228,7 +228,7 @@ def delete_organization_group_client_roles( organization_id: str, group_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from an organization group.""" raise NotImplementedError @@ -250,7 +250,7 @@ async def get_organization_groups( async def create_organization_group( self, organization_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakCreateResultDTO: """Create a top-level group in an organization.""" raise NotImplementedError @@ -270,7 +270,7 @@ async def update_organization_group( self, organization_id: str, group_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakUpdateResultDTO: """Update an organization group.""" raise NotImplementedError @@ -295,7 +295,7 @@ async def create_organization_subgroup( self, organization_id: str, group_id: str, - payload: KeycloakGroupRequestDTO | dict[str, Any], + payload: KeycloakGroupRequestDTO, ) -> KeycloakCreateResultDTO: """Create a child group under an organization group.""" raise NotImplementedError @@ -387,7 +387,7 @@ async def assign_organization_group_realm_roles( self, organization_id: str, group_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Assign realm roles to an organization group.""" raise NotImplementedError @@ -397,7 +397,7 @@ async def delete_organization_group_realm_roles( self, organization_id: str, group_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from an organization group.""" raise NotImplementedError @@ -438,7 +438,7 @@ async def assign_organization_group_client_roles( organization_id: str, group_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Assign client roles to an organization group.""" raise NotImplementedError @@ -449,7 +449,7 @@ async def delete_organization_group_client_roles( organization_id: str, group_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from an organization group.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/port.py index b64e8418e..0aeed4ed8 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/organizations/port.py @@ -120,7 +120,7 @@ def update_organization_idp( self, organization_id: str, idp_alias: str, - link: KeycloakOrganizationIdentityProviderLinkRequestDTO | dict[str, Any], + link: KeycloakOrganizationIdentityProviderLinkRequestDTO, ) -> KeycloakUpdateResultDTO: """Update how an identity provider is linked to an organization.""" raise NotImplementedError @@ -267,7 +267,7 @@ async def update_organization_idp( self, organization_id: str, idp_alias: str, - link: KeycloakOrganizationIdentityProviderLinkRequestDTO | dict[str, Any], + link: KeycloakOrganizationIdentityProviderLinkRequestDTO, ) -> KeycloakUpdateResultDTO: """Update how an identity provider is linked to an organization.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/protocol_mappers/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/protocol_mappers/adapter.py index 1a12a5211..2483eb284 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/protocol_mappers/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/protocol_mappers/adapter.py @@ -3,7 +3,6 @@ from __future__ import annotations from http import HTTPStatus -from typing import Any from archipy.adapters.keycloak._base import ( AsyncKeycloakMixinBase, @@ -46,7 +45,7 @@ def _find_client_mapper_id(self, client_id: str, name: str | None) -> str | None def add_mapper_to_client_scope( self, client_scope_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakCreateResultDTO: """Add a protocol mapper to a client scope.""" return with_created_id( @@ -77,7 +76,7 @@ def update_mapper_in_client_scope( self, client_scope_id: str, protocol_mapper_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a protocol mapper in a client scope.""" return to_mutation_result( @@ -112,7 +111,7 @@ def delete_mapper_from_client_scope( def add_mapper_to_client( self, client_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakCreateResultDTO: """Add a protocol mapper to a client.""" return with_created_id( @@ -143,7 +142,7 @@ def update_client_mapper( self, client_id: str, mapper_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a protocol mapper on a client.""" return to_mutation_result( @@ -191,7 +190,7 @@ def get_client_scope_protocol_mapper(self, client_scope_id: str, mapper_id: str) def add_client_scope_protocol_mappers( self, client_scope_id: str, - mappers: list[KeycloakProtocolMapperRequestDTO] | list[dict[str, Any]], + mappers: list[KeycloakProtocolMapperRequestDTO], ) -> KeycloakCreateResultDTO: """Add several protocol mappers to a client scope in one call. @@ -264,7 +263,7 @@ def get_client_protocol_mapper(self, client_uuid: str, mapper_id: str) -> Keyclo def add_client_protocol_mappers( self, client_uuid: str, - mappers: list[KeycloakProtocolMapperRequestDTO] | list[dict[str, Any]], + mappers: list[KeycloakProtocolMapperRequestDTO], ) -> KeycloakCreateResultDTO: """Add several protocol mappers to a client in one call. @@ -439,7 +438,7 @@ async def _find_client_mapper_id(self, client_id: str, name: str | None) -> str async def add_mapper_to_client_scope( self, client_scope_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakCreateResultDTO: """Add a protocol mapper to a client scope.""" return await with_created_id_async( @@ -470,7 +469,7 @@ async def update_mapper_in_client_scope( self, client_scope_id: str, protocol_mapper_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a protocol mapper in a client scope.""" return to_mutation_result( @@ -505,7 +504,7 @@ async def delete_mapper_from_client_scope( async def add_mapper_to_client( self, client_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakCreateResultDTO: """Add a protocol mapper to a client.""" return await with_created_id_async( @@ -536,7 +535,7 @@ async def update_client_mapper( self, client_id: str, mapper_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a protocol mapper on a client.""" return to_mutation_result( @@ -587,7 +586,7 @@ async def get_client_scope_protocol_mapper(self, client_scope_id: str, mapper_id async def add_client_scope_protocol_mappers( self, client_scope_id: str, - mappers: list[KeycloakProtocolMapperRequestDTO] | list[dict[str, Any]], + mappers: list[KeycloakProtocolMapperRequestDTO], ) -> KeycloakCreateResultDTO: """Add several protocol mappers to a client scope in one call. @@ -660,7 +659,7 @@ async def get_client_protocol_mapper(self, client_uuid: str, mapper_id: str) -> async def add_client_protocol_mappers( self, client_uuid: str, - mappers: list[KeycloakProtocolMapperRequestDTO] | list[dict[str, Any]], + mappers: list[KeycloakProtocolMapperRequestDTO], ) -> KeycloakCreateResultDTO: """Add several protocol mappers to a client in one call. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/protocol_mappers/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/protocol_mappers/port.py index 2c835559c..fe71accba 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/protocol_mappers/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/protocol_mappers/port.py @@ -3,7 +3,7 @@ from __future__ import annotations from abc import abstractmethod -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from archipy.models.dtos.keycloak.common_dtos import ( KeycloakCreateResultDTO, @@ -37,7 +37,7 @@ class KeycloakProtocolMappersPort: def add_mapper_to_client_scope( self, client_scope_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakCreateResultDTO: """Add a protocol mapper to a client scope.""" raise NotImplementedError @@ -52,7 +52,7 @@ def update_mapper_in_client_scope( self, client_scope_id: str, protocol_mapper_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a protocol mapper in a client scope.""" raise NotImplementedError @@ -70,7 +70,7 @@ def delete_mapper_from_client_scope( def add_mapper_to_client( self, client_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakCreateResultDTO: """Add a protocol mapper to a client.""" raise NotImplementedError @@ -85,7 +85,7 @@ def update_client_mapper( self, client_id: str, mapper_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a protocol mapper on a client.""" raise NotImplementedError @@ -104,7 +104,7 @@ def get_client_scope_protocol_mapper(self, client_scope_id: str, mapper_id: str) def add_client_scope_protocol_mappers( self, client_scope_id: str, - mappers: list[KeycloakProtocolMapperRequestDTO] | list[dict[str, Any]], + mappers: list[KeycloakProtocolMapperRequestDTO], ) -> KeycloakCreateResultDTO: """Add several protocol mappers to a client scope in one call.""" raise NotImplementedError @@ -127,7 +127,7 @@ def get_client_protocol_mapper(self, client_uuid: str, mapper_id: str) -> Keyclo def add_client_protocol_mappers( self, client_uuid: str, - mappers: list[KeycloakProtocolMapperRequestDTO] | list[dict[str, Any]], + mappers: list[KeycloakProtocolMapperRequestDTO], ) -> KeycloakCreateResultDTO: """Add several protocol mappers to a client in one call.""" raise NotImplementedError @@ -205,7 +205,7 @@ class AsyncKeycloakProtocolMappersPort: async def add_mapper_to_client_scope( self, client_scope_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakCreateResultDTO: """Add a protocol mapper to a client scope.""" raise NotImplementedError @@ -220,7 +220,7 @@ async def update_mapper_in_client_scope( self, client_scope_id: str, protocol_mapper_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a protocol mapper in a client scope.""" raise NotImplementedError @@ -238,7 +238,7 @@ async def delete_mapper_from_client_scope( async def add_mapper_to_client( self, client_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakCreateResultDTO: """Add a protocol mapper to a client.""" raise NotImplementedError @@ -253,7 +253,7 @@ async def update_client_mapper( self, client_id: str, mapper_id: str, - payload: KeycloakProtocolMapperRequestDTO | dict[str, Any], + payload: KeycloakProtocolMapperRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a protocol mapper on a client.""" raise NotImplementedError @@ -272,7 +272,7 @@ async def get_client_scope_protocol_mapper(self, client_scope_id: str, mapper_id async def add_client_scope_protocol_mappers( self, client_scope_id: str, - mappers: list[KeycloakProtocolMapperRequestDTO] | list[dict[str, Any]], + mappers: list[KeycloakProtocolMapperRequestDTO], ) -> KeycloakCreateResultDTO: """Add several protocol mappers to a client scope in one call.""" raise NotImplementedError @@ -295,7 +295,7 @@ async def get_client_protocol_mapper(self, client_uuid: str, mapper_id: str) -> async def add_client_protocol_mappers( self, client_uuid: str, - mappers: list[KeycloakProtocolMapperRequestDTO] | list[dict[str, Any]], + mappers: list[KeycloakProtocolMapperRequestDTO], ) -> KeycloakCreateResultDTO: """Add several protocol mappers to a client in one call.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/realms/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/realms/adapter.py index b67a18e36..8f6efed14 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/realms/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/realms/adapter.py @@ -306,7 +306,7 @@ def get_realm_events_config(self, realm_name: str) -> KeycloakRealmEventsConfigD def update_realm_events_config( self, realm_name: str, - config: KeycloakRealmEventsConfigRequestDTO | dict[str, Any], + config: KeycloakRealmEventsConfigRequestDTO, ) -> KeycloakUpdateResultDTO: """Update the event settings of a realm. @@ -358,7 +358,7 @@ def get_realm_client_policies( def update_realm_client_policies( self, realm_name: str, - policies: KeycloakClientPoliciesRequestDTO | dict[str, Any], + policies: KeycloakClientPoliciesRequestDTO, ) -> KeycloakUpdateResultDTO: """Replace the client policies of a realm. @@ -410,7 +410,7 @@ def get_realm_client_profiles( def update_realm_client_profiles( self, realm_name: str, - profiles: KeycloakClientProfilesRequestDTO | dict[str, Any], + profiles: KeycloakClientProfilesRequestDTO, ) -> KeycloakUpdateResultDTO: """Replace the client profiles of a realm. @@ -456,7 +456,7 @@ def get_realm_client_types(self, realm_name: str) -> KeycloakClientTypesDTO: def update_realm_client_types( self, realm_name: str, - client_types: KeycloakClientTypesRequestDTO | dict[str, Any], + client_types: KeycloakClientTypesRequestDTO, ) -> KeycloakUpdateResultDTO: """Replace the client types of a realm. @@ -762,7 +762,7 @@ def partial_export_realm( def partial_import_realm( self, realm_name: str, - payload: KeycloakPartialImportRequestDTO | dict[str, Any], + payload: KeycloakPartialImportRequestDTO, ) -> KeycloakPartialImportResultDTO: """Import users, clients, groups, roles and identity providers into a realm. @@ -858,7 +858,7 @@ def get_realm_users_management_permissions(self, realm_name: str) -> KeycloakMan def update_realm_users_management_permissions( self, realm_name: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of the realm's users. @@ -1139,7 +1139,7 @@ async def get_realm_events_config(self, realm_name: str) -> KeycloakRealmEventsC async def update_realm_events_config( self, realm_name: str, - config: KeycloakRealmEventsConfigRequestDTO | dict[str, Any], + config: KeycloakRealmEventsConfigRequestDTO, ) -> KeycloakUpdateResultDTO: """Update the event settings of a realm. @@ -1191,7 +1191,7 @@ async def get_realm_client_policies( async def update_realm_client_policies( self, realm_name: str, - policies: KeycloakClientPoliciesRequestDTO | dict[str, Any], + policies: KeycloakClientPoliciesRequestDTO, ) -> KeycloakUpdateResultDTO: """Replace the client policies of a realm. @@ -1243,7 +1243,7 @@ async def get_realm_client_profiles( async def update_realm_client_profiles( self, realm_name: str, - profiles: KeycloakClientProfilesRequestDTO | dict[str, Any], + profiles: KeycloakClientProfilesRequestDTO, ) -> KeycloakUpdateResultDTO: """Replace the client profiles of a realm. @@ -1289,7 +1289,7 @@ async def get_realm_client_types(self, realm_name: str) -> KeycloakClientTypesDT async def update_realm_client_types( self, realm_name: str, - client_types: KeycloakClientTypesRequestDTO | dict[str, Any], + client_types: KeycloakClientTypesRequestDTO, ) -> KeycloakUpdateResultDTO: """Replace the client types of a realm. @@ -1595,7 +1595,7 @@ async def partial_export_realm( async def partial_import_realm( self, realm_name: str, - payload: KeycloakPartialImportRequestDTO | dict[str, Any], + payload: KeycloakPartialImportRequestDTO, ) -> KeycloakPartialImportResultDTO: """Import users, clients, groups, roles and identity providers into a realm. @@ -1691,7 +1691,7 @@ async def get_realm_users_management_permissions(self, realm_name: str) -> Keycl async def update_realm_users_management_permissions( self, realm_name: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of the realm's users. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/realms/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/realms/port.py index 95c368eac..12202dab0 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/realms/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/realms/port.py @@ -116,7 +116,7 @@ def get_realm_events_config(self, realm_name: str) -> KeycloakRealmEventsConfigD def update_realm_events_config( self, realm_name: str, - config: KeycloakRealmEventsConfigRequestDTO | dict[str, Any], + config: KeycloakRealmEventsConfigRequestDTO, ) -> KeycloakUpdateResultDTO: """Update the event settings of a realm.""" raise NotImplementedError @@ -134,7 +134,7 @@ def get_realm_client_policies( def update_realm_client_policies( self, realm_name: str, - policies: KeycloakClientPoliciesRequestDTO | dict[str, Any], + policies: KeycloakClientPoliciesRequestDTO, ) -> KeycloakUpdateResultDTO: """Replace the client policies of a realm.""" raise NotImplementedError @@ -152,7 +152,7 @@ def get_realm_client_profiles( def update_realm_client_profiles( self, realm_name: str, - profiles: KeycloakClientProfilesRequestDTO | dict[str, Any], + profiles: KeycloakClientProfilesRequestDTO, ) -> KeycloakUpdateResultDTO: """Replace the client profiles of a realm.""" raise NotImplementedError @@ -166,7 +166,7 @@ def get_realm_client_types(self, realm_name: str) -> KeycloakClientTypesDTO: def update_realm_client_types( self, realm_name: str, - client_types: KeycloakClientTypesRequestDTO | dict[str, Any], + client_types: KeycloakClientTypesRequestDTO, ) -> KeycloakUpdateResultDTO: """Replace the client types of a realm.""" raise NotImplementedError @@ -255,7 +255,7 @@ def partial_export_realm( def partial_import_realm( self, realm_name: str, - payload: KeycloakPartialImportRequestDTO | dict[str, Any], + payload: KeycloakPartialImportRequestDTO, ) -> KeycloakPartialImportResultDTO: """Import users, clients, groups, roles and identity providers into a realm.""" raise NotImplementedError @@ -284,7 +284,7 @@ def get_realm_users_management_permissions(self, realm_name: str) -> KeycloakMan def update_realm_users_management_permissions( self, realm_name: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of the realm's users.""" raise NotImplementedError @@ -365,7 +365,7 @@ async def get_realm_events_config(self, realm_name: str) -> KeycloakRealmEventsC async def update_realm_events_config( self, realm_name: str, - config: KeycloakRealmEventsConfigRequestDTO | dict[str, Any], + config: KeycloakRealmEventsConfigRequestDTO, ) -> KeycloakUpdateResultDTO: """Update the event settings of a realm.""" raise NotImplementedError @@ -383,7 +383,7 @@ async def get_realm_client_policies( async def update_realm_client_policies( self, realm_name: str, - policies: KeycloakClientPoliciesRequestDTO | dict[str, Any], + policies: KeycloakClientPoliciesRequestDTO, ) -> KeycloakUpdateResultDTO: """Replace the client policies of a realm.""" raise NotImplementedError @@ -401,7 +401,7 @@ async def get_realm_client_profiles( async def update_realm_client_profiles( self, realm_name: str, - profiles: KeycloakClientProfilesRequestDTO | dict[str, Any], + profiles: KeycloakClientProfilesRequestDTO, ) -> KeycloakUpdateResultDTO: """Replace the client profiles of a realm.""" raise NotImplementedError @@ -415,7 +415,7 @@ async def get_realm_client_types(self, realm_name: str) -> KeycloakClientTypesDT async def update_realm_client_types( self, realm_name: str, - client_types: KeycloakClientTypesRequestDTO | dict[str, Any], + client_types: KeycloakClientTypesRequestDTO, ) -> KeycloakUpdateResultDTO: """Replace the client types of a realm.""" raise NotImplementedError @@ -504,7 +504,7 @@ async def partial_export_realm( async def partial_import_realm( self, realm_name: str, - payload: KeycloakPartialImportRequestDTO | dict[str, Any], + payload: KeycloakPartialImportRequestDTO, ) -> KeycloakPartialImportResultDTO: """Import users, clients, groups, roles and identity providers into a realm.""" raise NotImplementedError @@ -533,7 +533,7 @@ async def get_realm_users_management_permissions(self, realm_name: str) -> Keycl async def update_realm_users_management_permissions( self, realm_name: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of the realm's users.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/required_actions/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/required_actions/adapter.py index 37ac214d1..9ad9fbd7d 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/required_actions/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/required_actions/adapter.py @@ -3,7 +3,6 @@ from __future__ import annotations from http import HTTPStatus -from typing import Any from archipy.adapters.keycloak._base import ( AsyncKeycloakMixinBase, @@ -73,7 +72,7 @@ def get_required_action(self, alias: str) -> KeycloakRequiredActionProviderDTO: def update_required_action( self, alias: str, - payload: KeycloakRequiredActionProviderRequestDTO | dict[str, Any], + payload: KeycloakRequiredActionProviderRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a required action. @@ -218,7 +217,7 @@ def get_required_action_config(self, alias: str) -> KeycloakRequiredActionConfig def update_required_action_config( self, alias: str, - config: KeycloakRequiredActionConfigRequestDTO | dict[str, Any], + config: KeycloakRequiredActionConfigRequestDTO, ) -> KeycloakUpdateResultDTO: """Set the settings of a required action. @@ -323,7 +322,7 @@ async def get_required_action(self, alias: str) -> KeycloakRequiredActionProvide async def update_required_action( self, alias: str, - payload: KeycloakRequiredActionProviderRequestDTO | dict[str, Any], + payload: KeycloakRequiredActionProviderRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a required action. @@ -468,7 +467,7 @@ async def get_required_action_config(self, alias: str) -> KeycloakRequiredAction async def update_required_action_config( self, alias: str, - config: KeycloakRequiredActionConfigRequestDTO | dict[str, Any], + config: KeycloakRequiredActionConfigRequestDTO, ) -> KeycloakUpdateResultDTO: """Set the settings of a required action. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/required_actions/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/required_actions/port.py index bb0f8f089..795799495 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/required_actions/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/required_actions/port.py @@ -3,7 +3,7 @@ from __future__ import annotations from abc import abstractmethod -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING if TYPE_CHECKING: from archipy.models.dtos.keycloak.authenticator_dtos import KeycloakUnregisteredRequiredActionDTO @@ -38,7 +38,7 @@ def get_required_action(self, alias: str) -> KeycloakRequiredActionProviderDTO: def update_required_action( self, alias: str, - payload: KeycloakRequiredActionProviderRequestDTO | dict[str, Any], + payload: KeycloakRequiredActionProviderRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a required action.""" raise NotImplementedError @@ -77,7 +77,7 @@ def get_required_action_config(self, alias: str) -> KeycloakRequiredActionConfig def update_required_action_config( self, alias: str, - config: KeycloakRequiredActionConfigRequestDTO | dict[str, Any], + config: KeycloakRequiredActionConfigRequestDTO, ) -> KeycloakUpdateResultDTO: """Set the settings of a required action.""" raise NotImplementedError @@ -110,7 +110,7 @@ async def get_required_action(self, alias: str) -> KeycloakRequiredActionProvide async def update_required_action( self, alias: str, - payload: KeycloakRequiredActionProviderRequestDTO | dict[str, Any], + payload: KeycloakRequiredActionProviderRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a required action.""" raise NotImplementedError @@ -149,7 +149,7 @@ async def get_required_action_config(self, alias: str) -> KeycloakRequiredAction async def update_required_action_config( self, alias: str, - config: KeycloakRequiredActionConfigRequestDTO | dict[str, Any], + config: KeycloakRequiredActionConfigRequestDTO, ) -> KeycloakUpdateResultDTO: """Set the settings of a required action.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/role_mappings/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/role_mappings/adapter.py index b29aec676..d9af765ad 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/role_mappings/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/role_mappings/adapter.py @@ -3,7 +3,6 @@ from __future__ import annotations from http import HTTPStatus -from typing import Any from archipy.adapters.keycloak._base import ( AsyncKeycloakMixinBase, @@ -100,7 +99,7 @@ def get_user_realm_role_mappings_composite(self, user_id: str) -> list[KeycloakR def add_user_realm_role_mappings( self, user_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add realm roles to the role mappings of a user. @@ -125,7 +124,7 @@ def add_user_realm_role_mappings( def delete_user_realm_role_mappings( self, user_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from the role mappings of a user. @@ -211,7 +210,7 @@ def add_user_client_role_mappings( self, user_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add client roles to the role mappings of a user. @@ -238,7 +237,7 @@ def delete_user_client_role_mappings( self, user_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from the role mappings of a user. @@ -421,7 +420,7 @@ async def get_user_realm_role_mappings_composite(self, user_id: str) -> list[Key async def add_user_realm_role_mappings( self, user_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add realm roles to the role mappings of a user. @@ -446,7 +445,7 @@ async def add_user_realm_role_mappings( async def delete_user_realm_role_mappings( self, user_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from the role mappings of a user. @@ -532,7 +531,7 @@ async def add_user_client_role_mappings( self, user_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add client roles to the role mappings of a user. @@ -559,7 +558,7 @@ async def delete_user_client_role_mappings( self, user_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from the role mappings of a user. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/role_mappings/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/role_mappings/port.py index 90fdaab88..1a3b64c50 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/role_mappings/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/role_mappings/port.py @@ -3,7 +3,7 @@ from __future__ import annotations from abc import abstractmethod -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING if TYPE_CHECKING: from archipy.models.dtos.keycloak.common_dtos import KeycloakAssignResultDTO, KeycloakDeleteResultDTO @@ -37,7 +37,7 @@ def get_user_realm_role_mappings_composite(self, user_id: str) -> list[KeycloakR def add_user_realm_role_mappings( self, user_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add realm roles to the role mappings of a user.""" raise NotImplementedError @@ -46,7 +46,7 @@ def add_user_realm_role_mappings( def delete_user_realm_role_mappings( self, user_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from the role mappings of a user.""" raise NotImplementedError @@ -71,7 +71,7 @@ def add_user_client_role_mappings( self, user_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add client roles to the role mappings of a user.""" raise NotImplementedError @@ -81,7 +81,7 @@ def delete_user_client_role_mappings( self, user_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from the role mappings of a user.""" raise NotImplementedError @@ -134,7 +134,7 @@ async def get_user_realm_role_mappings_composite(self, user_id: str) -> list[Key async def add_user_realm_role_mappings( self, user_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add realm roles to the role mappings of a user.""" raise NotImplementedError @@ -143,7 +143,7 @@ async def add_user_realm_role_mappings( async def delete_user_realm_role_mappings( self, user_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from the role mappings of a user.""" raise NotImplementedError @@ -168,7 +168,7 @@ async def add_user_client_role_mappings( self, user_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add client roles to the role mappings of a user.""" raise NotImplementedError @@ -178,7 +178,7 @@ async def delete_user_client_role_mappings( self, user_id: str, client_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from the role mappings of a user.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/roles/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/roles/adapter.py index b901feeb7..35eaa7fa1 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/roles/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/roles/adapter.py @@ -540,7 +540,7 @@ def get_realm_roles_filtered(self, query: dict[str, Any] | None = None) -> list[ def update_realm_role( self, role_name: str, - payload: KeycloakRoleRequestDTO | dict[str, Any], + payload: KeycloakRoleRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a realm role. @@ -665,7 +665,7 @@ def get_realm_role_client_composites(self, role_name: str, target_client_uuid: s def add_realm_role_composites( self, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add child roles to a composite realm role. @@ -690,7 +690,7 @@ def add_realm_role_composites( def delete_realm_role_composites( self, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove child roles from a composite realm role. @@ -734,7 +734,7 @@ def get_realm_role_management_permissions(self, role_name: str) -> KeycloakManag def update_realm_role_management_permissions( self, role_name: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a realm role. @@ -781,7 +781,7 @@ def update_client_role( self, client_uuid: str, role_name: str, - payload: KeycloakRoleRequestDTO | dict[str, Any], + payload: KeycloakRoleRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a client role. @@ -968,7 +968,7 @@ def add_client_role_composites( self, client_uuid: str, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add child roles to a composite client role. @@ -995,7 +995,7 @@ def delete_client_role_composites( self, client_uuid: str, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove child roles from a composite client role. @@ -1046,7 +1046,7 @@ def update_client_role_management_permissions( self, client_uuid: str, role_name: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a client role. @@ -1569,7 +1569,7 @@ async def get_realm_roles_filtered(self, query: dict[str, Any] | None = None) -> async def update_realm_role( self, role_name: str, - payload: KeycloakRoleRequestDTO | dict[str, Any], + payload: KeycloakRoleRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a realm role. @@ -1702,7 +1702,7 @@ async def get_realm_role_client_composites(self, role_name: str, target_client_u async def add_realm_role_composites( self, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add child roles to a composite realm role. @@ -1727,7 +1727,7 @@ async def add_realm_role_composites( async def delete_realm_role_composites( self, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove child roles from a composite realm role. @@ -1771,7 +1771,7 @@ async def get_realm_role_management_permissions(self, role_name: str) -> Keycloa async def update_realm_role_management_permissions( self, role_name: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a realm role. @@ -1822,7 +1822,7 @@ async def update_client_role( self, client_uuid: str, role_name: str, - payload: KeycloakRoleRequestDTO | dict[str, Any], + payload: KeycloakRoleRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a client role. @@ -2009,7 +2009,7 @@ async def add_client_role_composites( self, client_uuid: str, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add child roles to a composite client role. @@ -2036,7 +2036,7 @@ async def delete_client_role_composites( self, client_uuid: str, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove child roles from a composite client role. @@ -2087,7 +2087,7 @@ async def update_client_role_management_permissions( self, client_uuid: str, role_name: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a client role. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/roles/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/roles/port.py index 4107db738..a21db06a0 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/roles/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/roles/port.py @@ -135,7 +135,7 @@ def get_realm_roles_filtered(self, query: dict[str, Any] | None = None) -> list[ def update_realm_role( self, role_name: str, - payload: KeycloakRoleRequestDTO | dict[str, Any], + payload: KeycloakRoleRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a realm role.""" raise NotImplementedError @@ -169,7 +169,7 @@ def get_realm_role_client_composites(self, role_name: str, target_client_uuid: s def add_realm_role_composites( self, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add child roles to a composite realm role.""" raise NotImplementedError @@ -178,7 +178,7 @@ def add_realm_role_composites( def delete_realm_role_composites( self, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove child roles from a composite realm role.""" raise NotImplementedError @@ -192,7 +192,7 @@ def get_realm_role_management_permissions(self, role_name: str) -> KeycloakManag def update_realm_role_management_permissions( self, role_name: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a realm role.""" raise NotImplementedError @@ -207,7 +207,7 @@ def update_client_role( self, client_uuid: str, role_name: str, - payload: KeycloakRoleRequestDTO | dict[str, Any], + payload: KeycloakRoleRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a client role.""" raise NotImplementedError @@ -267,7 +267,7 @@ def add_client_role_composites( self, client_uuid: str, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add child roles to a composite client role.""" raise NotImplementedError @@ -277,7 +277,7 @@ def delete_client_role_composites( self, client_uuid: str, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove child roles from a composite client role.""" raise NotImplementedError @@ -296,7 +296,7 @@ def update_client_role_management_permissions( self, client_uuid: str, role_name: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a client role.""" raise NotImplementedError @@ -415,7 +415,7 @@ async def get_realm_roles_filtered(self, query: dict[str, Any] | None = None) -> async def update_realm_role( self, role_name: str, - payload: KeycloakRoleRequestDTO | dict[str, Any], + payload: KeycloakRoleRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a realm role.""" raise NotImplementedError @@ -457,7 +457,7 @@ async def get_realm_role_client_composites(self, role_name: str, target_client_u async def add_realm_role_composites( self, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add child roles to a composite realm role.""" raise NotImplementedError @@ -466,7 +466,7 @@ async def add_realm_role_composites( async def delete_realm_role_composites( self, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove child roles from a composite realm role.""" raise NotImplementedError @@ -480,7 +480,7 @@ async def get_realm_role_management_permissions(self, role_name: str) -> Keycloa async def update_realm_role_management_permissions( self, role_name: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a realm role.""" raise NotImplementedError @@ -499,7 +499,7 @@ async def update_client_role( self, client_uuid: str, role_name: str, - payload: KeycloakRoleRequestDTO | dict[str, Any], + payload: KeycloakRoleRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a client role.""" raise NotImplementedError @@ -559,7 +559,7 @@ async def add_client_role_composites( self, client_uuid: str, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add child roles to a composite client role.""" raise NotImplementedError @@ -569,7 +569,7 @@ async def delete_client_role_composites( self, client_uuid: str, role_name: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove child roles from a composite client role.""" raise NotImplementedError @@ -588,7 +588,7 @@ async def update_client_role_management_permissions( self, client_uuid: str, role_name: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a client role.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/roles_by_id/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/roles_by_id/adapter.py index 225508f5f..3db6e128d 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/roles_by_id/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/roles_by_id/adapter.py @@ -52,7 +52,7 @@ def get_role_by_id(self, role_id: str) -> KeycloakRoleDTO: def update_role_by_id( self, role_id: str, - payload: KeycloakRoleRequestDTO | dict[str, Any], + payload: KeycloakRoleRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a role by its id. @@ -117,7 +117,7 @@ def get_role_composites_by_id(self, role_id: str, query: dict[str, Any] | None = def add_role_composites_by_id( self, role_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add child roles to a composite role. @@ -142,7 +142,7 @@ def add_role_composites_by_id( def delete_role_composites_by_id( self, role_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove child roles from a composite role. @@ -225,7 +225,7 @@ def get_role_management_permissions_by_id(self, role_id: str) -> KeycloakManagem def update_role_management_permissions_by_id( self, role_id: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a role. @@ -273,7 +273,7 @@ async def get_role_by_id(self, role_id: str) -> KeycloakRoleDTO: async def update_role_by_id( self, role_id: str, - payload: KeycloakRoleRequestDTO | dict[str, Any], + payload: KeycloakRoleRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a role by its id. @@ -342,7 +342,7 @@ async def get_role_composites_by_id( async def add_role_composites_by_id( self, role_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add child roles to a composite role. @@ -367,7 +367,7 @@ async def add_role_composites_by_id( async def delete_role_composites_by_id( self, role_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove child roles from a composite role. @@ -450,7 +450,7 @@ async def get_role_management_permissions_by_id(self, role_id: str) -> KeycloakM async def update_role_management_permissions_by_id( self, role_id: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a role. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/roles_by_id/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/roles_by_id/port.py index f66557d81..6cc0f3216 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/roles_by_id/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/roles_by_id/port.py @@ -30,7 +30,7 @@ def get_role_by_id(self, role_id: str) -> KeycloakRoleDTO: def update_role_by_id( self, role_id: str, - payload: KeycloakRoleRequestDTO | dict[str, Any], + payload: KeycloakRoleRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a role by its id.""" raise NotImplementedError @@ -49,7 +49,7 @@ def get_role_composites_by_id(self, role_id: str, query: dict[str, Any] | None = def add_role_composites_by_id( self, role_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add child roles to a composite role.""" raise NotImplementedError @@ -58,7 +58,7 @@ def add_role_composites_by_id( def delete_role_composites_by_id( self, role_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove child roles from a composite role.""" raise NotImplementedError @@ -82,7 +82,7 @@ def get_role_management_permissions_by_id(self, role_id: str) -> KeycloakManagem def update_role_management_permissions_by_id( self, role_id: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a role.""" raise NotImplementedError @@ -100,7 +100,7 @@ async def get_role_by_id(self, role_id: str) -> KeycloakRoleDTO: async def update_role_by_id( self, role_id: str, - payload: KeycloakRoleRequestDTO | dict[str, Any], + payload: KeycloakRoleRequestDTO, ) -> KeycloakUpdateResultDTO: """Update a role by its id.""" raise NotImplementedError @@ -123,7 +123,7 @@ async def get_role_composites_by_id( async def add_role_composites_by_id( self, role_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add child roles to a composite role.""" raise NotImplementedError @@ -132,7 +132,7 @@ async def add_role_composites_by_id( async def delete_role_composites_by_id( self, role_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove child roles from a composite role.""" raise NotImplementedError @@ -156,7 +156,7 @@ async def get_role_management_permissions_by_id(self, role_id: str) -> KeycloakM async def update_role_management_permissions_by_id( self, role_id: str, - payload: KeycloakManagementPermissionRequestDTO | dict[str, Any], + payload: KeycloakManagementPermissionRequestDTO, ) -> KeycloakManagementPermissionDTO: """Enable or disable the fine-grained permissions of a role.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/scope_mappings/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/scope_mappings/adapter.py index 1dd6df129..37e89aee3 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/scope_mappings/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/scope_mappings/adapter.py @@ -3,7 +3,6 @@ from __future__ import annotations from http import HTTPStatus -from typing import Any from archipy.adapters.keycloak._base import ( AsyncKeycloakMixinBase, @@ -100,7 +99,7 @@ def get_client_scope_realm_scope_mappings_composite(self, client_scope_id: str) def add_client_scope_realm_scope_mappings( self, client_scope_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add realm roles to the scope mappings of a client scope. @@ -125,7 +124,7 @@ def add_client_scope_realm_scope_mappings( def delete_client_scope_realm_scope_mappings( self, client_scope_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from the scope mappings of a client scope. @@ -219,7 +218,7 @@ def add_client_scope_client_scope_mappings( self, client_scope_id: str, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add client roles to the scope mappings of a client scope. @@ -246,7 +245,7 @@ def delete_client_scope_client_scope_mappings( self, client_scope_id: str, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from the scope mappings of a client scope. @@ -348,7 +347,7 @@ def get_client_realm_scope_mappings_composite(self, client_uuid: str) -> list[Ke def add_client_realm_scope_mappings( self, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add realm roles to the scope mappings of a client. @@ -373,7 +372,7 @@ def add_client_realm_scope_mappings( def delete_client_realm_scope_mappings( self, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from the scope mappings of a client. @@ -467,7 +466,7 @@ def add_client_client_scope_mappings( self, client_uuid: str, owner_client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add client roles to the scope mappings of a client. @@ -494,7 +493,7 @@ def delete_client_client_scope_mappings( self, client_uuid: str, owner_client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from the scope mappings of a client. @@ -600,7 +599,7 @@ async def get_client_scope_realm_scope_mappings_composite(self, client_scope_id: async def add_client_scope_realm_scope_mappings( self, client_scope_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add realm roles to the scope mappings of a client scope. @@ -625,7 +624,7 @@ async def add_client_scope_realm_scope_mappings( async def delete_client_scope_realm_scope_mappings( self, client_scope_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from the scope mappings of a client scope. @@ -723,7 +722,7 @@ async def add_client_scope_client_scope_mappings( self, client_scope_id: str, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add client roles to the scope mappings of a client scope. @@ -750,7 +749,7 @@ async def delete_client_scope_client_scope_mappings( self, client_scope_id: str, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from the scope mappings of a client scope. @@ -852,7 +851,7 @@ async def get_client_realm_scope_mappings_composite(self, client_uuid: str) -> l async def add_client_realm_scope_mappings( self, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add realm roles to the scope mappings of a client. @@ -877,7 +876,7 @@ async def add_client_realm_scope_mappings( async def delete_client_realm_scope_mappings( self, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from the scope mappings of a client. @@ -971,7 +970,7 @@ async def add_client_client_scope_mappings( self, client_uuid: str, owner_client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add client roles to the scope mappings of a client. @@ -998,7 +997,7 @@ async def delete_client_client_scope_mappings( self, client_uuid: str, owner_client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from the scope mappings of a client. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/scope_mappings/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/scope_mappings/port.py index 8c84657de..70a022d65 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/scope_mappings/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/scope_mappings/port.py @@ -3,7 +3,7 @@ from __future__ import annotations from abc import abstractmethod -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING if TYPE_CHECKING: from archipy.models.dtos.keycloak.common_dtos import KeycloakAssignResultDTO, KeycloakDeleteResultDTO @@ -37,7 +37,7 @@ def get_client_scope_realm_scope_mappings_composite(self, client_scope_id: str) def add_client_scope_realm_scope_mappings( self, client_scope_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add realm roles to the scope mappings of a client scope.""" raise NotImplementedError @@ -46,7 +46,7 @@ def add_client_scope_realm_scope_mappings( def delete_client_scope_realm_scope_mappings( self, client_scope_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from the scope mappings of a client scope.""" raise NotImplementedError @@ -79,7 +79,7 @@ def add_client_scope_client_scope_mappings( self, client_scope_id: str, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add client roles to the scope mappings of a client scope.""" raise NotImplementedError @@ -89,7 +89,7 @@ def delete_client_scope_client_scope_mappings( self, client_scope_id: str, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from the scope mappings of a client scope.""" raise NotImplementedError @@ -118,7 +118,7 @@ def get_client_realm_scope_mappings_composite(self, client_uuid: str) -> list[Ke def add_client_realm_scope_mappings( self, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add realm roles to the scope mappings of a client.""" raise NotImplementedError @@ -127,7 +127,7 @@ def add_client_realm_scope_mappings( def delete_client_realm_scope_mappings( self, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from the scope mappings of a client.""" raise NotImplementedError @@ -160,7 +160,7 @@ def add_client_client_scope_mappings( self, client_uuid: str, owner_client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add client roles to the scope mappings of a client.""" raise NotImplementedError @@ -170,7 +170,7 @@ def delete_client_client_scope_mappings( self, client_uuid: str, owner_client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from the scope mappings of a client.""" raise NotImplementedError @@ -203,7 +203,7 @@ async def get_client_scope_realm_scope_mappings_composite(self, client_scope_id: async def add_client_scope_realm_scope_mappings( self, client_scope_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add realm roles to the scope mappings of a client scope.""" raise NotImplementedError @@ -212,7 +212,7 @@ async def add_client_scope_realm_scope_mappings( async def delete_client_scope_realm_scope_mappings( self, client_scope_id: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from the scope mappings of a client scope.""" raise NotImplementedError @@ -249,7 +249,7 @@ async def add_client_scope_client_scope_mappings( self, client_scope_id: str, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add client roles to the scope mappings of a client scope.""" raise NotImplementedError @@ -259,7 +259,7 @@ async def delete_client_scope_client_scope_mappings( self, client_scope_id: str, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from the scope mappings of a client scope.""" raise NotImplementedError @@ -288,7 +288,7 @@ async def get_client_realm_scope_mappings_composite(self, client_uuid: str) -> l async def add_client_realm_scope_mappings( self, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add realm roles to the scope mappings of a client.""" raise NotImplementedError @@ -297,7 +297,7 @@ async def add_client_realm_scope_mappings( async def delete_client_realm_scope_mappings( self, client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove realm roles from the scope mappings of a client.""" raise NotImplementedError @@ -330,7 +330,7 @@ async def add_client_client_scope_mappings( self, client_uuid: str, owner_client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakAssignResultDTO: """Add client roles to the scope mappings of a client.""" raise NotImplementedError @@ -340,7 +340,7 @@ async def delete_client_client_scope_mappings( self, client_uuid: str, owner_client_uuid: str, - roles: list[KeycloakRoleDTO] | list[dict[str, Any]], + roles: list[KeycloakRoleDTO], ) -> KeycloakDeleteResultDTO: """Remove client roles from the scope mappings of a client.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/users/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_resources/users/adapter.py index 0858d06d0..a36ee8a03 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/users/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/users/adapter.py @@ -117,7 +117,7 @@ def get_user_by_email(self, email: str) -> KeycloakUserDTO | None: except KeycloakError as e: self._handle_keycloak_exception(e, "get_user_by_email") - def create_user(self, user_data: KeycloakUserRequestDTO | dict[str, Any]) -> str | None: + def create_user(self, user_data: KeycloakUserRequestDTO) -> str | None: """Create a new user in Keycloak. Args: @@ -141,7 +141,7 @@ def create_user(self, user_data: KeycloakUserRequestDTO | dict[str, Any]) -> str else: return user_id - def update_user(self, user_id: str, user_data: KeycloakUserRequestDTO | dict[str, Any]) -> None: + def update_user(self, user_id: str, user_data: KeycloakUserRequestDTO) -> None: """Update user details. Args: @@ -318,7 +318,7 @@ def get_user_profile_config(self) -> KeycloakUserProfileConfigDTO: def update_user_profile_config( self, - config: KeycloakUserProfileConfigRequestDTO | dict[str, Any], + config: KeycloakUserProfileConfigRequestDTO, ) -> KeycloakUserProfileConfigDTO: """Replace the realm's user profile configuration. @@ -584,7 +584,7 @@ def add_user_federated_identity( self, user_id: str, provider: str, - payload: KeycloakFederatedIdentityRequestDTO | dict[str, Any], + payload: KeycloakFederatedIdentityRequestDTO, ) -> KeycloakAssignResultDTO: """Link a user to an identity provider account. @@ -842,7 +842,7 @@ async def get_user_by_email(self, email: str) -> KeycloakUserDTO | None: except KeycloakError as e: self._handle_keycloak_exception(e, "get_user_by_email") - async def create_user(self, user_data: KeycloakUserRequestDTO | dict[str, Any]) -> str | None: + async def create_user(self, user_data: KeycloakUserRequestDTO) -> str | None: """Create a new user in Keycloak. Args: @@ -865,7 +865,7 @@ async def create_user(self, user_data: KeycloakUserRequestDTO | dict[str, Any]) else: return user_id - async def update_user(self, user_id: str, user_data: KeycloakUserRequestDTO | dict[str, Any]) -> None: + async def update_user(self, user_id: str, user_data: KeycloakUserRequestDTO) -> None: """Update user details. Args: @@ -1043,7 +1043,7 @@ async def get_user_profile_config(self) -> KeycloakUserProfileConfigDTO: async def update_user_profile_config( self, - config: KeycloakUserProfileConfigRequestDTO | dict[str, Any], + config: KeycloakUserProfileConfigRequestDTO, ) -> KeycloakUserProfileConfigDTO: """Replace the realm's user profile configuration. @@ -1309,7 +1309,7 @@ async def add_user_federated_identity( self, user_id: str, provider: str, - payload: KeycloakFederatedIdentityRequestDTO | dict[str, Any], + payload: KeycloakFederatedIdentityRequestDTO, ) -> KeycloakAssignResultDTO: """Link a user to an identity provider account. diff --git a/packages/keycloak/archipy/adapters/keycloak/_resources/users/port.py b/packages/keycloak/archipy/adapters/keycloak/_resources/users/port.py index 6523eb126..b6e19648f 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_resources/users/port.py +++ b/packages/keycloak/archipy/adapters/keycloak/_resources/users/port.py @@ -54,12 +54,12 @@ def get_user_by_email(self, email: str) -> KeycloakUserDTO | None: raise NotImplementedError @abstractmethod - def create_user(self, user_data: KeycloakUserRequestDTO | dict[str, Any]) -> str | None: + def create_user(self, user_data: KeycloakUserRequestDTO) -> str | None: """Create a new user in Keycloak.""" raise NotImplementedError @abstractmethod - def update_user(self, user_id: str, user_data: KeycloakUserRequestDTO | dict[str, Any]) -> None: + def update_user(self, user_id: str, user_data: KeycloakUserRequestDTO) -> None: """Update user details.""" raise NotImplementedError @@ -101,7 +101,7 @@ def get_user_profile_config(self) -> KeycloakUserProfileConfigDTO: @abstractmethod def update_user_profile_config( self, - config: KeycloakUserProfileConfigRequestDTO | dict[str, Any], + config: KeycloakUserProfileConfigRequestDTO, ) -> KeycloakUserProfileConfigDTO: """Replace the realm's user profile configuration.""" raise NotImplementedError @@ -176,7 +176,7 @@ def add_user_federated_identity( self, user_id: str, provider: str, - payload: KeycloakFederatedIdentityRequestDTO | dict[str, Any], + payload: KeycloakFederatedIdentityRequestDTO, ) -> KeycloakAssignResultDTO: """Link a user to an identity provider account.""" raise NotImplementedError @@ -250,12 +250,12 @@ async def get_user_by_email(self, email: str) -> KeycloakUserDTO | None: raise NotImplementedError @abstractmethod - async def create_user(self, user_data: KeycloakUserRequestDTO | dict[str, Any]) -> str | None: + async def create_user(self, user_data: KeycloakUserRequestDTO) -> str | None: """Create a new user in Keycloak.""" raise NotImplementedError @abstractmethod - async def update_user(self, user_id: str, user_data: KeycloakUserRequestDTO | dict[str, Any]) -> None: + async def update_user(self, user_id: str, user_data: KeycloakUserRequestDTO) -> None: """Update user details.""" raise NotImplementedError @@ -297,7 +297,7 @@ async def get_user_profile_config(self) -> KeycloakUserProfileConfigDTO: @abstractmethod async def update_user_profile_config( self, - config: KeycloakUserProfileConfigRequestDTO | dict[str, Any], + config: KeycloakUserProfileConfigRequestDTO, ) -> KeycloakUserProfileConfigDTO: """Replace the realm's user profile configuration.""" raise NotImplementedError @@ -372,7 +372,7 @@ async def add_user_federated_identity( self, user_id: str, provider: str, - payload: KeycloakFederatedIdentityRequestDTO | dict[str, Any], + payload: KeycloakFederatedIdentityRequestDTO, ) -> KeycloakAssignResultDTO: """Link a user to an identity provider account.""" raise NotImplementedError diff --git a/packages/keycloak/archipy/adapters/keycloak/_type_aliases.py b/packages/keycloak/archipy/adapters/keycloak/_type_aliases.py index dad2a0c15..0afbe21c2 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_type_aliases.py +++ b/packages/keycloak/archipy/adapters/keycloak/_type_aliases.py @@ -4,26 +4,12 @@ from typing import Any -from archipy.models.dtos.keycloak.client_scope_dtos import KeycloakClientScopeDTO -from archipy.models.dtos.keycloak.component_dtos import KeycloakComponentDTO -from archipy.models.dtos.keycloak.group_dtos import KeycloakGroupDTO -from archipy.models.dtos.keycloak.organization_dtos import KeycloakOrganizationDTO -from archipy.models.dtos.keycloak.protocol_mapper_dtos import KeycloakProtocolMapperDTO -from archipy.models.dtos.keycloak.role_dtos import KeycloakRoleDTO - # Define type aliases for better type hinting KeycloakResponseType = dict[str, Any] KeycloakTokenType = dict[str, Any] KeycloakUserType = dict[str, Any] -# Deprecated aliases of the pydantic DTOs that replaced the TypedDicts; removed in 6.0.0. -KeycloakRoleType = KeycloakRoleDTO -KeycloakGroupType = KeycloakGroupDTO -KeycloakOrganizationType = KeycloakOrganizationDTO -KeycloakClientScopeType = KeycloakClientScopeDTO -KeycloakProtocolMapperType = KeycloakProtocolMapperDTO -KeycloakComponentType = KeycloakComponentDTO # Define a type for the public key return type # Using Any for JWK.JWK object, since we don't want to depend on jwcrypto types diff --git a/packages/keycloak/archipy/adapters/keycloak/auth.py b/packages/keycloak/archipy/adapters/keycloak/auth.py index cdb4f92fa..9fb18154f 100644 --- a/packages/keycloak/archipy/adapters/keycloak/auth.py +++ b/packages/keycloak/archipy/adapters/keycloak/auth.py @@ -20,14 +20,13 @@ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from archipy.adapters.keycloak.adapters import AsyncKeycloakAdapter, KeycloakAdapter -from archipy.adapters.keycloak.deprecated_state import deprecated_dict, deprecated_list, deprecated_set +from archipy.models.dtos.keycloak.auth_dtos import ActorDTO, AuthenticatedUserDTO from archipy.models.dtos.keycloak.owner_dto import OwnerDTO from archipy.models.dtos.keycloak.token_dtos import ( KeycloakOrganizationClaimDTO, KeycloakTokenClaimsDTO, KeycloakUserInfoDTO, ) -from archipy.models.dtos.keycloak_dtos import ActorDTO, AuthenticatedUserDTO from archipy.models.errors import ( BaseError, ConfigurationError, @@ -735,18 +734,13 @@ def fastapi_auth( ) -> Callable[..., Any]: """FastAPI dependency for Keycloak authentication and resource-based authorization. - The dependency is always asynchronous: FastAPI awaits it on the event loop, whether the endpoint is a ``def`` - or an ``async def`` function. It returns the UserInfo dict and sets :class:`AuthContextManager` for the request, - like :func:`grpc_auth` does, so code below the endpoint reads the caller with - ``AuthContextManager.get_auth_context()``; the context is cleared when the request ends. + FastAPI awaits the dependency for both synchronous and asynchronous endpoints. It yields a + ``KeycloakUserInfoDTO`` and sets :class:`AuthContextManager` for the duration of the request. + Code below the endpoint can read the caller with ``AuthContextManager.get_auth_context()``. Organization details are available as ``auth_context.organizations`` and ``auth_context.selected_organization``. A selected organization is optional unless required by the guard or Keycloak configuration. - ``request.state.user_info``, ``token_info``, ``actor_chain`` and ``user_roles`` are still filled, but they are - deprecated: each is a dict, list or set that emits a ``DeprecationWarning`` when read and names the matching - attribute of the auth context (``raw_user_info``, ``token_info``, ``actor_chain``, ``roles``). - Args: resource_type_param: The parameter name in the path (e.g., 'user_uuid', 'employee_uuid') resource_type: The type of resource being accessed (e.g., 'users', 'employees') @@ -755,7 +749,8 @@ def fastapi_auth( required_permissions: List of (resource, scope) tuples to check admin_roles: Set of roles that grant administrative access to all resources lang: Language for error messages - require_organization: Require a selected organization. None uses KeycloakConfig.REQUIRE_ORGANIZATION (False). + require_organization: Require a selected organization. Defaults to the configured + ``KEYCLOAK.TOKEN_VALIDATION.REQUIRE_ORGANIZATION`` value. Raises: UnauthenticatedError: If no valid Authorization header is provided @@ -806,16 +801,6 @@ async def dependency( else require_organization ) - # Still filled for existing code, but each read warns: AuthContextManager carries the same data. - context_access = "AuthContextManager.get_auth_context()" - request.state.user_info = deprecated_dict(user_info.to_dict(), "user_info", f"{context_access}.raw_user_info") - request.state.token_info = deprecated_dict(token_info.to_dict(), "token_info", f"{context_access}.token_info") - request.state.actor_chain = deprecated_list( - _parse_actor_chain(token_info), - "actor_chain", - f"{context_access}.actor_chain", - ) - request.state.user_roles = deprecated_set(user_roles, "user_roles", f"{context_access}.roles") # UserInfo without ``sub`` cannot name a caller; keep serving it, as before, without an auth context. auth_token = ( AuthContextManager.set_auth_context( @@ -922,7 +907,8 @@ def grpc_auth( resource_attribute_name: Attribute name to extract resource UUID from context for ownership checking admin_roles: Set of admin roles that bypass resource ownership checks lang: Language for error messages - require_organization: Require a selected organization. None uses KeycloakConfig.REQUIRE_ORGANIZATION (False). + require_organization: Require a selected organization. Defaults to the configured + ``KEYCLOAK.TOKEN_VALIDATION.REQUIRE_ORGANIZATION`` value. Returns: Decorated function with authentication and authorization diff --git a/packages/keycloak/archipy/adapters/keycloak/deprecated_state.py b/packages/keycloak/archipy/adapters/keycloak/deprecated_state.py deleted file mode 100644 index 72d7f5f91..000000000 --- a/packages/keycloak/archipy/adapters/keycloak/deprecated_state.py +++ /dev/null @@ -1,93 +0,0 @@ -"""Values that warn when read, for the auth data ``fastapi_auth`` still puts on ``request.state``. - -``request.state`` gives no hook on attribute reads, and Starlette stays untouched, so the stored value warns instead: -each common read method of the dict, list or set emits a ``DeprecationWarning`` that names the replacement. The value -is a real ``dict``, ``list`` or ``set`` subclass with the same content, so existing code keeps working. - -This module goes away in 6.0.0, when ``fastapi_auth`` stops filling ``request.state``. -""" - -from __future__ import annotations - -import functools -from typing import TYPE_CHECKING - -from archipy.helpers._deprecation import warn_deprecated_name - -if TYPE_CHECKING: - from collections.abc import Callable - -_DICT_READS = ("__getitem__", "__iter__", "__contains__", "__len__", "get", "keys", "values", "items", "copy") -_LIST_READS = ("__getitem__", "__iter__", "__len__", "__contains__", "index", "count", "copy") -_SET_READS = ( - "__iter__", - "__contains__", - "__len__", - "copy", - "isdisjoint", - "issubset", - "issuperset", - "union", - "intersection", - "difference", -) - - -def _guard(base: type, name: str) -> Callable[..., object]: - """Wrap the ``name`` method of ``base`` so it warns before it reads.""" - original = getattr(base, name) - - @functools.wraps(original) - def method(self: _Warning, *args: object, **kwargs: object) -> object: - warn_deprecated_name(f"request.state.{self.field}", self.replacement) - return original(self, *args, **kwargs) - - return method - - -class _Warning: - """Mixin that remembers which ``request.state`` field a value stands for and what replaces it.""" - - field: str - replacement: str - - -class _WarningDict(_Warning, dict): - """A dict that warns on reads.""" - - -class _WarningList(_Warning, list): - """A list that warns on reads.""" - - -class _WarningSet(_Warning, set): - """A set that warns on reads.""" - - -for _name in _DICT_READS: - setattr(_WarningDict, _name, _guard(dict, _name)) -for _name in _LIST_READS: - setattr(_WarningList, _name, _guard(list, _name)) -for _name in _SET_READS: - setattr(_WarningSet, _name, _guard(set, _name)) - - -def deprecated_dict[K, V](value: dict[K, V], field: str, replacement: str) -> dict[K, V]: - """Return a copy of ``value`` that warns on reads.""" - result = _WarningDict(value) - result.field, result.replacement = field, replacement - return result - - -def deprecated_list[T](value: list[T], field: str, replacement: str) -> list[T]: - """Return a copy of ``value`` that warns on reads.""" - result = _WarningList(value) - result.field, result.replacement = field, replacement - return result - - -def deprecated_set[T](value: set[T], field: str, replacement: str) -> set[T]: - """Return a copy of ``value`` that warns on reads.""" - result = _WarningSet(value) - result.field, result.replacement = field, replacement - return result diff --git a/packages/keycloak/archipy/adapters/keycloak/ports.py b/packages/keycloak/archipy/adapters/keycloak/ports.py index e7a36c435..ab4c8552b 100644 --- a/packages/keycloak/archipy/adapters/keycloak/ports.py +++ b/packages/keycloak/archipy/adapters/keycloak/ports.py @@ -37,26 +37,20 @@ KeycloakClientInitialAccessPort, KeycloakClientRegistrationPolicyPort, KeycloakClientScopesPort, - KeycloakClientScopeType, KeycloakClientsPort, KeycloakComponentsPort, - KeycloakComponentType, KeycloakGroupsPort, - KeycloakGroupType, KeycloakIdentityProvidersPort, KeycloakKeysPort, KeycloakOrganizationGroupsPort, KeycloakOrganizationsPort, - KeycloakOrganizationType, KeycloakProtocolMappersPort, - KeycloakProtocolMapperType, KeycloakRealmsPort, KeycloakRequiredActionsPort, KeycloakResponseType, KeycloakRoleMappingsPort, KeycloakRolesByIdPort, KeycloakRolesPort, - KeycloakRoleType, KeycloakScopeMappingsPort, KeycloakTokenType, KeycloakUmaPort, @@ -67,14 +61,8 @@ __all__ = [ "AsyncKeycloakPort", - "KeycloakClientScopeType", - "KeycloakComponentType", - "KeycloakGroupType", - "KeycloakOrganizationType", "KeycloakPort", - "KeycloakProtocolMapperType", "KeycloakResponseType", - "KeycloakRoleType", "KeycloakTokenType", "KeycloakUserType", "PublicKeyType", diff --git a/packages/redis/archipy/adapters/redis/search.py b/packages/redis/archipy/adapters/redis/search.py index 2f1df80ef..1c84352e5 100644 --- a/packages/redis/archipy/adapters/redis/search.py +++ b/packages/redis/archipy/adapters/redis/search.py @@ -3,7 +3,6 @@ from __future__ import annotations import struct -import warnings from collections.abc import Awaitable from typing import TYPE_CHECKING, Any, cast, override @@ -606,28 +605,22 @@ def upsert_hash( fields: dict[str, str | int | float], vector_field: str | None = None, vector: list[float] | None = None, - *, - replace: bool = True, ) -> bool: """Upsert a HASH document and index it. - The write is a single atomic ``HSET``. ``replace`` is ignored (fields are merged into the hash) and - ``replace=False`` is deprecated. + The write merges fields into the hash in a single atomic ``HSET``. """ - if not replace: - warnings.warn("upsert_hash(replace=False) is ignored and deprecated", DeprecationWarning, stacklevel=2) _write_hash_document(self._client, doc_id, fields, vector_field, vector) return True @override - def upsert_hash_dto(self, document: HashDocumentUpsertDTO, *, replace: bool = True) -> bool: + def upsert_hash_dto(self, document: HashDocumentUpsertDTO) -> bool: """Upsert a HASH document from a DTO.""" return self.upsert_hash( document.doc_id, document.fields, vector_field=document.vector_field, vector=document.vector, - replace=replace, ) @override @@ -805,16 +798,11 @@ async def upsert_hash( fields: dict[str, str | int | float], vector_field: str | None = None, vector: list[float] | None = None, - *, - replace: bool = True, ) -> bool: """Upsert a HASH document and index it asynchronously. - The write is a single atomic ``HSET``. ``replace`` is ignored (fields are merged into the hash) and - ``replace=False`` is deprecated. + The write merges fields into the hash in a single atomic ``HSET``. """ - if not replace: - warnings.warn("upsert_hash(replace=False) is ignored and deprecated", DeprecationWarning, stacklevel=2) mapping: dict[str, Any] = dict(fields) if vector_field is not None and vector is not None: mapping[vector_field] = pack_vector(vector) @@ -823,14 +811,13 @@ async def upsert_hash( return True @override - async def upsert_hash_dto(self, document: HashDocumentUpsertDTO, *, replace: bool = True) -> bool: + async def upsert_hash_dto(self, document: HashDocumentUpsertDTO) -> bool: """Upsert a HASH document from a DTO asynchronously.""" return await self.upsert_hash( document.doc_id, document.fields, vector_field=document.vector_field, vector=document.vector, - replace=replace, ) @override diff --git a/packages/redis/archipy/adapters/redis/search_ports.py b/packages/redis/archipy/adapters/redis/search_ports.py index 7d3447ac0..ad78741f4 100644 --- a/packages/redis/archipy/adapters/redis/search_ports.py +++ b/packages/redis/archipy/adapters/redis/search_ports.py @@ -61,14 +61,12 @@ def upsert_hash( fields: dict[str, str | int | float], vector_field: str | None = None, vector: list[float] | None = None, - *, - replace: bool = True, ) -> bool: """Upsert a HASH document and index it.""" raise NotImplementedError @abstractmethod - def upsert_hash_dto(self, document: HashDocumentUpsertDTO, *, replace: bool = True) -> bool: + def upsert_hash_dto(self, document: HashDocumentUpsertDTO) -> bool: """Upsert a HASH document from a DTO.""" raise NotImplementedError @@ -164,14 +162,12 @@ async def upsert_hash( fields: dict[str, str | int | float], vector_field: str | None = None, vector: list[float] | None = None, - *, - replace: bool = True, ) -> bool: """Upsert a HASH document and index it asynchronously.""" raise NotImplementedError @abstractmethod - async def upsert_hash_dto(self, document: HashDocumentUpsertDTO, *, replace: bool = True) -> bool: + async def upsert_hash_dto(self, document: HashDocumentUpsertDTO) -> bool: """Upsert a HASH document from a DTO asynchronously.""" raise NotImplementedError diff --git a/packages/scylladb/archipy/adapters/scylladb/adapters.py b/packages/scylladb/archipy/adapters/scylladb/adapters.py index 94dbef69d..a6ca72c35 100644 --- a/packages/scylladb/archipy/adapters/scylladb/adapters.py +++ b/packages/scylladb/archipy/adapters/scylladb/adapters.py @@ -8,7 +8,6 @@ import logging import re import time -import warnings from typing import Any, Final, Literal, NoReturn, TypedDict, override from async_lru import alru_cache @@ -82,34 +81,6 @@ _POOL_STATS_FAILED: Final = "unavailable" -_POOL_SETTING_DEFAULTS: Final = { - "MAX_CONNECTIONS_PER_HOST": 2, - "MIN_CONNECTIONS_PER_HOST": 1, - "CORE_CONNECTIONS_PER_HOST": 1, - "MAX_REQUESTS_PER_CONNECTION": 100, -} - - -def _warn_ignored_pool_settings(config: ScyllaDBConfig) -> None: - """Warn about connection pool settings that scylla-driver does not apply. - - scylla-driver (protocol v3+) keeps one connection per host (per shard when shard-aware); it has no per-host pool - size or per-connection request limit, so these settings never had an effect. - - Args: - config (ScyllaDBConfig): The ScyllaDB configuration. - """ - values = vars(config) # read without the pydantic deprecation warning - ignored = [name for name, default in _POOL_SETTING_DEFAULTS.items() if values[name] != default] - if ignored: - warnings.warn( - f"{', '.join(ignored)} {'has' if len(ignored) == 1 else 'have'} no effect: scylla-driver does not support " - "per-host connection pool sizing, and the setting will be removed in a future release", - DeprecationWarning, - stacklevel=3, - ) - - _SERIAL_CONSISTENCY_LEVELS: Final = { "SERIAL": ConsistencyLevel.SERIAL, "LOCAL_SERIAL": ConsistencyLevel.LOCAL_SERIAL, @@ -729,7 +700,6 @@ def _create_cluster(self) -> Cluster: Cluster: Configured cluster instance. """ cluster = _build_cluster(self.config) - _warn_ignored_pool_settings(self.config) _warn_insecure_connection(self.config) return cluster @@ -1241,7 +1211,6 @@ def _create_cluster(self) -> Cluster: Cluster: Configured cluster instance. """ cluster = _build_cluster(self.config) - _warn_ignored_pool_settings(self.config) _warn_insecure_connection(self.config) return cluster diff --git a/packages/temporal/archipy/adapters/temporal/adapters.py b/packages/temporal/archipy/adapters/temporal/adapters.py index fd1ca26e2..59fa4c8a9 100644 --- a/packages/temporal/archipy/adapters/temporal/adapters.py +++ b/packages/temporal/archipy/adapters/temporal/adapters.py @@ -10,7 +10,6 @@ import asyncio import contextlib import logging -import warnings from datetime import timedelta from pathlib import Path from typing import TYPE_CHECKING, Any, TypeVar, override @@ -853,23 +852,6 @@ async def create_schedule( await client.create_schedule(schedule_id, sched) - @override - async def stop_schedule(self, schedule_id: str) -> None: - """Delete a schedule. - - Deprecated: the name hides that the schedule is deleted; use ``delete_schedule``, or ``pause_schedule`` to - stop it while keeping it. - - Args: - schedule_id (str): The schedule ID. - """ - warnings.warn( - "stop_schedule() deletes the schedule and is deprecated; use delete_schedule() or pause_schedule()", - DeprecationWarning, - stacklevel=2, - ) - await self.delete_schedule(schedule_id) - @override async def delete_schedule(self, schedule_id: str) -> None: """Delete a schedule permanently; ``pause_schedule`` stops it while keeping it. diff --git a/packages/temporal/archipy/adapters/temporal/base.py b/packages/temporal/archipy/adapters/temporal/base.py index 5dbb863ea..435ff9a26 100644 --- a/packages/temporal/archipy/adapters/temporal/base.py +++ b/packages/temporal/archipy/adapters/temporal/base.py @@ -655,7 +655,7 @@ def _get_atomic_decorator(self) -> Callable[..., Any]: ImportError: If SQLAlchemy is not installed and atomic decorators are needed. """ # Lazy import to avoid requiring SQLAlchemy when using temporalio without sqlalchemy extra - from archipy.helpers.decorators import ( + from archipy.adapters.base.sqlalchemy.atomic import ( postgres_sqlalchemy_atomic, sqlite_sqlalchemy_atomic, starrocks_sqlalchemy_atomic, diff --git a/packages/temporal/archipy/adapters/temporal/ports.py b/packages/temporal/archipy/adapters/temporal/ports.py index c30701306..3f4444d59 100644 --- a/packages/temporal/archipy/adapters/temporal/ports.py +++ b/packages/temporal/archipy/adapters/temporal/ports.py @@ -286,19 +286,13 @@ async def create_schedule( raise NotImplementedError @abstractmethod - async def stop_schedule(self, schedule_id: str) -> None: - """Delete a schedule (deprecated name, use ``delete_schedule``).""" - raise NotImplementedError - async def delete_schedule(self, schedule_id: str) -> None: """Delete a schedule permanently; ``pause_schedule`` stops it while keeping it. - Defaults to ``stop_schedule`` so existing implementations keep working. - Args: schedule_id (str): The schedule ID. """ - await self.stop_schedule(schedule_id) + raise NotImplementedError class WorkerPort: @@ -318,7 +312,6 @@ async def start_worker( task_queue: str, workflows: list[type] | None = None, activities: list[Callable[..., Any]] | None = None, - build_id: str | None = None, identity: str | None = None, max_concurrent_workflow_tasks: int | None = None, max_concurrent_activities: int | None = None, @@ -331,7 +324,6 @@ async def start_worker( Defaults to None. activities (list[Callable], optional): List of activity callables to register. Defaults to None. - build_id (str, optional): Build identifier for worker versioning. Defaults to None. identity (str, optional): Unique worker identity. If None, auto-generated. Defaults to None. diff --git a/packages/temporal/archipy/adapters/temporal/tracing.py b/packages/temporal/archipy/adapters/temporal/tracing.py index cd70d649a..f08194202 100644 --- a/packages/temporal/archipy/adapters/temporal/tracing.py +++ b/packages/temporal/archipy/adapters/temporal/tracing.py @@ -57,8 +57,6 @@ def _set_messaging_attributes(task_queue: str | None, operation: str = "process" """ span = trace.get_current_span() span.set_attribute("messaging.system", "temporal") - # ``messaging.operation`` is deprecated for ``messaging.operation.type``; backends still read the old key. - span.set_attribute("messaging.operation", operation) span.set_attribute("messaging.operation.type", operation) if task_queue is not None: span.set_attribute("messaging.destination.name", task_queue) diff --git a/packages/temporal/archipy/adapters/temporal/worker.py b/packages/temporal/archipy/adapters/temporal/worker.py index ba37c00a4..ad970f8ad 100644 --- a/packages/temporal/archipy/adapters/temporal/worker.py +++ b/packages/temporal/archipy/adapters/temporal/worker.py @@ -9,7 +9,6 @@ import asyncio import logging -import warnings from datetime import timedelta from typing import TYPE_CHECKING, Any, override from uuid import uuid7 @@ -24,7 +23,6 @@ from archipy.configs.base_config import BaseConfig from archipy.configs.config_template import TemporalConfig -from archipy.models.errors import InvalidArgumentError from archipy.models.errors.temporal_errors import ( WorkerConnectionError, WorkerShutdownError, @@ -355,7 +353,6 @@ async def start_worker( task_queue: str, workflows: list[type] | None = None, activities: list[Callable[..., Any]] | None = None, - build_id: str | None = None, identity: str | None = None, max_concurrent_workflow_tasks: int | None = None, max_concurrent_activities: int | None = None, @@ -373,8 +370,6 @@ async def start_worker( Defaults to None. activities (list[Callable], optional): List of activity callables to register. Defaults to None. - build_id (str, optional): Deprecated, use ``deployment_config``. Build identifier for worker - versioning. Defaults to None. identity (str, optional): Unique worker identity. If None, auto-generated. Defaults to None. max_concurrent_workflow_tasks (int, optional): Maximum concurrent workflow tasks. @@ -386,7 +381,7 @@ async def start_worker( activity_executor (Executor, optional): Executor that runs synchronous (non-async) activities. Required when registering sync activities. Defaults to None. deployment_config (WorkerDeploymentConfig, optional): Worker Deployment version this worker belongs - to, replacing ``build_id``. Defaults to None. + to. Defaults to None. workflow_failure_exception_types (Sequence[type[BaseException]], optional): Exception types that fail the workflow instead of retrying the workflow task (e.g. ``[Exception]`` to fail on any error). Defaults to () (only ``FailureError`` subclasses fail it). @@ -407,18 +402,6 @@ async def start_worker( }, ) - if build_id is not None: - if deployment_config is not None: - raise InvalidArgumentError( - argument_name="build_id", - additional_data={"reason": "build_id and deployment_config are mutually exclusive"}, - ) - warnings.warn( - "start_worker(build_id=...) is deprecated; pass deployment_config=WorkerDeploymentConfig(...) instead", - DeprecationWarning, - stacklevel=2, - ) - client = await self._get_client() worker_id = str(uuid7()) # uuid7 starts with the timestamp, so the random tail keeps identities of workers started together apart. @@ -432,7 +415,6 @@ async def start_worker( task_queue=task_queue, workflows=workflows or [], activities=activities or [], - build_id=build_id, deployment_config=deployment_config, workflow_failure_exception_types=workflow_failure_exception_types, workflow_runner=workflow_runner or SandboxedWorkflowRunner(), @@ -460,7 +442,7 @@ async def start_worker( task_queue=task_queue, workflows=workflows, activities=activities, - build_id=build_id or (deployment_config.version.build_id if deployment_config else None), + build_id=deployment_config.version.build_id if deployment_config else None, identity=worker_identity, max_concurrent_workflow_tasks=max_concurrent_workflow_tasks, max_concurrent_activities=max_concurrent_activities, diff --git a/pyproject.toml b/pyproject.toml index 11f26d916..502921f9f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -157,9 +157,6 @@ name = "ArchiPy layers: adapters -> helpers -> configs -> models" type = "layers" layers = ["archipy.adapters", "archipy.helpers", "archipy.configs", "archipy.models"] ignore_imports = [ - # Deprecated import paths of moved code (atomic decorators, Keycloak auth); remove with the shim modules in 6.0.0 - "archipy.helpers.decorators.sqlalchemy_transaction -> archipy.adapters.base.sqlalchemy.atomic", - "archipy.helpers.utils.keycloak_utils -> archipy.adapters.keycloak.auth", # Function-scoped import of the default Redis store; helpers-configs.mdc allows it and a store= argument replaces it "archipy.helpers.interceptors.grpc.rate_limit.grpc_rate_limit_interceptor -> archipy.adapters.redis.adapters", ] From e4c58b1e3579c639674cbd6dec562754b1368040 Mon Sep 17 00:00:00 2001 From: "h.nejati" Date: Sun, 22 Nov 2026 12:03:02 +0330 Subject: [PATCH 2/2] docs(changelog): date 6.0.0 release notes --- docs/community/changelog/6/6.0.0.md | 2 +- docs/community/changelog/6/index.md | 2 +- docs/community/changelog/index.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/community/changelog/6/6.0.0.md b/docs/community/changelog/6/6.0.0.md index 5a146e32a..8e6f68d6b 100644 --- a/docs/community/changelog/6/6.0.0.md +++ b/docs/community/changelog/6/6.0.0.md @@ -3,7 +3,7 @@ title: "Changelog 6.0.0" description: "Release notes for ArchiPy 6.0.0" --- -# 6.0.0 — Unreleased +# 6.0.0 — 2026-11-22 [← 5.32.0](../5/5.32.0.md) | [↑ 6.x series](index.md) diff --git a/docs/community/changelog/6/index.md b/docs/community/changelog/6/index.md index 4c3ddc3e9..8f1246119 100644 --- a/docs/community/changelog/6/index.md +++ b/docs/community/changelog/6/index.md @@ -9,4 +9,4 @@ description: "Release history for the ArchiPy 6.x series" | Version | Date | Summary | |---------|------|---------| -| [6.0.0](6.0.0.md) | Unreleased | Removes deprecated APIs and flat config fields. Enforces SMTP TLS for login and Keycloak issuer checks. | +| [6.0.0](6.0.0.md) | 2026-11-22 | Removes deprecated APIs and flat config fields. Enforces SMTP TLS for login and Keycloak issuer checks. | diff --git a/docs/community/changelog/index.md b/docs/community/changelog/index.md index f5510fc6a..5f1d5e1c1 100644 --- a/docs/community/changelog/index.md +++ b/docs/community/changelog/index.md @@ -9,7 +9,7 @@ All notable changes to ArchiPy are documented here, organized by major version s ## [6.x Series](6/index.md) -6.0.0 is unreleased. +1 release — 6.0.0 ## [5.x Series](5/index.md)