diff --git a/README.md b/README.md index 392b6a5..3876e0d 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ Once configured, try `list all my repositories` in the chat box. | package_read | Packages | Read | Read package registry: list packages, list versions, or get a version | | package_write | Packages | Write | Delete a package version (irreversible) | | list_issues | Issue | Read | List repository issues | +| attachment_read | Issue | Read | Read issue/comment attachments: list metadata, get metadata, or download content | | issue_read | Issue | Read | Read issue: details, comments, or labels | | issue_write | Issue | Write | Write issues: create, update, manage comments and labels | | list_pull_requests | Pull Request | Read | List repository pull requests | diff --git a/README.zh-cn.md b/README.zh-cn.md index 30e53b7..8903cd6 100644 --- a/README.zh-cn.md +++ b/README.zh-cn.md @@ -151,6 +151,7 @@ Cursor 等客户端可使用 stdio 命令: | package_read | 软件包 | 读取 | 读取软件包注册表:列出软件包、列出版本或获取某个版本 | | package_write | 软件包 | 写入 | 删除软件包版本(不可恢复) | | list_issues | 问题 | 读取 | 列出仓库问题 | +| attachment_read | 问题 | 读取 | 读取问题/评论附件:列出元数据、获取元数据或下载内容 | | issue_read | 问题 | 读取 | 读取问题:详情、评论或标签 | | issue_write | 问题 | 写入 | 写入问题:创建、更新、管理评论和标签 | | list_pull_requests | 拉取请求 | 读取 | 列出仓库拉取请求 | diff --git a/README.zh-tw.md b/README.zh-tw.md index 74ab0e4..0f40e69 100644 --- a/README.zh-tw.md +++ b/README.zh-tw.md @@ -151,6 +151,7 @@ Cursor 等客戶端可使用 stdio 命令: | package_read | 軟體套件 | 讀取 | 讀取軟體套件註冊表:列出套件、列出版本或取得某個版本 | | package_write | 軟體套件 | 寫入 | 刪除軟體套件版本(不可復原) | | list_issues | 問題 | 讀取 | 列出倉庫問題 | +| attachment_read | 問題 | 讀取 | 讀取問題/評論附件:列出中繼資料、取得中繼資料或下載內容 | | issue_read | 問題 | 讀取 | 讀取問題:詳情、評論或標籤 | | issue_write | 問題 | 寫入 | 寫入問題:創建、更新、管理評論和標籤 | | list_pull_requests | 拉取請求 | 讀取 | 列出倉庫拉取請求 | diff --git a/cmd/cmd.go b/cmd/cmd.go index 286b59d..ba70f32 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -4,7 +4,9 @@ import ( "context" "flag" "fmt" + "io" "os" + "strconv" "strings" "text/tabwriter" @@ -14,39 +16,56 @@ import ( ) var ( - host string - port int - token string - tools string - version bool + host string + port int + token string + tools string + version bool + maxInlineAttachmentBytes int + maxInlineAttachmentBytesFlagSet bool + osExit = os.Exit ) func init() { - flag.StringVar(&flagPkg.Mode, "t", "stdio", "") - flag.StringVar(&flagPkg.Mode, "transport", "stdio", "") - flag.StringVar(&host, "H", os.Getenv("GITEA_HOST"), "") - flag.StringVar(&host, "host", os.Getenv("GITEA_HOST"), "") - flag.IntVar(&port, "p", 8080, "") - flag.IntVar(&port, "port", 8080, "") - flag.StringVar(&token, "T", "", "") - flag.StringVar(&token, "token", "", "") - flag.BoolVar(&flagPkg.ReadOnly, "r", false, "") - flag.BoolVar(&flagPkg.ReadOnly, "read-only", false, "") - defaultTools := os.Getenv("GITEA_TOOLS") - flag.StringVar(&tools, "O", defaultTools, "") - flag.StringVar(&tools, "tools", defaultTools, "") - flag.BoolVar(&flagPkg.Debug, "d", false, "") - flag.BoolVar(&flagPkg.Debug, "debug", false, "") - flag.BoolVar(&flagPkg.Insecure, "k", false, "") - flag.BoolVar(&flagPkg.Insecure, "insecure", false, "") - flag.BoolVar(&version, "v", false, "") - flag.BoolVar(&version, "version", false, "") + initFlagSet(flag.CommandLine, os.Args[1:], os.Getenv, os.ReadFile, os.Stderr) +} - flag.Usage = func() { - w := tabwriter.NewWriter(os.Stderr, 0, 0, 3, ' ', 0) - fmt.Fprintln(os.Stderr, "Usage: gitea-mcp [options]") - fmt.Fprintln(os.Stderr) - fmt.Fprintln(os.Stderr, "Options:") +func initFlagSet(fs *flag.FlagSet, args []string, getenv func(string) string, readFile func(string) ([]byte, error), stderr io.Writer) { + fs.StringVar(&flagPkg.Mode, "t", "stdio", "") + fs.StringVar(&flagPkg.Mode, "transport", "stdio", "") + fs.StringVar(&host, "H", getenv("GITEA_HOST"), "") + fs.StringVar(&host, "host", getenv("GITEA_HOST"), "") + fs.IntVar(&port, "p", 8080, "") + fs.IntVar(&port, "port", 8080, "") + fs.StringVar(&token, "T", "", "") + fs.StringVar(&token, "token", "", "") + fs.BoolVar(&flagPkg.ReadOnly, "r", false, "") + fs.BoolVar(&flagPkg.ReadOnly, "read-only", false, "") + defaultTools := getenv("GITEA_TOOLS") + fs.StringVar(&tools, "O", defaultTools, "") + fs.StringVar(&tools, "tools", defaultTools, "") + fs.BoolVar(&flagPkg.Debug, "d", false, "") + fs.BoolVar(&flagPkg.Debug, "debug", false, "") + fs.BoolVar(&flagPkg.Insecure, "k", false, "") + fs.BoolVar(&flagPkg.Insecure, "insecure", false, "") + fs.BoolVar(&version, "v", false, "") + fs.BoolVar(&version, "version", false, "") + maxInlineAttachmentBytes = 5 * 1024 * 1024 + fs.Func("max-inline-attachment-bytes", "", func(val string) error { + parsed, err := strconv.Atoi(val) + if err != nil || parsed < 0 { + return fmt.Errorf("invalid value %q", val) + } + maxInlineAttachmentBytes = parsed + maxInlineAttachmentBytesFlagSet = true + return nil + }) + + fs.Usage = func() { + w := tabwriter.NewWriter(stderr, 0, 0, 3, ' ', 0) + fmt.Fprintln(stderr, "Usage: gitea-mcp [options]") + fmt.Fprintln(stderr) + fmt.Fprintln(stderr, "Options:") fmt.Fprintf(w, " -t, -transport \tTransport type: stdio or http (default: stdio)\n") fmt.Fprintf(w, " -H, -host \tGitea host URL (default: https://gitea.com)\n") fmt.Fprintf(w, " -p, -port \tHTTP server port (default: 8080)\n") @@ -55,6 +74,7 @@ func init() { fmt.Fprintf(w, " -O, -tools \tComma-separated list of tool names to expose\n") fmt.Fprintf(w, " -d, -debug\tEnable debug mode\n") fmt.Fprintf(w, " -k, -insecure\tIgnore TLS certificate errors\n") + fmt.Fprintf(w, " -max-inline-attachment-bytes \tInline image attachments up to this size (default: 5242880)\n") fmt.Fprintf(w, " -v, -version\tPrint version and exit\n") fmt.Fprintln(w) fmt.Fprintln(w, "Environment variables:") @@ -63,13 +83,14 @@ func init() { fmt.Fprintf(w, " GITEA_DEBUG\tSet to 'true' for debug mode\n") fmt.Fprintf(w, " GITEA_HOST\tOverride Gitea host URL\n") fmt.Fprintf(w, " GITEA_INSECURE\tSet to 'true' to ignore TLS errors\n") + fmt.Fprintf(w, " GITEA_MAX_INLINE_ATTACHMENT_BYTES\tOverride inline image attachment size limit in bytes\n") fmt.Fprintf(w, " GITEA_READONLY\tSet to 'true' for read-only mode\n") fmt.Fprintf(w, " GITEA_TOOLS\tComma-separated list of tool names to expose\n") fmt.Fprintf(w, " MCP_MODE\tOverride transport mode\n") - w.Flush() + _ = w.Flush() } - flag.Parse() + _ = fs.Parse(args) flagPkg.Host = host if flagPkg.Host == "" { @@ -77,27 +98,27 @@ func init() { } flagPkg.Port = port + flagPkg.MaxInlineAttachmentBytes = maxInlineAttachmentBytes flagPkg.Token = token if flagPkg.Token == "" { - flagPkg.Token = os.Getenv("GITEA_ACCESS_TOKEN") + flagPkg.Token = getenv("GITEA_ACCESS_TOKEN") } if flagPkg.Token == "" { - if tokenFile := os.Getenv("GITEA_ACCESS_TOKEN_FILE"); tokenFile != "" { - data, err := os.ReadFile(tokenFile) + if tokenFile := getenv("GITEA_ACCESS_TOKEN_FILE"); tokenFile != "" { + data, err := readFile(tokenFile) if err != nil { - fmt.Fprintf(os.Stderr, "error reading GITEA_ACCESS_TOKEN_FILE: %v\n", err) - os.Exit(1) + fmt.Fprintf(stderr, "error reading GITEA_ACCESS_TOKEN_FILE: %v\n", err) + osExit(1) } flagPkg.Token = strings.TrimRight(string(data), "\r\n") } } - if os.Getenv("MCP_MODE") != "" { - flagPkg.Mode = os.Getenv("MCP_MODE") + if getenv("MCP_MODE") != "" { + flagPkg.Mode = getenv("MCP_MODE") } - - if os.Getenv("GITEA_READONLY") == "true" { + if getenv("GITEA_READONLY") == "true" { flagPkg.ReadOnly = true } @@ -110,15 +131,22 @@ func init() { if len(allowed) > 0 { flagPkg.AllowedTools = allowed } - - if os.Getenv("GITEA_DEBUG") == "true" { + if getenv("GITEA_DEBUG") == "true" { flagPkg.Debug = true } - - // Set insecure mode based on environment variable - if os.Getenv("GITEA_INSECURE") == "true" { + if getenv("GITEA_INSECURE") == "true" { flagPkg.Insecure = true } + if !maxInlineAttachmentBytesFlagSet { + if val := getenv("GITEA_MAX_INLINE_ATTACHMENT_BYTES"); val != "" { + parsed, err := strconv.Atoi(val) + if err != nil || parsed < 0 { + fmt.Fprintf(stderr, "invalid GITEA_MAX_INLINE_ATTACHMENT_BYTES: %q\n", val) + osExit(1) + } + flagPkg.MaxInlineAttachmentBytes = parsed + } + } } func Execute() { @@ -126,12 +154,14 @@ func Execute() { fmt.Fprintln(os.Stdout, flagPkg.Version) return } - defer log.Default().Sync() //nolint:errcheck // best-effort flush if err := operation.Run(); err != nil { if err == context.Canceled { log.Info("Server shutdown due to context cancellation") + _ = log.Default().Sync() // best-effort flush return } - log.Fatalf("Run Gitea MCP Server Error: %v", err) //nolint:gocritic // intentional exit after defer + _ = log.Default().Sync() // best-effort flush + log.Fatalf("Run Gitea MCP Server Error: %v", err) } + _ = log.Default().Sync() // best-effort flush } diff --git a/operation/issue/attachment.go b/operation/issue/attachment.go new file mode 100644 index 0000000..b610158 --- /dev/null +++ b/operation/issue/attachment.go @@ -0,0 +1,311 @@ +package issue + +import ( + "bytes" + "context" + "encoding/base64" + "errors" + "fmt" + "io" + "mime" + "os" + "path/filepath" + "strings" + + "gitea.com/gitea/gitea-mcp/pkg/annotation" + "gitea.com/gitea/gitea-mcp/pkg/flag" + "gitea.com/gitea/gitea-mcp/pkg/gitea" + "gitea.com/gitea/gitea-mcp/pkg/params" + "gitea.com/gitea/gitea-mcp/pkg/to" + + gitea_sdk "gitea.dev/sdk" + "github.com/mark3labs/mcp-go/mcp" + "github.com/mark3labs/mcp-go/server" +) + +const AttachmentReadToolName = "attachment_read" + +var AttachmentReadTool = mcp.NewTool( + AttachmentReadToolName, + mcp.WithDescription("Read issue/comment attachments: list metadata, get metadata, or download content."), + mcp.WithToolAnnotation(annotation.ReadOnly("Read issue or comment attachments")), + mcp.WithString("method", mcp.Required(), mcp.Enum("list", "get", "download")), + mcp.WithString("owner", mcp.Required(), mcp.Description(params.OwnerDesc)), + mcp.WithString("repo", mcp.Required(), mcp.Description(params.RepoDesc)), + mcp.WithNumber("issue_number", mcp.Description("required for issue attachment list/get or issue-scoped metadata lookup")), + mcp.WithNumber("comment_id", mcp.Description("required for comment attachment list/get or comment-scoped metadata lookup")), + mcp.WithNumber("attachment_id", mcp.Description("required for get and for download when attachment_uuid is not provided")), + mcp.WithString("attachment_uuid", mcp.Description("attachment UUID for direct download path lookup")), + mcp.WithString("output_path", mcp.Description("write the attachment to this exact path")), +) + +func init() { + Tool.RegisterRead(server.ServerTool{Tool: AttachmentReadTool, Handler: attachmentReadFn}) +} + +func attachmentReadFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + method, err := params.GetString(req.GetArguments(), "method") + if err != nil { + return to.ErrorResult(err) + } + switch method { + case "list": + return listAttachmentsFn(ctx, req) + case "get": + return getAttachmentFn(ctx, req) + case "download": + return downloadAttachmentFn(ctx, req) + default: + return to.ErrorResult(fmt.Errorf("unknown method: %s", method)) + } +} + +func listAttachmentsFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + owner, repo, issueNumber, commentID, err := attachmentScopeArgs(req) + if err != nil { + return to.ErrorResult(err) + } + client, err := gitea.ClientFromContext(ctx) + if err != nil { + return to.ErrorResult(fmt.Errorf("get gitea client err: %v", err)) + } + var attachments []*gitea_sdk.Attachment + if issueNumber > 0 { + attachments, _, err = client.Issues.ListIssueAttachments(ctx, owner, repo, issueNumber) + } else { + attachments, _, err = client.Issues.ListIssueCommentAttachments(ctx, owner, repo, commentID) + } + if err != nil { + return to.ErrorResult(fmt.Errorf("list attachments err: %v", err)) + } + return to.TextResult(slimAttachments(attachments)) +} + +func getAttachmentFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + att, err := lookupAttachment(ctx, req) + if err != nil { + return to.ErrorResult(err) + } + return to.TextResult(slimAttachment(att)) +} + +func downloadAttachmentFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + owner, err := params.GetString(req.GetArguments(), "owner") + if err != nil { + return to.ErrorResult(err) + } + repo, err := params.GetString(req.GetArguments(), "repo") + if err != nil { + return to.ErrorResult(err) + } + explicitOutputPath := params.GetOptionalString(req.GetArguments(), "output_path", "") + attachmentUUID := strings.TrimSpace(params.GetOptionalString(req.GetArguments(), "attachment_uuid", "")) + + var att *gitea_sdk.Attachment + if attachmentUUID == "" { + att, err = lookupAttachment(ctx, req) + if err != nil { + return to.ErrorResult(err) + } + attachmentUUID = strings.TrimSpace(att.UUID) + } + if attachmentUUID == "" { + return to.ErrorResult(errors.New("attachment_uuid or attachment metadata with uuid is required")) + } + + name := attachmentUUID + if att != nil && strings.TrimSpace(att.Name) != "" { + name = strings.TrimSpace(att.Name) + } + + resp, err := gitea.OpenAttachment(ctx, "/attachments/"+attachmentUUID, "*/*") + if err != nil { + return to.ErrorResult(fmt.Errorf("download attachment err: %v", err)) + } + defer resp.Body.Close() + + mimeType := normalizeAttachmentContentType(resp.ContentType, name) + if explicitOutputPath == "" && shouldInlineAttachment(att, mimeType) { + limited, readErr := io.ReadAll(io.LimitReader(resp.Body, int64(flag.MaxInlineAttachmentBytes)+1)) + if readErr != nil { + return to.ErrorResult(fmt.Errorf("read attachment err: %v", readErr)) + } + if len(limited) <= flag.MaxInlineAttachmentBytes { + text := fmt.Sprintf("attachment %s (%s, %d bytes, %s)", name, attachmentUUID, len(limited), mimeType) + return mcp.NewToolResultImage(text, base64.StdEncoding.EncodeToString(limited), mimeType), nil + } + outputPath := defaultAttachmentPath(owner, repo, name, attachmentUUID) + if err := os.MkdirAll(filepath.Dir(outputPath), 0o700); err != nil { + return to.ErrorResult(fmt.Errorf("create output dir err: %v", err)) + } + reader := io.MultiReader(bytes.NewReader(limited), resp.Body) + written, err := gitea.WriteAttachment(reader, outputPath) + if err != nil { + return to.ErrorResult(fmt.Errorf("write attachment file err: %v", err)) + } + return attachmentFileResult(att, outputPath, written, name, attachmentUUID, mimeType) + } + + outputPath := explicitOutputPath + if outputPath == "" { + outputPath = defaultAttachmentPath(owner, repo, name, attachmentUUID) + } + if err := os.MkdirAll(filepath.Dir(outputPath), 0o700); err != nil { + return to.ErrorResult(fmt.Errorf("create output dir err: %v", err)) + } + written, err := gitea.WriteAttachment(resp.Body, outputPath) + if err != nil { + return to.ErrorResult(fmt.Errorf("write attachment file err: %v", err)) + } + return attachmentFileResult(att, outputPath, written, name, attachmentUUID, mimeType) +} + +func shouldInlineAttachment(att *gitea_sdk.Attachment, mimeType string) bool { + if !strings.HasPrefix(mimeType, "image/") || flag.MaxInlineAttachmentBytes <= 0 { + return false + } + if att == nil || att.Size <= 0 { + return true + } + return att.Size <= int64(flag.MaxInlineAttachmentBytes) +} + +func attachmentFileResult(att *gitea_sdk.Attachment, outputPath string, written int64, name, attachmentUUID, mimeType string) (*mcp.CallToolResult, error) { + res := map[string]any{ + "path": outputPath, + "bytes": written, + "name": name, + "uuid": attachmentUUID, + "mime_type": mimeType, + "content_type": mimeType, + } + if att != nil { + res["attachment_id"] = att.ID + } + return to.TextResult(res) +} + +func attachmentScopeArgs(req mcp.CallToolRequest) (owner, repo string, issueNumber, commentID int64, err error) { + owner, err = params.GetString(req.GetArguments(), "owner") + if err != nil { + return "", "", 0, 0, err + } + repo, err = params.GetString(req.GetArguments(), "repo") + if err != nil { + return "", "", 0, 0, err + } + issueNumber = params.GetOptionalInt(req.GetArguments(), "issue_number", 0) + commentID = params.GetOptionalInt(req.GetArguments(), "comment_id", 0) + if (issueNumber > 0) == (commentID > 0) { + return "", "", 0, 0, errors.New("exactly one of issue_number or comment_id is required") + } + return owner, repo, issueNumber, commentID, nil +} + +func lookupAttachment(ctx context.Context, req mcp.CallToolRequest) (*gitea_sdk.Attachment, error) { + owner, repo, issueNumber, commentID, err := attachmentScopeArgs(req) + if err != nil { + return nil, err + } + attachmentID := params.GetOptionalInt(req.GetArguments(), "attachment_id", 0) + if attachmentID <= 0 { + return nil, errors.New("attachment_id is required") + } + client, err := gitea.ClientFromContext(ctx) + if err != nil { + return nil, fmt.Errorf("get gitea client err: %v", err) + } + if issueNumber > 0 { + att, _, err := client.Issues.GetIssueAttachment(ctx, owner, repo, issueNumber, attachmentID) + if err != nil { + return nil, fmt.Errorf("get issue attachment err: %v", err) + } + return att, nil + } + att, _, err := client.Issues.GetIssueCommentAttachment(ctx, owner, repo, commentID, attachmentID) + if err != nil { + return nil, fmt.Errorf("get issue comment attachment err: %v", err) + } + return att, nil +} + +func slimAttachments(atts []*gitea_sdk.Attachment) []map[string]any { + out := make([]map[string]any, 0, len(atts)) + for _, att := range atts { + out = append(out, slimAttachment(att)) + } + return out +} + +func slimAttachment(att *gitea_sdk.Attachment) map[string]any { + if att == nil { + return nil + } + m := map[string]any{ + "id": att.ID, + "name": att.Name, + "uuid": att.UUID, + "size": att.Size, + "download_count": att.DownloadCount, + "created_at": att.Created, + "mime_type": inferAttachmentMimeType(att.Name), + } + if att.DownloadURL != "" { + m["browser_download_url"] = att.DownloadURL + } + return m +} + +func inferAttachmentMimeType(name string) string { + if ext := strings.ToLower(filepath.Ext(strings.TrimSpace(name))); ext != "" { + if mimeType := mime.TypeByExtension(ext); mimeType != "" { + return strings.Split(mimeType, ";")[0] + } + } + return "application/octet-stream" +} + +func normalizeAttachmentContentType(contentType, name string) string { + mediaType, _, err := mime.ParseMediaType(contentType) + if err == nil && mediaType != "" && mediaType != "application/octet-stream" { + return mediaType + } + return inferAttachmentMimeType(name) +} + +func defaultAttachmentPath(owner, repo, name, uuid string) string { + home, _ := os.UserHomeDir() + if home == "" { + home = os.TempDir() + } + filename := attachmentFilename(name, uuid) + ext := filepath.Ext(filename) + base := strings.TrimSuffix(filename, ext) + if uuid != "" { + filename = uuid + if base != "" && base != "attachment" { + filename = base + "-" + uuid + } + filename += ext + } + return filepath.Join(home, ".gitea-mcp", "attachments", safePathPart(owner), safePathPart(repo), filename) +} + +func attachmentFilename(name, uuid string) string { + name = strings.TrimSpace(name) + if name != "" && !strings.ContainsAny(name, `/\\`) && name != "." && name != ".." { + return name + } + if uuid != "" { + return uuid + ".bin" + } + return "attachment.bin" +} + +func safePathPart(name string) string { + name = strings.TrimSpace(name) + if name != "" && !strings.ContainsAny(name, `/\\`) && name != "." && name != ".." { + return name + } + return "unknown" +} diff --git a/operation/issue/attachment_test.go b/operation/issue/attachment_test.go new file mode 100644 index 0000000..5c143ce --- /dev/null +++ b/operation/issue/attachment_test.go @@ -0,0 +1,182 @@ +package issue + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "gitea.com/gitea/gitea-mcp/pkg/flag" + "gitea.com/gitea/gitea-mcp/pkg/gitea" + + "github.com/mark3labs/mcp-go/mcp" +) + +func TestAttachmentFilename(t *testing.T) { + tests := []struct { + name string + file string + uuid string + want string + }{ + {"uses attachment name", "screenshot.png", "abc", "screenshot.png"}, + {"falls back for traversal", "../etc/passwd", "abc", "abc.bin"}, + {"falls back for empty name", "", "abc", "abc.bin"}, + {"uses generic fallback", "", "", "attachment.bin"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := attachmentFilename(tt.file, tt.uuid); got != tt.want { + t.Fatalf("attachmentFilename() = %q, want %q", got, tt.want) + } + }) + } +} + +func TestInferAttachmentMimeType(t *testing.T) { + if got := inferAttachmentMimeType("shot.png"); got != "image/png" { + t.Fatalf("inferAttachmentMimeType() = %q, want image/png", got) + } + if got := inferAttachmentMimeType("archive.unknownext"); got != "application/octet-stream" { + t.Fatalf("inferAttachmentMimeType() = %q, want application/octet-stream", got) + } +} + +func TestDefaultAttachmentPath(t *testing.T) { + got := defaultAttachmentPath("octo", "demo", "shot.png", "uuid-1") + want := filepath.Join(".gitea-mcp", "attachments", "octo", "demo", "shot-uuid-1.png") + if !strings.HasSuffix(got, want) { + t.Fatalf("defaultAttachmentPath() = %q, want suffix %q", got, want) + } +} + +func TestAttachmentReadListIssueAttachments(t *testing.T) { + const owner = "octo" + const repo = "demo" + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/version": + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"version":"1.12.0"}`)) + case fmt.Sprintf("/api/v1/repos/%s/%s", owner, repo): + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"private":false}`)) + case fmt.Sprintf("/api/v1/repos/%s/%s/issues/42/assets", owner, repo): + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[{"id":1,"name":"shot.png","uuid":"uuid-1","size":10,"download_count":2}]`)) + default: + http.NotFound(w, r) + } + }) + server := httptest.NewServer(handler) + defer server.Close() + origHost, origToken, origVersion := flag.Host, flag.Token, flag.Version + flag.Host, flag.Token, flag.Version = server.URL, "", "test" + defer func() { flag.Host, flag.Token, flag.Version = origHost, origToken, origVersion }() + + res, err := attachmentReadFn(context.Background(), mcp.CallToolRequest{Params: mcp.CallToolParams{Arguments: map[string]any{ + "method": "list", "owner": owner, "repo": repo, "issue_number": float64(42), + }}}) + if err != nil { + t.Fatalf("attachmentReadFn() error = %v", err) + } + body := res.Content[0].(mcp.TextContent).Text + if !strings.Contains(body, `"mime_type":"image/png"`) || !strings.Contains(body, `"uuid":"uuid-1"`) { + t.Fatalf("unexpected body: %s", body) + } +} + +func TestDownloadAttachmentRejectsRedirectLoopAtHopLimit(t *testing.T) { + var serverURL string + redirects := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/attachments/uuid-1" { + t.Fatalf("path = %s", r.URL.Path) + } + redirects++ + http.Redirect(w, r, serverURL+"/attachments/uuid-1", http.StatusFound) + })) + defer server.Close() + serverURL = server.URL + + origHost := flag.Host + flag.Host = server.URL + defer func() { flag.Host = origHost }() + + _, _, _, err := gitea.DownloadAttachment(context.Background(), "/attachments/uuid-1", "*/*") + if err == nil { + t.Fatal("expected redirect limit error") + } + if !strings.Contains(err.Error(), "stopped after 10 redirects") { + t.Fatalf("unexpected error: %v", err) + } + if redirects != 10 { + t.Fatalf("redirects = %d, want 10", redirects) + } +} + +func TestAttachmentReadDownloadSavesLargeAttachmentToDefaultFile(t *testing.T) { + const owner = "octo" + const repo = "demo" + const uuid = "uuid-1" + const name = "large.bin" + payload := strings.Repeat("a", 32) + + home := t.TempDir() + t.Setenv("HOME", home) + + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/version": + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"version":"1.12.0"}`)) + case fmt.Sprintf("/api/v1/repos/%s/%s", owner, repo): + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"private":false}`)) + case fmt.Sprintf("/api/v1/repos/%s/%s/issues/42/assets/1", owner, repo): + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"id": 1, "name": name, "uuid": uuid, "size": len(payload)}) + case "/attachments/" + uuid: + w.Header().Set("Content-Type", "application/octet-stream") + _, _ = w.Write([]byte(payload)) + default: + http.NotFound(w, r) + } + }) + server := httptest.NewServer(handler) + defer server.Close() + + origHost, origToken, origVersion, origInline := flag.Host, flag.Token, flag.Version, flag.MaxInlineAttachmentBytes + flag.Host, flag.Token, flag.Version = server.URL, "", "test" + flag.MaxInlineAttachmentBytes = 8 + defer func() { + flag.Host, flag.Token, flag.Version, flag.MaxInlineAttachmentBytes = origHost, origToken, origVersion, origInline + }() + + res, err := attachmentReadFn(context.Background(), mcp.CallToolRequest{Params: mcp.CallToolParams{Arguments: map[string]any{ + "method": "download", "owner": owner, "repo": repo, "issue_number": float64(42), "attachment_id": float64(1), + }}}) + if err != nil { + t.Fatalf("attachmentReadFn() error = %v", err) + } + body := res.Content[0].(mcp.TextContent).Text + wantPath := filepath.Join(home, ".gitea-mcp", "attachments", owner, repo, "large-uuid-1.bin") + if !strings.Contains(body, wantPath) { + t.Fatalf("result missing path %q: %s", wantPath, body) + } + data, err := os.ReadFile(wantPath) + if err != nil { + t.Fatalf("ReadFile(%q): %v", wantPath, err) + } + if string(data) != payload { + t.Fatalf("saved payload mismatch") + } + if !strings.Contains(body, `"bytes":32`) { + t.Fatalf("result missing bytes: %s", body) + } +} diff --git a/pkg/flag/flag.go b/pkg/flag/flag.go index 9e537c4..fe796a3 100644 --- a/pkg/flag/flag.go +++ b/pkg/flag/flag.go @@ -7,6 +7,8 @@ var ( Version string Mode string + MaxInlineAttachmentBytes int + Insecure bool ReadOnly bool Debug bool diff --git a/pkg/gitea/attachment_test.go b/pkg/gitea/attachment_test.go new file mode 100644 index 0000000..2685e4d --- /dev/null +++ b/pkg/gitea/attachment_test.go @@ -0,0 +1,208 @@ +package gitea + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + + "gitea.com/gitea/gitea-mcp/pkg/flag" +) + +func TestBuildAttachmentURLRejectsExternalURL(t *testing.T) { + origHost := flag.Host + flag.Host = "https://example.com" + defer func() { flag.Host = origHost }() + + if _, err := buildAttachmentURL("https://evil.example.com/attachments/1"); err == nil { + t.Fatal("expected error for full URL attachment path") + } +} + +func TestBuildAttachmentURLPreservesHostPathPrefix(t *testing.T) { + origHost := flag.Host + flag.Host = "https://example.com/gitea" + defer func() { flag.Host = origHost }() + + got, err := buildAttachmentURL("/attachments/uuid-1") + if err != nil { + t.Fatalf("buildAttachmentURL() error = %v", err) + } + if got != "https://example.com/gitea/attachments/uuid-1" { + t.Fatalf("buildAttachmentURL() = %q", got) + } +} + +func TestDownloadAttachmentUsesTokenAndReturnsContentType(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/attachments/uuid-1" { + t.Fatalf("path = %s", r.URL.Path) + } + if got := r.Header.Get("Authorization"); got != "token secret-token" { + t.Fatalf("Authorization = %q", got) + } + if got := r.Header.Get("Accept"); got != "*/*" { + t.Fatalf("Accept = %q", got) + } + w.Header().Set("Content-Type", "image/png") + _, _ = w.Write([]byte("png-bytes")) + })) + defer server.Close() + + origHost, origToken := flag.Host, flag.Token + flag.Host, flag.Token = server.URL, "secret-token" + defer func() { flag.Host, flag.Token = origHost, origToken }() + + raw, contentType, status, err := DownloadAttachment(context.Background(), "/attachments/uuid-1", "*/*") + if err != nil { + t.Fatalf("DownloadAttachment() error = %v", err) + } + if status != http.StatusOK { + t.Fatalf("DownloadAttachment() status = %d, want %d", status, http.StatusOK) + } + if contentType != "image/png" { + t.Fatalf("contentType = %q", contentType) + } + if string(raw) != "png-bytes" { + t.Fatalf("body = %q", string(raw)) + } +} + +func TestDownloadAttachmentRejectsCrossOriginRedirect(t *testing.T) { + redirected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Fatalf("cross-origin redirect should not be followed: %s", r.URL.String()) + })) + defer redirected.Close() + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, redirected.URL+"/attachments/uuid-1", http.StatusFound) + })) + defer server.Close() + + origHost, origToken := flag.Host, flag.Token + flag.Host, flag.Token = server.URL, "secret-token" + defer func() { flag.Host, flag.Token = origHost, origToken }() + + _, _, _, err := DownloadAttachment(context.Background(), "/attachments/uuid-1", "*/*") + if err == nil { + t.Fatal("expected error for cross-origin redirect") + } + want := "do request: Get \"" + redirected.URL + "/attachments/uuid-1\": attachment redirect changed origin" + if err.Error() != want { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestDownloadAttachmentRejectsSameOriginRedirectLoopAtHopLimit(t *testing.T) { + var serverURL string + redirects := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + redirects++ + http.Redirect(w, r, serverURL+"/attachments/uuid-1", http.StatusFound) + })) + defer server.Close() + serverURL = server.URL + + origHost := flag.Host + flag.Host = server.URL + defer func() { flag.Host = origHost }() + + _, _, _, err := DownloadAttachment(context.Background(), "/attachments/uuid-1", "*/*") + if err == nil { + t.Fatal("expected redirect limit error") + } + if !strings.Contains(err.Error(), "stopped after 10 redirects") { + t.Fatalf("unexpected error: %v", err) + } + if redirects != 10 { + t.Fatalf("redirects = %d, want 10", redirects) + } +} + +func TestWriteAttachmentStreamsBodyToFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "attachment.bin") + written, err := WriteAttachment(strings.NewReader(strings.Repeat("z", 64)), path) + if err != nil { + t.Fatalf("WriteAttachment() error = %v", err) + } + if written != 64 { + t.Fatalf("written = %d, want 64", written) + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("ReadFile() error = %v", err) + } + if string(data) != strings.Repeat("z", 64) { + t.Fatalf("body mismatch") + } +} + +func TestWriteAttachmentCreatesPrivateFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "attachment.bin") + + if _, err := WriteAttachment(strings.NewReader("secret"), path); err != nil { + t.Fatalf("WriteAttachment() error = %v", err) + } + + info, err := os.Stat(path) + if err != nil { + t.Fatalf("Stat() error = %v", err) + } + if got := info.Mode().Perm() & 0o077; got != 0 { + t.Fatalf("permissions = %03o, want no group/other bits", info.Mode().Perm()) + } +} + +func TestWriteAttachmentTightensExistingFilePermissions(t *testing.T) { + path := filepath.Join(t.TempDir(), "attachment.bin") + if err := os.WriteFile(path, []byte("public"), 0o644); err != nil { + t.Fatalf("WriteFile() error = %v", err) + } + + if _, err := WriteAttachment(strings.NewReader("secret"), path); err != nil { + t.Fatalf("WriteAttachment() error = %v", err) + } + + info, err := os.Stat(path) + if err != nil { + t.Fatalf("Stat() error = %v", err) + } + if got := info.Mode().Perm(); got != 0o600 { + t.Fatalf("permissions = %03o, want 600", got) + } +} + +func TestDownloadAttachmentErrorsOnNon2xx(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "nope", http.StatusForbidden) + })) + defer server.Close() + + origHost := flag.Host + flag.Host = server.URL + defer func() { flag.Host = origHost }() + + _, _, status, err := DownloadAttachment(context.Background(), "/attachments/uuid-1", "*/*") + if status != http.StatusForbidden { + t.Fatalf("status = %d, want %d", status, http.StatusForbidden) + } + var httpErr *HTTPError + if !errors.As(err, &httpErr) { + t.Fatalf("expected HTTPError, got %T", err) + } +} + +func TestAttachmentHTTPClientHasNoTotalTimeout(t *testing.T) { + origin := &url.URL{Scheme: "https", Host: "example.com"} + + client := attachmentHTTPClient(origin) + + if client.Timeout != 0 { + t.Fatalf("Timeout = %v, want 0", client.Timeout) + } +} diff --git a/pkg/gitea/rest.go b/pkg/gitea/rest.go index ba745da..76fe1ad 100644 --- a/pkg/gitea/rest.go +++ b/pkg/gitea/rest.go @@ -9,6 +9,8 @@ import ( "io" "net/http" "net/url" + "os" + "path" "strings" "sync" "time" @@ -34,6 +36,12 @@ func (e *HTTPError) Error() string { return fmt.Sprintf("request failed with status %d: %s", e.StatusCode, e.Body) } +type AttachmentResponse struct { + Body io.ReadCloser + ContentType string + StatusCode int +} + func tokenFromContext(ctx context.Context) string { if ctx != nil { if token, ok := ctx.Value(mcpContext.TokenContextKey).(string); ok && token != "" { @@ -75,6 +83,40 @@ func buildAPIURL(path string, query url.Values) (string, error) { return u.String(), nil } +func buildAttachmentURL(attachmentPath string) (string, error) { + host := strings.TrimRight(flag.Host, "/") + if host == "" { + return "", errors.New("gitea host is empty") + } + baseURL, err := url.Parse(host) + if err != nil { + return "", err + } + if attachmentPath == "" { + return "", errors.New("attachment path is empty") + } + if strings.Contains(attachmentPath, "://") { + return "", errors.New("attachment path must not be a URL") + } + if !strings.HasPrefix(attachmentPath, "/attachments/") { + return "", errors.New("attachment path must start with /attachments/") + } + cleanPath := path.Clean(attachmentPath) + if !strings.HasPrefix(cleanPath, "/attachments/") { + return "", errors.New("attachment path must stay within /attachments/") + } + if cleanPath == "/attachments" || cleanPath == "/attachments/" { + return "", errors.New("attachment uuid is required") + } + joinedPath := strings.TrimRight(baseURL.Path, "/") + cleanPath + if joinedPath == "" { + joinedPath = cleanPath + } + baseURL.Path = joinedPath + baseURL.RawPath = joinedPath + return baseURL.String(), nil +} + // DoJSON performs an API request and decodes a JSON response into respOut (if non-nil). // It returns the HTTP status code. func DoJSON(ctx context.Context, method, path string, query url.Values, body, respOut any) (int, error) { @@ -91,45 +133,142 @@ func DoJSON(ctx context.Context, method, path string, query url.Values, body, re if err != nil { return 0, err } + req, err := http.NewRequestWithContext(ctx, method, u, bodyReader) if err != nil { return 0, fmt.Errorf("create request: %w", err) } - token := tokenFromContext(ctx) if token != "" { req.Header.Set("Authorization", "token "+token) } - req.Header.Set("Accept", "application/json") if body != nil { req.Header.Set("Content-Type", "application/json") } + if respOut != nil { + req.Header.Set("Accept", "application/json") + } - client := restHTTPClient() - resp, err := client.Do(req) + resp, err := restHTTPClient().Do(req) if err != nil { return 0, fmt.Errorf("do request: %w", err) } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { - bodySnippet, _ := io.ReadAll(io.LimitReader(resp.Body, errBodySnippetSize)) + bodySnippet, err := io.ReadAll(io.LimitReader(resp.Body, errBodySnippetSize+1)) + if err != nil { + return resp.StatusCode, fmt.Errorf("read response: %w", err) + } + if len(bodySnippet) > errBodySnippetSize { + bodySnippet = bodySnippet[:errBodySnippetSize] + } return resp.StatusCode, &HTTPError{StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(bodySnippet))} } if respOut == nil { - _, _ = io.Copy(io.Discard, resp.Body) // best-effort + _, _ = io.Copy(io.Discard, resp.Body) return resp.StatusCode, nil } if err := json.NewDecoder(resp.Body).Decode(respOut); err != nil { return resp.StatusCode, fmt.Errorf("decode response: %w", err) } + return resp.StatusCode, nil } +func attachmentHTTPClient(origin *url.URL) *http.Client { + return &http.Client{ + Transport: sharedTransport(), + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if err := checkRedirect(req, via); err != nil { + return err + } + if req.URL.Scheme != origin.Scheme || req.URL.Host != origin.Host { + return errors.New("attachment redirect changed origin") + } + return nil + }, + } +} + +func OpenAttachment(ctx context.Context, attachmentPath, accept string) (*AttachmentResponse, error) { + u, err := buildAttachmentURL(attachmentPath) + if err != nil { + return nil, err + } + origin, err := url.Parse(u) + if err != nil { + return nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) + if err != nil { + return nil, fmt.Errorf("create request: %w", err) + } + token := tokenFromContext(ctx) + if token != "" { + req.Header.Set("Authorization", "token "+token) + } + if accept != "" { + req.Header.Set("Accept", accept) + } + + resp, err := attachmentHTTPClient(origin).Do(req) + if err != nil { + return nil, fmt.Errorf("do request: %w", err) + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + defer resp.Body.Close() + bodySnippet, readErr := io.ReadAll(io.LimitReader(resp.Body, errBodySnippetSize+1)) + if readErr != nil { + return nil, fmt.Errorf("read response: %w", readErr) + } + if len(bodySnippet) > errBodySnippetSize { + bodySnippet = bodySnippet[:errBodySnippetSize] + } + return nil, &HTTPError{StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(bodySnippet))} + } + return &AttachmentResponse{Body: resp.Body, ContentType: resp.Header.Get("Content-Type"), StatusCode: resp.StatusCode}, nil +} + +// DownloadAttachment downloads attachment bytes from a same-host attachment path. +func DownloadAttachment(ctx context.Context, attachmentPath, accept string) ([]byte, string, int, error) { + resp, err := OpenAttachment(ctx, attachmentPath, accept) + if err != nil { + var httpErr *HTTPError + if errors.As(err, &httpErr) { + return nil, "", httpErr.StatusCode, err + } + return nil, "", 0, err + } + defer resp.Body.Close() + + respBytes, err := io.ReadAll(resp.Body) + if err != nil { + return nil, "", resp.StatusCode, fmt.Errorf("read response: %w", err) + } + return respBytes, resp.ContentType, resp.StatusCode, nil +} + +func WriteAttachment(body io.Reader, outputPath string) (int64, error) { + file, err := os.OpenFile(outputPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) + if err != nil { + return 0, err + } + defer file.Close() + if err := file.Chmod(0o600); err != nil { + return 0, err + } + + written, err := io.Copy(file, body) + if err != nil { + return written, err + } + return written, file.Close() +} + // DoBytes performs an API request and returns the raw response bytes. -// It returns the HTTP status code. func DoBytes(ctx context.Context, method, path string, query url.Values, body any, accept string) ([]byte, int, error) { var bodyReader io.Reader if body != nil { @@ -144,24 +283,23 @@ func DoBytes(ctx context.Context, method, path string, query url.Values, body an if err != nil { return nil, 0, err } + req, err := http.NewRequestWithContext(ctx, method, u, bodyReader) if err != nil { return nil, 0, fmt.Errorf("create request: %w", err) } - token := tokenFromContext(ctx) if token != "" { req.Header.Set("Authorization", "token "+token) } - if accept != "" { - req.Header.Set("Accept", accept) - } if body != nil { req.Header.Set("Content-Type", "application/json") } + if accept != "" { + req.Header.Set("Accept", accept) + } - client := restHTTPClient() - resp, err := client.Do(req) + resp, err := restHTTPClient().Do(req) if err != nil { return nil, 0, fmt.Errorf("do request: %w", err) } @@ -171,7 +309,6 @@ func DoBytes(ctx context.Context, method, path string, query url.Values, body an if err != nil { return nil, resp.StatusCode, fmt.Errorf("read response: %w", err) } - if resp.StatusCode < 200 || resp.StatusCode >= 300 { bodySnippet := respBytes if len(bodySnippet) > errBodySnippetSize { @@ -179,6 +316,5 @@ func DoBytes(ctx context.Context, method, path string, query url.Values, body an } return nil, resp.StatusCode, &HTTPError{StatusCode: resp.StatusCode, Body: strings.TrimSpace(string(bodySnippet))} } - return respBytes, resp.StatusCode, nil } diff --git a/pkg/gitea/rest_test.go b/pkg/gitea/rest_test.go index 4d3d841..2d89e46 100644 --- a/pkg/gitea/rest_test.go +++ b/pkg/gitea/rest_test.go @@ -2,6 +2,11 @@ package gitea import ( "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" "testing" mcpContext "gitea.com/gitea/gitea-mcp/pkg/context" @@ -28,3 +33,32 @@ func TestTokenFromContext(t *testing.T) { } }) } + +func TestDoJSON_LimitsErrorResponseBody(t *testing.T) { + payload := strings.Repeat("x", errBodySnippetSize+100) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, payload) + })) + defer srv.Close() + + origHost := flag.Host + defer func() { flag.Host = origHost }() + flag.Host = srv.URL + + status, err := DoJSON(context.Background(), http.MethodGet, "repos/owner/repo", nil, nil, nil) + if err == nil { + t.Fatal("expected error") + } + if status != http.StatusBadRequest { + t.Fatalf("expected status %d, got %d", http.StatusBadRequest, status) + } + + var httpErr *HTTPError + if !errors.As(err, &httpErr) { + t.Fatalf("expected HTTPError, got %T", err) + } + if len(httpErr.Body) != errBodySnippetSize { + t.Fatalf("expected body length %d, got %d", errBodySnippetSize, len(httpErr.Body)) + } +}