Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix(matomo): route every request to the instance through url_safety

Agrici Danielac70af18f5c1
diff --git a/PRIVACY.md b/PRIVACY.md
index 91db90c..90ff791 100644
--- a/PRIVACY.md
+++ b/PRIVACY.md
@@ -24,7 +24,7 @@ Optional extensions make API calls to third-party services when you invoke their
| **SE Ranking** | seranking.com/api | Domains and keywords you analyze | [SE Ranking Privacy](https://seranking.com/privacy-policy) |
| **Profound** | Profound API (tryprofound.com) | Brands and domains you track | [Profound Privacy](https://tryprofound.com/privacy) |
| **Bing Webmaster / IndexNow** | Bing Webmaster Tools API and IndexNow endpoints | Domains, submitted URLs, and key-verification URL data | [Microsoft Privacy](https://privacy.microsoft.com/) |
-| **Matomo** | Your own Matomo instance URL (self-hosted) or Matomo Cloud | Site IDs, default site ID, and the configured instance URL | [Matomo Privacy](https://matomo.org/privacy-policy/) (Cloud); self-hosted = your own policy |
+| **Matomo** | Your own Matomo instance (self-hosted or Matomo Cloud) — no claude-seo vendor is contacted | `idSite`, the report parameters (method, period, date range, segment, row limit), and `token_auth` in the POST body | [Matomo Privacy](https://matomo.org/privacy-policy/) (Cloud); self-hosted = your own policy |
| **Unlighthouse** | Local only — no third-party vendor | Runs Lighthouse locally against the target URL; only the target site is contacted (to crawl it). Nothing is sent to a third-party vendor. | N/A (runs locally) |
## Backlink APIs
@@ -46,13 +46,19 @@ configured Matomo instance (self-hosted or Matomo Cloud):
| Script | Endpoint | Data Sent |
|--------|----------|-----------|
-| `matomo_auth.py` | The configured `MATOMO_URL` | `API.getMatomoVersion` probe with `token_auth` (POST body; never logged) |
-| `matomo_report.py` | The configured `MATOMO_URL` | Reporting API queries for the configured `idSite`; `token_auth` in POST body, never logged |
-
-Self-hosted Matomo instances on private networks / localhost are supported
-because the script applies a light URL sanity check rather than the strict
-SSRF protection used for arbitrary web fetches. Verify your instance's
-trust boundary if you point the script at a non-localhost address.
+| `matomo_auth.py` | The configured `MATOMO_URL` | `API.getMatomoVersion` probe; `token_auth` in the POST body, never in a URL, never logged |
+| `matomo_report.py` | The configured `MATOMO_URL` | Reporting API queries for the configured `idSite`: method name, period, date range, segment, and row limit; `token_auth` in the POST body, never in a URL, never logged |
+
+The endpoint is the instance you configured and nothing else. No claude-seo
+vendor, telemetry endpoint, or third party sees any of it, and the URLs of the
+site you analyze are read back from your own Matomo, not sent to it.
+
+Both scripts reach the instance through `scripts/url_safety.py`, the same
+SSRF-guarded, DNS-pinned path as every other outbound request in claude-seo.
+A self-hosted instance on a private address is reached by naming it in the
+`CLAUDE_SEO_LOCAL_TARGETS` allowlist; redirects away from the instance are
+refused rather than followed. See SECURITY.md and
+`extensions/matomo/docs/MATOMO-SETUP.md`.
## Google SEO APIs
diff --git a/extensions/matomo/docs/MATOMO-SETUP.md b/extensions/matomo/docs/MATOMO-SETUP.md
index eee4257..3e07571 100644
--- a/extensions/matomo/docs/MATOMO-SETUP.md
+++ b/extensions/matomo/docs/MATOMO-SETUP.md
@@ -40,13 +40,41 @@ with `0o600` permissions.
4. Copy the generated `token_auth` (32 hex chars) — Matomo only shows
it once at creation
-## Self-hosted instance notes
+## Self-hosted instance on a private address
-`MATOMO_URL` may point at `http://analytics.internal`,
-`https://matomo.lan.example.com`, or behind a reverse proxy on a private
-network. The script applies a light URL sanity check (scheme + host only)
-rather than the strict SSRF protection used for arbitrary web fetches,
-because self-hosted Matomo frequently lives outside the public internet.
+Every request to your Matomo instance goes through claude-seo's shared SSRF
+guard, the `url_safety` module: the instance URL is validated, its hostname is
+pinned to the validated address for the life of the request, and a redirect
+away from the instance is refused rather than followed.
+
+That guard refuses private, loopback, and link-local addresses by default, so
+an instance at `http://matomo.internal:8080`, `http://192.168.1.20`, or
+`http://localhost:8080` is refused until you say it is yours. Name it in the
+`CLAUDE_SEO_LOCAL_TARGETS` allowlist:
+
+```bash
+export CLAUDE_SEO_LOCAL_TARGETS="matomo.internal:8080"
+```
+
+Entries are `host` or `host:port`, comma-separated, matched exactly. A bare
+`host` matches any port on that host; `host:port` matches that port only.
+There is no wildcard, no range, and no "allow private" mode. To make it
+permanent, put the export in your shell profile or the `env` block of
+`~/.claude/settings.json`.
+
+The allowlist is deliberately narrow, and the narrowness is the point:
+
+- It is consulted only for the top-level instance URL. A redirect target or
+ any other host stays fail-closed, so a compromised or misconfigured Matomo
+ cannot use the allowlist to reach the rest of your network.
+- Cloud metadata endpoints (169.254.169.254, `metadata.google.internal`,
+ 100.100.100.200, and their siblings) are refused even when listed.
+- Unset, claude-seo behaves exactly as it does without the feature.
+
+`extensions/matomo/install.sh` and `install.ps1` detect a private instance
+address at install time and print the exact line to add.
+
+Full semantics: [SECURITY.md](../../../SECURITY.md).
If your Matomo instance requires a self-signed certificate, install its
CA into the system trust store. The script uses `requests` defaults; it
diff --git a/extensions/matomo/install.ps1 b/extensions/matomo/install.ps1
index ac33977..35d2743 100644
--- a/extensions/matomo/install.ps1
+++ b/extensions/matomo/install.ps1
@@ -11,6 +11,20 @@ $TokenPlain = [System.Net.NetworkCredential]::new("", $TokenSecure).Password
if (-not $TokenPlain) { throw "Matomo token_auth required" }
$SiteId = Read-Host "Default site ID (idSite, optional, e.g. 1)"
$SourceDir = Split-Path -Parent $MyInvocation.MyCommand.Path
+$RepoRoot = Split-Path -Parent (Split-Path -Parent $SourceDir)
+$MatomoAuth = Join-Path $RepoRoot "scripts/matomo_auth.py"
+# Every Matomo request goes through the SSRF guard, which refuses private
+# addresses unless they are named in CLAUDE_SEO_LOCAL_TARGETS. Tell the user
+# now, with the exact host:port, rather than at the first failed call.
+if (Test-Path $MatomoAuth) {
+ $Hint = & python $MatomoAuth --local-target-hint $MatomoUrl 2>$null
+ if ($Hint) {
+ Write-Host ""
+ Write-Host "! $MatomoUrl is on a private address."
+ Write-Host " $Hint"
+ Write-Host ""
+ }
+}
$SkillTarget = Join-Path $SkillDir "seo-matomo"
New-Item -ItemType Directory -Path $SkillTarget -Force | Out-Null
Copy-Item (Join-Path $SourceDir "skills/seo-matomo/SKILL.md") (Join-Path $SkillTarget "SKILL.md") -Force
diff --git a/extensions/matomo/install.sh b/extensions/matomo/install.sh
index b811179..0c6db06 100755
--- a/extensions/matomo/install.sh
+++ b/extensions/matomo/install.sh
@@ -22,10 +22,25 @@ main() {
[ ! -d "${SKILL_DIR}/seo" ] && { echo "✗ claude-seo base not installed."; exit 1; }
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" >/dev/null 2>&1 && pwd)"
+ REPO_ROOT="$(cd "${SOURCE_DIR}/../.." >/dev/null 2>&1 && pwd)"
+ MATOMO_AUTH="${REPO_ROOT}/scripts/matomo_auth.py"
read -rp "Matomo instance URL (e.g. https://analytics.example.com): " MATOMO_URL
[ -z "${MATOMO_URL}" ] && { echo "✗ Matomo URL required."; exit 1; }
+ # Every Matomo request goes through the SSRF guard, which refuses private
+ # addresses unless they are named in CLAUDE_SEO_LOCAL_TARGETS. Tell the
+ # user now, with the exact host:port, rather than at the first failed call.
+ if [ -f "${MATOMO_AUTH}" ]; then
+ HINT="$(python3 "${MATOMO_AUTH}" --local-target-hint "${MATOMO_URL}" 2>/dev/null || true)"
+ if [ -n "${HINT}" ]; then
+ echo
+ echo "! ${MATOMO_URL} is on a private address."
+ echo " ${HINT}"
+ echo
+ fi
+ fi
+
read -rsp "Matomo API token_auth (32-char hex): " MATOMO_TOKEN
echo
[ -z "${MATOMO_TOKEN}" ] && { echo "✗ Matomo token_auth required."; exit 1; }
diff --git a/extensions/matomo/skills/seo-matomo/SKILL.md b/extensions/matomo/skills/seo-matomo/SKILL.md
index d935998..319e729 100644
--- a/extensions/matomo/skills/seo-matomo/SKILL.md
+++ b/extensions/matomo/skills/seo-matomo/SKILL.md
@@ -59,8 +59,35 @@ All commands accept `--days` (default 28), `--limit`, `--site-id`, and
--check` succeeds. Both agents can be active simultaneously when the
user has both GA4 and Matomo configured.
+## Self-hosted instance on a private address
+
+Every Matomo request goes through claude-seo's SSRF guard: the instance URL
+is validated and DNS-pinned, and a redirect off the instance is refused.
+Private, loopback, and link-local addresses are refused by default. When the
+user's instance lives on one (`http://matomo.internal:8080`,
+`http://192.168.1.20`, `http://localhost:8080`), tell them to name it in the
+`CLAUDE_SEO_LOCAL_TARGETS` allowlist:
+
+```bash
+export CLAUDE_SEO_LOCAL_TARGETS="matomo.internal:8080"
+```
+
+Entries are `host` or `host:port`, comma-separated, matched exactly. The
+allowlist covers only the top-level instance URL; redirect targets and every
+other host stay fail-closed, and cloud metadata addresses are refused even
+when listed. Never suggest disabling the guard or editing `url_safety.py`:
+the allowlist is the supported route. Details in
+`extensions/matomo/docs/MATOMO-SETUP.md` and SECURITY.md.
+
## Error Handling
+- Refused by the SSRF guard (error names `CLAUDE_SEO_LOCAL_TARGETS`): the
+ instance is on a private address that has not been allowlisted. Give the
+ user the exact export line from the error, which already carries the right
+ `host:port`.
+- Refused redirect: the instance answered a 30x pointing at another host.
+ `MATOMO_URL` is pointing at a redirector rather than at the Reporting API.
+ Ask the user for the URL their instance actually serves the API from.
- Missing credentials: report which env vars / config keys are unset and
remind the user to run `extensions/matomo/install.sh` or
`"${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo" run matomo_auth.py --setup`.
diff --git a/scripts/matomo_auth.py b/scripts/matomo_auth.py
index 8c782ea..020f8ff 100644
--- a/scripts/matomo_auth.py
+++ b/scripts/matomo_auth.py
@@ -13,10 +13,14 @@ Usage:
"""
import argparse
+import ipaddress
import json
import os
+import re
+import socket
import sys
from typing import Optional
+from urllib.parse import urlparse
try:
import requests
@@ -29,8 +33,28 @@ _SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))
if _SCRIPTS_DIR not in sys.path:
sys.path.insert(0, _SCRIPTS_DIR)
+from url_safety import ( # noqa: E402 (path bootstrap must run first)
+ URLSafetyError,
+ is_safe_ip,
+ safe_requests_session,
+)
+
CONFIG_PATH = os.path.expanduser("~/.config/claude-seo/matomo.json")
DEFAULT_TIMEOUT = 15
+USER_AGENT = "ClaudeSEO/2.3.0"
+LOCAL_TARGETS_ENV = "CLAUDE_SEO_LOCAL_TARGETS"
+
+_SECRET_RE = re.compile(r"(token_auth|token|password)=[^\s&\"']+", re.IGNORECASE)
+
+
+def redact(text: str) -> str:
+ """Strip any ``token_auth=``/``token=``/``password=`` value from a string.
+
+ Applied to every message this module emits. The token travels in the POST
+ body, so it should never reach an exception string in the first place;
+ this is the belt to that braces.
+ """
+ return _SECRET_RE.sub(r"\1=<redacted>", str(text))
def load_config() -> dict:
@@ -75,56 +99,157 @@ def load_config() -> dict:
return config
-def _sanity_check_instance_url(url: str) -> Optional[str]:
- """
- Light sanity check for a user-configured Matomo instance URL.
-
- Intentionally does NOT use scripts/url_safety.validate_url(): self-hosted
- Matomo instances frequently live on private networks, localhost, or
- behind reverse proxies on internal IPs. Forcing SSRF protection would
- block legitimate analytics setups. Instead we only enforce:
+def _normalize_instance_url(url: str) -> Optional[str]:
+ """Shape-check and normalize a configured Matomo instance URL.
- - non-empty
- - http or https scheme
- - non-empty host
- - no userinfo in URL
+ Shape only: scheme, host, no userinfo, no trailing slash. Whether the
+ instance may actually be contacted is decided by ``url_safety`` at request
+ time (see :func:`instance_endpoint` and :func:`post_to_instance`), which is
+ the single place in claude-seo that reads
+ ``CLAUDE_SEO_LOCAL_TARGETS``. Deciding it here as well would put a second,
+ divergent SSRF policy in the tree.
Returns:
- Normalized URL (trailing slash trimmed) or None if invalid.
+ Normalized URL (trailing slash trimmed) or None if malformed.
"""
if not url:
return None
url = url.strip()
if not (url.startswith("http://") or url.startswith("https://")):
return None
- if "@" in url.split("//", 1)[-1].split("/", 1)[0]:
- return None
- host = url.split("//", 1)[-1].split("/", 1)[0]
- if not host:
+ authority = url.split("//", 1)[-1].split("/", 1)[0]
+ if not authority or "@" in authority:
return None
return url.rstrip("/")
+def instance_endpoint(url: str) -> str:
+ """The Reporting API endpoint for a normalized instance URL."""
+ return f"{url.rstrip('/')}/index.php"
+
+
+def _local_targets_hint(endpoint: str) -> str:
+ """The one-line remedy for a self-hosted instance on a private address."""
+ parsed = urlparse(endpoint)
+ host = parsed.hostname or ""
+ port = parsed.port
+ target = f"{host}:{port}" if port else host
+ return (
+ f"A self-hosted Matomo on a private address is supported: add it to the "
+ f"{LOCAL_TARGETS_ENV} allowlist, for example "
+ f"{LOCAL_TARGETS_ENV}={target}. The allowlist is consulted only for this "
+ f"first, top-level URL; redirects and subresources stay fail-closed, and "
+ f"cloud metadata addresses are refused even when listed. See SECURITY.md."
+ )
+
+
+def resolves_to_private_address(url: str) -> bool:
+ """True when the instance URL's host resolves to a non-public address.
+
+ Used by the installers to decide whether to print the
+ ``CLAUDE_SEO_LOCAL_TARGETS`` hint. Best-effort: a host that does not
+ resolve at all is not reported as private.
+ """
+ normalized = _normalize_instance_url(url)
+ if not normalized:
+ return False
+ host = urlparse(normalized).hostname or ""
+ if not host:
+ return False
+ try:
+ ipaddress.ip_address(host)
+ except ValueError:
+ pass
+ else:
+ return not is_safe_ip(host)
+ try:
+ addrinfo = socket.getaddrinfo(host, None, family=socket.AF_INET,
+ type=socket.SOCK_STREAM)
+ except (OSError, UnicodeError):
+ return False
+ return any(not is_safe_ip(info[4][0]) for info in addrinfo)
+
+
+class MatomoRequestRefused(Exception):
+ """A request to the configured Matomo instance was refused before it left.
+
+ Raised for a URL ``url_safety`` will not allow (private address without the
+ allowlist, blocked hostname, failed DNS) and for a redirect away from the
+ instance. The message is always redacted.
+ """
+
+
+def post_to_instance(endpoint: str, data: dict,
+ timeout: int = DEFAULT_TIMEOUT) -> "requests.Response":
+ """POST to a Matomo instance through url_safety's DNS-pinned session.
+
+ Every outbound request to the user's Matomo instance goes through here.
+ ``safe_requests_session`` validates the endpoint with
+ ``validate_url_strict`` (which consults ``CLAUDE_SEO_LOCAL_TARGETS`` for
+ this top-level URL) and pins the hostname to the validated address for the
+ life of the session, so the address cannot be re-bound between validation
+ and connect.
+
+ Redirects are refused rather than followed. The Reporting API answers a
+ POST with a JSON body; a 30x is either a misconfigured ``MATOMO_URL`` or an
+ attempt to pivot the pinned session onto another host, and the pin does not
+ extend to a redirect target. The error names the redirect target's host so
+ the user can point ``MATOMO_URL`` at the final URL themselves.
+
+ Raises:
+ MatomoRequestRefused: refused before or instead of a response.
+ requests.exceptions.RequestException: transport failures, which the
+ callers already map to their own error envelopes.
+ """
+ headers = {"User-Agent": USER_AGENT}
+ try:
+ with safe_requests_session(endpoint) as session:
+ resp = session.post(
+ endpoint,
+ data=data,
+ headers=headers,
+ timeout=timeout,
+ allow_redirects=False,
+ )
+ except URLSafetyError as exc:
+ message = redact(exc)
+ if resolves_to_private_address(endpoint):
+ message = f"{message}. {_local_targets_hint(endpoint)}"
+ raise MatomoRequestRefused(message) from None
+
+ if 300 <= resp.status_code < 400:
+ location = resp.headers.get("Location", "")
+ target_host = urlparse(location).hostname or "an unnamed target"
+ raise MatomoRequestRefused(
+ f"Matomo answered HTTP {resp.status_code} with a redirect to "
+ f"{target_host}. Redirects are not followed: the DNS pin covers "
+ f"only the configured instance. Set MATOMO_URL to the URL your "
+ f"instance actually serves the Reporting API from."
+ )
+ return resp
+
+
def _probe_version(url: str, token: str, timeout: int = DEFAULT_TIMEOUT) -> dict:
"""
- Light probe: hit ``API.getMatomoVersion`` over HTTPS POST.
+ Light probe: POST ``API.getMatomoVersion`` through the pinned helpers.
Returns one of:
{"ok": True, "version": "x.y.z"}
{"ok": False, "status_code": int, "error": str}
"""
try:
- resp = requests.post(
- f"{url}/index.php",
- data={
+ resp = post_to_instance(
+ instance_endpoint(url),
+ {
"module": "API",
"method": "API.getMatomoVersion",
"format": "JSON",
"token_auth": token,
},
timeout=timeout,
- headers={"User-Agent": "ClaudeSEO/2.2.5"},
)
+ except MatomoRequestRefused as e:
+ return {"ok": False, "error": redact(e)}
except requests.exceptions.Timeout:
return {"ok": False, "error": f"timeout after {timeout}s"}
except requests.exceptions.SSLError as e:
@@ -172,7 +297,7 @@ def check_credentials() -> dict:
token = config.get("matomo_token")
site_id = config.get("matomo_site_id")
- url = _sanity_check_instance_url(raw_url)
+ url = _normalize_instance_url(raw_url)
if not url:
return {
"available": False,
@@ -256,7 +381,7 @@ def detect_tier() -> dict:
def get_matomo_url() -> Optional[str]:
"""Get the configured Matomo URL."""
config = load_config()
- return _sanity_check_instance_url(config.get("matomo_url"))
+ return _normalize_instance_url(config.get("matomo_url"))
def get_matomo_token() -> Optional[str]:
@@ -313,11 +438,17 @@ TIER 1: MATOMO REPORTING API (one token, your own instance)
organic search keywords (often "(not provided)" due to browser
privacy headers and Matomo's keyword anonymization rules).
- Note on self-hosted instances: MATOMO_URL may point to localhost, an
- internal IP, or behind a reverse proxy on a private network. The script
- applies a light URL sanity check (scheme + host only) rather than the
- strict SSRF protection used for arbitrary web fetches, because self-hosted
- Matomo instances frequently live outside the public internet.
+ Note on self-hosted instances: every request to your Matomo instance goes
+ through claude-seo's SSRF guard, which refuses private and loopback
+ addresses by default. If your instance lives on such an address, name it in
+ the CLAUDE_SEO_LOCAL_TARGETS allowlist:
+
+ export CLAUDE_SEO_LOCAL_TARGETS="matomo.internal:8080"
+
+ Entries are host or host:port, comma-separated, matched exactly. The
+ allowlist is consulted only for the top-level instance URL; redirects and
+ subresources stay fail-closed, and cloud metadata addresses are refused even
+ when listed. See SECURITY.md.
VERIFY CONFIGURATION:
"${{CLAUDE_PLUGIN_ROOT}}/scripts/claude-seo" run matomo_auth.py --check
@@ -349,9 +480,24 @@ def main() -> int:
action="store_true",
help="Output as JSON",
)
+ parser.add_argument(
+ "--local-target-hint",
+ metavar="URL",
+ help=(
+ "Print the CLAUDE_SEO_LOCAL_TARGETS line needed to reach URL when it "
+ "resolves to a private address, and nothing otherwise. Used by the "
+ "extension installers."
+ ),
+ )
args = parser.parse_args()
+ if args.local_target_hint:
+ url = _normalize_instance_url(args.local_target_hint)
+ if url and resolves_to_private_address(url):
+ print(_local_targets_hint(instance_endpoint(url)))
+ return 0
+
if args.setup:
print_setup_instructions()
return 0
diff --git a/scripts/matomo_report.py b/scripts/matomo_report.py
index 40f7a76..604c883 100644
--- a/scripts/matomo_report.py
+++ b/scripts/matomo_report.py
@@ -36,10 +36,13 @@ if _SCRIPTS_DIR not in sys.path:
sys.path.insert(0, _SCRIPTS_DIR)
try:
from matomo_auth import (
+ MatomoRequestRefused,
get_matomo_site_id,
get_matomo_token,
get_matomo_url,
+ instance_endpoint,
load_config,
+ post_to_instance,
)
except ImportError:
print("Error: matomo_auth.py required in scripts/", file=sys.stderr)
@@ -77,10 +80,13 @@ def _envelope(status: str, data: Any = None, error: Optional[str] = None,
def _request(url: str, token: str, params: dict, timeout: int = DEFAULT_TIMEOUT) -> dict:
"""
- POST to Matomo with token_auth in body.
+ POST to Matomo with token_auth in body, through the url_safety pinned helpers.
Matomo accepts both GET and POST. POST keeps the token out of URLs and
- access logs.
+ access logs. ``matomo_auth.post_to_instance`` applies the SSRF guard: the
+ endpoint is validated and DNS-pinned, ``CLAUDE_SEO_LOCAL_TARGETS`` is the
+ only way a private instance is reached, and a redirect off the instance is
+ refused rather than followed.
Returns:
Standard response envelope; on Matomo API ``result=error`` payloads,
@@ -91,14 +97,11 @@ def _request(url: str, token: str, params: dict, timeout: int = DEFAULT_TIMEOUT)
body["format"] = "JSON"
body["token_auth"] = token
- headers = {"User-Agent": "ClaudeSEO/2.2.5"}
try:
- resp = requests.post(
- f"{url.rstrip('/')}/index.php",
- data=body,
- headers=headers,
- timeout=timeout,
- )
+ resp = post_to_instance(instance_endpoint(url), body, timeout=timeout)
+ except MatomoRequestRefused as e:
+ return _envelope("error", None, _redact(str(e)),
+ method=params.get("method"))
except requests.exceptions.Timeout:
return _envelope("error", None,
f"Matomo request timed out after {timeout}s")
@@ -537,10 +540,10 @@ def keywords_report(site_id: str, url: str, token: str,
def check_command(site_id_override: Optional[str] = None) -> dict:
"""Lightweight probe: who am I + version, used by --check subcommand."""
- from matomo_auth import _probe_version, _sanity_check_instance_url
+ from matomo_auth import _normalize_instance_url, _probe_version
config = load_config()
- url = _sanity_check_instance_url(config.get("matomo_url") or "")
+ url = _normalize_instance_url(config.get("matomo_url") or "")
token = config.get("matomo_token")
site_id = site_id_override or config.get("matomo_site_id")
diff --git a/tests/test_matomo_report.py b/tests/test_matomo_report.py
index ec0849b..e7a2ce6 100644
--- a/tests/test_matomo_report.py
+++ b/tests/test_matomo_report.py
@@ -4,7 +4,9 @@ Covers:
- Envelope shape (status / data / error / metadata)
- Auth probe (HTTP error classes mapped to friendly error messages)
- Token never appears in output / URL parameters
-- URL sanity check (allows self-hosted, rejects malformed)
+- URL shape check (allows self-hosted, rejects malformed)
+- SSRF: every request goes through url_safety's pinned helpers; a private
+ instance needs CLAUDE_SEO_LOCAL_TARGETS; redirects off the instance refused
- Env-var and config-file credential loading (env wins over file when both set)
- Args / CLI error paths surface a structured error envelope
- Token redaction of incoming Matomo ``result=error`` messages
@@ -12,7 +14,9 @@ Covers:
from __future__ import annotations
+import contextlib
import json
+import socket
import sys
from pathlib import Path
from unittest.mock import Mock, patch
@@ -24,8 +28,10 @@ sys.path.insert(0, str(ROOT / "scripts"))
import matomo_auth # noqa: E402
import matomo_report # noqa: E402
+import url_safety # noqa: E402
SECRET_TOKEN = "abcdef0123456789abcdef0123456789"
+PUBLIC_IP = "93.184.216.34"
@pytest.fixture(autouse=True)
@@ -46,12 +52,68 @@ def _isolated_credentials(monkeypatch, tmp_path):
)
-def _mock_response(status_code: int, body) -> Mock:
+def _mock_response(status_code: int, body, headers=None) -> Mock:
resp = Mock(status_code=status_code, text=json.dumps(body))
resp.json.return_value = body
+ resp.headers = headers or {}
return resp
+def _patch_session(response=None, side_effect=None):
+ """Stub the DNS-pinned session so transport tests stay offline.
+
+ Patches ``matomo_auth.safe_requests_session``, the single seam every
+ Matomo request passes through. The SSRF behaviour of that seam is covered
+ separately by the tests that let the real ``url_safety`` run.
+ """
+ session = Mock()
+ if side_effect is not None:
+ session.post.side_effect = side_effect
+ else:
+ session.post.return_value = response
+
+ @contextlib.contextmanager
+ def fake_session(url):
+ fake_session.url = url
+ yield session
+
+ with patch.object(matomo_auth, "safe_requests_session", fake_session):
+ yield session, fake_session
+
+
+def _real_guard(monkeypatch, resolved_ip=PUBLIC_IP, response=None):
+ """Let ``url_safety`` run for real, with DNS and the socket write stubbed.
+
+ ``requests.Session.post`` is patched at the class level so the pinned
+ session is genuinely constructed and ``validate_url_strict`` genuinely
+ decides, but nothing leaves the machine.
+ """
+ for var in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy",
+ "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"):
+ monkeypatch.delenv(var, raising=False)
+
+ def fake_getaddrinfo(host, port, *args, **kwargs):
+ return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "",
+ (resolved_ip, port or 80))]
+
+ monkeypatch.setattr(url_safety.socket, "getaddrinfo", fake_getaddrinfo)
+ post = Mock(return_value=response if response is not None
+ else _mock_response(200, {"value": "5.13.0"}))
+
+ def _unguarded(*args, **kwargs):
+ raise AssertionError(
+ "a Matomo request bypassed url_safety: module-level requests.post "
+ "was called instead of the pinned session"
+ )
+
+ with patch.object(matomo_report.requests.Session, "post", post), \
+ patch.object(matomo_report.requests, "post", _unguarded), \
+ patch.object(matomo_auth.requests, "post", _unguarded):
+ yield post
+
+
def _ok_envelope(data=None, method=None):
return {
"status": "success",
@@ -76,21 +138,21 @@ def test_envelope_shape_and_metadata_source():
assert "timestamp" in env["metadata"]
-def test_url_sanity_allows_self_hosted_https():
- assert matomo_auth._sanity_check_instance_url("https://analytics.example.com") \
+def test_url_shape_check_allows_self_hosted_https():
+ assert matomo_auth._normalize_instance_url("https://analytics.example.com") \
== "https://analytics.example.com"
- assert matomo_auth._sanity_check_instance_url("http://localhost:8080/") \
+ assert matomo_auth._normalize_instance_url("http://localhost:8080/") \
== "http://localhost:8080"
- assert matomo_auth._sanity_check_instance_url("https://10.0.0.5/matomo/") \
+ assert matomo_auth._normalize_instance_url("https://10.0.0.5/matomo/") \
== "https://10.0.0.5/matomo"
-def test_url_sanity_rejects_malformed():
- assert matomo_auth._sanity_check_instance_url("") is None
- assert matomo_auth._sanity_check_instance_url("not-a-url") is None
- assert matomo_auth._sanity_check_instance_url("ftp://example.com") is None
+def test_url_shape_check_rejects_malformed():
+ assert matomo_auth._normalize_instance_url("") is None
+ assert matomo_auth._normalize_instance_url("not-a-url") is None
+ assert matomo_auth._normalize_instance_url("ftp://example.com") is None
# Userinfo in URL would leak credentials if accidentally configured.
- assert matomo_auth._sanity_check_instance_url(
+ assert matomo_auth._normalize_instance_url(
"https://user:[email protected]") is None
@@ -143,7 +205,7 @@ def test_check_credentials_probes_version(monkeypatch, tmp_path):
monkeypatch.setenv("MATOMO_SITE_ID", "1")
resp = _mock_response(200, "5.1.2")
- with patch.object(matomo_auth.requests, "post", return_value=resp) as post:
+ with _patch_session(resp) as (post_session, _):
status = matomo_auth.check_credentials()
assert status["available"] is True
@@ -152,7 +214,7 @@ def test_check_credentials_probes_version(monkeypatch, tmp_path):
assert status["verified"] is True
assert status["version"] == "5.1.2"
# Token must be in POST body, never in URL.
- call = post.call_args
+ call = post_session.post.call_args
assert call.kwargs["data"]["token_auth"] == SECRET_TOKEN
assert "token_auth" not in call.kwargs.get("params", {})
@@ -164,7 +226,7 @@ def test_check_credentials_handles_matomo5_version_object(monkeypatch, tmp_path)
monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)
resp = _mock_response(200, {"value": "5.13.0"})
- with patch.object(matomo_auth.requests, "post", return_value=resp):
+ with _patch_session(resp):
status = matomo_auth.check_credentials()
assert status["available"] is True
assert status["version"] == "5.13.0"
@@ -175,7 +237,7 @@ def test_check_credentials_surfaces_auth_failure(monkeypatch, tmp_path):
monkeypatch.setenv("MATOMO_URL", "https://analytics.example.com")
monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)
resp = _mock_response(401, {"result": "error", "message": "no access"})
- with patch.object(matomo_auth.requests, "post", return_value=resp):
+ with _patch_session(resp):
status = matomo_auth.check_credentials()
assert status["available"] is False
assert "authentication" in status["error"].lower() or "auth" in status["error"].lower()
@@ -187,10 +249,9 @@ def test_check_credentials_surfaces_connection_error(monkeypatch, tmp_path):
monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(tmp_path / "missing.json"))
monkeypatch.setenv("MATOMO_URL", "https://analytics.example.com")
monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)
- with patch.object(
- matomo_auth.requests, "post",
- side_effect=matomo_auth.requests.exceptions.ConnectionError("refused"),
- ):
+ with _patch_session(side_effect=matomo_auth.requests.exceptions.ConnectionError(
+ "refused"
+ )):
status = matomo_auth.check_credentials()
assert status["available"] is False
assert "connection" in status["error"].lower()
@@ -208,7 +269,7 @@ def test_token_redaction_strips_query_params():
def test_request_maps_matomo_result_error_to_envelope():
resp = _mock_response(200, {"result": "error",
"message": "No data available"})
- with patch.object(matomo_report.requests, "post", return_value=resp):
+ with _patch_session(resp):
env = matomo_report._request("https://m.test", "tok", {"method": "X"})
assert env["status"] == "error"
assert "No data available" in env["error"]
@@ -218,24 +279,23 @@ def test_request_maps_matomo_result_error_to_envelope():
def test_request_redacts_token_in_matomo_error():
leaked = "Bad token_auth=" + SECRET_TOKEN + " for site"
resp = _mock_response(200, {"result": "error", "message": leaked})
- with patch.object(matomo_report.requests, "post", return_value=resp):
+ with _patch_session(resp):
env = matomo_report._request("https://m.test", "tok", {"method": "X"})
assert SECRET_TOKEN not in (env.get("error") or "")
def test_request_maps_401_to_friendly_error():
resp = _mock_response(401, {})
- with patch.object(matomo_report.requests, "post", return_value=resp):
+ with _patch_session(resp):
env = matomo_report._request("https://m.test", "tok", {"method": "X"})
assert env["status"] == "error"
assert "authentication" in env["error"].lower() or "token" in env["error"].lower()
def test_request_maps_timeout_to_friendly_error():
- with patch.object(
- matomo_report.requests, "post",
- side_effect=matomo_report.requests.exceptions.Timeout("read timeout"),
- ):
+ with _patch_session(side_effect=matomo_report.requests.exceptions.Timeout(
+ "read timeout"
+ )):
env = matomo_report._request("https://m.test", "tok", {"method": "X"})
assert env["status"] == "error"
assert "timed out" in env["error"].lower() or "timeout" in env["error"].lower()
@@ -243,12 +303,14 @@ def test_request_maps_timeout_to_friendly_error():
def test_request_does_not_echo_token_in_call_args():
resp = _mock_response(200, "5.1.2")
- with patch.object(matomo_report.requests, "post", return_value=resp) as post:
+ with _patch_session(resp) as (session, _):
matomo_report._request("https://m.test", SECRET_TOKEN, {"method": "X"})
- call = post.call_args
+ call = session.post.call_args
assert call.kwargs["data"]["token_auth"] == SECRET_TOKEN
# No query params; token is POST body only.
assert "params" not in call.kwargs or not call.kwargs["params"]
+ # And never in the URL either.
+ assert SECRET_TOKEN not in call.args[0]
def test_cli_errors_when_url_missing(monkeypatch):
@@ -256,11 +318,11 @@ def test_cli_errors_when_url_missing(monkeypatch):
for k in ("MATOMO_URL", "MATOMO_API_TOKEN", "MATOMO_SITE_ID",
"MATOMO_TOKEN", "MATOMO_IDSITE"):
monkeypatch.delenv(k, raising=False)
- with patch.object(matomo_auth.requests, "post") as post:
+ with _patch_session(_mock_response(200, {"value": "5.13.0"})) as (post_session, _):
env = matomo_auth.check_credentials()
assert env["available"] is False
assert "url" in env["error"].lower()
- post.assert_not_called()
+ post_session.post.assert_not_called()
def test_organic_report_builds_daily_and_pages(monkeypatch):
@@ -289,8 +351,7 @@ def test_organic_report_builds_daily_and_pages(monkeypatch):
_mock_response(200, daily),
_mock_response(200, pages),
]
- with patch.object(matomo_report.requests, "post",
- side_effect=responses):
+ with _patch_session(side_effect=responses):
env = matomo_report.organic_traffic_report("1", "https://m.test",
SECRET_TOKEN, days=2)
assert env["status"] == "success"
@@ -321,8 +382,7 @@ def test_device_breakdown_handles_matomo5_array(monkeypatch):
{"label": "Tablet", "nb_visits": 20, "nb_actions": 60,
"bounce_count": 3, "sum_daily_nb_uniq_visitors": 18},
]
- with patch.object(matomo_report.requests, "post",
- return_value=_mock_response(200, raw)):
+ with _patch_session(_mock_response(200, raw)):
env = matomo_report.device_breakdown("1", "https://m.test",
SECRET_TOKEN, days=7)
assert env["status"] == "success"
@@ -342,8 +402,7 @@ def test_country_breakdown_handles_matomo5_array(monkeypatch):
{"label": "Vereinigte Staaten", "code": "us", "nb_visits": 79,
"sum_daily_nb_uniq_visitors": 70},
]
- with patch.object(matomo_report.requests, "post",
- return_value=_mock_response(200, raw)):
+ with _patch_session(_mock_response(200, raw)):
env = matomo_report.country_breakdown("1", "https://m.test",
SECRET_TOKEN, days=7, limit=5)
assert env["status"] == "success"
@@ -368,14 +427,13 @@ def test_referrers_report_uses_matomo5_method_and_shapes(monkeypatch):
{"label": "Google", "nb_visits": 142},
{"label": "Bing", "nb_visits": 95},
]
- with patch.object(matomo_report.requests, "post",
- side_effect=[_mock_response(200, types),
- _mock_response(200, engines)]) as post:
+ with _patch_session(side_effect=[_mock_response(200, types),
+ _mock_response(200, engines)]) as (post_session, _):
env = matomo_report.referrers_report("1", "https://m.test",
SECRET_TOKEN, days=7)
assert env["status"] == "success"
# Correct Matomo 4/5 method name (getReferrersType does not exist).
- first_method = post.call_args_list[0].kwargs["data"]["method"]
+ first_method = post_session.post.call_args_list[0].kwargs["data"]["method"]
assert first_method == "Referrers.getReferrerType"
channels = env["data"]["channels"]
assert [c["channel_code"] for c in channels] == ["direct", "search"]
@@ -402,8 +460,7 @@ def test_keywords_report_flags_anonymized_share(monkeypatch):
{"label": "kw2", "nb_visits": 5,
"segment": "referrerType==search;referrerKeyword==kw2"},
]
- with patch.object(matomo_report.requests, "post",
- return_value=_mock_response(200, raw)):
+ with _patch_session(_mock_response(200, raw)):
env = matomo_report.keywords_report("1", "https://m.test",
SECRET_TOKEN, days=7, limit=10)
assert env["status"] == "success"
@@ -426,8 +483,7 @@ def test_keywords_report_english_anonymized_label(monkeypatch):
{"label": "best seo tool", "nb_visits": 30,
"segment": "referrerType==search;referrerKeyword==best%20seo%20tool"},
]
- with patch.object(matomo_report.requests, "post",
- return_value=_mock_response(200, raw)):
+ with _patch_session(_mock_response(200, raw)):
env = matomo_report.keywords_report("1", "https://m.test",
SECRET_TOKEN, days=7, limit=10)
data = env["data"]
@@ -440,8 +496,7 @@ def test_device_breakdown_supports_legacy_dict_shape(monkeypatch):
"desktop": {"label": "Desktop", "nb_visits": 100,
"nb_uniq_visitors": 80, "bounce_rate": 0.4},
}
- with patch.object(matomo_report.requests, "post",
- return_value=_mock_response(200, raw)):
+ with _patch_session(_mock_response(200, raw)):
env = matomo_report.device_breakdown("1", "https://m.test",
SECRET_TOKEN, days=7)
assert env["status"] == "success"
@@ -464,10 +519,7 @@ def test_main_json_emits_envelope(monkeypatch):
monkeypatch.setenv("MATOMO_URL", "https://m.test")
monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)
monkeypatch.setenv("MATOMO_SITE_ID", "1")
- with patch.object(
- matomo_auth.requests, "post",
- return_value=_mock_response(200, "5.1.2"),
- ), patch("sys.argv",
+ with _patch_session(_mock_response(200, "5.1.2")), patch("sys.argv",
["matomo_report.py", "check", "--json"]):
rc = matomo_report.main()
assert rc == 0
@@ -482,7 +534,7 @@ def test_check_command_honors_site_id_override(monkeypatch, tmp_path):
}))
monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(config_file))
resp = _mock_response(200, {"value": "5.13.0"})
- with patch.object(matomo_auth.requests, "post", return_value=resp):
+ with _patch_session(resp):
env = matomo_report.check_command(site_id_override="5")
assert env["status"] == "success"
assert env["data"]["site_id"] == "5"
@@ -497,3 +549,141 @@ def test_main_missing_site_id_exits_one(monkeypatch, capsys):
assert rc == 1
captured = capsys.readouterr()
assert "--site-id" in captured.err or "MATOMO_SITE_ID" in captured.err
+
+
+# --------------------------------------------------------------------------
+# SSRF: every request to the Matomo instance goes through url_safety.
+# These let the real guard run; only DNS and the socket write are stubbed.
+# --------------------------------------------------------------------------
+
+
+def test_public_instance_goes_through_the_pinned_helpers(monkeypatch):
+ """A public MATOMO_URL is validated, pinned, and reached."""
+ with _real_guard(monkeypatch) as post:
+ env = matomo_report._request("https://analytics.example.com",
+ SECRET_TOKEN, {"method": "API.getX"})
+ assert env["status"] == "success"
+ assert env["data"] == {"value": "5.13.0"}
+ # Went out through the pinned session, not a bare requests.post.
+ assert post.call_count == 1
+ assert post.call_args.args[0] == "https://analytics.example.com/index.php"
+ assert post.call_args.kwargs["allow_redirects"] is False
+
+
+def test_private_instance_is_refused_without_the_allowlist(monkeypatch):
+ """A self-hosted instance on a private address fails closed by default."""
+ monkeypatch.delenv(matomo_auth.LOCAL_TARGETS_ENV, raising=False)
+ with _real_guard(monkeypatch, resolved_ip="10.0.0.5") as post:
+ env = matomo_report._request("http://10.0.0.5:8080", SECRET_TOKEN,
+ {"method": "API.getX"})
+ assert env["status"] == "error"
+ assert post.call_count == 0
+ assert matomo_auth.LOCAL_TARGETS_ENV in env["error"]
+ assert "10.0.0.5:8080" in env["error"]
+ assert SECRET_TOKEN not in env["error"]
+
+
+def test_private_instance_is_accepted_with_the_allowlist(monkeypatch):
+ """CLAUDE_SEO_LOCAL_TARGETS is the supported route to a private instance."""
+ monkeypatch.setenv(matomo_auth.LOCAL_TARGETS_ENV, "10.0.0.5:8080")
+ with _real_guard(monkeypatch, resolved_ip="10.0.0.5") as post:
+ env = matomo_report._request("http://10.0.0.5:8080", SECRET_TOKEN,
+ {"method": "API.getX"})
+ assert env["status"] == "success"
+ assert post.call_count == 1
+ assert post.call_args.args[0] == "http://10.0.0.5:8080/index.php"
+
+
+def test_allowlist_entry_does_not_open_a_different_private_host(monkeypatch):
+ """The allowlist matches exactly; a neighbour on the same subnet stays closed."""
+ monkeypatch.setenv(matomo_auth.LOCAL_TARGETS_ENV, "10.0.0.5:8080")
+ with _real_guard(monkeypatch, resolved_ip="10.0.0.6") as post:
+ env = matomo_report._request("http://10.0.0.6:8080", SECRET_TOKEN,
+ {"method": "API.getX"})
+ assert env["status"] == "error"
+ assert post.call_count == 0
+
+
+def test_redirect_off_the_instance_is_refused(monkeypatch):
+ """A 30x to another host is refused, not followed: the pin does not cover it."""
+ redirect = _mock_response(
+ 302, {}, headers={"Location": "https://attacker.example.com/index.php"}
+ )
+ with _real_guard(monkeypatch, response=redirect) as post:
+ env = matomo_report._request("https://analytics.example.com",
+ SECRET_TOKEN, {"method": "API.getX"})
+ assert env["status"] == "error"
+ assert "attacker.example.com" in env["error"]
+ assert "redirect" in env["error"].lower()
+ assert post.call_args.kwargs["allow_redirects"] is False
+ assert SECRET_TOKEN not in env["error"]
+
+
+def test_auth_probe_also_goes_through_the_guard(monkeypatch, tmp_path):
+ """matomo_auth --check uses the same pinned path, not a bare requests.post."""
+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(tmp_path / "missing.json"))
+ monkeypatch.setenv("MATOMO_URL", "http://10.0.0.5:8080")
+ monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)
+ monkeypatch.delenv(matomo_auth.LOCAL_TARGETS_ENV, raising=False)
+ with _real_guard(monkeypatch, resolved_ip="10.0.0.5") as post:
+ status = matomo_auth.check_credentials()
+ assert status["available"] is False
+ assert post.call_count == 0
+ assert matomo_auth.LOCAL_TARGETS_ENV in status["error"]
+ assert SECRET_TOKEN not in status["error"]
+
+
+def test_token_never_reaches_an_error_string_or_stderr(monkeypatch, capsys):
+ """The token stays out of every error path, envelope, and stream.
+
+ Three shapes at once: a Matomo error payload that echoes the token back,
+ a transport exception whose message carries it, and the CLI's own stderr.
+ """
+ leaked = f"Invalid token_auth={SECRET_TOKEN}&idSite=1"
+ resp = _mock_response(200, {"result": "error", "message": leaked})
+ with _patch_session(resp):
+ env = matomo_report._request("https://m.test", SECRET_TOKEN,
+ {"method": "API.getX"})
+ assert SECRET_TOKEN not in json.dumps(env)
+ assert "<redacted>" in env["error"]
+
+ boom = matomo_report.requests.exceptions.ConnectionError(
+ f"failed to POST token_auth={SECRET_TOKEN}"
+ )
+ with _patch_session(side_effect=boom):
+ env = matomo_report._request("https://m.test", SECRET_TOKEN,
+ {"method": "API.getX"})
+ assert SECRET_TOKEN not in json.dumps(env)
+
+ assert matomo_auth.redact(leaked) == "Invalid token_auth=<redacted>&idSite=1"
+
+ monkeypatch.setenv("MATOMO_URL", "http://10.0.0.5:8080")
+ monkeypatch.setenv("MATOMO_API_TOKEN", SECRET_TOKEN)
+ monkeypatch.setenv("MATOMO_SITE_ID", "1")
+ monkeypatch.delenv(matomo_auth.LOCAL_TARGETS_ENV, raising=False)
+ with _real_guard(monkeypatch, resolved_ip="10.0.0.5"), patch(
+ "sys.argv", ["matomo_report.py", "organic"]
+ ):
+ rc = matomo_report.main()
+ assert rc == 1
+ captured = capsys.readouterr()
+ assert SECRET_TOKEN not in captured.out
+ assert SECRET_TOKEN not in captured.err
+ assert matomo_auth.LOCAL_TARGETS_ENV in captured.err
+
+
+def test_resolves_to_private_address_drives_the_installer_hint(monkeypatch):
+ """The installers use this to decide whether to print the allowlist hint."""
+ def fake_getaddrinfo(host, port, *args, **kwargs):
+ ip = "10.1.2.3" if host == "matomo.internal" else PUBLIC_IP
+ return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "",
+ (ip, port or 80))]
+
+ monkeypatch.setattr(matomo_auth.socket, "getaddrinfo", fake_getaddrinfo)
+ assert matomo_auth.resolves_to_private_address("http://matomo.internal:8080")
+ assert not matomo_auth.resolves_to_private_address("https://analytics.example.com")
+ # IP literals need no DNS at all.
+ assert matomo_auth.resolves_to_private_address("http://127.0.0.1:8080")
+ assert not matomo_auth.resolves_to_private_address("https://93.184.216.34")
+ # A malformed URL is not a private address.
+ assert not matomo_auth.resolves_to_private_address("not-a-url")