Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(gitlab): 仓库文件下载补体积上限,超限报错而不是无界读入 (#3887)

linus-liu-web1dbe9d0c1a1b
diff --git a/internal/datasource/connector/gitlab/client.go b/internal/datasource/connector/gitlab/client.go
index 20990f1d2..5a26de625 100644
--- a/internal/datasource/connector/gitlab/client.go
+++ b/internal/datasource/connector/gitlab/client.go
@@ -16,10 +16,54 @@ import (
"github.com/Tencent/WeKnora/internal/datasource"
)
+const (
+ // maxJSONResponseBytes bounds project, user, commit and paginated tree JSON.
+ // Those listings are small; a larger body means a broken or hostile server.
+ maxJSONResponseBytes int64 = 16 << 20
+ // maxCompareResponseBytes bounds GET /repository/compare. That body carries
+ // the full commit list and patch text. A straight compare across a long
+ // unsynced range or a force-push routinely exceeds the metadata cap, and
+ // failing it aborts the project sync before the cursor advances. Sync only
+ // keeps paths and compare_timeout, but the response still has to be buffered.
+ maxCompareResponseBytes int64 = 128 << 20
+ // maxRawFileBytes bounds a single repository blob. GitLab's tree and
+ // compare endpoints do not report blob sizes, so the download itself is the
+ // only place a limit can be enforced. 512 MiB matches the Feishu connector,
+ // the other connector that pulls arbitrary binary files.
+ maxRawFileBytes int64 = 512 << 20
+)
+
+// base64FileBytes is the JSON cap for the file-detail fallback, whose body
+// carries the raw blob base64-encoded (4/3 of its size) plus an envelope.
+func base64FileBytes(rawLimit int64) int64 {
+ return rawLimit/3*4 + (1 << 20)
+}
+
type client struct {
baseURL, token string
http *http.Client
+ // jsonLimit, compareLimit and rawLimit are fields rather than direct uses of
+ // the constants above so tests can lower them without materialising hundreds
+ // of megabytes. newClient always sets the production values.
+ jsonLimit int64
+ compareLimit int64
+ rawLimit int64
}
+
+// readCapped reads a response body, refusing anything larger than limit instead
+// of buffering it. Oversized payloads are reported as an error: a truncated
+// body would be indexed as if it were the whole document.
+func readCapped(body io.Reader, limit int64) ([]byte, error) {
+ data, err := io.ReadAll(io.LimitReader(body, limit+1))
+ if err != nil {
+ return nil, err
+ }
+ if int64(len(data)) > limit {
+ return nil, fmt.Errorf("response exceeds maximum size (%d bytes)", limit)
+ }
+ return data, nil
+}
+
type apiError struct {
endpoint string
status int
@@ -71,9 +115,23 @@ func newClient(baseURL, token string) (*client, error) {
if !strings.HasSuffix(baseURL, "/api/v4") {
baseURL += "/api/v4"
}
- return &client{baseURL: baseURL, token: token, http: datasource.NewConnectorHTTPClient(30 * time.Second)}, nil
+ return &client{
+ baseURL: baseURL,
+ token: token,
+ http: datasource.NewConnectorHTTPClient(30 * time.Second),
+ jsonLimit: maxJSONResponseBytes,
+ compareLimit: maxCompareResponseBytes,
+ rawLimit: maxRawFileBytes,
+ }, nil
}
+
func (c *client) get(ctx context.Context, endpoint string, out interface{}) error {
+ return c.getCapped(ctx, endpoint, out, c.jsonLimit)
+}
+
+// getCapped is get with an explicit response cap. Compare and the base64 file
+// fallback pass their own limits because those bodies are larger than metadata.
+func (c *client) getCapped(ctx context.Context, endpoint string, out interface{}, limit int64) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+endpoint, nil)
if err != nil {
return err
@@ -84,15 +142,16 @@ func (c *client) get(ctx context.Context, endpoint string, out interface{}) erro
return err
}
defer resp.Body.Close()
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return err
- }
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return &apiError{endpoint: endpoint, status: resp.StatusCode}
}
+ body, err := readCapped(resp.Body, limit)
+ if err != nil {
+ return fmt.Errorf("gitlab API %s: %w", endpoint, err)
+ }
return json.Unmarshal(body, out)
}
+
func (c *client) getRaw(ctx context.Context, endpoint string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+endpoint, nil)
if err != nil {
@@ -107,7 +166,11 @@ func (c *client) getRaw(ctx context.Context, endpoint string) ([]byte, error) {
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, &apiError{endpoint: endpoint, status: resp.StatusCode}
}
- return io.ReadAll(resp.Body)
+ body, err := readCapped(resp.Body, c.rawLimit)
+ if err != nil {
+ return nil, fmt.Errorf("gitlab raw file %s: %w", endpoint, err)
+ }
+ return body, nil
}
// projectPath encodes a GitLab project identifier for URL path segments.
@@ -136,11 +199,13 @@ func projectPath(id string) string {
}
return url.PathEscape(decoded)
}
+
func (c *client) project(ctx context.Context, id string) (*project, error) {
var p project
err := c.get(ctx, "/projects/"+projectPath(id), &p)
return &p, err
}
+
func (c *client) projects(ctx context.Context) ([]project, error) {
q := url.Values{
"membership": {"true"}, "per_page": {"100"}, "page": {"1"},
@@ -170,6 +235,7 @@ func (c *client) ping(ctx context.Context) error {
}
return c.get(ctx, "/user", &user)
}
+
func (c *client) commitSHA(ctx context.Context, id, ref string) (string, error) {
var v struct {
ID string `json:"id"`
@@ -177,6 +243,7 @@ func (c *client) commitSHA(ctx context.Context, id, ref string) (string, error)
err := c.get(ctx, "/projects/"+projectPath(id)+"/repository/commits/"+url.PathEscape(ref), &v)
return v.ID, err
}
+
func (c *client) tree(ctx context.Context, id, ref, dir string) ([]treeEntry, error) {
q := url.Values{"ref": {ref}, "per_page": {"100"}, "page": {"1"}}
if dir != "" {
@@ -209,18 +276,19 @@ func (c *client) getPage(ctx context.Context, endpoint string, query url.Values,
return "", err
}
defer resp.Body.Close()
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return "", err
- }
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return "", &apiError{endpoint: endpoint, status: resp.StatusCode}
}
+ body, err := readCapped(resp.Body, c.jsonLimit)
+ if err != nil {
+ return "", fmt.Errorf("gitlab API %s: %w", endpoint, err)
+ }
if err := json.Unmarshal(body, out); err != nil {
return "", err
}
return resp.Header.Get("X-Next-Page"), nil
}
+
func (c *client) raw(ctx context.Context, id, ref, file string) ([]byte, error) {
q := url.Values{"ref": {ref}}
encodedFile := gitlabFilePathEscape(file)
@@ -231,7 +299,7 @@ func (c *client) raw(ctx context.Context, id, ref, file string) ([]byte, error)
}
var apiErr *apiError
if !errors.As(err, &apiErr) || apiErr.status != http.StatusNotFound {
- return nil, fmt.Errorf("gitlab raw file: %w", err)
+ return nil, fmt.Errorf("gitlab file %s: %w", file, err)
}
// Some GitLab deployments expose the file detail endpoint but return 404
@@ -242,15 +310,15 @@ func (c *client) raw(ctx context.Context, id, ref, file string) ([]byte, error)
Content string `json:"content"`
}
detailEndpoint := "/projects/" + projectPath(id) + "/repository/files/" + encodedFile + "?" + q.Encode()
- if err := c.get(ctx, detailEndpoint, &detail); err != nil {
- return nil, fmt.Errorf("gitlab file content: %w", err)
+ if err := c.getCapped(ctx, detailEndpoint, &detail, base64FileBytes(c.rawLimit)); err != nil {
+ return nil, fmt.Errorf("gitlab file %s: %w", file, err)
}
if detail.Encoding != "base64" {
- return nil, fmt.Errorf("gitlab file content: unsupported encoding %q", detail.Encoding)
+ return nil, fmt.Errorf("gitlab file %s: unsupported encoding %q", file, detail.Encoding)
}
content, err = base64.StdEncoding.DecodeString(detail.Content)
if err != nil {
- return nil, fmt.Errorf("gitlab file content: decode base64: %w", err)
+ return nil, fmt.Errorf("gitlab file %s: decode base64: %w", file, err)
}
return content, nil
}
@@ -273,11 +341,12 @@ func gitlabFilePathEscape(file string) string {
}
return b.String()
}
+
func (c *client) compare(ctx context.Context, id, from, to string) (*comparison, error) {
// Sync compares snapshots, not changes since their merge base. The default
// comparison misses reverted files when a branch is reset or force-pushed.
q := url.Values{"from": {from}, "to": {to}, "straight": {"true"}}
var v comparison
- err := c.get(ctx, "/projects/"+projectPath(id)+"/repository/compare?"+q.Encode(), &v)
+ err := c.getCapped(ctx, "/projects/"+projectPath(id)+"/repository/compare?"+q.Encode(), &v, c.compareLimit)
return &v, err
}
diff --git a/internal/datasource/connector/gitlab/client_test.go b/internal/datasource/connector/gitlab/client_test.go
index 3654bbdd1..6cd720ea5 100644
--- a/internal/datasource/connector/gitlab/client_test.go
+++ b/internal/datasource/connector/gitlab/client_test.go
@@ -1,6 +1,7 @@
package gitlab
import (
+ "bytes"
"context"
"errors"
"fmt"
@@ -202,7 +203,8 @@ func TestFetchIncrementalSyncsMultipleProjects(t *testing.T) {
map[string]interface{}{"project_id": "1", "ref": "master", "paths": []interface{}{}},
map[string]interface{}{"project_id": "2", "ref": "master", "paths": []interface{}{}},
},
- }}
+ },
+ }
items, cursor, err := connector.FetchIncremental(context.Background(), config, nil)
if err != nil {
@@ -406,3 +408,286 @@ func TestGitlabFilePathEscape(t *testing.T) {
t.Fatalf("gitlabFilePathEscape() = %q, want %q", got, want)
}
}
+
+// newCappedTestClient builds a client whose JSON and raw-file caps are small
+// enough to exercise them without materialising the production limits.
+// compareLimit stays at the production value unless the test assigns it.
+func newCappedTestClient(t *testing.T, serverURL string, jsonLimit, rawLimit int64) *client {
+ t.Helper()
+ c, err := newClient(serverURL, "token")
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.jsonLimit = jsonLimit
+ c.rawLimit = rawLimit
+ return c
+}
+
+func TestGetRawRejectsBlobLargerThanCap(t *testing.T) {
+ allowLocalGitLabServer(t)
+ const rawLimit = 1 << 20
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write(bytes.Repeat([]byte("a"), rawLimit+1))
+ }))
+ defer server.Close()
+
+ c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, rawLimit)
+ content, err := c.getRaw(context.Background(), "/projects/1/repository/files/big.bin/raw")
+ if err == nil {
+ t.Fatalf("getRaw() accepted a %d-byte blob under a %d-byte cap", len(content), rawLimit)
+ }
+ if content != nil {
+ t.Fatalf("getRaw() returned %d bytes alongside the error, want no partial body", len(content))
+ }
+ if !strings.Contains(err.Error(), "exceeds maximum size") {
+ t.Fatalf("error = %v, want an explicit over-limit error", err)
+ }
+ if !strings.Contains(err.Error(), fmt.Sprint(rawLimit)) {
+ t.Fatalf("error = %v, want it to name the %d-byte limit", err, rawLimit)
+ }
+}
+
+func TestGetRawAcceptsBlobAtCap(t *testing.T) {
+ allowLocalGitLabServer(t)
+ const rawLimit = 1 << 20
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write(bytes.Repeat([]byte("a"), rawLimit))
+ }))
+ defer server.Close()
+
+ c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, rawLimit)
+ content, err := c.getRaw(context.Background(), "/projects/1/repository/files/fit.bin/raw")
+ if err != nil {
+ t.Fatalf("getRaw() rejected a blob exactly at the cap: %v", err)
+ }
+ if len(content) != rawLimit {
+ t.Fatalf("content = %d bytes, want the full %d", len(content), rawLimit)
+ }
+}
+
+// TestRawSurfacesOversizedBlobInsteadOfFallingBack checks that hitting the size
+// cap fails the fetch rather than being mistaken for a missing /raw route and
+// retried through the base64 detail endpoint.
+func TestRawSurfacesOversizedBlobInsteadOfFallingBack(t *testing.T) {
+ allowLocalGitLabServer(t)
+ const rawLimit = 1 << 20
+ detailHits := 0
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.EscapedPath(), "/raw") {
+ _, _ = w.Write(bytes.Repeat([]byte("a"), rawLimit+1))
+ return
+ }
+ detailHits++
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"encoding":"base64","content":"SGk="}`))
+ }))
+ defer server.Close()
+
+ c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, rawLimit)
+ const file = "docs/guide.mp3"
+ content, err := c.raw(context.Background(), "1", "main", file)
+ if err == nil {
+ t.Fatalf("raw() accepted a %d-byte blob under a %d-byte cap", len(content), rawLimit)
+ }
+ if !strings.Contains(err.Error(), "exceeds maximum size") {
+ t.Fatalf("error = %v, want an explicit over-limit error", err)
+ }
+ if !strings.Contains(err.Error(), file) {
+ t.Fatalf("error = %v, want the repository path %s", err, file)
+ }
+ if detailHits != 0 {
+ t.Fatalf("base64 detail endpoint hit %d times, want 0", detailHits)
+ }
+}
+
+func TestBase64FallbackRejectsOversizedDetail(t *testing.T) {
+ allowLocalGitLabServer(t)
+ const rawLimit = 3 << 20
+ limit := base64FileBytes(rawLimit)
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.EscapedPath(), "/raw") {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write(bytes.Repeat([]byte("a"), int(limit)+1))
+ }))
+ defer server.Close()
+
+ c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, rawLimit)
+ const file = "docs/guide.mp3"
+ if _, err := c.raw(context.Background(), "1", "main", file); err == nil {
+ t.Fatal("raw() accepted an oversized base64 detail response")
+ } else if !strings.Contains(err.Error(), "exceeds maximum size") {
+ t.Fatalf("error = %v, want an explicit over-limit error", err)
+ } else if !strings.Contains(err.Error(), file) {
+ t.Fatalf("error = %v, want the repository path %s", err, file)
+ }
+}
+
+func TestGetRejectsOversizedJSONResponse(t *testing.T) {
+ allowLocalGitLabServer(t)
+ const jsonLimit = 512 << 10
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write(bytes.Repeat([]byte("a"), jsonLimit+1))
+ }))
+ defer server.Close()
+
+ c := newCappedTestClient(t, server.URL, jsonLimit, maxRawFileBytes)
+ var out struct{}
+ err := c.get(context.Background(), "/projects/1", &out)
+ if err == nil {
+ t.Fatal("get() accepted an oversized JSON response")
+ }
+ if !strings.Contains(err.Error(), "exceeds maximum size") {
+ t.Fatalf("error = %v, want an explicit over-limit error", err)
+ }
+}
+
+func TestGetPageRejectsOversizedJSONResponse(t *testing.T) {
+ allowLocalGitLabServer(t)
+ const jsonLimit = 512 << 10
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write(bytes.Repeat([]byte("a"), jsonLimit+1))
+ }))
+ defer server.Close()
+
+ c := newCappedTestClient(t, server.URL, jsonLimit, maxRawFileBytes)
+ if _, err := c.tree(context.Background(), "1", "main", ""); err == nil {
+ t.Fatal("tree() accepted an oversized JSON response")
+ } else if !strings.Contains(err.Error(), "exceeds maximum size") {
+ t.Fatalf("error = %v, want an explicit over-limit error", err)
+ }
+}
+
+// TestOversizedErrorBodyKeepsStatusError pins that an oversized body on a
+// non-2xx response is still reported as the HTTP status, so a large error page
+// cannot mask the real failure.
+func TestOversizedErrorBodyKeepsStatusError(t *testing.T) {
+ allowLocalGitLabServer(t)
+ const jsonLimit = 512 << 10
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusInternalServerError)
+ _, _ = w.Write(bytes.Repeat([]byte("a"), jsonLimit+1))
+ }))
+ defer server.Close()
+
+ for name, call := range map[string]func(*client) error{
+ "get": func(c *client) error {
+ var out struct{}
+ return c.get(context.Background(), "/projects/1", &out)
+ },
+ "getPage": func(c *client) error {
+ _, err := c.tree(context.Background(), "1", "main", "")
+ return err
+ },
+ } {
+ c := newCappedTestClient(t, server.URL, jsonLimit, maxRawFileBytes)
+ err := call(c)
+ var apiErr *apiError
+ if !errors.As(err, &apiErr) {
+ t.Fatalf("%s: error = %v, want an *apiError", name, err)
+ }
+ if apiErr.status != http.StatusInternalServerError {
+ t.Fatalf("%s: status = %d, want %d", name, apiErr.status, http.StatusInternalServerError)
+ }
+ }
+}
+
+func TestNewClientSetsResponseCaps(t *testing.T) {
+ allowLocalGitLabServer(t)
+ server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
+ defer server.Close()
+
+ c, err := newClient(server.URL, "token")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if c.jsonLimit != maxJSONResponseBytes ||
+ c.compareLimit != maxCompareResponseBytes ||
+ c.rawLimit != maxRawFileBytes {
+ t.Fatalf("caps = json %d compare %d raw %d", c.jsonLimit, c.compareLimit, c.rawLimit)
+ }
+ if c.compareLimit <= c.jsonLimit {
+ t.Fatalf("compare cap %d must sit above the metadata cap %d", c.compareLimit, c.jsonLimit)
+ }
+}
+
+// TestCompareAllowsPayloadAboveMetadataCap pins that a straight compare larger
+// than the metadata JSON cap still succeeds. That body carries commits and
+// patches the sync does not store; rejecting it would stall the project cursor.
+func TestCompareAllowsPayloadAboveMetadataCap(t *testing.T) {
+ allowLocalGitLabServer(t)
+ const (
+ jsonLimit = 512
+ compareLimit = 8 << 10
+ )
+ padding := strings.Repeat("p", jsonLimit)
+ payload := `{"diffs":[{"old_path":"docs/old.md","new_path":"docs/new.md","renamed_file":true}],` +
+ `"compare_timeout":false,"padding":"` + padding + `"}`
+ body := []byte(payload)
+ if int64(len(body)) <= jsonLimit || int64(len(body)) > compareLimit {
+ t.Fatalf("fixture is %d bytes, want it between %d and %d", len(body), jsonLimit, compareLimit)
+ }
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write(body)
+ }))
+ defer server.Close()
+
+ c := newCappedTestClient(t, server.URL, jsonLimit, maxRawFileBytes)
+ c.compareLimit = compareLimit
+
+ var project struct{}
+ if err := c.get(context.Background(), "/projects/1", &project); err == nil {
+ t.Fatal("get() accepted a body above the metadata cap")
+ } else if !strings.Contains(err.Error(), "exceeds maximum size") {
+ t.Fatalf("get() error = %v, want an explicit over-limit error", err)
+ }
+
+ diff, err := c.compare(context.Background(), "1", "abc", "def")
+ if err != nil {
+ t.Fatalf("compare() rejected a body above the metadata cap and under the compare cap: %v", err)
+ }
+ if diff.CompareTimeout {
+ t.Fatal("compare_timeout = true, want false")
+ }
+ if len(diff.Diffs) != 1 ||
+ diff.Diffs[0].OldPath != "docs/old.md" ||
+ diff.Diffs[0].NewPath != "docs/new.md" ||
+ !diff.Diffs[0].RenamedFile {
+ t.Fatalf("diffs = %+v", diff.Diffs)
+ }
+}
+
+func TestCompareRejectsPayloadAboveCompareCap(t *testing.T) {
+ allowLocalGitLabServer(t)
+ const compareLimit = 1024
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write(bytes.Repeat([]byte("a"), compareLimit+1))
+ }))
+ defer server.Close()
+
+ c := newCappedTestClient(t, server.URL, maxJSONResponseBytes, maxRawFileBytes)
+ c.compareLimit = compareLimit
+ _, err := c.compare(context.Background(), "1", "abc", "def")
+ if err == nil {
+ t.Fatal("compare() accepted a body above the compare cap")
+ }
+ if !strings.Contains(err.Error(), "exceeds maximum size") ||
+ !strings.Contains(err.Error(), fmt.Sprint(compareLimit)) {
+ t.Fatalf("error = %v, want an explicit over-limit error naming %d", err, compareLimit)
+ }
+}