Skip to content

Commit 14cd4cd

Browse files
marcobambiniclaude
andcommitted
fix: confine materialized paths, correct search constraints, bound remote JSON
Release 1.3.6. memory_search no longer claims to have satisfied an ORDER BY it did not produce, and identifies its hidden-column constraints by column instead of by argument position, so a repeated or multiple constraint cannot read the wrong value or silently return nothing. memory_materialize_files() refuses absolute paths as well as '..' segments and no longer follows symbolic links below the caller-supplied root, so content written by another writer cannot be materialized outside the destination directory or used to probe files outside it. memory_reindex() only re-reads a file named by the locally written source_path, and memory_rename_file() keeps that record in step with the rename. The remote provider's JSON is walked with explicit token bounds and a nesting limit, and a declared output_dimension larger than the array actually returned is reported instead of trusted. The CLI sends GITHUB_TOKEN only to GitHub hosts, refuses redirects away from https, and the MCP HTTP transport rejects foreign Origin headers. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent da90032 commit 14cd4cd

11 files changed

Lines changed: 500 additions & 88 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,27 @@ All notable changes to this project will be documented in this file.
44

55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
66

7+
## [1.3.6] - 2026-11-01
8+
9+
### Fixed
10+
11+
- **`ORDER BY ranking ASC` on `memory_search` returned rows in descending order.** The virtual table always claimed to have satisfied the `ORDER BY`, so SQLite skipped its own sorter whatever direction was asked for. The claim is now made only for `ORDER BY ranking DESC`, which is the order the table actually produces; every other `ORDER BY` is left to SQLite.
12+
- **A repeated or multiple hidden-column constraint could silently return no rows.** `memory_search` identified `query`, `max_entries` and `context` by their position in the argument list rather than by the column they came from, so a query such as `WHERE query = ? AND context = ? AND context = ?` could read the wrong value or none at all. Each claimed constraint now records which column it belongs to, and a duplicate is consumed instead of being left for SQLite to evaluate against a hidden column.
13+
- **`memory_rename_file()` left the source-path record behind**, so a renamed file kept pointing at its old location and `memory_reindex()` could re-read the wrong path. The `dbmem_content_source` row is now updated with the resolved path, and the new storage path is normalized the same way as on insert.
14+
- **`memory_reindex()` no longer re-reads a file named only by `dbmem_content.path`.** Only `dbmem_content_source.source_path`, which is written locally when content is ingested from disk, drives a re-read, so a `path` value that arrived from somewhere else cannot make the extension open a local file.
15+
- **One-byte buffer over-allocation** in the disambiguated-path helper.
16+
- **Possible use of an uninitialized counter** on an early error exit from `memory_materialize_files()`.
17+
- **A truncated or malformed embedding response could be read past its end.** The remote provider's JSON is walked with explicit token bounds and a nesting limit, the result of the token-filling pass is checked, and a declared `output_dimension` larger than the array actually returned is now reported as an error instead of trusted. A dimension smaller than the array keeps working, as some providers return a prefix.
18+
- **`llama_backend_free()` is no longer called when a local engine is released.** The llama.cpp backend is process-global and not reference-counted, so freeing it while another engine was still alive could leave that engine using torn-down global state.
19+
- The extension API macro was missing from two translation units, so an `OMIT_CURL=1` loadable-extension build did not compile.
20+
21+
### Security
22+
23+
- **`memory_materialize_files()` refuses absolute paths**, not only paths containing `..`. A stored path such as `/etc/passwd` or `C:/evil.txt` was previously resolved as given, so content written by another writer — a sync peer, or any process with access to the database — could be materialized outside the destination directory. An exhaustive sweep of the path resolver finds no input that escapes the root.
24+
- **Materialization no longer follows symbolic links.** Directory components below the caller-supplied root are checked with `lstat`, files are created with `O_NOFOLLOW`, and a path that is already a symlink is refused before its target is read, so neither the content of a file outside the root nor its existence can be inferred from the outcome. Components of the root itself are still resolved normally, so a root that legitimately lives under a symlink keeps working.
25+
- **The MCP HTTP transport validates the `Origin` header.** A request carrying an origin that is not `localhost`, `127.0.0.1` or `::1` is rejected with 403, which closes the DNS-rebinding and cross-site path that let any web page a user visited drive the local server's tools. Requests with no `Origin` are still accepted, because MCP clients do not send one.
26+
- **The extension installer only sends `GITHUB_TOKEN` to GitHub.** The download URL comes out of an API response, so the token is now attached only when the host is GitHub itself, and a redirect away from `https` is refused rather than followed.
27+
728
## [1.3.5] - 2026-06-10
829

930
### Added

