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 conf[confKeyDefaultLogin] = login
121
122 err = g.ValidateConfig(conf)
123 if err != nil {
124 return nil, err
125 }
126
127 // don't forget to store the now known valid token
128 if !auth.IdExist(repo, cred.ID()) {
129 err = auth.Store(repo, cred)
130 if err != nil {
131 return nil, err
132 }
133 }
134
135 return conf, core.FinishConfig(repo, metaKeyGitlabLogin, login)
136}
137
138func (g *Gitlab) ValidateConfig(conf core.Configuration) error {
139 if v, ok := conf[core.ConfigKeyTarget]; !ok {
140 return fmt.Errorf("missing %s key", core.ConfigKeyTarget)
141 } else if v != target {
142 return fmt.Errorf("unexpected target name: %v", v)
143 }
144 if _, ok := conf[confKeyGitlabBaseUrl]; !ok {
145 return fmt.Errorf("missing %s key", confKeyGitlabBaseUrl)
146 }
147 if _, ok := conf[confKeyProjectID]; !ok {
148 return fmt.Errorf("missing %s key", confKeyProjectID)
149 }
150 if _, ok := conf[confKeyDefaultLogin]; !ok {
151 return fmt.Errorf("missing %s key", confKeyDefaultLogin)
152 }
153
154 return nil
155}
156
157func promptTokenOptions(repo repository.RepoConfig, login, baseUrl string) (auth.Credential, error) {
158 creds, err := auth.List(repo,
159 auth.WithTarget(target),
160 auth.WithKind(auth.KindToken),
161 auth.WithMeta(auth.MetaKeyLogin, login),
162 auth.WithMeta(auth.MetaKeyBaseURL, baseUrl),
163 )
164 if err != nil {
165 return nil, err
166 }
167
168 cred, index, err := input.PromptCredential(target, "token", creds, []string{
169 "enter my token",
170 })
171 switch {
172 case err != nil:
173 return nil, err
174 case cred != nil:
175 return cred, nil
176 case index == 0:
177 return promptToken(baseUrl)
178 default:
179 panic("missed case")
180 }
181}
182
183func promptToken(baseUrl string) (*auth.Token, error) {
184 fmt.Printf("You can generate a new token by visiting %s.\n", path.Join(baseUrl, "profile/personal_access_tokens"))
185 fmt.Println("Choose 'Create personal access token' and set the necessary access scope for your repository.")
186 fmt.Println()
187 fmt.Println("'api' access scope: to be able to make api calls")
188 fmt.Println()
189
190 re := regexp.MustCompile(`^[a-zA-Z0-9\-\_]{20}$`)
191
192 var login string
193
194 validator := func(name string, value string) (complaint string, err error) {
195 if !re.MatchString(value) {
196 return "token has incorrect format", nil
197 }
198 login, err = getLoginFromToken(baseUrl, auth.NewToken(target, value))
199 if err != nil {
200 return fmt.Sprintf("token is invalid: %v", err), nil
201 }
202 return "", nil
203 }
204
205 rawToken, err := input.Prompt("Enter token", "token", input.Required, validator)
206 if err != nil {
207 return nil, err
208 }
209
210 token := auth.NewToken(target, rawToken)
211 token.SetMetadata(auth.MetaKeyLogin, login)
212 token.SetMetadata(auth.MetaKeyBaseURL, baseUrl)
213
214 return token, nil
215}
216
217func promptProjectURL(repo repository.RepoCommon, baseUrl string) (string, error) {
218 validRemotes, err := getValidGitlabRemoteURLs(repo, baseUrl)
219 if err != nil {
220 return "", err
221 }
222
223 return input.PromptURLWithRemote("Gitlab project URL", "URL", validRemotes, input.Required)
224}
225
226func getProjectPath(baseUrl, projectUrl string) (string, error) {
227 cleanUrl := strings.TrimSuffix(projectUrl, ".git")
228 cleanUrl = strings.Replace(cleanUrl, "git@", "https://", 1)
229 objectUrl, err := url.Parse(cleanUrl)
230 if err != nil {
231 return "", ErrBadProjectURL
232 }
233
234 objectBaseUrl, err := url.Parse(baseUrl)
235 if err != nil {
236 return "", ErrBadProjectURL
237 }
238
239 if objectUrl.Hostname() != objectBaseUrl.Hostname() {
240 return "", fmt.Errorf("base url and project url hostnames doesn't match")
241 }
242 return objectUrl.Path[1:], nil
243}
244
245func getValidGitlabRemoteURLs(repo repository.RepoCommon, baseUrl string) ([]string, error) {
246 remotes, err := repo.GetRemotes()
247 if err != nil {
248 return nil, err
249 }
250
251 urls := make([]string, 0, len(remotes))
252 for _, u := range remotes {
253 p, err := getProjectPath(baseUrl, u)
254 if err != nil {
255 continue
256 }
257
258 urls = append(urls, fmt.Sprintf("%s/%s", baseUrl, p))
259 }
260
261 return urls, nil
262}
263
264func validateProjectURL(baseUrl, url string, token *auth.Token) (int, error) {
265 projectPath, err := getProjectPath(baseUrl, url)
266 if err != nil {
267 return 0, err
268 }
269
270 client, err := buildClient(baseUrl, token)
271 if err != nil {
272 return 0, err
273 }
274
275 project, _, err := client.Projects.GetProject(projectPath, &gitlab.GetProjectOptions{})
276 if err != nil {
277 return 0, errors.Wrap(err, "wrong token scope ou non-existent project")
278 }
279
280 return project.ID, nil
281}
282
283func getLoginFromToken(baseUrl string, token *auth.Token) (string, error) {
284 client, err := buildClient(baseUrl, token)
285 if err != nil {
286 return "", err
287 }
288
289 user, _, err := client.Users.CurrentUser()
290 if err != nil {
291 return "", err
292 }
293 if user.Username == "" {
294 return "", fmt.Errorf("gitlab say username is empty")
295 }
296
297 return user.Username, nil
298}