git.sr.ht/gitsrht-update-hook/submitter.go -rw-r--r-- 7.9 KiB View raw
                                                                                
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
package main

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

	"github.com/fernet/fernet-go"
	"github.com/microcosm-cc/bluemonday"
	"github.com/pkg/errors"
	"gopkg.in/src-d/go-git.v4"
	"gopkg.in/src-d/go-git.v4/plumbing/object"
)

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) {
	tree, err := submitter.Repository.TreeObject(submitter.Commit.TreeHash)
	if err != nil {
		return nil, errors.Wrap(err, "lookup tree failed")
	}

	var files []*object.File
	file, err := tree.File(".build.yml")
	if err == nil {
		files = append(files, file)
	} else {
		subtree, err := tree.Tree(".builds")
		if err != nil {
			return nil, nil
		}
		entries := subtree.Files()
		for {
			file, err = entries.Next()
			if file == nil || err != nil {
				break
			}
			if strings.HasSuffix(file.Name, ".yml") {
				files = append(files, file)
			}
		}
		if err != io.EOF {
			return nil, errors.Wrap(err, "EOF finding build manifest")
		}
	}

	manifests := make(map[string]string)
	for _, file := range files {
		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[file.Name] = 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()
}

func (submitter GitBuildSubmitter) GetCommitNote() string {
	policy := bluemonday.StrictPolicy()
	commitUrl := fmt.Sprintf("%s/%s/%s/commit/%s", submitter.GitOrigin,
		submitter.OwnerName, submitter.RepoName,
		submitter.GetCommitId())
	return fmt.Sprintf(`[%s](%s) &mdash; [%s](mailto:%s)\n\n<pre>%s</pre>`,
		submitter.GetCommitId()[:7], commitUrl,
		submitter.Commit.Author.Name, submitter.Commit.Author.Email,
		policy.Sanitize(firstLine(submitter.Commit.Message)))
}

func (submitter GitBuildSubmitter) GetCloneUrl() string {
	if submitter.Visibility == "private" {
		origin := strings.ReplaceAll(submitter.GitOrigin, "http://", "")
		origin = strings.ReplaceAll(origin, "https://", "")
		// Use SSH URL
		return fmt.Sprintf("git+ssh://git@%s/~%s/%s", 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
	Url  string
}

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

	if submitter.GetOauthToken() != nil {
		req.Header.Add("Authorization", fmt.Sprintf("token %s",
			*submitter.GetOauthToken()))
	} else {
		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
	}

	var results []BuildSubmission
	for name, contents := range manifests {
		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"`
			Tags     []string `json:"tags"`
		}{
			Manifest: yaml,
			Tags:     []string{submitter.GetRepoName(), name},
		}
		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),
		})
	}

	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)
	}
}