Protect monitoring PF API with internal key

This commit is contained in:
Grendgi
2026-06-12 16:32:12 +03:00
parent 974090df4f
commit 47e259fa28
3 changed files with 17 additions and 0 deletions

View File

@@ -15,6 +15,7 @@ type Config struct {
ScrapeIntervalHours int
TGBotToken string
TGBotUsername string
InternalAPIKey string
WorkerPython string
WorkerModule string
}
@@ -28,6 +29,7 @@ func LoadConfig() Config {
ScrapeIntervalHours: max(1, envInt("SCRAPE_INTERVAL_HOURS", 4)),
TGBotToken: env("TG_BOT_TOKEN", ""),
TGBotUsername: strings.TrimPrefix(env("TG_BOT_USERNAME", ""), "@"),
InternalAPIKey: env("INTERNAL_API_KEY", env("PORTAL_INTERNAL_API_KEY", "")),
WorkerPython: env("WORKER_PYTHON", "python"),
WorkerModule: env("WORKER_MODULE", "app.worker"),
}

View File

@@ -29,6 +29,8 @@ func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"service": "monitoring-pf", "ui": "portal", "api": "go"})
case !strings.HasPrefix(path, "/api/v1"):
writeError(w, http.StatusNotFound, "not found")
case !s.checkInternalAuth(w, r):
return
case path == "/api/v1/access/me" && r.Method == http.MethodGet:
s.accessMe(w, r)
case path == "/api/v1/summary" && r.Method == http.MethodGet:
@@ -50,6 +52,18 @@ func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
func (s Server) checkInternalAuth(w http.ResponseWriter, r *http.Request) bool {
want := strings.TrimSpace(s.App.Cfg.InternalAPIKey)
if want == "" {
return true
}
if r.Header.Get("X-Internal-Key") != want {
writeError(w, http.StatusUnauthorized, "unauthorized")
return false
}
return true
}
func (s Server) apiPath(path string) string {
base := s.App.Cfg.PublicBasePath
if base != "" && path == base {