‎cli/internal/download/download.go‎

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"fmt"
1010
"io"
1111
"net/http"
12+
"net/url"
1213
"os"
1314
"path/filepath"
1415
"sort"
@@ -41,7 +42,7 @@ func (c Client) Install(ctx context.Context, owner, repo, version, baseDir strin
4142
version = "latest"
4243
}
4344
if c.HTTP == nil {
44-
c.HTTP = http.DefaultClient
45+
c.HTTP = &http.Client{CheckRedirect: httpsOnlyRedirect}
4546
}
4647
if c.Platform.OS == "" {
4748
c.Platform = CurrentPlatform()
@@ -84,11 +85,11 @@ func (c Client) Install(ctx context.Context, owner, repo, version, baseDir strin
8485
}
8586

8687
func (c Client) release(ctx context.Context, owner, repo, version string) (release, error) {
87-
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/latest", owner, repo)
88+
endpoint := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/latest", owner, repo)
8889
if version != "latest" {
89-
url = fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/tags/%s", owner, repo, version)
90+
endpoint = fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/tags/%s", owner, repo, version)
9091
}
91-
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
92+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
9293
if err != nil {
9394
return release{}, err
9495
}
@@ -112,12 +113,44 @@ func (c Client) release(ctx context.Context, owner, repo, version string) (relea
112113
return rel, nil
113114
}
114115

115-
func (c Client) download(ctx context.Context, url, path string) error {
116-
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
116+
// The asset URL comes out of the GitHub API response, and whatever it points at
117+
// is loaded into the process as a native SQLite extension, so it must not be
118+
// fetched over plaintext.
119+
func httpsOnlyRedirect(req *http.Request, via []*http.Request) error {
120+
if len(via) >= 10 {
121+
return fmt.Errorf("stopped after 10 redirects")
122+
}
123+
if req.URL.Scheme != "https" {
124+
return fmt.Errorf("refusing redirect to non-https URL %s", req.URL.Redacted())
125+
}
126+
return nil
127+
}
128+
129+
// GITHUB_TOKEN must only be offered to GitHub itself: the download URL is taken
130+
// from an API response, so sending the user's token wherever it points would hand
131+
// the credential to a third party.
132+
func isGitHubHost(host string) bool {
133+
host = strings.ToLower(host)
134+
if host == "github.com" || host == "api.github.com" {
135+
return true
136+
}
137+
return strings.HasSuffix(host, ".github.com") || strings.HasSuffix(host, ".githubusercontent.com")
138+
}
139+
140+
func (c Client) download(ctx context.Context, rawURL, path string) error {
141+
parsed, err := url.Parse(rawURL)
142+
if err != nil {
143+
return fmt.Errorf("invalid download URL: %w", err)
144+
}
145+
if parsed.Scheme != "https" {
146+
return fmt.Errorf("refusing to download over %q: only https is allowed", parsed.Scheme)
147+
}
148+
149+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
117150
if err != nil {
118151
return err
119152
}
120-
if token := os.Getenv("GITHUB_TOKEN"); token != "" {
153+
if token := os.Getenv("GITHUB_TOKEN"); token != "" && isGitHubHost(parsed.Hostname()) {
121154
req.Header.Set("Authorization", "Bearer "+token)
122155
}
123156
res, err := c.HTTP.Do(req)

‎cli/internal/download/download_test.go‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,12 @@ package download
33
import (
44
"archive/tar"
55
"compress/gzip"
6+
"context"
7+
"net/http"
8+
"net/http/httptest"
69
"os"
710
"path/filepath"
11+
"strings"
812
"testing"
913
)
1014

@@ -104,3 +108,84 @@ func writeTarGz(path string, headers []tar.Header, fileData []byte) error {
104108
}
105109
return nil
106110
}
111+
112+
func TestIsGitHubHost(t *testing.T) {
113+
cases := []struct {
114+
host string
115+
want bool
116+
}{
117+
{"github.com", true},
118+
{"api.github.com", true},
119+
{"objects.githubusercontent.com", true},
120+
{"codeload.github.com", true},
121+
{"GitHub.com", true},
122+
{"evil.example", false},
123+
{"github.com.evil.example", false},
124+
{"notgithub.com", false},
125+
{"githubusercontent.com.evil.test", false},
126+
{"", false},
127+
// a bare suffix is not a host, and a trailing dot is a different name
128+
{".github.com", true}, // genuinely a subdomain-shaped name under github.com
129+
{"github.com.", false},
130+
{"xgithub.com", false},
131+
{"githubusercontent.com", false}, // only *.githubusercontent.com serves assets
132+
}
133+
for _, c := range cases {
134+
if got := isGitHubHost(c.host); got != c.want {
135+
t.Errorf("isGitHubHost(%q) = %v, want %v", c.host, got, c.want)
136+
}
137+
}
138+
}
139+
140+
func TestDownloadRejectsNonHTTPS(t *testing.T) {
141+
dst := filepath.Join(t.TempDir(), "asset.tar.gz")
142+
c := Client{}
143+
err := c.download(context.Background(), "http://example.invalid/asset.tar.gz", dst)
144+
if err == nil {
145+
t.Fatal("expected plaintext download to be refused")
146+
}
147+
if !strings.Contains(err.Error(), "https") {
148+
t.Fatalf("error = %v, want it to mention https", err)
149+
}
150+
if _, statErr := os.Stat(dst); statErr == nil {
151+
t.Fatal("no file should have been created")
152+
}
153+
}
154+
155+
func TestHTTPSOnlyRedirectRefusesDowngrade(t *testing.T) {
156+
plain, _ := http.NewRequest(http.MethodGet, "http://example.invalid/x", nil)
157+
if err := httpsOnlyRedirect(plain, nil); err == nil {
158+
t.Fatal("expected a redirect to http to be refused")
159+
}
160+
secure, _ := http.NewRequest(http.MethodGet, "https://example.invalid/x", nil)
161+
if err := httpsOnlyRedirect(secure, nil); err != nil {
162+
t.Fatalf("https redirect refused: %v", err)
163+
}
164+
}
165+
166+
func TestDownloadDoesNotSendTokenToNonGitHubHost(t *testing.T) {
167+
var gotAuth string
168+
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
169+
gotAuth = r.Header.Get("Authorization")
170+
_, _ = w.Write([]byte("payload"))
171+
}))
172+
defer srv.Close()
173+
174+
// the asset URL comes from an API response, so it may point anywhere
175+
t.Setenv("GITHUB_TOKEN", "super-secret-token")
176+
dst := filepath.Join(t.TempDir(), "asset.bin")
177+
c := Client{HTTP: srv.Client()}
178+
if err := c.download(context.Background(), srv.URL+"/asset.bin", dst); err != nil {
179+
t.Fatal(err)
180+
}
181+
if gotAuth != "" {
182+
t.Fatalf("Authorization header leaked to a non-GitHub host: %q", gotAuth)
183+
}
184+
body, err := os.ReadFile(dst)
185+
if err != nil {
186+
t.Fatal(err)
187+
}
188+
if string(body) != "payload" {
189+
t.Fatalf("body = %q", body)
190+
}
191+
}

‎cli/internal/mcp/mcp.go‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"fmt"
99
"io"
1010
"net/http"
11+
"net/url"
1112
"strconv"
1213
"strings"
1314

@@ -74,10 +75,42 @@ func (s Server) ServeStdio(ctx context.Context, in io.Reader, out io.Writer) err
7475
}
7576
}
7677

