Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ The destination repository must already exist. Matching source branches, tags, r

Running the command again is safe: unchanged release assets are detected and skipped.

A push can start the destination's GitHub Actions workflows, including one introduced by the same push. Before cloning, `gh replicate` checks whether Actions are enabled there and warns when they are, or when the setting cannot be read (that check needs administration read access). For a passive mirror, disable them once in the destination: **Settings > Actions > General > Actions permissions > Disable actions > Save**. The warning never stops the replication.
A push can start the destination's GitHub Actions workflows, including one introduced by the same push. Once the source has been validated and the push is about to happen, `gh replicate` disables Actions in the destination when they are enabled and reports it; that needs administration write access, the same permission that changing the default branch needs. If the setting cannot be read or the update is rejected, the run warns and continues, and the remaining option is manual: **Settings > Actions > General > Actions permissions > Disable actions > Save**. A dry run only reports the update it would send. Runs that already started are not cancelled.

### Replicating between two accounts

Expand Down Expand Up @@ -115,7 +115,7 @@ When both sides resolve to the same account it prints a single line. An account
- **Timeout and cancellation.** `--timeout 30m` sets the limit per Git command or HTTP request, not for the entire replication. Use a larger duration for large repositories/assets. Ctrl-C cancels pending work.
- **Bounded read retries.** GET requests retry at most twice for selected transient HTTP failures and rate limits, respecting server delays up to 30 seconds. Longer rate limits fail rather than retry early. Mutating requests are never replayed automatically after uncertain failures; rerun the command to reconcile.
- **Asset replacement is not atomic.** Source downloads are checked for size and SHA-256 before a matching destination asset is deleted. Unchanged assets are detected by digest; when a digest is missing, equal-sized destination content is downloaded and hashed, so repeated runs preserve asset IDs at the cost of an extra download. Upload responses are checked for size and digest. A failed upload can still leave that asset absent until a successful rerun.
- Original release authors and publication dates are not preserved. Discussions, permissions and Actions settings are not replicated. Workflow files themselves are part of Git history and are copied with refs.
- Original release authors and publication dates are not preserved. Discussions, permissions and Actions settings are not replicated, although Actions are disabled in the destination. Workflow files themselves are part of Git history and are copied with refs.

## Release binaries

Expand Down
55 changes: 39 additions & 16 deletions accounts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
Expand Down Expand Up @@ -167,24 +168,47 @@ func TestPreflightAbortsBeforeWritesOnWrongAccount(t *testing.T) {
}
}

