8000 [pull] main from miniflux:main by pull[bot] · Pull Request #259 · suhaoGe/miniflux · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ require (
github.com/andybalholm/brotli v1.2.0
github.com/coreos/go-oidc/v3 v3.17.0
github.com/go-webauthn/webauthn v0.16.1
github.com/gorilla/mux v1.8.1
github.com/lib/pq v1.12.0
github.com/prometheus/client_golang v1.23.2
github.com/tdewolff/minify/v2 v2.24.10
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba h1:qJEJcuLz
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
Expand Down
2 changes: 1 addition & 1 deletion internal/googlereader/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,7 @@ func move(feedStream Stream, labelStream Stream, store *storage.Storage, userID

func (h *greaderHandler) feedIconURL(f *model.Feed) string {
if f.Icon != nil && f.Icon.ExternalIconID != "" {
return config.Opts.BaseURL() + "/feed/icon/" + f.Icon.ExternalIconID
return config.Opts.BaseURL() + "/feed-icon/" + f.Icon.ExternalIconID
}
return ""
}
Expand Down
7 changes: 0 additions & 7 deletions internal/http/request/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import (
"net/http"
"strconv"
"strings"

"github.com/gorilla/mux"
)

// FormInt64Value returns the named form value parsed as int64, or 0 on error.
Expand Down Expand Up @@ -129,10 +127,5 @@ func HasQueryParam(r *http.Request, param string) bool {
}

func routeParam(r *http.Request, param string) string {
vars := mux.Vars(r)
if value, found := vars[param]; found {
return value
}

return r.PathValue(param)
}
70 changes: 0 additions & 70 deletions internal/http/request/params_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import (
"net/url"
"reflect"
"testing"

"github.com/gorilla/mux"
)

func TestFormInt64Value(t *testing.T) {
Expand Down Expand Up @@ -42,33 +40,6 @@ func TestFormInt64Value(t *testing.T) {
}
}

func TestRouteStringParamWithGorillaMux(t *testing.T) {
router := mux.NewRouter()
router.HandleFunc("/route/{variable}/index", func(w http.ResponseWriter, r *http.Request) {
result := RouteStringParam(r, "variable")
expected := "value"

if result != expected {
t.Errorf(`Unexpected result, got %q instead of %q`, result, expected)
}

result = RouteStringParam(r, "missing variable")
expected = ""

if result != expected {
t.Errorf(`Unexpected result, got %q instead of %q`, result, expected)
}
})

r, err := http.NewRequest("GET", "/route/value/index", nil)
if err != nil {
t.Fatal(err)
}

w := httptest.NewRecorder()
router.ServeHTTP(w, r)
}

func TestRouteStringParamWithServerMux(t *testing.T) {
router := http.NewServeMux()
router.HandleFunc("GET /route/{variable}/index", func(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -96,47 +67,6 @@ func TestRouteStringParamWithServerMux(t *testing.T) {
router.ServeHTTP(w, r)
}

func TestRouteInt64ParamWithGorillaMux(t *testing.T) {
router := mux.NewRouter()
router.HandleFunc("/a/{variable1}/b/{variable2}/c/{variable3}", func(w http.ResponseWriter, r *http.Request) {
result := RouteInt64Param(r, "variable1")
expected := int64(42)

if result != expected {
t.Errorf(`Unexpected result, got %d instead of %d`, result, expected)
}

result = RouteInt64Param(r, "missing variable")
expected = 0

if result != expected {
t.Errorf(`Unexpected result, got %d instead of %d`, result, expected)
}

result = RouteInt64Param(r, "variable2")
expected = 0

if result != expected {
t.Errorf(`Unexpected result, got %d instead of %d`, result, expected)
}

result = RouteInt64Param(r, "variable3")
expected = 0

if result != expected {
t.Errorf(`Unexpected result, got %d instead of %d`, result, expected)
}
})

r, err := http.NewRequest("GET", "/a/42/b/not-int/c/-10", nil)
if err != nil {
t.Fatal(err)
}

w := httptest.NewRecorder()
router.ServeHTTP(w, r)
}

func TestRouteInt64ParamWithServerMux(t *testing.T) {
router := http.NewServeMux()
router.HandleFunc("GET /a/{variable1}/b/{variable2}/c/{variable3}", func(w http.ResponseWriter, r *http.Request) {
Expand Down
35 changes: 0 additions & 35 deletions internal/http/route/route.go

This file was deleted.

27 changes: 27 additions & 0 deletions internal/http/server/healthcheck.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package server // import "miniflux.app/v2/internal/http/server"

import (
"fmt"
"net/http"

"miniflux.app/v2/internal/storage"
)

func livenessProbe(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}

func newReadinessProbe(store *storage.Storage) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := store.Ping(); err != nil {
http.Error(w, fmt.Sprintf("Database Connection Error: %q", err), http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
}
131 changes: 1 addition & 130 deletions internal/http/server/httpd.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,10 @@ import (
"strconv"
"strings"

"miniflux.app/v2/internal/api"
"miniflux.app/v2/internal/config"
"miniflux.app/v2/internal/fever"
"miniflux.app/v2/internal/googlereader"
"miniflux.app/v2/internal/http/request"
"miniflux.app/v2/internal/storage"
"miniflux.app/v2/internal/ui"
"miniflux.app/v2/internal/worker"

"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
)
Expand Down Expand Up @@ -68,7 +61,7 @@ func StartWebServer(store *storage.Storage, pool *worker.Pool) []*http.Server {
ReadTimeout: config.Opts.HTTPServerTimeout(),
WriteTimeout: config.Opts.HTTPServerTimeout(),
IdleTimeout: config.Opts.HTTPServerTimeout(),
Handler: setupHandler(store, pool),
Handler: newRouter(store, pool),
}

isUNIXSocket := strings.HasPrefix(listenAddr, "/")
Expand Down Expand Up @@ -200,128 +193,6 @@ func startHTTPServer(server *http.Server) {
}()
}

func setupHandler(store *storage.Storage, pool *worker.Pool) *mux.Router {
livenessProbe := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
readinessProbe := func(w http.ResponseWriter, r *http.Request) {
if err := store.Ping(); err != nil {
http.Error(w, fmt.Sprintf("Database Connection Error: %q", err), http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}

router := mux.NewRouter()

// These routes do not take the base path into consideration and are always available at the root of the server.
router.HandleFunc("/liveness", livenessProbe).Name("liveness")
router.HandleFunc("/healthz", livenessProbe).Name("healthz")
router.HandleFunc("/readiness", readinessProbe).Name("readiness")
router.HandleFunc("/readyz", readinessProbe).Name("readyz")

var subrouter *mux.Router
if config.Opts.BasePath() != "" {
subrouter = router.PathPrefix(config.Opts.BasePath()).Subrouter()
} else {
subrouter = router.NewRoute().Subrouter()
}

if config.Opts.HasMaintenanceMode() {
subrouter.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(config.Opts.MaintenanceMessage()))
})
})
}

subrouter.Use(middleware)

// Fever API routing
feverSubrouter := subrouter.PathPrefix("/fever").Subrouter()
feverSubrouter.Use(fever.Middleware(store))
feverSubrouter.Handle("/", fever.NewHandler(store)).Name("feverEndpoint")

// Google Reader API routing
googleReaderHandler := http.StripPrefix(config.Opts.BasePath(), googlereader.NewHandler(store))
subrouter.HandleFunc("/accounts/ClientLogin", googleReaderHandler.ServeHTTP).Methods(http.MethodPost).Name("ClientLogin")
subrouter.PathPrefix("/reader/api/0").Handler(googleReaderHandler)

if config.Opts.HasAPI() {
apiHandler := http.StripPrefix(config.Opts.BasePath(), api.NewHandler(store, pool))
subrouter.PathPrefix("/v1").Handler(apiHandler)
}
ui.Serve(subrouter, store, pool)

subrouter.HandleFunc("/healthcheck", readinessProbe).Name("healthcheck")

if config.Opts.HasMetricsCollector() {
subrouter.Handle("/metrics", promhttp.Handler()).Name("metrics")
subrouter.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)

// Returns a 404 if the client is not authorized to access the metrics endpoint.
if route.GetName() == "metrics" && !isAllowedToAccessMetricsEndpoint(r) {
slog.Warn("Authentication failed while accessing the metrics endpoint",
slog.String("client_ip", request.ClientIP(r)),
slog.String("client_user_agent", r.UserAgent()),
slog.String("client_remote_addr", r.RemoteAddr),
)
http.NotFound(w, r)
return
}

next.ServeHTTP(w, r)
})
})
}

