-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.py
More file actions
151 lines (127 loc) · 5.11 KB
/
proxy.py
File metadata and controls
151 lines (127 loc) · 5.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""HTML proxy endpoint for interactive plots with size reporting."""
from urllib.parse import urlparse
import httpx
from fastapi import APIRouter, HTTPException
from fastapi.responses import HTMLResponse
router = APIRouter(tags=["proxy"])
# Script injected to report content size to parent window
# Uses specific origin (pyplots.ai) for postMessage security
SIZE_REPORTER_SCRIPT = """
<script>
(function() {
function reportSize() {
try {
// Find the main content element (try common patterns for different libraries)
var content = document.querySelector(
'.bk-root, .vega-embed, .plotly, .chart-container, #container, .lp-plot, svg, canvas'
) || document.body.firstElementChild || document.body;
// Get actual rendered size
var rect = content.getBoundingClientRect();
var width = Math.max(rect.width, content.scrollWidth || 0, document.body.scrollWidth || 0);
var height = Math.max(rect.height, content.scrollHeight || 0, document.body.scrollHeight || 0);
// Add padding to account for action buttons, toolbars, and other UI elements
var padding = 40;
width += padding;
height += padding;
// Send to parent with specific origin for security
if (width > 0 && height > 0 && window.parent !== window) {
window.parent.postMessage({
type: 'pyplots-size',
width: Math.ceil(width),
height: Math.ceil(height)
}, 'https://pyplots.ai');
}
} catch (e) {
// Silently fail if postMessage is blocked
}
}
// Report after load and after delays (for async rendering libraries)
if (document.readyState === 'complete') {
setTimeout(reportSize, 100);
setTimeout(reportSize, 500);
setTimeout(reportSize, 1000);
} else {
window.addEventListener('load', function() {
setTimeout(reportSize, 100);
setTimeout(reportSize, 500);
setTimeout(reportSize, 1000);
});
}
})();
</script>
"""
# Allowed GCS bucket for security
ALLOWED_HOST = "storage.googleapis.com"
ALLOWED_BUCKET = "pyplots-images"
def build_safe_gcs_url(url: str) -> str | None:
"""
Validate URL and return a reconstructed safe GCS URL.
This prevents SSRF by constructing the URL from hardcoded values
instead of passing user input directly.
Args:
url: User-provided URL to validate
Returns:
Reconstructed safe URL or None if validation fails
"""
try:
parsed = urlparse(url)
# Must be HTTPS
if parsed.scheme != "https":
return None
# Must be exact host (no subdomains)
if parsed.netloc != ALLOWED_HOST:
return None
# Path must start with bucket name
path_parts = parsed.path.strip("/").split("/")
if len(path_parts) < 2:
return None
if path_parts[0] != ALLOWED_BUCKET:
return None
# Check for path traversal attempts
if ".." in parsed.path:
return None
# Validate path contains only safe characters (alphanumeric, hyphens, underscores, dots, slashes)
safe_path = parsed.path.strip("/")
if not all(c.isalnum() or c in "-_./+" for c in safe_path):
return None
# Reconstruct URL from hardcoded values to prevent SSRF
# This breaks the taint flow by not using the original URL
return f"https://{ALLOWED_HOST}/{safe_path}"
except Exception:
return None
@router.get("/proxy/html", response_class=HTMLResponse)
async def proxy_html(url: str):
"""
Proxy an HTML file and inject size reporting script.
This endpoint fetches HTML from GCS, injects a script that reports
the content's actual dimensions via postMessage, and returns the
modified HTML. This allows the frontend to dynamically scale the
iframe based on actual content size.
Args:
url: The GCS URL to fetch (must be from allowed bucket)
Returns:
Modified HTML with size reporting script injected
"""
# Security: Validate and reconstruct URL to prevent SSRF
safe_url = build_safe_gcs_url(url)
if safe_url is None:
raise HTTPException(status_code=400, detail=f"Only URLs from {ALLOWED_HOST}/{ALLOWED_BUCKET} are allowed")
# Fetch the HTML with shorter timeout
async with httpx.AsyncClient(timeout=10.0) as client:
try:
response = await client.get(safe_url)
response.raise_for_status()
except httpx.HTTPStatusError as e:
raise HTTPException(status_code=e.response.status_code, detail="Failed to fetch HTML") from e
except httpx.RequestError as e:
raise HTTPException(status_code=502, detail="Failed to connect to storage") from e
html_content = response.text
# Inject the size reporter script before </body>
if "</body>" in html_content:
html_content = html_content.replace("</body>", f"{SIZE_REPORTER_SCRIPT}</body>")
elif "</html>" in html_content:
html_content = html_content.replace("</html>", f"{SIZE_REPORTER_SCRIPT}</html>")
else:
# Fallback: append to end
html_content += SIZE_REPORTER_SCRIPT
return HTMLResponse(content=html_content)