From 6c47c8c3e9c1c46bf18d2e0231780d01453d2f77 Mon Sep 17 00:00:00 2001 From: Max Richter Date: Fri, 31 Oct 2025 14:28:30 +0100 Subject: [PATCH] feat: protect post route with MARKA_API_KEY --- server/cmd/marka-server/main.go | 3 ++- server/internal/handler/handler.go | 14 +++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/server/cmd/marka-server/main.go b/server/cmd/marka-server/main.go index 380c2b3..ee96665 100644 --- a/server/cmd/marka-server/main.go +++ b/server/cmd/marka-server/main.go @@ -61,7 +61,8 @@ func main() { fsAdapter, err := adapters.NewLocalFsAdapter(absRoots) must(err) - http.Handle("/", handler.NewHandler(fsAdapter)) + apiKey := os.Getenv("MARKA_API_KEY") + http.Handle("/", handler.NewHandler(fsAdapter, apiKey)) log.Printf("listening on %s, roots=%s", *addr, strings.Join(absRoots, ", ")) log.Fatal(http.ListenAndServe(*addr, nil)) diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go index 7cbca84..d848a50 100644 --- a/server/internal/handler/handler.go +++ b/server/internal/handler/handler.go @@ -14,6 +14,7 @@ import ( type Handler struct { adapter adapters.FileAdapter + apiKey string } func (h *Handler) get(w http.ResponseWriter, target string) { @@ -49,6 +50,16 @@ func (h *Handler) get(w http.ResponseWriter, target string) { } func (h *Handler) post(w http.ResponseWriter, r *http.Request, target string) { + if h.apiKey != "" { + if r.Header.Get("Authentication") != h.apiKey { + writeError(w, http.StatusUnauthorized, errors.New("invalid api key")) + return + } + } else { + writeError(w, http.StatusUnauthorized, errors.New("invalid api key")) + return + } + body, err := io.ReadAll(r.Body) if err != nil { writeError(w, http.StatusBadRequest, err) @@ -97,8 +108,9 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -func NewHandler(adapter adapters.FileAdapter) http.Handler { +func NewHandler(adapter adapters.FileAdapter, apiKey string) http.Handler { return &Handler{ adapter: adapter, + apiKey: apiKey, } }