Compare commits
3 Commits
v3.4.0
...
86e631926f
| Author | SHA1 | Date | |
|---|---|---|---|
| 86e631926f | |||
| 4166520923 | |||
| d0819c2683 |
+21
-8
@@ -20,13 +20,6 @@ The bot now supports real-time video game information through IGDB (Internet Gam
|
||||
- **Category**: Select appropriate category
|
||||
3. Note down your **Client ID**
|
||||
4. Generate a **Client Secret**
|
||||
5. Get an access token using this curl command:
|
||||
```bash
|
||||
curl -X POST 'https://id.twitch.tv/oauth2/token' \
|
||||
-H 'Content-Type: application/x-www-form-urlencoded' \
|
||||
-d 'client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=client_credentials'
|
||||
```
|
||||
6. Save the `access_token` from the response
|
||||
|
||||
### 2. Configure the Bot
|
||||
|
||||
@@ -35,6 +28,25 @@ Update your `config.toml` file:
|
||||
```toml
|
||||
# IGDB Configuration for game information
|
||||
igdb-client-id = "your_actual_client_id_here"
|
||||
igdb-client-secret = "your_actual_client_secret_here"
|
||||
enable-game-info = true
|
||||
```
|
||||
|
||||
With the client secret configured, the bot fetches an app access token from
|
||||
Twitch itself and refreshes it automatically before it expires (Twitch app
|
||||
tokens live ~60 days) — no manual token handling needed.
|
||||
|
||||
Alternatively, a static token still works (legacy setup — it expires after
|
||||
~60 days and then game lookups fail with 401 until you replace it):
|
||||
|
||||
```bash
|
||||
curl -X POST 'https://id.twitch.tv/oauth2/token' \
|
||||
-H 'Content-Type: application/x-www-form-urlencoded' \
|
||||
-d 'client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=client_credentials'
|
||||
```
|
||||
|
||||
```toml
|
||||
igdb-client-id = "your_actual_client_id_here"
|
||||
igdb-access-token = "your_actual_access_token_here"
|
||||
enable-game-info = true
|
||||
```
|
||||
@@ -99,7 +111,8 @@ The integration provides two OpenAI functions:
|
||||
- Verify client ID and access token are set
|
||||
|
||||
2. **Authentication errors**
|
||||
- Regenerate access token (they expire)
|
||||
- Prefer `igdb-client-secret` — the bot then refreshes tokens itself
|
||||
- With a static `igdb-access-token`: regenerate it (they expire)
|
||||
- Verify client ID matches your Twitch app
|
||||
|
||||
3. **No game results**
|
||||
|
||||
@@ -83,3 +83,6 @@ ci: install-dev all-checks ## Full CI pipeline (install deps and run all checks)
|
||||
# Deploy targets (SPEC-007)
|
||||
deploy: ## Deploy a tag to a host: make deploy HOST=ggg TAG=v3.0.0
|
||||
bash deploy/deploy.sh $(HOST) $(TAG)
|
||||
|
||||
backup: ## Back up a local bot.db: make backup DB=history/bot.db DIR=backups
|
||||
uv run python deploy/backup_db.py $(DB) $(DIR) $(or $(KEEP),14)
|
||||
|
||||
+14
-1
@@ -14,7 +14,11 @@ system = "You are a smart AI assistant with access to real-time video game infor
|
||||
|
||||
# IGDB Configuration for game information
|
||||
igdb-client-id = "YOUR_IGDB_CLIENT_ID"
|
||||
igdb-access-token = "YOUR_IGDB_ACCESS_TOKEN"
|
||||
# With the Twitch app client secret set, the bot fetches and refreshes the
|
||||
# access token itself (recommended). A static igdb-access-token still works
|
||||
# but expires after ~60 days.
|
||||
igdb-client-secret = "YOUR_IGDB_CLIENT_SECRET"
|
||||
# igdb-access-token = "YOUR_IGDB_ACCESS_TOKEN"
|
||||
enable-game-info = true
|
||||
|
||||
# --- operator / safety (SPEC-003, SPEC-006) ---
|
||||
@@ -67,3 +71,12 @@ enable-game-info = true
|
||||
# idle-impulse-hours = 12
|
||||
# taskgen-interval-hours = 6
|
||||
# Staff: !bot tasks | task-approve <id> | task-cancel <id>
|
||||
# URL reading (SPEC-011, FDB-018) — DEFAULT OFF; web pages are hostile input:
|
||||
# enable-url-reading = true
|
||||
# url-max-bytes = 2097152 # 2 MB fetch cap
|
||||
# url-max-chars = 6000 # text handed to the model
|
||||
# url-max-images = 2 # page images into the vision cache
|
||||
# url-daily-per-user = 20
|
||||
# Ops (SPEC-012): consecutive OpenAI failures before a staff alert
|
||||
# api-error-alert-threshold = 5
|
||||
# Backups: cron runs deploy/backup_db.py daily -> ~/backups/<bot>/ (keep 14)
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Consistent, rotated bot.db backups (SPEC-012 OPS-13).
|
||||
|
||||
Run from cron on each host. Uses the sqlite3 online-backup API so the
|
||||
snapshot is consistent even while the bot writes (WAL-safe), gzips it,
|
||||
and keeps the newest N. Stdlib only.
|
||||
|
||||
Usage: python3 backup_db.py <bot.db> <backup-dir> [keep]
|
||||
"""
|
||||
|
||||
import gzip
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_KEEP = 14
|
||||
BACKUP_GLOB = "bot-*.db.gz"
|
||||
|
||||
|
||||
def snapshot(src: Path, dest_gz: Path) -> None:
|
||||
"""Write a consistent gzipped snapshot of src to dest_gz (OPS-13)."""
|
||||
fd, tmp_path = tempfile.mkstemp(suffix=".db", dir=str(dest_gz.parent))
|
||||
os.close(fd)
|
||||
tmp = Path(tmp_path)
|
||||
try:
|
||||
source = sqlite3.connect(str(src))
|
||||
try:
|
||||
target = sqlite3.connect(str(tmp))
|
||||
try:
|
||||
source.backup(target) # atomic, WAL-safe online backup
|
||||
finally:
|
||||
target.close()
|
||||
finally:
|
||||
source.close()
|
||||
with open(tmp, "rb") as raw, gzip.open(str(dest_gz), "wb") as gz:
|
||||
shutil.copyfileobj(raw, gz)
|
||||
os.chmod(dest_gz, 0o600) # conversation data
|
||||
finally:
|
||||
tmp.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def victims(existing: list, keep: int) -> list:
|
||||
"""Given backup paths (any order), return the ones to delete, oldest first (OPS-14)."""
|
||||
ordered = sorted(existing) # timestamped names sort chronologically
|
||||
return ordered[: max(0, len(ordered) - keep)]
|
||||
|
||||
|
||||
def rotate(backup_dir: Path, keep: int) -> int:
|
||||
removed = 0
|
||||
for path in victims(list(backup_dir.glob(BACKUP_GLOB)), keep):
|
||||
Path(path).unlink(missing_ok=True)
|
||||
removed += 1
|
||||
return removed
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) < 3:
|
||||
print("usage: backup_db.py <bot.db> <backup-dir> [keep]", file=sys.stderr)
|
||||
return 2
|
||||
src = Path(sys.argv[1]).expanduser()
|
||||
backup_dir = Path(sys.argv[2]).expanduser()
|
||||
keep = int(sys.argv[3]) if len(sys.argv) > 3 else DEFAULT_KEEP
|
||||
if not src.exists():
|
||||
print(f"backup: source {src} missing", file=sys.stderr)
|
||||
return 1
|
||||
backup_dir.mkdir(parents=True, exist_ok=True)
|
||||
stamp = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
|
||||
dest = backup_dir / f"bot-{stamp}.db.gz"
|
||||
snapshot(src, dest)
|
||||
removed = rotate(backup_dir, keep)
|
||||
print(f"backup: wrote {dest.name} ({dest.stat().st_size} bytes), rotated {removed} old")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -89,6 +89,7 @@ class FjerkroaBot(commands.Bot):
|
||||
self.tasks_enabled = True
|
||||
self.quiet_until = 0.0
|
||||
self._staff_alert_times: deque = deque()
|
||||
self._consecutive_api_errors = 0 # OPS-16
|
||||
|
||||
self.init_observer()
|
||||
self.init_aichannels()
|
||||
@@ -498,6 +499,14 @@ class FjerkroaBot(commands.Bot):
|
||||
return True, False
|
||||
return False, bool(verdict.get("factual", False))
|
||||
|
||||
async def _note_api_error(self, err: Exception) -> None:
|
||||
"""Count consecutive failures; alert staff once at threshold (OPS-16)."""
|
||||
self._consecutive_api_errors += 1
|
||||
logging.warning(f"responder call failed ({self._consecutive_api_errors} in a row): {repr(err)}")
|
||||
threshold = int(self.config.get("api-error-alert-threshold", 5))
|
||||
if self._consecutive_api_errors == threshold:
|
||||
await self.send_staff_alert(f"⚠️ {threshold} consecutive API errors — the bot may be down. Last: {str(err)[:200]}")
|
||||
|
||||
async def send_message_with_typing(self, airesponder, channel, message):
|
||||
"""Send the user message to the AI responder with typing animation in discord"""
|
||||
async with channel.typing():
|
||||
@@ -603,8 +612,15 @@ class FjerkroaBot(commands.Bot):
|
||||
# Get the AI responder based on the channel name
|
||||
airesponder = self.get_ai_responder(channel_name)
|
||||
|
||||
# Send the user message to the AI responder, with typing indicators
|
||||
# Send the user message to the AI responder, with typing indicators.
|
||||
# A raised call = a broken API path (cf. the gpt-5.6 tools incident):
|
||||
# count it, alert staff at threshold, never crash the handler (OPS-16).
|
||||
try:
|
||||
response = await self.send_message_with_typing(airesponder, channel, message)
|
||||
except Exception as err:
|
||||
await self._note_api_error(err)
|
||||
return
|
||||
self._consecutive_api_errors = 0
|
||||
|
||||
# SAF/OPS gates between model proposal and delivery
|
||||
await self._apply_response_gates(message, response)
|
||||
|
||||
+38
-5
@@ -1,27 +1,60 @@
|
||||
import logging
|
||||
import time
|
||||
from functools import cache
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import requests
|
||||
|
||||
TWITCH_OAUTH_URL = "https://id.twitch.tv/oauth2/token"
|
||||
# Refresh this long before Twitch expires the token (app tokens live ~60 days)
|
||||
TOKEN_REFRESH_MARGIN = 86400
|
||||
|
||||
|
||||
class IGDBQuery(object):
|
||||
def __init__(self, client_id, igdb_api_key):
|
||||
def __init__(self, client_id, igdb_api_key=None, client_secret=None):
|
||||
self.client_id = client_id
|
||||
self.igdb_api_key = igdb_api_key
|
||||
self.client_secret = client_secret
|
||||
# Unknown for statically configured tokens; set after each refresh
|
||||
self._token_expires_at = None
|
||||
|
||||
def _refresh_token(self):
|
||||
response = requests.post(
|
||||
TWITCH_OAUTH_URL,
|
||||
params={"client_id": self.client_id, "client_secret": self.client_secret, "grant_type": "client_credentials"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
self.igdb_api_key = data["access_token"]
|
||||
self._token_expires_at = time.time() + data.get("expires_in", 0) - TOKEN_REFRESH_MARGIN
|
||||
logging.info("IGDB: refreshed Twitch app access token")
|
||||
|
||||
def _ensure_token(self):
|
||||
if not self.client_secret:
|
||||
return
|
||||
if not self.igdb_api_key or (self._token_expires_at is not None and time.time() >= self._token_expires_at):
|
||||
self._refresh_token()
|
||||
|
||||
def send_igdb_request(self, endpoint, query_body):
|
||||
igdb_url = f"https://api.igdb.com/v4/{endpoint}"
|
||||
headers = {"Client-ID": self.client_id, "Authorization": f"Bearer {self.igdb_api_key}"}
|
||||
|
||||
try:
|
||||
response = requests.post(igdb_url, headers=headers, data=query_body)
|
||||
self._ensure_token()
|
||||
response = self._post_igdb(igdb_url, query_body)
|
||||
if self.client_secret and response.status_code == 401:
|
||||
# Token expired server-side (e.g. statically configured) — refresh and retry once
|
||||
self._refresh_token()
|
||||
response = self._post_igdb(igdb_url, query_body)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
print(f"Error during IGDB API request: {e}")
|
||||
return None
|
||||
|
||||
def _post_igdb(self, igdb_url, query_body):
|
||||
headers = {"Client-ID": self.client_id, "Authorization": f"Bearer {self.igdb_api_key}"}
|
||||
return requests.post(igdb_url, headers=headers, data=query_body)
|
||||
|
||||
@staticmethod
|
||||
def build_query(fields, filters=None, limit=10, offset=None):
|
||||
query = f"fields {','.join(fields) if fields is not None and len(fields) > 0 else '*'}; limit {limit};"
|
||||
@@ -79,7 +112,7 @@ class IGDBQuery(object):
|
||||
"id",
|
||||
"name",
|
||||
"alternative_names",
|
||||
"category",
|
||||
"game_type",
|
||||
"release_dates",
|
||||
"franchise",
|
||||
"language_supports",
|
||||
@@ -120,7 +153,7 @@ class IGDBQuery(object):
|
||||
"themes.name",
|
||||
"cover.url",
|
||||
],
|
||||
additional_filters={"category": "= 0"}, # Main games only
|
||||
additional_filters={"game_type": "= 0"}, # Main games only (IGDB renamed category -> game_type)
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ from .ai_responder import AIResponder, exponential_backoff, sanitize_external_te
|
||||
from .igdblib import IGDBQuery
|
||||
from .leonardo_draw import LeonardoAIDrawMixIn
|
||||
from .quota import QuotaLedger
|
||||
from .url_reader import FETCH_URL_TOOL, URLReader
|
||||
|
||||
# The response envelope, enforced server-side via structured outputs
|
||||
# (ENV-19). All fields required, closed object, nullable where the
|
||||
@@ -136,16 +137,20 @@ class OpenAIResponder(AIResponder, LeonardoAIDrawMixIn):
|
||||
|
||||
# Initialize IGDB if enabled
|
||||
self.igdb = None
|
||||
igdb_client_id = self.config.get("igdb-client-id")
|
||||
igdb_client_secret = self.config.get("igdb-client-secret")
|
||||
igdb_access_token = self.config.get("igdb-access-token")
|
||||
logging.info("IGDB Configuration Check:")
|
||||
logging.info(f" enable-game-info: {self.config.get('enable-game-info', 'NOT SET')}")
|
||||
logging.info(f" igdb-client-id: {'SET' if self.config.get('igdb-client-id') else 'NOT SET'}")
|
||||
logging.info(f" igdb-access-token: {'SET' if self.config.get('igdb-access-token') else 'NOT SET'}")
|
||||
logging.info(f" igdb-client-id: {'SET' if igdb_client_id else 'NOT SET'}")
|
||||
logging.info(f" igdb-client-secret: {'SET' if igdb_client_secret else 'NOT SET'}")
|
||||
logging.info(f" igdb-access-token: {'SET' if igdb_access_token else 'NOT SET'}")
|
||||
|
||||
if self.config.get("enable-game-info", False) and self.config.get("igdb-client-id") and self.config.get("igdb-access-token"):
|
||||
if self.config.get("enable-game-info", False) and igdb_client_id and (igdb_client_secret or igdb_access_token):
|
||||
try:
|
||||
self.igdb = IGDBQuery(self.config["igdb-client-id"], self.config["igdb-access-token"])
|
||||
self.igdb = IGDBQuery(igdb_client_id, igdb_access_token, client_secret=igdb_client_secret)
|
||||
logging.info("✅ IGDB integration SUCCESSFULLY enabled for game information")
|
||||
logging.info(f" Client ID: {self.config['igdb-client-id'][:8]}...")
|
||||
logging.info(f" Client ID: {igdb_client_id[:8]}...")
|
||||
logging.info(f" Available functions: {len(self.igdb.get_openai_functions())}")
|
||||
except Exception as e:
|
||||
logging.error(f"❌ Failed to initialize IGDB: {e}")
|
||||
@@ -153,6 +158,33 @@ class OpenAIResponder(AIResponder, LeonardoAIDrawMixIn):
|
||||
else:
|
||||
logging.warning("❌ IGDB integration DISABLED - missing configuration or disabled in config")
|
||||
|
||||
# URL reading tool (SPEC-011); shares the image cache for page images
|
||||
self.url_reader = URLReader(lambda: self.config, self.image_cache)
|
||||
|
||||
def _available_tools(self) -> List[Dict[str, Any]]:
|
||||
"""Assemble the function-tool list from every enabled provider (URL-01)."""
|
||||
functions: List[Dict[str, Any]] = []
|
||||
if self.igdb and self.config.get("enable-game-info", False):
|
||||
try:
|
||||
igdb_functions = self.igdb.get_openai_functions()
|
||||
if isinstance(igdb_functions, list):
|
||||
functions.extend(igdb_functions)
|
||||
except (TypeError, AttributeError) as err:
|
||||
logging.warning(f"Error setting up IGDB functions: {err}")
|
||||
if self.url_reader.enabled():
|
||||
functions.append(FETCH_URL_TOOL)
|
||||
return functions
|
||||
|
||||
async def _dispatch_tool(self, name: str, args: Dict[str, Any], author: str) -> Any:
|
||||
"""Route a tool call to its provider (IGDB or URL reader)."""
|
||||
if name == "fetch_url":
|
||||
per_user_cap = int(self.config.get("url-daily-per-user", 20))
|
||||
if self.ledger._get(f"url-fetch:{author}") >= per_user_cap: # URL-07
|
||||
return {"error": "daily URL fetch limit reached"}
|
||||
self.ledger._add(f"url-fetch:{author}", 1)
|
||||
return await self.url_reader.fetch(str(args.get("url", "")), self.channel, author or "user")
|
||||
return await self._execute_igdb_function(name, args)
|
||||
|
||||
async def draw_openai(self, description: str, count: int = 1) -> List[BytesIO]:
|
||||
if not self.ledger.budget_ok():
|
||||
raise RuntimeError("daily budget exhausted - refusing image call")
|
||||
@@ -241,24 +273,13 @@ class OpenAIResponder(AIResponder, LeonardoAIDrawMixIn):
|
||||
# hashed, never the raw Discord name (SAF-10)
|
||||
chat_kwargs["safety_identifier"] = "discord-" + hashlib.sha256(author.encode()).hexdigest()[:16]
|
||||
|
||||
if self.igdb and self.config.get("enable-game-info", False):
|
||||
try:
|
||||
igdb_functions = self.igdb.get_openai_functions()
|
||||
if igdb_functions and isinstance(igdb_functions, list):
|
||||
chat_kwargs["tools"] = [{"type": "function", "function": func} for func in igdb_functions]
|
||||
available_tools = self._available_tools()
|
||||
if available_tools:
|
||||
chat_kwargs["tools"] = [{"type": "function", "function": func} for func in available_tools]
|
||||
chat_kwargs["tool_choice"] = "auto"
|
||||
# gpt-5.6 rejects tools + reasoning on chat/completions (ENV-21)
|
||||
chat_kwargs["reasoning_effort"] = self.config.get("reasoning-effort", "none")
|
||||
logging.info(f"🎮 IGDB functions available to AI: {[f['name'] for f in igdb_functions]}")
|
||||
logging.debug(f" Full chat_kwargs with tools: {list(chat_kwargs.keys())}")
|
||||
except (TypeError, AttributeError) as e:
|
||||
logging.warning(f"Error setting up IGDB functions: {e}")
|
||||
else:
|
||||
logging.debug(
|
||||
"🎮 IGDB not available for this request (igdb={}, enabled={})".format(
|
||||
self.igdb is not None, self.config.get("enable-game-info", False)
|
||||
)
|
||||
)
|
||||
logging.info(f"🔧 Tools available to AI: {[func['name'] for func in available_tools]}")
|
||||
|
||||
result = await openai_chat(self.client, **chat_kwargs)
|
||||
self._record_usage(result)
|
||||
@@ -278,10 +299,8 @@ class OpenAIResponder(AIResponder, LeonardoAIDrawMixIn):
|
||||
tool_names = [tc.function.name for tc in message.tool_calls]
|
||||
logging.info(f"🔧 OpenAI requested function calls: {tool_names}")
|
||||
|
||||
# Check if we have function/tool calls and IGDB is enabled
|
||||
has_tool_calls = (
|
||||
hasattr(message, "tool_calls") and message.tool_calls and self.igdb and self.config.get("enable-game-info", False)
|
||||
)
|
||||
# Any offered tool may have been called (IGDB or fetch_url)
|
||||
has_tool_calls = bool(hasattr(message, "tool_calls") and message.tool_calls and available_tools)
|
||||
|
||||
# Clean up any existing tool messages in the history to avoid conflicts
|
||||
if has_tool_calls:
|
||||
@@ -304,12 +323,12 @@ class OpenAIResponder(AIResponder, LeonardoAIDrawMixIn):
|
||||
function_name = tool_call.function.name
|
||||
function_args = json.loads(tool_call.function.arguments)
|
||||
|
||||
logging.info(f"🎮 Executing IGDB function: {function_name} with args: {function_args}")
|
||||
logging.info(f"🔧 Executing tool: {function_name} with args: {function_args}")
|
||||
|
||||
# Execute IGDB function
|
||||
function_result = await self._execute_igdb_function(function_name, function_args)
|
||||
# Route to the right provider (IGDB or URL reader)
|
||||
function_result = await self._dispatch_tool(function_name, function_args, self._last_author(messages) or "")
|
||||
|
||||
logging.info(f"🎮 IGDB function result: {type(function_result)} - {str(function_result)[:200]}...")
|
||||
logging.info(f"🔧 Tool result: {type(function_result)} - {str(function_result)[:200]}...")
|
||||
|
||||
messages.append(
|
||||
{
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
"""URL reading tool (SPEC-011, FDB-018).
|
||||
|
||||
The model calls `fetch_url`; this module fetches safely and returns
|
||||
readable text plus prominent image URLs. Web pages are hostile input:
|
||||
every fetch is SSRF-guarded (no private/loopback/link-local targets,
|
||||
http/https only, redirects re-validated) and every byte of text is
|
||||
sanitized before it can reach the prompt.
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
import logging
|
||||
import re
|
||||
import socket
|
||||
from html.parser import HTMLParser
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
from urllib.parse import urljoin, urlparse
|
||||
|
||||
import aiohttp
|
||||
|
||||
from .ai_responder import sanitize_external_text
|
||||
|
||||
DEFAULT_MAX_BYTES = 2 * 1024 * 1024
|
||||
DEFAULT_MAX_CHARS = 6000
|
||||
DEFAULT_MAX_IMAGES = 2
|
||||
FETCH_TIMEOUT_S = 15
|
||||
MAX_REDIRECTS = 5
|
||||
|
||||
FETCH_URL_TOOL = {
|
||||
"name": "fetch_url",
|
||||
"description": "Fetch a public web page and return its readable text plus prominent image links. "
|
||||
"Use when the user shares a URL and asks about it, or to get details behind a news link.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"url": {"type": "string", "description": "The http/https URL to read."}},
|
||||
"required": ["url"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class _Extractor(HTMLParser):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self._skip = 0
|
||||
self.parts: List[str] = []
|
||||
self.images: List[str] = []
|
||||
self.og_image: Optional[str] = None
|
||||
|
||||
def handle_starttag(self, tag: str, attrs) -> None:
|
||||
if tag in ("script", "style", "noscript", "svg"):
|
||||
self._skip += 1
|
||||
attr = dict(attrs)
|
||||
src = attr.get("src")
|
||||
if tag == "img" and src:
|
||||
self.images.append(src)
|
||||
if tag == "meta" and attr.get("property") == "og:image" and attr.get("content"):
|
||||
self.og_image = attr["content"]
|
||||
|
||||
def handle_endtag(self, tag: str) -> None:
|
||||
if tag in ("script", "style", "noscript", "svg") and self._skip > 0:
|
||||
self._skip -= 1
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
if self._skip == 0 and data.strip():
|
||||
self.parts.append(data.strip())
|
||||
|
||||
|
||||
def _ip_is_public(ip_str: str) -> bool:
|
||||
try:
|
||||
ip = ipaddress.ip_address(ip_str)
|
||||
except ValueError:
|
||||
return False
|
||||
return not (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_reserved or ip.is_unspecified)
|
||||
|
||||
|
||||
def guard_url(url: str) -> Optional[str]:
|
||||
"""Return None if safe to fetch, else a human-readable refusal reason (URL-02/03)."""
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
return f"refused scheme {parsed.scheme!r} (only http/https)"
|
||||
host = parsed.hostname
|
||||
if not host:
|
||||
return "refused: no host"
|
||||
try:
|
||||
literal = ipaddress.ip_address(host)
|
||||
return None if _ip_is_public(str(literal)) else f"refused non-public address {host}"
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
infos = socket.getaddrinfo(host, None)
|
||||
except socket.gaierror:
|
||||
return f"refused: cannot resolve {host}"
|
||||
for info in infos:
|
||||
if not _ip_is_public(str(info[4][0])):
|
||||
return f"refused: {host} resolves to non-public address"
|
||||
return None
|
||||
|
||||
|
||||
class URLReader:
|
||||
def __init__(self, config_getter: Callable[[], Dict[str, Any]], image_cache) -> None:
|
||||
self._config = config_getter
|
||||
self.image_cache = image_cache
|
||||
|
||||
def enabled(self) -> bool:
|
||||
return bool(self._config().get("enable-url-reading", False))
|
||||
|
||||
async def _get(self, session, url: str, max_bytes: int) -> Tuple[str, bytes]:
|
||||
"""Manual redirect handling so every hop is re-guarded (URL-04)."""
|
||||
current = url
|
||||
for _ in range(MAX_REDIRECTS):
|
||||
reason = guard_url(current)
|
||||
if reason:
|
||||
raise ValueError(reason)
|
||||
async with session.get(current, allow_redirects=False) as response:
|
||||
if response.status in (301, 302, 303, 307, 308) and response.headers.get("Location"):
|
||||
current = urljoin(current, response.headers["Location"])
|
||||
continue
|
||||
response.raise_for_status()
|
||||
return str(response.url), await response.content.read(max_bytes + 1)
|
||||
raise ValueError("too many redirects")
|
||||
|
||||
async def fetch(self, url: str, channel: str, user: str) -> Dict[str, Any]:
|
||||
config = self._config()
|
||||
max_bytes = int(config.get("url-max-bytes", DEFAULT_MAX_BYTES))
|
||||
timeout = aiohttp.ClientTimeout(total=FETCH_TIMEOUT_S)
|
||||
try:
|
||||
async with aiohttp.ClientSession(timeout=timeout, headers={"User-Agent": "FjerkroaBot/1.0"}) as session:
|
||||
final_url, body = await self._get(session, url, max_bytes)
|
||||
except Exception as err:
|
||||
return {"error": str(err)}
|
||||
text = self._to_text(body.decode("utf-8", "ignore"))
|
||||
clean = sanitize_external_text(text, int(config.get("url-max-chars", DEFAULT_MAX_CHARS)))
|
||||
images = await self._ingest_images(body.decode("utf-8", "ignore"), final_url, channel, user)
|
||||
return {"url": final_url, "text": clean, "images_cached": images}
|
||||
|
||||
def _to_text(self, html: str) -> str:
|
||||
extractor = _Extractor()
|
||||
try:
|
||||
extractor.feed(html)
|
||||
except Exception as err:
|
||||
logging.debug(f"html parse (text) failed: {err!r}")
|
||||
return re.sub(r"\s+\n", "\n", " ".join(extractor.parts))
|
||||
|
||||
async def _ingest_images(self, html: str, base_url: str, channel: str, user: str) -> int:
|
||||
if self.image_cache is None:
|
||||
return 0
|
||||
extractor = _Extractor()
|
||||
try:
|
||||
extractor.feed(html)
|
||||
except Exception as err:
|
||||
logging.debug(f"html parse (images) failed: {err!r}")
|
||||
candidates = ([extractor.og_image] if extractor.og_image else []) + extractor.images
|
||||
limit = int(self._config().get("url-max-images", DEFAULT_MAX_IMAGES))
|
||||
cached = 0
|
||||
for src in candidates:
|
||||
if cached >= limit:
|
||||
break
|
||||
absolute = urljoin(base_url, src)
|
||||
if guard_url(absolute) is not None:
|
||||
continue
|
||||
sha = await self.image_cache.ingest_url(absolute, channel, user, None)
|
||||
if sha is not None:
|
||||
cached += 1
|
||||
return cached
|
||||
@@ -12,3 +12,4 @@ with date + result.
|
||||
| DEP-04 | 2026-07-13 | Smoke gate exercised on ggg: RUNNING + fresh login line. |
|
||||
| DEP-05 | 2026-07-13 | Live-verified: kroa deploy attempt ~15h Oslo refused without DEPLOY_FORCE=1. |
|
||||
| DEP-06 | 2026-07-13 | Rollback documented (older tag + db backup restore); live drill pending — next release. |
|
||||
| OPS-15 | 2026-07-13 | Backup cron installed on both hosts (daily 03:17 UTC → ~/backups/<bot>/, keep 14); first snapshots written + verified 0600 (kroa 10965 B, luma 25871 B). |
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# SPEC-011 — URL reading
|
||||
|
||||
A `fetch_url` tool alongside IGDB: the model decides when to read a
|
||||
link (user pastes a URL + question; a news item links an article
|
||||
Luma wants details on). Web pages are the number-one injection
|
||||
vector, so everything fetched is sanitized (SAF-03) and the fetch
|
||||
itself is SSRF-guarded — the bot runs on shared hosting. Active only
|
||||
when `enable-url-reading = true`.
|
||||
|
||||
### URL-01 — fetch_url is offered as a tool (coverage: test)
|
||||
|
||||
When `enable-url-reading` is true, the chat call's `tools` list
|
||||
includes a `fetch_url` function (url string param) next to any IGDB
|
||||
tools. When false, it is absent.
|
||||
|
||||
### URL-02 — Only http/https are fetched (coverage: test)
|
||||
|
||||
`file:`, `ftp:`, `data:`, `gopher:` and schemeless inputs are
|
||||
refused before any network call, with an error result the model can
|
||||
relay.
|
||||
|
||||
### URL-03 — SSRF guard blocks non-public addresses (coverage: test)
|
||||
|
||||
Before fetching, the host is resolved and every resulting IP is
|
||||
checked; the fetch is refused when any is private, loopback,
|
||||
link-local, or otherwise non-global (RFC1918, 127/8, 169.254/16,
|
||||
::1, fc00::/7, etc.). A URL literal that is already such an IP is
|
||||
refused without DNS.
|
||||
|
||||
### URL-04 — Redirects are re-validated (coverage: test)
|
||||
|
||||
Redirects are followed manually; each hop's target passes URL-02 and
|
||||
URL-03 again. A public URL that 302-redirects to `localhost` or an
|
||||
internal IP is refused at the redirect, not fetched.
|
||||
|
||||
### URL-05 — Fetched text is bounded and sanitized (coverage: test)
|
||||
|
||||
Responses are capped at `url-max-bytes` (default 2 MB) with a
|
||||
download timeout; HTML is reduced to readable text (script/style
|
||||
dropped, tags stripped, whitespace collapsed) and passed through
|
||||
`sanitize_external_text` before it reaches the model, truncated to
|
||||
`url-max-chars` (default 6000).
|
||||
|
||||
### URL-06 — Page images feed the cache (coverage: test)
|
||||
|
||||
Up to `url-max-images` (default 2) prominent images (og:image, then
|
||||
large `<img>`) are ingested into the ImageCache for the requesting
|
||||
channel (SSRF-guarded like the page), so the model can see them and
|
||||
`picture_edit` can remix them. Ingestion failures are skipped, never
|
||||
fatal to the text result.
|
||||
|
||||
### URL-07 — Fetches are metered and capped (coverage: test)
|
||||
|
||||
Each fetch increments a per-user daily counter; over
|
||||
`url-daily-per-user` (default 20) `fetch_url` refuses with an error
|
||||
result. The budget gate (SAF-04) still applies to the surrounding
|
||||
model calls.
|
||||
@@ -0,0 +1,32 @@
|
||||
# SPEC-012 — Operations hardening
|
||||
|
||||
Runtime + host operability (FDB-012). Backups and host wiring are
|
||||
`manual` coverage; the in-process alerting is `test`.
|
||||
|
||||
### OPS-13 — Consistent DB backups (coverage: test)
|
||||
|
||||
`deploy/backup_db.py` writes a gzipped snapshot of `bot.db` using the
|
||||
sqlite3 online-backup API — consistent even while the bot writes
|
||||
(WAL-safe) — with 0600 permissions. Restoring a snapshot yields a
|
||||
readable database with the same rows.
|
||||
|
||||
### OPS-14 — Backups are rotated (coverage: test)
|
||||
|
||||
The newest `backup-keep` (default 14) snapshots are kept; older ones
|
||||
are deleted. Timestamped names sort chronologically so rotation is a
|
||||
pure list operation.
|
||||
|
||||
### OPS-15 — Backup cron on each host (coverage: manual)
|
||||
|
||||
Each host runs `backup_db.py` daily via cron, writing to
|
||||
`~/backups/<bot>/` (outside `~/fjerkroa_bot`, so deploys and service
|
||||
restarts never touch it). Verified by presence of the cron line and a
|
||||
fresh snapshot.
|
||||
|
||||
### OPS-16 — Repeated API errors alert staff (coverage: test)
|
||||
|
||||
The responder counts consecutive OpenAI request failures; at
|
||||
`api-error-alert-threshold` (default 5) in a row it fires one staff
|
||||
alert (rate-limited like all staff alerts) so a silently-broken bot
|
||||
(cf. the gpt-5.6 tools/reasoning incident) surfaces within minutes
|
||||
instead of hours. A success resets the counter.
|
||||
@@ -28,7 +28,7 @@ class TestIGDBIntegration(unittest.IsolatedAsyncioTestCase):
|
||||
|
||||
responder = OpenAIResponder(self.config_with_igdb)
|
||||
|
||||
mock_igdb.assert_called_once_with("test_client", "test_token")
|
||||
mock_igdb.assert_called_once_with("test_client", "test_token", client_secret=None)
|
||||
self.assertEqual(responder.igdb, mock_igdb_instance)
|
||||
|
||||
def test_igdb_initialization_disabled(self):
|
||||
|
||||
+81
-1
@@ -160,7 +160,7 @@ class TestIGDBQuery(unittest.TestCase):
|
||||
"id",
|
||||
"name",
|
||||
"alternative_names",
|
||||
"category",
|
||||
"game_type",
|
||||
"release_dates",
|
||||
"franchise",
|
||||
"language_supports",
|
||||
@@ -174,5 +174,85 @@ class TestIGDBQuery(unittest.TestCase):
|
||||
self.assertEqual(result, [{"id": 1, "name": "Super Mario Bros"}])
|
||||
|
||||
|
||||
class TestIGDBTokenRefresh(unittest.TestCase):
|
||||
@staticmethod
|
||||
def _oauth_response(token="fresh_token", expires_in=5_000_000):
|
||||
response = Mock()
|
||||
response.json.return_value = {"access_token": token, "expires_in": expires_in}
|
||||
response.raise_for_status.return_value = None
|
||||
return response
|
||||
|
||||
@staticmethod
|
||||
def _api_response(payload, status_code=200):
|
||||
response = Mock()
|
||||
response.status_code = status_code
|
||||
response.json.return_value = payload
|
||||
response.raise_for_status.return_value = None
|
||||
return response
|
||||
|
||||
@patch("fjerkroa_bot.igdblib.requests.post")
|
||||
def test_fetches_token_when_only_secret_configured(self, mock_post):
|
||||
"""Without a static token, the first request fetches one via Twitch OAuth."""
|
||||
mock_post.side_effect = [self._oauth_response(), self._api_response([{"id": 1}])]
|
||||
igdb = IGDBQuery("cid", client_secret="secret")
|
||||
|
||||
result = igdb.send_igdb_request("games", "fields name; limit 1;")
|
||||
|
||||
self.assertEqual(result, [{"id": 1}])
|
||||
oauth_call, api_call = mock_post.call_args_list
|
||||
self.assertEqual(oauth_call.args[0], "https://id.twitch.tv/oauth2/token")
|
||||
self.assertEqual(
|
||||
oauth_call.kwargs["params"],
|
||||
{"client_id": "cid", "client_secret": "secret", "grant_type": "client_credentials"},
|
||||
)
|
||||
self.assertEqual(api_call.kwargs["headers"]["Authorization"], "Bearer fresh_token")
|
||||
|
||||
@patch("fjerkroa_bot.igdblib.requests.post")
|
||||
def test_refreshes_and_retries_on_401(self, mock_post):
|
||||
"""A 401 with a configured secret triggers one refresh and retry."""
|
||||
mock_post.side_effect = [
|
||||
self._api_response(None, status_code=401),
|
||||
self._oauth_response(),
|
||||
self._api_response([{"id": 2}]),
|
||||
]
|
||||
igdb = IGDBQuery("cid", "expired_token", client_secret="secret")
|
||||
|
||||
result = igdb.send_igdb_request("games", "fields name; limit 1;")
|
||||
|
||||
self.assertEqual(result, [{"id": 2}])
|
||||
self.assertEqual(igdb.igdb_api_key, "fresh_token")
|
||||
self.assertEqual(mock_post.call_args_list[2].kwargs["headers"]["Authorization"], "Bearer fresh_token")
|
||||
|
||||
@patch("fjerkroa_bot.igdblib.time.time")
|
||||
@patch("fjerkroa_bot.igdblib.requests.post")
|
||||
def test_proactive_refresh_before_expiry(self, mock_post, mock_time):
|
||||
"""An expired self-fetched token is refreshed before the request."""
|
||||
mock_time.return_value = 1_000_000.0
|
||||
mock_post.side_effect = [self._oauth_response("token_a", expires_in=5_000_000), self._api_response([])]
|
||||
igdb = IGDBQuery("cid", client_secret="secret")
|
||||
igdb.send_igdb_request("games", "fields name;")
|
||||
|
||||
# jump past the token expiry -> next request refreshes first
|
||||
mock_time.return_value = 1_000_000.0 + 5_000_000
|
||||
mock_post.side_effect = [self._oauth_response("token_b"), self._api_response([])]
|
||||
igdb.send_igdb_request("games", "fields name;")
|
||||
|
||||
self.assertEqual(igdb.igdb_api_key, "token_b")
|
||||
|
||||
@patch("fjerkroa_bot.igdblib.requests.post")
|
||||
def test_no_refresh_without_secret(self, mock_post):
|
||||
"""Static-token setups keep the old behavior: no OAuth calls, error -> None."""
|
||||
response = Mock()
|
||||
response.status_code = 401
|
||||
response.raise_for_status.side_effect = requests.RequestException("401 Client Error")
|
||||
mock_post.return_value = response
|
||||
igdb = IGDBQuery("cid", "expired_token")
|
||||
|
||||
result = igdb.send_igdb_request("games", "fields name; limit 1;")
|
||||
|
||||
self.assertIsNone(result)
|
||||
mock_post.assert_called_once()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Unit coverage for SPEC-012 ops hardening (OPS-13/14/16)."""
|
||||
|
||||
import gzip
|
||||
import sqlite3
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
from fjerkroa_bot.persistence import PersistentStore
|
||||
|
||||
from .test_spec_ops import OpsBase
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "deploy"))
|
||||
import backup_db # noqa: E402
|
||||
|
||||
|
||||
class TestSnapshotConsistency(unittest.TestCase):
|
||||
def test_snapshot_roundtrips(self):
|
||||
"""OPS-13: a gzipped snapshot restores to a readable DB with the same rows, 0600."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = Path(tmp) / "bot.db"
|
||||
store = PersistentStore(db)
|
||||
store.save_history("chat", [{"role": "user", "content": "hei"}])
|
||||
store.add_user_fact("alice", "likes espresso", "self")
|
||||
|
||||
dest = Path(tmp) / "snap.db.gz"
|
||||
backup_db.snapshot(db, dest)
|
||||
self.assertEqual(stat.S_IMODE(dest.stat().st_mode), 0o600)
|
||||
|
||||
restored = Path(tmp) / "restored.db"
|
||||
with gzip.open(dest, "rb") as gz, open(restored, "wb") as out:
|
||||
out.write(gz.read())
|
||||
conn = sqlite3.connect(restored)
|
||||
try:
|
||||
rows = conn.execute("SELECT content FROM history WHERE channel='chat'").fetchall()
|
||||
facts = conn.execute("SELECT fact FROM user_facts").fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
self.assertEqual(rows, [("hei",)])
|
||||
self.assertEqual(facts, [("likes espresso",)])
|
||||
|
||||
def test_snapshot_during_writes(self):
|
||||
"""OPS-13: snapshot succeeds while another connection holds the DB open (WAL)."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = Path(tmp) / "bot.db"
|
||||
store = PersistentStore(db)
|
||||
store.save_history("chat", [{"role": "user", "content": "x"}])
|
||||
live = sqlite3.connect(db) # simulate the running bot's open handle
|
||||
live.execute("PRAGMA journal_mode=WAL")
|
||||
try:
|
||||
dest = Path(tmp) / "snap.db.gz"
|
||||
backup_db.snapshot(db, dest) # must not raise
|
||||
self.assertTrue(dest.exists())
|
||||
finally:
|
||||
live.close()
|
||||
|
||||
|
||||
class TestRotation(unittest.TestCase):
|
||||
def test_victims_keeps_newest(self):
|
||||
"""OPS-14: only the oldest beyond `keep` are selected for deletion."""
|
||||
names = [f"bot-2026070{d}-000000.db.gz" for d in range(1, 8)] # 7 chronological
|
||||
victims = backup_db.victims(list(reversed(names)), keep=3)
|
||||
self.assertEqual(victims, names[:4]) # oldest 4 removed, newest 3 kept
|
||||
|
||||
def test_victims_under_keep_deletes_nothing(self):
|
||||
"""OPS-14: fewer than `keep` backups -> nothing deleted."""
|
||||
self.assertEqual(backup_db.victims(["bot-20260701-000000.db.gz"], keep=14), [])
|
||||
|
||||
def test_rotate_on_disk(self):
|
||||
"""OPS-14: rotate removes the right files from a real dir."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for d in range(1, 6):
|
||||
(Path(tmp) / f"bot-2026070{d}-000000.db.gz").write_bytes(b"x")
|
||||
removed = backup_db.rotate(Path(tmp), keep=2)
|
||||
self.assertEqual(removed, 3)
|
||||
self.assertEqual(len(list(Path(tmp).glob("bot-*.db.gz"))), 2)
|
||||
|
||||
|
||||
class TestApiErrorAlert(OpsBase):
|
||||
async def test_threshold_alert_and_reset(self):
|
||||
"""OPS-16: N consecutive failures fire one staff alert; success resets."""
|
||||
self.bot.config["api-error-alert-threshold"] = 3
|
||||
self.bot.send_message_with_typing = AsyncMock(side_effect=RuntimeError("boom"))
|
||||
origin = MagicMock()
|
||||
from fjerkroa_bot.ai_responder import AIMessage
|
||||
|
||||
for _ in range(3):
|
||||
await self.bot.respond(AIMessage("alice", "hei", "chat"), origin)
|
||||
self.assertEqual(self.bot.staff_channel.send.await_count, 1) # exactly one alert at threshold
|
||||
self.assertEqual(self.bot._consecutive_api_errors, 3)
|
||||
|
||||
# a success resets the counter
|
||||
from fjerkroa_bot.ai_responder import AIResponse
|
||||
|
||||
self.bot.send_message_with_typing = AsyncMock(return_value=AIResponse(None, False, "chat", None, None, False, False))
|
||||
await self.bot.respond(AIMessage("alice", "hei", "chat"), origin)
|
||||
self.assertEqual(self.bot._consecutive_api_errors, 0)
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Unit coverage for SPEC-011 URL reading (URL-01..07)."""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from fjerkroa_bot.openai_responder import OpenAIResponder
|
||||
from fjerkroa_bot.url_reader import FETCH_URL_TOOL, URLReader, guard_url
|
||||
|
||||
CONFIG = {"openai-token": "t", "model": "m", "system": "s", "history-limit": 5}
|
||||
|
||||
|
||||
class TestToolOffered(unittest.TestCase):
|
||||
def test_tool_present_only_when_enabled(self):
|
||||
"""URL-01: fetch_url appears in the tool list only with enable-url-reading."""
|
||||
off = OpenAIResponder(CONFIG, "chat")
|
||||
self.assertNotIn("fetch_url", [f["name"] for f in off._available_tools()])
|
||||
on = OpenAIResponder(dict(CONFIG, **{"enable-url-reading": True}), "chat")
|
||||
self.assertIn("fetch_url", [f["name"] for f in on._available_tools()])
|
||||
self.assertEqual(FETCH_URL_TOOL["name"], "fetch_url")
|
||||
|
||||
|
||||
class TestSchemeGuard(unittest.TestCase):
|
||||
def test_non_http_schemes_refused(self):
|
||||
"""URL-02: only http/https pass the guard."""
|
||||
self.assertIsNone(guard_url("https://example.com/article"))
|
||||
for bad in ("file:///etc/passwd", "ftp://host/x", "data:text/html,x", "gopher://h", "no-scheme.com/x"):
|
||||
self.assertIsNotNone(guard_url(bad))
|
||||
|
||||
|
||||
class TestSSRFGuard(unittest.TestCase):
|
||||
def test_private_and_loopback_refused(self):
|
||||
"""URL-03: private/loopback/link-local literals are refused without DNS."""
|
||||
for bad in (
|
||||
"http://127.0.0.1/admin",
|
||||
"http://localhost/x", # resolves to loopback
|
||||
"http://10.0.0.5/x",
|
||||
"http://192.168.1.1/x",
|
||||
"http://169.254.169.254/latest/meta-data", # cloud metadata
|
||||
"http://[::1]/x",
|
||||
):
|
||||
self.assertIsNotNone(guard_url(bad), f"{bad} should be refused")
|
||||
|
||||
def test_public_ip_allowed(self):
|
||||
"""URL-03: a public IP literal passes."""
|
||||
self.assertIsNone(guard_url("http://93.184.216.34/"))
|
||||
|
||||
@patch("fjerkroa_bot.url_reader.socket.getaddrinfo")
|
||||
def test_dns_to_private_refused(self, getaddrinfo):
|
||||
"""URL-03: a hostname resolving to a private IP is refused."""
|
||||
getaddrinfo.return_value = [(2, 1, 6, "", ("10.1.2.3", 0))]
|
||||
self.assertIsNotNone(guard_url("http://evil.example.com/x"))
|
||||
|
||||
|
||||
class TestRedirectRevalidation(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_redirect_to_internal_refused(self):
|
||||
"""URL-04: a public URL redirecting to localhost is refused at the hop."""
|
||||
reader = URLReader(lambda: {}, None)
|
||||
|
||||
class FakeResp:
|
||||
status = 302
|
||||
headers = {"Location": "http://127.0.0.1/secret"}
|
||||
url = "http://safe.example.com"
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *a):
|
||||
return False
|
||||
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
|
||||
class FakeSession:
|
||||
def get(self, url, allow_redirects=False):
|
||||
return FakeResp()
|
||||
|
||||
with patch("fjerkroa_bot.url_reader.guard_url", side_effect=[None, "refused internal"]):
|
||||
with self.assertRaises(ValueError):
|
||||
await reader._get(FakeSession(), "http://safe.example.com", 1000)
|
||||
|
||||
|
||||
class TestTextExtraction(unittest.TestCase):
|
||||
def test_html_reduced_to_text(self):
|
||||
"""URL-05: scripts/styles dropped, tags stripped."""
|
||||
reader = URLReader(lambda: {}, None)
|
||||
html = "<html><head><style>x{}</style></head><body><h1>Titel</h1><script>evil()</script><p>Inhalt hier</p></body></html>"
|
||||
text = reader._to_text(html)
|
||||
self.assertIn("Titel", text)
|
||||
self.assertIn("Inhalt hier", text)
|
||||
self.assertNotIn("evil", text)
|
||||
self.assertNotIn("x{}", text)
|
||||
|
||||
|
||||
class TestFetchSanitizes(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_fetch_result_is_sanitized_and_capped(self):
|
||||
"""URL-05: fetch output is length-capped and @everyone-neutralized."""
|
||||
reader = URLReader(lambda: {"url-max-chars": 50}, None)
|
||||
payload = ("<p>@everyone " + "x" * 5000 + "</p>").encode()
|
||||
with patch.object(reader, "_get", new=AsyncMock(return_value=("http://x.com", payload))):
|
||||
result = await reader.fetch("http://x.com", "chat", "alice")
|
||||
self.assertLessEqual(len(result["text"]), 50)
|
||||
self.assertNotIn("@everyone", result["text"])
|
||||
|
||||
async def test_fetch_error_is_reported_not_raised(self):
|
||||
"""URL-05: a fetch failure returns an error dict the model can relay."""
|
||||
reader = URLReader(lambda: {}, None)
|
||||
with patch.object(reader, "_get", new=AsyncMock(side_effect=ValueError("refused non-public address"))):
|
||||
result = await reader.fetch("http://10.0.0.1", "chat", "alice")
|
||||
self.assertIn("error", result)
|
||||
|
||||
|
||||
class TestImageIngest(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_page_images_go_to_cache_ssrf_guarded(self):
|
||||
"""URL-06: og:image + <img> ingested (cap honored), internal srcs skipped."""
|
||||
cache = type("C", (), {})()
|
||||
cache.ingest_url = AsyncMock(side_effect=["sha1", "sha2", "sha3"])
|
||||
reader = URLReader(lambda: {"url-max-images": 2}, cache)
|
||||
html = (
|
||||
'<meta property="og:image" content="https://cdn.example.com/hero.jpg">'
|
||||
'<img src="https://cdn.example.com/a.png"><img src="http://127.0.0.1/internal.png">'
|
||||
)
|
||||
|
||||
# guard by scheme/loopback only, no real DNS in the test
|
||||
def fake_guard(url):
|
||||
return "refused" if "127.0.0.1" in url else None
|
||||
|
||||
with patch("fjerkroa_bot.url_reader.guard_url", side_effect=fake_guard):
|
||||
count = await reader._ingest_images(html, "https://example.com", "chat", "alice")
|
||||
self.assertEqual(count, 2) # og:image + first public img, cap 2
|
||||
ingested = [call.args[0] for call in cache.ingest_url.await_args_list]
|
||||
self.assertNotIn("http://127.0.0.1/internal.png", ingested)
|
||||
|
||||
|
||||
class TestPerUserCap(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_dispatch_caps_fetches(self):
|
||||
"""URL-07: over url-daily-per-user, fetch_url returns an error without fetching."""
|
||||
responder = OpenAIResponder(dict(CONFIG, **{"enable-url-reading": True, "url-daily-per-user": 2}), "chat")
|
||||
responder.url_reader.fetch = AsyncMock(return_value={"url": "x", "text": "ok"})
|
||||
for _ in range(2):
|
||||
await responder._dispatch_tool("fetch_url", {"url": "http://x.com"}, "alice")
|
||||
blocked = await responder._dispatch_tool("fetch_url", {"url": "http://x.com"}, "alice")
|
||||
self.assertIn("error", blocked)
|
||||
self.assertEqual(responder.url_reader.fetch.await_count, 2)
|
||||
Reference in New Issue
Block a user