internal/control/import.go

fad7a633f45132422f6648c1c7508b4e19b6539c
gitbay/internal/control/import.go

187 lines · 6643 bytes

  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/gitpin"
 14	"gitbay.org/gitbay/internal/gitutil"
 15	"gitbay.org/gitbay/internal/policy"
 16	"gitbay.org/gitbay/internal/protocol"
 17)
 18
 19func init() {
 20	register(Command{Path: []string{"repo", "import"},
 21		Summary: "server-side mirror of a foreign repository",
 22		Usage:   "repo import <owner/name> --from <url> [--private] [--token-stdin]",
 23		Flags: []Flag{
 24			{"--from", "<url>", "the repository to import", ""},
 25			{"--private", "", "create it private", ""},
 26			{"--token-stdin", "", "read a credential token from stdin", ""},
 27		},
 28		Examples:   []string{"repo import krz/imported --from https://github.com/krz/old.git"},
 29		ReadsStdin: true, Run: runRepoImport})
 30}
 31
 32// askpassScript answers git's credential prompts from the environment, so
 33// the token never appears on a command line or in a URL. Username prompts
 34// get a placeholder (GitHub and GitLab ignore it for token auth).
 35const askpassScript = `#!/bin/sh
 36case "$1" in
 37  Username*) echo "x-access-token" ;;
 38  *)         echo "${GITBAY_IMPORT_TOKEN}" ;;
 39esac
 40`
 41
 42// importLookup resolves an import's host; tests replace it.
 43var importLookup gitpin.Lookup = gitpin.LookupIP
 44
 45func runRepoImport(c *Ctx, args []string) int {
 46	f, err := c.parseArgs(args, flagSpec{Values: []string{"--from"}, Bools: []string{"--private", "--token-stdin"}, MaxPos: 1,
 47		Usage: "repo import <owner/name> --from <url> [--private] [--token-stdin]"})
 48	if err != nil {
 49		return c.fail(protocol.ExitUsage, "%v", err)
 50	}
 51	path, from, private, tokenStdin := f.pos(0), f.Value("--from"), f.Has("--private"), f.Has("--token-stdin")
 52	if path == "" || from == "" {
 53		return c.usage()
 54	}
 55	owner, name, ok := strings.Cut(path, "/")
 56	if !ok {
 57		return c.usage()
 58	}
 59	if err := policy.ValidateName(name); err != nil {
 60		return c.failInput(err)
 61	}
 62	// Same ownership rule as repo create: yourself, or an org you admin.
 63	ownerKind, ownerID := "user", c.User.ID
 64	if owner != c.User.Username {
 65		org, err := c.Store.OrgByName(owner)
 66		if err != nil {
 67			return c.fail(protocol.ExitDenied, "cannot import under %q: not you and not an organization you can see", owner)
 68		}
 69		role, err := c.Store.OrgRole(org.ID, c.User.ID)
 70		if err != nil {
 71			return c.fail(protocol.ExitFailure, "%v", err)
 72		}
 73		if role != "admin" {
 74			return c.fail(protocol.ExitDenied, "only admins of %s can import repositories there", owner)
 75		}
 76		ownerKind, ownerID = "org", org.ID
 77	}
 78	if ownerKind == "user" {
 79		if code := checkRepoQuota(c); code >= 0 {
 80			return code
 81		}
 82	}
 83
 84	// http and https only. git:// has no equivalent of curl's resolve
 85	// list, so its connection cannot be held to a checked address;
 86	// file:// would read the server's filesystem, and ssh:// would use
 87	// the server's own keys.
 88	if !strings.HasPrefix(from, "https://") && !strings.HasPrefix(from, "http://") {
 89		return c.fail(protocol.ExitUsage, "import fetches over http:// and https:// only; use the repository's https:// URL")
 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	if strings.ContainsAny(from, "?#") {
 97		// The URL is logged and recorded; a query could carry a token.
 98		return c.fail(protocol.ExitUsage, "use the plain clone URL, without a query or fragment; credentials go on stdin with --token-stdin, never in the URL")
 99	}
100
101	// Resolve and check the host now and hold git to those addresses,
102	// as mirror sync does (#298).
103	timeout := time.Duration(c.Cfg.Limits.CloneTimeoutSec) * time.Second
104	ctx, cancel := context.WithTimeout(context.Background(), timeout)
105	defer cancel()
106	if err := gitpin.CheckGit(ctx); err != nil {
107		return c.fail(protocol.ExitFailure, "import unavailable: %v", err)
108	}
109	remote, err := gitpin.Resolve(ctx, importLookup, from, c.Cfg.Webhooks.AllowLocal)
110	if err != nil {
111		return c.fail(protocol.ExitFailure, "%v", err)
112	}
113
114	// The token is read from stdin and handed to git via GIT_ASKPASS and
115	// the environment — never argv, never the database, never a log line.
116	env := gitpin.Env(c.Cfg.Server.Root)
117	if tokenStdin {
118		token, err := bufio.NewReader(io.LimitReader(c.Stdin, 4096)).ReadString('\n')
119		if err != nil && err != io.EOF {
120			return c.fail(protocol.ExitFailure, "reading token: %v", err)
121		}
122		token = strings.TrimSpace(token)
123		if token == "" {
124			return c.fail(protocol.ExitUsage, "--token-stdin given but stdin held no token")
125		}
126		askpass := filepath.Join(c.Cfg.Server.Root, "askpass.sh")
127		if err := os.WriteFile(askpass, []byte(askpassScript), 0o700); err != nil {
128			return c.fail(protocol.ExitFailure, "%v", err)
129		}
130		env = append(env, "GIT_ASKPASS="+askpass, "GITBAY_IMPORT_TOKEN="+token)
131	}
132
133	visibility := "public"
134	if private {
135		visibility = "private"
136	}
137	// The early check above fails fast; this one holds the lock across
138	// the insert so a concurrent create cannot slip past the count.
139	repoCreateMu.Lock()
140	if ownerKind == "user" {
141		if code := checkRepoQuota(c); code >= 0 {
142			repoCreateMu.Unlock()
143			return code
144		}
145	}
146	id, err := c.Store.CreateRepo(ownerKind, ownerID, name, visibility)
147	repoCreateMu.Unlock()
148	if err != nil {
149		return c.fail(protocol.ExitFailure, "%v", err)
150	}
151	dir := RepoDir(c.Cfg.Server.Root, owner, name)
152	cleanup := func() {
153		c.Store.DeleteRepo(id)
154		os.RemoveAll(dir)
155	}
156	if err := gitutil.InitBare(dir, "main", HooksDir(c.Cfg.Server.Root)); err != nil {
157		cleanup()
158		return c.fail(protocol.ExitFailure, "%v", err)
159	}
160
161	fmt.Fprintf(c.Stderr, "importing %s into %s ...\n", from, path)
162	if err := gitutil.FetchMirror(ctx, dir, from, c.Stderr, remote.Args(), env); err != nil {
163		cleanup()
164		return c.fail(protocol.ExitFailure, "import failed: %v", err)
165	}
166
167	branch, err := gitutil.RemoteDefaultBranch(ctx, dir, from, remote.Args(), env)
168	if err != nil {
169		branch = "main" // remote gone quiet after the fetch; keep the default
170	}
171	if _, rerr := gitutil.ResolveRef(dir, "refs/heads/"+branch); rerr == nil {
172		gitutil.SetHead(dir, branch)
173		c.Store.UpdateDefaultBranch(id, branch)
174	}
175
176	c.Store.RecordEvent(id, c.User.ID, "repo.imported", fmt.Sprintf(`{"from":%q}`, from))
177	type out struct {
178		Path          string `json:"path"`
179		Visibility    string `json:"visibility"`
180		DefaultBranch string `json:"default_branch"`
181	}
182	d := out{path, visibility, branch}
183	return c.emit(d, func(w io.Writer) {
184		fmt.Fprintf(w, "imported %s (%s, default %s)\nnote: git data only — issues and pull requests do not transfer\n",
185			d.Path, d.Visibility, d.DefaultBranch)
186	})
187}