BlueGit

timfa posprint

Add local noconfirm test harness and optional localhost referrer.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-07-22 · 3 months ago

Hash
7cc2ff866f4de00911b07165d917b30f9d7ff8ec
Parent
fa182b1a
5 files changed +155 −12
docs/POSPRINT-URL.md +1 −1
@@ -50,7 +50,7 @@ The OS protocol handler only receives the URL string — not the browser Referer
50 50
51 51 Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
52 52
53 Localhost / private IP verification URLs are blocked.
53 Localhost / private IP verification URLs are blocked by default. For local harnesses only, set `POSPRINT_ALLOW_LOCAL_REFERRER=1` (see `scripts/test-noconfirm/`).
54 54
55 55 ---
56 56
@@ -50,7 +50,7 @@ The OS protocol handler only receives the URL string — not the browser Referer
50
50
51Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
51Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
52
52
53Localhost / private IP verification URLs are blocked.
53Localhost / private IP verification URLs are blocked by default. For local harnesses only, set `POSPRINT_ALLOW_LOCAL_REFERRER=1` (see `scripts/test-noconfirm/`).
54
54
55---
55---
56
56
examples/noconfirm-demo.pos added +9 −0
@@ -0,0 +1,9 @@
1 {
2 "version": 1,
3 "metadata": {
4 "title": "noconfirm demo",
5 "page_width_mm": 53,
6 "chars_per_line": 32
7 },
8 "body": "# noconfirm OK\n\nVerified print demo\n\n@cut\n"
9 }
@@ -0,0 +1,9 @@
1{
2 "version": 1,
3 "metadata": {
4 "title": "noconfirm demo",
5 "page_width_mm": 53,
6 "chars_per_line": 32
7 },
8 "body": "# noconfirm OK\n\nVerified print demo\n\n@cut\n"
9}
scripts/test-noconfirm/README.md added +52 −0
@@ -0,0 +1,52 @@
1 # Local noconfirm + referrer test
2
3 Docs: [docs/POSPRINT-URL.md](../../docs/POSPRINT-URL.md).
4
5 Production blocks localhost referrers. For this harness set:
6
7 ```powershell
8 $env:POSPRINT_ALLOW_LOCAL_REFERRER = "1"
9 ```
10
11 ## 1. Start the verify server
12
13 ```powershell
14 python scripts/test-noconfirm/server.py
15 ```
16
17 - `GET http://127.0.0.1:8765/verify?code=84923` → **200**
18 - `GET http://127.0.0.1:8765/verify?code=wrong` → **403**
19
20 ## 2. Build a debug posprint with the feature branch / master
21
22 ```powershell
23 cargo build
24 $env:POSPRINT_ALLOW_LOCAL_REFERRER = "1"
25 ```
26
27 ## 3. Open the test URL
28
29 Generate (from repo root):
30
31 ```powershell
32 cargo run --quiet -- link examples/noconfirm-demo.pos
33 ```
34
35 Then append (PowerShell):
36
37 ```powershell
38 $base = cargo run --quiet -- link examples/noconfirm-demo.pos
39 $ref = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=84923")
40 $url = "$base&noconfirm=1&referrer=$ref"
41 $url
42 Start-Process $url
43 ```
44
45 First run: trust dialog for `127.0.0.1`. After **Trust and print**, the next open with the same URL should print without asking (while the server still returns 200).
46
47 Try a bad code to confirm refusal:
48
49 ```powershell
50 $refBad = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=nope")
51 Start-Process "$base&noconfirm=1&referrer=$refBad"
52 ```
@@ -0,0 +1,52 @@
1# Local noconfirm + referrer test
2
3Docs: [docs/POSPRINT-URL.md](../../docs/POSPRINT-URL.md).
4
5Production blocks localhost referrers. For this harness set:
6
7```powershell
8$env:POSPRINT_ALLOW_LOCAL_REFERRER = "1"
9```
10
11## 1. Start the verify server
12
13```powershell
14python scripts/test-noconfirm/server.py
15```
16
17- `GET http://127.0.0.1:8765/verify?code=84923` → **200**
18- `GET http://127.0.0.1:8765/verify?code=wrong` → **403**
19
20## 2. Build a debug posprint with the feature branch / master
21
22```powershell
23cargo build
24$env:POSPRINT_ALLOW_LOCAL_REFERRER = "1"
25```
26
27## 3. Open the test URL
28
29Generate (from repo root):
30
31```powershell
32cargo run --quiet -- link examples/noconfirm-demo.pos
33```
34
35Then append (PowerShell):
36
37```powershell
38$base = cargo run --quiet -- link examples/noconfirm-demo.pos
39$ref = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=84923")
40$url = "$base&noconfirm=1&referrer=$ref"
41$url
42Start-Process $url
43```
44
45First run: trust dialog for `127.0.0.1`. After **Trust and print**, the next open with the same URL should print without asking (while the server still returns 200).
46
47Try a bad code to confirm refusal:
48
49```powershell
50$refBad = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=nope")
51Start-Process "$base&noconfirm=1&referrer=$refBad"
52```
scripts/test-noconfirm/server.py added +56 −0
@@ -0,0 +1,56 @@
1 #!/usr/bin/env python3
2 """Minimal verify server for local noconfirm testing.
3
4 GET /verify?code=84923 -> 200
5 GET /verify?code=other -> 403
6 GET anything else -> 404
7
8 Run:
9 python scripts/test-noconfirm/server.py
10 """
11
12 from __future__ import annotations
13
14 from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
15 from urllib.parse import parse_qs, urlparse
16
17 HOST = "127.0.0.1"
18 PORT = 8765
19 VALID_CODE = "84923"
20
21
22 class Handler(BaseHTTPRequestHandler):
23 def log_message(self, fmt: str, *args) -> None:
24 print(f"[verify] {self.address_string()} {fmt % args}")
25
26 def do_GET(self) -> None:
27 parsed = urlparse(self.path)
28 if parsed.path.rstrip("/") != "/verify":
29 self._reply(404, "not found")
30 return
31 code = parse_qs(parsed.query).get("code", [None])[0]
32 if code == VALID_CODE:
33 self._reply(200, "ok")
34 else:
35 self._reply(403, "invalid code")
36
37 def _reply(self, status: int, body: str) -> None:
38 data = body.encode("utf-8")
39 self.send_response(status)
40 self.send_header("Content-Type", "text/plain; charset=utf-8")
41 self.send_header("Content-Length", str(len(data)))
42 self.end_headers()
43 self.wfile.write(data)
44
45
46 def main() -> None:
47 server = ThreadingHTTPServer((HOST, PORT), Handler)
48 print(f"Listening on http://{HOST}:{PORT}")
49 print(f"Valid: http://{HOST}:{PORT}/verify?code={VALID_CODE} -> 200")
50 print(f"Invalid: http://{HOST}:{PORT}/verify?code=wrong -> 403")
51 print("Ctrl+C to stop")
52 server.serve_forever()
53
54
55 if __name__ == "__main__":
56 main()
@@ -0,0 +1,56 @@
1#!/usr/bin/env python3
2"""Minimal verify server for local noconfirm testing.
3
4GET /verify?code=84923 -> 200
5GET /verify?code=other -> 403
6GET anything else -> 404
7
8Run:
9 python scripts/test-noconfirm/server.py
10"""
11
12from __future__ import annotations
13
14from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
15from urllib.parse import parse_qs, urlparse
16
17HOST = "127.0.0.1"
18PORT = 8765
19VALID_CODE = "84923"
20
21
22class Handler(BaseHTTPRequestHandler):
23 def log_message(self, fmt: str, *args) -> None:
24 print(f"[verify] {self.address_string()} {fmt % args}")
25
26 def do_GET(self) -> None:
27 parsed = urlparse(self.path)
28 if parsed.path.rstrip("/") != "/verify":
29 self._reply(404, "not found")
30 return
31 code = parse_qs(parsed.query).get("code", [None])[0]
32 if code == VALID_CODE:
33 self._reply(200, "ok")
34 else:
35 self._reply(403, "invalid code")
36
37 def _reply(self, status: int, body: str) -> None:
38 data = body.encode("utf-8")
39 self.send_response(status)
40 self.send_header("Content-Type", "text/plain; charset=utf-8")
41 self.send_header("Content-Length", str(len(data)))
42 self.end_headers()
43 self.wfile.write(data)
44
45
46def main() -> None:
47 server = ThreadingHTTPServer((HOST, PORT), Handler)
48 print(f"Listening on http://{HOST}:{PORT}")
49 print(f"Valid: http://{HOST}:{PORT}/verify?code={VALID_CODE} -> 200")
50 print(f"Invalid: http://{HOST}:{PORT}/verify?code=wrong -> 403")
51 print("Ctrl+C to stop")
52 server.serve_forever()
53
54
55if __name__ == "__main__":
56 main()
src/referrer_verify.rs +37 −11
@@ -87,22 +87,34 @@ fn host_from_http_url(url: &str) -> Option<String> {
87 87 }
88 88 }
89 89
90 fn allow_local_referrer() -> bool {
91 matches!(
92 std::env::var("POSPRINT_ALLOW_LOCAL_REFERRER")
93 .unwrap_or_default()
94 .to_ascii_lowercase()
95 .as_str(),
96 "1" | "true" | "yes"
97 )
98 }
99
90 100 fn is_blocked_verify_host(host: &str) -> bool {
91 101 let h = host.to_ascii_lowercase();
92 if h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0" {
93 return true;
94 }
102 let is_loopback_name = h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0";
95 103 if let Ok(ip) = h.parse::<IpAddr>() {
96 return match ip {
97 IpAddr::V4(v4) => {
98 v4.is_loopback()
99 || v4.is_private()
100 || v4.is_link_local()
101 || v4.is_unspecified()
102 || v4.octets()[0] == 169 && v4.octets()[1] == 254
103 }
104 let loopback = match ip {
105 IpAddr::V4(v4) => v4.is_loopback() || v4.is_unspecified(),
104 106 IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(),
105 107 };
108 if loopback {
109 return !allow_local_referrer();
110 }
111 return match ip {
112 IpAddr::V4(v4) => v4.is_private() || v4.is_link_local(),
113 IpAddr::V6(_) => false,
114 };
115 }
116 if is_loopback_name {
117 return !allow_local_referrer();
106 118 }
107 119 false
108 120 }
@@ -139,6 +151,9 @@ pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError
139 151 #[cfg(test)]
140 152 mod tests {
141 153 use super::*;
154 use std::sync::Mutex;
155
156 static ENV_LOCK: Mutex<()> = Mutex::new(());
142 157
143 158 #[test]
144 159 fn normalizes_bare_host_path_to_https() {
@@ -155,12 +170,23 @@ mod tests {
155 170
156 171 #[test]
157 172 fn blocks_localhost() {
173 let _g = ENV_LOCK.lock().unwrap();
174 std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER");
158 175 let err = normalize_referrer_url("http://127.0.0.1/verify").unwrap_err();
159 176 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
160 177 let err = normalize_referrer_url("https://localhost/x").unwrap_err();
161 178 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
162 179 }
163 180
181 #[test]
182 fn allows_localhost_when_env_set() {
183 let _g = ENV_LOCK.lock().unwrap();
184 std::env::set_var("POSPRINT_ALLOW_LOCAL_REFERRER", "1");
185 let url = normalize_referrer_url("http://127.0.0.1:8765/verify?code=1").unwrap();
186 assert_eq!(url, "http://127.0.0.1:8765/verify?code=1");
187 std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER");
188 }
189
164 190 #[test]
165 191 fn only_http_200_counts_as_success() {
166 192 assert!(is_verification_success(200));
@@ -87,22 +87,34 @@ fn host_from_http_url(url: &str) -> Option<String> {
87 }
87 }
88}
88}
89
89
90fn allow_local_referrer() -> bool {
91 matches!(
92 std::env::var("POSPRINT_ALLOW_LOCAL_REFERRER")
93 .unwrap_or_default()
94 .to_ascii_lowercase()
95 .as_str(),
96 "1" | "true" | "yes"
97 )
98}
99
90fn is_blocked_verify_host(host: &str) -> bool {
100fn is_blocked_verify_host(host: &str) -> bool {
91 let h = host.to_ascii_lowercase();
101 let h = host.to_ascii_lowercase();
92 if h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0" {
102 let is_loopback_name = h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0";
93 return true;
94 }
95 if let Ok(ip) = h.parse::<IpAddr>() {
103 if let Ok(ip) = h.parse::<IpAddr>() {
96 return match ip {
104 let loopback = match ip {
97 IpAddr::V4(v4) => {
105 IpAddr::V4(v4) => v4.is_loopback() || v4.is_unspecified(),
98 v4.is_loopback()
99 || v4.is_private()
100 || v4.is_link_local()
101 || v4.is_unspecified()
102 || v4.octets()[0] == 169 && v4.octets()[1] == 254
103 }
104 IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(),
106 IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(),
105 };
107 };
108 if loopback {
109 return !allow_local_referrer();
110 }
111 return match ip {
112 IpAddr::V4(v4) => v4.is_private() || v4.is_link_local(),
113 IpAddr::V6(_) => false,
114 };
115 }
116 if is_loopback_name {
117 return !allow_local_referrer();
106 }
118 }
107 false
119 false
108}
120}
@@ -139,6 +151,9 @@ pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError
139#[cfg(test)]
151#[cfg(test)]
140mod tests {
152mod tests {
141 use super::*;
153 use super::*;
154 use std::sync::Mutex;
155
156 static ENV_LOCK: Mutex<()> = Mutex::new(());
142
157
143 #[test]
158 #[test]
144 fn normalizes_bare_host_path_to_https() {
159 fn normalizes_bare_host_path_to_https() {
@@ -155,12 +170,23 @@ mod tests {
155
170
156 #[test]
171 #[test]
157 fn blocks_localhost() {
172 fn blocks_localhost() {
173 let _g = ENV_LOCK.lock().unwrap();
174 std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER");
158 let err = normalize_referrer_url("http://127.0.0.1/verify").unwrap_err();
175 let err = normalize_referrer_url("http://127.0.0.1/verify").unwrap_err();
159 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
176 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
160 let err = normalize_referrer_url("https://localhost/x").unwrap_err();
177 let err = normalize_referrer_url("https://localhost/x").unwrap_err();
161 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
178 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
162 }
179 }
163
180
181 #[test]
182 fn allows_localhost_when_env_set() {
183 let _g = ENV_LOCK.lock().unwrap();
184 std::env::set_var("POSPRINT_ALLOW_LOCAL_REFERRER", "1");
185 let url = normalize_referrer_url("http://127.0.0.1:8765/verify?code=1").unwrap();
186 assert_eq!(url, "http://127.0.0.1:8765/verify?code=1");
187 std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER");
188 }
189
164 #[test]
190 #[test]
165 fn only_http_200_counts_as_success() {
191 fn only_http_200_counts_as_success() {
166 assert!(is_verification_success(200));
192 assert!(is_verification_success(200));