Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
refactor(skills): improve skill bundle size handling and error management
wizardchen17324c46e41d
diff --git a/.env.example b/.env.exampleindex 59c1d21a5..8ca098924 100644--- a/.env.example+++ b/.env.example@@ -187,7 +187,7 @@ LOCAL_STORAGE_BASE_DIR=/data/files# LOCAL_STORAGE_PATH_PREFIX=# 统一文件大小限制(MB,默认 50)。影响知识库/附件单文件上传、docreader gRPC 消息、浏览器知识库校验。属部署期配置:Go/Nginx/docreader/浏览器四层启动时读一次,运行中改不生效,改后须同步重启四层。# MAX_FILE_SIZE_MB=50-# 技能 zip 上传与 GitHub/ClawHub 来源下载上限(MB,默认 256)。与知识库上传分开:ppt-master 一类技能包会超过 50MB。未设置时不低于 MAX_FILE_SIZE_MB,且不超过 512。Nginx 只对技能上传的两条路由放宽到这个值,其余路由仍是 MAX_FILE_SIZE_MB。改后须重启 app 与 frontend。+# 技能 zip 上传与 GitHub/ClawHub 来源下载上限(MB,默认 256)。与知识库上传分开:ppt-master 一类技能包会超过 50MB。GitHub zipball 按整仓压缩包计,不是 SKILL.md 子树;仓过大仍会在下载阶段被拒。未设置时不低于 MAX_FILE_SIZE_MB,且不超过 512。Nginx 只对技能上传的两条路由放宽到这个值,其余路由仍是 MAX_FILE_SIZE_MB。改后须重启 app 与 frontend。# MAX_SKILL_BUNDLE_SIZE_MB=256# ========== B4. 对象存储 provider(按 STORAGE_TYPE 选其一)==========diff --git a/docker-compose.yml b/docker-compose.ymlindex 18535fae6..ea4bf225d 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -312,7 +312,7 @@ services:- JWT_SECRET=${JWT_SECRET:-}# File size limit (in MB)- MAX_FILE_SIZE_MB=${MAX_FILE_SIZE_MB:-50}- # Skill zip / GitHub source download cap (in MB); independent of knowledge uploads+ # Skill zip / GitHub source download cap (in MB); the GitHub zipball is the whole repo, not the skill subtree- MAX_SKILL_BUNDLE_SIZE_MB=${MAX_SKILL_BUNDLE_SIZE_MB:-256}# 文档处理任务总超时(Go duration,默认 2h)- WEKNORA_DOCUMENT_PROCESS_TIMEOUT=${WEKNORA_DOCUMENT_PROCESS_TIMEOUT:-}diff --git a/frontend/src/composables/useConfigSkillInstallProgress.test.mjs b/frontend/src/composables/useConfigSkillInstallProgress.test.mjsindex 787dc3531..39b3f7d47 100644--- a/frontend/src/composables/useConfigSkillInstallProgress.test.mjs+++ b/frontend/src/composables/useConfigSkillInstallProgress.test.mjs@@ -15,7 +15,12 @@ test('catalog install progress follows the same SSE as the sandbox panel', () =>assert.match(source, /fetchEventSource/)assert.match(source, /configSkillInstallEventsUrl/)assert.match(source, /openWhenHidden: true/)- assert.match(source, /existing\?\.done && existing\.stage !== 'detached'/)+ assert.match(source, /if \(!configId \|\| !skillId \|\| abortByKey\.has\(key\)\) return/)+ assert.doesNotMatch(+ source,+ /existing\?\.done && existing\.stage !== 'detached'/,+ 'a done event must not block reconnect: retry reuses the same skill id',+ )})test('progress keys isolate one install per sandbox', () => {diff --git a/frontend/src/composables/useConfigSkillInstallProgress.ts b/frontend/src/composables/useConfigSkillInstallProgress.tsindex 65ba645a0..04f71d625 100644--- a/frontend/src/composables/useConfigSkillInstallProgress.ts+++ b/frontend/src/composables/useConfigSkillInstallProgress.ts@@ -56,10 +56,9 @@ export function useConfigSkillInstallProgress(options?: {function follow(configId: string, skillId: string) {const key = progressKey(configId, skillId)if (!configId || !skillId || abortByKey.has(key)) return- const existing = progressByKey.value[key]- // A finished stream (success, failure, or no Redis) must not be reopened- // on every catalog poll. Detached is the exception: the run is still going.- if (existing?.done && existing.stage !== 'detached') return+ // abortByKey is the in-flight guard. A finished event for this key is+ // either status lag or a new run of the same skill id (retry); skipping+ // reconnect would leave the drawer showing the previous 100%.forget(key)const controller = new AbortController()abortByKey.set(key, controller)diff --git a/frontend/src/utils/request.ts b/frontend/src/utils/request.tsindex a032317f6..438a3780d 100644--- a/frontend/src/utils/request.ts+++ b/frontend/src/utils/request.ts@@ -1,8 +1,9 @@// src/utils/request.jsimport axios from "axios";-import { generateRandomString, MAX_FILE_SIZE_MB } from "./index";+import { generateRandomString, MAX_FILE_SIZE_MB, MAX_SKILL_BUNDLE_SIZE_MB } from "./index";import i18n from '@/i18n'import { getApiBaseUrl } from './api-base';+import { isSkillBundleUploadUrl } from './uploadLimit';const t = (key: string) => i18n.global.t(key)@@ -215,9 +216,12 @@ instance.interceptors.response.use(// 处理 Nginx 413 Request Entity Too Largeif (error.response.status === 413) {+ const skillUpload = isSkillBundleUploadUrl(error.config?.url)return Promise.reject({status: 413,- message: i18n.global.t('error.fileSizeExceeded', { size: MAX_FILE_SIZE_MB }),+ message: skillUpload+ ? i18n.global.t('settings.sandbox.skillBundleTooLarge', { size: MAX_SKILL_BUNDLE_SIZE_MB })+ : i18n.global.t('error.fileSizeExceeded', { size: MAX_FILE_SIZE_MB }),success: false});}diff --git a/frontend/src/utils/uploadLimit.test.mjs b/frontend/src/utils/uploadLimit.test.mjsnew file mode 100644index 000000000..ac76093db--- /dev/null+++ b/frontend/src/utils/uploadLimit.test.mjs@@ -0,0 +1,18 @@+import assert from 'node:assert/strict'+import test from 'node:test'++import { isSkillBundleUploadUrl } from './uploadLimit.ts'++test('skill catalog and sandbox skill uploads use the skill-bundle 413 path', () => {+ assert.equal(isSkillBundleUploadUrl('/api/v1/skills/catalog'), true)+ assert.equal(isSkillBundleUploadUrl('/api/v1/skills/catalog?foo=1'), true)+ assert.equal(isSkillBundleUploadUrl('/api/v1/sandbox-configs/cfg-a/skills'), true)+ assert.equal(isSkillBundleUploadUrl('https://host/api/v1/sandbox-configs/cfg-a/skills'), true)+})++test('knowledge and other API uploads stay on the knowledge-size 413 path', () => {+ assert.equal(isSkillBundleUploadUrl(undefined), false)+ assert.equal(isSkillBundleUploadUrl('/api/v1/knowledge'), false)+ assert.equal(isSkillBundleUploadUrl('/api/v1/knowledge-bases/kb-1/knowledge'), false)+ assert.equal(isSkillBundleUploadUrl('/api/v1/models/debug'), false)+})diff --git a/frontend/src/utils/uploadLimit.ts b/frontend/src/utils/uploadLimit.tsnew file mode 100644index 000000000..da4de35e6--- /dev/null+++ b/frontend/src/utils/uploadLimit.ts@@ -0,0 +1,9 @@+/** True when nginx's skill-upload location (256MB) applies, not the knowledge 50MB cap. */+export function isSkillBundleUploadUrl(url: string | undefined): boolean {+ if (!url) return false+ const path = url.split('?')[0]+ return /(?:^|\/)api\/v1\/skills\/catalog(?:\/|$)/.test(path)+ || /(?:^|\/)api\/v1\/sandbox-configs\/[^/]+\/skills(?:\/|$)/.test(path)+ || /(?:^|\/)skills\/catalog(?:\/|$)/.test(path)+ || /(?:^|\/)sandbox-configs\/[^/]+\/skills(?:\/|$)/.test(path)+}diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.goindex 2fffaecaf..ce7f84fcf 100644--- a/internal/application/service/agent_service.go+++ b/internal/application/service/agent_service.go@@ -578,10 +578,10 @@ func (s *agentService) tenantSkillSource(// loadInstalledSkillBundle reads the archive one installed skill was built// from. An object named by the row itself is that archive. A row that only// names a catalog is answered from the definition's zip, but the definition is-// mutable — registering the same skill again replaces those bytes in place,-// while this sandbox goes on running the image built from the previous ones.-// read_skill is documented as serving what was installed, so a definition that-// has moved on is reported rather than substituted.+// mutable — registering the same skill again stores a new object and updates+// the catalog ref, while this sandbox goes on running the image built from the+// previous bytes. read_skill is documented as serving what was installed, so a+// definition that has moved on is reported rather than substituted.func (s *agentService) loadInstalledSkillBundle(ctx context.Context, tenantID uint64, row *types.TenantSkillEntity,) ([]byte, error) {diff --git a/internal/application/service/agent_service_skill_bundle_test.go b/internal/application/service/agent_service_skill_bundle_test.gonew file mode 100644index 000000000..b419ce2af--- /dev/null+++ b/internal/application/service/agent_service_skill_bundle_test.go@@ -0,0 +1,134 @@+package service++import (+ "bytes"+ "context"+ "errors"+ "io"+ "mime/multipart"+ "strings"+ "testing"++ "github.com/Tencent/WeKnora/internal/application/repository"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "github.com/stretchr/testify/require"+ "gorm.io/driver/sqlite"+ "gorm.io/gorm"+)++type skillBundleFileMap struct {+ files map[string][]byte+}++func (s skillBundleFileMap) CheckConnectivity(context.Context) error { return nil }+func (s skillBundleFileMap) SaveFile(context.Context, *multipart.FileHeader, uint64, string) (string, error) {+ return "", errors.New("not implemented")+}+func (s skillBundleFileMap) SaveBytes(context.Context, []byte, uint64, string, bool) (string, error) {+ return "", errors.New("not implemented")+}+func (s skillBundleFileMap) GetFile(_ context.Context, ref string) (io.ReadCloser, error) {+ data, ok := s.files[ref]+ if !ok {+ return nil, errors.New("bundle not found")+ }+ return io.NopCloser(bytes.NewReader(data)), nil+}+func (s skillBundleFileMap) GetFileURL(context.Context, string) (string, error) { return "", nil }+func (s skillBundleFileMap) DeleteFile(context.Context, string) error { return nil }+func (s skillBundleFileMap) CopyFile(context.Context, string, uint64, string) (string, error) {+ return "", errors.New("not implemented")+}++type skillBundleResolver struct{ fs interfaces.FileService }++func (r skillBundleResolver) ResolveFileService(+ context.Context, *types.Tenant, string, string, string,+) (interfaces.FileService, string, error) {+ return r.fs, "", nil+}+func (skillBundleResolver) ResolveBackend(+ context.Context, *types.Tenant, string, string,+) (*types.StorageBackend, error) {+ return nil, nil+}++func newAgentSkillBundleService(t *testing.T, files map[string][]byte) (*agentService, *gorm.DB) {+ t.Helper()+ dsn := "file:agent-skill-" + strings.ReplaceAll(t.Name(), "/", "_") + "?mode=memory&cache=shared"+ db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})+ require.NoError(t, err)+ require.NoError(t, db.AutoMigrate(+ &types.TenantSkillEntity{}, &types.TenantSkillCatalogEntity{},+ &types.TenantSkillSnapshotEntity{}, &types.TenantUserEnvVar{},+ ))+ return &agentService{+ db: db,+ storageResolver: skillBundleResolver{fs: skillBundleFileMap{files: files}},+ }, db+}++func zipSkillArchive(t *testing.T, extract string) []byte {+ t.Helper()+ archive, err := zipSkillFiles(map[string][]byte{+ "SKILL.md": []byte(validSkillMD),+ "scripts/extract.py": []byte(extract),+ })+ require.NoError(t, err)+ return archive+}++func TestLoadInstalledSkillBundleReadsAMatchingCatalogArchive(t *testing.T) {+ v1 := zipSkillArchive(t, "print('v1')\n")+ svc, db := newAgentSkillBundleService(t, map[string][]byte{"file://catalog.zip": v1})+ ctx := context.Background()+ require.NoError(t, repository.NewTenantSkillRepository(db).CreateCatalog(ctx, &types.TenantSkillCatalogEntity{+ ID: "cat-1", TenantID: 7, Name: "pdf-tools",+ BundleRef: "file://catalog.zip", BundleSHA256: skillArchiveSHA256(v1),+ }))++ got, err := svc.loadInstalledSkillBundle(ctx, 7, &types.TenantSkillEntity{+ Name: "pdf-tools", CatalogID: "cat-1", BundleSHA256: skillArchiveSHA256(v1),+ })+ require.NoError(t, err)+ require.Equal(t, v1, got)+}++func TestLoadInstalledSkillBundleRejectsAReplacedCatalogArchive(t *testing.T) {+ v2 := zipSkillArchive(t, "print('v2')\n")+ svc, db := newAgentSkillBundleService(t, map[string][]byte{"file://catalog.zip": v2})+ ctx := context.Background()+ require.NoError(t, repository.NewTenantSkillRepository(db).CreateCatalog(ctx, &types.TenantSkillCatalogEntity{+ ID: "cat-1", TenantID: 7, Name: "pdf-tools",+ BundleRef: "file://catalog.zip", BundleSHA256: skillArchiveSHA256(v2),+ }))++ _, err := svc.loadInstalledSkillBundle(ctx, 7, &types.TenantSkillEntity{+ Name: "pdf-tools", CatalogID: "cat-1",+ BundleSHA256: strings.Repeat("d", 64),+ })+ require.Error(t, err)+ require.Contains(t, err.Error(), "registered again from a different archive")+}++func TestLoadInstalledSkillBundlePrefersAPinnedInstallRef(t *testing.T) {+ v1 := zipSkillArchive(t, "print('v1')\n")+ v2 := zipSkillArchive(t, "print('v2')\n")+ svc, db := newAgentSkillBundleService(t, map[string][]byte{+ "file://old.zip": v1,+ "file://catalog.zip": v2,+ })+ ctx := context.Background()+ require.NoError(t, repository.NewTenantSkillRepository(db).CreateCatalog(ctx, &types.TenantSkillCatalogEntity{+ ID: "cat-1", TenantID: 7, Name: "pdf-tools",+ BundleRef: "file://catalog.zip", BundleSHA256: skillArchiveSHA256(v2),+ }))++ got, err := svc.loadInstalledSkillBundle(ctx, 7, &types.TenantSkillEntity{+ Name: "pdf-tools", CatalogID: "cat-1",+ BundleRef: "file://old.zip", BundleSHA256: skillArchiveSHA256(v1),+ })+ require.NoError(t, err)+ require.Equal(t, v1, got)+}diff --git a/internal/application/service/tenant_skill_source.go b/internal/application/service/tenant_skill_source.goindex bde7da08c..b59ecb4cf 100644--- a/internal/application/service/tenant_skill_source.go+++ b/internal/application/service/tenant_skill_source.go@@ -638,6 +638,8 @@ func getSkillURL(defer func() { _ = resp.Body.Close() }()maxBytes := secutils.GetMaxSkillBundleSize()+ // The cap is the downloaded body — a GitHub zipball is the whole+ // repository, not the SKILL.md subtree counted later at parse time.if resp.ContentLength > maxBytes {return nil, "", fmt.Errorf("%w: skill bundle cannot exceed %d MB",ErrSkillSourceInvalid, secutils.GetMaxSkillBundleSizeMB())diff --git a/internal/handler/initialization.go b/internal/handler/initialization.goindex db67d65d8..f5a647ba1 100644--- a/internal/handler/initialization.go+++ b/internal/handler/initialization.go@@ -2227,7 +2227,7 @@ func (h *InitializationHandler) TestMultimodalFunction(c *gin.Context) {maxSize := maxSizeMB * 1024 * 1024// 上限必须在 multipart 解析之前生效:FormFile 会先把整个 body 缓冲下来// (超出内存部分落临时文件),之后的 header.Size 检查看到的已是收完的上传。- // nginx 的 client_max_body_size 现在取的是更大的技能包上限,不再兜住这里。+ // nginx 的 location /api/ 仍是 MAX_FILE_SIZE;这里是直连 app 时的同一道上限。limitUploadBody(c, maxSize)// 获取上传的图片文件diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.goindex 67e16d26b..68f98f605 100644--- a/internal/handler/knowledge.go+++ b/internal/handler/knowledge.go@@ -339,8 +339,8 @@ func (h *KnowledgeHandler) CreateKnowledgeFromFile(c *gin.Context) {maxSize := maxSizeMB * 1024 * 1024// Capped before the multipart parse, not after: FormFile buffers the whole// body first, so the size check below only ever sees an upload we already- // accepted. nginx no longer bounds this at the knowledge limit either — its- // cap is the larger skill-bundle one.+ // accepted. nginx location /api/ still enforces MAX_FILE_SIZE; this is the+ // same cap for requests that reach the app without that proxy.limitUploadBody(c, maxSize)// Get the uploaded filediff --git a/internal/handler/sandbox_skill.go b/internal/handler/sandbox_skill.goindex bda9b6ac5..e7c2c653d 100644--- a/internal/handler/sandbox_skill.go+++ b/internal/handler/sandbox_skill.go@@ -295,7 +295,7 @@ func (h *SandboxSkillHandler) GetFile(c *gin.Context) {// @Router /sandbox-configs/{id}/skills [post]func (h *SandboxSkillHandler) Upload(c *gin.Context) {maxBytes := secutils.GetMaxSkillBundleSize()- limitUploadBody(c, maxBytes)+ limitSkillUploadBody(c, maxBytes)if strings.HasPrefix(c.ContentType(), "application/json") {h.installFromSource(c)@@ -351,7 +351,7 @@ func (h *SandboxSkillHandler) installFromSource(c *gin.Context) {if err := c.ShouldBindJSON(&req); err != nil {var tooLarge *http.MaxBytesErrorif stderrors.As(err, &tooLarge) {- _ = c.Error(skillTooLargeError())+ _ = c.Error(skillSourceRequestTooLargeError())return}_ = c.Error(apperrors.NewBadRequestError("invalid skill source request"))@@ -403,6 +403,10 @@ func skillTooLargeError() error {fmt.Sprintf("skill bundle cannot exceed %d MB", secutils.GetMaxSkillBundleSizeMB()))}+func skillSourceRequestTooLargeError() error {+ return apperrors.NewBadRequestError("skill source request is too large")+}+type skillPatchRequest struct {// Enabled is a pointer because its absence is not a request to disable the// skill; a body may carry envs instead.diff --git a/internal/handler/sandbox_skill_test.go b/internal/handler/sandbox_skill_test.goindex 67586c52c..01ccdaa65 100644--- a/internal/handler/sandbox_skill_test.go+++ b/internal/handler/sandbox_skill_test.go@@ -423,6 +423,21 @@ func TestSandboxSkillInstallFromSourceAmbiguousShorthandReturns400(t *testing.T)require.Equal(t, "owner/slug", svc.installSource)}+func TestSandboxSkillInstallFromSourceRejectsAnOversizedJSONBody(t *testing.T) {+ svc := &fakeSandboxSkillService{}+ router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))++ req := httptest.NewRequest(http.MethodPost, "/sandbox-configs/cfg-a/skills",+ strings.NewReader(string(oversizedSkillSourceJSON(1))))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ router.ServeHTTP(w, req)++ require.Equal(t, http.StatusBadRequest, w.Code)+ require.Contains(t, w.Body.String(), "skill source request is too large")+ require.Empty(t, svc.installSource)+}+func TestSandboxSkillUploadWithoutFileReturns400(t *testing.T) {svc := &fakeSandboxSkillService{}router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))diff --git a/internal/handler/skill_catalog.go b/internal/handler/skill_catalog.goindex 5c91ecfc0..a6c2d8777 100644--- a/internal/handler/skill_catalog.go+++ b/internal/handler/skill_catalog.go@@ -51,7 +51,7 @@ func (h *SkillHandler) RegisterCatalog(c *gin.Context) {return}maxBytes := secutils.GetMaxSkillBundleSize()- limitUploadBody(c, maxBytes)+ limitSkillUploadBody(c, maxBytes)if strings.HasPrefix(c.ContentType(), "application/json") {h.registerCatalogFromSource(c)@@ -97,7 +97,7 @@ func (h *SkillHandler) registerCatalogFromSource(c *gin.Context) {if err := c.ShouldBindJSON(&req); err != nil {var tooLarge *http.MaxBytesErrorif stderrors.As(err, &tooLarge) {- _ = c.Error(skillTooLargeError())+ _ = c.Error(skillSourceRequestTooLargeError())return}_ = c.Error(apperrors.NewBadRequestError("invalid skill source request"))diff --git a/internal/handler/skill_catalog_test.go b/internal/handler/skill_catalog_test.goindex 8648489a9..d102298d4 100644--- a/internal/handler/skill_catalog_test.go+++ b/internal/handler/skill_catalog_test.go@@ -119,6 +119,21 @@ func TestRegisterCatalogFromSource(t *testing.T) {require.Equal(t, "@owner/pdf", catalog.source)}+func TestRegisterCatalogFromSourceRejectsAnOversizedJSONBody(t *testing.T) {+ catalog := &fakeSkillCatalog{registerID: "cat-9"}+ router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))++ req := httptest.NewRequest(http.MethodPost, "/skills/catalog",+ bytes.NewReader(oversizedSkillSourceJSON(1)))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ router.ServeHTTP(w, req)++ require.Equal(t, http.StatusBadRequest, w.Code)+ require.Contains(t, w.Body.String(), "skill source request is too large")+ require.Empty(t, catalog.source)+}+func TestInstallCatalogAcceptsPerConfigIDs(t *testing.T) {catalog := &fakeSkillCatalog{installs: map[string]string{"cfg-1": "sk-1"}}router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog))diff --git a/internal/handler/upload_limit.go b/internal/handler/upload_limit.goindex e8226e5b2..281e71216 100644--- a/internal/handler/upload_limit.go+++ b/internal/handler/upload_limit.go@@ -3,6 +3,7 @@ package handlerimport (stderrors "errors""net/http"+ "strings""github.com/gin-gonic/gin")@@ -12,18 +13,38 @@ import (// rejecting a legal one for its boundary lines.const uploadEnvelopeSlack = 1 << 20+// skillSourceJSONMaxBytes is the cap on {"source":"..."} (and similar) JSON+// bodies for skill endpoints. The zip is fetched server-side under+// GetMaxSkillBundleSize; this only needs to hold a locator URL.+const skillSourceJSONMaxBytes = 64 << 10+// limitUploadBody caps the request body before anything parses it.//// It has to run before FormFile rather than after: ParseMultipartForm buffers// the whole request, spilling to temp files, so a handler that only checks the-// declared part size has already accepted every byte by the time it looks. The-// frontend nginx used to be the only thing standing here, and its-// client_max_body_size is now the larger skill-bundle cap, so every-// knowledge-sized upload has to state its own limit.+// declared part size has already accepted every byte by the time it looks.+// nginx still enforces MAX_FILE_SIZE on location /api/; this is the same cap+// for requests that reach the app without that proxy.func limitUploadBody(c *gin.Context, maxBytes int64) {c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes+uploadEnvelopeSlack)}+// limitJSONBody caps a JSON body with no multipart slack.+func limitJSONBody(c *gin.Context, maxBytes int64) {+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)+}++// limitSkillUploadBody uses the zip cap for multipart skill uploads and a+// small JSON cap for source locators. Applying the zip cap to JSON would let+// a {"source":"..."} POST occupy hundreds of megabytes.+func limitSkillUploadBody(c *gin.Context, zipMaxBytes int64) {+ if strings.HasPrefix(c.ContentType(), "application/json") {+ limitJSONBody(c, skillSourceJSONMaxBytes)+ return+ }+ limitUploadBody(c, zipMaxBytes)+}+// isRequestBodyTooLarge reports whether a multipart parsing error is the body// cap firing rather than a malformed or absent part.//diff --git a/internal/handler/upload_limit_test.go b/internal/handler/upload_limit_test.goindex ac5f75768..a74552060 100644--- a/internal/handler/upload_limit_test.go+++ b/internal/handler/upload_limit_test.go@@ -99,3 +99,60 @@ func TestIsRequestBodyTooLargeIgnoresAnAbsentPart(t *testing.T) {req.Header.Set("Content-Type", writer.FormDataContentType())engine.ServeHTTP(httptest.NewRecorder(), req)}++func TestLimitJSONBodyRejectsAnOversizedBody(t *testing.T) {+ gin.SetMode(gin.TestMode)+ engine := gin.New()+ engine.POST("/json", func(c *gin.Context) {+ limitJSONBody(c, skillSourceJSONMaxBytes)+ var payload struct {+ Source string `json:"source"`+ }+ err := c.ShouldBindJSON(&payload)+ if isRequestBodyTooLarge(err) {+ c.String(http.StatusBadRequest, "too large")+ return+ }+ c.String(http.StatusOK, payload.Source)+ })++ req := httptest.NewRequest(http.MethodPost, "/json", bytes.NewReader(oversizedSkillSourceJSON(1)))+ req.Header.Set("Content-Type", "application/json")+ rec := httptest.NewRecorder()+ engine.ServeHTTP(rec, req)++ require.Equal(t, http.StatusBadRequest, rec.Code)+ require.Equal(t, "too large", rec.Body.String())+}++func TestLimitSkillUploadBodyKeepsJSONFarBelowTheZipCap(t *testing.T) {+ gin.SetMode(gin.TestMode)+ engine := gin.New()+ engine.POST("/skill", func(c *gin.Context) {+ limitSkillUploadBody(c, 256<<20)+ var payload struct {+ Source string `json:"source"`+ }+ err := c.ShouldBindJSON(&payload)+ if isRequestBodyTooLarge(err) {+ c.String(http.StatusBadRequest, "too large")+ return+ }+ c.String(http.StatusOK, "ok")+ })++ req := httptest.NewRequest(http.MethodPost, "/skill", bytes.NewReader(oversizedSkillSourceJSON(2<<20)))+ req.Header.Set("Content-Type", "application/json")+ rec := httptest.NewRecorder()+ engine.ServeHTTP(rec, req)++ require.Equal(t, http.StatusBadRequest, rec.Code)+ require.Equal(t, "too large", rec.Body.String())+}++func oversizedSkillSourceJSON(extra int) []byte {+ if extra < 1 {+ extra = 1+ }+ return []byte(`{"source":"` + strings.Repeat("x", skillSourceJSONMaxBytes+extra) + `"}`)+}diff --git a/internal/utils/filesize.go b/internal/utils/filesize.goindex 0fadb5b23..780b41293 100644--- a/internal/utils/filesize.go+++ b/internal/utils/filesize.go@@ -42,7 +42,9 @@ func GetMaxFileSizeMB() int64 {// GetMaxSkillBundleSize is the compressed zip / source-download cap for// skills. Knowledge uploads stay on GetMaxFileSize: packages such as// ppt-master exceed 50MB, but raising the document limit would also-// inflate docreader gRPC messages.+// inflate docreader gRPC messages. A GitHub zipball is the whole+// repository archive, not the SKILL.md subtree, so a huge monorepo can+// still be refused here even when the skill itself is small.func GetMaxSkillBundleSize() int64 {return GetMaxSkillBundleSizeMB() * 1024 * 1024}