Compare commits

..
2 Commits
Author SHA1 Message Date
mathiasandClaude Opus 4.8 64176fe6d7 fix(repo_mirror_push): resolve mirror credential from server env, not the payload (#49)
CD / Deploy via GitOps (push) Has been skipped
CD / Lint / Test / Vet (push) Successful in 7s
CD / Build & Import (push) Successful in 21s
The mirror credential no longer has to ride the tool-call payload (which is
persisted to transcript → claudewatcher → brain → gitea history). Adds
remote_password_env: the name of a server-side env var the tool resolves at call
time, so the secret stays in the server process. An env name that resolves to
empty errors loudly rather than silently sending an empty password. Raw
remote_password still works but the schema/description now mark it DISCOURAGED.

Tests: password resolved from the env var (never in output); unset env var →
ErrValidation.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 09:00:07 +02:00
mathiasandClaude Opus 4.8 6d344c74a8 feat(tbd_ship): idempotent re-invoke — resume existing branch/PR (#48)
CD / Lint / Test / Vet (push) Successful in 7s
CD / Build & Import (push) Successful in 22s
CD / Deploy via GitOps (push) Has been skipped
A second tbd_ship for the same change no longer errors on "branch exists":
CreateBranch conflict is tolerated, and if a PR is already open for the head,
CreatePullRequest's conflict/validation error resolves it via ListPullRequests
(matching head.ref). Identical file content on the branch skips the write, so a
resume produces no redundant empty-diff commit. Then the same CI gate runs and
merges if now green — so "poll or re-invoke" (the #40 UX) actually works.

Test: TestTBDShip_Resume_ExistingBranchAndPR (branch+PR exist, content
unchanged → no write, merges when green). First-call paths unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 08:30:30 +02:00
4 changed files with 170 additions and 23 deletions
+26 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"os"
"git.d-ma.be/mathias/gitea-mcp/internal/allowlist"
"git.d-ma.be/mathias/gitea-mcp/internal/gitea"
@@ -22,7 +23,7 @@ func NewRepoMirrorPush(c *gitea.Client, a *allowlist.Allowlist) *RepoMirrorPush
func (t *RepoMirrorPush) Descriptor() registry.ToolDescriptor {
return registry.ToolDescriptor{
Name: "repo_mirror_push",
Description: "Manage push mirrors for a repository: add, list, or delete.",
Description: "Manage push mirrors for a repository: add, list, or delete. For the mirror credential, PREFER remote_password_env (the name of an env var the server reads) so the secret never rides the tool-call payload/transcript; remote_password (raw) is discouraged and will be persisted in logs.",
InputSchema: json.RawMessage(`{
"type":"object",
"properties":{
@@ -31,7 +32,8 @@ func (t *RepoMirrorPush) Descriptor() registry.ToolDescriptor {
"action":{"type":"string","enum":["add","list","delete"]},
"remote_address":{"type":"string","description":"Mirror target URL (required for add)."},
"remote_username":{"type":"string"},
"remote_password":{"type":"string","description":"Never logged or returned."},
"remote_password_env":{"type":"string","description":"PREFERRED: name of a server-side env var holding the mirror credential; the server resolves it, so the secret is never in this call. Errors if the var is unset."},
"remote_password":{"type":"string","description":"DISCOURAGED: raw credential — lands in the tool-call transcript/logs. Use remote_password_env instead."},
"interval":{"type":"string","description":"Sync interval, e.g. '8h0m0s'."},
"sync_on_commit":{"type":"boolean"},
"mirror_name":{"type":"string","description":"Remote name to delete (required for delete)."}
@@ -48,6 +50,7 @@ type repoMirrorPushArgs struct {
RemoteAddress string `json:"remote_address"`
RemoteUsername string `json:"remote_username"`
RemotePassword string `json:"remote_password"`
RemotePasswordEnv string `json:"remote_password_env"`
Interval string `json:"interval"`
SyncOnCommit bool `json:"sync_on_commit"`
MirrorName string `json:"mirror_name"`
@@ -72,6 +75,22 @@ func toSafeMirror(m *gitea.PushMirror) safeMirror {
}
}
// resolveMirrorPassword prefers remote_password_env — the name of a server-side
// env var — so the credential never appears in the tool-call payload (#49). It
// falls back to the raw (discouraged) remote_password. An env name that resolves
// to empty is a loud error, not a silent empty password.
func resolveMirrorPassword(args repoMirrorPushArgs) (string, error) {
if args.RemotePasswordEnv != "" {
pw := os.Getenv(args.RemotePasswordEnv)
if pw == "" {
return "", fmt.Errorf("remote_password_env %q is unset or empty in the server environment: %w",
args.RemotePasswordEnv, gitea.ErrValidation)
}
return pw, nil
}
return args.RemotePassword, nil
}
func (t *RepoMirrorPush) Call(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) {
var args repoMirrorPushArgs
if err := parseArgs(raw, &args); err != nil {
@@ -82,10 +101,14 @@ func (t *RepoMirrorPush) Call(ctx context.Context, raw json.RawMessage) (json.Ra
}
switch args.Action {
case "add":
password, err := resolveMirrorPassword(args)
if err != nil {
return nil, err
}
m, err := t.c.AddPushMirror(ctx, args.Owner, args.Repo, gitea.AddPushMirrorArgs{
RemoteAddress: args.RemoteAddress,
RemoteUsername: args.RemoteUsername,
RemotePassword: args.RemotePassword,
RemotePassword: password,
Interval: args.Interval,
SyncOnCommit: args.SyncOnCommit,
})
+40
View File
@@ -3,6 +3,7 @@ package tools_test
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
@@ -14,6 +15,45 @@ import (
"github.com/stretchr/testify/require"
)
// #49: remote_password_env names a server-side env var; the secret is resolved
// from the server environment and never rides the tool-call payload.
func TestRepoMirrorPushTool_PasswordFromEnv(t *testing.T) {
t.Setenv("TEST_MIRROR_PW", "env-secret")
var gotPw string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
var m map[string]any
_ = json.Unmarshal(body, &m)
gotPw, _ = m["remote_password"].(string)
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"id":1,"remote_name":"m","remote_address":"a"}`))
}))
defer srv.Close()
tool := tools.NewRepoMirrorPush(gitea.NewClient(srv.URL, "tok"), allowlist.New([]string{"mathias"}))
out, err := tool.Call(context.Background(), json.RawMessage(`{
"owner":"mathias","name":"infra","action":"add",
"remote_address":"https://github.com/mathias/infra.git",
"remote_username":"mathias","remote_password_env":"TEST_MIRROR_PW"
}`))
require.NoError(t, err)
assert.Equal(t, "env-secret", gotPw, "password must be resolved from the server env var")
assert.NotContains(t, string(out), "env-secret")
}
// remote_password_env pointing at an unset var must fail loudly, not silently
// send an empty password.
func TestRepoMirrorPushTool_EnvUnsetErrors(t *testing.T) {
tool := tools.NewRepoMirrorPush(gitea.NewClient("http://unused", ""), allowlist.New([]string{"mathias"}))
_, err := tool.Call(context.Background(), json.RawMessage(`{
"owner":"mathias","name":"infra","action":"add",
"remote_address":"https://github.com/x/y.git","remote_username":"u",
"remote_password_env":"DEFINITELY_UNSET_MIRROR_VAR_XYZ"
}`))
require.Error(t, err)
assert.ErrorIs(t, err, gitea.ErrValidation)
}
func TestRepoMirrorPushTool_Add(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method)
+33 -3
View File
@@ -171,18 +171,26 @@ func (t *TBDShip) Call(ctx context.Context, raw json.RawMessage) (json.RawMessag
return nil, fmt.Errorf("branch protection probe: %w", err)
}
// Branch from base, write the change, open the PR.
if err := t.c.CreateBranch(ctx, args.Owner, args.Repo, branch, base); err != nil {
// Branch from base. A conflict means the branch already exists — resume on it
// (idempotent re-invoke, #48) rather than failing.
if err := t.c.CreateBranch(ctx, args.Owner, args.Repo, branch, base); err != nil && !errors.Is(err, gitea.ErrConflict) {
return nil, fmt.Errorf("create branch %s: %w", branch, err)
}
// A pre-existing file at path needs its blob sha to update; a new file does not.
// A pre-existing file at path needs its blob sha to update; a new file does
// not. If the content already on the branch is identical, skip the write so a
// resume doesn't produce a redundant empty-diff commit.
sha := ""
needWrite := true
if fc, ferr := t.c.GetFileContents(ctx, args.Owner, args.Repo, args.Path, branch); ferr == nil {
sha = fc.Sha
if decoded, derr := base64.StdEncoding.DecodeString(fc.Content); derr == nil && string(decoded) == args.Content {
needWrite = false
}
} else if !errors.Is(ferr, gitea.ErrNotFound) {
return nil, fmt.Errorf("read %s on %s: %w", args.Path, branch, ferr)
}
if needWrite {
if _, err := t.c.UpsertFile(ctx, args.Owner, args.Repo, args.Path, gitea.UpsertFileArgs{
Branch: branch,
Content: base64.StdEncoding.EncodeToString([]byte(args.Content)),
@@ -191,6 +199,7 @@ func (t *TBDShip) Call(ctx context.Context, raw json.RawMessage) (json.RawMessag
}); err != nil {
return nil, fmt.Errorf("write %s on %s: %w", args.Path, branch, err)
}
}
prTitle := args.PRTitle
if prTitle == "" {
@@ -202,9 +211,15 @@ func (t *TBDShip) Call(ctx context.Context, raw json.RawMessage) (json.RawMessag
Head: branch,
Base: base,
})
if err != nil {
// An open PR for this head already exists → resume it (#48).
if errors.Is(err, gitea.ErrConflict) || errors.Is(err, gitea.ErrValidation) {
pr, err = t.findOpenPR(ctx, args.Owner, args.Repo, branch)
}
if err != nil {
return nil, fmt.Errorf("open PR: %w", err)
}
}
// CI gate on the PR head commit.
runs := t.pollRuns(ctx, args.Owner, args.Repo, pr.Head.Sha, args.CITimeoutSec)
@@ -267,6 +282,21 @@ func (t *TBDShip) pollRuns(ctx context.Context, owner, repo, headSHA string, tim
}
}
// findOpenPR returns the open PR whose head is the given branch — used to resume
// an existing PR when CreatePullRequest reports one already exists (#48).
func (t *TBDShip) findOpenPR(ctx context.Context, owner, repo, branch string) (*gitea.PullRequest, error) {
prs, err := t.c.ListPullRequests(ctx, owner, repo, "open", branch, 1, 50)
if err != nil {
return nil, err
}
for i := range prs {
if prs[i].Head.Ref == branch {
return &prs[i], nil
}
}
return nil, fmt.Errorf("no open PR found for head %s: %w", branch, gitea.ErrNotFound)
}
func (t *TBDShip) listRuns(ctx context.Context, owner, repo, headSHA string) []gitea.WorkflowRun {
resp, err := t.c.ListWorkflowRuns(ctx, owner, repo, gitea.ListWorkflowRunsArgs{HeadSHA: headSHA, Limit: 50})
if err != nil || resp == nil {
+54
View File
@@ -150,6 +150,60 @@ func TestTBDShip_MergeConflict_FailsClosed(t *testing.T) {
assert.False(t, deleted.Load(), "branch is NOT deleted on a failed merge")
}
// Re-invoking with the same change must resume the existing branch/PR (not
// error on "branch exists"), skip the redundant write when content is
// unchanged, and merge once CI is green (#48).
func TestTBDShip_Resume_ExistingBranchAndPR(t *testing.T) {
var merged, deleted, wrote atomic.Bool
branch := "tbd/resume-me"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p := r.URL.Path
w.Header().Set("Content-Type", "application/json")
switch {
case r.Method == http.MethodGet && strings.Contains(p, "/branch_protections/"):
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"message":"not found"}`))
case r.Method == http.MethodPost && strings.HasSuffix(p, "/branches"):
w.WriteHeader(http.StatusConflict) // branch already exists
_, _ = w.Write([]byte(`{"message":"branch already exists"}`))
case r.Method == http.MethodGet && strings.Contains(p, "/contents/"):
// existing file with identical content ("hi") → write should be skipped
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"path":"docs/x.md","sha":"s","content":"aGk=","encoding":"base64"}`))
case (r.Method == http.MethodPost || r.Method == http.MethodPut) && strings.Contains(p, "/contents/"):
wrote.Store(true)
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"content":{"path":"x","sha":"s2"},"commit":{"sha":"c"}}`))
case r.Method == http.MethodPost && strings.HasSuffix(p, "/pulls"):
w.WriteHeader(http.StatusConflict) // PR already exists for this head
_, _ = w.Write([]byte(`{"message":"pull request already exists"}`))
case r.Method == http.MethodGet && strings.HasSuffix(p, "/pulls"):
_, _ = w.Write([]byte(`[{"number":7,"html_url":"http://x/pulls/7","state":"open","head":{"ref":"` + branch + `","sha":"abc"},"base":{"ref":"main"}}]`))
case r.Method == http.MethodGet && strings.Contains(p, "/actions/runs"):
_, _ = w.Write([]byte(`{"total_count":1,"workflow_runs":[{"id":1,"status":"completed","conclusion":"success","head_sha":"abc"}]}`))
case r.Method == http.MethodPost && strings.HasSuffix(p, "/pulls/7/merge"):
merged.Store(true)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{}`))
case r.Method == http.MethodDelete && strings.Contains(p, "/branches/"):
deleted.Store(true)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{}`))
default:
t.Errorf("unexpected request: %s %s", r.Method, p)
w.WriteHeader(http.StatusNotFound)
}
}))
defer srv.Close()
res := callShip(t, srv.URL, `{"owner":"mathias","repo":"myrepo","path":"docs/x.md","content":"hi","message":"add x","branch":"`+branch+`"}`)
assert.Equal(t, true, res["merged"], "resume must merge when CI is green")
assert.Equal(t, float64(7), res["pr_number"], "must reuse the existing PR #7")
assert.False(t, wrote.Load(), "identical content must not trigger a redundant write")
assert.True(t, merged.Load())
}
func TestTBDShip_AllowlistRejects(t *testing.T) {
tool := tools.NewTBDShip(gitea.NewClient("http://unused", ""), allowlist.New([]string{"mathias"}))
_, err := tool.Call(context.Background(), json.RawMessage(`{"owner":"evil","repo":"r","path":"p","content":"c","message":"m"}`))