Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
366 changes: 183 additions & 183 deletions .env.example

Large diffs are not rendered by default.

34 changes: 17 additions & 17 deletions .env.test
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,23 @@ APM_SERVER__IMAGE=elastic/apm-server:9.5.6
SCYLLADB__IMAGE=scylladb/scylla:2026.3.6

AUTH__SECRET_KEY=test-only-jwt-signing-key-not-a-secret-0123456789
AUTH__TOTP_SECRET_KEY=CHANGE_ME
AUTH__TOTP__SECRET_KEY=CHANGE_ME

FILE__SECRET_KEY=CHANGE_ME
FILE__DEFAULT_EXPIRY_MINUTES=10
FILE__ALLOWED_EXTENSIONS=["jpg","png","pdf","txt"]

FASTAPI__PROJECT_NAME="Test API"
FASTAPI__CORS_MIDDLEWARE_ALLOW_ORIGINS=["https://example.com"]
FASTAPI__CORS_MIDDLEWARE_ALLOW_CREDENTIALS=True
FASTAPI__CORS_MIDDLEWARE_ALLOW_METHODS=["GET", "POST"]
FASTAPI__CORS_MIDDLEWARE_ALLOW_HEADERS=["Content-Type", "Authorization"]
FASTAPI__CORS_MIDDLEWARE_ALLOW_ORIGIN_REGEX=
FASTAPI__CORS_MIDDLEWARE_EXPOSE_HEADERS=["X-Total-Count", "X-Request-ID"]
FASTAPI__CORS_MIDDLEWARE_MAX_AGE=600
FASTAPI__CORS__ALLOW_ORIGINS=["https://example.com"]
FASTAPI__CORS__ALLOW_CREDENTIALS=True
FASTAPI__CORS__ALLOW_METHODS=["GET", "POST"]
FASTAPI__CORS__ALLOW_HEADERS=["Content-Type", "Authorization"]
FASTAPI__CORS__ALLOW_ORIGIN_REGEX=
FASTAPI__CORS__EXPOSE_HEADERS=["X-Total-Count", "X-Request-ID"]
FASTAPI__CORS__MAX_AGE=600
FASTAPI__OPENAPI_URL="/openapi.json"
FASTAPI__DOCS_URL="/docs"
FASTAPI__RE_DOCS_URL="/redoc"
FASTAPI__RE_DOC_URL="/redoc"
FASTAPI__SWAGGER_UI_PARAMS={}

# Temporal Configuration
Expand Down Expand Up @@ -78,19 +78,19 @@ STARROCKS_SQLALCHEMY__PASSWORD=

# Keycloak Configuration
KEYCLOAK__SERVER_URL=http://localhost:8080
KEYCLOAK__ADMIN_USERNAME=admin
KEYCLOAK__ADMIN_PASSWORD=admin
KEYCLOAK__ADMIN__USERNAME=admin
KEYCLOAK__ADMIN__PASSWORD=admin
KEYCLOAK__REALM_NAME=master
KEYCLOAK__CLIENT_ID=admin-cli
KEYCLOAK__IS_ADMIN_MODE_ENABLED=true
KEYCLOAK__ADMIN_REALM_NAME=master
KEYCLOAK__VERIFY_SSL=false
KEYCLOAK__ADMIN__IS_ENABLED=true
KEYCLOAK__ADMIN__REALM_NAME=master
KEYCLOAK__TLS__VERIFY_SSL=false
KEYCLOAK__TIMEOUT=30

# Elasticsearch Configuration
ELASTIC__HOSTS=["http://localhost:9200"]
ELASTIC__HTTP_USER_NAME=elastic
ELASTIC__HTTP_PASSWORD=test_password
ELASTIC__AUTH__USER_NAME=elastic
ELASTIC__AUTH__PASSWORD=test_password

