mirror of
https://github.com/komari-monitor/komari.git
synced 2026-11-24 09:05:49 +00:00
feat(security): add configurable CORS and origin checks
Add settings for allowed CORS origins and WebSocket origin validation so deployments can restrict cross-origin access instead of using a global wildcard policy. Move CORS handling into the security middleware and update report cache usage to use the dedicated report package.
This commit is contained in:
1 parent
9d914e70b9
commit
7da616ce4c
31 files changed
+550
-320
No files matched your search
@@ -0,0 +1,61 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/komari-monitor/komari/pkg/config"
|
||||
"github.com/komari-monitor/komari/web/security"
|
||||
)
|
||||
|
||||
type WebSocketUpgradeOption func(*websocket.Upgrader)
|
||||
|
||||
func IsWebSocketUpgrade(c *gin.Context) bool {
|
||||
return websocket.IsWebSocketUpgrade(c.Request)
|
||||
}
|
||||
|
||||
func EnableWebSocketCompression(upgrader *websocket.Upgrader) {
|
||||
upgrader.EnableCompression = true
|
||||
}
|
||||
|
||||
func UpgradeWebSocket(c *gin.Context, options ...WebSocketUpgradeOption) (*websocket.Conn, error) {
|
||||
if !IsWebSocketUpgrade(c) {
|
||||
return nil, fmt.Errorf("require websocket upgrade")
|
||||
}
|
||||
upgrader := websocket.Upgrader{
|
||||
CheckOrigin: CheckWebSocketOrigin,
|
||||
}
|
||||
for _, option := range options {
|
||||
option(&upgrader)
|
||||
}
|
||||
return upgrader.Upgrade(c.Writer, c.Request, nil)
|
||||
}
|
||||
|
||||
func CheckWebSocketOrigin(r *http.Request) bool {
|
||||
origin := r.Header.Get("Origin")
|
||||
if strings.EqualFold(os.Getenv("KOMARI_WS_DISABLE_ORIGIN"), "true") {
|
||||
return true
|
||||
}
|
||||
if security.IsAPIKeyRequest(r) {
|
||||
return true
|
||||
}
|
||||
if origin == "" && r.URL.Query().Get("token") != "" {
|
||||
return true
|
||||
}
|
||||
enabled, _ := config.GetAs[bool](config.WsOriginCheckEnabledKey, true)
|
||||
if !enabled {
|
||||
return true
|
||||
}
|
||||
if origin == "" {
|
||||
return false
|
||||
}
|
||||
if security.OriginMatchesHost(origin, r.Host) {
|
||||
return true
|
||||
}
|
||||
allowlist, _ := config.GetAs[string](config.WsAllowedOriginsKey, "")
|
||||
return security.OriginInAllowlist(origin, allowlist)
|
||||
}
|
||||
Reference in new issue
Block a user