func TestPreflightWarnsAboutDestinationActions(t *testing.T) {
func TestDisableDestinationActions(t *testing.T) {
for _, tc := range []struct {
name string
status int
body string
want string
name string
read int
body string
put int
want string
wantPut bool
}{
{"enabled", http.StatusOK, `{"enabled":true}`, "GitHub Actions are enabled"},
{"disabled", http.StatusOK, `{"enabled":false}`, ""},
{"unreadable", http.StatusForbidden, `{"message":"Resource not accessible"}`, "could not check"},
{"enabled", http.StatusOK, `{"enabled":true}`, http.StatusOK, "Disabled GitHub Actions", true},
{"disabled", http.StatusOK, `{"enabled":false}`, http.StatusOK, "", false},
{"unreadable", http.StatusForbidden, `{"message":"Resource not accessible"}`, http.StatusOK, "could not check", false},
{"rejected", http.StatusOK, `{"enabled":true}`, http.StatusForbidden, "could not be disabled", true},
} {
t.Run(tc.name, func(t *testing.T) {
var puts int
server := fakeServer(t, func(w http.ResponseWriter, req *http.Request) {
switch {
case req.URL.Path == "/user":
fmt.Fprint(w, `{"login":"alice"}`)
case strings.HasSuffix(req.URL.Path, "/actions/permissions"):
w.WriteHeader(tc.status)
if req.Method == http.MethodPut {
puts++
if tc.put != http.StatusOK {
w.WriteHeader(tc.put)
fmt.Fprint(w, `{"message":"Resource not accessible"}`)
return
}
var body struct {
Enabled bool `json:"enabled"`
}
if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
t.Error(err)
}
if body.Enabled {
t.Errorf("PUT kept Actions enabled")
}
fmt.Fprint(w, `{}`)
return
}
w.WriteHeader(tc.read)
fmt.Fprint(w, tc.body)
case strings.HasSuffix(req.URL.Path, "/topics"):
fmt.Fprint(w, `{"names":[]}`)
Expand All @@ -201,14 +225,13 @@ func TestPreflightWarnsAboutDestinationActions(t *testing.T) {
side := fakeSide(t, server, "token")
r := &replicator{source: side, target: side, ctx: context.Background(), timeout: time.Minute}

out := captureStderr(t, func() {
if _, err := r.preflight("alice/project", "bob/project-replica"); err != nil {
t.Fatal(err)
}
})
out := captureStderr(t, func() { r.disableActions("bob/project-replica") })
if got := puts > 0; got != tc.wantPut {
t.Fatalf("sent update: %v, want %v (output %q)", got, tc.wantPut, out)
}
if tc.want == "" {
if strings.Contains(out, "Warning") {
t.Fatalf("unexpected warning: %q", out)
if strings.Contains(out, "Warning") || strings.Contains(out, "Disabled GitHub Actions") {
t.Fatalf("unexpected output: %q", out)
}
return
}
Expand Down
51 changes: 40 additions & 11 deletions entrypoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ func gitRefs(t *testing.T, dir string) string {
// fakeGitHubAPI serves the endpoints preflight reads. When writable, the
// metadata writes of a real run are accepted and label PATCH returns 404 so
// syncMetadata takes the POST path.
func fakeGitHubAPI(t *testing.T, labelSet []label, writable bool, defaultBranch string) (string, *[]string, *string) {
func fakeGitHubAPI(t *testing.T, labelSet []label, writable bool, defaultBranch string, actionsEnabled bool) (string, *[]string, *string, *[]string) {
t.Helper()
var methods []string
var methods, actionBodies []string
var metadataPatch string
server := fakeServer(t, func(w http.ResponseWriter, req *http.Request) {
methods = append(methods, req.Method+" "+req.URL.Path)
Expand All @@ -91,6 +91,13 @@ func fakeGitHubAPI(t *testing.T, labelSet []label, writable bool, defaultBranch
w.WriteHeader(http.StatusForbidden)
return
}
if req.Method == http.MethodPut && strings.HasSuffix(req.URL.Path, "/actions/permissions") {
body, err := io.ReadAll(req.Body)
if err != nil {
t.Error(err)
}
actionBodies = append(actionBodies, string(body))
}
if req.Method == http.MethodPatch && strings.HasSuffix(req.URL.Path, "/labels/bug") {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, `{"message":"Not Found"}`)
Expand All @@ -103,7 +110,7 @@ func fakeGitHubAPI(t *testing.T, labelSet []label, writable bool, defaultBranch
case req.URL.Path == "/user":
fmt.Fprint(w, `{"login":"user"}`)
case strings.HasSuffix(req.URL.Path, "/actions/permissions"):
fmt.Fprint(w, `{"enabled":false}`)
fmt.Fprintf(w, `{"enabled":%t}`, actionsEnabled)
case strings.HasSuffix(req.URL.Path, "/topics"):
fmt.Fprint(w, `{"names":[]}`)
case strings.HasSuffix(req.URL.Path, "/labels"):
Expand All @@ -123,7 +130,7 @@ func fakeGitHubAPI(t *testing.T, labelSet []label, writable bool, defaultBranch
t.Errorf("unexpected request: %s %s", req.Method, req.URL.Path)
}
})
return server, &methods, &metadataPatch
return server, &methods, &metadataPatch, &actionBodies
}

// stubRun wires newSide and gitRemote to the fake servers and local bare repos.
Expand Down Expand Up @@ -201,7 +208,7 @@ func TestRunLeavesDestinationUntouchedWhenPreflightFails(t *testing.T) {
case req.URL.Path == "/user":
fmt.Fprint(w, `{"login":"bob"}`)
case strings.HasSuffix(req.URL.Path, "/actions/permissions"):
fmt.Fprint(w, `{"enabled":false}`)
fmt.Fprint(w, `{"enabled":true}`)
default:
fmt.Fprint(w, `{"description":"","homepage":""}`)
}
Expand Down Expand Up @@ -236,8 +243,8 @@ func TestRunDryRunLeavesDestinationUntouched(t *testing.T) {
before := gitRefs(t, f.destination)

labels := []label{{Name: "bug", Color: "d73a4a", Description: "Something isn't working"}}
sourceURL, _, _ := fakeGitHubAPI(t, labels, false, "main")
targetURL, targetMethods, _ := fakeGitHubAPI(t, nil, false, "main")
sourceURL, _, _, _ := fakeGitHubAPI(t, labels, false, "main", true)
targetURL, targetMethods, _, actionBodies := fakeGitHubAPI(t, nil, false, "main", true)
stubRun(t, sourceURL, targetURL, f)

out := captureStderr(t, func() {
Expand All @@ -248,6 +255,12 @@ func TestRunDryRunLeavesDestinationUntouched(t *testing.T) {
if !strings.Contains(out, "Dry run complete") {
t.Fatalf("missing dry-run confirmation: %q", out)
}
if !strings.Contains(out, "Would PUT repos/"+targetRepo+"/actions/permissions") {
t.Fatalf("dry run did not report the Actions update: %q", out)
}
if len(*actionBodies) != 0 {
t.Fatalf("dry run wrote Actions settings: %q", *actionBodies)
}
if after := gitRefs(t, f.destination); after != before {
t.Fatalf("destination refs changed:\nbefore %q\nafter %q", before, after)
}
Expand All @@ -263,8 +276,8 @@ func TestRunReplicatesIntoDestination(t *testing.T) {
f := newGitFixture(t)

labels := []label{{Name: "bug", Color: "d73a4a", Description: "Something isn't working"}}
sourceURL, _, _ := fakeGitHubAPI(t, labels, false, "master")
targetURL, targetMethods, targetPatch := fakeGitHubAPI(t, nil, true, "main")
sourceURL, _, _, _ := fakeGitHubAPI(t, labels, false, "master", true)
targetURL, targetMethods, targetPatch, actionBodies := fakeGitHubAPI(t, nil, true, "main", true)
stubRun(t, sourceURL, targetURL, f)

out := captureStderr(t, func() {
Expand All @@ -278,6 +291,16 @@ func TestRunReplicatesIntoDestination(t *testing.T) {
if got, want := gitRefs(t, f.destination), gitRefs(t, f.source); got != want {
t.Fatalf("destination refs differ:\n got %q\nwant %q", got, want)
}
if len(*actionBodies) != 1 {
t.Fatalf("Actions PUT bodies = %q, want one", *actionBodies)
}
var actionsPayload map[string]any
if err := json.Unmarshal([]byte((*actionBodies)[0]), &actionsPayload); err != nil {
t.Fatal(err)
}
if enabled, ok := actionsPayload["enabled"]; !ok || enabled != false {
t.Fatalf("Actions payload = %s, want {\"enabled\":false}", (*actionBodies)[0])
}
issued := strings.Join(*targetMethods, "\n")
for _, want := range []string{
"PATCH /repos/" + targetRepo,
Expand Down Expand Up @@ -314,7 +337,10 @@ func TestSyncGitPropagatesRejectedPush(t *testing.T) {
t.Fatalf("unexpected repository %q", ownerRepo)
return ""
}
r := &replicator{ctx: context.Background(), timeout: time.Minute}
side := fakeSide(t, fakeServer(t, func(w http.ResponseWriter, req *http.Request) {
fmt.Fprint(w, `{"enabled":false}`)
}), "token")
r := &replicator{source: side, target: side, ctx: context.Background(), timeout: time.Minute}

err := r.syncGit(sourceRepo, targetRepo)
if err == nil || !strings.Contains(err.Error(), "push refs") {
Expand All @@ -338,7 +364,10 @@ func TestSyncGitClonesAndPushesRefs(t *testing.T) {
t.Fatalf("unexpected repository %q", ownerRepo)
return ""
}
r := &replicator{ctx: context.Background(), timeout: time.Minute}
side := fakeSide(t, fakeServer(t, func(w http.ResponseWriter, req *http.Request) {
fmt.Fprint(w, `{"enabled":false}`)
}), "token")
r := &replicator{source: side, target: side, ctx: context.Background(), timeout: time.Minute}

if err := r.syncGit(sourceRepo, targetRepo); err != nil {
t.Fatal(err)
Expand Down
22 changes: 15 additions & 7 deletions replicate.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,26 +230,33 @@ func (r *replicator) verifyIdentities() error {
return nil
}

// warnIfActionsRun reports that a push can start destination workflows. The
// check is advisory: an unreadable setting is reported, never fatal.
func (r *replicator) warnIfActionsRun(target string) {
// disableActions stops the destination from starting workflows when the push
// lands. The push itself cannot be suppressed, so a failure here is reported and
// never prevents the replication.
func (r *replicator) disableActions(target string) {
var permissions struct {
Enabled bool `json:"enabled"`
}
if err := r.call(r.target, "GET", "repos/"+target+"/actions/permissions", nil, &permissions); err != nil {
fmt.Fprintf(os.Stderr, "Warning: could not check whether GitHub Actions are enabled in %s: %v\n", target, err)
fmt.Fprintf(os.Stderr, "Warning: could not check whether GitHub Actions are enabled in %s (%v), so this push may start its workflows. Check them in Settings > Actions > General > Actions permissions.\n", target, err)
return
}
if permissions.Enabled {
fmt.Fprintf(os.Stderr, "Warning: GitHub Actions are enabled in %s, so this replication can start its workflows. For a passive mirror, disable them once: Settings > Actions > General > Actions permissions > Disable actions > Save.\n", target)
if !permissions.Enabled {
return
}
if err := r.call(r.target, "PUT", "repos/"+target+"/actions/permissions", jsonBody(map[string]bool{"enabled": false}), nil); err != nil {
fmt.Fprintf(os.Stderr, "Warning: GitHub Actions are enabled in %s and could not be disabled (%v), so this replication can start its workflows. Disable them manually: Settings > Actions > General > Actions permissions > Disable actions > Save.\n", target, err)
return
}
if !r.dryRun {
fmt.Fprintf(os.Stderr, "Disabled GitHub Actions in %s for a passive mirror.\n", target)
}
}

func (r *replicator) preflight(source, target string) (*plan, error) {
if err := r.verifyIdentities(); err != nil {
return nil, err
}
r.warnIfActionsRun(target)
p := &plan{}
if err := r.call(r.source, "GET", "repos/"+source, nil, &p.repository); err != nil {
return nil, err
Expand Down Expand Up @@ -333,6 +340,7 @@ func (r *replicator) syncGit(source, target string) error {
if err := r.checkLFS(gitDir); err != nil {
return err
}
r.disableActions(target)
fmt.Fprintf(os.Stderr, " Pushing branches and tags to %s...\n", target)
return r.pushRefs(gitDir)
}
Expand Down
Loading