Skip to content
Open
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@

## [Unreleased]

### Added

- Настраиваемые `ssl_context` и `aiohttp` connector для проверки доверенного CA
в исходящих API-запросах и прямого HTTPS webhook-сервера

## [1.1.0] - 2026-03-25

### Fixed
Expand Down
34 changes: 33 additions & 1 deletion docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,14 +254,46 @@ manager = WebhookManager(
)

import asyncio
asyncio.run(manager.start())
asyncio.run(manager.start("https://example.com/webhook"))
```

`WebhookManager` автоматически:
- Подписывает webhook при старте
- Переподписывается каждые 7.5 часов (Max отписывает через 8ч)
- Отписывается и останавливает сервер при shutdown

MAX принимает webhook только по внешнему HTTPS URL на публичном порту 443.
Обычная production-схема — оставить встроенный aiohttp-сервер на внутреннем
порту 8080 и проксировать к нему запросы через Nginx или Caddy, которые
завершают TLS. Сертификат должен быть доверенным MAX, включая сертификат
Минцифры при использовании соответствующей инфраструктуры.

Если TLS должен завершаться непосредственно в aiohttp, передайте серверный
`SSLContext` и сертификат с закрытым ключом:

```python
import ssl

server_ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
server_ssl_context.load_cert_chain(
"/etc/ssl/webhook/fullchain.pem",
"/etc/ssl/webhook/private.key",
)

manager = WebhookManager(
dispatcher=dp,
bot=bot,
host="0.0.0.0",
port=443,
ssl_context=server_ssl_context,
)
asyncio.run(manager.start("https://example.com/webhook"))
```

Для защиты от поддельных запросов рекомендуется включать `secret` в подписке
webhook. `polling`/Long Polling используйте для разработки и тестирования, а в
production — Webhook.

Для защиты от поддельных запросов используйте `IPWhitelistMiddleware`:

```python
Expand Down
320 changes: 320 additions & 0 deletions docs/superpowers/plans/2026-09-11-max-ssl-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,320 @@
# MAX TLS Configuration Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Expose safe custom TLS configuration for outbound MAX API requests and the optional embedded HTTPS webhook listener.

**Architecture:** Keep `AiohttpSession` as the owner of the lazy `ClientSession`. A supplied connector is forwarded unchanged; a supplied SSL context is converted to a `TCPConnector` only when the first request creates the client session. Keep `WebhookManager` compatible with reverse-proxy deployments by passing an optional SSL context directly to `web.TCPSite` and leaving the default listener as HTTP.

**Tech Stack:** Python 3.11+, aiohttp 3.9–3.x, asyncio, `ssl.SSLContext`, pytest, pytest-asyncio.

---

### Task 1: Add outbound SSL and connector configuration

**Files:**
- Modify: `src/maxogram/client/session/aiohttp.py`
- Test: `tests/test_session_aiohttp.py`

- [ ] **Step 1: Write failing tests for client configuration.**

Add a test class near the session-close tests. It must verify that the public
constructor rejects ambiguous configuration, that a supplied connector reaches
`ClientSession`, and that an SSL context is converted to a connector with that
same context:

```python
import ssl


class TestSessionTLSConfiguration:
def test_connector_and_ssl_context_are_mutually_exclusive(self) -> None:
connector = MagicMock()
context = ssl.create_default_context()

with pytest.raises(ValueError, match="connector.*ssl_context"):
AiohttpSession(connector=connector, ssl_context=context)

@pytest.mark.asyncio
async def test_custom_connector_is_forwarded_to_client_session(self) -> None:
connector = MagicMock()
session = AiohttpSession(connector=connector)
client_session = MagicMock()

with patch("aiohttp.ClientSession", return_value=client_session) as factory:
assert await session._get_session() is client_session

factory.assert_called_once_with(
json_serialize=session._json_dumps,
connector=connector,
)

@pytest.mark.asyncio
async def test_ssl_context_creates_tcp_connector(self) -> None:
context = ssl.create_default_context()
session = AiohttpSession(ssl_context=context)
client_session = MagicMock()

with (
patch("aiohttp.TCPConnector") as connector_factory,
patch("aiohttp.ClientSession", return_value=client_session) as session_factory,
):
connector = connector_factory.return_value
assert await session._get_session() is client_session

connector_factory.assert_called_once_with(ssl=context)
session_factory.assert_called_once_with(
json_serialize=session._json_dumps,
connector=connector,
)
```

- [ ] **Step 2: Run the focused tests and verify the expected RED state.**

Run:

```bash
poetry run pytest -q tests/test_session_aiohttp.py -k TLSConfiguration
```

Expected: collection succeeds and the new tests fail because the constructor
does not yet accept the new options.

- [ ] **Step 3: Implement the minimal client configuration.**

Import `ssl`, add keyword-only `connector` and `ssl_context` parameters after
`max_retries`, reject both when present, store them, and build the connector in
`_get_session`:

```python
def __init__(
self,
proxy: str | None = None,
max_retries: int = 3,
*,
connector: aiohttp.BaseConnector | None = None,
ssl_context: ssl.SSLContext | None = None,
**kwargs: Any,
) -> None:
if connector is not None and ssl_context is not None:
raise ValueError("connector and ssl_context are mutually exclusive")
super().__init__(**kwargs)
self._proxy = proxy
self._max_retries = max_retries
self._connector = connector
self._ssl_context = ssl_context
self._session: aiohttp.ClientSession | None = None

async def _get_session(self) -> aiohttp.ClientSession:
if self._session is None or self._session.closed:
connector = self._connector
if connector is None and self._ssl_context is not None:
connector = aiohttp.TCPConnector(ssl=self._ssl_context)
self._session = aiohttp.ClientSession(
json_serialize=self._json_dumps,
connector=connector,
)
return self._session
```

