~sircmpwn/git.sr.ht

git.sr.ht/gitsrht-update-hook/submitter.go -rw-r--r-- 10.0 KiB
5c21171dDrew DeVault API: Implement mutation { deleteArtifact } 22 hours ago
                                                                                
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"path"
	"strings"
	"unicode/utf8"

	"github.com/danwakefield/fnmatch"
	"github.com/fernet/fernet-go"
	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/filemode"
	"github.com/go-git/go-git/v5/plumbing/object"
	"github.com/pkg/errors"
)

var (
	fernetKey *fernet.Key
	clientId  string
)

// TODO: Consider moving Fernet code to a shared SourceHut Go module
func initSubmitter() {
	netkey, ok := config.Get("sr.ht", "network-key")
	if !ok {
		logger.Fatal("Configuration error: [sr.ht].network-key missing")
	}
	var err error
	fernetKey, err = fernet.DecodeKey(netkey)
	if err != nil {
		logger.Fatalf("Error decoding [sr.ht].network-key: %v", err)
	}
	clientId, ok = config.Get("git.sr.ht", "oauth-client-id")
	if !ok {
		logger.Fatal("Configuration error: [git.sr.ht].oauth-client-id missing")
	}
}

type InternalRequestAuthorization struct {
	ClientId string `json:"client_id"`
	Username string `json:"username"`
}

type BuildSubmitter interface {
	// Return a list of build manifests and their names
	FindManifests() (map[string]string, error)
	// Get builds.sr.ht origin
	GetBuildsOrigin() string
	// Get builds.sr.ht OAuth token
	GetOauthToken() *string
	// Get a checkout-able string to append to matching source URLs
	GetCommitId() string
	// Get the build note which corresponds to this commit
	GetCommitNote() string
	// Get the clone URL for this repository
	GetCloneUrl() string
	// Get the name of the repository
	GetRepoName() string
	// Get the name of the repository owner
	GetOwnerName() string
}

// SQL notes
//
// We need:
// - The repo ID
// - The repo name & visibility
// - The owner's username & canonical name
// - The owner's OAuth token & scopes
// - A list of affected webhooks
type GitBuildSubmitter struct {
	BuildOrigin string
	Commit      *object.Commit
	GitOrigin   string
	OwnerName   string
	OwnerToken  *string
	RepoName    string
	Repository  *git.Repository
	Visibility  string
}

func (submitter GitBuildSubmitter) FindManifests() (map[string]string, error) {
	rootTree, err := submitter.Repository.TreeObject(submitter.Commit.TreeHash)
	if err != nil {
		return nil, errors.Wrap(err, "root tree lookup failed")
	}

	var files []*object.File
	loadOptions()
	pattern := ".build.yml,.builds/*.yml"
	if pat, ok := options["submit"]; ok {
		pattern = pat
	}
	for _, pat := range strings.Split(pattern, ",") {
		// If exact match: get to the blob directly
		// Otherwise:      find the longest prefix and start walking from there

		asterisk := strings.Index(pat, "*")
		isWildcard := asterisk != -1
		if !isWildcard {
			file, err := rootTree.File(pat)
			if err != nil && err != object.ErrFileNotFound {
				return nil, errors.Wrap(err, "getting file")
			}
			if file != nil {
				files = append(files, file)
			}
		} else {
			var tree *object.Tree
			var prefix string
			for strings.HasPrefix(pat, "/") {
				pat = pat[1:]
			}
			if pref := strings.LastIndex(pat, "/"); pref != -1 {
				tree, err = rootTree.Tree(pat[:pref])
				if err != nil && err != object.ErrDirectoryNotFound {
					return nil, errors.Wrap(err, "getting pref tree")
				}
				prefix = pat[:pref+1]
				pat = pat[pref+1:]
			} else {
				tree = rootTree
			}
			if tree == nil {
				continue
			}

			traversal := object.NewTreeWalker(tree, true, make(map[plumbing.Hash]bool))
			defer traversal.Close()
			for {
				name, entry, err := traversal.Next()
				if err == io.EOF {
					break
				} else if err != nil {
					return nil, errors.Wrap(err, "iterating worktree")
				}

				if fnmatch.Match(pat, name, fnmatch.FNM_PATHNAME) {
					if entry.Mode == filemode.Dir || entry.Mode == filemode.Submodule {
						continue // Match iteration behaviour of subtree.Files()
					}

					file, err := tree.TreeEntryFile(&entry)
					if file == nil || err != nil {
						return nil, errors.Wrap(err, "getting file for entry")
					}

					file.Name = prefix + file.Name
					files = append(files, file)
				}
			}
		}
	}

	manifests := make(map[string]string)
	for _, file := range files {
		basename := path.Base(file.Name)
		if _, ok := manifests[basename]; ok {
			log.Printf("Not submitting duplicate manifest %s [%s]\n", file.Name, basename)
			continue
		}

		var (
			reader  io.Reader
			content []byte
		)
		if reader, err = file.Reader(); err != nil {
			return nil, errors.Wrapf(err, "creating reader for %s", file.Name)
		}
		if content, err = ioutil.ReadAll(reader); err != nil {
			return nil, errors.Wrap(err, "reading build manifest")
		}
		if !utf8.Valid(content) {
			return nil, errors.Wrap(err, "manifest is not valid UTF-8 file")
		}
		manifests[basename] = string(content)
	}
	return manifests, nil
}

