"""Tests for weak credential guard in gateway/config.py.""" import os import pytest from gateway.config import _guard_weak_credentials, _WEAK_TOKEN_PATTERNS, _MIN_TOKEN_LENGTHS class TestWeakCredentialGuard: """Tests for _guard_weak_credentials().""" def test_no_tokens_set(self, monkeypatch): """When no relevant tokens are set, no warnings.""" for var in _MIN_TOKEN_LENGTHS: monkeypatch.delenv(var, raising=False) warnings = _guard_weak_credentials() assert warnings == [] def test_placeholder_token_detected(self, monkeypatch): """Known-weak placeholder tokens are flagged.""" monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "your-token-here") warnings = _guard_weak_credentials() assert len(warnings) == 1 assert "TELEGRAM_BOT_TOKEN" in warnings[0] assert "placeholder" in warnings[0].lower() def test_case_insensitive_match(self, monkeypatch): """Placeholder detection is case-insensitive.""" monkeypatch.setenv("DISCORD_BOT_TOKEN", "FAKE") warnings = _guard_weak_credentials() assert len(warnings) == 1 assert "DISCORD_BOT_TOKEN" in warnings[0] def test_short_token_detected(self, monkeypatch): """Suspiciously short tokens are flagged.""" monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "abc123") # 6 chars, min is 30 warnings = _guard_weak_credentials() assert len(warnings) == 1 assert "short" in warnings[0].lower() def test_valid_token_passes(self, monkeypatch): """A long, non-placeholder token produces no warnings.""" monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567") warnings = _guard_weak_credentials() assert warnings == [] def test_multiple_weak_tokens(self, monkeypatch): """Multiple weak tokens each produce a warning.""" monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "change-me") monkeypatch.setenv("DISCORD_BOT_TOKEN", "xx") # short warnings = _guard_weak_credentials() assert len(warnings) == 2