From 674d55d8cadb71ab82f537da0f8115200d9d0dbc Mon Sep 17 00:00:00 2001 From: shhhhhhjokerist <104197119+shhhhhhjokerist@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:16:36 +0800 Subject: [PATCH] fix: reject directory paths and stale shas in delete_file The delete_file tool builds a tree entry with SHA=nil, so the commit deletes a whole subtree when the path is a directory, and there is no precondition: a stale read of the file cannot be detected. The REST contents DELETE is not an option here because it does not sign the resulting commit; the Git Data API is what gives delete_file verified commits, so the guard belongs in the handler. Look up the path before mutating the tree and reject: - directory paths, which would otherwise delete every file below them; - paths that are missing on the branch, which currently succeed and produce an empty commit; - an optional sha argument that no longer matches the blob on the branch, so callers can turn "delete whatever is there" into "delete only if the file is still the one I read". --- README.md | 3 +- pkg/github/__toolsnaps__/delete_file.snap | 6 +- pkg/github/repositories.go | 40 +++++- pkg/github/repositories_test.go | 165 +++++++++++++++++++++- pkg/github/repository_tool_types.go | 3 + 5 files changed, 213 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 432541f434..4cac81a12b 100644 --- a/README.md +++ b/README.md @@ -1413,8 +1413,9 @@ For negotiated supported protocol versions `2026-07-28` or newer, the consolidat - `branch`: Branch to delete the file from (string, required) - `message`: Commit message (string, required) - `owner`: Repository owner (username or organization) (string, required) - - `path`: Path to the file to delete (string, required) + - `path`: Path to the file to delete. A directory path is rejected; pass a single file path. (string, required) - `repo`: Repository name (string, required) + - `sha`: Blob SHA of the file, as returned by get_file_contents. When set, the delete is rejected if another writer changed the file since it was read. Omit to delete whatever is at the path. (string, optional) - **delete_repository** - Delete repository - **OAuth Challenge Scopes**: `delete_repo`, `repo` diff --git a/pkg/github/__toolsnaps__/delete_file.snap b/pkg/github/__toolsnaps__/delete_file.snap index 6240de7f04..3c9df4a84c 100644 --- a/pkg/github/__toolsnaps__/delete_file.snap +++ b/pkg/github/__toolsnaps__/delete_file.snap @@ -34,13 +34,17 @@ "x-mcp-header": "owner" }, "path": { - "description": "Path to the file to delete", + "description": "Path to the file to delete. A directory path is rejected; pass a single file path.", "type": "string" }, "repo": { "description": "Repository name", "type": "string", "x-mcp-header": "repo" + }, + "sha": { + "description": "Blob SHA of the file, as returned by get_file_contents. When set, the delete is rejected if another writer changed the file since it was read. Omit to delete whatever is at the path.", + "type": "string" } }, "required": [ diff --git a/pkg/github/repositories.go b/pkg/github/repositories.go index b884f4888d..9c859894a7 100644 --- a/pkg/github/repositories.go +++ b/pkg/github/repositories.go @@ -1355,7 +1355,7 @@ func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool { }, "path": { Type: "string", - Description: "Path to the file to delete", + Description: "Path to the file to delete. A directory path is rejected; pass a single file path.", }, "message": { Type: "string", @@ -1365,6 +1365,10 @@ func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool { Type: "string", Description: "Branch to delete the file from", }, + "sha": { + Type: "string", + Description: "Blob SHA of the file, as returned by get_file_contents. When set, the delete is rejected if another writer changed the file since it was read. Omit to delete whatever is at the path.", + }, }, Required: []string{"owner", "repo", "path", "message", "branch"}, }, @@ -1427,6 +1431,40 @@ func DeleteFile(t translations.TranslationHelperFunc) inventory.ServerTool { return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get commit", resp, body), nil, nil } + // Look up what is actually at the path before deleting it. The tree + // entry below deletes a whole subtree when the path is a directory, and + // carries no precondition, so this is the only place to notice that the + // requested blob is missing or that the caller holds a stale sha. + // + // Pin the lookup to the commit the tree is built from: a branch can be + // rewound between this read and the tree creation, and then the check + // would validate a different tree than the deletion modifies. + fileContent, dirContent, contentsResp, err := client.Repositories.GetContents(ctx, owner, repo, path, &github.RepositoryContentGetOptions{Ref: baseCommit.GetSHA()}) + if err != nil { + return ghErrors.NewGitHubAPIErrorResponse(ctx, + fmt.Sprintf("failed to get contents of %s on branch %s", path, branch), + contentsResp, + err, + ), nil, nil + } + // Close this response independently: the defers above capture resp, + // and a transport failure here can leave contentsResp nil. + if contentsResp != nil { + defer func() { _ = contentsResp.Body.Close() }() + } + if dirContent != nil { + return utils.NewToolResultError(fmt.Sprintf("path %q is a directory; delete_file only removes a single file", path)), nil, nil + } + if fileContent == nil { + return utils.NewToolResultError(fmt.Sprintf("path %q was not found on branch %s", path, branch)), nil, nil + } + if input.Sha != "" && fileContent.GetSHA() != input.Sha { + return utils.NewToolResultError(fmt.Sprintf( + "sha mismatch for %s: requested %s but the file is at %s; re-read the file and retry", + path, input.Sha, fileContent.GetSHA(), + )), nil, nil + } + // Create a tree entry for the file deletion by setting SHA to nil treeEntries := []*github.TreeEntry{ { diff --git a/pkg/github/repositories_test.go b/pkg/github/repositories_test.go index 9b40c932ff..91a415d1d0 100644 --- a/pkg/github/repositories_test.go +++ b/pkg/github/repositories_test.go @@ -4299,7 +4299,8 @@ func Test_DeleteFile(t *testing.T) { assert.Contains(t, schema.Properties, "path") assert.Contains(t, schema.Properties, "message") assert.Contains(t, schema.Properties, "branch") - // SHA is no longer required since we're using Git Data API + // sha is an optional precondition; the call still works without it + assert.Contains(t, schema.Properties, "sha") assert.ElementsMatch(t, schema.Required, []string{"owner", "repo", "path", "message", "branch"}) // Setup mock objects for Git Data API @@ -4348,6 +4349,15 @@ func Test_DeleteFile(t *testing.T) { GetReposGitCommitsByOwnerByRepoByCommitSHA, mockCommit, ), + // Get contents of the path being deleted + WithRequestMatch( + contentsRoute, + &github.RepositoryContent{ + Type: new("file"), + Path: new("docs/example.md"), + SHA: new("blob123"), + }, + ), // Create tree WithRequestMatchHandler( PostReposGitTreesByOwnerByRepo, @@ -4467,6 +4477,159 @@ func Test_DeleteFile(t *testing.T) { } } +// contentsRoute matches the contents endpoint for paths with slashes; the plain +// {path} placeholder only matches a single URL segment. +const contentsRoute EndpointPattern = "GET /repos/{owner}/{repo}/contents/{path:.*}" + +func Test_DeleteFile_Precondition(t *testing.T) { + serverTool := DeleteFile(translations.NullTranslationHelper) + + mockRef := &github.Reference{ + Ref: new("refs/heads/main"), + Object: &github.GitObject{SHA: new("abc123")}, + } + mockCommit := &github.Commit{ + SHA: new("abc123"), + Tree: &github.Tree{SHA: new("def456")}, + } + + tests := []struct { + name string + contents any + status int + args map[string]any + expectedText string + }{ + { + name: "rejects a stale sha", + contents: &github.RepositoryContent{ + Type: new("file"), + Path: new("docs/example.md"), + SHA: new("blob-current"), + }, + status: http.StatusOK, + args: map[string]any{"owner": "owner", "repo": "repo", "path": "docs/example.md", "message": "Delete", "branch": "main", "sha": "blob-stale"}, + expectedText: "sha mismatch", + }, + { + name: "rejects a directory path", + contents: []*github.RepositoryContent{ + {Type: new("file"), Path: new("docs"), SHA: new("blob-a")}, + {Type: new("file"), Path: new("docs/sub"), SHA: new("blob-b")}, + }, + status: http.StatusOK, + args: map[string]any{"owner": "owner", "repo": "repo", "path": "docs", "message": "Delete", "branch": "main"}, + expectedText: "is a directory", + }, + { + name: "reports a missing path instead of committing nothing", + contents: map[string]string{"message": "Not Found"}, + status: http.StatusNotFound, + args: map[string]any{"owner": "owner", "repo": "repo", "path": "docs/gone.md", "message": "Delete", "branch": "main"}, + expectedText: "failed to get contents", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + client := mustNewGHClient(t, NewMockedHTTPClient( + WithRequestMatch(GetReposGitRefByOwnerByRepoByRef, mockRef), + WithRequestMatch(GetReposGitCommitsByOwnerByRepoByCommitSHA, mockCommit), + WithRequestMatchHandler(contentsRoute, + mockResponse(t, tc.status, tc.contents), + ), + )) + deps := BaseDeps{Client: client} + handler := serverTool.Handler(deps) + request := createMCPRequest(tc.args) + + result, err := handler(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + require.NotNil(t, result) + require.True(t, result.IsError) + assert.Contains(t, getTextResult(t, result).Text, tc.expectedText) + }) + } +} + +func Test_DeleteFile_AcceptsMatchingSha(t *testing.T) { + serverTool := DeleteFile(translations.NullTranslationHelper) + + mockRef := &github.Reference{ + Ref: new("refs/heads/main"), + Object: &github.GitObject{SHA: new("abc123")}, + } + mockCommit := &github.Commit{ + SHA: new("abc123"), + Tree: &github.Tree{SHA: new("def456")}, + } + mockTree := &github.Tree{SHA: new("ghi789")} + mockNewCommit := &github.Commit{ + SHA: new("jkl012"), + Message: new("Delete example file"), + HTMLURL: new("https://github.com/owner/repo/commit/jkl012"), + } + + client := mustNewGHClient(t, NewMockedHTTPClient( + WithRequestMatch(GetReposGitRefByOwnerByRepoByRef, mockRef), + WithRequestMatch(GetReposGitCommitsByOwnerByRepoByCommitSHA, mockCommit), + WithRequestMatch(contentsRoute, &github.RepositoryContent{ + Type: new("file"), + Path: new("docs/example.md"), + SHA: new("blob123"), + }), + WithRequestMatchHandler(PostReposGitTreesByOwnerByRepo, + expectRequestBody(t, map[string]any{ + "base_tree": "def456", + "tree": []any{ + map[string]any{ + "path": "docs/example.md", + "mode": "100644", + "type": "blob", + "sha": nil, + }, + }, + }).andThen(mockResponse(t, http.StatusCreated, mockTree)), + ), + WithRequestMatchHandler(PostReposGitCommitsByOwnerByRepo, + expectRequestBody(t, map[string]any{ + "message": "Delete example file", + "tree": "ghi789", + "parents": []any{"abc123"}, + }).andThen(mockResponse(t, http.StatusCreated, mockNewCommit)), + ), + WithRequestMatchHandler(PatchReposGitRefsByOwnerByRepoByRef, + expectRequestBody(t, map[string]any{ + "sha": "jkl012", + "force": false, + }).andThen(mockResponse(t, http.StatusOK, &github.Reference{ + Ref: new("refs/heads/main"), + Object: &github.GitObject{SHA: new("jkl012")}, + })), + ), + )) + + deps := BaseDeps{Client: client} + handler := serverTool.Handler(deps) + request := createMCPRequest(map[string]any{ + "owner": "owner", + "repo": "repo", + "path": "docs/example.md", + "message": "Delete example file", + "branch": "main", + "sha": "blob123", + }) + + result, err := handler(ContextWithDeps(context.Background(), deps), &request) + require.NoError(t, err) + require.False(t, result.IsError) + var response map[string]any + require.NoError(t, json.Unmarshal([]byte(getTextResult(t, result).Text), &response)) + commit, ok := response["commit"].(map[string]any) + require.True(t, ok) + assert.Equal(t, "jkl012", commit["sha"]) +} + func Test_ListTags(t *testing.T) { // Verify tool definition once serverTool := ListTags(translations.NullTranslationHelper) diff --git a/pkg/github/repository_tool_types.go b/pkg/github/repository_tool_types.go index 4f3b584983..43a6f89721 100644 --- a/pkg/github/repository_tool_types.go +++ b/pkg/github/repository_tool_types.go @@ -57,6 +57,9 @@ type DeleteFileInput struct { Path string `json:"path"` Message string `json:"message"` Branch string `json:"branch"` + // Sha, when set, is the blob SHA the caller expects; the delete is rejected + // if the file has changed since it was read. + Sha string `json:"sha,omitempty"` } type CreateBranchInput struct {