func (submitter GitBuildSubmitter) GetBuildsOrigin() string {
	return submitter.BuildOrigin
}

func (submitter GitBuildSubmitter) GetOauthToken() *string {
	return submitter.OwnerToken
}

func (submitter GitBuildSubmitter) GetCommitId() string {
	return submitter.Commit.Hash.String()
}

func firstLine(text string) string {
	buf := bytes.NewBufferString(text)
	scanner := bufio.NewScanner(buf)
	if !scanner.Scan() {
		return ""
	}
	return scanner.Text()
}

// via https://github.com/openconfig/goyang, Apache 2.0
func indent(indent, s string) string {
	if indent == "" || s == "" {
		return s
	}
	lines := strings.SplitAfter(s, "\n")
	if len(lines[len(lines)-1]) == 0 {
		lines = lines[:len(lines)-1]
	}
	return strings.Join(append([]string{""}, lines...), indent)
}

func (submitter GitBuildSubmitter) GetCommitNote() string {
	commitUrl := fmt.Sprintf("%s/~%s/%s/commit/%s", submitter.GitOrigin,
		submitter.OwnerName, submitter.RepoName,
		submitter.GetCommitId())
	return fmt.Sprintf("[%s][0] — [%s][1]\n\n%s\n\n[0]: %s\n[1]: mailto:%s",
		submitter.GetCommitId()[:7],
		submitter.Commit.Author.Name,
		indent("    ", firstLine(submitter.Commit.Message)),
		commitUrl, submitter.Commit.Author.Email)
}

func (submitter GitBuildSubmitter) GetCloneUrl() string {
	if submitter.Visibility == "private" {
		origin := strings.ReplaceAll(submitter.GitOrigin, "http://", "")
		origin = strings.ReplaceAll(origin, "https://", "")
		// Use SSH URL
		git_user, ok := config.Get("git.sr.ht::dispatch", "/usr/bin/gitsrht-keys")
		if !ok {
			git_user = "git:git"
		}
		git_user = strings.Split(git_user, ":")[0]
		return fmt.Sprintf("git+ssh://%s@%s/~%s/%s", git_user, origin,
			submitter.OwnerName, submitter.RepoName)
	} else {
		// Use HTTP(s) URL
		return fmt.Sprintf("%s/~%s/%s", submitter.GitOrigin,
			submitter.OwnerName, submitter.RepoName)
	}
}

func (submitter GitBuildSubmitter) GetRepoName() string {
	return submitter.RepoName
}

func (submitter GitBuildSubmitter) GetOwnerName() string {
	return submitter.OwnerName
}