The `ssl` argument must receive the context; do not use `ssl=False` or alter
aiohttp verification defaults.

- [ ] **Step 4: Run focused and existing session tests.**

Run:

```bash
poetry run pytest -q tests/test_session_aiohttp.py tests/test_client/test_session/test_aiohttp.py
```

Expected: all session tests pass.

- [ ] **Step 5: Commit the client change.**

```bash
git add src/maxogram/client/session/aiohttp.py tests/test_session_aiohttp.py
git commit -m "feat: configure aiohttp TLS for API sessions"
```

### Task 2: Add optional HTTPS to WebhookManager

**Files:**
- Modify: `src/maxogram/webhook/manager.py`
- Test: `tests/test_webhook/test_manager.py`

- [ ] **Step 1: Write failing tests for server SSL forwarding.**

Extend `TestWebhookManagerInit` with storage coverage and add a lifecycle test
that inspects the `TCPSite` constructor:

```python
import ssl


def test_stores_ssl_context(self, dispatcher: MagicMock, bot: AsyncMock) -> None:
from maxogram.webhook.manager import WebhookManager

context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
manager = WebhookManager(dispatcher=dispatcher, bot=bot, ssl_context=context)

assert manager._ssl_context is context


@pytest.mark.asyncio
async def test_setup_passes_ssl_context_to_tcp_site(
self, dispatcher: MagicMock, bot: AsyncMock
) -> None:
from maxogram.webhook.manager import WebhookManager

context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
manager = WebhookManager(
dispatcher=dispatcher,
bot=bot,
ssl_context=context,
resubscribe_interval=100.0,
)

with patch("aiohttp.web.AppRunner") as runner_cls:
runner = AsyncMock()
runner_cls.return_value = runner
with patch("aiohttp.web.TCPSite") as site_cls:
site = AsyncMock()
site_cls.return_value = site

await manager._setup("https://example.com/webhook")
await manager._shutdown()

site_cls.assert_called_once_with(runner, "0.0.0.0", 8080, ssl_context=context)
```

- [ ] **Step 2: Run the focused tests and verify RED.**

Run:

```bash
poetry run pytest -q tests/test_webhook/test_manager.py -k "ssl_context"
```

Expected: the constructor and `TCPSite` assertion fail because the manager has
no SSL option yet.

- [ ] **Step 3: Implement optional server TLS.**

Import `ssl`, add keyword-only `ssl_context: ssl.SSLContext | None = None`,
store it, and pass it to `web.TCPSite`:

```python
self._ssl_context = ssl_context
site = web.TCPSite(
self._runner,
self._host,
self._port,
ssl_context=self._ssl_context,
)
```

Keep `ssl_context=None` as the default so Nginx/Caddy can terminate TLS and
forward to the internal HTTP listener. Update the startup log scheme to
`https` when a context is configured and `http` otherwise.

- [ ] **Step 4: Run manager tests.**

Run:

```bash
poetry run pytest -q tests/test_webhook/test_manager.py
```

Expected: all manager tests pass.

- [ ] **Step 5: Commit the manager change.**

```bash
git add src/maxogram/webhook/manager.py tests/test_webhook/test_manager.py
git commit -m "feat: support HTTPS webhook listener"
```

### Task 3: Document safe TLS deployment

**Files:**
- Modify: `docs/quickstart.md`
- Modify: `src/maxogram/client/README.md`
- Modify: `src/maxogram/webhook/README.md`
- Modify: `CHANGELOG.md`

- [ ] **Step 1: Document outbound trusted-CA configuration.**

Show `ssl.create_default_context(cafile=...)` passed to
`AiohttpSession(ssl_context=...)`, explain the alternative preconfigured
`aiohttp.TCPConnector`, and explicitly state that verification must remain
enabled. Mention that `connector` and `ssl_context` cannot be supplied
together.

- [ ] **Step 2: Document direct and reverse-proxy webhook TLS.**

Add a direct listener example using a server SSL context and
`load_cert_chain()`. Explain that MAX requires the external webhook URL to be
HTTPS on public port 443, while the embedded listener can remain on 8080 behind
Nginx/Caddy. State that a trusted certificate chain is required and that
disabling TLS verification is unsupported.

- [ ] **Step 3: Run documentation consistency checks.**

Run:

```bash
rg -n "ssl_context|TCPConnector|port 443|8080|verification" docs/quickstart.md src/maxogram/client/README.md src/maxogram/webhook/README.md CHANGELOG.md
```

Expected: both client and server configuration paths are present and no example
uses an unverified SSL context.

- [ ] **Step 4: Commit the documentation.**

```bash
git add docs/quickstart.md src/maxogram/client/README.md src/maxogram/webhook/README.md CHANGELOG.md
git commit -m "docs: explain MAX TLS configuration"
```

### Task 4: Full verification and handoff

**Files:**
- Verify: all changed files and the complete test suite

- [ ] **Step 1: Run the complete test suite.**

Run:

```bash
poetry run pytest -q
```

Expected: the full suite passes with zero failures.

- [ ] **Step 2: Run static checks.**

Run:

```bash
poetry run ruff check src tests
poetry run ruff format --check src tests
poetry run mypy src
git diff main...HEAD --check
```

Expected: ruff, formatting, mypy, and whitespace checks exit with status 0.

- [ ] **Step 3: Review the final diff and branch state.**

Run:

```bash
git status --short --branch
git diff --stat main...HEAD
git log --oneline --decorate --max-count=8
```

Confirm that only TLS configuration, tests, documentation, and the committed
design/plan are present, with no credentials, insecure TLS flags, or unrelated
changes.
Loading