1package gitlab
  2
  3import (
  4	"fmt"
  5	"net/url"
  6	"path"
  7	"regexp"
  8	"strconv"
  9	"strings"
 10
 11	"github.com/pkg/errors"
 12	"github.com/xanzy/go-gitlab"
 13
 14	"github.com/MichaelMure/git-bug/bridge/core"
 15	"github.com/MichaelMure/git-bug/bridge/core/auth"
 16	"github.com/MichaelMure/git-bug/cache"
 17	"github.com/MichaelMure/git-bug/input"
 18	"github.com/MichaelMure/git-bug/repository"
 19)
 20
 21var (
 22	ErrBadProjectURL = errors.New("bad project url")
 23)
 24
 25func (g *Gitlab) ValidParams() map[string]interface{} {
 26	return map[string]interface{}{
 27		"URL":        nil,
 28		"BaseURL":    nil,
 29		"Login":      nil,
 30		"CredPrefix": nil,
 31		"TokenRaw":   nil,
 32	}
 33}
 34
 35func (g *Gitlab) Configure(repo *cache.RepoCache, params core.BridgeParams) (core.Configuration, error) {
 36	var err error
 37	var baseUrl string
 38
 39	switch {
 40	case params.BaseURL != "":
 41		baseUrl = params.BaseURL
 42	default:
 43		baseUrl, err = input.PromptDefault("Gitlab server URL", "URL", defaultBaseURL, input.Required, input.IsURL)
 44		if err != nil {
 45			return nil, errors.Wrap(err, "base url prompt")
 46		}
 47	}
 48
 49	var projectURL string
 50
 51	// get project url
 52	switch {
 53	case params.URL != "":
 54		projectURL = params.URL
 55	default:
 56		// terminal prompt
 57		projectURL, err = promptProjectURL(repo, baseUrl)
 58		if err != nil {
 59			return nil, errors.Wrap(err, "url prompt")
 60		}
 61	}
 62
 63	if !strings.HasPrefix(projectURL, params.BaseURL) {
 64		return nil, fmt.Errorf("base URL (%s) doesn't match the project URL (%s)", params.BaseURL, projectURL)
 65	}
 66
 67	var login string
 68	var cred auth.Credential
 69
 70	switch {
 71	case params.CredPrefix != "":
 72		cred, err = auth.LoadWithPrefix(repo, params.CredPrefix)
 73		if err != nil {
 74			return nil, err
 75		}
 76		l, ok := cred.GetMetadata(auth.MetaKeyLogin)
 77		if !ok {
 78			return nil, fmt.Errorf("credential doesn't have a login")
 79		}
 80		login = l
 81	case params.TokenRaw != "":
 82		token := auth.NewToken(target, params.TokenRaw)
 83		login, err = getLoginFromToken(baseUrl, token)
 84		if err != nil {
 85			return nil, err
 86		}
 87		token.SetMetadata(auth.MetaKeyLogin, login)
 88		token.SetMetadata(auth.MetaKeyBaseURL, baseUrl)
 89		cred = token
 90	default:
 91		login := params.Login
 92		if login == "" {
 93			// TODO: validate username
 94			login, err = input.Prompt("Gitlab login", "login", input.Required)
 95			if err != nil {
 96				return nil, err
 97			}
 98		}
 99		cred, err = promptTokenOptions(repo, login, baseUrl)
100		if err != nil {
101			return nil, err
102		}
103	}
104
105	token, ok := cred.(*auth.Token)
106	if !ok {
107		return nil, fmt.Errorf("the Gitlab bridge only handle token credentials")
108	}
109
110	// validate project url and get its ID
111	id, err := validateProjectURL(baseUrl, projectURL, token)
112	if err != nil {
113		return nil, errors.Wrap(err, "project validation")
114	}
115
116	conf := make(core.Configuration)
117	conf[core.ConfigKeyTarget] = target
118	conf[confKeyProjectID] = strconv.Itoa(id)
119	conf[confKeyGitlabBaseUrl] = baseUrl
120
121	err = g.ValidateConfig(conf)
122	if err != nil {
123		return nil, err
124	}
125
126	// don't forget to store the now known valid token
127	if !auth.IdExist(repo, cred.ID()) {
128		err = auth.Store(repo, cred)
129		if err != nil {
130			return nil, err
131		}
132	}
133
134	return conf, core.FinishConfig(repo, metaKeyGitlabLogin, login)
135}
136
137func (g *Gitlab) ValidateConfig(conf core.Configuration) error {
138	if v, ok := conf[core.ConfigKeyTarget]; !ok {
139		return fmt.Errorf("missing %s key", core.ConfigKeyTarget)
140	} else if v != target {
141		return fmt.Errorf("unexpected target name: %v", v)
142	}
143	if _, ok := conf[confKeyGitlabBaseUrl]; !ok {
144		return fmt.Errorf("missing %s key", confKeyGitlabBaseUrl)
145	}
146	if _, ok := conf[confKeyProjectID]; !ok {
147		return fmt.Errorf("missing %s key", confKeyProjectID)
148	}
149
150	return nil
151}
152
153func promptTokenOptions(repo repository.RepoConfig, login, baseUrl string) (auth.Credential, error) {
154	creds, err := auth.List(repo,
155		auth.WithTarget(target),
156		auth.WithKind(auth.KindToken),
157		auth.WithMeta(auth.MetaKeyLogin, login),
158		auth.WithMeta(auth.MetaKeyBaseURL, baseUrl),
159	)
160	if err != nil {
161		return nil, err
162	}
163
164	cred, index, err := input.PromptCredential(target, "token", creds, []string{
165		"enter my token",
166	})
167	switch {
168	case err != nil:
169		return nil, err
170	case cred != nil:
171		return cred, nil
172	case index == 0:
173		return promptToken(baseUrl)
174	default:
175		panic("missed case")
176	}
177}
178
179func promptToken(baseUrl string) (*auth.Token, error) {
180	fmt.Printf("You can generate a new token by visiting %s.\n", path.Join(baseUrl, "profile/personal_access_tokens"))
181	fmt.Println("Choose 'Create personal access token' and set the necessary access scope for your repository.")
182	fmt.Println()
183	fmt.Println("'api' access scope: to be able to make api calls")
184	fmt.Println()
185
186	re := regexp.MustCompile(`^[a-zA-Z0-9\-\_]{20}$`)
187
188	var login string
189
190	validator := func(name string, value string) (complaint string, err error) {
191		if !re.MatchString(value) {
192			return "token has incorrect format", nil
193		}
194		login, err = getLoginFromToken(baseUrl, auth.NewToken(target, value))
195		if err != nil {
196			return fmt.Sprintf("token is invalid: %v", err), nil
197		}
198		return "", nil
199	}
200
201	rawToken, err := input.Prompt("Enter token", "token", input.Required, validator)
202	if err != nil {
203		return nil, err
204	}
205
206	token := auth.NewToken(target, rawToken)
207	token.SetMetadata(auth.MetaKeyLogin, login)
208	token.SetMetadata(auth.MetaKeyBaseURL, baseUrl)
209
210	return token, nil
211}
212
213func promptProjectURL(repo repository.RepoCommon, baseUrl string) (string, error) {
214	validRemotes, err := getValidGitlabRemoteURLs(repo, baseUrl)
215	if err != nil {
216		return "", err
217	}
218
219	return input.PromptURLWithRemote("Gitlab project URL", "URL", validRemotes, input.Required)
220}
221
222func getProjectPath(baseUrl, projectUrl string) (string, error) {
223	cleanUrl := strings.TrimSuffix(projectUrl, ".git")
224	cleanUrl = strings.Replace(cleanUrl, "git@", "https://", 1)
225	objectUrl, err := url.Parse(cleanUrl)
226	if err != nil {
227		return "", ErrBadProjectURL
228	}
229
230	objectBaseUrl, err := url.Parse(baseUrl)
231	if err != nil {
232		return "", ErrBadProjectURL
233	}
234
235	if objectUrl.Hostname() != objectBaseUrl.Hostname() {
236		return "", fmt.Errorf("base url and project url hostnames doesn't match")
237	}
238	return objectUrl.Path[1:], nil
239}
240
241func getValidGitlabRemoteURLs(repo repository.RepoCommon, baseUrl string) ([]string, error) {
242	remotes, err := repo.GetRemotes()
243	if err != nil {
244		return nil, err
245	}
246
247	urls := make([]string, 0, len(remotes))
248	for _, u := range remotes {
249		path, err := getProjectPath(baseUrl, u)
250		if err != nil {
251			continue
252		}
253
254		urls = append(urls, fmt.Sprintf("%s/%s", baseUrl, path))
255	}
256
257	return urls, nil
258}
259
260func validateProjectURL(baseUrl, url string, token *auth.Token) (int, error) {
261	projectPath, err := getProjectPath(baseUrl, url)
262	if err != nil {
263		return 0, err
264	}
265
266	client, err := buildClient(baseUrl, token)
267	if err != nil {
268		return 0, err
269	}
270
271	project, _, err := client.Projects.GetProject(projectPath, &gitlab.GetProjectOptions{})
272	if err != nil {
273		return 0, errors.Wrap(err, "wrong token scope ou non-existent project")
274	}
275
276	return project.ID, nil
277}
278
279func getLoginFromToken(baseUrl string, token *auth.Token) (string, error) {
280	client, err := buildClient(baseUrl, token)
281	if err != nil {
282		return "", err
283	}
284
285	user, _, err := client.Users.CurrentUser()
286	if err != nil {
287		return "", err
288	}
289	if user.Username == "" {
290		return "", fmt.Errorf("gitlab say username is empty")
291	}
292
293	return user.Username, nil
294}