package runnerproto import ( "amadan.net/oficina/equipo/internal/equipo/team" "context" "github.com/go-chi/chi/v5" "mime" "net/http" "strconv" "strings" "time" ) type ExecutionAPI interface { RecoverCoordinator(context.Context, RunnerPrincipal, string, int64) (CoordinatorClaim, error) CoordinatorToolResult(context.Context, RunnerPrincipal, CoordinatorClaim, CoordinatorToolCall) (CoordinatorToolResult, error) CallCoordinatorTool(context.Context, RunnerPrincipal, CoordinatorClaim, CoordinatorToolCall) (CoordinatorToolResult, error) PollCoordinator(context.Context, RunnerPrincipal) ([]CoordinatorTurn, error) ClaimCoordinator(context.Context, RunnerPrincipal, string, int64) (CoordinatorClaim, error) RenewCoordinator(context.Context, RunnerPrincipal, CoordinatorClaim) (time.Time, error) CoordinatorEvent(context.Context, RunnerPrincipal, CoordinatorClaim, Event) error ContainCoordinator(context.Context, RunnerPrincipal, CoordinatorClaim, ContainmentProof) error Sync(context.Context) error Poll(context.Context, RunnerPrincipal, string) ([]Assignment, error) Claim(context.Context, RunnerPrincipal, ClaimRequest) (ClaimResponse, error) RecoverClaim(context.Context, RunnerPrincipal, ClaimRequest) (ClaimResponse, error) Mutate(context.Context, RunnerPrincipal, string, RunnerRequest) (any, error) Cleanup(context.Context, string, string, RunnerRequest) (any, error) AcknowledgeRotation(context.Context, RunnerPrincipal, string) error ReadArtifact(context.Context, RunnerPrincipal, RunnerRequest, team.ArtifactID) (team.Artifact, error) } type Handler struct { ReportRepositories func(context.Context, RunnerPrincipal, []string) error AccountSetups AccountSetupAPI Execution func() ExecutionAPI AuthenticateRunner func(context.Context, string) (RunnerPrincipal, error) ReportConnections func(context.Context, RunnerPrincipal, []ConnectionReport) error PutBlob func(context.Context, RunnerPrincipal, team.Scope, team.Handle, string, []byte) error Blob func(context.Context, RunnerPrincipal, team.Scope, string) ([]byte, error) Failure func(http.ResponseWriter, error) JSON func(http.ResponseWriter, int, any) Invalid, Forbidden, Unavailable error MaxBlobBytes int64 } func (s *Handler) Router() chi.Router { r := chi.NewRouter() r.Post("/account-setups", s.runnerAccountSetup) // Thin v1: coordinator turns and work arrive on the runner stream // (/api/runner/stream). The poll and claim routes are gone. r.Post("/blobs", s.runnerPutBlob) r.Post("/blobs/read", s.runnerReadBlob) for _, op := range []string{"validate", "evidence", "freeze", "freeze_feature", "conclude", "publication_ready", "publication_authorize", "question_resolved", "questions", "answers", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} { r.Post("/"+op, s.runnerMutation(op)) } r.Post("/connections", s.runnerConnections) r.Post("/heartbeat", s.runnerConnections) r.Get("/artifacts/{assignment}/{artifact}", s.runnerArtifact) return r } func (s *Handler) Body(w http.ResponseWriter, r *http.Request, v any, limit int64) bool { content, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil || content != "application/json" || DecodeLimit(r.Body, v, limit) != nil { s.Failure(w, s.Invalid) return false } return true } func (s *Handler) Bearer(w http.ResponseWriter, r *http.Request) (RunnerPrincipal, string, bool) { w.Header().Set("Cache-Control", "no-store") values := r.Header.Values("Authorization") if len(r.Header.Values("Cookie")) != 0 || len(values) != 1 || !strings.HasPrefix(values[0], "Bearer ") { s.Failure(w, s.Forbidden) return RunnerPrincipal{}, "", false } token := strings.TrimPrefix(values[0], "Bearer ") p, err := s.AuthenticateRunner(r.Context(), token) if err != nil { s.Failure(w, err) return p, "", false } return p, token, true } func (s *Handler) runnerMutation(op string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if s.Execution() == nil { s.Failure(w, s.Unavailable) return } var q RunnerRequest limit := int64(MaxActionBytes) if op == "artifacts" { limit = 2 * MaxArtifactBytes } if op == "events" { limit = MaxEventBytes + 4096 } if !s.Body(w, r, &q, limit) { return } var value any var err error if strings.HasPrefix(r.Header.Get("Authorization"), "Cleanup ") { if len(r.Header.Values("Authorization")) != 1 || len(r.Header.Values("Cookie")) != 0 { s.Failure(w, s.Forbidden) return } value, err = s.Execution().Cleanup(r.Context(), strings.TrimPrefix(r.Header.Get("Authorization"), "Cleanup "), op, q) } else { p, _, ok := s.Bearer(w, r) if !ok { return } value, err = s.Execution().Mutate(r.Context(), p, op, q) } if err != nil { s.Failure(w, err) return } s.JSON(w, 200, WorkResponse{Version: 2, Result: value}) } } func (s *Handler) runnerConnections(w http.ResponseWriter, r *http.Request) { p, _, ok := s.Bearer(w, r) if !ok { return } var q HeartbeatRequest if !s.Body(w, r, &q, MaxActionBytes) { return } if q.Version != 2 || q.RequestID == "" || len(q.RequestID) > 256 { s.Failure(w, s.Invalid) return } if q.RotationRequestID != "" { if s.Execution() == nil { s.Failure(w, s.Unavailable) return } if err := s.Execution().AcknowledgeRotation(r.Context(), p, q.RotationRequestID); err != nil { s.Failure(w, err) return } } if len(q.Reports) > 0 { var reports []ConnectionReport if DecodeLimit(strings.NewReader(string(q.Reports)), &reports, MaxActionBytes) != nil { s.Failure(w, s.Invalid) return } if err := s.ReportConnections(r.Context(), p, reports); err != nil { s.Failure(w, err) return } } if s.ReportRepositories != nil && len(q.Reports) > 0 { if err := s.ReportRepositories(r.Context(), p, q.Repositories); err != nil { s.Failure(w, err) return } } s.JSON(w, 200, WorkResponse{Version: 2, Result: struct{}{}}) } func (s *Handler) runnerArtifact(w http.ResponseWriter, r *http.Request) { p, _, ok := s.Bearer(w, r) if !ok { return } if s.Execution() == nil { s.Failure(w, s.Unavailable) return } id, err := strconv.ParseInt(chi.URLParam(r, "artifact"), 10, 64) if err != nil { s.Failure(w, s.Invalid) return } q := r.URL.Query() if q.Get("version") != "1" { s.Failure(w, s.Invalid) return } attempt, err := strconv.ParseInt(q.Get("attempt"), 10, 64) if err != nil { s.Failure(w, s.Invalid) return } fence, err := strconv.ParseInt(q.Get("fence"), 10, 64) if err != nil { s.Failure(w, s.Invalid) return } job, err := strconv.ParseInt(q.Get("job"), 10, 64) if err != nil { s.Failure(w, s.Invalid) return } request := RunnerRequest{Version: 2, AssignmentID: chi.URLParam(r, "assignment"), RequestID: q.Get("request_id"), Scope: Scope{Account: team.AccountID(q.Get("account")), Job: team.JobID(job)}, Handle: team.Handle{Attempt: team.AttemptID(attempt), Fence: fence, Runner: p.RunnerID}} value, err := s.Execution().ReadArtifact(r.Context(), p, request, team.ArtifactID(id)) if err != nil { s.Failure(w, err) return } s.JSON(w, 200, WorkResponse{Version: 2, Result: value}) } func (s *Handler) runnerPutBlob(w http.ResponseWriter, r *http.Request) { p, _, ok := s.Bearer(w, r) if !ok { return } var q BlobRequest if !s.Body(w, r, &q, 2*s.MaxBlobBytes) { return } if q.Version != 2 { s.Failure(w, s.Invalid) return } if err := s.PutBlob(r.Context(), p, q.Scope, q.Handle, q.Digest, q.Bytes); err != nil { s.Failure(w, err) return } s.JSON(w, 200, WorkResponse{Version: 2, Result: struct{}{}}) } func (s *Handler) runnerReadBlob(w http.ResponseWriter, r *http.Request) { p, _, ok := s.Bearer(w, r) if !ok { return } var q BlobReadRequest if !s.Body(w, r, &q, 8192) { return } if q.Version != 2 { s.Failure(w, s.Invalid) return } b, err := s.Blob(r.Context(), p, q.Scope, q.Digest) if err != nil { s.Failure(w, err) return } s.JSON(w, 200, WorkResponse{Version: 2, Result: b}) }