feat(backend): replace JSON errors with user-friendly HTML error pages and reduce log noise

This commit is contained in:
pycook
2025-08-03 21:39:52 +08:00
parent 569db05b4b
commit 7c1b4b70c4
4 changed files with 199 additions and 22 deletions

View File

@@ -36,6 +36,30 @@ func (c *WebProxyController) renderSessionExpiredPage(ctx *gin.Context, reason s
ctx.String(http.StatusUnauthorized, html) ctx.String(http.StatusUnauthorized, html)
} }
func (c *WebProxyController) renderErrorPage(ctx *gin.Context, errorType, title, reason, details string) {
html := web_proxy.RenderErrorPage(errorType, title, reason, details)
ctx.Header("Content-Type", "text/html; charset=utf-8")
// Set appropriate HTTP status code based on error type
var statusCode int
switch errorType {
case "access_denied":
statusCode = http.StatusForbidden
case "session_expired":
statusCode = http.StatusUnauthorized
case "connection_error":
statusCode = http.StatusBadGateway
case "concurrent_limit":
statusCode = http.StatusTooManyRequests
case "server_error":
statusCode = http.StatusInternalServerError
default:
statusCode = http.StatusInternalServerError
}
ctx.String(statusCode, html)
}
// GetWebAssetConfig get web asset configuration // GetWebAssetConfig get web asset configuration
// @Summary Get web asset configuration // @Summary Get web asset configuration
// @Description Get web asset configuration by asset ID // @Description Get web asset configuration by asset ID
@@ -82,7 +106,7 @@ func (c *WebProxyController) StartWebSession(ctx *gin.Context) {
resp, err := web_proxy.StartWebSession(ctx, req) resp, err := web_proxy.StartWebSession(ctx, req)
if err != nil { if err != nil {
// Return appropriate HTTP status code based on error type // Return appropriate HTTP status code and JSON error for API
if strings.Contains(err.Error(), "not found") { if strings.Contains(err.Error(), "not found") {
ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
} else if strings.Contains(err.Error(), "not a web asset") { } else if strings.Contains(err.Error(), "not a web asset") {
@@ -126,7 +150,7 @@ func (c *WebProxyController) ProxyWebRequest(ctx *gin.Context) {
if strings.Contains(err.Error(), "invalid or expired session") || strings.Contains(err.Error(), "session expired") { if strings.Contains(err.Error(), "invalid or expired session") || strings.Contains(err.Error(), "session expired") {
c.renderSessionExpiredPage(ctx, err.Error()) c.renderSessionExpiredPage(ctx, err.Error())
} else { } else {
ctx.JSON(http.StatusForbidden, gin.H{"error": err.Error()}) c.renderErrorPage(ctx, "access_denied", "Access Denied", err.Error(), "Your request was blocked by the security policy.")
} }
return return
} }
@@ -134,7 +158,7 @@ func (c *WebProxyController) ProxyWebRequest(ctx *gin.Context) {
// Setup reverse proxy // Setup reverse proxy
proxy, err := web_proxy.SetupReverseProxy(ctx, proxyCtx, c.buildTargetURLWithHost, c.processHTMLResponse, c.recordWebActivity, c.isSameDomainOrSubdomain) proxy, err := web_proxy.SetupReverseProxy(ctx, proxyCtx, c.buildTargetURLWithHost, c.processHTMLResponse, c.recordWebActivity, c.isSameDomainOrSubdomain)
if err != nil { if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) c.renderErrorPage(ctx, "server_error", "Proxy Setup Failed", err.Error(), "Failed to establish connection to the target server.")
return return
} }

View File

@@ -16,12 +16,24 @@ func LoggerMiddleware() gin.HandlerFunc {
ctx.Next() ctx.Next()
cost := time.Since(start) cost := time.Since(start)
// Only log errors and slow requests
status := ctx.Writer.Status()
if status >= 400 || cost > 1*time.Second {
logger.L().Info(ctx.Request.URL.String(), logger.L().Info(ctx.Request.URL.String(),
zap.String("method", ctx.Request.Method), zap.String("method", ctx.Request.Method),
zap.Int("status", ctx.Writer.Status()), zap.Int("status", status),
zap.String("ip", ctx.ClientIP()), zap.String("ip", ctx.ClientIP()),
zap.Duration("cost", cost), zap.Duration("cost", cost),
) )
} else {
// Normal requests use debug level to reduce log noise
logger.L().Debug(ctx.Request.URL.String(),
zap.String("method", ctx.Request.Method),
zap.Int("status", status),
zap.String("ip", ctx.ClientIP()),
zap.Duration("cost", cost),
)
}
} }
} }