77-
func (s Server) ServeHTTP(ctx context.Context, addr string) error {
78+
// originAllowed guards the HTTP transport against browser-driven requests.
79+
//
80+
// A loopback listener is reachable from any page the user happens to visit, and
81+
// an attacker-controlled hostname can be rebound to 127.0.0.1, so the MCP spec
82+
// requires HTTP transports to validate Origin. Without it a visited page could
83+
// drive the tools below — memory_add_directory followed by memory_search reads
84+
// the user's files back out, and memory_clear destroys the index.
85+
//
86+
// A request with no Origin header is allowed: real MCP clients and curl do not
87+
// send one, while a browser always does for a cross-origin request.
88+
func originAllowed(r *http.Request) bool {
89+
origin := r.Header.Get("Origin")
90+
if origin == "" {
91+
return true
92+
}
93+
parsed, err := url.Parse(origin)
94+
if err != nil {
95+
return false
96+
}
97+
switch parsed.Hostname() {
98+
case "127.0.0.1", "::1", "localhost":
99+
return true
100+
}
101+
return false
102+
}
103+
104+
// httpHandler builds the transport's routes. Split out of ServeHTTP so the
105+
// Origin check can be exercised by a test without binding a port.
106+
func (s Server) httpHandler() http.Handler {
78107
mux := http.NewServeMux()
79108
mux.HandleFunc("/mcp", func(w http.ResponseWriter, r *http.Request) {
80109
defer r.Body.Close()
110+
if !originAllowed(r) {
111+
http.Error(w, "forbidden: cross-origin requests are not allowed", http.StatusForbidden)
112+
return
113+
}
81114
var req request
82115
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
83116
writeJSON(w, response{JSONRPC: "2.0", Error: errObj(-32700, err.Error())})
@@ -90,7 +123,11 @@ func (s Server) ServeHTTP(ctx context.Context, addr string) error {
90123
}
91124
writeJSON(w, res)
92125
})
93-
server := &http.Server{Addr: addr, Handler: mux}
126+
return mux
127+
}
128+
129+
func (s Server) ServeHTTP(ctx context.Context, addr string) error {
130+
server := &http.Server{Addr: addr, Handler: s.httpHandler()}
94131
go func() {
95132
<-ctx.Done()
96133
_ = server.Shutdown(context.Background())

‎cli/internal/mcp/mcp_test.go‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import (
77
"encoding/json"
88
"fmt"
99
"io"
10+
"net/http"
11+
"net/http/httptest"
1012
"strings"
1113
"testing"
1214
)
@@ -95,3 +97,80 @@ func TestServeStdioUsesContentLengthFraming(t *testing.T) {
9597
func bufioReader(r io.Reader) *bufio.Reader {
9698
return bufio.NewReader(r)
9799
}
100+
101+
func TestOriginAllowed(t *testing.T) {
102+
cases := []struct {
103+
origin string
104+
want bool
105+
}{
106+
{"", true}, // real MCP clients and curl send no Origin
107+
{"http://127.0.0.1:8765", true},
108+
{"http://localhost:8765", true},
109+
{"http://[::1]:8765", true},
110+
{"https://localhost", true},
111+
{"http://evil.example", false}, // a page the user happens to visit
112+
{"https://evil.example", false}, // ...over TLS
113+
{"http://127.0.0.1.evil.test", false},
114+
{"http://localhost.evil.test", false},
115+
{"null", false}, // sandboxed iframe / some redirects
116+
{"://", false}, // unparseable
117+
// userinfo must not be mistaken for the host
118+
{"http://localhost@evil.example", false},
119+
{"http://127.0.0.1@evil.example/x", false},
120+
// a host that merely contains a loopback name
121+
{"http://myLocalhost", false},
122+
{"http://localhost.", false},
123+
{"http://127.0.0.2", false},
124+
// non-http schemes still carry a host that must match
125+
{"file://localhost", true},
126+
{"https://evil.example:80", false},
127+
}
128+
for _, c := range cases {
129+
r := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader("{}"))
130+
if c.origin != "" {
131+
r.Header.Set("Origin", c.origin)
132+
}
133+
if got := originAllowed(r); got != c.want {
134+
t.Errorf("originAllowed(Origin: %q) = %v, want %v", c.origin, got, c.want)
135+
}
136+
}
137+
}
138+
139+
func TestHTTPHandlerRejectsForeignOrigin(t *testing.T) {
140+
srv := httptest.NewServer(Server{}.httpHandler())
141+
defer srv.Close()
142+
143+
body := `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`
144+
145+
// a browser on an attacker's page: must be refused before any tool runs
146+
req, err := http.NewRequest(http.MethodPost, srv.URL+"/mcp", strings.NewReader(body))
147+
if err != nil {
148+
t.Fatal(err)
149+
}
150+
req.Header.Set("Origin", "http://evil.example")
151+
res, err := srv.Client().Do(req)
152+
if err != nil {
153+
t.Fatal(err)
154+
}
155+
defer res.Body.Close()
156+
if res.StatusCode != http.StatusForbidden {
157+
t.Fatalf("cross-origin request: status = %d, want %d", res.StatusCode, http.StatusForbidden)
158+
}
159+
160+
// a non-browser client (no Origin) must still work
161+
res2, err := srv.Client().Post(srv.URL+"/mcp", "application/json", strings.NewReader(body))
162+
if err != nil {
163+
t.Fatal(err)
164+
}
165+
defer res2.Body.Close()
166+
if res2.StatusCode != http.StatusOK {
167+
t.Fatalf("no-Origin request: status = %d, want %d", res2.StatusCode, http.StatusOK)
168+
}
169+
var parsed response
170+
if err := json.NewDecoder(res2.Body).Decode(&parsed); err != nil {
171+
t.Fatal(err)
172+
}
173+
if parsed.Result == nil {
174+
t.Fatal("expected a tools/list result for a request without Origin")
175+
}
176+
}

‎src/dbmem-http.m‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@
1010
#include "sqlite-memory.h"
1111
#include <string.h>
1212

13+
#ifndef SQLITE_CORE
14+
SQLITE_EXTENSION_INIT3
15+
#endif
16+
1317
int dbmem_http_post(const char *url, const char *api_key, const char *body,
1418
void **out_data, size_t *out_size, long *out_http_code,
1519
char *err_msg, size_t err_msg_size) {

‎src/dbmem-lembed.c‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,11 @@ void dbmem_local_engine_free (dbmem_local_engine_t *engine) {
402402
llama_model_free(engine->model);
403403
engine->model = NULL;
404404
}
405-
406-
llama_backend_free();
405+
406+
// llama_backend_init()/llama_backend_free() act on process-global state and are
407+
// not reference counted, so freeing here would tear down state still in use by
408+
// another engine (memory_set_model builds the new engine before releasing the
409+
// old one, and every connection has its own engine). The global tables are
410+
// reclaimed at process exit.
407411
dbmemory_free(engine);
408412
}

0 commit comments

Comments
 (0)