This repository has no description
0

Configure Feed

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

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