Hermes Agent commited on
Commit
428df42
·
1 Parent(s): 9ade7f9

fix(shortener): set explicit User-Agent to bypass Cloudflare WAF

Browse files

The AI QR Space's outgoing POST to URL_SHORTENER_API_URL was being
blocked by Cloudflare WAF (Error 1010) because Python's urllib defaults
to User-Agent 'Python-urllib/3.x', which Cloudflare classifies as a
bot/script.

Symptom (visible in the Space UI):
'short link unavailable: HTTP Error 403. Using normalized URL instead.'

The shortener (qrcut.co) and its API key were both healthy. The block
happens at the Cloudflare edge before the request reaches the upstream
kvm9276 VPS. Same WAF error reproduced from this VM with curl and
User-Agent 'Python-urllib/3.10' (Cloudflare ray-id a0a8299b1ed5d0d1,
Error 1010). With any other UA, the same request returns 200.

Fix: set an explicit User-Agent on the urllib request, shaped like a
real operator/client, so Cloudflare does not flag it.

Regression test: tests/inference/test_shortener_ua.py parses app.py
textually and asserts (1) the request_headers dict is present, (2) it
contains a User-Agent entry, (3) the UA is not the urllib default.
Test runs in 2ms, no ML deps needed. TDD-verified: removing the
User-Agent line makes the test fail.

Verified live 2026-06-12: 4-probe recipe
1. qrcut health -> 200
2. POST /shorten (curl UA) -> 200 + short URL
3. GET /<code> -> 302
4. POST /shorten (Python-urllib UA) -> 403 WAF Error 1010

ai_qr_generator Supabase rows: zero new writes since 2026-06-08
19:13 UTC (last good write), aligning with the Cloudflare rule
change. After this patch + Space rebuild, the next generation should
hit /shorten successfully.

Refs: master_plan.md 'qrcut VPS migration executed' section; live probe
on 2026-06-12 from azureuser@second-brain-hermes-vm.

Files changed (2) hide show
  1. app.py +6 -0
  2. tests/inference/test_shortener_ua.py +111 -0
app.py CHANGED
@@ -785,10 +785,16 @@ def _maybe_shorten_url_for_qr(
785
  }
786
 
787
  request_body = json.dumps({"url": str(original_input or ""), "reuse_existing": False}).encode("utf-8")
 
 
 
 
 
788
  request_headers = {
789
  "Content-Type": "application/json",
790
  "X-API-Key": URL_SHORTENER_API_KEY,
791
  "X-Source-App": caller_app,
 
792
  }
793
  try:
794
  print(
 
785
  }
786
 
787
  request_body = json.dumps({"url": str(original_input or ""), "reuse_existing": False}).encode("utf-8")
788
+ # Set an explicit User-Agent: urllib's default "Python-urllib/3.x" is blocked
789
+ # by Cloudflare WAF (Error 1010) at the qrcut.co edge, which surfaced as
790
+ # "HTTP Error 403" → "short link unavailable, using normal link" in the UI.
791
+ # A space/operator-shaped UA is enough to pass the WAF; the shortener does
792
+ # not inspect the UA. See CHANGELOG / 2026-06-12 shortener-403 note.
793
  request_headers = {
794
  "Content-Type": "application/json",
795
  "X-API-Key": URL_SHORTENER_API_KEY,
796
  "X-Source-App": caller_app,
797
+ "User-Agent": "AI-QR-Code-Generator/1.0 (+https://huggingface.co/spaces/Oysiyl/AI-QR-code-generator)",
798
  }
799
  try:
