feat: protect post route with MARKA_API_KEY
Some checks failed
Build and Push Server / build-and-push (push) Has been cancelled

This commit is contained in:
Max Richter
2025-10-31 14:28:30 +01:00
parent 814be43be8
commit 6c47c8c3e9
2 changed files with 15 additions and 2 deletions

View File

@@ -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))

View File

@@ -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,
}
}