forked from harness/gitness
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coding.go
334 lines (298 loc) · 9.49 KB
/
coding.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package coding
import (
"crypto/tls"
"fmt"
"net/http"
"strings"
"github.com/drone/drone/model"
"github.com/drone/drone/remote"
"github.com/drone/drone/remote/coding/internal"
"github.com/drone/drone/shared/httputil"
"golang.org/x/net/context"
"golang.org/x/oauth2"
)
const (
defaultURL = "https://coding.net" // Default Coding URL
)
// Opts defines configuration options.
type Opts struct {
URL string // Coding server url.
Client string // Coding oauth client id.
Secret string // Coding oauth client secret.
Scopes []string // Coding oauth scopes.
Machine string // Optional machine name.
Username string // Optional machine account username.
Password string // Optional machine account password.
SkipVerify bool // Skip ssl verification.
}
// New returns a Remote implementation that integrates with a Coding Platform or
// Coding Enterprise version control hosting provider.
func New(opts Opts) (remote.Remote, error) {
remote := &Coding{
URL: defaultURL,
Client: opts.Client,
Secret: opts.Secret,
Scopes: opts.Scopes,
Machine: opts.Machine,
Username: opts.Username,
Password: opts.Password,
SkipVerify: opts.SkipVerify,
}
if opts.URL != defaultURL {
remote.URL = strings.TrimSuffix(opts.URL, "/")
}
// Hack to enable oauth2 access in coding's implementation
oauth2.RegisterBrokenAuthHeaderProvider(remote.URL)
return remote, nil
}
type Coding struct {
URL string
Client string
Secret string
Scopes []string
Machine string
Username string
Password string
SkipVerify bool
}
// Login authenticates the session and returns the
// remote user details.
func (c *Coding) Login(res http.ResponseWriter, req *http.Request) (*model.User, error) {
config := c.newConfig(httputil.GetURL(req))
// get the OAuth errors
if err := req.FormValue("error"); err != "" {
return nil, &remote.AuthError{
Err: err,
Description: req.FormValue("error_description"),
URI: req.FormValue("error_uri"),
}
}
// get the OAuth code
code := req.FormValue("code")
if len(code) == 0 {
http.Redirect(res, req, config.AuthCodeURL("drone"), http.StatusSeeOther)
return nil, nil
}
token, err := config.Exchange(c.newContext(), code)
if err != nil {
return nil, err
}
user, err := c.newClientToken(token.AccessToken, token.RefreshToken).GetCurrentUser()
if err != nil {
return nil, err
}
return &model.User{
Login: user.GlobalKey,
Email: user.Email,
Token: token.AccessToken,
Secret: token.RefreshToken,
Expiry: token.Expiry.UTC().Unix(),
Avatar: c.resourceLink(user.Avatar),
}, nil
}
// Auth authenticates the session and returns the remote user
// login for the given token and secret
func (c *Coding) Auth(token, secret string) (string, error) {
user, err := c.newClientToken(token, secret).GetCurrentUser()
if err != nil {
return "", err
}
return user.GlobalKey, nil
}
// Refresh refreshes an oauth token and expiration for the given
// user. It returns true if the token was refreshed, false if the
// token was not refreshed, and error if it failed to refersh.
func (c *Coding) Refresh(u *model.User) (bool, error) {
config := c.newConfig("")
source := config.TokenSource(c.newContext(), &oauth2.Token{RefreshToken: u.Secret})
token, err := source.Token()
if err != nil || len(token.AccessToken) == 0 {
return false, err
}
u.Token = token.AccessToken
u.Secret = token.RefreshToken
u.Expiry = token.Expiry.UTC().Unix()
return true, nil
}
// Teams fetches a list of team memberships from the remote system.
func (c *Coding) Teams(u *model.User) ([]*model.Team, error) {
// EMPTY: not implemented in Coding OAuth API
return nil, nil
}
// TeamPerm fetches the named organization permissions from
// the remote system for the specified user.
func (c *Coding) TeamPerm(u *model.User, org string) (*model.Perm, error) {
// EMPTY: not implemented in Coding OAuth API
return nil, nil
}
// Repo fetches the named repository from the remote system.
func (c *Coding) Repo(u *model.User, owner, repo string) (*model.Repo, error) {
project, err := c.newClient(u).GetProject(owner, repo)
if err != nil {
return nil, err
}
depot, err := c.newClient(u).GetDepot(owner, repo)
if err != nil {
return nil, err
}
return &model.Repo{
Owner: project.Owner,
Name: project.Name,
FullName: projectFullName(project.Owner, project.Name),
Avatar: c.resourceLink(project.Icon),
Link: c.resourceLink(project.DepotPath),
Kind: model.RepoGit,
Clone: project.HttpsURL,
Branch: depot.DefaultBranch,
IsPrivate: !project.IsPublic,
}, nil
}
// Repos fetches a list of repos from the remote system.
func (c *Coding) Repos(u *model.User) ([]*model.Repo, error) {
projectList, err := c.newClient(u).GetProjectList()
if err != nil {
return nil, err
}
repos := make([]*model.Repo, 0)
for _, project := range projectList {
depot, err := c.newClient(u).GetDepot(project.Owner, project.Name)
if err != nil {
return nil, err
}
repo := &model.Repo{
Owner: project.Owner,
Name: project.Name,
FullName: projectFullName(project.Owner, project.Name),
Avatar: c.resourceLink(project.Icon),
Link: c.resourceLink(project.DepotPath),
Kind: model.RepoGit,
Clone: project.HttpsURL,
Branch: depot.DefaultBranch,
IsPrivate: !project.IsPublic,
}
repos = append(repos, repo)
}
return repos, nil
}
// Perm fetches the named repository permissions from
// the remote system for the specified user.
func (c *Coding) Perm(u *model.User, owner, repo string) (*model.Perm, error) {
project, err := c.newClient(u).GetProject(owner, repo)
if err != nil {
return nil, err
}
if project.Role == "owner" || project.Role == "admin" {
return &model.Perm{Pull: true, Push: true, Admin: true}, nil
}
if project.Role == "member" {
return &model.Perm{Pull: true, Push: true, Admin: false}, nil
}
return &model.Perm{Pull: false, Push: false, Admin: false}, nil
}
// File fetches a file from the remote repository and returns in string
// format.
func (c *Coding) File(u *model.User, r *model.Repo, b *model.Build, f string) ([]byte, error) {
data, err := c.newClient(u).GetFile(r.Owner, r.Name, b.Commit, f)
if err != nil {
return nil, err
}
return data, nil
}
// FileRef fetches a file from the remote repository for the given ref
// and returns in string format.
func (c *Coding) FileRef(u *model.User, r *model.Repo, ref, f string) ([]byte, error) {
data, err := c.newClient(u).GetFile(r.Owner, r.Name, ref, f)
if err != nil {
return nil, err
}
return data, nil
}
// Status sends the commit status to the remote system.
func (c *Coding) Status(u *model.User, r *model.Repo, b *model.Build, link string) error {
// EMPTY: not implemented in Coding OAuth API
return nil
}
// Netrc returns a .netrc file that can be used to clone
// private repositories from a remote system.
func (c *Coding) Netrc(u *model.User, r *model.Repo) (*model.Netrc, error) {
if c.Password != "" {
return &model.Netrc{
Login: c.Username,
Password: c.Password,
Machine: c.Machine,
}, nil
}
return &model.Netrc{
Login: u.Token,
Password: "x-oauth-basic",
Machine: c.Machine,
}, nil
}
// Activate activates a repository by creating the post-commit hook.
func (c *Coding) Activate(u *model.User, r *model.Repo, link string) error {
return c.newClient(u).AddWebhook(r.Owner, r.Name, link)
}
// Deactivate deactivates a repository by removing all previously created
// post-commit hooks matching the given link.
func (c *Coding) Deactivate(u *model.User, r *model.Repo, link string) error {
return c.newClient(u).RemoveWebhook(r.Owner, r.Name, link)
}
// Hook parses the post-commit hook from the Request body and returns the
// required data in a standard format.
func (c *Coding) Hook(r *http.Request) (*model.Repo, *model.Build, error) {
repo, build, err := parseHook(r)
if build != nil {
build.Avatar = c.resourceLink(build.Avatar)
}
return repo, build, err
}
// helper function to return the Coding oauth2 context using an HTTPClient that
// disables TLS verification if disabled in the remote settings.
func (c *Coding) newContext() context.Context {
if !c.SkipVerify {
return oauth2.NoContext
}
return context.WithValue(nil, oauth2.HTTPClient, &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
})
}
// helper function to return the Coding oauth2 config
func (c *Coding) newConfig(redirect string) *oauth2.Config {
return &oauth2.Config{
ClientID: c.Client,
ClientSecret: c.Secret,
Scopes: []string{strings.Join(c.Scopes, ",")},
Endpoint: oauth2.Endpoint{
AuthURL: fmt.Sprintf("%s/oauth_authorize.html", c.URL),
TokenURL: fmt.Sprintf("%s/api/oauth/access_token_v2", c.URL),
},
RedirectURL: fmt.Sprintf("%s/authorize", redirect),
}
}
// helper function to return the Coding oauth2 client
func (c *Coding) newClient(u *model.User) *internal.Client {
return c.newClientToken(u.Token, u.Secret)
}
// helper function to return the Coding oauth2 client
func (c *Coding) newClientToken(token, secret string) *internal.Client {
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: c.SkipVerify,
},
},
}
return internal.NewClient(c.URL, "/api", token, "drone", client)
}
func (c *Coding) resourceLink(resourcePath string) string {
if strings.HasPrefix(resourcePath, "http") {
return resourcePath
}
return c.URL + resourcePath
}