Skip to content

Inconsistent env validation: invalid MT5API_PORT silently ignored, MT5API_LOG_LEVEL=trace crashes at import #48

Description

@dceoy

Problem

Environment configuration is validated inconsistently: an invalid MT5API_PORT is silently ignored (server binds to a different port than the operator asked for), while MT5API_LOG_LEVEL values that uvicorn itself accepts (e.g. trace) crash the app at import time with a raw traceback.

Evidence

  • mt5api/__main__.py:30-48 (_get_port): a non-integer (MT5API_PORT=80O0) or out-of-range (0, 70000) value falls back to 8000 without any warning or error. Contrast with MT5API_ROUTER_PREFIX and MT5API_MAX_MARKET_BOOK_SUBSCRIPTIONS, which raise ValueError on invalid input (mt5api/config.py:47-48,105-111) — same config surface, opposite behavior.

  • mt5api/main.py:66-76,130 (_configure_logging, run at module import): root_logger.setLevel(get_configured_api_log_level().upper()) passes the raw env string to logging. Verified locally:

    • uvicorn.config.LOG_LEVELS = ['critical', 'error', 'warning', 'info', 'debug', 'trace'] — so _get_log_level() in __main__.py happily hands trace to uvicorn.run(...);
    • logging.getLogger().setLevel('TRACE')ValueError: Unknown level: 'TRACE'.

    So MT5API_PORT typos are hidden, but MT5API_LOG_LEVEL=trace (a value uvicorn documents) makes the worker die while importing mt5api.main:app, after uvicorn has already started. Any other typo (MT5API_LOG_LEVEL=verbose) fails the same way, with an unhelpful traceback instead of a clear config error.

Impact

  • An operator who fat-fingers MT5API_PORT gets a server silently listening on 8000 — health checks/firewall rules pointing at the intended port fail, or worse, the API is exposed on an unintended port.
  • MT5API_LOG_LEVEL=trace (or any typo) prevents startup with a stack trace that doesn't name the offending variable.

Suggested fix

Validate both values explicitly and fail fast with actionable messages, mirroring the existing pattern in mt5api/config.py:

  • Move port parsing into config.py (e.g. get_configured_api_port() -> int) and raise ValueError("Invalid MT5API_PORT") on non-integer/out-of-range values instead of silently defaulting.
  • Validate MT5API_LOG_LEVEL against an allowlist; either map traceDEBUG for the app logger (keeping uvicorn's trace support) or reject it consistently in both places, with a clear error naming the variable.

Validation

  • Unit tests: invalid MT5API_PORT raises (or at minimum logs a warning and is covered by a test), MT5API_LOG_LEVEL=trace either starts cleanly or is rejected with the named-variable message.
  • uv run pytest keeps 100% coverage; manual smoke: MT5API_LOG_LEVEL=trace uv run python -m mt5api must not traceback.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions