| 1 | package git |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "unicode/utf8" |
| 12 | ) |
| 13 | |
| 14 | // secretPushStderr is a refused push whose other lines echo a URL with |
| 15 | // credentials and a remote helper's command line, as git prints them. |
| 16 | const secretPushStderr = "fatal: unable to access 'https://user:secret@host/x?token=y'z&k=secret': retrying\n" + |
| 17 | "helper: ext::ssh -i /home/operator/.ssh/secret-key example.org %S repo\n" + |
| 18 | "remote: policy denies refs/klaus/data \r\n" + |
| 19 | "remote: \x1b[31msee the policy\x1b[0m\n" + |
| 20 | "error: failed to push some refs to 'ext::ssh -i /home/operator/.ssh/secret-key example.org %S repo'\n" |
| 21 | |
| 22 | // porcelain is git push --porcelain's stdout for one ref with summary, after |
| 23 | // the destination line that echoes the remote's URL. |
| 24 | func porcelain(summary string) string { |
| 25 | return "To https://user:secret@host/x?token=y'z&k=secret\n!\t0123abcd:refs/klaus/data\t" + summary + "\nDone\n" |
| 26 | } |
| 27 | |
| 28 | func TestParsePushError(t *testing.T) { |
| 29 | for _, tc := range []struct { |
| 30 | name, stdout, stderr, class, message string |
| 31 | }{ |
| 32 | {"refused, other lines dropped", porcelain("[remote rejected] (pre-receive hook declined)"), secretPushStderr, PushRefused, |
| 33 | "remote: policy denies refs/klaus/data\nremote: [31msee the policy[0m\n[remote rejected] (pre-receive hook declined)"}, |
| 34 | {"an address in the reason", porcelain("[remote rejected] (permission denied for https://user:secret@example.org/x?token=secret)"), "", PushRefused, |
| 35 | "[remote rejected] " + PushWithheld}, |
| 36 | {"an address in a remote line", "", "remote: mirror operator@example.org:secret refused\nremote: try later\n", PushOther, |
| 37 | PushWithheld + "\nremote: try later"}, |
| 38 | {"a destination path made to look like a remote line", |
| 39 | "", "fatal: '/srv/x\nremote: see user:secret@example.org/x?token=secret' does not appear to be a git repository\n" + |
| 40 | "fatal: Could not read from remote repository.\n", PushNetwork, PushWithheld}, |
| 41 | {"a destination that forges a status line for another ref", |
| 42 | "To \n!\tx:y\t[https://example.org/x?token=secret]\n\n!\t0123abcd:refs/klaus/data\t[remote rejected] (pre-receive hook declined)\nDone\n", |
| 43 | "", PushRefused, "[remote rejected] (pre-receive hook declined)"}, |
| 44 | {"an address in the status", porcelain("[https://example.org/x?token=secret]"), "", PushRefused, PushWithheld}, |
| 45 | {"status lines come from stdout only", "", " ! [remote rejected] refs/klaus/data -> refs/klaus/data (declined)\n", PushOther, ""}, |
| 46 | {"not a fast-forward", porcelain("[rejected] (non-fast-forward)"), "hint: Updates were rejected\n", PushNotFastForward, |
| 47 | "[rejected] (non-fast-forward)"}, |
| 48 | {"fetch first", porcelain("[rejected] (fetch first)"), "", PushNotFastForward, "[rejected] (fetch first)"}, |
| 49 | {"no report from the remote", porcelain("[remote failure] (remote failed to report status)"), "", PushUnconfirmed, |
| 50 | "[remote failure] (remote failed to report status)"}, |
| 51 | {"authentication", "", "remote: Invalid username or password.\nfatal: Authentication failed for 'https://user:secret@host/x/'\n", PushAuthentication, |
| 52 | "remote: Invalid username or password."}, |
| 53 | {"ssh key refused", "", "git@example.org: Permission denied (publickey).\nfatal: Could not read from remote repository.\n", PushAuthentication, ""}, |
| 54 | {"network", "", "fatal: unable to access 'https://user:secret@host/x?token=y/': Could not resolve host: host\n", PushNetwork, ""}, |
| 55 | {"other", "", "fatal: 'origin' does not appear to be a git repository\n", PushOther, ""}, |
| 56 | } { |
| 57 | t.Run(tc.name, func(t *testing.T) { |
| 58 | got := ParsePushError("refs/klaus/data", tc.stdout, tc.stderr) |
| 59 | if got.Class != tc.class || got.Message != tc.message { |
| 60 | t.Errorf("ParsePushError = {%q, %q}, want {%q, %q}", got.Class, got.Message, tc.class, tc.message) |
| 61 | } |
| 62 | for _, leak := range []string{"secret", "token", "user:", "ext::", "https://", "example.org"} { |
| 63 | if strings.Contains(got.Error(), leak) { |
| 64 | t.Errorf("Error() = %q holds %q", got.Error(), leak) |
| 65 | } |
| 66 | } |
| 67 | }) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // TestParsePushErrorBounded: a remote that prints megabytes leaves a message |
| 72 | // of at most MaxPushMessage bytes that ends in the cut marker. |
| 73 | func TestParsePushErrorBounded(t *testing.T) { |
| 74 | stderr := "remote: START " + strings.Repeat("é", MaxPushMessage) + "\n" |
| 75 | got := ParsePushError("refs/klaus/data", porcelain("[remote rejected] (pre-receive hook declined)"), stderr) |
| 76 | if len(got.Message) > MaxPushMessage || !strings.HasPrefix(got.Message, "remote: START") || !strings.HasSuffix(got.Message, "\n"+PushMessageCut) { |
| 77 | t.Errorf("message of %d bytes = %.40q...%q", len(got.Message), got.Message, got.Message[max(len(got.Message)-20, 0):]) |
| 78 | } |
| 79 | if !utf8.ValidString(got.Message) { |
| 80 | t.Errorf("message was not cut at a character boundary") |
| 81 | } |
| 82 | if got.Class != PushRefused { |
| 83 | t.Errorf("class = %q, want %q from the status past the cut", got.Class, PushRefused) |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | // TestPushDataRefRefused: a receive hook's refusal reaches the caller as a |
| 88 | // PushError with the hook's own words. |
| 89 | func TestPushDataRefRefused(t *testing.T) { |
| 90 | ctx := context.Background() |
| 91 | repo := initTestRepo(t) |
| 92 | origin := filepath.Join(t.TempDir(), "origin.git") |
| 93 | if _, err := runGit(ctx, "", "init", "--bare", origin); err != nil { |
| 94 | t.Fatal(err) |
| 95 | } |
| 96 | if _, err := runGit(ctx, repo, "remote", "add", "origin", origin); err != nil { |
| 97 | t.Fatal(err) |
| 98 | } |
| 99 | hook := "#!/bin/sh\necho 'policy denies the data ref' >&2\nexit 1\n" |
| 100 | if err := os.WriteFile(filepath.Join(origin, "hooks", "pre-receive"), []byte(hook), 0o755); err != nil { |
| 101 | t.Fatal(err) |
| 102 | } |
| 103 | const ref = "refs/klaus/data" |
| 104 | if err := EnsureDataRef(ctx, repo, ref); err != nil { |
| 105 | t.Fatal(err) |
| 106 | } |
| 107 | var pushErr *PushError |
| 108 | if pushed, err := PushDataRef(ctx, repo, ref); !errors.As(err, &pushErr) || pushed != "" { |
| 109 | t.Fatalf("PushDataRef = %q, %v, want a *PushError", pushed, err) |
| 110 | } |
| 111 | if pushErr.Class != PushRefused || pushErr.Message != "remote: policy denies the data ref\n[remote rejected] (pre-receive hook declined)" { |
| 112 | t.Errorf("PushError = %+v, want refused with the hook's line and the ref's status", pushErr) |
| 113 | } |
| 114 | |
| 115 | if err := os.Remove(filepath.Join(origin, "hooks", "pre-receive")); err != nil { |
| 116 | t.Fatal(err) |
| 117 | } |
| 118 | pushed, err := PushDataRef(ctx, repo, ref) |
| 119 | if tip, _ := runGit(ctx, origin, "rev-parse", ref); err != nil || pushed == "" || pushed != tip { |
| 120 | t.Errorf("PushDataRef = %q, %v, want origin's new tip %q", pushed, err, tip) |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | // TestSyncToDataRefGivesUp: a data ref another writer moves during every |
| 125 | // attempt fails the sync after dataRefAttempts builds, and the other writer's |
| 126 | // commits stay on the ref. |
| 127 | func TestSyncToDataRefGivesUp(t *testing.T) { |
| 128 | ctx := context.Background() |
| 129 | repo := initTestRepo(t) |
| 130 | const ref = "refs/klaus/data" |
| 131 | if err := EnsureDataRef(ctx, repo, ref); err != nil { |
| 132 | t.Fatal(err) |
| 133 | } |
| 134 | file := filepath.Join(t.TempDir(), "state.json") |
| 135 | if err := os.WriteFile(file, []byte("{}"), 0o644); err != nil { |
| 136 | t.Fatal(err) |
| 137 | } |
| 138 | moves := 0 |
| 139 | t.Cleanup(SetBeforeDataRefUpdate(func() { |
| 140 | tip, _ := runGit(ctx, repo, "rev-parse", ref) |
| 141 | other, err := runGitStdin(ctx, repo, "other writer", "commit-tree", tip+"^{tree}", "-p", tip) |
| 142 | if err != nil { |
| 143 | t.Fatal(err) |
| 144 | } |
| 145 | if _, err := runGit(ctx, repo, "update-ref", ref, other); err != nil { |
| 146 | t.Fatal(err) |
| 147 | } |
| 148 | moves++ |
| 149 | })) |
| 150 | |
| 151 | if commit, err := SyncToDataRef(ctx, repo, ref, "Run a", map[string]string{"runs/a.json": file}); err == nil { |
| 152 | t.Fatalf("SyncToDataRef = %q, want an error while the ref keeps moving", commit) |
| 153 | } |
| 154 | if moves != dataRefAttempts { |
| 155 | t.Errorf("built %d times, want %d", moves, dataRefAttempts) |
| 156 | } |
| 157 | if n, _ := runGit(ctx, repo, "rev-list", "--count", ref); n != fmt.Sprint(dataRefAttempts+1) { |
| 158 | t.Errorf("%s holds %s commits, want the initial one and the other writer's %d", ref, n, dataRefAttempts) |
| 159 | } |
| 160 | } |