krz/gitbay
A CLI-first git forge.
clone: git clone https://gitbay.org/krz/gitbay.git
main: internal/control/import.go · raw
1package control
2
3import (
4 "bufio"
5 "context"
6 "fmt"
7 "io"
8 "os"
9 "path/filepath"
10 "strings"
11 "time"
12
13 "gitbay.org/gitbay/internal/gitutil"
14 "gitbay.org/gitbay/internal/policy"
15 "gitbay.org/gitbay/internal/protocol"
16)
17
18func init() {
19 register(Command{Path: []string{"repo", "import"},
20 Summary: "server-side mirror of a foreign repository: repo import <owner/name> --from <url> [--private] [--token-stdin]",
21 ReadsStdin: true, Run: runRepoImport})
22}
23
24// askpassScript answers git's credential prompts from the environment, so
25// the token never appears on a command line or in a URL. Username prompts
26// get a placeholder (GitHub and GitLab ignore it for token auth).
27const askpassScript = `#!/bin/sh
28case "$1" in
29 Username*) echo "x-access-token" ;;
30 *) echo "${GITBAY_IMPORT_TOKEN}" ;;
31esac
32`
33
34func runRepoImport(c *Ctx, args []string) int {
35 var path, from string
36 private := false
37 tokenStdin := false
38 for i := 0; i < len(args); i++ {
39 switch args[i] {
40 case "--from":
41 if i+1 >= len(args) {
42 return c.fail(protocol.ExitUsage, "--from requires a URL")
43 }
44 from = args[i+1]
45 i++
46 case "--private":
47 private = true
48 case "--token-stdin":
49 tokenStdin = true
50 default:
51 if path != "" {
52 return c.fail(protocol.ExitUsage, "unexpected argument %q", args[i])
53 }
54 path = args[i]
55 }
56 }
57 if path == "" || from == "" {
58 return c.fail(protocol.ExitUsage, "usage: repo import <owner/name> --from <url> [--private] [--token-stdin]")
59 }
60 owner, name, ok := strings.Cut(path, "/")
61 if !ok {
62 return c.fail(protocol.ExitUsage, "usage: repo import <owner/name> --from <url>")
63 }
64 if err := policy.ValidateName(name); err != nil {
65 return c.fail(protocol.ExitUsage, "%v", err)
66 }
67 // Same ownership rule as repo create: yourself, or an org you admin.
68 ownerKind, ownerID := "user", c.User.ID
69 if owner != c.User.Username {
70 org, err := c.Store.OrgByName(owner)
71 if err != nil {
72 return c.fail(protocol.ExitDenied, "cannot import under %q: not you and not an organization you can see", owner)
73 }
74 role, err := c.Store.OrgRole(org.ID, c.User.ID)
75 if err != nil {
76 return c.fail(protocol.ExitFailure, "%v", err)
77 }
78 if role != "admin" {
79 return c.fail(protocol.ExitDenied, "only admins of %s can import repositories there", owner)
80 }
81 ownerKind, ownerID = "org", org.ID
82 }
83
84 // Scheme allowlist. file:// (and anything else local) would read the
85 // server's filesystem; ssh:// would use the server's own keys.
86 switch {
87 case strings.HasPrefix(from, "https://"), strings.HasPrefix(from, "http://"), strings.HasPrefix(from, "git://"):
88 default:
89 return c.fail(protocol.ExitUsage, "import supports https://, http://, and git:// URLs only")
90 }
91 if strings.ContainsAny(from, "@") {
92 // Credentials belong on stdin, not in the URL where they would
93 // land in process listings and logs.
94 return c.fail(protocol.ExitUsage, "do not embed credentials in the URL; use --token-stdin")
95 }
96
97 // The token is read from stdin and handed to git via GIT_ASKPASS and
98 // the environment — never argv, never the database, never a log line.
99 var env []string
100 if tokenStdin {
101 token, err := bufio.NewReader(io.LimitReader(c.Stdin, 4096)).ReadString('\n')
102 if err != nil && err != io.EOF {
103 return c.fail(protocol.ExitFailure, "reading token: %v", err)
104 }
105 token = strings.TrimSpace(token)
106 if token == "" {
107 return c.fail(protocol.ExitUsage, "--token-stdin given but stdin held no token")
108 }
109 askpass := filepath.Join(c.Cfg.Server.Root, "askpass.sh")
110 if err := os.WriteFile(askpass, []byte(askpassScript), 0o700); err != nil {
111 return c.fail(protocol.ExitFailure, "%v", err)
112 }
113 env = []string{
114 "GIT_ASKPASS=" + askpass,
115 "GITBAY_IMPORT_TOKEN=" + token,
116 "GIT_TERMINAL_PROMPT=0",
117 }
118 } else {
119 env = []string{"GIT_TERMINAL_PROMPT=0"}
120 }
121
122 visibility := "public"
123 if private {
124 visibility = "private"
125 }
126 id, err := c.Store.CreateRepo(ownerKind, ownerID, name, visibility)
127 if err != nil {
128 return c.fail(protocol.ExitFailure, "%v", err)
129 }
130 dir := RepoDir(c.Cfg.Server.Root, owner, name)
131 cleanup := func() {
132 c.Store.DeleteRepo(id)
133 os.RemoveAll(dir)
134 }
135 if err := gitutil.InitBare(dir, "main", HooksDir(c.Cfg.Server.Root)); err != nil {
136 cleanup()
137 return c.fail(protocol.ExitFailure, "%v", err)
138 }
139
140 timeout := time.Duration(c.Cfg.Limits.CloneTimeoutSec) * time.Second
141 ctx, cancel := context.WithTimeout(context.Background(), timeout)
142 defer cancel()
143
144 fmt.Fprintf(c.Stderr, "importing %s into %s ...\n", from, path)
145 if err := gitutil.FetchMirror(ctx, dir, from, c.Stderr, env); err != nil {
146 cleanup()
147 return c.fail(protocol.ExitFailure, "import failed: %v", err)
148 }
149
150 branch, err := gitutil.RemoteDefaultBranch(ctx, from, env)
151 if err != nil {
152 branch = "main" // remote gone quiet after the fetch; keep the default
153 }
154 if _, rerr := gitutil.ResolveRef(dir, "refs/heads/"+branch); rerr == nil {
155 gitutil.SetHead(dir, branch)
156 c.Store.UpdateDefaultBranch(id, branch)
157 }
158
159 c.Store.RecordEvent(id, c.User.ID, "repo.imported", fmt.Sprintf(`{"from":%q}`, from))
160 type out struct {
161 Path string `json:"path"`
162 Visibility string `json:"visibility"`
163 DefaultBranch string `json:"default_branch"`
164 }
165 d := out{path, visibility, branch}
166 return c.emit(d, func(w io.Writer) {
167 fmt.Fprintf(w, "imported %s (%s, default %s)\nnote: git data only — issues and pull requests do not transfer\n",
168 d.Path, d.Visibility, d.DefaultBranch)
169 })
170}