refactor(server): replace Echo with net/http (#6475)

This commit is contained in:
Johnny
2026-10-15 09:32:02 +08:00
committed by GitHub
parent e0dbf5eeb1
commit 1511fd125d
31 changed files with 1227 additions and 532 deletions
+2 -2
View File
@@ -7,7 +7,7 @@ repo. If a fact here conflicts with source files or CI config, trust the source
Memos is a self-hosted note-taking app.
- Backend: Go 1.27.2, Echo v5, Connect RPC, gRPC-Gateway, Protocol Buffers.
- Backend: Go 1.27.2, net/http, Connect RPC, gRPC-Gateway, Protocol Buffers.
- Frontend: React 19, TypeScript 7, Vite 8, Tailwind CSS v4, React Query v5.
- Storage: SQLite, MySQL, PostgreSQL.
- Generated API outputs: `proto/gen/` for Go/OpenAPI, `web/src/types/proto/` for TypeScript.
@@ -69,7 +69,7 @@ Every root folder is named for what it holds. Read the folder's `doc.go` or `REA
| Path | Holds | May import |
| --- | --- | --- |
| `cmd/memos/` | Cobra/Viper CLI setup and server startup | anything |
| `server/` | The HTTP process: Echo bootstrap, graceful shutdown, every transport | core, store, provider, markdown, filter, internal |
| `server/` | The HTTP process: net/http bootstrap, graceful shutdown, every transport | core, store, provider, markdown, filter, internal |
| `server/api/` | Connect/gRPC-Gateway services, ACL config, SSE hub. Thin handlers; rules go to `core/` | |
| `server/fileserver/` | Native HTTP file serving, thumbnails, range requests | |
| `server/frontend/` | Static SPA serving; `dist/` is the built SPA baked in by `go:embed` | |
-1
View File
@@ -18,7 +18,6 @@ require (
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0
github.com/johannesboyne/gofakes3 v1.2.0
github.com/joho/godotenv v1.5.1
github.com/labstack/echo/v5 v5.3.1
github.com/lib/pq v1.12.3
github.com/lithammer/shortuuid/v4 v4.2.0
github.com/moby/moby/api v1.55.0
-2
View File
@@ -157,8 +157,6 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/labstack/echo/v5 v5.3.1 h1:75maCxkQVGualckLc/5s/ihgpH1a1Dc6AuGWNVNs6bw=
github.com/labstack/echo/v5 v5.3.1/go.mod h1:4iEGNQiPPZnkfYpNR/L6fINd3NLiGWUD5+eBotFALas=
github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ=
github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
github.com/lithammer/shortuuid/v4 v4.2.0 h1:LMFOzVB3996a7b8aBuEXxqOBflbfPQAiVzkIcHO0h8c=
+1
View File
@@ -9,6 +9,7 @@ nothing from `store`, `core`, `server`, `provider`, `markdown`, `filter`, or
| --- | --- |
| `clientip/` | trusted-proxy aware client IP resolution middleware |
| `email/` | SMTP client, config, and message types |
| `httphandler/` | HTTP response errors, panic recovery, and routing compatibility |
| `identifier/` | grammar of UIDs and usernames shared by parser, store, and API |
| `linkmeta/` | HTML metadata, oEmbed, and image fetching for link previews |
| `motionphoto/` | Live Photo and Motion Photo container parsing |
+6 -9
View File
@@ -13,7 +13,6 @@ import (
"slices"
"strings"
"github.com/labstack/echo/v5"
"github.com/pkg/errors"
)
@@ -172,13 +171,11 @@ func FromContext(ctx context.Context) string {
// Middleware resolves the client address once per request and stores it in
// the request context, where both API transports and the file server read it.
func Middleware(resolver *Resolver) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
request := c.Request()
ip := resolver.Resolve(request.RemoteAddr, request.Header)
c.SetRequest(request.WithContext(WithClientIP(request.Context(), ip)))
return next(c)
}
func Middleware(resolver *Resolver) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := resolver.Resolve(r.RemoteAddr, r.Header)
next.ServeHTTP(w, r.WithContext(WithClientIP(r.Context(), ip)))
})
}
}
+24
View File
@@ -2,6 +2,7 @@ package clientip
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
@@ -57,3 +58,26 @@ func TestParseTrustedProxiesRejectsGarbage(t *testing.T) {
_, err := ParseTrustedProxies([]string{"proxy.internal"})
require.Error(t, err)
}
func TestMiddlewareCarriesResolvedAddress(t *testing.T) {
resolver, err := ParseTrustedProxies([]string{"private"})
require.NoError(t, err)
for _, test := range []struct{ peer, want string }{
{"127.0.0.1:1234", "198.51.100.9"},
{"203.0.113.1:1234", "203.0.113.1"},
} {
t.Run(test.peer, func(t *testing.T) {
handler := Middleware(resolver)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, test.want, FromContext(r.Context()))
w.WriteHeader(http.StatusNoContent)
}))
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.RemoteAddr = test.peer
r.Header.Set("X-Forwarded-For", "198.51.100.9")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, r)
require.Equal(t, http.StatusNoContent, rec.Code)
require.Empty(t, FromContext(r.Context()), "the original request context must remain unchanged")
})
}
}
+189
View File
@@ -0,0 +1,189 @@
// Package httphandler implements shared HTTP response handling.
package httphandler
import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/url"
"runtime/debug"
"github.com/pkg/errors"
)
// Error carries a public HTTP error message and an optional underlying cause.
type Error struct {
Code int
Message string
Cause error
}
func (e *Error) Error() string { return e.Message }
func (e *Error) Unwrap() error { return e.Cause }
// Func adapts an error-returning handler without exposing internal errors.
type Func func(http.ResponseWriter, *http.Request) error
func (f Func) ServeHTTP(w http.ResponseWriter, r *http.Request) {
restoreURL(r)
response := &responseWriter{ResponseWriter: w}
if err := f(response, r); err != nil && !response.committed {
WriteError(w, r, err)
}
}
// WriteError preserves the public JSON error envelope, including bodyless HEAD errors.
func WriteError(w http.ResponseWriter, r *http.Request, err error) {
code, message := http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)
var publicError *Error
if errors.As(err, &publicError) {
code, message = publicError.Code, publicError.Message
}
if r.Method == http.MethodHead {
w.WriteHeader(code)
return
}
_ = JSON(w, code, map[string]string{"message": message})
}
// JSON sends a JSON response.
func JSON(w http.ResponseWriter, code int, value any) error {
body, err := json.Marshal(value)
if err != nil {
return err
}
return Blob(w, code, "application/json", append(body, '\n'))
}
// Blob sends bytes with the given content type.
func Blob(w http.ResponseWriter, code int, contentType string, body []byte) error {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", contentType)
}
w.WriteHeader(code)
_, err := w.Write(body)
return err
}
// Text sends a UTF-8 plain text response.
func Text(w http.ResponseWriter, code int, body string) error {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
}
w.WriteHeader(code)
_, err := io.WriteString(w, body)
return err
}
// NotFound sends the application's router-level 404 response.
func NotFound(w http.ResponseWriter, r *http.Request) {
WriteError(w, r, &Error{Code: http.StatusNotFound, Message: http.StatusText(http.StatusNotFound)})
}
// GET preserves explicit GET-only routes, without implicitly accepting HEAD.
// Other methods go to fallback when a broader route exists.
func GET(handler, fallback http.Handler) http.Handler {
return getHandler{handler: handler, fallback: fallback}
}
type getHandler struct {
handler, fallback http.Handler
}
// AllowedMethods returns the Allow header for a route without a broader fallback.
func (h getHandler) AllowedMethods() string {
if h.fallback != nil {
return ""
}
return "OPTIONS, GET"
}
func (h getHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
restoreURL(r)
if r.Method == http.MethodGet {
h.handler.ServeHTTP(w, r)
return
}
if h.fallback != nil {
h.fallback.ServeHTTP(w, r)
return
}
w.Header().Set("Allow", h.AllowedMethods())
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
WriteError(w, r, &Error{Code: http.StatusMethodNotAllowed, Message: http.StatusText(http.StatusMethodNotAllowed)})
}
type originalURLKey struct{}
// RoutingRequest preserves literal escaped segments during ServeMux matching.
// The previous router matched RawPath without unescaping parameters. Handlers
// still receive the original URL, with PathValue populated by ServeMux.
func RoutingRequest(r *http.Request) *http.Request {
if r.URL.RawPath == "" {
return r
}
request := r.WithContext(context.WithValue(r.Context(), originalURLKey{}, r.URL))
requestURL := *r.URL
requestURL.Path, requestURL.RawPath = r.URL.RawPath, ""
request.URL = &requestURL
return request
}
func restoreURL(r *http.Request) {
if original, ok := r.Context().Value(originalURLKey{}).(*url.URL); ok {
r.URL = original
}
}
// Recover turns panics before a response into JSON 500s, leaving started streams intact.
func Recover(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
response := &responseWriter{ResponseWriter: w}
defer func() {
if recovered := recover(); recovered != nil {
if recovered == http.ErrAbortHandler {
panic(recovered)
}
slog.Error("HTTP handler panic", "panic", recovered, "stack", string(debug.Stack()))
if !response.committed {
WriteError(w, r, errors.New("handler panic"))
}
}
}()
next.ServeHTTP(response, r)
})
}
type responseWriter struct {
http.ResponseWriter
committed bool
}
func (w *responseWriter) WriteHeader(code int) {
if code >= 200 {
w.committed = true
}
w.ResponseWriter.WriteHeader(code)
}
func (w *responseWriter) Write(body []byte) (int, error) {
w.committed = true
return w.ResponseWriter.Write(body)
}
func (w *responseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
func (w *responseWriter) Flush() {
_ = w.FlushError()
}
// FlushError propagates flush errors to http.ResponseController callers.
func (w *responseWriter) FlushError() error {
w.committed = true
return http.NewResponseController(w.ResponseWriter).Flush()
}
+146
View File
@@ -0,0 +1,146 @@
package httphandler
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
)
func TestErrorResponses(t *testing.T) {
for _, test := range []struct {
name string
err error
method string
status int
body string
}{
{"internal error is hidden", errors.New("database password"), http.MethodGet, 500, "{\"message\":\"Internal Server Error\"}\n"},
{"wrapped public error", errors.Wrap(&Error{Code: 403, Message: "forbidden", Cause: errors.New("private detail")}, "context"), http.MethodGet, 403, "{\"message\":\"forbidden\"}\n"},
{"HEAD has no error body", &Error{Code: 404, Message: "missing"}, http.MethodHead, 404, ""},
} {
t.Run(test.name, func(t *testing.T) {
rec := httptest.NewRecorder()
Func(func(http.ResponseWriter, *http.Request) error { return test.err }).ServeHTTP(rec, httptest.NewRequest(test.method, "/", nil))
require.Equal(t, test.status, rec.Code)
require.Equal(t, test.body, rec.Body.String())
if test.method == http.MethodHead {
require.Empty(t, rec.Header().Get("Content-Type"))
} else {
require.Equal(t, "application/json", rec.Header().Get("Content-Type"))
}
})
}
}
func TestStartedResponseIsNotReplaced(t *testing.T) {
for _, test := range []struct {
name string
panic bool
}{
{"write error", false},
{"panic", true},
} {
t.Run(test.name, func(t *testing.T) {
handler := Recover(Func(func(w http.ResponseWriter, _ *http.Request) error {
w.Header().Set("Content-Type", "text/event-stream")
_, err := io.WriteString(w, ": connected\n\n")
require.NoError(t, err)
require.NoError(t, http.NewResponseController(w).Flush())
if test.panic {
panic("stream failed")
}
return errors.New("client disconnected")
}))
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
require.Equal(t, http.StatusOK, rec.Code)
require.True(t, rec.Flushed)
require.Equal(t, "text/event-stream", rec.Header().Get("Content-Type"))
require.Equal(t, ": connected\n\n", rec.Body.String())
})
}
}
type flushErrorWriter struct {
http.ResponseWriter
err error
}
func (w flushErrorWriter) FlushError() error { return w.err }
func TestFlushErrorPropagation(t *testing.T) {
failure := errors.New("flush failed")
for _, test := range []struct {
name string
writer func(http.ResponseWriter) http.ResponseWriter
wantErr error
}{
{"underlying failure", func(w http.ResponseWriter) http.ResponseWriter { return flushErrorWriter{w, failure} }, failure},
{"unsupported flush", func(w http.ResponseWriter) http.ResponseWriter { return struct{ http.ResponseWriter }{w} }, http.ErrNotSupported},
} {
t.Run(test.name, func(t *testing.T) {
handler := Recover(Func(func(w http.ResponseWriter, _ *http.Request) error {
require.ErrorIs(t, http.NewResponseController(w).Flush(), test.wantErr)
return errors.New("error after flush")
}))
rec := httptest.NewRecorder()
handler.ServeHTTP(test.writer(rec), httptest.NewRequest(http.MethodGet, "/", nil))
require.Empty(t, rec.Body.String(), "a flush must prevent appending an error response")
})
}
}
func TestRecoverBeforeResponse(t *testing.T) {
handler := Recover(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { panic("private detail") }))
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
require.Equal(t, http.StatusInternalServerError, rec.Code)
require.JSONEq(t, `{"message":"Internal Server Error"}`, rec.Body.String())
abort := Recover(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { panic(http.ErrAbortHandler) }))
require.PanicsWithValue(t, http.ErrAbortHandler, func() {
abort.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
})
}
func TestJSONFailureBeforeCommit(t *testing.T) {
rec := httptest.NewRecorder()
Func(func(w http.ResponseWriter, _ *http.Request) error {
return JSON(w, http.StatusCreated, make(chan int))
}).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
require.Equal(t, http.StatusInternalServerError, rec.Code)
require.JSONEq(t, `{"message":"Internal Server Error"}`, rec.Body.String())
}
func TestErrorPreservesExistingContentType(t *testing.T) {
rec := httptest.NewRecorder()
Func(func(w http.ResponseWriter, _ *http.Request) error {
w.Header().Set("Content-Type", "video/mp4")
return &Error{Code: http.StatusRequestedRangeNotSatisfiable, Message: "requested range not satisfiable"}
}).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
require.Equal(t, http.StatusRequestedRangeNotSatisfiable, rec.Code)
require.Equal(t, "video/mp4", rec.Header().Get("Content-Type"))
require.JSONEq(t, `{"message":"requested range not satisfiable"}`, rec.Body.String())
}
func TestRoutingPreservesEscapedParametersAndOriginalURL(t *testing.T) {
mux := http.NewServeMux()
mux.Handle("/file/{uid}/{filename}", GET(Func(func(w http.ResponseWriter, r *http.Request) error {
require.Equal(t, "abc%31", r.PathValue("uid"))
require.Equal(t, "a%2Fb.txt", r.PathValue("filename"))
require.Equal(t, "/file/abc1/a/b.txt", r.URL.Path)
require.Equal(t, "/file/abc%31/a%2Fb.txt", r.URL.RawPath)
require.Equal(t, "true", r.URL.Query().Get("thumbnail"))
return Text(w, http.StatusOK, "ok")
}), nil))
r := httptest.NewRequest(http.MethodGet, "/file/abc%31/a%2Fb.txt?thumbnail=true", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, RoutingRequest(r))
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "ok", rec.Body.String())
require.Equal(t, "/file/abc1/a/b.txt", r.URL.Path, "routing must not mutate the caller's URL")
}
+43 -33
View File
@@ -4,6 +4,7 @@ import (
"context"
"log/slog"
"net/http"
"strings"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -11,11 +12,11 @@ import (
"connectrpc.com/connect"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/labstack/echo/v5"
"github.com/pkg/errors"
"golang.org/x/sync/semaphore"
"github.com/usememos/memos/core/notification"
"github.com/usememos/memos/internal/httphandler"
"github.com/usememos/memos/internal/linkmeta"
"github.com/usememos/memos/internal/profile"
"github.com/usememos/memos/internal/ratelimit"
@@ -134,8 +135,8 @@ func newGatewayMarshaler() *runtime.HTTPBodyMarshaler {
}
}
// RegisterGateway registers the gRPC-Gateway and Connect handlers with the given Echo instance.
func (s *APIService) RegisterGateway(ctx context.Context, echoServer *echo.Echo) error {
// NewHandler serves REST, Connect, and SSE with shared authentication policies.
func (s *APIService) NewHandler(ctx context.Context) (http.Handler, error) {
// Shared authorizer: one source of truth for authentication and anonymous-access
// policy, used by both the gRPC-Gateway middleware and the Connect interceptor.
authorizer := NewAuthorizer(s.Store, s.Secret).WithRateLimiter(s.RateLimiter)
@@ -146,7 +147,7 @@ func (s *APIService) RegisterGateway(ctx context.Context, echoServer *echo.Echo)
// instead so the policy check actually runs on this transport.
routeResolver, err := newGatewayRouteResolver()
if err != nil {
return errors.Wrap(err, "failed to build gateway route resolver")
return nil, errors.Wrap(err, "failed to build gateway route resolver")
}
gatewayAuthMiddleware := func(next runtime.HandlerFunc) runtime.HandlerFunc {
@@ -192,37 +193,29 @@ func (s *APIService) RegisterGateway(ctx context.Context, echoServer *echo.Echo)
runtime.WithIncomingHeaderMatcher(gatewayIncomingHeaderMatcher),
)
if err := apipb.RegisterInstanceServiceHandlerServer(ctx, gwMux, s); err != nil {
return err
return nil, err
}
if err := apipb.RegisterAuthServiceHandlerServer(ctx, gwMux, s); err != nil {
return err
return nil, err
}
if err := apipb.RegisterUserServiceHandlerServer(ctx, gwMux, s); err != nil {
return err
return nil, err
}
if err := apipb.RegisterMemoServiceHandlerServer(ctx, gwMux, s); err != nil {
return err
return nil, err
}
if err := apipb.RegisterSpaceServiceHandlerServer(ctx, gwMux, s); err != nil {
return err
return nil, err
}
if err := apipb.RegisterAttachmentServiceHandlerServer(ctx, gwMux, s); err != nil {
return err
return nil, err
}
if err := apipb.RegisterAIServiceHandlerServer(ctx, gwMux, s); err != nil {
return err
return nil, err
}
if err := apipb.RegisterIdentityProviderServiceHandlerServer(ctx, gwMux, s); err != nil {
return err
return nil, err
}
gwGroup := echoServer.Group("")
// Register SSE endpoint with same CORS as rest of /api.
RegisterSSERoutes(gwGroup, s.SSEHub, s.Store, s.Secret)
handler := echo.WrapHandler(gwMux)
gwGroup.Any("/api/*", handler)
gwGroup.Any("/file/*", handler)
gwGroup.Any("/api/v1/*", removedAPIVersionHandler(false))
// Connect handlers for browser clients (replaces grpc-web).
logStacktraces := s.Profile.Demo
@@ -240,14 +233,31 @@ func (s *APIService) RegisterGateway(ctx context.Context, echoServer *echo.Echo)
return []connect.HandlerOption{connect.WithReadMaxBytes(int(requestBodyLimit(spec.Procedure)))}
}))
connectGroup := echoServer.Group("")
connectGroup.Any("/memos.api.*", echo.WrapHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, requestBodyLimit(r.URL.Path))
connectMux.ServeHTTP(w, r)
})))
connectGroup.Any("/memos.api.v1.*", removedAPIVersionHandler(true))
return nil
// Prefixes within a path segment (memos.api.*) are dispatched explicitly;
// ServeMux wildcards match complete segments only.
sseMux := http.NewServeMux()
RegisterSSERoutes(sseMux, s.SSEHub, s.Store, s.Secret)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestPath := r.URL.Path
if r.URL.RawPath != "" {
requestPath = r.URL.RawPath
}
switch {
case requestPath == "/api/sse" && r.Method == http.MethodGet:
sseMux.ServeHTTP(w, r)
case strings.HasPrefix(requestPath, "/api/v1/"):
removedAPIVersionHandler(false).ServeHTTP(w, r)
case strings.HasPrefix(requestPath, "/memos.api.v1."):
removedAPIVersionHandler(true).ServeHTTP(w, r)
case strings.HasPrefix(requestPath, "/memos.api."):
r.Body = http.MaxBytesReader(w, r.Body, requestBodyLimit(r.URL.Path))
connectMux.ServeHTTP(w, r)
case strings.HasPrefix(requestPath, "/api/") || strings.HasPrefix(requestPath, "/file/"):
gwMux.ServeHTTP(w, r)
default:
httphandler.NotFound(w, r)
}
}), nil
}
// removedAPIMessage tells clients of the removed v1 API where it went.
@@ -258,13 +268,13 @@ const removedAPIMessage = "API v1 has been removed. Use /api/... for REST and /m
// memos.api.v1 routes with 410 Gone, in the error body shape each transport's
// clients decode. It exists for one release so old clients fail with a
// pointer to the migration; delete it in the release after.
func removedAPIVersionHandler(connectProtocol bool) echo.HandlerFunc {
return func(c *echo.Context) error {
func removedAPIVersionHandler(connectProtocol bool) http.Handler {
return httphandler.Func(func(w http.ResponseWriter, _ *http.Request) error {
if connectProtocol {
return c.JSON(http.StatusGone, map[string]string{"code": connect.CodeUnimplemented.String(), "message": removedAPIMessage})
return httphandler.JSON(w, http.StatusGone, map[string]string{"code": connect.CodeUnimplemented.String(), "message": removedAPIMessage})
}
return c.JSON(http.StatusGone, map[string]any{"code": int(codes.Unimplemented), "message": removedAPIMessage})
}
return httphandler.JSON(w, http.StatusGone, map[string]any{"code": int(codes.Unimplemented), "message": removedAPIMessage})
})
}
func setAPIResponseNoStoreHeaders(header http.Header) {
+4 -3
View File
@@ -8,14 +8,15 @@ import (
"strings"
"testing"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/require"
)
func TestRemovedAPIVersionRoutesReturnGone(t *testing.T) {
svc, _ := newUploadTestService(t)
e := echo.New()
require.NoError(t, svc.RegisterGateway(context.Background(), e))
e := http.NewServeMux()
apiHandler, handlerErr := svc.NewHandler(context.Background())
require.NoError(t, handlerErr)
e.Handle("/", apiHandler)
tests := []struct {
method string
@@ -10,7 +10,6 @@ import (
"testing"
"connectrpc.com/connect"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
@@ -37,8 +36,10 @@ func TestUploadAttachmentTransports(t *testing.T) {
require.NoError(t, err)
token, _, err := auth.GenerateAccessTokenV2(user.ID, user.Username, string(user.Role), string(user.RowStatus), user.PasswordHash, []byte(svc.Secret))
require.NoError(t, err)
e := echo.New()
require.NoError(t, svc.RegisterGateway(context.Background(), e))
e := http.NewServeMux()
apiHandler, handlerErr := svc.NewHandler(context.Background())
require.NoError(t, handlerErr)
e.Handle("/", apiHandler)
for _, path := range []string{"/api/attachments:upload", attachmentUploadProcedure} {
t.Run(path, func(t *testing.T) {
+12 -18
View File
@@ -6,8 +6,7 @@ import (
"net/http"
"time"
"github.com/labstack/echo/v5"
"github.com/usememos/memos/internal/httphandler"
"github.com/usememos/memos/server/auth"
"github.com/usememos/memos/store"
)
@@ -19,34 +18,29 @@ const (
sseHeartbeatComment = ": heartbeat\n\n"
)
type sseRouteRegistrar interface {
GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) echo.RouteInfo
}
// RegisterSSERoutes registers the SSE endpoint on the given Echo router.
func RegisterSSERoutes(router sseRouteRegistrar, hub *SSEHub, storeInstance *store.Store, secret string) {
// RegisterSSERoutes registers the SSE endpoint.
func RegisterSSERoutes(mux *http.ServeMux, hub *SSEHub, storeInstance *store.Store, secret string) {
authenticator := auth.NewAuthenticator(storeInstance, secret)
router.GET("/api/sse", func(c *echo.Context) error {
return handleSSE(c, hub, authenticator)
})
mux.Handle("/api/sse", httphandler.GET(httphandler.Func(func(w http.ResponseWriter, r *http.Request) error {
return handleSSE(w, r, hub, authenticator)
}), nil))
}
// handleSSE handles the SSE connection for live memo refresh.
// Authentication is done via Bearer token in the Authorization header.
func handleSSE(c *echo.Context, hub *SSEHub, authenticator *auth.Authenticator) error {
func handleSSE(w http.ResponseWriter, r *http.Request, hub *SSEHub, authenticator *auth.Authenticator) error {
// Authenticate the request.
authHeader := c.Request().Header.Get("Authorization")
result := authenticator.Authenticate(c.Request().Context(), authHeader)
authHeader := r.Header.Get("Authorization")
result := authenticator.Authenticate(r.Context(), authHeader)
if result == nil {
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "authentication required"})
return httphandler.JSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"})
}
userID := getSSEClientUserID(result)
if userID == 0 {
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "authentication required"})
return httphandler.JSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"})
}
// Set SSE headers.
w := c.Response()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
@@ -67,7 +61,7 @@ func handleSSE(c *echo.Context, hub *SSEHub, authenticator *auth.Authenticator)
client := hub.Subscribe()
defer hub.Unsubscribe(client)
ctx := c.Request().Context()
ctx := r.Context()
slog.Debug("SSE client connected", "userID", userID)
+1 -2
View File
@@ -9,7 +9,6 @@ import (
"testing"
"time"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/require"
apipb "github.com/usememos/memos/proto/gen/api"
@@ -35,7 +34,7 @@ func TestSSEHandler_Authentication(t *testing.T) {
)
require.NoError(t, err)
e := echo.New()
e := http.NewServeMux()
api.RegisterSSERoutes(e, ts.Service.SSEHub, ts.Store, ts.Secret)
t.Run("no token returns 401", func(t *testing.T) {
@@ -7,7 +7,6 @@ import (
"strings"
"testing"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/bcrypt"
"google.golang.org/grpc/codes"
@@ -70,8 +69,10 @@ func TestPasswordChangeRejectsOldAccessToken(t *testing.T) {
authenticator := auth.NewAuthenticator(ts.Store, ts.Secret)
require.NotNil(t, authenticator.Authenticate(ctx, "Bearer "+oldAccess))
e := echo.New()
require.NoError(t, ts.Service.RegisterGateway(ctx, e))
e := http.NewServeMux()
apiHandler, handlerErr := ts.Service.NewHandler(ctx)
require.NoError(t, handlerErr)
e.Handle("/", apiHandler)
updatePassword := func(password, cookie string) *httptest.ResponseRecorder {
t.Helper()
method, path := http.MethodPatch, "/api/users/password-victim?updateMask=password"
+43 -27
View File
@@ -1,41 +1,57 @@
package server
import (
"net/http"
"net/url"
"strings"
"github.com/labstack/echo/v5"
"github.com/labstack/echo/v5/middleware"
"github.com/usememos/memos/internal/httphandler"
"github.com/usememos/memos/internal/profile"
)
func newCORSMiddleware(profile *profile.Profile) echo.MiddlewareFunc {
return middleware.CORSWithConfig(middleware.CORSConfig{
// The API is open to any origin so that token-authenticated clients
// (Access Token V2 / PAT in the Authorization header) can call it from
// anywhere. Credentials — i.e. the SameSite=Lax refresh-token cookie — are
// granted only to trusted origins (same host or the configured InstanceURL).
//
// AllowCredentials stays false here on purpose: the per-origin
// Access-Control-Allow-Credentials header is set inside the func below.
// Do NOT switch this to AllowCredentials:true — emitting that header for
// every reflected origin would let a malicious same-site subdomain read the
// cookie-authenticated /auth/refresh response and steal an access token.
AllowCredentials: false,
UnsafeAllowOriginFunc: func(c *echo.Context, origin string) (string, bool, error) {
// Never reflect the opaque "null" origin (sandboxed iframes, file://).
if origin == "null" {
return "", false, nil
func newCORSMiddleware(profile *profile.Profile, mux *http.ServeMux) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Add("Vary", "Origin")
origin := r.Header.Get("Origin")
preflight := r.Method == http.MethodOptions
allowMethods := ""
if preflight {
handler, _ := mux.Handler(httphandler.RoutingRequest(r))
if route, ok := handler.(interface{ AllowedMethods() string }); ok {
allowMethods = route.AllowedMethods()
if allowMethods != "" {
h.Set("Allow", allowMethods)
}
}
}
// Trusted origins additionally get credentialed (cookie) access.
if isAllowedCORSOrigin(profile, c.Request().Host, origin) {
c.Response().Header().Set(echo.HeaderAccessControlAllowCredentials, "true")
if origin != "" && origin != "null" {
h.Set("Access-Control-Allow-Origin", origin)
// Cookie access remains restricted to trusted origins. Other origins
// may use Authorization tokens, but must not read credentialed responses.
if isAllowedCORSOrigin(profile, r.Host, origin) {
h.Set("Access-Control-Allow-Credentials", "true")
}
if preflight {
h.Add("Vary", "Access-Control-Request-Method")
h.Add("Vary", "Access-Control-Request-Headers")
if allowMethods == "" {
allowMethods = "GET,HEAD,PUT,PATCH,POST,DELETE"
}
h.Set("Access-Control-Allow-Methods", allowMethods)
if headers := r.Header.Get("Access-Control-Request-Headers"); headers != "" {
h.Set("Access-Control-Allow-Headers", headers)
}
}
}
// Reflect every origin; only trusted ones carry the credentials header.
return origin, true, nil
},
})
if preflight {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
}
func isAllowedCORSOrigin(profile *profile.Profile, requestHost, origin string) bool {
+11 -11
View File
@@ -6,8 +6,7 @@ import (
"strings"
"testing"
"github.com/labstack/echo/v5"
"github.com/usememos/memos/internal/httphandler"
"github.com/usememos/memos/internal/profile"
)
@@ -80,11 +79,12 @@ func TestAllowedCORSOrigin(t *testing.T) {
}
func TestCORSMiddleware(t *testing.T) {
e := echo.New()
e.Use(newCORSMiddleware(&profile.Profile{InstanceURL: "https://memos.example"}))
e.POST("/api/test", func(c *echo.Context) error {
return c.NoContent(http.StatusOK)
})
e := http.NewServeMux()
handler := newCORSMiddleware(&profile.Profile{InstanceURL: "https://memos.example"}, e)(e)
e.Handle("POST /api/test", httphandler.Func(func(w http.ResponseWriter, _ *http.Request) error {
w.WriteHeader(http.StatusOK)
return nil
}))
t.Run("trusted origin gets credentialed access", func(t *testing.T) {
req := httptest.NewRequest(http.MethodOptions, "/api/test", nil)
@@ -92,7 +92,7 @@ func TestCORSMiddleware(t *testing.T) {
req.Header.Set("Access-Control-Request-Method", http.MethodPost)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusNoContent {
t.Fatalf("expected status %d, got %d", http.StatusNoContent, rec.Code)
@@ -111,7 +111,7 @@ func TestCORSMiddleware(t *testing.T) {
req.Header.Set("Access-Control-Request-Method", http.MethodPost)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusNoContent {
t.Fatalf("expected status %d, got %d", http.StatusNoContent, rec.Code)
@@ -133,7 +133,7 @@ func TestCORSMiddleware(t *testing.T) {
req.Header.Set("Access-Control-Request-Headers", "Authorization")
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
handler.ServeHTTP(rec, req)
if got := rec.Header().Get("Access-Control-Allow-Headers"); !strings.Contains(strings.ToLower(got), "authorization") {
t.Fatalf("expected Authorization to be allowed for a cross-origin token client, got %q", got)
@@ -146,7 +146,7 @@ func TestCORSMiddleware(t *testing.T) {
req.Header.Set("Access-Control-Request-Method", http.MethodPost)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
handler.ServeHTTP(rec, req)
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" {
t.Fatalf("expected null origin not to be reflected, got %q", got)
+1 -1
View File
@@ -1,4 +1,4 @@
// Package server is the HTTP process: it boots the Echo server, mounts every
// Package server is the HTTP process: it boots the net/http server, mounts every
// transport (server/api, server/fileserver, server/frontend, server/mcp),
// and owns HTTP-only concerns such as auth tokens and process configuration.
//
+100 -98
View File
@@ -16,11 +16,11 @@ import (
"time"
"github.com/disintegration/imaging"
"github.com/labstack/echo/v5"
"github.com/pkg/errors"
"golang.org/x/sync/semaphore"
"github.com/usememos/memos/core/access"
"github.com/usememos/memos/internal/httphandler"
"github.com/usememos/memos/internal/imagelimit"
"github.com/usememos/memos/internal/motionphoto"
"github.com/usememos/memos/internal/profile"
@@ -125,11 +125,10 @@ func NewFileServerService(profile *profile.Profile, store *store.Store, secret s
}
// RegisterRoutes registers HTTP file serving routes.
func (s *FileServerService) RegisterRoutes(echoServer *echo.Echo) {
fileGroup := echoServer.Group("/file")
fileGroup.GET("/attachments/:uid", s.serveAttachmentFile)
fileGroup.GET("/attachments/:uid/:filename", s.serveAttachmentFile)
fileGroup.GET("/users/:identifier/avatar", s.serveUserAvatar)
func (s *FileServerService) RegisterRoutes(mux *http.ServeMux, fallback http.Handler) {
mux.Handle("/file/attachments/{uid}", httphandler.GET(httphandler.Func(s.serveAttachmentFile), fallback))
mux.Handle("/file/attachments/{uid}/{filename}", httphandler.GET(httphandler.Func(s.serveAttachmentFile), fallback))
mux.Handle("/file/users/{identifier}/avatar", httphandler.GET(httphandler.Func(s.serveUserAvatar), fallback))
}
// =============================================================================
@@ -137,103 +136,103 @@ func (s *FileServerService) RegisterRoutes(echoServer *echo.Echo) {
// =============================================================================
// serveAttachmentFile serves attachment binary content using native HTTP.
func (s *FileServerService) serveAttachmentFile(c *echo.Context) error {
ctx := c.Request().Context()
c.Response().Header().Set(echo.HeaderCacheControl, privateAttachmentCacheControl)
uid := c.Param("uid")
wantThumbnail := c.QueryParam("thumbnail") == "true"
wantMotion := c.QueryParam("motion") == "true"
func (s *FileServerService) serveAttachmentFile(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
w.Header().Set("Cache-Control", privateAttachmentCacheControl)
uid := r.PathValue("uid")
wantThumbnail := r.URL.Query().Get("thumbnail") == "true"
wantMotion := r.URL.Query().Get("motion") == "true"
// Authorize on metadata alone. Database-stored bytes are loaded only
// after the read is permitted, so an unauthorized request never pulls a
// blob out of the database.
attachment, err := s.Store.GetAttachment(ctx, &store.FindAttachment{UID: &uid})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get attachment").Wrap(err)
return &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to get attachment", Cause: err}
}
if attachment == nil {
return echo.NewHTTPError(http.StatusNotFound, "attachment not found")
return &httphandler.Error{Code: http.StatusNotFound, Message: "attachment not found"}
}
readClass, err := s.checkAttachmentPermission(ctx, c, attachment)
readClass, err := s.checkAttachmentPermission(ctx, r, attachment)
if err != nil {
return err
}
if readClass == access.MemoReadClassPublic {
c.Response().Header().Set(echo.HeaderCacheControl, publicAttachmentCacheControl)
w.Header().Set("Cache-Control", publicAttachmentCacheControl)
}
if attachment.StorageType != storepb.AttachmentStorageType_LOCAL && attachment.StorageType != storepb.AttachmentStorageType_S3 {
attachment, err = s.Store.GetAttachment(ctx, &store.FindAttachment{ID: &attachment.ID, GetBlob: true})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get attachment").Wrap(err)
return &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to get attachment", Cause: err}
}
if attachment == nil {
return echo.NewHTTPError(http.StatusNotFound, "attachment not found")
return &httphandler.Error{Code: http.StatusNotFound, Message: "attachment not found"}
}
}
if wantMotion {
return s.serveMotionClip(c, attachment)
return s.serveMotionClip(w, r, attachment)
}
contentType := sanitizeContentType(attachment.Type)
// Stream video/audio to avoid loading entire file into memory.
if isMediaType(attachment.Type) {
return s.serveMediaStream(c, attachment, contentType)
return s.serveMediaStream(w, r, attachment, contentType)
}
return s.serveStaticFile(c, attachment, contentType, wantThumbnail)
return s.serveStaticFile(w, r, attachment, contentType, wantThumbnail)
}
// serveUserAvatar serves user avatar images.
func (s *FileServerService) serveUserAvatar(c *echo.Context) error {
ctx := c.Request().Context()
func (s *FileServerService) serveUserAvatar(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
allowAnonymous, err := s.Store.AllowsAnonymousAccess(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get instance access policy").Wrap(err)
return &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to get instance access policy", Cause: err}
}
cacheControl := cacheMaxAge
// On a private instance, avatars are not exposed to anonymous visitors; a
// valid session, access token, or PAT is required.
if !allowAnonymous {
cacheControl = privateAttachmentCacheControl
viewer, err := s.getCurrentUser(ctx, c)
viewer, err := s.getCurrentUser(ctx, r)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get current user").Wrap(err)
return &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to get current user", Cause: err}
}
if viewer == nil {
return echo.NewHTTPError(http.StatusUnauthorized, "unauthorized access")
return &httphandler.Error{Code: http.StatusUnauthorized, Message: "unauthorized access"}
}
}
identifier := c.Param("identifier")
identifier := r.PathValue("identifier")
user, err := s.Store.GetUser(ctx, &store.FindUser{Username: &identifier})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get user").Wrap(err)
return &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to get user", Cause: err}
}
if user == nil {
return echo.NewHTTPError(http.StatusNotFound, "user not found")
return &httphandler.Error{Code: http.StatusNotFound, Message: "user not found"}
}
if user.AvatarURL == "" {
return echo.NewHTTPError(http.StatusNotFound, "avatar not found")
return &httphandler.Error{Code: http.StatusNotFound, Message: "avatar not found"}
}
imageType, imageData, err := parseDataURI(user.AvatarURL)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to parse avatar data").Wrap(err)
return &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to parse avatar data", Cause: err}
}
if !avatarAllowedTypes[imageType] {
return echo.NewHTTPError(http.StatusBadRequest, "invalid avatar image type")
return &httphandler.Error{Code: http.StatusBadRequest, Message: "invalid avatar image type"}
}
setSecurityHeaders(c)
c.Response().Header().Set(echo.HeaderCacheControl, cacheControl)
setSecurityHeaders(w)
w.Header().Set("Cache-Control", cacheControl)
return c.Blob(http.StatusOK, imageType, imageData)
return httphandler.Blob(w, http.StatusOK, imageType, imageData)
}
// =============================================================================
@@ -241,57 +240,57 @@ func (s *FileServerService) serveUserAvatar(c *echo.Context) error {
// =============================================================================
// serveMediaStream serves video/audio files using streaming to avoid memory exhaustion.
func (s *FileServerService) serveMediaStream(c *echo.Context, attachment *store.Attachment, contentType string) error {
setSecurityHeaders(c)
setMediaHeaders(c, contentType, attachment.Type)
func (s *FileServerService) serveMediaStream(w http.ResponseWriter, r *http.Request, attachment *store.Attachment, contentType string) error {
setSecurityHeaders(w)
setMediaHeaders(w, contentType, attachment.Type)
switch attachment.StorageType {
case storepb.AttachmentStorageType_LOCAL:
http.ServeFile(c.Response(), c.Request(), s.resolveLocalPath(attachment.Reference))
http.ServeFile(w, r, s.resolveLocalPath(attachment.Reference))
return nil
case storepb.AttachmentStorageType_S3:
return s.streamS3Object(c, attachment, contentType)
return s.streamS3Object(w, r, attachment, contentType)
default:
// Database storage fallback.
modTime := time.Unix(attachment.UpdatedTs, 0)
http.ServeContent(c.Response(), c.Request(), attachment.Filename, modTime, bytes.NewReader(attachment.Blob))
http.ServeContent(w, r, attachment.Filename, modTime, bytes.NewReader(attachment.Blob))
return nil
}
}
// serveStaticFile serves non-streaming files (images, documents, etc.).
func (s *FileServerService) serveStaticFile(c *echo.Context, attachment *store.Attachment, contentType string, wantThumbnail bool) error {
func (s *FileServerService) serveStaticFile(w http.ResponseWriter, r *http.Request, attachment *store.Attachment, contentType string, wantThumbnail bool) error {
// Generate thumbnail for supported image types.
if wantThumbnail && thumbnailSupportedTypes[attachment.Type] {
if thumbnailBlob, err := s.getOrGenerateThumbnail(c.Request().Context(), attachment); err != nil {
if thumbnailBlob, err := s.getOrGenerateThumbnail(r.Context(), attachment); err != nil {
if !errors.Is(err, errUseOriginalForThumbnail) {
slog.Warn("failed to get thumbnail", "error", err)
}
} else {
setSecurityHeaders(c)
setMediaHeaders(c, "image/jpeg", attachment.Type)
return c.Blob(http.StatusOK, "image/jpeg", thumbnailBlob)
setSecurityHeaders(w)
setMediaHeaders(w, "image/jpeg", attachment.Type)
return httphandler.Blob(w, http.StatusOK, "image/jpeg", thumbnailBlob)
}
}
setSecurityHeaders(c)
setMediaHeaders(c, contentType, attachment.Type)
setSecurityHeaders(w)
setMediaHeaders(w, contentType, attachment.Type)
// Force download for non-media files to prevent XSS execution.
if !strings.HasPrefix(contentType, "image/") && contentType != "application/pdf" {
c.Response().Header().Set(echo.HeaderContentDisposition, fmt.Sprintf("attachment; filename=%q", attachment.Filename))
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", attachment.Filename))
}
switch attachment.StorageType {
case storepb.AttachmentStorageType_LOCAL:
http.ServeFile(c.Response(), c.Request(), s.resolveLocalPath(attachment.Reference))
http.ServeFile(w, r, s.resolveLocalPath(attachment.Reference))
return nil
case storepb.AttachmentStorageType_S3:
return s.streamS3Object(c, attachment, contentType)
return s.streamS3Object(w, r, attachment, contentType)
default:
return c.Blob(http.StatusOK, contentType, attachment.Blob)
return httphandler.Blob(w, http.StatusOK, contentType, attachment.Blob)
}
}
@@ -356,39 +355,42 @@ func (s *FileServerService) resolveLocalPath(reference string) string {
// single Range so media players and document viewers can seek without a direct
// S3 URL. Multipart ranges are ignored and served as a complete response
// because S3 does not support multipart range responses.
func (s *FileServerService) streamS3Object(c *echo.Context, attachment *store.Attachment, contentType string) error {
ctx := c.Request().Context()
func (s *FileServerService) streamS3Object(w http.ResponseWriter, r *http.Request, attachment *store.Attachment, contentType string) error {
ctx := r.Context()
driver, s3Object, err := s.Store.ResolveAttachmentS3Driver(ctx, attachment)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to resolve S3 attachment driver").Wrap(err)
return &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to resolve S3 attachment driver", Cause: err}
}
object, err := driver.GetObjectStream(ctx, s3Object.Key, singleRangeHeader(c.Request().Header))
object, err := driver.GetObjectStream(ctx, s3Object.Key, singleRangeHeader(r.Header))
if err != nil {
if errors.Is(err, storage.ErrRangeNotSatisfiable) {
h := c.Response().Header()
h := w.Header()
h.Set("Accept-Ranges", "bytes")
var rangeErr *storage.RangeNotSatisfiableError
if errors.As(err, &rangeErr) && rangeErr.ContentRange != "" {
h.Set("Content-Range", rangeErr.ContentRange)
}
return echo.NewHTTPError(http.StatusRequestedRangeNotSatisfiable, "requested range not satisfiable")
return &httphandler.Error{Code: http.StatusRequestedRangeNotSatisfiable, Message: "requested range not satisfiable"}
}
return echo.NewHTTPError(http.StatusInternalServerError, "failed to stream from S3").Wrap(err)
return &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to stream from S3", Cause: err}
}
defer object.Body.Close()
h := c.Response().Header()
h := w.Header()
h.Set("Accept-Ranges", "bytes")
if object.ContentLength >= 0 {
h.Set(echo.HeaderContentLength, strconv.FormatInt(object.ContentLength, 10))
h.Set("Content-Length", strconv.FormatInt(object.ContentLength, 10))
}
status := http.StatusOK
if object.ContentRange != "" {
h.Set("Content-Range", object.ContentRange)
status = http.StatusPartialContent
}
return c.Stream(status, contentType, object.Body)
w.Header().Set("Content-Type", contentType)
w.WriteHeader(status)
_, err = io.Copy(w, object.Body)
return err
}
// singleRangeHeader returns a Range value only when it contains one range.
@@ -597,21 +599,21 @@ func calculateThumbnailDimensions(width, height int) (int, int) {
return 0, thumbnailMaxSize // Portrait: constrain height.
}
func (s *FileServerService) serveMotionClip(c *echo.Context, attachment *store.Attachment) error {
func (s *FileServerService) serveMotionClip(w http.ResponseWriter, r *http.Request, attachment *store.Attachment) error {
motionMedia := attachment.Payload.GetMotionMedia()
if motionMedia == nil || motionMedia.Family != storepb.MotionMediaFamily_ANDROID_MOTION_PHOTO || !motionMedia.HasEmbeddedVideo {
return echo.NewHTTPError(http.StatusBadRequest, "attachment does not have motion clip")
return &httphandler.Error{Code: http.StatusBadRequest, Message: "attachment does not have motion clip"}
}
clipBlob, err := s.getOrExtractMotionClip(c.Request().Context(), attachment)
clipBlob, err := s.getOrExtractMotionClip(r.Context(), attachment)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get motion clip").Wrap(err)
return &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to get motion clip", Cause: err}
}
setSecurityHeaders(c)
setMediaHeaders(c, "video/mp4", "video/mp4")
setSecurityHeaders(w)
setMediaHeaders(w, "video/mp4", "video/mp4")
modTime := time.Unix(attachment.UpdatedTs, 0)
http.ServeContent(c.Response(), c.Request(), attachment.UID+".mp4", modTime, bytes.NewReader(clipBlob))
http.ServeContent(w, r, attachment.UID+".mp4", modTime, bytes.NewReader(clipBlob))
return nil
}
@@ -656,40 +658,40 @@ func (s *FileServerService) getMotionPath(attachment *store.Attachment) (string,
// =============================================================================
// checkAttachmentPermission verifies the user has permission to access the attachment.
func (s *FileServerService) checkAttachmentPermission(ctx context.Context, c *echo.Context, attachment *store.Attachment) (access.MemoReadClass, error) {
func (s *FileServerService) checkAttachmentPermission(ctx context.Context, r *http.Request, attachment *store.Attachment) (access.MemoReadClass, error) {
// For unlinked attachments, only the creator or an admin can access, as in
// the API's GetAttachment.
if attachment.MemoID == nil {
user, err := s.getCurrentUser(ctx, c)
user, err := s.getCurrentUser(ctx, r)
if err != nil {
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusInternalServerError, "failed to get current user").Wrap(err)
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to get current user", Cause: err}
}
if user == nil {
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusUnauthorized, "unauthorized access")
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusUnauthorized, Message: "unauthorized access"}
}
if !access.CanManageAttachment(user, attachment) {
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusForbidden, "forbidden access")
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusForbidden, Message: "forbidden access"}
}
return access.MemoReadClassPrivate, nil
}
memo, err := s.Store.GetMemo(ctx, &store.FindMemo{ID: attachment.MemoID})
if err != nil {
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusInternalServerError, "failed to find memo").Wrap(err)
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to find memo", Cause: err}
}
if memo == nil {
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusNotFound, "memo not found")
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusNotFound, Message: "memo not found"}
}
allowAnonymous, err := s.Store.AllowsAnonymousAccess(ctx)
if err != nil {
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusInternalServerError, "failed to get instance access policy").Wrap(err)
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to get instance access policy", Cause: err}
}
var sharedMemoID *int32
if shareToken := (*c).QueryParam("share_token"); shareToken != "" {
if shareToken := r.URL.Query().Get("share_token"); shareToken != "" {
ms, err := s.Store.GetMemoShare(ctx, &store.FindMemoShare{UID: &shareToken})
if err != nil {
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusInternalServerError, "failed to get memo share").Wrap(err)
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to get memo share", Cause: err}
}
if ms != nil && !isMemoShareExpired(ms) {
sharedMemoID = &ms.MemoID
@@ -698,45 +700,45 @@ func (s *FileServerService) checkAttachmentPermission(ctx context.Context, c *ec
facts, err := access.ResolveMemoReadFacts(ctx, s.Store, memo)
if err != nil {
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusInternalServerError, "failed to resolve memo access").Wrap(err)
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to resolve memo access", Cause: err}
}
// Public and exact share-token reads do not depend on browser credentials.
// Decide those first so an expired cookie cannot turn an otherwise valid
// anonymous file request into a server error.
anonymousContext, err := facts.WithViewer(ctx, s.Store, nil, allowAnonymous, sharedMemoID)
if err != nil {
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusInternalServerError, "failed to resolve memo access").Wrap(err)
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to resolve memo access", Cause: err}
}
if anonymousDecision := access.CheckMemoReadContext(anonymousContext); anonymousDecision.Allowed() {
return anonymousDecision.Class, nil
}
user, err := s.getCurrentUser(ctx, c)
user, err := s.getCurrentUser(ctx, r)
if err != nil {
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusInternalServerError, "failed to get current user").Wrap(err)
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to get current user", Cause: err}
}
readContext, err := facts.WithViewer(ctx, s.Store, user, allowAnonymous, sharedMemoID)
if err != nil {
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusInternalServerError, "failed to find space membership").Wrap(err)
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to find space membership", Cause: err}
}
decision := access.CheckMemoReadContext(readContext)
switch decision.Denial {
case access.MemoReadDenialNone:
return decision.Class, nil
case access.MemoReadDenialNotFound:
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusNotFound, "memo not found")
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusNotFound, Message: "memo not found"}
case access.MemoReadDenialUnauthenticated:
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusUnauthorized, "unauthorized access")
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusUnauthorized, Message: "unauthorized access"}
default:
return access.MemoReadClassPrivate, echo.NewHTTPError(http.StatusForbidden, "forbidden access")
return access.MemoReadClassPrivate, &httphandler.Error{Code: http.StatusForbidden, Message: "forbidden access"}
}
}
// getCurrentUser retrieves the current authenticated user from the request.
// Authentication priority: Bearer token (Access Token V2 or PAT) > Refresh token cookie.
func (s *FileServerService) getCurrentUser(ctx context.Context, c *echo.Context) (*store.User, error) {
authHeader := c.Request().Header.Get(echo.HeaderAuthorization)
cookieHeader := c.Request().Header.Get("Cookie")
func (s *FileServerService) getCurrentUser(ctx context.Context, r *http.Request) (*store.User, error) {
authHeader := r.Header.Get("Authorization")
cookieHeader := r.Header.Get("Cookie")
return s.authenticator.AuthenticateToUser(ctx, authHeader, cookieHeader)
}
@@ -779,19 +781,19 @@ func isMediaType(mimeType string) bool {
}
// setSecurityHeaders sets common security headers for all responses.
func setSecurityHeaders(c *echo.Context) {
h := c.Response().Header()
func setSecurityHeaders(w http.ResponseWriter) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline';")
}
// setMediaHeaders sets headers for media file responses.
func setMediaHeaders(c *echo.Context, contentType, originalType string) {
h := c.Response().Header()
h.Set(echo.HeaderContentType, contentType)
if h.Get(echo.HeaderCacheControl) == "" {
h.Set(echo.HeaderCacheControl, cacheMaxAge)
func setMediaHeaders(w http.ResponseWriter, contentType, originalType string) {
h := w.Header()
h.Set("Content-Type", contentType)
if h.Get("Cache-Control") == "" {
h.Set("Cache-Control", cacheMaxAge)
}
// Support HDR/wide color gamut for images and videos.
+46 -46
View File
@@ -18,11 +18,11 @@ import (
"testing"
"time"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/usememos/memos/internal/httphandler"
"github.com/usememos/memos/internal/profile"
"github.com/usememos/memos/internal/random"
"github.com/usememos/memos/internal/testutil"
@@ -80,14 +80,14 @@ func TestServeAttachmentFile_S3(t *testing.T) {
}})
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
recorder := httptest.NewRecorder()
e.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, fmt.Sprintf("/file/%s/%s", attachment.Name, attachment.Filename), nil))
require.Equal(t, http.StatusOK, recorder.Code)
require.Equal(t, content, recorder.Body.Bytes())
require.Equal(t, "text/plain; charset=utf-8", recorder.Header().Get(echo.HeaderContentType))
require.Equal(t, "text/plain; charset=utf-8", recorder.Header().Get("Content-Type"))
// S3 cannot produce multipart range responses. The fileserver may ignore a
// Range request and send the complete representation instead of forwarding
@@ -142,8 +142,8 @@ func TestServeAttachmentFile_ShareTokenAllowsDirectMemoAttachment(t *testing.T)
require.NoError(t, err)
shareToken := share.Name[strings.LastIndex(share.Name, "/")+1:]
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/file/%s/%s?share_token=%s", attachment.Name, attachment.Filename, shareToken), nil)
req.AddCookie(newExpiredRefreshTokenCookie(ctx, t, stores, creator.ID, svc.Secret))
@@ -179,14 +179,14 @@ func TestServeAttachmentFile_CanonicalRouteAndVisibilityAwareCache(t *testing.T)
}})
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
url := "/file/" + attachment.Name
rec := httptest.NewRecorder()
e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, url, nil))
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "canonical image", rec.Body.String())
require.Equal(t, publicAttachmentCacheControl, rec.Header().Get(echo.HeaderCacheControl))
require.Equal(t, publicAttachmentCacheControl, rec.Header().Get("Cache-Control"))
_, err = svc.UpdateMemo(creatorCtx, &apipb.UpdateMemoRequest{
Memo: &apipb.Memo{Name: memo.Name, Visibility: apipb.Visibility_PROTECTED},
@@ -196,7 +196,7 @@ func TestServeAttachmentFile_CanonicalRouteAndVisibilityAwareCache(t *testing.T)
rec = httptest.NewRecorder()
e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, url, nil))
require.Equal(t, http.StatusUnauthorized, rec.Code)
require.Equal(t, privateAttachmentCacheControl, rec.Header().Get(echo.HeaderCacheControl))
require.Equal(t, privateAttachmentCacheControl, rec.Header().Get("Cache-Control"))
}
func TestServeAttachmentFileMemoCreatorLifecycle(t *testing.T) {
@@ -218,8 +218,8 @@ func TestServeAttachmentFileMemoCreatorLifecycle(t *testing.T) {
}})
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
url := fmt.Sprintf("/file/%s/%s", attachment.Name, attachment.Filename)
archived := store.Archived
_, err = stores.UpdateUser(ctx, &store.UpdateUser{ID: creator.ID, RowStatus: &archived})
@@ -269,8 +269,8 @@ func TestServeAttachmentFile_CommentUsesOwnVisibility(t *testing.T) {
})
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
url := "/file/" + attachment.Name
rec := httptest.NewRecorder()
e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, url, nil))
@@ -284,7 +284,7 @@ func TestServeAttachmentFile_CommentUsesOwnVisibility(t *testing.T) {
rec = httptest.NewRecorder()
e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, url, nil))
require.Equal(t, http.StatusOK, rec.Code, "changing the context memo must not change attachment access")
require.Equal(t, publicAttachmentCacheControl, rec.Header().Get(echo.HeaderCacheControl))
require.Equal(t, publicAttachmentCacheControl, rec.Header().Get("Cache-Control"))
_, err = svc.UpdateMemo(commenterCtx, &apipb.UpdateMemoRequest{
Memo: &apipb.Memo{Name: comment.Name, Visibility: apipb.Visibility_PROTECTED},
@@ -294,7 +294,7 @@ func TestServeAttachmentFile_CommentUsesOwnVisibility(t *testing.T) {
rec = httptest.NewRecorder()
e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, url, nil))
require.Equal(t, http.StatusUnauthorized, rec.Code)
require.Equal(t, privateAttachmentCacheControl, rec.Header().Get(echo.HeaderCacheControl))
require.Equal(t, privateAttachmentCacheControl, rec.Header().Get("Cache-Control"))
}
func TestServeAttachmentFile_LocalStaticFileSupportsRangeRequests(t *testing.T) {
@@ -330,8 +330,8 @@ func TestServeAttachmentFile_LocalStaticFileSupportsRangeRequests(t *testing.T)
})
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/file/%s/%s", attachment.Name, attachment.Filename), nil)
req.Header.Set("Range", "bytes=2-5")
@@ -400,8 +400,8 @@ func TestServeAttachmentFile_ShareTokenRejectsCommentAttachment(t *testing.T) {
require.NoError(t, err)
shareToken := share.Name[strings.LastIndex(share.Name, "/")+1:]
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/file/%s/%s?share_token=%s", commentAttachment.Name, commentAttachment.Filename, shareToken), nil)
rec := httptest.NewRecorder()
@@ -443,8 +443,8 @@ func TestServeAttachmentFile_MotionClip(t *testing.T) {
})
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/file/%s/%s?motion=true", attachment.Name, attachment.Filename), nil)
rec := httptest.NewRecorder()
@@ -489,8 +489,8 @@ func TestServeAttachmentFile_SVGThumbnailServedAsImageWithSecurityHeaders(t *tes
})
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/file/%s/%s?thumbnail=true", attachment.Name, attachment.Filename), nil)
rec := httptest.NewRecorder()
@@ -538,8 +538,8 @@ func TestServeAttachmentFile_ThumbnailWithSensitiveMetadataServesOriginal(t *tes
})
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/file/%s/%s?thumbnail=true", attachment.Name, attachment.Filename), nil)
rec := httptest.NewRecorder()
@@ -698,8 +698,8 @@ func TestServeAttachmentFile_PrivateInstanceDeniesAnonymous(t *testing.T) {
})
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
url := fmt.Sprintf("/file/%s/%s", attachment.Name, attachment.Filename)
anonymousGet := func() int {
@@ -742,8 +742,8 @@ func TestServeUserAvatar_PrivateInstanceRequiresAuth(t *testing.T) {
})
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
anonymousGet := func() *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
@@ -755,7 +755,7 @@ func TestServeUserAvatar_PrivateInstanceRequiresAuth(t *testing.T) {
setInstanceAccessMode(ctx, t, stores, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC)
publicRec := anonymousGet()
require.Equal(t, http.StatusOK, publicRec.Code)
require.Equal(t, cacheMaxAge, publicRec.Header().Get(echo.HeaderCacheControl))
require.Equal(t, cacheMaxAge, publicRec.Header().Get("Cache-Control"))
// A stale browser session must not turn a public avatar request into an
// authentication error.
@@ -764,7 +764,7 @@ func TestServeUserAvatar_PrivateInstanceRequiresAuth(t *testing.T) {
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "image/png", rec.Header().Get(echo.HeaderContentType))
require.Equal(t, "image/png", rec.Header().Get("Content-Type"))
// Private instance: anonymous avatar access is denied.
setInstanceAccessMode(ctx, t, stores, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE)
@@ -785,7 +785,7 @@ func TestServeUserAvatar_PrivateInstanceRequiresAuth(t *testing.T) {
privateRec := httptest.NewRecorder()
e.ServeHTTP(privateRec, privateReq)
require.Equal(t, http.StatusOK, privateRec.Code)
require.Equal(t, privateAttachmentCacheControl, privateRec.Header().Get(echo.HeaderCacheControl))
require.Equal(t, privateAttachmentCacheControl, privateRec.Header().Get("Cache-Control"))
}
// TestServeAttachmentFile_RefreshCookieAuthenticatesOwner verifies that the file
@@ -833,8 +833,8 @@ func TestServeAttachmentFile_RefreshCookieAuthenticatesOwner(t *testing.T) {
refreshToken, _, err := auth.GenerateRefreshToken(owner.ID, tokenID, []byte(svc.Secret))
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
url := fmt.Sprintf("/file/%s/%s", attachment.Name, attachment.Filename)
// Without credentials, the private attachment is denied.
@@ -877,8 +877,8 @@ func TestServeAttachmentFile_UnlinkedAttachmentOwnerOrAdmin(t *testing.T) {
})
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
url := fmt.Sprintf("/file/%s/%s", attachment.Name, attachment.Filename)
getAs := func(user *store.User) int {
req := httptest.NewRequest(http.MethodGet, url, nil)
@@ -968,13 +968,13 @@ func TestServeAttachmentFile_ThumbnailRefusesOversizedImage(t *testing.T) {
bomb := oversizedPNGHeader(100_000, 100_000)
attachment := createPublicImageMemo(ctx, t, svc, "bomb-owner", "bomb.png", "image/png", bomb)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
for range 2 {
rec := httptest.NewRecorder()
e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, fmt.Sprintf("/file/%s/bomb.png?thumbnail=true", attachment.Name), nil))
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "image/png", rec.Header().Get(echo.HeaderContentType))
require.Equal(t, "image/png", rec.Header().Get("Content-Type"))
require.Equal(t, bomb, rec.Body.Bytes(), "original is served instead of a thumbnail")
}
uid := strings.TrimPrefix(attachment.Name, "attachments/")
@@ -1024,12 +1024,12 @@ func TestDeleteAttachmentRemovesCachedThumbnail(t *testing.T) {
owner, err := svc.Store.GetUser(ctx, &store.FindUser{Username: func() *string { s := "thumb-owner"; return &s }()})
require.NoError(t, err)
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
rec := httptest.NewRecorder()
e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, fmt.Sprintf("/file/%s/small.png?thumbnail=true", attachment.Name), nil))
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "image/jpeg", rec.Header().Get(echo.HeaderContentType))
require.Equal(t, "image/jpeg", rec.Header().Get("Content-Type"))
uid := strings.TrimPrefix(attachment.Name, "attachments/")
thumbnailPath := filepath.Join(fs.Profile.Data, thumbnailCacheFolder, uid+".v2.jpeg")
require.FileExists(t, thumbnailPath)
@@ -1065,8 +1065,8 @@ func TestThumbnailFailureMarkerOnlyForUnsupportedImages(t *testing.T) {
localPath := fs.resolveLocalPath(stored.Reference)
require.NoError(t, os.Rename(localPath, localPath+".away"))
e := echo.New()
fs.RegisterRoutes(e)
e := http.NewServeMux()
fs.RegisterRoutes(e, http.HandlerFunc(httphandler.NotFound))
rec := httptest.NewRecorder()
e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, fmt.Sprintf("/file/%s/gone.png?thumbnail=true", attachment.Name), nil))
marker := filepath.Join(fs.Profile.Data, thumbnailCacheFolder, uid+".v2.jpeg"+thumbnailFailedMarkerSuffix)
@@ -1077,5 +1077,5 @@ func TestThumbnailFailureMarkerOnlyForUnsupportedImages(t *testing.T) {
rec = httptest.NewRecorder()
e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, fmt.Sprintf("/file/%s/gone.png?thumbnail=true", attachment.Name), nil))
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "image/jpeg", rec.Header().Get(echo.HeaderContentType))
require.Equal(t, "image/jpeg", rec.Header().Get("Content-Type"))
}
+76 -59
View File
@@ -4,15 +4,15 @@ import (
"context"
"embed"
"encoding/xml"
"io"
"io/fs"
"net/http"
"path"
"strings"
"github.com/labstack/echo/v5"
"github.com/labstack/echo/v5/middleware"
"github.com/pkg/errors"
"github.com/usememos/memos/internal/httphandler"
"github.com/usememos/memos/internal/profile"
"github.com/usememos/memos/store"
)
@@ -38,45 +38,54 @@ func NewFrontendService(profile *profile.Profile, store *store.Store) *FrontendS
}
}
func (s *FrontendService) Serve(_ context.Context, e *echo.Echo) {
frontendFS := getFileSystem("dist")
skipper := func(c *echo.Context) bool {
requestPath := c.Request().URL.Path
if shouldSkipFrontendStatic(requestPath) {
return true
}
setFrontendCacheHeaders(c, requestPath)
return false
}
// Route to serve the frontend static assets.
e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
Filesystem: frontendFS,
Skipper: skipper,
}))
e.Use(spaFallbackMiddleware(frontendFS))
s.registerRoutes(e)
func (s *FrontendService) Serve(_ context.Context, mux *http.ServeMux, fallback http.Handler) {
mux.Handle("/robots.txt", httphandler.GET(httphandler.Func(s.getRobotsTXT), nil))
mux.Handle("/sitemap.xml", httphandler.GET(httphandler.Func(s.getSitemapXML), nil))
mux.Handle("/", s.Handler(fallback))
}
func spaFallbackMiddleware(frontendFS fs.FS) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
err := next(c)
if err == nil {
return nil
}
requestPath := c.Request().URL.Path
if shouldSkipFrontendStatic(requestPath) || !shouldServeFrontendHTML(requestPath) || echo.StatusCode(err) != http.StatusNotFound {
return err
}
setFrontendCacheHeaders(c, requestPath)
return c.FileFS("index.html", frontendFS)
// Handler serves static files and SPA routes, passing API namespaces to fallback.
func (*FrontendService) Handler(fallback http.Handler) http.Handler {
frontendFS := getFileSystem("dist")
return httphandler.Func(func(w http.ResponseWriter, r *http.Request) error {
requestPath := r.URL.Path
if shouldSkipFrontendStatic(requestPath) {
fallback.ServeHTTP(w, r)
return nil
}
}
setFrontendCacheHeaders(w, requestPath)
filename := strings.TrimPrefix(path.Clean("/"+requestPath), "/")
if filename == "" {
filename = "index.html"
}
info, err := fs.Stat(frontendFS, filename)
if err == nil && info.IsDir() {
filename = path.Join(filename, "index.html")
_, err = fs.Stat(frontendFS, filename)
}
if err != nil {
if !shouldServeFrontendHTML(requestPath) {
return &httphandler.Error{Code: http.StatusNotFound, Message: http.StatusText(http.StatusNotFound)}
}
filename = "index.html"
}
// ServeContent avoids FileServer's /index.html and directory redirects.
file, err := frontendFS.Open(filename)
if err != nil {
return err
}
defer file.Close()
info, err = file.Stat()
if err != nil {
return err
}
content, ok := file.(io.ReadSeeker)
if !ok {
return errors.New("frontend file does not support seeking")
}
http.ServeContent(w, r, info.Name(), info.ModTime(), content)
return nil
})
}
func shouldSkipFrontendStatic(requestPath string) bool {
@@ -89,11 +98,19 @@ func shouldSkipFrontendStatic(requestPath string) bool {
strings.HasPrefix(requestPath, "/memos.api.")
}
func setFrontendCacheHeaders(c *echo.Context, requestPath string) {
// SetCacheHeaders applies the frontend cache policy before route dispatch.
// Dynamic namespaces and discovery routes manage their own cache headers.
func SetCacheHeaders(w http.ResponseWriter, r *http.Request) {
if !shouldSkipFrontendStatic(r.URL.Path) {
setFrontendCacheHeaders(w, r.URL.Path)
}
}
func setFrontendCacheHeaders(w http.ResponseWriter, requestPath string) {
if shouldServeFrontendHTML(requestPath) {
c.Response().Header().Set(echo.HeaderCacheControl, frontendHTMLCacheControl)
c.Response().Header().Set("Pragma", "no-cache")
c.Response().Header().Set("Expires", "0")
w.Header().Set("Cache-Control", frontendHTMLCacheControl)
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
return
}
@@ -101,7 +118,7 @@ func setFrontendCacheHeaders(c *echo.Context, requestPath string) {
if strings.HasPrefix(requestPath, "/assets/") {
cacheControl = frontendHashedAssetCacheControl
}
c.Response().Header().Set(echo.HeaderCacheControl, cacheControl)
w.Header().Set("Cache-Control", cacheControl)
}
func shouldServeFrontendHTML(requestPath string) bool {
@@ -120,13 +137,8 @@ func getFileSystem(path string) fs.FS {
return sub
}
func (s *FrontendService) registerRoutes(e *echo.Echo) {
e.GET("/robots.txt", s.getRobotsTXT)
e.GET("/sitemap.xml", s.getSitemapXML)
}
func (s *FrontendService) getRobotsTXT(c *echo.Context) error {
if err := s.requirePublicAccess(c.Request().Context()); err != nil {
func (s *FrontendService) getRobotsTXT(w http.ResponseWriter, r *http.Request) error {
if err := s.requirePublicAccess(r.Context()); err != nil {
return err
}
instanceURL, err := normalizeInstanceURL(s.Profile.InstanceURL)
@@ -140,11 +152,11 @@ func (s *FrontendService) getRobotsTXT(c *echo.Context) error {
"Host: " + instanceURL,
"Sitemap: " + instanceURL + "/sitemap.xml",
}, "\n")
return c.String(http.StatusOK, robotsTXT)
return httphandler.Text(w, http.StatusOK, robotsTXT)
}
func (s *FrontendService) getSitemapXML(c *echo.Context) error {
if err := s.requirePublicAccess(c.Request().Context()); err != nil {
func (s *FrontendService) getSitemapXML(w http.ResponseWriter, r *http.Request) error {
if err := s.requirePublicAccess(r.Context()); err != nil {
return err
}
instanceURL, err := normalizeInstanceURL(s.Profile.InstanceURL)
@@ -153,7 +165,7 @@ func (s *FrontendService) getSitemapXML(c *echo.Context) error {
}
normal := store.Normal
memos, err := s.Store.ListMemos(c.Request().Context(), &store.FindMemo{
memos, err := s.Store.ListMemos(r.Context(), &store.FindMemo{
RowStatus: &normal,
VisibilityList: []store.Visibility{store.Public},
Access: &store.MemoAccessScope{AllowPublic: true},
@@ -164,7 +176,7 @@ func (s *FrontendService) getSitemapXML(c *echo.Context) error {
}
// The set of public memo URLs changes with audience updates. Require
// revalidation so a revoked URL is not retained by an intermediary cache.
c.Response().Header().Set(echo.HeaderCacheControl, "public, no-cache")
w.Header().Set("Cache-Control", "public, no-cache")
urls := make([]sitemapURL, 0, len(memos))
for _, memo := range memos {
@@ -173,7 +185,12 @@ func (s *FrontendService) getSitemapXML(c *echo.Context) error {
})
}
return c.XML(http.StatusOK, sitemapURLSet{
w.Header().Set("Content-Type", "application/xml; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if _, err := io.WriteString(w, xml.Header); err != nil {
return err
}
return xml.NewEncoder(w).Encode(sitemapURLSet{
XMLNS: sitemapXMLNamespace,
URLs: urls,
})
@@ -182,10 +199,10 @@ func (s *FrontendService) getSitemapXML(c *echo.Context) error {
func (s *FrontendService) requirePublicAccess(ctx context.Context) error {
allowsAnonymous, err := s.Store.AllowsAnonymousAccess(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to get instance access policy").Wrap(err)
return &httphandler.Error{Code: http.StatusInternalServerError, Message: "failed to get instance access policy", Cause: err}
}
if !allowsAnonymous {
return echo.NewHTTPError(http.StatusNotFound, "public instance discovery is unavailable")
return &httphandler.Error{Code: http.StatusNotFound, Message: "public instance discovery is unavailable"}
}
return nil
}
@@ -193,7 +210,7 @@ func (s *FrontendService) requirePublicAccess(ctx context.Context) error {
func normalizeInstanceURL(instanceURL string) (string, error) {
instanceURL = strings.TrimRight(instanceURL, "/")
if instanceURL == "" {
return "", echo.NewHTTPError(http.StatusNotFound, "instance URL is not configured")
return "", &httphandler.Error{Code: http.StatusNotFound, Message: "instance URL is not configured"}
}
return instanceURL, nil
}
+23 -26
View File
@@ -6,9 +6,9 @@ import (
"net/http/httptest"
"testing"
"github.com/labstack/echo/v5"
"github.com/stretchr/testify/require"
"github.com/usememos/memos/internal/httphandler"
"github.com/usememos/memos/internal/profile"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/store"
@@ -56,16 +56,13 @@ func TestFrontendService_CacheHeaderRules(t *testing.T) {
},
}
e := echo.New()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, tt.path, nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
setFrontendCacheHeaders(c, tt.path)
setFrontendCacheHeaders(rec, tt.path)
require.Equal(t, tt.cacheControl, rec.Header().Get(echo.HeaderCacheControl))
require.Equal(t, tt.cacheControl, rec.Header().Get("Cache-Control"))
require.Equal(t, tt.pragma, rec.Header().Get("Pragma"))
require.Equal(t, tt.expires, rec.Header().Get("Expires"))
})
@@ -76,8 +73,8 @@ func TestFrontendService_StaticCacheHeaders(t *testing.T) {
ctx := context.Background()
testStore := teststore.NewTestingStore(ctx, t)
e := echo.New()
NewFrontendService(&profile.Profile{}, testStore).Serve(ctx, e)
e := http.NewServeMux()
NewFrontendService(&profile.Profile{}, testStore).Serve(ctx, e, http.HandlerFunc(httphandler.NotFound))
tests := []struct {
name string
@@ -116,7 +113,7 @@ func TestFrontendService_StaticCacheHeaders(t *testing.T) {
e.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, tt.cacheControl, rec.Header().Get(echo.HeaderCacheControl))
require.Equal(t, tt.cacheControl, rec.Header().Get("Cache-Control"))
require.Equal(t, tt.pragma, rec.Header().Get("Pragma"))
require.Equal(t, tt.expires, rec.Header().Get("Expires"))
})
@@ -127,8 +124,8 @@ func TestFrontendService_MissingAssetDoesNotFallbackToIndex(t *testing.T) {
ctx := context.Background()
testStore := teststore.NewTestingStore(ctx, t)
e := echo.New()
NewFrontendService(&profile.Profile{}, testStore).Serve(ctx, e)
e := http.NewServeMux()
NewFrontendService(&profile.Profile{}, testStore).Serve(ctx, e, http.HandlerFunc(httphandler.NotFound))
req := httptest.NewRequest(http.MethodGet, "/assets/missing.js", nil)
rec := httptest.NewRecorder()
@@ -141,18 +138,18 @@ func TestFrontendService_SkipsDynamicRoutes(t *testing.T) {
ctx := context.Background()
testStore := teststore.NewTestingStore(ctx, t)
e := echo.New()
NewFrontendService(&profile.Profile{}, testStore).Serve(ctx, e)
e.GET("/api/test", func(c *echo.Context) error {
return c.String(http.StatusOK, "ok")
})
e := http.NewServeMux()
NewFrontendService(&profile.Profile{}, testStore).Serve(ctx, e, http.HandlerFunc(httphandler.NotFound))
e.Handle("GET /api/test", httphandler.Func(func(w http.ResponseWriter, _ *http.Request) error {
return httphandler.Text(w, http.StatusOK, "ok")
}))
req := httptest.NewRequest(http.MethodGet, "/api/test", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Empty(t, rec.Header().Get(echo.HeaderCacheControl))
require.Empty(t, rec.Header().Get("Cache-Control"))
}
func TestFrontendService_RobotsTXT(t *testing.T) {
@@ -163,8 +160,8 @@ func TestFrontendService_RobotsTXT(t *testing.T) {
InstanceURL: "https://demo.usememos.com/",
}
e := echo.New()
NewFrontendService(profile, testStore).Serve(ctx, e)
e := http.NewServeMux()
NewFrontendService(profile, testStore).Serve(ctx, e, http.HandlerFunc(httphandler.NotFound))
req := httptest.NewRequest(http.MethodGet, "/robots.txt", nil)
rec := httptest.NewRecorder()
@@ -206,8 +203,8 @@ func TestFrontendService_SitemapXML(t *testing.T) {
})
require.NoError(t, err)
e := echo.New()
NewFrontendService(profile, testStore).Serve(ctx, e)
e := http.NewServeMux()
NewFrontendService(profile, testStore).Serve(ctx, e, http.HandlerFunc(httphandler.NotFound))
req := httptest.NewRequest(http.MethodGet, "/sitemap.xml", nil)
rec := httptest.NewRecorder()
@@ -215,7 +212,7 @@ func TestFrontendService_SitemapXML(t *testing.T) {
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, rec.Header().Get("Content-Type"), "application/xml")
require.Equal(t, "public, no-cache", rec.Header().Get(echo.HeaderCacheControl))
require.Equal(t, "public, no-cache", rec.Header().Get("Cache-Control"))
require.Contains(t, rec.Body.String(), `<loc>https://demo.usememos.com/memos/publicmemo</loc>`)
require.NotContains(t, rec.Body.String(), "privatememo")
}
@@ -225,8 +222,8 @@ func TestFrontendService_SitemapRoutesRequireInstanceURL(t *testing.T) {
testStore := teststore.NewTestingStore(ctx, t)
setFrontendAccessMode(ctx, t, testStore, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PUBLIC)
e := echo.New()
NewFrontendService(&profile.Profile{}, testStore).Serve(ctx, e)
e := http.NewServeMux()
NewFrontendService(&profile.Profile{}, testStore).Serve(ctx, e, http.HandlerFunc(httphandler.NotFound))
for _, path := range []string{"/robots.txt", "/sitemap.xml"} {
req := httptest.NewRequest(http.MethodGet, path, nil)
@@ -242,8 +239,8 @@ func TestFrontendService_SitemapRoutesRequirePublicAccess(t *testing.T) {
testStore := teststore.NewTestingStore(ctx, t)
setFrontendAccessMode(ctx, t, testStore, storepb.InstanceAccessMode_INSTANCE_ACCESS_MODE_PRIVATE)
e := echo.New()
NewFrontendService(&profile.Profile{InstanceURL: "https://private.example.com"}, testStore).Serve(ctx, e)
e := http.NewServeMux()
NewFrontendService(&profile.Profile{InstanceURL: "https://private.example.com"}, testStore).Serve(ctx, e, http.HandlerFunc(httphandler.NotFound))
for _, path := range []string{"/robots.txt", "/sitemap.xml"} {
req := httptest.NewRequest(http.MethodGet, path, nil)
+148
View File
@@ -0,0 +1,148 @@
package server
import (
"bufio"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/usememos/memos/internal/profile"
"github.com/usememos/memos/server/auth"
"github.com/usememos/memos/store"
teststore "github.com/usememos/memos/store/test"
)
type httpSnapshot struct {
Method string
Path string
RequestHeader http.Header
Status int
Header http.Header
Body string
}
// These responses were captured from the Echo implementation before replacing
// the router. Keep the transport boundaries and HTTP error contracts unchanged.
func TestHTTPCompatibility(t *testing.T) {
ctx := context.Background()
stores := teststore.NewTestingStore(ctx, t)
s, err := NewServer(ctx, &profile.Profile{Data: t.TempDir(), InstanceURL: "https://memos.example"}, stores)
require.NoError(t, err)
t.Cleanup(func() { s.apiService.CloseUploads(); s.apiService.SSEHub.Close() })
var snapshots []httpSnapshot
for _, path := range []string{
"/healthz", "/healthz/", "/health%7A", "/api", "/api/", "/api/missing", "/api/sse", "/api/sse/",
"/api/v1", "/api/v1/", "/api/v1/memos", "/file", "/file/", "/file/attachments/missing", "/file/attachments/missing/",
"/file/attachments/missing/a%2Fb.txt", "/file/attachments/%6dissing/file.txt", "/file/%61ttachments/missing/file.txt",
"/memos.api", "/memos.api.", "/memos.api.UnknownService/Unknown", "/memos.api.v1.MemoService/ListMemos",
"/memos/x", "/assets/missing.js", "/index.html", "/robots.txt", "/sitemap.xml",
"/api//instance/profile", "/api/../healthz", "/api/instance/profile/", "/mcp/",
} {
for _, method := range []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodOptions} {
rec := httptest.NewRecorder()
s.handler.ServeHTTP(rec, httptest.NewRequest(method, path, nil))
body := rec.Body.String()
if strings.Contains(strings.ToLower(body), "<!doctype html>") {
body = "<frontend HTML>"
}
header := rec.Header().Clone()
// The bundled SPA may be rebuilt independently of server code.
header.Del("Content-Length")
header.Del("Last-Modified")
snapshots = append(snapshots, httpSnapshot{Method: method, Path: path, Status: rec.Code, Header: header, Body: body})
}
}
for _, path := range []string{"/healthz", "/api/missing", "/memos/x"} {
for _, origin := range []string{"https://memos.example", "https://evil.example", "null"} {
for _, method := range []string{http.MethodGet, http.MethodOptions} {
req := httptest.NewRequest(method, path, nil)
req.Header.Set("Origin", origin)
req.Header.Set("Access-Control-Request-Method", "POST")
req.Header.Set("Access-Control-Request-Headers", "Authorization,Content-Type")
rec := httptest.NewRecorder()
s.handler.ServeHTTP(rec, req)
body := rec.Body.String()
if strings.Contains(strings.ToLower(body), "<!doctype html>") {
body = "<frontend HTML>"
}
header := rec.Header().Clone()
header.Del("Content-Length")
header.Del("Last-Modified")
snapshots = append(snapshots, httpSnapshot{Method: method, Path: path, RequestHeader: req.Header, Status: rec.Code, Header: header, Body: body})
}
}
}
f, err := os.Open("testdata/http_compat.jsonl")
require.NoError(t, err)
defer f.Close()
decoder := json.NewDecoder(f)
for _, got := range snapshots {
t.Run(got.Method+" "+got.Path+" "+got.RequestHeader.Get("Origin"), func(t *testing.T) {
var want httpSnapshot
require.NoError(t, decoder.Decode(&want))
if strings.HasPrefix(want.Header.Get("Content-Type"), "application/json") && want.Body != "" {
require.JSONEq(t, want.Body, got.Body)
want.Body, got.Body = "", ""
}
require.Equal(t, want, got)
})
}
var extra httpSnapshot
require.ErrorIs(t, decoder.Decode(&extra), io.EOF)
}
func TestHTTPStreaming(t *testing.T) {
ctx := context.Background()
stores := teststore.NewTestingStore(ctx, t)
s, err := NewServer(ctx, &profile.Profile{Data: t.TempDir()}, stores)
require.NoError(t, err)
t.Cleanup(func() { s.apiService.CloseUploads(); s.apiService.SSEHub.Close() })
user, err := stores.CreateUser(ctx, &store.User{Username: "stream-owner", Role: store.RoleUser})
require.NoError(t, err)
token, _, err := auth.GenerateAccessTokenV2(user.ID, user.Username, string(user.Role), string(user.RowStatus), user.PasswordHash, []byte(s.Secret))
require.NoError(t, err)
server := httptest.NewTestServer(t, s.handler)
client := server.Client()
streamCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(streamCtx, http.MethodGet, server.URL+"/api/sse", nil)
require.NoError(t, err)
req.Header.Set("Authorization", "Bearer "+token)
response, err := client.Do(req)
require.NoError(t, err)
defer response.Body.Close()
require.Equal(t, http.StatusOK, response.StatusCode)
require.Equal(t, "text/event-stream", response.Header.Get("Content-Type"))
reader := bufio.NewReader(response.Body)
line, err := reader.ReadString('\n')
require.NoError(t, err)
require.Equal(t, ": connected\n", line)
line, err = reader.ReadString('\n')
require.NoError(t, err)
require.Equal(t, "\n", line)
create, err := http.NewRequestWithContext(streamCtx, http.MethodPost, server.URL+"/api/memos", strings.NewReader(`{"memoId":"streamed","content":"streamed memo"}`))
require.NoError(t, err)
create.Header.Set("Authorization", "Bearer "+token)
create.Header.Set("Content-Type", "application/json")
created, err := client.Do(create)
require.NoError(t, err)
defer created.Body.Close()
require.Equal(t, http.StatusOK, created.StatusCode)
line, err = reader.ReadString('\n')
require.NoError(t, err)
require.Equal(t, "data: {\"type\":\"memo.changed\"}\n", line)
s.apiService.SSEHub.Close()
_, err = io.ReadAll(reader)
require.NoError(t, err, "closing the hub must terminate the HTTP stream")
}
+7 -7
View File
@@ -10,19 +10,19 @@ REST API.** The package owns no store or service logic of its own. Each tool is
derived from an operation in the generated OpenAPI document
(`proto/gen/openapi.yaml`, embedded via `proto.OpenAPIYAML()`), and a tool call
is translated into the matching `/api/...` HTTP request and run against the
same Echo server that serves the public API. This keeps OpenAPI as the single
same HTTP handler that serves the public API. This keeps OpenAPI as the single
source of truth and reuses the API's authentication and authorization as-is.
## Integration
`server.NewServer` calls `mcp.NewMCPService` after registering the API, file, and gRPC-gateway routes, passing the same Echo server:
`server.NewServer` calls `mcp.NewMCPService` after registering the API, file, and gRPC-gateway routes, passing the same HTTP handler:
```go
mcpService, err := mcp.NewMCPService(profile, echoServer)
mcpService, err := mcp.NewMCPService(profile, handler)
if err != nil {
return nil, errors.Wrap(err, "failed to create MCP service")
}
mcpService.RegisterRoutes(echoServer)
mcpService.RegisterRoutes(mux)
```
The service advertises the **tools** capability only — no prompts, no resources.
@@ -50,7 +50,7 @@ fast on any inconsistency:
## Request flow
`RegisterRoutes` binds `echoServer.Any("/mcp", ...)`. Each request:
`RegisterRoutes` binds `mux.HandleFunc("/mcp", ...)`. Each request:
1. `isAllowedMCPOrigin` (`origin.go`) rejects disallowed cross-origin browser requests with `403`.
2. The request body is capped at 256 MiB before the SDK reads it.
@@ -63,7 +63,7 @@ fast on any inconsistency:
7. `apiAdapter.execute` (`adapter.go`) builds the API request
(`buildAPIRequest`: path-parameter substitution, query encoding, JSON body),
forwards the bearer token, presents the caller's resolved client address as
the request peer, and runs it against the Echo server through an
the request peer, and runs it against the HTTP handler through an
`httptest.ResponseRecorder`.
8. The recorder body is decoded; a non-2xx status becomes a tool error
(`newToolErrorResult`), otherwise the value is wrapped by
@@ -272,7 +272,7 @@ validate an error payload against the tool's success-only output schema:
| --- | --- |
| `service.go` | Constructs the MCP server, registers tools, builds the streamable HTTP handler, and binds the `/mcp` route. |
| `catalog.go` | The curated operation allowlist, tool naming, input/output schema assembly, and method-derived annotations. |
| `adapter.go` | Translates a tool call into an `/api/...` request and runs it in-process against the Echo server. |
| `adapter.go` | Translates a tool call into an `/api/...` request and runs it in-process against the HTTP handler. |
| `openapi.go` | Parses the OpenAPI spec, builds the operation registry, and resolves `$ref` schemas into self-contained JSON Schema. |
| `validation.go` | Validates tool-call arguments against the tool's input schema. |
| `origin.go` | `Origin`-header check for browser DNS-rebinding safety. |
+4 -5
View File
@@ -12,7 +12,6 @@ import (
"strconv"
"strings"
"github.com/labstack/echo/v5"
sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/pkg/errors"
@@ -20,11 +19,11 @@ import (
)
type apiAdapter struct {
echoServer *echo.Echo
handler http.Handler
}
func newAPIAdapter(echoServer *echo.Echo) *apiAdapter {
return &apiAdapter{echoServer: echoServer}
func newAPIAdapter(handler http.Handler) *apiAdapter {
return &apiAdapter{handler: handler}
}
func (a *apiAdapter) execute(ctx context.Context, operation *openAPIOperation, arguments map[string]any, authorization string) (*sdkmcp.CallToolResult, error) {
@@ -34,7 +33,7 @@ func (a *apiAdapter) execute(ctx context.Context, operation *openAPIOperation, a
}
recorder := httptest.NewRecorder()
a.echoServer.ServeHTTP(recorder, req)
a.handler.ServeHTTP(recorder, req)
value, err := decodeJSONValue(recorder.Body.Bytes())
if err != nil {
+12 -12
View File
@@ -9,11 +9,11 @@ import (
"strings"
"testing"
"github.com/labstack/echo/v5"
sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/stretchr/testify/require"
"github.com/usememos/memos/internal/clientip"
"github.com/usememos/memos/internal/httphandler"
)
func TestNormalizeStructuredContentKeepsObjects(t *testing.T) {
@@ -336,19 +336,19 @@ func TestBuildAPIRequestEscapesPathAndStringifiesPrimitiveQueryParameters(t *tes
}
func TestExecuteOperationReturnsObjectStructuredContent(t *testing.T) {
echoServer := echo.New()
echoServer.GET("/api/memos", func(c *echo.Context) error {
require.Equal(t, "Bearer token", c.Request().Header.Get("Authorization"))
return c.JSON(http.StatusOK, map[string]any{
mux := http.NewServeMux()
mux.Handle("GET /api/memos", httphandler.Func(func(w http.ResponseWriter, r *http.Request) error {
require.Equal(t, "Bearer token", r.Header.Get("Authorization"))
return httphandler.JSON(w, http.StatusOK, map[string]any{
"memos": []any{map[string]any{"name": "memos/abc123"}},
})
})
}))
operation := &openAPIOperation{
Method: "GET",
Path: "/api/memos",
}
adapter := newAPIAdapter(echoServer)
adapter := newAPIAdapter(mux)
result, err := adapter.execute(context.Background(), operation, map[string]any{}, "Bearer token")
require.NoError(t, err)
@@ -359,17 +359,17 @@ func TestExecuteOperationReturnsObjectStructuredContent(t *testing.T) {
}
func TestExecuteOperationConvertsAPIErrorsToToolErrors(t *testing.T) {
echoServer := echo.New()
echoServer.GET("/api/memos/:memo", func(c *echo.Context) error {
return c.JSON(http.StatusNotFound, map[string]any{"message": "missing memo"})
})
mux := http.NewServeMux()
mux.Handle("GET /api/memos/{memo}", httphandler.Func(func(w http.ResponseWriter, _ *http.Request) error {
return httphandler.JSON(w, http.StatusNotFound, map[string]any{"message": "missing memo"})
}))
operation := &openAPIOperation{
Method: "GET",
Path: "/api/memos/{memo}",
Parameters: []openAPIParameter{{Name: "memo", In: "path", Required: true}},
}
adapter := newAPIAdapter(echoServer)
adapter := newAPIAdapter(mux)
result, err := adapter.execute(context.Background(), operation, map[string]any{"memo": "missing"}, "")
require.NoError(t, err)
+16 -13
View File
@@ -6,12 +6,11 @@ import (
"net/http"
"time"
"github.com/labstack/echo/v5"
"github.com/labstack/echo/v5/middleware"
sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/pkg/errors"
"gopkg.in/yaml.v3"
"github.com/usememos/memos/internal/httphandler"
"github.com/usememos/memos/internal/profile"
memosproto "github.com/usememos/memos/proto"
"github.com/usememos/memos/server/api"
@@ -20,7 +19,7 @@ import (
// maxMCPRequestBytes caps the /mcp request body. It tracks the API limit because
// every tool call is forwarded in-process through the API routes. The SDK
// enforces its own 4 MiB default, so the value is passed to the transport as
// well; otherwise attachment uploads over MCP fail with 413 before Echo sees them.
// well; otherwise attachment uploads over MCP fail with 413 before the API sees them.
const maxMCPRequestBytes int64 = api.MaxAPIRequestBytes
// toolCatalogTTL is the freshness hint advertised on tools/list and
@@ -37,7 +36,7 @@ type MCPService struct {
}
// NewMCPService creates an MCP service backed by the in-process API routes.
func NewMCPService(profile *profile.Profile, echoServer *echo.Echo) (*MCPService, error) {
func NewMCPService(profile *profile.Profile, handler http.Handler) (*MCPService, error) {
spec, err := loadMCPServiceOpenAPISpec()
if err != nil {
return nil, err
@@ -69,7 +68,7 @@ func NewMCPService(profile *profile.Profile, echoServer *echo.Echo) (*MCPService
})
server.AddReceivingMiddleware(catalogCacheMiddleware)
adapter := newAPIAdapter(echoServer)
adapter := newAPIAdapter(handler)
for _, tool := range tools {
operation := operationsByTool[tool.Name]
server.AddTool(tool, newMCPToolHandler(adapter, operation))
@@ -150,13 +149,17 @@ func newMCPToolHandler(adapter *apiAdapter, operation *registeredOperation) sdkm
}
// RegisterRoutes registers the streamable HTTP MCP endpoint.
func (s *MCPService) RegisterRoutes(echoServer *echo.Echo) {
echoServer.Any("/mcp", func(c *echo.Context) error {
request := c.Request()
if !isAllowedMCPOrigin(request.Host, request.Header.Get("Origin"), s.profile) {
return c.NoContent(http.StatusForbidden)
func (s *MCPService) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("/mcp", func(w http.ResponseWriter, r *http.Request) {
if r.ContentLength > maxMCPRequestBytes {
httphandler.WriteError(w, r, &httphandler.Error{Code: http.StatusRequestEntityTooLarge, Message: http.StatusText(http.StatusRequestEntityTooLarge)})
return
}
s.handler.ServeHTTP(c.Response(), request)
return nil
}, middleware.BodyLimit(maxMCPRequestBytes))
if !isAllowedMCPOrigin(r.Host, r.Header.Get("Origin"), s.profile) {
w.WriteHeader(http.StatusForbidden)
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxMCPRequestBytes)
s.handler.ServeHTTP(w, r)
})
}
+114 -121
View File
@@ -11,11 +11,11 @@ import (
"strings"
"testing"
"github.com/labstack/echo/v5"
sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/stretchr/testify/require"
"github.com/usememos/memos/internal/clientip"
"github.com/usememos/memos/internal/httphandler"
"github.com/usememos/memos/internal/profile"
memosproto "github.com/usememos/memos/proto"
)
@@ -46,9 +46,9 @@ func TestIsAllowedMCPOrigin(t *testing.T) {
}
func TestNewMCPServiceRegistersCuratedTools(t *testing.T) {
echoServer := echo.New()
mux := http.NewServeMux()
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, mux)
require.NoError(t, err)
require.NotNil(t, service.handler)
require.Len(t, service.operationsByTool, len(curatedOperationIDs))
@@ -63,7 +63,7 @@ func TestNewMCPServiceRegistersCuratedTools(t *testing.T) {
func TestNewMCPServiceUsesEmbeddedOpenAPISpec(t *testing.T) {
t.Chdir(t.TempDir())
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echo.New())
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, http.NewServeMux())
require.NoError(t, err)
require.NotNil(t, service.handler)
require.Len(t, service.operationsByTool, len(curatedOperationIDs))
@@ -76,14 +76,14 @@ func TestEmbeddedOpenAPISpecMatchesGeneratedFile(t *testing.T) {
}
func TestMCPToolHandlerForwardsArgumentsAndAuthorization(t *testing.T) {
echoServer := echo.New()
echoServer.GET("/api/memos", func(c *echo.Context) error {
require.Equal(t, "Bearer token", c.Request().Header.Get("Authorization"))
require.Equal(t, "7", c.QueryParam("pageSize"))
return c.JSON(http.StatusOK, map[string]any{
mux := http.NewServeMux()
mux.Handle("GET /api/memos", httphandler.Func(func(w http.ResponseWriter, r *http.Request) error {
require.Equal(t, "Bearer token", r.Header.Get("Authorization"))
require.Equal(t, "7", r.URL.Query().Get("pageSize"))
return httphandler.JSON(w, http.StatusOK, map[string]any{
"memos": []any{map[string]any{"name": "memos/test"}},
})
})
}))
operation := &registeredOperation{
Operation: &openAPIOperation{
@@ -92,7 +92,7 @@ func TestMCPToolHandlerForwardsArgumentsAndAuthorization(t *testing.T) {
Parameters: []openAPIParameter{{Name: "pageSize", In: "query", Schema: jsonSchema{"type": "integer"}}},
},
}
handler := newMCPToolHandler(newAPIAdapter(echoServer), operation)
handler := newMCPToolHandler(newAPIAdapter(mux), operation)
arguments, err := json.Marshal(map[string]any{"pageSize": 7})
require.NoError(t, err)
@@ -153,20 +153,20 @@ func TestMCPToolCallForwardsClientAddress(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
echoServer := echo.New()
mux := http.NewServeMux()
resolver, err := clientip.ParseTrustedProxies(nil)
require.NoError(t, err)
echoServer.Use(clientip.Middleware(resolver))
handler := clientip.Middleware(resolver)(mux)
seen := ""
echoServer.GET("/api/memos", func(c *echo.Context) error {
seen = clientip.FromContext(c.Request().Context())
return c.JSON(http.StatusOK, map[string]any{"memos": []any{}})
})
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
mux.Handle("GET /api/memos", httphandler.Func(func(w http.ResponseWriter, r *http.Request) error {
seen = clientip.FromContext(r.Context())
return httphandler.JSON(w, http.StatusOK, map[string]any{"memos": []any{}})
}))
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, handler)
require.NoError(t, err)
service.RegisterRoutes(echoServer)
initializeMCP(t, echoServer)
service.RegisterRoutes(mux)
initializeMCP(t, handler)
payload, err := json.Marshal(map[string]any{
"jsonrpc": "2.0",
@@ -183,7 +183,7 @@ func TestMCPToolCallForwardsClientAddress(t *testing.T) {
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json, text/event-stream")
recorder := httptest.NewRecorder()
echoServer.ServeHTTP(recorder, request)
handler.ServeHTTP(recorder, request)
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.Equal(t, test.expectedIP, seen)
})
@@ -289,31 +289,31 @@ func TestMCPToolCallBindsSpaceResourcesFromPath(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
echoServer := echo.New()
mux := http.NewServeMux()
routeHits := 0
echoServer.Any("/api/spaces/*", func(c *echo.Context) error {
mux.Handle("/api/spaces/{rest...}", httphandler.Func(func(w http.ResponseWriter, r *http.Request) error {
routeHits++
require.Equal(t, test.method, c.Request().Method)
require.Equal(t, test.path, c.Request().URL.Path)
require.Empty(t, c.QueryParam("updateMask"))
require.Equal(t, test.method, r.Method)
require.Equal(t, test.path, r.URL.Path)
require.Empty(t, r.URL.Query().Get("updateMask"))
if test.body != nil {
body := map[string]any{}
require.NoError(t, json.NewDecoder(c.Request().Body).Decode(&body))
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
require.Equal(t, test.body, body)
require.NotContains(t, body, "name")
require.NotContains(t, body, "user")
} else {
require.Empty(t, c.Request().Header.Get("Content-Type"))
require.Empty(t, r.Header.Get("Content-Type"))
}
return c.JSON(http.StatusOK, test.response)
})
return httphandler.JSON(w, http.StatusOK, test.response)
}))
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, mux)
require.NoError(t, err)
service.RegisterRoutes(echoServer)
service.RegisterRoutes(mux)
initializeMCP(t, echoServer)
response := postMCP(t, echoServer, map[string]any{
initializeMCP(t, mux)
response := postMCP(t, mux, map[string]any{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
@@ -333,14 +333,14 @@ func TestMCPToolCallBindsSpaceResourcesFromPath(t *testing.T) {
}
func TestMCPProtocolListsCuratedToolsOnly(t *testing.T) {
echoServer := echo.New()
mux := http.NewServeMux()
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, mux)
require.NoError(t, err)
service.RegisterRoutes(echoServer)
service.RegisterRoutes(mux)
initializeMCP(t, echoServer)
response := postMCP(t, echoServer, map[string]any{
initializeMCP(t, mux)
response := postMCP(t, mux, map[string]any{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
@@ -369,19 +369,19 @@ func TestMCPProtocolListsCuratedToolsOnly(t *testing.T) {
}
func TestMCPToolCallReturnsObjectStructuredContent(t *testing.T) {
echoServer := echo.New()
echoServer.GET("/api/memos", func(c *echo.Context) error {
return c.JSON(http.StatusOK, map[string]any{
mux := http.NewServeMux()
mux.Handle("GET /api/memos", httphandler.Func(func(w http.ResponseWriter, _ *http.Request) error {
return httphandler.JSON(w, http.StatusOK, map[string]any{
"memos": []any{map[string]any{"name": "memos/abc123"}},
})
})
}))
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, mux)
require.NoError(t, err)
service.RegisterRoutes(echoServer)
service.RegisterRoutes(mux)
initializeMCP(t, echoServer)
response := postMCP(t, echoServer, map[string]any{
initializeMCP(t, mux)
response := postMCP(t, mux, map[string]any{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
@@ -401,28 +401,28 @@ func TestMCPToolCallReturnsObjectStructuredContent(t *testing.T) {
}
func TestMCPToolCallAllowsGatewayToInferMemoUpdateMask(t *testing.T) {
echoServer := echo.New()
mux := http.NewServeMux()
routeHits := 0
echoServer.PATCH("/api/memos/:memo", func(c *echo.Context) error {
mux.Handle("PATCH /api/memos/{memo}", httphandler.Func(func(w http.ResponseWriter, r *http.Request) error {
routeHits++
require.Equal(t, "abc123", c.Param("memo"))
require.Empty(t, c.QueryParam("updateMask"))
require.Equal(t, "abc123", r.PathValue("memo"))
require.Empty(t, r.URL.Query().Get("updateMask"))
body := map[string]any{}
require.NoError(t, json.NewDecoder(c.Request().Body).Decode(&body))
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
require.Equal(t, map[string]any{"content": "updated"}, body)
return c.JSON(http.StatusOK, map[string]any{
return httphandler.JSON(w, http.StatusOK, map[string]any{
"name": "memos/abc123",
"content": "updated",
})
})
}))
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, mux)
require.NoError(t, err)
service.RegisterRoutes(echoServer)
service.RegisterRoutes(mux)
initializeMCP(t, echoServer)
response := postMCP(t, echoServer, map[string]any{
initializeMCP(t, mux)
response := postMCP(t, mux, map[string]any{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
@@ -446,15 +446,8 @@ func TestMCPToolCallAllowsGatewayToInferMemoUpdateMask(t *testing.T) {
}
func TestMCPToolCallBindsMemoFromPathForBodyStarOperations(t *testing.T) {
register := func(e *echo.Echo, method, path string, handler func(*echo.Context) error) {
switch method {
case http.MethodPatch:
e.PATCH(path, handler)
case http.MethodPost:
e.POST(path, handler)
default:
t.Fatalf("unsupported method %q", method)
}
register := func(mux *http.ServeMux, method, path string, handler httphandler.Func) {
mux.Handle(method+" "+strings.ReplaceAll(path, ":memo", "{memo}"), handler)
}
tests := []struct {
@@ -497,25 +490,25 @@ func TestMCPToolCallBindsMemoFromPathForBodyStarOperations(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
echoServer := echo.New()
mux := http.NewServeMux()
routeHits := 0
register(echoServer, test.method, test.path, func(c *echo.Context) error {
register(mux, test.method, test.path, func(w http.ResponseWriter, r *http.Request) error {
routeHits++
// The memo must be bound from the path, and the omitted "name"
// property must not reappear in the forwarded body.
require.Equal(t, "abc123", c.Param("memo"))
require.Equal(t, "abc123", r.PathValue("memo"))
body := map[string]any{}
require.NoError(t, json.NewDecoder(c.Request().Body).Decode(&body))
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
require.NotContains(t, body, "name")
return c.JSON(http.StatusOK, test.response)
return httphandler.JSON(w, http.StatusOK, test.response)
})
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, mux)
require.NoError(t, err)
service.RegisterRoutes(echoServer)
service.RegisterRoutes(mux)
initializeMCP(t, echoServer)
response := postMCP(t, echoServer, map[string]any{
initializeMCP(t, mux)
response := postMCP(t, mux, map[string]any{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
@@ -537,22 +530,22 @@ func TestMCPToolCallBindsMemoFromPathForBodyStarOperations(t *testing.T) {
}
func TestMCPToolCallRejectsInvalidArguments(t *testing.T) {
echoServer := echo.New()
mux := http.NewServeMux()
routeHits := 0
echoServer.GET("/api/memos", func(c *echo.Context) error {
mux.Handle("GET /api/memos", httphandler.Func(func(w http.ResponseWriter, _ *http.Request) error {
routeHits++
return c.JSON(http.StatusOK, map[string]any{"memos": []any{}})
})
echoServer.GET("/api/memos/:memo", func(c *echo.Context) error {
return httphandler.JSON(w, http.StatusOK, map[string]any{"memos": []any{}})
}))
mux.Handle("GET /api/memos/{memo}", httphandler.Func(func(w http.ResponseWriter, r *http.Request) error {
routeHits++
return c.JSON(http.StatusOK, map[string]any{"name": c.Param("memo")})
})
return httphandler.JSON(w, http.StatusOK, map[string]any{"name": r.PathValue("memo")})
}))
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, mux)
require.NoError(t, err)
service.RegisterRoutes(echoServer)
service.RegisterRoutes(mux)
initializeMCP(t, echoServer)
initializeMCP(t, mux)
tests := []struct {
name string
@@ -582,7 +575,7 @@ func TestMCPToolCallRejectsInvalidArguments(t *testing.T) {
for index, test := range tests {
t.Run(test.name, func(t *testing.T) {
response := postMCP(t, echoServer, map[string]any{
response := postMCP(t, mux, map[string]any{
"jsonrpc": "2.0",
"id": index + 2,
"method": "tools/call",
@@ -616,10 +609,10 @@ func TestMCPToolCallRejectsInvalidArguments(t *testing.T) {
// longer rejected by the SDK's DNS-rebinding guard, while memos' own Origin
// allowlist still rejects disallowed origins.
func TestMCPLoopbackBehindReverseProxy(t *testing.T) {
echoServer := echo.New()
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
mux := http.NewServeMux()
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, mux)
require.NoError(t, err)
service.RegisterRoutes(echoServer)
service.RegisterRoutes(mux)
initialize, err := json.Marshal(map[string]any{
"jsonrpc": "2.0",
@@ -647,7 +640,7 @@ func TestMCPLoopbackBehindReverseProxy(t *testing.T) {
t.Run("allows non-loopback host with no origin", func(t *testing.T) {
recorder := httptest.NewRecorder()
echoServer.ServeHTTP(recorder, newRequest())
mux.ServeHTTP(recorder, newRequest())
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
})
@@ -655,14 +648,14 @@ func TestMCPLoopbackBehindReverseProxy(t *testing.T) {
request := newRequest()
request.Header.Set("Origin", "https://evil.example.com")
recorder := httptest.NewRecorder()
echoServer.ServeHTTP(recorder, request)
mux.ServeHTTP(recorder, request)
require.Equal(t, http.StatusForbidden, recorder.Code)
})
}
func initializeMCP(t *testing.T, echoServer *echo.Echo) {
func initializeMCP(t *testing.T, mux http.Handler) {
t.Helper()
response := postMCP(t, echoServer, map[string]any{
response := postMCP(t, mux, map[string]any{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
@@ -678,7 +671,7 @@ func initializeMCP(t *testing.T, echoServer *echo.Echo) {
require.NotNil(t, response["result"])
}
func postMCP(t *testing.T, echoServer *echo.Echo, payload map[string]any) map[string]any {
func postMCP(t *testing.T, mux http.Handler, payload map[string]any) map[string]any {
t.Helper()
data, err := json.Marshal(payload)
require.NoError(t, err)
@@ -688,7 +681,7 @@ func postMCP(t *testing.T, echoServer *echo.Echo, payload map[string]any) map[st
request.Header.Set("Accept", "application/json, text/event-stream")
recorder := httptest.NewRecorder()
echoServer.ServeHTTP(recorder, request)
mux.ServeHTTP(recorder, request)
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
var response map[string]any
@@ -699,15 +692,15 @@ func postMCP(t *testing.T, echoServer *echo.Echo, payload map[string]any) map[st
// TestMCPStatelessProtocol2026 drives the endpoint the way a 2026-07-28 client
// does: no initialize handshake, per-request _meta, and the standard MCP headers.
func TestMCPStatelessProtocol2026(t *testing.T) {
echoServer := echo.New()
mux := http.NewServeMux()
var forwardedAuthorization string
echoServer.GET("/api/memos", func(c *echo.Context) error {
forwardedAuthorization = c.Request().Header.Get("Authorization")
return c.JSON(http.StatusOK, map[string]any{"memos": []any{}})
})
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
mux.Handle("GET /api/memos", httphandler.Func(func(w http.ResponseWriter, r *http.Request) error {
forwardedAuthorization = r.Header.Get("Authorization")
return httphandler.JSON(w, http.StatusOK, map[string]any{"memos": []any{}})
}))
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, mux)
require.NoError(t, err)
service.RegisterRoutes(echoServer)
service.RegisterRoutes(mux)
meta := map[string]any{
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
@@ -715,7 +708,7 @@ func TestMCPStatelessProtocol2026(t *testing.T) {
"io.modelcontextprotocol/clientInfo": map[string]any{"name": "memos-test", "version": "1.0.0"},
}
discover := postMCPWithHeaders(t, echoServer, map[string]any{
discover := postMCPWithHeaders(t, mux, map[string]any{
"jsonrpc": "2.0",
"id": 1,
"method": "server/discover",
@@ -731,7 +724,7 @@ func TestMCPStatelessProtocol2026(t *testing.T) {
require.NotContains(t, capabilities, "logging", "logging is deprecated and unused")
require.Positive(t, discoverResult["ttlMs"])
list := postMCPWithHeaders(t, echoServer, map[string]any{
list := postMCPWithHeaders(t, mux, map[string]any{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
@@ -743,7 +736,7 @@ func TestMCPStatelessProtocol2026(t *testing.T) {
require.Equal(t, float64(toolCatalogTTL.Milliseconds()), listResult["ttlMs"])
require.Equal(t, "public", listResult["cacheScope"])
call := postMCPWithHeaders(t, echoServer, map[string]any{
call := postMCPWithHeaders(t, mux, map[string]any{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
@@ -767,16 +760,16 @@ func TestMCPStatelessProtocol2026(t *testing.T) {
// TestMCPStatelessRejectsSessionMethods confirms the stateless transport shape
// required by 2026-07-28: no GET stream, no DELETE session teardown.
func TestMCPStatelessRejectsSessionMethods(t *testing.T) {
echoServer := echo.New()
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
mux := http.NewServeMux()
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, mux)
require.NoError(t, err)
service.RegisterRoutes(echoServer)
service.RegisterRoutes(mux)
for _, method := range []string{http.MethodGet, http.MethodDelete} {
request := httptest.NewRequest(method, "/mcp", nil)
request.Header.Set("Accept", "application/json, text/event-stream")
recorder := httptest.NewRecorder()
echoServer.ServeHTTP(recorder, request)
mux.ServeHTTP(recorder, request)
require.Equal(t, http.StatusMethodNotAllowed, recorder.Code, method)
}
}
@@ -784,22 +777,22 @@ func TestMCPStatelessRejectsSessionMethods(t *testing.T) {
// TestMCPRequestBodyLimitMatchesAPI guards against the SDK's 4 MiB default
// overriding the API-wide limit, which would break attachment uploads over MCP.
func TestMCPRequestBodyLimitMatchesAPI(t *testing.T) {
echoServer := echo.New()
mux := http.NewServeMux()
var receivedBytes int
echoServer.POST("/api/attachments", func(c *echo.Context) error {
mux.Handle("POST /api/attachments", httphandler.Func(func(w http.ResponseWriter, r *http.Request) error {
body := map[string]any{}
require.NoError(t, json.NewDecoder(c.Request().Body).Decode(&body))
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
content, ok := body["content"].(string)
require.True(t, ok)
receivedBytes = len(content)
return c.JSON(http.StatusOK, map[string]any{"name": "attachments/1"})
})
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
return httphandler.JSON(w, http.StatusOK, map[string]any{"name": "attachments/1"})
}))
service, err := NewMCPService(&profile.Profile{Version: "test-version"}, mux)
require.NoError(t, err)
service.RegisterRoutes(echoServer)
service.RegisterRoutes(mux)
content := strings.Repeat("A", 8<<20)
response := postMCPWithHeaders(t, echoServer, map[string]any{
response := postMCPWithHeaders(t, mux, map[string]any{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
@@ -823,11 +816,11 @@ func TestMCPRequestBodyLimitMatchesAPI(t *testing.T) {
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json, text/event-stream")
recorder := httptest.NewRecorder()
echoServer.ServeHTTP(recorder, request)
mux.ServeHTTP(recorder, request)
require.Equal(t, http.StatusRequestEntityTooLarge, recorder.Code)
}
func postMCPWithHeaders(t *testing.T, echoServer *echo.Echo, payload map[string]any, headers map[string]string) map[string]any {
func postMCPWithHeaders(t *testing.T, mux http.Handler, payload map[string]any, headers map[string]string) map[string]any {
t.Helper()
data, err := json.Marshal(payload)
require.NoError(t, err)
@@ -843,7 +836,7 @@ func postMCPWithHeaders(t *testing.T, echoServer *echo.Echo, payload map[string]
}
recorder := httptest.NewRecorder()
echoServer.ServeHTTP(recorder, request)
mux.ServeHTTP(recorder, request)
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
var response map[string]any
+33 -29
View File
@@ -7,14 +7,14 @@ import (
"net"
"net/http"
"os"
"path"
"time"
"uuid"
"github.com/labstack/echo/v5"
"github.com/labstack/echo/v5/middleware"
"github.com/pkg/errors"
"github.com/usememos/memos/internal/clientip"
"github.com/usememos/memos/internal/httphandler"
"github.com/usememos/memos/internal/profile"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/server/api"
@@ -44,7 +44,7 @@ type Server struct {
Profile *profile.Profile
Store *store.Store
echoServer *echo.Echo
handler http.Handler
httpServer *http.Server
apiService *api.APIService
}
@@ -55,17 +55,13 @@ func NewServer(ctx context.Context, profile *profile.Profile, store *store.Store
Profile: profile,
}
echoServer := echo.New()
echoServer.Use(middleware.Recover())
echoServer.Use(newCORSMiddleware(profile))
mux := http.NewServeMux()
// Resolve the client address once per request, before anything that keys
// on it: rate limits, session records, and the file server.
clientIPResolver, err := clientip.ParseTrustedProxies(profile.TrustedProxies)
if err != nil {
return nil, errors.Wrap(err, "invalid trusted proxies")
}
echoServer.Use(clientip.Middleware(clientIPResolver))
s.echoServer = echoServer
instanceBasicSetting, err := s.getOrUpsertInstanceBasicSetting(ctx)
if err != nil {
@@ -80,37 +76,45 @@ func NewServer(ctx context.Context, profile *profile.Profile, store *store.Store
// Register healthz endpoint. It reports ready only while the database
// answers, so a load balancer stops routing to an instance that lost it.
echoServer.GET("/healthz", func(c *echo.Context) error {
pingCtx, cancel := context.WithTimeout(c.Request().Context(), healthzDatabaseTimeout)
mux.Handle("/healthz", httphandler.GET(httphandler.Func(func(w http.ResponseWriter, r *http.Request) error {
pingCtx, cancel := context.WithTimeout(r.Context(), healthzDatabaseTimeout)
defer cancel()
if err := s.Store.GetDriver().GetDB().PingContext(pingCtx); err != nil {
slog.Warn("health check failed to reach the database", slog.String("error", err.Error()))
return c.String(http.StatusServiceUnavailable, "Database unavailable.")
return httphandler.Text(w, http.StatusServiceUnavailable, "Database unavailable.")
}
return c.String(http.StatusOK, "Service ready.")
})
// Serve frontend static files.
frontend.NewFrontendService(profile, store).Serve(ctx, echoServer)
return httphandler.Text(w, http.StatusOK, "Service ready.")
}), nil))
apiService := api.NewAPIService(s.Secret, profile, store)
s.apiService = apiService
// Register HTTP file server routes BEFORE gRPC-Gateway to ensure proper range request handling for Safari.
// This uses native HTTP serving (http.ServeContent) instead of gRPC for video/audio files.
fileServerService := fileserver.NewFileServerService(s.Profile, s.Store, s.Secret)
fileServerService.RegisterRoutes(echoServer)
// Register gRPC gateway as api v1 (includes SSE endpoint on CORS-enabled group).
if err := apiService.RegisterGateway(ctx, echoServer); err != nil {
return nil, errors.Wrap(err, "failed to register gRPC gateway")
apiHandler, err := apiService.NewHandler(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create API handler")
}
frontendService := frontend.NewFrontendService(profile, store)
frontendService.Serve(ctx, mux, apiHandler)
fileServerService := fileserver.NewFileServerService(s.Profile, s.Store, s.Secret)
fileServerService.RegisterRoutes(mux, apiHandler)
// Preserve unclean-path routing without ServeMux's automatic redirects.
fallback := frontendService.Handler(apiHandler)
router := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
frontend.SetCacheHeaders(w, r)
routingRequest := httphandler.RoutingRequest(r)
if path.Clean(routingRequest.URL.Path) != routingRequest.URL.Path && routingRequest.URL.Path != "/" {
fallback.ServeHTTP(w, r)
return
}
mux.ServeHTTP(w, routingRequest)
})
s.handler = httphandler.Recover(clientip.Middleware(clientIPResolver)(newCORSMiddleware(profile, mux)(router)))
mcpService, err := mcp.NewMCPService(profile, echoServer)
mcpService, err := mcp.NewMCPService(profile, s.handler)
if err != nil {
return nil, errors.Wrap(err, "failed to create MCP service")
}
mcpService.RegisterRoutes(echoServer)
mcpService.RegisterRoutes(mux)
return s, nil
}
@@ -136,15 +140,15 @@ func (s *Server) Start() error {
}
}
// Start Echo server directly (no cmux needed - all traffic is HTTP).
// All transports share the standard HTTP server.
s.httpServer = &http.Server{
Handler: s.echoServer,
Handler: s.handler,
ReadHeaderTimeout: readHeaderTimeout,
IdleTimeout: idleTimeout,
}
go func() {
if err := s.httpServer.Serve(listener); err != nil && err != http.ErrServerClosed {
slog.Error("failed to start echo server", "error", err)
slog.Error("failed to start HTTP server", "error", err)
}
}()
+1 -1
View File
@@ -474,7 +474,7 @@ func TestStartupPrivateInstanceGatewayPolicy(t *testing.T) {
// attachment; the schema types that field as an object, so clients validating
// responses against it — MCP clients serve that schema as the tool outputSchema
// — reject every memo carrying an attachment. The marshaler override lives in
// RegisterGateway, so only a booted server proves it is wired in.
// NewHandler, so only a booted server proves it is wired in.
func TestStartupGatewayOmitsNullMessageFields(t *testing.T) {
ctx := context.Background()
inst := bootInstance(ctx, t, instanceOptions{instanceURL: "http://localhost"})
+14
View File
@@ -0,0 +1,14 @@
# HTTP compatibility responses
`http_compat.jsonl` records 142 responses from the Echo implementation at
`ed838e805`, before the migration to `net/http`. `TestHTTPCompatibility` boots
the complete server and checks the same requests against these responses.
The cases cover method handling, CORS, API namespace boundaries, removed API
versions, escaped paths, trailing slashes, and SPA fallback. JSON bodies are
compared structurally because protobuf serialization may vary whitespace.
HTML bodies are represented by a marker, and Content-Length and Last-Modified
are excluded because rebuilding the embedded frontend changes them.
Treat these as the compatibility baseline. Do not regenerate them from the
new implementation to make a failing test pass.
+142
View File
@@ -0,0 +1,142 @@
{"Method":"GET","Path":"/healthz","RequestHeader":null,"Status":200,"Header":{"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/plain; charset=UTF-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"Service ready."}
{"Method":"HEAD","Path":"/healthz","RequestHeader":null,"Status":405,"Header":{"Allow":["OPTIONS, GET"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":""}
{"Method":"POST","Path":"/healthz","RequestHeader":null,"Status":405,"Header":{"Allow":["OPTIONS, GET"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["application/json"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"{\"message\":\"Method Not Allowed\"}\n"}
{"Method":"OPTIONS","Path":"/healthz","RequestHeader":null,"Status":204,"Header":{"Allow":["OPTIONS, GET"],"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/healthz/","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"HEAD","Path":"/healthz/","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":""}
{"Method":"POST","Path":"/healthz/","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"OPTIONS","Path":"/healthz/","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/health%7A","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"HEAD","Path":"/health%7A","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":""}
{"Method":"POST","Path":"/health%7A","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"OPTIONS","Path":"/health%7A","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/api","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"Not Found\"}\n"}
{"Method":"HEAD","Path":"/api","RequestHeader":null,"Status":404,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"POST","Path":"/api","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"Not Found\"}\n"}
{"Method":"OPTIONS","Path":"/api","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/api/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"HEAD","Path":"/api/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/api/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/api/","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/api/missing","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"HEAD","Path":"/api/missing","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/api/missing","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/api/missing","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/api/sse","RequestHeader":null,"Status":401,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"error\":\"authentication required\"}\n"}
{"Method":"HEAD","Path":"/api/sse","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/api/sse","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/api/sse","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/api/sse/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"HEAD","Path":"/api/sse/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/api/sse/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/api/sse/","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/api/v1","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"HEAD","Path":"/api/v1","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/api/v1","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/api/v1","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/api/v1/","RequestHeader":null,"Status":410,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":12,\"message\":\"API v1 has been removed. Use /api/... for REST and /memos.api.\\u003cService\\u003e/\\u003cMethod\\u003e for Connect. See https://github.com/usememos/memos/blob/main/proto/api/CHANGELOG.md\"}\n"}
{"Method":"HEAD","Path":"/api/v1/","RequestHeader":null,"Status":410,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":12,\"message\":\"API v1 has been removed. Use /api/... for REST and /memos.api.\\u003cService\\u003e/\\u003cMethod\\u003e for Connect. See https://github.com/usememos/memos/blob/main/proto/api/CHANGELOG.md\"}\n"}
{"Method":"POST","Path":"/api/v1/","RequestHeader":null,"Status":410,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":12,\"message\":\"API v1 has been removed. Use /api/... for REST and /memos.api.\\u003cService\\u003e/\\u003cMethod\\u003e for Connect. See https://github.com/usememos/memos/blob/main/proto/api/CHANGELOG.md\"}\n"}
{"Method":"OPTIONS","Path":"/api/v1/","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/api/v1/memos","RequestHeader":null,"Status":410,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":12,\"message\":\"API v1 has been removed. Use /api/... for REST and /memos.api.\\u003cService\\u003e/\\u003cMethod\\u003e for Connect. See https://github.com/usememos/memos/blob/main/proto/api/CHANGELOG.md\"}\n"}
{"Method":"HEAD","Path":"/api/v1/memos","RequestHeader":null,"Status":410,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":12,\"message\":\"API v1 has been removed. Use /api/... for REST and /memos.api.\\u003cService\\u003e/\\u003cMethod\\u003e for Connect. See https://github.com/usememos/memos/blob/main/proto/api/CHANGELOG.md\"}\n"}
{"Method":"POST","Path":"/api/v1/memos","RequestHeader":null,"Status":410,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":12,\"message\":\"API v1 has been removed. Use /api/... for REST and /memos.api.\\u003cService\\u003e/\\u003cMethod\\u003e for Connect. See https://github.com/usememos/memos/blob/main/proto/api/CHANGELOG.md\"}\n"}
{"Method":"OPTIONS","Path":"/api/v1/memos","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/file","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"Not Found\"}\n"}
{"Method":"HEAD","Path":"/file","RequestHeader":null,"Status":404,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"POST","Path":"/file","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"Not Found\"}\n"}
{"Method":"OPTIONS","Path":"/file","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/file/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"HEAD","Path":"/file/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/file/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/file/","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/file/attachments/missing","RequestHeader":null,"Status":404,"Header":{"Cache-Control":["private, no-store"],"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"attachment not found\"}\n"}
{"Method":"HEAD","Path":"/file/attachments/missing","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/file/attachments/missing","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/file/attachments/missing","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/file/attachments/missing/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"HEAD","Path":"/file/attachments/missing/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/file/attachments/missing/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/file/attachments/missing/","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/file/attachments/missing/a%2Fb.txt","RequestHeader":null,"Status":404,"Header":{"Cache-Control":["private, no-store"],"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"attachment not found\"}\n"}
{"Method":"HEAD","Path":"/file/attachments/missing/a%2Fb.txt","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/file/attachments/missing/a%2Fb.txt","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/file/attachments/missing/a%2Fb.txt","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/file/attachments/%6dissing/file.txt","RequestHeader":null,"Status":404,"Header":{"Cache-Control":["private, no-store"],"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"attachment not found\"}\n"}
{"Method":"HEAD","Path":"/file/attachments/%6dissing/file.txt","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/file/attachments/%6dissing/file.txt","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/file/attachments/%6dissing/file.txt","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/file/%61ttachments/missing/file.txt","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"HEAD","Path":"/file/%61ttachments/missing/file.txt","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/file/%61ttachments/missing/file.txt","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/file/%61ttachments/missing/file.txt","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/memos.api","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"Not Found\"}\n"}
{"Method":"HEAD","Path":"/memos.api","RequestHeader":null,"Status":404,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"POST","Path":"/memos.api","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"Not Found\"}\n"}
{"Method":"OPTIONS","Path":"/memos.api","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/memos.api.","RequestHeader":null,"Status":404,"Header":{"Content-Type":["text/plain; charset=utf-8"],"Vary":["Origin"],"X-Content-Type-Options":["nosniff"]},"Body":"404 page not found\n"}
{"Method":"HEAD","Path":"/memos.api.","RequestHeader":null,"Status":404,"Header":{"Content-Type":["text/plain; charset=utf-8"],"Vary":["Origin"],"X-Content-Type-Options":["nosniff"]},"Body":"404 page not found\n"}
{"Method":"POST","Path":"/memos.api.","RequestHeader":null,"Status":404,"Header":{"Content-Type":["text/plain; charset=utf-8"],"Vary":["Origin"],"X-Content-Type-Options":["nosniff"]},"Body":"404 page not found\n"}
{"Method":"OPTIONS","Path":"/memos.api.","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/memos.api.UnknownService/Unknown","RequestHeader":null,"Status":404,"Header":{"Content-Type":["text/plain; charset=utf-8"],"Vary":["Origin"],"X-Content-Type-Options":["nosniff"]},"Body":"404 page not found\n"}
{"Method":"HEAD","Path":"/memos.api.UnknownService/Unknown","RequestHeader":null,"Status":404,"Header":{"Content-Type":["text/plain; charset=utf-8"],"Vary":["Origin"],"X-Content-Type-Options":["nosniff"]},"Body":"404 page not found\n"}
{"Method":"POST","Path":"/memos.api.UnknownService/Unknown","RequestHeader":null,"Status":404,"Header":{"Content-Type":["text/plain; charset=utf-8"],"Vary":["Origin"],"X-Content-Type-Options":["nosniff"]},"Body":"404 page not found\n"}
{"Method":"OPTIONS","Path":"/memos.api.UnknownService/Unknown","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/memos.api.v1.MemoService/ListMemos","RequestHeader":null,"Status":410,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":\"unimplemented\",\"message\":\"API v1 has been removed. Use /api/... for REST and /memos.api.\\u003cService\\u003e/\\u003cMethod\\u003e for Connect. See https://github.com/usememos/memos/blob/main/proto/api/CHANGELOG.md\"}\n"}
{"Method":"HEAD","Path":"/memos.api.v1.MemoService/ListMemos","RequestHeader":null,"Status":410,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":\"unimplemented\",\"message\":\"API v1 has been removed. Use /api/... for REST and /memos.api.\\u003cService\\u003e/\\u003cMethod\\u003e for Connect. See https://github.com/usememos/memos/blob/main/proto/api/CHANGELOG.md\"}\n"}
{"Method":"POST","Path":"/memos.api.v1.MemoService/ListMemos","RequestHeader":null,"Status":410,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":\"unimplemented\",\"message\":\"API v1 has been removed. Use /api/... for REST and /memos.api.\\u003cService\\u003e/\\u003cMethod\\u003e for Connect. See https://github.com/usememos/memos/blob/main/proto/api/CHANGELOG.md\"}\n"}
{"Method":"OPTIONS","Path":"/memos.api.v1.MemoService/ListMemos","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/memos/x","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"HEAD","Path":"/memos/x","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":""}
{"Method":"POST","Path":"/memos/x","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"OPTIONS","Path":"/memos/x","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/assets/missing.js","RequestHeader":null,"Status":404,"Header":{"Cache-Control":["public, max-age=2592000, immutable"],"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"Not Found\"}\n"}
{"Method":"HEAD","Path":"/assets/missing.js","RequestHeader":null,"Status":404,"Header":{"Cache-Control":["public, max-age=2592000, immutable"],"Vary":["Origin"]},"Body":""}
{"Method":"POST","Path":"/assets/missing.js","RequestHeader":null,"Status":404,"Header":{"Cache-Control":["public, max-age=2592000, immutable"],"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"Not Found\"}\n"}
{"Method":"OPTIONS","Path":"/assets/missing.js","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/index.html","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"HEAD","Path":"/index.html","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":""}
{"Method":"POST","Path":"/index.html","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"OPTIONS","Path":"/index.html","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/robots.txt","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"public instance discovery is unavailable\"}\n"}
{"Method":"HEAD","Path":"/robots.txt","RequestHeader":null,"Status":405,"Header":{"Allow":["OPTIONS, GET"],"Vary":["Origin"]},"Body":""}
{"Method":"POST","Path":"/robots.txt","RequestHeader":null,"Status":405,"Header":{"Allow":["OPTIONS, GET"],"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"Method Not Allowed\"}\n"}
{"Method":"OPTIONS","Path":"/robots.txt","RequestHeader":null,"Status":204,"Header":{"Allow":["OPTIONS, GET"],"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/sitemap.xml","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"public instance discovery is unavailable\"}\n"}
{"Method":"HEAD","Path":"/sitemap.xml","RequestHeader":null,"Status":405,"Header":{"Allow":["OPTIONS, GET"],"Vary":["Origin"]},"Body":""}
{"Method":"POST","Path":"/sitemap.xml","RequestHeader":null,"Status":405,"Header":{"Allow":["OPTIONS, GET"],"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"message\":\"Method Not Allowed\"}\n"}
{"Method":"OPTIONS","Path":"/sitemap.xml","RequestHeader":null,"Status":204,"Header":{"Allow":["OPTIONS, GET"],"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/api//instance/profile","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"HEAD","Path":"/api//instance/profile","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/api//instance/profile","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/api//instance/profile","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/api/../healthz","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"HEAD","Path":"/api/../healthz","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/api/../healthz","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/api/../healthz","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/api/instance/profile/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"HEAD","Path":"/api/instance/profile/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"POST","Path":"/api/instance/profile/","RequestHeader":null,"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/api/instance/profile/","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/mcp/","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"HEAD","Path":"/mcp/","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":""}
{"Method":"POST","Path":"/mcp/","RequestHeader":null,"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"OPTIONS","Path":"/mcp/","RequestHeader":null,"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/healthz","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["https://memos.example"]},"Status":200,"Header":{"Access-Control-Allow-Credentials":["true"],"Access-Control-Allow-Origin":["https://memos.example"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/plain; charset=UTF-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"Service ready."}
{"Method":"OPTIONS","Path":"/healthz","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["https://memos.example"]},"Status":204,"Header":{"Access-Control-Allow-Credentials":["true"],"Access-Control-Allow-Headers":["Authorization,Content-Type"],"Access-Control-Allow-Methods":["OPTIONS, GET"],"Access-Control-Allow-Origin":["https://memos.example"],"Allow":["OPTIONS, GET"],"Vary":["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]},"Body":""}
{"Method":"GET","Path":"/healthz","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["https://evil.example"]},"Status":200,"Header":{"Access-Control-Allow-Origin":["https://evil.example"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/plain; charset=UTF-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"Service ready."}
{"Method":"OPTIONS","Path":"/healthz","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["https://evil.example"]},"Status":204,"Header":{"Access-Control-Allow-Headers":["Authorization,Content-Type"],"Access-Control-Allow-Methods":["OPTIONS, GET"],"Access-Control-Allow-Origin":["https://evil.example"],"Allow":["OPTIONS, GET"],"Vary":["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]},"Body":""}
{"Method":"GET","Path":"/healthz","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["null"]},"Status":200,"Header":{"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/plain; charset=UTF-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"Service ready."}
{"Method":"OPTIONS","Path":"/healthz","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["null"]},"Status":204,"Header":{"Allow":["OPTIONS, GET"],"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/api/missing","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["https://memos.example"]},"Status":404,"Header":{"Access-Control-Allow-Credentials":["true"],"Access-Control-Allow-Origin":["https://memos.example"],"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/api/missing","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["https://memos.example"]},"Status":204,"Header":{"Access-Control-Allow-Credentials":["true"],"Access-Control-Allow-Headers":["Authorization,Content-Type"],"Access-Control-Allow-Methods":["GET,HEAD,PUT,PATCH,POST,DELETE"],"Access-Control-Allow-Origin":["https://memos.example"],"Vary":["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]},"Body":""}
{"Method":"GET","Path":"/api/missing","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["https://evil.example"]},"Status":404,"Header":{"Access-Control-Allow-Origin":["https://evil.example"],"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/api/missing","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["https://evil.example"]},"Status":204,"Header":{"Access-Control-Allow-Headers":["Authorization,Content-Type"],"Access-Control-Allow-Methods":["GET,HEAD,PUT,PATCH,POST,DELETE"],"Access-Control-Allow-Origin":["https://evil.example"],"Vary":["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]},"Body":""}
{"Method":"GET","Path":"/api/missing","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["null"]},"Status":404,"Header":{"Content-Type":["application/json"],"Vary":["Origin"]},"Body":"{\"code\":5, \"message\":\"Not Found\", \"details\":[]}"}
{"Method":"OPTIONS","Path":"/api/missing","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["null"]},"Status":204,"Header":{"Vary":["Origin"]},"Body":""}
{"Method":"GET","Path":"/memos/x","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["https://memos.example"]},"Status":200,"Header":{"Accept-Ranges":["bytes"],"Access-Control-Allow-Credentials":["true"],"Access-Control-Allow-Origin":["https://memos.example"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"OPTIONS","Path":"/memos/x","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["https://memos.example"]},"Status":204,"Header":{"Access-Control-Allow-Credentials":["true"],"Access-Control-Allow-Headers":["Authorization,Content-Type"],"Access-Control-Allow-Methods":["GET,HEAD,PUT,PATCH,POST,DELETE"],"Access-Control-Allow-Origin":["https://memos.example"],"Vary":["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]},"Body":""}
{"Method":"GET","Path":"/memos/x","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["https://evil.example"]},"Status":200,"Header":{"Accept-Ranges":["bytes"],"Access-Control-Allow-Origin":["https://evil.example"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"OPTIONS","Path":"/memos/x","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["https://evil.example"]},"Status":204,"Header":{"Access-Control-Allow-Headers":["Authorization,Content-Type"],"Access-Control-Allow-Methods":["GET,HEAD,PUT,PATCH,POST,DELETE"],"Access-Control-Allow-Origin":["https://evil.example"],"Vary":["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]},"Body":""}
{"Method":"GET","Path":"/memos/x","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["null"]},"Status":200,"Header":{"Accept-Ranges":["bytes"],"Cache-Control":["no-cache, no-store, must-revalidate"],"Content-Type":["text/html; charset=utf-8"],"Expires":["0"],"Pragma":["no-cache"],"Vary":["Origin"]},"Body":"\u003cfrontend HTML\u003e"}
{"Method":"OPTIONS","Path":"/memos/x","RequestHeader":{"Access-Control-Request-Headers":["Authorization,Content-Type"],"Access-Control-Request-Method":["POST"],"Origin":["null"]},"Status":204,"Header":{"Vary":["Origin"]},"Body":""}