| 1 | import sys |
| 2 | from pathlib import Path |
| 3 | |
| 4 | PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| 5 | if str(PROJECT_ROOT) not in sys.path: |
| 6 | sys.path.insert(0, str(PROJECT_ROOT)) |
| 7 | |
| 8 | from helpers.ws import validate_ws_origin |
| 9 | |
| 10 | |
| 11 | def test_validate_ws_origin_allows_same_origin_with_explicit_port(): |
| 12 | ok, reason = validate_ws_origin( |
| 13 | { |
| 14 | "HTTP_ORIGIN": "http://localhost:5000", |
| 15 | "HTTP_HOST": "localhost:5000", |
| 16 | } |
| 17 | ) |
| 18 | assert ok is True |
| 19 | assert reason is None |
| 20 | |
| 21 | |
| 22 | def test_validate_ws_origin_allows_default_https_port_without_explicit_port(): |
| 23 | ok, reason = validate_ws_origin( |
| 24 | { |
| 25 | "HTTP_ORIGIN": "https://example.com", |
| 26 | "HTTP_HOST": "example.com", |
| 27 | } |
| 28 | ) |
| 29 | assert ok is True |
| 30 | assert reason is None |
| 31 | |
| 32 | |
| 33 | def test_validate_ws_origin_rejects_missing_origin(): |
| 34 | ok, reason = validate_ws_origin( |
| 35 | { |
| 36 | "HTTP_HOST": "localhost:5000", |
| 37 | } |
| 38 | ) |
| 39 | assert ok is False |
| 40 | assert reason == "missing_origin" |
| 41 | |
| 42 | |
| 43 | def test_validate_ws_origin_rejects_cross_origin(): |
| 44 | ok, reason = validate_ws_origin( |
| 45 | { |
| 46 | "HTTP_ORIGIN": "http://evil.test", |
| 47 | "HTTP_HOST": "localhost:5000", |
| 48 | } |
| 49 | ) |
| 50 | assert ok is False |
| 51 | assert reason == "origin_host_mismatch" |
| 52 | |
| 53 | |
| 54 | def test_validate_ws_origin_allows_active_tunnel_origin_with_local_upstream_host( |
| 55 | monkeypatch, |
| 56 | ): |
| 57 | import helpers.ws as ws |
| 58 | |
| 59 | monkeypatch.setattr( |
| 60 | ws, |
| 61 | "get_active_tunnel_origins", |
| 62 | lambda: ["https://agent-zero.tailabc.ts.net"], |
| 63 | raising=False, |
| 64 | ) |
| 65 | |
| 66 | ok, reason = validate_ws_origin( |
| 67 | { |
| 68 | "HTTP_ORIGIN": "https://agent-zero.tailabc.ts.net", |
| 69 | "HTTP_HOST": "127.0.0.1:80", |
| 70 | } |
| 71 | ) |
| 72 | |
| 73 | assert ok is True |
| 74 | assert reason is None |
| 75 | |
| 76 | |
| 77 | def test_validate_ws_origin_rejects_unrelated_origin_with_active_tunnel( |
| 78 | monkeypatch, |
| 79 | ): |
| 80 | import helpers.ws as ws |
| 81 | |
| 82 | monkeypatch.setattr( |
| 83 | ws, |
| 84 | "get_active_tunnel_origins", |
| 85 | lambda: ["https://agent-zero.tailabc.ts.net"], |
| 86 | raising=False, |
| 87 | ) |
| 88 | |
| 89 | ok, reason = validate_ws_origin( |
| 90 | { |
| 91 | "HTTP_ORIGIN": "https://evil.example", |
| 92 | "HTTP_HOST": "127.0.0.1:80", |
| 93 | } |
| 94 | ) |
| 95 | |
| 96 | assert ok is False |
| 97 | assert reason == "origin_host_mismatch" |