diff --git a/archipy/adapters/base/sqlalchemy/query_helpers.py b/archipy/adapters/base/sqlalchemy/query_helpers.py index 886b52f53..18a03bcb7 100644 --- a/archipy/adapters/base/sqlalchemy/query_helpers.py +++ b/archipy/adapters/base/sqlalchemy/query_helpers.py @@ -56,11 +56,11 @@ async def _run_async_count_request(request: _CountRequest) -> int: def _build_count_cache(config: SQLAlchemyConfig) -> Callable[[_CountRequest], int] | None: """Create the cached count runner when the config enables it (needs the ``cache`` extra).""" - if not config.COUNT_CACHE_ENABLED: + if not config.COUNT_CACHE.IS_ENABLED: return None from archipy.helpers.decorators.ttl_caching import ttl_cache # noqa: PLC0415 # optional "cache" extra - return ttl_cache(ttl_seconds=config.COUNT_CACHE_TTL_SECONDS, maxsize=config.COUNT_CACHE_MAX_SIZE)( + return ttl_cache(ttl_seconds=config.COUNT_CACHE.TTL_SECONDS, maxsize=config.COUNT_CACHE.MAX_SIZE)( _run_count_request, ) @@ -71,7 +71,7 @@ def _build_async_count_cache(config: SQLAlchemyConfig) -> Callable[[_CountReques Raises: ConfigurationError: If the count cache is enabled but ``async-lru`` is not installed. """ - if not config.COUNT_CACHE_ENABLED: + if not config.COUNT_CACHE.IS_ENABLED: return None try: from async_lru import alru_cache # noqa: PLC0415 # optional "cache" extra @@ -81,7 +81,7 @@ def _build_async_count_cache(config: SQLAlchemyConfig) -> Callable[[_CountReques reason="async-lru is not installed; install it with archipy[cache]", ) from exception - return alru_cache(ttl=config.COUNT_CACHE_TTL_SECONDS, maxsize=config.COUNT_CACHE_MAX_SIZE)( + return alru_cache(ttl=config.COUNT_CACHE.TTL_SECONDS, maxsize=config.COUNT_CACHE.MAX_SIZE)( _run_async_count_request, ) diff --git a/archipy/adapters/base/sqlalchemy/session_managers.py b/archipy/adapters/base/sqlalchemy/session_managers.py index 6a2cf9408..00a3fbd1c 100644 --- a/archipy/adapters/base/sqlalchemy/session_managers.py +++ b/archipy/adapters/base/sqlalchemy/session_managers.py @@ -201,13 +201,13 @@ def _get_pool_kwargs(self, configs: ConfigT) -> dict[str, Any]: A dictionary of pool-related keyword arguments for engine creation. """ return { - "pool_pre_ping": configs.POOL_PRE_PING, - "pool_size": configs.POOL_SIZE, - "pool_recycle": configs.POOL_RECYCLE_SECONDS, - "pool_reset_on_return": configs.POOL_RESET_ON_RETURN, - "pool_timeout": configs.POOL_TIMEOUT, - "pool_use_lifo": configs.POOL_USE_LIFO, - "max_overflow": configs.POOL_MAX_OVERFLOW, + "pool_pre_ping": configs.POOL.PRE_PING, + "pool_size": configs.POOL.SIZE, + "pool_recycle": configs.POOL.RECYCLE_SECONDS, + "pool_reset_on_return": configs.POOL.RESET_ON_RETURN, + "pool_timeout": configs.POOL.TIMEOUT, + "pool_use_lifo": configs.POOL.USE_LIFO, + "max_overflow": configs.POOL.MAX_OVERFLOW, } def _get_session_generator(self) -> scoped_session: @@ -430,13 +430,13 @@ def _get_pool_kwargs(self, configs: ConfigT) -> dict[str, Any]: A dictionary of pool-related keyword arguments for engine creation. """ return { - "pool_pre_ping": configs.POOL_PRE_PING, - "pool_size": configs.POOL_SIZE, - "pool_recycle": configs.POOL_RECYCLE_SECONDS, - "pool_reset_on_return": configs.POOL_RESET_ON_RETURN, - "pool_timeout": configs.POOL_TIMEOUT, - "pool_use_lifo": configs.POOL_USE_LIFO, - "max_overflow": configs.POOL_MAX_OVERFLOW, + "pool_pre_ping": configs.POOL.PRE_PING, + "pool_size": configs.POOL.SIZE, + "pool_recycle": configs.POOL.RECYCLE_SECONDS, + "pool_reset_on_return": configs.POOL.RESET_ON_RETURN, + "pool_timeout": configs.POOL.TIMEOUT, + "pool_use_lifo": configs.POOL.USE_LIFO, + "max_overflow": configs.POOL.MAX_OVERFLOW, } def _get_session_generator(self) -> async_scoped_session: diff --git a/archipy/adapters/email/adapters.py b/archipy/adapters/email/adapters.py index 26a9d7da3..4034b99cb 100644 --- a/archipy/adapters/email/adapters.py +++ b/archipy/adapters/email/adapters.py @@ -75,7 +75,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 only one of ``USERNAME`` and ``PASSWORD`` is set while ``TLS.MODE`` is not ``auto``. """ self.config = config self.smtp_connection: smtplib.SMTP | None = None @@ -86,10 +86,10 @@ def __init__(self, config: EmailConfig) -> None: 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": + 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'.", + "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, ) @@ -105,37 +105,37 @@ def _validate_security(self) -> None: 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: + 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.", + "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: + 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.", + "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, ) 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: + """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 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.""" - mode = self.config.TLS_MODE + 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] = { "local_hostname": self.config.LOCAL_HOSTNAME, - "timeout": self.config.CONNECTION_TIMEOUT, + "timeout": self.config.POOL.CONNECTION_TIMEOUT, "source_address": source_address, } server = cast("str", self.config.SMTP_SERVER) @@ -158,7 +158,7 @@ def _open_session(self) -> tuple[smtplib.SMTP, str]: 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.""" - mode = self.config.TLS_MODE + mode = self.config.TLS.MODE session.ehlo() offered = session.has_extn("starttls") if mode == "starttls" and not offered: @@ -220,7 +220,7 @@ def refresh_if_needed(self) -> None: return time_diff = (DatetimeUtils.get_datetime_now() - self.last_used).total_seconds() - if time_diff > self.config.CONNECTION_REFRESH_SECONDS: + if time_diff > self.config.POOL.CONNECTION_REFRESH_SECONDS: self.disconnect() self.connect() @@ -231,11 +231,11 @@ class EmailConnectionPool: def __init__(self, config: EmailConfig) -> None: """Initialize EmailConnectionPool.""" self.config = config - self.pool: Queue[EmailConnectionManager] = Queue(maxsize=config.POOL_SIZE) + self.pool: Queue[EmailConnectionManager] = Queue(maxsize=config.POOL.SIZE) self._initialize_pool() def _initialize_pool(self) -> None: - for _ in range(self.config.POOL_SIZE): + for _ in range(self.config.POOL.SIZE): connection = EmailConnectionManager(self.config) self.pool.put(connection) @@ -249,7 +249,7 @@ def get_connection(self) -> EmailConnectionManager: UnavailableError: If no slot becomes free within ``CONNECTION_TIMEOUT`` seconds. """ try: - connection = self.pool.get(timeout=self.config.CONNECTION_TIMEOUT) + connection = self.pool.get(timeout=self.config.POOL.CONNECTION_TIMEOUT) except Empty as exception: raise UnavailableError(resource_type="SMTP") from exception try: @@ -287,7 +287,7 @@ def create_attachment( content_type: Optional MIME type of the attachment. content_disposition: Whether the attachment is inline or a regular attachment. content_id: Optional Content-ID for inline attachments. - max_size: Maximum size in bytes; defaults to the configured ``ATTACHMENT_MAX_SIZE``. + max_size: Maximum size in bytes; defaults to the configured ``ATTACHMENTS.MAX_SIZE``. Returns: EmailAttachmentDTO: The validated attachment. @@ -297,7 +297,7 @@ def create_attachment( (for example it exceeds the maximum size). """ if max_size is None: - max_size = BaseConfig.global_config().EMAIL.ATTACHMENT_MAX_SIZE + max_size = BaseConfig.global_config().EMAIL.ATTACHMENTS.MAX_SIZE try: processed_content = AttachmentHandler._process_source(source, attachment_type, max_size) @@ -362,12 +362,12 @@ def _process_url_source(source: str | bytes | BinaryIO | HttpUrl, max_size: int parsed = urlparse(url) if parsed.scheme not in ("http", "https"): raise InvalidArgumentError(argument_name="source", additional_data={"reason": "unsupported_url_scheme"}) - allowed_hosts = config.ATTACHMENT_URL_ALLOWED_HOSTS + allowed_hosts = config.ATTACHMENTS.URL_ALLOWED_HOSTS if allowed_hosts is not None and parsed.hostname not in allowed_hosts: raise InvalidArgumentError(argument_name="source", additional_data={"reason": "url_host_not_allowed"}) - limit = max_size if max_size is not None else config.ATTACHMENT_MAX_SIZE + limit = max_size if max_size is not None else config.ATTACHMENTS.MAX_SIZE content = bytearray() - with httpx2.stream("GET", url, timeout=config.ATTACHMENT_URL_TIMEOUT) as response: + with httpx2.stream("GET", url, timeout=config.ATTACHMENTS.URL_TIMEOUT) as response: response.raise_for_status() for chunk in response.iter_bytes(): content.extend(chunk) diff --git a/archipy/configs/base_config.py b/archipy/configs/base_config.py index 1357c97c7..16f203a0d 100644 --- a/archipy/configs/base_config.py +++ b/archipy/configs/base_config.py @@ -236,7 +236,7 @@ def customize(self) -> None: It is called automatically by `set_global()`. When ``APP_NAME`` is set, unset or placeholder nested identity fields are - filled: ``OTEL.SERVICE_NAME``, ``FASTAPI.PROJECT_NAME``, ``AUTH.JWT_ISSUER``, + filled: ``OTEL.SERVICE_NAME``, ``FASTAPI.PROJECT_NAME``, ``AUTH.JWT.ISSUER``, and ``TEMPORAL.CLIENT_IDENTITY``. Explicit nested values always win. An unset ``COUNT_THRESHOLD`` of the SQLAlchemy configs is filled with ``PAGINATION.MAX_ITEMS``. @@ -257,8 +257,8 @@ def customize(self) -> None: self.OTEL.SERVICE_NAME = self.APP_NAME if self.FASTAPI.PROJECT_NAME == "project_name": self.FASTAPI.PROJECT_NAME = self.APP_NAME - if self.AUTH.JWT_ISSUER == "your-app-name": - self.AUTH.JWT_ISSUER = self.APP_NAME + if self.AUTH.JWT.ISSUER == "your-app-name": + self.AUTH.JWT.ISSUER = self.APP_NAME if self.TEMPORAL.CLIENT_IDENTITY is None: self.TEMPORAL.CLIENT_IDENTITY = self.APP_NAME diff --git a/archipy/configs/sections/_common.py b/archipy/configs/sections/_common.py new file mode 100644 index 000000000..6e8543dc6 --- /dev/null +++ b/archipy/configs/sections/_common.py @@ -0,0 +1,51 @@ +"""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 96018c5c5..87d17962f 100644 --- a/archipy/configs/sections/auth.py +++ b/archipy/configs/sections/auth.py @@ -1,17 +1,17 @@ """Authentication configuration.""" -from pydantic import BaseModel, Field, SecretStr +from typing import Self +from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator -class AuthConfig(BaseModel): - """Configuration settings for authentication and security. +from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields - Controls JWT token settings, TOTP configuration, rate limiting, - password policies, and token security features. - """ - # JWT Settings - SECRET_KEY: SecretStr | None = Field(default=None, description="JWT signing key") +class JwtConfig(BaseModel): + """JWT and token security settings.""" + + model_config = ConfigDict(extra="forbid") + ACCESS_TOKEN_EXPIRES_IN: int = Field( default=1 * 60 * 60, description="Access token expiration in seconds", @@ -20,35 +20,53 @@ class AuthConfig(BaseModel): default=24 * 60 * 60, description="Refresh token expiration in seconds", ) # 24 hours - HASH_ALGORITHM: str = Field(default="HS256", description="JWT signing algorithm") - JWT_ISSUER: str = Field(default="your-app-name", description="JWT issuer claim") - JWT_AUDIENCE: str = Field(default="your-app-audience", description="JWT audience claim") + ALGORITHM: str = Field(default="HS256", description="JWT signing algorithm") + ISSUER: str = Field(default="your-app-name", description="JWT issuer claim") + AUDIENCE: str = Field(default="your-app-audience", description="JWT audience claim") TOKEN_VERSION: int = Field(default=1, description="JWT token version") - JWT_LEEWAY: int = Field( + LEEWAY: int = Field( default=0, ge=0, description="Clock-skew tolerance in seconds applied to exp, nbf and iat when verifying tokens", ) + ENABLE_JTI_CLAIM: bool = Field(default=True, description="Enable JWT ID claim for token tracking") + ENABLE_TOKEN_ROTATION: bool = Field(default=True, description="Enable refresh token rotation") + REFRESH_TOKEN_REUSE_INTERVAL: int = Field(default=60, description="Grace period for refresh token reuse in seconds") - # TOTP Settings - TOTP_SECRET_KEY: SecretStr | None = Field(default=None, description="TOTP master key") - TOTP_HASH_ALGORITHM: str = Field( + +class TotpConfig(BaseModel): + """TOTP settings.""" + + model_config = ConfigDict(extra="forbid") + + SECRET_KEY: SecretStr | None = Field(default=None, description="TOTP master key") + HASH_ALGORITHM: str = Field( default="SHA1", description="Hash algorithm for TOTP generation (SHA1, SHA256, SHA512)", ) - TOTP_LENGTH: int = Field(default=6, ge=6, le=8, description="TOTP code length") - TOTP_EXPIRES_IN: int = Field(default=300, description="TOTP expiration time in seconds (5 minutes)") - TOTP_TIME_STEP: int = Field(default=30, description="TOTP time step in seconds") - TOTP_VERIFICATION_WINDOW: int = Field(default=1, description="Number of time steps to check before/after") - TOTP_MAX_ATTEMPTS: int = Field(default=3, description="Maximum failed TOTP attempts before lockout") - TOTP_LOCKOUT_TIME: int = Field(default=300, description="Lockout time in seconds after max attempts") + LENGTH: int = Field(default=6, ge=6, le=8, description="TOTP code length") + EXPIRES_IN: int = Field(default=300, description="TOTP expiration time in seconds (5 minutes)") + TIME_STEP: int = Field(default=30, description="TOTP time step in seconds") + VERIFICATION_WINDOW: int = Field(default=1, description="Number of time steps to check before/after") + MAX_ATTEMPTS: int = Field(default=3, description="Maximum failed TOTP attempts before lockout") + LOCKOUT_TIME: int = Field(default=300, description="Lockout time in seconds after max attempts") + + +class RateLimitsConfig(BaseModel): + """Rate limits per user action.""" - # Rate Limiting Settings - LOGIN_RATE_LIMIT: int = Field(default=5, description="Maximum login attempts per minute") - TOTP_RATE_LIMIT: int = Field(default=3, description="Maximum TOTP requests per minute") - PASSWORD_RESET_RATE_LIMIT: int = Field(default=3, description="Maximum password reset requests per hour") + model_config = ConfigDict(extra="forbid") + + LOGIN: int = Field(default=5, description="Maximum login attempts per minute") + TOTP: int = Field(default=3, description="Maximum TOTP requests per minute") + PASSWORD_RESET: int = Field(default=3, description="Maximum password reset requests per hour") + + +class PasswordPolicyConfig(BaseModel): + """Password hashing and strength policy.""" + + model_config = ConfigDict(extra="forbid") - # Password Policy HASH_ITERATIONS: int = Field( default=600000, ge=1, @@ -61,13 +79,247 @@ class AuthConfig(BaseModel): REQUIRE_UPPERCASE: bool = Field(default=True, description="Whether password requires uppercase") SALT_LENGTH: int = Field(default=16, description="Password salt length") SPECIAL_CHARACTERS: set[str] = Field(default=set("!@#$%^&*()-_+="), description="Set of allowed special characters") + HISTORY_SIZE: int = Field( + default=3, + ge=0, + description="Number of previous passwords to remember (0 disables the history check)", + ) + + +class AuthConfig(BaseModel): + """Configuration settings for authentication and security. + + Controls JWT token settings, TOTP configuration, rate limiting, + password policies, and token security features. + """ + + SECRET_KEY: SecretStr | None = Field(default=None, description="JWT signing key") + + JWT: JwtConfig = Field(default_factory=JwtConfig, description="JWT and token security settings") + TOTP: TotpConfig = Field(default_factory=TotpConfig, description="TOTP settings") + RATE_LIMITS: RateLimitsConfig = Field(default_factory=RateLimitsConfig, description="Rate limits per user action") + PASSWORD_POLICY: PasswordPolicyConfig = Field( + 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"), ) - # Token Security - ENABLE_JTI_CLAIM: bool = Field(default=True, description="Enable JWT ID claim for token tracking") - ENABLE_TOKEN_ROTATION: bool = Field(default=True, description="Enable refresh token rotation") - REFRESH_TOKEN_REUSE_INTERVAL: int = Field(default=60, description="Grace period for refresh token reuse in seconds") + @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 c216b22d2..3efc1f9f0 100644 --- a/archipy/configs/sections/elasticsearch.py +++ b/archipy/configs/sections/elasticsearch.py @@ -6,6 +6,7 @@ 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__) @@ -14,41 +15,121 @@ DEFAULT_RETRY_BACKOFF_CAP = 30.0 -class ElasticsearchConfig(BaseModel): - """Configuration settings for Elasticsearch connections and operations. - - Contains settings related to Elasticsearch server connectivity, authentication, - TLS/SSL, request handling, node status management, and batch operation parameters. - """ +class ElasticsearchAuthConfig(BaseModel): + """Authentication settings.""" - model_config = ConfigDict(arbitrary_types_allowed=True) + model_config = ConfigDict(extra="forbid") - HOSTS: list[str] = Field(default=["https://localhost:9200"], description="List of Elasticsearch server hosts") - HTTP_USER_NAME: str | None = None - HTTP_PASSWORD: SecretStr | None = None + USER_NAME: str | None = None + PASSWORD: SecretStr | None = None API_KEY: str | None = None API_SECRET: SecretStr | None = None - BEARER_AUTH: SecretStr | None = Field( + BEARER: SecretStr | None = Field( default=None, description="Bearer token for token or OIDC auth (exclusive with API key and basic auth)", ) - CLOUD_ID: str | None = Field( - default=None, - description="Elastic Cloud ID; when set it replaces HOSTS", - ) + + @model_validator(mode="after") + def validate_auth_settings(self) -> Self: + """Validate auth settings: no partial credential pairs, no bearer auth mixed with another method.""" + if bool(self.API_KEY) != bool(self.API_SECRET): + raise InvalidArgumentError(argument_name="API_KEY and API_SECRET") + if bool(self.USER_NAME) != bool(self.PASSWORD): + raise InvalidArgumentError(argument_name="HTTP_USER_NAME and HTTP_PASSWORD") + has_api_key = bool(self.API_KEY and self.API_SECRET) + has_basic = bool(self.USER_NAME and self.PASSWORD) + if self.BEARER and (has_api_key or has_basic): + raise InvalidArgumentError() + return self + + +class ElasticsearchTlsConfig(BaseModel): + """TLS and certificate settings.""" + + model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True) + CA_CERTS: str | None = Field(default=None, description="Path to CA bundle for SSL verification") - SSL_ASSERT_FINGERPRINT: str | None = Field(default=None, description="SSL certificate fingerprint for verification") + ASSERT_FINGERPRINT: str | None = Field(default=None, description="SSL certificate fingerprint for verification") VERIFY_CERTS: bool = Field(default=True, description="Whether to verify SSL certificates") CLIENT_CERT: str | None = Field(default=None, description="Path to client certificate for TLS authentication") CLIENT_KEY: str | None = Field(default=None, description="Path to client key for TLS authentication") - SSL_VERSION: ssl.TLSVersion | None = Field( + VERSION: ssl.TLSVersion | None = Field( default=None, description="TLS protocol version (client default if unset)", ) - SSL_CONTEXT: ssl.SSLContext | None = Field( + CONTEXT: ssl.SSLContext | None = Field( default=None, description="Custom SSL context; takes precedence over the other TLS file settings in the client", ) + + @model_validator(mode="after") + def validate_tls_settings(self) -> Self: + """Validate TLS-related settings to ensure compatibility.""" + if not self.VERIFY_CERTS and (self.CA_CERTS or self.ASSERT_FINGERPRINT): + raise InvalidArgumentError() + if self.CLIENT_CERT and not self.CLIENT_KEY: + raise FailedPreconditionError() + if self.CLIENT_KEY and not self.CLIENT_CERT: + raise InvalidArgumentError(argument_name="CLIENT_KEY") + return self + + +class ElasticsearchRetryConfig(BaseModel): + """Retry and backoff settings.""" + + model_config = ConfigDict(extra="forbid") + + MAX_RETRIES: int = Field(default=1, ge=0, description="Maximum number of retries per request") + ON_TIMEOUT: bool = Field(default=True, description="Retry on connection timeouts") + ON_STATUS: tuple[int, ...] = Field(default=(429, 502, 503, 504), description="HTTP status codes to retry on") + BACKOFF_BASE: float | None = Field( + default=None, + gt=0, + description="Base delay in seconds for exponential retry backoff (None: retry immediately)", + ) + BACKOFF_CAP: float | None = Field( + default=None, + gt=0, + description="Maximum delay in seconds between retries (None: client default)", + ) + + @model_validator(mode="after") + def default_retry_backoff_cap(self) -> Self: + """Set a backoff cap when only the base is given, since the client ignores a lone base.""" + if self.BACKOFF_BASE is not None and self.BACKOFF_CAP is None: + self.BACKOFF_CAP = max(self.BACKOFF_BASE, DEFAULT_RETRY_BACKOFF_CAP) + return self + + +class ElasticsearchSniffingConfig(BaseModel): + """Node sniffing settings.""" + + model_config = ConfigDict(extra="forbid") + + ON_START: bool = Field(default=False, description="Sniff nodes on client instantiation") + BEFORE_REQUESTS: bool = Field(default=False, description="Sniff nodes before requests") + ON_NODE_FAILURE: bool = Field(default=True, description="Sniff nodes on node failure") + MIN_DELAY: float = Field( + default=60.0, + ge=0.0, + description="Minimum delay between sniffing attempts in seconds (needs SNIFF_BEFORE_REQUESTS)", + ) + + +class ElasticsearchConfig(BaseModel): + """Configuration settings for Elasticsearch connections and operations. + + Contains settings related to Elasticsearch server connectivity, authentication, + TLS/SSL, request handling, node status management, and batch operation parameters. + """ + + model_config = ConfigDict(arbitrary_types_allowed=True) + + HOSTS: list[str] = Field(default=["https://localhost:9200"], description="List of Elasticsearch server hosts") + CLOUD_ID: str | None = Field( + default=None, + description="Elastic Cloud ID; when set it replaces HOSTS", + ) OPAQUE_ID: str | None = Field(default=None, description="Opaque ID sent as X-Opaque-Id to trace requests") HEADERS: dict[str, str] | None = Field(default=None, description="Extra HTTP headers sent with every request") HTTP_COMPRESS: bool = Field(default=True, description="Enable HTTP compression (gzip)") @@ -63,28 +144,7 @@ class ElasticsearchConfig(BaseModel): "Deprecated default: this will become True in a future release." ), ) - MAX_RETRIES: int = Field(default=1, ge=0, description="Maximum number of retries per request") - RETRY_ON_TIMEOUT: bool = Field(default=True, description="Retry on connection timeouts") - RETRY_ON_STATUS: tuple[int, ...] = Field(default=(429, 502, 503, 504), description="HTTP status codes to retry on") - RETRY_BACKOFF_BASE: float | None = Field( - default=None, - gt=0, - description="Base delay in seconds for exponential retry backoff (None: retry immediately)", - ) - RETRY_BACKOFF_CAP: float | None = Field( - default=None, - gt=0, - description="Maximum delay in seconds between retries (None: client default)", - ) IGNORE_STATUS: tuple[int, ...] = Field(default=(), description="HTTP status codes to ignore as errors") - SNIFF_ON_START: bool = Field(default=False, description="Sniff nodes on client instantiation") - SNIFF_BEFORE_REQUESTS: bool = Field(default=False, description="Sniff nodes before requests") - SNIFF_ON_NODE_FAILURE: bool = Field(default=True, description="Sniff nodes 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)", - ) NODE_SELECTOR_CLASS: Literal["round_robin", "random"] = Field( default="round_robin", description="Node selector strategy ('round_robin' or 'random')", @@ -101,53 +161,201 @@ class ElasticsearchConfig(BaseModel): description="Maximum timeout duration for a dead node in seconds", ) + AUTH: ElasticsearchAuthConfig = Field( + default_factory=ElasticsearchAuthConfig, + description="Authentication settings", + ) + TLS: ElasticsearchTlsConfig = Field( + default_factory=ElasticsearchTlsConfig, + description="TLS and certificate settings", + ) + RETRY: ElasticsearchRetryConfig = Field( + default_factory=ElasticsearchRetryConfig, + description="Retry and backoff settings", + ) + SNIFFING: ElasticsearchSniffingConfig = Field( + default_factory=ElasticsearchSniffingConfig, + 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 validate_auth_settings(self) -> Self: - """Validate auth settings: no partial credential pairs, no bearer auth mixed with another method.""" - if bool(self.API_KEY) != bool(self.API_SECRET): - raise InvalidArgumentError(argument_name="API_KEY and API_SECRET") - if bool(self.HTTP_USER_NAME) != bool(self.HTTP_PASSWORD): - raise InvalidArgumentError(argument_name="HTTP_USER_NAME and HTTP_PASSWORD") - has_api_key = bool(self.API_KEY and self.API_SECRET) - has_basic = bool(self.HTTP_USER_NAME and self.HTTP_PASSWORD) - if self.BEARER_AUTH and (has_api_key or has_basic): - raise InvalidArgumentError() + 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.""" - if not (self.API_KEY or self.HTTP_USER_NAME or self.BEARER_AUTH): + if not (self.AUTH.API_KEY or self.AUTH.USER_NAME or self.AUTH.BEARER): return self if not self.CLOUD_ID and any(host.lower().startswith("http://") for host in self.HOSTS): logger.warning("Elasticsearch credentials are sent over plaintext http://; use https:// hosts.") - if not self.VERIFY_CERTS: - logger.warning("Elasticsearch credentials are sent with VERIFY_CERTS disabled; enable certificate checks.") - return self - - @model_validator(mode="after") - def default_retry_backoff_cap(self) -> Self: - """Set a backoff cap when only the base is given, since the client ignores a lone base.""" - if self.RETRY_BACKOFF_BASE is not None and self.RETRY_BACKOFF_CAP is None: - self.RETRY_BACKOFF_CAP = max(self.RETRY_BACKOFF_BASE, DEFAULT_RETRY_BACKOFF_CAP) - return self - - @model_validator(mode="after") - def validate_tls_settings(self) -> Self: - """Validate TLS-related settings to ensure compatibility.""" - if not self.VERIFY_CERTS and (self.CA_CERTS or self.SSL_ASSERT_FINGERPRINT): - raise InvalidArgumentError() - if self.CLIENT_CERT and not self.CLIENT_KEY: - raise FailedPreconditionError() - if self.CLIENT_KEY and not self.CLIENT_CERT: - raise InvalidArgumentError(argument_name="CLIENT_KEY") + if not self.TLS.VERIFY_CERTS: + logger.warning( + "Elasticsearch credentials are sent with TLS.VERIFY_CERTS disabled; enable certificate checks.", + ) return self @model_validator(mode="after") def validate_sniffing_settings(self) -> Self: """Warn if sniffing is enabled with a load balancer.""" if ( - any([self.SNIFF_ON_START, self.SNIFF_BEFORE_REQUESTS, self.SNIFF_ON_NODE_FAILURE]) + any([self.SNIFFING.ON_START, self.SNIFFING.BEFORE_REQUESTS, self.SNIFFING.ON_NODE_FAILURE]) and len(self.HOSTS) == 1 and "localhost" not in self.HOSTS[0] ): diff --git a/archipy/configs/sections/email.py b/archipy/configs/sections/email.py index c70438c5c..56e339cee 100644 --- a/archipy/configs/sections/email.py +++ b/archipy/configs/sections/email.py @@ -1,8 +1,65 @@ """Email configuration.""" -from typing import Literal +from typing import Literal, Self -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields + + +class EmailTlsConfig(BaseModel): + """TLS settings of the SMTP connection.""" + + model_config = ConfigDict(extra="forbid") + + 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" + ), + ) + 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')", + ) + + +class EmailPoolConfig(BaseModel): + """Connection pool settings.""" + + model_config = ConfigDict(extra="forbid") + + SIZE: int = Field(default=5, ge=1, description="Connection pool size") + CONNECTION_TIMEOUT: int = Field(default=30, gt=0, description="Connection timeout in seconds") + CONNECTION_REFRESH_SECONDS: int = Field( + default=300, + ge=1, + description="Idle seconds after which a pooled SMTP connection is reconnected", + ) + + +class EmailAttachmentsConfig(BaseModel): + """Attachment limits.""" + + model_config = ConfigDict(extra="forbid") + + URL_TIMEOUT: int = Field( + default=30, + gt=0, + description="Timeout in seconds for downloading URL attachments", + ) + 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)", + ) + MAX_SIZE: int = Field(default=5 * 1024 * 1024, description="Maximum attachment size in bytes") class EmailConfig(BaseModel): @@ -16,6 +73,19 @@ class EmailConfig(BaseModel): SMTP_PORT: int = Field(default=587, description="SMTP server port") USERNAME: str | None = Field(default=None, description="SMTP username") PASSWORD: str | None = Field(default=None, description="SMTP password") + FROM_ADDRESS: str | None = Field( + default=None, + description="Sender address of outgoing emails; defaults to USERNAME, which is invalid for API-key usernames", + ) + LOCAL_HOSTNAME: str | None = Field(default=None, description="Host name sent in EHLO; defaults to the local FQDN") + SOURCE_ADDRESS: str | None = Field(default=None, description="Local address the SMTP socket binds to") + SOURCE_PORT: int = Field(default=0, ge=0, le=65535, description="Local port bound with SOURCE_ADDRESS (0 = any)") + MAX_RETRIES: int = Field(default=3, ge=1, description="Maximum retry attempts") + + 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=( @@ -24,37 +94,80 @@ class EmailConfig(BaseModel): "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"), ) - FROM_ADDRESS: str | None = Field( - default=None, - description="Sender address of outgoing emails; defaults to USERNAME, which is invalid for API-key usernames", + 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"), ) - LOCAL_HOSTNAME: str | None = Field(default=None, description="Host name sent in EHLO; defaults to the local FQDN") - SOURCE_ADDRESS: str | None = Field(default=None, description="Local address the SMTP socket binds to") - SOURCE_PORT: int = Field(default=0, ge=0, le=65535, description="Local port bound with SOURCE_ADDRESS (0 = any)") - POOL_SIZE: int = Field(default=5, ge=1, description="Connection pool size") - CONNECTION_TIMEOUT: int = Field(default=30, gt=0, description="Connection timeout in seconds") 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"), ) - MAX_RETRIES: int = Field(default=3, ge=1, description="Maximum retry attempts") 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") + 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 fa05fd378..f52b0ae6f 100644 --- a/archipy/configs/sections/fastapi.py +++ b/archipy/configs/sections/fastapi.py @@ -5,6 +5,7 @@ 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 @@ -23,6 +24,72 @@ class FastAPIFormLimits(BaseModel): MAX_PART_SIZE: NonNegativeInt | None = Field(default=None, serialization_alias="max_part_size") +class FastAPICorsConfig(BaseModel): + """CORS middleware settings.""" + + model_config = ConfigDict(extra="forbid") + + ALLOW_CREDENTIALS: bool = Field(default=True, description="Whether to allow credentials in CORS") + ALLOW_HEADERS: list[str] = Field(default=["*"], description="Allowed CORS headers") + ALLOW_METHODS: list[str] = Field(default=["*"], description="Allowed CORS methods") + ALLOW_ORIGIN_REGEX: str | None = Field( + default=None, + description="Regex pattern for allowed origins", + ) + ALLOW_ORIGINS: list[str] = Field(default=["*"], description="Allowed CORS origins") + EXPOSE_HEADERS: list[str] = Field(default=[], description="Exposed CORS headers") + MAX_AGE: int = Field(default=600, description="Preflight cache duration in seconds") + + +class FastAPIGzipConfig(BaseModel): + """GZip response compression settings.""" + + model_config = ConfigDict(extra="forbid") + + IS_ENABLED: bool = Field(default=False, description="Whether GZip response compression is enabled") + MINIMUM_SIZE: int = Field( + default=500, + ge=0, + description="Minimum response body size in bytes before compression is applied", + ) + COMPRESSLEVEL: int = Field( + default=6, + ge=1, + le=9, + description="GZip compression level (1=fastest, 9=best compression)", + ) + + +class FastAPITrustedHostConfig(BaseModel): + """TrustedHost middleware settings.""" + + model_config = ConfigDict(extra="forbid") + + IS_ENABLED: bool = Field( + default=False, + description="Whether TrustedHost middleware validates the Host header", + ) + ALLOWED_HOSTS: list[str] = Field( + default=[], + description="Allowed hostnames (e.g. example.com, *.example.com)", + ) + WWW_REDIRECT: bool = Field( + default=True, + description="Redirect www hosts to bare domain when allowed", + ) + + +class FastAPIHttpsRedirectConfig(BaseModel): + """HTTPS redirect middleware settings.""" + + model_config = ConfigDict(extra="forbid") + + IS_ENABLED: bool = Field( + default=False, + description="Whether HTTP requests are redirected to HTTPS", + ) + + class FastAPIConfig(BaseModel): """Configuration settings for FastAPI applications. @@ -40,7 +107,6 @@ 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", @@ -67,44 +133,6 @@ class FastAPIConfig(BaseModel): description="Maximum number of requests", deprecated=_moved("LIMIT_MAX_REQUESTS"), ) - CORS_MIDDLEWARE_ALLOW_CREDENTIALS: bool = Field(default=True, description="Whether to allow credentials in CORS") - CORS_MIDDLEWARE_ALLOW_HEADERS: list[str] = Field(default=["*"], description="Allowed CORS headers") - CORS_MIDDLEWARE_ALLOW_METHODS: list[str] = Field(default=["*"], description="Allowed CORS methods") - CORS_MIDDLEWARE_ALLOW_ORIGIN_REGEX: str | None = Field( - default=None, - description="Regex pattern for allowed origins", - ) - CORS_MIDDLEWARE_ALLOW_ORIGINS: list[str] = Field(default=["*"], description="Allowed CORS origins") - CORS_MIDDLEWARE_EXPOSE_HEADERS: list[str] = Field(default=[], description="Exposed CORS headers") - CORS_MIDDLEWARE_MAX_AGE: int = Field(default=600, description="Preflight cache duration in seconds") - GZIP_MIDDLEWARE_IS_ENABLED: bool = Field(default=False, description="Whether GZip response compression is enabled") - GZIP_MIDDLEWARE_MINIMUM_SIZE: int = Field( - default=500, - ge=0, - description="Minimum response body size in bytes before compression is applied", - ) - GZIP_MIDDLEWARE_COMPRESSLEVEL: int = Field( - default=6, - ge=1, - le=9, - description="GZip compression level (1=fastest, 9=best compression)", - ) - TRUSTED_HOST_MIDDLEWARE_IS_ENABLED: bool = Field( - default=False, - description="Whether TrustedHost middleware validates the Host header", - ) - TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS: list[str] = Field( - default=[], - description="Allowed hostnames (e.g. example.com, *.example.com)", - ) - TRUSTED_HOST_MIDDLEWARE_WWW_REDIRECT: bool = Field( - default=True, - description="Redirect www hosts to bare domain when allowed", - ) - HTTPS_REDIRECT_MIDDLEWARE_IS_ENABLED: bool = Field( - default=False, - description="Whether HTTP requests are redirected to HTTPS", - ) PROXY_HEADERS: bool = Field( default=True, description="Whether to trust proxy headers", @@ -160,6 +188,161 @@ class FastAPIConfig(BaseModel): description="Swagger UI parameters", ) + CORS: FastAPICorsConfig = Field(default_factory=FastAPICorsConfig, description="CORS middleware settings") + GZIP: FastAPIGzipConfig = Field(default_factory=FastAPIGzipConfig, description="GZip response compression settings") + TRUSTED_HOST: FastAPITrustedHostConfig = Field( + default_factory=FastAPITrustedHostConfig, + description="TrustedHost middleware settings", + ) + HTTPS_REDIRECT: FastAPIHttpsRedirectConfig = Field( + 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.""" diff --git a/archipy/configs/sections/grpc.py b/archipy/configs/sections/grpc.py index 4b1b20772..9bcd0dab9 100644 --- a/archipy/configs/sections/grpc.py +++ b/archipy/configs/sections/grpc.py @@ -3,8 +3,9 @@ import os from typing import Literal, Self -from pydantic import BaseModel, Field, model_validator +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 @@ -46,6 +47,69 @@ class GrpcRateLimitConfig(BaseModel): ) +class GrpcTlsConfig(BaseModel): + """Server TLS and mTLS settings.""" + + model_config = ConfigDict(extra="forbid") + + IS_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``." + ), + ) + CERT_FILE: str | None = Field(default=None, description="Path to the PEM server certificate chain") + KEY_FILE: str | None = Field(default=None, description="Path to the PEM server private key") + CA_FILE: str | None = Field( + default=None, + description="Path to the PEM CA bundle used to verify client certificates (mTLS)", + ) + REQUIRE_CLIENT_AUTH: bool = Field( + default=False, + description="When True, reject clients without a valid certificate. Requires ``TLS_CA_FILE``.", + ) + + @model_validator(mode="after") + def validate_tls_settings(self) -> Self: + """Check that TLS has a certificate and key, and mTLS has a CA.""" + if self.IS_ENABLED and not (self.CERT_FILE and self.KEY_FILE): + raise InvalidArgumentError(argument_name="GRPC.TLS.CERT_FILE") + if self.REQUIRE_CLIENT_AUTH and not self.CA_FILE: + raise InvalidArgumentError(argument_name="GRPC.TLS.CA_FILE") + return self + + +class GrpcStubTlsConfig(BaseModel): + """Client channel TLS and mTLS settings.""" + + model_config = ConfigDict(extra="forbid") + + IS_ENABLED: bool = Field( + default=False, + description="When True, ``AppUtils.create_grpc_channel`` opens a TLS channel instead of a plaintext one.", + ) + CA_FILE: str | None = Field( + default=None, + description="Path to the PEM CA bundle that verifies the server. None uses the gRPC default roots.", + ) + CERT_FILE: str | None = Field( + default=None, + description="Path to the PEM client certificate chain for mTLS. Requires ``STUB_TLS_KEY_FILE``.", + ) + KEY_FILE: str | None = Field( + default=None, + description="Path to the PEM client private key for mTLS. Requires ``STUB_TLS_CERT_FILE``.", + ) + + @model_validator(mode="after") + def validate_stub_tls_settings(self) -> Self: + """Check that the client certificate and key come as a pair.""" + if bool(self.CERT_FILE) != bool(self.KEY_FILE): + raise InvalidArgumentError(argument_name="GRPC.STUB_TLS.KEY_FILE") + return self + + class GrpcConfig(BaseModel): """Configuration settings for gRPC services. @@ -55,7 +119,6 @@ class GrpcConfig(BaseModel): SERVE_PORT: int = Field(default=8100, description="Port to serve gRPC on") SERVE_HOST: str = Field(default="[::]", description="Host to serve gRPC on") # IPv6 equivalent of 0.0.0.0 - THREAD_WORKER_COUNT: int | None = Field( default=None, description=( @@ -68,43 +131,31 @@ class GrpcConfig(BaseModel): default=40, description="Threads per CPU core. Adjust based on thread block to CPU time ratio.", ) - SERVER_OPTIONS_CONFIG_LIST: list[tuple[str, int | str]] = Field( default=[ - # ── Message limits ────────────────────────────────────────────── ("grpc.max_metadata_size", 16 * 1024), # 16KB (default is 8KB) ("grpc.max_message_length", 128 * 1024 * 1024), # 128MB ("grpc.max_receive_message_length", 128 * 1024 * 1024), ("grpc.max_send_message_length", 128 * 1024 * 1024), - # ── Keepalive ─────────────────────────────────────────────────── - # Server rarely initiates pings; 2h is the standard default. ("grpc.keepalive_time_ms", 7_200_000), # 2h ("grpc.keepalive_timeout_ms", 20_000), # 20s ("grpc.keepalive_permit_without_calls", 1), # allow pings on idle connections - # ── Ping enforcement (server-side) ────────────────────────────── - # Must be <= client keepalive_time_ms to avoid ENHANCE_YOUR_CALM. ("grpc.http2.min_recv_ping_interval_without_data_ms", 300_000), # 5min ("grpc.http2.min_ping_interval_without_data_ms", 300_000), # 5min ("grpc.http2.max_pings_without_data", 0), ("grpc.http2.max_ping_strikes", 2), - # ── Connection lifetime ───────────────────────────────────────── ("grpc.max_connection_idle_ms", 600_000), # 10min ("grpc.max_connection_age_ms", 1_800_000), # 30min ("grpc.max_connection_age_grace_ms", 5_000), # 5s graceful drain ], description="Server channel options. Values may be integers or strings.", ) - STUB_OPTIONS_CONFIG_LIST: list[tuple[str, int | str]] = Field( default=[ - # ── Message limits ────────────────────────────────────────────── ("grpc.max_metadata_size", 16 * 1024), # 16KB ("grpc.max_message_length", 128 * 1024 * 1024), # 128MB ("grpc.max_receive_message_length", 128 * 1024 * 1024), ("grpc.max_send_message_length", 128 * 1024 * 1024), - # ── Keepalive ─────────────────────────────────────────────────── - # 5min is the recommended minimum to avoid ENHANCE_YOUR_CALM / GOAWAY. - # Also activates TCP_USER_TIMEOUT for fast dead-connection detection. ("grpc.keepalive_time_ms", 300_000), # 5min ("grpc.keepalive_timeout_ms", 20_000), # 20s ("grpc.keepalive_permit_without_calls", 1), @@ -136,7 +187,6 @@ class GrpcConfig(BaseModel): "strings." ), ) - SERVER_COMPRESSION: Literal["none", "deflate", "gzip"] | None = Field( default=None, description=( @@ -159,58 +209,87 @@ class GrpcConfig(BaseModel): ), ) + TLS: GrpcTlsConfig = Field(default_factory=GrpcTlsConfig, description="Server TLS and mTLS settings") + STUB_TLS: GrpcStubTlsConfig = Field( + default_factory=GrpcStubTlsConfig, + 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_CERT_FILE: str | None = Field(default=None, description="Path to the PEM server certificate chain") - TLS_KEY_FILE: str | None = Field(default=None, description="Path to the PEM server private key") 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 validate_tls_settings(self) -> Self: - """Check that the TLS settings are consistent. - - Returns: - This model, unchanged. - - Raises: - InvalidArgumentError: If TLS is enabled without a certificate and key, mTLS is required without a CA, - or only one of the client certificate and key is set. - """ - if self.TLS_ENABLED and not (self.TLS_CERT_FILE and self.TLS_KEY_FILE): - raise InvalidArgumentError(argument_name="GRPC.TLS_CERT_FILE") - if self.TLS_REQUIRE_CLIENT_AUTH and not self.TLS_CA_FILE: - raise InvalidArgumentError(argument_name="GRPC.TLS_CA_FILE") - if bool(self.STUB_TLS_CERT_FILE) != bool(self.STUB_TLS_KEY_FILE): - raise InvalidArgumentError(argument_name="GRPC.STUB_TLS_KEY_FILE") + 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") diff --git a/archipy/configs/sections/kafka.py b/archipy/configs/sections/kafka.py index 1e141e1fe..22f26256d 100644 --- a/archipy/configs/sections/kafka.py +++ b/archipy/configs/sections/kafka.py @@ -1,10 +1,11 @@ """Kafka configuration.""" import logging -from typing import Literal +from typing import Literal, Self -from pydantic import BaseModel, Field, SecretStr, field_validator, model_validator +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__) @@ -14,22 +15,31 @@ _SECURITY_PROTOCOLS = frozenset({"PLAINTEXT", "SSL", "SASL_PLAINTEXT", "SASL_SSL"}) -class KafkaConfig(BaseModel): - """Configuration settings for Apache Kafka integration. +class KafkaSaslConfig(BaseModel): + """SASL authentication settings.""" - Controls Kafka producer and consumer behavior, including broker connections, - message delivery guarantees, and performance settings. - """ + model_config = ConfigDict(extra="forbid") - BROKERS_LIST: list[str] = Field(default=["localhost:9092"], description="List of Kafka broker addresses") - SECURITY_PROTOCOL: str = Field(default="PLAINTEXT", description="Security protocol for Kafka connections") - SASL_MECHANISM: str | None = Field(default=None, description="SASL mechanism for authentication") + MECHANISM: str | None = Field(default=None, description="SASL mechanism for authentication") USERNAME: str | None = Field(default=None, description="Username for SASL authentication") PASSWORD: SecretStr | None = Field(default=None, description="Password for SASL authentication") - SSL_CA_FILE: str | None = Field(default=None, description="Path to SSL CA certificate file") - SSL_CERT_FILE: str | None = Field(default=None, description="Path to SSL certificate file") - SSL_KEY_FILE: str | None = Field(default=None, description="Path to SSL key file") - SSL_ENDPOINT_IDENTIFICATION_ALGORITHM: Literal["https", "none"] = Field( + + @field_validator("MECHANISM", mode="before") + @classmethod + def normalize_mechanism(cls, value: object) -> object: + """Accept SASL mechanism names in any case or with surrounding spaces.""" + return value.strip().upper() if isinstance(value, str) else value + + +class KafkaSslConfig(BaseModel): + """SSL and TLS file settings.""" + + model_config = ConfigDict(extra="forbid") + + CA_FILE: str | None = Field(default=None, description="Path to SSL CA certificate file") + CERT_FILE: str | None = Field(default=None, description="Path to SSL certificate file") + KEY_FILE: str | None = Field(default=None, description="Path to SSL key file") + ENDPOINT_IDENTIFICATION_ALGORITHM: Literal["https", "none"] = Field( default="https", description=( "Broker hostname verification for SSL connections. 'https' checks the broker certificate against the " @@ -37,6 +47,17 @@ class KafkaConfig(BaseModel): "do not match their address" ), ) + + +class KafkaConfig(BaseModel): + """Configuration settings for Apache Kafka integration. + + Controls Kafka producer and consumer behavior, including broker connections, + message delivery guarantees, and performance settings. + """ + + BROKERS_LIST: list[str] = Field(default=["localhost:9092"], description="List of Kafka broker addresses") + SECURITY_PROTOCOL: str = Field(default="PLAINTEXT", description="Security protocol for Kafka connections") ACKS: Literal["0", "1", "all"] = Field(default="all", description="Acknowledgment mode for producers") AUTO_OFFSET_RESET: Literal["earliest", "latest", "none"] = Field( default="earliest", @@ -142,8 +163,6 @@ class KafkaConfig(BaseModel): ge=0, description="Frequency in milliseconds to send statistics data", ) - - # Async adapter settings (AIOProducer / AIOConsumer) CONSUMER_MAX_WORKERS: int = Field( default=2, ge=1, @@ -157,6 +176,76 @@ class KafkaConfig(BaseModel): ) PRODUCER_MAX_WORKERS: int = Field(default=4, ge=1, description="Thread pool workers for AIOProducer") + 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") @classmethod def normalize_security_names(cls, value: object) -> object: @@ -204,24 +293,26 @@ def validate_security_settings(self) -> KafkaConfig: ValueError: If SASL authentication is incomplete. """ if self.SECURITY_PROTOCOL in ["SASL_PLAINTEXT", "SASL_SSL"]: - if not self.SASL_MECHANISM: + if not self.SASL.MECHANISM: raise ConfigurationError(operation="kafka_validate", reason="sasl_auth_incomplete") - if self.SASL_MECHANISM in _SASL_MECHANISMS_WITH_CREDENTIALS and not (self.USERNAME and self.PASSWORD): + if self.SASL.MECHANISM in _SASL_MECHANISMS_WITH_CREDENTIALS and not ( + self.SASL.USERNAME and self.SASL.PASSWORD + ): raise ConfigurationError(operation="kafka_validate", reason="sasl_auth_incomplete") - if self.SECURITY_PROTOCOL == "SASL_PLAINTEXT" and self.SASL_MECHANISM == "PLAIN": + if self.SECURITY_PROTOCOL == "SASL_PLAINTEXT" and self.SASL.MECHANISM == "PLAIN": logger.warning( "SASL PLAIN over SASL_PLAINTEXT sends the username and password unencrypted; use SASL_SSL.", ) if self.SECURITY_PROTOCOL not in ("SASL_PLAINTEXT", "SASL_SSL") and ( - self.USERNAME or self.PASSWORD or self.SASL_MECHANISM + self.SASL.USERNAME or self.SASL.PASSWORD or self.SASL.MECHANISM ): logger.warning( "SASL credentials or a SASL mechanism are set but SECURITY_PROTOCOL is %s; they are ignored.", self.SECURITY_PROTOCOL, ) - if self.SECURITY_PROTOCOL == "SSL" and not (self.SSL_CA_FILE or self.SSL_CERT_FILE or self.SSL_KEY_FILE): + if self.SECURITY_PROTOCOL == "SSL" and not (self.SSL.CA_FILE or self.SSL.CERT_FILE or self.SSL.KEY_FILE): logger.warning("SSL enabled but no SSL certificates provided; this may cause connection issues.") - if self.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM == "none": + if self.SSL.ENDPOINT_IDENTIFICATION_ALGORITHM == "none": logger.warning( "Kafka broker hostname verification is disabled (SSL_ENDPOINT_IDENTIFICATION_ALGORITHM='none'); " "SSL connections will not check that the broker certificate matches its hostname.", diff --git a/archipy/configs/sections/keycloak.py b/archipy/configs/sections/keycloak.py index f4a6ac2ff..8702af1fe 100644 --- a/archipy/configs/sections/keycloak.py +++ b/archipy/configs/sections/keycloak.py @@ -1,27 +1,35 @@ """Keycloak configuration.""" -from pydantic import BaseModel, Field, SecretStr, field_validator, model_validator +from typing import Self + +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"}) -class KeycloakConfig(BaseModel): - """Configuration settings for Keycloak integration. +class KeycloakAdminConfig(BaseModel): + """Admin mode settings.""" - Controls connection parameters and authentication settings for the Keycloak - identity and access management service. - """ + model_config = ConfigDict(extra="forbid") - SERVER_URL: str | None = None - CLIENT_ID: str | None = None + IS_ENABLED: bool = False + USERNAME: str | None = None + PASSWORD: SecretStr | None = Field(default=None) REALM_NAME: str = "master" - CLIENT_SECRET_KEY: SecretStr | None = Field(default=None) + + +class KeycloakTlsConfig(BaseModel): + """TLS and client certificate settings.""" + + model_config = ConfigDict(extra="forbid") + 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", ) - TIMEOUT: float = Field(default=10, gt=0, description="Request timeout in seconds (fractions allowed)") 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", @@ -30,6 +38,70 @@ class KeycloakConfig(BaseModel): default=None, description="Path of the private key matching CLIENT_CERT_FILE", ) + + @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 + + @model_validator(mode="after") + def _check_client_key_has_cert(self) -> Self: + if self.CLIENT_KEY_FILE and not self.CLIENT_CERT_FILE: + msg = "CLIENT_KEY_FILE requires CLIENT_CERT_FILE" + raise ValueError(msg) + return self + + +class KeycloakTokenValidationConfig(BaseModel): + """Local token validation settings.""" + + model_config = ConfigDict(extra="forbid") + + LEEWAY_SECONDS: int = Field( + default=0, + ge=0, + description="Clock-skew tolerance in seconds when validating token expiry (python-keycloak defaults to 60)", + ) + 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." + ), + ) + 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." + ), + ) + REQUIRE_ORGANIZATION: bool = Field( + default=False, + description="Require a selected organization in FastAPI and gRPC guards unless the guard overrides this value", + ) + + +class KeycloakConfig(BaseModel): + """Configuration settings for Keycloak integration. + + Controls connection parameters and authentication settings for the Keycloak + identity and access management service. + """ + + SERVER_URL: str | None = None + CLIENT_ID: str | None = None + REALM_NAME: str = "master" + CLIENT_SECRET_KEY: SecretStr | None = Field(default=None) + TIMEOUT: float = Field(default=10, gt=0, description="Request timeout in seconds (fractions allowed)") MAX_RETRIES: int = Field(default=1, ge=0, description="Total times an HTTP request to Keycloak is retried") POOL_MAXSIZE: int | None = Field(default=None, ge=1, description="Maximum connections kept in the pool") PROXIES: dict[str, str] | None = Field( @@ -40,10 +112,59 @@ class KeycloakConfig(BaseModel): default=None, description="Extra HTTP headers sent with every request to Keycloak", ) + REMOTE_CACHE_TTL_SECONDS: float = Field( + default=0.0, + ge=0, + description=( + "Seconds the Keycloak auth decorators/dependencies cache UserInfo and UMA permission lookups per access " + "token. 0 disables the cache. A revoked token or changed permission stays accepted for up to this long, " + "so keep it short (a few seconds)." + ), + ) + + ADMIN: KeycloakAdminConfig = Field(default_factory=KeycloakAdminConfig, description="Admin mode settings") + TLS: KeycloakTlsConfig = Field(default_factory=KeycloakTlsConfig, description="TLS and client certificate settings") + TOKEN_VALIDATION: KeycloakTokenValidationConfig = Field( + 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, @@ -52,6 +173,7 @@ class KeycloakConfig(BaseModel): "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, @@ -59,24 +181,51 @@ class KeycloakConfig(BaseModel): "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", - ) - REMOTE_CACHE_TTL_SECONDS: float = Field( - default=0.0, - ge=0, - description=( - "Seconds the Keycloak auth decorators/dependencies cache UserInfo and UMA permission lookups per access " - "token. 0 disables the cache. A revoked token or changed permission stays accepted for up to this long, " - "so keep it short (a few seconds)." + deprecated=deprecated_flat_message( + "KEYCLOAK", + "REQUIRE_ORGANIZATION", + "TOKEN_VALIDATION", + "REQUIRE_ORGANIZATION", ), ) - IS_ADMIN_MODE_ENABLED: bool = False - ADMIN_USERNAME: str | None = None - ADMIN_PASSWORD: SecretStr | None = Field(default=None) - ADMIN_REALM_NAME: str = "master" + + @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 @@ -89,10 +238,3 @@ def _parse_verify_ssl(cls, value: object) -> object: if lowered in _FALSE_WORDS: return False return value - - @model_validator(mode="after") - def _check_client_key_has_cert(self) -> KeycloakConfig: - if self.CLIENT_KEY_FILE and not self.CLIENT_CERT_FILE: - msg = "CLIENT_KEY_FILE requires CLIENT_CERT_FILE" - raise ValueError(msg) - return self diff --git a/archipy/configs/sections/otel.py b/archipy/configs/sections/otel.py index 6079c404b..afa18aea4 100644 --- a/archipy/configs/sections/otel.py +++ b/archipy/configs/sections/otel.py @@ -5,8 +5,9 @@ from itertools import pairwise from typing import Literal, Self -from pydantic import BaseModel, Field, HttpUrl, model_validator +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__) @@ -44,6 +45,40 @@ class OtelSampler(StrEnum): PARENTBASED_TRACEIDRATIO = "parentbased_traceidratio" +class OtelPushgatewayConfig(BaseModel): + """Prometheus Pushgateway settings (METRICS_EXPORTER=pushgateway).""" + + model_config = ConfigDict(extra="forbid") + + URL: str | None = Field( + default=None, + description="Prometheus Pushgateway base URL when METRICS_EXPORTER=pushgateway (e.g. http://host:9091)", + ) + JOB: str | None = Field( + default=None, + description="Pushgateway job label (defaults to SERVICE_NAME when unset)", + ) + INTERVAL_SECONDS: int = Field( + default=60, + ge=1, + description="Interval between Pushgateway pushes when METRICS_EXPORTER=pushgateway", + ) + TIMEOUT_SECONDS: float = Field( + default=10.0, + gt=0, + description="HTTP timeout in seconds for Pushgateway push/delete calls", + ) + GROUPING_KEY: dict[str, str] = Field( + default_factory=dict, + max_length=16, + description="Extra Pushgateway grouping labels (instance, component, ...)", + ) + DELETE_ON_SHUTDOWN: bool = Field( + default=True, + description="Delete the Pushgateway grouping key on graceful OTel shutdown", + ) + + class OpentelemetryConfig(BaseModel): """Configuration settings for OpenTelemetry observability. @@ -330,33 +365,6 @@ class OpentelemetryConfig(BaseModel): le=65535, description="Bind port for the metrics pull scrape server (/metrics)", ) - METRICS_PUSHGATEWAY_URL: str | None = Field( - default=None, - description="Prometheus Pushgateway base URL when METRICS_EXPORTER=pushgateway (e.g. http://host:9091)", - ) - METRICS_PUSHGATEWAY_JOB: str | None = Field( - default=None, - description="Pushgateway job label (defaults to SERVICE_NAME when unset)", - ) - METRICS_PUSHGATEWAY_INTERVAL_SECONDS: int = Field( - default=60, - ge=1, - description="Interval between Pushgateway pushes when METRICS_EXPORTER=pushgateway", - ) - METRICS_PUSHGATEWAY_TIMEOUT_SECONDS: float = Field( - default=10.0, - gt=0, - description="HTTP timeout in seconds for Pushgateway push/delete calls", - ) - METRICS_PUSHGATEWAY_GROUPING_KEY: dict[str, str] = Field( - default_factory=dict, - max_length=16, - description="Extra Pushgateway grouping labels (instance, component, ...)", - ) - METRICS_PUSHGATEWAY_DELETE_ON_SHUTDOWN: bool = Field( - default=True, - description="Delete the Pushgateway grouping key on graceful OTel shutdown", - ) SYSTEM_METRICS_ENABLED: bool = Field( default=True, description="Instrument process/system metrics when METRICS_ENABLED is true", @@ -400,6 +408,78 @@ class OpentelemetryConfig(BaseModel): ), ) + PUSHGATEWAY: OtelPushgatewayConfig = Field( + default_factory=OtelPushgatewayConfig, + 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. @@ -455,7 +535,7 @@ def validate_otel_config(self) -> Self: if ( self.METRICS_ENABLED and self.METRICS_EXPORTER == OtelMetricsExporter.PUSHGATEWAY - and not (self.METRICS_PUSHGATEWAY_URL and self.METRICS_PUSHGATEWAY_URL.strip()) + and not (self.PUSHGATEWAY.URL and self.PUSHGATEWAY.URL.strip()) ): raise ConfigurationError( operation="otel", diff --git a/archipy/configs/sections/redis.py b/archipy/configs/sections/redis.py index 42930e891..a68ebc63d 100644 --- a/archipy/configs/sections/redis.py +++ b/archipy/configs/sections/redis.py @@ -4,8 +4,9 @@ from enum import StrEnum from typing import Literal, Self -from pydantic import BaseModel, Field, SecretStr, model_validator +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__) @@ -19,35 +20,76 @@ class RedisMode(StrEnum): CLUSTER = "CLUSTER" -class RedisConfig(BaseModel): - """Configuration settings for Redis cache integration. +class RedisClusterConfig(BaseModel): + """Cluster mode settings.""" - Supports standalone, sentinel, and cluster deployments. - """ + model_config = ConfigDict(extra="forbid") - # Deployment mode - MODE: RedisMode = Field(default=RedisMode.STANDALONE, description="Redis deployment mode") + NODES: list[str] = Field(default=[], description="List of cluster node addresses (host:port)") + REQUIRE_FULL_COVERAGE: bool = Field(default=True, description="Require full cluster coverage") + READ_FROM_REPLICAS: bool = Field(default=True, description="Allow reading from replica nodes") - # Standalone mode settings (existing) - MASTER_HOST: str | None = Field(default="localhost", description="Redis master host (standalone/sentinel)") - SLAVE_HOST: str | None = Field(default=None, description="Redis slave host (standalone)") - # Cluster mode settings - CLUSTER_NODES: list[str] = Field(default=[], description="List of cluster node addresses (host:port)") - CLUSTER_REQUIRE_FULL_COVERAGE: bool = Field(default=True, description="Require full cluster coverage") - CLUSTER_READ_FROM_REPLICAS: bool = Field(default=True, description="Allow reading from replica nodes") +class RedisSentinelConfig(BaseModel): + """Sentinel mode settings.""" - # Sentinel mode settings - SENTINEL_NODES: list[str] = Field(default=[], description="List of sentinel addresses (host:port)") - SENTINEL_SERVICE_NAME: str | None = Field(default=None, description="Master service name for sentinel") - SENTINEL_SOCKET_TIMEOUT: float = Field(default=0.1, description="Sentinel socket timeout") - SENTINEL_PASSWORD: SecretStr | None = Field( + model_config = ConfigDict(extra="forbid") + + NODES: list[str] = Field(default=[], description="List of sentinel addresses (host:port)") + SERVICE_NAME: str | None = Field(default=None, description="Master service name for sentinel") + SOCKET_TIMEOUT: float = Field(default=0.1, description="Sentinel socket timeout") + PASSWORD: SecretStr | None = Field( default=None, description="Password for sentinel nodes (if distinct)", ) - SENTINEL_USERNAME: str | None = Field(default=None, description="ACL username for sentinel nodes (if distinct)") + USERNAME: str | None = Field(default=None, description="ACL username for sentinel nodes (if distinct)") + + +class RedisTlsConfig(BaseModel): + """TLS settings of the Redis connection.""" + + model_config = ConfigDict(extra="forbid") + + IS_ENABLED: bool = Field(default=False, description="Connect to Redis over TLS") + CA_CERTS: str | None = Field(default=None, description="Path to the CA bundle used to verify the server") + CERTFILE: str | None = Field(default=None, description="Path to the client certificate (mTLS)") + KEYFILE: str | None = Field(default=None, description="Path to the client private key (mTLS)") + CHECK_HOSTNAME: bool = Field(default=True, description="Verify the server hostname against its certificate") + + @model_validator(mode="after") + def validate_tls_files(self) -> Self: + """Validate that the client certificate and key come together and need ``IS_ENABLED``.""" + if bool(self.CERTFILE) != bool(self.KEYFILE): + raise ConfigurationError(operation="redis", reason="ssl_certfile_and_keyfile_must_be_set_together") + if not self.IS_ENABLED and (self.CA_CERTS or self.CERTFILE): + raise ConfigurationError(operation="redis", reason="ssl_options_require_ssl_enabled") + return self + + +class RedisRetryConfig(BaseModel): + """Retry and backoff settings.""" + + model_config = ConfigDict(extra="forbid") - # Common settings + ATTEMPTS: int | None = Field( + default=None, + ge=0, + description="Retries per command with exponential backoff on connection errors; None keeps redis-py defaults", + ) + BACKOFF_BASE: float = Field(default=0.008, gt=0, description="Exponential backoff base delay in seconds") + BACKOFF_CAP: float = Field(default=0.512, gt=0, description="Exponential backoff maximum delay in seconds") + ON_TIMEOUT: bool = Field(default=False, description="Also retry commands that hit a socket timeout") + + +class RedisConfig(BaseModel): + """Configuration settings for Redis cache integration. + + Supports standalone, sentinel, and cluster deployments. + """ + + MODE: RedisMode = Field(default=RedisMode.STANDALONE, description="Redis deployment mode") + MASTER_HOST: str | None = Field(default="localhost", description="Redis master host (standalone/sentinel)") + SLAVE_HOST: str | None = Field(default=None, description="Redis slave host (standalone)") PORT: int = Field(default=6379, description="Default Redis server port") DATABASE: int = Field(default=0, description="Redis database number (standalone and sentinel; ignored in cluster)") USERNAME: str | None = Field(default=None, description="Redis ACL username (Redis 6+); None uses the default user") @@ -55,45 +97,162 @@ class RedisConfig(BaseModel): DECODE_RESPONSES: Literal[True] = Field(default=True, description="Whether to decode responses") PROTOCOL: Literal[2, 3] = Field(default=3, description="RESP protocol version (2 or 3)") HEALTH_CHECK_INTERVAL: int = Field(default=10, description="Health check interval in seconds") - - # TLS settings - SSL: bool = Field(default=False, description="Connect to Redis over TLS") - SSL_CA_CERTS: str | None = Field(default=None, description="Path to the CA bundle used to verify the server") - SSL_CERTFILE: str | None = Field(default=None, description="Path to the client certificate (mTLS)") - SSL_KEYFILE: str | None = Field(default=None, description="Path to the client private key (mTLS)") - SSL_CHECK_HOSTNAME: bool = Field(default=True, description="Verify the server hostname against its certificate") - - # Resilience and observability (unset keeps the redis-py defaults) - RETRY_ATTEMPTS: int | None = Field( - default=None, - ge=0, - description="Retries per command with exponential backoff on connection errors; None keeps redis-py defaults", - ) - RETRY_BACKOFF_BASE: float = Field(default=0.008, gt=0, description="Exponential backoff base delay in seconds") - RETRY_BACKOFF_CAP: float = Field(default=0.512, gt=0, description="Exponential backoff maximum delay in seconds") - RETRY_ON_TIMEOUT: bool = Field(default=False, description="Also retry commands that hit a socket timeout") SOCKET_KEEPALIVE: bool | None = Field( default=None, description="TCP keepalive to detect dead peers behind NAT; None keeps the redis-py default", ) CLIENT_NAME: str | None = Field(default=None, description="Connection name shown in CLIENT LIST") - - # Connection pooling MAX_CONNECTIONS: int = Field(default=50, description="Maximum connections per node") SOCKET_CONNECT_TIMEOUT: float = Field(default=5.0, description="Socket connection timeout") SOCKET_TIMEOUT: float = Field(default=5.0, description="Socket operation timeout") + CLUSTER: RedisClusterConfig = Field(default_factory=RedisClusterConfig, description="Cluster mode settings") + SENTINEL: RedisSentinelConfig = Field(default_factory=RedisSentinelConfig, description="Sentinel mode settings") + 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 validate_tls_configuration(self) -> Self: - """Validate TLS settings.""" - if bool(self.SSL_CERTFILE) != bool(self.SSL_KEYFILE): - raise ConfigurationError(operation="redis", reason="ssl_certfile_and_keyfile_must_be_set_together") - if not self.SSL and (self.SSL_CA_CERTS or self.SSL_CERTFILE): - raise ConfigurationError(operation="redis", reason="ssl_options_require_ssl_enabled") - if not self.SSL and (self.PASSWORD or self.SENTINEL_PASSWORD): - logger.warning("Redis credentials are configured without SSL; they are sent in clear text") - if self.SSL and not self.SSL_CHECK_HOSTNAME: - logger.warning("Redis SSL_CHECK_HOSTNAME is disabled; the server identity is not verified") + 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 @@ -107,20 +266,29 @@ def _validate_node_address(node: str, *, port_required: bool) -> None: def validate_mode_configuration(self) -> Self: """Validate mode-specific configuration.""" if self.MODE == RedisMode.CLUSTER: - if not self.CLUSTER_NODES: + if not self.CLUSTER.NODES: raise ConfigurationError(operation="redis", reason="cluster_nodes_required") - for node in self.CLUSTER_NODES: + for node in self.CLUSTER.NODES: self._validate_node_address(node, port_required=False) if self.DATABASE != 0: logger.warning("DATABASE setting ignored in cluster mode") elif self.MODE == RedisMode.SENTINEL: - if not self.SENTINEL_NODES or not self.SENTINEL_SERVICE_NAME: + if not self.SENTINEL.NODES or not self.SENTINEL.SERVICE_NAME: raise ConfigurationError(operation="redis", reason="sentinel_config_incomplete") - for node in self.SENTINEL_NODES: + for node in self.SENTINEL.NODES: self._validate_node_address(node, port_required=True) elif self.MODE == RedisMode.STANDALONE and not self.MASTER_HOST: raise ConfigurationError(operation="redis", reason="master_host_required") return self + + @model_validator(mode="after") + def warn_insecure_tls(self) -> Self: + """Warn when credentials travel without TLS or the server identity is not verified.""" + if not self.TLS.IS_ENABLED and (self.PASSWORD or self.SENTINEL.PASSWORD): + logger.warning("Redis credentials are configured without SSL; they are sent in clear text") + if self.TLS.IS_ENABLED and not self.TLS.CHECK_HOSTNAME: + logger.warning("Redis TLS.CHECK_HOSTNAME is disabled; the server identity is not verified") + return self diff --git a/archipy/configs/sections/scylladb.py b/archipy/configs/sections/scylladb.py index 45b2e4e8b..a25364814 100644 --- a/archipy/configs/sections/scylladb.py +++ b/archipy/configs/sections/scylladb.py @@ -3,8 +3,9 @@ import ssl from typing import Literal, Self -from pydantic import BaseModel, Field, SecretStr, model_validator +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 = ( @@ -12,6 +13,247 @@ ) +class ScyllaTlsConfig(BaseModel): + """TLS settings of the cluster connection.""" + + model_config = ConfigDict(extra="forbid") + + IS_ENABLED: bool = Field( + default=False, + description=( + "Encrypt the connection to the cluster with TLS. When disabled (default) credentials and data " + "travel in plain text." + ), + ) + CA_FILE: str | None = Field( + default=None, + description="Path to the CA bundle used to verify the server certificate (system CAs when unset)", + ) + CERT_FILE: str | None = Field( + default=None, + description="Path to the client certificate for mutual TLS (requires TLS_KEY_FILE)", + ) + KEY_FILE: str | None = Field( + default=None, + description="Path to the client private key for mutual TLS (requires TLS_CERT_FILE)", + ) + 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" + ), + ) + CHECK_HOSTNAME: bool = Field( + default=True, + description="Check that the server certificate matches the contact point host name", + ) + SERVER_NAME: str | None = Field( + default=None, + description="Host name to match the server certificate against, when it differs from the contact point address", + ) + 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" + ), + ) + + @model_validator(mode="after") + def validate_tls(self) -> Self: + """Validate TLS settings: files need IS_ENABLED, and the client cert and key come as a pair.""" + if (self.CERT_FILE is None) != (self.KEY_FILE is None): + raise InvalidArgumentError( + argument_name="tls", + additional_data={"error": "TLS_CERT_FILE and TLS_KEY_FILE must be provided together"}, + ) + if not self.IS_ENABLED and (self.CA_FILE or self.CERT_FILE): + raise InvalidArgumentError( + argument_name="tls", + additional_data={"error": "TLS_ENABLED must be true when TLS certificate files are set"}, + ) + return self + + def build_ssl_context(self) -> ssl.SSLContext | None: + """Build the TLS context for the cluster connection. + + Returns: + ssl.SSLContext | None: The context for ``Cluster(ssl_context=)``, or None when TLS is disabled. + """ + if not self.IS_ENABLED: + return None + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + if self.VERIFY_MODE == "CERT_NONE": + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + else: + context.check_hostname = self.CHECK_HOSTNAME + context.verify_mode = ssl.CERT_REQUIRED + if self.CA_FILE: + context.load_verify_locations(cafile=self.CA_FILE) + else: + context.load_default_certs() + if self.CERT_FILE and self.KEY_FILE: + context.load_cert_chain(certfile=self.CERT_FILE, keyfile=self.KEY_FILE) + return context + + +class ScyllaRetryConfig(BaseModel): + """Retry policy settings.""" + + model_config = ConfigDict(extra="forbid") + + 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)", + ) + MAX_NUM_RETRIES: float = Field( + default=3.0, + ge=0.0, + description="Maximum number of retries for ExponentialBackoffRetryPolicy", + ) + MIN_INTERVAL: float = Field( + default=0.1, + ge=0.0, + description="Minimum interval in seconds between retries for ExponentialBackoffRetryPolicy", + ) + MAX_INTERVAL: float = Field( + default=10.0, + ge=0.0, + description="Maximum interval in seconds between retries for ExponentialBackoffRetryPolicy", + ) + + +class ScyllaReconnectionConfig(BaseModel): + """Reconnection policy settings.""" + + model_config = ConfigDict(extra="forbid") + + 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)" + ), + ) + BASE_DELAY: float = Field( + default=1.0, + gt=0.0, + description="Seconds between reconnection attempts (first delay for EXPONENTIAL)", + ) + MAX_DELAY: float = Field( + default=600.0, + gt=0.0, + description="Upper bound in seconds of the delay between attempts for EXPONENTIAL", + ) + MAX_ATTEMPTS: int | None = Field( + default=None, + ge=1, + description="Stop reconnecting to a host after this many attempts (unlimited when unset)", + ) + + @model_validator(mode="after") + def validate_reconnection(self) -> Self: + """Validate that the exponential reconnection delay does not shrink below its base.""" + if self.POLICY == "EXPONENTIAL" and self.BASE_DELAY > self.MAX_DELAY: + raise InvalidArgumentError( + argument_name="reconnection", + additional_data={"error": "RECONNECTION_BASE_DELAY cannot exceed RECONNECTION_MAX_DELAY"}, + ) + return self + + +class ScyllaSpeculativeExecutionConfig(BaseModel): + """Speculative execution settings.""" + + model_config = ConfigDict(extra="forbid") + + 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" + ), + ) + MAX_ATTEMPTS: int = Field( + default=2, + ge=1, + description="Extra executions allowed per query when SPECULATIVE_EXECUTION_DELAY is set", + ) + + +class ScyllaPreparedCacheConfig(BaseModel): + """Prepared statement cache settings.""" + + model_config = ConfigDict(extra="forbid") + + IS_ENABLED: bool = Field( + default=True, + description="Enable prepared statement caching", + ) + SIZE: int = Field( + default=100, + ge=1, + description="Maximum cached prepared statements", + ) + TTL_SECONDS: int = Field( + default=3600, + ge=1, + description="TTL for prepared statement cache in seconds (1 hour)", + ) + + +class ScyllaHeartbeatConfig(BaseModel): + """Idle heartbeat settings.""" + + model_config = ConfigDict(extra="forbid") + + IDLE_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)" + ), + ) + IDLE_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)", + ) + + +class ScyllaReplicationConfig(BaseModel): + """Keyspace replication settings.""" + + model_config = ConfigDict(extra="forbid") + + STRATEGY: Literal["SimpleStrategy", "NetworkTopologyStrategy"] = Field( + default="NetworkTopologyStrategy", + description="Replication strategy for keyspace creation", + ) + CONFIG: dict[str, int] | None = Field( + default={"datacenter1": 1}, + description="Replication configuration (e.g., {'dc1': 3, 'dc2': 2} for NetworkTopologyStrategy)", + ) + + @model_validator(mode="after") + def validate_replication_config(self) -> Self: + """Validate replication configuration.""" + if self.STRATEGY == "NetworkTopologyStrategy" and not self.CONFIG: + raise InvalidArgumentError( + argument_name="replication_config", + additional_data={"error": "REPLICATION_CONFIG required for NetworkTopologyStrategy"}, + ) + return self + + class ScyllaDBConfig(BaseModel): """Configuration settings for ScyllaDB/Cassandra connections and operations. @@ -91,41 +333,6 @@ class ScyllaDBConfig(BaseModel): "connections through Docker's port mapping." ), ) - 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)", - ) - RETRY_MAX_NUM_RETRIES: float = Field( - default=3.0, - ge=0.0, - description="Maximum number of retries for ExponentialBackoffRetryPolicy", - ) - RETRY_MIN_INTERVAL: float = Field( - default=0.1, - ge=0.0, - description="Minimum interval in seconds between retries for ExponentialBackoffRetryPolicy", - ) - RETRY_MAX_INTERVAL: float = Field( - default=10.0, - ge=0.0, - description="Maximum interval in seconds between retries for ExponentialBackoffRetryPolicy", - ) - ENABLE_PREPARED_STATEMENT_CACHE: bool = Field( - default=True, - description="Enable prepared statement caching", - ) - PREPARED_STATEMENT_CACHE_SIZE: int = Field( - default=100, - ge=1, - description="Maximum cached prepared statements", - ) - PREPARED_STATEMENT_CACHE_TTL_SECONDS: int = Field( - default=3600, - ge=1, - description="TTL for prepared statement cache in seconds (1 hour)", - ) HEALTH_CHECK_TIMEOUT: int = Field( default=5, ge=1, @@ -135,86 +342,89 @@ class ScyllaDBConfig(BaseModel): default=False, description="Enable connection pool monitoring and metrics", ) - - # Resilience Configuration (unset keeps the driver default) - 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)" - ), - ) - 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)", - ) CONTROL_CONNECTION_TIMEOUT: float | None = Field( default=None, gt=0.0, description="Seconds the control connection waits for topology and schema queries (driver default 2)", ) - RECONNECTION_POLICY: Literal["CONSTANT", "EXPONENTIAL"] | None = Field( + SERIAL_CONSISTENCY_LEVEL: Literal["SERIAL", "LOCAL_SERIAL"] | 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)" - ), + description="Consistency level of the Paxos phase of lightweight transactions (IF clauses); unset keeps SERIAL", ) - RECONNECTION_BASE_DELAY: float = Field( - default=1.0, - gt=0.0, - description="Seconds between reconnection attempts (first delay for EXPONENTIAL)", + 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, ) - RECONNECTION_MAX_DELAY: float = Field( - default=600.0, - gt=0.0, - description="Upper bound in seconds of the delay between attempts for EXPONENTIAL", + MIN_CONNECTIONS_PER_HOST: int = Field( + default=1, + ge=1, + description="Minimum connections per host", + deprecated=_NO_POOL_SIZING, ) - RECONNECTION_MAX_ATTEMPTS: int | None = Field( - default=None, + CORE_CONNECTIONS_PER_HOST: int = Field( + default=1, ge=1, - description="Stop reconnecting to a host after this many attempts (unlimited when unset)", + description="Core connections per host to maintain", + deprecated=_NO_POOL_SIZING, ) - SERIAL_CONSISTENCY_LEVEL: Literal["SERIAL", "LOCAL_SERIAL"] | None = Field( - default=None, - description="Consistency level of the Paxos phase of lightweight transactions (IF clauses); unset keeps SERIAL", + MAX_REQUESTS_PER_CONNECTION: int = Field( + default=100, + ge=1, + description="Maximum concurrent requests per connection", + deprecated=_NO_POOL_SIZING, ) - SPECULATIVE_EXECUTION_DELAY: float | None = Field( + LOCAL_DC: str | 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" - ), + description="Local datacenter name for datacenter-aware routing", ) - SPECULATIVE_EXECUTION_MAX_ATTEMPTS: int = Field( - default=2, - ge=1, - description="Extra executions allowed per query when SPECULATIVE_EXECUTION_DELAY is set", + + TLS: ScyllaTlsConfig = Field(default_factory=ScyllaTlsConfig, description="TLS settings of the cluster connection") + RETRY: ScyllaRetryConfig = Field(default_factory=ScyllaRetryConfig, description="Retry policy settings") + RECONNECTION: ScyllaReconnectionConfig = Field( + default_factory=ScyllaReconnectionConfig, + description="Reconnection policy settings", + ) + SPECULATIVE_EXECUTION: ScyllaSpeculativeExecutionConfig = Field( + default_factory=ScyllaSpeculativeExecutionConfig, + description="Speculative execution settings", + ) + PREPARED_CACHE: ScyllaPreparedCacheConfig = Field( + default_factory=ScyllaPreparedCacheConfig, + description="Prepared statement cache settings", + ) + HEARTBEAT: ScyllaHeartbeatConfig = Field( + default_factory=ScyllaHeartbeatConfig, + description="Idle heartbeat settings", + ) + REPLICATION: ScyllaReplicationConfig = Field( + default_factory=ScyllaReplicationConfig, + description="Keyspace replication settings", ) - # TLS Configuration 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", @@ -222,14 +432,17 @@ class ScyllaDBConfig(BaseModel): "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, @@ -237,46 +450,131 @@ class ScyllaDBConfig(BaseModel): "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"), ) - - # Connection Pool Configuration - 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, + 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"), ) - MIN_CONNECTIONS_PER_HOST: int = Field( - default=1, + 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="Minimum connections per host", - deprecated=_NO_POOL_SIZING, + description="Stop reconnecting to a host after this many attempts (unlimited when unset)", + deprecated=deprecated_flat_message("SCYLLADB", "RECONNECTION_MAX_ATTEMPTS", "RECONNECTION", "MAX_ATTEMPTS"), ) - CORE_CONNECTIONS_PER_HOST: int = Field( - default=1, + 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="Core connections per host to maintain", - deprecated=_NO_POOL_SIZING, + 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", + ), ) - MAX_REQUESTS_PER_CONNECTION: int = Field( + 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 concurrent requests per connection", - deprecated=_NO_POOL_SIZING, + description="Maximum cached prepared statements", + deprecated=deprecated_flat_message("SCYLLADB", "PREPARED_STATEMENT_CACHE_SIZE", "PREPARED_CACHE", "SIZE"), ) - - # Datacenter Configuration - LOCAL_DC: str | None = Field( + 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, - description="Local datacenter name for datacenter-aware routing", + 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") @@ -316,60 +614,75 @@ def validate_connection_pool(self) -> Self: return self @model_validator(mode="after") - def validate_reconnection(self) -> Self: - """Validate that the exponential reconnection delay does not shrink below its base.""" - if self.RECONNECTION_POLICY == "EXPONENTIAL" and self.RECONNECTION_BASE_DELAY > self.RECONNECTION_MAX_DELAY: - raise InvalidArgumentError( - argument_name="reconnection", - additional_data={"error": "RECONNECTION_BASE_DELAY cannot exceed RECONNECTION_MAX_DELAY"}, - ) - return self - - @model_validator(mode="after") - def validate_replication_config(self) -> Self: - """Validate replication configuration.""" - if self.REPLICATION_STRATEGY == "NetworkTopologyStrategy" and not self.REPLICATION_CONFIG: - raise InvalidArgumentError( - argument_name="replication_config", - additional_data={"error": "REPLICATION_CONFIG required for NetworkTopologyStrategy"}, - ) - return self - - @model_validator(mode="after") - def validate_tls(self) -> Self: - """Validate TLS settings: files need TLS_ENABLED, and the client cert and key come as a pair.""" - if (self.TLS_CERT_FILE is None) != (self.TLS_KEY_FILE is None): - raise InvalidArgumentError( - argument_name="tls", - additional_data={"error": "TLS_CERT_FILE and TLS_KEY_FILE must be provided together"}, - ) - if not self.TLS_ENABLED and (self.TLS_CA_FILE or self.TLS_CERT_FILE): - raise InvalidArgumentError( - argument_name="tls", - additional_data={"error": "TLS_ENABLED must be true when TLS certificate files are set"}, - ) + 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. - - Returns: - ssl.SSLContext | None: The context for ``Cluster(ssl_context=)``, or None when TLS is disabled. - """ - if not self.TLS_ENABLED: - return None - context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) - context.minimum_version = ssl.TLSVersion.TLSv1_2 - if self.TLS_VERIFY_MODE == "CERT_NONE": - context.check_hostname = False - context.verify_mode = ssl.CERT_NONE - else: - context.check_hostname = self.TLS_CHECK_HOSTNAME - context.verify_mode = ssl.CERT_REQUIRED - if self.TLS_CA_FILE: - context.load_verify_locations(cafile=self.TLS_CA_FILE) - else: - context.load_default_certs() - if self.TLS_CERT_FILE and self.TLS_KEY_FILE: - context.load_cert_chain(certfile=self.TLS_CERT_FILE, keyfile=self.TLS_KEY_FILE) - return context + """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 eef01c32c..013a2aff4 100644 --- a/archipy/configs/sections/sqlalchemy.py +++ b/archipy/configs/sections/sqlalchemy.py @@ -7,30 +7,54 @@ 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 -class SQLAlchemyConfig(BaseModel): - """Configuration settings for SQLAlchemy ORM. +class SQLAlchemyPoolConfig(BaseModel): + """Connection pool settings.""" - Controls database connection parameters, pooling behavior, and query execution settings. - """ + model_config = ConfigDict(extra="forbid") - # Validation errors must not echo input values: they can contain the DSN and the password - model_config = ConfigDict(hide_input_in_errors=True) + MAX_OVERFLOW: int = Field(default=1, description="Maximum number of connections to allow in pool overflow") + PRE_PING: bool = Field(default=True, description="Whether to ping connections before use") + RECYCLE_SECONDS: int = Field(default=10 * 60, description="Number of seconds between connection recycling") + RESET_ON_RETURN: str = Field( + default="rollback", + description="Action to take when returning connections to pool", + ) + SIZE: int = Field(default=20, description="Number of connections to keep open in the pool") + TIMEOUT: int = Field(default=30, description="Seconds to wait before giving up on getting a connection") + USE_LIFO: bool = Field(default=True, description="Whether to use LIFO for connection pool") - DATABASE: str | None = Field(default=None, description="Database name") - DRIVER_NAME: str = Field(default="postgresql+psycopg", description="Database driver name") - COUNT_CACHE_ENABLED: bool = Field( + +class SQLAlchemyCountCacheConfig(BaseModel): + """Search query count cache settings.""" + + model_config = ConfigDict(extra="forbid") + + IS_ENABLED: bool = Field( default=False, description="Whether to cache the total count of search queries, so only the first page runs a COUNT", ) - COUNT_CACHE_MAX_SIZE: int = Field(default=1000, ge=1, description="Maximum number of cached search query totals") - COUNT_CACHE_TTL_SECONDS: int = Field( + MAX_SIZE: int = Field(default=1000, ge=1, description="Maximum number of cached search query totals") + TTL_SECONDS: int = Field( default=60, ge=1, description="Seconds a cached search query total stays valid", ) + + +class SQLAlchemyConfig(BaseModel): + """Configuration settings for SQLAlchemy ORM. + + Controls database connection parameters, pooling behavior, and query execution settings. + """ + + model_config = ConfigDict(hide_input_in_errors=True) + + DATABASE: str | None = Field(default=None, description="Database name") + DRIVER_NAME: str = Field(default="postgresql+psycopg", description="Database driver name") COUNT_THRESHOLD: int | None = Field( default=None, ge=0, @@ -50,19 +74,97 @@ class SQLAlchemyConfig(BaseModel): HOST: str | None = Field(default=None, description="Database host") ISOLATION_LEVEL: str | None = Field(default="REPEATABLE READ", description="Transaction isolation level") PASSWORD: SecretStr | None = Field(default=None, description="Database password") - POOL_MAX_OVERFLOW: int = Field(default=1, description="Maximum number of connections to allow in pool overflow") - POOL_PRE_PING: bool = Field(default=True, description="Whether to ping connections before use") - POOL_RECYCLE_SECONDS: int = Field(default=10 * 60, description="Number of seconds between connection recycling") + PORT: int | None = Field(default=5432, description="Database port") + QUERY_CACHE_SIZE: int = Field(default=500, description="Size of the query cache") + USERNAME: str | None = Field(default=None, description="Database username") + + POOL: SQLAlchemyPoolConfig = Field(default_factory=SQLAlchemyPoolConfig, description="Connection pool settings") + COUNT_CACHE: SQLAlchemyCountCacheConfig = Field( + default_factory=SQLAlchemyCountCacheConfig, + 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") - POOL_TIMEOUT: int = Field(default=30, description="Seconds to wait before giving up on getting a connection") - POOL_USE_LIFO: bool = Field(default=True, description="Whether to use LIFO for connection pool") - PORT: int | None = Field(default=5432, description="Database port") - QUERY_CACHE_SIZE: int = Field(default=500, description="Size of the query cache") - USERNAME: str | None = Field(default=None, description="Database username") + 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): diff --git a/archipy/configs/sections/temporal.py b/archipy/configs/sections/temporal.py index c03582479..19a7d6653 100644 --- a/archipy/configs/sections/temporal.py +++ b/archipy/configs/sections/temporal.py @@ -2,14 +2,248 @@ from typing import Literal, Self -from pydantic import BaseModel, Field, model_validator +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.""" + + model_config = ConfigDict(extra="forbid") + + IS_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)" + ), + ) + CA_CERT: str | None = Field(default=None, description="Path to TLS CA certificate") + CLIENT_CERT: str | None = Field(default=None, description="Path to TLS client certificate") + CLIENT_KEY: str | None = Field(default=None, description="Path to TLS client private key") + SERVER_NAME: str | None = Field( + default=None, + description="Server name to verify the TLS certificate against, when it differs from HOST", + ) + 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)" + ), + ) + + @model_validator(mode="after") + def validate_tls_configuration(self) -> Self: + """Validate the mutual TLS client certificate and key are set together; the CA certificate is optional. + + A certificate verification server name needs ``CA_CERT``, the root it verifies against. + """ + if (self.CLIENT_CERT is None) != (self.CLIENT_KEY is None): + raise InvalidArgumentError() + if self.VERIFICATION_SERVER_NAME is not None and self.CA_CERT is None: + raise InvalidArgumentError() + + return self + + +class TemporalWorkerConfig(BaseModel): + """Worker settings.""" + + model_config = ConfigDict(extra="forbid") + + GRACEFUL_SHUTDOWN_SECONDS: int = Field( + default=30, + ge=0, + description="Maximum time in seconds to wait for graceful worker shutdown", + ) + MAX_CACHED_WORKFLOWS: int = Field( + default=1000, + ge=0, + description="Maximum number of workflow instances cached in worker memory", + ) + DEBUG_MODE: bool = Field( + default=False, + description="Enable worker debug mode (e.g. breakpoint support in workflow sandbox)", + ) + MAX_CONCURRENT_LOCAL_ACTIVITIES: int | None = Field( + default=None, + ge=1, + description="Maximum concurrent local activities (None uses server default)", + ) + DISABLE_EAGER_ACTIVITY_EXECUTION: bool = Field( + default=False, + description="Disable eager activity execution on the 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)", + ) + 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+)" + ), + ) + MAX_ACTIVITIES_PER_SECOND: float | None = Field( + default=None, + gt=0, + description="Rate limit for activities this worker starts per second (None: unlimited)", + ) + 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)", + ) + + +class TemporalClientRetryConfig(BaseModel): + """Client RPC retry settings.""" + + model_config = ConfigDict(extra="forbid") + + MAX_RETRIES: int = Field( + default=10, + ge=0, + description="Maximum client-side RPC retry attempts", + ) + INITIAL_INTERVAL_MS: int = Field( + default=100, + ge=1, + description="Initial backoff interval for client-side RPC retries in milliseconds", + ) + MAX_INTERVAL_MS: int = Field( + default=5000, + ge=1, + description="Maximum backoff interval for client-side RPC retries in milliseconds", + ) + + +class TemporalKeepAliveConfig(BaseModel): + """Connection keep-alive settings.""" + + model_config = ConfigDict(extra="forbid") + + INTERVAL_MS: int = Field( + default=30000, + ge=1, + description="gRPC keep-alive ping interval in milliseconds", + ) + TIMEOUT_MS: int = Field( + default=15000, + ge=1, + description="gRPC keep-alive timeout in milliseconds", + ) + + @model_validator(mode="after") + def validate_keep_alive_configuration(self) -> Self: + """Validate keep-alive timeout is less than the keep-alive interval.""" + if self.TIMEOUT_MS >= self.INTERVAL_MS: + raise InvalidArgumentError() + + return self + + +class TemporalWorkflowConfig(BaseModel): + """Default workflow timeouts and retry.""" + + model_config = ConfigDict(extra="forbid") + + EXECUTION_TIMEOUT: int | None = Field( + default=None, + ge=1, + description="Maximum workflow execution time in seconds, retries included (None: unbounded)", + ) + RUN_TIMEOUT: int | None = Field( + default=None, + ge=1, + description="Maximum single workflow run time in seconds (None: unbounded)", + ) + TASK_TIMEOUT: int = Field( + default=30, + ge=1, + description="Maximum workflow task processing time in seconds", + ) + 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)" + ), + ) + + @model_validator(mode="after") + def validate_timeout_hierarchy(self) -> Self: + """Validate timeout configuration hierarchy.""" + # The task timeout bounds a single workflow task, so it is independent of the run timeout. + if ( + self.RUN_TIMEOUT is not None + and self.EXECUTION_TIMEOUT is not None + and self.RUN_TIMEOUT > self.EXECUTION_TIMEOUT + ): + raise InvalidArgumentError() + + return self + + +class TemporalActivityConfig(BaseModel): + """Default activity timeouts.""" + + model_config = ConfigDict(extra="forbid") + + START_TO_CLOSE_TIMEOUT: int = Field( + default=30, + ge=1, + description="Maximum activity execution time in seconds", + ) + 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)" + ), + ) + + +class TemporalRetryConfig(BaseModel): + """Default workflow and activity retry policy.""" + + model_config = ConfigDict(extra="forbid") + + MAXIMUM_ATTEMPTS: int = Field( + default=3, + ge=1, + description="Maximum retry attempts for failed activities", + ) + BACKOFF_COEFFICIENT: float = Field( + default=2.0, + ge=1.0, + description="Backoff multiplier for retry delays", + ) + MAXIMUM_INTERVAL: int = Field( + default=60, + ge=1, + description="Maximum retry interval in seconds", + ) + INITIAL_INTERVAL: int = Field( + default=1, + ge=1, + description="Initial retry interval in seconds for workflow and activity retry policies", + ) + NON_RETRYABLE_ERROR_TYPES: list[str] | None = Field( + default=None, + description="Error type names that should not be retried by workflow/activity retry policies", + ) + + class TemporalConfig(BaseModel): """Configuration settings for Temporal workflow engine integration. @@ -21,8 +255,6 @@ class TemporalConfig(BaseModel): PORT: int = Field(default=7233, ge=1, le=65535, description="Temporal server port number") NAMESPACE: str = Field(default="default", description="Temporal namespace for workflow isolation") TASK_QUEUE: str = Field(default="task-queue", description="Default task queue name") - - # Metrics Configuration (OTLP via global OTEL config) ENABLE_METRICS: bool = Field( default=False, description=( @@ -40,7 +272,6 @@ class TemporalConfig(BaseModel): "(bound on OTEL.METRICS_PULL_HOST; must differ from OTEL.METRICS_PULL_PORT)" ), ) - PYDANTIC_DATA_CONVERTER: bool = Field( default=True, description=( @@ -48,7 +279,6 @@ class TemporalConfig(BaseModel): "(Pydantic models, datetimes and decimals round trip); ignored when a data_converter is passed explicitly" ), ) - METRICS_GLOBAL_TAGS: dict[str, str] | None = Field( default=None, description="Tags added to every Temporal SDK metric, e.g. service and environment", @@ -61,8 +291,6 @@ class TemporalConfig(BaseModel): default=False, description="Keep runtime, hosting and platform information out of worker heartbeats sent to the server", ) - - # Client Connection Configuration CLIENT_IDENTITY: str | None = Field( default=None, description="Client identity string for Temporal server visibility", @@ -75,16 +303,6 @@ class TemporalConfig(BaseModel): default=False, description="Defer establishing the Temporal client connection until first use", ) - KEEP_ALIVE_INTERVAL_MS: int = Field( - default=30000, - ge=1, - description="gRPC keep-alive ping interval in milliseconds", - ) - KEEP_ALIVE_TIMEOUT_MS: int = Field( - default=15000, - ge=1, - description="gRPC keep-alive timeout in milliseconds", - ) RPC_METADATA: dict[str, str] | None = Field( default=None, description="Custom RPC metadata headers sent with every client request", @@ -111,123 +329,234 @@ class TemporalConfig(BaseModel): ge=1, description="Memo size in bytes above which the SDK logs a warning (None: SDK default, 2 KiB)", ) - CLIENT_RPC_RETRY_MAX_RETRIES: int = Field( - default=10, - ge=0, - description="Maximum client-side RPC retry attempts", + + TLS: TemporalTlsConfig = Field( + default_factory=TemporalTlsConfig, + description="TLS settings of the Temporal connection", ) - CLIENT_RPC_RETRY_INITIAL_INTERVAL_MS: int = Field( - default=100, - ge=1, - description="Initial backoff interval for client-side RPC retries in milliseconds", + WORKER: TemporalWorkerConfig = Field(default_factory=TemporalWorkerConfig, description="Worker settings") + CLIENT_RETRY: TemporalClientRetryConfig = Field( + default_factory=TemporalClientRetryConfig, + description="Client RPC retry settings", ) - CLIENT_RPC_RETRY_MAX_INTERVAL_MS: int = Field( - default=5000, - ge=1, - description="Maximum backoff interval for client-side RPC retries in milliseconds", + KEEP_ALIVE: TemporalKeepAliveConfig = Field( + default_factory=TemporalKeepAliveConfig, + description="Connection keep-alive settings", + ) + WORKFLOW: TemporalWorkflowConfig = Field( + default_factory=TemporalWorkflowConfig, + description="Default workflow timeouts and retry", + ) + ACTIVITY: TemporalActivityConfig = Field( + default_factory=TemporalActivityConfig, + description="Default activity timeouts", + ) + RETRY: TemporalRetryConfig = Field( + default_factory=TemporalRetryConfig, + description="Default workflow and activity retry policy", ) - # Worker Configuration + 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", + ), ) - - # TLS Configuration - TLS_CA_CERT: str | None = Field(default=None, description="Path to TLS CA certificate") - TLS_CLIENT_CERT: str | None = Field(default=None, description="Path to TLS client certificate") - TLS_CLIENT_KEY: str | None = Field(default=None, description="Path to TLS client private key") - TLS_SERVER_NAME: str | None = Field( - default=None, - description="Server name to verify the TLS certificate against, when it differs from HOST", + 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"), ) - 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)" + 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", ), ) - 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)" + 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", ), ) - - # Workflow Timeout Settings + 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 Timeout Settings 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, @@ -236,68 +565,43 @@ class TemporalConfig(BaseModel): "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 Configuration 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_tls_configuration(self) -> Self: - """Validate the mutual TLS client certificate and key are set together; the CA certificate is optional. - - A certificate verification server name needs ``TLS_CA_CERT``, the root it verifies against. - """ - if (self.TLS_CLIENT_CERT is None) != (self.TLS_CLIENT_KEY is None): - raise InvalidArgumentError() - if self.TLS_VERIFICATION_SERVER_NAME is not None and self.TLS_CA_CERT is None: - raise InvalidArgumentError() - - return self - - @model_validator(mode="after") - def validate_timeout_hierarchy(self) -> Self: - """Validate timeout configuration hierarchy.""" - # The task timeout bounds a single workflow task, so it is independent of the run timeout. - if ( - self.WORKFLOW_RUN_TIMEOUT is not None - and self.WORKFLOW_EXECUTION_TIMEOUT is not None - and self.WORKFLOW_RUN_TIMEOUT > self.WORKFLOW_EXECUTION_TIMEOUT - ): - raise InvalidArgumentError() - - return self - - @model_validator(mode="after") - def validate_keep_alive_configuration(self) -> Self: - """Validate keep-alive timeout is less than the keep-alive interval.""" - if self.KEEP_ALIVE_TIMEOUT_MS >= self.KEEP_ALIVE_INTERVAL_MS: - raise InvalidArgumentError() - - return self - @model_validator(mode="after") def validate_rpc_metadata(self) -> Self: """Validate RPC metadata keys and values are non-empty strings.""" @@ -309,3 +613,85 @@ 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 4a3e879b1..7624e0675 100644 --- a/archipy/configs/sections/uvicorn.py +++ b/archipy/configs/sections/uvicorn.py @@ -2,8 +2,9 @@ from typing import Self -from pydantic import BaseModel, Field, model_validator +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. @@ -27,6 +28,70 @@ ) +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)") + CA_CERTS: str | None = Field( + default=None, + description="Path to the CA bundle that verifies client certificates", + ) + + @model_validator(mode="after") + def validate_tls_pair(self) -> Self: + """Require the TLS key and certificate together. + + Raises: + ConfigurationError: If only one of KEYFILE and CERTFILE is set. + """ + if (self.KEYFILE is None) != (self.CERTFILE is None): + raise ConfigurationError( + operation="uvicorn", + reason="ssl_keyfile_and_certfile_required_together", + additional_data={"hint": "Set both SSL_KEYFILE and SSL_CERTFILE"}, + ) + return self + + +class UvicornWebSocketConfig(BaseModel): + """WebSocket settings.""" + + model_config = ConfigDict(extra="forbid") + + MAX_SIZE: int = Field(default=16777216, description="Maximum WebSocket message size in bytes") + PER_MESSAGE_DEFLATE: bool = Field(default=True, description="Whether to enable WebSocket compression") + PING_INTERVAL: float = Field(default=20.0, description="WebSocket ping interval in seconds") + PING_TIMEOUT: float = Field(default=20.0, description="WebSocket ping timeout in seconds") + + +class UvicornLimitsConfig(BaseModel): + """Connection and request limits.""" + + model_config = ConfigDict(extra="forbid") + + BACKLOG: int = Field(default=2048, description="Maximum number of queued connections") + CONCURRENCY: int | None = Field(default=None, description="Maximum concurrent connections or tasks") + 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. @@ -35,42 +100,100 @@ class UvicornConfig(BaseModel): """ ACCESS_LOG: bool = Field(default=True, description="Whether to enable access logging") - BACKLOG: int = Field(default=2048, description="Maximum number of queued connections") DATE_HEADER: bool = Field(default=True, description="Whether to include the Date header in responses") FORWARDED_ALLOW_IPS: list[str] | None = Field( default=None, description="Proxy IPs whose X-Forwarded-* headers are trusted (None: uvicorn's default, 127.0.0.1)", ) - LIMIT_CONCURRENCY: int | None = Field(default=None, description="Maximum concurrent connections or tasks") - LIMIT_MAX_REQUESTS: int | None = Field(default=None, description="Requests served before the worker restarts") PROXY_HEADERS: bool = Field(default=True, description="Whether to trust X-Forwarded-* proxy headers") RELOAD: bool = Field(default=False, description="Whether to enable auto-reload") SERVER_HEADER: bool = Field(default=True, description="Whether to include the Server header in responses") TIMEOUT_GRACEFUL_SHUTDOWN: int | None = Field(default=None, description="Graceful shutdown timeout in seconds") TIMEOUT_KEEP_ALIVE: int = Field(default=5, description="Keep-alive timeout in seconds") WORKERS_COUNT: int = Field(default=4, description="Number of worker processes (ignored with RELOAD)") - WS_MAX_SIZE: int = Field(default=16777216, description="Maximum WebSocket message size in bytes") - WS_PER_MESSAGE_DEFLATE: bool = Field(default=True, description="Whether to enable WebSocket compression") - WS_PING_INTERVAL: float = Field(default=20.0, description="WebSocket ping interval in seconds") - WS_PING_TIMEOUT: float = Field(default=20.0, description="WebSocket ping timeout in seconds") - SSL_KEYFILE: str | None = Field(default=None, description="Path to the PEM TLS private key (with SSL_CERTFILE)") - SSL_CERTFILE: str | None = Field(default=None, description="Path to the PEM TLS certificate (with SSL_KEYFILE)") + + TLS: UvicornTlsConfig = Field(default_factory=UvicornTlsConfig, description="TLS settings of the server") + WEBSOCKET: UvicornWebSocketConfig = Field(default_factory=UvicornWebSocketConfig, description="WebSocket settings") + LIMITS: UvicornLimitsConfig = Field( + 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 validate_tls_pair(self) -> Self: - """Require the TLS key and certificate together. - - Raises: - ConfigurationError: If only one of SSL_KEYFILE and SSL_CERTFILE is set. - """ - if (self.SSL_KEYFILE is None) != (self.SSL_CERTFILE is None): - raise ConfigurationError( - operation="uvicorn", - reason="ssl_keyfile_and_certfile_required_together", - additional_data={"hint": "Set both SSL_KEYFILE and SSL_CERTFILE"}, - ) + 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 7159f330a..5e711b2c5 100644 --- a/archipy/configs/sections/vault.py +++ b/archipy/configs/sections/vault.py @@ -1,8 +1,202 @@ """HashiCorp Vault configuration.""" -from typing import Literal +from typing import Literal, Self -from pydantic import BaseModel, Field, SecretStr +from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator + +from archipy.configs.sections._common import deprecated_flat_message, fold_flat_fields + + +class VaultAppRoleConfig(BaseModel): + """AppRole auth settings.""" + + model_config = ConfigDict(extra="forbid") + + ROLE_ID: str | None = Field(default=None, description="AppRole role_id") + SECRET_ID: SecretStr | None = Field(default=None, description="AppRole secret_id") + SECRET_ID_FILE: str | None = Field( + default=None, + description="Path to a file containing the AppRole secret_id; takes precedence over APPROLE_SECRET_ID", + ) + MOUNT_POINT: str = Field(default="approle", description="Mount point of the AppRole auth method") + + +class VaultKubernetesConfig(BaseModel): + """Kubernetes auth settings.""" + + model_config = ConfigDict(extra="forbid") + + ROLE: str | None = Field( + default=None, + description="Vault role bound to the Kubernetes service account", + ) + JWT_PATH: str = Field( + default="/var/run/secrets/kubernetes.io/serviceaccount/token", + description="Path to the service account JWT used for Kubernetes auth", + ) + MOUNT_POINT: str = Field( + default="kubernetes", + description="Mount point of the Kubernetes auth method", + ) + + +class VaultUserpassConfig(BaseModel): + """Userpass auth mount.""" + + model_config = ConfigDict(extra="forbid") + + MOUNT_POINT: str = Field(default="userpass", description="Mount point of the userpass auth method") + + +class VaultLdapConfig(BaseModel): + """LDAP auth mount.""" + + model_config = ConfigDict(extra="forbid") + + MOUNT_POINT: str = Field(default="ldap", description="Mount point of the LDAP auth method") + + +class VaultOktaConfig(BaseModel): + """Okta auth mount.""" + + model_config = ConfigDict(extra="forbid") + + MOUNT_POINT: str = Field(default="okta", description="Mount point of the Okta auth method") + + +class VaultJwtConfig(BaseModel): + """JWT auth settings.""" + + model_config = ConfigDict(extra="forbid") + + ROLE: str | None = Field(default=None, description="Role name for JWT auth") + JWT: SecretStr | None = Field(default=None, description="JWT for JWT auth") + JWT_FILE: str | None = Field( + default=None, + description="Path to a file containing the JWT; takes precedence over JWT", + ) + MOUNT_POINT: str = Field(default="jwt", description="Mount path of the JWT auth method") + + +class VaultAwsConfig(BaseModel): + """AWS IAM auth settings.""" + + model_config = ConfigDict(extra="forbid") + + ACCESS_KEY: str | None = Field(default=None, description="AWS access key for IAM auth") + SECRET_KEY: SecretStr | None = Field(default=None, description="AWS secret key for IAM auth") + SESSION_TOKEN: SecretStr | None = Field( + default=None, + description="Optional AWS session token for IAM auth", + ) + ROLE: str | None = Field(default=None, description="Optional Vault role for AWS IAM auth") + REGION: str = Field(default="us-east-1", description="AWS region used for IAM auth signing") + MOUNT_POINT: str = Field(default="aws", description="Mount point of the AWS auth method") + + +class VaultAzureConfig(BaseModel): + """Azure auth settings.""" + + model_config = ConfigDict(extra="forbid") + + ROLE: str | None = Field(default=None, description="Role name for Azure auth") + JWT: SecretStr | None = Field(default=None, description="JWT for Azure auth") + JWT_FILE: str | None = Field( + default=None, + description="Path to a file containing the Azure JWT; takes precedence over AZURE_JWT", + ) + SUBSCRIPTION_ID: str | None = Field(default=None, description="Optional Azure subscription id") + RESOURCE_GROUP_NAME: str | None = Field(default=None, description="Optional Azure resource group name") + VM_NAME: str | None = Field(default=None, description="Optional Azure VM name") + VMSS_NAME: str | None = Field(default=None, description="Optional Azure VMSS name") + MOUNT_POINT: str = Field(default="azure", description="Mount point of the Azure auth method") + + +class VaultGcpConfig(BaseModel): + """GCP auth settings.""" + + model_config = ConfigDict(extra="forbid") + + ROLE: str | None = Field(default=None, description="Role name for GCP auth") + JWT: SecretStr | None = Field(default=None, description="JWT for GCP auth") + JWT_FILE: str | None = Field( + default=None, + description="Path to a file containing the GCP JWT; takes precedence over GCP_JWT", + ) + MOUNT_POINT: str = Field(default="gcp", description="Mount point of the GCP auth method") + + +class VaultGithubConfig(BaseModel): + """GitHub auth settings.""" + + model_config = ConfigDict(extra="forbid") + + TOKEN: SecretStr | None = Field( + default=None, + description="GitHub personal access token for GitHub auth", + ) + TOKEN_FILE: str | None = Field( + default=None, + description="Path to a file containing the GitHub token; takes precedence over GITHUB_TOKEN", + ) + MOUNT_POINT: str = Field(default="github", description="Mount point of the GitHub auth method") + + +class VaultCertConfig(BaseModel): + """TLS client certificate auth settings.""" + + model_config = ConfigDict(extra="forbid") + + NAME: str = Field( + default="", + description="Optional named cert role for the cert auth method", + ) + MOUNT_POINT: str = Field(default="cert", description="Mount point of the cert auth method") + + +class VaultTlsConfig(BaseModel): + """TLS and mutual TLS settings.""" + + model_config = ConfigDict(extra="forbid") + + VERIFY_SSL: bool = Field(default=True, description="Verify the Vault server's TLS certificate") + CA_CERT_PATH: str | None = Field( + default=None, + description="Path to a CA bundle for verifying Vault's TLS certificate", + ) + CLIENT_CERT_PATH: str | None = Field( + default=None, + description="Path to a client certificate for mutual TLS", + ) + CLIENT_KEY_PATH: str | None = Field( + default=None, + description="Path to the client private key for mutual TLS", + ) + + +class VaultHttpConfig(BaseModel): + """Request timeouts and retries.""" + + model_config = ConfigDict(extra="forbid") + + CONNECT_TIMEOUT: float = Field(default=5.0, description="Connection timeout in seconds") + READ_TIMEOUT: float = Field(default=10.0, description="Read timeout in seconds") + RETRIES_MAX_ATTEMPTS: int = Field(default=3, description="Maximum retry attempts for failed requests") + + +class VaultTokenRenewalConfig(BaseModel): + """Token renewal settings (adapter only).""" + + model_config = ConfigDict(extra="forbid") + + AUTO_RENEW_TOKEN: bool = Field( + default=False, + description="Automatically renew the token before it expires", + ) + RENEW_THRESHOLD_SECONDS: int = Field( + default=60, + description="Renew the token once its remaining TTL drops below this many seconds", + ) class VaultConfig(BaseModel): @@ -10,6 +204,9 @@ 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. """ ENABLED: bool = Field(default=False, description="Whether Vault integration is active") @@ -33,146 +230,379 @@ class VaultConfig(BaseModel): description="Vault auth method (hvac-supported backends)", ) - # Token auth TOKEN: SecretStr | None = Field(default=None, description="Vault token (token auth)") TOKEN_FILE: str | None = Field( default=None, description="Path to a file containing the Vault token; takes precedence over TOKEN", ) + USERNAME: str | None = Field(default=None, description="Username for userpass/ldap/okta auth") + PASSWORD: SecretStr | None = Field(default=None, description="Password for userpass/ldap/okta auth") + PASSWORD_FILE: str | None = Field( + default=None, + description="Path to a file containing the password; takes precedence over PASSWORD", + ) + MOUNT_POINT: str = Field(default="secret", description="Mount point of the KV v2 secrets engine") + SECRET_PATHS: list[str] = Field( + default=[], + description="KV v2 paths read by the settings source; later paths win", + ) + SECRET_CACHE_TTL: int = Field( + default=0, + description="Cache VaultAdapter.read_secret() results for this many seconds; 0 disables caching", + ) + + APPROLE: VaultAppRoleConfig = Field(default_factory=VaultAppRoleConfig, description="AppRole auth settings") + KUBERNETES: VaultKubernetesConfig = Field( + default_factory=VaultKubernetesConfig, + description="Kubernetes auth settings", + ) + USERPASS: VaultUserpassConfig = Field(default_factory=VaultUserpassConfig, description="Userpass auth mount") + LDAP: VaultLdapConfig = Field(default_factory=VaultLdapConfig, description="LDAP auth mount") + OKTA: VaultOktaConfig = Field(default_factory=VaultOktaConfig, description="Okta auth mount") + JWT_AUTH: VaultJwtConfig = Field(default_factory=VaultJwtConfig, description="JWT auth settings") + AWS: VaultAwsConfig = Field(default_factory=VaultAwsConfig, description="AWS IAM auth settings") + AZURE: VaultAzureConfig = Field(default_factory=VaultAzureConfig, description="Azure auth settings") + GCP: VaultGcpConfig = Field(default_factory=VaultGcpConfig, description="GCP auth settings") + GITHUB: VaultGithubConfig = Field(default_factory=VaultGithubConfig, description="GitHub auth settings") + CERT: VaultCertConfig = Field(default_factory=VaultCertConfig, description="TLS client certificate auth settings") + TLS: VaultTlsConfig = Field(default_factory=VaultTlsConfig, description="TLS and mutual TLS settings") + HTTP: VaultHttpConfig = Field(default_factory=VaultHttpConfig, description="Request timeouts and retries") + TOKEN_RENEWAL: VaultTokenRenewalConfig = Field( + default_factory=VaultTokenRenewalConfig, + description="Token renewal settings (adapter only)", + ) - # AppRole auth - APPROLE_ROLE_ID: str | None = Field(default=None, description="AppRole role_id") - APPROLE_SECRET_ID: SecretStr | None = Field(default=None, description="AppRole secret_id") + 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"), ) - APPROLE_MOUNT_POINT: str = Field(default="approle", description="Mount point of the AppRole auth method") - - # Kubernetes auth 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"), ) - - # Username/password auth (userpass, ldap, okta) - USERNAME: str | None = Field(default=None, description="Username for userpass/ldap/okta auth") - PASSWORD: SecretStr | None = Field(default=None, description="Password for userpass/ldap/okta auth") - PASSWORD_FILE: str | None = Field( + 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="Path to a file containing the password; takes precedence over PASSWORD", + 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"), ) - USERPASS_MOUNT_POINT: str = Field(default="userpass", description="Mount point of the userpass auth method") - LDAP_MOUNT_POINT: str = Field(default="ldap", description="Mount point of the LDAP auth method") - OKTA_MOUNT_POINT: str = Field(default="okta", description="Mount point of the Okta auth method") - - # JWT auth - JWT_ROLE: str | None = Field(default=None, description="Role name for JWT auth") - JWT: SecretStr | None = Field(default=None, description="JWT for JWT auth") 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"), ) - JWT_MOUNT_POINT: str = Field(default="jwt", description="Mount path of the JWT auth method") - - # AWS IAM auth - AWS_ACCESS_KEY: str | None = Field(default=None, description="AWS access key for IAM auth") - AWS_SECRET_KEY: SecretStr | None = Field(default=None, description="AWS secret key for IAM auth") 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"), ) - AWS_ROLE: str | None = Field(default=None, description="Optional Vault role for AWS IAM auth") - AWS_REGION: str = Field(default="us-east-1", description="AWS region used for IAM auth signing") - AWS_MOUNT_POINT: str = Field(default="aws", description="Mount point of the AWS auth method") - - # Azure auth - AZURE_ROLE: str | None = Field(default=None, description="Role name for Azure auth") - AZURE_JWT: SecretStr | None = Field(default=None, description="JWT for Azure auth") 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"), ) - AZURE_SUBSCRIPTION_ID: str | None = Field(default=None, description="Optional Azure subscription id") - AZURE_RESOURCE_GROUP_NAME: str | None = Field(default=None, description="Optional Azure resource group name") - AZURE_VM_NAME: str | None = Field(default=None, description="Optional Azure VM name") - AZURE_VMSS_NAME: str | None = Field(default=None, description="Optional Azure VMSS name") - AZURE_MOUNT_POINT: str = Field(default="azure", description="Mount point of the Azure auth method") - - # GCP auth - GCP_ROLE: str | None = Field(default=None, description="Role name for GCP auth") - GCP_JWT: SecretStr | None = Field(default=None, description="JWT for GCP auth") 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"), ) - GCP_MOUNT_POINT: str = Field(default="gcp", description="Mount point of the GCP auth method") - - # GitHub auth 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"), ) - GITHUB_MOUNT_POINT: str = Field(default="github", description="Mount point of the GitHub auth method") - - # Cert auth (TLS client certificate auth method; often paired with CLIENT_CERT_PATH/KEY) 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") - - # KV v2 - MOUNT_POINT: str = Field(default="secret", description="Mount point of the KV v2 secrets engine") - SECRET_PATHS: list[str] = Field( - default=[], - description="KV v2 paths read by the settings source; later paths win", + 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"), ) - - # TLS / mTLS - VERIFY_SSL: bool = Field(default=True, description="Verify the Vault server's TLS certificate") 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"), ) - - # Timeouts / retries - CONNECT_TIMEOUT: float = Field(default=5.0, description="Connection timeout in seconds") - READ_TIMEOUT: float = Field(default=10.0, description="Read timeout in seconds") - RETRIES_MAX_ATTEMPTS: int = Field(default=3, description="Maximum retry attempts for failed requests") - - # Token lifecycle (adapter only — the settings source is one-shot at startup) 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", + ), ) - # Secret caching (adapter only) - SECRET_CACHE_TTL: int = Field( - default=0, - description="Cache VaultAdapter.read_secret() results for this many seconds; 0 disables caching", - ) + @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 084ecc042..84bf769ae 100644 --- a/archipy/configs/vault_settings_source.py +++ b/archipy/configs/vault_settings_source.py @@ -25,6 +25,22 @@ from urllib3.util.retry import Retry from archipy.configs.config_template import VaultConfig +from archipy.configs.sections.vault import ( + VaultAppRoleConfig, + VaultAwsConfig, + VaultAzureConfig, + VaultCertConfig, + VaultGcpConfig, + VaultGithubConfig, + VaultHttpConfig, + VaultJwtConfig, + VaultKubernetesConfig, + VaultLdapConfig, + VaultOktaConfig, + VaultTlsConfig, + VaultTokenRenewalConfig, + VaultUserpassConfig, +) from archipy.models.errors import ConfigurationError if TYPE_CHECKING: @@ -91,9 +107,9 @@ def _resolve_token(config: VaultConfig) -> str | None: def _resolve_approle_secret_id(config: VaultConfig) -> str | None: """Resolve the AppRole secret_id from file or inline value.""" - if config.APPROLE_SECRET_ID_FILE: - return _read_file_secret(config.APPROLE_SECRET_ID_FILE) - return _secret_value(config.APPROLE_SECRET_ID) + if config.APPROLE.SECRET_ID_FILE: + return _read_file_secret(config.APPROLE.SECRET_ID_FILE) + return _secret_value(config.APPROLE.SECRET_ID) def _resolve_password(config: VaultConfig) -> str | None: @@ -127,10 +143,10 @@ def _build_session(config: VaultConfig) -> Session: """ session = Session() retry = Retry( - total=config.RETRIES_MAX_ATTEMPTS, - connect=config.RETRIES_MAX_ATTEMPTS, - read=config.RETRIES_MAX_ATTEMPTS, - status=config.RETRIES_MAX_ATTEMPTS, + total=config.HTTP.RETRIES_MAX_ATTEMPTS, + connect=config.HTTP.RETRIES_MAX_ATTEMPTS, + read=config.HTTP.RETRIES_MAX_ATTEMPTS, + status=config.HTTP.RETRIES_MAX_ATTEMPTS, backoff_factor=0.3, status_forcelist=(500, 502, 503, 504), # Only idempotent reads are retried on read errors and 5xx statuses: replaying @@ -138,7 +154,7 @@ def _build_session(config: VaultConfig) -> Session: # are retried for every method. allowed_methods=frozenset({"GET", "HEAD", "LIST"}), ) - timeout = (config.CONNECT_TIMEOUT, config.READ_TIMEOUT) + timeout = (config.HTTP.CONNECT_TIMEOUT, config.HTTP.READ_TIMEOUT) adapter = _TimeoutHTTPAdapter(timeout=timeout, max_retries=retry) session.mount("http://", adapter) session.mount("https://", adapter) @@ -204,11 +220,11 @@ def create_vault_client(config: VaultConfig) -> hvac.Client: if not config.ADDR: raise ConfigurationError(operation="vault_connect", reason="VAULT.ADDR is required when Vault is enabled") - verify: bool | str = config.CA_CERT_PATH or config.VERIFY_SSL + verify: bool | str = config.TLS.CA_CERT_PATH or config.TLS.VERIFY_SSL cert: tuple[str, str] | None = None - if config.CLIENT_CERT_PATH and config.CLIENT_KEY_PATH: - cert = (config.CLIENT_CERT_PATH, config.CLIENT_KEY_PATH) - elif config.CLIENT_CERT_PATH or config.CLIENT_KEY_PATH: + if config.TLS.CLIENT_CERT_PATH and config.TLS.CLIENT_KEY_PATH: + cert = (config.TLS.CLIENT_CERT_PATH, config.TLS.CLIENT_KEY_PATH) + 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", @@ -226,7 +242,7 @@ def create_vault_client(config: VaultConfig) -> hvac.Client: namespace=config.NAMESPACE, verify=verify, cert=cert, - timeout=(config.CONNECT_TIMEOUT, config.READ_TIMEOUT), + timeout=(config.HTTP.CONNECT_TIMEOUT, config.HTTP.READ_TIMEOUT), session=session, ) @@ -268,7 +284,7 @@ def _authenticate_token(client: hvac.Client, config: VaultConfig) -> None: def _authenticate_approle(client: hvac.Client, config: VaultConfig) -> None: """Authenticate with AppRole.""" - if not config.APPROLE_ROLE_ID: + if not config.APPROLE.ROLE_ID: raise ConfigurationError( operation="vault_auth", reason="APPROLE_ROLE_ID is required for approle auth", @@ -280,25 +296,25 @@ def _authenticate_approle(client: hvac.Client, config: VaultConfig) -> None: 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, + role_id=config.APPROLE.ROLE_ID, secret_id=secret_id, - mount_point=config.APPROLE_MOUNT_POINT, + mount_point=config.APPROLE.MOUNT_POINT, ) _set_client_token_from_auth_response(client, response) def _authenticate_kubernetes(client: hvac.Client, config: VaultConfig) -> None: """Authenticate with Kubernetes service account JWT.""" - if not config.KUBERNETES_ROLE: + if not config.KUBERNETES.ROLE: raise ConfigurationError( operation="vault_auth", reason="KUBERNETES_ROLE is required for kubernetes auth", ) - jwt = _read_file_secret(config.KUBERNETES_JWT_PATH) + jwt = _read_file_secret(config.KUBERNETES.JWT_PATH) response = client.auth.kubernetes.login( - role=config.KUBERNETES_ROLE, + role=config.KUBERNETES.ROLE, jwt=jwt, - mount_point=config.KUBERNETES_MOUNT_POINT, + mount_point=config.KUBERNETES.MOUNT_POINT, ) _set_client_token_from_auth_response(client, response) @@ -320,108 +336,108 @@ def _authenticate_username_password(client: hvac.Client, config: VaultConfig) -> response = client.auth.userpass.login( username=config.USERNAME, password=password, - mount_point=config.USERPASS_MOUNT_POINT, + mount_point=config.USERPASS.MOUNT_POINT, ) elif config.AUTH_METHOD == "ldap": response = client.auth.ldap.login( username=config.USERNAME, password=password, - mount_point=config.LDAP_MOUNT_POINT, + mount_point=config.LDAP.MOUNT_POINT, ) else: response = client.auth.okta.login( username=config.USERNAME, password=password, - mount_point=config.OKTA_MOUNT_POINT, + mount_point=config.OKTA.MOUNT_POINT, ) _set_client_token_from_auth_response(client, response) def _authenticate_jwt(client: hvac.Client, config: VaultConfig) -> None: """Authenticate with the JWT auth method.""" - if not config.JWT_ROLE: + if not config.JWT_AUTH.ROLE: raise ConfigurationError(operation="vault_auth", reason="JWT_ROLE is required for jwt auth") - jwt = _resolve_optional_file_or_value(config.JWT_FILE, config.JWT) + 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", ) response = client.auth.jwt.jwt_login( - role=config.JWT_ROLE, + role=config.JWT_AUTH.ROLE, jwt=jwt, - path=config.JWT_MOUNT_POINT, + path=config.JWT_AUTH.MOUNT_POINT, ) _set_client_token_from_auth_response(client, response) def _authenticate_aws(client: hvac.Client, config: VaultConfig) -> None: """Authenticate with AWS IAM.""" - if not config.AWS_ACCESS_KEY or not config.AWS_SECRET_KEY: + 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", ) response = client.auth.aws.iam_login( - access_key=config.AWS_ACCESS_KEY, - secret_key=_secret_value(config.AWS_SECRET_KEY), - session_token=_secret_value(config.AWS_SESSION_TOKEN), - role=config.AWS_ROLE, - region=config.AWS_REGION, - mount_point=config.AWS_MOUNT_POINT, + access_key=config.AWS.ACCESS_KEY, + secret_key=_secret_value(config.AWS.SECRET_KEY), + session_token=_secret_value(config.AWS.SESSION_TOKEN), + role=config.AWS.ROLE, + region=config.AWS.REGION, + mount_point=config.AWS.MOUNT_POINT, ) _set_client_token_from_auth_response(client, response) def _authenticate_azure(client: hvac.Client, config: VaultConfig) -> None: """Authenticate with Azure.""" - if not config.AZURE_ROLE: + if not config.AZURE.ROLE: 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) + 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", ) response = client.auth.azure.login( - role=config.AZURE_ROLE, + role=config.AZURE.ROLE, jwt=jwt, - subscription_id=config.AZURE_SUBSCRIPTION_ID, - resource_group_name=config.AZURE_RESOURCE_GROUP_NAME, - vm_name=config.AZURE_VM_NAME, - vmss_name=config.AZURE_VMSS_NAME, - mount_point=config.AZURE_MOUNT_POINT, + subscription_id=config.AZURE.SUBSCRIPTION_ID, + resource_group_name=config.AZURE.RESOURCE_GROUP_NAME, + vm_name=config.AZURE.VM_NAME, + vmss_name=config.AZURE.VMSS_NAME, + mount_point=config.AZURE.MOUNT_POINT, ) _set_client_token_from_auth_response(client, response) def _authenticate_gcp(client: hvac.Client, config: VaultConfig) -> None: """Authenticate with GCP.""" - if not config.GCP_ROLE: + if not config.GCP.ROLE: 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) + 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", ) response = client.auth.gcp.login( - role=config.GCP_ROLE, + role=config.GCP.ROLE, jwt=jwt, - mount_point=config.GCP_MOUNT_POINT, + mount_point=config.GCP.MOUNT_POINT, ) _set_client_token_from_auth_response(client, response) def _authenticate_github(client: hvac.Client, config: VaultConfig) -> None: """Authenticate with a GitHub personal access token.""" - token = _resolve_optional_file_or_value(config.GITHUB_TOKEN_FILE, config.GITHUB_TOKEN) + token = _resolve_optional_file_or_value(config.GITHUB.TOKEN_FILE, config.GITHUB.TOKEN) if not token: raise ConfigurationError( operation="vault_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) + response = client.auth.github.login(token=token, mount_point=config.GITHUB.MOUNT_POINT) _set_client_token_from_auth_response(client, response) @@ -429,15 +445,15 @@ def _authenticate_cert(client: hvac.Client, config: VaultConfig) -> None: """Authenticate with the TLS certificates auth method.""" cert_pem = "" key_pem = "" - if config.CLIENT_CERT_PATH: - cert_pem = _read_file_secret(config.CLIENT_CERT_PATH) - if config.CLIENT_KEY_PATH: - key_pem = _read_file_secret(config.CLIENT_KEY_PATH) + if config.TLS.CLIENT_CERT_PATH: + cert_pem = _read_file_secret(config.TLS.CLIENT_CERT_PATH) + if config.TLS.CLIENT_KEY_PATH: + key_pem = _read_file_secret(config.TLS.CLIENT_KEY_PATH) response = client.auth.cert.login( - name=config.CERT_NAME, + name=config.CERT.NAME, cert_pem=cert_pem, key_pem=key_pem, - mount_point=config.CERT_MOUNT_POINT, + mount_point=config.CERT.MOUNT_POINT, ) _set_client_token_from_auth_response(client, response) @@ -554,6 +570,15 @@ def _parse_verify_ssl(raw: str | None) -> bool: ) +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. @@ -567,9 +592,6 @@ def _vault_config_from_env() -> VaultConfig: reason=f"Invalid VAULT__AUTH_METHOD: {auth_method}", ) - verify_raw = os.environ.get("VAULT__VERIFY_SSL") - verify_ssl = _parse_verify_ssl(verify_raw) - return VaultConfig( ENABLED=_env_truthy("VAULT__ENABLED"), ADDR=_env_opt("VAULT__ADDR"), @@ -577,60 +599,90 @@ def _vault_config_from_env() -> VaultConfig: AUTH_METHOD=resolved_auth_method, TOKEN=_env_opt("VAULT__TOKEN"), TOKEN_FILE=_env_opt("VAULT__TOKEN_FILE"), - APPROLE_ROLE_ID=_env_opt("VAULT__APPROLE_ROLE_ID"), - APPROLE_SECRET_ID=_env_opt("VAULT__APPROLE_SECRET_ID"), - APPROLE_SECRET_ID_FILE=_env_opt("VAULT__APPROLE_SECRET_ID_FILE"), - APPROLE_MOUNT_POINT=_env_mount("VAULT__APPROLE_MOUNT_POINT", "approle"), - KUBERNETES_ROLE=_env_opt("VAULT__KUBERNETES_ROLE"), - KUBERNETES_JWT_PATH=( - os.environ.get("VAULT__KUBERNETES_JWT_PATH") or "/var/run/secrets/kubernetes.io/serviceaccount/token" - ), - KUBERNETES_MOUNT_POINT=_env_mount("VAULT__KUBERNETES_MOUNT_POINT", "kubernetes"), USERNAME=_env_opt("VAULT__USERNAME"), PASSWORD=_env_opt("VAULT__PASSWORD"), PASSWORD_FILE=_env_opt("VAULT__PASSWORD_FILE"), - USERPASS_MOUNT_POINT=_env_mount("VAULT__USERPASS_MOUNT_POINT", "userpass"), - LDAP_MOUNT_POINT=_env_mount("VAULT__LDAP_MOUNT_POINT", "ldap"), - OKTA_MOUNT_POINT=_env_mount("VAULT__OKTA_MOUNT_POINT", "okta"), - JWT_ROLE=_env_opt("VAULT__JWT_ROLE"), - JWT=_env_opt("VAULT__JWT"), - JWT_FILE=_env_opt("VAULT__JWT_FILE"), - JWT_MOUNT_POINT=_env_mount("VAULT__JWT_MOUNT_POINT", "jwt"), - AWS_ACCESS_KEY=_env_opt("VAULT__AWS_ACCESS_KEY"), - AWS_SECRET_KEY=_env_opt("VAULT__AWS_SECRET_KEY"), - AWS_SESSION_TOKEN=_env_opt("VAULT__AWS_SESSION_TOKEN"), - AWS_ROLE=_env_opt("VAULT__AWS_ROLE"), - AWS_REGION=_env_mount("VAULT__AWS_REGION", "us-east-1"), - AWS_MOUNT_POINT=_env_mount("VAULT__AWS_MOUNT_POINT", "aws"), - AZURE_ROLE=_env_opt("VAULT__AZURE_ROLE"), - AZURE_JWT=_env_opt("VAULT__AZURE_JWT"), - AZURE_JWT_FILE=_env_opt("VAULT__AZURE_JWT_FILE"), - AZURE_SUBSCRIPTION_ID=_env_opt("VAULT__AZURE_SUBSCRIPTION_ID"), - AZURE_RESOURCE_GROUP_NAME=_env_opt("VAULT__AZURE_RESOURCE_GROUP_NAME"), - AZURE_VM_NAME=_env_opt("VAULT__AZURE_VM_NAME"), - AZURE_VMSS_NAME=_env_opt("VAULT__AZURE_VMSS_NAME"), - AZURE_MOUNT_POINT=_env_mount("VAULT__AZURE_MOUNT_POINT", "azure"), - GCP_ROLE=_env_opt("VAULT__GCP_ROLE"), - GCP_JWT=_env_opt("VAULT__GCP_JWT"), - GCP_JWT_FILE=_env_opt("VAULT__GCP_JWT_FILE"), - GCP_MOUNT_POINT=_env_mount("VAULT__GCP_MOUNT_POINT", "gcp"), - GITHUB_TOKEN=_env_opt("VAULT__GITHUB_TOKEN"), - GITHUB_TOKEN_FILE=_env_opt("VAULT__GITHUB_TOKEN_FILE"), - GITHUB_MOUNT_POINT=_env_mount("VAULT__GITHUB_MOUNT_POINT", "github"), - CERT_NAME=os.environ.get("VAULT__CERT_NAME", "") or "", - CERT_MOUNT_POINT=_env_mount("VAULT__CERT_MOUNT_POINT", "cert"), MOUNT_POINT=_env_mount("VAULT__MOUNT_POINT", "secret"), SECRET_PATHS=_parse_secret_paths(os.environ.get("VAULT__SECRET_PATHS")), - VERIFY_SSL=verify_ssl, - CA_CERT_PATH=_env_opt("VAULT__CA_CERT_PATH"), - CLIENT_CERT_PATH=_env_opt("VAULT__CLIENT_CERT_PATH"), - CLIENT_KEY_PATH=_env_opt("VAULT__CLIENT_KEY_PATH"), - CONNECT_TIMEOUT=_env_float("VAULT__CONNECT_TIMEOUT", 5.0), - READ_TIMEOUT=_env_float("VAULT__READ_TIMEOUT", 10.0), - RETRIES_MAX_ATTEMPTS=_env_int("VAULT__RETRIES_MAX_ATTEMPTS", 3), - AUTO_RENEW_TOKEN=_env_truthy("VAULT__AUTO_RENEW_TOKEN"), - RENEW_THRESHOLD_SECONDS=_env_int("VAULT__RENEW_THRESHOLD_SECONDS", 60), 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"), + ), + KUBERNETES=VaultKubernetesConfig( + ROLE=_env_opt(_env_name("KUBERNETES", "ROLE", "KUBERNETES_ROLE")), + JWT_PATH=os.environ.get(_env_name("KUBERNETES", "JWT_PATH", "KUBERNETES_JWT_PATH")) + or "/var/run/secrets/kubernetes.io/serviceaccount/token", + MOUNT_POINT=_env_mount(_env_name("KUBERNETES", "MOUNT_POINT", "KUBERNETES_MOUNT_POINT"), "kubernetes"), + ), + USERPASS=VaultUserpassConfig( + MOUNT_POINT=_env_mount(_env_name("USERPASS", "MOUNT_POINT", "USERPASS_MOUNT_POINT"), "userpass"), + ), + LDAP=VaultLdapConfig( + MOUNT_POINT=_env_mount(_env_name("LDAP", "MOUNT_POINT", "LDAP_MOUNT_POINT"), "ldap"), + ), + OKTA=VaultOktaConfig( + MOUNT_POINT=_env_mount(_env_name("OKTA", "MOUNT_POINT", "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"), + ), + 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"), + ), + 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"), + ), + 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"), + ), + 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"), + ), + 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"), + ), + 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")), + ), + 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), + ), + TOKEN_RENEWAL=VaultTokenRenewalConfig( + AUTO_RENEW_TOKEN=_env_truthy(_env_name("TOKEN_RENEWAL", "AUTO_RENEW_TOKEN", "AUTO_RENEW_TOKEN")), + RENEW_THRESHOLD_SECONDS=_env_int( + _env_name("TOKEN_RENEWAL", "RENEW_THRESHOLD_SECONDS", "RENEW_THRESHOLD_SECONDS"), + 60, + ), + ), ) diff --git a/archipy/helpers/utils/_otel/metrics_export.py b/archipy/helpers/utils/_otel/metrics_export.py index 9785a47a0..c389cfda4 100644 --- a/archipy/helpers/utils/_otel/metrics_export.py +++ b/archipy/helpers/utils/_otel/metrics_export.py @@ -26,7 +26,7 @@ def resolve_grouping_key(configured: dict[str, str] | None) -> dict[str, str]: ``hostNetwork`` and the container ID on plain Docker. Args: - configured: ``METRICS_PUSHGATEWAY_GROUPING_KEY`` from the configuration. + configured: ``PUSHGATEWAY.GROUPING_KEY`` from the configuration. Returns: The grouping key to push and delete with. @@ -184,16 +184,16 @@ def start_pushgateway_unlocked(self, otel: OpentelemetryConfig) -> None: msg = "Metrics registry missing before Pushgateway start" raise RuntimeError(msg) - gateway_url = str(otel.METRICS_PUSHGATEWAY_URL or "").strip() + gateway_url = str(otel.PUSHGATEWAY.URL or "").strip() if not gateway_url: - msg = "METRICS_PUSHGATEWAY_URL is required when METRICS_EXPORTER=pushgateway" + msg = "PUSHGATEWAY.URL is required when METRICS_EXPORTER=pushgateway" raise RuntimeError(msg) - job = str(otel.METRICS_PUSHGATEWAY_JOB or otel.SERVICE_NAME or "archipy").strip() or "archipy" - grouping_key = resolve_grouping_key(otel.METRICS_PUSHGATEWAY_GROUPING_KEY) - interval = int(otel.METRICS_PUSHGATEWAY_INTERVAL_SECONDS) - timeout = float(otel.METRICS_PUSHGATEWAY_TIMEOUT_SECONDS) - delete_on_shutdown = bool(otel.METRICS_PUSHGATEWAY_DELETE_ON_SHUTDOWN) + job = str(otel.PUSHGATEWAY.JOB or otel.SERVICE_NAME or "archipy").strip() or "archipy" + grouping_key = resolve_grouping_key(otel.PUSHGATEWAY.GROUPING_KEY) + interval = int(otel.PUSHGATEWAY.INTERVAL_SECONDS) + timeout = float(otel.PUSHGATEWAY.TIMEOUT_SECONDS) + delete_on_shutdown = bool(otel.PUSHGATEWAY.DELETE_ON_SHUTDOWN) stop_event = threading.Event() self._pushgateway_stop = stop_event diff --git a/archipy/helpers/utils/app_utils.py b/archipy/helpers/utils/app_utils.py index 10e72605c..4769ee642 100644 --- a/archipy/helpers/utils/app_utils.py +++ b/archipy/helpers/utils/app_utils.py @@ -86,18 +86,18 @@ def setup_cors(app: FastAPI, config: BaseConfig) -> None: app (FastAPI): The FastAPI application instance. config (BaseConfig): The configuration object containing CORS settings. """ - origins = [str(origin).strip("/") for origin in config.FASTAPI.CORS_MIDDLEWARE_ALLOW_ORIGINS] + origins = [str(origin).strip("/") for origin in config.FASTAPI.CORS.ALLOW_ORIGINS] # Use app.add_middleware with CORSMiddleware directly # CORSMiddleware is compatible with FastAPI's middleware system at runtime app.add_middleware( CORSMiddleware, allow_origins=origins, - allow_credentials=config.FASTAPI.CORS_MIDDLEWARE_ALLOW_CREDENTIALS, - allow_methods=config.FASTAPI.CORS_MIDDLEWARE_ALLOW_METHODS, - allow_headers=config.FASTAPI.CORS_MIDDLEWARE_ALLOW_HEADERS, - allow_origin_regex=config.FASTAPI.CORS_MIDDLEWARE_ALLOW_ORIGIN_REGEX, - expose_headers=config.FASTAPI.CORS_MIDDLEWARE_EXPOSE_HEADERS, - max_age=config.FASTAPI.CORS_MIDDLEWARE_MAX_AGE, + allow_credentials=config.FASTAPI.CORS.ALLOW_CREDENTIALS, + allow_methods=config.FASTAPI.CORS.ALLOW_METHODS, + allow_headers=config.FASTAPI.CORS.ALLOW_HEADERS, + allow_origin_regex=config.FASTAPI.CORS.ALLOW_ORIGIN_REGEX, + expose_headers=config.FASTAPI.CORS.EXPOSE_HEADERS, + max_age=config.FASTAPI.CORS.MAX_AGE, ) @staticmethod @@ -108,13 +108,13 @@ def setup_gzip(app: FastAPI, config: BaseConfig) -> None: app (FastAPI): The FastAPI application instance. config (BaseConfig): The configuration object containing GZip middleware settings. """ - if not config.FASTAPI.GZIP_MIDDLEWARE_IS_ENABLED: + if not config.FASTAPI.GZIP.IS_ENABLED: return app.add_middleware( GZipMiddleware, - minimum_size=config.FASTAPI.GZIP_MIDDLEWARE_MINIMUM_SIZE, - compresslevel=config.FASTAPI.GZIP_MIDDLEWARE_COMPRESSLEVEL, + minimum_size=config.FASTAPI.GZIP.MINIMUM_SIZE, + compresslevel=config.FASTAPI.GZIP.COMPRESSLEVEL, ) @staticmethod @@ -125,20 +125,20 @@ def setup_trusted_host(app: FastAPI, config: BaseConfig) -> None: app (FastAPI): The FastAPI application instance. config (BaseConfig): The configuration object containing TrustedHost middleware settings. """ - if not config.FASTAPI.TRUSTED_HOST_MIDDLEWARE_IS_ENABLED: + if not config.FASTAPI.TRUSTED_HOST.IS_ENABLED: return - allowed_hosts = config.FASTAPI.TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS + allowed_hosts = config.FASTAPI.TRUSTED_HOST.ALLOWED_HOSTS if not allowed_hosts: logger.warning( - "TrustedHost middleware enabled but TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS is empty; skipping", + "TrustedHost middleware enabled but TRUSTED_HOST.ALLOWED_HOSTS is empty; skipping", ) return app.add_middleware( TrustedHostMiddleware, allowed_hosts=allowed_hosts, - www_redirect=config.FASTAPI.TRUSTED_HOST_MIDDLEWARE_WWW_REDIRECT, + www_redirect=config.FASTAPI.TRUSTED_HOST.WWW_REDIRECT, ) @staticmethod @@ -149,7 +149,7 @@ def setup_https_redirect(app: FastAPI, config: BaseConfig) -> None: app (FastAPI): The FastAPI application instance. config (BaseConfig): The configuration object containing HTTPS redirect middleware settings. """ - if not config.FASTAPI.HTTPS_REDIRECT_MIDDLEWARE_IS_ENABLED: + if not config.FASTAPI.HTTPS_REDIRECT.IS_ENABLED: return app.add_middleware(HTTPSRedirectMiddleware) @@ -444,14 +444,23 @@ 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 + 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 - if name in uvicorn_section.model_fields_set or name not in UVICORN_FIELDS_ON_FASTAPI: - return getattr(uvicorn_section, name) + 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", @@ -459,7 +468,7 @@ def resolve(name: str) -> Any: # noqa: ANN401 stacklevel=3, ) return vars(fastapi_section)[name] # read without the pydantic deprecation warning - return getattr(uvicorn_section, name) + return value values = { "host": fastapi_section.SERVE_HOST, @@ -479,9 +488,9 @@ def resolve(name: str) -> Any: # noqa: ANN401 "ws_per_message_deflate": resolve("WS_PER_MESSAGE_DEFLATE"), "ws_ping_interval": resolve("WS_PING_INTERVAL"), "ws_ping_timeout": resolve("WS_PING_TIMEOUT"), - "ssl_keyfile": uvicorn_section.SSL_KEYFILE, - "ssl_certfile": uvicorn_section.SSL_CERTFILE, - "ssl_ca_certs": uvicorn_section.SSL_CA_CERTS, + "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") @@ -697,7 +706,7 @@ def _read_pem(path: str | None) -> bytes | None: @classmethod def add_grpc_port(cls, server: grpc.Server | GrpcAioServer, config: BaseConfig, address: str | None = None) -> int: - """Bind a port on a gRPC server, using TLS when ``GRPC.TLS_ENABLED`` is set. + """Bind a port on a gRPC server, using TLS when ``GRPC.TLS.IS_ENABLED`` is set. Without TLS this calls ``add_insecure_port``, so existing setups keep working. @@ -711,22 +720,22 @@ def add_grpc_port(cls, server: grpc.Server | GrpcAioServer, config: BaseConfig, """ grpc_config = config.GRPC bind_address = address or f"{grpc_config.SERVE_HOST}:{grpc_config.SERVE_PORT}" - if not grpc_config.TLS_ENABLED: + if not grpc_config.TLS.IS_ENABLED: return server.add_insecure_port(bind_address) - private_key = cls._read_pem(grpc_config.TLS_KEY_FILE) - certificate_chain = cls._read_pem(grpc_config.TLS_CERT_FILE) + private_key = cls._read_pem(grpc_config.TLS.KEY_FILE) + certificate_chain = cls._read_pem(grpc_config.TLS.CERT_FILE) if private_key is None or certificate_chain is None: raise ConfigurationError(operation="grpc_tls", reason="missing_server_certificate_or_key") credentials = grpc.ssl_server_credentials( [(private_key, certificate_chain)], - root_certificates=cls._read_pem(grpc_config.TLS_CA_FILE), - require_client_auth=grpc_config.TLS_REQUIRE_CLIENT_AUTH, + root_certificates=cls._read_pem(grpc_config.TLS.CA_FILE), + require_client_auth=grpc_config.TLS.REQUIRE_CLIENT_AUTH, ) return server.add_secure_port(bind_address, credentials) @classmethod def create_grpc_channel(cls, config: BaseConfig, target: str, *, aio: bool = False) -> grpc.Channel: - """Create a client channel, using TLS when ``GRPC.STUB_TLS_ENABLED`` is set. + """Create a client channel, using TLS when ``GRPC.STUB_TLS.IS_ENABLED`` is set. Channel options come from ``GRPC.STUB_OPTIONS_CONFIG_LIST`` and compression from ``GRPC.STUB_COMPRESSION``. Without TLS the channel is plaintext. @@ -743,12 +752,12 @@ def create_grpc_channel(cls, config: BaseConfig, target: str, *, aio: bool = Fal options = grpc_config.STUB_OPTIONS_CONFIG_LIST compression = cls._grpc_compression(grpc_config.STUB_COMPRESSION) module: Any = grpc_aio if aio else grpc - if not grpc_config.STUB_TLS_ENABLED: + if not grpc_config.STUB_TLS.IS_ENABLED: return module.insecure_channel(target, options=options, compression=compression) credentials = grpc.ssl_channel_credentials( - root_certificates=cls._read_pem(grpc_config.STUB_TLS_CA_FILE), - private_key=cls._read_pem(grpc_config.STUB_TLS_KEY_FILE), - certificate_chain=cls._read_pem(grpc_config.STUB_TLS_CERT_FILE), + root_certificates=cls._read_pem(grpc_config.STUB_TLS.CA_FILE), + private_key=cls._read_pem(grpc_config.STUB_TLS.KEY_FILE), + certificate_chain=cls._read_pem(grpc_config.STUB_TLS.CERT_FILE), ) return module.secure_channel(target, credentials, options=options, compression=compression) diff --git a/archipy/helpers/utils/jwt_utils.py b/archipy/helpers/utils/jwt_utils.py index 6140c3045..a37576778 100644 --- a/archipy/helpers/utils/jwt_utils.py +++ b/archipy/helpers/utils/jwt_utils.py @@ -25,7 +25,7 @@ def _validated_algorithm(configs: AuthConfig) -> str: """Return the configured signing algorithm, refusing the unsigned ``none`` algorithm.""" - algorithm = configs.HASH_ALGORITHM + algorithm = configs.JWT.ALGORITHM if not algorithm or algorithm.lower() == "none": raise InvalidArgumentError("HASH_ALGORITHM") return algorithm @@ -41,7 +41,7 @@ def _validated_secret(configs: AuthConfig) -> str: if secret_key is None: raise InvalidArgumentError("SECRET_KEY") value = secret_key.get_secret_value() - minimum = _MIN_HMAC_KEY_BYTES.get(configs.HASH_ALGORITHM.upper(), 0) + minimum = _MIN_HMAC_KEY_BYTES.get(configs.JWT.ALGORITHM.upper(), 0) if len(value.encode("utf-8")) < minimum: raise InvalidArgumentError("SECRET_KEY", additional_data={"detail": f"at least {minimum} bytes required"}) return value @@ -100,8 +100,8 @@ def create_token( to_encode.update( { # Registered claims (RFC 7519) - "iss": configs.JWT_ISSUER, - "aud": configs.JWT_AUDIENCE, + "iss": configs.JWT.ISSUER, + "aud": configs.JWT.AUDIENCE, "exp": expire, "iat": current_time, "nbf": current_time, @@ -109,7 +109,7 @@ def create_token( ) # Add JWT ID if enabled - if configs.ENABLE_JTI_CLAIM: + if configs.JWT.ENABLE_JTI_CLAIM: to_encode["jti"] = str(uuid4()) # Add additional claims @@ -144,9 +144,9 @@ def create_access_token( data={ "sub": str(user_uuid), "type": "access", - "token_version": configs.TOKEN_VERSION, + "token_version": configs.JWT.TOKEN_VERSION, }, - expires_in=configs.ACCESS_TOKEN_EXPIRES_IN, + expires_in=configs.JWT.ACCESS_TOKEN_EXPIRES_IN, additional_claims=additional_claims, auth_config=configs, ) @@ -175,9 +175,9 @@ def create_refresh_token( data={ "sub": str(user_uuid), "type": "refresh", - "token_version": configs.TOKEN_VERSION, + "token_version": configs.JWT.TOKEN_VERSION, }, - expires_in=configs.REFRESH_TOKEN_EXPIRES_IN, + expires_in=configs.JWT.REFRESH_TOKEN_EXPIRES_IN, additional_claims=additional_claims, auth_config=configs, ) @@ -209,7 +209,7 @@ def decode_token( configs = auth_config or BaseConfig.global_config().AUTH required_claims = ["exp", "iat", "nbf", "aud", "iss", "sub", "type", "token_version"] - if configs.ENABLE_JTI_CLAIM: + if configs.JWT.ENABLE_JTI_CLAIM: required_claims.append("jti") try: @@ -228,9 +228,9 @@ def decode_token( "verify_iss": True, "require": required_claims, }, - audience=configs.JWT_AUDIENCE, - issuer=configs.JWT_ISSUER, - leeway=configs.JWT_LEEWAY, + audience=configs.JWT.AUDIENCE, + issuer=configs.JWT.ISSUER, + leeway=configs.JWT.LEEWAY, ) # Verify token type @@ -238,7 +238,7 @@ def decode_token( raise InvalidTokenError # Verify token version - if payload.get("token_version") != configs.TOKEN_VERSION: + if payload.get("token_version") != configs.JWT.TOKEN_VERSION: raise InvalidTokenError # Ensure the return type is dict[str, object] as declared diff --git a/archipy/helpers/utils/password_utils.py b/archipy/helpers/utils/password_utils.py index 4cced44c2..f2ec34415 100644 --- a/archipy/helpers/utils/password_utils.py +++ b/archipy/helpers/utils/password_utils.py @@ -43,8 +43,8 @@ def hash_password(password: str, auth_config: AuthConfig | None = None) -> str: ``HASH_ITERATIONS`` or ``SALT_LENGTH`` later does not invalidate existing hashes. """ configs = auth_config or BaseConfig.global_config().AUTH - salt = os.urandom(configs.SALT_LENGTH) - iterations = configs.HASH_ITERATIONS + salt = os.urandom(configs.PASSWORD_POLICY.SALT_LENGTH) + iterations = configs.PASSWORD_POLICY.HASH_ITERATIONS pw_hash = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, iterations) return _HASH_SEPARATOR.join( @@ -79,9 +79,9 @@ def verify_password(password: str, stored_password: str, auth_config: AuthConfig # Legacy format: base64(salt + hash) decoded = b64decode(stored_password.encode("utf-8")) - salt = decoded[: configs.SALT_LENGTH] - stored_hash = decoded[configs.SALT_LENGTH :] - candidates = dict.fromkeys((configs.HASH_ITERATIONS, _LEGACY_DEFAULT_ITERATIONS)) + salt = decoded[: configs.PASSWORD_POLICY.SALT_LENGTH] + stored_hash = decoded[configs.PASSWORD_POLICY.SALT_LENGTH :] + candidates = dict.fromkeys((configs.PASSWORD_POLICY.HASH_ITERATIONS, _LEGACY_DEFAULT_ITERATIONS)) return any(PasswordUtils._matches(password, salt, stored_hash, count) for count in candidates) except ValueError, TypeError, IndexError: # Catch specific exceptions that could occur during decoding or comparison @@ -113,20 +113,24 @@ def validate_password( configs = auth_config or BaseConfig.global_config().AUTH errors = [] - if len(password) < configs.MIN_LENGTH: - errors.append(f"Password must be at least {configs.MIN_LENGTH} characters long.") + if len(password) < configs.PASSWORD_POLICY.MIN_LENGTH: + errors.append(f"Password must be at least {configs.PASSWORD_POLICY.MIN_LENGTH} characters long.") - if configs.REQUIRE_DIGIT and not any(char.isdigit() for char in password): + if configs.PASSWORD_POLICY.REQUIRE_DIGIT and not any(char.isdigit() for char in password): errors.append("Password must contain at least one digit.") - if configs.REQUIRE_LOWERCASE and not any(char.islower() for char in password): + if configs.PASSWORD_POLICY.REQUIRE_LOWERCASE and not any(char.islower() for char in password): errors.append("Password must contain at least one lowercase letter.") - if configs.REQUIRE_UPPERCASE and not any(char.isupper() for char in password): + if configs.PASSWORD_POLICY.REQUIRE_UPPERCASE and not any(char.isupper() for char in password): errors.append("Password must contain at least one uppercase letter.") - if configs.REQUIRE_SPECIAL and not any(char in configs.SPECIAL_CHARACTERS for char in password): - errors.append(f"Password must contain at least one special character: {configs.SPECIAL_CHARACTERS}") + if configs.PASSWORD_POLICY.REQUIRE_SPECIAL and not any( + char in configs.PASSWORD_POLICY.SPECIAL_CHARACTERS for char in password + ): + errors.append( + f"Password must contain at least one special character: {configs.PASSWORD_POLICY.SPECIAL_CHARACTERS}", + ) if errors: raise InvalidPasswordError(requirements=errors) @@ -147,21 +151,21 @@ def generate_password(auth_config: AuthConfig | None = None) -> str: lowercase_chars = string.ascii_lowercase uppercase_chars = string.ascii_uppercase digit_chars = string.digits - special_chars = "".join(configs.SPECIAL_CHARACTERS) + special_chars = "".join(configs.PASSWORD_POLICY.SPECIAL_CHARACTERS) # Initialize with required characters password_chars = [] - if configs.REQUIRE_LOWERCASE: + if configs.PASSWORD_POLICY.REQUIRE_LOWERCASE: password_chars.append(secrets.choice(lowercase_chars)) - if configs.REQUIRE_UPPERCASE: + if configs.PASSWORD_POLICY.REQUIRE_UPPERCASE: password_chars.append(secrets.choice(uppercase_chars)) - if configs.REQUIRE_DIGIT: + if configs.PASSWORD_POLICY.REQUIRE_DIGIT: password_chars.append(secrets.choice(digit_chars)) - if configs.REQUIRE_SPECIAL: + if configs.PASSWORD_POLICY.REQUIRE_SPECIAL: password_chars.append(secrets.choice(special_chars)) # Calculate remaining length - remaining_length = max(0, configs.MIN_LENGTH - len(password_chars)) + remaining_length = max(0, configs.PASSWORD_POLICY.MIN_LENGTH - len(password_chars)) # Add random characters to meet minimum length all_chars = lowercase_chars + uppercase_chars + digit_chars + special_chars @@ -199,7 +203,7 @@ def validate_password_history( cls.validate_password(new_password, configs) # Check password history (a size of 0 disables the check) - history_size = max(configs.PASSWORD_HISTORY_SIZE, 0) + history_size = max(configs.PASSWORD_POLICY.HISTORY_SIZE, 0) if history_size and any( cls.verify_password(new_password, old_password, configs) for old_password in password_history[-history_size:] diff --git a/archipy/helpers/utils/totp_utils.py b/archipy/helpers/utils/totp_utils.py index 10d26aed2..fe1bba379 100644 --- a/archipy/helpers/utils/totp_utils.py +++ b/archipy/helpers/utils/totp_utils.py @@ -105,15 +105,15 @@ def generate_totp(cls, secret: str | UUID, auth_config: AuthConfig | None = None # Get current timestamp and calculate time step current_time = DatetimeUtils.get_epoch_time_now() - time_step_counter = int(current_time / configs.TOTP_TIME_STEP) + time_step_counter = int(current_time / configs.TOTP.TIME_STEP) # Use the dedicated TOTP hash algorithm from config, with fallback to SHA1 hash_algo = getattr(configs, "TOTP_HASH_ALGORITHM", "SHA1") - totp_code = _compute_totp(_secret_to_key(secret), time_step_counter, hash_algo, configs.TOTP_LENGTH) + totp_code = _compute_totp(_secret_to_key(secret), time_step_counter, hash_algo, configs.TOTP.LENGTH) # The code is accepted until the last step of the verification window ends, so never report a later expiry. - valid_until = (time_step_counter + configs.TOTP_VERIFICATION_WINDOW + 1) * configs.TOTP_TIME_STEP - lifetime = min(configs.TOTP_EXPIRES_IN, max(valid_until - current_time, 0)) + valid_until = (time_step_counter + configs.TOTP.VERIFICATION_WINDOW + 1) * configs.TOTP.TIME_STEP + lifetime = min(configs.TOTP.EXPIRES_IN, max(valid_until - current_time, 0)) expires_in = DatetimeUtils.get_datetime_after_given_datetime_or_now(seconds=lifetime) return totp_code, expires_in @@ -165,7 +165,7 @@ def verify_totp( configs = auth_config or BaseConfig.global_config().AUTH # The expected length comes from the config, never from the caller's input. - if len(totp_code) != configs.TOTP_LENGTH: + if len(totp_code) != configs.TOTP.LENGTH: return False current_time = DatetimeUtils.get_epoch_time_now() @@ -174,12 +174,12 @@ def verify_totp( hash_algo = getattr(configs, "TOTP_HASH_ALGORITHM", "SHA1") key = _secret_to_key(secret) - current_step = int(current_time / configs.TOTP_TIME_STEP) + current_step = int(current_time / configs.TOTP.TIME_STEP) # Check every step in the window without early exit so timing does not reveal which step matched matched_step: int | None = None - for i in range(-configs.TOTP_VERIFICATION_WINDOW, configs.TOTP_VERIFICATION_WINDOW + 1): - computed_totp = _compute_totp(key, current_step + i, hash_algo, configs.TOTP_LENGTH) + for i in range(-configs.TOTP.VERIFICATION_WINDOW, configs.TOTP.VERIFICATION_WINDOW + 1): + computed_totp = _compute_totp(key, current_step + i, hash_algo, configs.TOTP.LENGTH) if hmac.compare_digest(totp_code, computed_totp): matched_step = current_step + i @@ -205,13 +205,13 @@ def generate_secret_key_for_totp(auth_config: AuthConfig | None = None) -> str: configs = auth_config or BaseConfig.global_config().AUTH # Use secrets module instead of random for better security - random_bytes = secrets.token_bytes(configs.SALT_LENGTH) + random_bytes = secrets.token_bytes(configs.PASSWORD_POLICY.SALT_LENGTH) # Check if TOTP secret key is configured - if not configs.TOTP_SECRET_KEY: + if not configs.TOTP.SECRET_KEY: _raise_missing_totp_secret() - master_key = configs.TOTP_SECRET_KEY.get_secret_value().encode("utf-8") + master_key = configs.TOTP.SECRET_KEY.get_secret_value().encode("utf-8") # Use the dedicated TOTP hash algorithm from config, with fallback to SHA1 hash_algo = getattr(configs, "TOTP_HASH_ALGORITHM", "SHA1") diff --git a/docs/api_reference/configs.md b/docs/api_reference/configs.md index 6514980bb..9645a2d3b 100644 --- a/docs/api_reference/configs.md +++ b/docs/api_reference/configs.md @@ -23,6 +23,32 @@ class AppConfig(BaseConfig): DB_PORT: int = 5432 ``` +## Nested Settings + +Related settings live in nested groups of a section, for example `REDIS.TLS`, `VAULT.APPROLE`, or `AUTH.JWT`. Groups +reject unknown keys, and every switch is named `IS_ENABLED`. Set them in code, or with the `__` delimiter in the +environment: + +```bash +REDIS__TLS__IS_ENABLED=true +REDIS__TLS__CA_CERTS=/certs/ca.pem +VAULT__APPROLE__ROLE_ID=my-role +AUTH__JWT__ISSUER=my-service +``` + +```python +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. + +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`, +`TRUSTED_HOST`, `HTTPS_REDIRECT`). + ## API Stability | Component | Status | Notes | diff --git a/docs/community/changelog/5/5.32.0.md b/docs/community/changelog/5/5.32.0.md index 6718899c1..e231f97c3 100644 --- a/docs/community/changelog/5/5.32.0.md +++ b/docs/community/changelog/5/5.32.0.md @@ -13,6 +13,31 @@ description: "Release notes for ArchiPy 5.32.0" - **Request Body and Form Limits** - Set `FASTAPI.MAX_BODY_SIZE` to cap the total request body in bytes, including uploaded files and multipart overhead. Use `FASTAPI.FORM_LIMITS` to limit the number of fields and files and the size of each text field. FastAPI uses its defaults for omitted form settings. Set the limits as `FASTAPI.FORM_LIMITS.MAX_FIELDS`, `MAX_FILES`, and `MAX_PART_SIZE`, or with environment variables such as `FASTAPI__FORM_LIMITS__MAX_FIELDS`. Oversized bodies return HTTP 413, and form parsing limit violations return HTTP 400. [#610](https://github.com/SyntaxArc/ArchiPy/pull/610), [#620](https://github.com/SyntaxArc/ArchiPy/pull/620) +### Configs - Nested Settings + +- **Grouped Settings** - Related settings now live in nested groups of their section. Groups reject unknown keys, use + UPPER_CASE fields, and name every on/off switch `IS_ENABLED`. Set them in code or with the `__` delimiter, for + example `REDIS__TLS__IS_ENABLED=true`. The flat settings they replace still work, emit a `DeprecationWarning` that + names the new path, and are removed in 6.0.0; a value set on a group wins over the flat one. For example + `REDIS.SSL` is now `REDIS.TLS.IS_ENABLED`, `VAULT.APPROLE_ROLE_ID` is `VAULT.APPROLE.ROLE_ID`, and + `AUTH.JWT_ISSUER` is `AUTH.JWT.ISSUER`. [#622](https://github.com/SyntaxArc/ArchiPy/pull/622) + - `VAULT`: `APPROLE`, `KUBERNETES`, `USERPASS`, `LDAP`, `OKTA`, `JWT_AUTH`, `AWS`, `AZURE`, `GCP`, `GITHUB`, + `CERT`, `TLS`, `HTTP`, `TOKEN_RENEWAL` + - `SCYLLADB`: `TLS`, `RETRY`, `RECONNECTION`, `SPECULATIVE_EXECUTION`, `PREPARED_CACHE`, `HEARTBEAT`, + `REPLICATION` + - `TEMPORAL`: `TLS`, `WORKER`, `CLIENT_RETRY`, `KEEP_ALIVE`, `WORKFLOW`, `ACTIVITY`, `RETRY` + - `REDIS`: `CLUSTER`, `SENTINEL`, `TLS`, `RETRY` + - `ELASTIC`: `AUTH`, `TLS`, `RETRY`, `SNIFFING` + - `SQLALCHEMY`: `POOL`, `COUNT_CACHE` + - `AUTH`: `JWT`, `TOTP`, `RATE_LIMITS`, `PASSWORD_POLICY` + - `KEYCLOAK`: `ADMIN`, `TLS`, `TOKEN_VALIDATION` + - `EMAIL`: `TLS`, `POOL`, `ATTACHMENTS` + - `GRPC`: `TLS`, `STUB_TLS` + - `KAFKA`: `SASL`, `SSL` + - `UVICORN`: `TLS`, `WEBSOCKET`, `LIMITS` + - `FASTAPI`: `CORS`, `GZIP`, `TRUSTED_HOST`, `HTTPS_REDIRECT` + - `OTEL`: `PUSHGATEWAY` + ## Changed ### Chore - Documentation diff --git a/docs/community/changelog/5/index.md b/docs/community/changelog/5/index.md index c0d3373c3..1998dc745 100644 --- a/docs/community/changelog/5/index.md +++ b/docs/community/changelog/5/index.md @@ -9,7 +9,7 @@ description: "Release history for ArchiPy 5.x series" | Version | Date | Summary | |-------------------|------------|----------------------------------------------------------------------------------------------------------------------------------| -| [5.32.0](5.32.0.md) | 2026-11-21 | Configurable FastAPI request and form limits, Zensical docs, and Python 3.15 CI | +| [5.32.0](5.32.0.md) | 2026-11-21 | Configurable FastAPI request and form limits, nested settings groups, Zensical docs, and Python 3.15 CI | | [5.31.2](5.31.2.md) | 2026-11-18 | Dependency minimums aligned with the refreshed lockfile and PostgreSQL test image updated | | [5.31.1](5.31.1.md) | 2026-11-17 | Dependency minimums aligned with uv.lock and Temporal, Vault, Mailpit, and ScyllaDB test images updated | | [5.31.0](5.31.0.md) | 2026-11-16 | Enriched OwnerDTO, explicit UUID fields, OIDC subject alias, and combined authenticated actor/owner helpers | diff --git a/features/app_utils.feature b/features/app_utils.feature index 749b3eaaa..bf2d421e5 100644 --- a/features/app_utils.feature +++ b/features/app_utils.feature @@ -309,14 +309,21 @@ Feature: App Utilities Then the gRPC config should be 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 | + | 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 | + | 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 | Scenario Outline: A rate limiter that fails to start stops a fail-closed gRPC server Given gRPC rate limiting is enabled with fail closed set to and a Redis client that cannot be created @@ -394,6 +401,49 @@ Feature: App Utilities 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 + Given a configuration built from: + """ + { + "UVICORN": { + "WEBSOCKET": { + "MAX_SIZE": 1024 + }, + "LIMITS": { + "BACKLOG": 10, + "CONCURRENCY": 5 + } + }, + "FASTAPI": { + "WS_MAX_SIZE": 2048 + } + } + """ + When the uvicorn arguments are built + Then the uvicorn argument "ws_max_size" is 1024 + And the uvicorn argument "backlog" is 10 + 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: """ diff --git a/features/base_config.feature b/features/base_config.feature index e80211083..b3a088142 100644 --- a/features/base_config.feature +++ b/features/base_config.feature @@ -55,7 +55,7 @@ Feature: Base Configuration System When the global configuration is set Then OTEL.SERVICE_NAME should be "my-service" And FASTAPI.PROJECT_NAME should be "my-service" - And AUTH.JWT_ISSUER should be "my-service" + And AUTH.JWT.ISSUER should be "my-service" And TEMPORAL.CLIENT_IDENTITY should be "my-service" Scenario: Explicit nested identity overrides win over APP_NAME @@ -234,12 +234,19 @@ Feature: Base Configuration System | section | problem | outcome | | Kafka | SASL_SSL without credentials | rejected | | Kafka | SASL_SSL with credentials | accepted | + | Kafka | grouped SASL_SSL with credentials | accepted | + | Kafka | grouped SASL_SSL without a password | rejected | | 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 | + | Redis | grouped sentinel mode without a service name | rejected | + | Redis | grouped client certificate without a key | rejected | + | 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 | @@ -248,7 +255,15 @@ Feature: Base Configuration System | 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 | | Elasticsearch | only a password | rejected | | Elasticsearch | only an API key | rejected | | Elasticsearch | only an API secret | rejected | @@ -258,6 +273,8 @@ Feature: Base Configuration System | Elasticsearch | an unknown node selector | rejected | | Elasticsearch | the random node selector | accepted | | Temporal | only a client certificate | rejected | + | OpenTelemetry | a pushgateway exporter without a URL | rejected | + | 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 | @@ -265,6 +282,10 @@ Feature: Base Configuration System | 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 | Scenario Outline: A ScyllaDB configuration with builds When a ScyllaDB TLS context is built with @@ -398,3 +419,16 @@ Feature: Base Configuration System | async | sqlite | TIMEOUT | 2.5 | {"timeout": 2.5} | | 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 + + 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 | diff --git a/features/email_adapter.feature b/features/email_adapter.feature index fd77eeb98..4efbbbce4 100644 --- a/features/email_adapter.feature +++ b/features/email_adapter.feature @@ -135,7 +135,7 @@ Feature: Email adapter 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" + Then an email deprecation warning mentions "TLS.MODE" Scenario Outline: Insecure credential and verification settings warn Given the Mailpit SMTP server is configured @@ -146,8 +146,8 @@ Feature: Email adapter 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 | + | starttls | without certificate verification | TLS.VERIFY=False | + | implicit | without certificate verification | TLS.VERIFY=False | Scenario Outline: Out-of-range pool, retry and timeout settings are rejected When I build an email config with set to diff --git a/features/environment.py b/features/environment.py index dbf591c61..9000ff462 100644 --- a/features/environment.py +++ b/features/environment.py @@ -231,7 +231,7 @@ def after_scenario(context: Context, scenario: Scenario) -> None: global_config.VAULT.ADDR = instance.addr global_config.VAULT.TOKEN = SecretStr(instance.root_token) global_config.VAULT.AUTH_METHOD = "token" - global_config.VAULT.VERIFY_SSL = False + global_config.VAULT.TLS.VERIFY_SSL = False global_config.VAULT.MOUNT_POINT = "secret" except Exception: pass diff --git a/features/jwt_utils.feature b/features/jwt_utils.feature index bfe264afc..8e4fea911 100644 --- a/features/jwt_utils.feature +++ b/features/jwt_utils.feature @@ -71,6 +71,10 @@ 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/redis_adapter.feature b/features/redis_adapter.feature index 629e42e40..5f6e090cb 100644 --- a/features/redis_adapter.feature +++ b/features/redis_adapter.feature @@ -1503,7 +1503,7 @@ Feature: Redis Testing Examples: Settings | settings | warning | | TLS disabled | without SSL | - | TLS enabled without hostname checks | SSL_CHECK_HOSTNAME | + | TLS enabled without hostname checks | TLS.CHECK_HOSTNAME | Scenario Outline: upsert_hash writes one atomic HSET and deprecates replace False Given a configured container diff --git a/features/steps/app_utils_steps.py b/features/steps/app_utils_steps.py index 65b33a13f..c96fffcf9 100644 --- a/features/steps/app_utils_steps.py +++ b/features/steps/app_utils_steps.py @@ -273,7 +273,7 @@ def step_when_options_preflight_type(context, preflight_type): scenario_context = get_current_scenario_context(context) app = scenario_context.get("app") test_config = BaseConfig.global_config() - allowed_origin = test_config.FASTAPI.CORS_MIDDLEWARE_ALLOW_ORIGINS[0] + allowed_origin = test_config.FASTAPI.CORS.ALLOW_ORIGINS[0] client = TestClient(app) @@ -402,10 +402,10 @@ def step_then_check_422_error(context): def _reset_optional_middleware_config(fastapi_config) -> None: - fastapi_config.GZIP_MIDDLEWARE_IS_ENABLED = False - fastapi_config.TRUSTED_HOST_MIDDLEWARE_IS_ENABLED = False - fastapi_config.TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS = [] - fastapi_config.HTTPS_REDIRECT_MIDDLEWARE_IS_ENABLED = False + fastapi_config.GZIP.IS_ENABLED = False + fastapi_config.TRUSTED_HOST.IS_ENABLED = False + fastapi_config.TRUSTED_HOST.ALLOWED_HOSTS = [] + fastapi_config.HTTPS_REDIRECT.IS_ENABLED = False @given("a FastAPI app with GZip middleware enabled") @@ -413,7 +413,7 @@ def step_given_fastapi_app_with_gzip(context): scenario_context = get_current_scenario_context(context) test_config = BaseConfig.global_config() _reset_optional_middleware_config(test_config.FASTAPI) - test_config.FASTAPI.GZIP_MIDDLEWARE_IS_ENABLED = True + test_config.FASTAPI.GZIP.IS_ENABLED = True app = AppUtils.create_fastapi_app(test_config, configure_exception_handlers=False) @@ -433,8 +433,8 @@ def step_given_fastapi_app_with_trusted_host(context, host): scenario_context = get_current_scenario_context(context) test_config = BaseConfig.global_config() _reset_optional_middleware_config(test_config.FASTAPI) - test_config.FASTAPI.TRUSTED_HOST_MIDDLEWARE_IS_ENABLED = True - test_config.FASTAPI.TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS = [host] + test_config.FASTAPI.TRUSTED_HOST.IS_ENABLED = True + test_config.FASTAPI.TRUSTED_HOST.ALLOWED_HOSTS = [host] app = AppUtils.create_fastapi_app(test_config, configure_exception_handlers=False) _add_test_endpoint(app) @@ -446,7 +446,7 @@ def step_given_fastapi_app_trusted_host_empty_hosts(context): scenario_context = get_current_scenario_context(context) test_config = BaseConfig.global_config() _reset_optional_middleware_config(test_config.FASTAPI) - test_config.FASTAPI.TRUSTED_HOST_MIDDLEWARE_IS_ENABLED = True + test_config.FASTAPI.TRUSTED_HOST.IS_ENABLED = True app = AppUtils.create_fastapi_app(test_config, configure_exception_handlers=False) scenario_context.store("app", app) @@ -457,7 +457,7 @@ def step_given_fastapi_app_with_https_redirect(context): scenario_context = get_current_scenario_context(context) test_config = BaseConfig.global_config() _reset_optional_middleware_config(test_config.FASTAPI) - test_config.FASTAPI.HTTPS_REDIRECT_MIDDLEWARE_IS_ENABLED = True + test_config.FASTAPI.HTTPS_REDIRECT.IS_ENABLED = True app = AppUtils.create_fastapi_app(test_config, configure_exception_handlers=False) _add_test_endpoint(app) @@ -704,15 +704,19 @@ def _tls_grpc_config(directory: Path, *, mtls: bool, client_cert: bool) -> BaseC cert_path, key_path = _write_self_signed_certificate(directory) return _config_with_grpc( GrpcConfig( - TLS_ENABLED=True, - TLS_CERT_FILE=str(cert_path), - TLS_KEY_FILE=str(key_path), - TLS_CA_FILE=str(cert_path) if mtls else None, - TLS_REQUIRE_CLIENT_AUTH=mtls, - STUB_TLS_ENABLED=True, - STUB_TLS_CA_FILE=str(cert_path), - STUB_TLS_CERT_FILE=str(cert_path) if client_cert else None, - STUB_TLS_KEY_FILE=str(key_path) if client_cert else None, + TLS={ + "IS_ENABLED": True, + "CERT_FILE": str(cert_path), + "KEY_FILE": str(key_path), + "CA_FILE": str(cert_path) if mtls else None, + "REQUIRE_CLIENT_AUTH": mtls, + }, + STUB_TLS={ + "IS_ENABLED": True, + "CA_FILE": str(cert_path), + "CERT_FILE": str(cert_path) if client_cert else None, + "KEY_FILE": str(key_path) if client_cert else None, + }, ), ) @@ -816,8 +820,14 @@ async def call() -> str: def step_when_grpc_config_built(context, settings): scenario_context = get_current_scenario_context(context) keys = settings.split(",") - values: dict[str, bool | str] = {key: True for key in keys if key in {"TLS_ENABLED", "TLS_REQUIRE_CLIENT_AUTH"}} - values.update({key: "/nonexistent/x.pem" for key in keys if key.endswith("_FILE")}) + values: dict = {} + 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"}: + target[name] = True + elif name.endswith("_FILE"): + target[name] = "/nonexistent/x.pem" try: GrpcConfig(**values) scenario_context.store("grpc_config_error", None) @@ -845,7 +855,9 @@ def step_given_rate_limit_enabled_failing_redis(context, fail_closed): # A sentinel-mode Redis config without a service name makes the real RedisAdapter refuse to build its clients. global_config = BaseConfig.global_config() original_redis = global_config.REDIS - global_config.REDIS = original_redis.model_copy(update={"MODE": RedisMode.SENTINEL, "SENTINEL_SERVICE_NAME": None}) + global_config.REDIS = original_redis.model_copy( + update={"MODE": RedisMode.SENTINEL, "SENTINEL": original_redis.SENTINEL.model_copy(update={"SERVICE_NAME": None})}, + ) def restore_redis() -> None: global_config.REDIS = original_redis @@ -904,8 +916,8 @@ def _store_websocket_app(context, configure) -> None: @given('a FastAPI app with TrustedHost middleware enabled for "{host}" and an echo WebSocket') def step_given_trusted_host_websocket_app(context, host): def configure(fastapi_config): - fastapi_config.TRUSTED_HOST_MIDDLEWARE_IS_ENABLED = True - fastapi_config.TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS = [host] + fastapi_config.TRUSTED_HOST.IS_ENABLED = True + fastapi_config.TRUSTED_HOST.ALLOWED_HOSTS = [host] _store_websocket_app(context, configure) @@ -914,7 +926,7 @@ def configure(fastapi_config): def step_given_https_redirect_websocket_app(context, state): _store_websocket_app( context, - lambda fastapi_config: setattr(fastapi_config, "HTTPS_REDIRECT_MIDDLEWARE_IS_ENABLED", state == "enabled"), + lambda fastapi_config: setattr(fastapi_config.HTTPS_REDIRECT, "IS_ENABLED", state == "enabled"), ) diff --git a/features/steps/base_config_steps.py b/features/steps/base_config_steps.py index 73fa7c54d..f886a3702 100644 --- a/features/steps/base_config_steps.py +++ b/features/steps/base_config_steps.py @@ -16,13 +16,14 @@ from cryptography.x509.oid import NameOID from features.environment import TestConfig from features.test_helpers import get_current_scenario_context -from pydantic import ValidationError +from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator from archipy.adapters.vault.adapters import VaultAdapter from archipy.configs.base_config import BaseConfig from archipy.configs.config_template import ( ElasticsearchConfig, KafkaConfig, + OpentelemetryConfig, PostgresSQLAlchemyConfig, RedisConfig, ScyllaDBConfig, @@ -31,6 +32,7 @@ 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 @@ -224,7 +226,7 @@ def step_given_app_name_with_identity_defaults(context, app_name): config.APP_NAME = app_name config.OTEL.SERVICE_NAME = None config.FASTAPI.PROJECT_NAME = "project_name" - config.AUTH.JWT_ISSUER = "your-app-name" + config.AUTH.JWT.ISSUER = "your-app-name" config.TEMPORAL.CLIENT_IDENTITY = None scenario_context.store("pending_global_config", config) @@ -250,10 +252,10 @@ def step_then_fastapi_project_name(context, expected): assert actual == expected, f"Expected FASTAPI.PROJECT_NAME={expected!r}, got {actual!r}" -@then('AUTH.JWT_ISSUER should be "{expected}"') +@then('AUTH.JWT.ISSUER should be "{expected}"') def step_then_auth_jwt_issuer(context, expected): - actual = BaseConfig.global_config().AUTH.JWT_ISSUER - assert actual == expected, f"Expected AUTH.JWT_ISSUER={expected!r}, got {actual!r}" + actual = BaseConfig.global_config().AUTH.JWT.ISSUER + assert actual == expected, f"Expected AUTH.JWT.ISSUER={expected!r}, got {actual!r}" @then('TEMPORAL.CLIENT_IDENTITY should be "{expected}"') @@ -609,6 +611,14 @@ def step_then_vault_client_request_options(context, verify, connect, read): 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"}, @@ -618,6 +628,20 @@ def step_then_vault_client_request_options(context, verify, connect, read): {"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 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, @@ -644,6 +668,32 @@ def step_then_vault_client_request_options(context, verify, connect, read): {"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"}}, + ), + ("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"}), @@ -659,7 +709,31 @@ def step_then_vault_client_request_options(context, verify, connect, read): ), ("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"): ( @@ -736,12 +810,12 @@ def step_when_elasticsearch_client_backoff(context, base, cap): from archipy.adapters.elasticsearch.adapters import ElasticsearchAdapter from archipy.configs.config_template import ElasticsearchConfig - updates = {} + retry = {} if base != "none": - updates["RETRY_BACKOFF_BASE"] = float(base) + retry["BACKOFF_BASE"] = float(base) if cap != "none": - updates["RETRY_BACKOFF_CAP"] = float(cap) - client = ElasticsearchAdapter._get_client(ElasticsearchConfig(**updates)) + retry["BACKOFF_CAP"] = float(cap) + client = ElasticsearchAdapter._get_client(ElasticsearchConfig(RETRY=retry)) get_current_scenario_context(context).store("es_backoff", (client._retry_backoff_base, client._retry_backoff_cap)) @@ -910,3 +984,53 @@ def emit(self, record): def step_then_elasticsearch_warning_count(context, count): messages = get_current_scenario_context(context).get("es_config_warnings") 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] diff --git a/features/steps/cache_decorator_steps.py b/features/steps/cache_decorator_steps.py index 126c48d35..b35656de7 100644 --- a/features/steps/cache_decorator_steps.py +++ b/features/steps/cache_decorator_steps.py @@ -784,7 +784,7 @@ def find_spec(self, name, path=None, target=None): from archipy.configs.config_template import SQLAlchemyConfig try: - _build_async_count_cache(SQLAlchemyConfig(COUNT_CACHE_ENABLED=True)) + _build_async_count_cache(SQLAlchemyConfig(COUNT_CACHE={"IS_ENABLED": True})) except Exception as exception: print(type(exception).__name__, exception.additional_data) """ diff --git a/features/steps/elastic_adapter_steps.py b/features/steps/elastic_adapter_steps.py index 365604736..65c75ea17 100644 --- a/features/steps/elastic_adapter_steps.py +++ b/features/steps/elastic_adapter_steps.py @@ -938,6 +938,30 @@ def _cloud_id_for_host(host: str) -> str: return "name:" + base64.b64encode(f"{domain}${es_id}$kibana".encode()).decode() +# Settings that live in a group of the Elasticsearch config, as ``GROUP.FIELD``. +_ES_GROUPED_FIELDS = { + "BEARER_AUTH": "AUTH.BEARER", + "SSL_VERSION": "TLS.VERSION", + "MIN_DELAY_BETWEEN_SNIFFING": "SNIFFING.MIN_DELAY", + "SNIFF_BEFORE_REQUESTS": "SNIFFING.BEFORE_REQUESTS", +} + + +def _apply_es_updates(config, updates): + """Copy ``config`` with ``updates``, whose ``GROUP.FIELD`` keys update a field inside a group.""" + top = {} + grouped = {} + for key, value in updates.items(): + if "." in key: + group, field = key.split(".") + grouped.setdefault(group, {})[field] = value + else: + top[key] = value + for group, values in grouped.items(): + top[group] = getattr(config, group).model_copy(update=values) + return config.model_copy(update=top) + + @given('an Elasticsearch config with "{field}" set to "{value}"') def step_es_config_field(context: Context, field: str, value: str) -> None: """Collect config overrides on top of the global Elasticsearch config.""" @@ -956,10 +980,10 @@ def step_es_config_field(context: Context, field: str, value: str) -> None: "MAP_ERRORS": lambda text: text == "true", "IGNORE_STATUS": lambda text: tuple(int(code) for code in text.split(",")), } - updates[field] = parsers[field](value) + updates[_ES_GROUPED_FIELDS.get(field, field)] = parsers[field](value) if field == "BEARER_AUTH": # Bearer auth is exclusive with the container's own credentials - updates.update(API_KEY=None, API_SECRET=None, HTTP_USER_NAME=None, HTTP_PASSWORD=None) + updates.update({"AUTH.API_KEY": None, "AUTH.API_SECRET": None, "AUTH.USER_NAME": None, "AUTH.PASSWORD": None}) scenario_context.store("es_config_updates", updates) @@ -967,7 +991,7 @@ def step_es_config_field(context: Context, field: str, value: str) -> None: 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 = BaseConfig.global_config().ELASTIC.model_copy(update=scenario_context.get("es_config_updates", {})) + 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): diff --git a/features/steps/email_adapter_steps.py b/features/steps/email_adapter_steps.py index 9607c69c9..a829391ab 100644 --- a/features/steps/email_adapter_steps.py +++ b/features/steps/email_adapter_steps.py @@ -53,7 +53,7 @@ def _install_email_config(context, **overrides): BaseConfig.set_global(BaseConfig()) config = BaseConfig.global_config() previous_email = config.EMAIL - values = {"POOL_SIZE": 1, "MAX_RETRIES": 3} + values = {"POOL": {"SIZE": 1}, "MAX_RETRIES": 3} values.update(overrides) config.EMAIL = EmailConfig(**values) @@ -166,7 +166,7 @@ def step_given_smtp_credentials(context, username, password): @given("the configured attachment maximum size is {size:d} bytes") def step_given_attachment_max_size(context, size): - BaseConfig.global_config().EMAIL.ATTACHMENT_MAX_SIZE = size + BaseConfig.global_config().EMAIL.ATTACHMENTS.MAX_SIZE = size @given("an email adapter") @@ -178,7 +178,7 @@ def step_given_email_adapter(context): @given("an email connection pool of size {size:d}") def step_given_connection_pool(context, size): scenario_context = get_current_scenario_context(context) - BaseConfig.global_config().EMAIL.POOL_SIZE = size + BaseConfig.global_config().EMAIL.POOL.SIZE = size scenario_context.store("pool", EmailConnectionPool(BaseConfig.global_config().EMAIL)) @@ -276,7 +276,7 @@ def step_given_url_attachment(context, filename, content): @given('the URL attachment hosts "{hosts}" are allowed') def step_given_url_hosts(context, hosts): - BaseConfig.global_config().EMAIL.ATTACHMENT_URL_ALLOWED_HOSTS = hosts.split(",") + BaseConfig.global_config().EMAIL.ATTACHMENTS.URL_ALLOWED_HOSTS = hosts.split(",") @when('I try to create a URL attachment from "{url}"') @@ -417,7 +417,7 @@ def step_when_take_connection(context): @given("the connection timeout is {seconds:d} seconds") def step_given_connection_timeout(context, seconds): - BaseConfig.global_config().EMAIL.CONNECTION_TIMEOUT = seconds + BaseConfig.global_config().EMAIL.POOL.CONNECTION_TIMEOUT = seconds @when("I try to take a connection from the pool {count:d} times") @@ -459,7 +459,7 @@ def step_when_return_connection(context): @given("the connection refresh interval is {seconds:d} seconds") def step_given_refresh_interval(context, seconds): - BaseConfig.global_config().EMAIL.CONNECTION_REFRESH_SECONDS = seconds + BaseConfig.global_config().EMAIL.POOL.CONNECTION_REFRESH_SECONDS = seconds @when("I wait {seconds:f} seconds") @@ -706,28 +706,28 @@ 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 + BaseConfig.global_config().EMAIL.TLS.MODE = mode @given('the SMTP transport security is "{mode}" verified with the Mailpit CA') def step_given_transport_security_mailpit_ca(context, mode): config = BaseConfig.global_config().EMAIL - config.TLS_MODE = mode - config.TLS_CA_FILE = _mailpit("mailpit").ca_file + config.TLS.MODE = 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): config = BaseConfig.global_config().EMAIL - config.TLS_MODE = mode - config.TLS_VERIFY = False + config.TLS.MODE = mode + config.TLS.VERIFY = False @given('the SMTP transport security is "{mode}" verified with the local SMTPS CA') def step_given_transport_security_local_ca(context, mode): config = BaseConfig.global_config().EMAIL - config.TLS_MODE = mode - config.TLS_CA_FILE = get_current_scenario_context(context).get("smtps_ca_file") + config.TLS.MODE = mode + config.TLS.CA_FILE = get_current_scenario_context(context).get("smtps_ca_file") @given("a local SMTPS server") diff --git a/features/steps/fastapi_sse_steps.py b/features/steps/fastapi_sse_steps.py index c4a5d24e9..8a7522d3b 100644 --- a/features/steps/fastapi_sse_steps.py +++ b/features/steps/fastapi_sse_steps.py @@ -77,10 +77,10 @@ async def stream_invalid_events() -> StreamingResponse: def _reset_optional_middleware(config: BaseConfig) -> None: fastapi_config = config.FASTAPI - fastapi_config.GZIP_MIDDLEWARE_IS_ENABLED = False - fastapi_config.TRUSTED_HOST_MIDDLEWARE_IS_ENABLED = False - fastapi_config.TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS = [] - fastapi_config.HTTPS_REDIRECT_MIDDLEWARE_IS_ENABLED = False + fastapi_config.GZIP.IS_ENABLED = False + fastapi_config.TRUSTED_HOST.IS_ENABLED = False + fastapi_config.TRUSTED_HOST.ALLOWED_HOSTS = [] + fastapi_config.HTTPS_REDIRECT.IS_ENABLED = False def _store_app(context, *, gzip: bool = False, reset: bool = True, trusted_hosts: list[str] | None = None) -> None: @@ -88,10 +88,10 @@ def _store_app(context, *, gzip: bool = False, reset: bool = True, trusted_hosts config = BaseConfig.global_config() if reset: _reset_optional_middleware(config) - config.FASTAPI.GZIP_MIDDLEWARE_IS_ENABLED = gzip + config.FASTAPI.GZIP.IS_ENABLED = gzip if trusted_hosts: - config.FASTAPI.TRUSTED_HOST_MIDDLEWARE_IS_ENABLED = True - config.FASTAPI.TRUSTED_HOST_MIDDLEWARE_ALLOWED_HOSTS = trusted_hosts + config.FASTAPI.TRUSTED_HOST.IS_ENABLED = True + config.FASTAPI.TRUSTED_HOST.ALLOWED_HOSTS = trusted_hosts state = _SseState() scenario_context.store("sse_state", state) scenario_context.store("sse_app", _build_sse_app(config, state)) diff --git a/features/steps/jwt_utils_steps.py b/features/steps/jwt_utils_steps.py index b2d22acd4..053848a70 100644 --- a/features/steps/jwt_utils_steps.py +++ b/features/steps/jwt_utils_steps.py @@ -144,7 +144,9 @@ def step_when_token_with_additional_claim(context, claim): @when('an access token is created with the signing algorithm "{algorithm}"') def step_when_token_with_algorithm(context, algorithm): scenario_context = get_current_scenario_context(context) - auth = BaseConfig.global_config().AUTH.model_copy(update={"HASH_ALGORITHM": algorithm}) + auth = BaseConfig.global_config().AUTH.model_copy( + update={"JWT": BaseConfig.global_config().AUTH.JWT.model_copy(update={"ALGORITHM": algorithm})}, + ) _try_create(scenario_context, auth_config=auth) @@ -169,7 +171,7 @@ def _decode(scenario_context, **kwargs): auth = BaseConfig.global_config().AUTH leeway = kwargs.pop("leeway", None) if leeway is not None: - auth = auth.model_copy(update={"JWT_LEEWAY": leeway}) + auth = auth.model_copy(update={"JWT": auth.JWT.model_copy(update={"LEEWAY": leeway})}) try: payload = JWTUtils.decode_token(scenario_context.get("token"), auth_config=auth, **kwargs) scenario_context.store("decode_success", True) @@ -195,6 +197,20 @@ def step_when_auth_config_leeway(context, leeway): 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) + + +@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) @@ -213,7 +229,10 @@ def step_when_token_with_key_length(context, length, algorithm): from pydantic import SecretStr auth = BaseConfig.global_config().AUTH.model_copy( - update={"SECRET_KEY": SecretStr("k" * length), "HASH_ALGORITHM": algorithm}, + update={ + "SECRET_KEY": SecretStr("k" * length), + "JWT": BaseConfig.global_config().AUTH.JWT.model_copy(update={"ALGORITHM": algorithm}), + }, ) _try_create(get_current_scenario_context(context), auth_config=auth) @@ -241,7 +260,7 @@ def step_given_valid_token_of_kind(context, kind): scenario_context = get_current_scenario_context(context) create = JWTUtils.create_access_token if kind == "access" else JWTUtils.create_refresh_token scenario_context.store( - "token", create(scenario_context.get("user_uuid"), auth_config=BaseConfig.global_config().AUTH) + "token", create(scenario_context.get("user_uuid"), auth_config=BaseConfig.global_config().AUTH), ) @@ -260,7 +279,9 @@ def step_when_token_verified_as(context, required): def step_when_decoded_after_version_change(context): scenario_context = get_current_scenario_context(context) auth_config = BaseConfig.global_config().AUTH - newer = auth_config.model_copy(update={"TOKEN_VERSION": auth_config.TOKEN_VERSION + 1}) + newer = auth_config.model_copy( + update={"JWT": auth_config.JWT.model_copy(update={"TOKEN_VERSION": auth_config.JWT.TOKEN_VERSION + 1})}, + ) try: JWTUtils.decode_token(scenario_context.get("token"), auth_config=newer) scenario_context.store("decode_error", None) diff --git a/features/steps/keycloak_adapter_steps.py b/features/steps/keycloak_adapter_steps.py index b66f8fa70..6e3d1243d 100644 --- a/features/steps/keycloak_adapter_steps.py +++ b/features/steps/keycloak_adapter_steps.py @@ -224,8 +224,8 @@ async def update_adapter_config( adapter.configs.REALM_NAME = realm_name adapter._admin_adapter = None adapter._admin_token_expiry = 0 - if adapter.configs.IS_ADMIN_MODE_ENABLED and ( - adapter.configs.CLIENT_SECRET_KEY or (adapter.configs.ADMIN_USERNAME and adapter.configs.ADMIN_PASSWORD) + if adapter.configs.ADMIN.IS_ENABLED and ( + adapter.configs.CLIENT_SECRET_KEY or (adapter.configs.ADMIN.USERNAME and adapter.configs.ADMIN.PASSWORD) ): adapter._initialize_admin_client() client_result = scenario_context.get(f"client_{client_name}") @@ -243,8 +243,8 @@ async def update_adapter_config( adapter.openid_adapter = adapter._get_openid_client(adapter.configs) adapter._admin_adapter = None adapter._admin_token_expiry = 0 - if adapter.configs.IS_ADMIN_MODE_ENABLED and ( - adapter.configs.CLIENT_SECRET_KEY or (adapter.configs.ADMIN_USERNAME and adapter.configs.ADMIN_PASSWORD) + if adapter.configs.ADMIN.IS_ENABLED and ( + adapter.configs.CLIENT_SECRET_KEY or (adapter.configs.ADMIN.USERNAME and adapter.configs.ADMIN.PASSWORD) ): adapter._initialize_admin_client() scenario_context.store( @@ -275,7 +275,7 @@ async def _ensure_introspection_audience_mapper( adapter.configs.REALM_NAME = realm_name adapter._admin_adapter = None adapter._admin_token_expiry = 0 - if adapter.configs.IS_ADMIN_MODE_ENABLED: + if adapter.configs.ADMIN.IS_ENABLED: adapter._initialize_admin_client() mapper_name = f"audience-{client_name}" @@ -347,7 +347,7 @@ async def step_create_client_and_update_adapter( # Force reinitialization of the OpenID client adapter._admin_adapter = None adapter._admin_token_expiry = 0 - if adapter.configs.IS_ADMIN_MODE_ENABLED: + if adapter.configs.ADMIN.IS_ENABLED: adapter._initialize_admin_client() # Extract the internal client ID from the result @@ -366,7 +366,7 @@ async def step_create_client_and_update_adapter( adapter.configs.REALM_NAME = realm_name adapter._admin_adapter = None adapter._admin_token_expiry = 0 - if adapter.configs.IS_ADMIN_MODE_ENABLED: + if adapter.configs.ADMIN.IS_ENABLED: adapter._initialize_admin_client() client_secret = await adapter.get_client_secret(client_id) @@ -388,9 +388,9 @@ async def step_create_client_and_update_adapter( new_config.CLIENT_SECRET_KEY = SecretStr(client_secret) new_config.VERIFY_SSL = adapter.configs.VERIFY_SSL new_config.TIMEOUT = adapter.configs.TIMEOUT - new_config.ADMIN_USERNAME = adapter.configs.ADMIN_USERNAME - new_config.ADMIN_PASSWORD = adapter.configs.ADMIN_PASSWORD - new_config.ADMIN_REALM_NAME = adapter.configs.ADMIN_REALM_NAME + new_config.ADMIN.USERNAME = adapter.configs.ADMIN.USERNAME + new_config.ADMIN.PASSWORD = adapter.configs.ADMIN.PASSWORD + new_config.ADMIN.REALM_NAME = adapter.configs.ADMIN.REALM_NAME # Create new adapter instance from archipy.adapters.keycloak.adapters import AsyncKeycloakAdapter @@ -441,7 +441,7 @@ async def step_create_client_and_update_adapter( adapter.configs.REALM_NAME = realm_name adapter._admin_adapter = None adapter._admin_token_expiry = 0 - if adapter.configs.IS_ADMIN_MODE_ENABLED: + if adapter.configs.ADMIN.IS_ENABLED: adapter._initialize_admin_client() client_secret = adapter.get_client_secret(client_id) @@ -460,7 +460,7 @@ async def step_create_client_and_update_adapter( adapter._openid_adapter = adapter._get_openid_client(adapter.configs) adapter._admin_adapter = None adapter._admin_token_expiry = 0 - if adapter.configs.IS_ADMIN_MODE_ENABLED: + if adapter.configs.ADMIN.IS_ENABLED: adapter._initialize_admin_client() await _ensure_introspection_audience_mapper( @@ -721,10 +721,10 @@ def step_rotate_realm_signing_key(context: Context, realm_name: str) -> None: config = BaseConfig.global_config().KEYCLOAK admin = KeycloakAdmin( server_url=config.SERVER_URL, - username=config.ADMIN_USERNAME, - password=config.ADMIN_PASSWORD.get_secret_value() if config.ADMIN_PASSWORD else None, + username=config.ADMIN.USERNAME, + password=config.ADMIN.PASSWORD.get_secret_value() if config.ADMIN.PASSWORD else None, realm_name=realm_name, - user_realm_name=config.ADMIN_REALM_NAME, + user_realm_name=config.ADMIN.REALM_NAME, verify=config.VERIFY_SSL, ) admin.create_component( @@ -4227,7 +4227,7 @@ def _async_adapter_for(realm_name: str, client_name: str) -> AsyncKeycloakAdapte "REALM_NAME": realm_name, "CLIENT_ID": client_name, "CLIENT_SECRET_KEY": None, - "IS_ADMIN_MODE_ENABLED": False, + "ADMIN": BaseConfig.global_config().KEYCLOAK.ADMIN.model_copy(update={"IS_ENABLED": False}), }, ) return AsyncKeycloakAdapter(config) @@ -4237,7 +4237,10 @@ def _async_adapter_for(realm_name: str, client_name: str) -> AsyncKeycloakAdapte def step_adapter_clears_caches_without_admin(context: Context, kind: str) -> None: """Clear the caches of an adapter that has no admin credentials: it must neither raise nor build an admin client.""" config = BaseConfig.global_config().KEYCLOAK.model_copy( - update={"CLIENT_SECRET_KEY": None, "IS_ADMIN_MODE_ENABLED": False}, + update={ + "CLIENT_SECRET_KEY": None, + "ADMIN": BaseConfig.global_config().KEYCLOAK.ADMIN.model_copy(update={"IS_ENABLED": False}), + }, ) adapter = AsyncKeycloakAdapter(config) if kind == "async" else KeycloakAdapter(config) adapter.clear_all_caches() @@ -4323,10 +4326,21 @@ async def step_async_adapter_reads_claims(context: Context, username: str) -> No assert claims is not None and claims.preferred_username == username, claims -def _no_admin_adapter(kind: str, **overrides: Any) -> AsyncKeycloakAdapter | KeycloakAdapter: +def _no_admin_adapter( + kind: str, + *, + token_validation: dict[str, str] | None = None, + **overrides: Any, +) -> AsyncKeycloakAdapter | KeycloakAdapter: """Build a sync or async adapter without admin mode, overriding config fields.""" - config = BaseConfig.global_config().KEYCLOAK.model_copy( - update={"CLIENT_SECRET_KEY": None, "IS_ADMIN_MODE_ENABLED": False, **overrides}, + base = BaseConfig.global_config().KEYCLOAK + 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), + **overrides, + }, ) return AsyncKeycloakAdapter(config) if kind == "async" else KeycloakAdapter(config) @@ -4418,7 +4432,7 @@ def segment_b64(value: dict[str, Any]) -> str: @then("the Keycloak config repr does not contain the client secret or the admin password") def step_config_repr_hides_secrets(context: Context) -> None: - config = KeycloakConfig(CLIENT_SECRET_KEY="client-secret-value", ADMIN_PASSWORD="admin-password-value") + config = KeycloakConfig(CLIENT_SECRET_KEY="client-secret-value", ADMIN={"PASSWORD": "admin-password-value"}) text = repr(config) + str(config) + config.model_dump_json() assert "client-secret-value" not in text and "admin-password-value" not in text, text @@ -4467,7 +4481,7 @@ async def step_adapter_expecting_claim_rejects_token( """A token whose issuer or audience differs from the configured expectation is rejected.""" scenario_context = get_current_scenario_context(context) token = scenario_context.get(f"token_response_{username}").access_token - adapter = _no_admin_adapter(kind, REALM_NAME=realm_name, CLIENT_ID=client_name, **{setting: value}) + adapter = _no_admin_adapter(kind, REALM_NAME=realm_name, CLIENT_ID=client_name, token_validation={setting: value}) valid, code = await _check_token(kind, adapter, token) assert not valid and code == "INVALID_TOKEN", f"expected rejection, got valid={valid} code={code}" @@ -4487,7 +4501,12 @@ async def step_adapter_enforces_correct_issuer( scenario_context = get_current_scenario_context(context) access_token = scenario_context.get(f"token_response_{username}").access_token issuer = _unverified_claims(access_token)["iss"] - adapter = _no_admin_adapter(kind, REALM_NAME=realm_name, CLIENT_ID=client_name, EXPECTED_ISSUER=issuer) + adapter = _no_admin_adapter( + kind, + REALM_NAME=realm_name, + CLIENT_ID=client_name, + token_validation={"EXPECTED_ISSUER": issuer}, + ) assert await _check_token(kind, adapter, access_token) == (True, None) @@ -4500,7 +4519,9 @@ def step_forged_claims_checked(context: Context, token_type: str, outcome: str) base = BaseConfig.global_config().KEYCLOAK claims = {"iss": f"{base.SERVER_URL}/realms/{base.REALM_NAME}", "typ": token_type} - enforcing = base.model_copy(update={"EXPECTED_ISSUER": claims["iss"]}) + enforcing = base.model_copy( + update={"TOKEN_VALIDATION": base.TOKEN_VALIDATION.model_copy(update={"EXPECTED_ISSUER": claims["iss"]})}, + ) try: _check_token_claims(claims, enforcing) except BaseError as error: diff --git a/features/steps/keycloak_auth_steps.py b/features/steps/keycloak_auth_steps.py index 616ff51ab..ec31486f1 100644 --- a/features/steps/keycloak_auth_steps.py +++ b/features/steps/keycloak_auth_steps.py @@ -1029,9 +1029,9 @@ def step_organization_token_memberships(context, username, count): @given("the default organization requirement is {required}") def step_organization_config_requirement(context, required): configs = _real_sync_adapter(_ctx(context)).configs - previous = configs.REQUIRE_ORGANIZATION - configs.REQUIRE_ORGANIZATION = required == "true" - context.add_cleanup(lambda: setattr(configs, "REQUIRE_ORGANIZATION", previous)) + previous = configs.TOKEN_VALIDATION.REQUIRE_ORGANIZATION + configs.TOKEN_VALIDATION.REQUIRE_ORGANIZATION = required == "true" + context.add_cleanup(lambda: setattr(configs.TOKEN_VALIDATION, "REQUIRE_ORGANIZATION", previous)) @given('the organization requirement of the guard is "{required}"') diff --git a/features/steps/keycloak_chaining_steps.py b/features/steps/keycloak_chaining_steps.py index 70b069d4d..52476208f 100644 --- a/features/steps/keycloak_chaining_steps.py +++ b/features/steps/keycloak_chaining_steps.py @@ -37,7 +37,7 @@ def _client_adapter(adapter, is_async: bool, realm: str, client: str, secret: st CLIENT_ID=client, CLIENT_SECRET_KEY=secret, VERIFY_SSL=False, - IS_ADMIN_MODE_ENABLED=False, + ADMIN={"IS_ENABLED": False}, ) return AsyncKeycloakAdapter(configs) if is_async else KeycloakAdapter(configs) diff --git a/features/steps/otel_steps.py b/features/steps/otel_steps.py index ab1b47ef4..1906bf910 100644 --- a/features/steps/otel_steps.py +++ b/features/steps/otel_steps.py @@ -29,6 +29,7 @@ trace_root, trace_span, ) +from archipy.configs.sections.otel import OtelPushgatewayConfig from archipy.helpers.errors import capture_exception from archipy.helpers.utils.otel_utils import OtelUtils from archipy.models.errors import ConfigurationError, NotFoundError @@ -42,12 +43,7 @@ def _reset_otel_config_defaults() -> None: config.OTEL.SYSTEM_METRICS_ENABLED = True config.OTEL.METRICS_PULL_HOST = "127.0.0.1" config.OTEL.METRICS_PULL_PORT = 8200 - config.OTEL.METRICS_PUSHGATEWAY_URL = None - config.OTEL.METRICS_PUSHGATEWAY_JOB = None - config.OTEL.METRICS_PUSHGATEWAY_INTERVAL_SECONDS = 60 - config.OTEL.METRICS_PUSHGATEWAY_TIMEOUT_SECONDS = 10.0 - config.OTEL.METRICS_PUSHGATEWAY_GROUPING_KEY = {} - config.OTEL.METRICS_PUSHGATEWAY_DELETE_ON_SHUTDOWN = True + config.OTEL.PUSHGATEWAY = OtelPushgatewayConfig() config.OTEL.LOGS_ENABLED = False config.OTEL.LOGS_LEVEL = "INFO" config.OTEL.FASTAPI_LOGS_ENABLED = False @@ -73,12 +69,7 @@ def _reset_otel_config_defaults() -> None: "METRICS_EXPORTER", "METRICS_PULL_HOST", "METRICS_PULL_PORT", - "METRICS_PUSHGATEWAY_URL", - "METRICS_PUSHGATEWAY_JOB", - "METRICS_PUSHGATEWAY_INTERVAL_SECONDS", - "METRICS_PUSHGATEWAY_TIMEOUT_SECONDS", - "METRICS_PUSHGATEWAY_GROUPING_KEY", - "METRICS_PUSHGATEWAY_DELETE_ON_SHUTDOWN", + "PUSHGATEWAY", "INSTRUMENTATION_SKIP_DEP_CHECK", ) @@ -2399,12 +2390,14 @@ def _configure_pushgateway(context, *, url: str | None = None, delete_on_shutdow config.OTEL.METRICS_ENABLED = True config.OTEL.LOGS_ENABLED = False config.OTEL.METRICS_EXPORTER = OtelMetricsExporter.PUSHGATEWAY - config.OTEL.METRICS_PUSHGATEWAY_URL = url or pushgateway.url - config.OTEL.METRICS_PUSHGATEWAY_JOB = _PUSHGATEWAY_JOB - config.OTEL.METRICS_PUSHGATEWAY_INTERVAL_SECONDS = 1 - config.OTEL.METRICS_PUSHGATEWAY_TIMEOUT_SECONDS = 1.0 - config.OTEL.METRICS_PUSHGATEWAY_GROUPING_KEY = {"instance": "bdd"} - config.OTEL.METRICS_PUSHGATEWAY_DELETE_ON_SHUTDOWN = delete_on_shutdown + config.OTEL.PUSHGATEWAY = OtelPushgatewayConfig( + URL=url or pushgateway.url, + JOB=_PUSHGATEWAY_JOB, + INTERVAL_SECONDS=1, + TIMEOUT_SECONDS=1.0, + GROUPING_KEY={"instance": "bdd"}, + DELETE_ON_SHUTDOWN=delete_on_shutdown, + ) config.OTEL.METRICS_PULL_HOST = "127.0.0.1" config.OTEL.METRICS_PULL_PORT = port config.OTEL.SYSTEM_METRICS_ENABLED = False diff --git a/features/steps/password_utils_steps.py b/features/steps/password_utils_steps.py index 33e36058a..64b566ae6 100644 --- a/features/steps/password_utils_steps.py +++ b/features/steps/password_utils_steps.py @@ -121,11 +121,11 @@ def step_then_secure_password_meets_requirements(context): generated_password = scenario_context.get("generated_password") test_config = BaseConfig.global_config() - assert len(generated_password) >= test_config.AUTH.MIN_LENGTH + assert len(generated_password) >= test_config.AUTH.PASSWORD_POLICY.MIN_LENGTH assert any(char.isdigit() for char in generated_password) assert any(char.islower() for char in generated_password) assert any(char.isupper() for char in generated_password) - assert any(char in test_config.AUTH.SPECIAL_CHARACTERS for char in generated_password) + assert any(char in test_config.AUTH.PASSWORD_POLICY.SPECIAL_CHARACTERS for char in generated_password) @given('a password history containing "{old_password}"') @@ -145,7 +145,9 @@ def step_when_reuse_old_password(context, new_password): auth = test_config.AUTH history_size = scenario_context.get("history_size") if history_size is not None: - auth = auth.model_copy(update={"PASSWORD_HISTORY_SIZE": history_size}) + auth = auth.model_copy( + update={"PASSWORD_POLICY": auth.PASSWORD_POLICY.model_copy(update={"HISTORY_SIZE": history_size})}, + ) try: PasswordUtils.validate_password_history(new_password, password_history, auth) @@ -177,13 +179,15 @@ def step_then_hash_is_versioned(context, scheme): parts = hashed_password.split("$") assert len(parts) == 4, hashed_password assert parts[0] == scheme - assert int(parts[1]) == BaseConfig.global_config().AUTH.HASH_ITERATIONS + assert int(parts[1]) == BaseConfig.global_config().AUTH.PASSWORD_POLICY.HASH_ITERATIONS @when("the password is verified with the iteration setting changed to {iterations:d}") def step_when_verified_with_changed_iterations(context, iterations): scenario_context = get_current_scenario_context(context) - auth = BaseConfig.global_config().AUTH.model_copy(update={"HASH_ITERATIONS": iterations}) + auth = BaseConfig.global_config().AUTH.model_copy( + update={"PASSWORD_POLICY": BaseConfig.global_config().AUTH.PASSWORD_POLICY.model_copy(update={"HASH_ITERATIONS": iterations})}, + ) scenario_context.store( "is_verified", PasswordUtils.verify_password(scenario_context.get("password"), scenario_context.get("hashed_password"), auth), @@ -199,7 +203,7 @@ def _legacy_hash(password, iterations): @given("the password is hashed in the legacy format with the configured iteration count") def step_given_legacy_hash_configured(context): scenario_context = get_current_scenario_context(context) - iterations = BaseConfig.global_config().AUTH.HASH_ITERATIONS + iterations = BaseConfig.global_config().AUTH.PASSWORD_POLICY.HASH_ITERATIONS scenario_context.store("hashed_password", _legacy_hash(scenario_context.get("password"), iterations)) diff --git a/features/steps/scylladb_adapter_steps.py b/features/steps/scylladb_adapter_steps.py index 2d54e8d65..4e4b9dc8e 100644 --- a/features/steps/scylladb_adapter_steps.py +++ b/features/steps/scylladb_adapter_steps.py @@ -10,6 +10,12 @@ from archipy.adapters.scylladb.adapters import AsyncScyllaDBAdapter, ScyllaDBAdapter from archipy.configs.base_config import BaseConfig +from archipy.configs.sections.scylladb import ( + ScyllaHeartbeatConfig, + ScyllaReconnectionConfig, + ScyllaSpeculativeExecutionConfig, + ScyllaTlsConfig, +) from archipy.models import errors from archipy.models.errors import NotFoundError @@ -1355,7 +1361,8 @@ async def step_create_keyspace_capture_log(context: Context, keyspace: str, fact factor (int): Replication factor. """ adapter = get_scylladb_adapter(context) - adapter.config = adapter.config.model_copy(update={"REPLICATION_CONFIG": {"datacenter1": factor}}) + replication = adapter.config.REPLICATION.model_copy(update={"CONFIG": {"datacenter1": factor}}) + adapter.config = adapter.config.model_copy(update={"REPLICATION": replication}) records: list[logging.LogRecord] = [] class _Capture(logging.Handler): @@ -1422,8 +1429,7 @@ def step_build_cluster_capture_security_log(context: Context, credentials: str, updates: dict[str, Any] = { "USERNAME": "user" if credentials == "set" else None, "PASSWORD": SecretStr("secret") if credentials == "set" else None, - "TLS_ENABLED": tls == "on", - "TLS_VERIFY_MODE": verify, + "TLS": ScyllaTlsConfig(IS_ENABLED=tls == "on", VERIFY_MODE=verify), } config = get_scylladb_adapter(context).config.model_copy(update=updates) adapter = ScyllaDBAdapter.__new__(ScyllaDBAdapter) # skip __init__, which would open a second connection @@ -1798,9 +1804,11 @@ def step_build_scylladb_tls_cluster(context: Context, enabled: str, server_name: from archipy.adapters.scylladb.adapters import ScyllaDBAdapter updates = { - "TLS_ENABLED": enabled == "yes", - "TLS_SERVER_NAME": None if server_name == "-" else server_name, - "TLS_SESSION_CACHE_ENABLED": cache == "yes", + "TLS": ScyllaTlsConfig( + IS_ENABLED=enabled == "yes", + SERVER_NAME=None if server_name == "-" else server_name, + SESSION_CACHE_ENABLED=cache == "yes", + ), } config = get_scylladb_adapter(context).config.model_copy(update=updates) adapter = ScyllaDBAdapter.__new__(ScyllaDBAdapter) # skip __init__, which would open a second connection @@ -1893,22 +1901,19 @@ def step_no_deprecation(context: Context) -> None: _RESILIENCE_PROFILES: dict[str, dict[str, Any]] = { "driver defaults": {}, "constant reconnect": { - "RECONNECTION_POLICY": "CONSTANT", - "RECONNECTION_BASE_DELAY": 2.0, - "RECONNECTION_MAX_ATTEMPTS": 5, + "RECONNECTION": ScyllaReconnectionConfig(POLICY="CONSTANT", BASE_DELAY=2.0, MAX_ATTEMPTS=5), }, "exponential reconnect": { - "RECONNECTION_POLICY": "EXPONENTIAL", - "RECONNECTION_BASE_DELAY": 0.5, - "RECONNECTION_MAX_DELAY": 30.0, + "RECONNECTION": ScyllaReconnectionConfig(POLICY="EXPONENTIAL", BASE_DELAY=0.5, MAX_DELAY=30.0), }, "heartbeat and timeouts": { - "IDLE_HEARTBEAT_INTERVAL": 7.0, - "IDLE_HEARTBEAT_TIMEOUT": 11.0, + "HEARTBEAT": ScyllaHeartbeatConfig(IDLE_INTERVAL=7.0, IDLE_TIMEOUT=11.0), "CONTROL_CONNECTION_TIMEOUT": 4.0, }, "serial consistency": {"SERIAL_CONSISTENCY_LEVEL": "LOCAL_SERIAL"}, - "speculative execution": {"SPECULATIVE_EXECUTION_DELAY": 0.25, "SPECULATIVE_EXECUTION_MAX_ATTEMPTS": 3}, + "speculative execution": { + "SPECULATIVE_EXECUTION": ScyllaSpeculativeExecutionConfig(DELAY=0.25, MAX_ATTEMPTS=3), + }, } @@ -1948,30 +1953,33 @@ def step_cluster_reflects_resilience(context: Context, profile: str) -> None: cluster = context.cluster default_profile = cluster.profile_manager.default settings = _RESILIENCE_PROFILES[profile] + reconnection_settings = settings.get("RECONNECTION") + heartbeat_settings = settings.get("HEARTBEAT") + speculative_settings = settings.get("SPECULATIVE_EXECUTION") reconnection = cluster.reconnection_policy - if settings.get("RECONNECTION_POLICY") == "CONSTANT": + if reconnection_settings is not None and reconnection_settings.POLICY == "CONSTANT": assert isinstance(reconnection, ConstantReconnectionPolicy), reconnection - assert reconnection.delay == settings["RECONNECTION_BASE_DELAY"] - assert reconnection.max_attempts == settings["RECONNECTION_MAX_ATTEMPTS"] - elif settings.get("RECONNECTION_POLICY") == "EXPONENTIAL": + assert reconnection.delay == reconnection_settings.BASE_DELAY + assert reconnection.max_attempts == reconnection_settings.MAX_ATTEMPTS + elif reconnection_settings is not None and reconnection_settings.POLICY == "EXPONENTIAL": assert isinstance(reconnection, ExponentialReconnectionPolicy), reconnection - assert reconnection.base_delay == settings["RECONNECTION_BASE_DELAY"] - assert reconnection.max_delay == settings["RECONNECTION_MAX_DELAY"] + assert reconnection.base_delay == reconnection_settings.BASE_DELAY + assert reconnection.max_delay == reconnection_settings.MAX_DELAY else: assert type(reconnection) is ExponentialReconnectionPolicy, reconnection assert reconnection.base_delay == 1.0 assert reconnection.max_delay == 600.0 - assert cluster.idle_heartbeat_interval == settings.get("IDLE_HEARTBEAT_INTERVAL", 30) - assert cluster.idle_heartbeat_timeout == settings.get("IDLE_HEARTBEAT_TIMEOUT", 30) + assert cluster.idle_heartbeat_interval == (heartbeat_settings.IDLE_INTERVAL if heartbeat_settings else 30) + assert cluster.idle_heartbeat_timeout == (heartbeat_settings.IDLE_TIMEOUT if heartbeat_settings else 30) assert cluster.control_connection_timeout == settings.get("CONTROL_CONNECTION_TIMEOUT", 2.0) expected_serial = None if "SERIAL_CONSISTENCY_LEVEL" in settings: expected_serial = getattr(ConsistencyLevel, settings["SERIAL_CONSISTENCY_LEVEL"]) assert default_profile.serial_consistency_level == expected_serial, default_profile.serial_consistency_level speculative = default_profile.speculative_execution_policy - if "SPECULATIVE_EXECUTION_DELAY" in settings: + if speculative_settings is not None: assert isinstance(speculative, ConstantSpeculativeExecutionPolicy), speculative - assert speculative.delay == settings["SPECULATIVE_EXECUTION_DELAY"] - assert speculative.max_attempts == settings["SPECULATIVE_EXECUTION_MAX_ATTEMPTS"] + assert speculative.delay == speculative_settings.DELAY + assert speculative.max_attempts == speculative_settings.MAX_ATTEMPTS else: assert isinstance(speculative, NoSpeculativeExecutionPolicy), speculative diff --git a/features/steps/sqlalchemy_multiple_databases_steps.py b/features/steps/sqlalchemy_multiple_databases_steps.py index 097edd090..8a3c79f76 100644 --- a/features/steps/sqlalchemy_multiple_databases_steps.py +++ b/features/steps/sqlalchemy_multiple_databases_steps.py @@ -279,7 +279,7 @@ def step_then_driver_receives_connect_timeout(context, seconds): def _in_memory_sqlite_config(): # A recycle time of 0 makes every checkout older than the recycle time, so no waiting is needed. - return SQLiteSQLAlchemyConfig(DRIVER_NAME="sqlite", DATABASE=":memory:", POOL_RECYCLE_SECONDS=0) + return SQLiteSQLAlchemyConfig(DRIVER_NAME="sqlite", DATABASE=":memory:", POOL={"RECYCLE_SECONDS": 0}) @when("a row is written to the sync in-memory SQLite database and read back after its pool recycle time") diff --git a/features/steps/temporal_adapter_steps.py b/features/steps/temporal_adapter_steps.py index 57a2cc0e1..c64ffd313 100644 --- a/features/steps/temporal_adapter_steps.py +++ b/features/steps/temporal_adapter_steps.py @@ -87,6 +87,7 @@ from archipy.adapters.temporal.worker import TemporalWorkerManager, WorkerHandle from archipy.configs.base_config import BaseConfig from archipy.configs.config_template import OtelMetricsExporter, TemporalConfig +from archipy.configs.sections.temporal import TemporalWorkerConfig from archipy.models.errors import BaseError, ConfigurationError, InvalidArgumentError from archipy.models.errors.temporal_errors import WorkerShutdownError @@ -358,7 +359,7 @@ def step_temporal_worker_manager_with_debug_mode(context) -> None: if hasattr(scenario_context, "temporal_adapter") and scenario_context.temporal_adapter is not None else temporal_container.config ) - temporal_config = base_config.model_copy(update={"WORKER_DEBUG_MODE": True}) + temporal_config = base_config.model_copy(update={"WORKER": TemporalWorkerConfig(DEBUG_MODE=True)}) scenario_context.worker_manager = TemporalWorkerManager(temporal_config) context.logger.info("Temporal worker manager configured with debug mode enabled") @@ -1733,7 +1734,7 @@ def step_temporal_adapter_config_should_have_client_identity(context, identity: def step_temporal_worker_manager_config_should_have_debug_mode(context) -> None: """Verify Temporal worker manager config has debug mode enabled.""" worker_manager = get_temporal_worker_manager(context) - assert worker_manager.config.WORKER_DEBUG_MODE is True, "Expected WORKER_DEBUG_MODE to be enabled" + assert worker_manager.config.WORKER.DEBUG_MODE is True, "Expected WORKER.DEBUG_MODE to be enabled" context.logger.info("Temporal worker manager config has debug mode enabled") @@ -2443,7 +2444,7 @@ def step_same_run_id(context): def step_temporal_worker_manager_tuned(context, rate): scenario_context = get_current_scenario_context(context) temporal_config = get_temporal_adapter(context).config.model_copy( - update={"WORKER_POLLER_AUTOSCALING": True, "WORKER_MAX_ACTIVITIES_PER_SECOND": float(rate)}, + update={"WORKER": TemporalWorkerConfig(POLLER_AUTOSCALING=True, MAX_ACTIVITIES_PER_SECOND=float(rate))}, ) scenario_context.worker_manager = TemporalWorkerManager(temporal_config) @@ -2452,7 +2453,7 @@ def step_temporal_worker_manager_tuned(context, rate): def step_temporal_worker_manager_eager_reservations(context, value): scenario_context = get_current_scenario_context(context) temporal_config = get_temporal_adapter(context).config.model_copy( - update={"WORKER_MAX_EAGER_ACTIVITY_RESERVATIONS": None if value == "none" else int(value)}, + update={"WORKER": TemporalWorkerConfig(MAX_EAGER_ACTIVITY_RESERVATIONS=None if value == "none" else int(value))}, ) scenario_context.worker_manager = TemporalWorkerManager(temporal_config) diff --git a/features/steps/totp_utils_steps.py b/features/steps/totp_utils_steps.py index 5ec12aa97..5ca6e1f54 100644 --- a/features/steps/totp_utils_steps.py +++ b/features/steps/totp_utils_steps.py @@ -163,14 +163,16 @@ def step_then_expiration_within_window(context): expires = get_current_scenario_context(context).get("expires") auth = BaseConfig.global_config().AUTH remaining = expires - DatetimeUtils.get_datetime_now() - longest = timedelta(seconds=(auth.TOTP_VERIFICATION_WINDOW + 1) * auth.TOTP_TIME_STEP) + longest = timedelta(seconds=(auth.TOTP.VERIFICATION_WINDOW + 1) * auth.TOTP.TIME_STEP) assert remaining <= longest + timedelta(seconds=1), f"{remaining} > {longest}" @when("a secret key is generated without a TOTP master key") def step_when_secret_key_without_master_key(context): scenario_context = get_current_scenario_context(context) - auth = BaseConfig.global_config().AUTH.model_copy(update={"TOTP_SECRET_KEY": None}) + auth = BaseConfig.global_config().AUTH.model_copy( + update={"TOTP": BaseConfig.global_config().AUTH.TOTP.model_copy(update={"SECRET_KEY": None})}, + ) try: TOTPUtils.generate_secret_key_for_totp(auth) scenario_context.store("secret_key_error", None) diff --git a/features/steps/vault_adapter_steps.py b/features/steps/vault_adapter_steps.py index 17ef54a11..3f0e9777d 100644 --- a/features/steps/vault_adapter_steps.py +++ b/features/steps/vault_adapter_steps.py @@ -12,6 +12,7 @@ from archipy.adapters.vault.adapters import VaultAdapter from archipy.configs.config_template import VaultConfig +from archipy.configs.sections.vault import VaultAppRoleConfig, VaultHttpConfig, VaultTokenRenewalConfig from archipy.configs.vault_settings_source import _vault_config_from_env from archipy.models.errors import ConfigurationError, InvalidArgumentError, NotFoundError, UnavailableError @@ -40,7 +41,7 @@ def _admin_client() -> hvac.Client: """Return an hvac client using the global Vault root token.""" vault = TestConfig.global_config().VAULT token = vault.TOKEN.get_secret_value() if vault.TOKEN else None - return hvac.Client(url=vault.ADDR, token=token, verify=vault.VERIFY_SSL) + return hvac.Client(url=vault.ADDR, token=token, verify=vault.TLS.VERIFY_SSL) @given("a configured Vault adapter") @@ -100,8 +101,7 @@ def _adapter_with_token(context, token: str, threshold: int) -> VaultAdapter: update={ "ENABLED": True, "TOKEN": token, - "AUTO_RENEW_TOKEN": True, - "RENEW_THRESHOLD_SECONDS": threshold, + "TOKEN_RENEWAL": VaultTokenRenewalConfig(AUTO_RENEW_TOKEN=True, RENEW_THRESHOLD_SECONDS=threshold), }, ) adapter = _store_adapter(context, VaultAdapter(config)) @@ -164,8 +164,7 @@ def step_given_approle_adapter(context): "ENABLED": True, "AUTH_METHOD": "approle", "TOKEN": None, - "APPROLE_ROLE_ID": role_id, - "APPROLE_SECRET_ID": secret_id, + "APPROLE": VaultAppRoleConfig(ROLE_ID=role_id, SECRET_ID=secret_id), }, ) adapter = _store_adapter(context, VaultAdapter(config)) @@ -441,8 +440,8 @@ def step_then_token_renewed(context): scenario_context = get_current_scenario_context(context) before_ttl = scenario_context.get("token_ttl_before") assert before_ttl is not None, "Missing token TTL before sample" - assert before_ttl <= adapter.configs.RENEW_THRESHOLD_SECONDS, ( - f"Precondition failed: TTL {before_ttl} should be <= threshold {adapter.configs.RENEW_THRESHOLD_SECONDS}" + assert before_ttl <= adapter.configs.TOKEN_RENEWAL.RENEW_THRESHOLD_SECONDS, ( + f"Precondition failed: TTL {before_ttl} should be <= threshold {adapter.configs.TOKEN_RENEWAL.RENEW_THRESHOLD_SECONDS}" ) assert adapter.token_renew_count >= 1, f"Expected at least one token renew, got {adapter.token_renew_count}" @@ -534,8 +533,8 @@ def step_given_unavailable_vault(context, retries: int): "ADDR": f"http://{host}:{port}", "TOKEN": "stub-token", "AUTH_METHOD": "token", - "RETRIES_MAX_ATTEMPTS": retries, - "AUTO_RENEW_TOKEN": False, + "HTTP": VaultHttpConfig(RETRIES_MAX_ATTEMPTS=retries), + "TOKEN_RENEWAL": VaultTokenRenewalConfig(AUTO_RENEW_TOKEN=False), "SECRET_CACHE_TTL": 0, }, ) @@ -590,7 +589,7 @@ def step_parse_verify_ssl(context, value): os.environ["VAULT__VERIFY_SSL"] = value result: object try: - result = _vault_config_from_env().VERIFY_SSL + result = _vault_config_from_env().TLS.VERIFY_SSL except ConfigurationError as e: result = e finally: @@ -616,3 +615,51 @@ def step_then_repr_hides_credentials(context): text = repr(config) for secret in ("tok-secret-1", "sid-secret-2", "pw-secret-3"): assert secret not in text, f"repr leaks {secret}" + + +def _vault_setting(config, path): + value = config + for part in path.split("."): + value = getattr(value, part) + return value.get_secret_value() if hasattr(value, "get_secret_value") else value + + +@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)]) + + +@when("the Vault bootstrap config is read with environment {env}") +def step_when_vault_bootstrap_env(context, env): + wanted = json.loads(env) + saved = {key: os.environ.get(key) for key in wanted} + os.environ.update(wanted) + try: + config = _vault_config_from_env() + finally: + for key, value in saved.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + get_current_scenario_context(context).store("vault_grouped_config", config) + + +@then('the Vault setting "{path}" should be "{expected}"') +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/test_containers.py b/features/test_containers.py index ed179c5d6..6df70e04a 100644 --- a/features/test_containers.py +++ b/features/test_containers.py @@ -625,8 +625,8 @@ def __init__(self, config: KeycloakConfig | None = None, image: str | None = Non # Container properties self.host: str | None = None self.port: int | None = None - self.admin_username: str | None = self.config.ADMIN_USERNAME - admin_password = self.config.ADMIN_PASSWORD + self.admin_username: str | None = self.config.ADMIN.USERNAME + admin_password = self.config.ADMIN.PASSWORD self.admin_password: str | None = admin_password.get_secret_value() if admin_password else None self.realm: str = self.config.REALM_NAME @@ -1419,7 +1419,7 @@ def start(self) -> VaultContainer: global_config.VAULT.ADDR = self.addr global_config.VAULT.TOKEN = SecretStr(self.root_token) global_config.VAULT.AUTH_METHOD = "token" - global_config.VAULT.VERIFY_SSL = False + global_config.VAULT.TLS.VERIFY_SSL = False global_config.VAULT.MOUNT_POINT = "secret" global_config.VAULT.ENABLED = False # settings source opt-in per scenario diff --git a/features/vault_adapter.feature b/features/vault_adapter.feature index 178dde625..2dba2ba56 100644 --- a/features/vault_adapter.feature +++ b/features/vault_adapter.feature @@ -139,3 +139,28 @@ Feature: Vault Adapter Given adapter spans are exported to the collector 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 + 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 + 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 | diff --git a/packages/elasticsearch/archipy/adapters/elasticsearch/adapters.py b/packages/elasticsearch/archipy/adapters/elasticsearch/adapters.py index c44c34c4c..35c05ef95 100644 --- a/packages/elasticsearch/archipy/adapters/elasticsearch/adapters.py +++ b/packages/elasticsearch/archipy/adapters/elasticsearch/adapters.py @@ -204,12 +204,12 @@ def _apply_optional_client_kwargs(kwargs: dict[str, Any], configs: Elasticsearch kwargs (dict[str, Any]): Client keyword arguments, updated in place. configs (ElasticsearchConfig): Configuration settings for Elasticsearch. """ - if configs.BEARER_AUTH: - kwargs["bearer_auth"] = configs.BEARER_AUTH.get_secret_value() - if configs.SSL_VERSION is not None: - kwargs["ssl_version"] = configs.SSL_VERSION - if configs.SSL_CONTEXT is not None: - kwargs["ssl_context"] = configs.SSL_CONTEXT + if configs.AUTH.BEARER: + kwargs["bearer_auth"] = configs.AUTH.BEARER.get_secret_value() + if configs.TLS.VERSION is not None: + kwargs["ssl_version"] = configs.TLS.VERSION + if configs.TLS.CONTEXT is not None: + kwargs["ssl_context"] = configs.TLS.CONTEXT if configs.OPAQUE_ID: kwargs["opaque_id"] = configs.OPAQUE_ID if configs.HEADERS: @@ -304,10 +304,10 @@ def _get_client(configs: ElasticsearchConfig) -> Elasticsearch: """ api_key: tuple[str, str] | None = None basic_auth: tuple[str, str] | None = None - if configs.API_KEY and configs.API_SECRET: - api_key = (configs.API_KEY, configs.API_SECRET.get_secret_value()) - elif configs.HTTP_USER_NAME and configs.HTTP_PASSWORD: - basic_auth = (configs.HTTP_USER_NAME, configs.HTTP_PASSWORD.get_secret_value()) + if configs.AUTH.API_KEY and configs.AUTH.API_SECRET: + api_key = (configs.AUTH.API_KEY, configs.AUTH.API_SECRET.get_secret_value()) + elif configs.AUTH.USER_NAME and configs.AUTH.PASSWORD: + basic_auth = (configs.AUTH.USER_NAME, configs.AUTH.PASSWORD.get_secret_value()) # Build kwargs, only including SSL parameters if they have values kwargs: dict[str, Any] = { @@ -315,20 +315,20 @@ def _get_client(configs: ElasticsearchConfig) -> Elasticsearch: "api_key": api_key, "basic_auth": basic_auth, "request_timeout": configs.REQUEST_TIMEOUT, - "retry_on_status": configs.RETRY_ON_STATUS, - "retry_on_timeout": configs.RETRY_ON_TIMEOUT, - "max_retries": configs.MAX_RETRIES, + "retry_on_status": configs.RETRY.ON_STATUS, + "retry_on_timeout": configs.RETRY.ON_TIMEOUT, + "max_retries": configs.RETRY.MAX_RETRIES, "http_compress": configs.HTTP_COMPRESS, "connections_per_node": configs.CONNECTIONS_PER_NODE, - "verify_certs": configs.VERIFY_CERTS, - "sniff_on_start": configs.SNIFF_ON_START, - "sniff_before_requests": configs.SNIFF_BEFORE_REQUESTS, - "sniff_on_node_failure": configs.SNIFF_ON_NODE_FAILURE, + "verify_certs": configs.TLS.VERIFY_CERTS, + "sniff_on_start": configs.SNIFFING.ON_START, + "sniff_before_requests": configs.SNIFFING.BEFORE_REQUESTS, + "sniff_on_node_failure": configs.SNIFFING.ON_NODE_FAILURE, "max_dead_node_backoff": configs.MAX_DEAD_NODE_BACKOFF, "dead_node_backoff_factor": configs.DEAD_NODE_BACKOFF_FACTOR, "node_selector_class": configs.NODE_SELECTOR_CLASS, - "retry_backoff_base": configs.RETRY_BACKOFF_BASE, - "retry_backoff_cap": configs.RETRY_BACKOFF_CAP, + "retry_backoff_base": configs.RETRY.BACKOFF_BASE, + "retry_backoff_cap": configs.RETRY.BACKOFF_CAP, } # Leave the backoff options out when unset so the client keeps its own defaults kwargs = { @@ -336,17 +336,17 @@ def _get_client(configs: ElasticsearchConfig) -> Elasticsearch: } # Only add SSL parameters if they have values (to avoid passing None) - if configs.CA_CERTS: - kwargs["ca_certs"] = configs.CA_CERTS - if configs.CLIENT_KEY: - kwargs["client_key"] = configs.CLIENT_KEY - if configs.CLIENT_CERT: - kwargs["client_cert"] = configs.CLIENT_CERT - if configs.SSL_ASSERT_FINGERPRINT: - kwargs["ssl_assert_fingerprint"] = configs.SSL_ASSERT_FINGERPRINT + if configs.TLS.CA_CERTS: + kwargs["ca_certs"] = configs.TLS.CA_CERTS + if configs.TLS.CLIENT_KEY: + kwargs["client_key"] = configs.TLS.CLIENT_KEY + if configs.TLS.CLIENT_CERT: + kwargs["client_cert"] = configs.TLS.CLIENT_CERT + if configs.TLS.ASSERT_FINGERPRINT: + kwargs["ssl_assert_fingerprint"] = configs.TLS.ASSERT_FINGERPRINT # The client forces sniff_before_requests when a sniffing delay is passed, so only pass it when enabled - if configs.SNIFF_BEFORE_REQUESTS: - kwargs["min_delay_between_sniffing"] = configs.MIN_DELAY_BETWEEN_SNIFFING + if configs.SNIFFING.BEFORE_REQUESTS: + kwargs["min_delay_between_sniffing"] = configs.SNIFFING.MIN_DELAY _apply_optional_client_kwargs(kwargs, configs) client = Elasticsearch(**kwargs) @@ -627,10 +627,10 @@ def _get_client(configs: ElasticsearchConfig) -> AsyncElasticsearch: """ api_key: tuple[str, str] | None = None basic_auth: tuple[str, str] | None = None - if configs.API_KEY and configs.API_SECRET: - api_key = (configs.API_KEY, configs.API_SECRET.get_secret_value()) - elif configs.HTTP_USER_NAME and configs.HTTP_PASSWORD: - basic_auth = (configs.HTTP_USER_NAME, configs.HTTP_PASSWORD.get_secret_value()) + if configs.AUTH.API_KEY and configs.AUTH.API_SECRET: + api_key = (configs.AUTH.API_KEY, configs.AUTH.API_SECRET.get_secret_value()) + elif configs.AUTH.USER_NAME and configs.AUTH.PASSWORD: + basic_auth = (configs.AUTH.USER_NAME, configs.AUTH.PASSWORD.get_secret_value()) # Build kwargs, only including SSL parameters if they have values kwargs: dict[str, Any] = { @@ -638,20 +638,20 @@ def _get_client(configs: ElasticsearchConfig) -> AsyncElasticsearch: "api_key": api_key, "basic_auth": basic_auth, "request_timeout": configs.REQUEST_TIMEOUT, - "retry_on_status": configs.RETRY_ON_STATUS, - "retry_on_timeout": configs.RETRY_ON_TIMEOUT, - "max_retries": configs.MAX_RETRIES, + "retry_on_status": configs.RETRY.ON_STATUS, + "retry_on_timeout": configs.RETRY.ON_TIMEOUT, + "max_retries": configs.RETRY.MAX_RETRIES, "http_compress": configs.HTTP_COMPRESS, "connections_per_node": configs.CONNECTIONS_PER_NODE, - "verify_certs": configs.VERIFY_CERTS, - "sniff_on_start": configs.SNIFF_ON_START, - "sniff_before_requests": configs.SNIFF_BEFORE_REQUESTS, - "sniff_on_node_failure": configs.SNIFF_ON_NODE_FAILURE, + "verify_certs": configs.TLS.VERIFY_CERTS, + "sniff_on_start": configs.SNIFFING.ON_START, + "sniff_before_requests": configs.SNIFFING.BEFORE_REQUESTS, + "sniff_on_node_failure": configs.SNIFFING.ON_NODE_FAILURE, "max_dead_node_backoff": configs.MAX_DEAD_NODE_BACKOFF, "dead_node_backoff_factor": configs.DEAD_NODE_BACKOFF_FACTOR, "node_selector_class": configs.NODE_SELECTOR_CLASS, - "retry_backoff_base": configs.RETRY_BACKOFF_BASE, - "retry_backoff_cap": configs.RETRY_BACKOFF_CAP, + "retry_backoff_base": configs.RETRY.BACKOFF_BASE, + "retry_backoff_cap": configs.RETRY.BACKOFF_CAP, } # Leave the backoff options out when unset so the client keeps its own defaults kwargs = { @@ -659,17 +659,17 @@ def _get_client(configs: ElasticsearchConfig) -> AsyncElasticsearch: } # Only add SSL parameters if they have values (to avoid passing None) - if configs.CA_CERTS: - kwargs["ca_certs"] = configs.CA_CERTS - if configs.CLIENT_KEY: - kwargs["client_key"] = configs.CLIENT_KEY - if configs.CLIENT_CERT: - kwargs["client_cert"] = configs.CLIENT_CERT - if configs.SSL_ASSERT_FINGERPRINT: - kwargs["ssl_assert_fingerprint"] = configs.SSL_ASSERT_FINGERPRINT + if configs.TLS.CA_CERTS: + kwargs["ca_certs"] = configs.TLS.CA_CERTS + if configs.TLS.CLIENT_KEY: + kwargs["client_key"] = configs.TLS.CLIENT_KEY + if configs.TLS.CLIENT_CERT: + kwargs["client_cert"] = configs.TLS.CLIENT_CERT + if configs.TLS.ASSERT_FINGERPRINT: + kwargs["ssl_assert_fingerprint"] = configs.TLS.ASSERT_FINGERPRINT # The client forces sniff_before_requests when a sniffing delay is passed, so only pass it when enabled - if configs.SNIFF_BEFORE_REQUESTS: - kwargs["min_delay_between_sniffing"] = configs.MIN_DELAY_BETWEEN_SNIFFING + if configs.SNIFFING.BEFORE_REQUESTS: + kwargs["min_delay_between_sniffing"] = configs.SNIFFING.MIN_DELAY _apply_optional_client_kwargs(kwargs, configs) client = AsyncElasticsearch(**kwargs) diff --git a/packages/kafka/archipy/adapters/kafka/adapters.py b/packages/kafka/archipy/adapters/kafka/adapters.py index 6e730be13..eb499e15c 100644 --- a/packages/kafka/archipy/adapters/kafka/adapters.py +++ b/packages/kafka/archipy/adapters/kafka/adapters.py @@ -96,20 +96,20 @@ def _apply_security_config(config: dict[str, str | int | float], configs: KafkaC protocol = configs.SECURITY_PROTOCOL config["security.protocol"] = protocol if protocol in ("SASL_PLAINTEXT", "SASL_SSL"): - if configs.SASL_MECHANISM: - config["sasl.mechanism"] = configs.SASL_MECHANISM - if configs.USERNAME: - config["sasl.username"] = configs.USERNAME - if configs.PASSWORD: - config["sasl.password"] = configs.PASSWORD.get_secret_value() + if configs.SASL.MECHANISM: + config["sasl.mechanism"] = configs.SASL.MECHANISM + if configs.SASL.USERNAME: + config["sasl.username"] = configs.SASL.USERNAME + if configs.SASL.PASSWORD: + config["sasl.password"] = configs.SASL.PASSWORD.get_secret_value() if protocol in ("SSL", "SASL_SSL"): - if configs.SSL_CA_FILE: - config["ssl.ca.location"] = configs.SSL_CA_FILE - if configs.SSL_CERT_FILE: - config["ssl.certificate.location"] = configs.SSL_CERT_FILE - if configs.SSL_KEY_FILE: - config["ssl.key.location"] = configs.SSL_KEY_FILE - config["ssl.endpoint.identification.algorithm"] = configs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM + if configs.SSL.CA_FILE: + config["ssl.ca.location"] = configs.SSL.CA_FILE + if configs.SSL.CERT_FILE: + config["ssl.certificate.location"] = configs.SSL.CERT_FILE + if configs.SSL.KEY_FILE: + config["ssl.key.location"] = configs.SSL.KEY_FILE + config["ssl.endpoint.identification.algorithm"] = configs.SSL.ENDPOINT_IDENTIFICATION_ALGORITHM def _apply_client_config(config: dict[str, str | int | float], configs: KafkaConfig, *, role: str) -> None: diff --git a/packages/keycloak/archipy/adapters/keycloak/_base.py b/packages/keycloak/archipy/adapters/keycloak/_base.py index 29e510081..f4272d71b 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_base.py +++ b/packages/keycloak/archipy/adapters/keycloak/_base.py @@ -91,12 +91,14 @@ def client_options( when asked, proxies and headers). """ cert: str | tuple[str, str] | None = None - if configs.CLIENT_CERT_FILE: + if configs.TLS.CLIENT_CERT_FILE: cert = ( - (configs.CLIENT_CERT_FILE, configs.CLIENT_KEY_FILE) if configs.CLIENT_KEY_FILE else configs.CLIENT_CERT_FILE + (configs.TLS.CLIENT_CERT_FILE, configs.TLS.CLIENT_KEY_FILE) + if configs.TLS.CLIENT_KEY_FILE + else configs.TLS.CLIENT_CERT_FILE ) options: dict[str, Any] = { - "verify": configs.VERIFY_SSL, + "verify": configs.TLS.VERIFY_SSL, "timeout": configs.TIMEOUT, "cert": cert, "max_retries": configs.MAX_RETRIES, diff --git a/packages/keycloak/archipy/adapters/keycloak/_connection.py b/packages/keycloak/archipy/adapters/keycloak/_connection.py index edfec992e..001df0d31 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_connection.py +++ b/packages/keycloak/archipy/adapters/keycloak/_connection.py @@ -84,8 +84,8 @@ def __init__(self, keycloak_configs: KeycloakConfig | None = None) -> None: self._uma_adapter: KeycloakUMA | None = None # Initialize admin client if admin mode is enabled and credentials are provided - if self.configs.IS_ADMIN_MODE_ENABLED and ( - self.configs.CLIENT_SECRET_KEY or (self.configs.ADMIN_USERNAME and self.configs.ADMIN_PASSWORD) + if self.configs.ADMIN.IS_ENABLED and ( + self.configs.CLIENT_SECRET_KEY or (self.configs.ADMIN.USERNAME and self.configs.ADMIN.PASSWORD) ): self._initialize_admin_client() @@ -122,15 +122,15 @@ def _initialize_admin_client(self) -> None: """Initialize or refresh the admin client.""" try: # Check if admin credentials are available - if self.configs.ADMIN_USERNAME and self.configs.ADMIN_PASSWORD: + if self.configs.ADMIN.USERNAME and self.configs.ADMIN.PASSWORD: # Create admin client using admin credentials self._admin_adapter = with_sync_proxies( KeycloakAdmin( server_url=self.configs.SERVER_URL, - username=self.configs.ADMIN_USERNAME, - password=_secret_value(self.configs.ADMIN_PASSWORD), + username=self.configs.ADMIN.USERNAME, + password=_secret_value(self.configs.ADMIN.PASSWORD), realm_name=self.configs.REALM_NAME, - user_realm_name=self.configs.ADMIN_REALM_NAME, + user_realm_name=self.configs.ADMIN.REALM_NAME, **client_options(self.configs, with_proxies=False), ), self.configs, @@ -189,8 +189,8 @@ def admin_adapter(self) -> KeycloakAdmin: UnauthenticatedError: If admin client is not available due to authentication issues UnavailableError: If Keycloak service is unavailable """ - if not self.configs.IS_ADMIN_MODE_ENABLED or not ( - self.configs.CLIENT_SECRET_KEY or (self.configs.ADMIN_USERNAME and self.configs.ADMIN_PASSWORD) + if not self.configs.ADMIN.IS_ENABLED or not ( + self.configs.CLIENT_SECRET_KEY or (self.configs.ADMIN.USERNAME and self.configs.ADMIN.PASSWORD) ): raise UnauthenticatedError( additional_data={ @@ -268,8 +268,8 @@ def __init__(self, keycloak_configs: KeycloakConfig | None = None) -> None: self._admin_lock = asyncio.Lock() # Initialize admin client if admin mode is enabled and credentials are provided - if self.configs.IS_ADMIN_MODE_ENABLED and ( - self.configs.CLIENT_SECRET_KEY or (self.configs.ADMIN_USERNAME and self.configs.ADMIN_PASSWORD) + if self.configs.ADMIN.IS_ENABLED and ( + self.configs.CLIENT_SECRET_KEY or (self.configs.ADMIN.USERNAME and self.configs.ADMIN.PASSWORD) ): self._initialize_admin_client() @@ -306,15 +306,15 @@ def _initialize_admin_client(self) -> None: """Initialize or refresh the admin client.""" try: # Check if admin credentials are available - if self.configs.ADMIN_USERNAME and self.configs.ADMIN_PASSWORD: + if self.configs.ADMIN.USERNAME and self.configs.ADMIN.PASSWORD: # Create admin client using admin credentials self._admin_adapter = with_sync_proxies( KeycloakAdmin( server_url=self.configs.SERVER_URL, - username=self.configs.ADMIN_USERNAME, - password=_secret_value(self.configs.ADMIN_PASSWORD), + username=self.configs.ADMIN.USERNAME, + password=_secret_value(self.configs.ADMIN.PASSWORD), realm_name=self.configs.REALM_NAME, - user_realm_name=self.configs.ADMIN_REALM_NAME, + user_realm_name=self.configs.ADMIN.REALM_NAME, **client_options(self.configs, with_proxies=False), ), self.configs, @@ -364,8 +364,8 @@ def _initialize_admin_client(self) -> None: def _admin_credentials_configured(self) -> bool: """Tell whether admin mode is on and credentials exist for an admin client.""" return bool( - self.configs.IS_ADMIN_MODE_ENABLED - and (self.configs.CLIENT_SECRET_KEY or (self.configs.ADMIN_USERNAME and self.configs.ADMIN_PASSWORD)), + self.configs.ADMIN.IS_ENABLED + and (self.configs.CLIENT_SECRET_KEY or (self.configs.ADMIN.USERNAME and self.configs.ADMIN.PASSWORD)), ) def _admin_is_fresh(self) -> bool: @@ -390,7 +390,7 @@ async def _ensure_admin(self) -> None: async def _a_initialize_admin_client(self) -> None: """Async variant of ``_initialize_admin_client``.""" - if self.configs.ADMIN_USERNAME and self.configs.ADMIN_PASSWORD: + if self.configs.ADMIN.USERNAME and self.configs.ADMIN.PASSWORD: # KeycloakAdmin logs in while it is built, so build it in a worker thread. await asyncio.to_thread(self._initialize_admin_client) return @@ -433,8 +433,8 @@ def admin_adapter(self) -> KeycloakAdmin: UnauthenticatedError: If admin client is not available due to authentication issues UnavailableError: If Keycloak service is unavailable """ - if not self.configs.IS_ADMIN_MODE_ENABLED or not ( - self.configs.CLIENT_SECRET_KEY or (self.configs.ADMIN_USERNAME and self.configs.ADMIN_PASSWORD) + if not self.configs.ADMIN.IS_ENABLED or not ( + self.configs.CLIENT_SECRET_KEY or (self.configs.ADMIN.USERNAME and self.configs.ADMIN.PASSWORD) ): raise UnauthenticatedError( additional_data={ diff --git a/packages/keycloak/archipy/adapters/keycloak/_protocols/oidc/adapter.py b/packages/keycloak/archipy/adapters/keycloak/_protocols/oidc/adapter.py index b8cc76fb2..c23ee1b10 100644 --- a/packages/keycloak/archipy/adapters/keycloak/_protocols/oidc/adapter.py +++ b/packages/keycloak/archipy/adapters/keycloak/_protocols/oidc/adapter.py @@ -110,15 +110,18 @@ def _check_token_claims(claims: dict[str, Any], configs: KeycloakConfig) -> None Raises: InvalidTokenError: If an enforced claim does not match. """ - expected_issuer = configs.EXPECTED_ISSUER or f"{(configs.SERVER_URL or '').rstrip('/')}/realms/{configs.REALM_NAME}" + expected_issuer = ( + 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.EXPECTED_ISSUER or configs.EXPECTED_AUDIENCE) + enforce_any = bool(configs.TOKEN_VALIDATION.EXPECTED_ISSUER or configs.TOKEN_VALIDATION.EXPECTED_AUDIENCE) enforced: list[str] = [] advisory: list[str] = [] if claims.get("iss") != expected_issuer: - (enforced if configs.EXPECTED_ISSUER else advisory).append("iss") - if configs.EXPECTED_AUDIENCE and configs.EXPECTED_AUDIENCE not in audiences: + (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") if claims.get("typ") != "Bearer": (enforced if enforce_any else advisory).append("typ") @@ -126,8 +129,9 @@ def _check_token_claims(claims: dict[str, Any], configs: KeycloakConfig) -> None raise InvalidTokenError(additional_data={"claims": enforced}) if advisory: warnings.warn( - f"Token claims {advisory} do not match the expected values; set KEYCLOAK.EXPECTED_ISSUER or " - "KEYCLOAK.EXPECTED_AUDIENCE to enforce them. Enforcement becomes the default in 6.0.", + 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, ) @@ -166,7 +170,7 @@ def _decode_token_locally(self, token: str) -> dict[str, Any]: claims = self._openid_adapter.decode_token( token, key=_build_jwk_set(self._jwks_raw or {"keys": []}), - leeway=self.configs.TOKEN_LEEWAY_SECONDS, + leeway=self.configs.TOKEN_VALIDATION.LEEWAY_SECONDS, ) _check_token_claims(claims, self.configs) return claims @@ -606,7 +610,7 @@ async def _decode_token_locally(self, token: str) -> dict[str, Any]: claims = await self.openid_adapter.a_decode_token( token, key=_build_jwk_set(self._jwks_raw or {"keys": []}), - leeway=self.configs.TOKEN_LEEWAY_SECONDS, + leeway=self.configs.TOKEN_VALIDATION.LEEWAY_SECONDS, ) _check_token_claims(claims, self.configs) return claims diff --git a/packages/keycloak/archipy/adapters/keycloak/auth.py b/packages/keycloak/archipy/adapters/keycloak/auth.py index 2f4d99c25..cdb4f92fa 100644 --- a/packages/keycloak/archipy/adapters/keycloak/auth.py +++ b/packages/keycloak/archipy/adapters/keycloak/auth.py @@ -801,7 +801,9 @@ async def dependency( ) organization_required = ( - keycloak.configs.REQUIRE_ORGANIZATION if require_organization is None else require_organization + keycloak.configs.TOKEN_VALIDATION.REQUIRE_ORGANIZATION + if require_organization is None + else require_organization ) # Still filled for existing code, but each read warns: AuthContextManager carries the same data. @@ -946,7 +948,9 @@ def authorize_sync(request: object, context: object) -> None: user_roles, token_info, require_organization=( - keycloak.configs.REQUIRE_ORGANIZATION if require_organization is None else require_organization + keycloak.configs.TOKEN_VALIDATION.REQUIRE_ORGANIZATION + if require_organization is None + else require_organization ), lang=lang, ), @@ -972,7 +976,9 @@ async def authorize_async(request: object, context: object) -> None: user_roles, token_info, require_organization=( - keycloak.configs.REQUIRE_ORGANIZATION if require_organization is None else require_organization + keycloak.configs.TOKEN_VALIDATION.REQUIRE_ORGANIZATION + if require_organization is None + else require_organization ), lang=lang, ), diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/_shared.py b/packages/redis/archipy/adapters/redis/adapter_mixins/_shared.py index a81f38345..68272b14a 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/_shared.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/_shared.py @@ -80,25 +80,25 @@ def _tls_acl_kwargs(configs: RedisConfig) -> dict[str, Any]: kwargs: dict[str, Any] = {} if configs.USERNAME: kwargs["username"] = configs.USERNAME - if configs.SSL: + if configs.TLS.IS_ENABLED: kwargs["ssl"] = True - kwargs["ssl_check_hostname"] = configs.SSL_CHECK_HOSTNAME - if configs.SSL_CA_CERTS: - kwargs["ssl_ca_certs"] = configs.SSL_CA_CERTS - if configs.SSL_CERTFILE and configs.SSL_KEYFILE: - kwargs["ssl_certfile"] = configs.SSL_CERTFILE - kwargs["ssl_keyfile"] = configs.SSL_KEYFILE + kwargs["ssl_check_hostname"] = configs.TLS.CHECK_HOSTNAME + if configs.TLS.CA_CERTS: + kwargs["ssl_ca_certs"] = configs.TLS.CA_CERTS + if configs.TLS.CERTFILE and configs.TLS.KEYFILE: + kwargs["ssl_certfile"] = configs.TLS.CERTFILE + kwargs["ssl_keyfile"] = configs.TLS.KEYFILE return kwargs def _resilience_kwargs(configs: RedisConfig, *, is_async: bool = False) -> dict[str, Any]: """Build retry, keepalive and client-name kwargs; empty when none is configured.""" kwargs: dict[str, Any] = {} - if configs.RETRY_ATTEMPTS is not None: - backoff = ExponentialBackoff(cap=configs.RETRY_BACKOFF_CAP, base=configs.RETRY_BACKOFF_BASE) + if configs.RETRY.ATTEMPTS is not None: + backoff = ExponentialBackoff(cap=configs.RETRY.BACKOFF_CAP, base=configs.RETRY.BACKOFF_BASE) retry_class = AsyncRetry if is_async else Retry - kwargs["retry"] = retry_class(backoff, configs.RETRY_ATTEMPTS) - if configs.RETRY_ON_TIMEOUT: + kwargs["retry"] = retry_class(backoff, configs.RETRY.ATTEMPTS) + if configs.RETRY.ON_TIMEOUT: kwargs["retry_on_error"] = [RedisTimeoutError] if configs.SOCKET_KEEPALIVE is not None: kwargs["socket_keepalive"] = configs.SOCKET_KEEPALIVE @@ -146,11 +146,11 @@ def _sentinel_redis_kwargs(configs: RedisConfig, *, is_async: bool = False) -> d def _sentinel_kwargs(configs: RedisConfig) -> dict[str, Any] | None: """Build sentinel-node kwargs: sentinel username, password and the shared TLS settings.""" kwargs: dict[str, Any] = {} - if configs.SENTINEL_USERNAME: - kwargs["username"] = configs.SENTINEL_USERNAME - if configs.SENTINEL_PASSWORD: - kwargs["password"] = configs.SENTINEL_PASSWORD.get_secret_value() - if configs.SSL: + if configs.SENTINEL.USERNAME: + kwargs["username"] = configs.SENTINEL.USERNAME + if configs.SENTINEL.PASSWORD: + kwargs["password"] = configs.SENTINEL.PASSWORD.get_secret_value() + if configs.TLS.IS_ENABLED: kwargs.update({k: v for k, v in _tls_acl_kwargs(configs).items() if k != "username"}) return kwargs or None diff --git a/packages/redis/archipy/adapters/redis/adapter_mixins/connection.py b/packages/redis/archipy/adapters/redis/adapter_mixins/connection.py index 63dda0459..0609a5d84 100644 --- a/packages/redis/archipy/adapters/redis/adapter_mixins/connection.py +++ b/packages/redis/archipy/adapters/redis/adapter_mixins/connection.py @@ -101,7 +101,7 @@ def _set_cluster_clients(self, configs: RedisConfig) -> None: configs (RedisConfig): Configuration settings for Redis cluster. """ startup_nodes = [] - for node in configs.CLUSTER_NODES: + for node in configs.CLUSTER.NODES: if ":" in node: host, port = node.split(":", 1) startup_nodes.append(ClusterNode(host, int(port))) @@ -109,7 +109,7 @@ def _set_cluster_clients(self, configs: RedisConfig) -> None: startup_nodes.append(ClusterNode(node, configs.PORT)) cluster_kwargs: dict[str, Any] = {} - if configs.CLUSTER_READ_FROM_REPLICAS: + if configs.CLUSTER.READ_FROM_REPLICAS: cluster_kwargs["load_balancing_strategy"] = LoadBalancingStrategy.ROUND_ROBIN cluster_client = RedisCluster( @@ -120,7 +120,7 @@ def _set_cluster_clients(self, configs: RedisConfig) -> None: socket_connect_timeout=configs.SOCKET_CONNECT_TIMEOUT, socket_timeout=configs.SOCKET_TIMEOUT, health_check_interval=configs.HEALTH_CHECK_INTERVAL, - require_full_coverage=configs.CLUSTER_REQUIRE_FULL_COVERAGE, + require_full_coverage=configs.CLUSTER.REQUIRE_FULL_COVERAGE, protocol=configs.PROTOCOL, **_tls_acl_kwargs(configs), **_resilience_kwargs(configs, is_async=False), @@ -137,14 +137,14 @@ def _set_sentinel_clients(self, configs: RedisConfig) -> None: Args: configs (RedisConfig): Configuration settings for Redis sentinel. """ - sentinel_service_name = configs.SENTINEL_SERVICE_NAME + sentinel_service_name = configs.SENTINEL.SERVICE_NAME if not sentinel_service_name: raise InvalidArgumentError(argument_name="SENTINEL_SERVICE_NAME") - sentinel_nodes = [(node.split(":")[0], int(node.split(":")[1])) for node in configs.SENTINEL_NODES] + sentinel_nodes = [(node.split(":")[0], int(node.split(":")[1])) for node in configs.SENTINEL.NODES] sentinel_connection = Sentinel( sentinel_nodes, - socket_timeout=configs.SENTINEL_SOCKET_TIMEOUT, + socket_timeout=configs.SENTINEL.SOCKET_TIMEOUT, password=configs.PASSWORD.get_secret_value() if configs.PASSWORD else None, sentinel_kwargs=_sentinel_kwargs(configs), ) @@ -187,7 +187,7 @@ def _build_binary_client(self, configs: RedisConfig) -> Redis | RedisCluster: ) if configs.MODE == RedisMode.CLUSTER: startup_nodes = [] - for node in configs.CLUSTER_NODES: + for node in configs.CLUSTER.NODES: if ":" in node: host, port = node.split(":", 1) startup_nodes.append(ClusterNode(host, int(port))) @@ -195,7 +195,7 @@ def _build_binary_client(self, configs: RedisConfig) -> Redis | RedisCluster: startup_nodes.append(ClusterNode(node, configs.PORT)) cluster_kwargs: dict[str, Any] = {} - if configs.CLUSTER_READ_FROM_REPLICAS: + if configs.CLUSTER.READ_FROM_REPLICAS: cluster_kwargs["load_balancing_strategy"] = LoadBalancingStrategy.ROUND_ROBIN return RedisCluster( @@ -206,7 +206,7 @@ def _build_binary_client(self, configs: RedisConfig) -> Redis | RedisCluster: socket_connect_timeout=configs.SOCKET_CONNECT_TIMEOUT, socket_timeout=configs.SOCKET_TIMEOUT, health_check_interval=configs.HEALTH_CHECK_INTERVAL, - require_full_coverage=configs.CLUSTER_REQUIRE_FULL_COVERAGE, + require_full_coverage=configs.CLUSTER.REQUIRE_FULL_COVERAGE, protocol=configs.PROTOCOL, **_tls_acl_kwargs(configs), **_resilience_kwargs(configs, is_async=False), @@ -379,7 +379,7 @@ def _set_cluster_clients(self, configs: RedisConfig) -> None: configs (RedisConfig): Configuration settings for Redis cluster. """ startup_nodes = [] - for node in configs.CLUSTER_NODES: + for node in configs.CLUSTER.NODES: if ":" in node: host, port = node.split(":", 1) startup_nodes.append(AsyncClusterNode(host, int(port))) @@ -387,7 +387,7 @@ def _set_cluster_clients(self, configs: RedisConfig) -> None: startup_nodes.append(AsyncClusterNode(node, configs.PORT)) cluster_kwargs: dict[str, Any] = {} - if configs.CLUSTER_READ_FROM_REPLICAS: + if configs.CLUSTER.READ_FROM_REPLICAS: cluster_kwargs["load_balancing_strategy"] = AsyncLoadBalancingStrategy.ROUND_ROBIN cluster_client = AsyncRedisCluster( @@ -398,7 +398,7 @@ def _set_cluster_clients(self, configs: RedisConfig) -> None: socket_connect_timeout=configs.SOCKET_CONNECT_TIMEOUT, socket_timeout=configs.SOCKET_TIMEOUT, health_check_interval=configs.HEALTH_CHECK_INTERVAL, - require_full_coverage=configs.CLUSTER_REQUIRE_FULL_COVERAGE, + require_full_coverage=configs.CLUSTER.REQUIRE_FULL_COVERAGE, protocol=configs.PROTOCOL, **_tls_acl_kwargs(configs), **_resilience_kwargs(configs, is_async=True), @@ -415,14 +415,14 @@ def _set_sentinel_clients(self, configs: RedisConfig) -> None: Args: configs (RedisConfig): Configuration settings for Redis sentinel. """ - sentinel_service_name = configs.SENTINEL_SERVICE_NAME + sentinel_service_name = configs.SENTINEL.SERVICE_NAME if not sentinel_service_name: raise InvalidArgumentError(argument_name="SENTINEL_SERVICE_NAME") - sentinel_nodes = [(node.split(":")[0], int(node.split(":")[1])) for node in configs.SENTINEL_NODES] + sentinel_nodes = [(node.split(":")[0], int(node.split(":")[1])) for node in configs.SENTINEL.NODES] sentinel_connection = AsyncSentinel( sentinel_nodes, - socket_timeout=configs.SENTINEL_SOCKET_TIMEOUT, + socket_timeout=configs.SENTINEL.SOCKET_TIMEOUT, password=configs.PASSWORD.get_secret_value() if configs.PASSWORD else None, sentinel_kwargs=_sentinel_kwargs(configs), ) @@ -465,7 +465,7 @@ def _build_binary_client(self, configs: RedisConfig) -> AsyncRedis | AsyncRedisC ) if configs.MODE == RedisMode.CLUSTER: startup_nodes = [] - for node in configs.CLUSTER_NODES: + for node in configs.CLUSTER.NODES: if ":" in node: host, port = node.split(":", 1) startup_nodes.append(AsyncClusterNode(host, int(port))) @@ -473,7 +473,7 @@ def _build_binary_client(self, configs: RedisConfig) -> AsyncRedis | AsyncRedisC startup_nodes.append(AsyncClusterNode(node, configs.PORT)) cluster_kwargs: dict[str, Any] = {} - if configs.CLUSTER_READ_FROM_REPLICAS: + if configs.CLUSTER.READ_FROM_REPLICAS: cluster_kwargs["load_balancing_strategy"] = AsyncLoadBalancingStrategy.ROUND_ROBIN return AsyncRedisCluster( @@ -484,7 +484,7 @@ def _build_binary_client(self, configs: RedisConfig) -> AsyncRedis | AsyncRedisC socket_connect_timeout=configs.SOCKET_CONNECT_TIMEOUT, socket_timeout=configs.SOCKET_TIMEOUT, health_check_interval=configs.HEALTH_CHECK_INTERVAL, - require_full_coverage=configs.CLUSTER_REQUIRE_FULL_COVERAGE, + require_full_coverage=configs.CLUSTER.REQUIRE_FULL_COVERAGE, protocol=configs.PROTOCOL, **_tls_acl_kwargs(configs), **_resilience_kwargs(configs, is_async=True), diff --git a/packages/scylladb/archipy/adapters/scylladb/adapters.py b/packages/scylladb/archipy/adapters/scylladb/adapters.py index bdef27aae..94dbef69d 100644 --- a/packages/scylladb/archipy/adapters/scylladb/adapters.py +++ b/packages/scylladb/archipy/adapters/scylladb/adapters.py @@ -128,22 +128,22 @@ def _cluster_resilience_options(config: ScyllaDBConfig) -> dict[str, Any]: dict[str, Any]: Keyword arguments for ``Cluster``. """ options: dict[str, Any] = {} - if config.IDLE_HEARTBEAT_INTERVAL is not None: - options["idle_heartbeat_interval"] = config.IDLE_HEARTBEAT_INTERVAL - if config.IDLE_HEARTBEAT_TIMEOUT is not None: - options["idle_heartbeat_timeout"] = config.IDLE_HEARTBEAT_TIMEOUT + if config.HEARTBEAT.IDLE_INTERVAL is not None: + options["idle_heartbeat_interval"] = config.HEARTBEAT.IDLE_INTERVAL + if config.HEARTBEAT.IDLE_TIMEOUT is not None: + options["idle_heartbeat_timeout"] = config.HEARTBEAT.IDLE_TIMEOUT if config.CONTROL_CONNECTION_TIMEOUT is not None: options["control_connection_timeout"] = config.CONTROL_CONNECTION_TIMEOUT - if config.RECONNECTION_POLICY == "CONSTANT": + if config.RECONNECTION.POLICY == "CONSTANT": options["reconnection_policy"] = ConstantReconnectionPolicy( - delay=config.RECONNECTION_BASE_DELAY, - max_attempts=config.RECONNECTION_MAX_ATTEMPTS, + delay=config.RECONNECTION.BASE_DELAY, + max_attempts=config.RECONNECTION.MAX_ATTEMPTS, ) - elif config.RECONNECTION_POLICY == "EXPONENTIAL": + elif config.RECONNECTION.POLICY == "EXPONENTIAL": options["reconnection_policy"] = ExponentialReconnectionPolicy( - base_delay=config.RECONNECTION_BASE_DELAY, - max_delay=config.RECONNECTION_MAX_DELAY, - max_attempts=config.RECONNECTION_MAX_ATTEMPTS, + base_delay=config.RECONNECTION.BASE_DELAY, + max_delay=config.RECONNECTION.MAX_DELAY, + max_attempts=config.RECONNECTION.MAX_ATTEMPTS, ) return options @@ -160,10 +160,10 @@ def _execution_profile_options(config: ScyllaDBConfig) -> dict[str, Any]: options: dict[str, Any] = {} if config.SERIAL_CONSISTENCY_LEVEL is not None: options["serial_consistency_level"] = _SERIAL_CONSISTENCY_LEVELS[config.SERIAL_CONSISTENCY_LEVEL] - if config.SPECULATIVE_EXECUTION_DELAY is not None: + if config.SPECULATIVE_EXECUTION.DELAY is not None: options["speculative_execution_policy"] = ConstantSpeculativeExecutionPolicy( - delay=config.SPECULATIVE_EXECUTION_DELAY, - max_attempts=config.SPECULATIVE_EXECUTION_MAX_ATTEMPTS, + delay=config.SPECULATIVE_EXECUTION.DELAY, + max_attempts=config.SPECULATIVE_EXECUTION.MAX_ATTEMPTS, ) return options @@ -177,12 +177,12 @@ def _tls_cluster_options(config: ScyllaDBConfig) -> dict[str, Any]: Returns: dict[str, Any]: Keyword arguments for ``Cluster``; empty when TLS is disabled. """ - if not config.TLS_ENABLED: + if not config.TLS.IS_ENABLED: return {} options: dict[str, Any] = {} - if config.TLS_SERVER_NAME: - options["ssl_options"] = {"server_hostname": config.TLS_SERVER_NAME} - if not config.TLS_SESSION_CACHE_ENABLED: + if config.TLS.SERVER_NAME: + options["ssl_options"] = {"server_hostname": config.TLS.SERVER_NAME} + if not config.TLS.SESSION_CACHE_ENABLED: options["ssl_session_cache"] = None return options @@ -218,9 +218,11 @@ def _warn_insecure_connection(config: ScyllaDBConfig) -> None: Args: config (ScyllaDBConfig): The ScyllaDB configuration. """ - if config.USERNAME and config.PASSWORD and not config.TLS_ENABLED: - logger.warning("ScyllaDB credentials are sent in plain text: enable TLS_ENABLED to encrypt the connection") - if config.TLS_ENABLED and config.TLS_VERIFY_MODE == "CERT_NONE": + if config.USERNAME and config.PASSWORD and not config.TLS.IS_ENABLED: + logger.warning( + "ScyllaDB credentials are sent in plain text: enable SCYLLADB.TLS.IS_ENABLED to encrypt the connection", + ) + if config.TLS.IS_ENABLED and config.TLS.VERIFY_MODE == "CERT_NONE": logger.warning("ScyllaDB TLS certificate verification is disabled: the server identity is not checked") @@ -262,13 +264,13 @@ def _build_cluster(config: ScyllaDBConfig) -> Cluster: else: load_balancing_policy = TokenAwarePolicy(RoundRobinPolicy()) - if config.RETRY_POLICY == "FALLTHROUGH": + if config.RETRY.POLICY == "FALLTHROUGH": retry_policy = FallthroughRetryPolicy() else: # EXPONENTIAL_BACKOFF (default) retry_policy = _IdempotentSafeRetryPolicy( - max_num_retries=config.RETRY_MAX_NUM_RETRIES, - min_interval=config.RETRY_MIN_INTERVAL, - max_interval=config.RETRY_MAX_INTERVAL, + max_num_retries=config.RETRY.MAX_NUM_RETRIES, + min_interval=config.RETRY.MIN_INTERVAL, + max_interval=config.RETRY.MAX_INTERVAL, ) # Shard awareness disabled for Docker/NAT environments shard_aware_options = None @@ -511,10 +513,10 @@ def _build_create_keyspace_query( if replication_factor is not None: replication_factor = cls._validate_non_negative_int(replication_factor, "replication_factor") - if config.REPLICATION_STRATEGY == "NetworkTopologyStrategy" and config.REPLICATION_CONFIG: + if config.REPLICATION.STRATEGY == "NetworkTopologyStrategy" and config.REPLICATION.CONFIG: parts = ["'class': 'NetworkTopologyStrategy'"] factors: list[int] = [] - for dc, configured in config.REPLICATION_CONFIG.items(): + for dc, configured in config.REPLICATION.CONFIG.items(): validated_dc = cls._validate_cql_identifier(dc, "replication_datacenter") factor = configured if replication_factor is None else replication_factor factors.append(factor) @@ -763,7 +765,7 @@ def prepare(self, query: str) -> PreparedStatement: """ session = self.get_session() try: - if self.config.ENABLE_PREPARED_STATEMENT_CACHE: + if self.config.PREPARED_CACHE.IS_ENABLED: # Use cached version if available - call the cached method cached_method: Any = getattr(self, "_prepare_cached", None) if cached_method is not None: @@ -778,7 +780,7 @@ def prepare(self, query: str) -> PreparedStatement: def __post_init__(self) -> None: """Post-initialization hook to apply cache decorator if enabled.""" - if self.config.ENABLE_PREPARED_STATEMENT_CACHE: + if self.config.PREPARED_CACHE.IS_ENABLED: # Create a method to cache def _prepare_internal(keyspace: str | None, query: str) -> PreparedStatement: # noqa: ARG001 """Prepare a CQL statement; the keyspace only keys the cache.""" @@ -793,8 +795,8 @@ def _prepare_internal(keyspace: str | None, query: str) -> PreparedStatement: # # Apply cache decorator cached_prepare = ttl_cache( - ttl_seconds=self.config.PREPARED_STATEMENT_CACHE_TTL_SECONDS, - maxsize=self.config.PREPARED_STATEMENT_CACHE_SIZE, + ttl_seconds=self.config.PREPARED_CACHE.TTL_SECONDS, + maxsize=self.config.PREPARED_CACHE.SIZE, )(_prepare_internal) # Store the cached version using setattr for dynamic attribute self._prepare_cached = cached_prepare @@ -814,7 +816,7 @@ def _execute_dml(self, query: str, params: tuple[Any, ...] | None, *, idempotent Returns: ResultSet: The query result set. """ - if self.config.ENABLE_PREPARED_STATEMENT_CACHE: + if self.config.PREPARED_CACHE.IS_ENABLED: statement = self.prepare(query.replace("%s", "?")) statement.is_idempotent = idempotent return self.execute_prepared(statement, params) @@ -1310,7 +1312,7 @@ async def prepare(self, query: str) -> PreparedStatement: """ session = await self.get_session() try: - if self.config.ENABLE_PREPARED_STATEMENT_CACHE: + if self.config.PREPARED_CACHE.IS_ENABLED: # Use cached version if available - call the cached method cached_method: Any = getattr(self, "_prepare_cached", None) if cached_method is not None: @@ -1325,7 +1327,7 @@ async def prepare(self, query: str) -> PreparedStatement: def __post_init__(self) -> None: """Post-initialization hook to apply cache decorator if enabled.""" - if self.config.ENABLE_PREPARED_STATEMENT_CACHE: + if self.config.PREPARED_CACHE.IS_ENABLED: # Create an async method to cache async def _prepare_internal(keyspace: str | None, query: str) -> PreparedStatement: # noqa: ARG001 """Prepare a CQL statement asynchronously; the keyspace only keys the cache.""" @@ -1340,8 +1342,8 @@ async def _prepare_internal(keyspace: str | None, query: str) -> PreparedStateme # Apply async cache decorator cached_prepare = alru_cache( - ttl=self.config.PREPARED_STATEMENT_CACHE_TTL_SECONDS, - maxsize=self.config.PREPARED_STATEMENT_CACHE_SIZE, + ttl=self.config.PREPARED_CACHE.TTL_SECONDS, + maxsize=self.config.PREPARED_CACHE.SIZE, )(_prepare_internal) # Store the cached version using setattr for dynamic attribute self._prepare_cached = cached_prepare @@ -1367,7 +1369,7 @@ async def _execute_dml( Returns: ResultSet: The query result set. """ - if self.config.ENABLE_PREPARED_STATEMENT_CACHE: + if self.config.PREPARED_CACHE.IS_ENABLED: statement = await self.prepare(query.replace("%s", "?")) statement.is_idempotent = idempotent return await self.execute_prepared(statement, params) diff --git a/packages/temporal/archipy/adapters/temporal/adapters.py b/packages/temporal/archipy/adapters/temporal/adapters.py index c07a92c33..fd1ca26e2 100644 --- a/packages/temporal/archipy/adapters/temporal/adapters.py +++ b/packages/temporal/archipy/adapters/temporal/adapters.py @@ -224,13 +224,13 @@ def _build_connect_kwargs(self) -> dict[str, Any]: "namespace": self.config.NAMESPACE, "lazy": self.config.LAZY_CONNECT, "keep_alive_config": KeepAliveConfig( - interval_millis=self.config.KEEP_ALIVE_INTERVAL_MS, - timeout_millis=self.config.KEEP_ALIVE_TIMEOUT_MS, + interval_millis=self.config.KEEP_ALIVE.INTERVAL_MS, + timeout_millis=self.config.KEEP_ALIVE.TIMEOUT_MS, ), "retry_config": RetryConfig( - initial_interval_millis=self.config.CLIENT_RPC_RETRY_INITIAL_INTERVAL_MS, - max_interval_millis=self.config.CLIENT_RPC_RETRY_MAX_INTERVAL_MS, - max_retries=self.config.CLIENT_RPC_RETRY_MAX_RETRIES, + initial_interval_millis=self.config.CLIENT_RETRY.INITIAL_INTERVAL_MS, + max_interval_millis=self.config.CLIENT_RETRY.MAX_INTERVAL_MS, + max_retries=self.config.CLIENT_RETRY.MAX_RETRIES, ), } connect_kwargs.update(self._optional_connect_kwargs()) @@ -323,9 +323,9 @@ def _has_tls_config(self) -> bool: """ return any( [ - self.config.TLS_CA_CERT, - self.config.TLS_CLIENT_CERT, - self.config.TLS_SERVER_NAME, + self.config.TLS.CA_CERT, + self.config.TLS.CLIENT_CERT, + self.config.TLS.SERVER_NAME, ], ) @@ -334,20 +334,20 @@ def _tls_option(self) -> TLSConfig | bool | None: Returns: TLSConfig | bool | None: A TLS configuration when TLS settings are present (unless TLS is forced off), - the ``TLS_ENABLED`` flag otherwise, or None to let the SDK enable TLS when an API key is set. + the ``TLS.IS_ENABLED`` flag otherwise, or None to let the SDK enable TLS when an API key is set. """ - if self.config.TLS_ENABLED is False: + if self.config.TLS.IS_ENABLED is False: return False if self._has_tls_config(): return self._build_tls_config() - return self.config.TLS_ENABLED + return self.config.TLS.IS_ENABLED def _build_tls_config(self) -> TLSConfig: """Build TLS configuration for secure connections from the configured files. Server-only TLS needs just the CA certificate (or none, to use the system CA bundle); mutual TLS adds the - client certificate and key. ``TLS_VERIFICATION_SERVER_NAME`` checks the certificate name without changing - the SNI that ``TLS_SERVER_NAME`` sets. + client certificate and key. ``TLS.VERIFICATION_SERVER_NAME`` checks the certificate name without changing + the SNI that ``TLS.SERVER_NAME`` sets. Returns: TLSConfig: The TLS configuration object. @@ -357,11 +357,11 @@ def _build_tls_config(self) -> TLSConfig: """ try: return TLSConfig( - server_root_ca_cert=self._read_tls_file(self.config.TLS_CA_CERT), - client_cert=self._read_tls_file(self.config.TLS_CLIENT_CERT), - client_private_key=self._read_tls_file(self.config.TLS_CLIENT_KEY), - domain=self.config.TLS_SERVER_NAME, - verification_server_name=self.config.TLS_VERIFICATION_SERVER_NAME, + server_root_ca_cert=self._read_tls_file(self.config.TLS.CA_CERT), + client_cert=self._read_tls_file(self.config.TLS.CLIENT_CERT), + client_private_key=self._read_tls_file(self.config.TLS.CLIENT_KEY), + domain=self.config.TLS.SERVER_NAME, + verification_server_name=self.config.TLS.VERIFICATION_SERVER_NAME, ) except OSError as error: raise InvalidArgumentError(additional_data={"error_type": type(error).__name__}) from error @@ -458,11 +458,11 @@ def _build_retry_policy(self) -> RetryPolicy: RetryPolicy: The configured retry policy. """ return RetryPolicy( - initial_interval=timedelta(seconds=self.config.RETRY_INITIAL_INTERVAL), - maximum_attempts=self.config.RETRY_MAXIMUM_ATTEMPTS, - backoff_coefficient=self.config.RETRY_BACKOFF_COEFFICIENT, - maximum_interval=timedelta(seconds=self.config.RETRY_MAXIMUM_INTERVAL), - non_retryable_error_types=self.config.RETRY_NON_RETRYABLE_ERROR_TYPES, + initial_interval=timedelta(seconds=self.config.RETRY.INITIAL_INTERVAL), + maximum_attempts=self.config.RETRY.MAXIMUM_ATTEMPTS, + backoff_coefficient=self.config.RETRY.BACKOFF_COEFFICIENT, + maximum_interval=timedelta(seconds=self.config.RETRY.MAXIMUM_INTERVAL), + non_retryable_error_types=self.config.RETRY.NON_RETRYABLE_ERROR_TYPES, ) def _build_workflow_retry_policy(self) -> RetryPolicy | None: @@ -473,7 +473,7 @@ def _build_workflow_retry_policy(self) -> RetryPolicy | None: Returns: RetryPolicy | None: The configured retry policy, or None when workflow retries are disabled. """ - if not self.config.WORKFLOW_RETRY_ENABLED: + if not self.config.WORKFLOW.RETRY_ENABLED: return None return self._build_retry_policy() @@ -559,9 +559,9 @@ async def start_workflow( *positional_args, id=workflow_id, task_queue=task_queue, - execution_timeout=self._timeout(execution_timeout, self.config.WORKFLOW_EXECUTION_TIMEOUT), - run_timeout=self._timeout(run_timeout, self.config.WORKFLOW_RUN_TIMEOUT), - task_timeout=self._timeout(task_timeout, self.config.WORKFLOW_TASK_TIMEOUT), + execution_timeout=self._timeout(execution_timeout, self.config.WORKFLOW.EXECUTION_TIMEOUT), + run_timeout=self._timeout(run_timeout, self.config.WORKFLOW.RUN_TIMEOUT), + task_timeout=self._timeout(task_timeout, self.config.WORKFLOW.TASK_TIMEOUT), retry_policy=self._build_workflow_retry_policy(), memo=memo, search_attributes=search_attributes, @@ -619,9 +619,9 @@ async def execute_workflow( *positional_args, id=workflow_id, task_queue=task_queue, - execution_timeout=self._timeout(execution_timeout, self.config.WORKFLOW_EXECUTION_TIMEOUT), - run_timeout=self._timeout(run_timeout, self.config.WORKFLOW_RUN_TIMEOUT), - task_timeout=self._timeout(task_timeout, self.config.WORKFLOW_TASK_TIMEOUT), + execution_timeout=self._timeout(execution_timeout, self.config.WORKFLOW.EXECUTION_TIMEOUT), + run_timeout=self._timeout(run_timeout, self.config.WORKFLOW.RUN_TIMEOUT), + task_timeout=self._timeout(task_timeout, self.config.WORKFLOW.TASK_TIMEOUT), retry_policy=self._build_workflow_retry_policy(), **self._id_policies(id_reuse_policy, id_conflict_policy), ) diff --git a/packages/temporal/archipy/adapters/temporal/base.py b/packages/temporal/archipy/adapters/temporal/base.py index c06d16ed9..5dbb863ea 100644 --- a/packages/temporal/archipy/adapters/temporal/base.py +++ b/packages/temporal/archipy/adapters/temporal/base.py @@ -121,16 +121,16 @@ async def _execute_activity_with_retry( # Use config defaults if not provided if start_to_close_timeout is None: - start_to_close_timeout = timedelta(seconds=temporal_config.ACTIVITY_START_TO_CLOSE_TIMEOUT) - if heartbeat_timeout is None and temporal_config.ACTIVITY_HEARTBEAT_TIMEOUT is not None: - heartbeat_timeout = timedelta(seconds=temporal_config.ACTIVITY_HEARTBEAT_TIMEOUT) + start_to_close_timeout = timedelta(seconds=temporal_config.ACTIVITY.START_TO_CLOSE_TIMEOUT) + if heartbeat_timeout is None and temporal_config.ACTIVITY.HEARTBEAT_TIMEOUT is not None: + heartbeat_timeout = timedelta(seconds=temporal_config.ACTIVITY.HEARTBEAT_TIMEOUT) if retry_policy is None: retry_policy = RetryPolicy( - initial_interval=timedelta(seconds=temporal_config.RETRY_INITIAL_INTERVAL), - maximum_attempts=temporal_config.RETRY_MAXIMUM_ATTEMPTS, - backoff_coefficient=temporal_config.RETRY_BACKOFF_COEFFICIENT, - maximum_interval=timedelta(seconds=temporal_config.RETRY_MAXIMUM_INTERVAL), - non_retryable_error_types=temporal_config.RETRY_NON_RETRYABLE_ERROR_TYPES, + initial_interval=timedelta(seconds=temporal_config.RETRY.INITIAL_INTERVAL), + maximum_attempts=temporal_config.RETRY.MAXIMUM_ATTEMPTS, + backoff_coefficient=temporal_config.RETRY.BACKOFF_COEFFICIENT, + maximum_interval=timedelta(seconds=temporal_config.RETRY.MAXIMUM_INTERVAL), + non_retryable_error_types=temporal_config.RETRY.NON_RETRYABLE_ERROR_TYPES, ) return await workflow.execute_activity( @@ -169,8 +169,8 @@ async def _execute_child_workflow( temporal_config = BaseConfig.global_config().TEMPORAL # Use config defaults if not provided - if execution_timeout is None and temporal_config.WORKFLOW_EXECUTION_TIMEOUT is not None: - execution_timeout = timedelta(seconds=temporal_config.WORKFLOW_EXECUTION_TIMEOUT) + if execution_timeout is None and temporal_config.WORKFLOW.EXECUTION_TIMEOUT is not None: + execution_timeout = timedelta(seconds=temporal_config.WORKFLOW.EXECUTION_TIMEOUT) return await workflow.execute_child_workflow( child_workflow, diff --git a/packages/temporal/archipy/adapters/temporal/worker.py b/packages/temporal/archipy/adapters/temporal/worker.py index b4d966327..ba37c00a4 100644 --- a/packages/temporal/archipy/adapters/temporal/worker.py +++ b/packages/temporal/archipy/adapters/temporal/worker.py @@ -186,7 +186,7 @@ async def stop(self, grace_period: int | None = None) -> None: grace_period (int, optional): Seconds this call waits for the worker to stop before giving up (plus ``SHUTDOWN_MARGIN_SECONDS``). If None, uses the configured graceful shutdown timeout. It does not change the SDK's own grace period for running activities, which is fixed when the - worker is built (``WORKER_GRACEFUL_SHUTDOWN_SECONDS``). + worker is built (``WORKER.GRACEFUL_SHUTDOWN_SECONDS``). Raises: WorkerShutdownError: If the worker fails to stop gracefully. @@ -336,7 +336,7 @@ def _poller_behavior(self) -> PollerBehavior: Returns: PollerBehavior: Autoscaling pollers, or the SDK default of at most 5 pollers. """ - if self.config.WORKER_POLLER_AUTOSCALING: + if self.config.WORKER.POLLER_AUTOSCALING: return PollerBehaviorAutoscaling() return PollerBehaviorSimpleMaximum(maximum=5) @@ -344,9 +344,9 @@ def _eager_activity_reservations(self) -> int: """Resolve how many eager activities one workflow task may reserve. Returns: - int: ``WORKER_MAX_EAGER_ACTIVITY_RESERVATIONS``, or the SDK default when it is unset. + int: ``WORKER.MAX_EAGER_ACTIVITY_RESERVATIONS``, or the SDK default when it is unset. """ - reservations = self.config.WORKER_MAX_EAGER_ACTIVITY_RESERVATIONS + reservations = self.config.WORKER.MAX_EAGER_ACTIVITY_RESERVATIONS return _SDK_EAGER_ACTIVITY_RESERVATIONS if reservations is None else reservations @override @@ -439,16 +439,16 @@ async def start_worker( identity=worker_identity, max_concurrent_workflow_tasks=max_concurrent_workflow_tasks, max_concurrent_activities=max_concurrent_activities, - max_cached_workflows=self.config.WORKER_MAX_CACHED_WORKFLOWS, - graceful_shutdown_timeout=timedelta(seconds=self.config.WORKER_GRACEFUL_SHUTDOWN_SECONDS), - debug_mode=self.config.WORKER_DEBUG_MODE, - disable_eager_activity_execution=self.config.WORKER_DISABLE_EAGER_ACTIVITY_EXECUTION, + max_cached_workflows=self.config.WORKER.MAX_CACHED_WORKFLOWS, + graceful_shutdown_timeout=timedelta(seconds=self.config.WORKER.GRACEFUL_SHUTDOWN_SECONDS), + debug_mode=self.config.WORKER.DEBUG_MODE, + disable_eager_activity_execution=self.config.WORKER.DISABLE_EAGER_ACTIVITY_EXECUTION, max_eager_activity_reservations_per_workflow_task=self._eager_activity_reservations(), - max_concurrent_local_activities=self.config.WORKER_MAX_CONCURRENT_LOCAL_ACTIVITIES, + max_concurrent_local_activities=self.config.WORKER.MAX_CONCURRENT_LOCAL_ACTIVITIES, tuner=tuner, activity_executor=activity_executor, - max_activities_per_second=self.config.WORKER_MAX_ACTIVITIES_PER_SECOND, - max_task_queue_activities_per_second=self.config.WORKER_MAX_TASK_QUEUE_ACTIVITIES_PER_SECOND, + max_activities_per_second=self.config.WORKER.MAX_ACTIVITIES_PER_SECOND, + max_task_queue_activities_per_second=self.config.WORKER.MAX_TASK_QUEUE_ACTIVITIES_PER_SECOND, workflow_task_poller_behavior=self._poller_behavior(), activity_task_poller_behavior=self._poller_behavior(), ) @@ -464,7 +464,7 @@ async def start_worker( identity=worker_identity, max_concurrent_workflow_tasks=max_concurrent_workflow_tasks, max_concurrent_activities=max_concurrent_activities, - graceful_shutdown_seconds=self.config.WORKER_GRACEFUL_SHUTDOWN_SECONDS, + graceful_shutdown_seconds=self.config.WORKER.GRACEFUL_SHUTDOWN_SECONDS, ) # Start the worker diff --git a/packages/vault/archipy/adapters/vault/adapters.py b/packages/vault/archipy/adapters/vault/adapters.py index 3ccb10a65..da3060e7f 100644 --- a/packages/vault/archipy/adapters/vault/adapters.py +++ b/packages/vault/archipy/adapters/vault/adapters.py @@ -256,7 +256,7 @@ def _maybe_renew_token(self) -> None: extra round trip. Non-expiring (``ttl == 0``) and non-renewable tokens are never renewed; a failed renewal is logged and the real call still runs. """ - if not self.configs.AUTO_RENEW_TOKEN: + if not self.configs.TOKEN_RENEWAL.AUTO_RENEW_TOKEN: return with self._token_lock: try: @@ -266,7 +266,7 @@ def _maybe_renew_token(self) -> None: if ( expires_at is None or not self._token_renewable - or expires_at - time.monotonic() > self.configs.RENEW_THRESHOLD_SECONDS + or expires_at - time.monotonic() > self.configs.TOKEN_RENEWAL.RENEW_THRESHOLD_SECONDS ): return response = self._client.auth.token.renew_self()