diff --git a/app/api/routes/v1.py b/app/api/routes/v1.py index e3ccbd6..7b0f5e1 100644 --- a/app/api/routes/v1.py +++ b/app/api/routes/v1.py @@ -87,7 +87,10 @@ async def notify( ) try: - await check_and_record(session, user.api_key_hash) + limit, window_seconds = settings.rate_limit_for(user.rate_limit_tier) + await check_and_record( + session, user.api_key_hash, limit=limit, window_seconds=window_seconds + ) except RateLimitExceeded as exc: raise HTTPException( status_code=status.HTTP_429_TOO_MANY_REQUESTS, diff --git a/app/bot/handlers.py b/app/bot/handlers.py index f2fc754..ca98a38 100644 --- a/app/bot/handlers.py +++ b/app/bot/handlers.py @@ -4,13 +4,13 @@ wiring lives in bot/main.py. """ +from html import escape from typing import Any import structlog from sqlalchemy import select from app.api.pages import issue_registration_token -from app.channels.registry import supported_channels from app.core.config import Settings from app.core.security import generate_api_key, hash_key from app.db import models as m @@ -70,10 +70,16 @@ async def subscribe(session: Any, settings: Settings, telegram_user_id: int) -> link = f"{settings.public_base_url.rstrip('/')}" f"/api/channels/entry/{token_raw}" intro = "🔑 Your new API key" if created else "🔑 Your API key (rotated)" return ( - f"{intro} — shown only once:\n\n" - f"`{raw_key}`\n\n" - "Register Slack, Discord or webhook channels here:\n" - f"{link}\n\n" - f"Then POST to {{base}}/api/v1/notify with X-API-Key header. " - f"Channels supported: {', '.join(supported_channels())}." + f"{intro} — save it securely; it's shown only once:\n\n" + f"{escape(raw_key)}\n\n" + "📡 Supported platforms:\n" + "• Telegram\n" + "• Slack\n" + "• Discord\n" + "• Custom Webhooks\n\n" + f"⚙️ Configure them here: " + f'Setup\n\n' + "🚀 Send notifications:\n" + f"• Endpoint: {{base}}/api/v1/notify\n" + "• Header: X-API-Key" ) diff --git a/app/bot/main.py b/app/bot/main.py index 3da26d5..db307b5 100644 --- a/app/bot/main.py +++ b/app/bot/main.py @@ -32,7 +32,7 @@ async def _cmd_subscribe(update: Update, context: ContextTypes.DEFAULT_TYPE) -> async with SessionLocal() as session: text = await subscribe(session, settings, telegram_user_id) await session.commit() - await _msg(update).reply_text(text, parse_mode=ParseMode.MARKDOWN) + await _msg(update).reply_text(text, parse_mode=ParseMode.HTML) def create_application() -> Application: @@ -46,7 +46,7 @@ def create_application() -> Application: def main() -> None: log.info("starting bot, long polling") - create_application().run_polling() + create_application().run_polling(bootstrap_retries=-1) if __name__ == "__main__": diff --git a/app/channels/webhook.py b/app/channels/webhook.py index e62fab2..d25573c 100644 --- a/app/channels/webhook.py +++ b/app/channels/webhook.py @@ -9,6 +9,7 @@ import httpx from app.channels.base import SendResult +from app.core.security import is_ssrf_safe_url class WebhookAdapter: @@ -30,6 +31,8 @@ async def send( target = str(config.get("url", "")) if not target: return SendResult(ok=False, detail="missing url") + if not is_ssrf_safe_url(target, allow_http=True): + return SendResult(ok=False, detail="blocked: unsafe url") payload = self.build_payload(config, user_id, message) try: if client is None: diff --git a/app/core/config.py b/app/core/config.py index 6c5bd92..b69b11c 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -21,6 +21,8 @@ class Settings(BaseSettings): rate_limit_window_seconds: int = 60 max_payload_bytes: int = 8192 + rate_limit_tiers: dict[str, tuple[int, int]] = {"standard": (60, 60)} + log_level: str = "INFO" # External base URL used in bot messages (channel page link) @@ -29,6 +31,12 @@ class Settings(BaseSettings): def rate_limit_tuples(self) -> tuple[int, int]: return self.rate_limit_requests, self.rate_limit_window_seconds + def rate_limit_for(self, tier: str) -> tuple[int, int]: + limits = self.rate_limit_tiers + if tier in limits: + return limits[tier] + return self.rate_limit_tuples() + @lru_cache def get_settings() -> Settings: diff --git a/app/core/rate_limit.py b/app/core/rate_limit.py index c8947e3..150428d 100644 --- a/app/core/rate_limit.py +++ b/app/core/rate_limit.py @@ -15,11 +15,22 @@ def __init__(self, retry_after: int) -> None: super().__init__(f"rate limit exceeded, retry in {retry_after}s") -async def check_and_record(session: AsyncSession, api_key_hash: str) -> None: +async def check_and_record( + session: AsyncSession, + api_key_hash: str, + limit: int | None = None, + window_seconds: int | None = None, +) -> None: """Count hits inside the window; raise if at the limit, else record one.""" settings = get_settings() - limit = settings.rate_limit_requests - window = timedelta(seconds=settings.rate_limit_window_seconds) + max_requests = limit if limit is not None else settings.rate_limit_requests + window = timedelta( + seconds=( + window_seconds + if window_seconds is not None + else settings.rate_limit_window_seconds + ) + ) now = utcnow() count = await session.scalar( @@ -28,8 +39,8 @@ async def check_and_record(session: AsyncSession, api_key_hash: str) -> None: .where(RateLimitHit.api_key_hash == api_key_hash) .where(RateLimitHit.ts > now - window) ) - if count is not None and count >= limit: - raise RateLimitExceeded(retry_after=settings.rate_limit_window_seconds) + if count is not None and count >= max_requests: + raise RateLimitExceeded(retry_after=int(window.total_seconds())) await session.execute( delete(RateLimitHit).where(RateLimitHit.ts < now - window - timedelta(days=7)) diff --git a/app/core/security.py b/app/core/security.py index 27f2b69..42a27e7 100644 --- a/app/core/security.py +++ b/app/core/security.py @@ -7,6 +7,7 @@ import hashlib import hmac import secrets +import socket from ipaddress import IPv4Address, IPv6Address, ip_address, ip_network from urllib.parse import urlparse @@ -48,23 +49,45 @@ def generate_registration_token() -> str: def is_private_ip(host: str) -> bool: """True when *host* is an IP literal in a private/restricted range. - Plain hostnames (not IP literals) return ``False``; DNS-rebinding - protections are documented — outbound sends never follow redirects. + Hostnames (not IP literals) are resolved before checking; unresolvable + hosts fail closed (treated as unsafe). """ try: addr: IPv4Address | IPv6Address = ip_address(host) except ValueError: - return False + return _hostname_resolves_private(host) return any(addr in net for net in _TRUSTED) +def _hostname_resolves_private(host: str) -> bool: + """Resolve *host* via DNS and report whether any address is private.""" + try: + infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP) + except (socket.gaierror, OSError): + return True # fail closed on unresolvable hosts + for info in infos: + sockaddr = info[4] + if isinstance(sockaddr, (tuple, list)): + ip_raw = sockaddr[0] + elif isinstance(sockaddr, (bytes, bytearray)): + ip_raw = bytes(sockaddr) + else: + ip_raw = sockaddr + try: + addr = ip_address(ip_raw) + except (ValueError, TypeError): + return True # fail closed on unparseable addresses + if is_private_ip(str(addr)): + return True + return False + + def is_ssrf_safe_url(url: str, allow_http: bool = False) -> bool: - """Validate an outbound webhook URL: scheme and host IP. + """Validate an outbound webhook URL: scheme and resolved host address. - scheme must be ``https`` (or ``http`` when *allow_http* is True) - - a host that is an IP literal must not be private/restricted - - hostname hosts are permitted; redirection is disabled in senders so a - user-supplied URL cannot be redirected into an internal address + - the host must not resolve to a private/restricted IP range + (IP literals and hostnames alike; unresolvable hosts fail closed) """ parsed = urlparse(url) allowed_schemes = ("https",) if not allow_http else ("http", "https") diff --git a/docker-compose.yml b/docker-compose.yml index 60a4650..deff5f8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -17,7 +17,7 @@ services: build: . command: alembic upgrade head environment: - DATABASE_URL: ${DATABASE_URL:-postgresql+asyncpg://rapid:rapid@postgres:5432/rapidnotify} + DATABASE_URL: ${COMPOSE_DATABASE_URL:-postgresql+asyncpg://rapid:rapid@postgres:5432/rapidnotify} KEY_PEPPER: ${KEY_PEPPER:?set KEY_PEPPER in .env} depends_on: postgres: @@ -31,7 +31,7 @@ services: - path: .env required: false environment: - DATABASE_URL: ${DATABASE_URL:-postgresql+asyncpg://rapid:rapid@postgres:5432/rapidnotify} + DATABASE_URL: ${COMPOSE_DATABASE_URL:-postgresql+asyncpg://rapid:rapid@postgres:5432/rapidnotify} depends_on: migrate: condition: service_completed_successfully @@ -45,7 +45,7 @@ services: - path: .env required: false environment: - DATABASE_URL: ${DATABASE_URL:-postgresql+asyncpg://rapid:rapid@postgres:5432/rapidnotify} + DATABASE_URL: ${COMPOSE_DATABASE_URL:-postgresql+asyncpg://rapid:rapid@postgres:5432/rapidnotify} depends_on: migrate: condition: service_completed_successfully diff --git a/tests/test_bot_handlers.py b/tests/test_bot_handlers.py index a3b83fd..a5de481 100644 --- a/tests/test_bot_handlers.py +++ b/tests/test_bot_handlers.py @@ -50,7 +50,7 @@ async def _run() -> str: text = anyio.run(_run) assert "Your new API key" in text - assert "`rn_" in text + assert "rn_" in text assert "rapid.example/api/channels/entry/" in text async def _check() -> m.User | None: @@ -63,7 +63,7 @@ async def _check() -> m.User | None: assert isinstance(user, m.User) assert len(user.api_key_hash) == 64 # exactly one key occurrence (shown once) - assert text.count("`rn_") == 1 + assert len(re.findall(r"rn_[^<]+", text)) == 1 def test_subscribe_again_rotates_key(tmp_path) -> None: @@ -78,8 +78,8 @@ async def _run(subscribe_id: int) -> str: first = anyio.run(_run, 888) second = anyio.run(_run, 888) assert "rotated" in second - raw_first = re.search(r"`(rn_[^`]+)`", first).group(1) - raw_second = re.search(r"`(rn_[^`]+)`", second).group(1) + raw_first = re.search(r"(rn_[^<]+)", first).group(1) + raw_second = re.search(r"(rn_[^<]+)", second).group(1) assert raw_first != raw_second async def _count() -> int: diff --git a/tests/test_core_security.py b/tests/test_core_security.py index eb3c9ad..afee99a 100644 --- a/tests/test_core_security.py +++ b/tests/test_core_security.py @@ -44,6 +44,14 @@ def test_ssrf_blocks_private_ip_literal_hosts() -> None: assert is_ssrf_safe_url("https://0.0.0.0/hook") is False +def test_ssrf_blocks_localhost_hostname_and_fails_closed_on_unresolvable() -> None: + # Hostname that resolves to loopback must be blocked now that hostnames + # are resolved (e.g. 127.0.0.1.nip.io style bypasses are closed by DNS check). + assert is_ssrf_safe_url("https://localhost/hook") is False + assert is_ssrf_safe_url("http://localhost:9000/hook", allow_http=True) is False + assert is_ssrf_safe_url("https://this-host-does-not-resolve.invalid/hook") is False + + def test_ssrf_allows_public_https_and_blocks_other_schemes() -> None: assert is_ssrf_safe_url("https://hooks.slack.com/services/a/b/c") is True assert is_ssrf_safe_url("https://8.8.8.8/hook") is True diff --git a/tests/test_rate_limit_unit.py b/tests/test_rate_limit_unit.py index ae13897..6fb9f4f 100644 --- a/tests/test_rate_limit_unit.py +++ b/tests/test_rate_limit_unit.py @@ -75,3 +75,22 @@ async def _run() -> int: def test_raise_is_exception_instance() -> None: assert isinstance(RateLimitExceeded(5), Exception) assert RateLimitExceeded(5).retry_after == 5 + + +def test_rate_limit_for_tier_falls_back_to_global_defaults() -> None: + s = get_settings() + assert s.rate_limit_for("standard") == ( + s.rate_limit_requests, + s.rate_limit_window_seconds, + ) + assert s.rate_limit_for("unknown-tier") == ( + s.rate_limit_requests, + s.rate_limit_window_seconds, + ) + + +def test_rate_limit_for_custom_tier_returns_tier_limits() -> None: + from app.core.config import Settings + + s = Settings(_env_file=None, rate_limit_tiers={"tight": (2, 60)}) + assert s.rate_limit_for("tight") == (2, 60)