# Kafka Configuration
KAFKA__BROKERS_LIST=["localhost:9092"]
Expand All @@ -104,7 +104,7 @@ MINIO__SECRET_KEY=test_secret_key
VAULT__ENABLED=false
VAULT__AUTH_METHOD=token
VAULT__MOUNT_POINT=secret
VAULT__VERIFY_SSL=false
VAULT__TLS__VERIFY_SSL=false

# ScyllaDB Configuration
SCYLLADB__CONTACT_POINTS=["localhost"]
Expand Down
56 changes: 0 additions & 56 deletions archipy/adapters/base/sqlalchemy/atomic.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
log_driver_error,
)
from archipy.adapters.base.sqlalchemy.session_manager_registry import SessionManagerRegistry
from archipy.helpers._deprecation import deprecated_alias, warn_deprecated_name
from archipy.models.errors import (
BaseError,
DatabaseConfigurationError,
Expand Down Expand Up @@ -807,58 +806,3 @@ def mysql_sqlalchemy_atomic[**P, R](
Callable: The wrapped function, or a decorator to apply later when ``function`` is None.
"""
return _atomic_for("mysql", function, registry, savepoint)


def sqlalchemy_atomic_decorator(
db_type: str,
is_async: bool = False,
function: Callable[..., Any] | None = None,
) -> Callable[..., Any]:
"""Deprecated: use :func:`sqlalchemy_atomic`, which detects async functions itself.

Args:
db_type (str): The database type ("postgres", "sqlite", "starrocks", or "mysql").
is_async (bool): Ignored; the function kind is detected automatically.
function (Callable | None): The function to wrap. If None, returns a decorator to apply later.

Returns:
Callable: The wrapped function, or a decorator to apply later when ``function`` is None.
"""
del is_async
warn_deprecated_name("sqlalchemy_atomic_decorator", "sqlalchemy_atomic")
return sqlalchemy_atomic(db_type, function)


postgres_sqlalchemy_atomic_decorator = deprecated_alias(
"postgres_sqlalchemy_atomic_decorator",
postgres_sqlalchemy_atomic,
)

async_postgres_sqlalchemy_atomic_decorator = deprecated_alias(
"async_postgres_sqlalchemy_atomic_decorator",
postgres_sqlalchemy_atomic,
)

sqlite_sqlalchemy_atomic_decorator = deprecated_alias("sqlite_sqlalchemy_atomic_decorator", sqlite_sqlalchemy_atomic)

async_sqlite_sqlalchemy_atomic_decorator = deprecated_alias(
"async_sqlite_sqlalchemy_atomic_decorator",
sqlite_sqlalchemy_atomic,
)

starrocks_sqlalchemy_atomic_decorator = deprecated_alias(
"starrocks_sqlalchemy_atomic_decorator",
starrocks_sqlalchemy_atomic,
)

async_starrocks_sqlalchemy_atomic_decorator = deprecated_alias(
"async_starrocks_sqlalchemy_atomic_decorator",
starrocks_sqlalchemy_atomic,
)

mysql_sqlalchemy_atomic_decorator = deprecated_alias("mysql_sqlalchemy_atomic_decorator", mysql_sqlalchemy_atomic)

async_mysql_sqlalchemy_atomic_decorator = deprecated_alias(
"async_mysql_sqlalchemy_atomic_decorator",
mysql_sqlalchemy_atomic,
)
77 changes: 23 additions & 54 deletions archipy/adapters/email/adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import os
import smtplib
import ssl
import warnings
from email import encoders
from email.errors import MessageError
from email.mime.audio import MIMEAudio
Expand All @@ -26,7 +25,7 @@
from archipy.adapters.email.ports import EmailPort
from archipy.configs.base_config import BaseConfig
from archipy.helpers.decorators.tracing import trace_span
from archipy.helpers.utils.base_utils import BaseUtils
from archipy.helpers.errors import capture_exception
from archipy.helpers.utils.datetime_utils import DatetimeUtils
from archipy.models.dtos.email_dtos import EmailAttachmentDTO
from archipy.models.errors import ConfigurationError, InvalidArgumentError, UnavailableError
Expand Down Expand Up @@ -75,7 +74,7 @@ def __init__(self, config: EmailConfig) -> None:
"""Initialize EmailConnectionManager.

Raises:
ConfigurationError: If only one of ``USERNAME`` and ``PASSWORD`` is set while ``TLS.MODE`` is not ``auto``.
ConfigurationError: If credentials are incomplete or SMTP authentication is configured without TLS.
"""
self.config = config
self.smtp_connection: smtplib.SMTP | None = None
Expand All @@ -84,53 +83,24 @@ def __init__(self, config: EmailConfig) -> None:
self._validate_security()

def _validate_security(self) -> None:
"""Check the TLS and credential settings; the legacy ``auto`` mode only warns."""
half_set = bool(self.config.USERNAME) != bool(self.config.PASSWORD)
if self.config.TLS.MODE == "auto":
warnings.warn(
"EMAIL.TLS.MODE='auto' is deprecated: STARTTLS is opportunistic, the certificate is not verified "
"and a failed upgrade falls back to clear text. Set TLS.MODE to 'starttls' or 'implicit'.",
DeprecationWarning,
stacklevel=3,
)
if half_set:
warnings.warn(
"EMAIL.USERNAME and EMAIL.PASSWORD must be set together; login is skipped. "
"This will be an error in a future release.",
DeprecationWarning,
stacklevel=3,
)
elif half_set:
"""Require paired credentials and TLS for SMTP authentication."""
if bool(self.config.USERNAME) != bool(self.config.PASSWORD):
raise ConfigurationError(
operation="email_credentials",
reason="USERNAME and PASSWORD must be set together",
)
if self.config.TLS.MODE == "none" and self.config.USERNAME and self.config.PASSWORD:
warnings.warn(
"EMAIL.TLS.MODE='none' sends USERNAME and PASSWORD in clear text. "
"Set TLS.MODE to 'starttls' or 'implicit'; clear-text login will be rejected in a future release.",
DeprecationWarning,
stacklevel=3,
)
if self.config.TLS.MODE in ("starttls", "implicit") and not self.config.TLS.VERIFY:
warnings.warn(
"EMAIL.TLS.VERIFY=False disables certificate and host name verification, which exposes the "
"session and credentials to interception. Use TLS.CA_FILE for a private CA; "
"TLS.VERIFY=False will be rejected in a future release.",
DeprecationWarning,
stacklevel=3,
if self.config.TLS.MODE == "none" and self.config.USERNAME:
raise ConfigurationError(
operation="email_credentials",
reason="SMTP authentication requires TLS.MODE 'starttls' or 'implicit'",
)

def _build_ssl_context(self) -> ssl.SSLContext:
"""Build the TLS context from ``TLS.CA_FILE`` and ``TLS.VERIFY``."""
context = ssl.create_default_context(cafile=self.config.TLS.CA_FILE)
if not self.config.TLS.VERIFY:
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
return context
"""Build the TLS context with certificate and hostname verification."""
return ssl.create_default_context(cafile=self.config.TLS.CA_FILE)

def _open_session(self) -> tuple[smtplib.SMTP, str]:
"""Open the SMTP session for ``TLS_MODE`` and return it with the TLS mode actually in use."""
"""Open the SMTP session for ``TLS.MODE`` and return it with the TLS mode actually in use."""
mode = self.config.TLS.MODE
source_address = (self.config.SOURCE_ADDRESS, self.config.SOURCE_PORT) if self.config.SOURCE_ADDRESS else None
common: dict[str, Any] = {
Expand All @@ -157,39 +127,38 @@ def _open_session(self) -> tuple[smtplib.SMTP, str]:
return session, tls_mode

def _negotiate_tls(self, session: smtplib.SMTP) -> str:
"""Greet the server and upgrade with STARTTLS as ``TLS_MODE`` demands; return the TLS mode in use."""
"""Greet the server and upgrade with STARTTLS as ``TLS.MODE`` demands; return the TLS mode in use."""
mode = self.config.TLS.MODE
session.ehlo()
offered = session.has_extn("starttls")
if mode == "starttls" and not offered:
if mode == "none":
return "none"
if not session.has_extn("starttls"):
message = "STARTTLS is required but the server does not offer it"
raise smtplib.SMTPNotSupportedError(message)
if mode == "none" or (mode == "auto" and not offered):
return "none"
session.starttls(context=self._build_ssl_context() if mode == "starttls" else None)
session.starttls(context=self._build_ssl_context())
session.ehlo()
return "starttls"

def connect(self) -> None:
"""Establish the SMTP connection with the configured transport security and authentication.

``TLS_MODE`` ``starttls`` fails when the server does not offer STARTTLS or the upgrade fails, and
``TLS.MODE`` ``starttls`` fails when the server does not offer STARTTLS or the upgrade fails, and
``implicit`` opens a TLS connection from the start; neither falls back to clear text.
Failures are captured and leave ``smtp_connection`` as ``None``; the cause is kept in ``last_error``.

Raises:
InvalidArgumentError: If no SMTP server is configured.
ConfigurationError: If the SMTP credentials or transport settings are incompatible.
"""
if not self.config.SMTP_SERVER:
raise InvalidArgumentError(argument_name="SMTP_SERVER")
self._validate_security()

try:
session, tls_mode = self._open_session()
try:
_annotate_current_span({"email.tls_mode": tls_mode})
if self.config.USERNAME and self.config.PASSWORD:
if tls_mode == "none":
logger.warning("Logging in to the SMTP server without TLS: credentials are sent in clear text")
session.login(self.config.USERNAME, self.config.PASSWORD)
except BaseException:
session.close()
Expand All @@ -198,7 +167,7 @@ def connect(self) -> None:
self.last_used = DatetimeUtils.get_datetime_now()
self.last_error = None
except (smtplib.SMTPException, OSError, TimeoutError) as e:
BaseUtils.capture_exception(e)
capture_exception(e)
self.smtp_connection = None
self.last_error = e

Expand All @@ -209,7 +178,7 @@ def disconnect(self) -> None:
self.smtp_connection.quit()
self.smtp_connection = None
except (smtplib.SMTPException, OSError, TimeoutError) as e:
BaseUtils.capture_exception(e)
capture_exception(e)
finally:
self.smtp_connection = None

Expand Down Expand Up @@ -574,15 +543,15 @@ def _send_email_traced(
additional_data={"reason": "invalid_header", "detail": str(e)},
) from e
except (smtplib.SMTPException, OSError, TimeoutError) as e:
BaseUtils.capture_exception(e)
capture_exception(e)
last_error = e
connection.disconnect() # Close the broken session; reconnect on next attempt
if isinstance(e, smtplib.SMTPResponseException) and e.smtp_code >= _PERMANENT_FAILURE_CODE:
break # Permanent rejection: a retry cannot succeed and could duplicate the message

raise UnavailableError(resource_type="SMTP") from last_error
except (smtplib.SMTPException, OSError, TimeoutError) as e:
BaseUtils.capture_exception(e)
capture_exception(e)
raise UnavailableError(resource_type="SMTP") from e
finally:
if connection:
Expand Down
2 changes: 0 additions & 2 deletions archipy/configs/config_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@
_extract_postgres_host_port_from_url, # noqa: F401
)
from archipy.configs.sections.temporal import (
TLS_CERT_PARTS_REQUIRED,
TemporalConfig,
)
from archipy.configs.sections.uvicorn import UvicornConfig
Expand All @@ -74,7 +73,6 @@
)

__all__ = [
"TLS_CERT_PARTS_REQUIRED",
"AuthConfig",
"DatetimeConfig",
"ElasticsearchConfig",
Expand Down
51 changes: 0 additions & 51 deletions archipy/configs/sections/_common.py

This file was deleted.

Loading
Loading