type BuildSubmission struct {
	// TODO: Move errors into this struct and set up per-submission error
	// tracking
	Name     string
	Response string
	Url      string
}

func configureRequestAuthorization(submitter BuildSubmitter,
	req *http.Request) {

	auth := InternalRequestAuthorization{
		ClientId: clientId,
		Username: submitter.GetOwnerName(),
	}
	authPayload, err := json.Marshal(&auth)
	if err != nil {
		logger.Fatalf("Failed to marshal internal authorization: %v", err)
	}
	enc, err := fernet.EncryptAndSign(authPayload, fernetKey)
	if err != nil {
		logger.Fatalf("Failed to encrypt internal authorization: %v", err)
	}
	req.Header.Add("X-Srht-Authorization", string(enc))
}

// TODO: Move this to scm.sr.ht
func SubmitBuild(submitter BuildSubmitter) ([]BuildSubmission, error) {
	manifests, err := submitter.FindManifests()
	if err != nil || manifests == nil {
		return nil, err
	}

	loadOptions()
	if _, ok := options["skip-ci"]; ok {
		log.Println("skip-ci was requested - not submitting build jobs")
		return nil, nil
	}

	var results []BuildSubmission
	for name, contents := range manifests {
		if len(results) >= 4 {
			log.Println("Notice: refusing to submit >4 builds")
			break
		}

		manifest, err := ManifestFromYAML(contents)
		if err != nil {
			return nil, errors.Wrap(err, name)
		}
		autoSetupManifest(submitter, &manifest)

		yaml, err := manifest.ToYAML()
		if err != nil {
			return nil, errors.Wrap(err, name)
		}

		client := &http.Client{}

		submission := struct {
			Manifest string   `json:"manifest"`
			Note     string   `json:"note"`
			Tags     []string `json:"tags"`
		}{
			Manifest: yaml,
			Tags:     []string{submitter.GetRepoName(), "commits", name},
			Note:     submitter.GetCommitNote(),
		}
		bodyBytes, err := json.Marshal(&submission)
		if err != nil {
			return nil, errors.Wrap(err, "preparing job")
		}
		body := bytes.NewBuffer(bodyBytes)

		req, err := http.NewRequest("POST", fmt.Sprintf("%s/api/jobs",
			submitter.GetBuildsOrigin()), body)
		configureRequestAuthorization(submitter, req)
		req.Header.Add("Content-Type", "application/json")
		resp, err := client.Do(req)
		if err != nil {
			return nil, errors.Wrap(err, "job submission")
		}

		if resp.StatusCode == 403 {
			return nil, errors.New("builds.sr.ht returned 403\n" +
				"Log out and back into the website to authorize " +
				"builds integration.")
		}

		defer resp.Body.Close()
		respBytes, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return nil, errors.Wrap(err, "read response")
		}

		if resp.StatusCode == 400 {
			return nil, errors.New(fmt.Sprintf(
				"builds.sr.ht returned %d\n", resp.StatusCode) +
				string(respBytes))
		}

		var job struct {
			Id int `json:"id"`
		}
		err = json.Unmarshal(respBytes, &job)
		if err != nil {
			return nil, errors.Wrap(err, "interpret response")
		}

		results = append(results, BuildSubmission{
			Name: name,
			Url: fmt.Sprintf("%s/~%s/job/%d",
				submitter.GetBuildsOrigin(),
				submitter.GetOwnerName(),
				job.Id),
			Response: string(respBytes),
		})
	}

	return results, nil
}

func autoSetupManifest(submitter BuildSubmitter, manifest *Manifest) {
	var hasSelf bool
	cloneUrl := submitter.GetCloneUrl() + "#" + submitter.GetCommitId()
	for i, src := range manifest.Sources {
		if path.Base(src) == submitter.GetRepoName() {
			manifest.Sources[i] = cloneUrl
			hasSelf = true
		}
	}
	if !hasSelf {
		manifest.Sources = append(manifest.Sources, cloneUrl)
	}
}