View File

@@ -241,18 +241,18 @@ func ProcessHTMLResponse(resp *http.Response, assetID int, scheme, proxyHost str
// Add session management JavaScript (always inject) // Add session management JavaScript (always inject)
sessionJS := fmt.Sprintf(` sessionJS := fmt.Sprintf(`
<script> <script>
(function() { (function() {tbeat', {
var sessionId = '%s';
var heartbeatInterval;
// Send heartbeat every 15 seconds
function sendHeartbeat() {
fetch('/api/oneterm/v1/web_proxy/heartbeat', {
method: 'POST', method: 'POST',
headers: {'Content-Type': 'application/json'}, headers: {'Content-Type': 'application/json'},
body: JSON.stringify({session_id: sessionId}) body: JSON.stringify({session_id: sessionId})
}).catch(function() {}); }).catch(function() {});
} }
var sessionId = '%s';
var heartbeatInterval;
// Send heartbeat every 15 seconds
function sendHeartbeat() {
fetch('/api/oneterm/v1/web_proxy/hear
// Universal heartbeat mechanism - no complex event handling // Universal heartbeat mechanism - no complex event handling
// The server will handle session cleanup based on heartbeat timeout // The server will handle session cleanup based on heartbeat timeout
@@ -504,8 +504,147 @@ func RenderExternalRedirectPage(targetURL string) string {
</html>`, targetURL) </html>`, targetURL)
} }
// RenderErrorPage renders a general error page for web proxy errors
func RenderErrorPage(errorType, title, reason, details string) string {
var bgColor, iconEmoji string
switch errorType {
case "access_denied":
bgColor = "#ff6b6b 0%, #ee5a52 100%"
iconEmoji = "🚫"
case "session_expired":
bgColor = "#f39c12 0%, #e67e22 100%"
iconEmoji = "⏰"
case "connection_error":
bgColor = "#95a5a6 0%, #7f8c8d 100%"
iconEmoji = "🔌"
case "server_error":
bgColor = "#8e44ad 0%, #9b59b6 100%"
iconEmoji = "⚠️"
case "concurrent_limit":
bgColor = "#e74c3c 0%, #c0392b 100%"
iconEmoji = "🚦"
default:
bgColor = "#34495e 0%, #2c3e50 100%"
iconEmoji = "❌"
}
detailsHtml := ""
if details != "" {
detailsHtml = fmt.Sprintf(`
<div class="info"><strong>Details:</strong></div>
<div class="details">%s</div>`, details)
}
return fmt.Sprintf(`<!DOCTYPE html>
<html>
<head>
<title>%s - OneTerm</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, %s);
min-height: 100vh;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
}
.container {
background: white;
padding: 40px;
border-radius: 12px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
max-width: 600px;
text-align: center;
}
.error-title { color: #e74c3c; font-size: 2em; margin-bottom: 20px; }
.info { color: #666; margin: 20px 0; text-align: left; }
.details {
background: #f8f9fa;
padding: 15px;
border-radius: 4px;
border-left: 4px solid #e74c3c;
font-family: monospace;
font-size: 14px;
text-align: left;
white-space: pre-wrap;
word-break: break-word;
}
.action {
background: #e8f5e8;
padding: 15px;
border-radius: 4px;
border-left: 4px solid #27ae60;
margin-top: 20px;
text-align: center;
}
.back-link {
color: #3498db;
text-decoration: none;
font-weight: 500;
margin: 0 10px;
}
.back-link:hover {
text-decoration: underline;
}
.reason {
background: #fff3cd;
color: #856404;
padding: 15px;
border-radius: 4px;
border-left: 4px solid #ffc107;
margin: 20px 0;
text-align: left;
}
</style>
</head>
<body>
<div class="container">
<h1 class="error-title">%s %s</h1>
<div class="reason">%s</div>
%s
<div class="action">
<a href="javascript:history.back()" class="back-link">← Go Back</a>
<a href="javascript:location.reload()" class="back-link">🔄 Refresh</a>
<a href="/" class="back-link">🏠 Home</a>
</div>
</div>
</body>
</html>`, title, bgColor, iconEmoji, title, reason, detailsHtml)
}
// RenderAccessDeniedPage renders the page shown when access is denied (download, read-only, etc.)
func RenderAccessDeniedPage(reason, details string) string {
return RenderErrorPage("access_denied", "Access Denied", reason, details)
}
// RenderSessionExpiredPage renders the page shown when session has expired // RenderSessionExpiredPage renders the page shown when session has expired
func RenderSessionExpiredPage(reason string) string { func RenderSessionExpiredPage(reason string) string {
return RenderErrorPage("session_expired", "Session Expired", reason, "")
}
// RenderConcurrentLimitPage renders the page when concurrent limit is exceeded
func RenderConcurrentLimitPage(maxConcurrent int) string {
reason := fmt.Sprintf("Maximum concurrent connections (%d) exceeded", maxConcurrent)
details := "Please wait for an existing session to end, or contact your administrator to increase the limit."
return RenderErrorPage("concurrent_limit", "Connection Limit Exceeded", reason, details)
}
// RenderServerErrorPage renders the page for server errors
func RenderServerErrorPage(reason, details string) string {
return RenderErrorPage("server_error", "Server Error", reason, details)
}
// RenderConnectionErrorPage renders the page for connection errors
func RenderConnectionErrorPage(reason, details string) string {
return RenderErrorPage("connection_error", "Connection Error", reason, details)
}
// Legacy function - keeping the original style for compatibility
func RenderSessionExpiredPageOld(reason string) string {
return fmt.Sprintf(`<!DOCTYPE html> return fmt.Sprintf(`<!DOCTYPE html>
<html> <html>
<head> <head>

View File

@@ -597,16 +597,18 @@ func SetupReverseProxy(ctx *gin.Context, proxyCtx *ProxyRequestContext, buildTar
strings.Contains(contentType, "application/zip") strings.Contains(contentType, "application/zip")
if isDownload && proxyCtx.Session.Permissions != nil && !proxyCtx.Session.Permissions.FileDownload { if isDownload && proxyCtx.Session.Permissions != nil && !proxyCtx.Session.Permissions.FileDownload {
// Replace the response with a 403 error // Replace the response with a 403 error page
resp.StatusCode = http.StatusForbidden resp.StatusCode = http.StatusForbidden
resp.Status = "403 Forbidden" resp.Status = "403 Forbidden"
resp.Header.Set("Content-Type", "application/json") resp.Header.Set("Content-Type", "text/html; charset=utf-8")
resp.Header.Del("Content-Disposition") resp.Header.Del("Content-Disposition")
errorMsg := `{"error":"File download not permitted"}` errorPage := RenderAccessDeniedPage(
resp.Body = io.NopCloser(strings.NewReader(errorMsg)) "File download not permitted",
resp.ContentLength = int64(len(errorMsg)) "Your user permissions do not allow file downloads through the web proxy.")
resp.Header.Set("Content-Length", fmt.Sprintf("%d", len(errorMsg))) resp.Body = io.NopCloser(strings.NewReader(errorPage))
resp.ContentLength = int64(len(errorPage))
resp.Header.Set("Content-Length", fmt.Sprintf("%d", len(errorPage)))
return nil return nil
} }