Monorepo for Tangled
0

Configure Feed

Select the types of activity you want to include in your feed.

core / knotserver / internal.go
16 kB 588 lines
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 191func (h *InternalHandle) PostReceiveHook(w http.ResponseWriter, r *http.Request) { 192 l := h.l.With("handler", "PostReceiveHook") 193 194 gitAbsoluteDir := r.Header.Get("X-Git-Dir") 195 gitRelativeDir, err := filepath.Rel(h.c.Repo.ScanPath, gitAbsoluteDir) 196 if err != nil { 197 l.Error("failed to calculate relative git dir", "scanPath", h.c.Repo.ScanPath, "gitAbsoluteDir", gitAbsoluteDir) 198 w.WriteHeader(http.StatusInternalServerError) 199 return 200 } 201 202 var repoDid string 203 var ownerDid, repoName string 204 205 if strings.HasPrefix(gitRelativeDir, "did:") { 206 repoDid = gitRelativeDir 207 var err error 208 ownerDid, repoName, err = h.db.GetRepoKeyOwner(repoDid) 209 if err != nil { 210 l.Error("failed to resolve repo DID from git dir", "repoDid", repoDid, "err", err) 211 w.WriteHeader(http.StatusBadRequest) 212 return 213 } 214 } else { 215 components := strings.SplitN(gitRelativeDir, "/", 2) 216 if len(components) != 2 { 217 l.Error("invalid git dir, expected repo DID or owner/repo", "gitRelativeDir", gitRelativeDir) 218 w.WriteHeader(http.StatusBadRequest) 219 return 220 } 221 ownerDid = components[0] 222 repoName = components[1] 223 var didErr error 224 repoDid, didErr = h.db.GetRepoDid(ownerDid, repoName) 225 if didErr != nil { 226 l.Error("failed to resolve repo DID from legacy path", "gitRelativeDir", gitRelativeDir, "err", didErr) 227 w.WriteHeader(http.StatusBadRequest) 228 return 229 } 230 } 231 232 gitUserDid := r.Header.Get("X-Git-User-Did") 233 234 lines, err := git.ParsePostReceive(r.Body) 235 if err != nil { 236 l.Error("failed to parse post-receive payload", "err", err) 237 // non-fatal 238 } 239 240 // extract max 50 push options 241 pushOptions := r.Header.Values("X-Git-Push-Option") 242 if len(pushOptions) > 50 { 243 pushOptions = pushOptions[:50] 244 } 245 246 repoPath, _, _, resolveErr := h.db.ResolveRepoDIDOnDisk(h.c.Repo.ScanPath, repoDid) 247 if resolveErr != nil { 248 l.Error("failed to resolve repo on disk", "repoDid", repoDid, "err", resolveErr) 249 w.WriteHeader(http.StatusInternalServerError) 250 return 251 } 252 253 resp := hook.HookResponse{ 254 Messages: make([]string, 0), 255 } 256 257 for _, line := range lines { 258 err := h.insertRefUpdate(line, gitUserDid, ownerDid, repoDid, repoPath, pushOptions) 259 if err != nil { 260 l.Error("failed to insert op", "err", err, "line", line, "did", gitUserDid, "repo", gitRelativeDir) 261 } 262 263 err = h.emitPullRequestLink(&resp.Messages, line, ownerDid, repoName, repoDid) 264 if err != nil { 265 l.Error("failed to reply with pull request link", "err", err, "line", line, "did", gitUserDid, "repo", gitRelativeDir) 266 } 267 268 if !git.HasSkipCIPushOption(pushOptions) { 269 verbose := hasVerboseCIPushOption(pushOptions) 270 if err := h.emitCiDiagnostics(&resp.Messages, line, ownerDid, repoName, repoDid, repoPath, verbose); err != nil { 271 l.Error("failed to emit ci diagnostics", "err", err, "line", line, "did", gitUserDid, "repo", gitRelativeDir) 272 } 273 } 274 275 // emit pipeline logs link 276 if h.c.LogsAddr != "" { 277 host, port, err := net.SplitHostPort(h.c.LogsAddr) 278 if err == nil { 279 resp.Messages = append(resp.Messages, "→ Browse CI logs in your terminal:") 280 resp.Messages = append(resp.Messages, fmt.Sprintf(" ssh -t -p %s %s %s %s", port, host, repoDid, line.NewSha)) 281 } 282 } 283 } 284 285 writeJSON(w, resp) 286} 287 288func (h *InternalHandle) insertRefUpdate(line git.PostReceiveLine, gitUserDid, ownerDid, repoDid string, repoPath string, pushOptions []string) error { 289 refUpdate := tangled.GitRefUpdate{ 290 OldSha: line.OldSha.String(), 291 NewSha: line.NewSha.String(), 292 Ref: line.Ref, 293 CommitterDid: gitUserDid, 294 OwnerDid: &ownerDid, 295 Repo: repoDid, 296 Meta: nil, 297 PushOptions: pushOptions, 298 } 299 300 if !line.NewSha.IsZero() { 301 302 gr, err := git.Open(repoPath, line.Ref) 303 if err != nil { 304 return fmt.Errorf("failed to open git repo at ref %s: %w", line.Ref, err) 305 } 306 307 changedFiles, err := gr.ChangedFilesBetween(line.OldSha.String(), line.NewSha.String()) 308 if err != nil { 309 return fmt.Errorf("failed to get ref update changed files: %w", err) 310 } 311 refUpdate.ChangedFiles = changedFiles 312 313 meta, err := gr.RefUpdateMeta(line) 314 if err != nil { 315 return fmt.Errorf("failed to get ref update metadata: %w", err) 316 } 317 318 refUpdate.Meta = new(tangled.GitRefUpdate_Meta) 319 *refUpdate.Meta = meta.AsRecord() 320 } 321 322 eventJson, err := json.Marshal(refUpdate) 323 if err != nil { 324 return err 325 } 326 327 event := eventstream.Event{ 328 Rkey: tid.TID(), 329 Nsid: tangled.GitRefUpdateNSID, 330 EventJson: eventJson, 331 } 332 333 return h.db.InsertEvent(event, h.n) 334} 335 336func hasVerboseCIPushOption(pushOptions []string) bool { 337 for _, opt := range pushOptions { 338 switch opt { 339 case "verbose-ci", "ci-verbose": 340 return true 341 } 342 } 343 return false 344} 345 346func (h *InternalHandle) emitCiDiagnostics( 347 clientMsgs *[]string, 348 line git.PostReceiveLine, 349 ownerDid string, 350 repoName string, 351 repoDid string, 352 repoPath string, 353 verbose bool, 354) error { 355 if line.NewSha.IsZero() { 356 return nil 357 } 358 359 gr, err := git.Open(repoPath, line.Ref) 360 if err != nil { 361 return fmt.Errorf("failed to open git repo at ref %s: %w", line.Ref, err) 362 } 363 364 workflowDir, err := gr.FileTree(context.Background(), workflow.WorkflowDir) 365 if err != nil { 366 return nil 367 } 368 369 var pipeline workflow.RawPipeline 370 for _, e := range workflowDir { 371 if !e.IsFile() { 372 continue 373 } 374 375 fpath := filepath.Join(workflow.WorkflowDir, e.Name) 376 contents, err := gr.RawContent(fpath) 377 if err != nil { 378 continue 379 } 380 381 pipeline = append(pipeline, workflow.RawWorkflow{ 382 Name: e.Name, 383 Contents: contents, 384 }) 385 } 386 387 defaultBranch, _ := gr.FindMainBranch() 388 389 trigger := tangled.Pipeline_PushTriggerData{ 390 Ref: line.Ref, 391 OldSha: line.OldSha.String(), 392 NewSha: line.NewSha.String(), 393 } 394 395 triggerRepo := &tangled.Pipeline_TriggerRepo{ 396 Did: ownerDid, 397 Knot: h.c.Server.Hostname, 398 Repo: &repoName, 399 RepoDid: &repoDid, 400 DefaultBranch: defaultBranch, 401 } 402 403 changedFiles, err := gr.ChangedFilesBetween(line.OldSha.String(), line.NewSha.String()) 404 if err != nil { 405 return fmt.Errorf("getting changed files: %w", err) 406 } 407 408 compiler := workflow.Compiler{ 409 Trigger: tangled.Pipeline_TriggerMetadata{ 410 Kind: string(workflow.TriggerKindPush), 411 Push: &trigger, 412 Repo: triggerRepo, 413 }, 414 ChangedFiles: changedFiles, 415 } 416 417 compiler.Compile(compiler.Parse(pipeline)) 418 419 for _, e := range compiler.Diagnostics.Errors { 420 *clientMsgs = append(*clientMsgs, e.String()) 421 } 422 if verbose { 423 if compiler.Diagnostics.IsEmpty() { 424 *clientMsgs = append(*clientMsgs, "success: pipeline compiled with no diagnostics") 425 } 426 for _, w := range compiler.Diagnostics.Warnings { 427 *clientMsgs = append(*clientMsgs, w.String()) 428 } 429 } 430 431 return nil 432} 433 434func (h *InternalHandle) emitPullRequestLink( 435 clientMsgs *[]string, 436 line git.PostReceiveLine, 437 ownerDid string, 438 repoName string, 439 repoDid string, 440) error { 441 if line.NewSha.IsZero() { 442 return nil 443 } 444 445 // the ref was not updated to a new hash, don't reply with the link 446 // 447 // NOTE: do we need this? 448 if line.NewSha == line.OldSha { 449 return nil 450 } 451 452 pushedRef := plumbing.ReferenceName(line.Ref) 453 if !pushedRef.IsBranch() { 454 return nil 455 } 456 457 if !line.OldSha.IsZero() { 458 return nil 459 } 460 461 repoPath, _, _, resolveErr := h.db.ResolveRepoDIDOnDisk(h.c.Repo.ScanPath, repoDid) 462 if resolveErr != nil { 463 return fmt.Errorf("failed to resolve repo on disk: %w", resolveErr) 464 } 465 466 gr, err := git.PlainOpen(repoPath) 467 if err != nil { 468 return err 469 } 470 471 remote, err := gr.Remote() 472 if err != nil { 473 return fmt.Errorf("checking for upstream remote: %w", err) 474 } 475 476 defaultBranch, err := gr.FindMainBranch() 477 if err != nil { 478 return err 479 } 480 481 pushedBranch := pushedRef.Short() 482 483 // pushing to default branch 484 if pushedBranch == defaultBranch { 485 return nil 486 } 487 488 userIdent, err := h.res.ResolveIdent(context.Background(), ownerDid) 489 user := ownerDid 490 if err == nil { 491 user = userIdent.Handle.String() 492 } 493 494 pullURL, err := h.createPullURL(h.c.AppViewEndpoint, remote, user, repoDid, repoName, pushedBranch, defaultBranch) 495 if err != nil { 496 return err 497 } 498 499 ZWS := "\u200B" 500 *clientMsgs = append(*clientMsgs, ZWS) 501 *clientMsgs = append(*clientMsgs, "→ Open pull request:") 502 *clientMsgs = append(*clientMsgs, " "+pullURL) 503 *clientMsgs = append(*clientMsgs, ZWS) 504 return nil 505} 506 507func (h *InternalHandle) createPullURL(appviewURL, remote, user, repoDid, repoName, pushedBranch, defaultBranch string) (string, error) { 508 if remote != "" { 509 return h.createForkPullURL(appviewURL, remote, repoDid, pushedBranch, defaultBranch) 510 } 511 512 query := url.Values{} 513 514 query.Set("source", "branch") 515 query.Set("sourceBranch", pushedBranch) 516 query.Set("targetBranch", defaultBranch) 517 518 basePath, err := url.JoinPath(appviewURL, user, repoName, "pulls", "new") 519 if err != nil { 520 return "", err 521 } 522 pullURL := basePath + "?" + query.Encode() 523 return pullURL, nil 524} 525 526func (h *InternalHandle) createForkPullURL(appviewURL, remote, repoDid, pushedBranch, defaultBranch string) (string, error) { 527 query := url.Values{} 528 529 query.Set("fork", repoDid) 530 query.Set("source", "fork") 531 query.Set("sourceBranch", pushedBranch) 532 query.Set("targetBranch", defaultBranch) 533 534 repoPath, err := h.getRemoteOwnerRepoNamePath(remote) 535 if err != nil { 536 return "", err 537 } 538 539 basePath, err := url.JoinPath(appviewURL, repoPath, "pulls", "new") 540 if err != nil { 541 return "", err 542 } 543 pullURL := basePath + "?" + query.Encode() 544 return pullURL, nil 545} 546 547func (h *InternalHandle) getRemoteOwnerRepoNamePath(remote string) (string, error) { 548 u, err := url.Parse(remote) 549 if err != nil { 550 return "", fmt.Errorf("invalid remote: %w", err) 551 } 552 553 if u.Scheme != "file" { 554 return u.Path, nil 555 } 556 557 repoDid := path.Base(u.String()) 558 559 owner, name, err := h.db.GetRepoKeyOwner(repoDid) 560 if err != nil { 561 return "", err 562 } 563 564 return fmt.Sprintf("%s/%s", owner, name), nil 565} 566 567func Internal(ctx context.Context, c *config.Config, db *db.DB, e *rbac.Enforcer, n *notifier.Notifier, res *idresolver.Resolver) http.Handler { 568 r := chi.NewRouter() 569 l := log.FromContext(ctx) 570 l = log.SubLogger(l, "internal") 571 572 h := InternalHandle{ 573 db: db, 574 c: c, 575 e: e, 576 l: l, 577 n: n, 578 res: res, 579 } 580 581 r.Get("/push-allowed", h.PushAllowed) 582 r.Get("/keys", h.InternalKeys) 583 r.Get("/guard", h.Guard) 584 r.Post("/hooks/post-receive", h.PostReceiveHook) 585 r.Mount("/debug", middleware.Profiler()) 586 587 return r 588}