internal/control/mirrorcmd.go
254 lines · 8484 bytes
7 symbols in this file
1package control
2
3import (
4 "bufio"
5 "errors"
6 "fmt"
7 "io"
8 "net/url"
9 "strconv"
10 "strings"
11
12 "gitbay.org/gitbay/internal/gitpin"
13 "gitbay.org/gitbay/internal/policy"
14 "gitbay.org/gitbay/internal/protocol"
15 "gitbay.org/gitbay/internal/store"
16 "gitbay.org/gitbay/internal/webhook"
17)
18
19func init() {
20 register(Command{Path: []string{"repo", "mirror", "add"},
21 NeedsRecentSignIn: true,
22 Summary: "mirror to or from a remote",
23 Usage: "repo mirror add <owner/name> <https-url> --direction push|pull [--username <u>] [--token-stdin]",
24 Flags: []Flag{
25 {"--direction", "push|pull", "which way the mirror syncs", ""},
26 {"--username", "<u>", "the remote's username", ""},
27 {"--token-stdin", "", "read a credential token from stdin", ""},
28 },
29 Examples: []string{"repo mirror add krz/gitbay https://github.com/krz-labs/gitbay.git --direction push"},
30 ReadsStdin: true, Run: runMirrorAdd})
31 register(Command{Path: []string{"repo", "mirror", "list"},
32 Summary: "list mirrors with sync status",
33 Usage: "repo mirror list <owner/name>",
34 Examples: []string{"repo mirror list krz/gitbay"},
35 ReadOnly: true, Run: runMirrorList})
36 register(Command{Path: []string{"repo", "mirror", "set-url"},
37 NeedsRecentSignIn: true,
38 Summary: "point a mirror at a new URL on the same host",
39 Usage: "repo mirror set-url <owner/name> <id> <https-url>",
40 Examples: []string{"repo mirror set-url krz/gitbay 3 https://github.com/krz-labs/gitbay.git"},
41 Run: runMirrorSetURL})
42 register(Command{Path: []string{"repo", "mirror", "remove"},
43 Summary: "remove a mirror",
44 Usage: "repo mirror remove <owner/name> <id>",
45 Examples: []string{"repo mirror remove krz/gitbay 3"},
46 Run: runMirrorRemove})
47 register(Command{Path: []string{"repo", "mirror", "sync"},
48 Summary: "schedule an immediate sync",
49 Usage: "repo mirror sync <owner/name>",
50 Examples: []string{"repo mirror sync krz/gitbay"},
51 Run: runMirrorSync})
52}
53
54func runMirrorAdd(c *Ctx, args []string) int {
55 f, err := c.parseArgs(args, flagSpec{Values: []string{"--direction", "--username"}, Bools: []string{"--token-stdin"}, MaxPos: 2,
56 Usage: "repo mirror add <owner/name> <url> --direction push|pull [--username <u>] [--token-stdin]"})
57 if err != nil {
58 return c.fail(protocol.ExitUsage, "%v", err)
59 }
60 path, urlArg := f.pos(0), f.pos(1)
61 direction, username, tokenStdin := f.Value("--direction"), f.Value("--username"), f.Has("--token-stdin")
62 if path == "" || urlArg == "" || (direction != "push" && direction != "pull") {
63 return c.usage()
64 }
65 // Sync refuses a numerically written host; say so now, before a
66 // resolver gets to read it.
67 if u, err := url.Parse(urlArg); err == nil {
68 if err := gitpin.CheckHost(u.Hostname()); err != nil {
69 return c.failInput(err)
70 }
71 }
72 // The worker's git process dials this URL from the server: same SSRF
73 // surface as a webhook target, same rules.
74 if err := webhook.ValidateURL(urlArg, c.Cfg.Webhooks.AllowLocal); err != nil {
75 return c.failInput(err)
76 }
77 repo, code := resolveRepo(c, path, policy.CanAdmin)
78 if code >= 0 {
79 return code
80 }
81 if code := refuseArchived(c, repo); code >= 0 {
82 return code
83 }
84 token := ""
85 if tokenStdin {
86 line, err := bufio.NewReader(io.LimitReader(c.Stdin, 4096)).ReadString('\n')
87 if err != nil && line == "" {
88 return c.fail(protocol.ExitUsage, "--token-stdin given but stdin held no token")
89 }
90 token = strings.TrimSpace(line)
91 }
92 id, err := c.Store.AddMirror(repo.ID, direction, urlArg, username, token)
93 if err != nil {
94 if errors.Is(err, store.ErrExists) {
95 return c.fail(protocol.ExitUsage, "that mirror already exists")
96 }
97 return c.fail(protocol.ExitFailure, "%v", err)
98 }
99 note := ""
100 if direction == "pull" {
101 note = "; local pushes are now refused — refs come from the upstream"
102 }
103 return c.emit(map[string]any{"id": id, "direction": direction, "url": urlArg}, func(w io.Writer) {
104 fmt.Fprintf(w, "mirror %d added (%s %s)%s\n", id, direction, urlArg, note)
105 })
106}
107
108func runMirrorList(c *Ctx, args []string) int {
109 if len(args) != 1 {
110 return c.usage()
111 }
112 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
113 if code >= 0 {
114 return code
115 }
116 ms, err := c.Store.ListMirrors(repo.ID)
117 if err != nil {
118 return c.fail(protocol.ExitFailure, "%v", err)
119 }
120 type out struct {
121 ID int64 `json:"id"`
122 Direction string `json:"direction"`
123 URL string `json:"url"`
124 Username string `json:"username,omitempty"`
125 Pending bool `json:"pending"`
126 LastSync string `json:"last_sync,omitempty"`
127 LastError string `json:"last_error,omitempty"`
128 }
129 var ds []out
130 for _, m := range ms {
131 // The token never leaves the server, in any encoding.
132 ds = append(ds, out{m.ID, m.Direction, m.URL, m.Username, m.Dirty, m.LastSync, m.LastError})
133 }
134 return c.emitView(ds, func(w io.Writer) {
135 tb := c.table(w, "ID", "DIRECTION", "URL", "LAST", "STATUS")
136 for _, d := range ds {
137 status := "ok"
138 if repo.Settings.Archived {
139 status = "disabled (archived)"
140 } else if d.Pending {
141 status = "pending"
142 }
143 if !repo.Settings.Archived && d.LastError != "" {
144 status = "error: " + d.LastError
145 }
146 tb.row(cRef(fmt.Sprintf("%d", d.ID)), cText(d.Direction), cText(d.URL), cText("last "+orDash(d.LastSync)), cState(status))
147 }
148 tb.flush()
149 }, func() screen {
150 rows := make([]row, len(ds))
151 for i, d := range ds {
152 state := "ok"
153 if repo.Settings.Archived {
154 state = "archived"
155 } else if d.Pending {
156 state = "pending"
157 }
158 if !repo.Settings.Archived && d.LastError != "" {
159 state = "error"
160 }
161 synced := "never synced"
162 if d.LastSync != "" {
163 synced = "synced " + relAge(d.LastSync, termNow())
164 }
165 rows[i] = rowOf(cRef(strconv.FormatInt(d.ID, 10)), cGlyph(state), cFlex(d.URL), cMeta(d.Direction, synced), cMark(d.LastError, sgrRed))
166 }
167 return listScreen("Mirrors", rows,
168 action{"Mirrors", []string{"repo", "mirror", "sync", repo.Path()}},
169 action{"Mirrors", []string{"repo", "mirror", "remove", repo.Path(), "<id>"}},
170 )
171 })
172}
173
174func orDash(s string) string {
175 if s == "" {
176 return "-"
177 }
178 return s
179}
180
181// runMirrorSetURL keeps the stored token, so it refuses a new host: the
182// token goes only where its owner sent it.
183func runMirrorSetURL(c *Ctx, args []string) int {
184 if len(args) != 3 {
185 return c.usage()
186 }
187 urlArg := args[2]
188 nu, err := url.Parse(urlArg)
189 if err != nil {
190 return c.fail(protocol.ExitUsage, "bad url %q", urlArg)
191 }
192 if err := gitpin.CheckHost(nu.Hostname()); err != nil {
193 return c.failInput(err)
194 }
195 if err := webhook.ValidateURL(urlArg, c.Cfg.Webhooks.AllowLocal); err != nil {
196 return c.failInput(err)
197 }
198 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
199 if code >= 0 {
200 return code
201 }
202 id, err := strconv.ParseInt(args[1], 10, 64)
203 if err != nil {
204 return c.fail(protocol.ExitUsage, "bad mirror id %q", args[1])
205 }
206 ms, err := c.Store.ListMirrors(repo.ID)
207 if err != nil {
208 return c.fail(protocol.ExitFailure, "%v", err)
209 }
210 var cur *store.Mirror
211 for i := range ms {
212 if ms[i].ID == id {
213 cur = &ms[i]
214 }
215 }
216 if cur == nil {
217 return c.fail(protocol.ExitNotFound, "no mirror %d on %s", id, repo.Path())
218 }
219 if ou, err := url.Parse(cur.URL); err != nil || !strings.EqualFold(ou.Scheme, nu.Scheme) || !strings.EqualFold(ou.Host, nu.Host) {
220 return c.fail(protocol.ExitUsage, "set-url keeps the stored token, so the host cannot change; remove the mirror and add it again")
221 }
222 if err := c.Store.SetMirrorURL(repo.ID, id, urlArg); err != nil {
223 if errors.Is(err, store.ErrExists) {
224 return c.fail(protocol.ExitUsage, "that mirror already exists")
225 }
226 return c.fail(protocol.ExitFailure, "%v", err)
227 }
228 return c.emit(map[string]any{"id": id, "url": urlArg}, func(w io.Writer) {
229 fmt.Fprintf(w, "mirror %d now %s; sync scheduled\n", id, urlArg)
230 })
231}
232
233func runMirrorRemove(c *Ctx, args []string) int {
234 return runRepoItemAction(c, args, "mirror", c.Store.RemoveMirror, "removed", "removed mirror %d")
235}
236
237func runMirrorSync(c *Ctx, args []string) int {
238 if len(args) != 1 {
239 return c.usage()
240 }
241 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
242 if code >= 0 {
243 return code
244 }
245 if code := refuseArchived(c, repo); code >= 0 {
246 return code
247 }
248 if err := c.Store.MarkMirrorsDirty(repo.ID, ""); err != nil {
249 return c.fail(protocol.ExitFailure, "%v", err)
250 }
251 return c.emit(map[string]string{"sync": "scheduled"}, func(w io.Writer) {
252 fmt.Fprintln(w, "sync scheduled; check repo mirror list for the outcome")
253 })
254}