-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathgithub.go
363 lines (293 loc) · 9.82 KB
/
github.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package auth
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"strconv"
"golang.org/x/crypto/ssh"
"github.com/taubyte/tau/services/auth/github"
"github.com/taubyte/tau/services/auth/hooks"
"github.com/taubyte/tau/services/auth/repositories"
"github.com/taubyte/utils/id"
)
// ref: https://github.com/keybase/bot-sshca/blob/master/src/keybaseca/sshutils/generate.go#L53
func generateKey() (string, string, string, error) {
_privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return "", "", "", err
}
privateKey, err := x509.MarshalECPrivateKey(_privateKey)
if err != nil {
return "", "", "", err
}
privateKeyPEM := &pem.Block{Type: "EC PRIVATE KEY", Bytes: privateKey}
var private bytes.Buffer
if err := pem.Encode(&private, privateKeyPEM); err != nil {
return "", "", "", err
}
pub, err := ssh.NewPublicKey(&_privateKey.PublicKey)
if err != nil {
return "", "", "", err
}
return deployKeyName, string(ssh.MarshalAuthorizedKey(pub)), private.String(), nil
}
func (srv *AuthService) registerGitHubRepository(ctx context.Context, client *github.Client, repoID string) (map[string]interface{}, error) {
err := client.GetByID(repoID)
if err != nil {
return nil, fmt.Errorf("fetch repository failed with %w", err)
}
repoKey := fmt.Sprintf("/repositories/github/%s/key", repoID)
// Re-register a repo should be fine. Could be needed if deploy keys were deleted for example
hook_id := id.Generate(repoKey)
defaultHookName := "taubyte_push_hook"
defaultGithubHookUrl := srv.webHookUrl + "/github/" + hook_id
var (
hook_githubid int64
secret string
)
if !srv.devMode {
hook_githubid, secret, err = client.CreatePushHook(&defaultHookName, &defaultGithubHookUrl, srv.devMode)
if err != nil {
return nil, fmt.Errorf("create push hook failed with: %s", err)
}
}
kname, kpub, kpriv, err := generateKey()
if err != nil {
return nil, fmt.Errorf("generate key failed with: %s", err)
}
// Dreamland also needs to create a deplyment key. TODO: use a pre-set key
err = client.CreateDeployKey(&kname, &kpub)
if err != nil {
return nil, fmt.Errorf("create deploy key failed with: %s", err)
}
_repo_id, err := strconv.ParseInt(repoID, 10, 64)
if err != nil {
return nil, fmt.Errorf("parse repoId failed with: %s", err)
}
repo, err := repositories.New(srv.KV(), repositories.Data{
"id": _repo_id,
"provider": "github",
"key": kpriv,
})
if err != nil {
return nil, fmt.Errorf("new repository failed with %s", err)
}
err = repo.Register(ctx)
if err != nil {
return nil, err
}
hook, err := hooks.New(srv.KV(), hooks.Data{
"id": hook_id,
"provider": "github",
"github_id": hook_githubid,
"repository": _repo_id,
"secret": secret,
})
if err != nil {
return nil, fmt.Errorf("hooks new failed with: %s", err)
}
err = hook.Register(ctx)
if err != nil {
return nil, fmt.Errorf("hooks register failed with: %s", err)
}
_repo, err := client.GetCurrentRepository()
if err != nil {
return nil, fmt.Errorf("get current repository failed with: %s", err)
}
repoInfo := make(map[string]string, 0)
if _repo.SSHURL != nil {
repoInfo["ssh"] = *_repo.SSHURL
}
if _repo.FullName != nil {
repoInfo["fullname"] = *_repo.FullName
}
//TODO add more items to the repoInfo that we are pushing to tns
err = srv.tnsClient.Push([]string{"resolve", "repo", "github", fmt.Sprintf("%d", _repo_id)}, repoInfo)
if err != nil {
return nil, fmt.Errorf("failed registering new job repo %d into tns with error: %v", _repo_id, err)
}
return map[string]interface{}{
"key": repoKey,
}, nil
}
func (srv *AuthService) unregisterGitHubRepository(ctx context.Context, client *github.Client, repoID string) (map[string]interface{}, error) {
// select repo
err := client.GetByID(repoID)
if err != nil {
return nil, fmt.Errorf("fetch repository failed with %w", err)
}
repoKey := fmt.Sprintf("/repositories/github/%s/key", repoID)
kpriv, err := srv.db.Get(ctx, repoKey)
if err != nil {
return nil, fmt.Errorf("repository `%s` (%s) not registred! err = %w", repoID, repoKey, err)
}
_repo_id, err := strconv.ParseInt(repoID, 10, 64)
if err != nil {
return nil, err
}
repo, err := repositories.New(srv.KV(), repositories.Data{
"id": _repo_id,
"provider": "github",
"key": string(kpriv),
})
if err != nil {
return nil, err
}
for _, hook := range repo.Hooks(ctx) {
// skip any error trying to delete the hook for now
hook.Delete(ctx)
}
repo.Delete(ctx)
if err != nil {
return nil, err
}
return nil, nil
}
func (srv *AuthService) newGitHubProject(ctx context.Context, client *github.Client, projectID, projectName, configID, codeID string) (map[string]interface{}, error) {
response := make(map[string]interface{})
logger.Debug("Creating project " + projectName)
logger.Debug("Project ID=" + projectID)
response["project"] = map[string]string{"id": projectID, "name": projectName}
gituser := client.Me()
project_key := "/projects/" + projectID
err := srv.db.Put(ctx, project_key+"/name", []byte(projectName))
if err != nil {
return nil, err
}
if err = srv.db.Put(ctx, project_key+"/repositories/provider", []byte("github")); err != nil {
return nil, err
}
err = srv.db.Put(ctx, project_key+"/owners/"+fmt.Sprintf("%d", *(gituser.ID)), []byte(gituser.GetLogin()))
if err != nil {
return nil, err
}
err = srv.db.Put(ctx, "/projects/"+projectID+"/repositories/config", []byte(configID))
if err != nil {
return nil, err
}
repo_key := fmt.Sprintf("/repositories/github/%s", configID)
if err = srv.db.Put(ctx, repo_key+"/project", []byte(projectID)); err != nil {
return nil, err
}
err = srv.db.Put(ctx, "/projects/"+projectID+"/repositories/code", []byte(codeID))
if err != nil {
return nil, err
}
repo_key = fmt.Sprintf("/repositories/github/%s", codeID)
if err = srv.db.Put(ctx, repo_key+"/project", []byte(projectID)); err != nil {
return nil, err
}
logger.Debugf("Project Add returned %v", response)
return response, nil
}
func (srv *AuthService) getGitHubUserRepositories(ctx context.Context, client *github.Client) (map[string]interface{}, error) {
response := make(map[string]interface{})
repos := client.ListMyRepos()
logger.Debugf("User repos:%v", repos)
user_repos := make(map[string]interface{}, 0)
for repo_id := range repos {
repo_key := fmt.Sprintf("/repositories/github/%s/name", repo_id)
v, err := srv.db.Get(ctx, repo_key)
if err == nil && len(v) > 0 {
logger.Debugf("Check %s got %s", repo_key, string(v))
user_repos[repo_id] = map[string]interface{}{
"id": repo_id,
"name": string(v),
}
}
}
logger.Debugf("getGitHubProjects: extracted %s", user_repos)
response["repositories"] = user_repos
return response, nil
}
func (srv *AuthService) getGitHubUserProjects(ctx context.Context, client *github.Client) (map[string]interface{}, error) {
response := make(map[string]interface{})
user_projects := make(map[string]interface{}, 0)
for repo_id := range client.ListMyRepos() {
repo_key := fmt.Sprintf("/repositories/github/%s/project", repo_id)
v, err := srv.db.Get(ctx, repo_key)
if err == nil && len(v) > 0 {
project_id := string(v)
proj_name_key := fmt.Sprintf("/projects/%s/name", project_id)
proj_name, err := srv.db.Get(ctx, proj_name_key)
if err == nil {
if _, ok := user_projects[project_id]; !ok {
user_projects[project_id] = map[string]interface{}{
"id": project_id,
"name": string(proj_name),
}
}
}
}
}
logger.Debug(user_projects)
response["projects"] = getMapValues(user_projects)
return response, nil
}
func (srv *AuthService) getGitHubProjectInfo(ctx context.Context, client *github.Client, projectid string) (map[string]interface{}, error) {
response := make(map[string]interface{})
proj_prefix_key := fmt.Sprintf("/projects/%s/", projectid)
proj_name, err := srv.db.Get(ctx, proj_prefix_key+"name")
if err != nil {
response["error"] = "Retreiving project error: " + err.Error()
return response, nil
}
proj_gitprovider, err := srv.db.Get(ctx, proj_prefix_key+"repositories/provider")
if err != nil {
response["error"] = "Retreiving project error: " + err.Error()
return response, nil
}
proj_config_repo, err := srv.db.Get(ctx, proj_prefix_key+"repositories/config")
if err != nil {
response["error"] = "Retreiving project error: " + err.Error()
return response, nil
}
proj_code_repo, err := srv.db.Get(ctx, proj_prefix_key+"repositories/code")
if err != nil {
response["error"] = "Retreiving project error: " + err.Error()
return response, nil
}
response["project"] = map[string]interface{}{
"id": projectid,
"name": string(proj_name),
"repositories": map[string]interface{}{
"provider": string(proj_gitprovider),
"configuration": client.ShortRepositoryInfo(string(proj_config_repo)),
"code": client.ShortRepositoryInfo(string(proj_code_repo)),
},
}
return response, nil
}
func (srv *AuthService) deleteGitHubUserProject(ctx context.Context, client *github.Client, projectid string) (map[string]interface{}, error) {
response := make(map[string]interface{})
proj_prefix_key := fmt.Sprintf("/projects/%s/", projectid)
c, err := srv.db.ListAsync(ctx, proj_prefix_key)
if err != nil {
response["error"] = "Retreiving project error: " + err.Error()
return response, nil
}
for entry := range c {
srv.db.Delete(ctx, entry)
}
response["project"] = map[string]interface{}{
"id": projectid,
"status": "deleted",
}
return response, nil
}
func (srv *AuthService) getGitHubUser(client *github.Client) (map[string]interface{}, error) {
response := make(map[string]interface{})
gituser := client.Me()
response["user"] = map[string]interface{}{
"name": gituser.GetName(),
"company": gituser.GetCompany(),
"email": gituser.GetEmail(),
"login": gituser.GetLogin(),
}
return response, nil
}