800
  print(
tests/inference/test_shortener_ua.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Regression test for the 2026-06-12 qrcut.co Cloudflare WAF 403.
3
+
4
+ The AI QR Space's outgoing POST to URL_SHORTENER_API_URL was being blocked
5
+ by Cloudflare WAF (Error 1010) because Python's urllib defaults to
6
+ User-Agent "Python-urllib/3.x", which Cloudflare classifies as a bot/script.
7
+
8
+ The fix: set an explicit User-Agent in the request headers inside
9
+ `_shortener_posted` in app.py. The shortener (qrcut.co) does not inspect
10
+ the UA; the Cloudflare edge rule is the relevant gate.
11
+
12
+ This test does NOT import app.py or run Gradio. The Space's app.py pulls
13
+ in torch/diffusers/gradio, none of which is installed in the test
14
+ environment. Instead, the test reads app.py as a text file and asserts
15
+ the structural property: inside `_shortener_posted`, the
16
+ `request_headers` dict must include a `User-Agent` entry that is NOT the
17
+ urllib default.
18
+
19
+ This is a fast, dependency-free, hermetic regression test that catches
20
+ the exact bug class: "the UA was reset / the dict was refactored / the
21
+ patch was reverted". If a future refactor removes the User-Agent entry,
22
+ this test fails before the Space is rebuilt.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import os
27
+ import re
28
+ import unittest
29
+
30
+ REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
31
+ APP_PY = os.path.join(REPO_ROOT, "app.py")
32
+
33
+ # Default UA Python's urllib sets when none is provided. Cloudflare WAF
34
+ # blocks requests carrying exactly this string (Error 1010) at the
35
+ # qrcut.co edge. See CHANGELOG / 2026-06-12 shortener-403 note.
36
+ URLLIB_DEFAULT_UA_RE = re.compile(r"Python-urllib/\d+\.\d+")
37
+
38
+
39
+ def _extract_request_headers_block(source: str) -> str | None:
40
+ """Find the request_headers dict literal inside _shortener_posted.
41
+
42
+ Strategy: locate the function definition, then slice the first
43
+ `request_headers = { ... }` assignment inside it. We bound the slice
44
+ by the next `try:` or top-level statement to avoid eating unrelated
45
+ code.
46
+ """
47
+ # Find the function start
48
+ m = re.search(r"^def\s+_maybe_shorten_url_for_qr\s*\(", source, re.MULTILINE)
49
+ if not m:
50
+ return None
51
+ # Find the next `request_headers = {` after the def
52
+ after = source.find('request_headers', m.end())
53
+ if after == -1:
54
+ return None
55
+ # Find the opening brace on the same line
56
+ brace = source.find('{', after)
57
+ if brace == -1:
58
+ return None
59
+ # Find the matching closing brace
60
+ depth = 0
61
+ i = brace
62
+ while i < len(source):
63
+ c = source[i]
64
+ if c == '{':
65
+ depth += 1
66
+ elif c == '}':
67
+ depth -= 1
68
+ if depth == 0:
69
+ return source[brace : i + 1]
70
+ i += 1
71
+ return None
72
+
73
+
74
+ class ShortenerUserAgentRegression(unittest.TestCase):
75
+ def setUp(self) -> None:
76
+ with open(APP_PY, encoding="utf-8") as f:
77
+ self.source = f.read()
78
+
79
+ def test_request_headers_dict_present(self) -> None:
80
+ block = _extract_request_headers_block(self.source)
81
+ self.assertIsNotNone(
82
+ block,
83
+ "Could not locate `request_headers = { ... }` inside _maybe_shorten_url_for_qr. "
84
+ "Was the function refactored? Update or remove this test.",
85
+ )
86
+
87
+ def test_user_agent_header_is_set(self) -> None:
88
+ block = _extract_request_headers_block(self.source) or ""
89
+ self.assertIn(
90
+ "User-Agent",
91
+ block,
92
+ "request_headers in _shortener_posted must include a User-Agent entry. "
93
+ "Cloudflare WAF (Error 1010) blocks urllib's default User-Agent "
94
+ "'Python-urllib/3.x' at the qrcut.co edge, causing HTTP 403 → "
95
+ "'short link unavailable, using normal link' in the UI.",
96
+ )
97
+
98
+ def test_user_agent_is_not_urllib_default(self) -> None:
99
+ block = _extract_request_headers_block(self.source) or ""
100
+ # The literal "Python-urllib/..." must not appear in the headers dict.
101
+ match = URLLIB_DEFAULT_UA_RE.search(block)
102
+ if match is not None:
103
+ self.fail(
104
+ f"User-Agent in request_headers is the urllib default {match.group(0)!r}, "
105
+ "which is exactly what Cloudflare WAF blocks. Set a real "
106
+ "User-Agent (e.g. 'AI-QR-Code-Generator/1.0 (+https://huggingface.co/spaces/...)')."
107
+ )
108
+
109
+
110
+ if __name__ == "__main__":
111
+ unittest.main()