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, err := regexp.Compile(`^[a-zA-Z0-9\-\_]{20}$`)
187 if err != nil {
188 panic("regexp compile:" + err.Error())
189 }
190
191 var login string
192
193 validator := func(name string, value string) (complaint string, err error) {
194 if !re.MatchString(value) {
195 return "token has incorrect format", nil
196 }
197 login, err = getLoginFromToken(baseUrl, auth.NewToken(target, value))
198 if err != nil {
199 return fmt.Sprintf("token is invalid: %v", err), nil
200 }
201 return "", nil
202 }
203
204 rawToken, err := input.Prompt("Enter token", "token", input.Required, validator)
205 if err != nil {
206 return nil, err
207 }
208
209 token := auth.NewToken(target, rawToken)
210 token.SetMetadata(auth.MetaKeyLogin, login)
211 token.SetMetadata(auth.MetaKeyBaseURL, baseUrl)
212
213 return token, nil
214}
215
216func promptProjectURL(repo repository.RepoCommon, baseUrl string) (string, error) {
217 validRemotes, err := getValidGitlabRemoteURLs(repo, baseUrl)
218 if err != nil {
219 return "", err
220 }
221
222 return input.PromptURLWithRemote("Gitlab project URL", "URL", validRemotes, input.Required)
223}
224
225func getProjectPath(baseUrl, projectUrl string) (string, error) {
226 cleanUrl := strings.TrimSuffix(projectUrl, ".git")
227 cleanUrl = strings.Replace(cleanUrl, "git@", "https://", 1)
228 objectUrl, err := url.Parse(cleanUrl)
229 if err != nil {
230 return "", ErrBadProjectURL
231 }
232
233 objectBaseUrl, err := url.Parse(baseUrl)
234 if err != nil {
235 return "", ErrBadProjectURL
236 }
237
238 if objectUrl.Hostname() != objectBaseUrl.Hostname() {
239 return "", fmt.Errorf("base url and project url hostnames doesn't match")
240 }
241 return objectUrl.Path[1:], nil
242}
243
244func getValidGitlabRemoteURLs(repo repository.RepoCommon, baseUrl string) ([]string, error) {
245 remotes, err := repo.GetRemotes()
246 if err != nil {
247 return nil, err
248 }
249
250 urls := make([]string, 0, len(remotes))
251 for _, u := range remotes {
252 path, err := getProjectPath(baseUrl, u)
253 if err != nil {
254 continue
255 }
256
257 urls = append(urls, fmt.Sprintf("%s/%s", baseUrl, path))
258 }
259
260 return urls, nil
261}
262
263func validateProjectURL(baseUrl, url string, token *auth.Token) (int, error) {
264 projectPath, err := getProjectPath(baseUrl, url)
265 if err != nil {
266 return 0, err
267 }
268
269 client, err := buildClient(baseUrl, token)
270 if err != nil {
271 return 0, err
272 }
273
274 project, _, err := client.Projects.GetProject(projectPath, &gitlab.GetProjectOptions{})
275 if err != nil {
276 return 0, errors.Wrap(err, "wrong token scope ou non-existent project")
277 }
278
279 return project.ID, nil
280}
281
282func getLoginFromToken(baseUrl string, token *auth.Token) (string, error) {
283 client, err := buildClient(baseUrl, token)
284 if err != nil {
285 return "", err
286 }
287
288 user, _, err := client.Users.CurrentUser()
289 if err != nil {
290 return "", err
291 }
292 if user.Username == "" {
293 return "", fmt.Errorf("gitlab say username is empty")
294 }
295
296 return user.Username, nil
297}