return router
}

func isAllowedToAccessMetricsEndpoint(r *http.Request) bool {
clientIP := request.ClientIP(r)

if config.Opts.MetricsUsername() != "" && config.Opts.MetricsPassword() != "" {
username, password, authOK := r.BasicAuth()
if !authOK {
slog.Warn("Metrics endpoint accessed without authentication header",
slog.Bool("authentication_failed", true),
slog.String("client_ip", clientIP),
slog.String("client_user_agent", r.UserAgent()),
slog.String("client_remote_addr", r.RemoteAddr),
)
return false
}

if username == "" || password == "" {
slog.Warn("Metrics endpoint accessed with empty username or password",
slog.Bool("authentication_failed", true),
slog.String("client_ip", clientIP),
slog.String("client_user_agent", r.UserAgent()),
slog.String("client_remote_addr", r.RemoteAddr),
)
return false
}

if username != config.Opts.MetricsUsername() || password != config.Opts.MetricsPassword() {
slog.Warn("Metrics endpoint accessed with invalid username or password",
slog.Bool("authentication_failed", true),
slog.String("client_ip", clientIP),
slog.String("client_user_agent", r.UserAgent()),
slog.String("client_remote_addr", r.RemoteAddr),
)
return false
}
}

remoteIP := request.FindRemoteIP(r)
return request.IsTrustedIP(remoteIP, config.Opts.MetricsAllowedNetworks())
}

func printErrorAndExit(format string, a ...any) {
message := fmt.Sprintf(format, a...)
slog.Error(message)
Expand Down
Loading
Loading
0