diff --git a/cmd/hvpn-node/hvpn-node.go b/cmd/hvpn-node/hvpn-node.go index 3b626d3..2183de7 100644 --- a/cmd/hvpn-node/hvpn-node.go +++ b/cmd/hvpn-node/hvpn-node.go @@ -63,6 +63,7 @@ func run(ctx *cli.Context) { apiMux.HandleFunc("GET /peers", hvpnnode3.HandleGetPeers(wgLink)) var handler http.Handler = apiMux + handler = hvpnnode3.HttpAuthToken(handler, ctx.String("http-api-key")) handler = hvpnnode3.HttpLogHandler2(handler) port := fmt.Sprintf("%d", httpPort) @@ -185,6 +186,12 @@ func createCliApp() *cli.App { } app.Flags = append(app.Flags, &httpPort) + apiSecret := cli.StringFlag{ + Name: "http-api-key", + Usage: "Secure endpoints with this key; 'Authorization: Bearer ' HTTP Header", + } + app.Flags = append(app.Flags, &apiSecret) + /* TLS Flags */ diff --git a/handlers.go b/handlers.go index c8a70cc..2040a5e 100644 --- a/handlers.go +++ b/handlers.go @@ -193,6 +193,20 @@ func HttpLogHandler2(h http.Handler) http.Handler { return http.HandlerFunc(fn) } +func HttpAuthToken(h http.Handler, token string) http.Handler { + fn := func(w http.ResponseWriter, r* http.Request) { + if token != "" { + if r.Header.Get("Authorization") != token { + slog.Debug("Invalid api key") + w.WriteHeader(http.StatusUnauthorized) + return + } + } + h.ServeHTTP(w, r) + } + return http.HandlerFunc(fn) +} + func debugf(format string, reqID uuid.UUID, args ...any) { format = format + " " + reqID.String() slog.Debug(fmt.Sprintf(format, args...)) @@ -202,3 +216,13 @@ func debug(msg string, reqID uuid.UUID) { msg = msg + " " + reqID.String() debugf("%s", reqID, msg) } + +func infof(format string, reqID uuid.UUID, args ...any) { + format = format + " " + reqID.String() + slog.Info(fmt.Sprintf(format, args...)) +} + +func info(msg string, reqID uuid.UUID) { + msg = msg + " " + reqID.String() + infof("%s", reqID, msg) +}