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
5 changes: 4 additions & 1 deletion app/api/routes/v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
20 changes: 13 additions & 7 deletions app/bot/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"<code>{escape(raw_key)}</code>\n\n"
"📡 <b>Supported platforms:</b>\n"
"• Telegram\n"
"• Slack\n"
"• Discord\n"
"• Custom Webhooks\n\n"
f"⚙️ Configure them here: "
f'<a href="{escape(link, quote=True)}">Setup</a>\n\n'
"🚀 <b>Send notifications:</b>\n"
f"• Endpoint: <code>{{base}}/api/v1/notify</code>\n"
"• Header: <code>X-API-Key</code>"
)
4 changes: 2 additions & 2 deletions app/bot/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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__":
Expand Down
3 changes: 3 additions & 0 deletions app/channels/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import httpx

from app.channels.base import SendResult
from app.core.security import is_ssrf_safe_url


class WebhookAdapter:
Expand All @@ -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:
Expand Down
8 changes: 8 additions & 0 deletions app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand Down
21 changes: 16 additions & 5 deletions app/core/rate_limit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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))
Expand Down
37 changes: 30 additions & 7 deletions app/core/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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")
Expand Down
6 changes: 3 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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
Expand Down
8 changes: 4 additions & 4 deletions tests/test_bot_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ async def _run() -> str:

text = anyio.run(_run)
assert "Your new API key" in text
assert "`rn_" in text
assert "<code>rn_" in text
assert "rapid.example/api/channels/entry/" in text

async def _check() -> m.User | None:
Expand All @@ -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"<code>rn_[^<]+</code>", text)) == 1


def test_subscribe_again_rotates_key(tmp_path) -> None:
Expand All @@ -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"<code>(rn_[^<]+)</code>", first).group(1)
raw_second = re.search(r"<code>(rn_[^<]+)</code>", second).group(1)
assert raw_first != raw_second

async def _count() -> int:
Expand Down
8 changes: 8 additions & 0 deletions tests/test_core_security.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions tests/test_rate_limit_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading