Monorepo for Tangled
tangled.org
1package knotserver
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log/slog"
8 "net"
9 "net/http"
10 "net/url"
11 "os"
12 "path"
13 "path/filepath"
14 "strings"
15
16 securejoin "github.com/cyphar/filepath-securejoin"
17 "github.com/go-chi/chi/v5"
18 "github.com/go-chi/chi/v5/middleware"
19 "github.com/go-git/go-git/v5/plumbing"
20 "tangled.org/core/api/tangled"
21 "tangled.org/core/eventstream"
22 "tangled.org/core/hook"
23 "tangled.org/core/idresolver"
24 "tangled.org/core/knotserver/config"
25 "tangled.org/core/knotserver/db"
26 "tangled.org/core/knotserver/git"
27 "tangled.org/core/log"
28 "tangled.org/core/notifier"
29 "tangled.org/core/rbac"
30 "tangled.org/core/tid"
31 "tangled.org/core/workflow"
32)
33
34type InternalHandle struct {
35 db *db.DB
36 c *config.Config
37 e *rbac.Enforcer
38 l *slog.Logger
39 n *notifier.Notifier
40 res *idresolver.Resolver
41}
42
43func (h *InternalHandle) PushAllowed(w http.ResponseWriter, r *http.Request) {
44 user := r.URL.Query().Get("user")
45 repo := r.URL.Query().Get("repo")
46
47 if user == "" || repo == "" {
48 w.WriteHeader(http.StatusBadRequest)
49 return
50 }
51
52 ok, err := h.e.IsPushAllowed(user, rbac.ThisServer, repo)
53 if err != nil || !ok {
54 w.WriteHeader(http.StatusForbidden)
55 return
56 }
57
58 w.WriteHeader(http.StatusNoContent)
59}
60
61func (h *InternalHandle) InternalKeys(w http.ResponseWriter, r *http.Request) {
62 keys, err := h.db.GetAllPublicKeys()
63 if err != nil {
64 writeError(w, err.Error(), http.StatusInternalServerError)
65 return
66 }
67
68 data := make([]map[string]interface{}, 0)
69 for _, key := range keys {
70 j := key.JSON()
71 data = append(data, j)
72 }
73 writeJSON(w, data)
74}
75
76// response in text/plain format
77// the body will be qualified repository path on success/push-denied
78// or an error message when process failed
79func (h *InternalHandle) Guard(w http.ResponseWriter, r *http.Request) {
80 l := h.l.With("handler", "Guard")
81
82 var (
83 incomingUser = r.URL.Query().Get("user")
84 repo = r.URL.Query().Get("repo")
85 gitCommand = r.URL.Query().Get("gitCmd")
86 )
87
88 if incomingUser == "" || repo == "" || gitCommand == "" {
89 w.WriteHeader(http.StatusBadRequest)
90 l.Error("invalid request", "incomingUser", incomingUser, "repo", repo, "gitCommand", gitCommand)
91 fmt.Fprintln(w, "invalid internal request")
92 return
93 }
94
95 components := strings.Split(strings.TrimPrefix(strings.Trim(repo, "'"), "/"), "/")
96 l.Info("command components", "components", components)
97
98 var rbacResource string
99 var diskRelative string
100
101 switch {
102 case len(components) == 1 && strings.HasPrefix(components[0], "did:"):
103 repoDid := components[0]
104 repoPath, _, _, lookupErr := h.db.ResolveRepoDIDOnDisk(h.c.Repo.ScanPath, repoDid)
105 if lookupErr != nil {
106 w.WriteHeader(http.StatusNotFound)
107 l.Error("repo DID not found", "repoDid", repoDid, "err", lookupErr)
108 fmt.Fprintln(w, "repo not found")
109 return
110 }
111 rbacResource = repoDid
112 rel, relErr := filepath.Rel(h.c.Repo.ScanPath, repoPath)
113 if relErr != nil {
114 w.WriteHeader(http.StatusInternalServerError)
115 l.Error("failed to compute relative path", "repoPath", repoPath, "err", relErr)
116 fmt.Fprintln(w, "internal error")
117 return
118 }
119 diskRelative = rel
120
121 case len(components) == 2:
122 repoOwner := components[0]
123 ownerIdent, resolveErr := h.res.ResolveAtIdentifier(r.Context(), repoOwner)
124 if resolveErr != nil {
125 l.Error("error resolving owner", "owner", repoOwner, "err", resolveErr)
126 w.WriteHeader(http.StatusInternalServerError)
127 fmt.Fprintf(w, "error resolving owner: invalid did or handle\n")
128 return
129 }
130 ownerDid := ownerIdent.DID
131 repoName := components[1]
132 repoDid, didErr := h.db.GetRepoDid(ownerDid.String(), repoName)
133 var repoPath string
134 if didErr == nil {
135 var lookupErr error
136 repoPath, _, _, lookupErr = h.db.ResolveRepoDIDOnDisk(h.c.Repo.ScanPath, repoDid)
137 if lookupErr != nil {
138 w.WriteHeader(http.StatusNotFound)
139 l.Error("repo not found on disk", "repoDid", repoDid, "err", lookupErr)
140 fmt.Fprintln(w, "repo not found")
141 return
142 }
143 rbacResource = repoDid
144 } else {
145 legacyPath, joinErr := securejoin.SecureJoin(h.c.Repo.ScanPath, filepath.Join(ownerDid.String(), repoName))
146 if joinErr != nil {
147 w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
148 w.WriteHeader(http.StatusNotFound)
149 fmt.Fprint(w, "repo not found\n")
150 return
151 }
152 if _, statErr := os.Stat(legacyPath); statErr != nil {
153 l.Info("legacy repo path missing, checking rename history", "owner", ownerDid, "name", repoName)
154 w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
155 w.WriteHeader(http.StatusNotFound)
156 fmt.Fprint(w, "repo not found\n")
157 return
158 }
159 repoPath = legacyPath
160 rbacResource = ownerDid.String() + "/" + repoName
161 }
162 rel, relErr := filepath.Rel(h.c.Repo.ScanPath, repoPath)
163 if relErr != nil {
164 w.WriteHeader(http.StatusInternalServerError)
165 l.Error("failed to compute relative path", "repoPath", repoPath, "err", relErr)
166 fmt.Fprintln(w, "internal error")
167 return
168 }
169 diskRelative = rel
170
171 default:
172 w.WriteHeader(http.StatusBadRequest)
173 l.Error("invalid repo format", "components", components)
174 fmt.Fprintln(w, "invalid repo format, needs <user>/<repo>, /<user>/<repo>, or <repo-did>")
175 return
176 }
177
178 if gitCommand == "git-receive-pack" {
179 ok, err := h.e.IsPushAllowed(incomingUser, rbac.ThisServer, rbacResource)
180 if err != nil || !ok {
181 w.WriteHeader(http.StatusForbidden)
182 fmt.Fprint(w, repo)
183 return
184 }
185 }
186
187 w.WriteHeader(http.StatusOK)
188 fmt.Fprint(w, diskRelative)
189}
190
191type PushOptions struct {
192 skipCi bool
193 verboseCi bool
194}
195
196func (h *InternalHandle) PostReceiveHook(w http.ResponseWriter, r *http.Request) {
197 l := h.l.With("handler", "PostReceiveHook")
198
199 gitAbsoluteDir := r.Header.Get("X-Git-Dir")
200 gitRelativeDir, err := filepath.Rel(h.c.Repo.ScanPath, gitAbsoluteDir)
201 if err != nil {
202 l.Error("failed to calculate relative git dir", "scanPath", h.c.Repo.ScanPath, "gitAbsoluteDir", gitAbsoluteDir)
203 w.WriteHeader(http.StatusInternalServerError)
204 return
205 }
206
207 var repoDid string
208 var ownerDid, repoName string
209
210 if strings.HasPrefix(gitRelativeDir, "did:") {
211 repoDid = gitRelativeDir
212 var err error
213 ownerDid, repoName, err = h.db.GetRepoKeyOwner(repoDid)
214 if err != nil {
215 l.Error("failed to resolve repo DID from git dir", "repoDid", repoDid, "err", err)
216 w.WriteHeader(http.StatusBadRequest)
217 return
218 }
219 } else {
220 components := strings.SplitN(gitRelativeDir, "/", 2)
221 if len(components) != 2 {
222 l.Error("invalid git dir, expected repo DID or owner/repo", "gitRelativeDir", gitRelativeDir)
223 w.WriteHeader(http.StatusBadRequest)
224 return
225 }
226 ownerDid = components[0]
227 repoName = components[1]
228 var didErr error
229 repoDid, didErr = h.db.GetRepoDid(ownerDid, repoName)
230 if didErr != nil {
231 l.Error("failed to resolve repo DID from legacy path", "gitRelativeDir", gitRelativeDir, "err", didErr)
232 w.WriteHeader(http.StatusBadRequest)
233 return
234 }
235 }
236
237 gitUserDid := r.Header.Get("X-Git-User-Did")
238
239 lines, err := git.ParsePostReceive(r.Body)
240 if err != nil {
241 l.Error("failed to parse post-receive payload", "err", err)
242 // non-fatal
243 }
244
245 // extract any push options
246 pushOptionsRaw := r.Header.Values("X-Git-Push-Option")
247 pushOptions := PushOptions{}
248 for _, option := range pushOptionsRaw {
249 if option == "skip-ci" || option == "ci-skip" {
250 pushOptions.skipCi = true
251 }
252 if option == "verbose-ci" || option == "ci-verbose" {
253 pushOptions.verboseCi = true
254 }
255 }
256
257 resp := hook.HookResponse{
258 Messages: make([]string, 0),
259 }
260
261 for _, line := range lines {
262 err := h.insertRefUpdate(line, gitUserDid, ownerDid, repoDid)
263 if err != nil {
264 l.Error("failed to insert op", "err", err, "line", line, "did", gitUserDid, "repo", gitRelativeDir)
265 }
266
267 err = h.emitPullRequestLink(&resp.Messages, line, ownerDid, repoName, repoDid)
268 if err != nil {
269 l.Error("failed to reply with pull request link", "err", err, "line", line, "did", gitUserDid, "repo", gitRelativeDir)
270 }
271
272 err = h.triggerPipeline(&resp.Messages, line, gitUserDid, ownerDid, repoName, repoDid, pushOptions)
273 if err != nil {
274 l.Error("failed to trigger pipeline", "err", err, "line", line, "did", gitUserDid, "repo", gitRelativeDir)
275 }
276 }
277
278 writeJSON(w, resp)
279}
280
281func (h *InternalHandle) insertRefUpdate(line git.PostReceiveLine, gitUserDid, ownerDid, repoDid string) error {
282 refUpdate := tangled.GitRefUpdate{
283 OldSha: line.OldSha.String(),
284 NewSha: line.NewSha.String(),
285 Ref: line.Ref,
286 CommitterDid: gitUserDid,
287 OwnerDid: &ownerDid,
288 Repo: repoDid,
289 Meta: nil,
290 }
291
292 if !line.NewSha.IsZero() {
293 repoPath, _, _, resolveErr := h.db.ResolveRepoDIDOnDisk(h.c.Repo.ScanPath, repoDid)
294 if resolveErr != nil {
295 return fmt.Errorf("failed to resolve repo on disk: %w", resolveErr)
296 }
297
298 gr, err := git.Open(repoPath, line.Ref)
299 if err != nil {
300 return fmt.Errorf("failed to open git repo at ref %s: %w", line.Ref, err)
301 }
302
303 meta, err := gr.RefUpdateMeta(line)
304 if err != nil {
305 return fmt.Errorf("failed to get ref update metadata: %w", err)
306 }
307
308 refUpdate.Meta = new(tangled.GitRefUpdate_Meta)
309 *refUpdate.Meta = meta.AsRecord()
310 }
311
312 eventJson, err := json.Marshal(refUpdate)
313 if err != nil {
314 return err
315 }
316
317 event := eventstream.Event{
318 Rkey: tid.TID(),
319 Nsid: tangled.GitRefUpdateNSID,
320 EventJson: eventJson,
321 }
322
323 return h.db.InsertEvent(event, h.n)
324}
325
326func (h *InternalHandle) triggerPipeline(
327 clientMsgs *[]string,
328 line git.PostReceiveLine,
329 gitUserDid string,
330 ownerDid string,
331 repoName string,
332 repoDid string,
333 pushOptions PushOptions,
334) error {
335 if pushOptions.skipCi {
336 return nil
337 }
338
339 repoPath, _, _, resolveErr := h.db.ResolveRepoDIDOnDisk(h.c.Repo.ScanPath, repoDid)
340 if resolveErr != nil {
341 return fmt.Errorf("failed to resolve repo on disk: %w", resolveErr)
342 }
343
344 gr, err := git.Open(repoPath, line.Ref)
345 if err != nil {
346 return err
347 }
348
349 workflowDir, err := gr.FileTree(context.Background(), workflow.WorkflowDir)
350 if err != nil {
351 return err
352 }
353
354 var pipeline workflow.RawPipeline
355 for _, e := range workflowDir {
356 if !e.IsFile() {
357 continue
358 }
359
360 fpath := filepath.Join(workflow.WorkflowDir, e.Name)
361 contents, err := gr.RawContent(fpath)
362 if err != nil {
363 continue
364 }
365
366 pipeline = append(pipeline, workflow.RawWorkflow{
367 Name: e.Name,
368 Contents: contents,
369 })
370 }
371
372 defaultBranch, _ := gr.FindMainBranch()
373
374 trigger := tangled.Pipeline_PushTriggerData{
375 Ref: line.Ref,
376 OldSha: line.OldSha.String(),
377 NewSha: line.NewSha.String(),
378 }
379
380 triggerRepo := &tangled.Pipeline_TriggerRepo{
381 Did: ownerDid,
382 Knot: h.c.Server.Hostname,
383 Repo: &repoName,
384 RepoDid: &repoDid,
385 DefaultBranch: defaultBranch,
386 }
387
388 compiler := workflow.Compiler{
389 Trigger: tangled.Pipeline_TriggerMetadata{
390 Kind: string(workflow.TriggerKindPush),
391 Push: &trigger,
392 Repo: triggerRepo,
393 },
394 }
395
396 cp := compiler.Compile(compiler.Parse(pipeline))
397 eventJson, err := json.Marshal(cp)
398 if err != nil {
399 return err
400 }
401
402 for _, e := range compiler.Diagnostics.Errors {
403 *clientMsgs = append(*clientMsgs, e.String())
404 }
405
406 if pushOptions.verboseCi {
407 if compiler.Diagnostics.IsEmpty() {
408 *clientMsgs = append(*clientMsgs, "success: pipeline compiled with no diagnostics")
409 }
410
411 for _, w := range compiler.Diagnostics.Warnings {
412 *clientMsgs = append(*clientMsgs, w.String())
413 }
414 }
415
416 // do not run empty pipelines
417 if cp.Workflows == nil {
418 return nil
419 }
420
421 event := eventstream.Event{
422 Rkey: tid.TID(),
423 Nsid: tangled.PipelineNSID,
424 EventJson: eventJson,
425 }
426
427 if h.c.LogsAddr != "" {
428 host, port, err := net.SplitHostPort(h.c.LogsAddr)
429 if err == nil {
430 *clientMsgs = append(*clientMsgs, "→ Browse CI logs in your terminal:")
431 *clientMsgs = append(*clientMsgs, fmt.Sprintf(" ssh -t -p %s %s %s %s", port, host, repoDid, line.NewSha))
432 }
433 }
434
435 return h.db.InsertEvent(event, h.n)
436}
437
438func (h *InternalHandle) emitPullRequestLink(
439 clientMsgs *[]string,
440 line git.PostReceiveLine,
441 ownerDid string,
442 repoName string,
443 repoDid string,
444) error {
445 if line.NewSha.IsZero() {
446 return nil
447 }
448
449 // the ref was not updated to a new hash, don't reply with the link
450 //
451 // NOTE: do we need this?
452 if line.NewSha == line.OldSha {
453 return nil
454 }
455
456 pushedRef := plumbing.ReferenceName(line.Ref)
457 if !pushedRef.IsBranch() {
458 return nil
459 }
460
461 if !line.OldSha.IsZero() {
462 return nil
463 }
464
465 repoPath, _, _, resolveErr := h.db.ResolveRepoDIDOnDisk(h.c.Repo.ScanPath, repoDid)
466 if resolveErr != nil {
467 return fmt.Errorf("failed to resolve repo on disk: %w", resolveErr)
468 }
469
470 gr, err := git.PlainOpen(repoPath)
471 if err != nil {
472 return err
473 }
474
475 remote, err := gr.Remote()
476 if err != nil {
477 return fmt.Errorf("checking for upstream remote: %w", err)
478 }
479
480 defaultBranch, err := gr.FindMainBranch()
481 if err != nil {
482 return err
483 }
484
485 pushedBranch := pushedRef.Short()
486
487 // pushing to default branch
488 if pushedBranch == defaultBranch {
489 return nil
490 }
491
492 userIdent, err := h.res.ResolveIdent(context.Background(), ownerDid)
493 user := ownerDid
494 if err == nil {
495 user = userIdent.Handle.String()
496 }
497
498 pullURL, err := h.createPullURL(h.c.AppViewEndpoint, remote, user, ownerDid, repoName, pushedBranch, defaultBranch)
499 if err != nil {
500 return err
501 }
502
503 ZWS := "\u200B"
504 *clientMsgs = append(*clientMsgs, ZWS)
505 *clientMsgs = append(*clientMsgs, "→ Open pull request:")
506 *clientMsgs = append(*clientMsgs, " "+pullURL)
507 *clientMsgs = append(*clientMsgs, ZWS)
508 return nil
509}
510
511func (h *InternalHandle) createPullURL(appviewURL, remote, user, ownerDID, repoName, pushedBranch, defaultBranch string) (string, error) {
512 if remote != "" {
513 return h.createForkPullURL(appviewURL, remote, ownerDID, repoName, pushedBranch, defaultBranch)
514 }
515
516 query := url.Values{}
517
518 query.Set("source", "branch")
519 query.Set("sourceBranch", pushedBranch)
520 query.Set("targetBranch", defaultBranch)
521
522 basePath, err := url.JoinPath(appviewURL, user, repoName, "pulls", "new")
523 if err != nil {
524 return "", err
525 }
526 pullURL := basePath + "?" + query.Encode()
527 return pullURL, nil
528}
529
530func (h *InternalHandle) createForkPullURL(appviewURL, remote, ownerDID, repoName, pushedBranch, defaultBranch string) (string, error) {
531 query := url.Values{}
532
533 query.Set("fork", fmt.Sprintf("%s/%s", ownerDID, repoName))
534 query.Set("source", "fork")
535 query.Set("sourceBranch", pushedBranch)
536 query.Set("targetBranch", defaultBranch)
537
538 repoPath, err := h.getRemoteOwnerRepoNamePath(remote)
539 if err != nil {
540 return "", err
541 }
542
543 basePath, err := url.JoinPath(appviewURL, repoPath, "pulls", "new")
544 if err != nil {
545 return "", err
546 }
547 pullURL := basePath + "?" + query.Encode()
548 return pullURL, nil
549}
550
551func (h *InternalHandle) getRemoteOwnerRepoNamePath(remote string) (string, error) {
552 u, err := url.Parse(remote)
553 if err != nil {
554 return "", fmt.Errorf("invalid remote: %w", err)
555 }
556
557 if u.Scheme != "file" {
558 return u.Path, nil
559 }
560
561 repoDid := path.Base(u.String())
562
563 owner, name, err := h.db.GetRepoKeyOwner(repoDid)
564 if err != nil {
565 return "", err
566 }
567
568 return fmt.Sprintf("%s/%s", owner, name), nil
569}
570
571func Internal(ctx context.Context, c *config.Config, db *db.DB, e *rbac.Enforcer, n *notifier.Notifier, res *idresolver.Resolver) http.Handler {
572 r := chi.NewRouter()
573 l := log.FromContext(ctx)
574 l = log.SubLogger(l, "internal")
575
576 h := InternalHandle{
577 db: db,
578 c: c,
579 e: e,
580 l: l,
581 n: n,
582 res: res,
583 }
584
585 r.Get("/push-allowed", h.PushAllowed)
586 r.Get("/keys", h.InternalKeys)
587 r.Get("/guard", h.Guard)
588 r.Post("/hooks/post-receive", h.PostReceiveHook)
589 r.Mount("/debug", middleware.Profiler())
590
591 return r
592}